1 ///////////////////////////////////////////////////////////////////////////////
2 // MuldeR's Utilities for Qt
3 // Copyright (C) 2004-2015 LoRd_MuldeR <MuldeR2@GMX.de>
5 // This library is free software; you can redistribute it and/or
6 // modify it under the terms of the GNU Lesser General Public
7 // License as published by the Free Software Foundation; either
8 // version 2.1 of the License, or (at your option) any later version.
10 // This library is distributed in the hope that it will be useful,
11 // but WITHOUT ANY WARRANTY; without even the implied warranty of
12 // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
13 // Lesser General Public License for more details.
15 // You should have received a copy of the GNU Lesser General Public
16 // License along with this library; if not, write to the Free Software
17 // Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
19 // http://www.gnu.org/licenses/lgpl-2.1.txt
20 //////////////////////////////////////////////////////////////////////////////////
23 #define WIN32_LEAN_AND_MEAN 1
33 #include <MUtils/Global.h>
34 #include <MUtils/OSSupport.h>
35 #include <MUtils/GUI.h>
36 #include "CriticalSection_Win32.h"
40 #include <QReadWriteLock>
47 static const DWORD g_main_thread_id
= GetCurrentThreadId();
49 ///////////////////////////////////////////////////////////////////////////////
51 ///////////////////////////////////////////////////////////////////////////////
53 static const UINT g_msgBoxFlags
= MB_TOPMOST
| MB_TASKMODAL
| MB_SETFOREGROUND
;
55 void MUtils::OS::system_message_nfo(const wchar_t *const title
, const wchar_t *const text
)
57 MessageBoxW(NULL
, text
, title
, g_msgBoxFlags
| MB_ICONINFORMATION
);
60 void MUtils::OS::system_message_wrn(const wchar_t *const title
, const wchar_t *const text
)
62 MessageBoxW(NULL
, text
, title
, g_msgBoxFlags
| MB_ICONWARNING
);
65 void MUtils::OS::system_message_err(const wchar_t *const title
, const wchar_t *const text
)
67 MessageBoxW(NULL
, text
, title
, g_msgBoxFlags
| MB_ICONERROR
);
70 ///////////////////////////////////////////////////////////////////////////////
71 // FETCH CLI ARGUMENTS
72 ///////////////////////////////////////////////////////////////////////////////
74 static QReadWriteLock g_arguments_lock
;
75 static QScopedPointer
<MUtils::OS::ArgumentMap
> g_arguments_list
;
77 const MUtils::OS::ArgumentMap
&MUtils::OS::arguments(void)
79 QReadLocker
readLock(&g_arguments_lock
);
81 //Already initialized?
82 if(!g_arguments_list
.isNull())
84 return (*(g_arguments_list
.data()));
88 QWriteLocker
writeLock(&g_arguments_lock
);
90 //Still not initialized?
91 if(!g_arguments_list
.isNull())
93 return (*(g_arguments_list
.data()));
96 g_arguments_list
.reset(new ArgumentMap());
98 LPWSTR
*szArglist
= CommandLineToArgvW(GetCommandLineW(), &nArgs
);
100 if(NULL
!= szArglist
)
102 const QChar separator
= QLatin1Char('=');
103 const QString argPrefix
= QLatin1String("--");
104 for(int i
= 0; i
< nArgs
; i
++)
106 const QString argStr
= MUTILS_QSTR(szArglist
[i
]).trimmed();
107 if(argStr
.startsWith(argPrefix
))
109 const QString argData
= argStr
.mid(2).trimmed();
110 if(argData
.length() > 0)
112 const int separatorIndex
= argData
.indexOf(separator
);
113 if(separatorIndex
> 0)
115 const QString argKey
= argData
.left(separatorIndex
).trimmed();
116 const QString argVal
= argData
.mid(separatorIndex
+ 1).trimmed();
117 g_arguments_list
->insertMulti(argKey
.toLower(), argVal
);
121 g_arguments_list
->insertMulti(argData
.toLower(), QString());
126 LocalFree(szArglist
);
130 qWarning("CommandLineToArgvW() has failed !!!");
133 return (*(g_arguments_list
.data()));
136 ///////////////////////////////////////////////////////////////////////////////
138 ///////////////////////////////////////////////////////////////////////////////
140 typedef struct _progress_callback_data_t
142 MUtils::OS::progress_callback_t callback_function
;
145 progress_callback_data_t
;
147 static DWORD __stdcall
copy_file_progress(LARGE_INTEGER TotalFileSize
, LARGE_INTEGER TotalBytesTransferred
, LARGE_INTEGER StreamSize
, LARGE_INTEGER StreamBytesTransferred
, DWORD dwStreamNumber
, DWORD dwCallbackReason
, HANDLE hSourceFile
, HANDLE hDestinationFile
, LPVOID lpData
)
149 if(const progress_callback_data_t
*data
= (progress_callback_data_t
*) lpData
)
151 const double progress
= qBound(0.0, double(TotalBytesTransferred
.QuadPart
) / double(TotalFileSize
.QuadPart
), 1.0);
152 return data
->callback_function(progress
, data
->user_data
) ? PROGRESS_CONTINUE
: PROGRESS_CANCEL
;
154 return PROGRESS_CONTINUE
;
157 MUTILS_API
bool MUtils::OS::copy_file(const QString
&sourcePath
, const QString
&outputPath
, const bool &overwrite
, const progress_callback_t callback
, void *const userData
)
159 progress_callback_data_t callback_data
= { callback
, userData
};
161 const BOOL result
= CopyFileExW(MUTILS_WCHR(QDir::toNativeSeparators(sourcePath
)), MUTILS_WCHR(QDir::toNativeSeparators(outputPath
)), ((callback_data
.callback_function
) ? copy_file_progress
: NULL
), ((callback_data
.callback_function
) ? &callback_data
: NULL
), &cancel
, (overwrite
? 0 : COPY_FILE_FAIL_IF_EXISTS
));
165 const DWORD errorCode
= GetLastError();
166 if(errorCode
!= ERROR_REQUEST_ABORTED
)
168 qWarning("CopyFile() failed with error code 0x%08X!", errorCode
);
172 qWarning("CopyFile() operation was abroted by user!");
176 return (result
!= FALSE
);
179 ///////////////////////////////////////////////////////////////////////////////
181 ///////////////////////////////////////////////////////////////////////////////
183 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
)
185 if(!GetFileVersionInfo(MUTILS_WCHR(fileName
), 0, size
, buffer
))
187 qWarning("GetFileVersionInfo() has failed, file version cannot be determined!");
191 VS_FIXEDFILEINFO
*verInfo
;
193 if(!VerQueryValue(buffer
, L
"\\", (LPVOID
*)(&verInfo
), &verInfoLen
))
195 qWarning("VerQueryValue() has failed, file version cannot be determined!");
199 if(major
) *major
= quint16((verInfo
->dwFileVersionMS
>> 16) & 0x0000FFFF);
200 if(minor
) *minor
= quint16((verInfo
->dwFileVersionMS
) & 0x0000FFFF);
201 if(patch
) *patch
= quint16((verInfo
->dwFileVersionLS
>> 16) & 0x0000FFFF);
202 if(build
) *build
= quint16((verInfo
->dwFileVersionLS
) & 0x0000FFFF);
207 bool MUtils::OS::get_file_version(const QString fileName
, quint16
*const major
, quint16
*const minor
, quint16
*const patch
, quint16
*const build
)
209 if(major
) *major
= 0U; if(minor
) *minor
= 0U;
210 if(patch
) *patch
= 0U; if(build
) *build
= 0U;
212 const DWORD size
= GetFileVersionInfoSize(MUTILS_WCHR(fileName
), NULL
);
215 qWarning("GetFileVersionInfoSize() has failed, file version cannot be determined!");
219 PVOID buffer
= _malloca(size
);
222 qWarning("Memory allocation has failed!");
226 const bool success
= get_file_version_helper(fileName
, buffer
, size
, major
, minor
, patch
, build
);
232 ///////////////////////////////////////////////////////////////////////////////
233 // OS VERSION DETECTION
234 ///////////////////////////////////////////////////////////////////////////////
236 static bool g_os_version_initialized
= false;
237 static MUtils::OS::Version::os_version_t g_os_version_info
= MUtils::OS::Version::UNKNOWN_OPSYS
;
238 static QReadWriteLock g_os_version_lock
;
240 //Maps marketing names to the actual Windows NT versions
243 MUtils::OS::Version::os_version_t version
;
244 const char friendlyName
[64];
248 { MUtils::OS::Version::WINDOWS_WIN2K
, "Windows 2000" }, //2000
249 { MUtils::OS::Version::WINDOWS_WINXP
, "Windows XP or Windows XP Media Center Edition" }, //XP
250 { MUtils::OS::Version::WINDOWS_XPX64
, "Windows Server 2003 or Windows XP x64" }, //XP_x64
251 { MUtils::OS::Version::WINDOWS_VISTA
, "Windows Vista or Windows Server 2008" }, //Vista
252 { MUtils::OS::Version::WINDOWS_WIN70
, "Windows 7 or Windows Server 2008 R2" }, //7
253 { MUtils::OS::Version::WINDOWS_WIN80
, "Windows 8 or Windows Server 2012" }, //8
254 { MUtils::OS::Version::WINDOWS_WIN81
, "Windows 8.1 or Windows Server 2012 R2" }, //8.1
255 { MUtils::OS::Version::WINDOWS_WN100
, "Windows 10 or Windows Server 2014 (Preview)" }, //10
256 { MUtils::OS::Version::UNKNOWN_OPSYS
, "N/A" }
259 //OS version data dtructures
266 //Comparision operators for os_version_t
267 bool os_version_t::operator== (const os_version_t
&rhs
) const { return (type
== rhs
.type
) && (versionMajor
== rhs
.versionMajor
) && ((versionMinor
== rhs
.versionMinor
)); }
268 bool os_version_t::operator!= (const os_version_t
&rhs
) const { return (type
!= rhs
.type
) || (versionMajor
!= rhs
.versionMajor
) || ((versionMinor
!= rhs
.versionMinor
)); }
269 bool os_version_t::operator> (const os_version_t
&rhs
) const { return (type
== rhs
.type
) && ((versionMajor
> rhs
.versionMajor
) || ((versionMajor
== rhs
.versionMajor
) && (versionMinor
> rhs
.versionMinor
))); }
270 bool os_version_t::operator>= (const os_version_t
&rhs
) const { return (type
== rhs
.type
) && ((versionMajor
> rhs
.versionMajor
) || ((versionMajor
== rhs
.versionMajor
) && (versionMinor
>= rhs
.versionMinor
))); }
271 bool os_version_t::operator< (const os_version_t
&rhs
) const { return (type
== rhs
.type
) && ((versionMajor
< rhs
.versionMajor
) || ((versionMajor
== rhs
.versionMajor
) && (versionMinor
< rhs
.versionMinor
))); }
272 bool os_version_t::operator<= (const os_version_t
&rhs
) const { return (type
== rhs
.type
) && ((versionMajor
< rhs
.versionMajor
) || ((versionMajor
== rhs
.versionMajor
) && (versionMinor
<= rhs
.versionMinor
))); }
274 //Known Windows NT versions
275 const os_version_t WINDOWS_WIN2K
= { OS_WINDOWS
, 5, 0 }; // 2000
276 const os_version_t WINDOWS_WINXP
= { OS_WINDOWS
, 5, 1 }; // XP
277 const os_version_t WINDOWS_XPX64
= { OS_WINDOWS
, 5, 2 }; // XP_x64
278 const os_version_t WINDOWS_VISTA
= { OS_WINDOWS
, 6, 0 }; // Vista
279 const os_version_t WINDOWS_WIN70
= { OS_WINDOWS
, 6, 1 }; // 7
280 const os_version_t WINDOWS_WIN80
= { OS_WINDOWS
, 6, 2 }; // 8
281 const os_version_t WINDOWS_WIN81
= { OS_WINDOWS
, 6, 3 }; // 8.1
282 const os_version_t WINDOWS_WN100
= { OS_WINDOWS
, 10, 0 }; // 10
285 const os_version_t UNKNOWN_OPSYS
= { OS_UNKNOWN
, 0, 0 }; // N/A
290 static bool verify_os_version(const DWORD major
, const DWORD minor
)
292 OSVERSIONINFOEXW osvi
;
293 DWORDLONG dwlConditionMask
= 0;
295 //Initialize the OSVERSIONINFOEX structure
296 memset(&osvi
, 0, sizeof(OSVERSIONINFOEXW
));
297 osvi
.dwOSVersionInfoSize
= sizeof(OSVERSIONINFOEXW
);
298 osvi
.dwMajorVersion
= major
;
299 osvi
.dwMinorVersion
= minor
;
300 osvi
.dwPlatformId
= VER_PLATFORM_WIN32_NT
;
302 //Initialize the condition mask
303 VER_SET_CONDITION(dwlConditionMask
, VER_MAJORVERSION
, VER_GREATER_EQUAL
);
304 VER_SET_CONDITION(dwlConditionMask
, VER_MINORVERSION
, VER_GREATER_EQUAL
);
305 VER_SET_CONDITION(dwlConditionMask
, VER_PLATFORMID
, VER_EQUAL
);
308 const BOOL ret
= VerifyVersionInfoW(&osvi
, VER_MAJORVERSION
| VER_MINORVERSION
| VER_PLATFORMID
, dwlConditionMask
);
313 if(GetLastError() != ERROR_OLD_WIN_VERSION
)
315 qWarning("VerifyVersionInfo() system call has failed!");
319 return (ret
!= FALSE
);
322 static bool get_real_os_version(unsigned int *major
, unsigned int *minor
, bool *pbOverride
)
327 //Initialize local variables
328 OSVERSIONINFOEXW osvi
;
329 memset(&osvi
, 0, sizeof(OSVERSIONINFOEXW
));
330 osvi
.dwOSVersionInfoSize
= sizeof(OSVERSIONINFOEXW
);
332 //Try GetVersionEx() first
333 if(GetVersionExW((LPOSVERSIONINFOW
)&osvi
) == FALSE
)
335 qWarning("GetVersionEx() has failed, cannot detect Windows version!");
339 //Make sure we are running on NT
340 if(osvi
.dwPlatformId
== VER_PLATFORM_WIN32_NT
)
342 *major
= osvi
.dwMajorVersion
;
343 *minor
= osvi
.dwMinorVersion
;
347 qWarning("Not running on Windows NT, unsupported operating system!");
351 //Determine the real *major* version first
354 const DWORD nextMajor
= (*major
) + 1;
355 if(verify_os_version(nextMajor
, 0))
365 //Now also determine the real *minor* version
368 const DWORD nextMinor
= (*minor
) + 1;
369 if(verify_os_version((*major
), nextMinor
))
378 //Workaround for the mess that is sometimes referred to as "Windows 10"
379 if(((*major
) > 6) || (((*major
) == 6) && ((*minor
) >= 2)))
381 quint16 kernel32_major
, kernel32_minor
;
382 if(MUtils::OS::get_file_version(QLatin1String("kernel32"), &kernel32_major
, &kernel32_minor
))
384 if((kernel32_major
> (*major
)) || ((kernel32_major
== (*major
)) && (kernel32_minor
> (*minor
))))
386 *major
= kernel32_major
;
387 *minor
= kernel32_minor
;
396 const MUtils::OS::Version::os_version_t
&MUtils::OS::os_version(void)
398 QReadLocker
readLock(&g_os_version_lock
);
400 //Already initialized?
401 if(g_os_version_initialized
)
403 return g_os_version_info
;
407 QWriteLocker
writeLock(&g_os_version_lock
);
410 if(g_os_version_initialized
)
412 return g_os_version_info
;
416 unsigned int major
, minor
; bool overrideFlg
;
417 if(get_real_os_version(&major
, &minor
, &overrideFlg
))
419 g_os_version_info
.type
= Version::OS_WINDOWS
;
420 g_os_version_info
.versionMajor
= major
;
421 g_os_version_info
.versionMinor
= minor
;
422 g_os_version_info
.overrideFlag
= overrideFlg
;
426 qWarning("Failed to determin the operating system version!");
430 g_os_version_initialized
= true;
431 return g_os_version_info
;
434 const char *MUtils::OS::os_friendly_name(const MUtils::OS::Version::os_version_t
&os_version
)
436 for(size_t i
= 0; g_os_version_lut
[i
].version
!= MUtils::OS::Version::UNKNOWN_OPSYS
; i
++)
438 if(os_version
== g_os_version_lut
[i
].version
)
440 return g_os_version_lut
[i
].friendlyName
;
447 ///////////////////////////////////////////////////////////////////////////////
449 ///////////////////////////////////////////////////////////////////////////////
451 static bool g_wine_deteced
= false;
452 static bool g_wine_initialized
= false;
453 static QReadWriteLock g_wine_lock
;
455 static const bool detect_wine(void)
457 bool is_wine
= false;
459 QLibrary
ntdll("ntdll.dll");
462 if(ntdll
.resolve("wine_nt_to_unix_file_name") != NULL
) is_wine
= true;
463 if(ntdll
.resolve("wine_get_version") != NULL
) is_wine
= true;
470 const bool &MUtils::OS::running_on_wine(void)
472 QReadLocker
readLock(&g_wine_lock
);
474 //Already initialized?
475 if(g_wine_initialized
)
477 return g_wine_deteced
;
481 QWriteLocker
writeLock(&g_wine_lock
);
484 if(g_wine_initialized
)
486 return g_wine_deteced
;
490 g_wine_deteced
= detect_wine();
491 g_wine_initialized
= true;
493 return g_wine_deteced
;
496 ///////////////////////////////////////////////////////////////////////////////
498 ///////////////////////////////////////////////////////////////////////////////
500 typedef QMap
<size_t, QString
> KFMap
;
501 typedef HRESULT (WINAPI
*SHGetKnownFolderPath_t
)(const GUID
&rfid
, DWORD dwFlags
, HANDLE hToken
, PWSTR
*ppszPath
);
502 typedef HRESULT (WINAPI
*SHGetFolderPath_t
)(HWND hwndOwner
, int nFolder
, HANDLE hToken
, DWORD dwFlags
, LPWSTR pszPath
);
504 static QScopedPointer
<KFMap
> g_known_folders_map
;
505 static SHGetKnownFolderPath_t g_known_folders_fpGetKnownFolderPath
;
506 static SHGetFolderPath_t g_known_folders_fpGetFolderPath
;
507 static QReadWriteLock g_known_folders_lock
;
509 const QString
&MUtils::OS::known_folder(known_folder_t folder_id
)
511 typedef enum { KF_FLAG_CREATE
= 0x00008000 } kf_flags_t
;
520 { 0x001c, {0xF1B32785,0x6FBA,0x4FCF,{0x9D,0x55,0x7B,0x8E,0x7F,0x15,0x70,0x91}} }, //CSIDL_LOCAL_APPDATA
521 { 0x0026, {0x905e63b6,0xc1bf,0x494e,{0xb2,0x9c,0x65,0xb7,0x32,0xd3,0xd2,0x1a}} }, //CSIDL_PROGRAM_FILES
522 { 0x0024, {0xF38BF404,0x1D43,0x42F2,{0x93,0x05,0x67,0xDE,0x0B,0x28,0xFC,0x23}} }, //CSIDL_WINDOWS_FOLDER
523 { 0x0025, {0x1AC14E77,0x02E7,0x4E5D,{0xB7,0x44,0x2E,0xB1,0xAE,0x51,0x98,0xB7}} }, //CSIDL_SYSTEM_FOLDER
526 size_t folderId
= size_t(-1);
530 case FOLDER_LOCALAPPDATA
: folderId
= 0; break;
531 case FOLDER_PROGRAMFILES
: folderId
= 1; break;
532 case FOLDER_SYSTROOT_DIR
: folderId
= 2; break;
533 case FOLDER_SYSTEMFOLDER
: folderId
= 3; break;
536 if(folderId
== size_t(-1))
538 qWarning("Invalid 'known' folder was requested!");
539 return *reinterpret_cast<QString
*>(NULL
);
542 QReadLocker
readLock(&g_known_folders_lock
);
545 if(!g_known_folders_map
.isNull())
547 if(g_known_folders_map
->contains(folderId
))
549 return g_known_folders_map
->operator[](folderId
);
553 //Obtain write lock to initialize
555 QWriteLocker
writeLock(&g_known_folders_lock
);
557 //Still not in cache?
558 if(!g_known_folders_map
.isNull())
560 if(g_known_folders_map
->contains(folderId
))
562 return g_known_folders_map
->operator[](folderId
);
566 //Initialize on first call
567 if(g_known_folders_map
.isNull())
569 QLibrary
shell32("shell32.dll");
572 g_known_folders_fpGetFolderPath
= (SHGetFolderPath_t
) shell32
.resolve("SHGetFolderPathW");
573 g_known_folders_fpGetKnownFolderPath
= (SHGetKnownFolderPath_t
) shell32
.resolve("SHGetKnownFolderPath");
575 g_known_folders_map
.reset(new QMap
<size_t, QString
>());
580 //Now try to get the folder path!
581 if(g_known_folders_fpGetKnownFolderPath
)
584 if(g_known_folders_fpGetKnownFolderPath(s_folders
[folderId
].guid
, KF_FLAG_CREATE
, NULL
, &path
) == S_OK
)
586 //MessageBoxW(0, path, L"SHGetKnownFolderPath", MB_TOPMOST);
587 QDir folderTemp
= QDir(QDir::fromNativeSeparators(MUTILS_QSTR(path
)));
588 if(folderTemp
.exists())
590 folderPath
= folderTemp
.canonicalPath();
595 else if(g_known_folders_fpGetFolderPath
)
597 QScopedArrayPointer
<WCHAR
> path(new WCHAR
[4096]);
598 if(g_known_folders_fpGetFolderPath(NULL
, s_folders
[folderId
].csidl
| CSIDL_FLAG_CREATE
, NULL
, NULL
, path
.data()) == S_OK
)
600 //MessageBoxW(0, path, L"SHGetFolderPathW", MB_TOPMOST);
601 QDir folderTemp
= QDir(QDir::fromNativeSeparators(MUTILS_QSTR(path
.data())));
602 if(folderTemp
.exists())
604 folderPath
= folderTemp
.canonicalPath();
610 g_known_folders_map
->insert(folderId
, folderPath
);
611 return g_known_folders_map
->operator[](folderId
);
614 ///////////////////////////////////////////////////////////////////////////////
615 // CURRENT DATA & TIME
616 ///////////////////////////////////////////////////////////////////////////////
618 QDate
MUtils::OS::current_date(void)
620 const DWORD MAX_PROC
= 1024;
621 QScopedArrayPointer
<DWORD
> processes(new DWORD
[MAX_PROC
]);
622 DWORD bytesReturned
= 0;
624 if(!EnumProcesses(processes
.data(), sizeof(DWORD
) * MAX_PROC
, &bytesReturned
))
626 return QDate::currentDate();
629 const DWORD procCount
= bytesReturned
/ sizeof(DWORD
);
630 ULARGE_INTEGER lastStartTime
;
631 memset(&lastStartTime
, 0, sizeof(ULARGE_INTEGER
));
633 for(DWORD i
= 0; i
< procCount
; i
++)
635 if(HANDLE hProc
= OpenProcess(PROCESS_QUERY_INFORMATION
, FALSE
, processes
[i
]))
637 FILETIME processTime
[4];
638 if(GetProcessTimes(hProc
, &processTime
[0], &processTime
[1], &processTime
[2], &processTime
[3]))
640 ULARGE_INTEGER timeCreation
;
641 timeCreation
.LowPart
= processTime
[0].dwLowDateTime
;
642 timeCreation
.HighPart
= processTime
[0].dwHighDateTime
;
643 if(timeCreation
.QuadPart
> lastStartTime
.QuadPart
)
645 lastStartTime
.QuadPart
= timeCreation
.QuadPart
;
652 FILETIME lastStartTime_fileTime
;
653 lastStartTime_fileTime
.dwHighDateTime
= lastStartTime
.HighPart
;
654 lastStartTime_fileTime
.dwLowDateTime
= lastStartTime
.LowPart
;
656 FILETIME lastStartTime_localTime
;
657 if(!FileTimeToLocalFileTime(&lastStartTime_fileTime
, &lastStartTime_localTime
))
659 memcpy(&lastStartTime_localTime
, &lastStartTime_fileTime
, sizeof(FILETIME
));
662 SYSTEMTIME lastStartTime_system
;
663 if(!FileTimeToSystemTime(&lastStartTime_localTime
, &lastStartTime_system
))
665 memset(&lastStartTime_system
, 0, sizeof(SYSTEMTIME
));
666 lastStartTime_system
.wYear
= 1970; lastStartTime_system
.wMonth
= lastStartTime_system
.wDay
= 1;
669 const QDate currentDate
= QDate::currentDate();
670 const QDate processDate
= QDate(lastStartTime_system
.wYear
, lastStartTime_system
.wMonth
, lastStartTime_system
.wDay
);
671 return (currentDate
>= processDate
) ? currentDate
: processDate
;
674 quint64
MUtils::OS::current_file_time(void)
677 GetSystemTimeAsFileTime(&fileTime
);
680 temp
.HighPart
= fileTime
.dwHighDateTime
;
681 temp
.LowPart
= fileTime
.dwLowDateTime
;
683 return temp
.QuadPart
;
686 ///////////////////////////////////////////////////////////////////////////////
688 ///////////////////////////////////////////////////////////////////////////////
690 static bool user_is_admin_helper(void)
692 HANDLE hToken
= NULL
;
693 if(!OpenProcessToken(GetCurrentProcess(), TOKEN_QUERY
, &hToken
))
699 if(!GetTokenInformation(hToken
, TokenGroups
, NULL
, 0, &dwSize
))
701 if(GetLastError() != ERROR_INSUFFICIENT_BUFFER
)
708 PTOKEN_GROUPS lpGroups
= (PTOKEN_GROUPS
) malloc(dwSize
);
715 if(!GetTokenInformation(hToken
, TokenGroups
, lpGroups
, dwSize
, &dwSize
))
722 PSID lpSid
= NULL
; SID_IDENTIFIER_AUTHORITY Authority
= {SECURITY_NT_AUTHORITY
};
723 if(!AllocateAndInitializeSid(&Authority
, 2, SECURITY_BUILTIN_DOMAIN_RID
, DOMAIN_ALIAS_RID_ADMINS
, 0, 0, 0, 0, 0, 0, &lpSid
))
730 bool bResult
= false;
731 for(DWORD i
= 0; i
< lpGroups
->GroupCount
; i
++)
733 if(EqualSid(lpSid
, lpGroups
->Groups
[i
].Sid
))
746 bool MUtils::OS::is_elevated(bool *bIsUacEnabled
)
750 *bIsUacEnabled
= false;
753 bool bIsProcessElevated
= false;
754 HANDLE hToken
= NULL
;
756 if(OpenProcessToken(GetCurrentProcess(), TOKEN_QUERY
, &hToken
))
758 TOKEN_ELEVATION_TYPE tokenElevationType
;
760 if(GetTokenInformation(hToken
, TokenElevationType
, &tokenElevationType
, sizeof(TOKEN_ELEVATION_TYPE
), &returnLength
))
762 if(returnLength
== sizeof(TOKEN_ELEVATION_TYPE
))
764 switch(tokenElevationType
)
766 case TokenElevationTypeDefault
:
767 qDebug("Process token elevation type: Default -> UAC is disabled.\n");
769 case TokenElevationTypeFull
:
770 qWarning("Process token elevation type: Full -> potential security risk!\n");
771 bIsProcessElevated
= true;
772 if(bIsUacEnabled
) *bIsUacEnabled
= true;
774 case TokenElevationTypeLimited
:
775 qDebug("Process token elevation type: Limited -> not elevated.\n");
776 if(bIsUacEnabled
) *bIsUacEnabled
= true;
779 qWarning("Unknown tokenElevationType value: %d", tokenElevationType
);
785 qWarning("GetTokenInformation() return an unexpected size!");
792 qWarning("Failed to open process token!");
795 return bIsProcessElevated
;
798 bool MUtils::OS::user_is_admin(void)
800 bool isAdmin
= false;
802 //Check for process elevation and UAC support first!
803 if(MUtils::OS::is_elevated(&isAdmin
))
805 qWarning("Process is elevated -> user is admin!");
809 //If not elevated and UAC is not available -> user must be in admin group!
812 qDebug("UAC is disabled/unavailable -> checking for Administrators group");
813 isAdmin
= user_is_admin_helper();
819 ///////////////////////////////////////////////////////////////////////////////
821 ///////////////////////////////////////////////////////////////////////////////
823 int MUtils::OS::network_status(void)
826 const BOOL ret
= IsNetworkAlive(&dwFlags
);
827 if(GetLastError() == 0)
829 return (ret
!= FALSE
) ? NETWORK_TYPE_YES
: NETWORK_TYPE_NON
;
831 return NETWORK_TYPE_ERR
;
834 ///////////////////////////////////////////////////////////////////////////////
836 ///////////////////////////////////////////////////////////////////////////////
838 bool MUtils::OS::handle_os_message(const void *const message
, long *result
)
840 const MSG
*const msg
= reinterpret_cast<const MSG
*>(message
);
844 case WM_QUERYENDSESSION
:
845 qWarning("WM_QUERYENDSESSION message received!");
846 *result
= MUtils::GUI::broadcast(MUtils::GUI::USER_EVENT_QUERYENDSESSION
, false) ? TRUE
: FALSE
;
849 qWarning("WM_ENDSESSION message received!");
850 if(msg
->wParam
== TRUE
)
852 MUtils::GUI::broadcast(MUtils::GUI::USER_EVENT_ENDSESSION
, false);
853 MUtils::GUI::force_quit();
859 /*ignore this message and let Qt handle it*/
864 ///////////////////////////////////////////////////////////////////////////////
866 ///////////////////////////////////////////////////////////////////////////////
868 void MUtils::OS::sleep_ms(const size_t &duration
)
870 Sleep((DWORD
) duration
);
873 ///////////////////////////////////////////////////////////////////////////////
875 ///////////////////////////////////////////////////////////////////////////////
877 bool MUtils::OS::is_executable_file(const QString
&path
)
879 bool bIsExecutable
= false;
881 if(GetBinaryType(MUTILS_WCHR(QDir::toNativeSeparators(path
)), &binaryType
))
883 bIsExecutable
= (binaryType
== SCS_32BIT_BINARY
|| binaryType
== SCS_64BIT_BINARY
);
885 return bIsExecutable
;
888 ///////////////////////////////////////////////////////////////////////////////
889 // HIBERNATION / SHUTDOWN
890 ///////////////////////////////////////////////////////////////////////////////
892 bool MUtils::OS::is_hibernation_supported(void)
894 bool hibernationSupported
= false;
896 SYSTEM_POWER_CAPABILITIES pwrCaps
;
897 SecureZeroMemory(&pwrCaps
, sizeof(SYSTEM_POWER_CAPABILITIES
));
899 if(GetPwrCapabilities(&pwrCaps
))
901 hibernationSupported
= pwrCaps
.SystemS4
&& pwrCaps
.HiberFilePresent
;
904 return hibernationSupported
;
907 bool MUtils::OS::shutdown_computer(const QString
&message
, const unsigned long timeout
, const bool forceShutdown
, const bool hibernate
)
909 HANDLE hToken
= NULL
;
911 if(OpenProcessToken(GetCurrentProcess(), TOKEN_ADJUST_PRIVILEGES
| TOKEN_QUERY
, &hToken
))
913 TOKEN_PRIVILEGES privileges
;
914 memset(&privileges
, 0, sizeof(TOKEN_PRIVILEGES
));
915 privileges
.PrivilegeCount
= 1;
916 privileges
.Privileges
[0].Attributes
= SE_PRIVILEGE_ENABLED
;
918 if(LookupPrivilegeValue(NULL
, SE_SHUTDOWN_NAME
, &privileges
.Privileges
[0].Luid
))
920 if(AdjustTokenPrivileges(hToken
, FALSE
, &privileges
, NULL
, NULL
, NULL
))
924 if(SetSuspendState(TRUE
, TRUE
, TRUE
))
929 const DWORD reason
= SHTDN_REASON_MAJOR_APPLICATION
| SHTDN_REASON_FLAG_PLANNED
;
930 return InitiateSystemShutdownEx(NULL
, const_cast<wchar_t*>(MUTILS_WCHR(message
)), timeout
, forceShutdown
? TRUE
: FALSE
, FALSE
, reason
);
938 ///////////////////////////////////////////////////////////////////////////////
940 ///////////////////////////////////////////////////////////////////////////////
942 bool MUtils::OS::free_diskspace(const QString
&path
, quint64
&freeSpace
)
944 ULARGE_INTEGER freeBytesAvailable
, totalNumberOfBytes
, totalNumberOfFreeBytes
;
945 if(GetDiskFreeSpaceExW(reinterpret_cast<const wchar_t*>(QDir::toNativeSeparators(path
).utf16()), &freeBytesAvailable
, &totalNumberOfBytes
, &totalNumberOfFreeBytes
))
947 freeSpace
= freeBytesAvailable
.QuadPart
;
955 ///////////////////////////////////////////////////////////////////////////////
957 ///////////////////////////////////////////////////////////////////////////////
959 bool MUtils::OS::shell_open(const QWidget
*parent
, const QString
&url
, const QString
¶meters
, const QString
&directory
, const bool explore
)
961 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;
964 bool MUtils::OS::shell_open(const QWidget
*parent
, const QString
&url
, const bool explore
)
966 return shell_open(parent
, url
, QString(), QString(), explore
);
969 ///////////////////////////////////////////////////////////////////////////////
971 ///////////////////////////////////////////////////////////////////////////////
973 bool MUtils::OS::open_media_file(const QString
&mediaFilePath
)
975 const static wchar_t *registryPrefix
[2] = { L
"SOFTWARE\\", L
"SOFTWARE\\Wow6432Node\\" };
976 const static wchar_t *registryKeys
[3] =
978 L
"Microsoft\\Windows\\CurrentVersion\\Uninstall\\{97D341C8-B0D1-4E4A-A49A-C30B52F168E9}",
979 L
"Microsoft\\Windows\\CurrentVersion\\Uninstall\\{DB9E4EAB-2717-499F-8D56-4CC8A644AB60}",
982 const static wchar_t *appNames
[4] = { L
"smplayer_portable.exe", L
"smplayer.exe", L
"MPUI.exe", L
"foobar2000.exe" };
983 const static wchar_t *valueNames
[2] = { L
"InstallLocation", L
"InstallDir" };
985 for(size_t i
= 0; i
< 3; i
++)
987 for(size_t j
= 0; j
< 2; j
++)
990 HKEY registryKeyHandle
= NULL
;
992 const QString currentKey
= MUTILS_QSTR(registryPrefix
[j
]).append(MUTILS_QSTR(registryKeys
[i
]));
993 if(RegOpenKeyExW(HKEY_LOCAL_MACHINE
, MUTILS_WCHR(currentKey
), 0, KEY_READ
, ®istryKeyHandle
) == ERROR_SUCCESS
)
995 for(size_t k
= 0; k
< 2; k
++)
997 wchar_t Buffer
[4096];
998 DWORD BuffSize
= sizeof(wchar_t*) * 4096;
999 DWORD DataType
= REG_NONE
;
1000 if(RegQueryValueExW(registryKeyHandle
, valueNames
[k
], 0, &DataType
, reinterpret_cast<BYTE
*>(Buffer
), &BuffSize
) == ERROR_SUCCESS
)
1002 if((DataType
== REG_SZ
) || (DataType
== REG_EXPAND_SZ
) || (DataType
== REG_LINK
))
1004 mplayerPath
= MUTILS_QSTR(Buffer
);
1009 RegCloseKey(registryKeyHandle
);
1012 if(!mplayerPath
.isEmpty())
1014 QDir
mplayerDir(mplayerPath
);
1015 if(mplayerDir
.exists())
1017 for(size_t k
= 0; k
< 4; k
++)
1019 if(mplayerDir
.exists(MUTILS_QSTR(appNames
[k
])))
1021 qDebug("Player found at:\n%s\n", MUTILS_UTF8(mplayerDir
.absoluteFilePath(MUTILS_QSTR(appNames
[k
]))));
1022 QProcess::startDetached(mplayerDir
.absoluteFilePath(MUTILS_QSTR(appNames
[k
])), QStringList() << QDir::toNativeSeparators(mediaFilePath
));
1033 ///////////////////////////////////////////////////////////////////////////////
1035 ///////////////////////////////////////////////////////////////////////////////
1037 static bool change_process_priority_helper(const HANDLE hProcess
, const int priority
)
1041 switch(qBound(-2, priority
, 2))
1044 ok
= (SetPriorityClass(hProcess
, HIGH_PRIORITY_CLASS
) == TRUE
);
1047 if(!(ok
= (SetPriorityClass(hProcess
, ABOVE_NORMAL_PRIORITY_CLASS
) == TRUE
)))
1049 ok
= (SetPriorityClass(hProcess
, HIGH_PRIORITY_CLASS
) == TRUE
);
1053 ok
= (SetPriorityClass(hProcess
, NORMAL_PRIORITY_CLASS
) == TRUE
);
1056 if(!(ok
= (SetPriorityClass(hProcess
, BELOW_NORMAL_PRIORITY_CLASS
) == TRUE
)))
1058 ok
= (SetPriorityClass(hProcess
, IDLE_PRIORITY_CLASS
) == TRUE
);
1062 ok
= (SetPriorityClass(hProcess
, IDLE_PRIORITY_CLASS
) == TRUE
);
1069 bool MUtils::OS::change_process_priority(const int priority
)
1071 return change_process_priority_helper(GetCurrentProcess(), priority
);
1074 bool MUtils::OS::change_process_priority(const QProcess
*proc
, const int priority
)
1076 if(Q_PID qPid
= proc
->pid())
1078 return change_process_priority_helper(qPid
->hProcess
, priority
);
1086 ///////////////////////////////////////////////////////////////////////////////
1088 ///////////////////////////////////////////////////////////////////////////////
1090 quint32
MUtils::OS::process_id(const QProcess
*const proc
)
1092 PROCESS_INFORMATION
*procInf
= proc
->pid();
1093 return (procInf
) ? procInf
->dwProcessId
: NULL
;
1096 ///////////////////////////////////////////////////////////////////////////////
1097 // PROCESS SUSPEND/RESUME
1098 ///////////////////////////////////////////////////////////////////////////////
1100 bool MUtils::OS::suspend_process(const QProcess
*proc
, const bool suspend
)
1102 if(Q_PID pid
= proc
->pid())
1106 return (SuspendThread(pid
->hThread
) != ((DWORD
) -1));
1110 return (ResumeThread(pid
->hThread
) != ((DWORD
) -1));
1119 ///////////////////////////////////////////////////////////////////////////////
1121 ///////////////////////////////////////////////////////////////////////////////
1123 bool MUtils::OS::setup_timer_resolution(const quint32
&interval
)
1125 return timeBeginPeriod(interval
) == TIMERR_NOERROR
;
1128 bool MUtils::OS::reset_timer_resolution(const quint32
&interval
)
1130 return timeEndPeriod(interval
) == TIMERR_NOERROR
;
1133 ///////////////////////////////////////////////////////////////////////////////
1135 ///////////////////////////////////////////////////////////////////////////////
1137 bool MUtils::OS::check_key_state_esc(void)
1139 return (GetAsyncKeyState(VK_ESCAPE
) & 0x0001) != 0;
1142 ///////////////////////////////////////////////////////////////////////////////
1143 // SHELL CHANGE NOTIFICATION
1144 ///////////////////////////////////////////////////////////////////////////////
1146 void MUtils::OS::shell_change_notification(void)
1148 SHChangeNotify(SHCNE_ASSOCCHANGED
, SHCNF_IDLIST
, NULL
, NULL
);
1151 ///////////////////////////////////////////////////////////////////////////////
1152 // WOW64 REDIRECTION
1153 ///////////////////////////////////////////////////////////////////////////////
1155 typedef BOOL (_stdcall
*Wow64DisableWow64FsRedirectionFun
)(void *OldValue
);
1156 typedef BOOL (_stdcall
*Wow64RevertWow64FsRedirectionFun
)(void *OldValue
);
1158 static QReadWriteLock g_wow64redir_lock
;
1159 static QScopedPointer
<QLibrary
> g_wow64redir_kernel32
;
1160 static Wow64DisableWow64FsRedirectionFun g_wow64redir_disable
= NULL
;
1161 static Wow64RevertWow64FsRedirectionFun g_wow64redir_revert
= NULL
;
1163 static bool wow64fsredir_init()
1165 QWriteLocker
writeLock(&g_wow64redir_lock
);
1166 if(g_wow64redir_disable
&& g_wow64redir_revert
)
1168 return true; /*already initialized*/
1171 if(g_wow64redir_kernel32
.isNull())
1173 g_wow64redir_kernel32
.reset(new QLibrary("kernel32.dll"));
1176 if(!g_wow64redir_kernel32
->isLoaded())
1178 if(!g_wow64redir_kernel32
->load())
1180 return false; /*faild to load kernel32.dll*/
1184 g_wow64redir_disable
= (Wow64DisableWow64FsRedirectionFun
) g_wow64redir_kernel32
->resolve("Wow64DisableWow64FsRedirection");
1185 g_wow64redir_revert
= (Wow64RevertWow64FsRedirectionFun
) g_wow64redir_kernel32
->resolve("Wow64RevertWow64FsRedirection");
1187 return (g_wow64redir_disable
&& g_wow64redir_revert
);
1190 #define WOW64FSREDIR_INIT(RDLOCK) do \
1192 while(!(g_wow64redir_disable && g_wow64redir_revert)) \
1194 (RDLOCK).unlock(); \
1195 if(!wow64fsredir_init()) return false; \
1196 (RDLOCK).relock(); \
1201 bool MUtils::OS::wow64fsredir_disable(void *oldValue
)
1203 QReadLocker
readLock(&g_wow64redir_lock
);
1204 WOW64FSREDIR_INIT(readLock
);
1205 if(g_wow64redir_disable(oldValue
))
1212 bool MUtils::OS::wow64fsredir_revert(void *oldValue
)
1214 QReadLocker
readLock(&g_wow64redir_lock
);
1215 WOW64FSREDIR_INIT(readLock
);
1216 if(g_wow64redir_revert(oldValue
))
1223 ///////////////////////////////////////////////////////////////////////////////
1225 ///////////////////////////////////////////////////////////////////////////////
1227 #if (!(MUTILS_DEBUG))
1228 static __forceinline
bool is_debugger_present(void)
1232 CloseHandle((HANDLE
)((DWORD_PTR
)-3));
1239 BOOL bHaveDebugger
= FALSE
;
1240 if(CheckRemoteDebuggerPresent(GetCurrentProcess(), &bHaveDebugger
))
1242 if(bHaveDebugger
) return true;
1245 return IsDebuggerPresent();
1247 static __forceinline
bool check_debugger_helper(void)
1249 if(is_debugger_present())
1251 MUtils::OS::fatal_exit(L
"Not a debug build. Please unload debugger and try again!");
1257 #define check_debugger_helper() (false)
1260 void MUtils::OS::check_debugger(void)
1262 check_debugger_helper();
1265 static volatile bool g_debug_check
= check_debugger_helper();
1267 ///////////////////////////////////////////////////////////////////////////////
1269 ///////////////////////////////////////////////////////////////////////////////
1271 static MUtils::Internal::CriticalSection g_fatal_exit_lock
;
1272 static volatile bool g_fatal_exit_flag
= true;
1274 static DWORD WINAPI
fatal_exit_helper(LPVOID lpParameter
)
1276 MUtils::OS::system_message_err(L
"GURU MEDITATION", (LPWSTR
) lpParameter
);
1280 void MUtils::OS::fatal_exit(const wchar_t* const errorMessage
)
1282 g_fatal_exit_lock
.enter();
1284 if(!g_fatal_exit_flag
)
1286 return; /*prevent recursive invocation*/
1289 g_fatal_exit_flag
= false;
1291 if(g_main_thread_id
!= GetCurrentThreadId())
1293 if(HANDLE hThreadMain
= OpenThread(THREAD_SUSPEND_RESUME
, FALSE
, g_main_thread_id
))
1295 SuspendThread(hThreadMain
); /*stop main thread*/
1299 if(HANDLE hThread
= CreateThread(NULL
, 0, fatal_exit_helper
, (LPVOID
) errorMessage
, 0, NULL
))
1301 WaitForSingleObject(hThread
, INFINITE
);
1306 TerminateProcess(GetCurrentProcess(), 666);
1310 ///////////////////////////////////////////////////////////////////////////////