OSDN Git Service

be00e9508dd15cfcb90b85a529c2c9f663d95218
[mutilities/MUtilities.git] / src / OSSupport_Win32.cpp
1 ///////////////////////////////////////////////////////////////////////////////
2 // MuldeR's Utilities for Qt
3 // Copyright (C) 2004-2015 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 //Win32 API
23 #define WIN32_LEAN_AND_MEAN 1
24 #include <Windows.h>
25 #include <Psapi.h>
26 #include <Sensapi.h>
27 #include <Shellapi.h>
28 #include <PowrProf.h>
29 #include <Mmsystem.h>
30 #pragma warning(push)
31 #pragma warning(disable:4091) //for MSVC2015
32 #include <ShlObj.h>
33 #pragma warning(pop)
34
35 //CRT
36 #include <io.h>
37
38 //Internal
39 #include <MUtils/Global.h>
40 #include <MUtils/OSSupport.h>
41 #include <MUtils/GUI.h>
42 #include "CriticalSection_Win32.h"
43
44 //Qt
45 #include <QMap>
46 #include <QReadWriteLock>
47 #include <QLibrary>
48 #include <QDir>
49 #include <QWidget>
50 #include <QProcess>
51
52 //Main thread ID
53 static const DWORD g_main_thread_id = GetCurrentThreadId();
54
55 ///////////////////////////////////////////////////////////////////////////////
56 // SYSTEM MESSAGE
57 ///////////////////////////////////////////////////////////////////////////////
58
59 static const UINT g_msgBoxFlags = MB_TOPMOST | MB_TASKMODAL | MB_SETFOREGROUND;
60
61 void MUtils::OS::system_message_nfo(const wchar_t *const title, const wchar_t *const text)
62 {
63         MessageBoxW(NULL, text, title, g_msgBoxFlags | MB_ICONINFORMATION);
64 }
65
66 void MUtils::OS::system_message_wrn(const wchar_t *const title, const wchar_t *const text)
67 {
68         MessageBoxW(NULL, text, title, g_msgBoxFlags | MB_ICONWARNING);
69 }
70
71 void MUtils::OS::system_message_err(const wchar_t *const title, const wchar_t *const text)
72 {
73         MessageBoxW(NULL, text, title, g_msgBoxFlags | MB_ICONERROR);
74 }
75
76 ///////////////////////////////////////////////////////////////////////////////
77 // FETCH CLI ARGUMENTS
78 ///////////////////////////////////////////////////////////////////////////////
79
80 static QReadWriteLock                          g_arguments_lock;
81 static QScopedPointer<MUtils::OS::ArgumentMap> g_arguments_list;
82
83 const QStringList MUtils::OS::crack_command_line(const QString &command_line)
84 {
85         int nArgs = 0;
86         LPWSTR *szArglist = CommandLineToArgvW(command_line.isNull() ? GetCommandLineW() : MUTILS_WCHR(command_line), &nArgs);
87
88         QStringList command_line_tokens;
89         if(NULL != szArglist)
90         {
91                 for(int i = 0; i < nArgs; i++)
92                 {
93                         const QString argStr = MUTILS_QSTR(szArglist[i]).trimmed();
94                         if(!argStr.isEmpty())
95                         {
96                                 command_line_tokens << argStr;
97                         }
98                 }
99                 LocalFree(szArglist);
100         }
101
102         return command_line_tokens;
103 }
104
105 const MUtils::OS::ArgumentMap &MUtils::OS::arguments(void)
106 {
107         QReadLocker readLock(&g_arguments_lock);
108
109         //Already initialized?
110         if(!g_arguments_list.isNull())
111         {
112                 return (*(g_arguments_list.data()));
113         }
114
115         readLock.unlock();
116         QWriteLocker writeLock(&g_arguments_lock);
117
118         //Still not initialized?
119         if(!g_arguments_list.isNull())
120         {
121                 return (*(g_arguments_list.data()));
122         }
123
124         g_arguments_list.reset(new ArgumentMap());
125         const QStringList argList = crack_command_line();
126
127         if(!argList.isEmpty())
128         {
129                 const QString argPrefix = QLatin1String("--");
130                 const QChar   separator = QLatin1Char('=');
131
132                 bool firstToken = true;
133                 for(QStringList::ConstIterator iter = argList.constBegin(); iter != argList.constEnd(); iter++)
134                 {
135                         if(firstToken)
136                         {
137                                 firstToken = false;
138                                 continue; /*skip executable file name*/
139                         }
140                         if(iter->startsWith(argPrefix))
141                         {
142                                 const QString argData = iter->mid(2).trimmed();
143                                 if(argData.length() > 0)
144                                 {
145                                         const int separatorIndex = argData.indexOf(separator);
146                                         if(separatorIndex > 0)
147                                         {
148                                                 const QString argKey = argData.left(separatorIndex).trimmed();
149                                                 const QString argVal = argData.mid(separatorIndex + 1).trimmed();
150                                                 g_arguments_list->insertMulti(argKey.toLower(), argVal);
151                                         }
152                                         else
153                                         {
154                                                 g_arguments_list->insertMulti(argData.toLower(), QString());
155                                         }
156                                 }
157                         }
158                 }
159         }
160         else if(argList.empty())
161         {
162                 qWarning("CommandLineToArgvW() has failed !!!");
163         }
164
165         return (*(g_arguments_list.data()));
166 }
167
168 ///////////////////////////////////////////////////////////////////////////////
169 // COPY FILE
170 ///////////////////////////////////////////////////////////////////////////////
171
172 typedef struct _progress_callback_data_t
173 {
174         MUtils::OS::progress_callback_t callback_function;
175         void *user_data;
176 }
177 progress_callback_data_t;
178
179 static DWORD __stdcall copy_file_progress(LARGE_INTEGER TotalFileSize, LARGE_INTEGER TotalBytesTransferred, LARGE_INTEGER StreamSize, LARGE_INTEGER StreamBytesTransferred, DWORD dwStreamNumber, DWORD dwCallbackReason, HANDLE hSourceFile, HANDLE hDestinationFile, LPVOID lpData)
180 {
181         if(const progress_callback_data_t *data = (progress_callback_data_t*) lpData)
182         {
183                 const double progress = qBound(0.0, double(TotalBytesTransferred.QuadPart) / double(TotalFileSize.QuadPart), 1.0);
184                 return data->callback_function(progress, data->user_data) ? PROGRESS_CONTINUE : PROGRESS_CANCEL;
185         }
186         return PROGRESS_CONTINUE;
187 }
188
189 MUTILS_API bool MUtils::OS::copy_file(const QString &sourcePath, const QString &outputPath, const bool &overwrite, const progress_callback_t callback, void *const userData)
190 {
191         progress_callback_data_t callback_data = { callback, userData };
192         BOOL cancel = FALSE;
193         const BOOL result = CopyFileExW(MUTILS_WCHR(QDir::toNativeSeparators(sourcePath)), MUTILS_WCHR(QDir::toNativeSeparators(outputPath)), ((callback_data.callback_function) ? copy_file_progress : NULL), ((callback_data.callback_function) ? &callback_data : NULL), &cancel, (overwrite ? 0 : COPY_FILE_FAIL_IF_EXISTS));
194
195         if(result == FALSE)
196         {
197                 const DWORD errorCode = GetLastError();
198                 if(errorCode != ERROR_REQUEST_ABORTED)
199                 {
200                         qWarning("CopyFile() failed with error code 0x%08X!", errorCode);
201                 }
202                 else
203                 {
204                         qWarning("CopyFile() operation was abroted by user!");
205                 }
206         }
207
208         return (result != FALSE);
209 }
210
211 ///////////////////////////////////////////////////////////////////////////////
212 // GET FILE VERSION
213 ///////////////////////////////////////////////////////////////////////////////
214
215 static bool get_file_version_helper(const QString fileName, PVOID buffer, const size_t &size, quint16 *const major, quint16 *const minor, quint16 *const patch, quint16 *const build)
216 {
217         if(!GetFileVersionInfo(MUTILS_WCHR(fileName), 0, size, buffer))
218         {
219                 qWarning("GetFileVersionInfo() has failed, file version cannot be determined!");
220                 return false;
221         }
222
223         VS_FIXEDFILEINFO *verInfo;
224         UINT verInfoLen;
225         if(!VerQueryValue(buffer, L"\\", (LPVOID*)(&verInfo), &verInfoLen))
226         {
227                 qWarning("VerQueryValue() has failed, file version cannot be determined!");
228                 return false;
229         }
230
231         if(major) *major = quint16((verInfo->dwFileVersionMS >> 16) & 0x0000FFFF);
232         if(minor) *minor = quint16((verInfo->dwFileVersionMS)       & 0x0000FFFF);
233         if(patch) *patch = quint16((verInfo->dwFileVersionLS >> 16) & 0x0000FFFF);
234         if(build) *build = quint16((verInfo->dwFileVersionLS)       & 0x0000FFFF);
235
236         return true;
237 }
238
239 bool MUtils::OS::get_file_version(const QString fileName, quint16 *const major, quint16 *const minor, quint16 *const patch, quint16 *const build)
240 {
241         if(major) *major = 0U; if(minor) *minor = 0U;
242         if(patch) *patch = 0U; if(build) *build = 0U;
243
244         const DWORD size = GetFileVersionInfoSize(MUTILS_WCHR(fileName), NULL);
245         if(size < 1)
246         {
247                 qWarning("GetFileVersionInfoSize() has failed, file version cannot be determined!");
248                 return false;
249         }
250         
251         PVOID buffer = _malloca(size);
252         if(!buffer)
253         {
254                 qWarning("Memory allocation has failed!");
255                 return false;
256         }
257
258         const bool success = get_file_version_helper(fileName, buffer, size, major, minor, patch, build);
259
260         _freea(buffer);
261         return success;
262 }
263
264 ///////////////////////////////////////////////////////////////////////////////
265 // OS VERSION DETECTION
266 ///////////////////////////////////////////////////////////////////////////////
267
268 static bool g_os_version_initialized = false;
269 static MUtils::OS::Version::os_version_t g_os_version_info = MUtils::OS::Version::UNKNOWN_OPSYS;
270 static QReadWriteLock g_os_version_lock;
271
272 //Maps marketing names to the actual Windows NT versions
273 static const struct
274 {
275         MUtils::OS::Version::os_version_t version;
276         const char friendlyName[64];
277 }
278 g_os_version_lut[] =
279 {
280         { MUtils::OS::Version::WINDOWS_WIN2K, "Windows 2000"                                  },        //2000
281         { MUtils::OS::Version::WINDOWS_WINXP, "Windows XP or Windows XP Media Center Edition" },        //XP
282         { MUtils::OS::Version::WINDOWS_XPX64, "Windows Server 2003 or Windows XP x64"         },        //XP_x64
283         { MUtils::OS::Version::WINDOWS_VISTA, "Windows Vista or Windows Server 2008"          },        //Vista
284         { MUtils::OS::Version::WINDOWS_WIN70, "Windows 7 or Windows Server 2008 R2"           },        //7
285         { MUtils::OS::Version::WINDOWS_WIN80, "Windows 8 or Windows Server 2012"              },        //8
286         { MUtils::OS::Version::WINDOWS_WIN81, "Windows 8.1 or Windows Server 2012 R2"         },        //8.1
287         { MUtils::OS::Version::WINDOWS_WN100, "Windows 10 or Windows Server 2014 (Preview)"   },        //10
288         { MUtils::OS::Version::UNKNOWN_OPSYS, "N/A" }
289 };
290
291 //OS version data dtructures
292 namespace MUtils
293 {
294         namespace OS
295         {
296                 namespace Version
297                 {
298                         //Comparision operators for os_version_t
299                         bool os_version_t::operator== (const os_version_t &rhs) const { return (type == rhs.type) && (versionMajor == rhs.versionMajor) && ((versionMinor == rhs.versionMinor)); }
300                         bool os_version_t::operator!= (const os_version_t &rhs) const { return (type != rhs.type) || (versionMajor != rhs.versionMajor) || ((versionMinor != rhs.versionMinor)); }
301                         bool os_version_t::operator>  (const os_version_t &rhs) const { return (type == rhs.type) && ((versionMajor > rhs.versionMajor) || ((versionMajor == rhs.versionMajor) && (versionMinor >  rhs.versionMinor))); }
302                         bool os_version_t::operator>= (const os_version_t &rhs) const { return (type == rhs.type) && ((versionMajor > rhs.versionMajor) || ((versionMajor == rhs.versionMajor) && (versionMinor >= rhs.versionMinor))); }
303                         bool os_version_t::operator<  (const os_version_t &rhs) const { return (type == rhs.type) && ((versionMajor < rhs.versionMajor) || ((versionMajor == rhs.versionMajor) && (versionMinor <  rhs.versionMinor))); }
304                         bool os_version_t::operator<= (const os_version_t &rhs) const { return (type == rhs.type) && ((versionMajor < rhs.versionMajor) || ((versionMajor == rhs.versionMajor) && (versionMinor <= rhs.versionMinor))); }
305
306                         //Known Windows NT versions
307                         const os_version_t WINDOWS_WIN2K = { OS_WINDOWS,  5, 0 };       // 2000
308                         const os_version_t WINDOWS_WINXP = { OS_WINDOWS,  5, 1 };       // XP
309                         const os_version_t WINDOWS_XPX64 = { OS_WINDOWS,  5, 2 };       // XP_x64
310                         const os_version_t WINDOWS_VISTA = { OS_WINDOWS,  6, 0 };       // Vista
311                         const os_version_t WINDOWS_WIN70 = { OS_WINDOWS,  6, 1 };       // 7
312                         const os_version_t WINDOWS_WIN80 = { OS_WINDOWS,  6, 2 };       // 8
313                         const os_version_t WINDOWS_WIN81 = { OS_WINDOWS,  6, 3 };       // 8.1
314                         const os_version_t WINDOWS_WN100 = { OS_WINDOWS, 10, 0 };       // 10
315
316                         //Unknown OS
317                         const os_version_t UNKNOWN_OPSYS = { OS_UNKNOWN, 0, 0 };        // N/A
318                 }
319         }
320 }
321
322 static bool verify_os_version(const DWORD major, const DWORD minor)
323 {
324         OSVERSIONINFOEXW osvi;
325         DWORDLONG dwlConditionMask = 0;
326
327         //Initialize the OSVERSIONINFOEX structure
328         memset(&osvi, 0, sizeof(OSVERSIONINFOEXW));
329         osvi.dwOSVersionInfoSize = sizeof(OSVERSIONINFOEXW);
330         osvi.dwMajorVersion = major;
331         osvi.dwMinorVersion = minor;
332         osvi.dwPlatformId = VER_PLATFORM_WIN32_NT;
333
334         //Initialize the condition mask
335         VER_SET_CONDITION(dwlConditionMask, VER_MAJORVERSION, VER_GREATER_EQUAL);
336         VER_SET_CONDITION(dwlConditionMask, VER_MINORVERSION, VER_GREATER_EQUAL);
337         VER_SET_CONDITION(dwlConditionMask, VER_PLATFORMID,   VER_EQUAL);
338
339         // Perform the test
340         const BOOL ret = VerifyVersionInfoW(&osvi, VER_MAJORVERSION | VER_MINORVERSION | VER_PLATFORMID, dwlConditionMask);
341
342         //Error checking
343         if(!ret)
344         {
345                 if(GetLastError() != ERROR_OLD_WIN_VERSION)
346                 {
347                         qWarning("VerifyVersionInfo() system call has failed!");
348                 }
349         }
350
351         return (ret != FALSE);
352 }
353
354 static bool get_real_os_version(unsigned int *major, unsigned int *minor, bool *pbOverride)
355 {
356         *major = *minor = 0;
357         *pbOverride = false;
358         
359         //Initialize local variables
360         OSVERSIONINFOEXW osvi;
361         memset(&osvi, 0, sizeof(OSVERSIONINFOEXW));
362         osvi.dwOSVersionInfoSize = sizeof(OSVERSIONINFOEXW);
363
364         //Try GetVersionEx() first
365         if(GetVersionExW((LPOSVERSIONINFOW)&osvi) == FALSE)
366         {
367                 qWarning("GetVersionEx() has failed, cannot detect Windows version!");
368                 return false;
369         }
370
371         //Make sure we are running on NT
372         if(osvi.dwPlatformId == VER_PLATFORM_WIN32_NT)
373         {
374                 *major = osvi.dwMajorVersion;
375                 *minor = osvi.dwMinorVersion;
376         }
377         else
378         {
379                 qWarning("Not running on Windows NT, unsupported operating system!");
380                 return false;
381         }
382
383         //Determine the real *major* version first
384         forever
385         {
386                 const DWORD nextMajor = (*major) + 1;
387                 if(verify_os_version(nextMajor, 0))
388                 {
389                         *pbOverride = true;
390                         *major = nextMajor;
391                         *minor = 0;
392                         continue;
393                 }
394                 break;
395         }
396
397         //Now also determine the real *minor* version
398         forever
399         {
400                 const DWORD nextMinor = (*minor) + 1;
401                 if(verify_os_version((*major), nextMinor))
402                 {
403                         *pbOverride = true;
404                         *minor = nextMinor;
405                         continue;
406                 }
407                 break;
408         }
409
410         //Workaround for the mess that is sometimes referred to as "Windows 10"
411         if(((*major) > 6) || (((*major) == 6) && ((*minor) >= 2)))
412         {
413                 quint16 kernel32_major, kernel32_minor;
414                 if(MUtils::OS::get_file_version(QLatin1String("kernel32"), &kernel32_major, &kernel32_minor))
415                 {
416                         if((kernel32_major > (*major)) || ((kernel32_major == (*major)) && (kernel32_minor > (*minor))))
417                         {
418                                 *major = kernel32_major;
419                                 *minor = kernel32_minor;
420                                 *pbOverride = true;
421                         }
422                 }
423         }
424
425         return true;
426 }
427
428 const MUtils::OS::Version::os_version_t &MUtils::OS::os_version(void)
429 {
430         QReadLocker readLock(&g_os_version_lock);
431
432         //Already initialized?
433         if(g_os_version_initialized)
434         {
435                 return g_os_version_info;
436         }
437         
438         readLock.unlock();
439         QWriteLocker writeLock(&g_os_version_lock);
440
441         //Initialized now?
442         if(g_os_version_initialized)
443         {
444                 return g_os_version_info;
445         }
446
447         //Detect OS version
448         unsigned int major, minor; bool overrideFlg;
449         if(get_real_os_version(&major, &minor, &overrideFlg))
450         {
451                 g_os_version_info.type = Version::OS_WINDOWS;
452                 g_os_version_info.versionMajor = major;
453                 g_os_version_info.versionMinor = minor;
454                 g_os_version_info.overrideFlag = overrideFlg;
455         }
456         else
457         {
458                 qWarning("Failed to determin the operating system version!");
459         }
460
461         //Completed
462         g_os_version_initialized = true;
463         return g_os_version_info;
464 }
465
466 const char *MUtils::OS::os_friendly_name(const MUtils::OS::Version::os_version_t &os_version)
467 {
468         for(size_t i = 0; g_os_version_lut[i].version != MUtils::OS::Version::UNKNOWN_OPSYS; i++)
469         {
470                 if(os_version == g_os_version_lut[i].version)
471                 {
472                         return g_os_version_lut[i].friendlyName;
473                 }
474         }
475
476         return NULL;
477 }
478
479 ///////////////////////////////////////////////////////////////////////////////
480 // WINE DETECTION
481 ///////////////////////////////////////////////////////////////////////////////
482
483 static bool g_wine_deteced = false;
484 static bool g_wine_initialized = false;
485 static QReadWriteLock g_wine_lock;
486
487 static const bool detect_wine(void)
488 {
489         bool is_wine = false;
490         
491         QLibrary ntdll("ntdll.dll");
492         if(ntdll.load())
493         {
494                 if(ntdll.resolve("wine_nt_to_unix_file_name") != NULL) is_wine = true;
495                 if(ntdll.resolve("wine_get_version")          != NULL) is_wine = true;
496                 ntdll.unload();
497         }
498
499         return is_wine;
500 }
501
502 const bool &MUtils::OS::running_on_wine(void)
503 {
504         QReadLocker readLock(&g_wine_lock);
505
506         //Already initialized?
507         if(g_wine_initialized)
508         {
509                 return g_wine_deteced;
510         }
511
512         readLock.unlock();
513         QWriteLocker writeLock(&g_wine_lock);
514
515         //Initialized now?
516         if(g_wine_initialized)
517         {
518                 return g_wine_deteced;
519         }
520
521         //Try to detect Wine
522         g_wine_deteced = detect_wine();
523         g_wine_initialized = true;
524
525         return g_wine_deteced;
526 }
527
528 ///////////////////////////////////////////////////////////////////////////////
529 // KNWON FOLDERS
530 ///////////////////////////////////////////////////////////////////////////////
531
532 typedef QMap<size_t, QString> KFMap;
533 typedef HRESULT (WINAPI *SHGetKnownFolderPath_t)(const GUID &rfid, DWORD dwFlags, HANDLE hToken, PWSTR *ppszPath);
534 typedef HRESULT (WINAPI *SHGetFolderPath_t)(HWND hwndOwner, int nFolder, HANDLE hToken, DWORD dwFlags, LPWSTR pszPath);
535
536 static QScopedPointer<KFMap>  g_known_folders_map;
537 static SHGetKnownFolderPath_t g_known_folders_fpGetKnownFolderPath;
538 static SHGetFolderPath_t      g_known_folders_fpGetFolderPath;
539 static QReadWriteLock         g_known_folders_lock;
540
541 const QString &MUtils::OS::known_folder(known_folder_t folder_id)
542 {
543         typedef enum { KF_FLAG_CREATE = 0x00008000 } kf_flags_t;
544         
545         struct
546         {
547                 const int csidl;
548                 const GUID guid;
549         }
550         static s_folders[] =
551         {
552                 { 0x001c, {0xF1B32785,0x6FBA,0x4FCF,{0x9D,0x55,0x7B,0x8E,0x7F,0x15,0x70,0x91}} },  //CSIDL_LOCAL_APPDATA
553                 { 0x0026, {0x905e63b6,0xc1bf,0x494e,{0xb2,0x9c,0x65,0xb7,0x32,0xd3,0xd2,0x1a}} },  //CSIDL_PROGRAM_FILES
554                 { 0x0024, {0xF38BF404,0x1D43,0x42F2,{0x93,0x05,0x67,0xDE,0x0B,0x28,0xFC,0x23}} },  //CSIDL_WINDOWS_FOLDER
555                 { 0x0025, {0x1AC14E77,0x02E7,0x4E5D,{0xB7,0x44,0x2E,0xB1,0xAE,0x51,0x98,0xB7}} },  //CSIDL_SYSTEM_FOLDER
556         };
557
558         size_t folderId = size_t(-1);
559
560         switch(folder_id)
561         {
562                 case FOLDER_LOCALAPPDATA: folderId = 0; break;
563                 case FOLDER_PROGRAMFILES: folderId = 1; break;
564                 case FOLDER_SYSTROOT_DIR: folderId = 2; break;
565                 case FOLDER_SYSTEMFOLDER: folderId = 3; break;
566         }
567
568         if(folderId == size_t(-1))
569         {
570                 qWarning("Invalid 'known' folder was requested!");
571                 return *reinterpret_cast<QString*>(NULL);
572         }
573
574         QReadLocker readLock(&g_known_folders_lock);
575
576         //Already in cache?
577         if(!g_known_folders_map.isNull())
578         {
579                 if(g_known_folders_map->contains(folderId))
580                 {
581                         return g_known_folders_map->operator[](folderId);
582                 }
583         }
584
585         //Obtain write lock to initialize
586         readLock.unlock();
587         QWriteLocker writeLock(&g_known_folders_lock);
588
589         //Still not in cache?
590         if(!g_known_folders_map.isNull())
591         {
592                 if(g_known_folders_map->contains(folderId))
593                 {
594                         return g_known_folders_map->operator[](folderId);
595                 }
596         }
597
598         //Initialize on first call
599         if(g_known_folders_map.isNull())
600         {
601                 QLibrary shell32("shell32.dll");
602                 if(shell32.load())
603                 {
604                         g_known_folders_fpGetFolderPath =      (SHGetFolderPath_t)      shell32.resolve("SHGetFolderPathW");
605                         g_known_folders_fpGetKnownFolderPath = (SHGetKnownFolderPath_t) shell32.resolve("SHGetKnownFolderPath");
606                 }
607                 g_known_folders_map.reset(new QMap<size_t, QString>());
608         }
609
610         QString folderPath;
611
612         //Now try to get the folder path!
613         if(g_known_folders_fpGetKnownFolderPath)
614         {
615                 WCHAR *path = NULL;
616                 if(g_known_folders_fpGetKnownFolderPath(s_folders[folderId].guid, KF_FLAG_CREATE, NULL, &path) == S_OK)
617                 {
618                         //MessageBoxW(0, path, L"SHGetKnownFolderPath", MB_TOPMOST);
619                         QDir folderTemp = QDir(QDir::fromNativeSeparators(MUTILS_QSTR(path)));
620                         if(folderTemp.exists())
621                         {
622                                 folderPath = folderTemp.canonicalPath();
623                         }
624                         CoTaskMemFree(path);
625                 }
626         }
627         else if(g_known_folders_fpGetFolderPath)
628         {
629                 QScopedArrayPointer<WCHAR> path(new WCHAR[4096]);
630                 if(g_known_folders_fpGetFolderPath(NULL, s_folders[folderId].csidl | CSIDL_FLAG_CREATE, NULL, NULL, path.data()) == S_OK)
631                 {
632                         //MessageBoxW(0, path, L"SHGetFolderPathW", MB_TOPMOST);
633                         QDir folderTemp = QDir(QDir::fromNativeSeparators(MUTILS_QSTR(path.data())));
634                         if(folderTemp.exists())
635                         {
636                                 folderPath = folderTemp.canonicalPath();
637                         }
638                 }
639         }
640
641         //Update cache
642         g_known_folders_map->insert(folderId, folderPath);
643         return g_known_folders_map->operator[](folderId);
644 }
645
646 ///////////////////////////////////////////////////////////////////////////////
647 // CURRENT DATA & TIME
648 ///////////////////////////////////////////////////////////////////////////////
649
650 QDate MUtils::OS::current_date(void)
651 {
652         const DWORD MAX_PROC = 1024;
653         QScopedArrayPointer<DWORD> processes(new DWORD[MAX_PROC]);
654         DWORD bytesReturned = 0;
655         
656         if(!EnumProcesses(processes.data(), sizeof(DWORD) * MAX_PROC, &bytesReturned))
657         {
658                 return QDate::currentDate();
659         }
660
661         const DWORD procCount = bytesReturned / sizeof(DWORD);
662         ULARGE_INTEGER lastStartTime;
663         memset(&lastStartTime, 0, sizeof(ULARGE_INTEGER));
664
665         for(DWORD i = 0; i < procCount; i++)
666         {
667                 if(HANDLE hProc = OpenProcess(PROCESS_QUERY_INFORMATION, FALSE, processes[i]))
668                 {
669                         FILETIME processTime[4];
670                         if(GetProcessTimes(hProc, &processTime[0], &processTime[1], &processTime[2], &processTime[3]))
671                         {
672                                 ULARGE_INTEGER timeCreation;
673                                 timeCreation.LowPart  = processTime[0].dwLowDateTime;
674                                 timeCreation.HighPart = processTime[0].dwHighDateTime;
675                                 if(timeCreation.QuadPart > lastStartTime.QuadPart)
676                                 {
677                                         lastStartTime.QuadPart = timeCreation.QuadPart;
678                                 }
679                         }
680                         CloseHandle(hProc);
681                 }
682         }
683         
684         FILETIME lastStartTime_fileTime;
685         lastStartTime_fileTime.dwHighDateTime = lastStartTime.HighPart;
686         lastStartTime_fileTime.dwLowDateTime  = lastStartTime.LowPart;
687
688         FILETIME lastStartTime_localTime;
689         if(!FileTimeToLocalFileTime(&lastStartTime_fileTime, &lastStartTime_localTime))
690         {
691                 memcpy(&lastStartTime_localTime, &lastStartTime_fileTime, sizeof(FILETIME));
692         }
693         
694         SYSTEMTIME lastStartTime_system;
695         if(!FileTimeToSystemTime(&lastStartTime_localTime, &lastStartTime_system))
696         {
697                 memset(&lastStartTime_system, 0, sizeof(SYSTEMTIME));
698                 lastStartTime_system.wYear = 1970; lastStartTime_system.wMonth = lastStartTime_system.wDay = 1;
699         }
700
701         const QDate currentDate = QDate::currentDate();
702         const QDate processDate = QDate(lastStartTime_system.wYear, lastStartTime_system.wMonth, lastStartTime_system.wDay);
703         return (currentDate >= processDate) ? currentDate : processDate;
704 }
705
706 quint64 MUtils::OS::current_file_time(void)
707 {
708         FILETIME fileTime;
709         GetSystemTimeAsFileTime(&fileTime);
710
711         ULARGE_INTEGER temp;
712         temp.HighPart = fileTime.dwHighDateTime;
713         temp.LowPart = fileTime.dwLowDateTime;
714
715         return temp.QuadPart;
716 }
717
718 ///////////////////////////////////////////////////////////////////////////////
719 // PROCESS ELEVATION
720 ///////////////////////////////////////////////////////////////////////////////
721
722 static bool user_is_admin_helper(void)
723 {
724         HANDLE hToken = NULL;
725         if(!OpenProcessToken(GetCurrentProcess(), TOKEN_QUERY, &hToken))
726         {
727                 return false;
728         }
729
730         DWORD dwSize = 0;
731         if(!GetTokenInformation(hToken, TokenGroups, NULL, 0, &dwSize))
732         {
733                 if(GetLastError() != ERROR_INSUFFICIENT_BUFFER)
734                 {
735                         CloseHandle(hToken);
736                         return false;
737                 }
738         }
739
740         PTOKEN_GROUPS lpGroups = (PTOKEN_GROUPS) malloc(dwSize);
741         if(!lpGroups)
742         {
743                 CloseHandle(hToken);
744                 return false;
745         }
746
747         if(!GetTokenInformation(hToken, TokenGroups, lpGroups, dwSize, &dwSize))
748         {
749                 free(lpGroups);
750                 CloseHandle(hToken);
751                 return false;
752         }
753
754         PSID lpSid = NULL; SID_IDENTIFIER_AUTHORITY Authority = {SECURITY_NT_AUTHORITY};
755         if(!AllocateAndInitializeSid(&Authority, 2, SECURITY_BUILTIN_DOMAIN_RID, DOMAIN_ALIAS_RID_ADMINS, 0, 0, 0, 0, 0, 0, &lpSid))
756         {
757                 free(lpGroups);
758                 CloseHandle(hToken);
759                 return false;
760         }
761
762         bool bResult = false;
763         for(DWORD i = 0; i < lpGroups->GroupCount; i++)
764         {
765                 if(EqualSid(lpSid, lpGroups->Groups[i].Sid))
766                 {
767                         bResult = true;
768                         break;
769                 }
770         }
771
772         FreeSid(lpSid);
773         free(lpGroups);
774         CloseHandle(hToken);
775         return bResult;
776 }
777
778 bool MUtils::OS::is_elevated(bool *bIsUacEnabled)
779 {
780         if(bIsUacEnabled)
781         {
782                 *bIsUacEnabled = false;
783         }
784
785         bool bIsProcessElevated = false;
786         HANDLE hToken = NULL;
787         
788         if(OpenProcessToken(GetCurrentProcess(), TOKEN_QUERY, &hToken))
789         {
790                 TOKEN_ELEVATION_TYPE tokenElevationType;
791                 DWORD returnLength;
792                 if(GetTokenInformation(hToken, TokenElevationType, &tokenElevationType, sizeof(TOKEN_ELEVATION_TYPE), &returnLength))
793                 {
794                         if(returnLength == sizeof(TOKEN_ELEVATION_TYPE))
795                         {
796                                 switch(tokenElevationType)
797                                 {
798                                 case TokenElevationTypeDefault:
799                                         qDebug("Process token elevation type: Default -> UAC is disabled.\n");
800                                         break;
801                                 case TokenElevationTypeFull:
802                                         qWarning("Process token elevation type: Full -> potential security risk!\n");
803                                         bIsProcessElevated = true;
804                                         if(bIsUacEnabled) *bIsUacEnabled = true;
805                                         break;
806                                 case TokenElevationTypeLimited:
807                                         qDebug("Process token elevation type: Limited -> not elevated.\n");
808                                         if(bIsUacEnabled) *bIsUacEnabled = true;
809                                         break;
810                                 default:
811                                         qWarning("Unknown tokenElevationType value: %d", tokenElevationType);
812                                         break;
813                                 }
814                         }
815                         else
816                         {
817                                 qWarning("GetTokenInformation() return an unexpected size!");
818                         }
819                 }
820                 CloseHandle(hToken);
821         }
822         else
823         {
824                 qWarning("Failed to open process token!");
825         }
826
827         return bIsProcessElevated;
828 }
829
830 bool MUtils::OS::user_is_admin(void)
831 {
832         bool isAdmin = false;
833
834         //Check for process elevation and UAC support first!
835         if(MUtils::OS::is_elevated(&isAdmin))
836         {
837                 qWarning("Process is elevated -> user is admin!");
838                 return true;
839         }
840         
841         //If not elevated and UAC is not available -> user must be in admin group!
842         if(!isAdmin)
843         {
844                 qDebug("UAC is disabled/unavailable -> checking for Administrators group");
845                 isAdmin = user_is_admin_helper();
846         }
847
848         return isAdmin;
849 }
850
851 ///////////////////////////////////////////////////////////////////////////////
852 // NETWORK STATE
853 ///////////////////////////////////////////////////////////////////////////////
854
855 int MUtils::OS::network_status(void)
856 {
857         DWORD dwFlags;
858         const BOOL ret = IsNetworkAlive(&dwFlags);
859         if(GetLastError() == 0)
860         {
861                 return (ret != FALSE) ? NETWORK_TYPE_YES : NETWORK_TYPE_NON;
862         }
863         return NETWORK_TYPE_ERR;
864 }
865
866 ///////////////////////////////////////////////////////////////////////////////
867 // MESSAGE HANDLER
868 ///////////////////////////////////////////////////////////////////////////////
869
870 bool MUtils::OS::handle_os_message(const void *const message, long *result)
871 {
872         const MSG *const msg = reinterpret_cast<const MSG*>(message);
873
874         switch(msg->message)
875         {
876         case WM_QUERYENDSESSION:
877                 qWarning("WM_QUERYENDSESSION message received!");
878                 *result = MUtils::GUI::broadcast(MUtils::GUI::USER_EVENT_QUERYENDSESSION, false) ? TRUE : FALSE;
879                 return true;
880         case WM_ENDSESSION:
881                 qWarning("WM_ENDSESSION message received!");
882                 if(msg->wParam == TRUE)
883                 {
884                         MUtils::GUI::broadcast(MUtils::GUI::USER_EVENT_ENDSESSION, false);
885                         MUtils::GUI::force_quit();
886                         exit(1);
887                 }
888                 *result = 0;
889                 return true;
890         default:
891                 /*ignore this message and let Qt handle it*/
892                 return false;
893         }
894 }
895
896 ///////////////////////////////////////////////////////////////////////////////
897 // SLEEP
898 ///////////////////////////////////////////////////////////////////////////////
899
900 void MUtils::OS::sleep_ms(const size_t &duration)
901 {
902         Sleep((DWORD) duration);
903 }
904
905 ///////////////////////////////////////////////////////////////////////////////
906 // EXECUTABLE CHECK
907 ///////////////////////////////////////////////////////////////////////////////
908
909 bool MUtils::OS::is_executable_file(const QString &path)
910 {
911         bool bIsExecutable = false;
912         DWORD binaryType;
913         if(GetBinaryType(MUTILS_WCHR(QDir::toNativeSeparators(path)), &binaryType))
914         {
915                 bIsExecutable = (binaryType == SCS_32BIT_BINARY || binaryType == SCS_64BIT_BINARY);
916         }
917         return bIsExecutable;
918 }
919
920 ///////////////////////////////////////////////////////////////////////////////
921 // HIBERNATION / SHUTDOWN
922 ///////////////////////////////////////////////////////////////////////////////
923
924 bool MUtils::OS::is_hibernation_supported(void)
925 {
926         bool hibernationSupported = false;
927
928         SYSTEM_POWER_CAPABILITIES pwrCaps;
929         SecureZeroMemory(&pwrCaps, sizeof(SYSTEM_POWER_CAPABILITIES));
930         
931         if(GetPwrCapabilities(&pwrCaps))
932         {
933                 hibernationSupported = pwrCaps.SystemS4 && pwrCaps.HiberFilePresent;
934         }
935
936         return hibernationSupported;
937 }
938
939 bool MUtils::OS::shutdown_computer(const QString &message, const unsigned long timeout, const bool forceShutdown, const bool hibernate)
940 {
941         HANDLE hToken = NULL;
942
943         if(OpenProcessToken(GetCurrentProcess(), TOKEN_ADJUST_PRIVILEGES | TOKEN_QUERY, &hToken))
944         {
945                 TOKEN_PRIVILEGES privileges;
946                 memset(&privileges, 0, sizeof(TOKEN_PRIVILEGES));
947                 privileges.PrivilegeCount = 1;
948                 privileges.Privileges[0].Attributes = SE_PRIVILEGE_ENABLED;
949                 
950                 if(LookupPrivilegeValue(NULL, SE_SHUTDOWN_NAME, &privileges.Privileges[0].Luid))
951                 {
952                         if(AdjustTokenPrivileges(hToken, FALSE, &privileges, NULL, NULL, NULL))
953                         {
954                                 if(hibernate)
955                                 {
956                                         if(SetSuspendState(TRUE, TRUE, TRUE))
957                                         {
958                                                 return true;
959                                         }
960                                 }
961                                 const DWORD reason = SHTDN_REASON_MAJOR_APPLICATION | SHTDN_REASON_FLAG_PLANNED;
962                                 return InitiateSystemShutdownEx(NULL, const_cast<wchar_t*>(MUTILS_WCHR(message)), timeout, forceShutdown ? TRUE : FALSE, FALSE, reason);
963                         }
964                 }
965         }
966         
967         return false;
968 }
969
970 ///////////////////////////////////////////////////////////////////////////////
971 // FREE DISKSPACE
972 ///////////////////////////////////////////////////////////////////////////////
973
974 bool MUtils::OS::free_diskspace(const QString &path, quint64 &freeSpace)
975 {
976         ULARGE_INTEGER freeBytesAvailable, totalNumberOfBytes, totalNumberOfFreeBytes;
977         if(GetDiskFreeSpaceExW(reinterpret_cast<const wchar_t*>(QDir::toNativeSeparators(path).utf16()), &freeBytesAvailable, &totalNumberOfBytes, &totalNumberOfFreeBytes))
978         {
979                 freeSpace = freeBytesAvailable.QuadPart;
980                 return true;;
981         }
982
983         freeSpace = -1;
984         return false;
985 }
986
987 ///////////////////////////////////////////////////////////////////////////////
988 // SHELL OPEN
989 ///////////////////////////////////////////////////////////////////////////////
990
991 bool MUtils::OS::shell_open(const QWidget *parent, const QString &url, const QString &parameters, const QString &directory, const bool explore)
992 {
993         return ((int) ShellExecuteW((parent ? parent->winId() : NULL), (explore ? L"explore" : L"open"), MUTILS_WCHR(url), ((!parameters.isEmpty()) ? MUTILS_WCHR(parameters) : NULL), ((!directory.isEmpty()) ? MUTILS_WCHR(directory) : NULL), SW_SHOW)) > 32;
994 }
995
996 bool MUtils::OS::shell_open(const QWidget *parent, const QString &url, const bool explore)
997 {
998         return shell_open(parent, url, QString(), QString(), explore);
999 }
1000
1001 ///////////////////////////////////////////////////////////////////////////////
1002 // OPEN MEDIA FILE
1003 ///////////////////////////////////////////////////////////////////////////////
1004
1005 bool MUtils::OS::open_media_file(const QString &mediaFilePath)
1006 {
1007         const static wchar_t *registryPrefix[2] = { L"SOFTWARE\\", L"SOFTWARE\\Wow6432Node\\" };
1008         const static wchar_t *registryKeys[3] = 
1009         {
1010                 L"Microsoft\\Windows\\CurrentVersion\\Uninstall\\{97D341C8-B0D1-4E4A-A49A-C30B52F168E9}",
1011                 L"Microsoft\\Windows\\CurrentVersion\\Uninstall\\{DB9E4EAB-2717-499F-8D56-4CC8A644AB60}",
1012                 L"foobar2000"
1013         };
1014         const static wchar_t *appNames[4] = { L"smplayer_portable.exe", L"smplayer.exe", L"MPUI.exe", L"foobar2000.exe" };
1015         const static wchar_t *valueNames[2] = { L"InstallLocation", L"InstallDir" };
1016
1017         for(size_t i = 0; i < 3; i++)
1018         {
1019                 for(size_t j = 0; j < 2; j++)
1020                 {
1021                         QString mplayerPath;
1022                         HKEY registryKeyHandle = NULL;
1023
1024                         const QString currentKey = MUTILS_QSTR(registryPrefix[j]).append(MUTILS_QSTR(registryKeys[i]));
1025                         if(RegOpenKeyExW(HKEY_LOCAL_MACHINE, MUTILS_WCHR(currentKey), 0, KEY_READ, &registryKeyHandle) == ERROR_SUCCESS)
1026                         {
1027                                 for(size_t k = 0; k < 2; k++)
1028                                 {
1029                                         wchar_t Buffer[4096];
1030                                         DWORD BuffSize = sizeof(wchar_t*) * 4096;
1031                                         DWORD DataType = REG_NONE;
1032                                         if(RegQueryValueExW(registryKeyHandle, valueNames[k], 0, &DataType, reinterpret_cast<BYTE*>(Buffer), &BuffSize) == ERROR_SUCCESS)
1033                                         {
1034                                                 if((DataType == REG_SZ) || (DataType == REG_EXPAND_SZ) || (DataType == REG_LINK))
1035                                                 {
1036                                                         mplayerPath = MUTILS_QSTR(Buffer);
1037                                                         break;
1038                                                 }
1039                                         }
1040                                 }
1041                                 RegCloseKey(registryKeyHandle);
1042                         }
1043
1044                         if(!mplayerPath.isEmpty())
1045                         {
1046                                 QDir mplayerDir(mplayerPath);
1047                                 if(mplayerDir.exists())
1048                                 {
1049                                         for(size_t k = 0; k < 4; k++)
1050                                         {
1051                                                 if(mplayerDir.exists(MUTILS_QSTR(appNames[k])))
1052                                                 {
1053                                                         qDebug("Player found at:\n%s\n", MUTILS_UTF8(mplayerDir.absoluteFilePath(MUTILS_QSTR(appNames[k]))));
1054                                                         QProcess::startDetached(mplayerDir.absoluteFilePath(MUTILS_QSTR(appNames[k])), QStringList() << QDir::toNativeSeparators(mediaFilePath));
1055                                                         return true;
1056                                                 }
1057                                         }
1058                                 }
1059                         }
1060                 }
1061         }
1062         return false;
1063 }
1064
1065 ///////////////////////////////////////////////////////////////////////////////
1066 // DEBUGGER CHECK
1067 ///////////////////////////////////////////////////////////////////////////////
1068
1069 static bool change_process_priority_helper(const HANDLE hProcess, const int priority)
1070 {
1071         bool ok = false;
1072
1073         switch(qBound(-2, priority, 2))
1074         {
1075         case 2:
1076                 ok = (SetPriorityClass(hProcess, HIGH_PRIORITY_CLASS) == TRUE);
1077                 break;
1078         case 1:
1079                 if(!(ok = (SetPriorityClass(hProcess, ABOVE_NORMAL_PRIORITY_CLASS) == TRUE)))
1080                 {
1081                         ok = (SetPriorityClass(hProcess, HIGH_PRIORITY_CLASS) == TRUE);
1082                 }
1083                 break;
1084         case 0:
1085                 ok = (SetPriorityClass(hProcess, NORMAL_PRIORITY_CLASS) == TRUE);
1086                 break;
1087         case -1:
1088                 if(!(ok = (SetPriorityClass(hProcess, BELOW_NORMAL_PRIORITY_CLASS) == TRUE)))
1089                 {
1090                         ok = (SetPriorityClass(hProcess, IDLE_PRIORITY_CLASS) == TRUE);
1091                 }
1092                 break;
1093         case -2:
1094                 ok = (SetPriorityClass(hProcess, IDLE_PRIORITY_CLASS) == TRUE);
1095                 break;
1096         }
1097
1098         return ok;
1099 }
1100
1101 bool MUtils::OS::change_process_priority(const int priority)
1102 {
1103         return change_process_priority_helper(GetCurrentProcess(), priority);
1104 }
1105
1106 bool MUtils::OS::change_process_priority(const QProcess *proc, const int priority)
1107 {
1108         if(Q_PID qPid = proc->pid())
1109         {
1110                 return change_process_priority_helper(qPid->hProcess, priority);
1111         }
1112         else
1113         {
1114                 return false;
1115         }
1116 }
1117
1118 ///////////////////////////////////////////////////////////////////////////////
1119 // PROCESS ID
1120 ///////////////////////////////////////////////////////////////////////////////
1121
1122 quint32 MUtils::OS::process_id(const QProcess *const proc)
1123 {
1124         PROCESS_INFORMATION *procInf = proc->pid();
1125         return (procInf) ? procInf->dwProcessId : NULL;
1126 }
1127
1128 ///////////////////////////////////////////////////////////////////////////////
1129 // PROCESS SUSPEND/RESUME
1130 ///////////////////////////////////////////////////////////////////////////////
1131
1132 bool MUtils::OS::suspend_process(const QProcess *proc, const bool suspend)
1133 {
1134         if(Q_PID pid = proc->pid())
1135         {
1136                 if(suspend)
1137                 {
1138                         return (SuspendThread(pid->hThread) != ((DWORD) -1));
1139                 }
1140                 else
1141                 {
1142                         return (ResumeThread(pid->hThread)  != ((DWORD) -1));
1143                 }
1144         }
1145         else
1146         {
1147                 return false;
1148         }
1149 }
1150
1151 ///////////////////////////////////////////////////////////////////////////////
1152 // SYSTEM TIMER
1153 ///////////////////////////////////////////////////////////////////////////////
1154
1155 bool MUtils::OS::setup_timer_resolution(const quint32 &interval)
1156 {
1157         return timeBeginPeriod(interval) == TIMERR_NOERROR;
1158 }
1159
1160 bool MUtils::OS::reset_timer_resolution(const quint32 &interval)
1161 {
1162         return timeEndPeriod(interval) == TIMERR_NOERROR;
1163 }
1164
1165 ///////////////////////////////////////////////////////////////////////////////
1166 // SET FILE TIME
1167 ///////////////////////////////////////////////////////////////////////////////
1168
1169 static QScopedPointer<QDateTime> s_epoch;
1170 static QReadWriteLock            s_epochLock;
1171
1172 static const QDateTime *get_epoch(void)
1173 {
1174         QReadLocker rdLock(&s_epochLock);
1175
1176         if (s_epoch.isNull())
1177         {
1178                 rdLock.unlock();
1179                 QWriteLocker wrLock(&s_epochLock);
1180                 if (s_epoch.isNull())
1181                 {
1182                         s_epoch.reset(new QDateTime(QDate(1601, 1, 1), QTime(0, 0, 0, 0), Qt::UTC));
1183                 }
1184                 wrLock.unlock();
1185                 rdLock.relock();
1186         }
1187
1188         return s_epoch.data();
1189 }
1190
1191 static FILETIME *qt_time_to_file_time(FILETIME *const fileTime, const QDateTime &dateTime)
1192 {
1193         memset(fileTime, 0, sizeof(FILETIME));
1194
1195         if (const QDateTime *const epoch = get_epoch())
1196         {
1197                 const qint64 msecs = epoch->msecsTo(dateTime);
1198                 if (msecs > 0)
1199                 {
1200                         const quint64 ticks = 10000U * quint64(msecs);
1201                         fileTime->dwHighDateTime = ((ticks >> 32) & 0xFFFFFFFF);
1202                         fileTime->dwLowDateTime = (ticks & 0xFFFFFFFF);
1203                         return fileTime;
1204                 }
1205         }
1206
1207         return NULL;
1208 }
1209
1210 static bool set_file_time(const HANDLE hFile, const QDateTime &created, const QDateTime &lastMod, const QDateTime &lastAcc)
1211 {
1212         FILETIME ftCreated, ftLastMod, ftLastAcc;
1213
1214         FILETIME *const pCreated = created.isValid() ? qt_time_to_file_time(&ftCreated, created) : NULL;
1215         FILETIME *const pLastMod = lastMod.isValid() ? qt_time_to_file_time(&ftLastMod, lastMod) : NULL;
1216         FILETIME *const pLastAcc = lastAcc.isValid() ? qt_time_to_file_time(&ftLastAcc, lastAcc) : NULL;
1217
1218         if (pCreated || pLastMod || pLastAcc)
1219         {
1220                 return (SetFileTime(hFile, pCreated, pLastAcc, pLastMod) != FALSE);
1221         }
1222
1223         return false;
1224 }
1225
1226 bool MUtils::OS::set_file_time(const QFile &file, const QDateTime &created, const QDateTime &lastMod, const QDateTime &lastAcc)
1227 {
1228         const int fd = file.handle();
1229         if (fd >= 0)
1230         {
1231                 return set_file_time((HANDLE)_get_osfhandle(fd), created, lastMod, lastAcc);
1232         }
1233         return false;
1234 }
1235
1236 bool MUtils::OS::set_file_time(const QString &path, const QDateTime &created, const QDateTime &lastMod, const QDateTime &lastAcc)
1237 {
1238         const HANDLE hFile = CreateFileW(MUTILS_WCHR(path), FILE_WRITE_ATTRIBUTES, FILE_SHARE_READ, NULL, OPEN_EXISTING, 0, 0);
1239         bool okay = false;
1240         if ((hFile != NULL) && (hFile != INVALID_HANDLE_VALUE))
1241         {
1242                 okay = set_file_time(hFile, created, lastMod, lastAcc);
1243                 CloseHandle(hFile);
1244         }
1245         return okay;
1246 }
1247
1248 ///////////////////////////////////////////////////////////////////////////////
1249 // CHECK KEY STATE
1250 ///////////////////////////////////////////////////////////////////////////////
1251
1252 bool MUtils::OS::check_key_state_esc(void)
1253 {
1254         return (GetAsyncKeyState(VK_ESCAPE) & 0x0001) != 0;
1255 }
1256
1257 ///////////////////////////////////////////////////////////////////////////////
1258 // SHELL CHANGE NOTIFICATION
1259 ///////////////////////////////////////////////////////////////////////////////
1260
1261 void MUtils::OS::shell_change_notification(void)
1262 {
1263         SHChangeNotify(SHCNE_ASSOCCHANGED, SHCNF_IDLIST, NULL, NULL);
1264 }
1265
1266 ///////////////////////////////////////////////////////////////////////////////
1267 // WOW64 REDIRECTION
1268 ///////////////////////////////////////////////////////////////////////////////
1269
1270 typedef BOOL (_stdcall *Wow64DisableWow64FsRedirectionFun)(void *OldValue);
1271 typedef BOOL (_stdcall *Wow64RevertWow64FsRedirectionFun )(void *OldValue);
1272
1273 static QReadWriteLock                    g_wow64redir_lock;
1274 static QScopedPointer<QLibrary>          g_wow64redir_kernel32;
1275 static Wow64DisableWow64FsRedirectionFun g_wow64redir_disable = NULL;
1276 static Wow64RevertWow64FsRedirectionFun  g_wow64redir_revert  = NULL;
1277
1278 static bool wow64fsredir_init()
1279 {
1280         QWriteLocker writeLock(&g_wow64redir_lock);
1281         if(g_wow64redir_disable && g_wow64redir_revert)
1282         {
1283                 return true; /*already initialized*/
1284         }
1285
1286         if(g_wow64redir_kernel32.isNull())
1287         {
1288                 g_wow64redir_kernel32.reset(new QLibrary("kernel32.dll"));
1289         }
1290
1291         if(!g_wow64redir_kernel32->isLoaded())
1292         {
1293                 if(!g_wow64redir_kernel32->load())
1294                 {
1295                         return false; /*faild to load kernel32.dll*/
1296                 }
1297         }
1298
1299         g_wow64redir_disable = (Wow64DisableWow64FsRedirectionFun) g_wow64redir_kernel32->resolve("Wow64DisableWow64FsRedirection");
1300         g_wow64redir_revert  = (Wow64RevertWow64FsRedirectionFun)  g_wow64redir_kernel32->resolve("Wow64RevertWow64FsRedirection");
1301
1302         return (g_wow64redir_disable && g_wow64redir_revert);
1303 }
1304
1305 #define WOW64FSREDIR_INIT(RDLOCK) do \
1306 { \
1307         while(!(g_wow64redir_disable && g_wow64redir_revert)) \
1308         { \
1309                 (RDLOCK).unlock(); \
1310                 if(!wow64fsredir_init()) return false; \
1311                 (RDLOCK).relock(); \
1312         } \
1313 } \
1314 while(0)
1315
1316 bool MUtils::OS::wow64fsredir_disable(void *oldValue)
1317 {
1318         QReadLocker readLock(&g_wow64redir_lock);
1319         WOW64FSREDIR_INIT(readLock);
1320         if(g_wow64redir_disable(oldValue))
1321         {
1322                 return true;
1323         }
1324         return false;
1325 }
1326
1327 bool MUtils::OS::wow64fsredir_revert(void *oldValue)
1328 {
1329         QReadLocker readLock(&g_wow64redir_lock);
1330         WOW64FSREDIR_INIT(readLock);
1331         if(g_wow64redir_revert(oldValue))
1332         {
1333                 return true;
1334         }
1335         return false;
1336 }
1337
1338 ///////////////////////////////////////////////////////////////////////////////
1339 // DEBUGGER CHECK
1340 ///////////////////////////////////////////////////////////////////////////////
1341
1342 #if (!(MUTILS_DEBUG))
1343 static __forceinline bool is_debugger_present(void)
1344 {
1345         __try
1346         {
1347                 CloseHandle((HANDLE)((DWORD_PTR)-3));
1348         }
1349         __except(1)
1350         {
1351                 return true;
1352         }
1353
1354         BOOL bHaveDebugger = FALSE;
1355         if(CheckRemoteDebuggerPresent(GetCurrentProcess(), &bHaveDebugger))
1356         {
1357                 if(bHaveDebugger) return true;
1358         }
1359
1360         return IsDebuggerPresent();
1361 }
1362 static __forceinline bool check_debugger_helper(void)
1363 {
1364         if(is_debugger_present())
1365         {
1366                 MUtils::OS::fatal_exit(L"Not a debug build. Please unload debugger and try again!");
1367                 return true;
1368         }
1369         return false;
1370 }
1371 #else
1372 #define check_debugger_helper() (false)
1373 #endif
1374
1375 void MUtils::OS::check_debugger(void)
1376 {
1377         check_debugger_helper();
1378 }
1379
1380 static volatile bool g_debug_check = check_debugger_helper();
1381
1382 ///////////////////////////////////////////////////////////////////////////////
1383 // FATAL EXIT
1384 ///////////////////////////////////////////////////////////////////////////////
1385
1386 static MUtils::Internal::CriticalSection g_fatal_exit_lock;
1387 static volatile bool g_fatal_exit_flag = true;
1388
1389 static DWORD WINAPI fatal_exit_helper(LPVOID lpParameter)
1390 {
1391         MUtils::OS::system_message_err(L"GURU MEDITATION", (LPWSTR) lpParameter);
1392         return 0;
1393 }
1394
1395 void MUtils::OS::fatal_exit(const wchar_t* const errorMessage)
1396 {
1397         g_fatal_exit_lock.enter();
1398         
1399         if(!g_fatal_exit_flag)
1400         {
1401                 return; /*prevent recursive invocation*/
1402         }
1403
1404         g_fatal_exit_flag = false;
1405
1406         if(g_main_thread_id != GetCurrentThreadId())
1407         {
1408                 if(HANDLE hThreadMain = OpenThread(THREAD_SUSPEND_RESUME, FALSE, g_main_thread_id))
1409                 {
1410                         SuspendThread(hThreadMain); /*stop main thread*/
1411                 }
1412         }
1413
1414         if(HANDLE hThread = CreateThread(NULL, 0, fatal_exit_helper, (LPVOID) errorMessage, 0, NULL))
1415         {
1416                 WaitForSingleObject(hThread, INFINITE);
1417         }
1418
1419         for(;;)
1420         {
1421                 TerminateProcess(GetCurrentProcess(), 666);
1422         }
1423 }
1424
1425 ///////////////////////////////////////////////////////////////////////////////