///////////////////////////////////////////////////////////////////////////////
// MuldeR's Utilities for Qt
-// Copyright (C) 2004-2014 LoRd_MuldeR <MuldeR2@GMX.de>
+// Copyright (C) 2004-2016 LoRd_MuldeR <MuldeR2@GMX.de>
//
// This library is free software; you can redistribute it and/or
// modify it under the terms of the GNU Lesser General Public
#define _CRT_RAND_S 1
#endif
+//MUtils
#include <MUtils/Global.h>
#include <MUtils/OSSupport.h>
+//Internal
+#include "DirLocker.h"
+#include "3rd_party/strnatcmp/include/strnatcmp.h"
+
//Qt
#include <QDir>
#include <QReadWriteLock>
#include <QProcess>
+#include <QTextCodec>
+#include <QPair>
//CRT
#include <cstdlib>
#include <ctime>
#include <process.h>
+//VLD
+#ifdef _MSC_VER
+#include <vld.h>
+#endif
+
///////////////////////////////////////////////////////////////////////////////
// Random Support
///////////////////////////////////////////////////////////////////////////////
}
///////////////////////////////////////////////////////////////////////////////
-// TEMP FOLDER
+// GET TEMP FILE NAME
///////////////////////////////////////////////////////////////////////////////
-static QReadWriteLock g_temp_folder_lock;
-static QFile* g_temp_folder_file = NULL;
-static QString* g_temp_folder_path = NULL;
-
-#define INIT_TEMP_FOLDER_RAND(OUT_PTR, FILE_PTR, BASE_DIR) do \
-{ \
- for(int _i = 0; _i < 128; _i++) \
- { \
- const QString _randDir = QString("%1/%2").arg((BASE_DIR), rand_str()); \
- if(!QDir(_randDir).exists()) \
- { \
- *(OUT_PTR) = try_init_folder(_randDir, (FILE_PTR)); \
- if(!(OUT_PTR)->isEmpty()) break; \
- } \
- } \
-} \
-while(0)
-
-static QString try_init_folder(const QString &folderPath, QFile *&lockFile)
+QString MUtils::make_temp_file(const QString &basePath, const QString &extension, const bool placeholder)
{
- static const char *TEST_DATA = "Lorem ipsum dolor sit amet, consectetur, adipisci velit!";
-
- bool success = false;
+ for(int i = 0; i < 4096; i++)
+ {
+ const QString tempFileName = QString("%1/%2.%3").arg(basePath, rand_str(), extension);
+ if(!QFileInfo(tempFileName).exists())
+ {
+ if(placeholder)
+ {
+ QFile file(tempFileName);
+ if(file.open(QFile::ReadWrite))
+ {
+ file.close();
+ return tempFileName;
+ }
+ }
+ else
+ {
+ return tempFileName;
+ }
+ }
+ }
+
+ qWarning("Failed to generate unique temp file name!");
+ return QString();
+}
+
+///////////////////////////////////////////////////////////////////////////////
+// COMPUTE PARITY
+///////////////////////////////////////////////////////////////////////////////
+
+/*
+ * Compute parity in parallel
+ * http://www.graphics.stanford.edu/~seander/bithacks.html#ParityParallel
+ */
+bool MUtils::parity(quint32 value)
+{
+ value ^= value >> 16;
+ value ^= value >> 8;
+ value ^= value >> 4;
+ value &= 0xf;
+ return ((0x6996 >> value) & 1) != 0;
+}
+
+///////////////////////////////////////////////////////////////////////////////
+// TEMP FOLDER
+///////////////////////////////////////////////////////////////////////////////
- const QFileInfo folderInfo(folderPath);
- const QDir folderDir(folderInfo.absoluteFilePath());
+static QScopedPointer<MUtils::Internal::DirLock> g_temp_folder_file;
+static QReadWriteLock g_temp_folder_lock;
- //Remove existing lock file
- if(lockFile)
+static QString try_create_subfolder(const QString &baseDir, const QString &postfix)
+{
+ const QString baseDirPath = QDir(baseDir).absolutePath();
+ for(int i = 0; i < 32; i++)
{
- lockFile->remove();
- MUTILS_DELETE(lockFile);
+ QDir directory(baseDirPath);
+ if(directory.mkpath(postfix) && directory.cd(postfix))
+ {
+ return directory.canonicalPath();
+ }
}
+ return QString();
+}
- //Create folder, if it does *not* exist yet
- if(!folderDir.exists())
+static MUtils::Internal::DirLock *try_init_temp_folder(const QString &baseDir)
+{
+ const QString tempPath = try_create_subfolder(baseDir, MUtils::rand_str());
+ if(!tempPath.isEmpty())
{
- for(int i = 0; i < 16; i++)
+ for(int i = 0; i < 32; i++)
{
- if(folderDir.mkpath(".")) break;
+ MUtils::Internal::DirLock *lockFile = NULL;
+ try
+ {
+ lockFile = new MUtils::Internal::DirLock(tempPath);
+ return lockFile;
+ }
+ catch(MUtils::Internal::DirLockException&)
+ {
+ /*ignore error and try again*/
+ }
}
}
+ return NULL;
+}
- //Make sure folder exists now *and* is writable
- if(folderDir.exists())
+static bool temp_folder_cleanup_helper(const QString &tempPath)
+{
+ size_t delay = 1;
+ static const size_t MAX_DELAY = 8192;
+ forever
{
- const QByteArray testData = QByteArray(TEST_DATA);
- for(int i = 0; i < 32; i++)
+ QDir::setCurrent(QDir::rootPath());
+ if(MUtils::remove_directory(tempPath, true))
+ {
+ return true;
+ }
+ else
{
- lockFile = new QFile(folderDir.absoluteFilePath(QString("~%1.tmp").arg(MUtils::rand_str())));
- if(lockFile->open(QIODevice::ReadWrite | QIODevice::Truncate))
+ if(delay > MAX_DELAY)
{
- if(lockFile->write(testData) >= testData.size())
- {
- success = true;
- break;
- }
- lockFile->remove();
- MUTILS_DELETE(lockFile);
+ return false;
}
+ MUtils::OS::sleep_ms(delay);
+ delay *= 2;
}
}
+}
- return (success ? folderDir.canonicalPath() : QString());
+static void temp_folder_cleaup(void)
+{
+ QWriteLocker writeLock(&g_temp_folder_lock);
+
+ //Clean the directory
+ while(!g_temp_folder_file.isNull())
+ {
+ const QString tempPath = g_temp_folder_file->getPath();
+ g_temp_folder_file.reset(NULL);
+ if(!temp_folder_cleanup_helper(tempPath))
+ {
+ MUtils::OS::system_message_wrn(L"Temp Cleaner", L"Warning: Not all temporary files could be removed!");
+ }
+ }
}
const QString &MUtils::temp_folder(void)
QReadLocker readLock(&g_temp_folder_lock);
//Already initialized?
- if(g_temp_folder_path && (!g_temp_folder_path->isEmpty()))
+ if(!g_temp_folder_file.isNull())
{
- return (*g_temp_folder_path);
+ return g_temp_folder_file->getPath();
}
//Obtain the write lock to initilaize
QWriteLocker writeLock(&g_temp_folder_lock);
//Still uninitilaized?
- if(g_temp_folder_path && (!g_temp_folder_path->isEmpty()))
- {
- return (*g_temp_folder_path);
- }
-
- //Create the string, if not done yet
- if(!g_temp_folder_path)
+ if(!g_temp_folder_file.isNull())
{
- g_temp_folder_path = new QString();
+ return g_temp_folder_file->getPath();
}
-
- g_temp_folder_path->clear();
//Try the %TMP% or %TEMP% directory first
- QString tempPath = try_init_folder(QDir::temp().absolutePath(), g_temp_folder_file);
- if(!tempPath.isEmpty())
+ if(MUtils::Internal::DirLock *lockFile = try_init_temp_folder(QDir::tempPath()))
{
- INIT_TEMP_FOLDER_RAND(g_temp_folder_path, g_temp_folder_file, tempPath);
+ g_temp_folder_file.reset(lockFile);
+ atexit(temp_folder_cleaup);
+ return lockFile->getPath();
}
- //Otherwise create TEMP folder in %LOCALAPPDATA% or %SYSTEMROOT%
- if(g_temp_folder_path->isEmpty())
+ qWarning("%%TEMP%% directory not found -> trying fallback mode now!");
+ static const OS::known_folder_t FOLDER_ID[2] = { OS::FOLDER_LOCALAPPDATA, OS::FOLDER_SYSTROOT_DIR };
+ for(size_t id = 0; id < 2; id++)
{
- qWarning("%%TEMP%% directory not found -> trying fallback mode now!");
- static const OS::known_folder_t folderId[2] = { OS::FOLDER_LOCALAPPDATA, OS::FOLDER_SYSTROOT_DIR };
- for(size_t id = 0; (g_temp_folder_path->isEmpty() && (id < 2)); id++)
+ const QString &knownFolder = OS::known_folder(FOLDER_ID[id]);
+ if(!knownFolder.isEmpty())
{
- const QString &knownFolder = OS::known_folder(folderId[id]);
- if(!knownFolder.isEmpty())
+ const QString tempRoot = try_create_subfolder(knownFolder, QLatin1String("TEMP"));
+ if(!tempRoot.isEmpty())
{
- tempPath = try_init_folder(QString("%1/Temp").arg(knownFolder), g_temp_folder_file);
- if(!tempPath.isEmpty())
+ if(MUtils::Internal::DirLock *lockFile = try_init_temp_folder(tempRoot))
{
- INIT_TEMP_FOLDER_RAND(g_temp_folder_path, g_temp_folder_file, tempPath);
+ g_temp_folder_file.reset(lockFile);
+ atexit(temp_folder_cleaup);
+ return lockFile->getPath();
}
}
}
}
- //Failed to create TEMP folder?
- if(g_temp_folder_path->isEmpty())
+ qFatal("Temporary directory could not be initialized !!!");
+ return (*((QString*)NULL));
+}
+
+///////////////////////////////////////////////////////////////////////////////
+// REMOVE DIRECTORY / FILE
+///////////////////////////////////////////////////////////////////////////////
+
+static const QFile::Permissions FILE_PERMISSIONS_NONE = QFile::ReadOther | QFile::WriteOther;
+
+bool MUtils::remove_file(const QString &fileName)
+{
+ QFileInfo fileInfo(fileName);
+ if(!(fileInfo.exists() && fileInfo.isFile()))
+ {
+ return true;
+ }
+
+ for(int i = 0; i < 32; i++)
+ {
+ QFile file(fileName);
+ file.setPermissions(FILE_PERMISSIONS_NONE);
+ if((!(fileInfo.exists() && fileInfo.isFile())) || file.remove())
+ {
+ return true;
+ }
+ fileInfo.refresh();
+ }
+
+ qWarning("Could not delete \"%s\"", MUTILS_UTF8(fileName));
+ return false;
+}
+
+static bool remove_directory_helper(const QDir &folder)
+{
+ if(!folder.exists())
+ {
+ return true;
+ }
+ const QString dirName = folder.dirName();
+ if(!dirName.isEmpty())
+ {
+ QDir parent(folder);
+ if(parent.cdUp())
+ {
+ QFile::setPermissions(folder.absolutePath(), FILE_PERMISSIONS_NONE);
+ if(parent.rmdir(dirName))
+ {
+ return true;
+ }
+ }
+ }
+ return false;
+}
+
+bool MUtils::remove_directory(const QString &folderPath, const bool &recursive)
+{
+ QDir folder(folderPath);
+ if(!folder.exists())
+ {
+ return true;
+ }
+
+ if(recursive)
+ {
+ const QFileInfoList entryList = folder.entryInfoList(QDir::AllEntries | QDir::NoDotAndDotDot | QDir::Hidden);
+ for(QFileInfoList::ConstIterator iter = entryList.constBegin(); iter != entryList.constEnd(); iter++)
+ {
+ if(iter->isDir())
+ {
+ remove_directory(iter->canonicalFilePath(), true);
+ }
+ else if(iter->isFile())
+ {
+ remove_file(iter->canonicalFilePath());
+ }
+ }
+ }
+
+ for(int i = 0; i < 32; i++)
{
- qFatal("Temporary directory could not be initialized !!!");
+ if(remove_directory_helper(folder))
+ {
+ return true;
+ }
+ folder.refresh();
}
- return (*g_temp_folder_path);
+ qWarning("Could not rmdir \"%s\"", MUTILS_UTF8(folderPath));
+ return false;
}
///////////////////////////////////////////////////////////////////////////////
process.setReadChannel(QProcess::StandardOutput);
process.setProcessEnvironment(env);
}
+
+///////////////////////////////////////////////////////////////////////////////
+// NATURAL ORDER STRING COMPARISON
+///////////////////////////////////////////////////////////////////////////////
+
+static bool natural_string_sort_helper(const QString &str1, const QString &str2)
+{
+ return (MUtils::Internal::NaturalSort::strnatcmp(MUTILS_WCHR(str1), MUTILS_WCHR(str2)) < 0);
+}
+
+static bool natural_string_sort_helper_fold_case(const QString &str1, const QString &str2)
+{
+ return (MUtils::Internal::NaturalSort::strnatcasecmp(MUTILS_WCHR(str1), MUTILS_WCHR(str2)) < 0);
+}
+
+void MUtils::natural_string_sort(QStringList &list, const bool bIgnoreCase)
+{
+ qSort(list.begin(), list.end(), bIgnoreCase ? natural_string_sort_helper_fold_case : natural_string_sort_helper);
+}
+
+///////////////////////////////////////////////////////////////////////////////
+// CLEAN FILE PATH
+///////////////////////////////////////////////////////////////////////////////
+
+static const struct
+{
+ const char *const search;
+ const char *const replace;
+}
+CLEAN_FILE_NAME[] =
+{
+ { "\\", "-" },
+ { " / ", ", " },
+ { "/", "," },
+ { ":", "-" },
+ { "*", "x" },
+ { "?", "!" },
+ { "<", "[" },
+ { ">", "]" },
+ { "|", "!" },
+ { "\"", "'" },
+ { NULL, NULL }
+};
+
+QString MUtils::clean_file_name(const QString &name)
+{
+ QRegExp regExp("\"(.+)\"");
+ regExp.setMinimal(true);
+
+ QString str = QString(name).replace(regExp, "``\\1ยดยด").trimmed();
+ for(size_t i = 0; CLEAN_FILE_NAME[i].search; i++)
+ {
+ str.replace(CLEAN_FILE_NAME[i].search, CLEAN_FILE_NAME[i].replace);
+ }
+
+ while(str.endsWith(QLatin1Char('.')))
+ {
+ str.chop(1);
+ str = str.trimmed();
+ }
+
+ return str.trimmed();
+}
+
+static QPair<QString,QString> clean_file_path_get_prefix(const QString path)
+{
+ static const char *const PREFIXES[] =
+ {
+ "//?/", "//", "/", NULL
+ };
+ const QString posixPath = QDir::fromNativeSeparators(path.trimmed());
+ for (int i = 0; PREFIXES[i]; i++)
+ {
+ const QString prefix = QString::fromLatin1(PREFIXES[i]);
+ if (posixPath.startsWith(prefix))
+ {
+ return qMakePair(prefix, posixPath.mid(prefix.length()));
+ }
+ }
+ return qMakePair(QString(), posixPath);
+}
+
+QString MUtils::clean_file_path(const QString &path)
+{
+ const QPair<QString, QString> prefix = clean_file_path_get_prefix(path);
+
+ QStringList parts = prefix.second.split(QLatin1Char('/'), QString::SkipEmptyParts);
+ for(int i = 0; i < parts.count(); i++)
+ {
+ if((i == 0) && (parts[i].length() == 2) && parts[i][0].isLetter() && (parts[i][1] == QLatin1Char(':')))
+ {
+ continue; //handle case "c:\"
+ }
+ parts[i] = MUtils::clean_file_name(parts[i]);
+ }
+
+ const QString cleanPath = parts.join(QLatin1String("/"));
+ return prefix.first.isEmpty() ? cleanPath : prefix.first + cleanPath;
+}
+
+///////////////////////////////////////////////////////////////////////////////
+// REGULAR EXPESSION HELPER
+///////////////////////////////////////////////////////////////////////////////
+
+bool MUtils::regexp_parse_uint32(const QRegExp ®exp, quint32 &value)
+{
+ return regexp_parse_uint32(regexp, &value, 1);
+}
+
+bool MUtils::regexp_parse_uint32(const QRegExp ®exp, quint32 *values, const size_t &count)
+{
+ const QStringList caps = regexp.capturedTexts();
+
+ if(caps.isEmpty() || (quint32(caps.count()) <= count))
+ {
+ return false;
+ }
+
+ for(size_t i = 0; i < count; i++)
+ {
+ bool ok = false;
+ values[i] = caps[i+1].toUInt(&ok);
+ if(!ok)
+ {
+ return false;
+ }
+ }
+
+ return true;
+}
+
+///////////////////////////////////////////////////////////////////////////////
+// AVAILABLE CODEPAGES
+///////////////////////////////////////////////////////////////////////////////
+
+QStringList MUtils::available_codepages(const bool &noAliases)
+{
+ QStringList codecList;
+ QList<QByteArray> availableCodecs = QTextCodec::availableCodecs();
+
+ while(!availableCodecs.isEmpty())
+ {
+ const QByteArray current = availableCodecs.takeFirst();
+ if(!current.toLower().startsWith("system"))
+ {
+ codecList << QString::fromLatin1(current.constData(), current.size());
+ if(noAliases)
+ {
+ if(QTextCodec *const currentCodec = QTextCodec::codecForName(current.constData()))
+ {
+ const QList<QByteArray> aliases = currentCodec->aliases();
+ for(QList<QByteArray>::ConstIterator iter = aliases.constBegin(); iter != aliases.constEnd(); iter++)
+ {
+ availableCodecs.removeAll(*iter);
+ }
+ }
+ }
+ }
+ }
+
+ return codecList;
+}
+
+///////////////////////////////////////////////////////////////////////////////
+// SELF-TEST
+///////////////////////////////////////////////////////////////////////////////
+
+int MUtils::Internal::selfTest(const char *const buildKey, const bool debug)
+{
+ static const bool MY_DEBUG_FLAG = MUTILS_DEBUG;
+ static const char *const MY_BUILD_KEY = __DATE__ "@" __TIME__;
+
+ if(strncmp(buildKey, MY_BUILD_KEY, 13) || (MY_DEBUG_FLAG != debug))
+ {
+ MUtils::OS::system_message_err(L"MUtils", L"FATAL ERROR: MUtils library version mismatch detected!");
+ MUtils::OS::system_message_wrn(L"MUtils", L"Perform a clean(!) re-install of the application to fix the problem!");
+ abort();
+ }
+ return 0;
+}