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>
48 ///////////////////////////////////////////////////////////////////////////////
50 ///////////////////////////////////////////////////////////////////////////////
52 //Robert Jenkins' 96 bit Mix Function
53 static unsigned int mix_function(const unsigned int x, const unsigned int y, const unsigned int z)
59 a=a-b; a=a-c; a=a^(c >> 13);
60 b=b-c; b=b-a; b=b^(a << 8 );
61 c=c-a; c=c-b; c=c^(b >> 13);
62 a=a-b; a=a-c; a=a^(c >> 12);
63 b=b-c; b=b-a; b=b^(a << 16);
64 c=c-a; c=c-b; c=c^(b >> 5 );
65 a=a-b; a=a-c; a=a^(c >> 3 );
66 b=b-c; b=b-a; b=b^(a << 10);
67 c=c-a; c=c-b; c=c^(b >> 15);
72 void MUtils::seed_rand(void)
74 qsrand(mix_function(clock(), time(NULL), _getpid()));
77 quint32 MUtils::next_rand32(void)
79 quint32 rnd = 0xDEADBEEF;
88 for(size_t i = 0; i < sizeof(quint32); i++)
90 rnd = (rnd << 8) ^ qrand();
96 quint64 MUtils::next_rand64(void)
98 return (quint64(next_rand32()) << 32) | quint64(next_rand32());
101 QString MUtils::rand_str(const bool &bLong)
105 return QString::number(next_rand64(), 16).rightJustified(16, QLatin1Char('0'));
107 return QString("%1%2").arg(rand_str(false), rand_str(false));
110 ///////////////////////////////////////////////////////////////////////////////
112 ///////////////////////////////////////////////////////////////////////////////
114 static QScopedPointer<MUtils::Internal::DirLock> g_temp_folder_file;
115 static QReadWriteLock g_temp_folder_lock;
117 static QString try_create_subfolder(const QString &baseDir, const QString &postfix)
119 const QString baseDirPath = QDir(baseDir).absolutePath();
120 for(int i = 0; i < 32; i++)
122 QDir directory(baseDirPath);
123 if(directory.mkpath(postfix) && directory.cd(postfix))
125 return directory.canonicalPath();
131 static MUtils::Internal::DirLock *try_init_temp_folder(const QString &baseDir)
133 const QString tempPath = try_create_subfolder(baseDir, MUtils::rand_str());
134 if(!tempPath.isEmpty())
136 for(int i = 0; i < 32; i++)
138 MUtils::Internal::DirLock *lockFile = NULL;
141 lockFile = new MUtils::Internal::DirLock(tempPath);
144 catch(MUtils::Internal::DirLockException&)
146 /*ignore error and try again*/
153 const QString &MUtils::temp_folder(void)
155 QReadLocker readLock(&g_temp_folder_lock);
157 //Already initialized?
158 if(!g_temp_folder_file.isNull())
160 return g_temp_folder_file->path();
163 //Obtain the write lock to initilaize
165 QWriteLocker writeLock(&g_temp_folder_lock);
167 //Still uninitilaized?
168 if(!g_temp_folder_file.isNull())
170 return g_temp_folder_file->path();
173 //Try the %TMP% or %TEMP% directory first
174 if(MUtils::Internal::DirLock *lockFile = try_init_temp_folder(QDir::tempPath()))
176 g_temp_folder_file.reset(lockFile);
177 return lockFile->path();
180 qWarning("%%TEMP%% directory not found -> trying fallback mode now!");
181 static const OS::known_folder_t FOLDER_ID[2] = { OS::FOLDER_LOCALAPPDATA, OS::FOLDER_SYSTROOT_DIR };
182 for(size_t id = 0; id < 2; id++)
184 const QString &knownFolder = OS::known_folder(FOLDER_ID[id]);
185 if(!knownFolder.isEmpty())
187 const QString tempRoot = try_create_subfolder(knownFolder, QLatin1String("TEMP"));
188 if(!tempRoot.isEmpty())
190 if(MUtils::Internal::DirLock *lockFile = try_init_temp_folder(tempRoot))
192 g_temp_folder_file.reset(lockFile);
193 return lockFile->path();
199 qFatal("Temporary directory could not be initialized !!!");
200 return (*((QString*)NULL));
203 ///////////////////////////////////////////////////////////////////////////////
204 // REMOVE DIRECTORY / FILE
205 ///////////////////////////////////////////////////////////////////////////////
207 bool MUtils::remove_file(const QString &fileName)
209 QFileInfo fileInfo(fileName);
210 if(!(fileInfo.exists() && fileInfo.isFile()))
215 for(int i = 0; i < 32; i++)
217 QFile file(fileName);
218 file.setPermissions(QFile::ReadOther | QFile::WriteOther);
225 qWarning("Could not delete \"%s\"", MUTILS_UTF8(fileName));
229 bool MUtils::remove_directory(const QString &folderPath)
231 QDir folder(folderPath);
237 const QFileInfoList entryList = folder.entryInfoList(QDir::AllEntries | QDir::NoDotAndDotDot | QDir::Hidden);
238 for(int i = 0; i < entryList.count(); i++)
240 if(entryList.at(i).isDir())
242 remove_directory(entryList.at(i).canonicalFilePath());
246 remove_file(entryList.at(i).canonicalFilePath());
250 for(int i = 0; i < 32; i++)
252 if(folder.rmdir("."))
258 qWarning("Could not rmdir \"%s\"", MUTILS_UTF8(folderPath));
262 ///////////////////////////////////////////////////////////////////////////////
264 ///////////////////////////////////////////////////////////////////////////////
266 void MUtils::init_process(QProcess &process, const QString &wokringDir, const bool bReplaceTempDir)
268 //Environment variable names
269 static const char *const s_envvar_names_temp[] =
271 "TEMP", "TMP", "TMPDIR", "HOME", "USERPROFILE", "HOMEPATH", NULL
273 static const char *const s_envvar_names_remove[] =
275 "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
278 //Initialize environment
279 QProcessEnvironment env = process.processEnvironment();
280 if(env.isEmpty()) env = QProcessEnvironment::systemEnvironment();
282 //Clean a number of enviroment variables that might affect our tools
283 for(size_t i = 0; s_envvar_names_remove[i]; i++)
285 env.remove(QString::fromLatin1(s_envvar_names_remove[i]));
286 env.remove(QString::fromLatin1(s_envvar_names_remove[i]).toLower());
289 const QString tempDir = QDir::toNativeSeparators(temp_folder());
291 //Replace TEMP directory in environment
294 for(size_t i = 0; s_envvar_names_temp[i]; i++)
296 env.insert(s_envvar_names_temp[i], tempDir);
300 //Setup PATH variable
301 const QString path = env.value("PATH", QString()).trimmed();
302 env.insert("PATH", path.isEmpty() ? tempDir : QString("%1;%2").arg(tempDir, path));
304 //Setup QPorcess object
305 process.setWorkingDirectory(wokringDir);
306 process.setProcessChannelMode(QProcess::MergedChannels);
307 process.setReadChannel(QProcess::StandardOutput);
308 process.setProcessEnvironment(env);
311 ///////////////////////////////////////////////////////////////////////////////
312 // NATURAL ORDER STRING COMPARISON
313 ///////////////////////////////////////////////////////////////////////////////
315 static bool natural_string_sort_helper(const QString &str1, const QString &str2)
317 return (MUtils::Internal::NaturalSort::strnatcmp(MUTILS_WCHR(str1), MUTILS_WCHR(str2)) < 0);
320 static bool natural_string_sort_helper_fold_case(const QString &str1, const QString &str2)
322 return (MUtils::Internal::NaturalSort::strnatcasecmp(MUTILS_WCHR(str1), MUTILS_WCHR(str2)) < 0);
325 void MUtils::natural_string_sort(QStringList &list, const bool bIgnoreCase)
327 qSort(list.begin(), list.end(), bIgnoreCase ? natural_string_sort_helper_fold_case : natural_string_sort_helper);
330 ///////////////////////////////////////////////////////////////////////////////
332 ///////////////////////////////////////////////////////////////////////////////
336 const char *const search;
337 const char *const replace;
354 QString MUtils::clean_file_name(const QString &name)
356 QString str = name.simplified();
358 for(size_t i = 0; CLEAN_FILE_NAME[i].search; i++)
360 str.replace(CLEAN_FILE_NAME[i].search, CLEAN_FILE_NAME[i].replace);
363 QRegExp regExp("\"(.+)\"");
364 regExp.setMinimal(true);
365 str.replace(regExp, "`\\1ยด");
367 return str.simplified();
370 QString MUtils::clean_file_path(const QString &path)
372 QStringList parts = path.simplified().replace("\\", "/").split("/", QString::SkipEmptyParts);
374 for(int i = 0; i < parts.count(); i++)
376 parts[i] = MUtils::clean_file_name(parts[i]);
379 return parts.join("/");
382 ///////////////////////////////////////////////////////////////////////////////
383 // AVAILABLE CODEPAGES
384 ///////////////////////////////////////////////////////////////////////////////
386 QStringList MUtils::available_codepages(const bool &noAliases)
388 QStringList codecList;
389 QList<QByteArray> availableCodecs = QTextCodec::availableCodecs();
391 while(!availableCodecs.isEmpty())
393 const QByteArray current = availableCodecs.takeFirst();
394 if(!current.toLower().startsWith("system"))
396 codecList << QString::fromLatin1(current.constData(), current.size());
399 if(QTextCodec *const currentCodec = QTextCodec::codecForName(current.constData()))
401 const QList<QByteArray> aliases = currentCodec->aliases();
402 for(QList<QByteArray>::ConstIterator iter = aliases.constBegin(); iter != aliases.constEnd(); iter++)
404 availableCodecs.removeAll(*iter);
414 ///////////////////////////////////////////////////////////////////////////////
416 ///////////////////////////////////////////////////////////////////////////////
418 int MUtils::Internal::selfTest(const char *const buildKey, const bool debug)
420 static const bool MY_DEBUG_FLAG = MUTILS_DEBUG;
421 static const char *const MY_BUILD_KEY = __DATE__"@"__TIME__;
423 if(strncmp(buildKey, MY_BUILD_KEY, 14) || (MY_DEBUG_FLAG != debug))
425 MUtils::OS::system_message_err(L"MUtils", L"FATAL ERROR: MUtils library version mismatch detected!");
426 MUtils::OS::system_message_wrn(L"MUtils", L"Please re-build the complete solution in order to fix this issue!");