1 ///////////////////////////////////////////////////////////////////////////////
2 // MuldeR's Utilities for Qt
3 // Copyright (C) 2004-2015 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
31 #pragma warning(disable:4091) //for MSVC2015
36 #include <MUtils/Global.h>
37 #include <MUtils/OSSupport.h>
38 #include <MUtils/GUI.h>
39 #include "CriticalSection_Win32.h"
43 #include <QReadWriteLock>
50 static const DWORD g_main_thread_id = GetCurrentThreadId();
52 ///////////////////////////////////////////////////////////////////////////////
54 ///////////////////////////////////////////////////////////////////////////////
56 static const UINT g_msgBoxFlags = MB_TOPMOST | MB_TASKMODAL | MB_SETFOREGROUND;
58 void MUtils::OS::system_message_nfo(const wchar_t *const title, const wchar_t *const text)
60 MessageBoxW(NULL, text, title, g_msgBoxFlags | MB_ICONINFORMATION);
63 void MUtils::OS::system_message_wrn(const wchar_t *const title, const wchar_t *const text)
65 MessageBoxW(NULL, text, title, g_msgBoxFlags | MB_ICONWARNING);
68 void MUtils::OS::system_message_err(const wchar_t *const title, const wchar_t *const text)
70 MessageBoxW(NULL, text, title, g_msgBoxFlags | MB_ICONERROR);
73 ///////////////////////////////////////////////////////////////////////////////
74 // FETCH CLI ARGUMENTS
75 ///////////////////////////////////////////////////////////////////////////////
77 static QReadWriteLock g_arguments_lock;
78 static QScopedPointer<MUtils::OS::ArgumentMap> g_arguments_list;
80 const QStringList MUtils::OS::crack_command_line(const QString &command_line)
83 LPWSTR *szArglist = CommandLineToArgvW(command_line.isNull() ? GetCommandLineW() : MUTILS_WCHR(command_line), &nArgs);
85 QStringList command_line_tokens;
88 for(int i = 0; i < nArgs; i++)
90 const QString argStr = MUTILS_QSTR(szArglist[i]).trimmed();
93 command_line_tokens << argStr;
99 return command_line_tokens;
102 const MUtils::OS::ArgumentMap &MUtils::OS::arguments(void)
104 QReadLocker readLock(&g_arguments_lock);
106 //Already initialized?
107 if(!g_arguments_list.isNull())
109 return (*(g_arguments_list.data()));
113 QWriteLocker writeLock(&g_arguments_lock);
115 //Still not initialized?
116 if(!g_arguments_list.isNull())
118 return (*(g_arguments_list.data()));
121 g_arguments_list.reset(new ArgumentMap());
123 const QStringList argList = crack_command_line();
125 if(argList.count() > 1)
127 const QString argPrefix = QLatin1String("--");
128 const QChar separator = QLatin1Char('=');
130 for(int i = 1; i < nArgs; i++)
132 const QString &argStr = argList[i];
133 if(argStr.startsWith(argPrefix))
135 const QString argData = argStr.mid(2).trimmed();
136 if(argData.length() > 0)
138 const int separatorIndex = argData.indexOf(separator);
139 if(separatorIndex > 0)
141 const QString argKey = argData.left(separatorIndex).trimmed();
142 const QString argVal = argData.mid(separatorIndex + 1).trimmed();
143 g_arguments_list->insertMulti(argKey.toLower(), argVal);
147 g_arguments_list->insertMulti(argData.toLower(), QString());
153 else if(argList.empty())
155 qWarning("CommandLineToArgvW() has failed !!!");
158 return (*(g_arguments_list.data()));
161 ///////////////////////////////////////////////////////////////////////////////
163 ///////////////////////////////////////////////////////////////////////////////
165 typedef struct _progress_callback_data_t
167 MUtils::OS::progress_callback_t callback_function;
170 progress_callback_data_t;
172 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)
174 if(const progress_callback_data_t *data = (progress_callback_data_t*) lpData)
176 const double progress = qBound(0.0, double(TotalBytesTransferred.QuadPart) / double(TotalFileSize.QuadPart), 1.0);
177 return data->callback_function(progress, data->user_data) ? PROGRESS_CONTINUE : PROGRESS_CANCEL;
179 return PROGRESS_CONTINUE;
182 MUTILS_API bool MUtils::OS::copy_file(const QString &sourcePath, const QString &outputPath, const bool &overwrite, const progress_callback_t callback, void *const userData)
184 progress_callback_data_t callback_data = { callback, userData };
186 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));
190 const DWORD errorCode = GetLastError();
191 if(errorCode != ERROR_REQUEST_ABORTED)
193 qWarning("CopyFile() failed with error code 0x%08X!", errorCode);
197 qWarning("CopyFile() operation was abroted by user!");
201 return (result != FALSE);
204 ///////////////////////////////////////////////////////////////////////////////
206 ///////////////////////////////////////////////////////////////////////////////
208 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)
210 if(!GetFileVersionInfo(MUTILS_WCHR(fileName), 0, size, buffer))
212 qWarning("GetFileVersionInfo() has failed, file version cannot be determined!");
216 VS_FIXEDFILEINFO *verInfo;
218 if(!VerQueryValue(buffer, L"\\", (LPVOID*)(&verInfo), &verInfoLen))
220 qWarning("VerQueryValue() has failed, file version cannot be determined!");
224 if(major) *major = quint16((verInfo->dwFileVersionMS >> 16) & 0x0000FFFF);
225 if(minor) *minor = quint16((verInfo->dwFileVersionMS) & 0x0000FFFF);
226 if(patch) *patch = quint16((verInfo->dwFileVersionLS >> 16) & 0x0000FFFF);
227 if(build) *build = quint16((verInfo->dwFileVersionLS) & 0x0000FFFF);
232 bool MUtils::OS::get_file_version(const QString fileName, quint16 *const major, quint16 *const minor, quint16 *const patch, quint16 *const build)
234 if(major) *major = 0U; if(minor) *minor = 0U;
235 if(patch) *patch = 0U; if(build) *build = 0U;
237 const DWORD size = GetFileVersionInfoSize(MUTILS_WCHR(fileName), NULL);
240 qWarning("GetFileVersionInfoSize() has failed, file version cannot be determined!");
244 PVOID buffer = _malloca(size);
247 qWarning("Memory allocation has failed!");
251 const bool success = get_file_version_helper(fileName, buffer, size, major, minor, patch, build);
257 ///////////////////////////////////////////////////////////////////////////////
258 // OS VERSION DETECTION
259 ///////////////////////////////////////////////////////////////////////////////
261 static bool g_os_version_initialized = false;
262 static MUtils::OS::Version::os_version_t g_os_version_info = MUtils::OS::Version::UNKNOWN_OPSYS;
263 static QReadWriteLock g_os_version_lock;
265 //Maps marketing names to the actual Windows NT versions
268 MUtils::OS::Version::os_version_t version;
269 const char friendlyName[64];
273 { MUtils::OS::Version::WINDOWS_WIN2K, "Windows 2000" }, //2000
274 { MUtils::OS::Version::WINDOWS_WINXP, "Windows XP or Windows XP Media Center Edition" }, //XP
275 { MUtils::OS::Version::WINDOWS_XPX64, "Windows Server 2003 or Windows XP x64" }, //XP_x64
276 { MUtils::OS::Version::WINDOWS_VISTA, "Windows Vista or Windows Server 2008" }, //Vista
277 { MUtils::OS::Version::WINDOWS_WIN70, "Windows 7 or Windows Server 2008 R2" }, //7
278 { MUtils::OS::Version::WINDOWS_WIN80, "Windows 8 or Windows Server 2012" }, //8
279 { MUtils::OS::Version::WINDOWS_WIN81, "Windows 8.1 or Windows Server 2012 R2" }, //8.1
280 { MUtils::OS::Version::WINDOWS_WN100, "Windows 10 or Windows Server 2014 (Preview)" }, //10
281 { MUtils::OS::Version::UNKNOWN_OPSYS, "N/A" }
284 //OS version data dtructures
291 //Comparision operators for os_version_t
292 bool os_version_t::operator== (const os_version_t &rhs) const { return (type == rhs.type) && (versionMajor == rhs.versionMajor) && ((versionMinor == rhs.versionMinor)); }
293 bool os_version_t::operator!= (const os_version_t &rhs) const { return (type != rhs.type) || (versionMajor != rhs.versionMajor) || ((versionMinor != rhs.versionMinor)); }
294 bool os_version_t::operator> (const os_version_t &rhs) const { return (type == rhs.type) && ((versionMajor > rhs.versionMajor) || ((versionMajor == rhs.versionMajor) && (versionMinor > rhs.versionMinor))); }
295 bool os_version_t::operator>= (const os_version_t &rhs) const { return (type == rhs.type) && ((versionMajor > rhs.versionMajor) || ((versionMajor == rhs.versionMajor) && (versionMinor >= rhs.versionMinor))); }
296 bool os_version_t::operator< (const os_version_t &rhs) const { return (type == rhs.type) && ((versionMajor < rhs.versionMajor) || ((versionMajor == rhs.versionMajor) && (versionMinor < rhs.versionMinor))); }
297 bool os_version_t::operator<= (const os_version_t &rhs) const { return (type == rhs.type) && ((versionMajor < rhs.versionMajor) || ((versionMajor == rhs.versionMajor) && (versionMinor <= rhs.versionMinor))); }
299 //Known Windows NT versions
300 const os_version_t WINDOWS_WIN2K = { OS_WINDOWS, 5, 0 }; // 2000
301 const os_version_t WINDOWS_WINXP = { OS_WINDOWS, 5, 1 }; // XP
302 const os_version_t WINDOWS_XPX64 = { OS_WINDOWS, 5, 2 }; // XP_x64
303 const os_version_t WINDOWS_VISTA = { OS_WINDOWS, 6, 0 }; // Vista
304 const os_version_t WINDOWS_WIN70 = { OS_WINDOWS, 6, 1 }; // 7
305 const os_version_t WINDOWS_WIN80 = { OS_WINDOWS, 6, 2 }; // 8
306 const os_version_t WINDOWS_WIN81 = { OS_WINDOWS, 6, 3 }; // 8.1
307 const os_version_t WINDOWS_WN100 = { OS_WINDOWS, 10, 0 }; // 10
310 const os_version_t UNKNOWN_OPSYS = { OS_UNKNOWN, 0, 0 }; // N/A
315 static bool verify_os_version(const DWORD major, const DWORD minor)
317 OSVERSIONINFOEXW osvi;
318 DWORDLONG dwlConditionMask = 0;
320 //Initialize the OSVERSIONINFOEX structure
321 memset(&osvi, 0, sizeof(OSVERSIONINFOEXW));
322 osvi.dwOSVersionInfoSize = sizeof(OSVERSIONINFOEXW);
323 osvi.dwMajorVersion = major;
324 osvi.dwMinorVersion = minor;
325 osvi.dwPlatformId = VER_PLATFORM_WIN32_NT;
327 //Initialize the condition mask
328 VER_SET_CONDITION(dwlConditionMask, VER_MAJORVERSION, VER_GREATER_EQUAL);
329 VER_SET_CONDITION(dwlConditionMask, VER_MINORVERSION, VER_GREATER_EQUAL);
330 VER_SET_CONDITION(dwlConditionMask, VER_PLATFORMID, VER_EQUAL);
333 const BOOL ret = VerifyVersionInfoW(&osvi, VER_MAJORVERSION | VER_MINORVERSION | VER_PLATFORMID, dwlConditionMask);
338 if(GetLastError() != ERROR_OLD_WIN_VERSION)
340 qWarning("VerifyVersionInfo() system call has failed!");
344 return (ret != FALSE);
347 static bool get_real_os_version(unsigned int *major, unsigned int *minor, bool *pbOverride)
352 //Initialize local variables
353 OSVERSIONINFOEXW osvi;
354 memset(&osvi, 0, sizeof(OSVERSIONINFOEXW));
355 osvi.dwOSVersionInfoSize = sizeof(OSVERSIONINFOEXW);
357 //Try GetVersionEx() first
358 if(GetVersionExW((LPOSVERSIONINFOW)&osvi) == FALSE)
360 qWarning("GetVersionEx() has failed, cannot detect Windows version!");
364 //Make sure we are running on NT
365 if(osvi.dwPlatformId == VER_PLATFORM_WIN32_NT)
367 *major = osvi.dwMajorVersion;
368 *minor = osvi.dwMinorVersion;
372 qWarning("Not running on Windows NT, unsupported operating system!");
376 //Determine the real *major* version first
379 const DWORD nextMajor = (*major) + 1;
380 if(verify_os_version(nextMajor, 0))
390 //Now also determine the real *minor* version
393 const DWORD nextMinor = (*minor) + 1;
394 if(verify_os_version((*major), nextMinor))
403 //Workaround for the mess that is sometimes referred to as "Windows 10"
404 if(((*major) > 6) || (((*major) == 6) && ((*minor) >= 2)))
406 quint16 kernel32_major, kernel32_minor;
407 if(MUtils::OS::get_file_version(QLatin1String("kernel32"), &kernel32_major, &kernel32_minor))
409 if((kernel32_major > (*major)) || ((kernel32_major == (*major)) && (kernel32_minor > (*minor))))
411 *major = kernel32_major;
412 *minor = kernel32_minor;
421 const MUtils::OS::Version::os_version_t &MUtils::OS::os_version(void)
423 QReadLocker readLock(&g_os_version_lock);
425 //Already initialized?
426 if(g_os_version_initialized)
428 return g_os_version_info;
432 QWriteLocker writeLock(&g_os_version_lock);
435 if(g_os_version_initialized)
437 return g_os_version_info;
441 unsigned int major, minor; bool overrideFlg;
442 if(get_real_os_version(&major, &minor, &overrideFlg))
444 g_os_version_info.type = Version::OS_WINDOWS;
445 g_os_version_info.versionMajor = major;
446 g_os_version_info.versionMinor = minor;
447 g_os_version_info.overrideFlag = overrideFlg;
451 qWarning("Failed to determin the operating system version!");
455 g_os_version_initialized = true;
456 return g_os_version_info;
459 const char *MUtils::OS::os_friendly_name(const MUtils::OS::Version::os_version_t &os_version)
461 for(size_t i = 0; g_os_version_lut[i].version != MUtils::OS::Version::UNKNOWN_OPSYS; i++)
463 if(os_version == g_os_version_lut[i].version)
465 return g_os_version_lut[i].friendlyName;
472 ///////////////////////////////////////////////////////////////////////////////
474 ///////////////////////////////////////////////////////////////////////////////
476 static bool g_wine_deteced = false;
477 static bool g_wine_initialized = false;
478 static QReadWriteLock g_wine_lock;
480 static const bool detect_wine(void)
482 bool is_wine = false;
484 QLibrary ntdll("ntdll.dll");
487 if(ntdll.resolve("wine_nt_to_unix_file_name") != NULL) is_wine = true;
488 if(ntdll.resolve("wine_get_version") != NULL) is_wine = true;
495 const bool &MUtils::OS::running_on_wine(void)
497 QReadLocker readLock(&g_wine_lock);
499 //Already initialized?
500 if(g_wine_initialized)
502 return g_wine_deteced;
506 QWriteLocker writeLock(&g_wine_lock);
509 if(g_wine_initialized)
511 return g_wine_deteced;
515 g_wine_deteced = detect_wine();
516 g_wine_initialized = true;
518 return g_wine_deteced;
521 ///////////////////////////////////////////////////////////////////////////////
523 ///////////////////////////////////////////////////////////////////////////////
525 typedef QMap<size_t, QString> KFMap;
526 typedef HRESULT (WINAPI *SHGetKnownFolderPath_t)(const GUID &rfid, DWORD dwFlags, HANDLE hToken, PWSTR *ppszPath);
527 typedef HRESULT (WINAPI *SHGetFolderPath_t)(HWND hwndOwner, int nFolder, HANDLE hToken, DWORD dwFlags, LPWSTR pszPath);
529 static QScopedPointer<KFMap> g_known_folders_map;
530 static SHGetKnownFolderPath_t g_known_folders_fpGetKnownFolderPath;
531 static SHGetFolderPath_t g_known_folders_fpGetFolderPath;
532 static QReadWriteLock g_known_folders_lock;
534 const QString &MUtils::OS::known_folder(known_folder_t folder_id)
536 typedef enum { KF_FLAG_CREATE = 0x00008000 } kf_flags_t;
545 { 0x001c, {0xF1B32785,0x6FBA,0x4FCF,{0x9D,0x55,0x7B,0x8E,0x7F,0x15,0x70,0x91}} }, //CSIDL_LOCAL_APPDATA
546 { 0x0026, {0x905e63b6,0xc1bf,0x494e,{0xb2,0x9c,0x65,0xb7,0x32,0xd3,0xd2,0x1a}} }, //CSIDL_PROGRAM_FILES
547 { 0x0024, {0xF38BF404,0x1D43,0x42F2,{0x93,0x05,0x67,0xDE,0x0B,0x28,0xFC,0x23}} }, //CSIDL_WINDOWS_FOLDER
548 { 0x0025, {0x1AC14E77,0x02E7,0x4E5D,{0xB7,0x44,0x2E,0xB1,0xAE,0x51,0x98,0xB7}} }, //CSIDL_SYSTEM_FOLDER
551 size_t folderId = size_t(-1);
555 case FOLDER_LOCALAPPDATA: folderId = 0; break;
556 case FOLDER_PROGRAMFILES: folderId = 1; break;
557 case FOLDER_SYSTROOT_DIR: folderId = 2; break;
558 case FOLDER_SYSTEMFOLDER: folderId = 3; break;
561 if(folderId == size_t(-1))
563 qWarning("Invalid 'known' folder was requested!");
564 return *reinterpret_cast<QString*>(NULL);
567 QReadLocker readLock(&g_known_folders_lock);
570 if(!g_known_folders_map.isNull())
572 if(g_known_folders_map->contains(folderId))
574 return g_known_folders_map->operator[](folderId);
578 //Obtain write lock to initialize
580 QWriteLocker writeLock(&g_known_folders_lock);
582 //Still not in cache?
583 if(!g_known_folders_map.isNull())
585 if(g_known_folders_map->contains(folderId))
587 return g_known_folders_map->operator[](folderId);
591 //Initialize on first call
592 if(g_known_folders_map.isNull())
594 QLibrary shell32("shell32.dll");
597 g_known_folders_fpGetFolderPath = (SHGetFolderPath_t) shell32.resolve("SHGetFolderPathW");
598 g_known_folders_fpGetKnownFolderPath = (SHGetKnownFolderPath_t) shell32.resolve("SHGetKnownFolderPath");
600 g_known_folders_map.reset(new QMap<size_t, QString>());
605 //Now try to get the folder path!
606 if(g_known_folders_fpGetKnownFolderPath)
609 if(g_known_folders_fpGetKnownFolderPath(s_folders[folderId].guid, KF_FLAG_CREATE, NULL, &path) == S_OK)
611 //MessageBoxW(0, path, L"SHGetKnownFolderPath", MB_TOPMOST);
612 QDir folderTemp = QDir(QDir::fromNativeSeparators(MUTILS_QSTR(path)));
613 if(folderTemp.exists())
615 folderPath = folderTemp.canonicalPath();
620 else if(g_known_folders_fpGetFolderPath)
622 QScopedArrayPointer<WCHAR> path(new WCHAR[4096]);
623 if(g_known_folders_fpGetFolderPath(NULL, s_folders[folderId].csidl | CSIDL_FLAG_CREATE, NULL, NULL, path.data()) == S_OK)
625 //MessageBoxW(0, path, L"SHGetFolderPathW", MB_TOPMOST);
626 QDir folderTemp = QDir(QDir::fromNativeSeparators(MUTILS_QSTR(path.data())));
627 if(folderTemp.exists())
629 folderPath = folderTemp.canonicalPath();
635 g_known_folders_map->insert(folderId, folderPath);
636 return g_known_folders_map->operator[](folderId);
639 ///////////////////////////////////////////////////////////////////////////////
640 // CURRENT DATA & TIME
641 ///////////////////////////////////////////////////////////////////////////////
643 QDate MUtils::OS::current_date(void)
645 const DWORD MAX_PROC = 1024;
646 QScopedArrayPointer<DWORD> processes(new DWORD[MAX_PROC]);
647 DWORD bytesReturned = 0;
649 if(!EnumProcesses(processes.data(), sizeof(DWORD) * MAX_PROC, &bytesReturned))
651 return QDate::currentDate();
654 const DWORD procCount = bytesReturned / sizeof(DWORD);
655 ULARGE_INTEGER lastStartTime;
656 memset(&lastStartTime, 0, sizeof(ULARGE_INTEGER));
658 for(DWORD i = 0; i < procCount; i++)
660 if(HANDLE hProc = OpenProcess(PROCESS_QUERY_INFORMATION, FALSE, processes[i]))
662 FILETIME processTime[4];
663 if(GetProcessTimes(hProc, &processTime[0], &processTime[1], &processTime[2], &processTime[3]))
665 ULARGE_INTEGER timeCreation;
666 timeCreation.LowPart = processTime[0].dwLowDateTime;
667 timeCreation.HighPart = processTime[0].dwHighDateTime;
668 if(timeCreation.QuadPart > lastStartTime.QuadPart)
670 lastStartTime.QuadPart = timeCreation.QuadPart;
677 FILETIME lastStartTime_fileTime;
678 lastStartTime_fileTime.dwHighDateTime = lastStartTime.HighPart;
679 lastStartTime_fileTime.dwLowDateTime = lastStartTime.LowPart;
681 FILETIME lastStartTime_localTime;
682 if(!FileTimeToLocalFileTime(&lastStartTime_fileTime, &lastStartTime_localTime))
684 memcpy(&lastStartTime_localTime, &lastStartTime_fileTime, sizeof(FILETIME));
687 SYSTEMTIME lastStartTime_system;
688 if(!FileTimeToSystemTime(&lastStartTime_localTime, &lastStartTime_system))
690 memset(&lastStartTime_system, 0, sizeof(SYSTEMTIME));
691 lastStartTime_system.wYear = 1970; lastStartTime_system.wMonth = lastStartTime_system.wDay = 1;
694 const QDate currentDate = QDate::currentDate();
695 const QDate processDate = QDate(lastStartTime_system.wYear, lastStartTime_system.wMonth, lastStartTime_system.wDay);
696 return (currentDate >= processDate) ? currentDate : processDate;
699 quint64 MUtils::OS::current_file_time(void)
702 GetSystemTimeAsFileTime(&fileTime);
705 temp.HighPart = fileTime.dwHighDateTime;
706 temp.LowPart = fileTime.dwLowDateTime;
708 return temp.QuadPart;
711 ///////////////////////////////////////////////////////////////////////////////
713 ///////////////////////////////////////////////////////////////////////////////
715 static bool user_is_admin_helper(void)
717 HANDLE hToken = NULL;
718 if(!OpenProcessToken(GetCurrentProcess(), TOKEN_QUERY, &hToken))
724 if(!GetTokenInformation(hToken, TokenGroups, NULL, 0, &dwSize))
726 if(GetLastError() != ERROR_INSUFFICIENT_BUFFER)
733 PTOKEN_GROUPS lpGroups = (PTOKEN_GROUPS) malloc(dwSize);
740 if(!GetTokenInformation(hToken, TokenGroups, lpGroups, dwSize, &dwSize))
747 PSID lpSid = NULL; SID_IDENTIFIER_AUTHORITY Authority = {SECURITY_NT_AUTHORITY};
748 if(!AllocateAndInitializeSid(&Authority, 2, SECURITY_BUILTIN_DOMAIN_RID, DOMAIN_ALIAS_RID_ADMINS, 0, 0, 0, 0, 0, 0, &lpSid))
755 bool bResult = false;
756 for(DWORD i = 0; i < lpGroups->GroupCount; i++)
758 if(EqualSid(lpSid, lpGroups->Groups[i].Sid))
771 bool MUtils::OS::is_elevated(bool *bIsUacEnabled)
775 *bIsUacEnabled = false;
778 bool bIsProcessElevated = false;
779 HANDLE hToken = NULL;
781 if(OpenProcessToken(GetCurrentProcess(), TOKEN_QUERY, &hToken))
783 TOKEN_ELEVATION_TYPE tokenElevationType;
785 if(GetTokenInformation(hToken, TokenElevationType, &tokenElevationType, sizeof(TOKEN_ELEVATION_TYPE), &returnLength))
787 if(returnLength == sizeof(TOKEN_ELEVATION_TYPE))
789 switch(tokenElevationType)
791 case TokenElevationTypeDefault:
792 qDebug("Process token elevation type: Default -> UAC is disabled.\n");
794 case TokenElevationTypeFull:
795 qWarning("Process token elevation type: Full -> potential security risk!\n");
796 bIsProcessElevated = true;
797 if(bIsUacEnabled) *bIsUacEnabled = true;
799 case TokenElevationTypeLimited:
800 qDebug("Process token elevation type: Limited -> not elevated.\n");
801 if(bIsUacEnabled) *bIsUacEnabled = true;
804 qWarning("Unknown tokenElevationType value: %d", tokenElevationType);
810 qWarning("GetTokenInformation() return an unexpected size!");
817 qWarning("Failed to open process token!");
820 return bIsProcessElevated;
823 bool MUtils::OS::user_is_admin(void)
825 bool isAdmin = false;
827 //Check for process elevation and UAC support first!
828 if(MUtils::OS::is_elevated(&isAdmin))
830 qWarning("Process is elevated -> user is admin!");
834 //If not elevated and UAC is not available -> user must be in admin group!
837 qDebug("UAC is disabled/unavailable -> checking for Administrators group");
838 isAdmin = user_is_admin_helper();
844 ///////////////////////////////////////////////////////////////////////////////
846 ///////////////////////////////////////////////////////////////////////////////
848 int MUtils::OS::network_status(void)
851 const BOOL ret = IsNetworkAlive(&dwFlags);
852 if(GetLastError() == 0)
854 return (ret != FALSE) ? NETWORK_TYPE_YES : NETWORK_TYPE_NON;
856 return NETWORK_TYPE_ERR;
859 ///////////////////////////////////////////////////////////////////////////////
861 ///////////////////////////////////////////////////////////////////////////////
863 bool MUtils::OS::handle_os_message(const void *const message, long *result)
865 const MSG *const msg = reinterpret_cast<const MSG*>(message);
869 case WM_QUERYENDSESSION:
870 qWarning("WM_QUERYENDSESSION message received!");
871 *result = MUtils::GUI::broadcast(MUtils::GUI::USER_EVENT_QUERYENDSESSION, false) ? TRUE : FALSE;
874 qWarning("WM_ENDSESSION message received!");
875 if(msg->wParam == TRUE)
877 MUtils::GUI::broadcast(MUtils::GUI::USER_EVENT_ENDSESSION, false);
878 MUtils::GUI::force_quit();
884 /*ignore this message and let Qt handle it*/
889 ///////////////////////////////////////////////////////////////////////////////
891 ///////////////////////////////////////////////////////////////////////////////
893 void MUtils::OS::sleep_ms(const size_t &duration)
895 Sleep((DWORD) duration);
898 ///////////////////////////////////////////////////////////////////////////////
900 ///////////////////////////////////////////////////////////////////////////////
902 bool MUtils::OS::is_executable_file(const QString &path)
904 bool bIsExecutable = false;
906 if(GetBinaryType(MUTILS_WCHR(QDir::toNativeSeparators(path)), &binaryType))
908 bIsExecutable = (binaryType == SCS_32BIT_BINARY || binaryType == SCS_64BIT_BINARY);
910 return bIsExecutable;
913 ///////////////////////////////////////////////////////////////////////////////
914 // HIBERNATION / SHUTDOWN
915 ///////////////////////////////////////////////////////////////////////////////
917 bool MUtils::OS::is_hibernation_supported(void)
919 bool hibernationSupported = false;
921 SYSTEM_POWER_CAPABILITIES pwrCaps;
922 SecureZeroMemory(&pwrCaps, sizeof(SYSTEM_POWER_CAPABILITIES));
924 if(GetPwrCapabilities(&pwrCaps))
926 hibernationSupported = pwrCaps.SystemS4 && pwrCaps.HiberFilePresent;
929 return hibernationSupported;
932 bool MUtils::OS::shutdown_computer(const QString &message, const unsigned long timeout, const bool forceShutdown, const bool hibernate)
934 HANDLE hToken = NULL;
936 if(OpenProcessToken(GetCurrentProcess(), TOKEN_ADJUST_PRIVILEGES | TOKEN_QUERY, &hToken))
938 TOKEN_PRIVILEGES privileges;
939 memset(&privileges, 0, sizeof(TOKEN_PRIVILEGES));
940 privileges.PrivilegeCount = 1;
941 privileges.Privileges[0].Attributes = SE_PRIVILEGE_ENABLED;
943 if(LookupPrivilegeValue(NULL, SE_SHUTDOWN_NAME, &privileges.Privileges[0].Luid))
945 if(AdjustTokenPrivileges(hToken, FALSE, &privileges, NULL, NULL, NULL))
949 if(SetSuspendState(TRUE, TRUE, TRUE))
954 const DWORD reason = SHTDN_REASON_MAJOR_APPLICATION | SHTDN_REASON_FLAG_PLANNED;
955 return InitiateSystemShutdownEx(NULL, const_cast<wchar_t*>(MUTILS_WCHR(message)), timeout, forceShutdown ? TRUE : FALSE, FALSE, reason);
963 ///////////////////////////////////////////////////////////////////////////////
965 ///////////////////////////////////////////////////////////////////////////////
967 bool MUtils::OS::free_diskspace(const QString &path, quint64 &freeSpace)
969 ULARGE_INTEGER freeBytesAvailable, totalNumberOfBytes, totalNumberOfFreeBytes;
970 if(GetDiskFreeSpaceExW(reinterpret_cast<const wchar_t*>(QDir::toNativeSeparators(path).utf16()), &freeBytesAvailable, &totalNumberOfBytes, &totalNumberOfFreeBytes))
972 freeSpace = freeBytesAvailable.QuadPart;
980 ///////////////////////////////////////////////////////////////////////////////
982 ///////////////////////////////////////////////////////////////////////////////
984 bool MUtils::OS::shell_open(const QWidget *parent, const QString &url, const QString ¶meters, const QString &directory, const bool explore)
986 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;
989 bool MUtils::OS::shell_open(const QWidget *parent, const QString &url, const bool explore)
991 return shell_open(parent, url, QString(), QString(), explore);
994 ///////////////////////////////////////////////////////////////////////////////
996 ///////////////////////////////////////////////////////////////////////////////
998 bool MUtils::OS::open_media_file(const QString &mediaFilePath)
1000 const static wchar_t *registryPrefix[2] = { L"SOFTWARE\\", L"SOFTWARE\\Wow6432Node\\" };
1001 const static wchar_t *registryKeys[3] =
1003 L"Microsoft\\Windows\\CurrentVersion\\Uninstall\\{97D341C8-B0D1-4E4A-A49A-C30B52F168E9}",
1004 L"Microsoft\\Windows\\CurrentVersion\\Uninstall\\{DB9E4EAB-2717-499F-8D56-4CC8A644AB60}",
1007 const static wchar_t *appNames[4] = { L"smplayer_portable.exe", L"smplayer.exe", L"MPUI.exe", L"foobar2000.exe" };
1008 const static wchar_t *valueNames[2] = { L"InstallLocation", L"InstallDir" };
1010 for(size_t i = 0; i < 3; i++)
1012 for(size_t j = 0; j < 2; j++)
1014 QString mplayerPath;
1015 HKEY registryKeyHandle = NULL;
1017 const QString currentKey = MUTILS_QSTR(registryPrefix[j]).append(MUTILS_QSTR(registryKeys[i]));
1018 if(RegOpenKeyExW(HKEY_LOCAL_MACHINE, MUTILS_WCHR(currentKey), 0, KEY_READ, ®istryKeyHandle) == ERROR_SUCCESS)
1020 for(size_t k = 0; k < 2; k++)
1022 wchar_t Buffer[4096];
1023 DWORD BuffSize = sizeof(wchar_t*) * 4096;
1024 DWORD DataType = REG_NONE;
1025 if(RegQueryValueExW(registryKeyHandle, valueNames[k], 0, &DataType, reinterpret_cast<BYTE*>(Buffer), &BuffSize) == ERROR_SUCCESS)
1027 if((DataType == REG_SZ) || (DataType == REG_EXPAND_SZ) || (DataType == REG_LINK))
1029 mplayerPath = MUTILS_QSTR(Buffer);
1034 RegCloseKey(registryKeyHandle);
1037 if(!mplayerPath.isEmpty())
1039 QDir mplayerDir(mplayerPath);
1040 if(mplayerDir.exists())
1042 for(size_t k = 0; k < 4; k++)
1044 if(mplayerDir.exists(MUTILS_QSTR(appNames[k])))
1046 qDebug("Player found at:\n%s\n", MUTILS_UTF8(mplayerDir.absoluteFilePath(MUTILS_QSTR(appNames[k]))));
1047 QProcess::startDetached(mplayerDir.absoluteFilePath(MUTILS_QSTR(appNames[k])), QStringList() << QDir::toNativeSeparators(mediaFilePath));
1058 ///////////////////////////////////////////////////////////////////////////////
1060 ///////////////////////////////////////////////////////////////////////////////
1062 static bool change_process_priority_helper(const HANDLE hProcess, const int priority)
1066 switch(qBound(-2, priority, 2))
1069 ok = (SetPriorityClass(hProcess, HIGH_PRIORITY_CLASS) == TRUE);
1072 if(!(ok = (SetPriorityClass(hProcess, ABOVE_NORMAL_PRIORITY_CLASS) == TRUE)))
1074 ok = (SetPriorityClass(hProcess, HIGH_PRIORITY_CLASS) == TRUE);
1078 ok = (SetPriorityClass(hProcess, NORMAL_PRIORITY_CLASS) == TRUE);
1081 if(!(ok = (SetPriorityClass(hProcess, BELOW_NORMAL_PRIORITY_CLASS) == TRUE)))
1083 ok = (SetPriorityClass(hProcess, IDLE_PRIORITY_CLASS) == TRUE);
1087 ok = (SetPriorityClass(hProcess, IDLE_PRIORITY_CLASS) == TRUE);
1094 bool MUtils::OS::change_process_priority(const int priority)
1096 return change_process_priority_helper(GetCurrentProcess(), priority);
1099 bool MUtils::OS::change_process_priority(const QProcess *proc, const int priority)
1101 if(Q_PID qPid = proc->pid())
1103 return change_process_priority_helper(qPid->hProcess, priority);
1111 ///////////////////////////////////////////////////////////////////////////////
1113 ///////////////////////////////////////////////////////////////////////////////
1115 quint32 MUtils::OS::process_id(const QProcess *const proc)
1117 PROCESS_INFORMATION *procInf = proc->pid();
1118 return (procInf) ? procInf->dwProcessId : NULL;
1121 ///////////////////////////////////////////////////////////////////////////////
1122 // PROCESS SUSPEND/RESUME
1123 ///////////////////////////////////////////////////////////////////////////////
1125 bool MUtils::OS::suspend_process(const QProcess *proc, const bool suspend)
1127 if(Q_PID pid = proc->pid())
1131 return (SuspendThread(pid->hThread) != ((DWORD) -1));
1135 return (ResumeThread(pid->hThread) != ((DWORD) -1));
1144 ///////////////////////////////////////////////////////////////////////////////
1146 ///////////////////////////////////////////////////////////////////////////////
1148 bool MUtils::OS::setup_timer_resolution(const quint32 &interval)
1150 return timeBeginPeriod(interval) == TIMERR_NOERROR;
1153 bool MUtils::OS::reset_timer_resolution(const quint32 &interval)
1155 return timeEndPeriod(interval) == TIMERR_NOERROR;
1158 ///////////////////////////////////////////////////////////////////////////////
1160 ///////////////////////////////////////////////////////////////////////////////
1162 bool MUtils::OS::check_key_state_esc(void)
1164 return (GetAsyncKeyState(VK_ESCAPE) & 0x0001) != 0;
1167 ///////////////////////////////////////////////////////////////////////////////
1168 // SHELL CHANGE NOTIFICATION
1169 ///////////////////////////////////////////////////////////////////////////////
1171 void MUtils::OS::shell_change_notification(void)
1173 SHChangeNotify(SHCNE_ASSOCCHANGED, SHCNF_IDLIST, NULL, NULL);
1176 ///////////////////////////////////////////////////////////////////////////////
1177 // WOW64 REDIRECTION
1178 ///////////////////////////////////////////////////////////////////////////////
1180 typedef BOOL (_stdcall *Wow64DisableWow64FsRedirectionFun)(void *OldValue);
1181 typedef BOOL (_stdcall *Wow64RevertWow64FsRedirectionFun )(void *OldValue);
1183 static QReadWriteLock g_wow64redir_lock;
1184 static QScopedPointer<QLibrary> g_wow64redir_kernel32;
1185 static Wow64DisableWow64FsRedirectionFun g_wow64redir_disable = NULL;
1186 static Wow64RevertWow64FsRedirectionFun g_wow64redir_revert = NULL;
1188 static bool wow64fsredir_init()
1190 QWriteLocker writeLock(&g_wow64redir_lock);
1191 if(g_wow64redir_disable && g_wow64redir_revert)
1193 return true; /*already initialized*/
1196 if(g_wow64redir_kernel32.isNull())
1198 g_wow64redir_kernel32.reset(new QLibrary("kernel32.dll"));
1201 if(!g_wow64redir_kernel32->isLoaded())
1203 if(!g_wow64redir_kernel32->load())
1205 return false; /*faild to load kernel32.dll*/
1209 g_wow64redir_disable = (Wow64DisableWow64FsRedirectionFun) g_wow64redir_kernel32->resolve("Wow64DisableWow64FsRedirection");
1210 g_wow64redir_revert = (Wow64RevertWow64FsRedirectionFun) g_wow64redir_kernel32->resolve("Wow64RevertWow64FsRedirection");
1212 return (g_wow64redir_disable && g_wow64redir_revert);
1215 #define WOW64FSREDIR_INIT(RDLOCK) do \
1217 while(!(g_wow64redir_disable && g_wow64redir_revert)) \
1219 (RDLOCK).unlock(); \
1220 if(!wow64fsredir_init()) return false; \
1221 (RDLOCK).relock(); \
1226 bool MUtils::OS::wow64fsredir_disable(void *oldValue)
1228 QReadLocker readLock(&g_wow64redir_lock);
1229 WOW64FSREDIR_INIT(readLock);
1230 if(g_wow64redir_disable(oldValue))
1237 bool MUtils::OS::wow64fsredir_revert(void *oldValue)
1239 QReadLocker readLock(&g_wow64redir_lock);
1240 WOW64FSREDIR_INIT(readLock);
1241 if(g_wow64redir_revert(oldValue))
1248 ///////////////////////////////////////////////////////////////////////////////
1250 ///////////////////////////////////////////////////////////////////////////////
1252 #if (!(MUTILS_DEBUG))
1253 static __forceinline bool is_debugger_present(void)
1257 CloseHandle((HANDLE)((DWORD_PTR)-3));
1264 BOOL bHaveDebugger = FALSE;
1265 if(CheckRemoteDebuggerPresent(GetCurrentProcess(), &bHaveDebugger))
1267 if(bHaveDebugger) return true;
1270 return IsDebuggerPresent();
1272 static __forceinline bool check_debugger_helper(void)
1274 if(is_debugger_present())
1276 MUtils::OS::fatal_exit(L"Not a debug build. Please unload debugger and try again!");
1282 #define check_debugger_helper() (false)
1285 void MUtils::OS::check_debugger(void)
1287 check_debugger_helper();
1290 static volatile bool g_debug_check = check_debugger_helper();
1292 ///////////////////////////////////////////////////////////////////////////////
1294 ///////////////////////////////////////////////////////////////////////////////
1296 static MUtils::Internal::CriticalSection g_fatal_exit_lock;
1297 static volatile bool g_fatal_exit_flag = true;
1299 static DWORD WINAPI fatal_exit_helper(LPVOID lpParameter)
1301 MUtils::OS::system_message_err(L"GURU MEDITATION", (LPWSTR) lpParameter);
1305 void MUtils::OS::fatal_exit(const wchar_t* const errorMessage)
1307 g_fatal_exit_lock.enter();
1309 if(!g_fatal_exit_flag)
1311 return; /*prevent recursive invocation*/
1314 g_fatal_exit_flag = false;
1316 if(g_main_thread_id != GetCurrentThreadId())
1318 if(HANDLE hThreadMain = OpenThread(THREAD_SUSPEND_RESUME, FALSE, g_main_thread_id))
1320 SuspendThread(hThreadMain); /*stop main thread*/
1324 if(HANDLE hThread = CreateThread(NULL, 0, fatal_exit_helper, (LPVOID) errorMessage, 0, NULL))
1326 WaitForSingleObject(hThread, INFINITE);
1331 TerminateProcess(GetCurrentProcess(), 666);
1335 ///////////////////////////////////////////////////////////////////////////////