OSDN Git Service

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