OSDN Git Service

Added an optional parameter to init_process() function, which allows for passing...
[mutilities/MUtilities.git] / src / Global.cpp
1 ///////////////////////////////////////////////////////////////////////////////
2 // MuldeR's Utilities for Qt
3 // Copyright (C) 2004-2018 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.
14 //
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
18 //
19 // http://www.gnu.org/licenses/lgpl-2.1.txt
20 //////////////////////////////////////////////////////////////////////////////////
21
22 #if _MSC_VER
23 #define _CRT_RAND_S 1
24 #endif
25
26 //MUtils
27 #include <MUtils/Global.h>
28 #include <MUtils/OSSupport.h>
29 #include <MUtils/Version.h>
30
31 //Internal
32 #include "DirLocker.h"
33 #include "3rd_party/strnatcmp/include/strnatcmp.h"
34
35 //Qt
36 #include <QDir>
37 #include <QReadWriteLock>
38 #include <QProcess>
39 #include <QTextCodec>
40 #include <QPair>
41 #include <QHash>
42 #include <QListIterator>
43 #include <QMutex>
44 #include <QThreadStorage>
45
46 //CRT
47 #include <cstdlib>
48 #include <ctime>
49 #include <process.h>
50
51 //VLD
52 #ifdef _MSC_VER
53 #include <vld.h>
54 #endif
55
56 ///////////////////////////////////////////////////////////////////////////////
57 // Random Support
58 ///////////////////////////////////////////////////////////////////////////////
59
60 #ifndef _CRT_RAND_S
61 #define rand_s(X) (true)
62 #endif
63
64 //Per-thread init flag
65 static QThreadStorage<bool> g_srand_flag;
66
67 //32-Bit wrapper for qrand()
68 #define QRAND() ((static_cast<quint32>(qrand()) & 0xFFFF) | (static_cast<quint32>(qrand()) << 16U))
69
70 //Robert Jenkins' 96 bit Mix Function
71 static quint32 mix_function(quint32 a, quint32 b, quint32 c)
72 {
73         a=a-b;  a=a-c;  a=a^(c >> 13);
74         b=b-c;  b=b-a;  b=b^(a <<  8); 
75         c=c-a;  c=c-b;  c=c^(b >> 13);
76         a=a-b;  a=a-c;  a=a^(c >> 12);
77         b=b-c;  b=b-a;  b=b^(a << 16);
78         c=c-a;  c=c-b;  c=c^(b >>  5);
79         a=a-b;  a=a-c;  a=a^(c >>  3);
80         b=b-c;  b=b-a;  b=b^(a << 10);
81         c=c-a;  c=c-b;  c=c^(b >> 15);
82
83         return a ^ b ^ c;
84 }
85
86 static void seed_rand(void)
87 {
88         QDateTime build(MUtils::Version::lib_build_date(), MUtils::Version::lib_build_time());
89         const quint32 seed_0 = mix_function(MUtils::OS::process_id(), MUtils::OS::thread_id(), build.toMSecsSinceEpoch());
90         qsrand(mix_function(clock(), time(NULL), seed_0));
91 }
92
93 static quint32 rand_fallback(void)
94 {
95         Q_ASSERT(RAND_MAX >= 0x7FFF);
96
97         if (!(g_srand_flag.hasLocalData() && g_srand_flag.localData()))
98         {
99                 seed_rand();
100                 g_srand_flag.setLocalData(true);
101         }
102
103         quint32 rnd_val = mix_function(0x32288EA3, clock(), time(NULL));
104
105         for (size_t i = 0; i < 42; i++)
106         {
107                 rnd_val = mix_function(rnd_val, QRAND(), QRAND());
108                 rnd_val = mix_function(QRAND(), rnd_val, QRAND());
109                 rnd_val = mix_function(QRAND(), QRAND(), rnd_val);
110         }
111
112         return rnd_val;
113 }
114
115 quint32 MUtils::next_rand_u32(void)
116 {
117         quint32 rnd;
118         if (rand_s(&rnd))
119         {
120                 return rand_fallback();
121         }
122         return rnd;
123 }
124
125 quint64 MUtils::next_rand_u64(void)
126 {
127         return (quint64(next_rand_u32()) << 32) | quint64(next_rand_u32());
128 }
129
130 QString MUtils::next_rand_str(const bool &bLong)
131 {
132         if (bLong)
133         {
134                 return next_rand_str(false) + next_rand_str(false);
135         }
136         else
137         {
138                 return QString::number(next_rand_u64(), 16).rightJustified(16, QLatin1Char('0'));
139         }
140 }
141
142 ///////////////////////////////////////////////////////////////////////////////
143 // STRING UTILITY FUNCTIONS
144 ///////////////////////////////////////////////////////////////////////////////
145
146 static QScopedPointer<QRegExp> g_str_trim_rx_r;
147 static QScopedPointer<QRegExp> g_str_trim_rx_l;
148 static QMutex                  g_str_trim_lock;
149
150 static QString& trim_helper(QString &str, QScopedPointer<QRegExp> &regex, const char *const pattern)
151 {
152         QMutexLocker lock(&g_str_trim_lock);
153         if (regex.isNull())
154         {
155                 regex.reset(new QRegExp(QLatin1String(pattern)));
156         }
157         str.remove(*regex.data());
158         return str;
159 }
160
161 QString& MUtils::trim_right(QString &str)
162 {
163         static const char *const TRIM_RIGHT = "\\s+$";
164         return trim_helper(str, g_str_trim_rx_r, TRIM_RIGHT);
165 }
166
167 QString& MUtils::trim_left(QString &str)
168 {
169         static const char *const TRIM_LEFT = "^\\s+";
170         return trim_helper(str, g_str_trim_rx_l, TRIM_LEFT);
171 }
172
173 QString MUtils::trim_right(const QString &str)
174 {
175         QString temp(str);
176         return trim_right(temp);
177 }
178
179 QString MUtils::trim_left(const QString &str)
180 {
181         QString temp(str);
182         return trim_left(temp);
183 }
184
185 ///////////////////////////////////////////////////////////////////////////////
186 // GENERATE FILE NAME
187 ///////////////////////////////////////////////////////////////////////////////
188
189 QString MUtils::make_temp_file(const QString &basePath, const QString &extension, const bool placeholder)
190 {
191         return make_temp_file(QDir(basePath), extension, placeholder);
192 }
193
194 QString MUtils::make_temp_file(const QDir &basePath, const QString &extension, const bool placeholder)
195 {
196         if (extension.isEmpty())
197         {
198                 qWarning("Cannot generate temp file name with invalid parameters!");
199                 return QString();
200         }
201
202         for(int i = 0; i < 4096; i++)
203         {
204                 const QString tempFileName = basePath.absoluteFilePath(QString("%1.%2").arg(next_rand_str(), extension));
205                 if(!QFileInfo(tempFileName).exists())
206                 {
207                         if(placeholder)
208                         {
209                                 QFile file(tempFileName);
210                                 if(file.open(QFile::ReadWrite))
211                                 {
212                                         file.close();
213                                         return tempFileName;
214                                 }
215                         }
216                         else
217                         {
218                                 return tempFileName;
219                         }
220                 }
221         }
222
223         qWarning("Failed to generate temp file name!");
224         return QString();
225 }
226
227 QString MUtils::make_unique_file(const QString &basePath, const QString &baseName, const QString &extension, const bool fancy, const bool placeholder)
228 {
229         return make_unique_file(QDir(basePath), baseName, extension, fancy);
230 }
231
232 QString MUtils::make_unique_file(const QDir &basePath, const QString &baseName, const QString &extension, const bool fancy, const bool placeholder)
233 {
234         if (baseName.isEmpty() || extension.isEmpty())
235         {
236                 qWarning("Cannot generate unique file name with invalid parameters!");
237                 return QString();
238         }
239
240         quint32 n = fancy ? 2 : 0;
241         QString fileName = fancy ? basePath.absoluteFilePath(QString("%1.%2").arg(baseName, extension)) : QString();
242         while (fileName.isEmpty() || QFileInfo(fileName).exists())
243         {
244                 if (n <= quint32(USHRT_MAX))
245                 {
246                         if (fancy)
247                         {
248                                 fileName = basePath.absoluteFilePath(QString("%1 (%2).%3").arg(baseName, QString::number(n++), extension));
249                         }
250                         else
251                         {
252                                 fileName = basePath.absoluteFilePath(QString("%1.%2.%3").arg(baseName, QString::number(n++, 16).rightJustified(4, QLatin1Char('0')), extension));
253                         }
254                 }
255                 else
256                 {
257                         qWarning("Failed to generate unique file name!");
258                         return QString();
259                 }
260         }
261
262         if (placeholder && (!fileName.isEmpty()))
263         {
264                 QFile placeholder(fileName);
265                 if (placeholder.open(QIODevice::WriteOnly))
266                 {
267                         placeholder.close();
268                 }
269         }
270
271         return fileName;
272 }
273
274 ///////////////////////////////////////////////////////////////////////////////
275 // COMPUTE PARITY
276 ///////////////////////////////////////////////////////////////////////////////
277
278 /*
279  * Compute parity in parallel
280  * http://www.graphics.stanford.edu/~seander/bithacks.html#ParityParallel
281  */
282 bool MUtils::parity(quint32 value)
283 {
284         value ^= value >> 16;
285         value ^= value >> 8;
286         value ^= value >> 4;
287         value &= 0xf;
288         return ((0x6996 >> value) & 1) != 0;
289 }
290
291 ///////////////////////////////////////////////////////////////////////////////
292 // TEMP FOLDER
293 ///////////////////////////////////////////////////////////////////////////////
294
295 static QScopedPointer<MUtils::Internal::DirLock> g_temp_folder_file;
296 static QReadWriteLock                            g_temp_folder_lock;
297
298 static QString try_create_subfolder(const QString &baseDir, const QString &postfix)
299 {
300         const QString baseDirPath = QDir(baseDir).absolutePath();
301         for(int i = 0; i < 32; i++)
302         {
303                 QDir directory(baseDirPath);
304                 if(directory.mkpath(postfix) && directory.cd(postfix))
305                 {
306                         return directory.canonicalPath();
307                 }
308         }
309         return QString();
310 }
311
312 static MUtils::Internal::DirLock *try_init_temp_folder(const QString &baseDir)
313 {
314         const QString tempPath = try_create_subfolder(baseDir, MUtils::next_rand_str());
315         if(!tempPath.isEmpty())
316         {
317                 for(int i = 0; i < 32; i++)
318                 {
319                         MUtils::Internal::DirLock *lockFile = NULL;
320                         try
321                         {
322                                 lockFile = new MUtils::Internal::DirLock(tempPath);
323                                 return lockFile;
324                         }
325                         catch(MUtils::Internal::DirLockException&)
326                         {
327                                 /*ignore error and try again*/
328                         }
329                 }
330         }
331         return NULL;
332 }
333
334 static bool temp_folder_cleanup_helper(const QString &tempPath)
335 {
336         size_t delay = 1;
337         static const size_t MAX_DELAY = 8192;
338         forever
339         {
340                 QDir::setCurrent(QDir::rootPath());
341                 if(MUtils::remove_directory(tempPath, true))
342                 {
343                         return true;
344                 }
345                 else
346                 {
347                         if(delay > MAX_DELAY)
348                         {
349                                 return false;
350                         }
351                         MUtils::OS::sleep_ms(delay);
352                         delay *= 2;
353                 }
354         }
355 }
356
357 static void temp_folder_cleaup(void)
358 {
359         QWriteLocker writeLock(&g_temp_folder_lock);
360
361         //Clean the directory
362         while(!g_temp_folder_file.isNull())
363         {
364                 const QString tempPath = g_temp_folder_file->getPath();
365                 g_temp_folder_file.reset(NULL);
366                 if(!temp_folder_cleanup_helper(tempPath))
367                 {
368                         MUtils::OS::system_message_wrn(L"Temp Cleaner", L"Warning: Not all temporary files could be removed!");
369                 }
370         }
371 }
372
373 const QString &MUtils::temp_folder(void)
374 {
375         QReadLocker readLock(&g_temp_folder_lock);
376
377         //Already initialized?
378         if(!g_temp_folder_file.isNull())
379         {
380                 return g_temp_folder_file->getPath();
381         }
382
383         //Obtain the write lock to initilaize
384         readLock.unlock();
385         QWriteLocker writeLock(&g_temp_folder_lock);
386         
387         //Still uninitilaized?
388         if(!g_temp_folder_file.isNull())
389         {
390                 return g_temp_folder_file->getPath();
391         }
392
393         //Try the %TMP% or %TEMP% directory first
394         if(MUtils::Internal::DirLock *lockFile = try_init_temp_folder(QDir::tempPath()))
395         {
396                 g_temp_folder_file.reset(lockFile);
397                 atexit(temp_folder_cleaup);
398                 return lockFile->getPath();
399         }
400
401         qWarning("%%TEMP%% directory not found -> trying fallback mode now!");
402         static const OS::known_folder_t FOLDER_ID[2] = { OS::FOLDER_LOCALAPPDATA, OS::FOLDER_SYSTROOT_DIR };
403         for(size_t id = 0; id < 2; id++)
404         {
405                 const QString &knownFolder = OS::known_folder(FOLDER_ID[id]);
406                 if(!knownFolder.isEmpty())
407                 {
408                         const QString tempRoot = try_create_subfolder(knownFolder, QLatin1String("TEMP"));
409                         if(!tempRoot.isEmpty())
410                         {
411                                 if(MUtils::Internal::DirLock *lockFile = try_init_temp_folder(tempRoot))
412                                 {
413                                         g_temp_folder_file.reset(lockFile);
414                                         atexit(temp_folder_cleaup);
415                                         return lockFile->getPath();
416                                 }
417                         }
418                 }
419         }
420
421         qFatal("Temporary directory could not be initialized !!!");
422         return (*((QString*)NULL));
423 }
424
425 ///////////////////////////////////////////////////////////////////////////////
426 // REMOVE DIRECTORY / FILE
427 ///////////////////////////////////////////////////////////////////////////////
428
429 static const QFile::Permissions FILE_PERMISSIONS_NONE = QFile::ReadOther | QFile::WriteOther;
430
431 bool MUtils::remove_file(const QString &fileName)
432 {
433         QFileInfo fileInfo(fileName);
434
435         for(size_t round = 0; round < 13; ++round)
436         {
437                 if (round > 0)
438                 {
439                         MUtils::OS::sleep_ms(round);
440                         fileInfo.refresh();
441                 }
442                 if (fileInfo.exists())
443                 {
444                         QFile file(fileName);
445                         if (round > 0)
446                         {
447                                 file.setPermissions(FILE_PERMISSIONS_NONE);
448                         }
449                         file.remove();
450                         fileInfo.refresh();
451                 }
452                 if (!fileInfo.exists())
453                 {
454                         return true; /*success*/
455                 }
456         }
457
458         qWarning("Could not delete \"%s\"", MUTILS_UTF8(fileName));
459         return false;
460 }
461
462 bool MUtils::remove_directory(const QString &folderPath, const bool &recursive)
463 {
464         const QDir folder(folderPath);
465
466         if(recursive && folder.exists())
467         {
468                 const QFileInfoList entryList = folder.entryInfoList(QDir::AllEntries | QDir::NoDotAndDotDot | QDir::Hidden);
469                 for(QFileInfoList::ConstIterator iter = entryList.constBegin(); iter != entryList.constEnd(); iter++)
470                 {
471                         if(iter->isDir())
472                         {
473                                 remove_directory(iter->canonicalFilePath(), true);
474                         }
475                         else
476                         {
477                                 remove_file(iter->canonicalFilePath());
478                         }
479                 }
480         }
481
482         for(size_t round = 0; round < 13; ++round)
483         {
484                 if(round > 0)
485                 {
486                         MUtils::OS::sleep_ms(round);
487                         folder.refresh();
488                 }
489                 if (folder.exists())
490                 {
491                         QDir parent = folder;
492                         if (parent.cdUp())
493                         {
494                                 if (round > 0)
495                                 {
496                                         QFile::setPermissions(folder.absolutePath(), FILE_PERMISSIONS_NONE);
497                                 }
498                                 parent.rmdir(folder.dirName());
499                                 folder.refresh();
500                         }
501                 }
502                 if (!folder.exists())
503                 {
504                         return true; /*success*/
505                 }
506         }
507         
508         qWarning("Could not rmdir \"%s\"", MUTILS_UTF8(folderPath));
509         return false;
510 }
511
512 ///////////////////////////////////////////////////////////////////////////////
513 // PROCESS UTILS
514 ///////////////////////////////////////////////////////////////////////////////
515
516 static void prependToPath(QProcessEnvironment &env, const QString &value)
517 {
518         static const QLatin1String PATH("PATH");
519         const QString path = env.value(PATH, QString()).trimmed();
520         env.insert(PATH, path.isEmpty() ? value : QString("%1;%2").arg(value, path));
521 }
522
523 void MUtils::init_process(QProcess &process, const QString &wokringDir, const bool bReplaceTempDir, const QStringList *const extraPaths, const QHash<QString, QString> *const extraEnv)
524 {
525         //Environment variable names
526         static const char *const s_envvar_names_temp[] =
527         {
528                 "TEMP", "TMP", "TMPDIR", "HOME", "USERPROFILE", "HOMEPATH", NULL
529         };
530         static const char *const s_envvar_names_remove[] =
531         {
532                 "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
533         };
534
535         //Initialize environment
536         QProcessEnvironment env = process.processEnvironment();
537         if(env.isEmpty()) env = QProcessEnvironment::systemEnvironment();
538
539         //Clean a number of enviroment variables that might affect our tools
540         for(size_t i = 0; s_envvar_names_remove[i]; i++)
541         {
542                 env.remove(QString::fromLatin1(s_envvar_names_remove[i]));
543                 env.remove(QString::fromLatin1(s_envvar_names_remove[i]).toLower());
544         }
545
546         const QString tempDir = QDir::toNativeSeparators(temp_folder());
547
548         //Replace TEMP directory in environment
549         if(bReplaceTempDir)
550         {
551                 for(size_t i = 0; s_envvar_names_temp[i]; i++)
552                 {
553                         env.insert(s_envvar_names_temp[i], tempDir);
554                 }
555         }
556
557         //Setup PATH variable
558         prependToPath(env, tempDir);
559         if (extraPaths && (!extraPaths->isEmpty()))
560         {
561                 QListIterator<QString> iter(*extraPaths);
562                 iter.toBack();
563                 while (iter.hasPrevious())
564                 {
565                         prependToPath(env, QDir::toNativeSeparators(iter.previous()));
566                 }
567         }
568         
569         //Setup environment
570         if (extraEnv && (!extraEnv->isEmpty()))
571         {
572                 for (QHash<QString, QString>::ConstIterator iter = extraEnv->constBegin(); iter != extraEnv->constEnd(); iter++)
573                 {
574                         env.insert(iter.key(), iter.value());
575                 }
576         }
577
578         //Setup QPorcess object
579         process.setWorkingDirectory(wokringDir);
580         process.setProcessChannelMode(QProcess::MergedChannels);
581         process.setReadChannel(QProcess::StandardOutput);
582         process.setProcessEnvironment(env);
583 }
584
585 ///////////////////////////////////////////////////////////////////////////////
586 // NATURAL ORDER STRING COMPARISON
587 ///////////////////////////////////////////////////////////////////////////////
588
589 static bool natural_string_sort_helper(const QString &str1, const QString &str2)
590 {
591         return (MUtils::Internal::NaturalSort::strnatcmp(MUTILS_WCHR(str1), MUTILS_WCHR(str2)) < 0);
592 }
593
594 static bool natural_string_sort_helper_fold_case(const QString &str1, const QString &str2)
595 {
596         return (MUtils::Internal::NaturalSort::strnatcasecmp(MUTILS_WCHR(str1), MUTILS_WCHR(str2)) < 0);
597 }
598
599 void MUtils::natural_string_sort(QStringList &list, const bool bIgnoreCase)
600 {
601         qSort(list.begin(), list.end(), bIgnoreCase ? natural_string_sort_helper_fold_case : natural_string_sort_helper);
602 }
603
604 ///////////////////////////////////////////////////////////////////////////////
605 // CLEAN FILE PATH
606 ///////////////////////////////////////////////////////////////////////////////
607
608 static QMutex                                              g_clean_file_name_mutex;
609 static QScopedPointer<const QList<QPair<QRegExp,QString>>> g_clean_file_name_regex;
610
611 static void clean_file_name_make_pretty(QString &str)
612 {
613         static const struct { const char *p; const char *r; } PATTERN[] =
614         {
615                 { "^\\s*\"([^\"]*)\"\\s*$",    "\\1"                         },  //Remove straight double quotes around the whole string
616                 { "\"([^\"]*)\"",              "\xE2\x80\x9C\\1\xE2\x80\x9D" },  //Replace remaining pairs of straight double quotes with opening/closing double quote
617                 { "^[\\\\/:]+([^\\\\/:]+.*)$", "\\1"                         },  //Remove leading slash, backslash and colon characters
618                 { "^(.*[^\\\\/:]+)[\\\\/:]+$", "\\1"                         },  //Remove trailing slash, backslash and colon characters
619                 { "(\\s*[\\\\/:]\\s*)+",       " - "                         },  //Replace any slash, backslash or colon character that appears in the middle
620                 { NULL, NULL }
621         };
622
623         QMutexLocker locker(&g_clean_file_name_mutex);
624
625         if (g_clean_file_name_regex.isNull())
626         {
627                 QScopedPointer<QList<QPair<QRegExp, QString>>> list(new QList<QPair<QRegExp, QString>>());
628                 for (size_t i = 0; PATTERN[i].p; ++i)
629                 {
630                         list->append(qMakePair(QRegExp(QString::fromUtf8(PATTERN[i].p), Qt::CaseInsensitive), PATTERN[i].r ? QString::fromUtf8(PATTERN[i].r) : QString()));
631                 }
632                 g_clean_file_name_regex.reset(list.take());
633         }
634
635         bool keepOnGoing = !str.isEmpty();
636         while(keepOnGoing)
637         {
638                 const QString prev = str;
639                 keepOnGoing = false;
640                 for (QList<QPair<QRegExp, QString>>::ConstIterator iter = g_clean_file_name_regex->constBegin(); iter != g_clean_file_name_regex->constEnd(); ++iter)
641                 {
642                         str.replace(iter->first, iter->second);
643                         if (str.compare(prev))
644                         {
645                                 str = str.simplified();
646                                 keepOnGoing = !str.isEmpty();
647                                 break;
648                         }
649                 }
650         }
651 }
652
653 QString MUtils::clean_file_name(const QString &name, const bool &pretty)
654 {
655         static const QLatin1Char REPLACEMENT_CHAR('_');
656         static const char FILENAME_ILLEGAL_CHARS[] = "<>:\"/\\|?*";
657         static const char *const FILENAME_RESERVED_NAMES[] =
658         {
659                 "CON", "PRN", "AUX", "NUL",
660                 "COM1", "COM2", "COM3", "COM4", "COM5", "COM6", "COM7", "COM8", "COM9",
661                 "LPT1", "LPT2", "LPT3", "LPT4", "LPT5", "LPT6", "LPT7", "LPT8", "LPT9", NULL
662         };
663
664         QString result(name);
665         if (pretty)
666         {
667                 clean_file_name_make_pretty(result);
668         }
669
670         for(QString::Iterator iter = result.begin(); iter != result.end(); iter++)
671         {
672                 if (iter->category() == QChar::Other_Control)
673                 {
674                         *iter = REPLACEMENT_CHAR;
675                 }
676         }
677                 
678         for(size_t i = 0; FILENAME_ILLEGAL_CHARS[i]; i++)
679         {
680                 result.replace(QLatin1Char(FILENAME_ILLEGAL_CHARS[i]), REPLACEMENT_CHAR);
681         }
682         
683         trim_right(result);
684         while (result.endsWith(QLatin1Char('.')))
685         {
686                 result.chop(1);
687                 trim_right(result);
688         }
689
690         for (size_t i = 0; FILENAME_RESERVED_NAMES[i]; i++)
691         {
692                 const QString reserved = QString::fromLatin1(FILENAME_RESERVED_NAMES[i]);
693                 if ((!result.compare(reserved, Qt::CaseInsensitive)) || result.startsWith(reserved + QLatin1Char('.'), Qt::CaseInsensitive))
694                 {
695                         result.replace(0, reserved.length(), QString().leftJustified(reserved.length(), REPLACEMENT_CHAR));
696                 }
697         }
698
699         return result;
700 }
701
702 static QPair<QString,QString> clean_file_path_get_prefix(const QString path)
703 {
704         static const char *const PREFIXES[] =
705         {
706                 "//?/", "//", "/", NULL
707         };
708         const QString posixPath = QDir::fromNativeSeparators(path.trimmed());
709         for (int i = 0; PREFIXES[i]; i++)
710         {
711                 const QString prefix = QString::fromLatin1(PREFIXES[i]);
712                 if (posixPath.startsWith(prefix))
713                 {
714                         return qMakePair(prefix, posixPath.mid(prefix.length()));
715                 }
716         }
717         return qMakePair(QString(), posixPath);
718 }
719
720 QString MUtils::clean_file_path(const QString &path, const bool &pretty)
721 {
722         const QPair<QString, QString> prefix = clean_file_path_get_prefix(path);
723
724         QStringList parts = prefix.second.split(QLatin1Char('/'), QString::SkipEmptyParts);
725         for(int i = 0; i < parts.count(); i++)
726         {
727                 if((i == 0) && (parts[i].length() == 2) && parts[i][0].isLetter() && (parts[i][1] == QLatin1Char(':')))
728                 {
729                         continue; //handle case "c:\"
730                 }
731                 parts[i] = MUtils::clean_file_name(parts[i], pretty);
732         }
733
734         const QString cleanPath = parts.join(QLatin1String("/"));
735         return prefix.first.isEmpty() ? cleanPath : prefix.first + cleanPath;
736 }
737
738 ///////////////////////////////////////////////////////////////////////////////
739 // REGULAR EXPESSION HELPER
740 ///////////////////////////////////////////////////////////////////////////////
741
742 bool MUtils::regexp_parse_uint32(const QRegExp &regexp, quint32 &value)
743 {
744         return regexp_parse_uint32(regexp, &value, 1U, 1U);
745 }
746
747 bool MUtils::regexp_parse_int32(const QRegExp &regexp, qint32 &value)
748 {
749         return regexp_parse_int32(regexp, &value, 1U, 1U);
750 }
751
752 bool MUtils::regexp_parse_uint32(const QRegExp &regexp, quint32 &value, const size_t &offset)
753 {
754         return regexp_parse_uint32(regexp, &value, offset, 1U);
755 }
756
757 bool MUtils::regexp_parse_int32(const QRegExp &regexp, qint32 &value, const size_t &offset)
758 {
759         return regexp_parse_int32(regexp, &value, offset, 1U);
760 }
761
762 bool MUtils::regexp_parse_uint32(const QRegExp &regexp, quint32 *values, const size_t &count)
763 {
764         return regexp_parse_uint32(regexp, values, 1U, count);
765 }
766
767 bool MUtils::regexp_parse_int32(const QRegExp &regexp, qint32 *values, const size_t &count)
768 {
769         return regexp_parse_int32(regexp, values, 1U, count);
770 }
771
772 bool MUtils::regexp_parse_uint32(const QRegExp &regexp, quint32 *values, const size_t &offset, const size_t &count)
773 {
774         const QStringList caps = regexp.capturedTexts();
775
776         if (caps.isEmpty() || (quint32(caps.count()) <= count))
777         {
778                 return false;
779         }
780
781         for (size_t i = 0; i < count; i++)
782         {
783                 bool ok = false;
784                 values[i] = caps[offset+i].toUInt(&ok);
785                 if (!ok)
786                 {
787                         return false;
788                 }
789         }
790
791         return true;
792 }
793
794 bool MUtils::regexp_parse_int32(const QRegExp &regexp, qint32 *values, const size_t &offset, const size_t &count)
795 {
796         const QStringList caps = regexp.capturedTexts();
797
798         if (caps.isEmpty() || (quint32(caps.count()) <= count))
799         {
800                 return false;
801         }
802
803         for (size_t i = 0; i < count; i++)
804         {
805                 bool ok = false;
806                 values[i] = caps[offset+i].toInt(&ok);
807                 if (!ok)
808                 {
809                         return false;
810                 }
811         }
812
813         return true;
814 }
815
816 ///////////////////////////////////////////////////////////////////////////////
817 // AVAILABLE CODEPAGES
818 ///////////////////////////////////////////////////////////////////////////////
819
820 QStringList MUtils::available_codepages(const bool &noAliases)
821 {
822         QStringList codecList;
823         QList<QByteArray> availableCodecs = QTextCodec::availableCodecs();
824
825         while(!availableCodecs.isEmpty())
826         {
827                 const QByteArray current = availableCodecs.takeFirst();
828                 if(!current.toLower().startsWith("system"))
829                 {
830                         codecList << QString::fromLatin1(current.constData(), current.size());
831                         if(noAliases)
832                         {
833                                 if(QTextCodec *const currentCodec = QTextCodec::codecForName(current.constData()))
834                                 {
835                                         const QList<QByteArray> aliases = currentCodec->aliases();
836                                         for(QList<QByteArray>::ConstIterator iter = aliases.constBegin(); iter != aliases.constEnd(); iter++)
837                                         {
838                                                 availableCodecs.removeAll(*iter);
839                                         }
840                                 }
841                         }
842                 }
843         }
844
845         return codecList;
846 }
847
848 ///////////////////////////////////////////////////////////////////////////////
849 // FP MATH SUPPORT
850 ///////////////////////////////////////////////////////////////////////////////
851
852 MUtils::fp_parts_t MUtils::break_fp(const double value)
853 {
854         fp_parts_t result = { };
855         if (_finite(value))
856         {
857                 result.parts[1] = modf(value, &result.parts[0]);
858         }
859         else
860         {
861                 result.parts[0] = std::numeric_limits<double>::quiet_NaN();
862                 result.parts[1] = std::numeric_limits<double>::quiet_NaN();
863         }
864         return result;
865 }
866
867 ///////////////////////////////////////////////////////////////////////////////
868 // SELF-TEST
869 ///////////////////////////////////////////////////////////////////////////////
870
871 int MUtils::Internal::selfTest(const char *const buildKey, const bool debug)
872 {
873         static const bool MY_DEBUG_FLAG = MUTILS_DEBUG;
874         static const char *const MY_BUILD_KEY = __DATE__ "@" __TIME__;
875
876         if(strncmp(buildKey, MY_BUILD_KEY, 13) || (MY_DEBUG_FLAG != debug))
877         {
878                 MUtils::OS::system_message_err(L"MUtils", L"FATAL ERROR: MUtils library version mismatch detected!");
879                 MUtils::OS::system_message_wrn(L"MUtils", L"Perform a clean(!) re-install of the application to fix the problem!");
880                 abort();
881         }
882         return 0;
883 }