OSDN Git Service

7206d7763ae53c49e68c1bee92d465d173c7907e
[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
39 //CRT
40 #include <cstdlib>
41 #include <ctime>
42 #include <process.h>
43
44 //VLD
45 #include <vld.h>
46
47 ///////////////////////////////////////////////////////////////////////////////
48 // Random Support
49 ///////////////////////////////////////////////////////////////////////////////
50
51 //Robert Jenkins' 96 bit Mix Function
52 static unsigned int mix_function(const unsigned int x, const unsigned int y, const unsigned int z)
53 {
54         unsigned int a = x;
55         unsigned int b = y;
56         unsigned int c = z;
57         
58         a=a-b;  a=a-c;  a=a^(c >> 13);
59         b=b-c;  b=b-a;  b=b^(a << 8 ); 
60         c=c-a;  c=c-b;  c=c^(b >> 13);
61         a=a-b;  a=a-c;  a=a^(c >> 12);
62         b=b-c;  b=b-a;  b=b^(a << 16);
63         c=c-a;  c=c-b;  c=c^(b >> 5 );
64         a=a-b;  a=a-c;  a=a^(c >> 3 );
65         b=b-c;  b=b-a;  b=b^(a << 10);
66         c=c-a;  c=c-b;  c=c^(b >> 15);
67
68         return a ^ b ^ c;
69 }
70
71 void MUtils::seed_rand(void)
72 {
73         qsrand(mix_function(clock(), time(NULL), _getpid()));
74 }
75
76 quint32 MUtils::next_rand32(void)
77 {
78         quint32 rnd = 0xDEADBEEF;
79
80 #ifdef _CRT_RAND_S
81         if(rand_s(&rnd) == 0)
82         {
83                 return rnd;
84         }
85 #endif //_CRT_RAND_S
86
87         for(size_t i = 0; i < sizeof(quint32); i++)
88         {
89                 rnd = (rnd << 8) ^ qrand();
90         }
91
92         return rnd;
93 }
94
95 quint64 MUtils::next_rand64(void)
96 {
97         return (quint64(next_rand32()) << 32) | quint64(next_rand32());
98 }
99
100 QString MUtils::rand_str(const bool &bLong)
101 {
102         if(!bLong)
103         {
104                 return QString::number(next_rand64(), 16).rightJustified(16, QLatin1Char('0'));
105         }
106         return QString("%1%2").arg(rand_str(false), rand_str(false));
107 }
108
109 ///////////////////////////////////////////////////////////////////////////////
110 // TEMP FOLDER
111 ///////////////////////////////////////////////////////////////////////////////
112
113 static QScopedPointer<MUtils::Internal::DirLock> g_temp_folder_file;
114 static QReadWriteLock g_temp_folder_lock;
115
116 static QString try_create_subfolder(const QString &baseDir, const QString &postfix)
117 {
118         const QString baseDirPath = QDir(baseDir).absolutePath();
119         for(int i = 0; i < 32; i++)
120         {
121                 QDir directory(baseDirPath);
122                 if(directory.mkpath(postfix) && directory.cd(postfix))
123                 {
124                         return directory.canonicalPath();
125                 }
126         }
127         return QString();
128 }
129
130 static MUtils::Internal::DirLock *try_init_temp_folder(const QString &baseDir)
131 {
132         const QString tempPath = try_create_subfolder(baseDir, MUtils::rand_str());
133         if(!tempPath.isEmpty())
134         {
135                 for(int i = 0; i < 32; i++)
136                 {
137                         MUtils::Internal::DirLock *lockFile = NULL;
138                         try
139                         {
140                                 lockFile = new MUtils::Internal::DirLock(tempPath);
141                                 return lockFile;
142                         }
143                         catch(MUtils::Internal::DirLockException&)
144                         {
145                                 /*ignore error and try again*/
146                         }
147                 }
148         }
149         return NULL;
150 }
151
152 const QString &MUtils::temp_folder(void)
153 {
154         QReadLocker readLock(&g_temp_folder_lock);
155
156         //Already initialized?
157         if(!g_temp_folder_file.isNull())
158         {
159                 return g_temp_folder_file->path();
160         }
161
162         //Obtain the write lock to initilaize
163         readLock.unlock();
164         QWriteLocker writeLock(&g_temp_folder_lock);
165         
166         //Still uninitilaized?
167         if(!g_temp_folder_file.isNull())
168         {
169                 return g_temp_folder_file->path();
170         }
171
172         //Try the %TMP% or %TEMP% directory first
173         if(MUtils::Internal::DirLock *lockFile = try_init_temp_folder(QDir::tempPath()))
174         {
175                 g_temp_folder_file.reset(lockFile);
176                 return lockFile->path();
177         }
178
179         qWarning("%%TEMP%% directory not found -> trying fallback mode now!");
180         static const OS::known_folder_t FOLDER_ID[2] = { OS::FOLDER_LOCALAPPDATA, OS::FOLDER_SYSTROOT_DIR };
181         for(size_t id = 0; id < 2; id++)
182         {
183                 const QString &knownFolder = OS::known_folder(FOLDER_ID[id]);
184                 if(!knownFolder.isEmpty())
185                 {
186                         const QString tempRoot = try_create_subfolder(knownFolder, QLatin1String("TEMP"));
187                         if(!tempRoot.isEmpty())
188                         {
189                                 if(MUtils::Internal::DirLock *lockFile = try_init_temp_folder(tempRoot))
190                                 {
191                                         g_temp_folder_file.reset(lockFile);
192                                         return lockFile->path();
193                                 }
194                         }
195                 }
196         }
197
198         qFatal("Temporary directory could not be initialized !!!");
199         return (*((QString*)NULL));
200 }
201
202 ///////////////////////////////////////////////////////////////////////////////
203 // REMOVE DIRECTORY / FILE
204 ///////////////////////////////////////////////////////////////////////////////
205
206 bool MUtils::remove_file(const QString &fileName)
207 {
208         QFileInfo fileInfo(fileName);
209         if(!(fileInfo.exists() && fileInfo.isFile()))
210         {
211                 return true;
212         }
213
214         for(int i = 0; i < 32; i++)
215         {
216                 QFile file(fileName);
217                 file.setPermissions(QFile::ReadOther | QFile::WriteOther);
218                 if(file.remove())
219                 {
220                         return true;
221                 }
222         }
223
224         qWarning("Could not delete \"%s\"", MUTILS_UTF8(fileName));
225         return false;
226 }
227
228 bool MUtils::remove_directory(const QString &folderPath)
229 {
230         QDir folder(folderPath);
231         if(!folder.exists())
232         {
233                 return true;
234         }
235
236         const QFileInfoList entryList = folder.entryInfoList(QDir::AllEntries | QDir::NoDotAndDotDot | QDir::Hidden);
237         for(int i = 0; i < entryList.count(); i++)
238         {
239                 if(entryList.at(i).isDir())
240                 {
241                         remove_directory(entryList.at(i).canonicalFilePath());
242                 }
243                 else
244                 {
245                         remove_file(entryList.at(i).canonicalFilePath());
246                 }
247         }
248
249         for(int i = 0; i < 32; i++)
250         {
251                 if(folder.rmdir("."))
252                 {
253                         return true;
254                 }
255         }
256         
257         qWarning("Could not rmdir \"%s\"", MUTILS_UTF8(folderPath));
258         return false;
259 }
260
261 ///////////////////////////////////////////////////////////////////////////////
262 // PROCESS UTILS
263 ///////////////////////////////////////////////////////////////////////////////
264
265 void MUtils::init_process(QProcess &process, const QString &wokringDir, const bool bReplaceTempDir)
266 {
267         //Environment variable names
268         static const char *const s_envvar_names_temp[] =
269         {
270                 "TEMP", "TMP", "TMPDIR", "HOME", "USERPROFILE", "HOMEPATH", NULL
271         };
272         static const char *const s_envvar_names_remove[] =
273         {
274                 "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
275         };
276
277         //Initialize environment
278         QProcessEnvironment env = process.processEnvironment();
279         if(env.isEmpty()) env = QProcessEnvironment::systemEnvironment();
280
281         //Clean a number of enviroment variables that might affect our tools
282         for(size_t i = 0; s_envvar_names_remove[i]; i++)
283         {
284                 env.remove(QString::fromLatin1(s_envvar_names_remove[i]));
285                 env.remove(QString::fromLatin1(s_envvar_names_remove[i]).toLower());
286         }
287
288         const QString tempDir = QDir::toNativeSeparators(temp_folder());
289
290         //Replace TEMP directory in environment
291         if(bReplaceTempDir)
292         {
293                 for(size_t i = 0; s_envvar_names_temp[i]; i++)
294                 {
295                         env.insert(s_envvar_names_temp[i], tempDir);
296                 }
297         }
298
299         //Setup PATH variable
300         const QString path = env.value("PATH", QString()).trimmed();
301         env.insert("PATH", path.isEmpty() ? tempDir : QString("%1;%2").arg(tempDir, path));
302         
303         //Setup QPorcess object
304         process.setWorkingDirectory(wokringDir);
305         process.setProcessChannelMode(QProcess::MergedChannels);
306         process.setReadChannel(QProcess::StandardOutput);
307         process.setProcessEnvironment(env);
308 }
309
310 ///////////////////////////////////////////////////////////////////////////////
311 // NATURAL ORDER STRING COMPARISON
312 ///////////////////////////////////////////////////////////////////////////////
313
314 static bool natural_string_sort_helper(const QString &str1, const QString &str2)
315 {
316         return (MUtils::Internal::NaturalSort::strnatcmp(MUTILS_WCHR(str1), MUTILS_WCHR(str2)) < 0);
317 }
318
319 static bool natural_string_sort_helper_fold_case(const QString &str1, const QString &str2)
320 {
321         return (MUtils::Internal::NaturalSort::strnatcasecmp(MUTILS_WCHR(str1), MUTILS_WCHR(str2)) < 0);
322 }
323
324 void MUtils::natural_string_sort(QStringList &list, const bool bIgnoreCase)
325 {
326         qSort(list.begin(), list.end(), bIgnoreCase ? natural_string_sort_helper_fold_case : natural_string_sort_helper);
327 }
328
329 ///////////////////////////////////////////////////////////////////////////////
330 // SELF-TEST
331 ///////////////////////////////////////////////////////////////////////////////
332
333 int MUtils::Internal::selfTest(const char *const buildKey, const bool debug)
334 {
335         static const bool MY_DEBUG_FLAG = MUTILS_DEBUG;
336         static const char *const MY_BUILD_KEY = __DATE__"@"__TIME__;
337
338         if(strncmp(buildKey, MY_BUILD_KEY, 14) || (MY_DEBUG_FLAG != debug))
339         {
340                 MUtils::OS::system_message_err(L"MUtils", L"FATAL ERROR: MUtils library version mismatch detected!");
341                 MUtils::OS::system_message_wrn(L"MUtils", L"Please re-build the complete solution in order to fix this issue!");
342                 abort();
343         }
344         return 0;
345 }