IPC status fields will be protected by an Adler-32 checksum too.
[MUtilities.git] / src / OSSupport_Win32.cpp
bloba875e3d40f7d2f95593bbfb50331da10db0354b0
1 ///////////////////////////////////////////////////////////////////////////////
2 // MuldeR's Utilities for Qt
3 // Copyright (C) 2004-2014 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.
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 //////////////////////////////////////////////////////////////////////////////////
22 #pragma once
24 //Win32 API
25 #define WIN32_LEAN_AND_MEAN 1
26 #include <Windows.h>
27 #include <Objbase.h>
28 #include <Psapi.h>
29 #include <Sensapi.h>
30 #include <Shellapi.h>
31 #include <PowrProf.h>
32 #include <Mmsystem.h>
34 //Internal
35 #include <MUtils/Global.h>
36 #include <MUtils/OSSupport.h>
37 #include <MUtils/GUI.h>
38 #include "CriticalSection_Win32.h"
40 //Qt
41 #include <QMap>
42 #include <QReadWriteLock>
43 #include <QLibrary>
44 #include <QDir>
45 #include <QWidget>
46 #include <QProcess>
48 //Main thread ID
49 static const DWORD g_main_thread_id = GetCurrentThreadId();
51 ///////////////////////////////////////////////////////////////////////////////
52 // SYSTEM MESSAGE
53 ///////////////////////////////////////////////////////////////////////////////
55 static const UINT g_msgBoxFlags = MB_TOPMOST | MB_TASKMODAL | MB_SETFOREGROUND;
57 void MUtils::OS::system_message_nfo(const wchar_t *const title, const wchar_t *const text)
59 MessageBoxW(NULL, text, title, g_msgBoxFlags | MB_ICONINFORMATION);
62 void MUtils::OS::system_message_wrn(const wchar_t *const title, const wchar_t *const text)
64 MessageBoxW(NULL, text, title, g_msgBoxFlags | MB_ICONWARNING);
67 void MUtils::OS::system_message_err(const wchar_t *const title, const wchar_t *const text)
69 MessageBoxW(NULL, text, title, g_msgBoxFlags | MB_ICONERROR);
72 ///////////////////////////////////////////////////////////////////////////////
73 // FETCH CLI ARGUMENTS
74 ///////////////////////////////////////////////////////////////////////////////
76 static QReadWriteLock g_arguments_lock;
77 static QScopedPointer<QStringList> g_arguments_list;
79 const QStringList &MUtils::OS::arguments(void)
81 QReadLocker readLock(&g_arguments_lock);
83 //Already initialized?
84 if(!g_arguments_list.isNull())
86 return (*(g_arguments_list.data()));
89 readLock.unlock();
90 QWriteLocker writeLock(&g_arguments_lock);
92 //Still not initialized?
93 if(!g_arguments_list.isNull())
95 return (*(g_arguments_list.data()));
98 g_arguments_list.reset(new QStringList);
99 int nArgs = 0;
100 LPWSTR *szArglist = CommandLineToArgvW(GetCommandLineW(), &nArgs);
102 if(NULL != szArglist)
104 for(int i = 0; i < nArgs; i++)
106 *(g_arguments_list.data()) << MUTILS_QSTR(szArglist[i]);
108 LocalFree(szArglist);
110 else
112 qWarning("CommandLineToArgvW() has failed !!!");
115 return (*(g_arguments_list.data()));
118 ///////////////////////////////////////////////////////////////////////////////
119 // OS VERSION DETECTION
120 ///////////////////////////////////////////////////////////////////////////////
122 static bool g_os_version_initialized = false;
123 static MUtils::OS::Version::os_version_t g_os_version_info = MUtils::OS::Version::UNKNOWN_OPSYS;
124 static QReadWriteLock g_os_version_lock;
126 //Maps marketing names to the actual Windows NT versions
127 static const struct
129 MUtils::OS::Version::os_version_t version;
130 const char friendlyName[64];
132 g_os_version_lut[] =
134 { MUtils::OS::Version::WINDOWS_WIN2K, "Windows 2000" }, //2000
135 { MUtils::OS::Version::WINDOWS_WINXP, "Windows XP or Windows XP Media Center Edition" }, //XP
136 { MUtils::OS::Version::WINDOWS_XPX64, "Windows Server 2003 or Windows XP x64" }, //XP_x64
137 { MUtils::OS::Version::WINDOWS_VISTA, "Windows Vista or Windows Server 2008" }, //Vista
138 { MUtils::OS::Version::WINDOWS_WIN70, "Windows 7 or Windows Server 2008 R2" }, //7
139 { MUtils::OS::Version::WINDOWS_WIN80, "Windows 8 or Windows Server 2012" }, //8
140 { MUtils::OS::Version::WINDOWS_WIN81, "Windows 8.1 or Windows Server 2012 R2" }, //8.1
141 { MUtils::OS::Version::WINDOWS_WN100, "Windows 10 or Windows Server 2014 (Preview)" }, //10
142 { MUtils::OS::Version::UNKNOWN_OPSYS, "N/A" }
145 static bool verify_os_version(const DWORD major, const DWORD minor)
147 OSVERSIONINFOEXW osvi;
148 DWORDLONG dwlConditionMask = 0;
150 //Initialize the OSVERSIONINFOEX structure
151 memset(&osvi, 0, sizeof(OSVERSIONINFOEXW));
152 osvi.dwOSVersionInfoSize = sizeof(OSVERSIONINFOEXW);
153 osvi.dwMajorVersion = major;
154 osvi.dwMinorVersion = minor;
155 osvi.dwPlatformId = VER_PLATFORM_WIN32_NT;
157 //Initialize the condition mask
158 VER_SET_CONDITION(dwlConditionMask, VER_MAJORVERSION, VER_GREATER_EQUAL);
159 VER_SET_CONDITION(dwlConditionMask, VER_MINORVERSION, VER_GREATER_EQUAL);
160 VER_SET_CONDITION(dwlConditionMask, VER_PLATFORMID, VER_EQUAL);
162 // Perform the test
163 const BOOL ret = VerifyVersionInfoW(&osvi, VER_MAJORVERSION | VER_MINORVERSION | VER_PLATFORMID, dwlConditionMask);
165 //Error checking
166 if(!ret)
168 if(GetLastError() != ERROR_OLD_WIN_VERSION)
170 qWarning("VerifyVersionInfo() system call has failed!");
174 return (ret != FALSE);
177 static bool get_real_os_version(unsigned int *major, unsigned int *minor, bool *pbOverride)
179 *major = *minor = 0;
180 *pbOverride = false;
182 //Initialize local variables
183 OSVERSIONINFOEXW osvi;
184 memset(&osvi, 0, sizeof(OSVERSIONINFOEXW));
185 osvi.dwOSVersionInfoSize = sizeof(OSVERSIONINFOEXW);
187 //Try GetVersionEx() first
188 if(GetVersionExW((LPOSVERSIONINFOW)&osvi) == FALSE)
190 qWarning("GetVersionEx() has failed, cannot detect Windows version!");
191 return false;
194 //Make sure we are running on NT
195 if(osvi.dwPlatformId == VER_PLATFORM_WIN32_NT)
197 *major = osvi.dwMajorVersion;
198 *minor = osvi.dwMinorVersion;
200 else
202 qWarning("Not running on Windows NT, unsupported operating system!");
203 return false;
206 //Determine the real *major* version first
207 forever
209 const DWORD nextMajor = (*major) + 1;
210 if(verify_os_version(nextMajor, 0))
212 *pbOverride = true;
213 *major = nextMajor;
214 *minor = 0;
215 continue;
217 break;
220 //Now also determine the real *minor* version
221 forever
223 const DWORD nextMinor = (*minor) + 1;
224 if(verify_os_version((*major), nextMinor))
226 *pbOverride = true;
227 *minor = nextMinor;
228 continue;
230 break;
233 return true;
236 const MUtils::OS::Version::os_version_t &MUtils::OS::os_version(void)
238 QReadLocker readLock(&g_os_version_lock);
240 //Already initialized?
241 if(g_os_version_initialized)
243 return g_os_version_info;
246 readLock.unlock();
247 QWriteLocker writeLock(&g_os_version_lock);
249 //Initialized now?
250 if(g_os_version_initialized)
252 return g_os_version_info;
255 //Detect OS version
256 unsigned int major, minor; bool overrideFlg;
257 if(get_real_os_version(&major, &minor, &overrideFlg))
259 g_os_version_info.type = Version::OS_WINDOWS;
260 g_os_version_info.versionMajor = major;
261 g_os_version_info.versionMinor = minor;
262 g_os_version_info.overrideFlag = overrideFlg;
264 else
266 qWarning("Failed to determin the operating system version!");
269 //Completed
270 g_os_version_initialized = true;
271 return g_os_version_info;
274 const char *MUtils::OS::os_friendly_name(const MUtils::OS::Version::os_version_t &os_version)
276 for(size_t i = 0; g_os_version_lut[i].version != MUtils::OS::Version::UNKNOWN_OPSYS; i++)
278 if(os_version == g_os_version_lut[i].version)
280 return g_os_version_lut[i].friendlyName;
284 return NULL;
287 ///////////////////////////////////////////////////////////////////////////////
288 // WINE DETECTION
289 ///////////////////////////////////////////////////////////////////////////////
291 static bool g_wine_deteced = false;
292 static bool g_wine_initialized = false;
293 static QReadWriteLock g_wine_lock;
295 static const bool detect_wine(void)
297 bool is_wine = false;
299 QLibrary ntdll("ntdll.dll");
300 if(ntdll.load())
302 if(ntdll.resolve("wine_nt_to_unix_file_name") != NULL) is_wine = true;
303 if(ntdll.resolve("wine_get_version") != NULL) is_wine = true;
304 ntdll.unload();
307 return is_wine;
310 const bool &MUtils::OS::running_on_wine(void)
312 QReadLocker readLock(&g_wine_lock);
314 //Already initialized?
315 if(g_wine_initialized)
317 return g_wine_deteced;
320 readLock.unlock();
321 QWriteLocker writeLock(&g_wine_lock);
323 //Initialized now?
324 if(g_wine_initialized)
326 return g_wine_deteced;
329 //Try to detect Wine
330 g_wine_deteced = detect_wine();
331 g_wine_initialized = true;
333 return g_wine_deteced;
336 ///////////////////////////////////////////////////////////////////////////////
337 // KNWON FOLDERS
338 ///////////////////////////////////////////////////////////////////////////////
340 typedef QMap<size_t, QString> KFMap;
341 typedef HRESULT (WINAPI *SHGetKnownFolderPath_t)(const GUID &rfid, DWORD dwFlags, HANDLE hToken, PWSTR *ppszPath);
342 typedef HRESULT (WINAPI *SHGetFolderPath_t)(HWND hwndOwner, int nFolder, HANDLE hToken, DWORD dwFlags, LPWSTR pszPath);
344 static QScopedPointer<KFMap> g_known_folders_map;
345 static SHGetKnownFolderPath_t g_known_folders_fpGetKnownFolderPath;
346 static SHGetFolderPath_t g_known_folders_fpGetFolderPath;
347 static QReadWriteLock g_known_folders_lock;
349 const QString &MUtils::OS::known_folder(known_folder_t folder_id)
351 static const int CSIDL_FLAG_CREATE = 0x8000;
352 typedef enum { KF_FLAG_CREATE = 0x00008000 } kf_flags_t;
354 struct
356 const int csidl;
357 const GUID guid;
359 static s_folders[] =
361 { 0x001c, {0xF1B32785,0x6FBA,0x4FCF,{0x9D,0x55,0x7B,0x8E,0x7F,0x15,0x70,0x91}} }, //CSIDL_LOCAL_APPDATA
362 { 0x0026, {0x905e63b6,0xc1bf,0x494e,{0xb2,0x9c,0x65,0xb7,0x32,0xd3,0xd2,0x1a}} }, //CSIDL_PROGRAM_FILES
363 { 0x0024, {0xF38BF404,0x1D43,0x42F2,{0x93,0x05,0x67,0xDE,0x0B,0x28,0xFC,0x23}} }, //CSIDL_WINDOWS_FOLDER
364 { 0x0025, {0x1AC14E77,0x02E7,0x4E5D,{0xB7,0x44,0x2E,0xB1,0xAE,0x51,0x98,0xB7}} }, //CSIDL_SYSTEM_FOLDER
367 size_t folderId = size_t(-1);
369 switch(folder_id)
371 case FOLDER_LOCALAPPDATA: folderId = 0; break;
372 case FOLDER_PROGRAMFILES: folderId = 1; break;
373 case FOLDER_SYSTROOT_DIR: folderId = 2; break;
374 case FOLDER_SYSTEMFOLDER: folderId = 3; break;
377 if(folderId == size_t(-1))
379 qWarning("Invalid 'known' folder was requested!");
380 return *reinterpret_cast<QString*>(NULL);
383 QReadLocker readLock(&g_known_folders_lock);
385 //Already in cache?
386 if(!g_known_folders_map.isNull())
388 if(g_known_folders_map->contains(folderId))
390 return g_known_folders_map->operator[](folderId);
394 //Obtain write lock to initialize
395 readLock.unlock();
396 QWriteLocker writeLock(&g_known_folders_lock);
398 //Still not in cache?
399 if(!g_known_folders_map.isNull())
401 if(g_known_folders_map->contains(folderId))
403 return g_known_folders_map->operator[](folderId);
407 //Initialize on first call
408 if(g_known_folders_map.isNull())
410 QLibrary shell32("shell32.dll");
411 if(shell32.load())
413 g_known_folders_fpGetFolderPath = (SHGetFolderPath_t) shell32.resolve("SHGetFolderPathW");
414 g_known_folders_fpGetKnownFolderPath = (SHGetKnownFolderPath_t) shell32.resolve("SHGetKnownFolderPath");
416 g_known_folders_map.reset(new QMap<size_t, QString>());
419 QString folderPath;
421 //Now try to get the folder path!
422 if(g_known_folders_fpGetKnownFolderPath)
424 WCHAR *path = NULL;
425 if(g_known_folders_fpGetKnownFolderPath(s_folders[folderId].guid, KF_FLAG_CREATE, NULL, &path) == S_OK)
427 //MessageBoxW(0, path, L"SHGetKnownFolderPath", MB_TOPMOST);
428 QDir folderTemp = QDir(QDir::fromNativeSeparators(MUTILS_QSTR(path)));
429 if(folderTemp.exists())
431 folderPath = folderTemp.canonicalPath();
433 CoTaskMemFree(path);
436 else if(g_known_folders_fpGetFolderPath)
438 QScopedArrayPointer<WCHAR> path(new WCHAR[4096]);
439 if(g_known_folders_fpGetFolderPath(NULL, s_folders[folderId].csidl | CSIDL_FLAG_CREATE, NULL, NULL, path.data()) == S_OK)
441 //MessageBoxW(0, path, L"SHGetFolderPathW", MB_TOPMOST);
442 QDir folderTemp = QDir(QDir::fromNativeSeparators(MUTILS_QSTR(path.data())));
443 if(folderTemp.exists())
445 folderPath = folderTemp.canonicalPath();
450 //Update cache
451 g_known_folders_map->insert(folderId, folderPath);
452 return g_known_folders_map->operator[](folderId);
455 ///////////////////////////////////////////////////////////////////////////////
456 // CURRENT DATA & TIME
457 ///////////////////////////////////////////////////////////////////////////////
459 QDate MUtils::OS::current_date(void)
461 const DWORD MAX_PROC = 1024;
462 QScopedArrayPointer<DWORD> processes(new DWORD[MAX_PROC]);
463 DWORD bytesReturned = 0;
465 if(!EnumProcesses(processes.data(), sizeof(DWORD) * MAX_PROC, &bytesReturned))
467 return QDate::currentDate();
470 const DWORD procCount = bytesReturned / sizeof(DWORD);
471 ULARGE_INTEGER lastStartTime;
472 memset(&lastStartTime, 0, sizeof(ULARGE_INTEGER));
474 for(DWORD i = 0; i < procCount; i++)
476 if(HANDLE hProc = OpenProcess(PROCESS_QUERY_INFORMATION, FALSE, processes[i]))
478 FILETIME processTime[4];
479 if(GetProcessTimes(hProc, &processTime[0], &processTime[1], &processTime[2], &processTime[3]))
481 ULARGE_INTEGER timeCreation;
482 timeCreation.LowPart = processTime[0].dwLowDateTime;
483 timeCreation.HighPart = processTime[0].dwHighDateTime;
484 if(timeCreation.QuadPart > lastStartTime.QuadPart)
486 lastStartTime.QuadPart = timeCreation.QuadPart;
489 CloseHandle(hProc);
493 FILETIME lastStartTime_fileTime;
494 lastStartTime_fileTime.dwHighDateTime = lastStartTime.HighPart;
495 lastStartTime_fileTime.dwLowDateTime = lastStartTime.LowPart;
497 FILETIME lastStartTime_localTime;
498 if(!FileTimeToLocalFileTime(&lastStartTime_fileTime, &lastStartTime_localTime))
500 memcpy(&lastStartTime_localTime, &lastStartTime_fileTime, sizeof(FILETIME));
503 SYSTEMTIME lastStartTime_system;
504 if(!FileTimeToSystemTime(&lastStartTime_localTime, &lastStartTime_system))
506 memset(&lastStartTime_system, 0, sizeof(SYSTEMTIME));
507 lastStartTime_system.wYear = 1970; lastStartTime_system.wMonth = lastStartTime_system.wDay = 1;
510 const QDate currentDate = QDate::currentDate();
511 const QDate processDate = QDate(lastStartTime_system.wYear, lastStartTime_system.wMonth, lastStartTime_system.wDay);
512 return (currentDate >= processDate) ? currentDate : processDate;
515 quint64 MUtils::OS::current_file_time(void)
517 FILETIME fileTime;
518 GetSystemTimeAsFileTime(&fileTime);
520 ULARGE_INTEGER temp;
521 temp.HighPart = fileTime.dwHighDateTime;
522 temp.LowPart = fileTime.dwLowDateTime;
524 return temp.QuadPart;
527 ///////////////////////////////////////////////////////////////////////////////
528 // PROCESS ELEVATION
529 ///////////////////////////////////////////////////////////////////////////////
531 static bool user_is_admin_helper(void)
533 HANDLE hToken = NULL;
534 if(!OpenProcessToken(GetCurrentProcess(), TOKEN_QUERY, &hToken))
536 return false;
539 DWORD dwSize = 0;
540 if(!GetTokenInformation(hToken, TokenGroups, NULL, 0, &dwSize))
542 if(GetLastError() != ERROR_INSUFFICIENT_BUFFER)
544 CloseHandle(hToken);
545 return false;
549 PTOKEN_GROUPS lpGroups = (PTOKEN_GROUPS) malloc(dwSize);
550 if(!lpGroups)
552 CloseHandle(hToken);
553 return false;
556 if(!GetTokenInformation(hToken, TokenGroups, lpGroups, dwSize, &dwSize))
558 free(lpGroups);
559 CloseHandle(hToken);
560 return false;
563 PSID lpSid = NULL; SID_IDENTIFIER_AUTHORITY Authority = {SECURITY_NT_AUTHORITY};
564 if(!AllocateAndInitializeSid(&Authority, 2, SECURITY_BUILTIN_DOMAIN_RID, DOMAIN_ALIAS_RID_ADMINS, 0, 0, 0, 0, 0, 0, &lpSid))
566 free(lpGroups);
567 CloseHandle(hToken);
568 return false;
571 bool bResult = false;
572 for(DWORD i = 0; i < lpGroups->GroupCount; i++)
574 if(EqualSid(lpSid, lpGroups->Groups[i].Sid))
576 bResult = true;
577 break;
581 FreeSid(lpSid);
582 free(lpGroups);
583 CloseHandle(hToken);
584 return bResult;
587 bool MUtils::OS::is_elevated(bool *bIsUacEnabled)
589 if(bIsUacEnabled)
591 *bIsUacEnabled = false;
594 bool bIsProcessElevated = false;
595 HANDLE hToken = NULL;
597 if(OpenProcessToken(GetCurrentProcess(), TOKEN_QUERY, &hToken))
599 TOKEN_ELEVATION_TYPE tokenElevationType;
600 DWORD returnLength;
601 if(GetTokenInformation(hToken, TokenElevationType, &tokenElevationType, sizeof(TOKEN_ELEVATION_TYPE), &returnLength))
603 if(returnLength == sizeof(TOKEN_ELEVATION_TYPE))
605 switch(tokenElevationType)
607 case TokenElevationTypeDefault:
608 qDebug("Process token elevation type: Default -> UAC is disabled.\n");
609 break;
610 case TokenElevationTypeFull:
611 qWarning("Process token elevation type: Full -> potential security risk!\n");
612 bIsProcessElevated = true;
613 if(bIsUacEnabled) *bIsUacEnabled = true;
614 break;
615 case TokenElevationTypeLimited:
616 qDebug("Process token elevation type: Limited -> not elevated.\n");
617 if(bIsUacEnabled) *bIsUacEnabled = true;
618 break;
619 default:
620 qWarning("Unknown tokenElevationType value: %d", tokenElevationType);
621 break;
624 else
626 qWarning("GetTokenInformation() return an unexpected size!");
629 CloseHandle(hToken);
631 else
633 qWarning("Failed to open process token!");
636 return bIsProcessElevated;
639 bool MUtils::OS::user_is_admin(void)
641 bool isAdmin = false;
643 //Check for process elevation and UAC support first!
644 if(MUtils::OS::is_elevated(&isAdmin))
646 qWarning("Process is elevated -> user is admin!");
647 return true;
650 //If not elevated and UAC is not available -> user must be in admin group!
651 if(!isAdmin)
653 qDebug("UAC is disabled/unavailable -> checking for Administrators group");
654 isAdmin = user_is_admin_helper();
657 return isAdmin;
660 ///////////////////////////////////////////////////////////////////////////////
661 // NETWORK STATE
662 ///////////////////////////////////////////////////////////////////////////////
664 int MUtils::OS::network_status(void)
666 DWORD dwFlags;
667 const BOOL ret = IsNetworkAlive(&dwFlags);
668 if(GetLastError() == 0)
670 return (ret != FALSE) ? NETWORK_TYPE_YES : NETWORK_TYPE_NON;
672 return NETWORK_TYPE_ERR;
675 ///////////////////////////////////////////////////////////////////////////////
676 // MESSAGE HANDLER
677 ///////////////////////////////////////////////////////////////////////////////
679 bool MUtils::OS::handle_os_message(const void *const message, long *result)
681 const MSG *const msg = reinterpret_cast<const MSG*>(message);
683 switch(msg->message)
685 case WM_QUERYENDSESSION:
686 qWarning("WM_QUERYENDSESSION message received!");
687 *result = MUtils::GUI::broadcast(MUtils::GUI::USER_EVENT_QUERYENDSESSION, false) ? TRUE : FALSE;
688 return true;
689 case WM_ENDSESSION:
690 qWarning("WM_ENDSESSION message received!");
691 if(msg->wParam == TRUE)
693 MUtils::GUI::broadcast(MUtils::GUI::USER_EVENT_ENDSESSION, false);
694 MUtils::GUI::force_quit();
695 exit(1);
697 *result = 0;
698 return true;
699 default:
700 /*ignore this message and let Qt handle it*/
701 return false;
705 ///////////////////////////////////////////////////////////////////////////////
706 // SLEEP
707 ///////////////////////////////////////////////////////////////////////////////
709 void MUtils::OS::sleep_ms(const size_t &duration)
711 Sleep((DWORD) duration);
714 ///////////////////////////////////////////////////////////////////////////////
715 // EXECUTABLE CHECK
716 ///////////////////////////////////////////////////////////////////////////////
718 bool MUtils::OS::is_executable_file(const QString &path)
720 bool bIsExecutable = false;
721 DWORD binaryType;
722 if(GetBinaryType(MUTILS_WCHR(QDir::toNativeSeparators(path)), &binaryType))
724 bIsExecutable = (binaryType == SCS_32BIT_BINARY || binaryType == SCS_64BIT_BINARY);
726 return bIsExecutable;
729 ///////////////////////////////////////////////////////////////////////////////
730 // HIBERNATION / SHUTDOWN
731 ///////////////////////////////////////////////////////////////////////////////
733 bool MUtils::OS::is_hibernation_supported(void)
735 bool hibernationSupported = false;
737 SYSTEM_POWER_CAPABILITIES pwrCaps;
738 SecureZeroMemory(&pwrCaps, sizeof(SYSTEM_POWER_CAPABILITIES));
740 if(GetPwrCapabilities(&pwrCaps))
742 hibernationSupported = pwrCaps.SystemS4 && pwrCaps.HiberFilePresent;
745 return hibernationSupported;
748 bool MUtils::OS::shutdown_computer(const QString &message, const unsigned long timeout, const bool forceShutdown, const bool hibernate)
750 HANDLE hToken = NULL;
752 if(OpenProcessToken(GetCurrentProcess(), TOKEN_ADJUST_PRIVILEGES | TOKEN_QUERY, &hToken))
754 TOKEN_PRIVILEGES privileges;
755 memset(&privileges, 0, sizeof(TOKEN_PRIVILEGES));
756 privileges.PrivilegeCount = 1;
757 privileges.Privileges[0].Attributes = SE_PRIVILEGE_ENABLED;
759 if(LookupPrivilegeValue(NULL, SE_SHUTDOWN_NAME, &privileges.Privileges[0].Luid))
761 if(AdjustTokenPrivileges(hToken, FALSE, &privileges, NULL, NULL, NULL))
763 if(hibernate)
765 if(SetSuspendState(TRUE, TRUE, TRUE))
767 return true;
770 const DWORD reason = SHTDN_REASON_MAJOR_APPLICATION | SHTDN_REASON_FLAG_PLANNED;
771 return InitiateSystemShutdownEx(NULL, const_cast<wchar_t*>(MUTILS_WCHR(message)), timeout, forceShutdown ? TRUE : FALSE, FALSE, reason);
776 return false;
779 ///////////////////////////////////////////////////////////////////////////////
780 // FREE DISKSPACE
781 ///////////////////////////////////////////////////////////////////////////////
783 bool MUtils::OS::free_diskspace(const QString &path, quint64 &freeSpace)
785 ULARGE_INTEGER freeBytesAvailable, totalNumberOfBytes, totalNumberOfFreeBytes;
786 if(GetDiskFreeSpaceExW(reinterpret_cast<const wchar_t*>(QDir::toNativeSeparators(path).utf16()), &freeBytesAvailable, &totalNumberOfBytes, &totalNumberOfFreeBytes))
788 freeSpace = freeBytesAvailable.QuadPart;
789 return true;;
792 freeSpace = -1;
793 return false;
796 ///////////////////////////////////////////////////////////////////////////////
797 // SHELL OPEN
798 ///////////////////////////////////////////////////////////////////////////////
800 bool MUtils::OS::shell_open(const QWidget *parent, const QString &url, const QString &parameters, const QString &directory, const bool explore)
802 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;
805 bool MUtils::OS::shell_open(const QWidget *parent, const QString &url, const bool explore)
807 return shell_open(parent, url, QString(), QString(), explore);
810 ///////////////////////////////////////////////////////////////////////////////
811 // OPEN MEDIA FILE
812 ///////////////////////////////////////////////////////////////////////////////
814 bool MUtils::OS::open_media_file(const QString &mediaFilePath)
816 const static wchar_t *registryPrefix[2] = { L"SOFTWARE\\", L"SOFTWARE\\Wow6432Node\\" };
817 const static wchar_t *registryKeys[3] =
819 L"Microsoft\\Windows\\CurrentVersion\\Uninstall\\{97D341C8-B0D1-4E4A-A49A-C30B52F168E9}",
820 L"Microsoft\\Windows\\CurrentVersion\\Uninstall\\{DB9E4EAB-2717-499F-8D56-4CC8A644AB60}",
821 L"foobar2000"
823 const static wchar_t *appNames[4] = { L"smplayer_portable.exe", L"smplayer.exe", L"MPUI.exe", L"foobar2000.exe" };
824 const static wchar_t *valueNames[2] = { L"InstallLocation", L"InstallDir" };
826 for(size_t i = 0; i < 3; i++)
828 for(size_t j = 0; j < 2; j++)
830 QString mplayerPath;
831 HKEY registryKeyHandle = NULL;
833 const QString currentKey = MUTILS_QSTR(registryPrefix[j]).append(MUTILS_QSTR(registryKeys[i]));
834 if(RegOpenKeyExW(HKEY_LOCAL_MACHINE, MUTILS_WCHR(currentKey), 0, KEY_READ, &registryKeyHandle) == ERROR_SUCCESS)
836 for(size_t k = 0; k < 2; k++)
838 wchar_t Buffer[4096];
839 DWORD BuffSize = sizeof(wchar_t*) * 4096;
840 DWORD DataType = REG_NONE;
841 if(RegQueryValueExW(registryKeyHandle, valueNames[k], 0, &DataType, reinterpret_cast<BYTE*>(Buffer), &BuffSize) == ERROR_SUCCESS)
843 if((DataType == REG_SZ) || (DataType == REG_EXPAND_SZ) || (DataType == REG_LINK))
845 mplayerPath = MUTILS_QSTR(Buffer);
846 break;
850 RegCloseKey(registryKeyHandle);
853 if(!mplayerPath.isEmpty())
855 QDir mplayerDir(mplayerPath);
856 if(mplayerDir.exists())
858 for(size_t k = 0; k < 4; k++)
860 if(mplayerDir.exists(MUTILS_QSTR(appNames[k])))
862 qDebug("Player found at:\n%s\n", MUTILS_UTF8(mplayerDir.absoluteFilePath(MUTILS_QSTR(appNames[k]))));
863 QProcess::startDetached(mplayerDir.absoluteFilePath(MUTILS_QSTR(appNames[k])), QStringList() << QDir::toNativeSeparators(mediaFilePath));
864 return true;
871 return false;
874 ///////////////////////////////////////////////////////////////////////////////
875 // DEBUGGER CHECK
876 ///////////////////////////////////////////////////////////////////////////////
878 static bool change_process_priority_helper(const HANDLE hProcess, const int priority)
880 bool ok = false;
882 switch(qBound(-2, priority, 2))
884 case 2:
885 ok = (SetPriorityClass(hProcess, HIGH_PRIORITY_CLASS) == TRUE);
886 break;
887 case 1:
888 if(!(ok = (SetPriorityClass(hProcess, ABOVE_NORMAL_PRIORITY_CLASS) == TRUE)))
890 ok = (SetPriorityClass(hProcess, HIGH_PRIORITY_CLASS) == TRUE);
892 break;
893 case 0:
894 ok = (SetPriorityClass(hProcess, NORMAL_PRIORITY_CLASS) == TRUE);
895 break;
896 case -1:
897 if(!(ok = (SetPriorityClass(hProcess, BELOW_NORMAL_PRIORITY_CLASS) == TRUE)))
899 ok = (SetPriorityClass(hProcess, IDLE_PRIORITY_CLASS) == TRUE);
901 break;
902 case -2:
903 ok = (SetPriorityClass(hProcess, IDLE_PRIORITY_CLASS) == TRUE);
904 break;
907 return ok;
910 bool MUtils::OS::change_process_priority(const int priority)
912 return change_process_priority_helper(GetCurrentProcess(), priority);
915 bool MUtils::OS::change_process_priority(const QProcess *proc, const int priority)
917 if(Q_PID qPid = proc->pid())
919 return change_process_priority_helper(qPid->hProcess, priority);
921 else
923 return false;
927 ///////////////////////////////////////////////////////////////////////////////
928 // PROCESS ID
929 ///////////////////////////////////////////////////////////////////////////////
931 quint32 MUtils::OS::process_id(const QProcess *proc)
933 PROCESS_INFORMATION *procInf = proc->pid();
934 return (procInf) ? procInf->dwProcessId : NULL;
937 ///////////////////////////////////////////////////////////////////////////////
938 // SYSTEM TIMER
939 ///////////////////////////////////////////////////////////////////////////////
941 bool MUtils::OS::setup_timer_resolution(const quint32 &interval)
943 return timeBeginPeriod(interval) == TIMERR_NOERROR;
946 bool MUtils::OS::reset_timer_resolution(const quint32 &interval)
948 return timeEndPeriod(interval) == TIMERR_NOERROR;
951 ///////////////////////////////////////////////////////////////////////////////
952 // CHECK KEY STATE
953 ///////////////////////////////////////////////////////////////////////////////
955 bool MUtils::OS::check_key_state_esc(void)
957 return (GetAsyncKeyState(VK_ESCAPE) & 0x0001) != 0;
960 ///////////////////////////////////////////////////////////////////////////////
961 // DEBUGGER CHECK
962 ///////////////////////////////////////////////////////////////////////////////
964 #if (!(MUTILS_DEBUG))
965 static __forceinline bool is_debugger_present(void)
967 __try
969 CloseHandle((HANDLE)((DWORD_PTR)-3));
971 __except(1)
973 return true;
976 BOOL bHaveDebugger = FALSE;
977 if(CheckRemoteDebuggerPresent(GetCurrentProcess(), &bHaveDebugger))
979 if(bHaveDebugger) return true;
982 return IsDebuggerPresent();
984 static __forceinline bool check_debugger_helper(void)
986 if(is_debugger_present())
988 MUtils::OS::fatal_exit(L"Not a debug build. Please unload debugger and try again!");
989 return true;
991 return false;
993 #else
994 #define check_debugger_helper() (false)
995 #endif
997 void MUtils::OS::check_debugger(void)
999 check_debugger_helper();
1002 static volatile bool g_debug_check = check_debugger_helper();
1004 ///////////////////////////////////////////////////////////////////////////////
1005 // FATAL EXIT
1006 ///////////////////////////////////////////////////////////////////////////////
1008 static MUtils::Internal::CriticalSection g_fatal_exit_lock;
1009 static volatile bool g_fatal_exit_flag = true;
1011 static DWORD WINAPI fatal_exit_helper(LPVOID lpParameter)
1013 MUtils::OS::system_message_err(L"GURU MEDITATION", (LPWSTR) lpParameter);
1014 return 0;
1017 void MUtils::OS::fatal_exit(const wchar_t* const errorMessage)
1019 g_fatal_exit_lock.enter();
1021 if(!g_fatal_exit_flag)
1023 return; /*prevent recursive invocation*/
1026 g_fatal_exit_flag = false;
1028 if(g_main_thread_id != GetCurrentThreadId())
1030 if(HANDLE hThreadMain = OpenThread(THREAD_SUSPEND_RESUME, FALSE, g_main_thread_id))
1032 SuspendThread(hThreadMain); /*stop main thread*/
1036 if(HANDLE hThread = CreateThread(NULL, 0, fatal_exit_helper, (LPVOID) errorMessage, 0, NULL))
1038 WaitForSingleObject(hThread, INFINITE);
1041 for(;;)
1043 TerminateProcess(GetCurrentProcess(), 666);
1047 ///////////////////////////////////////////////////////////////////////////////