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
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>
54 static const DWORD g_main_thread_id = GetCurrentThreadId();
56 ///////////////////////////////////////////////////////////////////////////////
58 ///////////////////////////////////////////////////////////////////////////////
60 static const UINT g_msgBoxFlags = MB_TOPMOST | MB_TASKMODAL | MB_SETFOREGROUND;
62 void MUtils::OS::system_message_nfo(const wchar_t *const title, const wchar_t *const text)
64 MessageBoxW(NULL, text, title, g_msgBoxFlags | MB_ICONINFORMATION);
67 void MUtils::OS::system_message_wrn(const wchar_t *const title, const wchar_t *const text)
69 MessageBoxW(NULL, text, title, g_msgBoxFlags | MB_ICONWARNING);
72 void MUtils::OS::system_message_err(const wchar_t *const title, const wchar_t *const text)
74 MessageBoxW(NULL, text, title, g_msgBoxFlags | MB_ICONERROR);
77 ///////////////////////////////////////////////////////////////////////////////
78 // FETCH CLI ARGUMENTS
79 ///////////////////////////////////////////////////////////////////////////////
81 static QReadWriteLock g_arguments_lock;
82 static QScopedPointer<MUtils::OS::ArgumentMap> g_arguments_list;
84 const QStringList MUtils::OS::crack_command_line(const QString &command_line)
87 LPWSTR *szArglist = CommandLineToArgvW(command_line.isNull() ? GetCommandLineW() : MUTILS_WCHR(command_line), &nArgs);
89 QStringList command_line_tokens;
92 for(int i = 0; i < nArgs; i++)
94 const QString argStr = MUTILS_QSTR(szArglist[i]).trimmed();
97 command_line_tokens << argStr;
100 LocalFree(szArglist);
103 return command_line_tokens;
106 const MUtils::OS::ArgumentMap &MUtils::OS::arguments(void)
108 QReadLocker readLock(&g_arguments_lock);
110 //Already initialized?
111 if(!g_arguments_list.isNull())
113 return (*(g_arguments_list.data()));
117 QWriteLocker writeLock(&g_arguments_lock);
119 //Still not initialized?
120 if(!g_arguments_list.isNull())
122 return (*(g_arguments_list.data()));
125 g_arguments_list.reset(new ArgumentMap());
126 const QStringList argList = crack_command_line();
128 if(!argList.isEmpty())
130 const QString argPrefix = QLatin1String("--");
131 const QChar separator = QLatin1Char('=');
133 bool firstToken = true;
134 for(QStringList::ConstIterator iter = argList.constBegin(); iter != argList.constEnd(); iter++)
139 continue; /*skip executable file name*/
141 if(iter->startsWith(argPrefix))
143 const QString argData = iter->mid(2).trimmed();
144 if(argData.length() > 0)
146 const int separatorIndex = argData.indexOf(separator);
147 if(separatorIndex > 0)
149 const QString argKey = argData.left(separatorIndex).trimmed();
150 const QString argVal = argData.mid(separatorIndex + 1).trimmed();
151 g_arguments_list->insertMulti(argKey.toLower(), argVal);
155 g_arguments_list->insertMulti(argData.toLower(), QString());
161 else if(argList.empty())
163 qWarning("CommandLineToArgvW() has failed !!!");
166 return (*(g_arguments_list.data()));
169 ///////////////////////////////////////////////////////////////////////////////
171 ///////////////////////////////////////////////////////////////////////////////
173 typedef struct _progress_callback_data_t
175 MUtils::OS::progress_callback_t callback_function;
178 progress_callback_data_t;
180 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)
182 if(const progress_callback_data_t *data = (progress_callback_data_t*) lpData)
184 const double progress = qBound(0.0, double(TotalBytesTransferred.QuadPart) / double(TotalFileSize.QuadPart), 1.0);
185 return data->callback_function(progress, data->user_data) ? PROGRESS_CONTINUE : PROGRESS_CANCEL;
187 return PROGRESS_CONTINUE;
190 MUTILS_API bool MUtils::OS::copy_file(const QString &sourcePath, const QString &outputPath, const bool &overwrite, const progress_callback_t callback, void *const userData)
192 progress_callback_data_t callback_data = { callback, userData };
194 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));
198 const DWORD errorCode = GetLastError();
199 if(errorCode != ERROR_REQUEST_ABORTED)
201 qWarning("CopyFile() failed with error code 0x%08X!", errorCode);
205 qWarning("CopyFile() operation was abroted by user!");
209 return (result != FALSE);
212 ///////////////////////////////////////////////////////////////////////////////
214 ///////////////////////////////////////////////////////////////////////////////
216 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)
218 if(!GetFileVersionInfo(MUTILS_WCHR(fileName), 0, size, buffer))
220 qWarning("GetFileVersionInfo() has failed, file version cannot be determined!");
224 VS_FIXEDFILEINFO *verInfo;
226 if(!VerQueryValue(buffer, L"\\", (LPVOID*)(&verInfo), &verInfoLen))
228 qWarning("VerQueryValue() has failed, file version cannot be determined!");
232 if(major) *major = quint16((verInfo->dwFileVersionMS >> 16) & 0x0000FFFF);
233 if(minor) *minor = quint16((verInfo->dwFileVersionMS) & 0x0000FFFF);
234 if(patch) *patch = quint16((verInfo->dwFileVersionLS >> 16) & 0x0000FFFF);
235 if(build) *build = quint16((verInfo->dwFileVersionLS) & 0x0000FFFF);
240 bool MUtils::OS::get_file_version(const QString fileName, quint16 *const major, quint16 *const minor, quint16 *const patch, quint16 *const build)
242 if(major) *major = 0U; if(minor) *minor = 0U;
243 if(patch) *patch = 0U; if(build) *build = 0U;
245 const DWORD size = GetFileVersionInfoSize(MUTILS_WCHR(fileName), NULL);
248 qWarning("GetFileVersionInfoSize() has failed, file version cannot be determined!");
252 PVOID buffer = _malloca(size);
255 qWarning("Memory allocation has failed!");
259 const bool success = get_file_version_helper(fileName, buffer, size, major, minor, patch, build);
265 ///////////////////////////////////////////////////////////////////////////////
266 // OS VERSION DETECTION
267 ///////////////////////////////////////////////////////////////////////////////
269 static bool g_os_version_initialized = false;
270 static MUtils::OS::Version::os_version_t g_os_version_info = MUtils::OS::Version::UNKNOWN_OPSYS;
271 static QReadWriteLock g_os_version_lock;
273 //Maps marketing names to the actual Windows NT versions
276 MUtils::OS::Version::os_version_t version;
277 const char friendlyName[64];
281 { MUtils::OS::Version::WINDOWS_WIN2K, "Windows 2000" }, //2000
282 { MUtils::OS::Version::WINDOWS_WINXP, "Windows XP or Windows XP Media Center Edition" }, //XP
283 { MUtils::OS::Version::WINDOWS_XPX64, "Windows Server 2003 or Windows XP x64" }, //XP_x64
284 { MUtils::OS::Version::WINDOWS_VISTA, "Windows Vista or Windows Server 2008" }, //Vista
285 { MUtils::OS::Version::WINDOWS_WIN70, "Windows 7 or Windows Server 2008 R2" }, //7
286 { MUtils::OS::Version::WINDOWS_WIN80, "Windows 8 or Windows Server 2012" }, //8
287 { MUtils::OS::Version::WINDOWS_WIN81, "Windows 8.1 or Windows Server 2012 R2" }, //8.1
288 { MUtils::OS::Version::WINDOWS_WN100, "Windows 10 or Windows Server 2014 (Preview)" }, //10
289 { MUtils::OS::Version::UNKNOWN_OPSYS, "N/A" }
292 //OS version data dtructures
299 //Comparision operators for os_version_t
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) || ((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))); }
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))); }
307 //Known Windows NT versions
308 const os_version_t WINDOWS_WIN2K = { OS_WINDOWS, 5, 0 }; // 2000
309 const os_version_t WINDOWS_WINXP = { OS_WINDOWS, 5, 1 }; // XP
310 const os_version_t WINDOWS_XPX64 = { OS_WINDOWS, 5, 2 }; // XP_x64
311 const os_version_t WINDOWS_VISTA = { OS_WINDOWS, 6, 0 }; // Vista
312 const os_version_t WINDOWS_WIN70 = { OS_WINDOWS, 6, 1 }; // 7
313 const os_version_t WINDOWS_WIN80 = { OS_WINDOWS, 6, 2 }; // 8
314 const os_version_t WINDOWS_WIN81 = { OS_WINDOWS, 6, 3 }; // 8.1
315 const os_version_t WINDOWS_WN100 = { OS_WINDOWS, 10, 0 }; // 10
318 const os_version_t UNKNOWN_OPSYS = { OS_UNKNOWN, 0, 0 }; // N/A
323 static bool verify_os_version(const DWORD major, const DWORD minor)
325 OSVERSIONINFOEXW osvi;
326 DWORDLONG dwlConditionMask = 0;
328 //Initialize the OSVERSIONINFOEX structure
329 memset(&osvi, 0, sizeof(OSVERSIONINFOEXW));
330 osvi.dwOSVersionInfoSize = sizeof(OSVERSIONINFOEXW);
331 osvi.dwMajorVersion = major;
332 osvi.dwMinorVersion = minor;
333 osvi.dwPlatformId = VER_PLATFORM_WIN32_NT;
335 //Initialize the condition mask
336 VER_SET_CONDITION(dwlConditionMask, VER_MAJORVERSION, VER_GREATER_EQUAL);
337 VER_SET_CONDITION(dwlConditionMask, VER_MINORVERSION, VER_GREATER_EQUAL);
338 VER_SET_CONDITION(dwlConditionMask, VER_PLATFORMID, VER_EQUAL);
341 const BOOL ret = VerifyVersionInfoW(&osvi, VER_MAJORVERSION | VER_MINORVERSION | VER_PLATFORMID, dwlConditionMask);
346 if(GetLastError() != ERROR_OLD_WIN_VERSION)
348 qWarning("VerifyVersionInfo() system call has failed!");
352 return (ret != FALSE);
355 static bool get_real_os_version(unsigned int *major, unsigned int *minor, bool *pbOverride)
360 //Initialize local variables
361 OSVERSIONINFOEXW osvi;
362 memset(&osvi, 0, sizeof(OSVERSIONINFOEXW));
363 osvi.dwOSVersionInfoSize = sizeof(OSVERSIONINFOEXW);
365 //Try GetVersionEx() first
366 if(GetVersionExW((LPOSVERSIONINFOW)&osvi) == FALSE)
368 qWarning("GetVersionEx() has failed, cannot detect Windows version!");
372 //Make sure we are running on NT
373 if(osvi.dwPlatformId == VER_PLATFORM_WIN32_NT)
375 *major = osvi.dwMajorVersion;
376 *minor = osvi.dwMinorVersion;
380 qWarning("Not running on Windows NT, unsupported operating system!");
384 //Determine the real *major* version first
387 const DWORD nextMajor = (*major) + 1;
388 if(verify_os_version(nextMajor, 0))
398 //Now also determine the real *minor* version
401 const DWORD nextMinor = (*minor) + 1;
402 if(verify_os_version((*major), nextMinor))
411 //Workaround for the mess that is sometimes referred to as "Windows 10"
412 if(((*major) > 6) || (((*major) == 6) && ((*minor) >= 2)))
414 quint16 kernel32_major, kernel32_minor;
415 if(MUtils::OS::get_file_version(QLatin1String("kernel32"), &kernel32_major, &kernel32_minor))
417 if((kernel32_major > (*major)) || ((kernel32_major == (*major)) && (kernel32_minor > (*minor))))
419 *major = kernel32_major;
420 *minor = kernel32_minor;
429 const MUtils::OS::Version::os_version_t &MUtils::OS::os_version(void)
431 QReadLocker readLock(&g_os_version_lock);
433 //Already initialized?
434 if(g_os_version_initialized)
436 return g_os_version_info;
440 QWriteLocker writeLock(&g_os_version_lock);
443 if(g_os_version_initialized)
445 return g_os_version_info;
449 unsigned int major, minor; bool overrideFlg;
450 if(get_real_os_version(&major, &minor, &overrideFlg))
452 g_os_version_info.type = Version::OS_WINDOWS;
453 g_os_version_info.versionMajor = major;
454 g_os_version_info.versionMinor = minor;
455 g_os_version_info.overrideFlag = overrideFlg;
459 qWarning("Failed to determin the operating system version!");
463 g_os_version_initialized = true;
464 return g_os_version_info;
467 const char *MUtils::OS::os_friendly_name(const MUtils::OS::Version::os_version_t &os_version)
469 for(size_t i = 0; g_os_version_lut[i].version != MUtils::OS::Version::UNKNOWN_OPSYS; i++)
471 if(os_version == g_os_version_lut[i].version)
473 return g_os_version_lut[i].friendlyName;
480 ///////////////////////////////////////////////////////////////////////////////
482 ///////////////////////////////////////////////////////////////////////////////
484 static bool g_wine_deteced = false;
485 static bool g_wine_initialized = false;
486 static QReadWriteLock g_wine_lock;
488 static const bool detect_wine(void)
490 void *const ptr = MUtils::Win32Utils::resolve<void*>(QLatin1String("ntdll"), QLatin1String("wine_get_version"));
491 return (ptr != NULL);
494 const bool &MUtils::OS::running_on_wine(void)
496 QReadLocker readLock(&g_wine_lock);
498 //Already initialized?
499 if(g_wine_initialized)
501 return g_wine_deteced;
505 QWriteLocker writeLock(&g_wine_lock);
508 if(g_wine_initialized)
510 return g_wine_deteced;
514 g_wine_deteced = detect_wine();
515 g_wine_initialized = true;
517 return g_wine_deteced;
520 ///////////////////////////////////////////////////////////////////////////////
522 ///////////////////////////////////////////////////////////////////////////////
524 typedef QMap<size_t, QString> KFMap;
525 typedef HRESULT (WINAPI *SHGetKnownFolderPath_t)(const GUID &rfid, DWORD dwFlags, HANDLE hToken, PWSTR *ppszPath);
526 typedef HRESULT (WINAPI *SHGetFolderPath_t) (HWND hwndOwner, int nFolder, HANDLE hToken, DWORD dwFlags, LPWSTR pszPath);
528 static QScopedPointer<KFMap> g_known_folders_map;
529 static QReadWriteLock g_known_folders_lock;
531 const QString &MUtils::OS::known_folder(known_folder_t folder_id)
533 typedef enum { KF_FLAG_CREATE = 0x00008000 } kf_flags_t;
542 { 0x001c, {0xF1B32785,0x6FBA,0x4FCF,{0x9D,0x55,0x7B,0x8E,0x7F,0x15,0x70,0x91}} }, //CSIDL_LOCAL_APPDATA
543 { 0x0026, {0x905e63b6,0xc1bf,0x494e,{0xb2,0x9c,0x65,0xb7,0x32,0xd3,0xd2,0x1a}} }, //CSIDL_PROGRAM_FILES
544 { 0x0024, {0xF38BF404,0x1D43,0x42F2,{0x93,0x05,0x67,0xDE,0x0B,0x28,0xFC,0x23}} }, //CSIDL_WINDOWS_FOLDER
545 { 0x0025, {0x1AC14E77,0x02E7,0x4E5D,{0xB7,0x44,0x2E,0xB1,0xAE,0x51,0x98,0xB7}} }, //CSIDL_SYSTEM_FOLDER
548 size_t folderId = size_t(-1);
552 case FOLDER_LOCALAPPDATA: folderId = 0; break;
553 case FOLDER_PROGRAMFILES: folderId = 1; break;
554 case FOLDER_SYSTROOT_DIR: folderId = 2; break;
555 case FOLDER_SYSTEMFOLDER: folderId = 3; break;
558 if(folderId == size_t(-1))
560 qWarning("Invalid 'known' folder was requested!");
561 return *reinterpret_cast<QString*>(NULL);
564 QReadLocker readLock(&g_known_folders_lock);
567 if(!g_known_folders_map.isNull())
569 if(g_known_folders_map->contains(folderId))
571 return g_known_folders_map->operator[](folderId);
575 //Obtain write lock to initialize
577 QWriteLocker writeLock(&g_known_folders_lock);
579 //Still not in cache?
580 if(!g_known_folders_map.isNull())
582 if(g_known_folders_map->contains(folderId))
584 return g_known_folders_map->operator[](folderId);
588 //Initialize on first call
589 if(g_known_folders_map.isNull())
591 g_known_folders_map.reset(new QMap<size_t, QString>());
596 //Now try to get the folder path!
597 if(const SHGetKnownFolderPath_t known_folders_fpGetKnownFolderPath = MUtils::Win32Utils::resolve<SHGetKnownFolderPath_t>(QLatin1String("shell32"), QLatin1String("SHGetKnownFolderPath")))
600 if(known_folders_fpGetKnownFolderPath(s_folders[folderId].guid, KF_FLAG_CREATE, NULL, &path) == S_OK)
602 //MessageBoxW(0, path, L"SHGetKnownFolderPath", MB_TOPMOST);
603 QDir folderTemp = QDir(QDir::fromNativeSeparators(MUTILS_QSTR(path)));
604 if(folderTemp.exists())
606 folderPath = folderTemp.canonicalPath();
611 else if(const SHGetFolderPath_t known_folders_fpGetFolderPath = MUtils::Win32Utils::resolve<SHGetFolderPath_t>(QLatin1String("shell32"), QLatin1String("SHGetFolderPathW")))
613 QScopedArrayPointer<WCHAR> path(new WCHAR[4096]);
614 if(known_folders_fpGetFolderPath(NULL, s_folders[folderId].csidl | CSIDL_FLAG_CREATE, NULL, NULL, path.data()) == S_OK)
616 //MessageBoxW(0, path, L"SHGetFolderPathW", MB_TOPMOST);
617 QDir folderTemp = QDir(QDir::fromNativeSeparators(MUTILS_QSTR(path.data())));
618 if(folderTemp.exists())
620 folderPath = folderTemp.canonicalPath();
626 g_known_folders_map->insert(folderId, folderPath);
627 return g_known_folders_map->operator[](folderId);
630 ///////////////////////////////////////////////////////////////////////////////
631 // CURRENT DATA & TIME
632 ///////////////////////////////////////////////////////////////////////////////
634 QDate MUtils::OS::current_date(void)
636 const DWORD MAX_PROC = 1024;
637 QScopedArrayPointer<DWORD> processes(new DWORD[MAX_PROC]);
638 DWORD bytesReturned = 0;
640 if(!EnumProcesses(processes.data(), sizeof(DWORD) * MAX_PROC, &bytesReturned))
642 return QDate::currentDate();
645 const DWORD procCount = bytesReturned / sizeof(DWORD);
646 ULARGE_INTEGER lastStartTime;
647 memset(&lastStartTime, 0, sizeof(ULARGE_INTEGER));
649 for(DWORD i = 0; i < procCount; i++)
651 if(HANDLE hProc = OpenProcess(PROCESS_QUERY_INFORMATION, FALSE, processes[i]))
653 FILETIME processTime[4];
654 if(GetProcessTimes(hProc, &processTime[0], &processTime[1], &processTime[2], &processTime[3]))
656 ULARGE_INTEGER timeCreation;
657 timeCreation.LowPart = processTime[0].dwLowDateTime;
658 timeCreation.HighPart = processTime[0].dwHighDateTime;
659 if(timeCreation.QuadPart > lastStartTime.QuadPart)
661 lastStartTime.QuadPart = timeCreation.QuadPart;
668 FILETIME lastStartTime_fileTime;
669 lastStartTime_fileTime.dwHighDateTime = lastStartTime.HighPart;
670 lastStartTime_fileTime.dwLowDateTime = lastStartTime.LowPart;
672 FILETIME lastStartTime_localTime;
673 if(!FileTimeToLocalFileTime(&lastStartTime_fileTime, &lastStartTime_localTime))
675 memcpy(&lastStartTime_localTime, &lastStartTime_fileTime, sizeof(FILETIME));
678 SYSTEMTIME lastStartTime_system;
679 if(!FileTimeToSystemTime(&lastStartTime_localTime, &lastStartTime_system))
681 memset(&lastStartTime_system, 0, sizeof(SYSTEMTIME));
682 lastStartTime_system.wYear = 1970; lastStartTime_system.wMonth = lastStartTime_system.wDay = 1;
685 const QDate currentDate = QDate::currentDate();
686 const QDate processDate = QDate(lastStartTime_system.wYear, lastStartTime_system.wMonth, lastStartTime_system.wDay);
687 return (currentDate >= processDate) ? currentDate : processDate;
690 quint64 MUtils::OS::current_file_time(void)
693 GetSystemTimeAsFileTime(&fileTime);
696 temp.HighPart = fileTime.dwHighDateTime;
697 temp.LowPart = fileTime.dwLowDateTime;
699 return temp.QuadPart;
702 ///////////////////////////////////////////////////////////////////////////////
704 ///////////////////////////////////////////////////////////////////////////////
706 typedef DWORD(_stdcall *GetPathNameByHandleFun)(HANDLE hFile, LPWSTR lpszFilePath, DWORD cchFilePath, DWORD dwFlags);
708 static QString get_file_path_drive_list(void)
711 const DWORD len = GetLogicalDriveStringsW(0, NULL);
714 if (wchar_t *const buffer = (wchar_t*) _malloca(sizeof(wchar_t) * len))
716 const DWORD ret = GetLogicalDriveStringsW(len, buffer);
717 if ((ret > 0) && (ret < len))
719 const wchar_t *ptr = buffer;
720 while (const size_t current_len = wcslen(ptr))
722 list.append(QChar(*reinterpret_cast<const ushort*>(ptr)));
723 ptr += (current_len + 1);
732 static QString &get_file_path_translate(QString &path)
734 static const DWORD BUFSIZE = 4096;
735 wchar_t buffer[BUFSIZE], drive[3];
737 const QString driveList = get_file_path_drive_list();
738 wcscpy_s(drive, 3, L"?:");
739 for (const wchar_t *current = MUTILS_WCHR(driveList); *current; current++)
741 drive[0] = (*current);
742 if (QueryDosDeviceW(drive, buffer, MAX_PATH))
744 const QString prefix = MUTILS_QSTR(buffer);
745 if (path.startsWith(prefix, Qt::CaseInsensitive))
747 path.remove(0, prefix.length()).prepend(QLatin1Char(':')).prepend(QChar(*reinterpret_cast<const ushort*>(current)));
756 static QString get_file_path_fallback(const HANDLE &hFile)
760 const HANDLE hFileMap = CreateFileMappingW(hFile, NULL, PAGE_READONLY, 0, 1, NULL);
763 void* pMem = MapViewOfFile(hFileMap, FILE_MAP_READ, 0, 0, 1);
766 static const DWORD BUFSIZE = 4096;
767 wchar_t buffer[BUFSIZE];
768 if (GetMappedFileNameW(GetCurrentProcess(), pMem, buffer, BUFSIZE))
770 filePath = get_file_path_translate(MUTILS_QSTR(buffer));
772 UnmapViewOfFile(pMem);
774 CloseHandle(hFileMap);
780 QString MUtils::OS::get_file_path(const int &fd)
784 const GetPathNameByHandleFun getPathNameByHandleFun = MUtils::Win32Utils::resolve<GetPathNameByHandleFun>(QLatin1String("kernel32"), QLatin1String("GetFinalPathNameByHandleW"));
785 if (!getPathNameByHandleFun)
787 qWarning("MUtils::OS::get_file_path() --> fallback!");
788 return get_file_path_fallback((HANDLE)_get_osfhandle(fd));
791 const HANDLE handle = (HANDLE) _get_osfhandle(fd);
792 const DWORD len = getPathNameByHandleFun(handle, NULL, 0, FILE_NAME_OPENED);
795 if (wchar_t *const buffer = (wchar_t*)_malloca(sizeof(wchar_t) * len))
797 const DWORD ret = getPathNameByHandleFun(handle, buffer, len, FILE_NAME_OPENED);
798 if ((ret > 0) && (ret < len))
800 const QString path(MUTILS_QSTR(buffer));
801 return path.startsWith(QLatin1String("\\\\?\\")) ? path.mid(4) : path;
811 ///////////////////////////////////////////////////////////////////////////////
813 ///////////////////////////////////////////////////////////////////////////////
815 static bool user_is_admin_helper(void)
817 HANDLE hToken = NULL;
818 if(!OpenProcessToken(GetCurrentProcess(), TOKEN_QUERY, &hToken))
824 if(!GetTokenInformation(hToken, TokenGroups, NULL, 0, &dwSize))
826 if(GetLastError() != ERROR_INSUFFICIENT_BUFFER)
833 PTOKEN_GROUPS lpGroups = (PTOKEN_GROUPS) malloc(dwSize);
840 if(!GetTokenInformation(hToken, TokenGroups, lpGroups, dwSize, &dwSize))
847 PSID lpSid = NULL; SID_IDENTIFIER_AUTHORITY Authority = {SECURITY_NT_AUTHORITY};
848 if(!AllocateAndInitializeSid(&Authority, 2, SECURITY_BUILTIN_DOMAIN_RID, DOMAIN_ALIAS_RID_ADMINS, 0, 0, 0, 0, 0, 0, &lpSid))
855 bool bResult = false;
856 for(DWORD i = 0; i < lpGroups->GroupCount; i++)
858 if(EqualSid(lpSid, lpGroups->Groups[i].Sid))
871 bool MUtils::OS::is_elevated(bool *bIsUacEnabled)
875 *bIsUacEnabled = false;
878 bool bIsProcessElevated = false;
879 HANDLE hToken = NULL;
881 if(OpenProcessToken(GetCurrentProcess(), TOKEN_QUERY, &hToken))
883 TOKEN_ELEVATION_TYPE tokenElevationType;
885 if(GetTokenInformation(hToken, TokenElevationType, &tokenElevationType, sizeof(TOKEN_ELEVATION_TYPE), &returnLength))
887 if(returnLength == sizeof(TOKEN_ELEVATION_TYPE))
889 switch(tokenElevationType)
891 case TokenElevationTypeDefault:
892 qDebug("Process token elevation type: Default -> UAC is disabled.\n");
894 case TokenElevationTypeFull:
895 qWarning("Process token elevation type: Full -> potential security risk!\n");
896 bIsProcessElevated = true;
897 if(bIsUacEnabled) *bIsUacEnabled = true;
899 case TokenElevationTypeLimited:
900 qDebug("Process token elevation type: Limited -> not elevated.\n");
901 if(bIsUacEnabled) *bIsUacEnabled = true;
904 qWarning("Unknown tokenElevationType value: %d", tokenElevationType);
910 qWarning("GetTokenInformation() return an unexpected size!");
917 qWarning("Failed to open process token!");
920 return bIsProcessElevated;
923 bool MUtils::OS::user_is_admin(void)
925 bool isAdmin = false;
927 //Check for process elevation and UAC support first!
928 if(MUtils::OS::is_elevated(&isAdmin))
930 qWarning("Process is elevated -> user is admin!");
934 //If not elevated and UAC is not available -> user must be in admin group!
937 qDebug("UAC is disabled/unavailable -> checking for Administrators group");
938 isAdmin = user_is_admin_helper();
944 ///////////////////////////////////////////////////////////////////////////////
946 ///////////////////////////////////////////////////////////////////////////////
948 int MUtils::OS::network_status(void)
951 const BOOL ret = IsNetworkAlive(&dwFlags);
952 if(GetLastError() == 0)
954 return (ret != FALSE) ? NETWORK_TYPE_YES : NETWORK_TYPE_NON;
956 return NETWORK_TYPE_ERR;
959 ///////////////////////////////////////////////////////////////////////////////
961 ///////////////////////////////////////////////////////////////////////////////
963 bool MUtils::OS::handle_os_message(const void *const message, long *result)
965 const MSG *const msg = reinterpret_cast<const MSG*>(message);
969 case WM_QUERYENDSESSION:
970 qWarning("WM_QUERYENDSESSION message received!");
971 *result = MUtils::GUI::broadcast(MUtils::GUI::USER_EVENT_QUERYENDSESSION, false) ? TRUE : FALSE;
974 qWarning("WM_ENDSESSION message received!");
975 if(msg->wParam == TRUE)
977 MUtils::GUI::broadcast(MUtils::GUI::USER_EVENT_ENDSESSION, false);
978 MUtils::GUI::force_quit();
984 /*ignore this message and let Qt handle it*/
989 ///////////////////////////////////////////////////////////////////////////////
991 ///////////////////////////////////////////////////////////////////////////////
993 void MUtils::OS::sleep_ms(const size_t &duration)
995 Sleep((DWORD) duration);
998 ///////////////////////////////////////////////////////////////////////////////
1000 ///////////////////////////////////////////////////////////////////////////////
1002 bool MUtils::OS::is_executable_file(const QString &path)
1004 bool bIsExecutable = false;
1006 if(GetBinaryType(MUTILS_WCHR(QDir::toNativeSeparators(path)), &binaryType))
1008 bIsExecutable = (binaryType == SCS_32BIT_BINARY || binaryType == SCS_64BIT_BINARY);
1010 return bIsExecutable;
1013 ///////////////////////////////////////////////////////////////////////////////
1014 // HIBERNATION / SHUTDOWN
1015 ///////////////////////////////////////////////////////////////////////////////
1017 bool MUtils::OS::is_hibernation_supported(void)
1019 bool hibernationSupported = false;
1021 SYSTEM_POWER_CAPABILITIES pwrCaps;
1022 SecureZeroMemory(&pwrCaps, sizeof(SYSTEM_POWER_CAPABILITIES));
1024 if(GetPwrCapabilities(&pwrCaps))
1026 hibernationSupported = pwrCaps.SystemS4 && pwrCaps.HiberFilePresent;
1029 return hibernationSupported;
1032 bool MUtils::OS::shutdown_computer(const QString &message, const unsigned long timeout, const bool forceShutdown, const bool hibernate)
1034 HANDLE hToken = NULL;
1036 if(OpenProcessToken(GetCurrentProcess(), TOKEN_ADJUST_PRIVILEGES | TOKEN_QUERY, &hToken))
1038 TOKEN_PRIVILEGES privileges;
1039 memset(&privileges, 0, sizeof(TOKEN_PRIVILEGES));
1040 privileges.PrivilegeCount = 1;
1041 privileges.Privileges[0].Attributes = SE_PRIVILEGE_ENABLED;
1043 if(LookupPrivilegeValue(NULL, SE_SHUTDOWN_NAME, &privileges.Privileges[0].Luid))
1045 if(AdjustTokenPrivileges(hToken, FALSE, &privileges, NULL, NULL, NULL))
1049 if(SetSuspendState(TRUE, TRUE, TRUE))
1054 const DWORD reason = SHTDN_REASON_MAJOR_APPLICATION | SHTDN_REASON_FLAG_PLANNED;
1055 return InitiateSystemShutdownEx(NULL, const_cast<wchar_t*>(MUTILS_WCHR(message)), timeout, forceShutdown ? TRUE : FALSE, FALSE, reason);
1063 ///////////////////////////////////////////////////////////////////////////////
1065 ///////////////////////////////////////////////////////////////////////////////
1067 bool MUtils::OS::free_diskspace(const QString &path, quint64 &freeSpace)
1069 ULARGE_INTEGER freeBytesAvailable, totalNumberOfBytes, totalNumberOfFreeBytes;
1070 if(GetDiskFreeSpaceExW(reinterpret_cast<const wchar_t*>(QDir::toNativeSeparators(path).utf16()), &freeBytesAvailable, &totalNumberOfBytes, &totalNumberOfFreeBytes))
1072 freeSpace = freeBytesAvailable.QuadPart;
1080 ///////////////////////////////////////////////////////////////////////////////
1082 ///////////////////////////////////////////////////////////////////////////////
1084 bool MUtils::OS::shell_open(const QWidget *parent, const QString &url, const QString ¶meters, const QString &directory, const bool explore)
1086 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;
1089 bool MUtils::OS::shell_open(const QWidget *parent, const QString &url, const bool explore)
1091 return shell_open(parent, url, QString(), QString(), explore);
1094 ///////////////////////////////////////////////////////////////////////////////
1096 ///////////////////////////////////////////////////////////////////////////////
1098 bool MUtils::OS::open_media_file(const QString &mediaFilePath)
1100 const static wchar_t *registryPrefix[2] = { L"SOFTWARE\\", L"SOFTWARE\\Wow6432Node\\" };
1101 const static wchar_t *registryKeys[3] =
1103 L"Microsoft\\Windows\\CurrentVersion\\Uninstall\\{97D341C8-B0D1-4E4A-A49A-C30B52F168E9}",
1104 L"Microsoft\\Windows\\CurrentVersion\\Uninstall\\{DB9E4EAB-2717-499F-8D56-4CC8A644AB60}",
1107 const static wchar_t *appNames[4] = { L"smplayer_portable.exe", L"smplayer.exe", L"MPUI.exe", L"foobar2000.exe" };
1108 const static wchar_t *valueNames[2] = { L"InstallLocation", L"InstallDir" };
1110 for(size_t i = 0; i < 3; i++)
1112 for(size_t j = 0; j < 2; j++)
1114 QString mplayerPath;
1115 HKEY registryKeyHandle = NULL;
1117 const QString currentKey = MUTILS_QSTR(registryPrefix[j]).append(MUTILS_QSTR(registryKeys[i]));
1118 if(RegOpenKeyExW(HKEY_LOCAL_MACHINE, MUTILS_WCHR(currentKey), 0, KEY_READ, ®istryKeyHandle) == ERROR_SUCCESS)
1120 for(size_t k = 0; k < 2; k++)
1122 wchar_t Buffer[4096];
1123 DWORD BuffSize = sizeof(wchar_t*) * 4096;
1124 DWORD DataType = REG_NONE;
1125 if(RegQueryValueExW(registryKeyHandle, valueNames[k], 0, &DataType, reinterpret_cast<BYTE*>(Buffer), &BuffSize) == ERROR_SUCCESS)
1127 if((DataType == REG_SZ) || (DataType == REG_EXPAND_SZ) || (DataType == REG_LINK))
1129 mplayerPath = MUTILS_QSTR(Buffer);
1134 RegCloseKey(registryKeyHandle);
1137 if(!mplayerPath.isEmpty())
1139 QDir mplayerDir(mplayerPath);
1140 if(mplayerDir.exists())
1142 for(size_t k = 0; k < 4; k++)
1144 if(mplayerDir.exists(MUTILS_QSTR(appNames[k])))
1146 qDebug("Player found at:\n%s\n", MUTILS_UTF8(mplayerDir.absoluteFilePath(MUTILS_QSTR(appNames[k]))));
1147 QProcess::startDetached(mplayerDir.absoluteFilePath(MUTILS_QSTR(appNames[k])), QStringList() << QDir::toNativeSeparators(mediaFilePath));
1158 ///////////////////////////////////////////////////////////////////////////////
1160 ///////////////////////////////////////////////////////////////////////////////
1162 static bool change_process_priority_helper(const HANDLE hProcess, const int priority)
1166 switch(qBound(-2, priority, 2))
1169 ok = (SetPriorityClass(hProcess, HIGH_PRIORITY_CLASS) == TRUE);
1172 if(!(ok = (SetPriorityClass(hProcess, ABOVE_NORMAL_PRIORITY_CLASS) == TRUE)))
1174 ok = (SetPriorityClass(hProcess, HIGH_PRIORITY_CLASS) == TRUE);
1178 ok = (SetPriorityClass(hProcess, NORMAL_PRIORITY_CLASS) == TRUE);
1181 if(!(ok = (SetPriorityClass(hProcess, BELOW_NORMAL_PRIORITY_CLASS) == TRUE)))
1183 ok = (SetPriorityClass(hProcess, IDLE_PRIORITY_CLASS) == TRUE);
1187 ok = (SetPriorityClass(hProcess, IDLE_PRIORITY_CLASS) == TRUE);
1194 bool MUtils::OS::change_process_priority(const int priority)
1196 return change_process_priority_helper(GetCurrentProcess(), priority);
1199 bool MUtils::OS::change_process_priority(const QProcess *proc, const int priority)
1201 if(Q_PID qPid = proc->pid())
1203 return change_process_priority_helper(qPid->hProcess, priority);
1211 ///////////////////////////////////////////////////////////////////////////////
1213 ///////////////////////////////////////////////////////////////////////////////
1215 quint32 MUtils::OS::process_id(const QProcess *const proc)
1217 PROCESS_INFORMATION *procInf = proc->pid();
1218 return (procInf) ? procInf->dwProcessId : NULL;
1221 ///////////////////////////////////////////////////////////////////////////////
1222 // PROCESS SUSPEND/RESUME
1223 ///////////////////////////////////////////////////////////////////////////////
1225 bool MUtils::OS::suspend_process(const QProcess *proc, const bool suspend)
1227 if(Q_PID pid = proc->pid())
1231 return (SuspendThread(pid->hThread) != ((DWORD) -1));
1235 return (ResumeThread(pid->hThread) != ((DWORD) -1));
1244 ///////////////////////////////////////////////////////////////////////////////
1246 ///////////////////////////////////////////////////////////////////////////////
1248 bool MUtils::OS::setup_timer_resolution(const quint32 &interval)
1250 return timeBeginPeriod(interval) == TIMERR_NOERROR;
1253 bool MUtils::OS::reset_timer_resolution(const quint32 &interval)
1255 return timeEndPeriod(interval) == TIMERR_NOERROR;
1258 ///////////////////////////////////////////////////////////////////////////////
1260 ///////////////////////////////////////////////////////////////////////////////
1262 static QScopedPointer<QDateTime> s_epoch;
1263 static QReadWriteLock s_epochLock;
1265 static const QDateTime *get_epoch(void)
1267 QReadLocker rdLock(&s_epochLock);
1269 if (s_epoch.isNull())
1272 QWriteLocker wrLock(&s_epochLock);
1273 if (s_epoch.isNull())
1275 s_epoch.reset(new QDateTime(QDate(1601, 1, 1), QTime(0, 0, 0, 0), Qt::UTC));
1281 return s_epoch.data();
1284 static FILETIME *qt_time_to_file_time(FILETIME *const fileTime, const QDateTime &dateTime)
1286 memset(fileTime, 0, sizeof(FILETIME));
1288 if (const QDateTime *const epoch = get_epoch())
1290 const qint64 msecs = epoch->msecsTo(dateTime);
1293 const quint64 ticks = 10000U * quint64(msecs);
1294 fileTime->dwHighDateTime = ((ticks >> 32) & 0xFFFFFFFF);
1295 fileTime->dwLowDateTime = (ticks & 0xFFFFFFFF);
1303 static bool set_file_time(const HANDLE hFile, const QDateTime &created, const QDateTime &lastMod, const QDateTime &lastAcc)
1305 FILETIME ftCreated, ftLastMod, ftLastAcc;
1307 FILETIME *const pCreated = created.isValid() ? qt_time_to_file_time(&ftCreated, created) : NULL;
1308 FILETIME *const pLastMod = lastMod.isValid() ? qt_time_to_file_time(&ftLastMod, lastMod) : NULL;
1309 FILETIME *const pLastAcc = lastAcc.isValid() ? qt_time_to_file_time(&ftLastAcc, lastAcc) : NULL;
1311 if (pCreated || pLastMod || pLastAcc)
1313 return (SetFileTime(hFile, pCreated, pLastAcc, pLastMod) != FALSE);
1319 bool MUtils::OS::set_file_time(const QFile &file, const QDateTime &created, const QDateTime &lastMod, const QDateTime &lastAcc)
1321 const int fd = file.handle();
1324 return set_file_time((HANDLE)_get_osfhandle(fd), created, lastMod, lastAcc);
1329 bool MUtils::OS::set_file_time(const QString &path, const QDateTime &created, const QDateTime &lastMod, const QDateTime &lastAcc)
1331 const HANDLE hFile = CreateFileW(MUTILS_WCHR(path), FILE_WRITE_ATTRIBUTES, FILE_SHARE_READ, NULL, OPEN_EXISTING, 0, 0);
1333 if ((hFile != NULL) && (hFile != INVALID_HANDLE_VALUE))
1335 okay = set_file_time(hFile, created, lastMod, lastAcc);
1341 ///////////////////////////////////////////////////////////////////////////////
1343 ///////////////////////////////////////////////////////////////////////////////
1345 bool MUtils::OS::check_key_state_esc(void)
1347 return (GetAsyncKeyState(VK_ESCAPE) & 0x0001) != 0;
1350 ///////////////////////////////////////////////////////////////////////////////
1351 // SHELL CHANGE NOTIFICATION
1352 ///////////////////////////////////////////////////////////////////////////////
1354 void MUtils::OS::shell_change_notification(void)
1356 SHChangeNotify(SHCNE_ASSOCCHANGED, SHCNF_IDLIST, NULL, NULL);
1359 ///////////////////////////////////////////////////////////////////////////////
1360 // WOW64 REDIRECTION
1361 ///////////////////////////////////////////////////////////////////////////////
1363 typedef BOOL (_stdcall *Wow64DisableWow64FsRedirectionFun)(void *OldValue);
1364 typedef BOOL (_stdcall *Wow64RevertWow64FsRedirectionFun )(void *OldValue);
1366 bool MUtils::OS::wow64fsredir_disable(void *oldValue)
1368 const Wow64DisableWow64FsRedirectionFun wow64redir_disable = MUtils::Win32Utils::resolve<Wow64DisableWow64FsRedirectionFun>(QLatin1String("kernel32"), QLatin1String("Wow64DisableWow64FsRedirection"));
1369 if(wow64redir_disable)
1371 if (wow64redir_disable(oldValue))
1379 bool MUtils::OS::wow64fsredir_revert(void *oldValue)
1381 const Wow64RevertWow64FsRedirectionFun wow64redir_disable = MUtils::Win32Utils::resolve<Wow64RevertWow64FsRedirectionFun>(QLatin1String("kernel32"), QLatin1String("Wow64RevertWow64FsRedirection"));
1382 if (wow64redir_disable)
1384 if (wow64redir_disable(oldValue))
1392 ///////////////////////////////////////////////////////////////////////////////
1394 ///////////////////////////////////////////////////////////////////////////////
1396 #if (!(MUTILS_DEBUG))
1397 static __forceinline bool is_debugger_present(void)
1401 CloseHandle((HANDLE)((DWORD_PTR)-3));
1408 BOOL bHaveDebugger = FALSE;
1409 if(CheckRemoteDebuggerPresent(GetCurrentProcess(), &bHaveDebugger))
1411 if(bHaveDebugger) return true;
1414 return IsDebuggerPresent();
1416 static __forceinline bool check_debugger_helper(void)
1418 if(is_debugger_present())
1420 MUtils::OS::fatal_exit(L"Not a debug build. Please unload debugger and try again!");
1426 #define check_debugger_helper() (false)
1429 void MUtils::OS::check_debugger(void)
1431 check_debugger_helper();
1434 static volatile bool g_debug_check = check_debugger_helper();
1436 ///////////////////////////////////////////////////////////////////////////////
1438 ///////////////////////////////////////////////////////////////////////////////
1440 static MUtils::Internal::CriticalSection g_fatal_exit_lock;
1441 static volatile bool g_fatal_exit_flag = true;
1443 static DWORD WINAPI fatal_exit_helper(LPVOID lpParameter)
1445 MUtils::OS::system_message_err(L"GURU MEDITATION", (LPWSTR) lpParameter);
1449 void MUtils::OS::fatal_exit(const wchar_t* const errorMessage)
1451 g_fatal_exit_lock.enter();
1453 if(!g_fatal_exit_flag)
1455 return; /*prevent recursive invocation*/
1458 g_fatal_exit_flag = false;
1460 if(g_main_thread_id != GetCurrentThreadId())
1462 if(HANDLE hThreadMain = OpenThread(THREAD_SUSPEND_RESUME, FALSE, g_main_thread_id))
1464 SuspendThread(hThreadMain); /*stop main thread*/
1468 if(HANDLE hThread = CreateThread(NULL, 0, fatal_exit_helper, (LPVOID) errorMessage, 0, NULL))
1470 WaitForSingleObject(hThread, INFINITE);
1475 TerminateProcess(GetCurrentProcess(), 666);
1479 ///////////////////////////////////////////////////////////////////////////////