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
*SHGetKnownFolderPathProc
)(const GUID
&rfid
, DWORD dwFlags
, HANDLE hToken
, PWSTR
*ppszPath
);
694 typedef HRESULT (WINAPI
*SHGetFolderPathProc
)(HWND hwndOwner
, int nFolder
, HANDLE hToken
, DWORD dwFlags
, LPWSTR pszPath
);
701 s_known_folders_lut
[] =
703 { 0x001A, { 0x3EB685DB, 0x65F9, 0x4CF6, { 0xA0, 0x3A, 0xE3, 0xEF, 0x65, 0x72, 0x9F, 0x3D } } }, //CSIDL_APPDATA
704 { 0x001C, { 0xF1B32785, 0x6FBA, 0x4FCF, { 0x9D, 0x55, 0x7B, 0x8E, 0x7F, 0x15, 0x70, 0x91 } } }, //CSIDL_LOCAL_APPDATA
705 { 0x0028, { 0x5E6C858F, 0x0E22, 0x4760, { 0x9A, 0xFE, 0xEA, 0x33, 0x17, 0xB6, 0x71, 0x73 } } }, //CSIDL_PROFILE
706 { 0x0026, { 0x905E63B6, 0xC1BF, 0x494E, { 0xB2, 0x9C, 0x65, 0xB7, 0x32, 0xD3, 0xD2, 0x1A } } }, //CSIDL_PROGRAM_FILES
707 { 0x0025, { 0x1AC14E77, 0x02E7, 0x4E5D, { 0xB7, 0x44, 0x2E, 0xB1, 0xAE, 0x51, 0x98, 0xB7 } } }, //CSIDL_SYSTEM_FOLDER
708 { 0x0024, { 0xF38BF404, 0x1D43, 0x42F2, { 0x93, 0x05, 0x67, 0xDE, 0x0B, 0x28, 0xFC, 0x23 } } }, //CSIDL_WINDOWS_FOLDER
711 static QString
known_folder_verify(const wchar_t *const path
)
713 const QDir folderPath
= QDir(QDir::fromNativeSeparators(MUTILS_QSTR(path
)));
714 if (folderPath
.exists())
716 const QString absolutePath
= folderPath
.absolutePath();
717 const HANDLE handle
= CreateFileW(MUTILS_WCHR(QDir::toNativeSeparators(absolutePath
)), 0U, FILE_SHARE_READ
| FILE_SHARE_WRITE
, NULL
, OPEN_EXISTING
, FILE_FLAG_BACKUP_SEMANTICS
, NULL
);
718 if (handle
!= INVALID_HANDLE_VALUE
)
720 SetHandleInformation(handle
, HANDLE_FLAG_PROTECT_FROM_CLOSE
, HANDLE_FLAG_PROTECT_FROM_CLOSE
);
725 return QString(); /*failed*/
728 static QString
known_folder_fallback(const size_t folderId
)
730 static const DWORD s_shgfpTypes
[3] =
732 0, /*SHGFP_TYPE_CURRENT*/
733 1, /*SHGFP_TYPE_DEFAULT*/
737 static const INT32 s_shgfpFlags
[3] =
739 0x0000, /*No extra flags*/
740 0x8000, /*SHGFP_FLAG_CREATE*/
744 const SHGetFolderPathProc getFolderPath
= MUtils::Win32Utils::resolve
<SHGetFolderPathProc
>(QLatin1String("shell32"), QLatin1String("SHGetFolderPathW"));
747 QVector
<WCHAR
> pathBuffer(MAX_PATH
);
748 for (size_t i
= 0; s_shgfpTypes
[i
] != MAXDWORD
; ++i
)
750 for (size_t j
= 0; s_shgfpFlags
[j
] != MAXINT32
; ++j
)
752 if (getFolderPath(NULL
, s_known_folders_lut
[folderId
].csidl
| s_shgfpFlags
[j
], NULL
, s_shgfpTypes
[i
], pathBuffer
.data()) == S_OK
)
754 //MessageBoxW(0, path, L"SHGetFolderPathW", MB_TOPMOST);
755 const QString folderPath
= known_folder_verify(pathBuffer
.data());
756 if (!folderPath
.isEmpty())
765 return QString(); /*failed!*/
768 static QString
known_folder_detect(const size_t folderId
)
772 KF_FLAG_DEFAULT
= 0x00000000,
773 KF_FLAG_DEFAULT_PATH
= 0x00000400,
774 KF_FLAG_CREATE
= 0x00008000
778 static const DWORD s_kfFlags
[5] =
782 KF_FLAG_DEFAULT_PATH
,
783 KF_FLAG_DEFAULT_PATH
| KF_FLAG_CREATE
,
787 const SHGetKnownFolderPathProc getKnownFolderPath
= MUtils::Win32Utils::resolve
<SHGetKnownFolderPathProc
>(QLatin1String("shell32"), QLatin1String("SHGetKnownFolderPath"));
788 if (getKnownFolderPath
)
790 for (size_t i
= 0; s_kfFlags
[i
] != MAXDWORD
; ++i
)
793 if (getKnownFolderPath(s_known_folders_lut
[folderId
].kfuid
, s_kfFlags
[i
], NULL
, &path
) == S_OK
)
795 //MessageBoxW(0, path, L"SHGetKnownFolderPath", MB_TOPMOST);
796 const QString folderPath
= known_folder_verify(path
);
798 if (!folderPath
.isEmpty())
806 return known_folder_fallback(folderId
); /*fallback!*/
809 static size_t known_folder_decode(const MUtils::OS::known_folder_t folder_id
)
813 case MUtils::OS::FOLDER_ROAMING_DATA
: return 0U;
814 case MUtils::OS::FOLDER_LOCALAPPDATA
: return 1U;
815 case MUtils::OS::FOLDER_USER_PROFILE
: return 2U;
816 case MUtils::OS::FOLDER_PROGRAMFILES
: return 3U;
817 case MUtils::OS::FOLDER_SYSTEMFOLDER
: return 4U;
818 case MUtils::OS::FOLDER_SYSTROOT_DIR
: return 5U;
820 qWarning("Invalid 'known' folder was requested!");
825 const QString
&MUtils::OS::known_folder(const known_folder_t folder_id
)
828 const size_t folderId
= known_folder_decode(folder_id
);
829 if (folderId
== SIZE_MAX
)
831 return Internal::g_empty
;
835 QReadLocker
readLock(&g_known_folders_lock
);
838 if(!g_known_folders_data
.isNull())
840 if(g_known_folders_data
->contains(folderId
))
842 return (*g_known_folders_data
)[folderId
];
846 //Obtain write lock to initialize
848 QWriteLocker
writeLock(&g_known_folders_lock
);
850 //Still not in cache?
851 if(!g_known_folders_data
.isNull())
853 if(g_known_folders_data
->contains(folderId
))
855 return (*g_known_folders_data
)[folderId
];
859 //Initialize on first call
860 if(g_known_folders_data
.isNull())
862 g_known_folders_data
.reset(new QHash
<size_t, QString
>());
866 const QString folderPath
= known_folder_detect(folderId
);
869 if (!folderPath
.isEmpty())
871 g_known_folders_data
->insert(folderId
, folderPath
);
872 return (*g_known_folders_data
)[folderId
];
875 return Internal::g_empty
;
878 ///////////////////////////////////////////////////////////////////////////////
879 // CURRENT DATA & TIME
880 ///////////////////////////////////////////////////////////////////////////////
882 QDate
MUtils::OS::current_date(void)
884 const DWORD MAX_PROC
= 1024;
885 QScopedArrayPointer
<DWORD
> processes(new DWORD
[MAX_PROC
]);
886 DWORD bytesReturned
= 0;
888 if(!EnumProcesses(processes
.data(), sizeof(DWORD
) * MAX_PROC
, &bytesReturned
))
890 return QDate::currentDate();
893 const DWORD procCount
= bytesReturned
/ sizeof(DWORD
);
894 ULARGE_INTEGER lastStartTime
;
895 memset(&lastStartTime
, 0, sizeof(ULARGE_INTEGER
));
897 for(DWORD i
= 0; i
< procCount
; i
++)
899 if(HANDLE hProc
= OpenProcess(PROCESS_QUERY_INFORMATION
, FALSE
, processes
[i
]))
901 FILETIME processTime
[4];
902 if(GetProcessTimes(hProc
, &processTime
[0], &processTime
[1], &processTime
[2], &processTime
[3]))
904 ULARGE_INTEGER timeCreation
;
905 timeCreation
.LowPart
= processTime
[0].dwLowDateTime
;
906 timeCreation
.HighPart
= processTime
[0].dwHighDateTime
;
907 if(timeCreation
.QuadPart
> lastStartTime
.QuadPart
)
909 lastStartTime
.QuadPart
= timeCreation
.QuadPart
;
916 FILETIME lastStartTime_fileTime
;
917 lastStartTime_fileTime
.dwHighDateTime
= lastStartTime
.HighPart
;
918 lastStartTime_fileTime
.dwLowDateTime
= lastStartTime
.LowPart
;
920 FILETIME lastStartTime_localTime
;
921 if(!FileTimeToLocalFileTime(&lastStartTime_fileTime
, &lastStartTime_localTime
))
923 memcpy(&lastStartTime_localTime
, &lastStartTime_fileTime
, sizeof(FILETIME
));
926 SYSTEMTIME lastStartTime_system
;
927 if(!FileTimeToSystemTime(&lastStartTime_localTime
, &lastStartTime_system
))
929 memset(&lastStartTime_system
, 0, sizeof(SYSTEMTIME
));
930 lastStartTime_system
.wYear
= 1970; lastStartTime_system
.wMonth
= lastStartTime_system
.wDay
= 1;
933 const QDate currentDate
= QDate::currentDate();
934 const QDate processDate
= QDate(lastStartTime_system
.wYear
, lastStartTime_system
.wMonth
, lastStartTime_system
.wDay
);
935 return (currentDate
>= processDate
) ? currentDate
: processDate
;
938 quint64
MUtils::OS::current_file_time(void)
941 GetSystemTimeAsFileTime(&fileTime
);
944 temp
.HighPart
= fileTime
.dwHighDateTime
;
945 temp
.LowPart
= fileTime
.dwLowDateTime
;
947 return temp
.QuadPart
;
950 ///////////////////////////////////////////////////////////////////////////////
952 ///////////////////////////////////////////////////////////////////////////////
954 typedef DWORD(_stdcall
*GetPathNameByHandleFun
)(HANDLE hFile
, LPWSTR lpszFilePath
, DWORD cchFilePath
, DWORD dwFlags
);
956 static QString
get_file_path_drive_list(void)
959 const DWORD len
= GetLogicalDriveStringsW(0, NULL
);
962 if (wchar_t *const buffer
= (wchar_t*) _malloca(sizeof(wchar_t) * len
))
964 const DWORD ret
= GetLogicalDriveStringsW(len
, buffer
);
965 if ((ret
> 0) && (ret
< len
))
967 const wchar_t *ptr
= buffer
;
968 while (const size_t current_len
= wcslen(ptr
))
970 list
.append(QChar(*reinterpret_cast<const ushort
*>(ptr
)));
971 ptr
+= (current_len
+ 1);
980 static void get_file_path_translate(QString
&path
)
982 static const DWORD BUFSIZE
= 2048;
983 wchar_t buffer
[BUFSIZE
], drive
[3];
985 const QString driveList
= get_file_path_drive_list();
986 wcscpy_s(drive
, 3, L
"?:");
987 for (const wchar_t *current
= MUTILS_WCHR(driveList
); *current
; current
++)
989 drive
[0] = (*current
);
990 if (QueryDosDeviceW(drive
, buffer
, MAX_PATH
))
992 const QString prefix
= MUTILS_QSTR(buffer
);
993 if (path
.startsWith(prefix
, Qt::CaseInsensitive
))
995 path
.remove(0, prefix
.length()).prepend(QLatin1Char(':')).prepend(QChar(*reinterpret_cast<const ushort
*>(current
)));
1002 static QString
get_file_path_fallback(const HANDLE
&hFile
)
1006 const HANDLE hFileMap
= CreateFileMappingW(hFile
, NULL
, PAGE_READONLY
, 0, 1, NULL
);
1009 void *const pMem
= MapViewOfFile(hFileMap
, FILE_MAP_READ
, 0, 0, 1);
1012 static const size_t BUFFSIZE
= 2048;
1013 wchar_t buffer
[BUFFSIZE
];
1014 if (GetMappedFileNameW(GetCurrentProcess(), pMem
, buffer
, BUFFSIZE
) > 0)
1016 filePath
= MUTILS_QSTR(buffer
);
1018 UnmapViewOfFile(pMem
);
1020 CloseHandle(hFileMap
);
1023 if (!filePath
.isEmpty())
1025 get_file_path_translate(filePath
);
1031 QString
MUtils::OS::get_file_path(const int &fd
)
1035 const GetPathNameByHandleFun getPathNameByHandleFun
= MUtils::Win32Utils::resolve
<GetPathNameByHandleFun
>(QLatin1String("kernel32"), QLatin1String("GetFinalPathNameByHandleW"));
1036 if (!getPathNameByHandleFun
)
1038 return get_file_path_fallback((HANDLE
)_get_osfhandle(fd
));
1041 const HANDLE handle
= (HANDLE
) _get_osfhandle(fd
);
1042 const DWORD len
= getPathNameByHandleFun(handle
, NULL
, 0, FILE_NAME_OPENED
);
1045 if (wchar_t *const buffer
= (wchar_t*)_malloca(sizeof(wchar_t) * len
))
1047 const DWORD ret
= getPathNameByHandleFun(handle
, buffer
, len
, FILE_NAME_OPENED
);
1048 if ((ret
> 0) && (ret
< len
))
1050 const QString
path(MUTILS_QSTR(buffer
));
1051 return path
.startsWith(QLatin1String("\\\\?\\")) ? path
.mid(4) : path
;
1061 ///////////////////////////////////////////////////////////////////////////////
1062 // PROCESS ELEVATION
1063 ///////////////////////////////////////////////////////////////////////////////
1065 static bool user_is_admin_helper(void)
1067 HANDLE hToken
= NULL
;
1068 if(!OpenProcessToken(GetCurrentProcess(), TOKEN_QUERY
, &hToken
))
1074 if(!GetTokenInformation(hToken
, TokenGroups
, NULL
, 0, &dwSize
))
1076 if(GetLastError() != ERROR_INSUFFICIENT_BUFFER
)
1078 CloseHandle(hToken
);
1083 PTOKEN_GROUPS lpGroups
= (PTOKEN_GROUPS
) malloc(dwSize
);
1086 CloseHandle(hToken
);
1090 if(!GetTokenInformation(hToken
, TokenGroups
, lpGroups
, dwSize
, &dwSize
))
1093 CloseHandle(hToken
);
1097 PSID lpSid
= NULL
; SID_IDENTIFIER_AUTHORITY Authority
= {SECURITY_NT_AUTHORITY
};
1098 if(!AllocateAndInitializeSid(&Authority
, 2, SECURITY_BUILTIN_DOMAIN_RID
, DOMAIN_ALIAS_RID_ADMINS
, 0, 0, 0, 0, 0, 0, &lpSid
))
1101 CloseHandle(hToken
);
1105 bool bResult
= false;
1106 for(DWORD i
= 0; i
< lpGroups
->GroupCount
; i
++)
1108 if(EqualSid(lpSid
, lpGroups
->Groups
[i
].Sid
))
1117 CloseHandle(hToken
);
1121 bool MUtils::OS::is_elevated(bool *bIsUacEnabled
)
1125 *bIsUacEnabled
= false;
1128 bool bIsProcessElevated
= false;
1129 HANDLE hToken
= NULL
;
1131 if(OpenProcessToken(GetCurrentProcess(), TOKEN_QUERY
, &hToken
))
1133 TOKEN_ELEVATION_TYPE tokenElevationType
;
1135 if(GetTokenInformation(hToken
, TokenElevationType
, &tokenElevationType
, sizeof(TOKEN_ELEVATION_TYPE
), &returnLength
))
1137 if(returnLength
== sizeof(TOKEN_ELEVATION_TYPE
))
1139 switch(tokenElevationType
)
1141 case TokenElevationTypeDefault
:
1142 qDebug("Process token elevation type: Default -> UAC is disabled.\n");
1144 case TokenElevationTypeFull
:
1145 qWarning("Process token elevation type: Full -> potential security risk!\n");
1146 bIsProcessElevated
= true;
1147 if(bIsUacEnabled
) *bIsUacEnabled
= true;
1149 case TokenElevationTypeLimited
:
1150 qDebug("Process token elevation type: Limited -> not elevated.\n");
1151 if(bIsUacEnabled
) *bIsUacEnabled
= true;
1154 qWarning("Unknown tokenElevationType value: %d", tokenElevationType
);
1160 qWarning("GetTokenInformation() return an unexpected size!");
1163 CloseHandle(hToken
);
1167 qWarning("Failed to open process token!");
1170 return bIsProcessElevated
;
1173 bool MUtils::OS::user_is_admin(void)
1175 bool isAdmin
= false;
1177 //Check for process elevation and UAC support first!
1178 if(MUtils::OS::is_elevated(&isAdmin
))
1180 qWarning("Process is elevated -> user is admin!");
1184 //If not elevated and UAC is not available -> user must be in admin group!
1187 qDebug("UAC is disabled/unavailable -> checking for Administrators group");
1188 isAdmin
= user_is_admin_helper();
1194 ///////////////////////////////////////////////////////////////////////////////
1196 ///////////////////////////////////////////////////////////////////////////////
1198 int MUtils::OS::network_status(void)
1201 const BOOL ret
= IsNetworkAlive(&dwFlags
);
1202 if(GetLastError() == 0)
1204 return (ret
!= FALSE
) ? NETWORK_TYPE_YES
: NETWORK_TYPE_NON
;
1206 return NETWORK_TYPE_ERR
;
1209 ///////////////////////////////////////////////////////////////////////////////
1211 ///////////////////////////////////////////////////////////////////////////////
1213 bool MUtils::OS::handle_os_message(const void *const message
, long *result
)
1215 const MSG
*const msg
= reinterpret_cast<const MSG
*>(message
);
1217 switch(msg
->message
)
1219 case WM_QUERYENDSESSION
:
1220 qWarning("WM_QUERYENDSESSION message received!");
1221 *result
= MUtils::GUI::broadcast(MUtils::GUI::USER_EVENT_QUERYENDSESSION
, false) ? TRUE
: FALSE
;
1224 qWarning("WM_ENDSESSION message received!");
1225 if(msg
->wParam
== TRUE
)
1227 MUtils::GUI::broadcast(MUtils::GUI::USER_EVENT_ENDSESSION
, false);
1228 MUtils::GUI::force_quit();
1234 /*ignore this message and let Qt handle it*/
1239 ///////////////////////////////////////////////////////////////////////////////
1241 ///////////////////////////////////////////////////////////////////////////////
1243 void MUtils::OS::sleep_ms(const size_t &duration
)
1245 Sleep((DWORD
) duration
);
1248 ///////////////////////////////////////////////////////////////////////////////
1250 ///////////////////////////////////////////////////////////////////////////////
1252 static int g_library_as_image_resource_supported
= -1;
1253 static QReadWriteLock g_library_as_image_resource_supported_lock
;
1255 static bool library_as_image_resource_supported()
1257 QReadLocker
readLocker(&g_library_as_image_resource_supported_lock
);
1258 if (g_library_as_image_resource_supported
>= 0)
1260 return (g_library_as_image_resource_supported
> 0);
1263 readLocker
.unlock();
1264 QWriteLocker
writeLocker(&g_library_as_image_resource_supported_lock
);
1266 if (g_library_as_image_resource_supported
< 0)
1268 g_library_as_image_resource_supported
= 0;
1269 OSVERSIONINFOEXW osvi
;
1270 if (rtl_get_version(&osvi
))
1272 if ((osvi
.dwPlatformId
== VER_PLATFORM_WIN32_NT
) && (osvi
.dwMajorVersion
>= 6U))
1274 g_library_as_image_resource_supported
= 1;
1279 return (g_library_as_image_resource_supported
> 0);
1282 bool MUtils::OS::is_executable_file(const QString
&path
)
1285 if(GetBinaryType(MUTILS_WCHR(QDir::toNativeSeparators(path
)), &binaryType
))
1287 return ((binaryType
== SCS_32BIT_BINARY
) || (binaryType
== SCS_64BIT_BINARY
));
1290 const DWORD errorCode
= GetLastError();
1291 qWarning("GetBinaryType() failed with error: 0x%08X", errorCode
);
1295 bool MUtils::OS::is_library_file(const QString
&path
)
1297 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
);
1298 if (const HMODULE hMod
= LoadLibraryEx(MUTILS_WCHR(QDir::toNativeSeparators(path
)), NULL
, flags
))
1304 const DWORD errorCode
= GetLastError();
1305 qWarning("LoadLibraryEx() failed with error: 0x%08X", errorCode
);
1309 ///////////////////////////////////////////////////////////////////////////////
1310 // HIBERNATION / SHUTDOWN
1311 ///////////////////////////////////////////////////////////////////////////////
1313 bool MUtils::OS::is_hibernation_supported(void)
1315 bool hibernationSupported
= false;
1317 SYSTEM_POWER_CAPABILITIES pwrCaps
;
1318 SecureZeroMemory(&pwrCaps
, sizeof(SYSTEM_POWER_CAPABILITIES
));
1320 if(GetPwrCapabilities(&pwrCaps
))
1322 hibernationSupported
= pwrCaps
.SystemS4
&& pwrCaps
.HiberFilePresent
;
1325 return hibernationSupported
;
1328 bool MUtils::OS::shutdown_computer(const QString
&message
, const unsigned long timeout
, const bool forceShutdown
, const bool hibernate
)
1330 HANDLE hToken
= NULL
;
1332 if(OpenProcessToken(GetCurrentProcess(), TOKEN_ADJUST_PRIVILEGES
| TOKEN_QUERY
, &hToken
))
1334 TOKEN_PRIVILEGES privileges
;
1335 memset(&privileges
, 0, sizeof(TOKEN_PRIVILEGES
));
1336 privileges
.PrivilegeCount
= 1;
1337 privileges
.Privileges
[0].Attributes
= SE_PRIVILEGE_ENABLED
;
1339 if(LookupPrivilegeValue(NULL
, SE_SHUTDOWN_NAME
, &privileges
.Privileges
[0].Luid
))
1341 if(AdjustTokenPrivileges(hToken
, FALSE
, &privileges
, NULL
, NULL
, NULL
))
1345 if(SetSuspendState(TRUE
, TRUE
, TRUE
))
1350 const DWORD reason
= SHTDN_REASON_MAJOR_APPLICATION
| SHTDN_REASON_FLAG_PLANNED
;
1351 return InitiateSystemShutdownEx(NULL
, const_cast<wchar_t*>(MUTILS_WCHR(message
)), timeout
, forceShutdown
? TRUE
: FALSE
, FALSE
, reason
);
1359 ///////////////////////////////////////////////////////////////////////////////
1361 ///////////////////////////////////////////////////////////////////////////////
1363 bool MUtils::OS::free_diskspace(const QString
&path
, quint64
&freeSpace
)
1365 ULARGE_INTEGER freeBytesAvailable
, totalNumberOfBytes
, totalNumberOfFreeBytes
;
1366 if(GetDiskFreeSpaceExW(reinterpret_cast<const wchar_t*>(QDir::toNativeSeparators(path
).utf16()), &freeBytesAvailable
, &totalNumberOfBytes
, &totalNumberOfFreeBytes
))
1368 freeSpace
= freeBytesAvailable
.QuadPart
;
1376 ///////////////////////////////////////////////////////////////////////////////
1378 ///////////////////////////////////////////////////////////////////////////////
1380 static wchar_t get_drive_letter(const QString
&path
)
1382 QString nativePath
= QDir::toNativeSeparators(path
);
1383 while (nativePath
.startsWith("\\\\?\\") || nativePath
.startsWith("\\\\.\\"))
1385 nativePath
= QDir::toNativeSeparators(nativePath
.mid(4));
1387 if ((path
.length() > 1) && (path
[1] == QLatin1Char(':')))
1389 const wchar_t letter
= static_cast<wchar_t>(path
[0].unicode());
1390 if (((letter
>= 'A') && (letter
<= 'Z')) || ((letter
>= 'a') && (letter
<= 'z')))
1392 return towupper(letter
);
1395 return L
'\0'; /*invalid path spec*/
1398 static QSet
<DWORD
> get_physical_drive_ids(const wchar_t drive_letter
)
1400 QSet
<DWORD
> physical_drives
;
1401 wchar_t driveName
[8];
1402 _snwprintf_s(driveName
, 8, _TRUNCATE
, L
"\\\\.\\%c:", drive_letter
);
1403 const HANDLE hDrive
= CreateFileW(driveName
, 0, FILE_SHARE_READ
| FILE_SHARE_WRITE
, NULL
, OPEN_EXISTING
, 0, NULL
);
1404 if (hDrive
&& (hDrive
!= INVALID_HANDLE_VALUE
))
1406 const size_t BUFF_SIZE
= sizeof(VOLUME_DISK_EXTENTS
) + (32U * sizeof(DISK_EXTENT
));
1407 VOLUME_DISK_EXTENTS
*const diskExtents
= (VOLUME_DISK_EXTENTS
*)_malloca(BUFF_SIZE
);
1409 if (DeviceIoControl(hDrive
, IOCTL_VOLUME_GET_VOLUME_DISK_EXTENTS
, NULL
, 0, (LPVOID
)diskExtents
, (DWORD
)BUFF_SIZE
, (LPDWORD
)&dwSize
, NULL
))
1411 for (DWORD index
= 0U; index
< diskExtents
->NumberOfDiskExtents
; ++index
)
1413 physical_drives
.insert(diskExtents
->Extents
[index
].DiskNumber
);
1416 _freea(diskExtents
);
1417 CloseHandle(hDrive
);
1419 return physical_drives
;
1422 static bool incurs_seek_penalty(const DWORD device_id
)
1424 wchar_t driveName
[24];
1425 _snwprintf_s(driveName
, 24, _TRUNCATE
, L
"\\\\?\\PhysicalDrive%u", device_id
);
1426 const HANDLE hDevice
= CreateFileW(driveName
, 0, FILE_SHARE_READ
| FILE_SHARE_WRITE
, NULL
, OPEN_EXISTING
, 0, NULL
);
1427 bool seeking_penalty
= true;
1428 if (hDevice
&& (hDevice
!= INVALID_HANDLE_VALUE
))
1430 STORAGE_PROPERTY_QUERY spq
;
1431 DEVICE_SEEK_PENALTY_DESCRIPTOR dspd
;
1432 memset(&spq
, 0, sizeof(STORAGE_PROPERTY_QUERY
));
1433 spq
.PropertyId
= (STORAGE_PROPERTY_ID
)StorageDeviceSeekPenaltyProperty
;
1434 spq
.QueryType
= PropertyStandardQuery
;
1436 if (DeviceIoControl(hDevice
, IOCTL_STORAGE_QUERY_PROPERTY
, (LPVOID
)&spq
, (DWORD
)sizeof(spq
), (LPVOID
)&dspd
, (DWORD
)sizeof(dspd
), (LPDWORD
)&dwSize
, NULL
))
1438 seeking_penalty
= dspd
.IncursSeekPenalty
;
1440 CloseHandle(hDevice
);
1442 return seeking_penalty
;
1445 static bool is_fast_seeking_drive(const wchar_t drive_letter
)
1447 bool fast_seeking
= false;
1448 const QSet
<DWORD
> physical_drive_ids
= get_physical_drive_ids(drive_letter
);
1449 if (!physical_drive_ids
.empty())
1451 fast_seeking
= true;
1452 for (QSet
<DWORD
>::const_iterator iter
= physical_drive_ids
.constBegin(); iter
!= physical_drive_ids
.constEnd(); ++iter
)
1454 fast_seeking
= fast_seeking
&& (!incurs_seek_penalty(*iter
));
1457 return fast_seeking
;
1460 MUtils::OS::drive_type_t
MUtils::OS::get_drive_type(const QString
&path
, bool *fast_seeking
)
1462 drive_type_t driveType
= DRIVE_TYPE_ERR
;
1463 const wchar_t driveLetter
= get_drive_letter(path
);
1466 wchar_t driveName
[8];
1467 _snwprintf_s(driveName
, 8, _TRUNCATE
, L
"\\\\.\\%c:\\", driveLetter
);
1468 switch (GetDriveTypeW(driveName
))
1470 case DRIVE_REMOVABLE
: driveType
= DRIVE_TYPE_FDD
; break;
1471 case DRIVE_FIXED
: driveType
= DRIVE_TYPE_HDD
; break;
1472 case DRIVE_REMOTE
: driveType
= DRIVE_TYPE_NET
; break;
1473 case DRIVE_CDROM
: driveType
= DRIVE_TYPE_OPT
; break;
1474 case DRIVE_RAMDISK
: driveType
= DRIVE_TYPE_RAM
; break;
1479 if (driveType
== DRIVE_TYPE_HDD
)
1481 *fast_seeking
= is_fast_seeking_drive(driveLetter
);
1485 *fast_seeking
= (driveType
== DRIVE_TYPE_RAM
);
1491 ///////////////////////////////////////////////////////////////////////////////
1493 ///////////////////////////////////////////////////////////////////////////////
1495 bool MUtils::OS::shell_open(const QWidget
*parent
, const QString
&url
, const QString
¶meters
, const QString
&directory
, const bool explore
)
1497 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;
1500 bool MUtils::OS::shell_open(const QWidget
*parent
, const QString
&url
, const bool explore
)
1502 return shell_open(parent
, url
, QString(), QString(), explore
);
1505 ///////////////////////////////////////////////////////////////////////////////
1507 ///////////////////////////////////////////////////////////////////////////////
1509 bool MUtils::OS::open_media_file(const QString
&mediaFilePath
)
1511 const static wchar_t *registryPrefix
[2] = { L
"SOFTWARE\\", L
"SOFTWARE\\Wow6432Node\\" };
1512 const static wchar_t *registryKeys
[3] =
1514 L
"Microsoft\\Windows\\CurrentVersion\\Uninstall\\{97D341C8-B0D1-4E4A-A49A-C30B52F168E9}",
1515 L
"Microsoft\\Windows\\CurrentVersion\\Uninstall\\{DB9E4EAB-2717-499F-8D56-4CC8A644AB60}",
1518 const static wchar_t *appNames
[4] = { L
"smplayer_portable.exe", L
"smplayer.exe", L
"MPUI.exe", L
"foobar2000.exe" };
1519 const static wchar_t *valueNames
[2] = { L
"InstallLocation", L
"InstallDir" };
1521 for(size_t i
= 0; i
< 3; i
++)
1523 for(size_t j
= 0; j
< 2; j
++)
1525 QString mplayerPath
;
1526 HKEY registryKeyHandle
= NULL
;
1528 const QString currentKey
= MUTILS_QSTR(registryPrefix
[j
]).append(MUTILS_QSTR(registryKeys
[i
]));
1529 if(RegOpenKeyExW(HKEY_LOCAL_MACHINE
, MUTILS_WCHR(currentKey
), 0, KEY_READ
, ®istryKeyHandle
) == ERROR_SUCCESS
)
1531 for(size_t k
= 0; k
< 2; k
++)
1533 wchar_t Buffer
[4096];
1534 DWORD BuffSize
= sizeof(wchar_t*) * 4096;
1535 DWORD DataType
= REG_NONE
;
1536 if(RegQueryValueExW(registryKeyHandle
, valueNames
[k
], 0, &DataType
, reinterpret_cast<BYTE
*>(Buffer
), &BuffSize
) == ERROR_SUCCESS
)
1538 if((DataType
== REG_SZ
) || (DataType
== REG_EXPAND_SZ
) || (DataType
== REG_LINK
))
1540 mplayerPath
= MUTILS_QSTR(Buffer
);
1545 RegCloseKey(registryKeyHandle
);
1548 if(!mplayerPath
.isEmpty())
1550 QDir
mplayerDir(mplayerPath
);
1551 if(mplayerDir
.exists())
1553 for(size_t k
= 0; k
< 4; k
++)
1555 if(mplayerDir
.exists(MUTILS_QSTR(appNames
[k
])))
1557 qDebug("Player found at:\n%s\n", MUTILS_UTF8(mplayerDir
.absoluteFilePath(MUTILS_QSTR(appNames
[k
]))));
1558 QProcess::startDetached(mplayerDir
.absoluteFilePath(MUTILS_QSTR(appNames
[k
])), QStringList() << QDir::toNativeSeparators(mediaFilePath
));
1569 ///////////////////////////////////////////////////////////////////////////////
1571 ///////////////////////////////////////////////////////////////////////////////
1573 static bool change_process_priority_helper(const HANDLE hProcess
, const int priority
)
1577 switch(qBound(-2, priority
, 2))
1580 ok
= (SetPriorityClass(hProcess
, HIGH_PRIORITY_CLASS
) == TRUE
);
1583 if(!(ok
= (SetPriorityClass(hProcess
, ABOVE_NORMAL_PRIORITY_CLASS
) == TRUE
)))
1585 ok
= (SetPriorityClass(hProcess
, HIGH_PRIORITY_CLASS
) == TRUE
);
1589 ok
= (SetPriorityClass(hProcess
, NORMAL_PRIORITY_CLASS
) == TRUE
);
1592 if(!(ok
= (SetPriorityClass(hProcess
, BELOW_NORMAL_PRIORITY_CLASS
) == TRUE
)))
1594 ok
= (SetPriorityClass(hProcess
, IDLE_PRIORITY_CLASS
) == TRUE
);
1598 ok
= (SetPriorityClass(hProcess
, IDLE_PRIORITY_CLASS
) == TRUE
);
1605 bool MUtils::OS::change_process_priority(const int priority
)
1607 return change_process_priority_helper(GetCurrentProcess(), priority
);
1610 bool MUtils::OS::change_process_priority(const QProcess
*proc
, const int priority
)
1612 if(Q_PID qPid
= proc
->pid())
1614 return change_process_priority_helper(qPid
->hProcess
, priority
);
1622 ///////////////////////////////////////////////////////////////////////////////
1624 ///////////////////////////////////////////////////////////////////////////////
1626 quint32
MUtils::OS::process_id(void)
1628 return GetCurrentProcessId();
1631 quint32
MUtils::OS::process_id(const QProcess
*const proc
)
1633 PROCESS_INFORMATION
*procInf
= proc
->pid();
1634 return (procInf
) ? procInf
->dwProcessId
: 0;
1637 quint32
MUtils::OS::thread_id(void)
1639 return GetCurrentThreadId();
1642 quint32
MUtils::OS::thread_id(const QProcess
*const proc
)
1644 PROCESS_INFORMATION
*procInf
= proc
->pid();
1645 return (procInf
) ? procInf
->dwThreadId
: 0;
1648 ///////////////////////////////////////////////////////////////////////////////
1649 // PROCESS SUSPEND/RESUME
1650 ///////////////////////////////////////////////////////////////////////////////
1652 bool MUtils::OS::suspend_process(const QProcess
*proc
, const bool suspend
)
1654 if(Q_PID pid
= proc
->pid())
1658 return (SuspendThread(pid
->hThread
) != ((DWORD
) -1));
1662 return (ResumeThread(pid
->hThread
) != ((DWORD
) -1));
1671 ///////////////////////////////////////////////////////////////////////////////
1673 ///////////////////////////////////////////////////////////////////////////////
1675 bool MUtils::OS::setup_timer_resolution(const quint32
&interval
)
1677 return timeBeginPeriod(interval
) == TIMERR_NOERROR
;
1680 bool MUtils::OS::reset_timer_resolution(const quint32
&interval
)
1682 return timeEndPeriod(interval
) == TIMERR_NOERROR
;
1685 ///////////////////////////////////////////////////////////////////////////////
1687 ///////////////////////////////////////////////////////////////////////////////
1689 static QScopedPointer
<QDateTime
> s_epoch
;
1690 static QReadWriteLock s_epochLock
;
1692 static const QDateTime
*get_epoch(void)
1694 QReadLocker
rdLock(&s_epochLock
);
1696 if (s_epoch
.isNull())
1699 QWriteLocker
wrLock(&s_epochLock
);
1700 if (s_epoch
.isNull())
1702 s_epoch
.reset(new QDateTime(QDate(1601, 1, 1), QTime(0, 0, 0, 0), Qt::UTC
));
1708 return s_epoch
.data();
1711 static FILETIME
*qt_time_to_file_time(FILETIME
*const fileTime
, const QDateTime
&dateTime
)
1713 memset(fileTime
, 0, sizeof(FILETIME
));
1715 if (const QDateTime
*const epoch
= get_epoch())
1717 const qint64 msecs
= epoch
->msecsTo(dateTime
);
1720 const quint64 ticks
= 10000U * quint64(msecs
);
1721 fileTime
->dwHighDateTime
= ((ticks
>> 32) & 0xFFFFFFFF);
1722 fileTime
->dwLowDateTime
= (ticks
& 0xFFFFFFFF);
1730 static bool set_file_time(const HANDLE hFile
, const QDateTime
&created
, const QDateTime
&lastMod
, const QDateTime
&lastAcc
)
1732 FILETIME ftCreated
, ftLastMod
, ftLastAcc
;
1734 FILETIME
*const pCreated
= created
.isValid() ? qt_time_to_file_time(&ftCreated
, created
) : NULL
;
1735 FILETIME
*const pLastMod
= lastMod
.isValid() ? qt_time_to_file_time(&ftLastMod
, lastMod
) : NULL
;
1736 FILETIME
*const pLastAcc
= lastAcc
.isValid() ? qt_time_to_file_time(&ftLastAcc
, lastAcc
) : NULL
;
1738 if (pCreated
|| pLastMod
|| pLastAcc
)
1740 return (SetFileTime(hFile
, pCreated
, pLastAcc
, pLastMod
) != FALSE
);
1746 bool MUtils::OS::set_file_time(const QFile
&file
, const QDateTime
&created
, const QDateTime
&lastMod
, const QDateTime
&lastAcc
)
1748 const int fd
= file
.handle();
1751 return set_file_time((HANDLE
)_get_osfhandle(fd
), created
, lastMod
, lastAcc
);
1756 bool MUtils::OS::set_file_time(const QString
&path
, const QDateTime
&created
, const QDateTime
&lastMod
, const QDateTime
&lastAcc
)
1758 const HANDLE hFile
= CreateFileW(MUTILS_WCHR(path
), FILE_WRITE_ATTRIBUTES
, FILE_SHARE_READ
, NULL
, OPEN_EXISTING
, 0, 0);
1760 if ((hFile
!= NULL
) && (hFile
!= INVALID_HANDLE_VALUE
))
1762 okay
= set_file_time(hFile
, created
, lastMod
, lastAcc
);
1768 ///////////////////////////////////////////////////////////////////////////////
1770 ///////////////////////////////////////////////////////////////////////////////
1772 bool MUtils::OS::check_key_state_esc(void)
1774 return (GetAsyncKeyState(VK_ESCAPE
) & 0x0001) != 0;
1777 ///////////////////////////////////////////////////////////////////////////////
1778 // SHELL CHANGE NOTIFICATION
1779 ///////////////////////////////////////////////////////////////////////////////
1781 void MUtils::OS::shell_change_notification(void)
1783 SHChangeNotify(SHCNE_ASSOCCHANGED
, SHCNF_IDLIST
, NULL
, NULL
);
1786 ///////////////////////////////////////////////////////////////////////////////
1787 // WOW64 REDIRECTION
1788 ///////////////////////////////////////////////////////////////////////////////
1790 typedef BOOL (_stdcall
*Wow64DisableWow64FsRedirectionFun
)(PVOID
*OldValue
);
1791 typedef BOOL (_stdcall
*Wow64RevertWow64FsRedirectionFun
) (PVOID OldValue
);
1793 bool MUtils::OS::wow64fsredir_disable(uintptr_t &oldValue
)
1795 oldValue
= reinterpret_cast<uintptr_t>(nullptr);
1796 const Wow64DisableWow64FsRedirectionFun wow64redir_disable
= MUtils::Win32Utils::resolve
<Wow64DisableWow64FsRedirectionFun
>(QLatin1String("kernel32"), QLatin1String("Wow64DisableWow64FsRedirection"));
1797 if(wow64redir_disable
)
1800 if (wow64redir_disable(&temp
))
1802 oldValue
= reinterpret_cast<uintptr_t>(temp
);
1809 bool MUtils::OS::wow64fsredir_revert(const uintptr_t oldValue
)
1811 const Wow64RevertWow64FsRedirectionFun wow64redir_disable
= MUtils::Win32Utils::resolve
<Wow64RevertWow64FsRedirectionFun
>(QLatin1String("kernel32"), QLatin1String("Wow64RevertWow64FsRedirection"));
1812 if (wow64redir_disable
)
1814 if (wow64redir_disable(reinterpret_cast<PVOID
>(oldValue
)))
1822 ///////////////////////////////////////////////////////////////////////////////
1824 ///////////////////////////////////////////////////////////////////////////////
1826 QString
MUtils::OS::get_envvar(const QString
&name
)
1828 wchar_t *buffer
= NULL
;
1829 size_t requiredSize
= 0, buffSize
= 0;
1834 //Adjust the buffer size as required first!
1835 if (buffSize
< requiredSize
)
1841 if (!(buffer
= (wchar_t*)_malloca(sizeof(wchar_t) * requiredSize
)))
1843 break; /*out of memory error!*/
1845 buffSize
= requiredSize
;
1848 //Try to fetch the environment variable now
1849 const errno_t error
= _wgetenv_s(&requiredSize
, buffer
, buffSize
, MUTILS_WCHR(name
));
1852 if (requiredSize
> 0)
1854 result
= MUTILS_QSTR(buffer
);
1858 else if (error
!= ERANGE
)
1860 break; /*somethging else went wrong!*/
1874 bool MUtils::OS::set_envvar(const QString
&name
, const QString
&value
)
1876 if (!_wputenv_s(MUTILS_WCHR(name
), MUTILS_WCHR(value
)))
1883 ///////////////////////////////////////////////////////////////////////////////
1885 ///////////////////////////////////////////////////////////////////////////////
1887 static const QLatin1String
NULL_DEVICE("NUL");
1889 const QLatin1String
&MUtils::OS::null_device(void)
1894 ///////////////////////////////////////////////////////////////////////////////
1896 ///////////////////////////////////////////////////////////////////////////////
1898 #if (!(MUTILS_DEBUG))
1899 static __forceinline
bool is_debugger_present(void)
1903 CloseHandle((HANDLE
)((DWORD_PTR
)-3));
1910 BOOL bHaveDebugger
= FALSE
;
1911 if(CheckRemoteDebuggerPresent(GetCurrentProcess(), &bHaveDebugger
))
1913 if(bHaveDebugger
) return true;
1916 return IsDebuggerPresent();
1918 static __forceinline
bool check_debugger_helper(void)
1920 if(is_debugger_present())
1922 MUtils::OS::fatal_exit(L
"Not a debug build. Please unload debugger and try again!");
1928 #define check_debugger_helper() (false)
1931 void MUtils::OS::check_debugger(void)
1933 check_debugger_helper();
1936 static volatile bool g_debug_check
= check_debugger_helper();
1938 ///////////////////////////////////////////////////////////////////////////////
1940 ///////////////////////////////////////////////////////////////////////////////
1942 static MUtils::Internal::CriticalSection g_fatal_exit_lock
;
1943 static QAtomicInt g_fatal_exit_flag
;
1945 static DWORD WINAPI
fatal_exit_helper(LPVOID lpParameter
)
1947 MUtils::OS::system_message_err(L
"GURU MEDITATION", (LPWSTR
) lpParameter
);
1951 void MUtils::OS::fatal_exit(const wchar_t* const errorMessage
)
1953 g_fatal_exit_lock
.enter();
1955 if(!g_fatal_exit_flag
.testAndSetOrdered(0, 1))
1957 return; /*prevent recursive invocation*/
1960 if(g_main_thread_id
!= GetCurrentThreadId())
1962 if(HANDLE hThreadMain
= OpenThread(THREAD_SUSPEND_RESUME
, FALSE
, g_main_thread_id
))
1964 SuspendThread(hThreadMain
); /*stop main thread*/
1968 if(HANDLE hThread
= CreateThread(NULL
, 0, fatal_exit_helper
, (LPVOID
)errorMessage
, 0, NULL
))
1970 WaitForSingleObject(hThread
, INFINITE
);
1974 fatal_exit_helper((LPVOID
)errorMessage
);
1979 TerminateProcess(GetCurrentProcess(), 666);
1983 ///////////////////////////////////////////////////////////////////////////////