OSDN Git Service

Change current directory to root directory *before* trying to clean up the TEMP folde...
[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 #ifdef _MSC_VER
47 #include <vld.h>
48 #endif
49
50 ///////////////////////////////////////////////////////////////////////////////
51 // Random Support
52 ///////////////////////////////////////////////////////////////////////////////
53
54 //Robert Jenkins' 96 bit Mix Function
55 static unsigned int mix_function(const unsigned int x, const unsigned int y, const unsigned int z)
56 {
57         unsigned int a = x;
58         unsigned int b = y;
59         unsigned int c = z;
60         
61         a=a-b;  a=a-c;  a=a^(c >> 13);
62         b=b-c;  b=b-a;  b=b^(a << 8 ); 
63         c=c-a;  c=c-b;  c=c^(b >> 13);
64         a=a-b;  a=a-c;  a=a^(c >> 12);
65         b=b-c;  b=b-a;  b=b^(a << 16);
66         c=c-a;  c=c-b;  c=c^(b >> 5 );
67         a=a-b;  a=a-c;  a=a^(c >> 3 );
68         b=b-c;  b=b-a;  b=b^(a << 10);
69         c=c-a;  c=c-b;  c=c^(b >> 15);
70
71         return a ^ b ^ c;
72 }
73
74 void MUtils::seed_rand(void)
75 {
76         qsrand(mix_function(clock(), time(NULL), _getpid()));
77 }
78
79 quint32 MUtils::next_rand32(void)
80 {
81         quint32 rnd = 0xDEADBEEF;
82
83 #ifdef _CRT_RAND_S
84         if(rand_s(&rnd) == 0)
85         {
86                 return rnd;
87         }
88 #endif //_CRT_RAND_S
89
90         for(size_t i = 0; i < sizeof(quint32); i++)
91         {
92                 rnd = (rnd << 8) ^ qrand();
93         }
94
95         return rnd;
96 }
97
98 quint64 MUtils::next_rand64(void)
99 {
100         return (quint64(next_rand32()) << 32) | quint64(next_rand32());
101 }
102
103 QString MUtils::rand_str(const bool &bLong)
104 {
105         if(!bLong)
106         {
107                 return QString::number(next_rand64(), 16).rightJustified(16, QLatin1Char('0'));
108         }
109         return QString("%1%2").arg(rand_str(false), rand_str(false));
110 }
111
112 ///////////////////////////////////////////////////////////////////////////////
113 // TEMP FOLDER
114 ///////////////////////////////////////////////////////////////////////////////
115
116 static QScopedPointer<MUtils::Internal::DirLock> g_temp_folder_file;
117 static QReadWriteLock                            g_temp_folder_lock;
118
119 static QString try_create_subfolder(const QString &baseDir, const QString &postfix)
120 {
121         const QString baseDirPath = QDir(baseDir).absolutePath();
122         for(int i = 0; i < 32; i++)
123         {
124                 QDir directory(baseDirPath);
125                 if(directory.mkpath(postfix) && directory.cd(postfix))
126                 {
127                         return directory.canonicalPath();
128                 }
129         }
130         return QString();
131 }
132
133 static MUtils::Internal::DirLock *try_init_temp_folder(const QString &baseDir)
134 {
135         const QString tempPath = try_create_subfolder(baseDir, MUtils::rand_str());
136         if(!tempPath.isEmpty())
137         {
138                 for(int i = 0; i < 32; i++)
139                 {
140                         MUtils::Internal::DirLock *lockFile = NULL;
141                         try
142                         {
143                                 lockFile = new MUtils::Internal::DirLock(tempPath);
144                                 return lockFile;
145                         }
146                         catch(MUtils::Internal::DirLockException&)
147                         {
148                                 /*ignore error and try again*/
149                         }
150                 }
151         }
152         return NULL;
153 }
154
155 static void temp_folder_cleanup_helper(const QString &tempPath)
156 {
157         bool okay = false;
158         for(int i = 0; i < 32; i++)
159         {
160                 QDir::setCurrent(QDir::rootPath());
161                 if(MUtils::remove_directory(tempPath, true))
162                 {
163                         okay = true;
164                         break;
165                 }
166                 MUtils::OS::sleep_ms(125);
167         }
168         if(!okay)
169         {
170                 MUtils::OS::system_message_wrn(L"Temp Cleaner", L"Warning: Not all temporary files could be removed!");
171         }
172 }
173
174 static void temp_folder_cleaup(void)
175 {
176         QWriteLocker writeLock(&g_temp_folder_lock);
177         
178         //Clean the directory
179         while(!g_temp_folder_file.isNull())
180         {
181                 const QString tempPath = g_temp_folder_file->getPath();
182                 g_temp_folder_file.reset(NULL);
183                 temp_folder_cleanup_helper(tempPath);
184         }
185 }
186
187 const QString &MUtils::temp_folder(void)
188 {
189         QReadLocker readLock(&g_temp_folder_lock);
190
191         //Already initialized?
192         if(!g_temp_folder_file.isNull())
193         {
194                 return g_temp_folder_file->getPath();
195         }
196
197         //Obtain the write lock to initilaize
198         readLock.unlock();
199         QWriteLocker writeLock(&g_temp_folder_lock);
200         
201         //Still uninitilaized?
202         if(!g_temp_folder_file.isNull())
203         {
204                 return g_temp_folder_file->getPath();
205         }
206
207         //Try the %TMP% or %TEMP% directory first
208         if(MUtils::Internal::DirLock *lockFile = try_init_temp_folder(QDir::tempPath()))
209         {
210                 g_temp_folder_file.reset(lockFile);
211                 atexit(temp_folder_cleaup);
212                 return lockFile->getPath();
213         }
214
215         qWarning("%%TEMP%% directory not found -> trying fallback mode now!");
216         static const OS::known_folder_t FOLDER_ID[2] = { OS::FOLDER_LOCALAPPDATA, OS::FOLDER_SYSTROOT_DIR };
217         for(size_t id = 0; id < 2; id++)
218         {
219                 const QString &knownFolder = OS::known_folder(FOLDER_ID[id]);
220                 if(!knownFolder.isEmpty())
221                 {
222                         const QString tempRoot = try_create_subfolder(knownFolder, QLatin1String("TEMP"));
223                         if(!tempRoot.isEmpty())
224                         {
225                                 if(MUtils::Internal::DirLock *lockFile = try_init_temp_folder(tempRoot))
226                                 {
227                                         g_temp_folder_file.reset(lockFile);
228                                         atexit(temp_folder_cleaup);
229                                         return lockFile->getPath();
230                                 }
231                         }
232                 }
233         }
234
235         qFatal("Temporary directory could not be initialized !!!");
236         return (*((QString*)NULL));
237 }
238
239 ///////////////////////////////////////////////////////////////////////////////
240 // REMOVE DIRECTORY / FILE
241 ///////////////////////////////////////////////////////////////////////////////
242
243 bool MUtils::remove_file(const QString &fileName)
244 {
245         QFileInfo fileInfo(fileName);
246         if(!(fileInfo.exists() && fileInfo.isFile()))
247         {
248                 return true;
249         }
250
251         for(int i = 0; i < 32; i++)
252         {
253                 QFile file(fileName);
254                 file.setPermissions(QFile::ReadOther | QFile::WriteOther);
255                 if((!(fileInfo.exists() && fileInfo.isFile())) || file.remove())
256                 {
257                         return true;
258                 }
259                 fileInfo.refresh();
260         }
261
262         qWarning("Could not delete \"%s\"", MUTILS_UTF8(fileName));
263         return false;
264 }
265
266 static bool remove_directory_helper(QDir folder)
267 {
268         if(!folder.exists())
269         {
270                 return true;
271         }
272         
273         const QString dirName = folder.dirName();
274         if(dirName.isEmpty() || (!folder.cdUp()))
275         {
276                 return false;
277         }
278
279         return folder.rmdir(dirName);
280 }
281
282 bool MUtils::remove_directory(const QString &folderPath, const bool &recursive)
283 {
284         QDir folder(folderPath);
285         if(!folder.exists())
286         {
287                 return true;
288         }
289
290         if(recursive)
291         {
292                 const QFileInfoList entryList = folder.entryInfoList(QDir::AllEntries | QDir::NoDotAndDotDot | QDir::Hidden);
293                 for(QFileInfoList::ConstIterator iter = entryList.constBegin(); iter != entryList.constEnd(); iter++)
294                 {
295                         if(iter->isDir())
296                         {
297                                 remove_directory(iter->canonicalFilePath(), true);
298                         }
299                         else if(iter->isFile())
300                         {
301                                 remove_file(iter->canonicalFilePath());
302                         }
303                 }
304         }
305
306         for(int i = 0; i < 32; i++)
307         {
308                 if(!folder.exists())
309                 {
310                         return true;
311                 }
312                 const QString dirName = folder.dirName();
313                 if(!dirName.isEmpty())
314                 {
315                         QDir parent(folder);
316                         if(parent.cdUp())
317                         {
318                                 if(parent.rmdir(dirName))
319                                 {
320                                         return true;
321                                 }
322                         }
323                 }
324                 folder.refresh();
325         }
326         
327         qWarning("Could not rmdir \"%s\"", MUTILS_UTF8(folderPath));
328         return false;
329 }
330
331 ///////////////////////////////////////////////////////////////////////////////
332 // PROCESS UTILS
333 ///////////////////////////////////////////////////////////////////////////////
334
335 void MUtils::init_process(QProcess &process, const QString &wokringDir, const bool bReplaceTempDir)
336 {
337         //Environment variable names
338         static const char *const s_envvar_names_temp[] =
339         {
340                 "TEMP", "TMP", "TMPDIR", "HOME", "USERPROFILE", "HOMEPATH", NULL
341         };
342         static const char *const s_envvar_names_remove[] =
343         {
344                 "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
345         };
346
347         //Initialize environment
348         QProcessEnvironment env = process.processEnvironment();
349         if(env.isEmpty()) env = QProcessEnvironment::systemEnvironment();
350
351         //Clean a number of enviroment variables that might affect our tools
352         for(size_t i = 0; s_envvar_names_remove[i]; i++)
353         {
354                 env.remove(QString::fromLatin1(s_envvar_names_remove[i]));
355                 env.remove(QString::fromLatin1(s_envvar_names_remove[i]).toLower());
356         }
357
358         const QString tempDir = QDir::toNativeSeparators(temp_folder());
359
360         //Replace TEMP directory in environment
361         if(bReplaceTempDir)
362         {
363                 for(size_t i = 0; s_envvar_names_temp[i]; i++)
364                 {
365                         env.insert(s_envvar_names_temp[i], tempDir);
366                 }
367         }
368
369         //Setup PATH variable
370         const QString path = env.value("PATH", QString()).trimmed();
371         env.insert("PATH", path.isEmpty() ? tempDir : QString("%1;%2").arg(tempDir, path));
372         
373         //Setup QPorcess object
374         process.setWorkingDirectory(wokringDir);
375         process.setProcessChannelMode(QProcess::MergedChannels);
376         process.setReadChannel(QProcess::StandardOutput);
377         process.setProcessEnvironment(env);
378 }
379
380 ///////////////////////////////////////////////////////////////////////////////
381 // NATURAL ORDER STRING COMPARISON
382 ///////////////////////////////////////////////////////////////////////////////
383
384 static bool natural_string_sort_helper(const QString &str1, const QString &str2)
385 {
386         return (MUtils::Internal::NaturalSort::strnatcmp(MUTILS_WCHR(str1), MUTILS_WCHR(str2)) < 0);
387 }
388
389 static bool natural_string_sort_helper_fold_case(const QString &str1, const QString &str2)
390 {
391         return (MUtils::Internal::NaturalSort::strnatcasecmp(MUTILS_WCHR(str1), MUTILS_WCHR(str2)) < 0);
392 }
393
394 void MUtils::natural_string_sort(QStringList &list, const bool bIgnoreCase)
395 {
396         qSort(list.begin(), list.end(), bIgnoreCase ? natural_string_sort_helper_fold_case : natural_string_sort_helper);
397 }
398
399 ///////////////////////////////////////////////////////////////////////////////
400 // CLEAN FILE PATH
401 ///////////////////////////////////////////////////////////////////////////////
402
403 static const struct
404 {
405         const char *const search;
406         const char *const replace;
407 }
408 CLEAN_FILE_NAME[] =
409 {
410         { "\\",  "-"  },
411         { " / ", ", " },
412         { "/",   ","  },
413         { ":",   "-"  },
414         { "*",   "x"  },
415         { "?",   "!"  },
416         { "<",   "["  },
417         { ">",   "]"  },
418         { "|",   "!"  },
419         { "\"",  "'"  },
420         { NULL,  NULL }
421 };
422
423 QString MUtils::clean_file_name(const QString &name)
424 {
425         QString str = name.simplified();
426
427         for(size_t i = 0; CLEAN_FILE_NAME[i].search; i++) 
428         {
429                 str.replace(CLEAN_FILE_NAME[i].search, CLEAN_FILE_NAME[i].replace);
430         }
431         
432         QRegExp regExp("\"(.+)\"");
433         regExp.setMinimal(true);
434         str.replace(regExp, "`\\1ยด");
435         
436         return str.simplified();
437 }
438
439 QString MUtils::clean_file_path(const QString &path)
440 {
441         QStringList parts = path.simplified().replace("\\", "/").split("/", QString::SkipEmptyParts);
442
443         for(int i = 0; i < parts.count(); i++)
444         {
445                 parts[i] = MUtils::clean_file_name(parts[i]);
446         }
447
448         return parts.join("/");
449 }
450
451 ///////////////////////////////////////////////////////////////////////////////
452 // REGULAR EXPESSION HELPER
453 ///////////////////////////////////////////////////////////////////////////////
454
455 bool MUtils::regexp_parse_uint32(const QRegExp &regexp, quint32 &value)
456 {
457         return regexp_parse_uint32(regexp, &value, 1);
458 }
459
460 bool MUtils::regexp_parse_uint32(const QRegExp &regexp, quint32 *values, const size_t &count)
461 {
462         const QStringList caps = regexp.capturedTexts();
463         
464         if(caps.isEmpty() || (quint32(caps.count()) <= count))
465         {
466                 return false;
467         }
468
469         for(size_t i = 0; i < count; i++)
470         {
471                 bool ok = false;
472                 values[i] = caps[i+1].toUInt(&ok);
473                 if(!ok)
474                 {
475                         return false;
476                 }
477         }
478
479         return true;
480 }
481
482 ///////////////////////////////////////////////////////////////////////////////
483 // AVAILABLE CODEPAGES
484 ///////////////////////////////////////////////////////////////////////////////
485
486 QStringList MUtils::available_codepages(const bool &noAliases)
487 {
488         QStringList codecList;
489         QList<QByteArray> availableCodecs = QTextCodec::availableCodecs();
490
491         while(!availableCodecs.isEmpty())
492         {
493                 const QByteArray current = availableCodecs.takeFirst();
494                 if(!current.toLower().startsWith("system"))
495                 {
496                         codecList << QString::fromLatin1(current.constData(), current.size());
497                         if(noAliases)
498                         {
499                                 if(QTextCodec *const currentCodec = QTextCodec::codecForName(current.constData()))
500                                 {
501                                         const QList<QByteArray> aliases = currentCodec->aliases();
502                                         for(QList<QByteArray>::ConstIterator iter = aliases.constBegin(); iter != aliases.constEnd(); iter++)
503                                         {
504                                                 availableCodecs.removeAll(*iter);
505                                         }
506                                 }
507                         }
508                 }
509         }
510
511         return codecList;
512 }
513
514 ///////////////////////////////////////////////////////////////////////////////
515 // SELF-TEST
516 ///////////////////////////////////////////////////////////////////////////////
517
518 int MUtils::Internal::selfTest(const char *const buildKey, const bool debug)
519 {
520         static const bool MY_DEBUG_FLAG = MUTILS_DEBUG;
521         static const char *const MY_BUILD_KEY = __DATE__"@"__TIME__;
522
523         if(strncmp(buildKey, MY_BUILD_KEY, 14) || (MY_DEBUG_FLAG != debug))
524         {
525                 MUtils::OS::system_message_err(L"MUtils", L"FATAL ERROR: MUtils library version mismatch detected!");
526                 MUtils::OS::system_message_wrn(L"MUtils", L"Please re-build the complete solution in order to fix this issue!");
527                 abort();
528         }
529         return 0;
530 }