1 ///////////////////////////////////////////////////////////////////////////////
2 // MuldeR's Utilities for Qt
3 // Copyright (C) 2004-2019 LoRd_MuldeR <MuldeR2@GMX.de>
5 // This library is free software; you can redistribute it and/or
6 // modify it under the terms of the GNU Lesser General Public
7 // License as published by the Free Software Foundation; either
8 // version 2.1 of the License, or (at your option) any later version.
10 // This library is distributed in the hope that it will be useful,
11 // but WITHOUT ANY WARRANTY; without even the implied warranty of
12 // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
13 // Lesser General Public License for more details.
15 // You should have received a copy of the GNU Lesser General Public
16 // License along with this library; if not, write to the Free Software
17 // Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
19 // http://www.gnu.org/licenses/lgpl-2.1.txt
20 //////////////////////////////////////////////////////////////////////////////////
23 #define WIN32_LEAN_AND_MEAN 1
32 #pragma warning(disable:4091) //for MSVC2015
40 #include <MUtils/Global.h>
41 #include <MUtils/OSSupport.h>
42 #include <MUtils/GUI.h>
44 #include "CriticalSection_Win32.h"
45 #include "Utils_Win32.h"
49 #include <QReadWriteLock>
56 static const DWORD g_main_thread_id
= GetCurrentThreadId();
58 ///////////////////////////////////////////////////////////////////////////////
60 ///////////////////////////////////////////////////////////////////////////////
62 static const UINT g_msgBoxFlags
= MB_TOPMOST
| MB_TASKMODAL
| MB_SETFOREGROUND
;
64 void MUtils::OS::system_message_nfo(const wchar_t *const title
, const wchar_t *const text
)
66 MessageBoxW(NULL
, text
, title
, g_msgBoxFlags
| MB_ICONINFORMATION
);
69 void MUtils::OS::system_message_wrn(const wchar_t *const title
, const wchar_t *const text
)
71 MessageBoxW(NULL
, text
, title
, g_msgBoxFlags
| MB_ICONWARNING
);
74 void MUtils::OS::system_message_err(const wchar_t *const title
, const wchar_t *const text
)
76 MessageBoxW(NULL
, text
, title
, g_msgBoxFlags
| MB_ICONERROR
);
79 ///////////////////////////////////////////////////////////////////////////////
80 // FETCH CLI ARGUMENTS
81 ///////////////////////////////////////////////////////////////////////////////
83 static QReadWriteLock g_arguments_lock
;
84 static QScopedPointer
<MUtils::OS::ArgumentMap
> g_arguments_list
;
86 const QStringList
MUtils::OS::crack_command_line(const QString
&command_line
)
89 LPWSTR
*szArglist
= CommandLineToArgvW(command_line
.isNull() ? GetCommandLineW() : MUTILS_WCHR(command_line
), &nArgs
);
91 QStringList command_line_tokens
;
94 for(int i
= 0; i
< nArgs
; i
++)
96 const QString argStr
= MUTILS_QSTR(szArglist
[i
]).trimmed();
99 command_line_tokens
<< argStr
;
102 LocalFree(szArglist
);
105 return command_line_tokens
;
108 const MUtils::OS::ArgumentMap
&MUtils::OS::arguments(void)
110 QReadLocker
readLock(&g_arguments_lock
);
112 //Already initialized?
113 if(!g_arguments_list
.isNull())
115 return (*(g_arguments_list
.data()));
119 QWriteLocker
writeLock(&g_arguments_lock
);
121 //Still not initialized?
122 if(!g_arguments_list
.isNull())
124 return (*(g_arguments_list
.data()));
127 g_arguments_list
.reset(new ArgumentMap());
128 const QStringList argList
= crack_command_line();
130 if(!argList
.isEmpty())
132 const QString argPrefix
= QLatin1String("--");
133 const QChar separator
= QLatin1Char('=');
135 bool firstToken
= true;
136 for(QStringList::ConstIterator iter
= argList
.constBegin(); iter
!= argList
.constEnd(); iter
++)
141 continue; /*skip executable file name*/
143 if(iter
->startsWith(argPrefix
))
145 const QString argData
= iter
->mid(2).trimmed();
146 if(argData
.length() > 0)
148 const int separatorIndex
= argData
.indexOf(separator
);
149 if(separatorIndex
> 0)
151 const QString argKey
= argData
.left(separatorIndex
).trimmed();
152 const QString argVal
= argData
.mid(separatorIndex
+ 1).trimmed();
153 g_arguments_list
->insertMulti(argKey
.toLower(), argVal
);
157 g_arguments_list
->insertMulti(argData
.toLower(), QString());
163 else if(argList
.empty())
165 qWarning("CommandLineToArgvW() has failed !!!");
168 return (*(g_arguments_list
.data()));
171 ///////////////////////////////////////////////////////////////////////////////
173 ///////////////////////////////////////////////////////////////////////////////
175 typedef struct _progress_callback_data_t
177 MUtils::OS::progress_callback_t callback_function
;
180 progress_callback_data_t
;
182 static DWORD __stdcall
copy_file_progress(LARGE_INTEGER TotalFileSize
, LARGE_INTEGER TotalBytesTransferred
, LARGE_INTEGER StreamSize
, LARGE_INTEGER StreamBytesTransferred
, DWORD dwStreamNumber
, DWORD dwCallbackReason
, HANDLE hSourceFile
, HANDLE hDestinationFile
, LPVOID lpData
)
184 if(const progress_callback_data_t
*data
= (progress_callback_data_t
*) lpData
)
186 const double progress
= qBound(0.0, double(TotalBytesTransferred
.QuadPart
) / double(TotalFileSize
.QuadPart
), 1.0);
187 return data
->callback_function(progress
, data
->user_data
) ? PROGRESS_CONTINUE
: PROGRESS_CANCEL
;
189 return PROGRESS_CONTINUE
;
192 MUTILS_API
bool MUtils::OS::copy_file(const QString
&sourcePath
, const QString
&outputPath
, const bool &overwrite
, const progress_callback_t callback
, void *const userData
)
194 progress_callback_data_t callback_data
= { callback
, userData
};
196 const BOOL result
= CopyFileExW(MUTILS_WCHR(QDir::toNativeSeparators(sourcePath
)), MUTILS_WCHR(QDir::toNativeSeparators(outputPath
)), ((callback_data
.callback_function
) ? copy_file_progress
: NULL
), ((callback_data
.callback_function
) ? &callback_data
: NULL
), &cancel
, (overwrite
? 0 : COPY_FILE_FAIL_IF_EXISTS
));
200 const DWORD errorCode
= GetLastError();
201 if(errorCode
!= ERROR_REQUEST_ABORTED
)
203 qWarning("CopyFile() failed with error code 0x%08X!", errorCode
);
207 qWarning("CopyFile() operation was abroted by user!");
211 return (result
!= FALSE
);
214 ///////////////////////////////////////////////////////////////////////////////
216 ///////////////////////////////////////////////////////////////////////////////
218 static bool get_file_version_helper(const QString fileName
, PVOID buffer
, const size_t &size
, quint16
*const major
, quint16
*const minor
, quint16
*const patch
, quint16
*const build
)
220 if(!GetFileVersionInfo(MUTILS_WCHR(fileName
), 0, size
, buffer
))
222 qWarning("GetFileVersionInfo() has failed, file version cannot be determined!");
226 VS_FIXEDFILEINFO
*verInfo
;
228 if(!VerQueryValue(buffer
, L
"\\", (LPVOID
*)(&verInfo
), &verInfoLen
))
230 qWarning("VerQueryValue() has failed, file version cannot be determined!");
234 if(major
) *major
= quint16((verInfo
->dwFileVersionMS
>> 16) & 0x0000FFFF);
235 if(minor
) *minor
= quint16((verInfo
->dwFileVersionMS
) & 0x0000FFFF);
236 if(patch
) *patch
= quint16((verInfo
->dwFileVersionLS
>> 16) & 0x0000FFFF);
237 if(build
) *build
= quint16((verInfo
->dwFileVersionLS
) & 0x0000FFFF);
242 bool MUtils::OS::get_file_version(const QString fileName
, quint16
*const major
, quint16
*const minor
, quint16
*const patch
, quint16
*const build
)
244 if(major
) *major
= 0U; if(minor
) *minor
= 0U;
245 if(patch
) *patch
= 0U; if(build
) *build
= 0U;
247 const DWORD size
= GetFileVersionInfoSize(MUTILS_WCHR(fileName
), NULL
);
250 qWarning("GetFileVersionInfoSize() has failed, file version cannot be determined!");
254 PVOID buffer
= _malloca(size
);
257 qWarning("Memory allocation has failed!");
261 const bool success
= get_file_version_helper(fileName
, buffer
, size
, major
, minor
, patch
, build
);
267 ///////////////////////////////////////////////////////////////////////////////
268 // OS VERSION DETECTION
269 ///////////////////////////////////////////////////////////////////////////////
271 static bool g_os_version_initialized
= false;
272 static MUtils::OS::Version::os_version_t g_os_version_info
= MUtils::OS::Version::UNKNOWN_OPSYS
;
273 static QReadWriteLock g_os_version_lock
;
275 //Maps marketing names to the actual Windows NT versions
278 MUtils::OS::Version::os_version_t version
;
279 const char friendlyName
[64];
283 { MUtils::OS::Version::WINDOWS_WIN2K
, "Windows 2000" }, //2000
284 { MUtils::OS::Version::WINDOWS_WINXP
, "Windows XP or Windows XP Media Center Edition" }, //XP
285 { MUtils::OS::Version::WINDOWS_XPX64
, "Windows Server 2003 or Windows XP x64" }, //XP_x64
286 { MUtils::OS::Version::WINDOWS_VISTA
, "Windows Vista or Windows Server 2008" }, //Vista
287 { MUtils::OS::Version::WINDOWS_WIN70
, "Windows 7 or Windows Server 2008 R2" }, //7
288 { MUtils::OS::Version::WINDOWS_WIN80
, "Windows 8 or Windows Server 2012" }, //8
289 { MUtils::OS::Version::WINDOWS_WIN81
, "Windows 8.1 or Windows Server 2012 R2" }, //8.1
290 { MUtils::OS::Version::WINDOWS_WN100
, "Windows 10 or Windows Server 2016" }, //10
291 { MUtils::OS::Version::UNKNOWN_OPSYS
, "N/A" }
294 //OS version data dtructures
301 //Comparision operators for os_version_t
302 bool os_version_t::operator== (const os_version_t
&rhs
) const { return (type
== rhs
.type
) && (versionMajor
== rhs
.versionMajor
) && ((versionMinor
== rhs
.versionMinor
)); }
303 bool os_version_t::operator!= (const os_version_t
&rhs
) const { return (type
!= rhs
.type
) || (versionMajor
!= rhs
.versionMajor
) || ((versionMinor
!= rhs
.versionMinor
)); }
304 bool os_version_t::operator> (const os_version_t
&rhs
) const { return (type
== rhs
.type
) && ((versionMajor
> rhs
.versionMajor
) || ((versionMajor
== rhs
.versionMajor
) && (versionMinor
> rhs
.versionMinor
))); }
305 bool os_version_t::operator>= (const os_version_t
&rhs
) const { return (type
== rhs
.type
) && ((versionMajor
> rhs
.versionMajor
) || ((versionMajor
== rhs
.versionMajor
) && (versionMinor
>= rhs
.versionMinor
))); }
306 bool os_version_t::operator< (const os_version_t
&rhs
) const { return (type
== rhs
.type
) && ((versionMajor
< rhs
.versionMajor
) || ((versionMajor
== rhs
.versionMajor
) && (versionMinor
< rhs
.versionMinor
))); }
307 bool os_version_t::operator<= (const os_version_t
&rhs
) const { return (type
== rhs
.type
) && ((versionMajor
< rhs
.versionMajor
) || ((versionMajor
== rhs
.versionMajor
) && (versionMinor
<= rhs
.versionMinor
))); }
309 //Known Windows NT versions
310 const os_version_t WINDOWS_WIN2K
= { OS_WINDOWS
, 5, 0, 2195, 0 }; // 2000
311 const os_version_t WINDOWS_WINXP
= { OS_WINDOWS
, 5, 1, 2600, 0 }; // XP
312 const os_version_t WINDOWS_XPX64
= { OS_WINDOWS
, 5, 2, 3790, 0 }; // XP_x64
313 const os_version_t WINDOWS_VISTA
= { OS_WINDOWS
, 6, 0, 6000, 0 }; // Vista
314 const os_version_t WINDOWS_WIN70
= { OS_WINDOWS
, 6, 1, 7600, 0 }; // 7
315 const os_version_t WINDOWS_WIN80
= { OS_WINDOWS
, 6, 2, 9200, 0 }; // 8
316 const os_version_t WINDOWS_WIN81
= { OS_WINDOWS
, 6, 3, 9600, 0 }; // 8.1
317 const os_version_t WINDOWS_WN100
= { OS_WINDOWS
, 10, 0, 10240, 0 }; // 10
320 const os_version_t UNKNOWN_OPSYS
= { OS_UNKNOWN
, 0, 0, 0, 0 }; // N/A
325 static inline DWORD
SAFE_ADD(const DWORD
&a
, const DWORD
&b
, const DWORD
&limit
= MAXDWORD
)
327 return ((a
>= limit
) || (b
>= limit
) || ((limit
- a
) <= b
)) ? limit
: (a
+ b
);
331 static void initialize_os_version(OSVERSIONINFOEXW
*const osInfo
)
333 memset(osInfo
, 0, sizeof(OSVERSIONINFOEXW
));
334 osInfo
->dwOSVersionInfoSize
= sizeof(OSVERSIONINFOEXW
);
337 static inline DWORD
initialize_step_size(const DWORD
&limit
)
340 while (result
< limit
)
342 result
= SAFE_ADD(result
, result
);
347 #pragma warning(push)
348 #pragma warning(disable: 4996)
350 static bool rtl_get_version(OSVERSIONINFOEXW
*const osInfo
)
352 typedef LONG(__stdcall
*RtlGetVersion
)(LPOSVERSIONINFOEXW
);
353 if (const HMODULE ntdll
= GetModuleHandleW(L
"ntdll"))
355 if (const RtlGetVersion pRtlGetVersion
= (RtlGetVersion
)GetProcAddress(ntdll
, "RtlGetVersion"))
357 initialize_os_version(osInfo
);
358 if (pRtlGetVersion(osInfo
) == 0)
366 initialize_os_version(osInfo
);
367 return (GetVersionExW((LPOSVERSIONINFOW
)osInfo
) != FALSE
);
372 static bool rtl_verify_version(OSVERSIONINFOEXW
*const osInfo
, const ULONG typeMask
, const ULONGLONG condMask
)
374 typedef LONG(__stdcall
*RtlVerifyVersionInfo
)(LPOSVERSIONINFOEXW
, ULONG
, ULONGLONG
);
375 if (const HMODULE ntdll
= GetModuleHandleW(L
"ntdll"))
377 if (const RtlVerifyVersionInfo pRtlVerifyVersionInfo
= (RtlVerifyVersionInfo
)GetProcAddress(ntdll
, "RtlVerifyVersionInfo"))
379 if (pRtlVerifyVersionInfo(osInfo
, typeMask
, condMask
) == 0)
387 return (VerifyVersionInfoW(osInfo
, typeMask
, condMask
) != FALSE
);
390 static bool verify_os_version(const DWORD major
, const DWORD minor
)
392 OSVERSIONINFOEXW osvi
;
393 DWORDLONG dwlConditionMask
= 0;
394 initialize_os_version(&osvi
);
396 //Initialize the OSVERSIONINFOEX structure
397 osvi
.dwMajorVersion
= major
;
398 osvi
.dwMinorVersion
= minor
;
399 osvi
.dwPlatformId
= VER_PLATFORM_WIN32_NT
;
401 //Initialize the condition mask
402 VER_SET_CONDITION(dwlConditionMask
, VER_MAJORVERSION
, VER_GREATER_EQUAL
);
403 VER_SET_CONDITION(dwlConditionMask
, VER_MINORVERSION
, VER_GREATER_EQUAL
);
404 VER_SET_CONDITION(dwlConditionMask
, VER_PLATFORMID
, VER_EQUAL
);
407 const BOOL ret
= rtl_verify_version(&osvi
, VER_MAJORVERSION
| VER_MINORVERSION
| VER_PLATFORMID
, dwlConditionMask
);
412 if(GetLastError() != ERROR_OLD_WIN_VERSION
)
414 qWarning("VerifyVersionInfo() system call has failed!");
418 return (ret
!= FALSE
);
421 static bool verify_os_build(const DWORD build
)
423 OSVERSIONINFOEXW osvi
;
424 DWORDLONG dwlConditionMask
= 0;
425 initialize_os_version(&osvi
);
427 //Initialize the OSVERSIONINFOEX structure
428 osvi
.dwBuildNumber
= build
;
429 osvi
.dwPlatformId
= VER_PLATFORM_WIN32_NT
;
431 //Initialize the condition mask
432 VER_SET_CONDITION(dwlConditionMask
, VER_BUILDNUMBER
, VER_GREATER_EQUAL
);
433 VER_SET_CONDITION(dwlConditionMask
, VER_PLATFORMID
, VER_EQUAL
);
436 const BOOL ret
= rtl_verify_version(&osvi
, VER_BUILDNUMBER
| VER_PLATFORMID
, dwlConditionMask
);
441 if (GetLastError() != ERROR_OLD_WIN_VERSION
)
443 qWarning("VerifyVersionInfo() system call has failed!");
447 return (ret
!= FALSE
);
450 static bool verify_os_spack(const WORD spack
)
452 OSVERSIONINFOEXW osvi
;
453 DWORDLONG dwlConditionMask
= 0;
454 initialize_os_version(&osvi
);
456 //Initialize the OSVERSIONINFOEX structure
457 osvi
.wServicePackMajor
= spack
;
458 osvi
.dwPlatformId
= VER_PLATFORM_WIN32_NT
;
460 //Initialize the condition mask
461 VER_SET_CONDITION(dwlConditionMask
, VER_SERVICEPACKMAJOR
, VER_GREATER_EQUAL
);
462 VER_SET_CONDITION(dwlConditionMask
, VER_PLATFORMID
, VER_EQUAL
);
465 const BOOL ret
= rtl_verify_version(&osvi
, VER_SERVICEPACKMAJOR
| VER_PLATFORMID
, dwlConditionMask
);
470 if (GetLastError() != ERROR_OLD_WIN_VERSION
)
472 qWarning("VerifyVersionInfo() system call has failed!");
476 return (ret
!= FALSE
);
479 static bool get_real_os_version(unsigned int *const major
, unsigned int *const minor
, unsigned int *const build
, unsigned int *const spack
, bool *const pbOverride
)
481 static const DWORD MAX_VERSION
= MAXWORD
;
482 static const DWORD MAX_BUILDNO
= MAXINT
;
483 static const DWORD MAX_SRVCPCK
= MAXWORD
;
485 *major
= *minor
= *build
= *spack
= 0U;
488 //Initialize local variables
489 OSVERSIONINFOEXW osvi
;
490 memset(&osvi
, 0, sizeof(OSVERSIONINFOEXW
));
491 osvi
.dwOSVersionInfoSize
= sizeof(OSVERSIONINFOEXW
);
493 //Try GetVersionEx() first
494 if(rtl_get_version(&osvi
) == FALSE
)
496 qWarning("GetVersionEx() has failed, cannot detect Windows version!");
500 //Make sure we are running on NT
501 if(osvi
.dwPlatformId
== VER_PLATFORM_WIN32_NT
)
503 *major
= osvi
.dwMajorVersion
;
504 *minor
= osvi
.dwMinorVersion
;
505 *build
= osvi
.dwBuildNumber
;
506 *spack
= osvi
.wServicePackMajor
;
510 if (verify_os_version(4, 0))
518 qWarning("Not running on Windows NT, unsupported operating system!");
524 for (DWORD nextMajor
= (*major
) + 1; nextMajor
<= MAX_VERSION
; nextMajor
++)
526 if (verify_os_version(nextMajor
, 0))
537 for (DWORD nextMinor
= (*minor
) + 1; nextMinor
<= MAX_VERSION
; nextMinor
++)
539 if (verify_os_version((*major
), nextMinor
))
549 if (verify_os_build(SAFE_ADD((*build
), 1, MAX_BUILDNO
)))
551 DWORD stepSize
= initialize_step_size(MAX_BUILDNO
);
552 for (DWORD nextBuildNo
= SAFE_ADD((*build
), stepSize
, MAX_BUILDNO
); (*build
) < MAX_BUILDNO
; nextBuildNo
= SAFE_ADD((*build
), stepSize
, MAX_BUILDNO
))
554 if (verify_os_build(nextBuildNo
))
556 *build
= nextBuildNo
;
562 stepSize
= stepSize
/ 2;
570 if (verify_os_spack(SAFE_ADD((*spack
), 1, MAX_SRVCPCK
)))
572 DWORD stepSize
= initialize_step_size(MAX_SRVCPCK
);
573 for (DWORD nextSPackNo
= SAFE_ADD((*spack
), stepSize
, MAX_SRVCPCK
); (*spack
) < MAX_SRVCPCK
; nextSPackNo
= SAFE_ADD((*spack
), stepSize
, MAX_SRVCPCK
))
575 if (verify_os_spack(nextSPackNo
))
577 *build
= nextSPackNo
;
583 stepSize
= stepSize
/ 2;
593 const MUtils::OS::Version::os_version_t
&MUtils::OS::os_version(void)
595 QReadLocker
readLock(&g_os_version_lock
);
597 //Already initialized?
598 if(g_os_version_initialized
)
600 return g_os_version_info
;
604 QWriteLocker
writeLock(&g_os_version_lock
);
607 if(g_os_version_initialized
)
609 return g_os_version_info
;
613 unsigned int major
, minor
, build
, spack
; bool overrideFlg
;
614 if(get_real_os_version(&major
, &minor
, &build
, &spack
, &overrideFlg
))
616 g_os_version_info
.type
= Version::OS_WINDOWS
;
617 g_os_version_info
.versionMajor
= major
;
618 g_os_version_info
.versionMinor
= minor
;
619 g_os_version_info
.versionBuild
= build
;
620 g_os_version_info
.versionSPack
= spack
;
621 g_os_version_info
.overrideFlag
= overrideFlg
;
625 qWarning("Failed to determine the operating system version!");
629 g_os_version_initialized
= true;
630 return g_os_version_info
;
633 const char *MUtils::OS::os_friendly_name(const MUtils::OS::Version::os_version_t
&os_version
)
635 for(size_t i
= 0; g_os_version_lut
[i
].version
!= MUtils::OS::Version::UNKNOWN_OPSYS
; i
++)
637 if(os_version
== g_os_version_lut
[i
].version
)
639 return g_os_version_lut
[i
].friendlyName
;
646 ///////////////////////////////////////////////////////////////////////////////
648 ///////////////////////////////////////////////////////////////////////////////
650 static bool g_wine_deteced
= false;
651 static bool g_wine_initialized
= false;
652 static QReadWriteLock g_wine_lock
;
654 static const bool detect_wine(void)
656 void *const ptr
= MUtils::Win32Utils::resolve
<void*>(QLatin1String("ntdll"), QLatin1String("wine_get_version"));
657 return (ptr
!= NULL
);
660 const bool &MUtils::OS::running_on_wine(void)
662 QReadLocker
readLock(&g_wine_lock
);
664 //Already initialized?
665 if(g_wine_initialized
)
667 return g_wine_deteced
;
671 QWriteLocker
writeLock(&g_wine_lock
);
674 if(g_wine_initialized
)
676 return g_wine_deteced
;
680 g_wine_deteced
= detect_wine();
681 g_wine_initialized
= true;
683 return g_wine_deteced
;
686 ///////////////////////////////////////////////////////////////////////////////
688 ///////////////////////////////////////////////////////////////////////////////
690 static QReadWriteLock g_known_folders_lock
;
691 static QScopedPointer
<QHash
<size_t, QString
>> g_known_folders_data
;
693 typedef HRESULT (WINAPI
*SHGetKnownFolderPath_t
)(const GUID
&rfid
, DWORD dwFlags
, HANDLE hToken
, PWSTR
*ppszPath
);
694 typedef HRESULT (WINAPI
*SHGetFolderPath_t
) (HWND hwndOwner
, int nFolder
, HANDLE hToken
, DWORD dwFlags
, LPWSTR pszPath
);
696 const QString
&MUtils::OS::known_folder(known_folder_t folder_id
)
698 typedef enum { KF_FLAG_CREATE
= 0x00008000 } kf_flags_t
;
707 { 0x001a, {0x3EB685DB,0x65F9,0x4CF6,{0xA0,0x3A,0xE3,0xEF,0x65,0x72,0x9F,0x3D}} }, //CSIDL_APPDATA
708 { 0x001c, {0xF1B32785,0x6FBA,0x4FCF,{0x9D,0x55,0x7B,0x8E,0x7F,0x15,0x70,0x91}} }, //CSIDL_LOCAL_APPDATA
709 { 0x0028, {0x5E6C858F,0x0E22,0x4760,{0x9A,0xFE,0xEA,0x33,0x17,0xB6,0x71,0x73}} }, //CSIDL_PROFILE
710 { 0x0026, {0x905e63b6,0xc1bf,0x494e,{0xb2,0x9c,0x65,0xb7,0x32,0xd3,0xd2,0x1a}} }, //CSIDL_PROGRAM_FILES
711 { 0x0025, {0x1AC14E77,0x02E7,0x4E5D,{0xB7,0x44,0x2E,0xB1,0xAE,0x51,0x98,0xB7}} }, //CSIDL_SYSTEM_FOLDER
712 { 0x0024, {0xF38BF404,0x1D43,0x42F2,{0x93,0x05,0x67,0xDE,0x0B,0x28,0xFC,0x23}} }, //CSIDL_WINDOWS_FOLDER
715 size_t folderId
= size_t(-1);
719 case FOLDER_ROAMING_DATA
: folderId
= 0; break;
720 case FOLDER_LOCALAPPDATA
: folderId
= 1; break;
721 case FOLDER_USER_PROFILE
: folderId
= 2; break;
722 case FOLDER_PROGRAMFILES
: folderId
= 3; break;
723 case FOLDER_SYSTEMFOLDER
: folderId
= 4; break;
724 case FOLDER_SYSTROOT_DIR
: folderId
= 5; break;
726 qWarning("Invalid 'known' folder was requested!");
727 return Internal::g_empty
;
730 QReadLocker
readLock(&g_known_folders_lock
);
733 if(!g_known_folders_data
.isNull())
735 if(g_known_folders_data
->contains(folderId
))
737 return (*g_known_folders_data
)[folderId
];
741 //Obtain write lock to initialize
743 QWriteLocker
writeLock(&g_known_folders_lock
);
745 //Still not in cache?
746 if(!g_known_folders_data
.isNull())
748 if(g_known_folders_data
->contains(folderId
))
750 return (*g_known_folders_data
)[folderId
];
754 //Initialize on first call
755 if(g_known_folders_data
.isNull())
757 g_known_folders_data
.reset(new QHash
<size_t, QString
>());
762 //Try SHGetKnownFolderPath() first!
763 if(const SHGetKnownFolderPath_t known_folders_fpGetKnownFolderPath
= MUtils::Win32Utils::resolve
<SHGetKnownFolderPath_t
>(QLatin1String("shell32"), QLatin1String("SHGetKnownFolderPath")))
766 if(known_folders_fpGetKnownFolderPath(s_folders
[folderId
].guid
, KF_FLAG_CREATE
, NULL
, &path
) == S_OK
)
768 //MessageBoxW(0, path, L"SHGetKnownFolderPath", MB_TOPMOST);
769 const QDir folderTemp
= QDir(QDir::fromNativeSeparators(MUTILS_QSTR(path
)));
770 if(folderTemp
.exists())
772 folderPath
= folderTemp
.canonicalPath();
778 //Fall back to SHGetFolderPathW()
779 if (folderPath
.isEmpty())
781 if (const SHGetFolderPath_t known_folders_fpGetFolderPath
= MUtils::Win32Utils::resolve
<SHGetFolderPath_t
>(QLatin1String("shell32"), QLatin1String("SHGetFolderPathW")))
783 QScopedArrayPointer
<WCHAR
> path(new WCHAR
[4096]);
784 if (known_folders_fpGetFolderPath(NULL
, s_folders
[folderId
].csidl
| CSIDL_FLAG_CREATE
, NULL
, NULL
, path
.data()) == S_OK
)
786 //MessageBoxW(0, path, L"SHGetFolderPathW", MB_TOPMOST);
787 const QDir folderTemp
= QDir(QDir::fromNativeSeparators(MUTILS_QSTR(path
.data())));
788 if (folderTemp
.exists())
790 folderPath
= folderTemp
.canonicalPath();
797 if (!folderPath
.isEmpty())
799 g_known_folders_data
->insert(folderId
, folderPath
);
800 return (*g_known_folders_data
)[folderId
];
803 return Internal::g_empty
;
806 ///////////////////////////////////////////////////////////////////////////////
807 // CURRENT DATA & TIME
808 ///////////////////////////////////////////////////////////////////////////////
810 QDate
MUtils::OS::current_date(void)
812 const DWORD MAX_PROC
= 1024;
813 QScopedArrayPointer
<DWORD
> processes(new DWORD
[MAX_PROC
]);
814 DWORD bytesReturned
= 0;
816 if(!EnumProcesses(processes
.data(), sizeof(DWORD
) * MAX_PROC
, &bytesReturned
))
818 return QDate::currentDate();
821 const DWORD procCount
= bytesReturned
/ sizeof(DWORD
);
822 ULARGE_INTEGER lastStartTime
;
823 memset(&lastStartTime
, 0, sizeof(ULARGE_INTEGER
));
825 for(DWORD i
= 0; i
< procCount
; i
++)
827 if(HANDLE hProc
= OpenProcess(PROCESS_QUERY_INFORMATION
, FALSE
, processes
[i
]))
829 FILETIME processTime
[4];
830 if(GetProcessTimes(hProc
, &processTime
[0], &processTime
[1], &processTime
[2], &processTime
[3]))
832 ULARGE_INTEGER timeCreation
;
833 timeCreation
.LowPart
= processTime
[0].dwLowDateTime
;
834 timeCreation
.HighPart
= processTime
[0].dwHighDateTime
;
835 if(timeCreation
.QuadPart
> lastStartTime
.QuadPart
)
837 lastStartTime
.QuadPart
= timeCreation
.QuadPart
;
844 FILETIME lastStartTime_fileTime
;
845 lastStartTime_fileTime
.dwHighDateTime
= lastStartTime
.HighPart
;
846 lastStartTime_fileTime
.dwLowDateTime
= lastStartTime
.LowPart
;
848 FILETIME lastStartTime_localTime
;
849 if(!FileTimeToLocalFileTime(&lastStartTime_fileTime
, &lastStartTime_localTime
))
851 memcpy(&lastStartTime_localTime
, &lastStartTime_fileTime
, sizeof(FILETIME
));
854 SYSTEMTIME lastStartTime_system
;
855 if(!FileTimeToSystemTime(&lastStartTime_localTime
, &lastStartTime_system
))
857 memset(&lastStartTime_system
, 0, sizeof(SYSTEMTIME
));
858 lastStartTime_system
.wYear
= 1970; lastStartTime_system
.wMonth
= lastStartTime_system
.wDay
= 1;
861 const QDate currentDate
= QDate::currentDate();
862 const QDate processDate
= QDate(lastStartTime_system
.wYear
, lastStartTime_system
.wMonth
, lastStartTime_system
.wDay
);
863 return (currentDate
>= processDate
) ? currentDate
: processDate
;
866 quint64
MUtils::OS::current_file_time(void)
869 GetSystemTimeAsFileTime(&fileTime
);
872 temp
.HighPart
= fileTime
.dwHighDateTime
;
873 temp
.LowPart
= fileTime
.dwLowDateTime
;
875 return temp
.QuadPart
;
878 ///////////////////////////////////////////////////////////////////////////////
880 ///////////////////////////////////////////////////////////////////////////////
882 typedef DWORD(_stdcall
*GetPathNameByHandleFun
)(HANDLE hFile
, LPWSTR lpszFilePath
, DWORD cchFilePath
, DWORD dwFlags
);
884 static QString
get_file_path_drive_list(void)
887 const DWORD len
= GetLogicalDriveStringsW(0, NULL
);
890 if (wchar_t *const buffer
= (wchar_t*) _malloca(sizeof(wchar_t) * len
))
892 const DWORD ret
= GetLogicalDriveStringsW(len
, buffer
);
893 if ((ret
> 0) && (ret
< len
))
895 const wchar_t *ptr
= buffer
;
896 while (const size_t current_len
= wcslen(ptr
))
898 list
.append(QChar(*reinterpret_cast<const ushort
*>(ptr
)));
899 ptr
+= (current_len
+ 1);
908 static void get_file_path_translate(QString
&path
)
910 static const DWORD BUFSIZE
= 2048;
911 wchar_t buffer
[BUFSIZE
], drive
[3];
913 const QString driveList
= get_file_path_drive_list();
914 wcscpy_s(drive
, 3, L
"?:");
915 for (const wchar_t *current
= MUTILS_WCHR(driveList
); *current
; current
++)
917 drive
[0] = (*current
);
918 if (QueryDosDeviceW(drive
, buffer
, MAX_PATH
))
920 const QString prefix
= MUTILS_QSTR(buffer
);
921 if (path
.startsWith(prefix
, Qt::CaseInsensitive
))
923 path
.remove(0, prefix
.length()).prepend(QLatin1Char(':')).prepend(QChar(*reinterpret_cast<const ushort
*>(current
)));
930 static QString
get_file_path_fallback(const HANDLE
&hFile
)
934 const HANDLE hFileMap
= CreateFileMappingW(hFile
, NULL
, PAGE_READONLY
, 0, 1, NULL
);
937 void *const pMem
= MapViewOfFile(hFileMap
, FILE_MAP_READ
, 0, 0, 1);
940 static const size_t BUFFSIZE
= 2048;
941 wchar_t buffer
[BUFFSIZE
];
942 if (GetMappedFileNameW(GetCurrentProcess(), pMem
, buffer
, BUFFSIZE
) > 0)
944 filePath
= MUTILS_QSTR(buffer
);
946 UnmapViewOfFile(pMem
);
948 CloseHandle(hFileMap
);
951 if (!filePath
.isEmpty())
953 get_file_path_translate(filePath
);
959 QString
MUtils::OS::get_file_path(const int &fd
)
963 const GetPathNameByHandleFun getPathNameByHandleFun
= MUtils::Win32Utils::resolve
<GetPathNameByHandleFun
>(QLatin1String("kernel32"), QLatin1String("GetFinalPathNameByHandleW"));
964 if (!getPathNameByHandleFun
)
966 return get_file_path_fallback((HANDLE
)_get_osfhandle(fd
));
969 const HANDLE handle
= (HANDLE
) _get_osfhandle(fd
);
970 const DWORD len
= getPathNameByHandleFun(handle
, NULL
, 0, FILE_NAME_OPENED
);
973 if (wchar_t *const buffer
= (wchar_t*)_malloca(sizeof(wchar_t) * len
))
975 const DWORD ret
= getPathNameByHandleFun(handle
, buffer
, len
, FILE_NAME_OPENED
);
976 if ((ret
> 0) && (ret
< len
))
978 const QString
path(MUTILS_QSTR(buffer
));
979 return path
.startsWith(QLatin1String("\\\\?\\")) ? path
.mid(4) : path
;
989 ///////////////////////////////////////////////////////////////////////////////
991 ///////////////////////////////////////////////////////////////////////////////
993 static bool user_is_admin_helper(void)
995 HANDLE hToken
= NULL
;
996 if(!OpenProcessToken(GetCurrentProcess(), TOKEN_QUERY
, &hToken
))
1002 if(!GetTokenInformation(hToken
, TokenGroups
, NULL
, 0, &dwSize
))
1004 if(GetLastError() != ERROR_INSUFFICIENT_BUFFER
)
1006 CloseHandle(hToken
);
1011 PTOKEN_GROUPS lpGroups
= (PTOKEN_GROUPS
) malloc(dwSize
);
1014 CloseHandle(hToken
);
1018 if(!GetTokenInformation(hToken
, TokenGroups
, lpGroups
, dwSize
, &dwSize
))
1021 CloseHandle(hToken
);
1025 PSID lpSid
= NULL
; SID_IDENTIFIER_AUTHORITY Authority
= {SECURITY_NT_AUTHORITY
};
1026 if(!AllocateAndInitializeSid(&Authority
, 2, SECURITY_BUILTIN_DOMAIN_RID
, DOMAIN_ALIAS_RID_ADMINS
, 0, 0, 0, 0, 0, 0, &lpSid
))
1029 CloseHandle(hToken
);
1033 bool bResult
= false;
1034 for(DWORD i
= 0; i
< lpGroups
->GroupCount
; i
++)
1036 if(EqualSid(lpSid
, lpGroups
->Groups
[i
].Sid
))
1045 CloseHandle(hToken
);
1049 bool MUtils::OS::is_elevated(bool *bIsUacEnabled
)
1053 *bIsUacEnabled
= false;
1056 bool bIsProcessElevated
= false;
1057 HANDLE hToken
= NULL
;
1059 if(OpenProcessToken(GetCurrentProcess(), TOKEN_QUERY
, &hToken
))
1061 TOKEN_ELEVATION_TYPE tokenElevationType
;
1063 if(GetTokenInformation(hToken
, TokenElevationType
, &tokenElevationType
, sizeof(TOKEN_ELEVATION_TYPE
), &returnLength
))
1065 if(returnLength
== sizeof(TOKEN_ELEVATION_TYPE
))
1067 switch(tokenElevationType
)
1069 case TokenElevationTypeDefault
:
1070 qDebug("Process token elevation type: Default -> UAC is disabled.\n");
1072 case TokenElevationTypeFull
:
1073 qWarning("Process token elevation type: Full -> potential security risk!\n");
1074 bIsProcessElevated
= true;
1075 if(bIsUacEnabled
) *bIsUacEnabled
= true;
1077 case TokenElevationTypeLimited
:
1078 qDebug("Process token elevation type: Limited -> not elevated.\n");
1079 if(bIsUacEnabled
) *bIsUacEnabled
= true;
1082 qWarning("Unknown tokenElevationType value: %d", tokenElevationType
);
1088 qWarning("GetTokenInformation() return an unexpected size!");
1091 CloseHandle(hToken
);
1095 qWarning("Failed to open process token!");
1098 return bIsProcessElevated
;
1101 bool MUtils::OS::user_is_admin(void)
1103 bool isAdmin
= false;
1105 //Check for process elevation and UAC support first!
1106 if(MUtils::OS::is_elevated(&isAdmin
))
1108 qWarning("Process is elevated -> user is admin!");
1112 //If not elevated and UAC is not available -> user must be in admin group!
1115 qDebug("UAC is disabled/unavailable -> checking for Administrators group");
1116 isAdmin
= user_is_admin_helper();
1122 ///////////////////////////////////////////////////////////////////////////////
1124 ///////////////////////////////////////////////////////////////////////////////
1126 int MUtils::OS::network_status(void)
1129 const BOOL ret
= IsNetworkAlive(&dwFlags
);
1130 if(GetLastError() == 0)
1132 return (ret
!= FALSE
) ? NETWORK_TYPE_YES
: NETWORK_TYPE_NON
;
1134 return NETWORK_TYPE_ERR
;
1137 ///////////////////////////////////////////////////////////////////////////////
1139 ///////////////////////////////////////////////////////////////////////////////
1141 bool MUtils::OS::handle_os_message(const void *const message
, long *result
)
1143 const MSG
*const msg
= reinterpret_cast<const MSG
*>(message
);
1145 switch(msg
->message
)
1147 case WM_QUERYENDSESSION
:
1148 qWarning("WM_QUERYENDSESSION message received!");
1149 *result
= MUtils::GUI::broadcast(MUtils::GUI::USER_EVENT_QUERYENDSESSION
, false) ? TRUE
: FALSE
;
1152 qWarning("WM_ENDSESSION message received!");
1153 if(msg
->wParam
== TRUE
)
1155 MUtils::GUI::broadcast(MUtils::GUI::USER_EVENT_ENDSESSION
, false);
1156 MUtils::GUI::force_quit();
1162 /*ignore this message and let Qt handle it*/
1167 ///////////////////////////////////////////////////////////////////////////////
1169 ///////////////////////////////////////////////////////////////////////////////
1171 void MUtils::OS::sleep_ms(const size_t &duration
)
1173 Sleep((DWORD
) duration
);
1176 ///////////////////////////////////////////////////////////////////////////////
1178 ///////////////////////////////////////////////////////////////////////////////
1180 static int g_library_as_image_resource_supported
= -1;
1181 static QReadWriteLock g_library_as_image_resource_supported_lock
;
1183 static bool library_as_image_resource_supported()
1185 QReadLocker
readLocker(&g_library_as_image_resource_supported_lock
);
1186 if (g_library_as_image_resource_supported
>= 0)
1188 return (g_library_as_image_resource_supported
> 0);
1191 readLocker
.unlock();
1192 QWriteLocker
writeLocker(&g_library_as_image_resource_supported_lock
);
1194 if (g_library_as_image_resource_supported
< 0)
1196 g_library_as_image_resource_supported
= 0;
1197 OSVERSIONINFOEXW osvi
;
1198 if (rtl_get_version(&osvi
))
1200 if ((osvi
.dwPlatformId
== VER_PLATFORM_WIN32_NT
) && (osvi
.dwMajorVersion
>= 6U))
1202 g_library_as_image_resource_supported
= 1;
1207 return (g_library_as_image_resource_supported
> 0);
1210 bool MUtils::OS::is_executable_file(const QString
&path
)
1213 if(GetBinaryType(MUTILS_WCHR(QDir::toNativeSeparators(path
)), &binaryType
))
1215 return ((binaryType
== SCS_32BIT_BINARY
) || (binaryType
== SCS_64BIT_BINARY
));
1218 const DWORD errorCode
= GetLastError();
1219 qWarning("GetBinaryType() failed with error: 0x%08X", errorCode
);
1223 bool MUtils::OS::is_library_file(const QString
&path
)
1225 const DWORD flags
= library_as_image_resource_supported() ? (LOAD_LIBRARY_AS_DATAFILE
| LOAD_LIBRARY_AS_IMAGE_RESOURCE
) : (LOAD_LIBRARY_AS_DATAFILE
| DONT_RESOLVE_DLL_REFERENCES
);
1226 if (const HMODULE hMod
= LoadLibraryEx(MUTILS_WCHR(QDir::toNativeSeparators(path
)), NULL
, flags
))
1232 const DWORD errorCode
= GetLastError();
1233 qWarning("LoadLibraryEx() failed with error: 0x%08X", errorCode
);
1237 ///////////////////////////////////////////////////////////////////////////////
1238 // HIBERNATION / SHUTDOWN
1239 ///////////////////////////////////////////////////////////////////////////////
1241 bool MUtils::OS::is_hibernation_supported(void)
1243 bool hibernationSupported
= false;
1245 SYSTEM_POWER_CAPABILITIES pwrCaps
;
1246 SecureZeroMemory(&pwrCaps
, sizeof(SYSTEM_POWER_CAPABILITIES
));
1248 if(GetPwrCapabilities(&pwrCaps
))
1250 hibernationSupported
= pwrCaps
.SystemS4
&& pwrCaps
.HiberFilePresent
;
1253 return hibernationSupported
;
1256 bool MUtils::OS::shutdown_computer(const QString
&message
, const unsigned long timeout
, const bool forceShutdown
, const bool hibernate
)
1258 HANDLE hToken
= NULL
;
1260 if(OpenProcessToken(GetCurrentProcess(), TOKEN_ADJUST_PRIVILEGES
| TOKEN_QUERY
, &hToken
))
1262 TOKEN_PRIVILEGES privileges
;
1263 memset(&privileges
, 0, sizeof(TOKEN_PRIVILEGES
));
1264 privileges
.PrivilegeCount
= 1;
1265 privileges
.Privileges
[0].Attributes
= SE_PRIVILEGE_ENABLED
;
1267 if(LookupPrivilegeValue(NULL
, SE_SHUTDOWN_NAME
, &privileges
.Privileges
[0].Luid
))
1269 if(AdjustTokenPrivileges(hToken
, FALSE
, &privileges
, NULL
, NULL
, NULL
))
1273 if(SetSuspendState(TRUE
, TRUE
, TRUE
))
1278 const DWORD reason
= SHTDN_REASON_MAJOR_APPLICATION
| SHTDN_REASON_FLAG_PLANNED
;
1279 return InitiateSystemShutdownEx(NULL
, const_cast<wchar_t*>(MUTILS_WCHR(message
)), timeout
, forceShutdown
? TRUE
: FALSE
, FALSE
, reason
);
1287 ///////////////////////////////////////////////////////////////////////////////
1289 ///////////////////////////////////////////////////////////////////////////////
1291 bool MUtils::OS::free_diskspace(const QString
&path
, quint64
&freeSpace
)
1293 ULARGE_INTEGER freeBytesAvailable
, totalNumberOfBytes
, totalNumberOfFreeBytes
;
1294 if(GetDiskFreeSpaceExW(reinterpret_cast<const wchar_t*>(QDir::toNativeSeparators(path
).utf16()), &freeBytesAvailable
, &totalNumberOfBytes
, &totalNumberOfFreeBytes
))
1296 freeSpace
= freeBytesAvailable
.QuadPart
;
1304 ///////////////////////////////////////////////////////////////////////////////
1306 ///////////////////////////////////////////////////////////////////////////////
1308 static wchar_t get_drive_letter(const QString
&path
)
1310 QString nativePath
= QDir::toNativeSeparators(path
);
1311 while (nativePath
.startsWith("\\\\?\\") || nativePath
.startsWith("\\\\.\\"))
1313 nativePath
= QDir::toNativeSeparators(nativePath
.mid(4));
1315 if ((path
.length() > 1) && (path
[1] == QLatin1Char(':')))
1317 const wchar_t letter
= static_cast<wchar_t>(path
[0].unicode());
1318 if (((letter
>= 'A') && (letter
<= 'Z')) || ((letter
>= 'a') && (letter
<= 'z')))
1320 return towupper(letter
);
1323 return L
'\0'; /*invalid path spec*/
1326 static QSet
<DWORD
> get_physical_drive_ids(const wchar_t drive_letter
)
1328 QSet
<DWORD
> physical_drives
;
1329 wchar_t driveName
[8];
1330 _snwprintf_s(driveName
, 8, _TRUNCATE
, L
"\\\\.\\%c:", drive_letter
);
1331 const HANDLE hDrive
= CreateFileW(driveName
, 0, FILE_SHARE_READ
| FILE_SHARE_WRITE
, NULL
, OPEN_EXISTING
, 0, NULL
);
1332 if (hDrive
&& (hDrive
!= INVALID_HANDLE_VALUE
))
1334 const size_t BUFF_SIZE
= sizeof(VOLUME_DISK_EXTENTS
) + (32U * sizeof(DISK_EXTENT
));
1335 VOLUME_DISK_EXTENTS
*const diskExtents
= (VOLUME_DISK_EXTENTS
*)_malloca(BUFF_SIZE
);
1337 if (DeviceIoControl(hDrive
, IOCTL_VOLUME_GET_VOLUME_DISK_EXTENTS
, NULL
, 0, (LPVOID
)diskExtents
, (DWORD
)BUFF_SIZE
, (LPDWORD
)&dwSize
, NULL
))
1339 for (DWORD index
= 0U; index
< diskExtents
->NumberOfDiskExtents
; ++index
)
1341 physical_drives
.insert(diskExtents
->Extents
[index
].DiskNumber
);
1344 _freea(diskExtents
);
1345 CloseHandle(hDrive
);
1347 return physical_drives
;
1350 static bool incurs_seek_penalty(const DWORD device_id
)
1352 wchar_t driveName
[24];
1353 _snwprintf_s(driveName
, 24, _TRUNCATE
, L
"\\\\?\\PhysicalDrive%u", device_id
);
1354 const HANDLE hDevice
= CreateFileW(driveName
, 0, FILE_SHARE_READ
| FILE_SHARE_WRITE
, NULL
, OPEN_EXISTING
, 0, NULL
);
1355 bool seeking_penalty
= true;
1356 if (hDevice
&& (hDevice
!= INVALID_HANDLE_VALUE
))
1358 STORAGE_PROPERTY_QUERY spq
;
1359 DEVICE_SEEK_PENALTY_DESCRIPTOR dspd
;
1360 memset(&spq
, 0, sizeof(STORAGE_PROPERTY_QUERY
));
1361 spq
.PropertyId
= (STORAGE_PROPERTY_ID
)StorageDeviceSeekPenaltyProperty
;
1362 spq
.QueryType
= PropertyStandardQuery
;
1364 if (DeviceIoControl(hDevice
, IOCTL_STORAGE_QUERY_PROPERTY
, (LPVOID
)&spq
, (DWORD
)sizeof(spq
), (LPVOID
)&dspd
, (DWORD
)sizeof(dspd
), (LPDWORD
)&dwSize
, NULL
))
1366 seeking_penalty
= dspd
.IncursSeekPenalty
;
1368 CloseHandle(hDevice
);
1370 return seeking_penalty
;
1373 static bool is_fast_seeking_drive(const wchar_t drive_letter
)
1375 bool fast_seeking
= false;
1376 const QSet
<DWORD
> physical_drive_ids
= get_physical_drive_ids(drive_letter
);
1377 if (!physical_drive_ids
.empty())
1379 fast_seeking
= true;
1380 for (QSet
<DWORD
>::const_iterator iter
= physical_drive_ids
.constBegin(); iter
!= physical_drive_ids
.constEnd(); ++iter
)
1382 fast_seeking
= fast_seeking
&& (!incurs_seek_penalty(*iter
));
1385 return fast_seeking
;
1388 MUtils::OS::drive_type_t
MUtils::OS::get_drive_type(const QString
&path
, bool *fast_seeking
)
1390 drive_type_t driveType
= DRIVE_TYPE_ERR
;
1391 const wchar_t driveLetter
= get_drive_letter(path
);
1394 wchar_t driveName
[8];
1395 _snwprintf_s(driveName
, 8, _TRUNCATE
, L
"\\\\.\\%c:\\", driveLetter
);
1396 switch (GetDriveTypeW(driveName
))
1398 case DRIVE_REMOVABLE
: driveType
= DRIVE_TYPE_FDD
; break;
1399 case DRIVE_FIXED
: driveType
= DRIVE_TYPE_HDD
; break;
1400 case DRIVE_REMOTE
: driveType
= DRIVE_TYPE_NET
; break;
1401 case DRIVE_CDROM
: driveType
= DRIVE_TYPE_OPT
; break;
1402 case DRIVE_RAMDISK
: driveType
= DRIVE_TYPE_RAM
; break;
1407 if (driveType
== DRIVE_TYPE_HDD
)
1409 *fast_seeking
= is_fast_seeking_drive(driveLetter
);
1413 *fast_seeking
= (driveType
== DRIVE_TYPE_RAM
);
1419 ///////////////////////////////////////////////////////////////////////////////
1421 ///////////////////////////////////////////////////////////////////////////////
1423 bool MUtils::OS::shell_open(const QWidget
*parent
, const QString
&url
, const QString
¶meters
, const QString
&directory
, const bool explore
)
1425 return ((int) ShellExecuteW((parent
? reinterpret_cast<HWND
>(parent
->winId()) : NULL
), (explore
? L
"explore" : L
"open"), MUTILS_WCHR(url
), ((!parameters
.isEmpty()) ? MUTILS_WCHR(parameters
) : NULL
), ((!directory
.isEmpty()) ? MUTILS_WCHR(directory
) : NULL
), SW_SHOW
)) > 32;
1428 bool MUtils::OS::shell_open(const QWidget
*parent
, const QString
&url
, const bool explore
)
1430 return shell_open(parent
, url
, QString(), QString(), explore
);
1433 ///////////////////////////////////////////////////////////////////////////////
1435 ///////////////////////////////////////////////////////////////////////////////
1437 bool MUtils::OS::open_media_file(const QString
&mediaFilePath
)
1439 const static wchar_t *registryPrefix
[2] = { L
"SOFTWARE\\", L
"SOFTWARE\\Wow6432Node\\" };
1440 const static wchar_t *registryKeys
[3] =
1442 L
"Microsoft\\Windows\\CurrentVersion\\Uninstall\\{97D341C8-B0D1-4E4A-A49A-C30B52F168E9}",
1443 L
"Microsoft\\Windows\\CurrentVersion\\Uninstall\\{DB9E4EAB-2717-499F-8D56-4CC8A644AB60}",
1446 const static wchar_t *appNames
[4] = { L
"smplayer_portable.exe", L
"smplayer.exe", L
"MPUI.exe", L
"foobar2000.exe" };
1447 const static wchar_t *valueNames
[2] = { L
"InstallLocation", L
"InstallDir" };
1449 for(size_t i
= 0; i
< 3; i
++)
1451 for(size_t j
= 0; j
< 2; j
++)
1453 QString mplayerPath
;
1454 HKEY registryKeyHandle
= NULL
;
1456 const QString currentKey
= MUTILS_QSTR(registryPrefix
[j
]).append(MUTILS_QSTR(registryKeys
[i
]));
1457 if(RegOpenKeyExW(HKEY_LOCAL_MACHINE
, MUTILS_WCHR(currentKey
), 0, KEY_READ
, ®istryKeyHandle
) == ERROR_SUCCESS
)
1459 for(size_t k
= 0; k
< 2; k
++)
1461 wchar_t Buffer
[4096];
1462 DWORD BuffSize
= sizeof(wchar_t*) * 4096;
1463 DWORD DataType
= REG_NONE
;
1464 if(RegQueryValueExW(registryKeyHandle
, valueNames
[k
], 0, &DataType
, reinterpret_cast<BYTE
*>(Buffer
), &BuffSize
) == ERROR_SUCCESS
)
1466 if((DataType
== REG_SZ
) || (DataType
== REG_EXPAND_SZ
) || (DataType
== REG_LINK
))
1468 mplayerPath
= MUTILS_QSTR(Buffer
);
1473 RegCloseKey(registryKeyHandle
);
1476 if(!mplayerPath
.isEmpty())
1478 QDir
mplayerDir(mplayerPath
);
1479 if(mplayerDir
.exists())
1481 for(size_t k
= 0; k
< 4; k
++)
1483 if(mplayerDir
.exists(MUTILS_QSTR(appNames
[k
])))
1485 qDebug("Player found at:\n%s\n", MUTILS_UTF8(mplayerDir
.absoluteFilePath(MUTILS_QSTR(appNames
[k
]))));
1486 QProcess::startDetached(mplayerDir
.absoluteFilePath(MUTILS_QSTR(appNames
[k
])), QStringList() << QDir::toNativeSeparators(mediaFilePath
));
1497 ///////////////////////////////////////////////////////////////////////////////
1499 ///////////////////////////////////////////////////////////////////////////////
1501 static bool change_process_priority_helper(const HANDLE hProcess
, const int priority
)
1505 switch(qBound(-2, priority
, 2))
1508 ok
= (SetPriorityClass(hProcess
, HIGH_PRIORITY_CLASS
) == TRUE
);
1511 if(!(ok
= (SetPriorityClass(hProcess
, ABOVE_NORMAL_PRIORITY_CLASS
) == TRUE
)))
1513 ok
= (SetPriorityClass(hProcess
, HIGH_PRIORITY_CLASS
) == TRUE
);
1517 ok
= (SetPriorityClass(hProcess
, NORMAL_PRIORITY_CLASS
) == TRUE
);
1520 if(!(ok
= (SetPriorityClass(hProcess
, BELOW_NORMAL_PRIORITY_CLASS
) == TRUE
)))
1522 ok
= (SetPriorityClass(hProcess
, IDLE_PRIORITY_CLASS
) == TRUE
);
1526 ok
= (SetPriorityClass(hProcess
, IDLE_PRIORITY_CLASS
) == TRUE
);
1533 bool MUtils::OS::change_process_priority(const int priority
)
1535 return change_process_priority_helper(GetCurrentProcess(), priority
);
1538 bool MUtils::OS::change_process_priority(const QProcess
*proc
, const int priority
)
1540 if(Q_PID qPid
= proc
->pid())
1542 return change_process_priority_helper(qPid
->hProcess
, priority
);
1550 ///////////////////////////////////////////////////////////////////////////////
1552 ///////////////////////////////////////////////////////////////////////////////
1554 quint32
MUtils::OS::process_id(void)
1556 return GetCurrentProcessId();
1559 quint32
MUtils::OS::process_id(const QProcess
*const proc
)
1561 PROCESS_INFORMATION
*procInf
= proc
->pid();
1562 return (procInf
) ? procInf
->dwProcessId
: 0;
1565 quint32
MUtils::OS::thread_id(void)
1567 return GetCurrentThreadId();
1570 quint32
MUtils::OS::thread_id(const QProcess
*const proc
)
1572 PROCESS_INFORMATION
*procInf
= proc
->pid();
1573 return (procInf
) ? procInf
->dwThreadId
: 0;
1576 ///////////////////////////////////////////////////////////////////////////////
1577 // PROCESS SUSPEND/RESUME
1578 ///////////////////////////////////////////////////////////////////////////////
1580 bool MUtils::OS::suspend_process(const QProcess
*proc
, const bool suspend
)
1582 if(Q_PID pid
= proc
->pid())
1586 return (SuspendThread(pid
->hThread
) != ((DWORD
) -1));
1590 return (ResumeThread(pid
->hThread
) != ((DWORD
) -1));
1599 ///////////////////////////////////////////////////////////////////////////////
1601 ///////////////////////////////////////////////////////////////////////////////
1603 bool MUtils::OS::setup_timer_resolution(const quint32
&interval
)
1605 return timeBeginPeriod(interval
) == TIMERR_NOERROR
;
1608 bool MUtils::OS::reset_timer_resolution(const quint32
&interval
)
1610 return timeEndPeriod(interval
) == TIMERR_NOERROR
;
1613 ///////////////////////////////////////////////////////////////////////////////
1615 ///////////////////////////////////////////////////////////////////////////////
1617 static QScopedPointer
<QDateTime
> s_epoch
;
1618 static QReadWriteLock s_epochLock
;
1620 static const QDateTime
*get_epoch(void)
1622 QReadLocker
rdLock(&s_epochLock
);
1624 if (s_epoch
.isNull())
1627 QWriteLocker
wrLock(&s_epochLock
);
1628 if (s_epoch
.isNull())
1630 s_epoch
.reset(new QDateTime(QDate(1601, 1, 1), QTime(0, 0, 0, 0), Qt::UTC
));
1636 return s_epoch
.data();
1639 static FILETIME
*qt_time_to_file_time(FILETIME
*const fileTime
, const QDateTime
&dateTime
)
1641 memset(fileTime
, 0, sizeof(FILETIME
));
1643 if (const QDateTime
*const epoch
= get_epoch())
1645 const qint64 msecs
= epoch
->msecsTo(dateTime
);
1648 const quint64 ticks
= 10000U * quint64(msecs
);
1649 fileTime
->dwHighDateTime
= ((ticks
>> 32) & 0xFFFFFFFF);
1650 fileTime
->dwLowDateTime
= (ticks
& 0xFFFFFFFF);
1658 static bool set_file_time(const HANDLE hFile
, const QDateTime
&created
, const QDateTime
&lastMod
, const QDateTime
&lastAcc
)
1660 FILETIME ftCreated
, ftLastMod
, ftLastAcc
;
1662 FILETIME
*const pCreated
= created
.isValid() ? qt_time_to_file_time(&ftCreated
, created
) : NULL
;
1663 FILETIME
*const pLastMod
= lastMod
.isValid() ? qt_time_to_file_time(&ftLastMod
, lastMod
) : NULL
;
1664 FILETIME
*const pLastAcc
= lastAcc
.isValid() ? qt_time_to_file_time(&ftLastAcc
, lastAcc
) : NULL
;
1666 if (pCreated
|| pLastMod
|| pLastAcc
)
1668 return (SetFileTime(hFile
, pCreated
, pLastAcc
, pLastMod
) != FALSE
);
1674 bool MUtils::OS::set_file_time(const QFile
&file
, const QDateTime
&created
, const QDateTime
&lastMod
, const QDateTime
&lastAcc
)
1676 const int fd
= file
.handle();
1679 return set_file_time((HANDLE
)_get_osfhandle(fd
), created
, lastMod
, lastAcc
);
1684 bool MUtils::OS::set_file_time(const QString
&path
, const QDateTime
&created
, const QDateTime
&lastMod
, const QDateTime
&lastAcc
)
1686 const HANDLE hFile
= CreateFileW(MUTILS_WCHR(path
), FILE_WRITE_ATTRIBUTES
, FILE_SHARE_READ
, NULL
, OPEN_EXISTING
, 0, 0);
1688 if ((hFile
!= NULL
) && (hFile
!= INVALID_HANDLE_VALUE
))
1690 okay
= set_file_time(hFile
, created
, lastMod
, lastAcc
);
1696 ///////////////////////////////////////////////////////////////////////////////
1698 ///////////////////////////////////////////////////////////////////////////////
1700 bool MUtils::OS::check_key_state_esc(void)
1702 return (GetAsyncKeyState(VK_ESCAPE
) & 0x0001) != 0;
1705 ///////////////////////////////////////////////////////////////////////////////
1706 // SHELL CHANGE NOTIFICATION
1707 ///////////////////////////////////////////////////////////////////////////////
1709 void MUtils::OS::shell_change_notification(void)
1711 SHChangeNotify(SHCNE_ASSOCCHANGED
, SHCNF_IDLIST
, NULL
, NULL
);
1714 ///////////////////////////////////////////////////////////////////////////////
1715 // WOW64 REDIRECTION
1716 ///////////////////////////////////////////////////////////////////////////////
1718 typedef BOOL (_stdcall
*Wow64DisableWow64FsRedirectionFun
)(void *OldValue
);
1719 typedef BOOL (_stdcall
*Wow64RevertWow64FsRedirectionFun
)(void *OldValue
);
1721 bool MUtils::OS::wow64fsredir_disable(void *oldValue
)
1723 const Wow64DisableWow64FsRedirectionFun wow64redir_disable
= MUtils::Win32Utils::resolve
<Wow64DisableWow64FsRedirectionFun
>(QLatin1String("kernel32"), QLatin1String("Wow64DisableWow64FsRedirection"));
1724 if(wow64redir_disable
)
1726 if (wow64redir_disable(oldValue
))
1734 bool MUtils::OS::wow64fsredir_revert(void *oldValue
)
1736 const Wow64RevertWow64FsRedirectionFun wow64redir_disable
= MUtils::Win32Utils::resolve
<Wow64RevertWow64FsRedirectionFun
>(QLatin1String("kernel32"), QLatin1String("Wow64RevertWow64FsRedirection"));
1737 if (wow64redir_disable
)
1739 if (wow64redir_disable(oldValue
))
1747 ///////////////////////////////////////////////////////////////////////////////
1749 ///////////////////////////////////////////////////////////////////////////////
1751 QString
MUtils::OS::get_envvar(const QString
&name
)
1753 wchar_t *buffer
= NULL
;
1754 size_t requiredSize
= 0, buffSize
= 0;
1759 //Adjust the buffer size as required first!
1760 if (buffSize
< requiredSize
)
1766 if (!(buffer
= (wchar_t*)_malloca(sizeof(wchar_t) * requiredSize
)))
1768 break; /*out of memory error!*/
1770 buffSize
= requiredSize
;
1773 //Try to fetch the environment variable now
1774 const errno_t error
= _wgetenv_s(&requiredSize
, buffer
, buffSize
, MUTILS_WCHR(name
));
1777 if (requiredSize
> 0)
1779 result
= MUTILS_QSTR(buffer
);
1783 else if (error
!= ERANGE
)
1785 break; /*somethging else went wrong!*/
1799 bool MUtils::OS::set_envvar(const QString
&name
, const QString
&value
)
1801 if (!_wputenv_s(MUTILS_WCHR(name
), MUTILS_WCHR(value
)))
1808 ///////////////////////////////////////////////////////////////////////////////
1810 ///////////////////////////////////////////////////////////////////////////////
1812 static const QLatin1String
NULL_DEVICE("NUL");
1814 const QLatin1String
&MUtils::OS::null_device(void)
1819 ///////////////////////////////////////////////////////////////////////////////
1821 ///////////////////////////////////////////////////////////////////////////////
1823 #if (!(MUTILS_DEBUG))
1824 static __forceinline
bool is_debugger_present(void)
1828 CloseHandle((HANDLE
)((DWORD_PTR
)-3));
1835 BOOL bHaveDebugger
= FALSE
;
1836 if(CheckRemoteDebuggerPresent(GetCurrentProcess(), &bHaveDebugger
))
1838 if(bHaveDebugger
) return true;
1841 return IsDebuggerPresent();
1843 static __forceinline
bool check_debugger_helper(void)
1845 if(is_debugger_present())
1847 MUtils::OS::fatal_exit(L
"Not a debug build. Please unload debugger and try again!");
1853 #define check_debugger_helper() (false)
1856 void MUtils::OS::check_debugger(void)
1858 check_debugger_helper();
1861 static volatile bool g_debug_check
= check_debugger_helper();
1863 ///////////////////////////////////////////////////////////////////////////////
1865 ///////////////////////////////////////////////////////////////////////////////
1867 static MUtils::Internal::CriticalSection g_fatal_exit_lock
;
1868 static QAtomicInt g_fatal_exit_flag
;
1870 static DWORD WINAPI
fatal_exit_helper(LPVOID lpParameter
)
1872 MUtils::OS::system_message_err(L
"GURU MEDITATION", (LPWSTR
) lpParameter
);
1876 void MUtils::OS::fatal_exit(const wchar_t* const errorMessage
)
1878 g_fatal_exit_lock
.enter();
1880 if(!g_fatal_exit_flag
.testAndSetOrdered(0, 1))
1882 return; /*prevent recursive invocation*/
1885 if(g_main_thread_id
!= GetCurrentThreadId())
1887 if(HANDLE hThreadMain
= OpenThread(THREAD_SUSPEND_RESUME
, FALSE
, g_main_thread_id
))
1889 SuspendThread(hThreadMain
); /*stop main thread*/
1893 if(HANDLE hThread
= CreateThread(NULL
, 0, fatal_exit_helper
, (LPVOID
)errorMessage
, 0, NULL
))
1895 WaitForSingleObject(hThread
, INFINITE
);
1899 fatal_exit_helper((LPVOID
)errorMessage
);
1904 TerminateProcess(GetCurrentProcess(), 666);
1908 ///////////////////////////////////////////////////////////////////////////////