OSDN Git Service

Moved available_codepages() function into MUtilities library.
[mutilities/MUtilities.git] / src / Global.cpp
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.
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
30 //Internal
31 #include "DirLocker.h"
32 #include "3rd_party/strnatcmp/include/strnatcmp.h"
33
34 //Qt
35 #include <QDir>
36 #include <QReadWriteLock>
37 #include <QProcess>
38 #include <QTextCodec>
39
40 //CRT
41 #include <cstdlib>
42 #include <ctime>
43 #include <process.h>
44
45 //VLD
46 #include <vld.h>
47
48 ///////////////////////////////////////////////////////////////////////////////
49 // Random Support
50 ///////////////////////////////////////////////////////////////////////////////
51
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)
54 {
55         unsigned int a = x;
56         unsigned int b = y;
57         unsigned int c = z;
58         
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);
68
69         return a ^ b ^ c;
70 }
71
72 void MUtils::seed_rand(void)
73 {
74         qsrand(mix_function(clock(), time(NULL), _getpid()));
75 }
76
77 quint32 MUtils::next_rand32(void)
78 {
79         quint32 rnd = 0xDEADBEEF;
80
81 #ifdef _CRT_RAND_S
82         if(rand_s(&rnd) == 0)
83         {
84                 return rnd;
85         }
86 #endif //_CRT_RAND_S
87
88         for(size_t i = 0; i < sizeof(quint32); i++)
89         {
90                 rnd = (rnd << 8) ^ qrand();
91         }
92
93         return rnd;
94 }
95
96 quint64 MUtils::next_rand64(void)
97 {
98         return (quint64(next_rand32()) << 32) | quint64(next_rand32());
99 }
100
101 QString MUtils::rand_str(const bool &bLong)
102 {
103         if(!bLong)
104         {
105                 return QString::number(next_rand64(), 16).rightJustified(16, QLatin1Char('0'));
106         }
107         return QString("%1%2").arg(rand_str(false), rand_str(false));
108 }
109
110 ///////////////////////////////////////////////////////////////////////////////
111 // TEMP FOLDER
112 ///////////////////////////////////////////////////////////////////////////////
113
114 static QScopedPointer<MUtils::Internal::DirLock> g_temp_folder_file;
115 static QReadWriteLock g_temp_folder_lock;
116
117 static QString try_create_subfolder(const QString &baseDir, const QString &postfix)
118 {
119         const QString baseDirPath = QDir(baseDir).absolutePath();
120         for(int i = 0; i < 32; i++)
121         {
122                 QDir directory(baseDirPath);
123                 if(directory.mkpath(postfix) && directory.cd(postfix))
124                 {
125                         return directory.canonicalPath();
126                 }
127         }
128         return QString();
129 }
130
131 static MUtils::Internal::DirLock *try_init_temp_folder(const QString &baseDir)
132 {
133         const QString tempPath = try_create_subfolder(baseDir, MUtils::rand_str());
134         if(!tempPath.isEmpty())
135         {
136                 for(int i = 0; i < 32; i++)
137                 {
138                         MUtils::Internal::DirLock *lockFile = NULL;
139                         try
140                         {
141                                 lockFile = new MUtils::Internal::DirLock(tempPath);
142                                 return lockFile;
143                         }
144                         catch(MUtils::Internal::DirLockException&)
145                         {
146                                 /*ignore error and try again*/
147                         }
148                 }
149         }
150         return NULL;
151 }
152
153 const QString &MUtils::temp_folder(void)
154 {
155         QReadLocker readLock(&g_temp_folder_lock);
156
157         //Already initialized?
158         if(!g_temp_folder_file.isNull())
159         {
160                 return g_temp_folder_file->path();
161         }
162
163         //Obtain the write lock to initilaize
164         readLock.unlock();
165         QWriteLocker writeLock(&g_temp_folder_lock);
166         
167         //Still uninitilaized?
168         if(!g_temp_folder_file.isNull())
169         {
170                 return g_temp_folder_file->path();
171         }
172
173         //Try the %TMP% or %TEMP% directory first
174         if(MUtils::Internal::DirLock *lockFile = try_init_temp_folder(QDir::tempPath()))
175         {
176                 g_temp_folder_file.reset(lockFile);
177                 return lockFile->path();
178         }
179
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++)
183         {
184                 const QString &knownFolder = OS::known_folder(FOLDER_ID[id]);
185                 if(!knownFolder.isEmpty())
186                 {
187                         const QString tempRoot = try_create_subfolder(knownFolder, QLatin1String("TEMP"));
188                         if(!tempRoot.isEmpty())
189                         {
190                                 if(MUtils::Internal::DirLock *lockFile = try_init_temp_folder(tempRoot))
191                                 {
192                                         g_temp_folder_file.reset(lockFile);
193                                         return lockFile->path();
194                                 }
195                         }
196                 }
197         }
198
199         qFatal("Temporary directory could not be initialized !!!");
200         return (*((QString*)NULL));
201 }
202
203 ///////////////////////////////////////////////////////////////////////////////
204 // REMOVE DIRECTORY / FILE
205 ///////////////////////////////////////////////////////////////////////////////
206
207 bool MUtils::remove_file(const QString &fileName)
208 {
209         QFileInfo fileInfo(fileName);
210         if(!(fileInfo.exists() && fileInfo.isFile()))
211         {
212                 return true;
213         }
214
215         for(int i = 0; i < 32; i++)
216         {
217                 QFile file(fileName);
218                 file.setPermissions(QFile::ReadOther | QFile::WriteOther);
219                 if(file.remove())
220                 {
221                         return true;
222                 }
223         }
224
225         qWarning("Could not delete \"%s\"", MUTILS_UTF8(fileName));
226         return false;
227 }
228
229 bool MUtils::remove_directory(const QString &folderPath)
230 {
231         QDir folder(folderPath);
232         if(!folder.exists())
233         {
234                 return true;
235         }
236
237         const QFileInfoList entryList = folder.entryInfoList(QDir::AllEntries | QDir::NoDotAndDotDot | QDir::Hidden);
238         for(int i = 0; i < entryList.count(); i++)
239         {
240                 if(entryList.at(i).isDir())
241                 {
242                         remove_directory(entryList.at(i).canonicalFilePath());
243                 }
244                 else
245                 {
246                         remove_file(entryList.at(i).canonicalFilePath());
247                 }
248         }
249
250         for(int i = 0; i < 32; i++)
251         {
252                 if(folder.rmdir("."))
253                 {
254                         return true;
255                 }
256         }
257         
258         qWarning("Could not rmdir \"%s\"", MUTILS_UTF8(folderPath));
259         return false;
260 }
261
262 ///////////////////////////////////////////////////////////////////////////////
263 // PROCESS UTILS
264 ///////////////////////////////////////////////////////////////////////////////
265
266 void MUtils::init_process(QProcess &process, const QString &wokringDir, const bool bReplaceTempDir)
267 {
268         //Environment variable names
269         static const char *const s_envvar_names_temp[] =
270         {
271                 "TEMP", "TMP", "TMPDIR", "HOME", "USERPROFILE", "HOMEPATH", NULL
272         };
273         static const char *const s_envvar_names_remove[] =
274         {
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
276         };
277
278         //Initialize environment
279         QProcessEnvironment env = process.processEnvironment();
280         if(env.isEmpty()) env = QProcessEnvironment::systemEnvironment();
281
282         //Clean a number of enviroment variables that might affect our tools
283         for(size_t i = 0; s_envvar_names_remove[i]; i++)
284         {
285                 env.remove(QString::fromLatin1(s_envvar_names_remove[i]));
286                 env.remove(QString::fromLatin1(s_envvar_names_remove[i]).toLower());
287         }
288
289         const QString tempDir = QDir::toNativeSeparators(temp_folder());
290
291         //Replace TEMP directory in environment
292         if(bReplaceTempDir)
293         {
294                 for(size_t i = 0; s_envvar_names_temp[i]; i++)
295                 {
296                         env.insert(s_envvar_names_temp[i], tempDir);
297                 }
298         }
299
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));
303         
304         //Setup QPorcess object
305         process.setWorkingDirectory(wokringDir);
306         process.setProcessChannelMode(QProcess::MergedChannels);
307         process.setReadChannel(QProcess::StandardOutput);
308         process.setProcessEnvironment(env);
309 }
310
311 ///////////////////////////////////////////////////////////////////////////////
312 // NATURAL ORDER STRING COMPARISON
313 ///////////////////////////////////////////////////////////////////////////////
314
315 static bool natural_string_sort_helper(const QString &str1, const QString &str2)
316 {
317         return (MUtils::Internal::NaturalSort::strnatcmp(MUTILS_WCHR(str1), MUTILS_WCHR(str2)) < 0);
318 }
319
320 static bool natural_string_sort_helper_fold_case(const QString &str1, const QString &str2)
321 {
322         return (MUtils::Internal::NaturalSort::strnatcasecmp(MUTILS_WCHR(str1), MUTILS_WCHR(str2)) < 0);
323 }
324
325 void MUtils::natural_string_sort(QStringList &list, const bool bIgnoreCase)
326 {
327         qSort(list.begin(), list.end(), bIgnoreCase ? natural_string_sort_helper_fold_case : natural_string_sort_helper);
328 }
329
330 ///////////////////////////////////////////////////////////////////////////////
331 // CLEAN FILE PATH
332 ///////////////////////////////////////////////////////////////////////////////
333
334 static const struct
335 {
336         const char *const search;
337         const char *const replace;
338 }
339 CLEAN_FILE_NAME[] =
340 {
341         { "\\",  "-"  },
342         { " / ", ", " },
343         { "/",   ","  },
344         { ":",   "-"  },
345         { "*",   "x"  },
346         { "?",   "!"  },
347         { "<",   "["  },
348         { ">",   "]"  },
349         { "|",   "!"  },
350         { "\"",  "'"  },
351         { NULL,  NULL }
352 };
353
354 QString MUtils::clean_file_name(const QString &name)
355 {
356         QString str = name.simplified();
357
358         for(size_t i = 0; CLEAN_FILE_NAME[i].search; i++) 
359         {
360                 str.replace(CLEAN_FILE_NAME[i].search, CLEAN_FILE_NAME[i].replace);
361         }
362         
363         QRegExp regExp("\"(.+)\"");
364         regExp.setMinimal(true);
365         str.replace(regExp, "`\\1ยด");
366         
367         return str.simplified();
368 }
369
370 QString MUtils::clean_file_path(const QString &path)
371 {
372         QStringList parts = path.simplified().replace("\\", "/").split("/", QString::SkipEmptyParts);
373
374         for(int i = 0; i < parts.count(); i++)
375         {
376                 parts[i] = MUtils::clean_file_name(parts[i]);
377         }
378
379         return parts.join("/");
380 }
381
382 ///////////////////////////////////////////////////////////////////////////////
383 // AVAILABLE CODEPAGES
384 ///////////////////////////////////////////////////////////////////////////////
385
386 QStringList MUtils::available_codepages(const bool &noAliases)
387 {
388         QStringList codecList;
389         QList<QByteArray> availableCodecs = QTextCodec::availableCodecs();
390
391         while(!availableCodecs.isEmpty())
392         {
393                 const QByteArray current = availableCodecs.takeFirst();
394                 if(!current.toLower().startsWith("system"))
395                 {
396                         codecList << QString::fromLatin1(current.constData(), current.size());
397                         if(noAliases)
398                         {
399                                 if(QTextCodec *const currentCodec = QTextCodec::codecForName(current.constData()))
400                                 {
401                                         const QList<QByteArray> aliases = currentCodec->aliases();
402                                         for(QList<QByteArray>::ConstIterator iter = aliases.constBegin(); iter != aliases.constEnd(); iter++)
403                                         {
404                                                 availableCodecs.removeAll(*iter);
405                                         }
406                                 }
407                         }
408                 }
409         }
410
411         return codecList;
412 }
413
414 ///////////////////////////////////////////////////////////////////////////////
415 // SELF-TEST
416 ///////////////////////////////////////////////////////////////////////////////
417
418 int MUtils::Internal::selfTest(const char *const buildKey, const bool debug)
419 {
420         static const bool MY_DEBUG_FLAG = MUTILS_DEBUG;
421         static const char *const MY_BUILD_KEY = __DATE__"@"__TIME__;
422
423         if(strncmp(buildKey, MY_BUILD_KEY, 14) || (MY_DEBUG_FLAG != debug))
424         {
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!");
427                 abort();
428         }
429         return 0;
430 }