1 ///////////////////////////////////////////////////////////////////////////////
2 // MuldeR's Utilities for Qt
3 // Copyright (C) 2004-2014 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 //////////////////////////////////////////////////////////////////////////////////
25 #include <MUtils/Global.h>
26 #include <MUtils/OSSupport.h>
27 #include "CriticalSection_Win32.h"
30 #define WIN32_LEAN_AND_MEAN 1
38 #include <QReadWriteLock>
43 static const DWORD g_main_thread_id = GetCurrentThreadId();
45 ///////////////////////////////////////////////////////////////////////////////
47 ///////////////////////////////////////////////////////////////////////////////
49 static const UINT g_msgBoxFlags = MB_TOPMOST | MB_TASKMODAL | MB_SETFOREGROUND;
51 void MUtils::OS::system_message_nfo(const wchar_t *const title, const wchar_t *const text)
53 MessageBoxW(NULL, text, title, g_msgBoxFlags | MB_ICONINFORMATION);
56 void MUtils::OS::system_message_wrn(const wchar_t *const title, const wchar_t *const text)
58 MessageBoxW(NULL, text, title, g_msgBoxFlags | MB_ICONWARNING);
61 void MUtils::OS::system_message_err(const wchar_t *const title, const wchar_t *const text)
63 MessageBoxW(NULL, text, title, g_msgBoxFlags | MB_ICONERROR);
66 ///////////////////////////////////////////////////////////////////////////////
67 // OS VERSION DETECTION
68 ///////////////////////////////////////////////////////////////////////////////
70 static bool g_os_version_initialized = false;
71 static MUtils::OS::Version::os_version_t g_os_version_info = MUtils::OS::Version::UNKNOWN_OPSYS;
72 static QReadWriteLock g_os_version_lock;
74 //Maps marketing names to the actual Windows NT versions
77 MUtils::OS::Version::os_version_t version;
78 const char friendlyName[64];
82 { MUtils::OS::Version::WINDOWS_WIN2K, "Windows 2000" }, //2000
83 { MUtils::OS::Version::WINDOWS_WINXP, "Windows XP or Windows XP Media Center Edition" }, //XP
84 { MUtils::OS::Version::WINDOWS_XPX64, "Windows Server 2003 or Windows XP x64" }, //XP_x64
85 { MUtils::OS::Version::WINDOWS_VISTA, "Windows Vista or Windows Server 2008" }, //Vista
86 { MUtils::OS::Version::WINDOWS_WIN70, "Windows 7 or Windows Server 2008 R2" }, //7
87 { MUtils::OS::Version::WINDOWS_WIN80, "Windows 8 or Windows Server 2012" }, //8
88 { MUtils::OS::Version::WINDOWS_WIN81, "Windows 8.1 or Windows Server 2012 R2" }, //8.1
89 { MUtils::OS::Version::WINDOWS_WN100, "Windows 10 or Windows Server 2014 (Preview)" }, //10
90 { MUtils::OS::Version::UNKNOWN_OPSYS, "N/A" }
93 static bool verify_os_version(const DWORD major, const DWORD minor)
95 OSVERSIONINFOEXW osvi;
96 DWORDLONG dwlConditionMask = 0;
98 //Initialize the OSVERSIONINFOEX structure
99 memset(&osvi, 0, sizeof(OSVERSIONINFOEXW));
100 osvi.dwOSVersionInfoSize = sizeof(OSVERSIONINFOEXW);
101 osvi.dwMajorVersion = major;
102 osvi.dwMinorVersion = minor;
103 osvi.dwPlatformId = VER_PLATFORM_WIN32_NT;
105 //Initialize the condition mask
106 VER_SET_CONDITION(dwlConditionMask, VER_MAJORVERSION, VER_GREATER_EQUAL);
107 VER_SET_CONDITION(dwlConditionMask, VER_MINORVERSION, VER_GREATER_EQUAL);
108 VER_SET_CONDITION(dwlConditionMask, VER_PLATFORMID, VER_EQUAL);
111 const BOOL ret = VerifyVersionInfoW(&osvi, VER_MAJORVERSION | VER_MINORVERSION | VER_PLATFORMID, dwlConditionMask);
116 if(GetLastError() != ERROR_OLD_WIN_VERSION)
118 qWarning("VerifyVersionInfo() system call has failed!");
122 return (ret != FALSE);
125 static bool get_real_os_version(unsigned int *major, unsigned int *minor, bool *pbOverride)
130 //Initialize local variables
131 OSVERSIONINFOEXW osvi;
132 memset(&osvi, 0, sizeof(OSVERSIONINFOEXW));
133 osvi.dwOSVersionInfoSize = sizeof(OSVERSIONINFOEXW);
135 //Try GetVersionEx() first
136 if(GetVersionExW((LPOSVERSIONINFOW)&osvi) == FALSE)
138 qWarning("GetVersionEx() has failed, cannot detect Windows version!");
142 //Make sure we are running on NT
143 if(osvi.dwPlatformId == VER_PLATFORM_WIN32_NT)
145 *major = osvi.dwMajorVersion;
146 *minor = osvi.dwMinorVersion;
150 qWarning("Not running on Windows NT, unsupported operating system!");
154 //Determine the real *major* version first
157 const DWORD nextMajor = (*major) + 1;
158 if(verify_os_version(nextMajor, 0))
168 //Now also determine the real *minor* version
171 const DWORD nextMinor = (*minor) + 1;
172 if(verify_os_version((*major), nextMinor))
184 const MUtils::OS::Version::os_version_t &MUtils::OS::os_version(void)
186 QReadLocker readLock(&g_os_version_lock);
188 //Already initialized?
189 if(g_os_version_initialized)
191 return g_os_version_info;
195 QWriteLocker writeLock(&g_os_version_lock);
198 if(g_os_version_initialized)
200 return g_os_version_info;
204 unsigned int major, minor; bool overrideFlg;
205 if(get_real_os_version(&major, &minor, &overrideFlg))
207 g_os_version_info.type = Version::OS_WINDOWS;
208 g_os_version_info.versionMajor = major;
209 g_os_version_info.versionMinor = minor;
210 g_os_version_info.overrideFlag = overrideFlg;
214 qWarning("Failed to determin the operating system version!");
217 g_os_version_initialized = true;
218 return g_os_version_info;
221 const char *MUtils::OS::os_friendly_name(const MUtils::OS::Version::os_version_t &os_version)
223 for(size_t i = 0; g_os_version_lut[i].version != MUtils::OS::Version::UNKNOWN_OPSYS; i++)
225 if(os_version == g_os_version_lut[i].version)
227 return g_os_version_lut[i].friendlyName;
234 ///////////////////////////////////////////////////////////////////////////////
236 ///////////////////////////////////////////////////////////////////////////////
238 typedef QMap<size_t, QString> KFMap;
239 typedef HRESULT (WINAPI *SHGetKnownFolderPath_t)(const GUID &rfid, DWORD dwFlags, HANDLE hToken, PWSTR *ppszPath);
240 typedef HRESULT (WINAPI *SHGetFolderPath_t)(HWND hwndOwner, int nFolder, HANDLE hToken, DWORD dwFlags, LPWSTR pszPath);
242 static QScopedPointer<KFMap> g_known_folders_map;
243 static SHGetKnownFolderPath_t g_known_folders_fpGetKnownFolderPath;
244 static SHGetFolderPath_t g_known_folders_fpGetFolderPath;
245 static QReadWriteLock g_known_folders_lock;
247 const QString &MUtils::OS::known_folder(known_folder_t folder_id)
249 static const int CSIDL_FLAG_CREATE = 0x8000;
250 typedef enum { KF_FLAG_CREATE = 0x00008000 } kf_flags_t;
259 { 0x001c, {0xF1B32785,0x6FBA,0x4FCF,{0x9D,0x55,0x7B,0x8E,0x7F,0x15,0x70,0x91}} }, //CSIDL_LOCAL_APPDATA
260 { 0x0026, {0x905e63b6,0xc1bf,0x494e,{0xb2,0x9c,0x65,0xb7,0x32,0xd3,0xd2,0x1a}} }, //CSIDL_PROGRAM_FILES
261 { 0x0024, {0xF38BF404,0x1D43,0x42F2,{0x93,0x05,0x67,0xDE,0x0B,0x28,0xFC,0x23}} }, //CSIDL_WINDOWS_FOLDER
262 { 0x0025, {0x1AC14E77,0x02E7,0x4E5D,{0xB7,0x44,0x2E,0xB1,0xAE,0x51,0x98,0xB7}} }, //CSIDL_SYSTEM_FOLDER
265 size_t folderId = size_t(-1);
269 case FOLDER_LOCALAPPDATA: folderId = 0; break;
270 case FOLDER_PROGRAMFILES: folderId = 1; break;
271 case FOLDER_SYSTROOT_DIR: folderId = 2; break;
272 case FOLDER_SYSTEMFOLDER: folderId = 3; break;
275 if(folderId == size_t(-1))
277 qWarning("Invalid 'known' folder was requested!");
278 return *reinterpret_cast<QString*>(NULL);
281 QReadLocker readLock(&g_known_folders_lock);
284 if(!g_known_folders_map.isNull())
286 if(g_known_folders_map->contains(folderId))
288 return g_known_folders_map->operator[](folderId);
292 //Obtain write lock to initialize
294 QWriteLocker writeLock(&g_known_folders_lock);
296 //Still not in cache?
297 if(!g_known_folders_map.isNull())
299 if(g_known_folders_map->contains(folderId))
301 return g_known_folders_map->operator[](folderId);
305 //Initialize on first call
306 if(g_known_folders_map.isNull())
308 QLibrary shell32("shell32.dll");
311 g_known_folders_fpGetFolderPath = (SHGetFolderPath_t) shell32.resolve("SHGetFolderPathW");
312 g_known_folders_fpGetKnownFolderPath = (SHGetKnownFolderPath_t) shell32.resolve("SHGetKnownFolderPath");
314 g_known_folders_map.reset(new QMap<size_t, QString>());
319 //Now try to get the folder path!
320 if(g_known_folders_fpGetKnownFolderPath)
323 if(g_known_folders_fpGetKnownFolderPath(s_folders[folderId].guid, KF_FLAG_CREATE, NULL, &path) == S_OK)
325 //MessageBoxW(0, path, L"SHGetKnownFolderPath", MB_TOPMOST);
326 QDir folderTemp = QDir(QDir::fromNativeSeparators(MUTILS_QSTR(path)));
327 if(folderTemp.exists())
329 folderPath = folderTemp.canonicalPath();
334 else if(g_known_folders_fpGetFolderPath)
336 QScopedArrayPointer<WCHAR> path(new WCHAR[4096]);
337 if(g_known_folders_fpGetFolderPath(NULL, s_folders[folderId].csidl | CSIDL_FLAG_CREATE, NULL, NULL, path.data()) == S_OK)
339 //MessageBoxW(0, path, L"SHGetFolderPathW", MB_TOPMOST);
340 QDir folderTemp = QDir(QDir::fromNativeSeparators(MUTILS_QSTR(path.data())));
341 if(folderTemp.exists())
343 folderPath = folderTemp.canonicalPath();
349 g_known_folders_map->insert(folderId, folderPath);
350 return g_known_folders_map->operator[](folderId);
353 ///////////////////////////////////////////////////////////////////////////////
354 // CURRENT DATA (SAFE)
355 ///////////////////////////////////////////////////////////////////////////////
357 QDate MUtils::OS::current_date(void)
359 const DWORD MAX_PROC = 1024;
360 QScopedArrayPointer<DWORD> processes(new DWORD[MAX_PROC]);
361 DWORD bytesReturned = 0;
363 if(!EnumProcesses(processes.data(), sizeof(DWORD) * MAX_PROC, &bytesReturned))
365 return QDate::currentDate();
368 const DWORD procCount = bytesReturned / sizeof(DWORD);
369 ULARGE_INTEGER lastStartTime;
370 memset(&lastStartTime, 0, sizeof(ULARGE_INTEGER));
372 for(DWORD i = 0; i < procCount; i++)
374 if(HANDLE hProc = OpenProcess(PROCESS_QUERY_INFORMATION, FALSE, processes[i]))
376 FILETIME processTime[4];
377 if(GetProcessTimes(hProc, &processTime[0], &processTime[1], &processTime[2], &processTime[3]))
379 ULARGE_INTEGER timeCreation;
380 timeCreation.LowPart = processTime[0].dwLowDateTime;
381 timeCreation.HighPart = processTime[0].dwHighDateTime;
382 if(timeCreation.QuadPart > lastStartTime.QuadPart)
384 lastStartTime.QuadPart = timeCreation.QuadPart;
391 FILETIME lastStartTime_fileTime;
392 lastStartTime_fileTime.dwHighDateTime = lastStartTime.HighPart;
393 lastStartTime_fileTime.dwLowDateTime = lastStartTime.LowPart;
395 FILETIME lastStartTime_localTime;
396 if(!FileTimeToLocalFileTime(&lastStartTime_fileTime, &lastStartTime_localTime))
398 memcpy(&lastStartTime_localTime, &lastStartTime_fileTime, sizeof(FILETIME));
401 SYSTEMTIME lastStartTime_system;
402 if(!FileTimeToSystemTime(&lastStartTime_localTime, &lastStartTime_system))
404 memset(&lastStartTime_system, 0, sizeof(SYSTEMTIME));
405 lastStartTime_system.wYear = 1970; lastStartTime_system.wMonth = lastStartTime_system.wDay = 1;
408 const QDate currentDate = QDate::currentDate();
409 const QDate processDate = QDate(lastStartTime_system.wYear, lastStartTime_system.wMonth, lastStartTime_system.wDay);
410 return (currentDate >= processDate) ? currentDate : processDate;
413 ///////////////////////////////////////////////////////////////////////////////
415 ///////////////////////////////////////////////////////////////////////////////
417 int MUtils::OS::network_status(void)
420 const BOOL ret = IsNetworkAlive(&dwFlags);
421 if(GetLastError() == 0)
423 return (ret != FALSE) ? NETWORK_TYPE_YES : NETWORK_TYPE_NON;
425 return NETWORK_TYPE_ERR;
428 ///////////////////////////////////////////////////////////////////////////////
430 ///////////////////////////////////////////////////////////////////////////////
432 static MUtils::Internal::CriticalSection g_fatal_exit_lock;
433 static volatile bool g_fatal_exit_flag = true;
435 static DWORD WINAPI fatal_exit_helper(LPVOID lpParameter)
437 MUtils::OS::system_message_err((LPWSTR) lpParameter, L"GURU MEDITATION");
441 void MUtils::OS::fatal_exit(const wchar_t* const errorMessage)
443 g_fatal_exit_lock.enter();
445 if(!g_fatal_exit_flag)
447 return; /*prevent recursive invocation*/
450 g_fatal_exit_flag = false;
452 if(g_main_thread_id != GetCurrentThreadId())
454 if(HANDLE hThreadMain = OpenThread(THREAD_SUSPEND_RESUME, FALSE, g_main_thread_id))
456 SuspendThread(hThreadMain); /*stop main thread*/
460 if(HANDLE hThread = CreateThread(NULL, 0, fatal_exit_helper, (LPVOID) errorMessage, 0, NULL))
462 WaitForSingleObject(hThread, INFINITE);
467 TerminateProcess(GetCurrentProcess(), 666);
471 ///////////////////////////////////////////////////////////////////////////////