Renamed functions for consistency.
[MUtilities.git] / src / Global.cpp
blob2cfce45527ceb06f800bf48ab84673f85a5e97eb
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 #ifndef _CRT_RAND_S
58 #define rand_s(X) (true)
59 #endif
61 //Robert Jenkins' 96 bit Mix Function
62 static unsigned int mix_function(const unsigned int x, const unsigned int y, const unsigned int z)
64 unsigned int a = x;
65 unsigned int b = y;
66 unsigned int c = z;
68 a=a-b; a=a-c; a=a^(c >> 13);
69 b=b-c; b=b-a; b=b^(a << 8 );
70 c=c-a; c=c-b; c=c^(b >> 13);
71 a=a-b; a=a-c; a=a^(c >> 12);
72 b=b-c; b=b-a; b=b^(a << 16);
73 c=c-a; c=c-b; c=c^(b >> 5 );
74 a=a-b; a=a-c; a=a^(c >> 3 );
75 b=b-c; b=b-a; b=b^(a << 10);
76 c=c-a; c=c-b; c=c^(b >> 15);
78 return a ^ b ^ c;
81 void MUtils::seed_rand(void)
83 qsrand(mix_function(clock(), time(NULL), _getpid()));
86 quint32 MUtils::next_rand_u32(void)
88 quint32 rnd;
89 if (rand_s(&rnd))
91 for (size_t i = 0; i < sizeof(quint32); i += 2)
93 rnd = (rnd << 16) ^ qrand();
96 return rnd;
99 quint64 MUtils::next_rand_u64(void)
101 return (quint64(next_rand_u32()) << 32) | quint64(next_rand_u32());
104 QString MUtils::next_rand_str(const bool &bLong)
106 if (bLong)
108 return next_rand_str(false) + next_rand_str(false);
110 else
112 return QString::number(next_rand_u64(), 16).rightJustified(16, QLatin1Char('0'));
116 ///////////////////////////////////////////////////////////////////////////////
117 // STRING UTILITY FUNCTIONS
118 ///////////////////////////////////////////////////////////////////////////////
120 static QScopedPointer<QRegExp> g_str_trim_rx_r;
121 static QScopedPointer<QRegExp> g_str_trim_rx_l;
122 static QMutex g_str_trim_lock;
124 static QString& trim_helper(QString &str, QScopedPointer<QRegExp> &regex, const char *const pattern)
126 QMutexLocker lock(&g_str_trim_lock);
127 if (regex.isNull())
129 regex.reset(new QRegExp(QLatin1String(pattern)));
131 str.remove(*regex.data());
132 return str;
135 QString& MUtils::trim_right(QString &str)
137 static const char *const TRIM_RIGHT = "\\s+$";
138 return trim_helper(str, g_str_trim_rx_r, TRIM_RIGHT);
141 QString& MUtils::trim_left(QString &str)
143 static const char *const TRIM_LEFT = "^\\s+";
144 return trim_helper(str, g_str_trim_rx_l, TRIM_LEFT);
147 QString MUtils::trim_right(const QString &str)
149 QString temp(str);
150 return trim_right(temp);
153 QString MUtils::trim_left(const QString &str)
155 QString temp(str);
156 return trim_left(temp);
159 ///////////////////////////////////////////////////////////////////////////////
160 // GENERATE FILE NAME
161 ///////////////////////////////////////////////////////////////////////////////
163 QString MUtils::make_temp_file(const QString &basePath, const QString &extension, const bool placeholder)
165 for(int i = 0; i < 4096; i++)
167 const QString tempFileName = QString("%1/%2.%3").arg(basePath, next_rand_str(), extension);
168 if(!QFileInfo(tempFileName).exists())
170 if(placeholder)
172 QFile file(tempFileName);
173 if(file.open(QFile::ReadWrite))
175 file.close();
176 return tempFileName;
179 else
181 return tempFileName;
186 qWarning("Failed to generate temp file name!");
187 return QString();
190 QString MUtils::make_unique_file(const QString &basePath, const QString &baseName, const QString &extension, const bool fancy)
192 quint32 n = fancy ? 2 : 0;
193 QString fileName = fancy ? QString("%1/%2.%3").arg(basePath, baseName, extension) : QString();
194 while (fileName.isEmpty() || QFileInfo(fileName).exists())
196 if (n <= quint32(USHRT_MAX))
198 if (fancy)
200 fileName = QString("%1/%2 (%3).%4").arg(basePath, baseName, QString::number(n++), extension);
202 else
204 fileName = QString("%1/%2.%3.%4").arg(basePath, baseName, QString::number(n++, 16).rightJustified(4, QLatin1Char('0')), extension);
207 else
209 qWarning("Failed to generate unique file name!");
210 return QString();
213 return fileName;
216 ///////////////////////////////////////////////////////////////////////////////
217 // COMPUTE PARITY
218 ///////////////////////////////////////////////////////////////////////////////
221 * Compute parity in parallel
222 * http://www.graphics.stanford.edu/~seander/bithacks.html#ParityParallel
224 bool MUtils::parity(quint32 value)
226 value ^= value >> 16;
227 value ^= value >> 8;
228 value ^= value >> 4;
229 value &= 0xf;
230 return ((0x6996 >> value) & 1) != 0;
233 ///////////////////////////////////////////////////////////////////////////////
234 // TEMP FOLDER
235 ///////////////////////////////////////////////////////////////////////////////
237 static QScopedPointer<MUtils::Internal::DirLock> g_temp_folder_file;
238 static QReadWriteLock g_temp_folder_lock;
240 static QString try_create_subfolder(const QString &baseDir, const QString &postfix)
242 const QString baseDirPath = QDir(baseDir).absolutePath();
243 for(int i = 0; i < 32; i++)
245 QDir directory(baseDirPath);
246 if(directory.mkpath(postfix) && directory.cd(postfix))
248 return directory.canonicalPath();
251 return QString();
254 static MUtils::Internal::DirLock *try_init_temp_folder(const QString &baseDir)
256 const QString tempPath = try_create_subfolder(baseDir, MUtils::next_rand_str());
257 if(!tempPath.isEmpty())
259 for(int i = 0; i < 32; i++)
261 MUtils::Internal::DirLock *lockFile = NULL;
264 lockFile = new MUtils::Internal::DirLock(tempPath);
265 return lockFile;
267 catch(MUtils::Internal::DirLockException&)
269 /*ignore error and try again*/
273 return NULL;
276 static bool temp_folder_cleanup_helper(const QString &tempPath)
278 size_t delay = 1;
279 static const size_t MAX_DELAY = 8192;
280 forever
282 QDir::setCurrent(QDir::rootPath());
283 if(MUtils::remove_directory(tempPath, true))
285 return true;
287 else
289 if(delay > MAX_DELAY)
291 return false;
293 MUtils::OS::sleep_ms(delay);
294 delay *= 2;
299 static void temp_folder_cleaup(void)
301 QWriteLocker writeLock(&g_temp_folder_lock);
303 //Clean the directory
304 while(!g_temp_folder_file.isNull())
306 const QString tempPath = g_temp_folder_file->getPath();
307 g_temp_folder_file.reset(NULL);
308 if(!temp_folder_cleanup_helper(tempPath))
310 MUtils::OS::system_message_wrn(L"Temp Cleaner", L"Warning: Not all temporary files could be removed!");
315 const QString &MUtils::temp_folder(void)
317 QReadLocker readLock(&g_temp_folder_lock);
319 //Already initialized?
320 if(!g_temp_folder_file.isNull())
322 return g_temp_folder_file->getPath();
325 //Obtain the write lock to initilaize
326 readLock.unlock();
327 QWriteLocker writeLock(&g_temp_folder_lock);
329 //Still uninitilaized?
330 if(!g_temp_folder_file.isNull())
332 return g_temp_folder_file->getPath();
335 //Try the %TMP% or %TEMP% directory first
336 if(MUtils::Internal::DirLock *lockFile = try_init_temp_folder(QDir::tempPath()))
338 g_temp_folder_file.reset(lockFile);
339 atexit(temp_folder_cleaup);
340 return lockFile->getPath();
343 qWarning("%%TEMP%% directory not found -> trying fallback mode now!");
344 static const OS::known_folder_t FOLDER_ID[2] = { OS::FOLDER_LOCALAPPDATA, OS::FOLDER_SYSTROOT_DIR };
345 for(size_t id = 0; id < 2; id++)
347 const QString &knownFolder = OS::known_folder(FOLDER_ID[id]);
348 if(!knownFolder.isEmpty())
350 const QString tempRoot = try_create_subfolder(knownFolder, QLatin1String("TEMP"));
351 if(!tempRoot.isEmpty())
353 if(MUtils::Internal::DirLock *lockFile = try_init_temp_folder(tempRoot))
355 g_temp_folder_file.reset(lockFile);
356 atexit(temp_folder_cleaup);
357 return lockFile->getPath();
363 qFatal("Temporary directory could not be initialized !!!");
364 return (*((QString*)NULL));
367 ///////////////////////////////////////////////////////////////////////////////
368 // REMOVE DIRECTORY / FILE
369 ///////////////////////////////////////////////////////////////////////////////
371 static const QFile::Permissions FILE_PERMISSIONS_NONE = QFile::ReadOther | QFile::WriteOther;
373 bool MUtils::remove_file(const QString &fileName)
375 QFileInfo fileInfo(fileName);
376 if(!(fileInfo.exists() && fileInfo.isFile()))
378 return true;
381 for(int i = 0; i < 32; i++)
383 QFile file(fileName);
384 file.setPermissions(FILE_PERMISSIONS_NONE);
385 if((!(fileInfo.exists() && fileInfo.isFile())) || file.remove())
387 return true;
389 fileInfo.refresh();
392 qWarning("Could not delete \"%s\"", MUTILS_UTF8(fileName));
393 return false;
396 static bool remove_directory_helper(const QDir &folder)
398 if(!folder.exists())
400 return true;
402 const QString dirName = folder.dirName();
403 if(!dirName.isEmpty())
405 QDir parent(folder);
406 if(parent.cdUp())
408 QFile::setPermissions(folder.absolutePath(), FILE_PERMISSIONS_NONE);
409 if(parent.rmdir(dirName))
411 return true;
415 return false;
418 bool MUtils::remove_directory(const QString &folderPath, const bool &recursive)
420 QDir folder(folderPath);
421 if(!folder.exists())
423 return true;
426 if(recursive)
428 const QFileInfoList entryList = folder.entryInfoList(QDir::AllEntries | QDir::NoDotAndDotDot | QDir::Hidden);
429 for(QFileInfoList::ConstIterator iter = entryList.constBegin(); iter != entryList.constEnd(); iter++)
431 if(iter->isDir())
433 remove_directory(iter->canonicalFilePath(), true);
435 else if(iter->isFile())
437 remove_file(iter->canonicalFilePath());
442 for(int i = 0; i < 32; i++)
444 if(remove_directory_helper(folder))
446 return true;
448 folder.refresh();
451 qWarning("Could not rmdir \"%s\"", MUTILS_UTF8(folderPath));
452 return false;
455 ///////////////////////////////////////////////////////////////////////////////
456 // PROCESS UTILS
457 ///////////////////////////////////////////////////////////////////////////////
459 static void prependToPath(QProcessEnvironment &env, const QString &value)
461 const QLatin1String PATH = QLatin1String("PATH");
462 const QString path = env.value(PATH, QString()).trimmed();
463 env.insert(PATH, path.isEmpty() ? value : QString("%1;%2").arg(value, path));
466 void MUtils::init_process(QProcess &process, const QString &wokringDir, const bool bReplaceTempDir, const QStringList *const extraPaths)
468 //Environment variable names
469 static const char *const s_envvar_names_temp[] =
471 "TEMP", "TMP", "TMPDIR", "HOME", "USERPROFILE", "HOMEPATH", NULL
473 static const char *const s_envvar_names_remove[] =
475 "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
478 //Initialize environment
479 QProcessEnvironment env = process.processEnvironment();
480 if(env.isEmpty()) env = QProcessEnvironment::systemEnvironment();
482 //Clean a number of enviroment variables that might affect our tools
483 for(size_t i = 0; s_envvar_names_remove[i]; i++)
485 env.remove(QString::fromLatin1(s_envvar_names_remove[i]));
486 env.remove(QString::fromLatin1(s_envvar_names_remove[i]).toLower());
489 const QString tempDir = QDir::toNativeSeparators(temp_folder());
491 //Replace TEMP directory in environment
492 if(bReplaceTempDir)
494 for(size_t i = 0; s_envvar_names_temp[i]; i++)
496 env.insert(s_envvar_names_temp[i], tempDir);
500 //Setup PATH variable
501 prependToPath(env, tempDir);
502 if (extraPaths && (!extraPaths->isEmpty()))
504 QListIterator<QString> iter(*extraPaths);
505 iter.toBack();
506 while (iter.hasPrevious())
508 prependToPath(env, QDir::toNativeSeparators(iter.previous()));
512 //Setup QPorcess object
513 process.setWorkingDirectory(wokringDir);
514 process.setProcessChannelMode(QProcess::MergedChannels);
515 process.setReadChannel(QProcess::StandardOutput);
516 process.setProcessEnvironment(env);
519 ///////////////////////////////////////////////////////////////////////////////
520 // NATURAL ORDER STRING COMPARISON
521 ///////////////////////////////////////////////////////////////////////////////
523 static bool natural_string_sort_helper(const QString &str1, const QString &str2)
525 return (MUtils::Internal::NaturalSort::strnatcmp(MUTILS_WCHR(str1), MUTILS_WCHR(str2)) < 0);
528 static bool natural_string_sort_helper_fold_case(const QString &str1, const QString &str2)
530 return (MUtils::Internal::NaturalSort::strnatcasecmp(MUTILS_WCHR(str1), MUTILS_WCHR(str2)) < 0);
533 void MUtils::natural_string_sort(QStringList &list, const bool bIgnoreCase)
535 qSort(list.begin(), list.end(), bIgnoreCase ? natural_string_sort_helper_fold_case : natural_string_sort_helper);
538 ///////////////////////////////////////////////////////////////////////////////
539 // CLEAN FILE PATH
540 ///////////////////////////////////////////////////////////////////////////////
542 QString MUtils::clean_file_name(const QString &name)
544 static const QLatin1Char REPLACEMENT_CHAR('_');
545 static const char FILENAME_ILLEGAL_CHARS[] = "<>:\"/\\|?*";
546 static const char *const FILENAME_RESERVED_NAMES[] =
548 "CON", "PRN", "AUX", "NUL",
549 "COM1", "COM2", "COM3", "COM4", "COM5", "COM6", "COM7", "COM8", "COM9",
550 "LPT1", "LPT2", "LPT3", "LPT4", "LPT5", "LPT6", "LPT7", "LPT8", "LPT9", NULL
553 QString result(name);
554 if (result.contains(QLatin1Char('"')))
556 QRegExp quoted("\"(.+)\"");
557 quoted.setMinimal(true);
558 result.replace(quoted, "``\\1ยดยด");
561 for(QString::Iterator iter = result.begin(); iter != result.end(); iter++)
563 if (iter->category() == QChar::Other_Control)
565 *iter = REPLACEMENT_CHAR;
569 for(size_t i = 0; FILENAME_ILLEGAL_CHARS[i]; i++)
571 result.replace(QLatin1Char(FILENAME_ILLEGAL_CHARS[i]), REPLACEMENT_CHAR);
574 trim_right(result);
575 while (result.endsWith(QLatin1Char('.')))
577 result.chop(1);
578 trim_right(result);
581 for (size_t i = 0; FILENAME_RESERVED_NAMES[i]; i++)
583 const QString reserved = QString::fromLatin1(FILENAME_RESERVED_NAMES[i]);
584 if ((!result.compare(reserved, Qt::CaseInsensitive)) || result.startsWith(reserved + QLatin1Char('.'), Qt::CaseInsensitive))
586 result.replace(0, reserved.length(), QString().leftJustified(reserved.length(), REPLACEMENT_CHAR));
590 return result;
593 static QPair<QString,QString> clean_file_path_get_prefix(const QString path)
595 static const char *const PREFIXES[] =
597 "//?/", "//", "/", NULL
599 const QString posixPath = QDir::fromNativeSeparators(path.trimmed());
600 for (int i = 0; PREFIXES[i]; i++)
602 const QString prefix = QString::fromLatin1(PREFIXES[i]);
603 if (posixPath.startsWith(prefix))
605 return qMakePair(prefix, posixPath.mid(prefix.length()));
608 return qMakePair(QString(), posixPath);
611 QString MUtils::clean_file_path(const QString &path)
613 const QPair<QString, QString> prefix = clean_file_path_get_prefix(path);
615 QStringList parts = prefix.second.split(QLatin1Char('/'), QString::SkipEmptyParts);
616 for(int i = 0; i < parts.count(); i++)
618 if((i == 0) && (parts[i].length() == 2) && parts[i][0].isLetter() && (parts[i][1] == QLatin1Char(':')))
620 continue; //handle case "c:\"
622 parts[i] = MUtils::clean_file_name(parts[i]);
625 const QString cleanPath = parts.join(QLatin1String("/"));
626 return prefix.first.isEmpty() ? cleanPath : prefix.first + cleanPath;
629 ///////////////////////////////////////////////////////////////////////////////
630 // REGULAR EXPESSION HELPER
631 ///////////////////////////////////////////////////////////////////////////////
633 bool MUtils::regexp_parse_uint32(const QRegExp &regexp, quint32 &value)
635 return regexp_parse_uint32(regexp, &value, 1);
638 bool MUtils::regexp_parse_uint32(const QRegExp &regexp, quint32 *values, const size_t &count)
640 const QStringList caps = regexp.capturedTexts();
642 if(caps.isEmpty() || (quint32(caps.count()) <= count))
644 return false;
647 for(size_t i = 0; i < count; i++)
649 bool ok = false;
650 values[i] = caps[i+1].toUInt(&ok);
651 if(!ok)
653 return false;
657 return true;
660 ///////////////////////////////////////////////////////////////////////////////
661 // AVAILABLE CODEPAGES
662 ///////////////////////////////////////////////////////////////////////////////
664 QStringList MUtils::available_codepages(const bool &noAliases)
666 QStringList codecList;
667 QList<QByteArray> availableCodecs = QTextCodec::availableCodecs();
669 while(!availableCodecs.isEmpty())
671 const QByteArray current = availableCodecs.takeFirst();
672 if(!current.toLower().startsWith("system"))
674 codecList << QString::fromLatin1(current.constData(), current.size());
675 if(noAliases)
677 if(QTextCodec *const currentCodec = QTextCodec::codecForName(current.constData()))
679 const QList<QByteArray> aliases = currentCodec->aliases();
680 for(QList<QByteArray>::ConstIterator iter = aliases.constBegin(); iter != aliases.constEnd(); iter++)
682 availableCodecs.removeAll(*iter);
689 return codecList;
692 ///////////////////////////////////////////////////////////////////////////////
693 // SELF-TEST
694 ///////////////////////////////////////////////////////////////////////////////
696 int MUtils::Internal::selfTest(const char *const buildKey, const bool debug)
698 static const bool MY_DEBUG_FLAG = MUTILS_DEBUG;
699 static const char *const MY_BUILD_KEY = __DATE__ "@" __TIME__;
701 if(strncmp(buildKey, MY_BUILD_KEY, 13) || (MY_DEBUG_FLAG != debug))
703 MUtils::OS::system_message_err(L"MUtils", L"FATAL ERROR: MUtils library version mismatch detected!");
704 MUtils::OS::system_message_wrn(L"MUtils", L"Perform a clean(!) re-install of the application to fix the problem!");
705 abort();
707 return 0;