1 ///////////////////////////////////////////////////////////////////////////////
2 // MuldeR's Utilities for Qt
3 // Copyright (C) 2004-2014 LoRd_MuldeR <MuldeR2@GMX.de>
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.
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 //////////////////////////////////////////////////////////////////////////////////
27 #include <MUtils/Global.h>
28 #include <MUtils/OSSupport.h>
29 #include "DirLocker.h"
33 #include <QReadWriteLock>
41 ///////////////////////////////////////////////////////////////////////////////
43 ///////////////////////////////////////////////////////////////////////////////
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)
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);
65 void MUtils::seed_rand(void)
67 qsrand(mix_function(clock(), time(NULL), _getpid()));
70 quint32 MUtils::next_rand32(void)
72 quint32 rnd = 0xDEADBEEF;
81 for(size_t i = 0; i < sizeof(quint32); i++)
83 rnd = (rnd << 8) ^ qrand();
89 quint64 MUtils::next_rand64(void)
91 return (quint64(next_rand32()) << 32) | quint64(next_rand32());
94 QString MUtils::rand_str(const bool &bLong)
98 return QString::number(next_rand64(), 16).rightJustified(16, QLatin1Char('0'));
100 return QString("%1%2").arg(rand_str(false), rand_str(false));
103 ///////////////////////////////////////////////////////////////////////////////
105 ///////////////////////////////////////////////////////////////////////////////
107 static QScopedPointer<MUtils::Internal::DirLock> g_temp_folder_file;
108 static QReadWriteLock g_temp_folder_lock;
110 static QString try_create_subfolder(const QString &baseDir, const QString &postfix)
112 const QString baseDirPath = QDir(baseDir).absolutePath();
113 for(int i = 0; i < 32; i++)
115 QDir directory(baseDirPath);
116 if(directory.mkpath(postfix) && directory.cd(postfix))
118 return directory.canonicalPath();
124 static MUtils::Internal::DirLock *try_init_temp_folder(const QString &baseDir)
126 const QString tempPath = try_create_subfolder(baseDir, MUtils::rand_str());
127 if(!tempPath.isEmpty())
129 for(int i = 0; i < 32; i++)
131 MUtils::Internal::DirLock *lockFile = NULL;
134 lockFile = new MUtils::Internal::DirLock(tempPath);
137 catch(MUtils::Internal::DirLockException&)
139 /*ignore error and try again*/
146 const QString &MUtils::temp_folder(void)
148 QReadLocker readLock(&g_temp_folder_lock);
150 //Already initialized?
151 if(!g_temp_folder_file.isNull())
153 return g_temp_folder_file->path();
156 //Obtain the write lock to initilaize
158 QWriteLocker writeLock(&g_temp_folder_lock);
160 //Still uninitilaized?
161 if(!g_temp_folder_file.isNull())
163 return g_temp_folder_file->path();
166 //Try the %TMP% or %TEMP% directory first
167 if(MUtils::Internal::DirLock *lockFile = try_init_temp_folder(QDir::tempPath()))
169 g_temp_folder_file.reset(lockFile);
170 return lockFile->path();
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++)
177 const QString &knownFolder = OS::known_folder(FOLDER_ID[id]);
178 if(!knownFolder.isEmpty())
180 const QString tempRoot = try_create_subfolder(knownFolder, QLatin1String("TEMP"));
181 if(!tempRoot.isEmpty())
183 if(MUtils::Internal::DirLock *lockFile = try_init_temp_folder(tempRoot))
185 g_temp_folder_file.reset(lockFile);
186 return lockFile->path();
192 qFatal("Temporary directory could not be initialized !!!");
193 return (*((QString*)NULL));
196 ///////////////////////////////////////////////////////////////////////////////
197 // REMOVE DIRECTORY / FILE
198 ///////////////////////////////////////////////////////////////////////////////
200 bool MUtils::remove_file(const QString &fileName)
202 QFileInfo fileInfo(fileName);
203 if(!(fileInfo.exists() && fileInfo.isFile()))
208 for(int i = 0; i < 32; i++)
210 QFile file(fileName);
211 file.setPermissions(QFile::ReadOther | QFile::WriteOther);
218 qWarning("Could not delete \"%s\"", MUTILS_UTF8(fileName));
222 bool MUtils::remove_directory(const QString &folderPath)
224 QDir folder(folderPath);
230 const QFileInfoList entryList = folder.entryInfoList(QDir::AllEntries | QDir::NoDotAndDotDot | QDir::Hidden);
231 for(int i = 0; i < entryList.count(); i++)
233 if(entryList.at(i).isDir())
235 remove_directory(entryList.at(i).canonicalFilePath());
239 remove_file(entryList.at(i).canonicalFilePath());
243 for(int i = 0; i < 32; i++)
245 if(folder.rmdir("."))
251 qWarning("Could not rmdir \"%s\"", MUTILS_UTF8(folderPath));
255 ///////////////////////////////////////////////////////////////////////////////
257 ///////////////////////////////////////////////////////////////////////////////
259 void MUtils::init_process(QProcess &process, const QString &wokringDir, const bool bReplaceTempDir)
261 //Environment variable names
262 static const char *const s_envvar_names_temp[] =
264 "TEMP", "TMP", "TMPDIR", "HOME", "USERPROFILE", "HOMEPATH", NULL
266 static const char *const s_envvar_names_remove[] =
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
271 //Initialize environment
272 QProcessEnvironment env = process.processEnvironment();
273 if(env.isEmpty()) env = QProcessEnvironment::systemEnvironment();
275 //Clean a number of enviroment variables that might affect our tools
276 for(size_t i = 0; s_envvar_names_remove[i]; i++)
278 env.remove(QString::fromLatin1(s_envvar_names_remove[i]));
279 env.remove(QString::fromLatin1(s_envvar_names_remove[i]).toLower());
282 const QString tempDir = QDir::toNativeSeparators(temp_folder());
284 //Replace TEMP directory in environment
287 for(size_t i = 0; s_envvar_names_temp[i]; i++)
289 env.insert(s_envvar_names_temp[i], tempDir);
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));
297 //Setup QPorcess object
298 process.setWorkingDirectory(wokringDir);
299 process.setProcessChannelMode(QProcess::MergedChannels);
300 process.setReadChannel(QProcess::StandardOutput);
301 process.setProcessEnvironment(env);
304 ///////////////////////////////////////////////////////////////////////////////
306 ///////////////////////////////////////////////////////////////////////////////
308 int MUtils::Internal::selfTest(const char *const date, const bool debug)
310 if(strncmp(date, __DATE__"@"__TIME__, 14) || (MUTILS_DEBUG != debug))
312 MUtils::OS::system_message_err(L"MUtils", L"FATAL ERROR: MUtils library version mismatch detected!");