Improved handling of command-line arguments: Arguments are now provided in the from...
[MUtilities.git] / src / Global.cpp
blob613482ba1ae6ffcda0dabcc4aa63caff9c586a6c
1 ///////////////////////////////////////////////////////////////////////////////
2 // MuldeR's Utilities for Qt
3 // Copyright (C) 2004-2014 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>
40 //CRT
41 #include <cstdlib>
42 #include <ctime>
43 #include <process.h>
45 //VLD
46 #ifdef _MSC_VER
47 #include <vld.h>
48 #endif
50 ///////////////////////////////////////////////////////////////////////////////
51 // Random Support
52 ///////////////////////////////////////////////////////////////////////////////
54 //Robert Jenkins' 96 bit Mix Function
55 static unsigned int mix_function(const unsigned int x, const unsigned int y, const unsigned int z)
57 unsigned int a = x;
58 unsigned int b = y;
59 unsigned int c = z;
61 a=a-b; a=a-c; a=a^(c >> 13);
62 b=b-c; b=b-a; b=b^(a << 8 );
63 c=c-a; c=c-b; c=c^(b >> 13);
64 a=a-b; a=a-c; a=a^(c >> 12);
65 b=b-c; b=b-a; b=b^(a << 16);
66 c=c-a; c=c-b; c=c^(b >> 5 );
67 a=a-b; a=a-c; a=a^(c >> 3 );
68 b=b-c; b=b-a; b=b^(a << 10);
69 c=c-a; c=c-b; c=c^(b >> 15);
71 return a ^ b ^ c;
74 void MUtils::seed_rand(void)
76 qsrand(mix_function(clock(), time(NULL), _getpid()));
79 quint32 MUtils::next_rand32(void)
81 quint32 rnd = 0xDEADBEEF;
83 #ifdef _CRT_RAND_S
84 if(rand_s(&rnd) == 0)
86 return rnd;
88 #endif //_CRT_RAND_S
90 for(size_t i = 0; i < sizeof(quint32); i++)
92 rnd = (rnd << 8) ^ qrand();
95 return rnd;
98 quint64 MUtils::next_rand64(void)
100 return (quint64(next_rand32()) << 32) | quint64(next_rand32());
103 QString MUtils::rand_str(const bool &bLong)
105 if(!bLong)
107 return QString::number(next_rand64(), 16).rightJustified(16, QLatin1Char('0'));
109 return QString("%1%2").arg(rand_str(false), rand_str(false));
112 ///////////////////////////////////////////////////////////////////////////////
113 // TEMP FOLDER
114 ///////////////////////////////////////////////////////////////////////////////
116 static QScopedPointer<MUtils::Internal::DirLock> g_temp_folder_file;
117 static QReadWriteLock g_temp_folder_lock;
119 static QString try_create_subfolder(const QString &baseDir, const QString &postfix)
121 const QString baseDirPath = QDir(baseDir).absolutePath();
122 for(int i = 0; i < 32; i++)
124 QDir directory(baseDirPath);
125 if(directory.mkpath(postfix) && directory.cd(postfix))
127 return directory.canonicalPath();
130 return QString();
133 static MUtils::Internal::DirLock *try_init_temp_folder(const QString &baseDir)
135 const QString tempPath = try_create_subfolder(baseDir, MUtils::rand_str());
136 if(!tempPath.isEmpty())
138 for(int i = 0; i < 32; i++)
140 MUtils::Internal::DirLock *lockFile = NULL;
143 lockFile = new MUtils::Internal::DirLock(tempPath);
144 return lockFile;
146 catch(MUtils::Internal::DirLockException&)
148 /*ignore error and try again*/
152 return NULL;
155 static void temp_folder_cleanup_helper(const QString &tempPath)
157 bool okay = false;
158 for(int i = 0; i < 32; i++)
160 if(MUtils::remove_directory(tempPath, true))
162 okay = true;
163 break;
165 MUtils::OS::sleep_ms(125);
167 if(!okay)
169 MUtils::OS::system_message_wrn(L"Temp Cleaner", L"Warning: Not all temporary files could be removed!");
173 static void temp_folder_cleaup(void)
175 QWriteLocker writeLock(&g_temp_folder_lock);
177 //Clean the directory
178 while(!g_temp_folder_file.isNull())
180 const QString tempPath = g_temp_folder_file->getPath();
181 g_temp_folder_file.reset(NULL);
182 temp_folder_cleanup_helper(tempPath);
186 const QString &MUtils::temp_folder(void)
188 QReadLocker readLock(&g_temp_folder_lock);
190 //Already initialized?
191 if(!g_temp_folder_file.isNull())
193 return g_temp_folder_file->getPath();
196 //Obtain the write lock to initilaize
197 readLock.unlock();
198 QWriteLocker writeLock(&g_temp_folder_lock);
200 //Still uninitilaized?
201 if(!g_temp_folder_file.isNull())
203 return g_temp_folder_file->getPath();
206 //Try the %TMP% or %TEMP% directory first
207 if(MUtils::Internal::DirLock *lockFile = try_init_temp_folder(QDir::tempPath()))
209 g_temp_folder_file.reset(lockFile);
210 atexit(temp_folder_cleaup);
211 return lockFile->getPath();
214 qWarning("%%TEMP%% directory not found -> trying fallback mode now!");
215 static const OS::known_folder_t FOLDER_ID[2] = { OS::FOLDER_LOCALAPPDATA, OS::FOLDER_SYSTROOT_DIR };
216 for(size_t id = 0; id < 2; id++)
218 const QString &knownFolder = OS::known_folder(FOLDER_ID[id]);
219 if(!knownFolder.isEmpty())
221 const QString tempRoot = try_create_subfolder(knownFolder, QLatin1String("TEMP"));
222 if(!tempRoot.isEmpty())
224 if(MUtils::Internal::DirLock *lockFile = try_init_temp_folder(tempRoot))
226 g_temp_folder_file.reset(lockFile);
227 atexit(temp_folder_cleaup);
228 return lockFile->getPath();
234 qFatal("Temporary directory could not be initialized !!!");
235 return (*((QString*)NULL));
238 ///////////////////////////////////////////////////////////////////////////////
239 // REMOVE DIRECTORY / FILE
240 ///////////////////////////////////////////////////////////////////////////////
242 bool MUtils::remove_file(const QString &fileName)
244 QFileInfo fileInfo(fileName);
245 if(!(fileInfo.exists() && fileInfo.isFile()))
247 return true;
250 for(int i = 0; i < 32; i++)
252 QFile file(fileName);
253 file.setPermissions(QFile::ReadOther | QFile::WriteOther);
254 if((!(fileInfo.exists() && fileInfo.isFile())) || file.remove())
256 return true;
258 fileInfo.refresh();
261 qWarning("Could not delete \"%s\"", MUTILS_UTF8(fileName));
262 return false;
265 static bool remove_directory_helper(QDir folder)
267 if(!folder.exists())
269 return true;
272 const QString dirName = folder.dirName();
273 if(dirName.isEmpty() || (!folder.cdUp()))
275 return false;
278 return folder.rmdir(dirName);
281 bool MUtils::remove_directory(const QString &folderPath, const bool &recursive)
283 QDir folder(folderPath);
284 if(!folder.exists())
286 return true;
289 if(recursive)
291 const QFileInfoList entryList = folder.entryInfoList(QDir::AllEntries | QDir::NoDotAndDotDot | QDir::Hidden);
292 for(QFileInfoList::ConstIterator iter = entryList.constBegin(); iter != entryList.constEnd(); iter++)
294 if(iter->isDir())
296 remove_directory(iter->canonicalFilePath(), true);
298 else if(iter->isFile())
300 remove_file(iter->canonicalFilePath());
305 for(int i = 0; i < 32; i++)
307 if(!folder.exists())
309 return true;
311 const QString dirName = folder.dirName();
312 if(!dirName.isEmpty())
314 QDir parent(folder);
315 if(parent.cdUp())
317 if(parent.rmdir(dirName))
319 return true;
323 folder.refresh();
326 qWarning("Could not rmdir \"%s\"", MUTILS_UTF8(folderPath));
327 return false;
330 ///////////////////////////////////////////////////////////////////////////////
331 // PROCESS UTILS
332 ///////////////////////////////////////////////////////////////////////////////
334 void MUtils::init_process(QProcess &process, const QString &wokringDir, const bool bReplaceTempDir)
336 //Environment variable names
337 static const char *const s_envvar_names_temp[] =
339 "TEMP", "TMP", "TMPDIR", "HOME", "USERPROFILE", "HOMEPATH", NULL
341 static const char *const s_envvar_names_remove[] =
343 "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
346 //Initialize environment
347 QProcessEnvironment env = process.processEnvironment();
348 if(env.isEmpty()) env = QProcessEnvironment::systemEnvironment();
350 //Clean a number of enviroment variables that might affect our tools
351 for(size_t i = 0; s_envvar_names_remove[i]; i++)
353 env.remove(QString::fromLatin1(s_envvar_names_remove[i]));
354 env.remove(QString::fromLatin1(s_envvar_names_remove[i]).toLower());
357 const QString tempDir = QDir::toNativeSeparators(temp_folder());
359 //Replace TEMP directory in environment
360 if(bReplaceTempDir)
362 for(size_t i = 0; s_envvar_names_temp[i]; i++)
364 env.insert(s_envvar_names_temp[i], tempDir);
368 //Setup PATH variable
369 const QString path = env.value("PATH", QString()).trimmed();
370 env.insert("PATH", path.isEmpty() ? tempDir : QString("%1;%2").arg(tempDir, path));
372 //Setup QPorcess object
373 process.setWorkingDirectory(wokringDir);
374 process.setProcessChannelMode(QProcess::MergedChannels);
375 process.setReadChannel(QProcess::StandardOutput);
376 process.setProcessEnvironment(env);
379 ///////////////////////////////////////////////////////////////////////////////
380 // NATURAL ORDER STRING COMPARISON
381 ///////////////////////////////////////////////////////////////////////////////
383 static bool natural_string_sort_helper(const QString &str1, const QString &str2)
385 return (MUtils::Internal::NaturalSort::strnatcmp(MUTILS_WCHR(str1), MUTILS_WCHR(str2)) < 0);
388 static bool natural_string_sort_helper_fold_case(const QString &str1, const QString &str2)
390 return (MUtils::Internal::NaturalSort::strnatcasecmp(MUTILS_WCHR(str1), MUTILS_WCHR(str2)) < 0);
393 void MUtils::natural_string_sort(QStringList &list, const bool bIgnoreCase)
395 qSort(list.begin(), list.end(), bIgnoreCase ? natural_string_sort_helper_fold_case : natural_string_sort_helper);
398 ///////////////////////////////////////////////////////////////////////////////
399 // CLEAN FILE PATH
400 ///////////////////////////////////////////////////////////////////////////////
402 static const struct
404 const char *const search;
405 const char *const replace;
407 CLEAN_FILE_NAME[] =
409 { "\\", "-" },
410 { " / ", ", " },
411 { "/", "," },
412 { ":", "-" },
413 { "*", "x" },
414 { "?", "!" },
415 { "<", "[" },
416 { ">", "]" },
417 { "|", "!" },
418 { "\"", "'" },
419 { NULL, NULL }
422 QString MUtils::clean_file_name(const QString &name)
424 QString str = name.simplified();
426 for(size_t i = 0; CLEAN_FILE_NAME[i].search; i++)
428 str.replace(CLEAN_FILE_NAME[i].search, CLEAN_FILE_NAME[i].replace);
431 QRegExp regExp("\"(.+)\"");
432 regExp.setMinimal(true);
433 str.replace(regExp, "`\\1ยด");
435 return str.simplified();
438 QString MUtils::clean_file_path(const QString &path)
440 QStringList parts = path.simplified().replace("\\", "/").split("/", QString::SkipEmptyParts);
442 for(int i = 0; i < parts.count(); i++)
444 parts[i] = MUtils::clean_file_name(parts[i]);
447 return parts.join("/");
450 ///////////////////////////////////////////////////////////////////////////////
451 // REGULAR EXPESSION HELPER
452 ///////////////////////////////////////////////////////////////////////////////
454 bool MUtils::regexp_parse_uint32(const QRegExp &regexp, quint32 &value)
456 return regexp_parse_uint32(regexp, &value, 1);
459 bool MUtils::regexp_parse_uint32(const QRegExp &regexp, quint32 *values, const size_t &count)
461 const QStringList caps = regexp.capturedTexts();
463 if(caps.isEmpty() || (quint32(caps.count()) <= count))
465 return false;
468 for(size_t i = 0; i < count; i++)
470 bool ok = false;
471 values[i] = caps[i+1].toUInt(&ok);
472 if(!ok)
474 return false;
478 return true;
481 ///////////////////////////////////////////////////////////////////////////////
482 // AVAILABLE CODEPAGES
483 ///////////////////////////////////////////////////////////////////////////////
485 QStringList MUtils::available_codepages(const bool &noAliases)
487 QStringList codecList;
488 QList<QByteArray> availableCodecs = QTextCodec::availableCodecs();
490 while(!availableCodecs.isEmpty())
492 const QByteArray current = availableCodecs.takeFirst();
493 if(!current.toLower().startsWith("system"))
495 codecList << QString::fromLatin1(current.constData(), current.size());
496 if(noAliases)
498 if(QTextCodec *const currentCodec = QTextCodec::codecForName(current.constData()))
500 const QList<QByteArray> aliases = currentCodec->aliases();
501 for(QList<QByteArray>::ConstIterator iter = aliases.constBegin(); iter != aliases.constEnd(); iter++)
503 availableCodecs.removeAll(*iter);
510 return codecList;
513 ///////////////////////////////////////////////////////////////////////////////
514 // SELF-TEST
515 ///////////////////////////////////////////////////////////////////////////////
517 int MUtils::Internal::selfTest(const char *const buildKey, const bool debug)
519 static const bool MY_DEBUG_FLAG = MUTILS_DEBUG;
520 static const char *const MY_BUILD_KEY = __DATE__"@"__TIME__;
522 if(strncmp(buildKey, MY_BUILD_KEY, 14) || (MY_DEBUG_FLAG != debug))
524 MUtils::OS::system_message_err(L"MUtils", L"FATAL ERROR: MUtils library version mismatch detected!");
525 MUtils::OS::system_message_wrn(L"MUtils", L"Please re-build the complete solution in order to fix this issue!");
526 abort();
528 return 0;