Some improvements to remove_file() and remove_directory() functions.
[MUtilities.git] / src / Global.cpp
blob36b6baff5828d0bb8edec3ef93e9377f7342f0f4
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.
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>
29 #include <MUtils/Version.h>
31 //Internal
32 #include "DirLocker.h"
33 #include "3rd_party/strnatcmp/include/strnatcmp.h"
35 //Qt
36 #include <QDir>
37 #include <QReadWriteLock>
38 #include <QProcess>
39 #include <QTextCodec>
40 #include <QPair>
41 #include <QListIterator>
42 #include <QMutex>
43 #include <QThreadStorage>
45 //CRT
46 #include <cstdlib>
47 #include <ctime>
48 #include <process.h>
50 //VLD
51 #ifdef _MSC_VER
52 #include <vld.h>
53 #endif
55 ///////////////////////////////////////////////////////////////////////////////
56 // Random Support
57 ///////////////////////////////////////////////////////////////////////////////
59 #ifndef _CRT_RAND_S
60 #define rand_s(X) (true)
61 #endif
63 //Per-thread init flag
64 static QThreadStorage<bool> g_srand_flag;
66 //32-Bit wrapper for qrand()
67 #define QRAND() ((static_cast<quint32>(qrand()) & 0xFFFF) | (static_cast<quint32>(qrand()) << 16U))
69 //Robert Jenkins' 96 bit Mix Function
70 static quint32 mix_function(quint32 a, quint32 b, quint32 c)
72 a=a-b; a=a-c; a=a^(c >> 13);
73 b=b-c; b=b-a; b=b^(a << 8);
74 c=c-a; c=c-b; c=c^(b >> 13);
75 a=a-b; a=a-c; a=a^(c >> 12);
76 b=b-c; b=b-a; b=b^(a << 16);
77 c=c-a; c=c-b; c=c^(b >> 5);
78 a=a-b; a=a-c; a=a^(c >> 3);
79 b=b-c; b=b-a; b=b^(a << 10);
80 c=c-a; c=c-b; c=c^(b >> 15);
82 return a ^ b ^ c;
85 static void seed_rand(void)
87 QDateTime build(MUtils::Version::lib_build_date(), MUtils::Version::lib_build_time());
88 const quint32 seed_0 = mix_function(MUtils::OS::process_id(), MUtils::OS::thread_id(), build.toMSecsSinceEpoch());
89 qsrand(mix_function(clock(), time(NULL), seed_0));
92 static quint32 rand_fallback(void)
94 Q_ASSERT(RAND_MAX >= 0x7FFF);
96 if (!(g_srand_flag.hasLocalData() && g_srand_flag.localData()))
98 seed_rand();
99 g_srand_flag.setLocalData(true);
102 quint32 rnd_val = mix_function(0x32288EA3, clock(), time(NULL));
104 for (size_t i = 0; i < 42; i++)
106 rnd_val = mix_function(rnd_val, QRAND(), QRAND());
107 rnd_val = mix_function(QRAND(), rnd_val, QRAND());
108 rnd_val = mix_function(QRAND(), QRAND(), rnd_val);
111 return rnd_val;
114 quint32 MUtils::next_rand_u32(void)
116 quint32 rnd;
117 if (rand_s(&rnd))
119 return rand_fallback();
121 return rnd;
124 quint64 MUtils::next_rand_u64(void)
126 return (quint64(next_rand_u32()) << 32) | quint64(next_rand_u32());
129 QString MUtils::next_rand_str(const bool &bLong)
131 if (bLong)
133 return next_rand_str(false) + next_rand_str(false);
135 else
137 return QString::number(next_rand_u64(), 16).rightJustified(16, QLatin1Char('0'));
141 ///////////////////////////////////////////////////////////////////////////////
142 // STRING UTILITY FUNCTIONS
143 ///////////////////////////////////////////////////////////////////////////////
145 static QScopedPointer<QRegExp> g_str_trim_rx_r;
146 static QScopedPointer<QRegExp> g_str_trim_rx_l;
147 static QMutex g_str_trim_lock;
149 static QString& trim_helper(QString &str, QScopedPointer<QRegExp> &regex, const char *const pattern)
151 QMutexLocker lock(&g_str_trim_lock);
152 if (regex.isNull())
154 regex.reset(new QRegExp(QLatin1String(pattern)));
156 str.remove(*regex.data());
157 return str;
160 QString& MUtils::trim_right(QString &str)
162 static const char *const TRIM_RIGHT = "\\s+$";
163 return trim_helper(str, g_str_trim_rx_r, TRIM_RIGHT);
166 QString& MUtils::trim_left(QString &str)
168 static const char *const TRIM_LEFT = "^\\s+";
169 return trim_helper(str, g_str_trim_rx_l, TRIM_LEFT);
172 QString MUtils::trim_right(const QString &str)
174 QString temp(str);
175 return trim_right(temp);
178 QString MUtils::trim_left(const QString &str)
180 QString temp(str);
181 return trim_left(temp);
184 ///////////////////////////////////////////////////////////////////////////////
185 // GENERATE FILE NAME
186 ///////////////////////////////////////////////////////////////////////////////
188 QString MUtils::make_temp_file(const QString &basePath, const QString &extension, const bool placeholder)
190 for(int i = 0; i < 4096; i++)
192 const QString tempFileName = QString("%1/%2.%3").arg(basePath, next_rand_str(), extension);
193 if(!QFileInfo(tempFileName).exists())
195 if(placeholder)
197 QFile file(tempFileName);
198 if(file.open(QFile::ReadWrite))
200 file.close();
201 return tempFileName;
204 else
206 return tempFileName;
211 qWarning("Failed to generate temp file name!");
212 return QString();
215 QString MUtils::make_unique_file(const QString &basePath, const QString &baseName, const QString &extension, const bool fancy)
217 quint32 n = fancy ? 2 : 0;
218 QString fileName = fancy ? QString("%1/%2.%3").arg(basePath, baseName, extension) : QString();
219 while (fileName.isEmpty() || QFileInfo(fileName).exists())
221 if (n <= quint32(USHRT_MAX))
223 if (fancy)
225 fileName = QString("%1/%2 (%3).%4").arg(basePath, baseName, QString::number(n++), extension);
227 else
229 fileName = QString("%1/%2.%3.%4").arg(basePath, baseName, QString::number(n++, 16).rightJustified(4, QLatin1Char('0')), extension);
232 else
234 qWarning("Failed to generate unique file name!");
235 return QString();
238 return fileName;
241 ///////////////////////////////////////////////////////////////////////////////
242 // COMPUTE PARITY
243 ///////////////////////////////////////////////////////////////////////////////
246 * Compute parity in parallel
247 * http://www.graphics.stanford.edu/~seander/bithacks.html#ParityParallel
249 bool MUtils::parity(quint32 value)
251 value ^= value >> 16;
252 value ^= value >> 8;
253 value ^= value >> 4;
254 value &= 0xf;
255 return ((0x6996 >> value) & 1) != 0;
258 ///////////////////////////////////////////////////////////////////////////////
259 // TEMP FOLDER
260 ///////////////////////////////////////////////////////////////////////////////
262 static QScopedPointer<MUtils::Internal::DirLock> g_temp_folder_file;
263 static QReadWriteLock g_temp_folder_lock;
265 static QString try_create_subfolder(const QString &baseDir, const QString &postfix)
267 const QString baseDirPath = QDir(baseDir).absolutePath();
268 for(int i = 0; i < 32; i++)
270 QDir directory(baseDirPath);
271 if(directory.mkpath(postfix) && directory.cd(postfix))
273 return directory.canonicalPath();
276 return QString();
279 static MUtils::Internal::DirLock *try_init_temp_folder(const QString &baseDir)
281 const QString tempPath = try_create_subfolder(baseDir, MUtils::next_rand_str());
282 if(!tempPath.isEmpty())
284 for(int i = 0; i < 32; i++)
286 MUtils::Internal::DirLock *lockFile = NULL;
289 lockFile = new MUtils::Internal::DirLock(tempPath);
290 return lockFile;
292 catch(MUtils::Internal::DirLockException&)
294 /*ignore error and try again*/
298 return NULL;
301 static bool temp_folder_cleanup_helper(const QString &tempPath)
303 size_t delay = 1;
304 static const size_t MAX_DELAY = 8192;
305 forever
307 QDir::setCurrent(QDir::rootPath());
308 if(MUtils::remove_directory(tempPath, true))
310 return true;
312 else
314 if(delay > MAX_DELAY)
316 return false;
318 MUtils::OS::sleep_ms(delay);
319 delay *= 2;
324 static void temp_folder_cleaup(void)
326 QWriteLocker writeLock(&g_temp_folder_lock);
328 //Clean the directory
329 while(!g_temp_folder_file.isNull())
331 const QString tempPath = g_temp_folder_file->getPath();
332 g_temp_folder_file.reset(NULL);
333 if(!temp_folder_cleanup_helper(tempPath))
335 MUtils::OS::system_message_wrn(L"Temp Cleaner", L"Warning: Not all temporary files could be removed!");
340 const QString &MUtils::temp_folder(void)
342 QReadLocker readLock(&g_temp_folder_lock);
344 //Already initialized?
345 if(!g_temp_folder_file.isNull())
347 return g_temp_folder_file->getPath();
350 //Obtain the write lock to initilaize
351 readLock.unlock();
352 QWriteLocker writeLock(&g_temp_folder_lock);
354 //Still uninitilaized?
355 if(!g_temp_folder_file.isNull())
357 return g_temp_folder_file->getPath();
360 //Try the %TMP% or %TEMP% directory first
361 if(MUtils::Internal::DirLock *lockFile = try_init_temp_folder(QDir::tempPath()))
363 g_temp_folder_file.reset(lockFile);
364 atexit(temp_folder_cleaup);
365 return lockFile->getPath();
368 qWarning("%%TEMP%% directory not found -> trying fallback mode now!");
369 static const OS::known_folder_t FOLDER_ID[2] = { OS::FOLDER_LOCALAPPDATA, OS::FOLDER_SYSTROOT_DIR };
370 for(size_t id = 0; id < 2; id++)
372 const QString &knownFolder = OS::known_folder(FOLDER_ID[id]);
373 if(!knownFolder.isEmpty())
375 const QString tempRoot = try_create_subfolder(knownFolder, QLatin1String("TEMP"));
376 if(!tempRoot.isEmpty())
378 if(MUtils::Internal::DirLock *lockFile = try_init_temp_folder(tempRoot))
380 g_temp_folder_file.reset(lockFile);
381 atexit(temp_folder_cleaup);
382 return lockFile->getPath();
388 qFatal("Temporary directory could not be initialized !!!");
389 return (*((QString*)NULL));
392 ///////////////////////////////////////////////////////////////////////////////
393 // REMOVE DIRECTORY / FILE
394 ///////////////////////////////////////////////////////////////////////////////
396 static const QFile::Permissions FILE_PERMISSIONS_NONE = QFile::ReadOther | QFile::WriteOther;
398 bool MUtils::remove_file(const QString &fileName)
400 QFileInfo fileInfo(fileName);
402 for(size_t round = 0; round < 13; ++round)
404 if (round > 0)
406 MUtils::OS::sleep_ms(round);
407 fileInfo.refresh();
409 if (fileInfo.exists())
411 QFile file(fileName);
412 if (round > 0)
414 file.setPermissions(FILE_PERMISSIONS_NONE);
416 file.remove();
417 fileInfo.refresh();
419 if (!fileInfo.exists())
421 return true; /*success*/
425 qWarning("Could not delete \"%s\"", MUTILS_UTF8(fileName));
426 return false;
429 bool MUtils::remove_directory(const QString &folderPath, const bool &recursive)
431 const QDir folder(folderPath);
433 if(recursive && folder.exists())
435 const QFileInfoList entryList = folder.entryInfoList(QDir::AllEntries | QDir::NoDotAndDotDot | QDir::Hidden);
436 for(QFileInfoList::ConstIterator iter = entryList.constBegin(); iter != entryList.constEnd(); iter++)
438 if(iter->isDir())
440 remove_directory(iter->canonicalFilePath(), true);
442 else
444 remove_file(iter->canonicalFilePath());
449 for(size_t round = 0; round < 13; ++round)
451 if(round > 0)
453 MUtils::OS::sleep_ms(round);
454 folder.refresh();
456 if (folder.exists())
458 QDir parent = folder;
459 if (parent.cdUp())
461 if (round > 0)
463 QFile::setPermissions(folder.absolutePath(), FILE_PERMISSIONS_NONE);
465 parent.rmdir(folder.dirName());
466 folder.refresh();
469 if (!folder.exists())
471 return true; /*success*/
475 qWarning("Could not rmdir \"%s\"", MUTILS_UTF8(folderPath));
476 return false;
479 ///////////////////////////////////////////////////////////////////////////////
480 // PROCESS UTILS
481 ///////////////////////////////////////////////////////////////////////////////
483 static void prependToPath(QProcessEnvironment &env, const QString &value)
485 const QLatin1String PATH = QLatin1String("PATH");
486 const QString path = env.value(PATH, QString()).trimmed();
487 env.insert(PATH, path.isEmpty() ? value : QString("%1;%2").arg(value, path));
490 void MUtils::init_process(QProcess &process, const QString &wokringDir, const bool bReplaceTempDir, const QStringList *const extraPaths)
492 //Environment variable names
493 static const char *const s_envvar_names_temp[] =
495 "TEMP", "TMP", "TMPDIR", "HOME", "USERPROFILE", "HOMEPATH", NULL
497 static const char *const s_envvar_names_remove[] =
499 "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
502 //Initialize environment
503 QProcessEnvironment env = process.processEnvironment();
504 if(env.isEmpty()) env = QProcessEnvironment::systemEnvironment();
506 //Clean a number of enviroment variables that might affect our tools
507 for(size_t i = 0; s_envvar_names_remove[i]; i++)
509 env.remove(QString::fromLatin1(s_envvar_names_remove[i]));
510 env.remove(QString::fromLatin1(s_envvar_names_remove[i]).toLower());
513 const QString tempDir = QDir::toNativeSeparators(temp_folder());
515 //Replace TEMP directory in environment
516 if(bReplaceTempDir)
518 for(size_t i = 0; s_envvar_names_temp[i]; i++)
520 env.insert(s_envvar_names_temp[i], tempDir);
524 //Setup PATH variable
525 prependToPath(env, tempDir);
526 if (extraPaths && (!extraPaths->isEmpty()))
528 QListIterator<QString> iter(*extraPaths);
529 iter.toBack();
530 while (iter.hasPrevious())
532 prependToPath(env, QDir::toNativeSeparators(iter.previous()));
536 //Setup QPorcess object
537 process.setWorkingDirectory(wokringDir);
538 process.setProcessChannelMode(QProcess::MergedChannels);
539 process.setReadChannel(QProcess::StandardOutput);
540 process.setProcessEnvironment(env);
543 ///////////////////////////////////////////////////////////////////////////////
544 // NATURAL ORDER STRING COMPARISON
545 ///////////////////////////////////////////////////////////////////////////////
547 static bool natural_string_sort_helper(const QString &str1, const QString &str2)
549 return (MUtils::Internal::NaturalSort::strnatcmp(MUTILS_WCHR(str1), MUTILS_WCHR(str2)) < 0);
552 static bool natural_string_sort_helper_fold_case(const QString &str1, const QString &str2)
554 return (MUtils::Internal::NaturalSort::strnatcasecmp(MUTILS_WCHR(str1), MUTILS_WCHR(str2)) < 0);
557 void MUtils::natural_string_sort(QStringList &list, const bool bIgnoreCase)
559 qSort(list.begin(), list.end(), bIgnoreCase ? natural_string_sort_helper_fold_case : natural_string_sort_helper);
562 ///////////////////////////////////////////////////////////////////////////////
563 // CLEAN FILE PATH
564 ///////////////////////////////////////////////////////////////////////////////
566 static QMutex g_clean_file_name_mutex;
567 static QScopedPointer<const QList<QPair<QRegExp,QString>>> g_clean_file_name_regex;
569 static void clean_file_name_make_pretty(QString &str)
571 static const struct { const char *p; const char *r; } PATTERN[] =
573 { "^\\s*\"([^\"]*)\"\\s*$", "\\1" }, //Remove straight double quotes around the whole string
574 { "\"([^\"]*)\"", "\xE2\x80\x9C\\1\xE2\x80\x9D" }, //Replace remaining pairs of straight double quotes with opening/closing double quote
575 { "^[\\\\/:]+([^\\\\/:]+.*)$", "\\1" }, //Remove leading slash, backslash and colon characters
576 { "^(.*[^\\\\/:]+)[\\\\/:]+$", "\\1" }, //Remove trailing slash, backslash and colon characters
577 { "(\\s*[\\\\/:]\\s*)+", " - " }, //Replace any slash, backslash or colon character that appears in the middle
578 { NULL, NULL }
581 QMutexLocker locker(&g_clean_file_name_mutex);
583 if (g_clean_file_name_regex.isNull())
585 QScopedPointer<QList<QPair<QRegExp, QString>>> list(new QList<QPair<QRegExp, QString>>());
586 for (size_t i = 0; PATTERN[i].p; ++i)
588 list->append(qMakePair(QRegExp(QString::fromUtf8(PATTERN[i].p), Qt::CaseInsensitive), PATTERN[i].r ? QString::fromUtf8(PATTERN[i].r) : QString()));
590 g_clean_file_name_regex.reset(list.take());
593 bool keepOnGoing = !str.isEmpty();
594 while(keepOnGoing)
596 const QString prev = str;
597 keepOnGoing = false;
598 for (QList<QPair<QRegExp, QString>>::ConstIterator iter = g_clean_file_name_regex->constBegin(); iter != g_clean_file_name_regex->constEnd(); ++iter)
600 str.replace(iter->first, iter->second);
601 if (str.compare(prev))
603 str = str.simplified();
604 keepOnGoing = !str.isEmpty();
605 break;
611 QString MUtils::clean_file_name(const QString &name, const bool &pretty)
613 static const QLatin1Char REPLACEMENT_CHAR('_');
614 static const char FILENAME_ILLEGAL_CHARS[] = "<>:\"/\\|?*";
615 static const char *const FILENAME_RESERVED_NAMES[] =
617 "CON", "PRN", "AUX", "NUL",
618 "COM1", "COM2", "COM3", "COM4", "COM5", "COM6", "COM7", "COM8", "COM9",
619 "LPT1", "LPT2", "LPT3", "LPT4", "LPT5", "LPT6", "LPT7", "LPT8", "LPT9", NULL
622 QString result(name);
623 if (pretty)
625 clean_file_name_make_pretty(result);
628 for(QString::Iterator iter = result.begin(); iter != result.end(); iter++)
630 if (iter->category() == QChar::Other_Control)
632 *iter = REPLACEMENT_CHAR;
636 for(size_t i = 0; FILENAME_ILLEGAL_CHARS[i]; i++)
638 result.replace(QLatin1Char(FILENAME_ILLEGAL_CHARS[i]), REPLACEMENT_CHAR);
641 trim_right(result);
642 while (result.endsWith(QLatin1Char('.')))
644 result.chop(1);
645 trim_right(result);
648 for (size_t i = 0; FILENAME_RESERVED_NAMES[i]; i++)
650 const QString reserved = QString::fromLatin1(FILENAME_RESERVED_NAMES[i]);
651 if ((!result.compare(reserved, Qt::CaseInsensitive)) || result.startsWith(reserved + QLatin1Char('.'), Qt::CaseInsensitive))
653 result.replace(0, reserved.length(), QString().leftJustified(reserved.length(), REPLACEMENT_CHAR));
657 return result;
660 static QPair<QString,QString> clean_file_path_get_prefix(const QString path)
662 static const char *const PREFIXES[] =
664 "//?/", "//", "/", NULL
666 const QString posixPath = QDir::fromNativeSeparators(path.trimmed());
667 for (int i = 0; PREFIXES[i]; i++)
669 const QString prefix = QString::fromLatin1(PREFIXES[i]);
670 if (posixPath.startsWith(prefix))
672 return qMakePair(prefix, posixPath.mid(prefix.length()));
675 return qMakePair(QString(), posixPath);
678 QString MUtils::clean_file_path(const QString &path, const bool &pretty)
680 const QPair<QString, QString> prefix = clean_file_path_get_prefix(path);
682 QStringList parts = prefix.second.split(QLatin1Char('/'), QString::SkipEmptyParts);
683 for(int i = 0; i < parts.count(); i++)
685 if((i == 0) && (parts[i].length() == 2) && parts[i][0].isLetter() && (parts[i][1] == QLatin1Char(':')))
687 continue; //handle case "c:\"
689 parts[i] = MUtils::clean_file_name(parts[i], pretty);
692 const QString cleanPath = parts.join(QLatin1String("/"));
693 return prefix.first.isEmpty() ? cleanPath : prefix.first + cleanPath;
696 ///////////////////////////////////////////////////////////////////////////////
697 // REGULAR EXPESSION HELPER
698 ///////////////////////////////////////////////////////////////////////////////
700 bool MUtils::regexp_parse_uint32(const QRegExp &regexp, quint32 &value)
702 return regexp_parse_uint32(regexp, &value, 1U, 1U);
705 bool MUtils::regexp_parse_int32(const QRegExp &regexp, qint32 &value)
707 return regexp_parse_int32(regexp, &value, 1U, 1U);
710 bool MUtils::regexp_parse_uint32(const QRegExp &regexp, quint32 &value, const size_t &offset)
712 return regexp_parse_uint32(regexp, &value, offset, 1U);
715 bool MUtils::regexp_parse_int32(const QRegExp &regexp, qint32 &value, const size_t &offset)
717 return regexp_parse_int32(regexp, &value, offset, 1U);
720 bool MUtils::regexp_parse_uint32(const QRegExp &regexp, quint32 *values, const size_t &count)
722 return regexp_parse_uint32(regexp, values, 1U, count);
725 bool MUtils::regexp_parse_int32(const QRegExp &regexp, qint32 *values, const size_t &count)
727 return regexp_parse_int32(regexp, values, 1U, count);
730 bool MUtils::regexp_parse_uint32(const QRegExp &regexp, quint32 *values, const size_t &offset, const size_t &count)
732 const QStringList caps = regexp.capturedTexts();
734 if (caps.isEmpty() || (quint32(caps.count()) <= count))
736 return false;
739 for (size_t i = 0; i < count; i++)
741 bool ok = false;
742 values[i] = caps[offset+i].toUInt(&ok);
743 if (!ok)
745 return false;
749 return true;
752 bool MUtils::regexp_parse_int32(const QRegExp &regexp, qint32 *values, const size_t &offset, const size_t &count)
754 const QStringList caps = regexp.capturedTexts();
756 if (caps.isEmpty() || (quint32(caps.count()) <= count))
758 return false;
761 for (size_t i = 0; i < count; i++)
763 bool ok = false;
764 values[i] = caps[offset+i].toInt(&ok);
765 if (!ok)
767 return false;
771 return true;
774 ///////////////////////////////////////////////////////////////////////////////
775 // AVAILABLE CODEPAGES
776 ///////////////////////////////////////////////////////////////////////////////
778 QStringList MUtils::available_codepages(const bool &noAliases)
780 QStringList codecList;
781 QList<QByteArray> availableCodecs = QTextCodec::availableCodecs();
783 while(!availableCodecs.isEmpty())
785 const QByteArray current = availableCodecs.takeFirst();
786 if(!current.toLower().startsWith("system"))
788 codecList << QString::fromLatin1(current.constData(), current.size());
789 if(noAliases)
791 if(QTextCodec *const currentCodec = QTextCodec::codecForName(current.constData()))
793 const QList<QByteArray> aliases = currentCodec->aliases();
794 for(QList<QByteArray>::ConstIterator iter = aliases.constBegin(); iter != aliases.constEnd(); iter++)
796 availableCodecs.removeAll(*iter);
803 return codecList;
806 ///////////////////////////////////////////////////////////////////////////////
807 // FP MATH SUPPORT
808 ///////////////////////////////////////////////////////////////////////////////
810 MUtils::fp_parts_t MUtils::break_fp(const double value)
812 fp_parts_t result = { };
813 if (_finite(value))
815 result.parts[1] = modf(value, &result.parts[0]);
817 else
819 result.parts[0] = std::numeric_limits<double>::quiet_NaN();
820 result.parts[1] = std::numeric_limits<double>::quiet_NaN();
822 return result;
825 ///////////////////////////////////////////////////////////////////////////////
826 // SELF-TEST
827 ///////////////////////////////////////////////////////////////////////////////
829 int MUtils::Internal::selfTest(const char *const buildKey, const bool debug)
831 static const bool MY_DEBUG_FLAG = MUTILS_DEBUG;
832 static const char *const MY_BUILD_KEY = __DATE__ "@" __TIME__;
834 if(strncmp(buildKey, MY_BUILD_KEY, 13) || (MY_DEBUG_FLAG != debug))
836 MUtils::OS::system_message_err(L"MUtils", L"FATAL ERROR: MUtils library version mismatch detected!");
837 MUtils::OS::system_message_wrn(L"MUtils", L"Perform a clean(!) re-install of the application to fix the problem!");
838 abort();
840 return 0;