1 ///////////////////////////////////////////////////////////////////////////////
2 // MuldeR's Utilities for Qt
3 // Copyright (C) 2004-2018 LoRd_MuldeR <MuldeR2@GMX.de>
5 // This library is free software; you can redistribute it and/or
6 // modify it under the terms of the GNU Lesser General Public
7 // License as published by the Free Software Foundation; either
8 // version 2.1 of the License, or (at your option) any later version.
10 // This library is distributed in the hope that it will be useful,
11 // but WITHOUT ANY WARRANTY; without even the implied warranty of
12 // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
13 // Lesser General Public License for more details.
15 // You should have received a copy of the GNU Lesser General Public
16 // License along with this library; if not, write to the Free Software
17 // Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
19 // http://www.gnu.org/licenses/lgpl-2.1.txt
20 //////////////////////////////////////////////////////////////////////////////////
23 #define WIN32_LEAN_AND_MEAN 1
32 #pragma warning(disable:4091) //for MSVC2015
40 #include <MUtils/Global.h>
41 #include <MUtils/OSSupport.h>
42 #include <MUtils/GUI.h>
44 #include "CriticalSection_Win32.h"
45 #include "Utils_Win32.h"
49 #include <QReadWriteLock>
56 static const DWORD g_main_thread_id = GetCurrentThreadId();
58 ///////////////////////////////////////////////////////////////////////////////
60 ///////////////////////////////////////////////////////////////////////////////
62 static const UINT g_msgBoxFlags = MB_TOPMOST | MB_TASKMODAL | MB_SETFOREGROUND;
64 void MUtils::OS::system_message_nfo(const wchar_t *const title, const wchar_t *const text)
66 MessageBoxW(NULL, text, title, g_msgBoxFlags | MB_ICONINFORMATION);
69 void MUtils::OS::system_message_wrn(const wchar_t *const title, const wchar_t *const text)
71 MessageBoxW(NULL, text, title, g_msgBoxFlags | MB_ICONWARNING);
74 void MUtils::OS::system_message_err(const wchar_t *const title, const wchar_t *const text)
76 MessageBoxW(NULL, text, title, g_msgBoxFlags | MB_ICONERROR);
79 ///////////////////////////////////////////////////////////////////////////////
80 // FETCH CLI ARGUMENTS
81 ///////////////////////////////////////////////////////////////////////////////
83 static QReadWriteLock g_arguments_lock;
84 static QScopedPointer<MUtils::OS::ArgumentMap> g_arguments_list;
86 const QStringList MUtils::OS::crack_command_line(const QString &command_line)
89 LPWSTR *szArglist = CommandLineToArgvW(command_line.isNull() ? GetCommandLineW() : MUTILS_WCHR(command_line), &nArgs);
91 QStringList command_line_tokens;
94 for(int i = 0; i < nArgs; i++)
96 const QString argStr = MUTILS_QSTR(szArglist[i]).trimmed();
99 command_line_tokens << argStr;
102 LocalFree(szArglist);
105 return command_line_tokens;
108 const MUtils::OS::ArgumentMap &MUtils::OS::arguments(void)
110 QReadLocker readLock(&g_arguments_lock);
112 //Already initialized?
113 if(!g_arguments_list.isNull())
115 return (*(g_arguments_list.data()));
119 QWriteLocker writeLock(&g_arguments_lock);
121 //Still not initialized?
122 if(!g_arguments_list.isNull())
124 return (*(g_arguments_list.data()));
127 g_arguments_list.reset(new ArgumentMap());
128 const QStringList argList = crack_command_line();
130 if(!argList.isEmpty())
132 const QString argPrefix = QLatin1String("--");
133 const QChar separator = QLatin1Char('=');
135 bool firstToken = true;
136 for(QStringList::ConstIterator iter = argList.constBegin(); iter != argList.constEnd(); iter++)
141 continue; /*skip executable file name*/
143 if(iter->startsWith(argPrefix))
145 const QString argData = iter->mid(2).trimmed();
146 if(argData.length() > 0)
148 const int separatorIndex = argData.indexOf(separator);
149 if(separatorIndex > 0)
151 const QString argKey = argData.left(separatorIndex).trimmed();
152 const QString argVal = argData.mid(separatorIndex + 1).trimmed();
153 g_arguments_list->insertMulti(argKey.toLower(), argVal);
157 g_arguments_list->insertMulti(argData.toLower(), QString());
163 else if(argList.empty())
165 qWarning("CommandLineToArgvW() has failed !!!");
168 return (*(g_arguments_list.data()));
171 ///////////////////////////////////////////////////////////////////////////////
173 ///////////////////////////////////////////////////////////////////////////////
175 typedef struct _progress_callback_data_t
177 MUtils::OS::progress_callback_t callback_function;
180 progress_callback_data_t;
182 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)
184 if(const progress_callback_data_t *data = (progress_callback_data_t*) lpData)
186 const double progress = qBound(0.0, double(TotalBytesTransferred.QuadPart) / double(TotalFileSize.QuadPart), 1.0);
187 return data->callback_function(progress, data->user_data) ? PROGRESS_CONTINUE : PROGRESS_CANCEL;
189 return PROGRESS_CONTINUE;
192 MUTILS_API bool MUtils::OS::copy_file(const QString &sourcePath, const QString &outputPath, const bool &overwrite, const progress_callback_t callback, void *const userData)
194 progress_callback_data_t callback_data = { callback, userData };
196 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));
200 const DWORD errorCode = GetLastError();
201 if(errorCode != ERROR_REQUEST_ABORTED)
203 qWarning("CopyFile() failed with error code 0x%08X!", errorCode);
207 qWarning("CopyFile() operation was abroted by user!");
211 return (result != FALSE);
214 ///////////////////////////////////////////////////////////////////////////////
216 ///////////////////////////////////////////////////////////////////////////////
218 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)
220 if(!GetFileVersionInfo(MUTILS_WCHR(fileName), 0, size, buffer))
222 qWarning("GetFileVersionInfo() has failed, file version cannot be determined!");
226 VS_FIXEDFILEINFO *verInfo;
228 if(!VerQueryValue(buffer, L"\\", (LPVOID*)(&verInfo), &verInfoLen))
230 qWarning("VerQueryValue() has failed, file version cannot be determined!");
234 if(major) *major = quint16((verInfo->dwFileVersionMS >> 16) & 0x0000FFFF);
235 if(minor) *minor = quint16((verInfo->dwFileVersionMS) & 0x0000FFFF);
236 if(patch) *patch = quint16((verInfo->dwFileVersionLS >> 16) & 0x0000FFFF);
237 if(build) *build = quint16((verInfo->dwFileVersionLS) & 0x0000FFFF);
242 bool MUtils::OS::get_file_version(const QString fileName, quint16 *const major, quint16 *const minor, quint16 *const patch, quint16 *const build)
244 if(major) *major = 0U; if(minor) *minor = 0U;
245 if(patch) *patch = 0U; if(build) *build = 0U;
247 const DWORD size = GetFileVersionInfoSize(MUTILS_WCHR(fileName), NULL);
250 qWarning("GetFileVersionInfoSize() has failed, file version cannot be determined!");
254 PVOID buffer = _malloca(size);
257 qWarning("Memory allocation has failed!");
261 const bool success = get_file_version_helper(fileName, buffer, size, major, minor, patch, build);
267 ///////////////////////////////////////////////////////////////////////////////
268 // OS VERSION DETECTION
269 ///////////////////////////////////////////////////////////////////////////////
271 static bool g_os_version_initialized = false;
272 static MUtils::OS::Version::os_version_t g_os_version_info = MUtils::OS::Version::UNKNOWN_OPSYS;
273 static QReadWriteLock g_os_version_lock;
275 //Maps marketing names to the actual Windows NT versions
278 MUtils::OS::Version::os_version_t version;
279 const char friendlyName[64];
283 { MUtils::OS::Version::WINDOWS_WIN2K, "Windows 2000" }, //2000
284 { MUtils::OS::Version::WINDOWS_WINXP, "Windows XP or Windows XP Media Center Edition" }, //XP
285 { MUtils::OS::Version::WINDOWS_XPX64, "Windows Server 2003 or Windows XP x64" }, //XP_x64
286 { MUtils::OS::Version::WINDOWS_VISTA, "Windows Vista or Windows Server 2008" }, //Vista
287 { MUtils::OS::Version::WINDOWS_WIN70, "Windows 7 or Windows Server 2008 R2" }, //7
288 { MUtils::OS::Version::WINDOWS_WIN80, "Windows 8 or Windows Server 2012" }, //8
289 { MUtils::OS::Version::WINDOWS_WIN81, "Windows 8.1 or Windows Server 2012 R2" }, //8.1
290 { MUtils::OS::Version::WINDOWS_WN100, "Windows 10 or Windows Server 2016" }, //10
291 { MUtils::OS::Version::UNKNOWN_OPSYS, "N/A" }
294 //OS version data dtructures
301 //Comparision operators for os_version_t
302 bool os_version_t::operator== (const os_version_t &rhs) const { return (type == rhs.type) && (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) || ((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 bool os_version_t::operator< (const os_version_t &rhs) const { return (type == rhs.type) && ((versionMajor < rhs.versionMajor) || ((versionMajor == rhs.versionMajor) && (versionMinor < rhs.versionMinor))); }
307 bool os_version_t::operator<= (const os_version_t &rhs) const { return (type == rhs.type) && ((versionMajor < rhs.versionMajor) || ((versionMajor == rhs.versionMajor) && (versionMinor <= rhs.versionMinor))); }
309 //Known Windows NT versions
310 const os_version_t WINDOWS_WIN2K = { OS_WINDOWS, 5, 0, 2195, 0 }; // 2000
311 const os_version_t WINDOWS_WINXP = { OS_WINDOWS, 5, 1, 2600, 0 }; // XP
312 const os_version_t WINDOWS_XPX64 = { OS_WINDOWS, 5, 2, 3790, 0 }; // XP_x64
313 const os_version_t WINDOWS_VISTA = { OS_WINDOWS, 6, 0, 6000, 0 }; // Vista
314 const os_version_t WINDOWS_WIN70 = { OS_WINDOWS, 6, 1, 7600, 0 }; // 7
315 const os_version_t WINDOWS_WIN80 = { OS_WINDOWS, 6, 2, 9200, 0 }; // 8
316 const os_version_t WINDOWS_WIN81 = { OS_WINDOWS, 6, 3, 9600, 0 }; // 8.1
317 const os_version_t WINDOWS_WN100 = { OS_WINDOWS, 10, 0, 10240, 0 }; // 10
320 const os_version_t UNKNOWN_OPSYS = { OS_UNKNOWN, 0, 0, 0, 0 }; // N/A
325 static inline DWORD SAFE_ADD(const DWORD &a, const DWORD &b, const DWORD &limit = MAXDWORD)
327 return ((a >= limit) || (b >= limit) || ((limit - a) <= b)) ? limit : (a + b);
331 static void initialize_os_version(OSVERSIONINFOEXW *const osInfo)
333 memset(osInfo, 0, sizeof(OSVERSIONINFOEXW));
334 osInfo->dwOSVersionInfoSize = sizeof(OSVERSIONINFOEXW);
337 static inline DWORD initialize_step_size(const DWORD &limit)
340 while (result < limit)
342 result = SAFE_ADD(result, result);
347 static bool rtl_get_version(OSVERSIONINFOEXW *const osInfo)
349 typedef LONG(__stdcall *RtlGetVersion)(LPOSVERSIONINFOEXW);
350 if (const HMODULE ntdll = GetModuleHandleW(L"ntdll"))
352 if (const RtlGetVersion pRtlGetVersion = (RtlGetVersion)GetProcAddress(ntdll, "RtlGetVersion"))
354 initialize_os_version(osInfo);
355 if (pRtlGetVersion(osInfo) == 0)
363 initialize_os_version(osInfo);
364 return (GetVersionExW((LPOSVERSIONINFOW)osInfo) != FALSE);
367 static bool rtl_verify_version(OSVERSIONINFOEXW *const osInfo, const ULONG typeMask, const ULONGLONG condMask)
369 typedef LONG(__stdcall *RtlVerifyVersionInfo)(LPOSVERSIONINFOEXW, ULONG, ULONGLONG);
370 if (const HMODULE ntdll = GetModuleHandleW(L"ntdll"))
372 if (const RtlVerifyVersionInfo pRtlVerifyVersionInfo = (RtlVerifyVersionInfo)GetProcAddress(ntdll, "RtlVerifyVersionInfo"))
374 if (pRtlVerifyVersionInfo(osInfo, typeMask, condMask) == 0)
382 return (VerifyVersionInfoW(osInfo, typeMask, condMask) != FALSE);
385 static bool verify_os_version(const DWORD major, const DWORD minor)
387 OSVERSIONINFOEXW osvi;
388 DWORDLONG dwlConditionMask = 0;
389 initialize_os_version(&osvi);
391 //Initialize the OSVERSIONINFOEX structure
392 osvi.dwMajorVersion = major;
393 osvi.dwMinorVersion = minor;
394 osvi.dwPlatformId = VER_PLATFORM_WIN32_NT;
396 //Initialize the condition mask
397 VER_SET_CONDITION(dwlConditionMask, VER_MAJORVERSION, VER_GREATER_EQUAL);
398 VER_SET_CONDITION(dwlConditionMask, VER_MINORVERSION, VER_GREATER_EQUAL);
399 VER_SET_CONDITION(dwlConditionMask, VER_PLATFORMID, VER_EQUAL);
402 const BOOL ret = rtl_verify_version(&osvi, VER_MAJORVERSION | VER_MINORVERSION | VER_PLATFORMID, dwlConditionMask);
407 if(GetLastError() != ERROR_OLD_WIN_VERSION)
409 qWarning("VerifyVersionInfo() system call has failed!");
413 return (ret != FALSE);
416 static bool verify_os_build(const DWORD build)
418 OSVERSIONINFOEXW osvi;
419 DWORDLONG dwlConditionMask = 0;
420 initialize_os_version(&osvi);
422 //Initialize the OSVERSIONINFOEX structure
423 osvi.dwBuildNumber = build;
424 osvi.dwPlatformId = VER_PLATFORM_WIN32_NT;
426 //Initialize the condition mask
427 VER_SET_CONDITION(dwlConditionMask, VER_BUILDNUMBER, VER_GREATER_EQUAL);
428 VER_SET_CONDITION(dwlConditionMask, VER_PLATFORMID, VER_EQUAL);
431 const BOOL ret = rtl_verify_version(&osvi, VER_BUILDNUMBER | VER_PLATFORMID, dwlConditionMask);
436 if (GetLastError() != ERROR_OLD_WIN_VERSION)
438 qWarning("VerifyVersionInfo() system call has failed!");
442 return (ret != FALSE);
445 static bool verify_os_spack(const WORD spack)
447 OSVERSIONINFOEXW osvi;
448 DWORDLONG dwlConditionMask = 0;
449 initialize_os_version(&osvi);
451 //Initialize the OSVERSIONINFOEX structure
452 osvi.wServicePackMajor = spack;
453 osvi.dwPlatformId = VER_PLATFORM_WIN32_NT;
455 //Initialize the condition mask
456 VER_SET_CONDITION(dwlConditionMask, VER_SERVICEPACKMAJOR, VER_GREATER_EQUAL);
457 VER_SET_CONDITION(dwlConditionMask, VER_PLATFORMID, VER_EQUAL);
460 const BOOL ret = rtl_verify_version(&osvi, VER_SERVICEPACKMAJOR | VER_PLATFORMID, dwlConditionMask);
465 if (GetLastError() != ERROR_OLD_WIN_VERSION)
467 qWarning("VerifyVersionInfo() system call has failed!");
471 return (ret != FALSE);
474 static bool get_real_os_version(unsigned int *const major, unsigned int *const minor, unsigned int *const build, unsigned int *const spack, bool *const pbOverride)
476 static const DWORD MAX_VERSION = MAXWORD;
477 static const DWORD MAX_BUILDNO = MAXINT;
478 static const DWORD MAX_SRVCPCK = MAXWORD;
480 *major = *minor = *build = *spack = 0U;
483 //Initialize local variables
484 OSVERSIONINFOEXW osvi;
485 memset(&osvi, 0, sizeof(OSVERSIONINFOEXW));
486 osvi.dwOSVersionInfoSize = sizeof(OSVERSIONINFOEXW);
488 //Try GetVersionEx() first
489 if(rtl_get_version(&osvi) == FALSE)
491 qWarning("GetVersionEx() has failed, cannot detect Windows version!");
495 //Make sure we are running on NT
496 if(osvi.dwPlatformId == VER_PLATFORM_WIN32_NT)
498 *major = osvi.dwMajorVersion;
499 *minor = osvi.dwMinorVersion;
500 *build = osvi.dwBuildNumber;
501 *spack = osvi.wServicePackMajor;
505 if (verify_os_version(4, 0))
513 qWarning("Not running on Windows NT, unsupported operating system!");
519 for (DWORD nextMajor = (*major) + 1; nextMajor <= MAX_VERSION; nextMajor++)
521 if (verify_os_version(nextMajor, 0))
532 for (DWORD nextMinor = (*minor) + 1; nextMinor <= MAX_VERSION; nextMinor++)
534 if (verify_os_version((*major), nextMinor))
544 if (verify_os_build(SAFE_ADD((*build), 1, MAX_BUILDNO)))
546 DWORD stepSize = initialize_step_size(MAX_BUILDNO);
547 for (DWORD nextBuildNo = SAFE_ADD((*build), stepSize, MAX_BUILDNO); (*build) < MAX_BUILDNO; nextBuildNo = SAFE_ADD((*build), stepSize, MAX_BUILDNO))
549 if (verify_os_build(nextBuildNo))
551 *build = nextBuildNo;
557 stepSize = stepSize / 2;
565 if (verify_os_spack(SAFE_ADD((*spack), 1, MAX_SRVCPCK)))
567 DWORD stepSize = initialize_step_size(MAX_SRVCPCK);
568 for (DWORD nextSPackNo = SAFE_ADD((*spack), stepSize, MAX_SRVCPCK); (*spack) < MAX_SRVCPCK; nextSPackNo = SAFE_ADD((*spack), stepSize, MAX_SRVCPCK))
570 if (verify_os_spack(nextSPackNo))
572 *build = nextSPackNo;
578 stepSize = stepSize / 2;
588 const MUtils::OS::Version::os_version_t &MUtils::OS::os_version(void)
590 QReadLocker readLock(&g_os_version_lock);
592 //Already initialized?
593 if(g_os_version_initialized)
595 return g_os_version_info;
599 QWriteLocker writeLock(&g_os_version_lock);
602 if(g_os_version_initialized)
604 return g_os_version_info;
608 unsigned int major, minor, build, spack; bool overrideFlg;
609 if(get_real_os_version(&major, &minor, &build, &spack, &overrideFlg))
611 g_os_version_info.type = Version::OS_WINDOWS;
612 g_os_version_info.versionMajor = major;
613 g_os_version_info.versionMinor = minor;
614 g_os_version_info.versionBuild = build;
615 g_os_version_info.versionSPack = spack;
616 g_os_version_info.overrideFlag = overrideFlg;
620 qWarning("Failed to determine the operating system version!");
624 g_os_version_initialized = true;
625 return g_os_version_info;
628 const char *MUtils::OS::os_friendly_name(const MUtils::OS::Version::os_version_t &os_version)
630 for(size_t i = 0; g_os_version_lut[i].version != MUtils::OS::Version::UNKNOWN_OPSYS; i++)
632 if(os_version == g_os_version_lut[i].version)
634 return g_os_version_lut[i].friendlyName;
641 ///////////////////////////////////////////////////////////////////////////////
643 ///////////////////////////////////////////////////////////////////////////////
645 static bool g_wine_deteced = false;
646 static bool g_wine_initialized = false;
647 static QReadWriteLock g_wine_lock;
649 static const bool detect_wine(void)
651 void *const ptr = MUtils::Win32Utils::resolve<void*>(QLatin1String("ntdll"), QLatin1String("wine_get_version"));
652 return (ptr != NULL);
655 const bool &MUtils::OS::running_on_wine(void)
657 QReadLocker readLock(&g_wine_lock);
659 //Already initialized?
660 if(g_wine_initialized)
662 return g_wine_deteced;
666 QWriteLocker writeLock(&g_wine_lock);
669 if(g_wine_initialized)
671 return g_wine_deteced;
675 g_wine_deteced = detect_wine();
676 g_wine_initialized = true;
678 return g_wine_deteced;
681 ///////////////////////////////////////////////////////////////////////////////
683 ///////////////////////////////////////////////////////////////////////////////
685 static QReadWriteLock g_known_folders_lock;
686 static QScopedPointer<QHash<size_t, QString>> g_known_folders_data;
688 typedef HRESULT (WINAPI *SHGetKnownFolderPath_t)(const GUID &rfid, DWORD dwFlags, HANDLE hToken, PWSTR *ppszPath);
689 typedef HRESULT (WINAPI *SHGetFolderPath_t) (HWND hwndOwner, int nFolder, HANDLE hToken, DWORD dwFlags, LPWSTR pszPath);
691 const QString &MUtils::OS::known_folder(known_folder_t folder_id)
693 typedef enum { KF_FLAG_CREATE = 0x00008000 } kf_flags_t;
702 { 0x001c, {0xF1B32785,0x6FBA,0x4FCF,{0x9D,0x55,0x7B,0x8E,0x7F,0x15,0x70,0x91}} }, //CSIDL_LOCAL_APPDATA
703 { 0x0026, {0x905e63b6,0xc1bf,0x494e,{0xb2,0x9c,0x65,0xb7,0x32,0xd3,0xd2,0x1a}} }, //CSIDL_PROGRAM_FILES
704 { 0x0024, {0xF38BF404,0x1D43,0x42F2,{0x93,0x05,0x67,0xDE,0x0B,0x28,0xFC,0x23}} }, //CSIDL_WINDOWS_FOLDER
705 { 0x0025, {0x1AC14E77,0x02E7,0x4E5D,{0xB7,0x44,0x2E,0xB1,0xAE,0x51,0x98,0xB7}} }, //CSIDL_SYSTEM_FOLDER
708 size_t folderId = size_t(-1);
712 case FOLDER_LOCALAPPDATA: folderId = 0; break;
713 case FOLDER_PROGRAMFILES: folderId = 1; break;
714 case FOLDER_SYSTROOT_DIR: folderId = 2; break;
715 case FOLDER_SYSTEMFOLDER: folderId = 3; break;
718 if(folderId == size_t(-1))
720 qWarning("Invalid 'known' folder was requested!");
721 return *reinterpret_cast<QString*>(NULL);
724 QReadLocker readLock(&g_known_folders_lock);
727 if(!g_known_folders_data.isNull())
729 if(g_known_folders_data->contains(folderId))
731 return (*g_known_folders_data)[folderId];
735 //Obtain write lock to initialize
737 QWriteLocker writeLock(&g_known_folders_lock);
739 //Still not in cache?
740 if(!g_known_folders_data.isNull())
742 if(g_known_folders_data->contains(folderId))
744 return (*g_known_folders_data)[folderId];
748 //Initialize on first call
749 if(g_known_folders_data.isNull())
751 g_known_folders_data.reset(new QHash<size_t, QString>());
756 //Try SHGetKnownFolderPath() first!
757 if(const SHGetKnownFolderPath_t known_folders_fpGetKnownFolderPath = MUtils::Win32Utils::resolve<SHGetKnownFolderPath_t>(QLatin1String("shell32"), QLatin1String("SHGetKnownFolderPath")))
760 if(known_folders_fpGetKnownFolderPath(s_folders[folderId].guid, KF_FLAG_CREATE, NULL, &path) == S_OK)
762 //MessageBoxW(0, path, L"SHGetKnownFolderPath", MB_TOPMOST);
763 const QDir folderTemp = QDir(QDir::fromNativeSeparators(MUTILS_QSTR(path)));
764 if(folderTemp.exists())
766 folderPath = folderTemp.canonicalPath();
772 //Fall back to SHGetFolderPathW()
773 if (folderPath.isEmpty())
775 if (const SHGetFolderPath_t known_folders_fpGetFolderPath = MUtils::Win32Utils::resolve<SHGetFolderPath_t>(QLatin1String("shell32"), QLatin1String("SHGetFolderPathW")))
777 QScopedArrayPointer<WCHAR> path(new WCHAR[4096]);
778 if (known_folders_fpGetFolderPath(NULL, s_folders[folderId].csidl | CSIDL_FLAG_CREATE, NULL, NULL, path.data()) == S_OK)
780 //MessageBoxW(0, path, L"SHGetFolderPathW", MB_TOPMOST);
781 const QDir folderTemp = QDir(QDir::fromNativeSeparators(MUTILS_QSTR(path.data())));
782 if (folderTemp.exists())
784 folderPath = folderTemp.canonicalPath();
791 if (!folderPath.isEmpty())
793 g_known_folders_data->insert(folderId, folderPath);
794 return (*g_known_folders_data)[folderId];
797 return Internal::g_empty;
800 ///////////////////////////////////////////////////////////////////////////////
801 // CURRENT DATA & TIME
802 ///////////////////////////////////////////////////////////////////////////////
804 QDate MUtils::OS::current_date(void)
806 const DWORD MAX_PROC = 1024;
807 QScopedArrayPointer<DWORD> processes(new DWORD[MAX_PROC]);
808 DWORD bytesReturned = 0;
810 if(!EnumProcesses(processes.data(), sizeof(DWORD) * MAX_PROC, &bytesReturned))
812 return QDate::currentDate();
815 const DWORD procCount = bytesReturned / sizeof(DWORD);
816 ULARGE_INTEGER lastStartTime;
817 memset(&lastStartTime, 0, sizeof(ULARGE_INTEGER));
819 for(DWORD i = 0; i < procCount; i++)
821 if(HANDLE hProc = OpenProcess(PROCESS_QUERY_INFORMATION, FALSE, processes[i]))
823 FILETIME processTime[4];
824 if(GetProcessTimes(hProc, &processTime[0], &processTime[1], &processTime[2], &processTime[3]))
826 ULARGE_INTEGER timeCreation;
827 timeCreation.LowPart = processTime[0].dwLowDateTime;
828 timeCreation.HighPart = processTime[0].dwHighDateTime;
829 if(timeCreation.QuadPart > lastStartTime.QuadPart)
831 lastStartTime.QuadPart = timeCreation.QuadPart;
838 FILETIME lastStartTime_fileTime;
839 lastStartTime_fileTime.dwHighDateTime = lastStartTime.HighPart;
840 lastStartTime_fileTime.dwLowDateTime = lastStartTime.LowPart;
842 FILETIME lastStartTime_localTime;
843 if(!FileTimeToLocalFileTime(&lastStartTime_fileTime, &lastStartTime_localTime))
845 memcpy(&lastStartTime_localTime, &lastStartTime_fileTime, sizeof(FILETIME));
848 SYSTEMTIME lastStartTime_system;
849 if(!FileTimeToSystemTime(&lastStartTime_localTime, &lastStartTime_system))
851 memset(&lastStartTime_system, 0, sizeof(SYSTEMTIME));
852 lastStartTime_system.wYear = 1970; lastStartTime_system.wMonth = lastStartTime_system.wDay = 1;
855 const QDate currentDate = QDate::currentDate();
856 const QDate processDate = QDate(lastStartTime_system.wYear, lastStartTime_system.wMonth, lastStartTime_system.wDay);
857 return (currentDate >= processDate) ? currentDate : processDate;
860 quint64 MUtils::OS::current_file_time(void)
863 GetSystemTimeAsFileTime(&fileTime);
866 temp.HighPart = fileTime.dwHighDateTime;
867 temp.LowPart = fileTime.dwLowDateTime;
869 return temp.QuadPart;
872 ///////////////////////////////////////////////////////////////////////////////
874 ///////////////////////////////////////////////////////////////////////////////
876 typedef DWORD(_stdcall *GetPathNameByHandleFun)(HANDLE hFile, LPWSTR lpszFilePath, DWORD cchFilePath, DWORD dwFlags);
878 static QString get_file_path_drive_list(void)
881 const DWORD len = GetLogicalDriveStringsW(0, NULL);
884 if (wchar_t *const buffer = (wchar_t*) _malloca(sizeof(wchar_t) * len))
886 const DWORD ret = GetLogicalDriveStringsW(len, buffer);
887 if ((ret > 0) && (ret < len))
889 const wchar_t *ptr = buffer;
890 while (const size_t current_len = wcslen(ptr))
892 list.append(QChar(*reinterpret_cast<const ushort*>(ptr)));
893 ptr += (current_len + 1);
902 static void get_file_path_translate(QString &path)
904 static const DWORD BUFSIZE = 2048;
905 wchar_t buffer[BUFSIZE], drive[3];
907 const QString driveList = get_file_path_drive_list();
908 wcscpy_s(drive, 3, L"?:");
909 for (const wchar_t *current = MUTILS_WCHR(driveList); *current; current++)
911 drive[0] = (*current);
912 if (QueryDosDeviceW(drive, buffer, MAX_PATH))
914 const QString prefix = MUTILS_QSTR(buffer);
915 if (path.startsWith(prefix, Qt::CaseInsensitive))
917 path.remove(0, prefix.length()).prepend(QLatin1Char(':')).prepend(QChar(*reinterpret_cast<const ushort*>(current)));
924 static QString get_file_path_fallback(const HANDLE &hFile)
928 const HANDLE hFileMap = CreateFileMappingW(hFile, NULL, PAGE_READONLY, 0, 1, NULL);
931 void *const pMem = MapViewOfFile(hFileMap, FILE_MAP_READ, 0, 0, 1);
934 static const size_t BUFFSIZE = 2048;
935 wchar_t buffer[BUFFSIZE];
936 if (GetMappedFileNameW(GetCurrentProcess(), pMem, buffer, BUFFSIZE) > 0)
938 filePath = MUTILS_QSTR(buffer);
940 UnmapViewOfFile(pMem);
942 CloseHandle(hFileMap);
945 if (!filePath.isEmpty())
947 get_file_path_translate(filePath);
953 QString MUtils::OS::get_file_path(const int &fd)
957 const GetPathNameByHandleFun getPathNameByHandleFun = MUtils::Win32Utils::resolve<GetPathNameByHandleFun>(QLatin1String("kernel32"), QLatin1String("GetFinalPathNameByHandleW"));
958 if (!getPathNameByHandleFun)
960 return get_file_path_fallback((HANDLE)_get_osfhandle(fd));
963 const HANDLE handle = (HANDLE) _get_osfhandle(fd);
964 const DWORD len = getPathNameByHandleFun(handle, NULL, 0, FILE_NAME_OPENED);
967 if (wchar_t *const buffer = (wchar_t*)_malloca(sizeof(wchar_t) * len))
969 const DWORD ret = getPathNameByHandleFun(handle, buffer, len, FILE_NAME_OPENED);
970 if ((ret > 0) && (ret < len))
972 const QString path(MUTILS_QSTR(buffer));
973 return path.startsWith(QLatin1String("\\\\?\\")) ? path.mid(4) : path;
983 ///////////////////////////////////////////////////////////////////////////////
985 ///////////////////////////////////////////////////////////////////////////////
987 static bool user_is_admin_helper(void)
989 HANDLE hToken = NULL;
990 if(!OpenProcessToken(GetCurrentProcess(), TOKEN_QUERY, &hToken))
996 if(!GetTokenInformation(hToken, TokenGroups, NULL, 0, &dwSize))
998 if(GetLastError() != ERROR_INSUFFICIENT_BUFFER)
1000 CloseHandle(hToken);
1005 PTOKEN_GROUPS lpGroups = (PTOKEN_GROUPS) malloc(dwSize);
1008 CloseHandle(hToken);
1012 if(!GetTokenInformation(hToken, TokenGroups, lpGroups, dwSize, &dwSize))
1015 CloseHandle(hToken);
1019 PSID lpSid = NULL; SID_IDENTIFIER_AUTHORITY Authority = {SECURITY_NT_AUTHORITY};
1020 if(!AllocateAndInitializeSid(&Authority, 2, SECURITY_BUILTIN_DOMAIN_RID, DOMAIN_ALIAS_RID_ADMINS, 0, 0, 0, 0, 0, 0, &lpSid))
1023 CloseHandle(hToken);
1027 bool bResult = false;
1028 for(DWORD i = 0; i < lpGroups->GroupCount; i++)
1030 if(EqualSid(lpSid, lpGroups->Groups[i].Sid))
1039 CloseHandle(hToken);
1043 bool MUtils::OS::is_elevated(bool *bIsUacEnabled)
1047 *bIsUacEnabled = false;
1050 bool bIsProcessElevated = false;
1051 HANDLE hToken = NULL;
1053 if(OpenProcessToken(GetCurrentProcess(), TOKEN_QUERY, &hToken))
1055 TOKEN_ELEVATION_TYPE tokenElevationType;
1057 if(GetTokenInformation(hToken, TokenElevationType, &tokenElevationType, sizeof(TOKEN_ELEVATION_TYPE), &returnLength))
1059 if(returnLength == sizeof(TOKEN_ELEVATION_TYPE))
1061 switch(tokenElevationType)
1063 case TokenElevationTypeDefault:
1064 qDebug("Process token elevation type: Default -> UAC is disabled.\n");
1066 case TokenElevationTypeFull:
1067 qWarning("Process token elevation type: Full -> potential security risk!\n");
1068 bIsProcessElevated = true;
1069 if(bIsUacEnabled) *bIsUacEnabled = true;
1071 case TokenElevationTypeLimited:
1072 qDebug("Process token elevation type: Limited -> not elevated.\n");
1073 if(bIsUacEnabled) *bIsUacEnabled = true;
1076 qWarning("Unknown tokenElevationType value: %d", tokenElevationType);
1082 qWarning("GetTokenInformation() return an unexpected size!");
1085 CloseHandle(hToken);
1089 qWarning("Failed to open process token!");
1092 return bIsProcessElevated;
1095 bool MUtils::OS::user_is_admin(void)
1097 bool isAdmin = false;
1099 //Check for process elevation and UAC support first!
1100 if(MUtils::OS::is_elevated(&isAdmin))
1102 qWarning("Process is elevated -> user is admin!");
1106 //If not elevated and UAC is not available -> user must be in admin group!
1109 qDebug("UAC is disabled/unavailable -> checking for Administrators group");
1110 isAdmin = user_is_admin_helper();
1116 ///////////////////////////////////////////////////////////////////////////////
1118 ///////////////////////////////////////////////////////////////////////////////
1120 int MUtils::OS::network_status(void)
1123 const BOOL ret = IsNetworkAlive(&dwFlags);
1124 if(GetLastError() == 0)
1126 return (ret != FALSE) ? NETWORK_TYPE_YES : NETWORK_TYPE_NON;
1128 return NETWORK_TYPE_ERR;
1131 ///////////////////////////////////////////////////////////////////////////////
1133 ///////////////////////////////////////////////////////////////////////////////
1135 bool MUtils::OS::handle_os_message(const void *const message, long *result)
1137 const MSG *const msg = reinterpret_cast<const MSG*>(message);
1139 switch(msg->message)
1141 case WM_QUERYENDSESSION:
1142 qWarning("WM_QUERYENDSESSION message received!");
1143 *result = MUtils::GUI::broadcast(MUtils::GUI::USER_EVENT_QUERYENDSESSION, false) ? TRUE : FALSE;
1146 qWarning("WM_ENDSESSION message received!");
1147 if(msg->wParam == TRUE)
1149 MUtils::GUI::broadcast(MUtils::GUI::USER_EVENT_ENDSESSION, false);
1150 MUtils::GUI::force_quit();
1156 /*ignore this message and let Qt handle it*/
1161 ///////////////////////////////////////////////////////////////////////////////
1163 ///////////////////////////////////////////////////////////////////////////////
1165 void MUtils::OS::sleep_ms(const size_t &duration)
1167 Sleep((DWORD) duration);
1170 ///////////////////////////////////////////////////////////////////////////////
1172 ///////////////////////////////////////////////////////////////////////////////
1174 static int g_library_as_image_resource_supported = -1;
1175 static QReadWriteLock g_library_as_image_resource_supported_lock;
1177 static bool library_as_image_resource_supported()
1179 QReadLocker readLocker(&g_library_as_image_resource_supported_lock);
1180 if (g_library_as_image_resource_supported >= 0)
1182 return (g_library_as_image_resource_supported > 0);
1185 readLocker.unlock();
1186 QWriteLocker writeLocker(&g_library_as_image_resource_supported_lock);
1188 if (g_library_as_image_resource_supported < 0)
1190 g_library_as_image_resource_supported = 0;
1191 OSVERSIONINFOEXW osvi;
1192 if (rtl_get_version(&osvi))
1194 if ((osvi.dwPlatformId == VER_PLATFORM_WIN32_NT) && (osvi.dwMajorVersion >= 6U))
1196 g_library_as_image_resource_supported = 1;
1201 return (g_library_as_image_resource_supported > 0);
1204 bool MUtils::OS::is_executable_file(const QString &path)
1207 if(GetBinaryType(MUTILS_WCHR(QDir::toNativeSeparators(path)), &binaryType))
1209 return ((binaryType == SCS_32BIT_BINARY) || (binaryType == SCS_64BIT_BINARY));
1212 const DWORD errorCode = GetLastError();
1213 qWarning("GetBinaryType() failed with error: 0x%08X", errorCode);
1217 bool MUtils::OS::is_library_file(const QString &path)
1219 const DWORD flags = library_as_image_resource_supported() ? (LOAD_LIBRARY_AS_DATAFILE | LOAD_LIBRARY_AS_IMAGE_RESOURCE) : (LOAD_LIBRARY_AS_DATAFILE | DONT_RESOLVE_DLL_REFERENCES);
1220 if (const HMODULE hMod = LoadLibraryEx(MUTILS_WCHR(QDir::toNativeSeparators(path)), NULL, flags))
1226 const DWORD errorCode = GetLastError();
1227 qWarning("LoadLibraryEx() failed with error: 0x%08X", errorCode);
1231 ///////////////////////////////////////////////////////////////////////////////
1232 // HIBERNATION / SHUTDOWN
1233 ///////////////////////////////////////////////////////////////////////////////
1235 bool MUtils::OS::is_hibernation_supported(void)
1237 bool hibernationSupported = false;
1239 SYSTEM_POWER_CAPABILITIES pwrCaps;
1240 SecureZeroMemory(&pwrCaps, sizeof(SYSTEM_POWER_CAPABILITIES));
1242 if(GetPwrCapabilities(&pwrCaps))
1244 hibernationSupported = pwrCaps.SystemS4 && pwrCaps.HiberFilePresent;
1247 return hibernationSupported;
1250 bool MUtils::OS::shutdown_computer(const QString &message, const unsigned long timeout, const bool forceShutdown, const bool hibernate)
1252 HANDLE hToken = NULL;
1254 if(OpenProcessToken(GetCurrentProcess(), TOKEN_ADJUST_PRIVILEGES | TOKEN_QUERY, &hToken))
1256 TOKEN_PRIVILEGES privileges;
1257 memset(&privileges, 0, sizeof(TOKEN_PRIVILEGES));
1258 privileges.PrivilegeCount = 1;
1259 privileges.Privileges[0].Attributes = SE_PRIVILEGE_ENABLED;
1261 if(LookupPrivilegeValue(NULL, SE_SHUTDOWN_NAME, &privileges.Privileges[0].Luid))
1263 if(AdjustTokenPrivileges(hToken, FALSE, &privileges, NULL, NULL, NULL))
1267 if(SetSuspendState(TRUE, TRUE, TRUE))
1272 const DWORD reason = SHTDN_REASON_MAJOR_APPLICATION | SHTDN_REASON_FLAG_PLANNED;
1273 return InitiateSystemShutdownEx(NULL, const_cast<wchar_t*>(MUTILS_WCHR(message)), timeout, forceShutdown ? TRUE : FALSE, FALSE, reason);
1281 ///////////////////////////////////////////////////////////////////////////////
1283 ///////////////////////////////////////////////////////////////////////////////
1285 bool MUtils::OS::free_diskspace(const QString &path, quint64 &freeSpace)
1287 ULARGE_INTEGER freeBytesAvailable, totalNumberOfBytes, totalNumberOfFreeBytes;
1288 if(GetDiskFreeSpaceExW(reinterpret_cast<const wchar_t*>(QDir::toNativeSeparators(path).utf16()), &freeBytesAvailable, &totalNumberOfBytes, &totalNumberOfFreeBytes))
1290 freeSpace = freeBytesAvailable.QuadPart;
1298 ///////////////////////////////////////////////////////////////////////////////
1300 ///////////////////////////////////////////////////////////////////////////////
1302 static wchar_t get_drive_letter(const QString &path)
1304 QString nativePath = QDir::toNativeSeparators(path);
1305 while (nativePath.startsWith("\\\\?\\") || nativePath.startsWith("\\\\.\\"))
1307 nativePath = QDir::toNativeSeparators(nativePath.mid(4));
1309 if ((path.length() > 1) && (path[1] == QLatin1Char(':')))
1311 const wchar_t letter = static_cast<wchar_t>(path[0].unicode());
1312 if (((letter >= 'A') && (letter <= 'Z')) || ((letter >= 'a') && (letter <= 'z')))
1314 return towupper(letter);
1317 return L'\0'; /*invalid path spec*/
1320 static QSet<DWORD> get_physical_drive_ids(const wchar_t drive_letter)
1322 QSet<DWORD> physical_drives;
1323 wchar_t driveName[8];
1324 _snwprintf_s(driveName, 8, _TRUNCATE, L"\\\\.\\%c:", drive_letter);
1325 const HANDLE hDrive = CreateFileW(driveName, 0, FILE_SHARE_READ | FILE_SHARE_WRITE, NULL, OPEN_EXISTING, 0, NULL);
1326 if (hDrive && (hDrive != INVALID_HANDLE_VALUE))
1328 const size_t BUFF_SIZE = sizeof(VOLUME_DISK_EXTENTS) + (32U * sizeof(DISK_EXTENT));
1329 VOLUME_DISK_EXTENTS *const diskExtents = (VOLUME_DISK_EXTENTS*)_malloca(BUFF_SIZE);
1331 if (DeviceIoControl(hDrive, IOCTL_VOLUME_GET_VOLUME_DISK_EXTENTS, NULL, 0, (LPVOID)diskExtents, (DWORD)BUFF_SIZE, (LPDWORD)&dwSize, NULL))
1333 for (DWORD index = 0U; index < diskExtents->NumberOfDiskExtents; ++index)
1335 physical_drives.insert(diskExtents->Extents[index].DiskNumber);
1338 _freea(diskExtents);
1339 CloseHandle(hDrive);
1341 return physical_drives;
1344 static bool incurs_seek_penalty(const DWORD device_id)
1346 wchar_t driveName[24];
1347 _snwprintf_s(driveName, 24, _TRUNCATE, L"\\\\?\\PhysicalDrive%u", device_id);
1348 const HANDLE hDevice = CreateFileW(driveName, 0, FILE_SHARE_READ | FILE_SHARE_WRITE, NULL, OPEN_EXISTING, 0, NULL);
1349 bool seeking_penalty = true;
1350 if (hDevice && (hDevice != INVALID_HANDLE_VALUE))
1352 STORAGE_PROPERTY_QUERY spq;
1353 DEVICE_SEEK_PENALTY_DESCRIPTOR dspd;
1354 memset(&spq, 0, sizeof(STORAGE_PROPERTY_QUERY));
1355 spq.PropertyId = (STORAGE_PROPERTY_ID)StorageDeviceSeekPenaltyProperty;
1356 spq.QueryType = PropertyStandardQuery;
1358 if (DeviceIoControl(hDevice, IOCTL_STORAGE_QUERY_PROPERTY, (LPVOID)&spq, (DWORD)sizeof(spq), (LPVOID)&dspd, (DWORD)sizeof(dspd), (LPDWORD)&dwSize, NULL))
1360 seeking_penalty = dspd.IncursSeekPenalty;
1362 CloseHandle(hDevice);
1364 return seeking_penalty;
1367 static bool is_fast_seeking_drive(const wchar_t drive_letter)
1369 bool fast_seeking = false;
1370 const QSet<DWORD> physical_drive_ids = get_physical_drive_ids(drive_letter);
1371 if (!physical_drive_ids.empty())
1373 fast_seeking = true;
1374 for (QSet<DWORD>::const_iterator iter = physical_drive_ids.constBegin(); iter != physical_drive_ids.constEnd(); ++iter)
1376 fast_seeking = fast_seeking && (!incurs_seek_penalty(*iter));
1379 return fast_seeking;
1382 MUtils::OS::drive_type_t MUtils::OS::get_drive_type(const QString &path, bool *fast_seeking)
1384 drive_type_t driveType = DRIVE_TYPE_ERR;
1385 const wchar_t driveLetter = get_drive_letter(path);
1388 wchar_t driveName[8];
1389 _snwprintf_s(driveName, 8, _TRUNCATE, L"\\\\.\\%c:\\", driveLetter);
1390 switch (GetDriveTypeW(driveName))
1392 case DRIVE_REMOVABLE: driveType = DRIVE_TYPE_FDD; break;
1393 case DRIVE_FIXED: driveType = DRIVE_TYPE_HDD; break;
1394 case DRIVE_REMOTE: driveType = DRIVE_TYPE_NET; break;
1395 case DRIVE_CDROM: driveType = DRIVE_TYPE_OPT; break;
1396 case DRIVE_RAMDISK: driveType = DRIVE_TYPE_RAM; break;
1401 if (driveType == DRIVE_TYPE_HDD)
1403 *fast_seeking = is_fast_seeking_drive(driveLetter);
1407 *fast_seeking = (driveType == DRIVE_TYPE_RAM);
1413 ///////////////////////////////////////////////////////////////////////////////
1415 ///////////////////////////////////////////////////////////////////////////////
1417 bool MUtils::OS::shell_open(const QWidget *parent, const QString &url, const QString ¶meters, const QString &directory, const bool explore)
1419 return ((int) ShellExecuteW((parent ? reinterpret_cast<HWND>(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;
1422 bool MUtils::OS::shell_open(const QWidget *parent, const QString &url, const bool explore)
1424 return shell_open(parent, url, QString(), QString(), explore);
1427 ///////////////////////////////////////////////////////////////////////////////
1429 ///////////////////////////////////////////////////////////////////////////////
1431 bool MUtils::OS::open_media_file(const QString &mediaFilePath)
1433 const static wchar_t *registryPrefix[2] = { L"SOFTWARE\\", L"SOFTWARE\\Wow6432Node\\" };
1434 const static wchar_t *registryKeys[3] =
1436 L"Microsoft\\Windows\\CurrentVersion\\Uninstall\\{97D341C8-B0D1-4E4A-A49A-C30B52F168E9}",
1437 L"Microsoft\\Windows\\CurrentVersion\\Uninstall\\{DB9E4EAB-2717-499F-8D56-4CC8A644AB60}",
1440 const static wchar_t *appNames[4] = { L"smplayer_portable.exe", L"smplayer.exe", L"MPUI.exe", L"foobar2000.exe" };
1441 const static wchar_t *valueNames[2] = { L"InstallLocation", L"InstallDir" };
1443 for(size_t i = 0; i < 3; i++)
1445 for(size_t j = 0; j < 2; j++)
1447 QString mplayerPath;
1448 HKEY registryKeyHandle = NULL;
1450 const QString currentKey = MUTILS_QSTR(registryPrefix[j]).append(MUTILS_QSTR(registryKeys[i]));
1451 if(RegOpenKeyExW(HKEY_LOCAL_MACHINE, MUTILS_WCHR(currentKey), 0, KEY_READ, ®istryKeyHandle) == ERROR_SUCCESS)
1453 for(size_t k = 0; k < 2; k++)
1455 wchar_t Buffer[4096];
1456 DWORD BuffSize = sizeof(wchar_t*) * 4096;
1457 DWORD DataType = REG_NONE;
1458 if(RegQueryValueExW(registryKeyHandle, valueNames[k], 0, &DataType, reinterpret_cast<BYTE*>(Buffer), &BuffSize) == ERROR_SUCCESS)
1460 if((DataType == REG_SZ) || (DataType == REG_EXPAND_SZ) || (DataType == REG_LINK))
1462 mplayerPath = MUTILS_QSTR(Buffer);
1467 RegCloseKey(registryKeyHandle);
1470 if(!mplayerPath.isEmpty())
1472 QDir mplayerDir(mplayerPath);
1473 if(mplayerDir.exists())
1475 for(size_t k = 0; k < 4; k++)
1477 if(mplayerDir.exists(MUTILS_QSTR(appNames[k])))
1479 qDebug("Player found at:\n%s\n", MUTILS_UTF8(mplayerDir.absoluteFilePath(MUTILS_QSTR(appNames[k]))));
1480 QProcess::startDetached(mplayerDir.absoluteFilePath(MUTILS_QSTR(appNames[k])), QStringList() << QDir::toNativeSeparators(mediaFilePath));
1491 ///////////////////////////////////////////////////////////////////////////////
1493 ///////////////////////////////////////////////////////////////////////////////
1495 static bool change_process_priority_helper(const HANDLE hProcess, const int priority)
1499 switch(qBound(-2, priority, 2))
1502 ok = (SetPriorityClass(hProcess, HIGH_PRIORITY_CLASS) == TRUE);
1505 if(!(ok = (SetPriorityClass(hProcess, ABOVE_NORMAL_PRIORITY_CLASS) == TRUE)))
1507 ok = (SetPriorityClass(hProcess, HIGH_PRIORITY_CLASS) == TRUE);
1511 ok = (SetPriorityClass(hProcess, NORMAL_PRIORITY_CLASS) == TRUE);
1514 if(!(ok = (SetPriorityClass(hProcess, BELOW_NORMAL_PRIORITY_CLASS) == TRUE)))
1516 ok = (SetPriorityClass(hProcess, IDLE_PRIORITY_CLASS) == TRUE);
1520 ok = (SetPriorityClass(hProcess, IDLE_PRIORITY_CLASS) == TRUE);
1527 bool MUtils::OS::change_process_priority(const int priority)
1529 return change_process_priority_helper(GetCurrentProcess(), priority);
1532 bool MUtils::OS::change_process_priority(const QProcess *proc, const int priority)
1534 if(Q_PID qPid = proc->pid())
1536 return change_process_priority_helper(qPid->hProcess, priority);
1544 ///////////////////////////////////////////////////////////////////////////////
1546 ///////////////////////////////////////////////////////////////////////////////
1548 quint32 MUtils::OS::process_id(void)
1550 return GetCurrentProcessId();
1553 quint32 MUtils::OS::process_id(const QProcess *const proc)
1555 PROCESS_INFORMATION *procInf = proc->pid();
1556 return (procInf) ? procInf->dwProcessId : 0;
1559 quint32 MUtils::OS::thread_id(void)
1561 return GetCurrentThreadId();
1564 quint32 MUtils::OS::thread_id(const QProcess *const proc)
1566 PROCESS_INFORMATION *procInf = proc->pid();
1567 return (procInf) ? procInf->dwThreadId : 0;
1570 ///////////////////////////////////////////////////////////////////////////////
1571 // PROCESS SUSPEND/RESUME
1572 ///////////////////////////////////////////////////////////////////////////////
1574 bool MUtils::OS::suspend_process(const QProcess *proc, const bool suspend)
1576 if(Q_PID pid = proc->pid())
1580 return (SuspendThread(pid->hThread) != ((DWORD) -1));
1584 return (ResumeThread(pid->hThread) != ((DWORD) -1));
1593 ///////////////////////////////////////////////////////////////////////////////
1595 ///////////////////////////////////////////////////////////////////////////////
1597 bool MUtils::OS::setup_timer_resolution(const quint32 &interval)
1599 return timeBeginPeriod(interval) == TIMERR_NOERROR;
1602 bool MUtils::OS::reset_timer_resolution(const quint32 &interval)
1604 return timeEndPeriod(interval) == TIMERR_NOERROR;
1607 ///////////////////////////////////////////////////////////////////////////////
1609 ///////////////////////////////////////////////////////////////////////////////
1611 static QScopedPointer<QDateTime> s_epoch;
1612 static QReadWriteLock s_epochLock;
1614 static const QDateTime *get_epoch(void)
1616 QReadLocker rdLock(&s_epochLock);
1618 if (s_epoch.isNull())
1621 QWriteLocker wrLock(&s_epochLock);
1622 if (s_epoch.isNull())
1624 s_epoch.reset(new QDateTime(QDate(1601, 1, 1), QTime(0, 0, 0, 0), Qt::UTC));
1630 return s_epoch.data();
1633 static FILETIME *qt_time_to_file_time(FILETIME *const fileTime, const QDateTime &dateTime)
1635 memset(fileTime, 0, sizeof(FILETIME));
1637 if (const QDateTime *const epoch = get_epoch())
1639 const qint64 msecs = epoch->msecsTo(dateTime);
1642 const quint64 ticks = 10000U * quint64(msecs);
1643 fileTime->dwHighDateTime = ((ticks >> 32) & 0xFFFFFFFF);
1644 fileTime->dwLowDateTime = (ticks & 0xFFFFFFFF);
1652 static bool set_file_time(const HANDLE hFile, const QDateTime &created, const QDateTime &lastMod, const QDateTime &lastAcc)
1654 FILETIME ftCreated, ftLastMod, ftLastAcc;
1656 FILETIME *const pCreated = created.isValid() ? qt_time_to_file_time(&ftCreated, created) : NULL;
1657 FILETIME *const pLastMod = lastMod.isValid() ? qt_time_to_file_time(&ftLastMod, lastMod) : NULL;
1658 FILETIME *const pLastAcc = lastAcc.isValid() ? qt_time_to_file_time(&ftLastAcc, lastAcc) : NULL;
1660 if (pCreated || pLastMod || pLastAcc)
1662 return (SetFileTime(hFile, pCreated, pLastAcc, pLastMod) != FALSE);
1668 bool MUtils::OS::set_file_time(const QFile &file, const QDateTime &created, const QDateTime &lastMod, const QDateTime &lastAcc)
1670 const int fd = file.handle();
1673 return set_file_time((HANDLE)_get_osfhandle(fd), created, lastMod, lastAcc);
1678 bool MUtils::OS::set_file_time(const QString &path, const QDateTime &created, const QDateTime &lastMod, const QDateTime &lastAcc)
1680 const HANDLE hFile = CreateFileW(MUTILS_WCHR(path), FILE_WRITE_ATTRIBUTES, FILE_SHARE_READ, NULL, OPEN_EXISTING, 0, 0);
1682 if ((hFile != NULL) && (hFile != INVALID_HANDLE_VALUE))
1684 okay = set_file_time(hFile, created, lastMod, lastAcc);
1690 ///////////////////////////////////////////////////////////////////////////////
1692 ///////////////////////////////////////////////////////////////////////////////
1694 bool MUtils::OS::check_key_state_esc(void)
1696 return (GetAsyncKeyState(VK_ESCAPE) & 0x0001) != 0;
1699 ///////////////////////////////////////////////////////////////////////////////
1700 // SHELL CHANGE NOTIFICATION
1701 ///////////////////////////////////////////////////////////////////////////////
1703 void MUtils::OS::shell_change_notification(void)
1705 SHChangeNotify(SHCNE_ASSOCCHANGED, SHCNF_IDLIST, NULL, NULL);
1708 ///////////////////////////////////////////////////////////////////////////////
1709 // WOW64 REDIRECTION
1710 ///////////////////////////////////////////////////////////////////////////////
1712 typedef BOOL (_stdcall *Wow64DisableWow64FsRedirectionFun)(void *OldValue);
1713 typedef BOOL (_stdcall *Wow64RevertWow64FsRedirectionFun )(void *OldValue);
1715 bool MUtils::OS::wow64fsredir_disable(void *oldValue)
1717 const Wow64DisableWow64FsRedirectionFun wow64redir_disable = MUtils::Win32Utils::resolve<Wow64DisableWow64FsRedirectionFun>(QLatin1String("kernel32"), QLatin1String("Wow64DisableWow64FsRedirection"));
1718 if(wow64redir_disable)
1720 if (wow64redir_disable(oldValue))
1728 bool MUtils::OS::wow64fsredir_revert(void *oldValue)
1730 const Wow64RevertWow64FsRedirectionFun wow64redir_disable = MUtils::Win32Utils::resolve<Wow64RevertWow64FsRedirectionFun>(QLatin1String("kernel32"), QLatin1String("Wow64RevertWow64FsRedirection"));
1731 if (wow64redir_disable)
1733 if (wow64redir_disable(oldValue))
1741 ///////////////////////////////////////////////////////////////////////////////
1743 ///////////////////////////////////////////////////////////////////////////////
1745 QString MUtils::OS::get_envvar(const QString &name)
1747 wchar_t *buffer = NULL;
1748 size_t requiredSize = 0, buffSize = 0;
1753 //Adjust the buffer size as required first!
1754 if (buffSize < requiredSize)
1760 if (!(buffer = (wchar_t*)_malloca(sizeof(wchar_t) * requiredSize)))
1762 break; /*out of memory error!*/
1764 buffSize = requiredSize;
1767 //Try to fetch the environment variable now
1768 const errno_t error = _wgetenv_s(&requiredSize, buffer, buffSize, MUTILS_WCHR(name));
1771 if (requiredSize > 0)
1773 result = MUTILS_QSTR(buffer);
1777 else if (error != ERANGE)
1779 break; /*somethging else went wrong!*/
1793 bool MUtils::OS::set_envvar(const QString &name, const QString &value)
1795 if (!_wputenv_s(MUTILS_WCHR(name), MUTILS_WCHR(value)))
1802 ///////////////////////////////////////////////////////////////////////////////
1804 ///////////////////////////////////////////////////////////////////////////////
1806 static const QLatin1String NULL_DEVICE("NUL");
1808 const QLatin1String &MUtils::OS::null_device(void)
1813 ///////////////////////////////////////////////////////////////////////////////
1815 ///////////////////////////////////////////////////////////////////////////////
1817 #if (!(MUTILS_DEBUG))
1818 static __forceinline bool is_debugger_present(void)
1822 CloseHandle((HANDLE)((DWORD_PTR)-3));
1829 BOOL bHaveDebugger = FALSE;
1830 if(CheckRemoteDebuggerPresent(GetCurrentProcess(), &bHaveDebugger))
1832 if(bHaveDebugger) return true;
1835 return IsDebuggerPresent();
1837 static __forceinline bool check_debugger_helper(void)
1839 if(is_debugger_present())
1841 MUtils::OS::fatal_exit(L"Not a debug build. Please unload debugger and try again!");
1847 #define check_debugger_helper() (false)
1850 void MUtils::OS::check_debugger(void)
1852 check_debugger_helper();
1855 static volatile bool g_debug_check = check_debugger_helper();
1857 ///////////////////////////////////////////////////////////////////////////////
1859 ///////////////////////////////////////////////////////////////////////////////
1861 static MUtils::Internal::CriticalSection g_fatal_exit_lock;
1862 static QAtomicInt g_fatal_exit_flag;
1864 static DWORD WINAPI fatal_exit_helper(LPVOID lpParameter)
1866 MUtils::OS::system_message_err(L"GURU MEDITATION", (LPWSTR) lpParameter);
1870 void MUtils::OS::fatal_exit(const wchar_t* const errorMessage)
1872 g_fatal_exit_lock.enter();
1874 if(!g_fatal_exit_flag.testAndSetOrdered(0, 1))
1876 return; /*prevent recursive invocation*/
1879 if(g_main_thread_id != GetCurrentThreadId())
1881 if(HANDLE hThreadMain = OpenThread(THREAD_SUSPEND_RESUME, FALSE, g_main_thread_id))
1883 SuspendThread(hThreadMain); /*stop main thread*/
1887 if(HANDLE hThread = CreateThread(NULL, 0, fatal_exit_helper, (LPVOID)errorMessage, 0, NULL))
1889 WaitForSingleObject(hThread, INFINITE);
1893 fatal_exit_helper((LPVOID)errorMessage);
1898 TerminateProcess(GetCurrentProcess(), 666);
1902 ///////////////////////////////////////////////////////////////////////////////