Fixed compilation for "Release" and "Debug" configuration.
[MUtilities.git] / src / Global.cpp
blob2e13b09bc7f7356a198c41024f42d7f65dac6112
1 ///////////////////////////////////////////////////////////////////////////////
2 // MuldeR's Utilities for Qt
3 // Copyright (C) 2004-2016 LoRd_MuldeR <MuldeR2@GMX.de>
4 //
5 // This library is free software; you can redistribute it and/or
6 // modify it under the terms of the GNU Lesser General Public
7 // License as published by the Free Software Foundation; either
8 // version 2.1 of the License, or (at your option) any later version.
9 //
10 // This library is distributed in the hope that it will be useful,
11 // but WITHOUT ANY WARRANTY; without even the implied warranty of
12 // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
13 // Lesser General Public License for more details.
15 // You should have received a copy of the GNU Lesser General Public
16 // License along with this library; if not, write to the Free Software
17 // Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
19 // http://www.gnu.org/licenses/lgpl-2.1.txt
20 //////////////////////////////////////////////////////////////////////////////////
22 #if _MSC_VER
23 #define _CRT_RAND_S 1
24 #endif
26 //MUtils
27 #include <MUtils/Global.h>
28 #include <MUtils/OSSupport.h>
30 //Internal
31 #include "DirLocker.h"
32 #include "3rd_party/strnatcmp/include/strnatcmp.h"
34 //Qt
35 #include <QDir>
36 #include <QReadWriteLock>
37 #include <QProcess>
38 #include <QTextCodec>
39 #include <QPair>
40 #include <QListIterator>
41 #include <QMutex>
43 //CRT
44 #include <cstdlib>
45 #include <ctime>
46 #include <process.h>
48 //VLD
49 #ifdef _MSC_VER
50 #include <vld.h>
51 #endif
53 ///////////////////////////////////////////////////////////////////////////////
54 // Random Support
55 ///////////////////////////////////////////////////////////////////////////////
57 //Robert Jenkins' 96 bit Mix Function
58 static unsigned int mix_function(const unsigned int x, const unsigned int y, const unsigned int z)
60 unsigned int a = x;
61 unsigned int b = y;
62 unsigned int c = z;
64 a=a-b; a=a-c; a=a^(c >> 13);
65 b=b-c; b=b-a; b=b^(a << 8 );
66 c=c-a; c=c-b; c=c^(b >> 13);
67 a=a-b; a=a-c; a=a^(c >> 12);
68 b=b-c; b=b-a; b=b^(a << 16);
69 c=c-a; c=c-b; c=c^(b >> 5 );
70 a=a-b; a=a-c; a=a^(c >> 3 );
71 b=b-c; b=b-a; b=b^(a << 10);
72 c=c-a; c=c-b; c=c^(b >> 15);
74 return a ^ b ^ c;
77 void MUtils::seed_rand(void)
79 qsrand(mix_function(clock(), time(NULL), _getpid()));
82 quint32 MUtils::next_rand32(void)
84 quint32 rnd = 0xDEADBEEF;
86 #ifdef _CRT_RAND_S
87 if(rand_s(&rnd) == 0)
89 return rnd;
91 #endif //_CRT_RAND_S
93 for(size_t i = 0; i < sizeof(quint32); i++)
95 rnd = (rnd << 8) ^ qrand();
98 return rnd;
101 quint64 MUtils::next_rand64(void)
103 return (quint64(next_rand32()) << 32) | quint64(next_rand32());
106 QString MUtils::rand_str(const bool &bLong)
108 if(!bLong)
110 return QString::number(next_rand64(), 16).rightJustified(16, QLatin1Char('0'));
112 return QString("%1%2").arg(rand_str(false), rand_str(false));
115 ///////////////////////////////////////////////////////////////////////////////
116 // STRING UTILITY FUNCTIONS
117 ///////////////////////////////////////////////////////////////////////////////
119 static QScopedPointer<QRegExp> g_str_trim_rx_r;
120 static QScopedPointer<QRegExp> g_str_trim_rx_l;
121 static QMutex g_str_trim_lock;
123 static QString& trim_helper(QString &str, QScopedPointer<QRegExp> &regex, const char *const pattern)
125 QMutexLocker lock(&g_str_trim_lock);
126 if (regex.isNull())
128 regex.reset(new QRegExp(QLatin1String(pattern)));
130 str.remove(*regex.data());
131 return str;
134 QString& MUtils::trim_right(QString &str)
136 static const char *const TRIM_RIGHT = "\\s+$";
137 return trim_helper(str, g_str_trim_rx_r, TRIM_RIGHT);
140 QString& MUtils::trim_left(QString &str)
142 static const char *const TRIM_LEFT = "^\\s+";
143 return trim_helper(str, g_str_trim_rx_l, TRIM_LEFT);
146 QString MUtils::trim_right(const QString &str)
148 QString temp(str);
149 return trim_right(temp);
152 QString MUtils::trim_left(const QString &str)
154 QString temp(str);
155 return trim_left(temp);
158 ///////////////////////////////////////////////////////////////////////////////
159 // GENERATE FILE NAME
160 ///////////////////////////////////////////////////////////////////////////////
162 QString MUtils::make_temp_file(const QString &basePath, const QString &extension, const bool placeholder)
164 for(int i = 0; i < 4096; i++)
166 const QString tempFileName = QString("%1/%2.%3").arg(basePath, rand_str(), extension);
167 if(!QFileInfo(tempFileName).exists())
169 if(placeholder)
171 QFile file(tempFileName);
172 if(file.open(QFile::ReadWrite))
174 file.close();
175 return tempFileName;
178 else
180 return tempFileName;
185 qWarning("Failed to generate temp file name!");
186 return QString();
189 QString MUtils::make_unique_file(const QString &basePath, const QString &baseName, const QString &extension, const bool fancy)
191 quint32 n = fancy ? 2 : 0;
192 QString fileName = fancy ? QString("%1/%2.%3").arg(basePath, baseName, extension) : QString();
193 while (fileName.isEmpty() || QFileInfo(fileName).exists())
195 if (n <= quint32(USHRT_MAX))
197 if (fancy)
199 fileName = QString("%1/%2 (%3).%4").arg(basePath, baseName, QString::number(n++), extension);
201 else
203 fileName = QString("%1/%2.%3.%4").arg(basePath, baseName, QString::number(n++, 16).rightJustified(4, QLatin1Char('0')), extension);
206 else
208 qWarning("Failed to generate unique file name!");
209 return QString();
212 return fileName;
215 ///////////////////////////////////////////////////////////////////////////////
216 // COMPUTE PARITY
217 ///////////////////////////////////////////////////////////////////////////////
220 * Compute parity in parallel
221 * http://www.graphics.stanford.edu/~seander/bithacks.html#ParityParallel
223 bool MUtils::parity(quint32 value)
225 value ^= value >> 16;
226 value ^= value >> 8;
227 value ^= value >> 4;
228 value &= 0xf;
229 return ((0x6996 >> value) & 1) != 0;
232 ///////////////////////////////////////////////////////////////////////////////
233 // TEMP FOLDER
234 ///////////////////////////////////////////////////////////////////////////////
236 static QScopedPointer<MUtils::Internal::DirLock> g_temp_folder_file;
237 static QReadWriteLock g_temp_folder_lock;
239 static QString try_create_subfolder(const QString &baseDir, const QString &postfix)
241 const QString baseDirPath = QDir(baseDir).absolutePath();
242 for(int i = 0; i < 32; i++)
244 QDir directory(baseDirPath);
245 if(directory.mkpath(postfix) && directory.cd(postfix))
247 return directory.canonicalPath();
250 return QString();
253 static MUtils::Internal::DirLock *try_init_temp_folder(const QString &baseDir)
255 const QString tempPath = try_create_subfolder(baseDir, MUtils::rand_str());
256 if(!tempPath.isEmpty())
258 for(int i = 0; i < 32; i++)
260 MUtils::Internal::DirLock *lockFile = NULL;
263 lockFile = new MUtils::Internal::DirLock(tempPath);
264 return lockFile;
266 catch(MUtils::Internal::DirLockException&)
268 /*ignore error and try again*/
272 return NULL;
275 static bool temp_folder_cleanup_helper(const QString &tempPath)
277 size_t delay = 1;
278 static const size_t MAX_DELAY = 8192;
279 forever
281 QDir::setCurrent(QDir::rootPath());
282 if(MUtils::remove_directory(tempPath, true))
284 return true;
286 else
288 if(delay > MAX_DELAY)
290 return false;
292 MUtils::OS::sleep_ms(delay);
293 delay *= 2;
298 static void temp_folder_cleaup(void)
300 QWriteLocker writeLock(&g_temp_folder_lock);
302 //Clean the directory
303 while(!g_temp_folder_file.isNull())
305 const QString tempPath = g_temp_folder_file->getPath();
306 g_temp_folder_file.reset(NULL);
307 if(!temp_folder_cleanup_helper(tempPath))
309 MUtils::OS::system_message_wrn(L"Temp Cleaner", L"Warning: Not all temporary files could be removed!");
314 const QString &MUtils::temp_folder(void)
316 QReadLocker readLock(&g_temp_folder_lock);
318 //Already initialized?
319 if(!g_temp_folder_file.isNull())
321 return g_temp_folder_file->getPath();
324 //Obtain the write lock to initilaize
325 readLock.unlock();
326 QWriteLocker writeLock(&g_temp_folder_lock);
328 //Still uninitilaized?
329 if(!g_temp_folder_file.isNull())
331 return g_temp_folder_file->getPath();
334 //Try the %TMP% or %TEMP% directory first
335 if(MUtils::Internal::DirLock *lockFile = try_init_temp_folder(QDir::tempPath()))
337 g_temp_folder_file.reset(lockFile);
338 atexit(temp_folder_cleaup);
339 return lockFile->getPath();
342 qWarning("%%TEMP%% directory not found -> trying fallback mode now!");
343 static const OS::known_folder_t FOLDER_ID[2] = { OS::FOLDER_LOCALAPPDATA, OS::FOLDER_SYSTROOT_DIR };
344 for(size_t id = 0; id < 2; id++)
346 const QString &knownFolder = OS::known_folder(FOLDER_ID[id]);
347 if(!knownFolder.isEmpty())
349 const QString tempRoot = try_create_subfolder(knownFolder, QLatin1String("TEMP"));
350 if(!tempRoot.isEmpty())
352 if(MUtils::Internal::DirLock *lockFile = try_init_temp_folder(tempRoot))
354 g_temp_folder_file.reset(lockFile);
355 atexit(temp_folder_cleaup);
356 return lockFile->getPath();
362 qFatal("Temporary directory could not be initialized !!!");
363 return (*((QString*)NULL));
366 ///////////////////////////////////////////////////////////////////////////////
367 // REMOVE DIRECTORY / FILE
368 ///////////////////////////////////////////////////////////////////////////////
370 static const QFile::Permissions FILE_PERMISSIONS_NONE = QFile::ReadOther | QFile::WriteOther;
372 bool MUtils::remove_file(const QString &fileName)
374 QFileInfo fileInfo(fileName);
375 if(!(fileInfo.exists() && fileInfo.isFile()))
377 return true;
380 for(int i = 0; i < 32; i++)
382 QFile file(fileName);
383 file.setPermissions(FILE_PERMISSIONS_NONE);
384 if((!(fileInfo.exists() && fileInfo.isFile())) || file.remove())
386 return true;
388 fileInfo.refresh();
391 qWarning("Could not delete \"%s\"", MUTILS_UTF8(fileName));
392 return false;
395 static bool remove_directory_helper(const QDir &folder)
397 if(!folder.exists())
399 return true;
401 const QString dirName = folder.dirName();
402 if(!dirName.isEmpty())
404 QDir parent(folder);
405 if(parent.cdUp())
407 QFile::setPermissions(folder.absolutePath(), FILE_PERMISSIONS_NONE);
408 if(parent.rmdir(dirName))
410 return true;
414 return false;
417 bool MUtils::remove_directory(const QString &folderPath, const bool &recursive)
419 QDir folder(folderPath);
420 if(!folder.exists())
422 return true;
425 if(recursive)
427 const QFileInfoList entryList = folder.entryInfoList(QDir::AllEntries | QDir::NoDotAndDotDot | QDir::Hidden);
428 for(QFileInfoList::ConstIterator iter = entryList.constBegin(); iter != entryList.constEnd(); iter++)
430 if(iter->isDir())
432 remove_directory(iter->canonicalFilePath(), true);
434 else if(iter->isFile())
436 remove_file(iter->canonicalFilePath());
441 for(int i = 0; i < 32; i++)
443 if(remove_directory_helper(folder))
445 return true;
447 folder.refresh();
450 qWarning("Could not rmdir \"%s\"", MUTILS_UTF8(folderPath));
451 return false;
454 ///////////////////////////////////////////////////////////////////////////////
455 // PROCESS UTILS
456 ///////////////////////////////////////////////////////////////////////////////
458 static void prependToPath(QProcessEnvironment &env, const QString &value)
460 const QLatin1String PATH = QLatin1String("PATH");
461 const QString path = env.value(PATH, QString()).trimmed();
462 env.insert(PATH, path.isEmpty() ? value : QString("%1;%2").arg(value, path));
465 void MUtils::init_process(QProcess &process, const QString &wokringDir, const bool bReplaceTempDir, const QStringList *const extraPaths)
467 //Environment variable names
468 static const char *const s_envvar_names_temp[] =
470 "TEMP", "TMP", "TMPDIR", "HOME", "USERPROFILE", "HOMEPATH", NULL
472 static const char *const s_envvar_names_remove[] =
474 "WGETRC", "SYSTEM_WGETRC", "HTTP_PROXY", "FTP_PROXY", "NO_PROXY", "GNUPGHOME", "LC_ALL", "LC_COLLATE", "LC_CTYPE", "LC_MESSAGES", "LC_MONETARY", "LC_NUMERIC", "LC_TIME", "LANG", NULL
477 //Initialize environment
478 QProcessEnvironment env = process.processEnvironment();
479 if(env.isEmpty()) env = QProcessEnvironment::systemEnvironment();
481 //Clean a number of enviroment variables that might affect our tools
482 for(size_t i = 0; s_envvar_names_remove[i]; i++)
484 env.remove(QString::fromLatin1(s_envvar_names_remove[i]));
485 env.remove(QString::fromLatin1(s_envvar_names_remove[i]).toLower());
488 const QString tempDir = QDir::toNativeSeparators(temp_folder());
490 //Replace TEMP directory in environment
491 if(bReplaceTempDir)
493 for(size_t i = 0; s_envvar_names_temp[i]; i++)
495 env.insert(s_envvar_names_temp[i], tempDir);
499 //Setup PATH variable
500 prependToPath(env, tempDir);
501 if (extraPaths && (!extraPaths->isEmpty()))
503 QListIterator<QString> iter(*extraPaths);
504 iter.toBack();
505 while (iter.hasPrevious())
507 prependToPath(env, QDir::toNativeSeparators(iter.previous()));
511 //Setup QPorcess object
512 process.setWorkingDirectory(wokringDir);
513 process.setProcessChannelMode(QProcess::MergedChannels);
514 process.setReadChannel(QProcess::StandardOutput);
515 process.setProcessEnvironment(env);
518 ///////////////////////////////////////////////////////////////////////////////
519 // NATURAL ORDER STRING COMPARISON
520 ///////////////////////////////////////////////////////////////////////////////
522 static bool natural_string_sort_helper(const QString &str1, const QString &str2)
524 return (MUtils::Internal::NaturalSort::strnatcmp(MUTILS_WCHR(str1), MUTILS_WCHR(str2)) < 0);
527 static bool natural_string_sort_helper_fold_case(const QString &str1, const QString &str2)
529 return (MUtils::Internal::NaturalSort::strnatcasecmp(MUTILS_WCHR(str1), MUTILS_WCHR(str2)) < 0);
532 void MUtils::natural_string_sort(QStringList &list, const bool bIgnoreCase)
534 qSort(list.begin(), list.end(), bIgnoreCase ? natural_string_sort_helper_fold_case : natural_string_sort_helper);
537 ///////////////////////////////////////////////////////////////////////////////
538 // CLEAN FILE PATH
539 ///////////////////////////////////////////////////////////////////////////////
541 QString MUtils::clean_file_name(const QString &name)
543 static const QLatin1Char REPLACEMENT_CHAR('_');
544 static const char FILENAME_ILLEGAL_CHARS[] = "<>:\"/\\|?*";
545 static const char *const FILENAME_RESERVED_NAMES[] =
547 "CON", "PRN", "AUX", "NUL",
548 "COM1", "COM2", "COM3", "COM4", "COM5", "COM6", "COM7", "COM8", "COM9",
549 "LPT1", "LPT2", "LPT3", "LPT4", "LPT5", "LPT6", "LPT7", "LPT8", "LPT9", NULL
552 QString result(name);
553 if (result.contains(QLatin1Char('"')))
555 QRegExp quoted("\"(.+)\"");
556 quoted.setMinimal(true);
557 result.replace(quoted, "``\\1ยดยด");
560 for(QString::Iterator iter = result.begin(); iter != result.end(); iter++)
562 if (iter->category() == QChar::Other_Control)
564 *iter = REPLACEMENT_CHAR;
568 for(size_t i = 0; FILENAME_ILLEGAL_CHARS[i]; i++)
570 result.replace(QLatin1Char(FILENAME_ILLEGAL_CHARS[i]), REPLACEMENT_CHAR);
573 trim_right(result);
574 while (result.endsWith(QLatin1Char('.')))
576 result.chop(1);
577 trim_right(result);
580 for (size_t i = 0; FILENAME_RESERVED_NAMES[i]; i++)
582 const QString reserved = QString::fromLatin1(FILENAME_RESERVED_NAMES[i]);
583 if ((!result.compare(reserved, Qt::CaseInsensitive)) || result.startsWith(reserved + QLatin1Char('.'), Qt::CaseInsensitive))
585 result.replace(0, reserved.length(), QString().leftJustified(reserved.length(), REPLACEMENT_CHAR));
589 return result;
592 static QPair<QString,QString> clean_file_path_get_prefix(const QString path)
594 static const char *const PREFIXES[] =
596 "//?/", "//", "/", NULL
598 const QString posixPath = QDir::fromNativeSeparators(path.trimmed());
599 for (int i = 0; PREFIXES[i]; i++)
601 const QString prefix = QString::fromLatin1(PREFIXES[i]);
602 if (posixPath.startsWith(prefix))
604 return qMakePair(prefix, posixPath.mid(prefix.length()));
607 return qMakePair(QString(), posixPath);
610 QString MUtils::clean_file_path(const QString &path)
612 const QPair<QString, QString> prefix = clean_file_path_get_prefix(path);
614 QStringList parts = prefix.second.split(QLatin1Char('/'), QString::SkipEmptyParts);
615 for(int i = 0; i < parts.count(); i++)
617 if((i == 0) && (parts[i].length() == 2) && parts[i][0].isLetter() && (parts[i][1] == QLatin1Char(':')))
619 continue; //handle case "c:\"
621 parts[i] = MUtils::clean_file_name(parts[i]);
624 const QString cleanPath = parts.join(QLatin1String("/"));
625 return prefix.first.isEmpty() ? cleanPath : prefix.first + cleanPath;
628 ///////////////////////////////////////////////////////////////////////////////
629 // REGULAR EXPESSION HELPER
630 ///////////////////////////////////////////////////////////////////////////////
632 bool MUtils::regexp_parse_uint32(const QRegExp &regexp, quint32 &value)
634 return regexp_parse_uint32(regexp, &value, 1);
637 bool MUtils::regexp_parse_uint32(const QRegExp &regexp, quint32 *values, const size_t &count)
639 const QStringList caps = regexp.capturedTexts();
641 if(caps.isEmpty() || (quint32(caps.count()) <= count))
643 return false;
646 for(size_t i = 0; i < count; i++)
648 bool ok = false;
649 values[i] = caps[i+1].toUInt(&ok);
650 if(!ok)
652 return false;
656 return true;
659 ///////////////////////////////////////////////////////////////////////////////
660 // AVAILABLE CODEPAGES
661 ///////////////////////////////////////////////////////////////////////////////
663 QStringList MUtils::available_codepages(const bool &noAliases)
665 QStringList codecList;
666 QList<QByteArray> availableCodecs = QTextCodec::availableCodecs();
668 while(!availableCodecs.isEmpty())
670 const QByteArray current = availableCodecs.takeFirst();
671 if(!current.toLower().startsWith("system"))
673 codecList << QString::fromLatin1(current.constData(), current.size());
674 if(noAliases)
676 if(QTextCodec *const currentCodec = QTextCodec::codecForName(current.constData()))
678 const QList<QByteArray> aliases = currentCodec->aliases();
679 for(QList<QByteArray>::ConstIterator iter = aliases.constBegin(); iter != aliases.constEnd(); iter++)
681 availableCodecs.removeAll(*iter);
688 return codecList;
691 ///////////////////////////////////////////////////////////////////////////////
692 // SELF-TEST
693 ///////////////////////////////////////////////////////////////////////////////
695 int MUtils::Internal::selfTest(const char *const buildKey, const bool debug)
697 static const bool MY_DEBUG_FLAG = MUTILS_DEBUG;
698 static const char *const MY_BUILD_KEY = __DATE__ "@" __TIME__;
700 if(strncmp(buildKey, MY_BUILD_KEY, 13) || (MY_DEBUG_FLAG != debug))
702 MUtils::OS::system_message_err(L"MUtils", L"FATAL ERROR: MUtils library version mismatch detected!");
703 MUtils::OS::system_message_wrn(L"MUtils", L"Perform a clean(!) re-install of the application to fix the problem!");
704 abort();
706 return 0;