1 ///////////////////////////////////////////////////////////////////////////////
2 // MuldeR's Utilities for Qt
3 // Copyright (C) 2004-2014 LoRd_MuldeR <MuldeR2@GMX.de>
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.
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 //////////////////////////////////////////////////////////////////////////////////
27 #include <MUtils/Global.h>
28 #include <MUtils/OSSupport.h>
31 #include "DirLocker.h"
32 #include "3rd_party/strnatcmp/include/strnatcmp.h"
36 #include <QReadWriteLock>
50 ///////////////////////////////////////////////////////////////////////////////
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)
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);
74 void MUtils::seed_rand(void)
76 qsrand(mix_function(clock(), time(NULL), _getpid()));
79 quint32 MUtils::next_rand32(void)
81 quint32 rnd = 0xDEADBEEF;
90 for(size_t i = 0; i < sizeof(quint32); i++)
92 rnd = (rnd << 8) ^ qrand();
98 quint64 MUtils::next_rand64(void)
100 return (quint64(next_rand32()) << 32) | quint64(next_rand32());
103 QString MUtils::rand_str(const bool &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 ///////////////////////////////////////////////////////////////////////////////
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();
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);
146 catch(MUtils::Internal::DirLockException&)
148 /*ignore error and try again*/
155 static void temp_folder_cleanup_helper(const QString &tempPath)
158 for(int i = 0; i < 32; i++)
160 QDir::setCurrent(QDir::rootPath());
161 if(MUtils::remove_directory(tempPath, true))
166 MUtils::OS::sleep_ms(125);
170 MUtils::OS::system_message_wrn(L"Temp Cleaner", L"Warning: Not all temporary files could be removed!");
174 static void temp_folder_cleaup(void)
176 QWriteLocker writeLock(&g_temp_folder_lock);
178 //Clean the directory
179 while(!g_temp_folder_file.isNull())
181 const QString tempPath = g_temp_folder_file->getPath();
182 g_temp_folder_file.reset(NULL);
183 temp_folder_cleanup_helper(tempPath);
187 const QString &MUtils::temp_folder(void)
189 QReadLocker readLock(&g_temp_folder_lock);
191 //Already initialized?
192 if(!g_temp_folder_file.isNull())
194 return g_temp_folder_file->getPath();
197 //Obtain the write lock to initilaize
199 QWriteLocker writeLock(&g_temp_folder_lock);
201 //Still uninitilaized?
202 if(!g_temp_folder_file.isNull())
204 return g_temp_folder_file->getPath();
207 //Try the %TMP% or %TEMP% directory first
208 if(MUtils::Internal::DirLock *lockFile = try_init_temp_folder(QDir::tempPath()))
210 g_temp_folder_file.reset(lockFile);
211 atexit(temp_folder_cleaup);
212 return lockFile->getPath();
215 qWarning("%%TEMP%% directory not found -> trying fallback mode now!");
216 static const OS::known_folder_t FOLDER_ID[2] = { OS::FOLDER_LOCALAPPDATA, OS::FOLDER_SYSTROOT_DIR };
217 for(size_t id = 0; id < 2; id++)
219 const QString &knownFolder = OS::known_folder(FOLDER_ID[id]);
220 if(!knownFolder.isEmpty())
222 const QString tempRoot = try_create_subfolder(knownFolder, QLatin1String("TEMP"));
223 if(!tempRoot.isEmpty())
225 if(MUtils::Internal::DirLock *lockFile = try_init_temp_folder(tempRoot))
227 g_temp_folder_file.reset(lockFile);
228 atexit(temp_folder_cleaup);
229 return lockFile->getPath();
235 qFatal("Temporary directory could not be initialized !!!");
236 return (*((QString*)NULL));
239 ///////////////////////////////////////////////////////////////////////////////
240 // REMOVE DIRECTORY / FILE
241 ///////////////////////////////////////////////////////////////////////////////
243 static const QFile::Permissions FILE_PERMISSIONS_NONE = QFile::ReadOther | QFile::WriteOther;
245 bool MUtils::remove_file(const QString &fileName)
247 QFileInfo fileInfo(fileName);
248 if(!(fileInfo.exists() && fileInfo.isFile()))
253 for(int i = 0; i < 32; i++)
255 QFile file(fileName);
256 file.setPermissions(FILE_PERMISSIONS_NONE);
257 if((!(fileInfo.exists() && fileInfo.isFile())) || file.remove())
264 qWarning("Could not delete \"%s\"", MUTILS_UTF8(fileName));
268 static bool remove_directory_helper(const QDir &folder)
274 const QString dirName = folder.dirName();
275 if(!dirName.isEmpty())
280 QFile::setPermissions(folder.absolutePath(), FILE_PERMISSIONS_NONE);
281 if(parent.rmdir(dirName))
290 bool MUtils::remove_directory(const QString &folderPath, const bool &recursive)
292 QDir folder(folderPath);
300 const QFileInfoList entryList = folder.entryInfoList(QDir::AllEntries | QDir::NoDotAndDotDot | QDir::Hidden);
301 for(QFileInfoList::ConstIterator iter = entryList.constBegin(); iter != entryList.constEnd(); iter++)
305 remove_directory(iter->canonicalFilePath(), true);
307 else if(iter->isFile())
309 remove_file(iter->canonicalFilePath());
314 for(int i = 0; i < 32; i++)
316 if(remove_directory_helper(folder))
323 qWarning("Could not rmdir \"%s\"", MUTILS_UTF8(folderPath));
327 ///////////////////////////////////////////////////////////////////////////////
329 ///////////////////////////////////////////////////////////////////////////////
331 void MUtils::init_process(QProcess &process, const QString &wokringDir, const bool bReplaceTempDir)
333 //Environment variable names
334 static const char *const s_envvar_names_temp[] =
336 "TEMP", "TMP", "TMPDIR", "HOME", "USERPROFILE", "HOMEPATH", NULL
338 static const char *const s_envvar_names_remove[] =
340 "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
343 //Initialize environment
344 QProcessEnvironment env = process.processEnvironment();
345 if(env.isEmpty()) env = QProcessEnvironment::systemEnvironment();
347 //Clean a number of enviroment variables that might affect our tools
348 for(size_t i = 0; s_envvar_names_remove[i]; i++)
350 env.remove(QString::fromLatin1(s_envvar_names_remove[i]));
351 env.remove(QString::fromLatin1(s_envvar_names_remove[i]).toLower());
354 const QString tempDir = QDir::toNativeSeparators(temp_folder());
356 //Replace TEMP directory in environment
359 for(size_t i = 0; s_envvar_names_temp[i]; i++)
361 env.insert(s_envvar_names_temp[i], tempDir);
365 //Setup PATH variable
366 const QString path = env.value("PATH", QString()).trimmed();
367 env.insert("PATH", path.isEmpty() ? tempDir : QString("%1;%2").arg(tempDir, path));
369 //Setup QPorcess object
370 process.setWorkingDirectory(wokringDir);
371 process.setProcessChannelMode(QProcess::MergedChannels);
372 process.setReadChannel(QProcess::StandardOutput);
373 process.setProcessEnvironment(env);
376 ///////////////////////////////////////////////////////////////////////////////
377 // NATURAL ORDER STRING COMPARISON
378 ///////////////////////////////////////////////////////////////////////////////
380 static bool natural_string_sort_helper(const QString &str1, const QString &str2)
382 return (MUtils::Internal::NaturalSort::strnatcmp(MUTILS_WCHR(str1), MUTILS_WCHR(str2)) < 0);
385 static bool natural_string_sort_helper_fold_case(const QString &str1, const QString &str2)
387 return (MUtils::Internal::NaturalSort::strnatcasecmp(MUTILS_WCHR(str1), MUTILS_WCHR(str2)) < 0);
390 void MUtils::natural_string_sort(QStringList &list, const bool bIgnoreCase)
392 qSort(list.begin(), list.end(), bIgnoreCase ? natural_string_sort_helper_fold_case : natural_string_sort_helper);
395 ///////////////////////////////////////////////////////////////////////////////
397 ///////////////////////////////////////////////////////////////////////////////
401 const char *const search;
402 const char *const replace;
419 QString MUtils::clean_file_name(const QString &name)
421 QString str = name.simplified();
423 for(size_t i = 0; CLEAN_FILE_NAME[i].search; i++)
425 str.replace(CLEAN_FILE_NAME[i].search, CLEAN_FILE_NAME[i].replace);
428 QRegExp regExp("\"(.+)\"");
429 regExp.setMinimal(true);
430 str.replace(regExp, "`\\1ยด");
432 return str.simplified();
435 QString MUtils::clean_file_path(const QString &path)
437 QStringList parts = path.simplified().replace("\\", "/").split("/", QString::SkipEmptyParts);
439 for(int i = 0; i < parts.count(); i++)
441 parts[i] = MUtils::clean_file_name(parts[i]);
444 return parts.join("/");
447 ///////////////////////////////////////////////////////////////////////////////
448 // REGULAR EXPESSION HELPER
449 ///////////////////////////////////////////////////////////////////////////////
451 bool MUtils::regexp_parse_uint32(const QRegExp ®exp, quint32 &value)
453 return regexp_parse_uint32(regexp, &value, 1);
456 bool MUtils::regexp_parse_uint32(const QRegExp ®exp, quint32 *values, const size_t &count)
458 const QStringList caps = regexp.capturedTexts();
460 if(caps.isEmpty() || (quint32(caps.count()) <= count))
465 for(size_t i = 0; i < count; i++)
468 values[i] = caps[i+1].toUInt(&ok);
478 ///////////////////////////////////////////////////////////////////////////////
479 // AVAILABLE CODEPAGES
480 ///////////////////////////////////////////////////////////////////////////////
482 QStringList MUtils::available_codepages(const bool &noAliases)
484 QStringList codecList;
485 QList<QByteArray> availableCodecs = QTextCodec::availableCodecs();
487 while(!availableCodecs.isEmpty())
489 const QByteArray current = availableCodecs.takeFirst();
490 if(!current.toLower().startsWith("system"))
492 codecList << QString::fromLatin1(current.constData(), current.size());
495 if(QTextCodec *const currentCodec = QTextCodec::codecForName(current.constData()))
497 const QList<QByteArray> aliases = currentCodec->aliases();
498 for(QList<QByteArray>::ConstIterator iter = aliases.constBegin(); iter != aliases.constEnd(); iter++)
500 availableCodecs.removeAll(*iter);
510 ///////////////////////////////////////////////////////////////////////////////
512 ///////////////////////////////////////////////////////////////////////////////
514 int MUtils::Internal::selfTest(const char *const buildKey, const bool debug)
516 static const bool MY_DEBUG_FLAG = MUTILS_DEBUG;
517 static const char *const MY_BUILD_KEY = __DATE__"@"__TIME__;
519 if(strncmp(buildKey, MY_BUILD_KEY, 14) || (MY_DEBUG_FLAG != debug))
521 MUtils::OS::system_message_err(L"MUtils", L"FATAL ERROR: MUtils library version mismatch detected!");
522 MUtils::OS::system_message_wrn(L"MUtils", L"Please re-build the complete solution in order to fix this issue!");