Fixed some typos + moved "main" page to a separate .dox file.
[MUtilities.git] / include / MUtils / Global.h
blob4a577c8a8b2723cc4ba47892f3481e676443dcfc
1 ///////////////////////////////////////////////////////////////////////////////
2 // MuldeR's Utilities for Qt
3 // Copyright (C) 2004-2016 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 /**
23 * @file
24 * @brief This file contains miscellaneous functions that are generally useful for Qt-based applications
27 #pragma once
29 #include <QString>
31 //Forward Declarations
32 class QProcess;
34 ///////////////////////////////////////////////////////////////////////////////
36 //MUtils API
37 #ifdef _MSC_VER
38 # ifdef MUTILS_DLL_EXPORT
39 # define MUTILS_API __declspec(dllexport)
40 # else
41 # ifndef MUTILS_STATIC_LIB
42 # define MUTILS_API __declspec(dllimport)
43 # else
44 # define MUTILS_API /*static lib*/
45 # endif
46 # endif
47 #else
48 # define MUTILS_API
49 #endif
51 //Helper Macros
52 #define MUTILS_MAKE_STRING_HELPER(X) #X
53 #define MUTILS_MAKE_STRING(X) MUTILS_MAKE_STRING_HELPER(X)
54 #define MUTILS_COMPILER_WARNING(TXT) __pragma(message(__FILE__ "(" MUTILS_MAKE_STRING(__LINE__) ") : warning: " TXT))
56 //Check Debug Flags
57 #if defined(_DEBUG) || defined(DEBUG) || (!defined(NDEBUG))
58 # define MUTILS_DEBUG (1)
59 # if defined(NDEBUG) || defined(QT_NO_DEBUG) || (!defined(QT_DEBUG))
60 # error Inconsistent DEBUG flags have been detected!
61 # endif
62 #else
63 # define MUTILS_DEBUG (0)
64 # if (!defined(NDEBUG)) || (!defined(QT_NO_DEBUG)) || defined(QT_DEBUG)
65 # error Inconsistent DEBUG flags have been detected!
66 # endif
67 #endif
69 //Check CPU options
70 #if defined(_MSC_VER) && (!defined(__INTELLISENSE__)) && (!defined(_M_X64)) && defined(_M_IX86_FP)
71 #if (_M_IX86_FP != 0)
72 #error We should not enabled SSE or SSE2 in release builds!
73 #endif
74 #endif
76 ///////////////////////////////////////////////////////////////////////////////
78 namespace MUtils
80 /**
81 * \brief Rerieves the full path of the application's *Temp* folder.
83 * The application's *Temp* folder is a unique application-specific folder, intended to store any temporary files that the application may need. It will be created when this function is called for the first time (lazy initialization); subsequent calls are guaranteed to return the same path. Usually the application's *Temp* folder will be created as a sub-folder of the system's global *Temp* folder, as indicated by the `TMP` or `TEMP` environment variables. However, it may be created at a different place (e.g. in the users *Profile* directory), if those environment variables don't point to a usable directory. In any case, this function makes sure that the application's *Temp* folder exists for the whole lifetime of the application and that it is writable. When the application terminates normally, the application's *Temp* folder and all files or sub-directories thereof will be *removed* automatically!
85 * \return If the function succeeds, it returns a read-only reference to a QString holding the full path of the application's *Temp* folder; otherwise a read-only reference to a default-constructed QString is returned.
87 MUTILS_API const QString& temp_folder(void);
89 //Process Utils
90 MUTILS_API void init_process(QProcess &process, const QString &wokringDir, const bool bReplaceTempDir = true, const QStringList *const extraPaths = NULL);
92 /**
93 * \brief Generates a *random* unsigned 32-Bit value.
95 * The *random* value is created using a "strong" PRNG of the underlying system, if possible. Otherwise a fallback PRNG is used. It is **not** required or useful to call `srand()` or `qsrand()` prior to using this function. If necessary, the seeding of the PRNG happen *automatically* on the first call.
97 * \return The function returns a *random* unsigned 32-Bit value.
99 MUTILS_API quint32 next_rand_u32(void);
102 * \brief Generates a *random* unsigned 64-Bit value.
104 * The *random* value is created using a "strong" PRNG of the underlying system, if possible. Otherwise a fallback PRNG is used. It is **not** required or useful to call `srand()` or `qsrand()` prior to using this function. If necessary, the seeding of the PRNG happen *automatically* on the first call.
106 * \return The function returns a *random* unsigned 64-Bit value.
108 MUTILS_API quint64 next_rand_u64(void);
111 * \brief Generates a *random* string.
113 * The random string is generated using the same PRNG as the `next_rand_u64()` function. The *random* bytes are converted to a hexadecimal string and, if necessary, zero-padded to a toal length of 16 or 32 characters. There is **no** `0x`-prefix included in the result.
115 * \param bLong If set to `true`, a "long" random string (32 characters) will be generated; if set to `false`, a "short" random string (16 characters) is generated.
117 * \return The function returns a QString holding a *random* hexadecimal string
119 MUTILS_API QString next_rand_str(const bool &bLong = false);
122 * \brief Generates a temporary file name.
124 * The function generates a file name that contains a *random* component and that is guaranteed to **not** exist yet. The generated file name follows a `"<basedir>/<random>.<ext>"` pattern. This is useful (not only) for creating temporary files.
126 * \param basePath Specifies the "base" directory where the temporary file is supposed to be created. This must be a valid *existing* directory.
128 * \param extension Specifies the desired file extensions of the temporary file. Do **not** include a leading dot (`.`) character.
130 * \param placeholder If set to `true`, the function creates an empty "placeholder" file under the returned file name; if set to `false`, it does *not*.
132 * \return If the function succeeds, it returns a QString holding the full path of the temporary file; otherwise it returns a default-constructed QString.
134 MUTILS_API QString make_temp_file(const QString &basePath, const QString &extension, const bool placeholder = false);
137 * \brief Generates a unique file name.
139 * The function generates a unique file name in the specified directory. The function guarantees that the returned file name does *not* exist yet. If necessary, a *counter* will be included in the file name in order to ensure its uniqueness.
141 * \param basePath Specifies the "base" directory where the unique file is supposed to be created. This must be a valid *existing* directory.
143 * \param baseName Specifies the desired "base" file name of the unique file. Do **not** include a file extension.
145 * \param extension Specifies the desired file extensions of the unique file. Do **not** include a leading dot (`.`) character.
147 * \param fancy If set to `true`, the file name is generated according to the `"<basedir>/<basename> (N).<ext>"` pattern; if set to `false`, the file name is generated according to the `"<basedir>/<basename>.XXXX.<ext>"` pattern.
149 * \return If the function succeeds, it returns a QString holding the full path of the unique file; otherwise it returns a default-constructed QString.
151 MUTILS_API QString make_unique_file(const QString &basePath, const QString &baseName, const QString &extension, const bool fancy = false);
154 * \brief Computes the *parity* of the given unsigned 32-Bit value
156 * \param value The 32-Bit unsigned value from which the parity is to be computed.
158 * \return The function returns `true`, if the number of **1** bits in the given value is *odd*; it returns `false`, if the number of **1** bits in the given value is *even*.
160 MUTILS_API bool parity(quint32 value);
163 * \brief Deletes the specified file
165 * The function deletes the specified file, even if it has the "read only" flag set. If the file is currently locked (e.g. by another process), the function retries multiple times to delete the file before it fails.
167 * \param fileName The path to the file to be deleted. This should be a full path.
169 * \return The function returns `true`, if the file was deleted successfully or if the file doesn't exist; it returns `false`, if the file could *not* be deleted.
171 MUTILS_API bool remove_file(const QString &fileName);
174 * \brief Recursively deletes the specified directory
176 * The function deletes the specified directory. In *recursive* mode, the directory will be removed including all of its files and sub-directories. Files are deleted using the `remove_file()` function.
178 * \param folderPath The path to the directory to be deleted. This should be a full path.
180 * \param recursive If set to `true` the function removes all files and sub-directories in the specified directory; if set to `false`, the function will *not* try to delete any files or sub-directories, which means that it will fail on non-empty directories.
182 * \return The function returns `true`, if the directory was deleted successfully or if the directory doesn't exist; it returns `false`, if the directory could *not* be deleted.
184 MUTILS_API bool remove_directory(const QString &folderPath, const bool &recursive);
187 * \brief Remove *trailing* white-space characters
189 * The function removes all *trailing* white-space characters from the specified string. Leading white-space characters are *not* removed. White-space characters are defined by the `\s` character class.
191 * \param str A reference to the QString object to be trimmed. This QString object will be modified directly.
193 * \return A reference to the trimmed QString object. This is the same QString object that was specified in the `str` parameter.
195 MUTILS_API QString& trim_right(QString &str);
198 * \brief Remove *leading* white-space characters
200 * The function removes all *leading* white-space characters from the specified string. Trailing white-space characters are *not* removed. White-space characters are defined by the `\s` character class.
202 * \param str A reference to the QString object to be trimmed. This QString object will be modified directly.
204 * \return A reference to the trimmed QString object. This is the same QString object that was specified in the `str` parameter.
206 MUTILS_API QString& trim_left(QString &str);
209 * \brief Remove *trailing* white-space characters
211 * The function removes all *trailing* white-space characters from the specified string. Leading white-space characters are *not* removed. White-space characters are defined by the `\s` character class.
213 * \param str A read-only reference to the QString object to be trimmed. The original QString object is *not* modified.
215 * \return A new QString object that equals the original QString object, except that it has all *trailing* white-space characters removed.
217 MUTILS_API QString trim_right(const QString &str);
220 * \brief Remove *trailing* white-space characters
222 * The function removes all *leading* white-space characters from the specified string. Trailing white-space characters are *not* removed. White-space characters are defined by the `\s` character class.
224 * \param str A read-only reference to the QString object to be trimmed. The original QString object is *not* modified.
226 * \return A new QString object that equals the original QString object, except that it has all *leading* white-space characters removed.
228 MUTILS_API QString trim_left(const QString &str);
231 * \brief Sort a list of strings using "natural ordering" algorithm
233 * This function implements a sort algorithm that orders alphanumeric strings in the way a human being would. See [*Natural Order String Comparison*](http://sourcefrog.net/projects/natsort/) for details!
235 * \param list A reference to the QStringList object to be sorted. The list will be sorted "in place".
237 * \param bIgnoreCase If set to `true`, the list will be sorted disregarding the character case, i.e. upper-case and lower-case characters (of the same letter) are treated the same; if set to `false`, the character case *is* taken into account.
239 MUTILS_API void natural_string_sort(QStringList &list, const bool bIgnoreCase);
241 MUTILS_API QString clean_file_name(const QString &name);
242 MUTILS_API QString clean_file_path(const QString &path);
245 * \brief Parse regular expression results
247 * This function tries to parses the result (capture) of a regular expression as an unsigned 32-Bit value. The given regular expression must contain at least *one* capture. Only the *first* capture is considered, additional captures are ignored.
249 * \param regexp A read-only reference to the [QRegExp](http://doc.qt.io/qt-4.8/qregexp.html) object whose result (capture) will be parsed. This [QRegExp](http://doc.qt.io/qt-4.8/qregexp.html) must already have been *successfully* matched against the respective input string, e.g. via `QRegExp::indexIn()`, prior to calling this function.
251 * \param value A reference to a variable of type `quint32`, where the unsigned 32-Bit representation of the result will be stored. The contents of this variable are *undefined*, if the function failed.
253 * \return The function returns `true`, if the regular expression's capture could be parsed successfully; it returns `false`, if the capture contains an invalid string or if there are insufficient captures in given the [QRegExp](http://doc.qt.io/qt-4.8/qregexp.html) object.
255 MUTILS_API bool regexp_parse_uint32(const QRegExp &regexp, quint32 &value);
258 * \brief Parse regular expression results
260 * This function tries to parses the results (captures) of a regular expression as unsigned 32-Bit values. The given regular expression must contain at least \p count captures. Only the *first* \p count captures are considered, additional captures are ignored.
262 * \param regexp A read-only reference to the [QRegExp](http://doc.qt.io/qt-4.8/qregexp.html) object whose results (captures) will be parsed. This [QRegExp](http://doc.qt.io/qt-4.8/qregexp.html) must already have been *successfully* matched against the respective input string, e.g. via `QRegExp::indexIn()`, prior to calling this function.
264 * \param value A pointer to an array of type `quint32`, where the unsigned 32-Bit representations of the results will be stored (the `n`-th result is stored at `value[n-1]`). The array must be at least \p count elements in length. The contents of this array are *undefined*, if the function failed.
266 * \param count Specifies the number of results (captures) in the given [QRegExp](http://doc.qt.io/qt-4.8/qregexp.html) object. The function tries to parse the first \p count captures and ignores any additional captures that may exist. This parameter also determines the required (minimum) length of the \p value array.
268 * \return The function returns `true`, if all of the regular expression's captures could be parsed successfully; it returns `false`, if any of the captures contain an invalid string or if there are insufficient captures in given the [QRegExp](http://doc.qt.io/qt-4.8/qregexp.html) object.
270 MUTILS_API bool regexp_parse_uint32(const QRegExp &regexp, quint32 *values, const size_t &count);
273 * \brief Retrieve a list of all available codepages
275 * The function generates a list of all codepages that are available on the system. Each codepage name returned by this function may be passed to the `QTextCodec::codecForName()` function in order to obtain a corresponding [QTextCodec](http://doc.qt.io/qt-4.8/qtextcodec.html) object.
277 * \param noAliases If set to `true`, only distinct codepages are returned, i.e. any codepage aliases are discarded from the list; if set to `false`, the returned list may (and usually will) also contain codepage aliases.
279 * \return If the function succeeds, it returns a QStringList holding the names of all codepages available on the system; otherwise it returns a default-constructed QStringList.
281 MUTILS_API QStringList available_codepages(const bool &noAliases = true);
283 //Internal
284 namespace Internal
286 MUTILS_API int selfTest(const char *const buildKey, const bool debug);
287 static const int s_selfTest = selfTest(__DATE__ "@" __TIME__, MUTILS_DEBUG);
291 ///////////////////////////////////////////////////////////////////////////////
293 //Delete helper
294 #define MUTILS_DELETE(PTR) do { if((PTR)) { delete (PTR); (PTR) = NULL; } } while(0)
295 #define MUTILS_DELETE_ARRAY(PTR) do { if((PTR)) { delete [] (PTR); (PTR) = NULL; } } while(0)
297 //Zero memory
298 #define MUTILS_ZERO_MEMORY(PTR) memset(&(PTR), 0, sizeof((PTR)))
300 //String conversion macros
301 #define MUTILS_WCHR(STR) (reinterpret_cast<const wchar_t*>((STR).utf16()))
302 #define MUTILS_UTF8(STR) ((STR).toUtf8().constData())
303 #define MUTILS_QSTR(STR) (QString::fromUtf16(reinterpret_cast<const unsigned short*>((STR))))
305 //Boolean helper
306 #define MUTILS_BOOL2STR(X) ((X) ? "1" : "0")