Moved all the Sound-specific functions into MUtilities library.
[MUtilities.git] / src / Global.cpp
blob984b56db737b4b7c19861e0d3fdd91e30beacfe6
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>
39 //CRT
40 #include <cstdlib>
41 #include <ctime>
42 #include <process.h>
44 //VLD
45 #include <vld.h>
47 ///////////////////////////////////////////////////////////////////////////////
48 // Random Support
49 ///////////////////////////////////////////////////////////////////////////////
51 //Robert Jenkins' 96 bit Mix Function
52 static unsigned int mix_function(const unsigned int x, const unsigned int y, const unsigned int z)
54 unsigned int a = x;
55 unsigned int b = y;
56 unsigned int c = z;
58 a=a-b; a=a-c; a=a^(c >> 13);
59 b=b-c; b=b-a; b=b^(a << 8 );
60 c=c-a; c=c-b; c=c^(b >> 13);
61 a=a-b; a=a-c; a=a^(c >> 12);
62 b=b-c; b=b-a; b=b^(a << 16);
63 c=c-a; c=c-b; c=c^(b >> 5 );
64 a=a-b; a=a-c; a=a^(c >> 3 );
65 b=b-c; b=b-a; b=b^(a << 10);
66 c=c-a; c=c-b; c=c^(b >> 15);
68 return a ^ b ^ c;
71 void MUtils::seed_rand(void)
73 qsrand(mix_function(clock(), time(NULL), _getpid()));
76 quint32 MUtils::next_rand32(void)
78 quint32 rnd = 0xDEADBEEF;
80 #ifdef _CRT_RAND_S
81 if(rand_s(&rnd) == 0)
83 return rnd;
85 #endif //_CRT_RAND_S
87 for(size_t i = 0; i < sizeof(quint32); i++)
89 rnd = (rnd << 8) ^ qrand();
92 return rnd;
95 quint64 MUtils::next_rand64(void)
97 return (quint64(next_rand32()) << 32) | quint64(next_rand32());
100 QString MUtils::rand_str(const bool &bLong)
102 if(!bLong)
104 return QString::number(next_rand64(), 16).rightJustified(16, QLatin1Char('0'));
106 return QString("%1%2").arg(rand_str(false), rand_str(false));
109 ///////////////////////////////////////////////////////////////////////////////
110 // TEMP FOLDER
111 ///////////////////////////////////////////////////////////////////////////////
113 static QScopedPointer<MUtils::Internal::DirLock> g_temp_folder_file;
114 static QReadWriteLock g_temp_folder_lock;
116 static QString try_create_subfolder(const QString &baseDir, const QString &postfix)
118 const QString baseDirPath = QDir(baseDir).absolutePath();
119 for(int i = 0; i < 32; i++)
121 QDir directory(baseDirPath);
122 if(directory.mkpath(postfix) && directory.cd(postfix))
124 return directory.canonicalPath();
127 return QString();
130 static MUtils::Internal::DirLock *try_init_temp_folder(const QString &baseDir)
132 const QString tempPath = try_create_subfolder(baseDir, MUtils::rand_str());
133 if(!tempPath.isEmpty())
135 for(int i = 0; i < 32; i++)
137 MUtils::Internal::DirLock *lockFile = NULL;
140 lockFile = new MUtils::Internal::DirLock(tempPath);
141 return lockFile;
143 catch(MUtils::Internal::DirLockException&)
145 /*ignore error and try again*/
149 return NULL;
152 const QString &MUtils::temp_folder(void)
154 QReadLocker readLock(&g_temp_folder_lock);
156 //Already initialized?
157 if(!g_temp_folder_file.isNull())
159 return g_temp_folder_file->path();
162 //Obtain the write lock to initilaize
163 readLock.unlock();
164 QWriteLocker writeLock(&g_temp_folder_lock);
166 //Still uninitilaized?
167 if(!g_temp_folder_file.isNull())
169 return g_temp_folder_file->path();
172 //Try the %TMP% or %TEMP% directory first
173 if(MUtils::Internal::DirLock *lockFile = try_init_temp_folder(QDir::tempPath()))
175 g_temp_folder_file.reset(lockFile);
176 return lockFile->path();
179 qWarning("%%TEMP%% directory not found -> trying fallback mode now!");
180 static const OS::known_folder_t FOLDER_ID[2] = { OS::FOLDER_LOCALAPPDATA, OS::FOLDER_SYSTROOT_DIR };
181 for(size_t id = 0; id < 2; id++)
183 const QString &knownFolder = OS::known_folder(FOLDER_ID[id]);
184 if(!knownFolder.isEmpty())
186 const QString tempRoot = try_create_subfolder(knownFolder, QLatin1String("TEMP"));
187 if(!tempRoot.isEmpty())
189 if(MUtils::Internal::DirLock *lockFile = try_init_temp_folder(tempRoot))
191 g_temp_folder_file.reset(lockFile);
192 return lockFile->path();
198 qFatal("Temporary directory could not be initialized !!!");
199 return (*((QString*)NULL));
202 ///////////////////////////////////////////////////////////////////////////////
203 // REMOVE DIRECTORY / FILE
204 ///////////////////////////////////////////////////////////////////////////////
206 bool MUtils::remove_file(const QString &fileName)
208 QFileInfo fileInfo(fileName);
209 if(!(fileInfo.exists() && fileInfo.isFile()))
211 return true;
214 for(int i = 0; i < 32; i++)
216 QFile file(fileName);
217 file.setPermissions(QFile::ReadOther | QFile::WriteOther);
218 if(file.remove())
220 return true;
224 qWarning("Could not delete \"%s\"", MUTILS_UTF8(fileName));
225 return false;
228 bool MUtils::remove_directory(const QString &folderPath)
230 QDir folder(folderPath);
231 if(!folder.exists())
233 return true;
236 const QFileInfoList entryList = folder.entryInfoList(QDir::AllEntries | QDir::NoDotAndDotDot | QDir::Hidden);
237 for(int i = 0; i < entryList.count(); i++)
239 if(entryList.at(i).isDir())
241 remove_directory(entryList.at(i).canonicalFilePath());
243 else
245 remove_file(entryList.at(i).canonicalFilePath());
249 for(int i = 0; i < 32; i++)
251 if(folder.rmdir("."))
253 return true;
257 qWarning("Could not rmdir \"%s\"", MUTILS_UTF8(folderPath));
258 return false;
261 ///////////////////////////////////////////////////////////////////////////////
262 // PROCESS UTILS
263 ///////////////////////////////////////////////////////////////////////////////
265 void MUtils::init_process(QProcess &process, const QString &wokringDir, const bool bReplaceTempDir)
267 //Environment variable names
268 static const char *const s_envvar_names_temp[] =
270 "TEMP", "TMP", "TMPDIR", "HOME", "USERPROFILE", "HOMEPATH", NULL
272 static const char *const s_envvar_names_remove[] =
274 "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
277 //Initialize environment
278 QProcessEnvironment env = process.processEnvironment();
279 if(env.isEmpty()) env = QProcessEnvironment::systemEnvironment();
281 //Clean a number of enviroment variables that might affect our tools
282 for(size_t i = 0; s_envvar_names_remove[i]; i++)
284 env.remove(QString::fromLatin1(s_envvar_names_remove[i]));
285 env.remove(QString::fromLatin1(s_envvar_names_remove[i]).toLower());
288 const QString tempDir = QDir::toNativeSeparators(temp_folder());
290 //Replace TEMP directory in environment
291 if(bReplaceTempDir)
293 for(size_t i = 0; s_envvar_names_temp[i]; i++)
295 env.insert(s_envvar_names_temp[i], tempDir);
299 //Setup PATH variable
300 const QString path = env.value("PATH", QString()).trimmed();
301 env.insert("PATH", path.isEmpty() ? tempDir : QString("%1;%2").arg(tempDir, path));
303 //Setup QPorcess object
304 process.setWorkingDirectory(wokringDir);
305 process.setProcessChannelMode(QProcess::MergedChannels);
306 process.setReadChannel(QProcess::StandardOutput);
307 process.setProcessEnvironment(env);
310 ///////////////////////////////////////////////////////////////////////////////
311 // NATURAL ORDER STRING COMPARISON
312 ///////////////////////////////////////////////////////////////////////////////
314 static bool natural_string_sort_helper(const QString &str1, const QString &str2)
316 return (MUtils::Internal::NaturalSort::strnatcmp(MUTILS_WCHR(str1), MUTILS_WCHR(str2)) < 0);
319 static bool natural_string_sort_helper_fold_case(const QString &str1, const QString &str2)
321 return (MUtils::Internal::NaturalSort::strnatcasecmp(MUTILS_WCHR(str1), MUTILS_WCHR(str2)) < 0);
324 void MUtils::natural_string_sort(QStringList &list, const bool bIgnoreCase)
326 qSort(list.begin(), list.end(), bIgnoreCase ? natural_string_sort_helper_fold_case : natural_string_sort_helper);
329 ///////////////////////////////////////////////////////////////////////////////
330 // CLEAN FILE PATH
331 ///////////////////////////////////////////////////////////////////////////////
333 static const struct
335 const char *const search;
336 const char *const replace;
338 CLEAN_FILE_NAME[] =
340 { "\\", "-" },
341 { " / ", ", " },
342 { "/", "," },
343 { ":", "-" },
344 { "*", "x" },
345 { "?", "!" },
346 { "<", "[" },
347 { ">", "]" },
348 { "|", "!" },
349 { "\"", "'" },
350 { NULL, NULL }
353 QString MUtils::clean_file_name(const QString &name)
355 QString str = name.simplified();
357 for(size_t i = 0; CLEAN_FILE_NAME[i].search; i++)
359 str.replace(CLEAN_FILE_NAME[i].search, CLEAN_FILE_NAME[i].replace);
362 QRegExp regExp("\"(.+)\"");
363 regExp.setMinimal(true);
364 str.replace(regExp, "`\\1ยด");
366 return str.simplified();
369 QString MUtils::clean_file_path(const QString &path)
371 QStringList parts = path.simplified().replace("\\", "/").split("/", QString::SkipEmptyParts);
373 for(int i = 0; i < parts.count(); i++)
375 parts[i] = MUtils::clean_file_name(parts[i]);
378 return parts.join("/");
381 ///////////////////////////////////////////////////////////////////////////////
382 // SELF-TEST
383 ///////////////////////////////////////////////////////////////////////////////
385 int MUtils::Internal::selfTest(const char *const buildKey, const bool debug)
387 static const bool MY_DEBUG_FLAG = MUTILS_DEBUG;
388 static const char *const MY_BUILD_KEY = __DATE__"@"__TIME__;
390 if(strncmp(buildKey, MY_BUILD_KEY, 14) || (MY_DEBUG_FLAG != debug))
392 MUtils::OS::system_message_err(L"MUtils", L"FATAL ERROR: MUtils library version mismatch detected!");
393 MUtils::OS::system_message_wrn(L"MUtils", L"Please re-build the complete solution in order to fix this issue!");
394 abort();
396 return 0;