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>
31 #include "DirLocker.h"
32 #include "3rd_party/strnatcmp/include/strnatcmp.h"
36 #include <QReadWriteLock>
47 ///////////////////////////////////////////////////////////////////////////////
49 ///////////////////////////////////////////////////////////////////////////////
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
)
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);
71 void MUtils::seed_rand(void)
73 qsrand(mix_function(clock(), time(NULL
), _getpid()));
76 quint32
MUtils::next_rand32(void)
78 quint32 rnd
= 0xDEADBEEF;
87 for(size_t i
= 0; i
< sizeof(quint32
); i
++)
89 rnd
= (rnd
<< 8) ^ qrand();
95 quint64
MUtils::next_rand64(void)
97 return (quint64(next_rand32()) << 32) | quint64(next_rand32());
100 QString
MUtils::rand_str(const bool &bLong
)
104 return QString::number(next_rand64(), 16).rightJustified(16, QLatin1Char('0'));
106 return QString("%1%2").arg(rand_str(false), rand_str(false));
109 ///////////////////////////////////////////////////////////////////////////////
111 ///////////////////////////////////////////////////////////////////////////////
113 static QScopedPointer
<MUtils::Internal::DirLock
> g_temp_folder_file
;
114 static QReadWriteLock g_temp_folder_lock
;
116 static QString
try_create_subfolder(const QString
&baseDir
, const QString
&postfix
)
118 const QString baseDirPath
= QDir(baseDir
).absolutePath();
119 for(int i
= 0; i
< 32; i
++)
121 QDir
directory(baseDirPath
);
122 if(directory
.mkpath(postfix
) && directory
.cd(postfix
))
124 return directory
.canonicalPath();
130 static MUtils::Internal::DirLock
*try_init_temp_folder(const QString
&baseDir
)
132 const QString tempPath
= try_create_subfolder(baseDir
, MUtils::rand_str());
133 if(!tempPath
.isEmpty())
135 for(int i
= 0; i
< 32; i
++)
137 MUtils::Internal::DirLock
*lockFile
= NULL
;
140 lockFile
= new MUtils::Internal::DirLock(tempPath
);
143 catch(MUtils::Internal::DirLockException
&)
145 /*ignore error and try again*/
152 const QString
&MUtils::temp_folder(void)
154 QReadLocker
readLock(&g_temp_folder_lock
);
156 //Already initialized?
157 if(!g_temp_folder_file
.isNull())
159 return g_temp_folder_file
->path();
162 //Obtain the write lock to initilaize
164 QWriteLocker
writeLock(&g_temp_folder_lock
);
166 //Still uninitilaized?
167 if(!g_temp_folder_file
.isNull())
169 return g_temp_folder_file
->path();
172 //Try the %TMP% or %TEMP% directory first
173 if(MUtils::Internal::DirLock
*lockFile
= try_init_temp_folder(QDir::tempPath()))
175 g_temp_folder_file
.reset(lockFile
);
176 return lockFile
->path();
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
++)
183 const QString
&knownFolder
= OS::known_folder(FOLDER_ID
[id
]);
184 if(!knownFolder
.isEmpty())
186 const QString tempRoot
= try_create_subfolder(knownFolder
, QLatin1String("TEMP"));
187 if(!tempRoot
.isEmpty())
189 if(MUtils::Internal::DirLock
*lockFile
= try_init_temp_folder(tempRoot
))
191 g_temp_folder_file
.reset(lockFile
);
192 return lockFile
->path();
198 qFatal("Temporary directory could not be initialized !!!");
199 return (*((QString
*)NULL
));
202 ///////////////////////////////////////////////////////////////////////////////
203 // REMOVE DIRECTORY / FILE
204 ///////////////////////////////////////////////////////////////////////////////
206 bool MUtils::remove_file(const QString
&fileName
)
208 QFileInfo
fileInfo(fileName
);
209 if(!(fileInfo
.exists() && fileInfo
.isFile()))
214 for(int i
= 0; i
< 32; i
++)
216 QFile
file(fileName
);
217 file
.setPermissions(QFile::ReadOther
| QFile::WriteOther
);
224 qWarning("Could not delete \"%s\"", MUTILS_UTF8(fileName
));
228 bool MUtils::remove_directory(const QString
&folderPath
)
230 QDir
folder(folderPath
);
236 const QFileInfoList entryList
= folder
.entryInfoList(QDir::AllEntries
| QDir::NoDotAndDotDot
| QDir::Hidden
);
237 for(int i
= 0; i
< entryList
.count(); i
++)
239 if(entryList
.at(i
).isDir())
241 remove_directory(entryList
.at(i
).canonicalFilePath());
245 remove_file(entryList
.at(i
).canonicalFilePath());
249 for(int i
= 0; i
< 32; i
++)
251 if(folder
.rmdir("."))
257 qWarning("Could not rmdir \"%s\"", MUTILS_UTF8(folderPath
));
261 ///////////////////////////////////////////////////////////////////////////////
263 ///////////////////////////////////////////////////////////////////////////////
265 void MUtils::init_process(QProcess
&process
, const QString
&wokringDir
, const bool bReplaceTempDir
)
267 //Environment variable names
268 static const char *const s_envvar_names_temp
[] =
270 "TEMP", "TMP", "TMPDIR", "HOME", "USERPROFILE", "HOMEPATH", NULL
272 static const char *const s_envvar_names_remove
[] =
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
277 //Initialize environment
278 QProcessEnvironment env
= process
.processEnvironment();
279 if(env
.isEmpty()) env
= QProcessEnvironment::systemEnvironment();
281 //Clean a number of enviroment variables that might affect our tools
282 for(size_t i
= 0; s_envvar_names_remove
[i
]; i
++)
284 env
.remove(QString::fromLatin1(s_envvar_names_remove
[i
]));
285 env
.remove(QString::fromLatin1(s_envvar_names_remove
[i
]).toLower());
288 const QString tempDir
= QDir::toNativeSeparators(temp_folder());
290 //Replace TEMP directory in environment
293 for(size_t i
= 0; s_envvar_names_temp
[i
]; i
++)
295 env
.insert(s_envvar_names_temp
[i
], tempDir
);
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
));
303 //Setup QPorcess object
304 process
.setWorkingDirectory(wokringDir
);
305 process
.setProcessChannelMode(QProcess::MergedChannels
);
306 process
.setReadChannel(QProcess::StandardOutput
);
307 process
.setProcessEnvironment(env
);
310 ///////////////////////////////////////////////////////////////////////////////
311 // NATURAL ORDER STRING COMPARISON
312 ///////////////////////////////////////////////////////////////////////////////
314 static bool natural_string_sort_helper(const QString
&str1
, const QString
&str2
)
316 return (MUtils::Internal::NaturalSort::strnatcmp(MUTILS_WCHR(str1
), MUTILS_WCHR(str2
)) < 0);
319 static bool natural_string_sort_helper_fold_case(const QString
&str1
, const QString
&str2
)
321 return (MUtils::Internal::NaturalSort::strnatcasecmp(MUTILS_WCHR(str1
), MUTILS_WCHR(str2
)) < 0);
324 void MUtils::natural_string_sort(QStringList
&list
, const bool bIgnoreCase
)
326 qSort(list
.begin(), list
.end(), bIgnoreCase
? natural_string_sort_helper_fold_case
: natural_string_sort_helper
);
329 ///////////////////////////////////////////////////////////////////////////////
331 ///////////////////////////////////////////////////////////////////////////////
335 const char *const search
;
336 const char *const replace
;
353 QString
MUtils::clean_file_name(const QString
&name
)
355 QString str
= name
.simplified();
357 for(size_t i
= 0; CLEAN_FILE_NAME
[i
].search
; i
++)
359 str
.replace(CLEAN_FILE_NAME
[i
].search
, CLEAN_FILE_NAME
[i
].replace
);
362 QRegExp
regExp("\"(.+)\"");
363 regExp
.setMinimal(true);
364 str
.replace(regExp
, "`\\1ยด");
366 return str
.simplified();
369 QString
MUtils::clean_file_path(const QString
&path
)
371 QStringList parts
= path
.simplified().replace("\\", "/").split("/", QString::SkipEmptyParts
);
373 for(int i
= 0; i
< parts
.count(); i
++)
375 parts
[i
] = MUtils::clean_file_name(parts
[i
]);
378 return parts
.join("/");
381 ///////////////////////////////////////////////////////////////////////////////
383 ///////////////////////////////////////////////////////////////////////////////
385 int MUtils::Internal::selfTest(const char *const buildKey
, const bool debug
)
387 static const bool MY_DEBUG_FLAG
= MUTILS_DEBUG
;
388 static const char *const MY_BUILD_KEY
= __DATE__
"@"__TIME__
;
390 if(strncmp(buildKey
, MY_BUILD_KEY
, 14) || (MY_DEBUG_FLAG
!= debug
))
392 MUtils::OS::system_message_err(L
"MUtils", L
"FATAL ERROR: MUtils library version mismatch detected!");
393 MUtils::OS::system_message_wrn(L
"MUtils", L
"Please re-build the complete solution in order to fix this issue!");