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
33 #include <MUtils/Global.h>
34 #include <MUtils/OSSupport.h>
35 #include <MUtils/GUI.h>
36 #include "CriticalSection_Win32.h"
40 #include <QReadWriteLock>
47 static const DWORD g_main_thread_id
= GetCurrentThreadId();
49 ///////////////////////////////////////////////////////////////////////////////
51 ///////////////////////////////////////////////////////////////////////////////
53 static const UINT g_msgBoxFlags
= MB_TOPMOST
| MB_TASKMODAL
| MB_SETFOREGROUND
;
55 void MUtils::OS::system_message_nfo(const wchar_t *const title
, const wchar_t *const text
)
57 MessageBoxW(NULL
, text
, title
, g_msgBoxFlags
| MB_ICONINFORMATION
);
60 void MUtils::OS::system_message_wrn(const wchar_t *const title
, const wchar_t *const text
)
62 MessageBoxW(NULL
, text
, title
, g_msgBoxFlags
| MB_ICONWARNING
);
65 void MUtils::OS::system_message_err(const wchar_t *const title
, const wchar_t *const text
)
67 MessageBoxW(NULL
, text
, title
, g_msgBoxFlags
| MB_ICONERROR
);
70 ///////////////////////////////////////////////////////////////////////////////
71 // FETCH CLI ARGUMENTS
72 ///////////////////////////////////////////////////////////////////////////////
74 static QReadWriteLock g_arguments_lock
;
75 static QScopedPointer
<MUtils::OS::ArgumentMap
> g_arguments_list
;
77 const MUtils::OS::ArgumentMap
&MUtils::OS::arguments(void)
79 QReadLocker
readLock(&g_arguments_lock
);
81 //Already initialized?
82 if(!g_arguments_list
.isNull())
84 return (*(g_arguments_list
.data()));
88 QWriteLocker
writeLock(&g_arguments_lock
);
90 //Still not initialized?
91 if(!g_arguments_list
.isNull())
93 return (*(g_arguments_list
.data()));
96 g_arguments_list
.reset(new ArgumentMap());
98 LPWSTR
*szArglist
= CommandLineToArgvW(GetCommandLineW(), &nArgs
);
100 if(NULL
!= szArglist
)
102 const QChar separator
= QLatin1Char('=');
103 const QString argPrefix
= QLatin1String("--");
104 for(int i
= 0; i
< nArgs
; i
++)
106 const QString argStr
= MUTILS_QSTR(szArglist
[i
]).trimmed();
107 if(argStr
.startsWith(argPrefix
))
109 const QString argData
= argStr
.mid(2).trimmed();
110 if(argData
.length() > 0)
112 const int separatorIndex
= argData
.indexOf(separator
);
113 if(separatorIndex
> 0)
115 const QString argKey
= argData
.left(separatorIndex
).trimmed();
116 const QString argVal
= argData
.mid(separatorIndex
+ 1).trimmed();
117 g_arguments_list
->insertMulti(argKey
.toLower(), argVal
);
121 g_arguments_list
->insertMulti(argData
.toLower(), QString());
126 LocalFree(szArglist
);
130 qWarning("CommandLineToArgvW() has failed !!!");
133 return (*(g_arguments_list
.data()));
136 ///////////////////////////////////////////////////////////////////////////////
138 ///////////////////////////////////////////////////////////////////////////////
140 typedef struct _progress_callback_data_t
142 MUtils::OS::progress_callback_t callback_function
;
145 progress_callback_data_t
;
147 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
)
149 if(const progress_callback_data_t
*data
= (progress_callback_data_t
*) lpData
)
151 const double progress
= qBound(0.0, double(TotalBytesTransferred
.QuadPart
) / double(TotalFileSize
.QuadPart
), 1.0);
152 return data
->callback_function(progress
, data
->user_data
) ? PROGRESS_CONTINUE
: PROGRESS_CANCEL
;
154 return PROGRESS_CONTINUE
;
157 MUTILS_API
bool MUtils::OS::copy_file(const QString
&sourcePath
, const QString
&outputPath
, const bool &overwrite
, const progress_callback_t callback
, void *const userData
)
159 progress_callback_data_t callback_data
= { callback
, userData
};
161 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
));
165 const DWORD errorCode
= GetLastError();
166 if(errorCode
!= ERROR_REQUEST_ABORTED
)
168 qWarning("CopyFile() failed with error code 0x%08X!", errorCode
);
172 qWarning("CopyFile() operation was abroted by user!");
176 return (result
!= FALSE
);
179 ///////////////////////////////////////////////////////////////////////////////
180 // OS VERSION DETECTION
181 ///////////////////////////////////////////////////////////////////////////////
183 static bool g_os_version_initialized
= false;
184 static MUtils::OS::Version::os_version_t g_os_version_info
= MUtils::OS::Version::UNKNOWN_OPSYS
;
185 static QReadWriteLock g_os_version_lock
;
187 //Maps marketing names to the actual Windows NT versions
190 MUtils::OS::Version::os_version_t version
;
191 const char friendlyName
[64];
195 { MUtils::OS::Version::WINDOWS_WIN2K
, "Windows 2000" }, //2000
196 { MUtils::OS::Version::WINDOWS_WINXP
, "Windows XP or Windows XP Media Center Edition" }, //XP
197 { MUtils::OS::Version::WINDOWS_XPX64
, "Windows Server 2003 or Windows XP x64" }, //XP_x64
198 { MUtils::OS::Version::WINDOWS_VISTA
, "Windows Vista or Windows Server 2008" }, //Vista
199 { MUtils::OS::Version::WINDOWS_WIN70
, "Windows 7 or Windows Server 2008 R2" }, //7
200 { MUtils::OS::Version::WINDOWS_WIN80
, "Windows 8 or Windows Server 2012" }, //8
201 { MUtils::OS::Version::WINDOWS_WIN81
, "Windows 8.1 or Windows Server 2012 R2" }, //8.1
202 { MUtils::OS::Version::WINDOWS_WN100
, "Windows 10 or Windows Server 2014 (Preview)" }, //10
203 { MUtils::OS::Version::UNKNOWN_OPSYS
, "N/A" }
206 //OS version data dtructures
213 //Comparision operators for os_version_t
214 bool os_version_t::operator== (const os_version_t
&rhs
) const { return (type
== rhs
.type
) && (versionMajor
== rhs
.versionMajor
) && ((versionMinor
== rhs
.versionMinor
)); }
215 bool os_version_t::operator!= (const os_version_t
&rhs
) const { return (type
!= rhs
.type
) || (versionMajor
!= rhs
.versionMajor
) || ((versionMinor
!= rhs
.versionMinor
)); }
216 bool os_version_t::operator> (const os_version_t
&rhs
) const { return (type
== rhs
.type
) && ((versionMajor
> rhs
.versionMajor
) || ((versionMajor
== rhs
.versionMajor
) && (versionMinor
> rhs
.versionMinor
))); }
217 bool os_version_t::operator>= (const os_version_t
&rhs
) const { return (type
== rhs
.type
) && ((versionMajor
> rhs
.versionMajor
) || ((versionMajor
== rhs
.versionMajor
) && (versionMinor
>= rhs
.versionMinor
))); }
218 bool os_version_t::operator< (const os_version_t
&rhs
) const { return (type
== rhs
.type
) && ((versionMajor
< rhs
.versionMajor
) || ((versionMajor
== rhs
.versionMajor
) && (versionMinor
< rhs
.versionMinor
))); }
219 bool os_version_t::operator<= (const os_version_t
&rhs
) const { return (type
== rhs
.type
) && ((versionMajor
< rhs
.versionMajor
) || ((versionMajor
== rhs
.versionMajor
) && (versionMinor
<= rhs
.versionMinor
))); }
221 //Known Windows NT versions
222 const os_version_t WINDOWS_WIN2K
= { OS_WINDOWS
, 5, 0 }; // 2000
223 const os_version_t WINDOWS_WINXP
= { OS_WINDOWS
, 5, 1 }; // XP
224 const os_version_t WINDOWS_XPX64
= { OS_WINDOWS
, 5, 2 }; // XP_x64
225 const os_version_t WINDOWS_VISTA
= { OS_WINDOWS
, 6, 0 }; // Vista
226 const os_version_t WINDOWS_WIN70
= { OS_WINDOWS
, 6, 1 }; // 7
227 const os_version_t WINDOWS_WIN80
= { OS_WINDOWS
, 6, 2 }; // 8
228 const os_version_t WINDOWS_WIN81
= { OS_WINDOWS
, 6, 3 }; // 8.1
229 const os_version_t WINDOWS_WN100
= { OS_WINDOWS
, 10, 0 }; // 10
232 const os_version_t UNKNOWN_OPSYS
= { OS_UNKNOWN
, 0, 0 }; // N/A
237 static bool verify_os_version(const DWORD major
, const DWORD minor
)
239 OSVERSIONINFOEXW osvi
;
240 DWORDLONG dwlConditionMask
= 0;
242 //Initialize the OSVERSIONINFOEX structure
243 memset(&osvi
, 0, sizeof(OSVERSIONINFOEXW
));
244 osvi
.dwOSVersionInfoSize
= sizeof(OSVERSIONINFOEXW
);
245 osvi
.dwMajorVersion
= major
;
246 osvi
.dwMinorVersion
= minor
;
247 osvi
.dwPlatformId
= VER_PLATFORM_WIN32_NT
;
249 //Initialize the condition mask
250 VER_SET_CONDITION(dwlConditionMask
, VER_MAJORVERSION
, VER_GREATER_EQUAL
);
251 VER_SET_CONDITION(dwlConditionMask
, VER_MINORVERSION
, VER_GREATER_EQUAL
);
252 VER_SET_CONDITION(dwlConditionMask
, VER_PLATFORMID
, VER_EQUAL
);
255 const BOOL ret
= VerifyVersionInfoW(&osvi
, VER_MAJORVERSION
| VER_MINORVERSION
| VER_PLATFORMID
, dwlConditionMask
);
260 if(GetLastError() != ERROR_OLD_WIN_VERSION
)
262 qWarning("VerifyVersionInfo() system call has failed!");
266 return (ret
!= FALSE
);
269 static bool get_real_os_version(unsigned int *major
, unsigned int *minor
, bool *pbOverride
)
274 //Initialize local variables
275 OSVERSIONINFOEXW osvi
;
276 memset(&osvi
, 0, sizeof(OSVERSIONINFOEXW
));
277 osvi
.dwOSVersionInfoSize
= sizeof(OSVERSIONINFOEXW
);
279 //Try GetVersionEx() first
280 if(GetVersionExW((LPOSVERSIONINFOW
)&osvi
) == FALSE
)
282 qWarning("GetVersionEx() has failed, cannot detect Windows version!");
286 //Make sure we are running on NT
287 if(osvi
.dwPlatformId
== VER_PLATFORM_WIN32_NT
)
289 *major
= osvi
.dwMajorVersion
;
290 *minor
= osvi
.dwMinorVersion
;
294 qWarning("Not running on Windows NT, unsupported operating system!");
298 //Determine the real *major* version first
301 const DWORD nextMajor
= (*major
) + 1;
302 if(verify_os_version(nextMajor
, 0))
312 //Now also determine the real *minor* version
315 const DWORD nextMinor
= (*minor
) + 1;
316 if(verify_os_version((*major
), nextMinor
))
328 const MUtils::OS::Version::os_version_t
&MUtils::OS::os_version(void)
330 QReadLocker
readLock(&g_os_version_lock
);
332 //Already initialized?
333 if(g_os_version_initialized
)
335 return g_os_version_info
;
339 QWriteLocker
writeLock(&g_os_version_lock
);
342 if(g_os_version_initialized
)
344 return g_os_version_info
;
348 unsigned int major
, minor
; bool overrideFlg
;
349 if(get_real_os_version(&major
, &minor
, &overrideFlg
))
351 g_os_version_info
.type
= Version::OS_WINDOWS
;
352 g_os_version_info
.versionMajor
= major
;
353 g_os_version_info
.versionMinor
= minor
;
354 g_os_version_info
.overrideFlag
= overrideFlg
;
358 qWarning("Failed to determin the operating system version!");
362 g_os_version_initialized
= true;
363 return g_os_version_info
;
366 const char *MUtils::OS::os_friendly_name(const MUtils::OS::Version::os_version_t
&os_version
)
368 for(size_t i
= 0; g_os_version_lut
[i
].version
!= MUtils::OS::Version::UNKNOWN_OPSYS
; i
++)
370 if(os_version
== g_os_version_lut
[i
].version
)
372 return g_os_version_lut
[i
].friendlyName
;
379 ///////////////////////////////////////////////////////////////////////////////
381 ///////////////////////////////////////////////////////////////////////////////
383 static bool g_wine_deteced
= false;
384 static bool g_wine_initialized
= false;
385 static QReadWriteLock g_wine_lock
;
387 static const bool detect_wine(void)
389 bool is_wine
= false;
391 QLibrary
ntdll("ntdll.dll");
394 if(ntdll
.resolve("wine_nt_to_unix_file_name") != NULL
) is_wine
= true;
395 if(ntdll
.resolve("wine_get_version") != NULL
) is_wine
= true;
402 const bool &MUtils::OS::running_on_wine(void)
404 QReadLocker
readLock(&g_wine_lock
);
406 //Already initialized?
407 if(g_wine_initialized
)
409 return g_wine_deteced
;
413 QWriteLocker
writeLock(&g_wine_lock
);
416 if(g_wine_initialized
)
418 return g_wine_deteced
;
422 g_wine_deteced
= detect_wine();
423 g_wine_initialized
= true;
425 return g_wine_deteced
;
428 ///////////////////////////////////////////////////////////////////////////////
430 ///////////////////////////////////////////////////////////////////////////////
432 typedef QMap
<size_t, QString
> KFMap
;
433 typedef HRESULT (WINAPI
*SHGetKnownFolderPath_t
)(const GUID
&rfid
, DWORD dwFlags
, HANDLE hToken
, PWSTR
*ppszPath
);
434 typedef HRESULT (WINAPI
*SHGetFolderPath_t
)(HWND hwndOwner
, int nFolder
, HANDLE hToken
, DWORD dwFlags
, LPWSTR pszPath
);
436 static QScopedPointer
<KFMap
> g_known_folders_map
;
437 static SHGetKnownFolderPath_t g_known_folders_fpGetKnownFolderPath
;
438 static SHGetFolderPath_t g_known_folders_fpGetFolderPath
;
439 static QReadWriteLock g_known_folders_lock
;
441 const QString
&MUtils::OS::known_folder(known_folder_t folder_id
)
443 typedef enum { KF_FLAG_CREATE
= 0x00008000 } kf_flags_t
;
452 { 0x001c, {0xF1B32785,0x6FBA,0x4FCF,{0x9D,0x55,0x7B,0x8E,0x7F,0x15,0x70,0x91}} }, //CSIDL_LOCAL_APPDATA
453 { 0x0026, {0x905e63b6,0xc1bf,0x494e,{0xb2,0x9c,0x65,0xb7,0x32,0xd3,0xd2,0x1a}} }, //CSIDL_PROGRAM_FILES
454 { 0x0024, {0xF38BF404,0x1D43,0x42F2,{0x93,0x05,0x67,0xDE,0x0B,0x28,0xFC,0x23}} }, //CSIDL_WINDOWS_FOLDER
455 { 0x0025, {0x1AC14E77,0x02E7,0x4E5D,{0xB7,0x44,0x2E,0xB1,0xAE,0x51,0x98,0xB7}} }, //CSIDL_SYSTEM_FOLDER
458 size_t folderId
= size_t(-1);
462 case FOLDER_LOCALAPPDATA
: folderId
= 0; break;
463 case FOLDER_PROGRAMFILES
: folderId
= 1; break;
464 case FOLDER_SYSTROOT_DIR
: folderId
= 2; break;
465 case FOLDER_SYSTEMFOLDER
: folderId
= 3; break;
468 if(folderId
== size_t(-1))
470 qWarning("Invalid 'known' folder was requested!");
471 return *reinterpret_cast<QString
*>(NULL
);
474 QReadLocker
readLock(&g_known_folders_lock
);
477 if(!g_known_folders_map
.isNull())
479 if(g_known_folders_map
->contains(folderId
))
481 return g_known_folders_map
->operator[](folderId
);
485 //Obtain write lock to initialize
487 QWriteLocker
writeLock(&g_known_folders_lock
);
489 //Still not in cache?
490 if(!g_known_folders_map
.isNull())
492 if(g_known_folders_map
->contains(folderId
))
494 return g_known_folders_map
->operator[](folderId
);
498 //Initialize on first call
499 if(g_known_folders_map
.isNull())
501 QLibrary
shell32("shell32.dll");
504 g_known_folders_fpGetFolderPath
= (SHGetFolderPath_t
) shell32
.resolve("SHGetFolderPathW");
505 g_known_folders_fpGetKnownFolderPath
= (SHGetKnownFolderPath_t
) shell32
.resolve("SHGetKnownFolderPath");
507 g_known_folders_map
.reset(new QMap
<size_t, QString
>());
512 //Now try to get the folder path!
513 if(g_known_folders_fpGetKnownFolderPath
)
516 if(g_known_folders_fpGetKnownFolderPath(s_folders
[folderId
].guid
, KF_FLAG_CREATE
, NULL
, &path
) == S_OK
)
518 //MessageBoxW(0, path, L"SHGetKnownFolderPath", MB_TOPMOST);
519 QDir folderTemp
= QDir(QDir::fromNativeSeparators(MUTILS_QSTR(path
)));
520 if(folderTemp
.exists())
522 folderPath
= folderTemp
.canonicalPath();
527 else if(g_known_folders_fpGetFolderPath
)
529 QScopedArrayPointer
<WCHAR
> path(new WCHAR
[4096]);
530 if(g_known_folders_fpGetFolderPath(NULL
, s_folders
[folderId
].csidl
| CSIDL_FLAG_CREATE
, NULL
, NULL
, path
.data()) == S_OK
)
532 //MessageBoxW(0, path, L"SHGetFolderPathW", MB_TOPMOST);
533 QDir folderTemp
= QDir(QDir::fromNativeSeparators(MUTILS_QSTR(path
.data())));
534 if(folderTemp
.exists())
536 folderPath
= folderTemp
.canonicalPath();
542 g_known_folders_map
->insert(folderId
, folderPath
);
543 return g_known_folders_map
->operator[](folderId
);
546 ///////////////////////////////////////////////////////////////////////////////
547 // CURRENT DATA & TIME
548 ///////////////////////////////////////////////////////////////////////////////
550 QDate
MUtils::OS::current_date(void)
552 const DWORD MAX_PROC
= 1024;
553 QScopedArrayPointer
<DWORD
> processes(new DWORD
[MAX_PROC
]);
554 DWORD bytesReturned
= 0;
556 if(!EnumProcesses(processes
.data(), sizeof(DWORD
) * MAX_PROC
, &bytesReturned
))
558 return QDate::currentDate();
561 const DWORD procCount
= bytesReturned
/ sizeof(DWORD
);
562 ULARGE_INTEGER lastStartTime
;
563 memset(&lastStartTime
, 0, sizeof(ULARGE_INTEGER
));
565 for(DWORD i
= 0; i
< procCount
; i
++)
567 if(HANDLE hProc
= OpenProcess(PROCESS_QUERY_INFORMATION
, FALSE
, processes
[i
]))
569 FILETIME processTime
[4];
570 if(GetProcessTimes(hProc
, &processTime
[0], &processTime
[1], &processTime
[2], &processTime
[3]))
572 ULARGE_INTEGER timeCreation
;
573 timeCreation
.LowPart
= processTime
[0].dwLowDateTime
;
574 timeCreation
.HighPart
= processTime
[0].dwHighDateTime
;
575 if(timeCreation
.QuadPart
> lastStartTime
.QuadPart
)
577 lastStartTime
.QuadPart
= timeCreation
.QuadPart
;
584 FILETIME lastStartTime_fileTime
;
585 lastStartTime_fileTime
.dwHighDateTime
= lastStartTime
.HighPart
;
586 lastStartTime_fileTime
.dwLowDateTime
= lastStartTime
.LowPart
;
588 FILETIME lastStartTime_localTime
;
589 if(!FileTimeToLocalFileTime(&lastStartTime_fileTime
, &lastStartTime_localTime
))
591 memcpy(&lastStartTime_localTime
, &lastStartTime_fileTime
, sizeof(FILETIME
));
594 SYSTEMTIME lastStartTime_system
;
595 if(!FileTimeToSystemTime(&lastStartTime_localTime
, &lastStartTime_system
))
597 memset(&lastStartTime_system
, 0, sizeof(SYSTEMTIME
));
598 lastStartTime_system
.wYear
= 1970; lastStartTime_system
.wMonth
= lastStartTime_system
.wDay
= 1;
601 const QDate currentDate
= QDate::currentDate();
602 const QDate processDate
= QDate(lastStartTime_system
.wYear
, lastStartTime_system
.wMonth
, lastStartTime_system
.wDay
);
603 return (currentDate
>= processDate
) ? currentDate
: processDate
;
606 quint64
MUtils::OS::current_file_time(void)
609 GetSystemTimeAsFileTime(&fileTime
);
612 temp
.HighPart
= fileTime
.dwHighDateTime
;
613 temp
.LowPart
= fileTime
.dwLowDateTime
;
615 return temp
.QuadPart
;
618 ///////////////////////////////////////////////////////////////////////////////
620 ///////////////////////////////////////////////////////////////////////////////
622 static bool user_is_admin_helper(void)
624 HANDLE hToken
= NULL
;
625 if(!OpenProcessToken(GetCurrentProcess(), TOKEN_QUERY
, &hToken
))
631 if(!GetTokenInformation(hToken
, TokenGroups
, NULL
, 0, &dwSize
))
633 if(GetLastError() != ERROR_INSUFFICIENT_BUFFER
)
640 PTOKEN_GROUPS lpGroups
= (PTOKEN_GROUPS
) malloc(dwSize
);
647 if(!GetTokenInformation(hToken
, TokenGroups
, lpGroups
, dwSize
, &dwSize
))
654 PSID lpSid
= NULL
; SID_IDENTIFIER_AUTHORITY Authority
= {SECURITY_NT_AUTHORITY
};
655 if(!AllocateAndInitializeSid(&Authority
, 2, SECURITY_BUILTIN_DOMAIN_RID
, DOMAIN_ALIAS_RID_ADMINS
, 0, 0, 0, 0, 0, 0, &lpSid
))
662 bool bResult
= false;
663 for(DWORD i
= 0; i
< lpGroups
->GroupCount
; i
++)
665 if(EqualSid(lpSid
, lpGroups
->Groups
[i
].Sid
))
678 bool MUtils::OS::is_elevated(bool *bIsUacEnabled
)
682 *bIsUacEnabled
= false;
685 bool bIsProcessElevated
= false;
686 HANDLE hToken
= NULL
;
688 if(OpenProcessToken(GetCurrentProcess(), TOKEN_QUERY
, &hToken
))
690 TOKEN_ELEVATION_TYPE tokenElevationType
;
692 if(GetTokenInformation(hToken
, TokenElevationType
, &tokenElevationType
, sizeof(TOKEN_ELEVATION_TYPE
), &returnLength
))
694 if(returnLength
== sizeof(TOKEN_ELEVATION_TYPE
))
696 switch(tokenElevationType
)
698 case TokenElevationTypeDefault
:
699 qDebug("Process token elevation type: Default -> UAC is disabled.\n");
701 case TokenElevationTypeFull
:
702 qWarning("Process token elevation type: Full -> potential security risk!\n");
703 bIsProcessElevated
= true;
704 if(bIsUacEnabled
) *bIsUacEnabled
= true;
706 case TokenElevationTypeLimited
:
707 qDebug("Process token elevation type: Limited -> not elevated.\n");
708 if(bIsUacEnabled
) *bIsUacEnabled
= true;
711 qWarning("Unknown tokenElevationType value: %d", tokenElevationType
);
717 qWarning("GetTokenInformation() return an unexpected size!");
724 qWarning("Failed to open process token!");
727 return bIsProcessElevated
;
730 bool MUtils::OS::user_is_admin(void)
732 bool isAdmin
= false;
734 //Check for process elevation and UAC support first!
735 if(MUtils::OS::is_elevated(&isAdmin
))
737 qWarning("Process is elevated -> user is admin!");
741 //If not elevated and UAC is not available -> user must be in admin group!
744 qDebug("UAC is disabled/unavailable -> checking for Administrators group");
745 isAdmin
= user_is_admin_helper();
751 ///////////////////////////////////////////////////////////////////////////////
753 ///////////////////////////////////////////////////////////////////////////////
755 int MUtils::OS::network_status(void)
758 const BOOL ret
= IsNetworkAlive(&dwFlags
);
759 if(GetLastError() == 0)
761 return (ret
!= FALSE
) ? NETWORK_TYPE_YES
: NETWORK_TYPE_NON
;
763 return NETWORK_TYPE_ERR
;
766 ///////////////////////////////////////////////////////////////////////////////
768 ///////////////////////////////////////////////////////////////////////////////
770 bool MUtils::OS::handle_os_message(const void *const message
, long *result
)
772 const MSG
*const msg
= reinterpret_cast<const MSG
*>(message
);
776 case WM_QUERYENDSESSION
:
777 qWarning("WM_QUERYENDSESSION message received!");
778 *result
= MUtils::GUI::broadcast(MUtils::GUI::USER_EVENT_QUERYENDSESSION
, false) ? TRUE
: FALSE
;
781 qWarning("WM_ENDSESSION message received!");
782 if(msg
->wParam
== TRUE
)
784 MUtils::GUI::broadcast(MUtils::GUI::USER_EVENT_ENDSESSION
, false);
785 MUtils::GUI::force_quit();
791 /*ignore this message and let Qt handle it*/
796 ///////////////////////////////////////////////////////////////////////////////
798 ///////////////////////////////////////////////////////////////////////////////
800 void MUtils::OS::sleep_ms(const size_t &duration
)
802 Sleep((DWORD
) duration
);
805 ///////////////////////////////////////////////////////////////////////////////
807 ///////////////////////////////////////////////////////////////////////////////
809 bool MUtils::OS::is_executable_file(const QString
&path
)
811 bool bIsExecutable
= false;
813 if(GetBinaryType(MUTILS_WCHR(QDir::toNativeSeparators(path
)), &binaryType
))
815 bIsExecutable
= (binaryType
== SCS_32BIT_BINARY
|| binaryType
== SCS_64BIT_BINARY
);
817 return bIsExecutable
;
820 ///////////////////////////////////////////////////////////////////////////////
821 // HIBERNATION / SHUTDOWN
822 ///////////////////////////////////////////////////////////////////////////////
824 bool MUtils::OS::is_hibernation_supported(void)
826 bool hibernationSupported
= false;
828 SYSTEM_POWER_CAPABILITIES pwrCaps
;
829 SecureZeroMemory(&pwrCaps
, sizeof(SYSTEM_POWER_CAPABILITIES
));
831 if(GetPwrCapabilities(&pwrCaps
))
833 hibernationSupported
= pwrCaps
.SystemS4
&& pwrCaps
.HiberFilePresent
;
836 return hibernationSupported
;
839 bool MUtils::OS::shutdown_computer(const QString
&message
, const unsigned long timeout
, const bool forceShutdown
, const bool hibernate
)
841 HANDLE hToken
= NULL
;
843 if(OpenProcessToken(GetCurrentProcess(), TOKEN_ADJUST_PRIVILEGES
| TOKEN_QUERY
, &hToken
))
845 TOKEN_PRIVILEGES privileges
;
846 memset(&privileges
, 0, sizeof(TOKEN_PRIVILEGES
));
847 privileges
.PrivilegeCount
= 1;
848 privileges
.Privileges
[0].Attributes
= SE_PRIVILEGE_ENABLED
;
850 if(LookupPrivilegeValue(NULL
, SE_SHUTDOWN_NAME
, &privileges
.Privileges
[0].Luid
))
852 if(AdjustTokenPrivileges(hToken
, FALSE
, &privileges
, NULL
, NULL
, NULL
))
856 if(SetSuspendState(TRUE
, TRUE
, TRUE
))
861 const DWORD reason
= SHTDN_REASON_MAJOR_APPLICATION
| SHTDN_REASON_FLAG_PLANNED
;
862 return InitiateSystemShutdownEx(NULL
, const_cast<wchar_t*>(MUTILS_WCHR(message
)), timeout
, forceShutdown
? TRUE
: FALSE
, FALSE
, reason
);
870 ///////////////////////////////////////////////////////////////////////////////
872 ///////////////////////////////////////////////////////////////////////////////
874 bool MUtils::OS::free_diskspace(const QString
&path
, quint64
&freeSpace
)
876 ULARGE_INTEGER freeBytesAvailable
, totalNumberOfBytes
, totalNumberOfFreeBytes
;
877 if(GetDiskFreeSpaceExW(reinterpret_cast<const wchar_t*>(QDir::toNativeSeparators(path
).utf16()), &freeBytesAvailable
, &totalNumberOfBytes
, &totalNumberOfFreeBytes
))
879 freeSpace
= freeBytesAvailable
.QuadPart
;
887 ///////////////////////////////////////////////////////////////////////////////
889 ///////////////////////////////////////////////////////////////////////////////
891 bool MUtils::OS::shell_open(const QWidget
*parent
, const QString
&url
, const QString
¶meters
, const QString
&directory
, const bool explore
)
893 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;
896 bool MUtils::OS::shell_open(const QWidget
*parent
, const QString
&url
, const bool explore
)
898 return shell_open(parent
, url
, QString(), QString(), explore
);
901 ///////////////////////////////////////////////////////////////////////////////
903 ///////////////////////////////////////////////////////////////////////////////
905 bool MUtils::OS::open_media_file(const QString
&mediaFilePath
)
907 const static wchar_t *registryPrefix
[2] = { L
"SOFTWARE\\", L
"SOFTWARE\\Wow6432Node\\" };
908 const static wchar_t *registryKeys
[3] =
910 L
"Microsoft\\Windows\\CurrentVersion\\Uninstall\\{97D341C8-B0D1-4E4A-A49A-C30B52F168E9}",
911 L
"Microsoft\\Windows\\CurrentVersion\\Uninstall\\{DB9E4EAB-2717-499F-8D56-4CC8A644AB60}",
914 const static wchar_t *appNames
[4] = { L
"smplayer_portable.exe", L
"smplayer.exe", L
"MPUI.exe", L
"foobar2000.exe" };
915 const static wchar_t *valueNames
[2] = { L
"InstallLocation", L
"InstallDir" };
917 for(size_t i
= 0; i
< 3; i
++)
919 for(size_t j
= 0; j
< 2; j
++)
922 HKEY registryKeyHandle
= NULL
;
924 const QString currentKey
= MUTILS_QSTR(registryPrefix
[j
]).append(MUTILS_QSTR(registryKeys
[i
]));
925 if(RegOpenKeyExW(HKEY_LOCAL_MACHINE
, MUTILS_WCHR(currentKey
), 0, KEY_READ
, ®istryKeyHandle
) == ERROR_SUCCESS
)
927 for(size_t k
= 0; k
< 2; k
++)
929 wchar_t Buffer
[4096];
930 DWORD BuffSize
= sizeof(wchar_t*) * 4096;
931 DWORD DataType
= REG_NONE
;
932 if(RegQueryValueExW(registryKeyHandle
, valueNames
[k
], 0, &DataType
, reinterpret_cast<BYTE
*>(Buffer
), &BuffSize
) == ERROR_SUCCESS
)
934 if((DataType
== REG_SZ
) || (DataType
== REG_EXPAND_SZ
) || (DataType
== REG_LINK
))
936 mplayerPath
= MUTILS_QSTR(Buffer
);
941 RegCloseKey(registryKeyHandle
);
944 if(!mplayerPath
.isEmpty())
946 QDir
mplayerDir(mplayerPath
);
947 if(mplayerDir
.exists())
949 for(size_t k
= 0; k
< 4; k
++)
951 if(mplayerDir
.exists(MUTILS_QSTR(appNames
[k
])))
953 qDebug("Player found at:\n%s\n", MUTILS_UTF8(mplayerDir
.absoluteFilePath(MUTILS_QSTR(appNames
[k
]))));
954 QProcess::startDetached(mplayerDir
.absoluteFilePath(MUTILS_QSTR(appNames
[k
])), QStringList() << QDir::toNativeSeparators(mediaFilePath
));
965 ///////////////////////////////////////////////////////////////////////////////
967 ///////////////////////////////////////////////////////////////////////////////
969 static bool change_process_priority_helper(const HANDLE hProcess
, const int priority
)
973 switch(qBound(-2, priority
, 2))
976 ok
= (SetPriorityClass(hProcess
, HIGH_PRIORITY_CLASS
) == TRUE
);
979 if(!(ok
= (SetPriorityClass(hProcess
, ABOVE_NORMAL_PRIORITY_CLASS
) == TRUE
)))
981 ok
= (SetPriorityClass(hProcess
, HIGH_PRIORITY_CLASS
) == TRUE
);
985 ok
= (SetPriorityClass(hProcess
, NORMAL_PRIORITY_CLASS
) == TRUE
);
988 if(!(ok
= (SetPriorityClass(hProcess
, BELOW_NORMAL_PRIORITY_CLASS
) == TRUE
)))
990 ok
= (SetPriorityClass(hProcess
, IDLE_PRIORITY_CLASS
) == TRUE
);
994 ok
= (SetPriorityClass(hProcess
, IDLE_PRIORITY_CLASS
) == TRUE
);
1001 bool MUtils::OS::change_process_priority(const int priority
)
1003 return change_process_priority_helper(GetCurrentProcess(), priority
);
1006 bool MUtils::OS::change_process_priority(const QProcess
*proc
, const int priority
)
1008 if(Q_PID qPid
= proc
->pid())
1010 return change_process_priority_helper(qPid
->hProcess
, priority
);
1018 ///////////////////////////////////////////////////////////////////////////////
1020 ///////////////////////////////////////////////////////////////////////////////
1022 quint32
MUtils::OS::process_id(const QProcess
*const proc
)
1024 PROCESS_INFORMATION
*procInf
= proc
->pid();
1025 return (procInf
) ? procInf
->dwProcessId
: NULL
;
1028 ///////////////////////////////////////////////////////////////////////////////
1029 // PROCESS SUSPEND/RESUME
1030 ///////////////////////////////////////////////////////////////////////////////
1032 bool MUtils::OS::suspend_process(const QProcess
*proc
, const bool suspend
)
1034 if(Q_PID pid
= proc
->pid())
1038 return (SuspendThread(pid
->hThread
) != ((DWORD
) -1));
1042 return (ResumeThread(pid
->hThread
) != ((DWORD
) -1));
1051 ///////////////////////////////////////////////////////////////////////////////
1053 ///////////////////////////////////////////////////////////////////////////////
1055 bool MUtils::OS::setup_timer_resolution(const quint32
&interval
)
1057 return timeBeginPeriod(interval
) == TIMERR_NOERROR
;
1060 bool MUtils::OS::reset_timer_resolution(const quint32
&interval
)
1062 return timeEndPeriod(interval
) == TIMERR_NOERROR
;
1065 ///////////////////////////////////////////////////////////////////////////////
1067 ///////////////////////////////////////////////////////////////////////////////
1069 bool MUtils::OS::check_key_state_esc(void)
1071 return (GetAsyncKeyState(VK_ESCAPE
) & 0x0001) != 0;
1074 ///////////////////////////////////////////////////////////////////////////////
1075 // SHELL CHANGE NOTIFICATION
1076 ///////////////////////////////////////////////////////////////////////////////
1078 void MUtils::OS::shell_change_notification(void)
1080 SHChangeNotify(SHCNE_ASSOCCHANGED
, SHCNF_IDLIST
, NULL
, NULL
);
1083 ///////////////////////////////////////////////////////////////////////////////
1084 // WOW64 REDIRECTION
1085 ///////////////////////////////////////////////////////////////////////////////
1087 typedef BOOL (_stdcall
*Wow64DisableWow64FsRedirectionFun
)(void *OldValue
);
1088 typedef BOOL (_stdcall
*Wow64RevertWow64FsRedirectionFun
)(void *OldValue
);
1090 static QReadWriteLock g_wow64redir_lock
;
1091 static QScopedPointer
<QLibrary
> g_wow64redir_kernel32
;
1092 static Wow64DisableWow64FsRedirectionFun g_wow64redir_disable
= NULL
;
1093 static Wow64RevertWow64FsRedirectionFun g_wow64redir_revert
= NULL
;
1095 static bool wow64fsredir_init()
1097 QWriteLocker
writeLock(&g_wow64redir_lock
);
1098 if(g_wow64redir_disable
&& g_wow64redir_revert
)
1100 return true; /*already initialized*/
1103 if(g_wow64redir_kernel32
.isNull())
1105 g_wow64redir_kernel32
.reset(new QLibrary("kernel32.dll"));
1108 if(!g_wow64redir_kernel32
->isLoaded())
1110 if(!g_wow64redir_kernel32
->load())
1112 return false; /*faild to load kernel32.dll*/
1116 g_wow64redir_disable
= (Wow64DisableWow64FsRedirectionFun
) g_wow64redir_kernel32
->resolve("Wow64DisableWow64FsRedirection");
1117 g_wow64redir_revert
= (Wow64RevertWow64FsRedirectionFun
) g_wow64redir_kernel32
->resolve("Wow64RevertWow64FsRedirection");
1119 return (g_wow64redir_disable
&& g_wow64redir_revert
);
1122 #define WOW64FSREDIR_INIT(RDLOCK) do \
1124 while(!(g_wow64redir_disable && g_wow64redir_revert)) \
1126 (RDLOCK).unlock(); \
1127 if(!wow64fsredir_init()) return false; \
1128 (RDLOCK).relock(); \
1133 bool MUtils::OS::wow64fsredir_disable(void *oldValue
)
1135 QReadLocker
readLock(&g_wow64redir_lock
);
1136 WOW64FSREDIR_INIT(readLock
);
1137 if(g_wow64redir_disable(oldValue
))
1144 bool MUtils::OS::wow64fsredir_revert(void *oldValue
)
1146 QReadLocker
readLock(&g_wow64redir_lock
);
1147 WOW64FSREDIR_INIT(readLock
);
1148 if(g_wow64redir_revert(oldValue
))
1155 ///////////////////////////////////////////////////////////////////////////////
1157 ///////////////////////////////////////////////////////////////////////////////
1159 #if (!(MUTILS_DEBUG))
1160 static __forceinline
bool is_debugger_present(void)
1164 CloseHandle((HANDLE
)((DWORD_PTR
)-3));
1171 BOOL bHaveDebugger
= FALSE
;
1172 if(CheckRemoteDebuggerPresent(GetCurrentProcess(), &bHaveDebugger
))
1174 if(bHaveDebugger
) return true;
1177 return IsDebuggerPresent();
1179 static __forceinline
bool check_debugger_helper(void)
1181 if(is_debugger_present())
1183 MUtils::OS::fatal_exit(L
"Not a debug build. Please unload debugger and try again!");
1189 #define check_debugger_helper() (false)
1192 void MUtils::OS::check_debugger(void)
1194 check_debugger_helper();
1197 static volatile bool g_debug_check
= check_debugger_helper();
1199 ///////////////////////////////////////////////////////////////////////////////
1201 ///////////////////////////////////////////////////////////////////////////////
1203 static MUtils::Internal::CriticalSection g_fatal_exit_lock
;
1204 static volatile bool g_fatal_exit_flag
= true;
1206 static DWORD WINAPI
fatal_exit_helper(LPVOID lpParameter
)
1208 MUtils::OS::system_message_err(L
"GURU MEDITATION", (LPWSTR
) lpParameter
);
1212 void MUtils::OS::fatal_exit(const wchar_t* const errorMessage
)
1214 g_fatal_exit_lock
.enter();
1216 if(!g_fatal_exit_flag
)
1218 return; /*prevent recursive invocation*/
1221 g_fatal_exit_flag
= false;
1223 if(g_main_thread_id
!= GetCurrentThreadId())
1225 if(HANDLE hThreadMain
= OpenThread(THREAD_SUSPEND_RESUME
, FALSE
, g_main_thread_id
))
1227 SuspendThread(hThreadMain
); /*stop main thread*/
1231 if(HANDLE hThread
= CreateThread(NULL
, 0, fatal_exit_helper
, (LPVOID
) errorMessage
, 0, NULL
))
1233 WaitForSingleObject(hThread
, INFINITE
);
1238 TerminateProcess(GetCurrentProcess(), 666);
1242 ///////////////////////////////////////////////////////////////////////////////