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_cleaup(void)
157 QWriteLocker writeLock(&g_temp_folder_lock);
159 //Clean the directory
160 while(!g_temp_folder_file.isNull())
162 g_temp_folder_file.reset(NULL);
166 const QString &MUtils::temp_folder(void)
168 QReadLocker readLock(&g_temp_folder_lock);
170 //Already initialized?
171 if(!g_temp_folder_file.isNull())
173 return g_temp_folder_file->getPath();
176 //Obtain the write lock to initilaize
178 QWriteLocker writeLock(&g_temp_folder_lock);
180 //Still uninitilaized?
181 if(!g_temp_folder_file.isNull())
183 return g_temp_folder_file->getPath();
186 //Try the %TMP% or %TEMP% directory first
187 if(MUtils::Internal::DirLock *lockFile = try_init_temp_folder(QDir::tempPath()))
189 g_temp_folder_file.reset(lockFile);
190 atexit(temp_folder_cleaup);
191 return lockFile->getPath();
194 qWarning("%%TEMP%% directory not found -> trying fallback mode now!");
195 static const OS::known_folder_t FOLDER_ID[2] = { OS::FOLDER_LOCALAPPDATA, OS::FOLDER_SYSTROOT_DIR };
196 for(size_t id = 0; id < 2; id++)
198 const QString &knownFolder = OS::known_folder(FOLDER_ID[id]);
199 if(!knownFolder.isEmpty())
201 const QString tempRoot = try_create_subfolder(knownFolder, QLatin1String("TEMP"));
202 if(!tempRoot.isEmpty())
204 if(MUtils::Internal::DirLock *lockFile = try_init_temp_folder(tempRoot))
206 g_temp_folder_file.reset(lockFile);
207 atexit(temp_folder_cleaup);
208 return lockFile->getPath();
214 qFatal("Temporary directory could not be initialized !!!");
215 return (*((QString*)NULL));
218 ///////////////////////////////////////////////////////////////////////////////
219 // REMOVE DIRECTORY / FILE
220 ///////////////////////////////////////////////////////////////////////////////
222 bool MUtils::remove_file(const QString &fileName)
224 QFileInfo fileInfo(fileName);
225 if(!(fileInfo.exists() && fileInfo.isFile()))
230 for(int i = 0; i < 32; i++)
232 QFile file(fileName);
233 file.setPermissions(QFile::ReadOther | QFile::WriteOther);
234 if((!(fileInfo.exists() && fileInfo.isFile())) || file.remove())
241 qWarning("Could not delete \"%s\"", MUTILS_UTF8(fileName));
245 static bool remove_directory_helper(QDir folder)
252 const QString dirName = folder.dirName();
253 if(dirName.isEmpty() || (!folder.cdUp()))
258 return folder.rmdir(dirName);
261 bool MUtils::remove_directory(const QString &folderPath, const bool &recursive)
263 QDir folder(folderPath);
271 const QFileInfoList entryList = folder.entryInfoList(QDir::AllEntries | QDir::NoDotAndDotDot | QDir::Hidden);
272 for(QFileInfoList::ConstIterator iter = entryList.constBegin(); iter != entryList.constEnd(); iter++)
276 remove_directory(iter->canonicalFilePath(), true);
278 else if(iter->isFile())
280 remove_file(iter->canonicalFilePath());
285 for(int i = 0; i < 32; i++)
291 const QString dirName = folder.dirName();
292 if(!dirName.isEmpty())
297 if(parent.rmdir(dirName))
306 qWarning("Could not rmdir \"%s\"", MUTILS_UTF8(folderPath));
310 ///////////////////////////////////////////////////////////////////////////////
312 ///////////////////////////////////////////////////////////////////////////////
314 void MUtils::init_process(QProcess &process, const QString &wokringDir, const bool bReplaceTempDir)
316 //Environment variable names
317 static const char *const s_envvar_names_temp[] =
319 "TEMP", "TMP", "TMPDIR", "HOME", "USERPROFILE", "HOMEPATH", NULL
321 static const char *const s_envvar_names_remove[] =
323 "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
326 //Initialize environment
327 QProcessEnvironment env = process.processEnvironment();
328 if(env.isEmpty()) env = QProcessEnvironment::systemEnvironment();
330 //Clean a number of enviroment variables that might affect our tools
331 for(size_t i = 0; s_envvar_names_remove[i]; i++)
333 env.remove(QString::fromLatin1(s_envvar_names_remove[i]));
334 env.remove(QString::fromLatin1(s_envvar_names_remove[i]).toLower());
337 const QString tempDir = QDir::toNativeSeparators(temp_folder());
339 //Replace TEMP directory in environment
342 for(size_t i = 0; s_envvar_names_temp[i]; i++)
344 env.insert(s_envvar_names_temp[i], tempDir);
348 //Setup PATH variable
349 const QString path = env.value("PATH", QString()).trimmed();
350 env.insert("PATH", path.isEmpty() ? tempDir : QString("%1;%2").arg(tempDir, path));
352 //Setup QPorcess object
353 process.setWorkingDirectory(wokringDir);
354 process.setProcessChannelMode(QProcess::MergedChannels);
355 process.setReadChannel(QProcess::StandardOutput);
356 process.setProcessEnvironment(env);
359 ///////////////////////////////////////////////////////////////////////////////
360 // NATURAL ORDER STRING COMPARISON
361 ///////////////////////////////////////////////////////////////////////////////
363 static bool natural_string_sort_helper(const QString &str1, const QString &str2)
365 return (MUtils::Internal::NaturalSort::strnatcmp(MUTILS_WCHR(str1), MUTILS_WCHR(str2)) < 0);
368 static bool natural_string_sort_helper_fold_case(const QString &str1, const QString &str2)
370 return (MUtils::Internal::NaturalSort::strnatcasecmp(MUTILS_WCHR(str1), MUTILS_WCHR(str2)) < 0);
373 void MUtils::natural_string_sort(QStringList &list, const bool bIgnoreCase)
375 qSort(list.begin(), list.end(), bIgnoreCase ? natural_string_sort_helper_fold_case : natural_string_sort_helper);
378 ///////////////////////////////////////////////////////////////////////////////
380 ///////////////////////////////////////////////////////////////////////////////
384 const char *const search;
385 const char *const replace;
402 QString MUtils::clean_file_name(const QString &name)
404 QString str = name.simplified();
406 for(size_t i = 0; CLEAN_FILE_NAME[i].search; i++)
408 str.replace(CLEAN_FILE_NAME[i].search, CLEAN_FILE_NAME[i].replace);
411 QRegExp regExp("\"(.+)\"");
412 regExp.setMinimal(true);
413 str.replace(regExp, "`\\1ยด");
415 return str.simplified();
418 QString MUtils::clean_file_path(const QString &path)
420 QStringList parts = path.simplified().replace("\\", "/").split("/", QString::SkipEmptyParts);
422 for(int i = 0; i < parts.count(); i++)
424 parts[i] = MUtils::clean_file_name(parts[i]);
427 return parts.join("/");
430 ///////////////////////////////////////////////////////////////////////////////
431 // REGULAR EXPESSION HELPER
432 ///////////////////////////////////////////////////////////////////////////////
434 bool MUtils::regexp_parse_uint32(const QRegExp ®exp, quint32 &value)
436 return regexp_parse_uint32(regexp, &value, 1);
439 bool MUtils::regexp_parse_uint32(const QRegExp ®exp, quint32 *values, const size_t &count)
441 const QStringList caps = regexp.capturedTexts();
443 if(caps.isEmpty() || (quint32(caps.count()) <= count))
448 for(size_t i = 0; i < count; i++)
451 values[i] = caps[i+1].toUInt(&ok);
461 ///////////////////////////////////////////////////////////////////////////////
462 // AVAILABLE CODEPAGES
463 ///////////////////////////////////////////////////////////////////////////////
465 QStringList MUtils::available_codepages(const bool &noAliases)
467 QStringList codecList;
468 QList<QByteArray> availableCodecs = QTextCodec::availableCodecs();
470 while(!availableCodecs.isEmpty())
472 const QByteArray current = availableCodecs.takeFirst();
473 if(!current.toLower().startsWith("system"))
475 codecList << QString::fromLatin1(current.constData(), current.size());
478 if(QTextCodec *const currentCodec = QTextCodec::codecForName(current.constData()))
480 const QList<QByteArray> aliases = currentCodec->aliases();
481 for(QList<QByteArray>::ConstIterator iter = aliases.constBegin(); iter != aliases.constEnd(); iter++)
483 availableCodecs.removeAll(*iter);
493 ///////////////////////////////////////////////////////////////////////////////
495 ///////////////////////////////////////////////////////////////////////////////
497 int MUtils::Internal::selfTest(const char *const buildKey, const bool debug)
499 static const bool MY_DEBUG_FLAG = MUTILS_DEBUG;
500 static const char *const MY_BUILD_KEY = __DATE__"@"__TIME__;
502 if(strncmp(buildKey, MY_BUILD_KEY, 14) || (MY_DEBUG_FLAG != debug))
504 MUtils::OS::system_message_err(L"MUtils", L"FATAL ERROR: MUtils library version mismatch detected!");
505 MUtils::OS::system_message_wrn(L"MUtils", L"Please re-build the complete solution in order to fix this issue!");