1 ///////////////////////////////////////////////////////////////////////////////
2 // MuldeR's Utilities for Qt
3 // Copyright (C) 2004-2016 LoRd_MuldeR <MuldeR2@GMX.de>
5 // This library is free software; you can redistribute it and/or
6 // modify it under the terms of the GNU Lesser General Public
7 // License as published by the Free Software Foundation; either
8 // version 2.1 of the License, or (at your option) any later version.
10 // This library is distributed in the hope that it will be useful,
11 // but WITHOUT ANY WARRANTY; without even the implied warranty of
12 // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
13 // Lesser General Public License for more details.
15 // You should have received a copy of the GNU Lesser General Public
16 // License along with this library; if not, write to the Free Software
17 // Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
19 // http://www.gnu.org/licenses/lgpl-2.1.txt
20 //////////////////////////////////////////////////////////////////////////////////
23 #define WIN32_LEAN_AND_MEAN 1
31 #pragma warning(disable:4091) //for MSVC2015
39 #include <MUtils/Global.h>
40 #include <MUtils/OSSupport.h>
41 #include <MUtils/GUI.h>
42 #include "CriticalSection_Win32.h"
43 #include "Utils_Win32.h"
47 #include <QReadWriteLock>
53 static const DWORD g_main_thread_id
= GetCurrentThreadId();
55 ///////////////////////////////////////////////////////////////////////////////
57 ///////////////////////////////////////////////////////////////////////////////
59 static const UINT g_msgBoxFlags
= MB_TOPMOST
| MB_TASKMODAL
| MB_SETFOREGROUND
;
61 void MUtils::OS::system_message_nfo(const wchar_t *const title
, const wchar_t *const text
)
63 MessageBoxW(NULL
, text
, title
, g_msgBoxFlags
| MB_ICONINFORMATION
);
66 void MUtils::OS::system_message_wrn(const wchar_t *const title
, const wchar_t *const text
)
68 MessageBoxW(NULL
, text
, title
, g_msgBoxFlags
| MB_ICONWARNING
);
71 void MUtils::OS::system_message_err(const wchar_t *const title
, const wchar_t *const text
)
73 MessageBoxW(NULL
, text
, title
, g_msgBoxFlags
| MB_ICONERROR
);
76 ///////////////////////////////////////////////////////////////////////////////
77 // FETCH CLI ARGUMENTS
78 ///////////////////////////////////////////////////////////////////////////////
80 static QReadWriteLock g_arguments_lock
;
81 static QScopedPointer
<MUtils::OS::ArgumentMap
> g_arguments_list
;
83 const QStringList
MUtils::OS::crack_command_line(const QString
&command_line
)
86 LPWSTR
*szArglist
= CommandLineToArgvW(command_line
.isNull() ? GetCommandLineW() : MUTILS_WCHR(command_line
), &nArgs
);
88 QStringList command_line_tokens
;
91 for(int i
= 0; i
< nArgs
; i
++)
93 const QString argStr
= MUTILS_QSTR(szArglist
[i
]).trimmed();
96 command_line_tokens
<< argStr
;
102 return command_line_tokens
;
105 const MUtils::OS::ArgumentMap
&MUtils::OS::arguments(void)
107 QReadLocker
readLock(&g_arguments_lock
);
109 //Already initialized?
110 if(!g_arguments_list
.isNull())
112 return (*(g_arguments_list
.data()));
116 QWriteLocker
writeLock(&g_arguments_lock
);
118 //Still not initialized?
119 if(!g_arguments_list
.isNull())
121 return (*(g_arguments_list
.data()));
124 g_arguments_list
.reset(new ArgumentMap());
125 const QStringList argList
= crack_command_line();
127 if(!argList
.isEmpty())
129 const QString argPrefix
= QLatin1String("--");
130 const QChar separator
= QLatin1Char('=');
132 bool firstToken
= true;
133 for(QStringList::ConstIterator iter
= argList
.constBegin(); iter
!= argList
.constEnd(); iter
++)
138 continue; /*skip executable file name*/
140 if(iter
->startsWith(argPrefix
))
142 const QString argData
= iter
->mid(2).trimmed();
143 if(argData
.length() > 0)
145 const int separatorIndex
= argData
.indexOf(separator
);
146 if(separatorIndex
> 0)
148 const QString argKey
= argData
.left(separatorIndex
).trimmed();
149 const QString argVal
= argData
.mid(separatorIndex
+ 1).trimmed();
150 g_arguments_list
->insertMulti(argKey
.toLower(), argVal
);
154 g_arguments_list
->insertMulti(argData
.toLower(), QString());
160 else if(argList
.empty())
162 qWarning("CommandLineToArgvW() has failed !!!");
165 return (*(g_arguments_list
.data()));
168 ///////////////////////////////////////////////////////////////////////////////
170 ///////////////////////////////////////////////////////////////////////////////
172 typedef struct _progress_callback_data_t
174 MUtils::OS::progress_callback_t callback_function
;
177 progress_callback_data_t
;
179 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
)
181 if(const progress_callback_data_t
*data
= (progress_callback_data_t
*) lpData
)
183 const double progress
= qBound(0.0, double(TotalBytesTransferred
.QuadPart
) / double(TotalFileSize
.QuadPart
), 1.0);
184 return data
->callback_function(progress
, data
->user_data
) ? PROGRESS_CONTINUE
: PROGRESS_CANCEL
;
186 return PROGRESS_CONTINUE
;
189 MUTILS_API
bool MUtils::OS::copy_file(const QString
&sourcePath
, const QString
&outputPath
, const bool &overwrite
, const progress_callback_t callback
, void *const userData
)
191 progress_callback_data_t callback_data
= { callback
, userData
};
193 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
));
197 const DWORD errorCode
= GetLastError();
198 if(errorCode
!= ERROR_REQUEST_ABORTED
)
200 qWarning("CopyFile() failed with error code 0x%08X!", errorCode
);
204 qWarning("CopyFile() operation was abroted by user!");
208 return (result
!= FALSE
);
211 ///////////////////////////////////////////////////////////////////////////////
213 ///////////////////////////////////////////////////////////////////////////////
215 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
)
217 if(!GetFileVersionInfo(MUTILS_WCHR(fileName
), 0, size
, buffer
))
219 qWarning("GetFileVersionInfo() has failed, file version cannot be determined!");
223 VS_FIXEDFILEINFO
*verInfo
;
225 if(!VerQueryValue(buffer
, L
"\\", (LPVOID
*)(&verInfo
), &verInfoLen
))
227 qWarning("VerQueryValue() has failed, file version cannot be determined!");
231 if(major
) *major
= quint16((verInfo
->dwFileVersionMS
>> 16) & 0x0000FFFF);
232 if(minor
) *minor
= quint16((verInfo
->dwFileVersionMS
) & 0x0000FFFF);
233 if(patch
) *patch
= quint16((verInfo
->dwFileVersionLS
>> 16) & 0x0000FFFF);
234 if(build
) *build
= quint16((verInfo
->dwFileVersionLS
) & 0x0000FFFF);
239 bool MUtils::OS::get_file_version(const QString fileName
, quint16
*const major
, quint16
*const minor
, quint16
*const patch
, quint16
*const build
)
241 if(major
) *major
= 0U; if(minor
) *minor
= 0U;
242 if(patch
) *patch
= 0U; if(build
) *build
= 0U;
244 const DWORD size
= GetFileVersionInfoSize(MUTILS_WCHR(fileName
), NULL
);
247 qWarning("GetFileVersionInfoSize() has failed, file version cannot be determined!");
251 PVOID buffer
= _malloca(size
);
254 qWarning("Memory allocation has failed!");
258 const bool success
= get_file_version_helper(fileName
, buffer
, size
, major
, minor
, patch
, build
);
264 ///////////////////////////////////////////////////////////////////////////////
265 // OS VERSION DETECTION
266 ///////////////////////////////////////////////////////////////////////////////
268 static bool g_os_version_initialized
= false;
269 static MUtils::OS::Version::os_version_t g_os_version_info
= MUtils::OS::Version::UNKNOWN_OPSYS
;
270 static QReadWriteLock g_os_version_lock
;
272 //Maps marketing names to the actual Windows NT versions
275 MUtils::OS::Version::os_version_t version
;
276 const char friendlyName
[64];
280 { MUtils::OS::Version::WINDOWS_WIN2K
, "Windows 2000" }, //2000
281 { MUtils::OS::Version::WINDOWS_WINXP
, "Windows XP or Windows XP Media Center Edition" }, //XP
282 { MUtils::OS::Version::WINDOWS_XPX64
, "Windows Server 2003 or Windows XP x64" }, //XP_x64
283 { MUtils::OS::Version::WINDOWS_VISTA
, "Windows Vista or Windows Server 2008" }, //Vista
284 { MUtils::OS::Version::WINDOWS_WIN70
, "Windows 7 or Windows Server 2008 R2" }, //7
285 { MUtils::OS::Version::WINDOWS_WIN80
, "Windows 8 or Windows Server 2012" }, //8
286 { MUtils::OS::Version::WINDOWS_WIN81
, "Windows 8.1 or Windows Server 2012 R2" }, //8.1
287 { MUtils::OS::Version::WINDOWS_WN100
, "Windows 10 or Windows Server 2016" }, //10
288 { MUtils::OS::Version::UNKNOWN_OPSYS
, "N/A" }
291 //OS version data dtructures
298 //Comparision operators for os_version_t
299 bool os_version_t::operator== (const os_version_t
&rhs
) const { return (type
== rhs
.type
) && (versionMajor
== rhs
.versionMajor
) && ((versionMinor
== rhs
.versionMinor
)); }
300 bool os_version_t::operator!= (const os_version_t
&rhs
) const { return (type
!= rhs
.type
) || (versionMajor
!= rhs
.versionMajor
) || ((versionMinor
!= rhs
.versionMinor
)); }
301 bool os_version_t::operator> (const os_version_t
&rhs
) const { return (type
== rhs
.type
) && ((versionMajor
> rhs
.versionMajor
) || ((versionMajor
== rhs
.versionMajor
) && (versionMinor
> rhs
.versionMinor
))); }
302 bool os_version_t::operator>= (const os_version_t
&rhs
) const { return (type
== rhs
.type
) && ((versionMajor
> rhs
.versionMajor
) || ((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
) || ((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
))); }
306 //Known Windows NT versions
307 const os_version_t WINDOWS_WIN2K
= { OS_WINDOWS
, 5, 0 }; // 2000
308 const os_version_t WINDOWS_WINXP
= { OS_WINDOWS
, 5, 1 }; // XP
309 const os_version_t WINDOWS_XPX64
= { OS_WINDOWS
, 5, 2 }; // XP_x64
310 const os_version_t WINDOWS_VISTA
= { OS_WINDOWS
, 6, 0 }; // Vista
311 const os_version_t WINDOWS_WIN70
= { OS_WINDOWS
, 6, 1 }; // 7
312 const os_version_t WINDOWS_WIN80
= { OS_WINDOWS
, 6, 2 }; // 8
313 const os_version_t WINDOWS_WIN81
= { OS_WINDOWS
, 6, 3 }; // 8.1
314 const os_version_t WINDOWS_WN100
= { OS_WINDOWS
, 10, 0 }; // 10
317 const os_version_t UNKNOWN_OPSYS
= { OS_UNKNOWN
, 0, 0 }; // N/A
322 static inline DWORD
SAFE_ADD(const DWORD
&a
, const DWORD
&b
)
324 const DWORD temp
= a
+ b
;
325 return ((temp
>= a
) && (temp
>= b
)) ? temp
: MAXDWORD
;
328 static void initialize_os_version(OSVERSIONINFOEXW
*const osInfo
)
330 memset(osInfo
, 0, sizeof(OSVERSIONINFOEXW
));
331 osInfo
->dwOSVersionInfoSize
= sizeof(OSVERSIONINFOEXW
);
334 static bool rtl_get_version(OSVERSIONINFOEXW
*const osInfo
)
336 typedef LONG(__stdcall
*RtlGetVersion
)(LPOSVERSIONINFOEXW
);
337 if (const HMODULE ntdll
= GetModuleHandleW(L
"ntdll"))
339 if (const RtlGetVersion pRtlGetVersion
= (RtlGetVersion
)GetProcAddress(ntdll
, "RtlGetVersion"))
341 initialize_os_version(osInfo
);
342 if (pRtlGetVersion(osInfo
) == 0)
350 initialize_os_version(osInfo
);
351 return (GetVersionExW((LPOSVERSIONINFOW
)osInfo
) != FALSE
);
354 static bool rtl_verify_version(OSVERSIONINFOEXW
*const osInfo
, const ULONG typeMask
, const ULONGLONG condMask
)
356 typedef LONG(__stdcall
*RtlVerifyVersionInfo
)(LPOSVERSIONINFOEXW
, ULONG
, ULONGLONG
);
357 if (const HMODULE ntdll
= GetModuleHandleW(L
"ntdll"))
359 if (const RtlVerifyVersionInfo pRtlVerifyVersionInfo
= (RtlVerifyVersionInfo
)GetProcAddress(ntdll
, "RtlVerifyVersionInfo"))
361 if (pRtlVerifyVersionInfo(osInfo
, typeMask
, condMask
) == 0)
369 return (VerifyVersionInfoW(osInfo
, typeMask
, condMask
) != FALSE
);
372 static bool verify_os_version(const DWORD major
, const DWORD minor
)
374 OSVERSIONINFOEXW osvi
;
375 DWORDLONG dwlConditionMask
= 0;
376 initialize_os_version(&osvi
);
378 //Initialize the OSVERSIONINFOEX structure
379 osvi
.dwMajorVersion
= major
;
380 osvi
.dwMinorVersion
= minor
;
381 osvi
.dwPlatformId
= VER_PLATFORM_WIN32_NT
;
383 //Initialize the condition mask
384 VER_SET_CONDITION(dwlConditionMask
, VER_MAJORVERSION
, VER_GREATER_EQUAL
);
385 VER_SET_CONDITION(dwlConditionMask
, VER_MINORVERSION
, VER_GREATER_EQUAL
);
386 VER_SET_CONDITION(dwlConditionMask
, VER_PLATFORMID
, VER_EQUAL
);
389 const BOOL ret
= rtl_verify_version(&osvi
, VER_MAJORVERSION
| VER_MINORVERSION
| VER_PLATFORMID
, dwlConditionMask
);
394 if(GetLastError() != ERROR_OLD_WIN_VERSION
)
396 qWarning("VerifyVersionInfo() system call has failed!");
400 return (ret
!= FALSE
);
403 static bool verify_os_build(const DWORD build
)
405 OSVERSIONINFOEXW osvi
;
406 DWORDLONG dwlConditionMask
= 0;
407 initialize_os_version(&osvi
);
409 //Initialize the OSVERSIONINFOEX structure
410 osvi
.dwBuildNumber
= build
;
411 osvi
.dwPlatformId
= VER_PLATFORM_WIN32_NT
;
413 //Initialize the condition mask
414 VER_SET_CONDITION(dwlConditionMask
, VER_BUILDNUMBER
, VER_GREATER_EQUAL
);
415 VER_SET_CONDITION(dwlConditionMask
, VER_PLATFORMID
, VER_EQUAL
);
418 const BOOL ret
= rtl_verify_version(&osvi
, VER_BUILDNUMBER
| VER_PLATFORMID
, dwlConditionMask
);
423 if (GetLastError() != ERROR_OLD_WIN_VERSION
)
425 qWarning("VerifyVersionInfo() system call has failed!");
429 return (ret
!= FALSE
);
432 static bool get_real_os_version(unsigned int *major
, unsigned int *minor
, unsigned int *build
, bool *pbOverride
)
434 static const DWORD MAX_VERSION
= 0xFFFF;
436 *major
= *minor
= *build
= 0;
439 //Initialize local variables
440 OSVERSIONINFOEXW osvi
;
441 memset(&osvi
, 0, sizeof(OSVERSIONINFOEXW
));
442 osvi
.dwOSVersionInfoSize
= sizeof(OSVERSIONINFOEXW
);
444 //Try GetVersionEx() first
445 if(rtl_get_version(&osvi
) == FALSE
)
447 qWarning("GetVersionEx() has failed, cannot detect Windows version!");
451 //Make sure we are running on NT
452 if(osvi
.dwPlatformId
== VER_PLATFORM_WIN32_NT
)
454 *major
= osvi
.dwMajorVersion
;
455 *minor
= osvi
.dwMinorVersion
;
456 *build
= osvi
.dwBuildNumber
;
460 if (verify_os_version(4, 0))
468 qWarning("Not running on Windows NT, unsupported operating system!");
474 for (DWORD nextMajor
= (*major
) + 1; nextMajor
<= MAX_VERSION
; nextMajor
++)
476 if (verify_os_version(nextMajor
, 0))
487 for (DWORD nextMinor
= (*minor
) + 1; nextMinor
<= MAX_VERSION
; nextMinor
++)
489 if (verify_os_version((*major
), nextMinor
))
499 DWORD stepSize
= 32768;
500 for (DWORD nextBuildNo
= SAFE_ADD((*build
), stepSize
); (*build
) < MAXDWORD
; nextBuildNo
= SAFE_ADD((*build
), stepSize
))
502 if (verify_os_build(nextBuildNo
))
504 *build
= nextBuildNo
;
510 stepSize
= stepSize
/ 2;
519 const MUtils::OS::Version::os_version_t
&MUtils::OS::os_version(void)
521 QReadLocker
readLock(&g_os_version_lock
);
523 //Already initialized?
524 if(g_os_version_initialized
)
526 return g_os_version_info
;
530 QWriteLocker
writeLock(&g_os_version_lock
);
533 if(g_os_version_initialized
)
535 return g_os_version_info
;
539 unsigned int major
, minor
, build
; bool overrideFlg
;
540 if(get_real_os_version(&major
, &minor
, &build
, &overrideFlg
))
542 g_os_version_info
.type
= Version::OS_WINDOWS
;
543 g_os_version_info
.versionMajor
= major
;
544 g_os_version_info
.versionMinor
= minor
;
545 g_os_version_info
.versionBuild
= build
;
546 g_os_version_info
.overrideFlag
= overrideFlg
;
550 qWarning("Failed to determin the operating system version!");
554 g_os_version_initialized
= true;
555 return g_os_version_info
;
558 const char *MUtils::OS::os_friendly_name(const MUtils::OS::Version::os_version_t
&os_version
)
560 for(size_t i
= 0; g_os_version_lut
[i
].version
!= MUtils::OS::Version::UNKNOWN_OPSYS
; i
++)
562 if(os_version
== g_os_version_lut
[i
].version
)
564 return g_os_version_lut
[i
].friendlyName
;
571 ///////////////////////////////////////////////////////////////////////////////
573 ///////////////////////////////////////////////////////////////////////////////
575 static bool g_wine_deteced
= false;
576 static bool g_wine_initialized
= false;
577 static QReadWriteLock g_wine_lock
;
579 static const bool detect_wine(void)
581 void *const ptr
= MUtils::Win32Utils::resolve
<void*>(QLatin1String("ntdll"), QLatin1String("wine_get_version"));
582 return (ptr
!= NULL
);
585 const bool &MUtils::OS::running_on_wine(void)
587 QReadLocker
readLock(&g_wine_lock
);
589 //Already initialized?
590 if(g_wine_initialized
)
592 return g_wine_deteced
;
596 QWriteLocker
writeLock(&g_wine_lock
);
599 if(g_wine_initialized
)
601 return g_wine_deteced
;
605 g_wine_deteced
= detect_wine();
606 g_wine_initialized
= true;
608 return g_wine_deteced
;
611 ///////////////////////////////////////////////////////////////////////////////
613 ///////////////////////////////////////////////////////////////////////////////
615 typedef QMap
<size_t, QString
> KFMap
;
616 typedef HRESULT (WINAPI
*SHGetKnownFolderPath_t
)(const GUID
&rfid
, DWORD dwFlags
, HANDLE hToken
, PWSTR
*ppszPath
);
617 typedef HRESULT (WINAPI
*SHGetFolderPath_t
) (HWND hwndOwner
, int nFolder
, HANDLE hToken
, DWORD dwFlags
, LPWSTR pszPath
);
619 static QScopedPointer
<KFMap
> g_known_folders_map
;
620 static QReadWriteLock g_known_folders_lock
;
622 const QString
&MUtils::OS::known_folder(known_folder_t folder_id
)
624 typedef enum { KF_FLAG_CREATE
= 0x00008000 } kf_flags_t
;
633 { 0x001c, {0xF1B32785,0x6FBA,0x4FCF,{0x9D,0x55,0x7B,0x8E,0x7F,0x15,0x70,0x91}} }, //CSIDL_LOCAL_APPDATA
634 { 0x0026, {0x905e63b6,0xc1bf,0x494e,{0xb2,0x9c,0x65,0xb7,0x32,0xd3,0xd2,0x1a}} }, //CSIDL_PROGRAM_FILES
635 { 0x0024, {0xF38BF404,0x1D43,0x42F2,{0x93,0x05,0x67,0xDE,0x0B,0x28,0xFC,0x23}} }, //CSIDL_WINDOWS_FOLDER
636 { 0x0025, {0x1AC14E77,0x02E7,0x4E5D,{0xB7,0x44,0x2E,0xB1,0xAE,0x51,0x98,0xB7}} }, //CSIDL_SYSTEM_FOLDER
639 size_t folderId
= size_t(-1);
643 case FOLDER_LOCALAPPDATA
: folderId
= 0; break;
644 case FOLDER_PROGRAMFILES
: folderId
= 1; break;
645 case FOLDER_SYSTROOT_DIR
: folderId
= 2; break;
646 case FOLDER_SYSTEMFOLDER
: folderId
= 3; break;
649 if(folderId
== size_t(-1))
651 qWarning("Invalid 'known' folder was requested!");
652 return *reinterpret_cast<QString
*>(NULL
);
655 QReadLocker
readLock(&g_known_folders_lock
);
658 if(!g_known_folders_map
.isNull())
660 if(g_known_folders_map
->contains(folderId
))
662 return g_known_folders_map
->operator[](folderId
);
666 //Obtain write lock to initialize
668 QWriteLocker
writeLock(&g_known_folders_lock
);
670 //Still not in cache?
671 if(!g_known_folders_map
.isNull())
673 if(g_known_folders_map
->contains(folderId
))
675 return g_known_folders_map
->operator[](folderId
);
679 //Initialize on first call
680 if(g_known_folders_map
.isNull())
682 g_known_folders_map
.reset(new QMap
<size_t, QString
>());
687 //Now try to get the folder path!
688 if(const SHGetKnownFolderPath_t known_folders_fpGetKnownFolderPath
= MUtils::Win32Utils::resolve
<SHGetKnownFolderPath_t
>(QLatin1String("shell32"), QLatin1String("SHGetKnownFolderPath")))
691 if(known_folders_fpGetKnownFolderPath(s_folders
[folderId
].guid
, KF_FLAG_CREATE
, NULL
, &path
) == S_OK
)
693 //MessageBoxW(0, path, L"SHGetKnownFolderPath", MB_TOPMOST);
694 QDir folderTemp
= QDir(QDir::fromNativeSeparators(MUTILS_QSTR(path
)));
695 if(folderTemp
.exists())
697 folderPath
= folderTemp
.canonicalPath();
702 else if(const SHGetFolderPath_t known_folders_fpGetFolderPath
= MUtils::Win32Utils::resolve
<SHGetFolderPath_t
>(QLatin1String("shell32"), QLatin1String("SHGetFolderPathW")))
704 QScopedArrayPointer
<WCHAR
> path(new WCHAR
[4096]);
705 if(known_folders_fpGetFolderPath(NULL
, s_folders
[folderId
].csidl
| CSIDL_FLAG_CREATE
, NULL
, NULL
, path
.data()) == S_OK
)
707 //MessageBoxW(0, path, L"SHGetFolderPathW", MB_TOPMOST);
708 QDir folderTemp
= QDir(QDir::fromNativeSeparators(MUTILS_QSTR(path
.data())));
709 if(folderTemp
.exists())
711 folderPath
= folderTemp
.canonicalPath();
717 g_known_folders_map
->insert(folderId
, folderPath
);
718 return g_known_folders_map
->operator[](folderId
);
721 ///////////////////////////////////////////////////////////////////////////////
722 // CURRENT DATA & TIME
723 ///////////////////////////////////////////////////////////////////////////////
725 QDate
MUtils::OS::current_date(void)
727 const DWORD MAX_PROC
= 1024;
728 QScopedArrayPointer
<DWORD
> processes(new DWORD
[MAX_PROC
]);
729 DWORD bytesReturned
= 0;
731 if(!EnumProcesses(processes
.data(), sizeof(DWORD
) * MAX_PROC
, &bytesReturned
))
733 return QDate::currentDate();
736 const DWORD procCount
= bytesReturned
/ sizeof(DWORD
);
737 ULARGE_INTEGER lastStartTime
;
738 memset(&lastStartTime
, 0, sizeof(ULARGE_INTEGER
));
740 for(DWORD i
= 0; i
< procCount
; i
++)
742 if(HANDLE hProc
= OpenProcess(PROCESS_QUERY_INFORMATION
, FALSE
, processes
[i
]))
744 FILETIME processTime
[4];
745 if(GetProcessTimes(hProc
, &processTime
[0], &processTime
[1], &processTime
[2], &processTime
[3]))
747 ULARGE_INTEGER timeCreation
;
748 timeCreation
.LowPart
= processTime
[0].dwLowDateTime
;
749 timeCreation
.HighPart
= processTime
[0].dwHighDateTime
;
750 if(timeCreation
.QuadPart
> lastStartTime
.QuadPart
)
752 lastStartTime
.QuadPart
= timeCreation
.QuadPart
;
759 FILETIME lastStartTime_fileTime
;
760 lastStartTime_fileTime
.dwHighDateTime
= lastStartTime
.HighPart
;
761 lastStartTime_fileTime
.dwLowDateTime
= lastStartTime
.LowPart
;
763 FILETIME lastStartTime_localTime
;
764 if(!FileTimeToLocalFileTime(&lastStartTime_fileTime
, &lastStartTime_localTime
))
766 memcpy(&lastStartTime_localTime
, &lastStartTime_fileTime
, sizeof(FILETIME
));
769 SYSTEMTIME lastStartTime_system
;
770 if(!FileTimeToSystemTime(&lastStartTime_localTime
, &lastStartTime_system
))
772 memset(&lastStartTime_system
, 0, sizeof(SYSTEMTIME
));
773 lastStartTime_system
.wYear
= 1970; lastStartTime_system
.wMonth
= lastStartTime_system
.wDay
= 1;
776 const QDate currentDate
= QDate::currentDate();
777 const QDate processDate
= QDate(lastStartTime_system
.wYear
, lastStartTime_system
.wMonth
, lastStartTime_system
.wDay
);
778 return (currentDate
>= processDate
) ? currentDate
: processDate
;
781 quint64
MUtils::OS::current_file_time(void)
784 GetSystemTimeAsFileTime(&fileTime
);
787 temp
.HighPart
= fileTime
.dwHighDateTime
;
788 temp
.LowPart
= fileTime
.dwLowDateTime
;
790 return temp
.QuadPart
;
793 ///////////////////////////////////////////////////////////////////////////////
795 ///////////////////////////////////////////////////////////////////////////////
797 typedef DWORD(_stdcall
*GetPathNameByHandleFun
)(HANDLE hFile
, LPWSTR lpszFilePath
, DWORD cchFilePath
, DWORD dwFlags
);
799 static QString
get_file_path_drive_list(void)
802 const DWORD len
= GetLogicalDriveStringsW(0, NULL
);
805 if (wchar_t *const buffer
= (wchar_t*) _malloca(sizeof(wchar_t) * len
))
807 const DWORD ret
= GetLogicalDriveStringsW(len
, buffer
);
808 if ((ret
> 0) && (ret
< len
))
810 const wchar_t *ptr
= buffer
;
811 while (const size_t current_len
= wcslen(ptr
))
813 list
.append(QChar(*reinterpret_cast<const ushort
*>(ptr
)));
814 ptr
+= (current_len
+ 1);
823 static void get_file_path_translate(QString
&path
)
825 static const DWORD BUFSIZE
= 2048;
826 wchar_t buffer
[BUFSIZE
], drive
[3];
828 const QString driveList
= get_file_path_drive_list();
829 wcscpy_s(drive
, 3, L
"?:");
830 for (const wchar_t *current
= MUTILS_WCHR(driveList
); *current
; current
++)
832 drive
[0] = (*current
);
833 if (QueryDosDeviceW(drive
, buffer
, MAX_PATH
))
835 const QString prefix
= MUTILS_QSTR(buffer
);
836 if (path
.startsWith(prefix
, Qt::CaseInsensitive
))
838 path
.remove(0, prefix
.length()).prepend(QLatin1Char(':')).prepend(QChar(*reinterpret_cast<const ushort
*>(current
)));
845 static QString
get_file_path_fallback(const HANDLE
&hFile
)
849 const HANDLE hFileMap
= CreateFileMappingW(hFile
, NULL
, PAGE_READONLY
, 0, 1, NULL
);
852 void *const pMem
= MapViewOfFile(hFileMap
, FILE_MAP_READ
, 0, 0, 1);
855 static const size_t BUFFSIZE
= 2048;
856 wchar_t buffer
[BUFFSIZE
];
857 if (GetMappedFileNameW(GetCurrentProcess(), pMem
, buffer
, BUFFSIZE
) > 0)
859 filePath
= MUTILS_QSTR(buffer
);
861 UnmapViewOfFile(pMem
);
863 CloseHandle(hFileMap
);
866 if (!filePath
.isEmpty())
868 get_file_path_translate(filePath
);
874 QString
MUtils::OS::get_file_path(const int &fd
)
878 const GetPathNameByHandleFun getPathNameByHandleFun
= MUtils::Win32Utils::resolve
<GetPathNameByHandleFun
>(QLatin1String("kernel32"), QLatin1String("GetFinalPathNameByHandleW"));
879 if (!getPathNameByHandleFun
)
881 return get_file_path_fallback((HANDLE
)_get_osfhandle(fd
));
884 const HANDLE handle
= (HANDLE
) _get_osfhandle(fd
);
885 const DWORD len
= getPathNameByHandleFun(handle
, NULL
, 0, FILE_NAME_OPENED
);
888 if (wchar_t *const buffer
= (wchar_t*)_malloca(sizeof(wchar_t) * len
))
890 const DWORD ret
= getPathNameByHandleFun(handle
, buffer
, len
, FILE_NAME_OPENED
);
891 if ((ret
> 0) && (ret
< len
))
893 const QString
path(MUTILS_QSTR(buffer
));
894 return path
.startsWith(QLatin1String("\\\\?\\")) ? path
.mid(4) : path
;
904 ///////////////////////////////////////////////////////////////////////////////
906 ///////////////////////////////////////////////////////////////////////////////
908 static bool user_is_admin_helper(void)
910 HANDLE hToken
= NULL
;
911 if(!OpenProcessToken(GetCurrentProcess(), TOKEN_QUERY
, &hToken
))
917 if(!GetTokenInformation(hToken
, TokenGroups
, NULL
, 0, &dwSize
))
919 if(GetLastError() != ERROR_INSUFFICIENT_BUFFER
)
926 PTOKEN_GROUPS lpGroups
= (PTOKEN_GROUPS
) malloc(dwSize
);
933 if(!GetTokenInformation(hToken
, TokenGroups
, lpGroups
, dwSize
, &dwSize
))
940 PSID lpSid
= NULL
; SID_IDENTIFIER_AUTHORITY Authority
= {SECURITY_NT_AUTHORITY
};
941 if(!AllocateAndInitializeSid(&Authority
, 2, SECURITY_BUILTIN_DOMAIN_RID
, DOMAIN_ALIAS_RID_ADMINS
, 0, 0, 0, 0, 0, 0, &lpSid
))
948 bool bResult
= false;
949 for(DWORD i
= 0; i
< lpGroups
->GroupCount
; i
++)
951 if(EqualSid(lpSid
, lpGroups
->Groups
[i
].Sid
))
964 bool MUtils::OS::is_elevated(bool *bIsUacEnabled
)
968 *bIsUacEnabled
= false;
971 bool bIsProcessElevated
= false;
972 HANDLE hToken
= NULL
;
974 if(OpenProcessToken(GetCurrentProcess(), TOKEN_QUERY
, &hToken
))
976 TOKEN_ELEVATION_TYPE tokenElevationType
;
978 if(GetTokenInformation(hToken
, TokenElevationType
, &tokenElevationType
, sizeof(TOKEN_ELEVATION_TYPE
), &returnLength
))
980 if(returnLength
== sizeof(TOKEN_ELEVATION_TYPE
))
982 switch(tokenElevationType
)
984 case TokenElevationTypeDefault
:
985 qDebug("Process token elevation type: Default -> UAC is disabled.\n");
987 case TokenElevationTypeFull
:
988 qWarning("Process token elevation type: Full -> potential security risk!\n");
989 bIsProcessElevated
= true;
990 if(bIsUacEnabled
) *bIsUacEnabled
= true;
992 case TokenElevationTypeLimited
:
993 qDebug("Process token elevation type: Limited -> not elevated.\n");
994 if(bIsUacEnabled
) *bIsUacEnabled
= true;
997 qWarning("Unknown tokenElevationType value: %d", tokenElevationType
);
1003 qWarning("GetTokenInformation() return an unexpected size!");
1006 CloseHandle(hToken
);
1010 qWarning("Failed to open process token!");
1013 return bIsProcessElevated
;
1016 bool MUtils::OS::user_is_admin(void)
1018 bool isAdmin
= false;
1020 //Check for process elevation and UAC support first!
1021 if(MUtils::OS::is_elevated(&isAdmin
))
1023 qWarning("Process is elevated -> user is admin!");
1027 //If not elevated and UAC is not available -> user must be in admin group!
1030 qDebug("UAC is disabled/unavailable -> checking for Administrators group");
1031 isAdmin
= user_is_admin_helper();
1037 ///////////////////////////////////////////////////////////////////////////////
1039 ///////////////////////////////////////////////////////////////////////////////
1041 int MUtils::OS::network_status(void)
1044 const BOOL ret
= IsNetworkAlive(&dwFlags
);
1045 if(GetLastError() == 0)
1047 return (ret
!= FALSE
) ? NETWORK_TYPE_YES
: NETWORK_TYPE_NON
;
1049 return NETWORK_TYPE_ERR
;
1052 ///////////////////////////////////////////////////////////////////////////////
1054 ///////////////////////////////////////////////////////////////////////////////
1056 bool MUtils::OS::handle_os_message(const void *const message
, long *result
)
1058 const MSG
*const msg
= reinterpret_cast<const MSG
*>(message
);
1060 switch(msg
->message
)
1062 case WM_QUERYENDSESSION
:
1063 qWarning("WM_QUERYENDSESSION message received!");
1064 *result
= MUtils::GUI::broadcast(MUtils::GUI::USER_EVENT_QUERYENDSESSION
, false) ? TRUE
: FALSE
;
1067 qWarning("WM_ENDSESSION message received!");
1068 if(msg
->wParam
== TRUE
)
1070 MUtils::GUI::broadcast(MUtils::GUI::USER_EVENT_ENDSESSION
, false);
1071 MUtils::GUI::force_quit();
1077 /*ignore this message and let Qt handle it*/
1082 ///////////////////////////////////////////////////////////////////////////////
1084 ///////////////////////////////////////////////////////////////////////////////
1086 void MUtils::OS::sleep_ms(const size_t &duration
)
1088 Sleep((DWORD
) duration
);
1091 ///////////////////////////////////////////////////////////////////////////////
1093 ///////////////////////////////////////////////////////////////////////////////
1095 static int g_library_as_image_resource_supported
= -1;
1096 static QReadWriteLock g_library_as_image_resource_supported_lock
;
1098 static bool library_as_image_resource_supported()
1100 QReadLocker
readLocker(&g_library_as_image_resource_supported_lock
);
1101 if (g_library_as_image_resource_supported
>= 0)
1103 return (g_library_as_image_resource_supported
> 0);
1106 readLocker
.unlock();
1107 QWriteLocker
writeLocker(&g_library_as_image_resource_supported_lock
);
1109 if (g_library_as_image_resource_supported
< 0)
1111 g_library_as_image_resource_supported
= 0;
1112 OSVERSIONINFOEXW osvi
;
1113 if (rtl_get_version(&osvi
))
1115 if ((osvi
.dwPlatformId
== VER_PLATFORM_WIN32_NT
) && (osvi
.dwMajorVersion
>= 6U))
1117 g_library_as_image_resource_supported
= 1;
1122 return (g_library_as_image_resource_supported
> 0);
1125 bool MUtils::OS::is_executable_file(const QString
&path
)
1128 if(GetBinaryType(MUTILS_WCHR(QDir::toNativeSeparators(path
)), &binaryType
))
1130 return ((binaryType
== SCS_32BIT_BINARY
) || (binaryType
== SCS_64BIT_BINARY
));
1133 const DWORD errorCode
= GetLastError();
1134 qWarning("GetBinaryType() failed with error: 0x%08X", errorCode
);
1138 bool MUtils::OS::is_library_file(const QString
&path
)
1140 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
);
1141 if (const HMODULE hMod
= LoadLibraryEx(MUTILS_WCHR(QDir::toNativeSeparators(path
)), NULL
, flags
))
1147 const DWORD errorCode
= GetLastError();
1148 qWarning("LoadLibraryEx() failed with error: 0x%08X", errorCode
);
1152 ///////////////////////////////////////////////////////////////////////////////
1153 // HIBERNATION / SHUTDOWN
1154 ///////////////////////////////////////////////////////////////////////////////
1156 bool MUtils::OS::is_hibernation_supported(void)
1158 bool hibernationSupported
= false;
1160 SYSTEM_POWER_CAPABILITIES pwrCaps
;
1161 SecureZeroMemory(&pwrCaps
, sizeof(SYSTEM_POWER_CAPABILITIES
));
1163 if(GetPwrCapabilities(&pwrCaps
))
1165 hibernationSupported
= pwrCaps
.SystemS4
&& pwrCaps
.HiberFilePresent
;
1168 return hibernationSupported
;
1171 bool MUtils::OS::shutdown_computer(const QString
&message
, const unsigned long timeout
, const bool forceShutdown
, const bool hibernate
)
1173 HANDLE hToken
= NULL
;
1175 if(OpenProcessToken(GetCurrentProcess(), TOKEN_ADJUST_PRIVILEGES
| TOKEN_QUERY
, &hToken
))
1177 TOKEN_PRIVILEGES privileges
;
1178 memset(&privileges
, 0, sizeof(TOKEN_PRIVILEGES
));
1179 privileges
.PrivilegeCount
= 1;
1180 privileges
.Privileges
[0].Attributes
= SE_PRIVILEGE_ENABLED
;
1182 if(LookupPrivilegeValue(NULL
, SE_SHUTDOWN_NAME
, &privileges
.Privileges
[0].Luid
))
1184 if(AdjustTokenPrivileges(hToken
, FALSE
, &privileges
, NULL
, NULL
, NULL
))
1188 if(SetSuspendState(TRUE
, TRUE
, TRUE
))
1193 const DWORD reason
= SHTDN_REASON_MAJOR_APPLICATION
| SHTDN_REASON_FLAG_PLANNED
;
1194 return InitiateSystemShutdownEx(NULL
, const_cast<wchar_t*>(MUTILS_WCHR(message
)), timeout
, forceShutdown
? TRUE
: FALSE
, FALSE
, reason
);
1202 ///////////////////////////////////////////////////////////////////////////////
1204 ///////////////////////////////////////////////////////////////////////////////
1206 bool MUtils::OS::free_diskspace(const QString
&path
, quint64
&freeSpace
)
1208 ULARGE_INTEGER freeBytesAvailable
, totalNumberOfBytes
, totalNumberOfFreeBytes
;
1209 if(GetDiskFreeSpaceExW(reinterpret_cast<const wchar_t*>(QDir::toNativeSeparators(path
).utf16()), &freeBytesAvailable
, &totalNumberOfBytes
, &totalNumberOfFreeBytes
))
1211 freeSpace
= freeBytesAvailable
.QuadPart
;
1219 ///////////////////////////////////////////////////////////////////////////////
1221 ///////////////////////////////////////////////////////////////////////////////
1223 bool MUtils::OS::shell_open(const QWidget
*parent
, const QString
&url
, const QString
¶meters
, const QString
&directory
, const bool explore
)
1225 return ((int) ShellExecuteW((parent
? parent
->winId() : NULL
), (explore
? L
"explore" : L
"open"), MUTILS_WCHR(url
), ((!parameters
.isEmpty()) ? MUTILS_WCHR(parameters
) : NULL
), ((!directory
.isEmpty()) ? MUTILS_WCHR(directory
) : NULL
), SW_SHOW
)) > 32;
1228 bool MUtils::OS::shell_open(const QWidget
*parent
, const QString
&url
, const bool explore
)
1230 return shell_open(parent
, url
, QString(), QString(), explore
);
1233 ///////////////////////////////////////////////////////////////////////////////
1235 ///////////////////////////////////////////////////////////////////////////////
1237 bool MUtils::OS::open_media_file(const QString
&mediaFilePath
)
1239 const static wchar_t *registryPrefix
[2] = { L
"SOFTWARE\\", L
"SOFTWARE\\Wow6432Node\\" };
1240 const static wchar_t *registryKeys
[3] =
1242 L
"Microsoft\\Windows\\CurrentVersion\\Uninstall\\{97D341C8-B0D1-4E4A-A49A-C30B52F168E9}",
1243 L
"Microsoft\\Windows\\CurrentVersion\\Uninstall\\{DB9E4EAB-2717-499F-8D56-4CC8A644AB60}",
1246 const static wchar_t *appNames
[4] = { L
"smplayer_portable.exe", L
"smplayer.exe", L
"MPUI.exe", L
"foobar2000.exe" };
1247 const static wchar_t *valueNames
[2] = { L
"InstallLocation", L
"InstallDir" };
1249 for(size_t i
= 0; i
< 3; i
++)
1251 for(size_t j
= 0; j
< 2; j
++)
1253 QString mplayerPath
;
1254 HKEY registryKeyHandle
= NULL
;
1256 const QString currentKey
= MUTILS_QSTR(registryPrefix
[j
]).append(MUTILS_QSTR(registryKeys
[i
]));
1257 if(RegOpenKeyExW(HKEY_LOCAL_MACHINE
, MUTILS_WCHR(currentKey
), 0, KEY_READ
, ®istryKeyHandle
) == ERROR_SUCCESS
)
1259 for(size_t k
= 0; k
< 2; k
++)
1261 wchar_t Buffer
[4096];
1262 DWORD BuffSize
= sizeof(wchar_t*) * 4096;
1263 DWORD DataType
= REG_NONE
;
1264 if(RegQueryValueExW(registryKeyHandle
, valueNames
[k
], 0, &DataType
, reinterpret_cast<BYTE
*>(Buffer
), &BuffSize
) == ERROR_SUCCESS
)
1266 if((DataType
== REG_SZ
) || (DataType
== REG_EXPAND_SZ
) || (DataType
== REG_LINK
))
1268 mplayerPath
= MUTILS_QSTR(Buffer
);
1273 RegCloseKey(registryKeyHandle
);
1276 if(!mplayerPath
.isEmpty())
1278 QDir
mplayerDir(mplayerPath
);
1279 if(mplayerDir
.exists())
1281 for(size_t k
= 0; k
< 4; k
++)
1283 if(mplayerDir
.exists(MUTILS_QSTR(appNames
[k
])))
1285 qDebug("Player found at:\n%s\n", MUTILS_UTF8(mplayerDir
.absoluteFilePath(MUTILS_QSTR(appNames
[k
]))));
1286 QProcess::startDetached(mplayerDir
.absoluteFilePath(MUTILS_QSTR(appNames
[k
])), QStringList() << QDir::toNativeSeparators(mediaFilePath
));
1297 ///////////////////////////////////////////////////////////////////////////////
1299 ///////////////////////////////////////////////////////////////////////////////
1301 static bool change_process_priority_helper(const HANDLE hProcess
, const int priority
)
1305 switch(qBound(-2, priority
, 2))
1308 ok
= (SetPriorityClass(hProcess
, HIGH_PRIORITY_CLASS
) == TRUE
);
1311 if(!(ok
= (SetPriorityClass(hProcess
, ABOVE_NORMAL_PRIORITY_CLASS
) == TRUE
)))
1313 ok
= (SetPriorityClass(hProcess
, HIGH_PRIORITY_CLASS
) == TRUE
);
1317 ok
= (SetPriorityClass(hProcess
, NORMAL_PRIORITY_CLASS
) == TRUE
);
1320 if(!(ok
= (SetPriorityClass(hProcess
, BELOW_NORMAL_PRIORITY_CLASS
) == TRUE
)))
1322 ok
= (SetPriorityClass(hProcess
, IDLE_PRIORITY_CLASS
) == TRUE
);
1326 ok
= (SetPriorityClass(hProcess
, IDLE_PRIORITY_CLASS
) == TRUE
);
1333 bool MUtils::OS::change_process_priority(const int priority
)
1335 return change_process_priority_helper(GetCurrentProcess(), priority
);
1338 bool MUtils::OS::change_process_priority(const QProcess
*proc
, const int priority
)
1340 if(Q_PID qPid
= proc
->pid())
1342 return change_process_priority_helper(qPid
->hProcess
, priority
);
1350 ///////////////////////////////////////////////////////////////////////////////
1352 ///////////////////////////////////////////////////////////////////////////////
1354 quint32
MUtils::OS::process_id(const QProcess
*const proc
)
1356 PROCESS_INFORMATION
*procInf
= proc
->pid();
1357 return (procInf
) ? procInf
->dwProcessId
: NULL
;
1360 ///////////////////////////////////////////////////////////////////////////////
1361 // PROCESS SUSPEND/RESUME
1362 ///////////////////////////////////////////////////////////////////////////////
1364 bool MUtils::OS::suspend_process(const QProcess
*proc
, const bool suspend
)
1366 if(Q_PID pid
= proc
->pid())
1370 return (SuspendThread(pid
->hThread
) != ((DWORD
) -1));
1374 return (ResumeThread(pid
->hThread
) != ((DWORD
) -1));
1383 ///////////////////////////////////////////////////////////////////////////////
1385 ///////////////////////////////////////////////////////////////////////////////
1387 bool MUtils::OS::setup_timer_resolution(const quint32
&interval
)
1389 return timeBeginPeriod(interval
) == TIMERR_NOERROR
;
1392 bool MUtils::OS::reset_timer_resolution(const quint32
&interval
)
1394 return timeEndPeriod(interval
) == TIMERR_NOERROR
;
1397 ///////////////////////////////////////////////////////////////////////////////
1399 ///////////////////////////////////////////////////////////////////////////////
1401 static QScopedPointer
<QDateTime
> s_epoch
;
1402 static QReadWriteLock s_epochLock
;
1404 static const QDateTime
*get_epoch(void)
1406 QReadLocker
rdLock(&s_epochLock
);
1408 if (s_epoch
.isNull())
1411 QWriteLocker
wrLock(&s_epochLock
);
1412 if (s_epoch
.isNull())
1414 s_epoch
.reset(new QDateTime(QDate(1601, 1, 1), QTime(0, 0, 0, 0), Qt::UTC
));
1420 return s_epoch
.data();
1423 static FILETIME
*qt_time_to_file_time(FILETIME
*const fileTime
, const QDateTime
&dateTime
)
1425 memset(fileTime
, 0, sizeof(FILETIME
));
1427 if (const QDateTime
*const epoch
= get_epoch())
1429 const qint64 msecs
= epoch
->msecsTo(dateTime
);
1432 const quint64 ticks
= 10000U * quint64(msecs
);
1433 fileTime
->dwHighDateTime
= ((ticks
>> 32) & 0xFFFFFFFF);
1434 fileTime
->dwLowDateTime
= (ticks
& 0xFFFFFFFF);
1442 static bool set_file_time(const HANDLE hFile
, const QDateTime
&created
, const QDateTime
&lastMod
, const QDateTime
&lastAcc
)
1444 FILETIME ftCreated
, ftLastMod
, ftLastAcc
;
1446 FILETIME
*const pCreated
= created
.isValid() ? qt_time_to_file_time(&ftCreated
, created
) : NULL
;
1447 FILETIME
*const pLastMod
= lastMod
.isValid() ? qt_time_to_file_time(&ftLastMod
, lastMod
) : NULL
;
1448 FILETIME
*const pLastAcc
= lastAcc
.isValid() ? qt_time_to_file_time(&ftLastAcc
, lastAcc
) : NULL
;
1450 if (pCreated
|| pLastMod
|| pLastAcc
)
1452 return (SetFileTime(hFile
, pCreated
, pLastAcc
, pLastMod
) != FALSE
);
1458 bool MUtils::OS::set_file_time(const QFile
&file
, const QDateTime
&created
, const QDateTime
&lastMod
, const QDateTime
&lastAcc
)
1460 const int fd
= file
.handle();
1463 return set_file_time((HANDLE
)_get_osfhandle(fd
), created
, lastMod
, lastAcc
);
1468 bool MUtils::OS::set_file_time(const QString
&path
, const QDateTime
&created
, const QDateTime
&lastMod
, const QDateTime
&lastAcc
)
1470 const HANDLE hFile
= CreateFileW(MUTILS_WCHR(path
), FILE_WRITE_ATTRIBUTES
, FILE_SHARE_READ
, NULL
, OPEN_EXISTING
, 0, 0);
1472 if ((hFile
!= NULL
) && (hFile
!= INVALID_HANDLE_VALUE
))
1474 okay
= set_file_time(hFile
, created
, lastMod
, lastAcc
);
1480 ///////////////////////////////////////////////////////////////////////////////
1482 ///////////////////////////////////////////////////////////////////////////////
1484 bool MUtils::OS::check_key_state_esc(void)
1486 return (GetAsyncKeyState(VK_ESCAPE
) & 0x0001) != 0;
1489 ///////////////////////////////////////////////////////////////////////////////
1490 // SHELL CHANGE NOTIFICATION
1491 ///////////////////////////////////////////////////////////////////////////////
1493 void MUtils::OS::shell_change_notification(void)
1495 SHChangeNotify(SHCNE_ASSOCCHANGED
, SHCNF_IDLIST
, NULL
, NULL
);
1498 ///////////////////////////////////////////////////////////////////////////////
1499 // WOW64 REDIRECTION
1500 ///////////////////////////////////////////////////////////////////////////////
1502 typedef BOOL (_stdcall
*Wow64DisableWow64FsRedirectionFun
)(void *OldValue
);
1503 typedef BOOL (_stdcall
*Wow64RevertWow64FsRedirectionFun
)(void *OldValue
);
1505 bool MUtils::OS::wow64fsredir_disable(void *oldValue
)
1507 const Wow64DisableWow64FsRedirectionFun wow64redir_disable
= MUtils::Win32Utils::resolve
<Wow64DisableWow64FsRedirectionFun
>(QLatin1String("kernel32"), QLatin1String("Wow64DisableWow64FsRedirection"));
1508 if(wow64redir_disable
)
1510 if (wow64redir_disable(oldValue
))
1518 bool MUtils::OS::wow64fsredir_revert(void *oldValue
)
1520 const Wow64RevertWow64FsRedirectionFun wow64redir_disable
= MUtils::Win32Utils::resolve
<Wow64RevertWow64FsRedirectionFun
>(QLatin1String("kernel32"), QLatin1String("Wow64RevertWow64FsRedirection"));
1521 if (wow64redir_disable
)
1523 if (wow64redir_disable(oldValue
))
1531 ///////////////////////////////////////////////////////////////////////////////
1533 ///////////////////////////////////////////////////////////////////////////////
1535 #if (!(MUTILS_DEBUG))
1536 static __forceinline
bool is_debugger_present(void)
1540 CloseHandle((HANDLE
)((DWORD_PTR
)-3));
1547 BOOL bHaveDebugger
= FALSE
;
1548 if(CheckRemoteDebuggerPresent(GetCurrentProcess(), &bHaveDebugger
))
1550 if(bHaveDebugger
) return true;
1553 return IsDebuggerPresent();
1555 static __forceinline
bool check_debugger_helper(void)
1557 if(is_debugger_present())
1559 MUtils::OS::fatal_exit(L
"Not a debug build. Please unload debugger and try again!");
1565 #define check_debugger_helper() (false)
1568 void MUtils::OS::check_debugger(void)
1570 check_debugger_helper();
1573 static volatile bool g_debug_check
= check_debugger_helper();
1575 ///////////////////////////////////////////////////////////////////////////////
1577 ///////////////////////////////////////////////////////////////////////////////
1579 static MUtils::Internal::CriticalSection g_fatal_exit_lock
;
1580 static volatile bool g_fatal_exit_flag
= true;
1582 static DWORD WINAPI
fatal_exit_helper(LPVOID lpParameter
)
1584 MUtils::OS::system_message_err(L
"GURU MEDITATION", (LPWSTR
) lpParameter
);
1588 void MUtils::OS::fatal_exit(const wchar_t* const errorMessage
)
1590 g_fatal_exit_lock
.enter();
1592 if(!g_fatal_exit_flag
)
1594 return; /*prevent recursive invocation*/
1597 g_fatal_exit_flag
= false;
1599 if(g_main_thread_id
!= GetCurrentThreadId())
1601 if(HANDLE hThreadMain
= OpenThread(THREAD_SUSPEND_RESUME
, FALSE
, g_main_thread_id
))
1603 SuspendThread(hThreadMain
); /*stop main thread*/
1607 if(HANDLE hThread
= CreateThread(NULL
, 0, fatal_exit_helper
, (LPVOID
) errorMessage
, 0, NULL
))
1609 WaitForSingleObject(hThread
, INFINITE
);
1614 TerminateProcess(GetCurrentProcess(), 666);
1618 ///////////////////////////////////////////////////////////////////////////////