OSDN Git Service

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