Fixed "mailto:" links in about dialog box.
[LameXP.git] / src / Global_Win32.cpp
blob374fd7b6e359f2e40f0cc7c895b742a501ed124f
1 ///////////////////////////////////////////////////////////////////////////////
2 // LameXP - Audio Encoder Front-End
3 // Copyright (C) 2004-2014 LoRd_MuldeR <MuldeR2@GMX.de>
4 //
5 // This program is free software; you can redistribute it and/or modify
6 // it under the terms of the GNU General Public License as published by
7 // the Free Software Foundation; either version 2 of the License, or
8 // (at your option) any later version, but always including the *additional*
9 // restrictions defined in the "License.txt" file.
11 // This program is distributed in the hope that it will be useful,
12 // but WITHOUT ANY WARRANTY; without even the implied warranty of
13 // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
14 // GNU General Public License for more details.
16 // You should have received a copy of the GNU General Public License along
17 // with this program; if not, write to the Free Software Foundation, Inc.,
18 // 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
20 // http://www.gnu.org/licenses/gpl-2.0.txt
21 ///////////////////////////////////////////////////////////////////////////////
23 #include "Global.h"
25 //Target version
26 #include "Targetver.h"
28 //Visual Leaks Detector
29 #include <vld.h>
31 //Windows includes
32 #define NOMINMAX
33 #define WIN32_LEAN_AND_MEAN
34 #include <Windows.h>
35 #include <MMSystem.h>
36 #include <ShellAPI.h>
37 #include <SensAPI.h>
38 #include <Objbase.h>
39 #include <PowrProf.h>
40 #include <Psapi.h>
41 #include <dwmapi.h>
43 //Qt includes
44 #include <QApplication>
45 #include <QDate>
46 #include <QDir>
47 #include <QEvent>
48 #include <QIcon>
49 #include <QImageReader>
50 #include <QLibrary>
51 #include <QLibraryInfo>
52 #include <QMap>
53 #include <QMessageBox>
54 #include <QMutex>
55 #include <QPlastiqueStyle>
56 #include <QProcess>
57 #include <QReadWriteLock>
58 #include <QRegExp>
59 #include <QSysInfo>
60 #include <QTextCodec>
61 #include <QTimer>
62 #include <QTranslator>
63 #include <QUuid>
64 #include <QResource>
66 //LameXP includes
67 #define LAMEXP_INC_CONFIG
68 #include "Resource.h"
69 #include "Config.h"
71 //CRT includes
72 #include <cstdio>
73 #include <iostream>
74 #include <fstream>
75 #include <io.h>
76 #include <fcntl.h>
77 #include <intrin.h>
78 #include <cmath>
79 #include <ctime>
80 #include <process.h>
81 #include <csignal>
83 //Initialize static Qt plugins
84 #ifdef QT_NODLL
85 #if QT_VERSION < QT_VERSION_CHECK(5,0,0)
86 Q_IMPORT_PLUGIN(qico)
87 Q_IMPORT_PLUGIN(qsvg)
88 #else
89 Q_IMPORT_PLUGIN(QWindowsIntegrationPlugin)
90 Q_IMPORT_PLUGIN(QICOPlugin)
91 #endif
92 #endif
94 ///////////////////////////////////////////////////////////////////////////////
95 // HELPER MACROS
96 ///////////////////////////////////////////////////////////////////////////////
98 #define _LAMEXP_MAKE_STR(STR) #STR
99 #define LAMEXP_MAKE_STR(STR) _LAMEXP_MAKE_STR(STR)
101 //String helper
102 #define CLEAN_OUTPUT_STRING(STR) do \
104 const char CTRL_CHARS[3] = { '\r', '\n', '\t' }; \
105 for(size_t i = 0; i < 3; i++) \
107 while(char *pos = strchr((STR), CTRL_CHARS[i])) *pos = char(0x20); \
110 while(0)
112 //String helper
113 #define TRIM_LEFT(STR) do \
115 const char WHITE_SPACE[4] = { char(0x20), '\r', '\n', '\t' }; \
116 for(size_t i = 0; i < 4; i++) \
118 while(*(STR) == WHITE_SPACE[i]) (STR)++; \
121 while(0)
123 ///////////////////////////////////////////////////////////////////////////////
124 // GLOBAL TYPES
125 ///////////////////////////////////////////////////////////////////////////////
127 typedef HRESULT (WINAPI *SHGetKnownFolderPath_t)(const GUID &rfid, DWORD dwFlags, HANDLE hToken, PWSTR *ppszPath);
128 typedef HRESULT (WINAPI *SHGetFolderPath_t)(HWND hwndOwner, int nFolder, HANDLE hToken, DWORD dwFlags, LPWSTR pszPath);
130 ///////////////////////////////////////////////////////////////////////////////
131 // GLOBAL VARS
132 ///////////////////////////////////////////////////////////////////////////////
134 //Console attached flag
135 static bool g_lamexp_console_attached = false;
137 //Special folders
138 static struct
140 QMap<size_t, QString> *knownFolders;
141 SHGetKnownFolderPath_t getKnownFolderPath;
142 SHGetFolderPath_t getFolderPath;
143 QReadWriteLock lock;
145 g_lamexp_known_folder;
147 //CLI Arguments
148 static struct
150 QStringList *list;
151 QReadWriteLock lock;
153 g_lamexp_argv;
155 //OS Version
156 static struct
158 bool bInitialized;
159 lamexp_os_version_t version;
160 QReadWriteLock lock;
162 g_lamexp_os_version;
164 //Wine detection
165 static struct
167 bool bInitialized;
168 bool bIsWine;
169 QReadWriteLock lock;
171 g_lamexp_wine;
173 //Win32 Theme support
174 static struct
176 bool bInitialized;
177 bool bThemesEnabled;
178 QReadWriteLock lock;
180 g_lamexp_themes_enabled;
182 //Win32 DWM API functions
183 static struct
185 bool bInitialized;
186 HRESULT (__stdcall *dwmIsCompositionEnabled)(BOOL *bEnabled);
187 HRESULT (__stdcall *dwmExtendFrameIntoClientArea)(HWND hWnd, const MARGINS* pMarInset);
188 HRESULT (__stdcall *dwmEnableBlurBehindWindow)(HWND hWnd, const DWM_BLURBEHIND* pBlurBehind);
189 QLibrary *dwmapi_dll;
190 QReadWriteLock lock;
192 g_lamexp_dwmapi;
194 //Sound file cache
195 static struct
197 QHash<const QString, const unsigned char*> *sound_db;
198 QReadWriteLock lock;
200 g_lamexp_sounds;
202 //Image formats
203 static const char *g_lamexp_imageformats[] = {"bmp", "png", "jpg", "gif", "ico", "xpm", NULL}; //"svg"
205 //Global locks
206 static QMutex g_lamexp_message_mutex;
208 //Main thread ID
209 static const DWORD g_main_thread_id = GetCurrentThreadId();
211 //Log file
212 static FILE *g_lamexp_log_file = NULL;
214 //Localization
215 const char* LAMEXP_DEFAULT_LANGID = "en";
216 const char* LAMEXP_DEFAULT_TRANSLATION = "LameXP_EN.qm";
218 //Known Windows versions - maps marketing names to the actual Windows NT versions
219 const lamexp_os_version_t lamexp_winver_win2k = {5,0};
220 const lamexp_os_version_t lamexp_winver_winxp = {5,1};
221 const lamexp_os_version_t lamexp_winver_xpx64 = {5,2};
222 const lamexp_os_version_t lamexp_winver_vista = {6,0};
223 const lamexp_os_version_t lamexp_winver_win70 = {6,1};
224 const lamexp_os_version_t lamexp_winver_win80 = {6,2};
225 const lamexp_os_version_t lamexp_winver_win81 = {6,3};
227 //GURU MEDITATION
228 static const char *GURU_MEDITATION = "\n\nGURU MEDITATION !!!\n\n";
230 ///////////////////////////////////////////////////////////////////////////////
231 // GLOBAL FUNCTIONS
232 ///////////////////////////////////////////////////////////////////////////////
235 * Verify a specific Windows version
237 static bool lamexp_verify_os_version(const DWORD major, const DWORD minor)
239 OSVERSIONINFOEXW osvi;
240 DWORDLONG dwlConditionMask = 0;
242 //Initialize the OSVERSIONINFOEX structure
243 memset(&osvi, 0, sizeof(OSVERSIONINFOEXW));
244 osvi.dwOSVersionInfoSize = sizeof(OSVERSIONINFOEXW);
245 osvi.dwMajorVersion = major;
246 osvi.dwMinorVersion = minor;
247 osvi.dwPlatformId = VER_PLATFORM_WIN32_NT;
249 //Initialize the condition mask
250 VER_SET_CONDITION(dwlConditionMask, VER_MAJORVERSION, VER_GREATER_EQUAL);
251 VER_SET_CONDITION(dwlConditionMask, VER_MINORVERSION, VER_GREATER_EQUAL);
252 VER_SET_CONDITION(dwlConditionMask, VER_PLATFORMID, VER_EQUAL);
254 // Perform the test
255 const BOOL ret = VerifyVersionInfoW(&osvi, VER_MAJORVERSION | VER_MINORVERSION | VER_PLATFORMID, dwlConditionMask);
257 //Error checking
258 if(!ret)
260 if(GetLastError() != ERROR_OLD_WIN_VERSION)
262 qWarning("VerifyVersionInfo() system call has failed!");
266 return (ret != FALSE);
270 * Determine the *real* Windows version
272 static bool lamexp_get_real_os_version(unsigned int *major, unsigned int *minor, bool *pbOverride)
274 *major = *minor = 0;
275 *pbOverride = false;
277 //Initialize local variables
278 OSVERSIONINFOEXW osvi;
279 memset(&osvi, 0, sizeof(OSVERSIONINFOEXW));
280 osvi.dwOSVersionInfoSize = sizeof(OSVERSIONINFOEXW);
282 //Try GetVersionEx() first
283 if(GetVersionExW((LPOSVERSIONINFOW)&osvi) == FALSE)
285 qWarning("GetVersionEx() has failed, cannot detect Windows version!");
286 return false;
289 //Make sure we are running on NT
290 if(osvi.dwPlatformId == VER_PLATFORM_WIN32_NT)
292 *major = osvi.dwMajorVersion;
293 *minor = osvi.dwMinorVersion;
295 else
297 qWarning("Not running on Windows NT, unsupported operating system!");
298 return false;
301 //Determine the real *major* version first
302 forever
304 const DWORD nextMajor = (*major) + 1;
305 if(lamexp_verify_os_version(nextMajor, 0))
307 *pbOverride = true;
308 *major = nextMajor;
309 *minor = 0;
310 continue;
312 break;
315 //Now also determine the real *minor* version
316 forever
318 const DWORD nextMinor = (*minor) + 1;
319 if(lamexp_verify_os_version((*major), nextMinor))
321 *pbOverride = true;
322 *minor = nextMinor;
323 continue;
325 break;
328 return true;
332 * Get the native operating system version
334 const lamexp_os_version_t &lamexp_get_os_version(void)
336 QReadLocker readLock(&g_lamexp_os_version.lock);
338 //Already initialized?
339 if(g_lamexp_os_version.bInitialized)
341 return g_lamexp_os_version.version;
344 readLock.unlock();
345 QWriteLocker writeLock(&g_lamexp_os_version.lock);
347 //Detect OS version
348 if(!g_lamexp_os_version.bInitialized)
350 unsigned int major, minor; bool oflag;
351 if(lamexp_get_real_os_version(&major, &minor, &oflag))
353 g_lamexp_os_version.version.versionMajor = major;
354 g_lamexp_os_version.version.versionMinor = minor;
355 g_lamexp_os_version.version.overrideFlag = oflag;
356 g_lamexp_os_version.bInitialized = true;
358 else
360 qWarning("Failed to determin the operating system version!");
364 return g_lamexp_os_version.version;
368 * Check if we are running under wine
370 bool lamexp_detect_wine(void)
372 QReadLocker readLock(&g_lamexp_wine.lock);
374 //Already initialized?
375 if(g_lamexp_wine.bInitialized)
377 return g_lamexp_wine.bIsWine;
380 readLock.unlock();
381 QWriteLocker writeLock(&g_lamexp_wine.lock);
383 if(!g_lamexp_wine.bInitialized)
385 g_lamexp_wine.bIsWine = false;
386 QLibrary ntdll("ntdll.dll");
387 if(ntdll.load())
389 if(ntdll.resolve("wine_nt_to_unix_file_name") != NULL) g_lamexp_wine.bIsWine = true;
390 if(ntdll.resolve("wine_get_version") != NULL) g_lamexp_wine.bIsWine = true;
391 ntdll.unload();
393 g_lamexp_wine.bInitialized = true;
396 return g_lamexp_wine.bIsWine;
400 * Change console text color
402 static void lamexp_console_color(FILE* file, WORD attributes)
404 const HANDLE hConsole = (HANDLE)(_get_osfhandle(_fileno(file)));
405 if((hConsole != NULL) && (hConsole != INVALID_HANDLE_VALUE))
407 SetConsoleTextAttribute(hConsole, attributes);
412 * Output logging message to console
414 static void lamexp_write_console(const int type, const char *msg)
416 __try
418 if(_isatty(_fileno(stderr)))
420 UINT oldOutputCP = GetConsoleOutputCP();
421 if(oldOutputCP != CP_UTF8) SetConsoleOutputCP(CP_UTF8);
423 switch(type)
425 case QtCriticalMsg:
426 case QtFatalMsg:
427 lamexp_console_color(stderr, FOREGROUND_RED | FOREGROUND_INTENSITY);
428 fprintf(stderr, GURU_MEDITATION);
429 fprintf(stderr, "%s\n", msg);
430 fflush(stderr);
431 break;
432 case QtWarningMsg:
433 lamexp_console_color(stderr, FOREGROUND_GREEN | FOREGROUND_RED | FOREGROUND_INTENSITY);
434 fprintf(stderr, "%s\n", msg);
435 fflush(stderr);
436 break;
437 default:
438 lamexp_console_color(stderr, FOREGROUND_BLUE | FOREGROUND_GREEN | FOREGROUND_RED | FOREGROUND_INTENSITY);
439 fprintf(stderr, "%s\n", msg);
440 fflush(stderr);
441 break;
444 lamexp_console_color(stderr, FOREGROUND_BLUE | FOREGROUND_GREEN | FOREGROUND_RED);
445 if(oldOutputCP != CP_UTF8) SetConsoleOutputCP(oldOutputCP);
448 __except(1)
450 /*ignore any exception that might occur here!*/
455 * Output logging message to debugger
457 static void lamexp_write_dbg_out(const int type, const char *msg)
459 const char *FORMAT = "[LameXP][%c] %s\n";
461 __try
463 char buffer[512];
464 const char* input = msg;
465 TRIM_LEFT(input);
467 switch(type)
469 case QtCriticalMsg:
470 case QtFatalMsg:
471 _snprintf_s(buffer, 512, _TRUNCATE, FORMAT, 'C', input);
472 break;
473 case QtWarningMsg:
474 _snprintf_s(buffer, 512, _TRUNCATE, FORMAT, 'W', input);
475 break;
476 default:
477 _snprintf_s(buffer, 512, _TRUNCATE, FORMAT, 'I', input);
478 break;
481 char *temp = &buffer[0];
482 CLEAN_OUTPUT_STRING(temp);
483 OutputDebugStringA(temp);
485 __except(1)
487 /*ignore any exception that might occur here!*/
492 * Output logging message to logfile
494 static void lamexp_write_logfile(const int type, const char *msg)
496 const char *FORMAT = "[%c][%04u] %s\r\n";
498 __try
500 if(g_lamexp_log_file)
502 char buffer[512];
503 strncpy_s(buffer, 512, msg, _TRUNCATE);
505 char *temp = &buffer[0];
506 TRIM_LEFT(temp);
507 CLEAN_OUTPUT_STRING(temp);
509 const unsigned int timestamp = static_cast<unsigned int>(_time64(NULL) % 3600I64);
511 switch(type)
513 case QtCriticalMsg:
514 case QtFatalMsg:
515 fprintf(g_lamexp_log_file, FORMAT, 'C', timestamp, temp);
516 break;
517 case QtWarningMsg:
518 fprintf(g_lamexp_log_file, FORMAT, 'W', timestamp, temp);
519 break;
520 default:
521 fprintf(g_lamexp_log_file, FORMAT, 'I', timestamp, temp);
522 break;
525 fflush(g_lamexp_log_file);
528 __except(1)
530 /*ignore any exception that might occur here!*/
535 * Qt message handler
537 void lamexp_message_handler(QtMsgType type, const char *msg)
539 if((!msg) || (!(msg[0])))
541 return;
544 QMutexLocker lock(&g_lamexp_message_mutex);
546 if(g_lamexp_log_file)
548 lamexp_write_logfile(type, msg);
551 if(g_lamexp_console_attached)
553 lamexp_write_console(type, msg);
555 else
557 lamexp_write_dbg_out(type, msg);
560 if((type == QtCriticalMsg) || (type == QtFatalMsg))
562 lock.unlock();
563 lamexp_fatal_exit(L"The application has encountered a critical error and will exit now!", QWCHAR(QString::fromUtf8(msg)));
568 * Invalid parameters handler
570 static void lamexp_invalid_param_handler(const wchar_t* exp, const wchar_t* fun, const wchar_t* fil, unsigned int, uintptr_t)
572 lamexp_fatal_exit(L"Invalid parameter handler invoked, application will exit!");
576 * Signal handler
578 static void lamexp_signal_handler(int signal_num)
580 signal(signal_num, lamexp_signal_handler);
581 lamexp_fatal_exit(L"Signal handler invoked, application will exit!");
585 * Global exception handler
587 static LONG WINAPI lamexp_exception_handler(struct _EXCEPTION_POINTERS *ExceptionInfo)
589 lamexp_fatal_exit(L"Unhandeled exception handler invoked, application will exit!");
590 return LONG_MAX;
594 * Initialize error handlers
596 void lamexp_init_error_handlers(void)
598 SetErrorMode(SEM_FAILCRITICALERRORS | SEM_NOOPENFILEERRORBOX);
599 SetUnhandledExceptionFilter(lamexp_exception_handler);
600 SetThreadPriority(GetCurrentThread(), THREAD_PRIORITY_ABOVE_NORMAL);
601 _set_invalid_parameter_handler(lamexp_invalid_param_handler);
603 static const int signal_num[6] = { SIGABRT, SIGFPE, SIGILL, SIGINT, SIGSEGV, SIGTERM };
605 for(size_t i = 0; i < 6; i++)
607 signal(signal_num[i], lamexp_signal_handler);
612 * Initialize the console
614 void lamexp_init_console(const QStringList &argv)
616 bool enableConsole = (LAMEXP_DEBUG) || ((VER_LAMEXP_CONSOLE_ENABLED) && lamexp_version_demo());
618 if(_environ)
620 wchar_t *logfile = NULL;
621 size_t logfile_len = 0;
622 if(!_wdupenv_s(&logfile, &logfile_len, L"LAMEXP_LOGFILE"))
624 if(logfile && (logfile_len > 0))
626 FILE *temp = NULL;
627 if(!_wfopen_s(&temp, logfile, L"wb"))
629 fprintf(temp, "%c%c%c", char(0xEF), char(0xBB), char(0xBF));
630 g_lamexp_log_file = temp;
632 free(logfile);
637 if(!LAMEXP_DEBUG)
639 for(int i = 0; i < argv.count(); i++)
641 if(!argv.at(i).compare("--console", Qt::CaseInsensitive))
643 enableConsole = true;
645 else if(!argv.at(i).compare("--no-console", Qt::CaseInsensitive))
647 enableConsole = false;
652 if(enableConsole)
654 if(!g_lamexp_console_attached)
656 if(AllocConsole() != FALSE)
658 SetConsoleCtrlHandler(NULL, TRUE);
659 SetConsoleTitle(L"LameXP - Audio Encoder Front-End | Debug Console");
660 SetConsoleOutputCP(CP_UTF8);
661 g_lamexp_console_attached = true;
665 if(g_lamexp_console_attached)
667 //-------------------------------------------------------------------
668 //See: http://support.microsoft.com/default.aspx?scid=kb;en-us;105305
669 //-------------------------------------------------------------------
670 const int flags = _O_WRONLY | _O_U8TEXT;
671 int hCrtStdOut = _open_osfhandle((intptr_t) GetStdHandle(STD_OUTPUT_HANDLE), flags);
672 int hCrtStdErr = _open_osfhandle((intptr_t) GetStdHandle(STD_ERROR_HANDLE), flags);
673 FILE *hfStdOut = (hCrtStdOut >= 0) ? _fdopen(hCrtStdOut, "wb") : NULL;
674 FILE *hfStdErr = (hCrtStdErr >= 0) ? _fdopen(hCrtStdErr, "wb") : NULL;
675 if(hfStdOut) { *stdout = *hfStdOut; std::cout.rdbuf(new std::filebuf(hfStdOut)); }
676 if(hfStdErr) { *stderr = *hfStdErr; std::cerr.rdbuf(new std::filebuf(hfStdErr)); }
679 HWND hwndConsole = GetConsoleWindow();
681 if((hwndConsole != NULL) && (hwndConsole != INVALID_HANDLE_VALUE))
683 HMENU hMenu = GetSystemMenu(hwndConsole, 0);
684 EnableMenuItem(hMenu, SC_CLOSE, MF_BYCOMMAND | MF_GRAYED);
685 RemoveMenu(hMenu, SC_CLOSE, MF_BYCOMMAND);
687 SetWindowPos(hwndConsole, HWND_TOP, 0, 0, 0, 0, SWP_NOMOVE|SWP_NOSIZE|SWP_NOZORDER|SWP_FRAMECHANGED);
688 SetWindowLong(hwndConsole, GWL_STYLE, GetWindowLong(hwndConsole, GWL_STYLE) & (~WS_MAXIMIZEBOX) & (~WS_MINIMIZEBOX));
689 SetWindowPos(hwndConsole, HWND_TOP, 0, 0, 0, 0, SWP_NOMOVE|SWP_NOSIZE|SWP_NOZORDER|SWP_FRAMECHANGED);
695 * Detect CPU features
697 lamexp_cpu_t lamexp_detect_cpu_features(const QStringList &argv)
699 typedef BOOL (WINAPI *IsWow64ProcessFun)(__in HANDLE hProcess, __out PBOOL Wow64Process);
701 lamexp_cpu_t features;
702 SYSTEM_INFO systemInfo;
703 int CPUInfo[4] = {-1};
704 char CPUIdentificationString[0x40];
705 char CPUBrandString[0x40];
707 memset(&features, 0, sizeof(lamexp_cpu_t));
708 memset(&systemInfo, 0, sizeof(SYSTEM_INFO));
709 memset(CPUIdentificationString, 0, sizeof(CPUIdentificationString));
710 memset(CPUBrandString, 0, sizeof(CPUBrandString));
712 __cpuid(CPUInfo, 0);
713 memcpy(CPUIdentificationString, &CPUInfo[1], sizeof(int));
714 memcpy(CPUIdentificationString + 4, &CPUInfo[3], sizeof(int));
715 memcpy(CPUIdentificationString + 8, &CPUInfo[2], sizeof(int));
716 features.intel = (_stricmp(CPUIdentificationString, "GenuineIntel") == 0);
717 strncpy_s(features.vendor, 0x40, CPUIdentificationString, _TRUNCATE);
719 if(CPUInfo[0] >= 1)
721 __cpuid(CPUInfo, 1);
722 features.mmx = (CPUInfo[3] & 0x800000) || false;
723 features.sse = (CPUInfo[3] & 0x2000000) || false;
724 features.sse2 = (CPUInfo[3] & 0x4000000) || false;
725 features.ssse3 = (CPUInfo[2] & 0x200) || false;
726 features.sse3 = (CPUInfo[2] & 0x1) || false;
727 features.ssse3 = (CPUInfo[2] & 0x200) || false;
728 features.stepping = CPUInfo[0] & 0xf;
729 features.model = ((CPUInfo[0] >> 4) & 0xf) + (((CPUInfo[0] >> 16) & 0xf) << 4);
730 features.family = ((CPUInfo[0] >> 8) & 0xf) + ((CPUInfo[0] >> 20) & 0xff);
733 __cpuid(CPUInfo, 0x80000000);
734 int nExIds = qMax<int>(qMin<int>(CPUInfo[0], 0x80000004), 0x80000000);
736 for(int i = 0x80000002; i <= nExIds; ++i)
738 __cpuid(CPUInfo, i);
739 switch(i)
741 case 0x80000002:
742 memcpy(CPUBrandString, CPUInfo, sizeof(CPUInfo));
743 break;
744 case 0x80000003:
745 memcpy(CPUBrandString + 16, CPUInfo, sizeof(CPUInfo));
746 break;
747 case 0x80000004:
748 memcpy(CPUBrandString + 32, CPUInfo, sizeof(CPUInfo));
749 break;
753 strncpy_s(features.brand, 0x40, CPUBrandString, _TRUNCATE);
755 if(strlen(features.brand) < 1) strncpy_s(features.brand, 0x40, "Unknown", _TRUNCATE);
756 if(strlen(features.vendor) < 1) strncpy_s(features.vendor, 0x40, "Unknown", _TRUNCATE);
758 #if (!(defined(_M_X64) || defined(_M_IA64)))
759 QLibrary Kernel32Lib("kernel32.dll");
760 if(IsWow64ProcessFun IsWow64ProcessPtr = (IsWow64ProcessFun) Kernel32Lib.resolve("IsWow64Process"))
762 BOOL x64flag = FALSE;
763 if(IsWow64ProcessPtr(GetCurrentProcess(), &x64flag))
765 features.x64 = (x64flag == TRUE);
768 #else
769 features.x64 = true;
770 #endif
772 DWORD_PTR procAffinity, sysAffinity;
773 if(GetProcessAffinityMask(GetCurrentProcess(), &procAffinity, &sysAffinity))
775 for(DWORD_PTR mask = 1; mask; mask <<= 1)
777 features.count += ((sysAffinity & mask) ? (1) : (0));
780 if(features.count < 1)
782 GetNativeSystemInfo(&systemInfo);
783 features.count = qBound(1UL, systemInfo.dwNumberOfProcessors, 64UL);
786 if(argv.count() > 0)
788 bool flag = false;
789 for(int i = 0; i < argv.count(); i++)
791 if(!argv[i].compare("--force-cpu-no-64bit", Qt::CaseInsensitive)) { flag = true; features.x64 = false; }
792 if(!argv[i].compare("--force-cpu-no-sse", Qt::CaseInsensitive)) { flag = true; features.sse = features.sse2 = features.sse3 = features.ssse3 = false; }
793 if(!argv[i].compare("--force-cpu-no-intel", Qt::CaseInsensitive)) { flag = true; features.intel = false; }
795 if(flag) qWarning("CPU flags overwritten by user-defined parameters. Take care!\n");
798 return features;
802 * Check for debugger (detect routine)
804 static __forceinline bool lamexp_check_for_debugger(void)
806 __try
808 CloseHandle((HANDLE)((DWORD_PTR)-3));
810 __except(1)
812 return true;
814 __try
816 __debugbreak();
818 __except(1)
820 return IsDebuggerPresent();
822 return true;
826 * Check for debugger (thread proc)
828 static unsigned int __stdcall lamexp_debug_thread_proc(LPVOID lpParameter)
830 SetThreadPriority(GetCurrentThread(), THREAD_PRIORITY_LOWEST);
831 forever
833 if(lamexp_check_for_debugger())
835 lamexp_fatal_exit(L"Not a debug build. Please unload debugger and try again!");
836 return 666;
838 lamexp_sleep(100);
843 * Check for debugger (startup routine)
845 static HANDLE lamexp_debug_thread_init()
847 if(lamexp_check_for_debugger())
849 lamexp_fatal_exit(L"Not a debug build. Please unload debugger and try again!");
851 const uintptr_t h = _beginthreadex(NULL, 0, lamexp_debug_thread_proc, NULL, 0, NULL);
852 return (HANDLE)(h^0xdeadbeef);
856 * Qt event filter
858 static bool lamexp_event_filter(void *message, long *result)
860 if((!(LAMEXP_DEBUG)) && lamexp_check_for_debugger())
862 lamexp_fatal_exit(L"Not a debug build. Please unload debugger and try again!");
865 switch(reinterpret_cast<MSG*>(message)->message)
867 case WM_QUERYENDSESSION:
868 qWarning("WM_QUERYENDSESSION message received!");
869 *result = lamexp_broadcast(lamexp_event_queryendsession, false) ? TRUE : FALSE;
870 return true;
871 case WM_ENDSESSION:
872 qWarning("WM_ENDSESSION message received!");
873 if(reinterpret_cast<MSG*>(message)->wParam == TRUE)
875 lamexp_broadcast(lamexp_event_endsession, false);
876 if(QApplication *app = reinterpret_cast<QApplication*>(QApplication::instance()))
878 app->closeAllWindows();
879 app->quit();
881 lamexp_finalization();
882 exit(1);
884 *result = 0;
885 return true;
886 default:
887 /*ignore this message and let Qt handle it*/
888 return false;
893 * Check for process elevation
895 static bool lamexp_process_is_elevated(bool *bIsUacEnabled = NULL)
897 bool bIsProcessElevated = false;
898 if(bIsUacEnabled) *bIsUacEnabled = false;
899 HANDLE hToken = NULL;
901 if(OpenProcessToken(GetCurrentProcess(), TOKEN_QUERY, &hToken))
903 TOKEN_ELEVATION_TYPE tokenElevationType;
904 DWORD returnLength;
905 if(GetTokenInformation(hToken, TokenElevationType, &tokenElevationType, sizeof(TOKEN_ELEVATION_TYPE), &returnLength))
907 if(returnLength == sizeof(TOKEN_ELEVATION_TYPE))
909 switch(tokenElevationType)
911 case TokenElevationTypeDefault:
912 qDebug("Process token elevation type: Default -> UAC is disabled.\n");
913 break;
914 case TokenElevationTypeFull:
915 qWarning("Process token elevation type: Full -> potential security risk!\n");
916 bIsProcessElevated = true;
917 if(bIsUacEnabled) *bIsUacEnabled = true;
918 break;
919 case TokenElevationTypeLimited:
920 qDebug("Process token elevation type: Limited -> not elevated.\n");
921 if(bIsUacEnabled) *bIsUacEnabled = true;
922 break;
923 default:
924 qWarning("Unknown tokenElevationType value: %d", tokenElevationType);
925 break;
928 else
930 qWarning("GetTokenInformation() return an unexpected size!");
933 CloseHandle(hToken);
935 else
937 qWarning("Failed to open process token!");
940 return bIsProcessElevated;
944 * Convert QIcon to HICON -> caller is responsible for destroying the HICON!
946 static HICON lamexp_qicon2hicon(const QIcon &icon, const int w, const int h)
948 if(!icon.isNull())
950 QPixmap pixmap = icon.pixmap(w, h);
951 if(!pixmap.isNull())
953 return pixmap.toWinHICON();
956 return NULL;
960 * Initialize Qt framework
962 bool lamexp_init_qt(int argc, char* argv[])
964 static bool qt_initialized = false;
965 typedef BOOL (WINAPI *SetDllDirectoryProc)(WCHAR *lpPathName);
966 const QStringList &arguments = lamexp_arguments();
968 //Don't initialized again, if done already
969 if(qt_initialized)
971 return true;
974 //Secure DLL loading
975 QLibrary kernel32("kernel32.dll");
976 if(kernel32.load())
978 SetDllDirectoryProc pSetDllDirectory = (SetDllDirectoryProc) kernel32.resolve("SetDllDirectoryW");
979 if(pSetDllDirectory != NULL) pSetDllDirectory(L"");
982 //Extract executable name from argv[] array
983 QString executableName = QLatin1String("LameXP.exe");
984 if(arguments.count() > 0)
986 static const char *delimiters = "\\/:?";
987 executableName = arguments[0].trimmed();
988 for(int i = 0; delimiters[i]; i++)
990 int temp = executableName.lastIndexOf(QChar(delimiters[i]));
991 if(temp >= 0) executableName = executableName.mid(temp + 1);
993 executableName = executableName.trimmed();
994 if(executableName.isEmpty())
996 executableName = QLatin1String("LameXP.exe");
1000 //Check Qt version
1001 #ifdef QT_BUILD_KEY
1002 qDebug("Using Qt v%s [%s], %s, %s", qVersion(), QLibraryInfo::buildDate().toString(Qt::ISODate).toLatin1().constData(), (qSharedBuild() ? "DLL" : "Static"), QLibraryInfo::buildKey().toLatin1().constData());
1003 qDebug("Compiled with Qt v%s [%s], %s\n", QT_VERSION_STR, QT_PACKAGEDATE_STR, QT_BUILD_KEY);
1004 if(_stricmp(qVersion(), QT_VERSION_STR))
1006 qFatal("%s", QApplication::tr("Executable '%1' requires Qt v%2, but found Qt v%3.").arg(executableName, QString::fromLatin1(QT_VERSION_STR), QString::fromLatin1(qVersion())).toLatin1().constData());
1007 return false;
1009 if(QLibraryInfo::buildKey().compare(QString::fromLatin1(QT_BUILD_KEY), Qt::CaseInsensitive))
1011 qFatal("%s", QApplication::tr("Executable '%1' was built for Qt '%2', but found Qt '%3'.").arg(executableName, QString::fromLatin1(QT_BUILD_KEY), QLibraryInfo::buildKey()).toLatin1().constData());
1012 return false;
1014 #else
1015 qDebug("Using Qt v%s [%s], %s", qVersion(), QLibraryInfo::buildDate().toString(Qt::ISODate).toLatin1().constData(), (qSharedBuild() ? "DLL" : "Static"));
1016 qDebug("Compiled with Qt v%s [%s]\n", QT_VERSION_STR, QT_PACKAGEDATE_STR);
1017 #endif
1019 //Check the Windows version
1020 const lamexp_os_version_t &osVersionNo = lamexp_get_os_version();
1021 if(osVersionNo < lamexp_winver_winxp)
1023 qFatal("%s", QApplication::tr("Executable '%1' requires Windows XP or later.").arg(executableName).toLatin1().constData());
1026 //Supported Windows version?
1027 if(osVersionNo == lamexp_winver_winxp)
1029 qDebug("Running on Windows XP or Windows XP Media Center Edition.\n"); //lamexp_check_compatibility_mode("GetLargePageMinimum", executableName);
1031 else if(osVersionNo == lamexp_winver_xpx64)
1033 qDebug("Running on Windows Server 2003, Windows Server 2003 R2 or Windows XP x64.\n"); //lamexp_check_compatibility_mode("GetLocaleInfoEx", executableName);
1035 else if(osVersionNo == lamexp_winver_vista)
1037 qDebug("Running on Windows Vista or Windows Server 2008.\n"); //lamexp_check_compatibility_mode("CreateRemoteThreadEx", executableName*/);
1039 else if(osVersionNo == lamexp_winver_win70)
1041 qDebug("Running on Windows 7 or Windows Server 2008 R2.\n"); //lamexp_check_compatibility_mode("CreateFile2", executableName);
1043 else if(osVersionNo == lamexp_winver_win80)
1045 qDebug("Running on Windows 8 or Windows Server 2012.\n"); //lamexp_check_compatibility_mode("FindPackagesByPackageFamily", executableName);
1047 else if(osVersionNo == lamexp_winver_win81)
1049 qDebug("Running on Windows 8.1 or Windows Server 2012 R2.\n"); //lamexp_check_compatibility_mode(NULL, executableName);
1051 else
1053 const QString message = QString().sprintf("Running on an unknown WindowsNT-based system (v%u.%u).", osVersionNo.versionMajor, osVersionNo.versionMinor);
1054 qWarning("%s\n", QUTF8(message));
1055 MessageBoxW(NULL, QWCHAR(message), L"LameXP", MB_OK | MB_TOPMOST | MB_ICONWARNING);
1058 //Check for compat mode
1059 if(osVersionNo.overrideFlag && (osVersionNo <= lamexp_winver_win81))
1061 qWarning("Windows compatibility mode detected!");
1062 if(!arguments.contains("--ignore-compat-mode", Qt::CaseInsensitive))
1064 qFatal("%s", QApplication::tr("Executable '%1' doesn't support Windows compatibility mode.").arg(executableName).toLatin1().constData());
1065 return false;
1069 //Check for Wine
1070 if(lamexp_detect_wine())
1072 qWarning("It appears we are running under Wine, unexpected things might happen!\n");
1075 //Set text Codec for locale
1076 QTextCodec::setCodecForLocale(QTextCodec::codecForName("UTF-8"));
1078 //Create Qt application instance
1079 QApplication *application = new QApplication(argc, argv);
1081 //Load plugins from application directory
1082 QCoreApplication::setLibraryPaths(QStringList() << QApplication::applicationDirPath());
1083 qDebug("Library Path:\n%s\n", QUTF8(QApplication::libraryPaths().first()));
1085 //Set application properties
1086 application->setApplicationName("LameXP - Audio Encoder Front-End");
1087 application->setApplicationVersion(QString().sprintf("%d.%02d.%04d", lamexp_version_major(), lamexp_version_minor(), lamexp_version_build()));
1088 application->setOrganizationName("LoRd_MuldeR");
1089 application->setOrganizationDomain("mulder.at.gg");
1090 application->setWindowIcon(lamexp_app_icon());
1091 application->setEventFilter(lamexp_event_filter);
1093 //Check for supported image formats
1094 QList<QByteArray> supportedFormats = QImageReader::supportedImageFormats();
1095 for(int i = 0; g_lamexp_imageformats[i]; i++)
1097 if(!supportedFormats.contains(g_lamexp_imageformats[i]))
1099 qFatal("Qt initialization error: QImageIOHandler for '%s' missing!", g_lamexp_imageformats[i]);
1100 return false;
1104 //Enable larger/smaller font size
1105 double fontScaleFactor = 1.0;
1106 if(arguments.contains("--huge-font", Qt::CaseInsensitive)) fontScaleFactor = 1.500;
1107 if(arguments.contains("--big-font", Qt::CaseInsensitive)) fontScaleFactor = 1.250;
1108 if(arguments.contains("--small-font", Qt::CaseInsensitive)) fontScaleFactor = 0.875;
1109 if(arguments.contains("--tiny-font", Qt::CaseInsensitive)) fontScaleFactor = 0.750;
1110 if(!qFuzzyCompare(fontScaleFactor, 1.0))
1112 qWarning("Application font scale factor set to: %.3f\n", fontScaleFactor);
1113 QFont appFont = application->font();
1114 appFont.setPointSizeF(appFont.pointSizeF() * fontScaleFactor);
1115 application->setFont(appFont);
1118 //Add the default translations
1119 lamexp_translation_init();
1121 //Check for process elevation
1122 if(lamexp_process_is_elevated() && (!lamexp_detect_wine()))
1124 QMessageBox messageBox(QMessageBox::Warning, "LameXP", "<nobr>LameXP was started with 'elevated' rights, altough LameXP does not need these rights.<br>Running an applications with unnecessary rights is a potential security risk!</nobr>", QMessageBox::NoButton, NULL, Qt::Dialog | Qt::MSWindowsFixedSizeDialogHint | Qt::WindowStaysOnTopHint);
1125 messageBox.addButton("Quit Program (Recommended)", QMessageBox::NoRole);
1126 messageBox.addButton("Ignore", QMessageBox::NoRole);
1127 if(messageBox.exec() == 0)
1129 return false;
1133 //Update console icon, if a console is attached
1134 #if QT_VERSION < QT_VERSION_CHECK(5,0,0)
1135 if(g_lamexp_console_attached && (!lamexp_detect_wine()))
1137 QLibrary kernel32("kernel32.dll");
1138 if(kernel32.load())
1140 typedef DWORD (__stdcall *SetConsoleIconFun)(HICON);
1141 if(SetConsoleIconFun SetConsoleIconPtr = (SetConsoleIconFun) kernel32.resolve("SetConsoleIcon"))
1143 if(HICON hIcon = lamexp_qicon2hicon(QIcon(":/icons/sound.png"), 16, 16))
1145 SetConsoleIconPtr(hIcon);
1146 DestroyIcon(hIcon);
1151 #endif
1153 //Done
1154 qt_initialized = true;
1155 return true;
1158 const QStringList &lamexp_arguments(void)
1160 QReadLocker readLock(&g_lamexp_argv.lock);
1162 if(!g_lamexp_argv.list)
1164 readLock.unlock();
1165 QWriteLocker writeLock(&g_lamexp_argv.lock);
1167 g_lamexp_argv.list = new QStringList;
1169 int nArgs = 0;
1170 LPWSTR *szArglist = CommandLineToArgvW(GetCommandLineW(), &nArgs);
1172 if(NULL != szArglist)
1174 for(int i = 0; i < nArgs; i++)
1176 (*g_lamexp_argv.list) << WCHAR2QSTR(szArglist[i]);
1178 LocalFree(szArglist);
1180 else
1182 qWarning("CommandLineToArgvW() has failed !!!");
1186 return (*g_lamexp_argv.list);
1190 * Locate known folder on local system
1192 const QString &lamexp_known_folder(lamexp_known_folder_t folder_id)
1194 static const int CSIDL_FLAG_CREATE = 0x8000;
1195 typedef enum { KF_FLAG_CREATE = 0x00008000 } kf_flags_t;
1197 struct
1199 const int csidl;
1200 const GUID guid;
1202 static s_folders[] =
1204 { 0x001c, {0xF1B32785,0x6FBA,0x4FCF,{0x9D,0x55,0x7B,0x8E,0x7F,0x15,0x70,0x91}} }, //CSIDL_LOCAL_APPDATA
1205 { 0x0026, {0x905e63b6,0xc1bf,0x494e,{0xb2,0x9c,0x65,0xb7,0x32,0xd3,0xd2,0x1a}} }, //CSIDL_PROGRAM_FILES
1206 { 0x0024, {0xF38BF404,0x1D43,0x42F2,{0x93,0x05,0x67,0xDE,0x0B,0x28,0xFC,0x23}} }, //CSIDL_WINDOWS_FOLDER
1207 { 0x0025, {0x1AC14E77,0x02E7,0x4E5D,{0xB7,0x44,0x2E,0xB1,0xAE,0x51,0x98,0xB7}} }, //CSIDL_SYSTEM_FOLDER
1210 size_t folderId = size_t(-1);
1212 switch(folder_id)
1214 case lamexp_folder_localappdata: folderId = 0; break;
1215 case lamexp_folder_programfiles: folderId = 1; break;
1216 case lamexp_folder_systroot_dir: folderId = 2; break;
1217 case lamexp_folder_systemfolder: folderId = 3; break;
1220 if(folderId == size_t(-1))
1222 qWarning("Invalid 'known' folder was requested!");
1223 return *reinterpret_cast<QString*>(NULL);
1226 QReadLocker readLock(&g_lamexp_known_folder.lock);
1228 //Already in cache?
1229 if(g_lamexp_known_folder.knownFolders)
1231 if(g_lamexp_known_folder.knownFolders->contains(folderId))
1233 return (*g_lamexp_known_folder.knownFolders)[folderId];
1237 //Obtain write lock to initialize
1238 readLock.unlock();
1239 QWriteLocker writeLock(&g_lamexp_known_folder.lock);
1241 //Still not in cache?
1242 if(g_lamexp_known_folder.knownFolders)
1244 if(g_lamexp_known_folder.knownFolders->contains(folderId))
1246 return (*g_lamexp_known_folder.knownFolders)[folderId];
1250 //Initialize on first call
1251 if(!g_lamexp_known_folder.knownFolders)
1253 QLibrary shell32("shell32.dll");
1254 if(shell32.load())
1256 g_lamexp_known_folder.getFolderPath = (SHGetFolderPath_t) shell32.resolve("SHGetFolderPathW");
1257 g_lamexp_known_folder.getKnownFolderPath = (SHGetKnownFolderPath_t) shell32.resolve("SHGetKnownFolderPath");
1259 g_lamexp_known_folder.knownFolders = new QMap<size_t, QString>();
1262 QString folderPath;
1264 //Now try to get the folder path!
1265 if(g_lamexp_known_folder.getKnownFolderPath)
1267 WCHAR *path = NULL;
1268 if(g_lamexp_known_folder.getKnownFolderPath(s_folders[folderId].guid, KF_FLAG_CREATE, NULL, &path) == S_OK)
1270 //MessageBoxW(0, path, L"SHGetKnownFolderPath", MB_TOPMOST);
1271 QDir folderTemp = QDir(QDir::fromNativeSeparators(QString::fromUtf16(reinterpret_cast<const unsigned short*>(path))));
1272 if(folderTemp.exists())
1274 folderPath = folderTemp.canonicalPath();
1276 CoTaskMemFree(path);
1279 else if(g_lamexp_known_folder.getFolderPath)
1281 WCHAR *path = new WCHAR[4096];
1282 if(g_lamexp_known_folder.getFolderPath(NULL, s_folders[folderId].csidl | CSIDL_FLAG_CREATE, NULL, NULL, path) == S_OK)
1284 //MessageBoxW(0, path, L"SHGetFolderPathW", MB_TOPMOST);
1285 QDir folderTemp = QDir(QDir::fromNativeSeparators(QString::fromUtf16(reinterpret_cast<const unsigned short*>(path))));
1286 if(folderTemp.exists())
1288 folderPath = folderTemp.canonicalPath();
1291 LAMEXP_DELETE_ARRAY(path);
1294 //Update cache
1295 g_lamexp_known_folder.knownFolders->insert(folderId, folderPath);
1296 return (*g_lamexp_known_folder.knownFolders)[folderId];
1300 * Safely remove a file
1302 bool lamexp_remove_file(const QString &filename)
1304 if(!QFileInfo(filename).exists() || !QFileInfo(filename).isFile())
1306 return true;
1308 else
1310 if(!QFile::remove(filename))
1312 static const DWORD attrMask = FILE_ATTRIBUTE_READONLY | FILE_ATTRIBUTE_HIDDEN | FILE_ATTRIBUTE_SYSTEM;
1313 const DWORD attributes = GetFileAttributesW(QWCHAR(filename));
1314 if(attributes & attrMask)
1316 SetFileAttributesW(QWCHAR(filename), FILE_ATTRIBUTE_NORMAL);
1318 if(!QFile::remove(filename))
1320 qWarning("Could not delete \"%s\"", filename.toLatin1().constData());
1321 return false;
1323 else
1325 return true;
1328 else
1330 return true;
1336 * Check if visual themes are enabled (WinXP and later)
1338 bool lamexp_themes_enabled(void)
1340 typedef int (WINAPI *IsAppThemedFun)(void);
1342 QReadLocker readLock(&g_lamexp_themes_enabled.lock);
1343 if(g_lamexp_themes_enabled.bInitialized)
1345 return g_lamexp_themes_enabled.bThemesEnabled;
1348 readLock.unlock();
1349 QWriteLocker writeLock(&g_lamexp_themes_enabled.lock);
1351 if(!g_lamexp_themes_enabled.bInitialized)
1353 g_lamexp_themes_enabled.bThemesEnabled = false;
1354 const lamexp_os_version_t &osVersion = lamexp_get_os_version();
1355 if(osVersion >= lamexp_winver_winxp)
1357 IsAppThemedFun IsAppThemedPtr = NULL;
1358 QLibrary uxTheme(QString("%1/UxTheme.dll").arg(lamexp_known_folder(lamexp_folder_systemfolder)));
1359 if(uxTheme.load())
1361 IsAppThemedPtr = (IsAppThemedFun) uxTheme.resolve("IsAppThemed");
1363 if(IsAppThemedPtr)
1365 g_lamexp_themes_enabled.bThemesEnabled = IsAppThemedPtr();
1366 if(!g_lamexp_themes_enabled.bThemesEnabled)
1368 qWarning("Theme support is disabled for this process!");
1372 g_lamexp_themes_enabled.bInitialized = true;
1375 return g_lamexp_themes_enabled.bThemesEnabled;
1379 * Get number of free bytes on disk
1381 unsigned __int64 lamexp_free_diskspace(const QString &path, bool *ok)
1383 ULARGE_INTEGER freeBytesAvailable, totalNumberOfBytes, totalNumberOfFreeBytes;
1384 if(GetDiskFreeSpaceExW(reinterpret_cast<const wchar_t*>(QDir::toNativeSeparators(path).utf16()), &freeBytesAvailable, &totalNumberOfBytes, &totalNumberOfFreeBytes))
1386 if(ok) *ok = true;
1387 return freeBytesAvailable.QuadPart;
1389 else
1391 if(ok) *ok = false;
1392 return 0;
1397 * Check if computer does support hibernation
1399 bool lamexp_is_hibernation_supported(void)
1401 bool hibernationSupported = false;
1403 SYSTEM_POWER_CAPABILITIES pwrCaps;
1404 SecureZeroMemory(&pwrCaps, sizeof(SYSTEM_POWER_CAPABILITIES));
1406 if(GetPwrCapabilities(&pwrCaps))
1408 hibernationSupported = pwrCaps.SystemS4 && pwrCaps.HiberFilePresent;
1411 return hibernationSupported;
1415 * Shutdown the computer
1417 bool lamexp_shutdown_computer(const QString &message, const unsigned long timeout, const bool forceShutdown, const bool hibernate)
1419 HANDLE hToken = NULL;
1421 if(OpenProcessToken(GetCurrentProcess(), TOKEN_ADJUST_PRIVILEGES | TOKEN_QUERY, &hToken))
1423 TOKEN_PRIVILEGES privileges;
1424 memset(&privileges, 0, sizeof(TOKEN_PRIVILEGES));
1425 privileges.PrivilegeCount = 1;
1426 privileges.Privileges[0].Attributes = SE_PRIVILEGE_ENABLED;
1428 if(LookupPrivilegeValue(NULL, SE_SHUTDOWN_NAME, &privileges.Privileges[0].Luid))
1430 if(AdjustTokenPrivileges(hToken, FALSE, &privileges, NULL, NULL, NULL))
1432 if(hibernate)
1434 if(SetSuspendState(TRUE, TRUE, TRUE))
1436 return true;
1439 const DWORD reason = SHTDN_REASON_MAJOR_APPLICATION | SHTDN_REASON_FLAG_PLANNED;
1440 return InitiateSystemShutdownEx(NULL, const_cast<wchar_t*>(QWCHAR(message)), timeout, forceShutdown ? TRUE : FALSE, FALSE, reason);
1445 return false;
1449 * Determines the current date, resistant against certain manipulations
1451 QDate lamexp_current_date_safe(void)
1453 const DWORD MAX_PROC = 1024;
1454 DWORD *processes = new DWORD[MAX_PROC];
1455 DWORD bytesReturned = 0;
1457 if(!EnumProcesses(processes, sizeof(DWORD) * MAX_PROC, &bytesReturned))
1459 LAMEXP_DELETE_ARRAY(processes);
1460 return QDate::currentDate();
1463 const DWORD procCount = bytesReturned / sizeof(DWORD);
1464 ULARGE_INTEGER lastStartTime;
1465 memset(&lastStartTime, 0, sizeof(ULARGE_INTEGER));
1467 for(DWORD i = 0; i < procCount; i++)
1469 HANDLE hProc = OpenProcess(PROCESS_QUERY_INFORMATION, FALSE, processes[i]);
1470 if(hProc)
1472 FILETIME processTime[4];
1473 if(GetProcessTimes(hProc, &processTime[0], &processTime[1], &processTime[2], &processTime[3]))
1475 ULARGE_INTEGER timeCreation;
1476 timeCreation.LowPart = processTime[0].dwLowDateTime;
1477 timeCreation.HighPart = processTime[0].dwHighDateTime;
1478 if(timeCreation.QuadPart > lastStartTime.QuadPart)
1480 lastStartTime.QuadPart = timeCreation.QuadPart;
1483 CloseHandle(hProc);
1487 LAMEXP_DELETE_ARRAY(processes);
1489 FILETIME lastStartTime_fileTime;
1490 lastStartTime_fileTime.dwHighDateTime = lastStartTime.HighPart;
1491 lastStartTime_fileTime.dwLowDateTime = lastStartTime.LowPart;
1493 FILETIME lastStartTime_localTime;
1494 if(!FileTimeToLocalFileTime(&lastStartTime_fileTime, &lastStartTime_localTime))
1496 memcpy(&lastStartTime_localTime, &lastStartTime_fileTime, sizeof(FILETIME));
1499 SYSTEMTIME lastStartTime_system;
1500 if(!FileTimeToSystemTime(&lastStartTime_localTime, &lastStartTime_system))
1502 memset(&lastStartTime_system, 0, sizeof(SYSTEMTIME));
1503 lastStartTime_system.wYear = 1970; lastStartTime_system.wMonth = lastStartTime_system.wDay = 1;
1506 const QDate currentDate = QDate::currentDate();
1507 const QDate processDate = QDate(lastStartTime_system.wYear, lastStartTime_system.wMonth, lastStartTime_system.wDay);
1508 return (currentDate >= processDate) ? currentDate : processDate;
1512 * Show system message box
1514 int lamexp_system_message(const wchar_t *text, int beepType)
1516 UINT flags = MB_OK | MB_TOPMOST;
1518 switch(beepType)
1520 case lamexp_beep_info: flags = flags | MB_ICONASTERISK;
1521 case lamexp_beep_warning: flags = flags | MB_ICONEXCLAMATION;
1522 case lamexp_beep_error: flags = flags | MB_ICONHAND;
1525 return MessageBoxW(NULL, text, L"LameXP", flags);
1529 * Block window "move" message
1531 bool lamexp_block_window_move(void *message)
1533 if(message)
1535 MSG *msg = reinterpret_cast<MSG*>(message);
1536 if((msg->message == WM_SYSCOMMAND) && (msg->wParam == SC_MOVE))
1538 return true;
1540 if((msg->message == WM_NCLBUTTONDOWN) && (msg->wParam == HTCAPTION))
1542 return true;
1545 return false;
1549 * Suspend calling thread for N milliseconds
1551 inline void lamexp_sleep(const unsigned int delay)
1553 Sleep(delay);
1556 bool lamexp_beep(int beepType)
1558 switch(beepType)
1560 case lamexp_beep_info: return MessageBeep(MB_ICONASTERISK) == TRUE; break;
1561 case lamexp_beep_warning: return MessageBeep(MB_ICONEXCLAMATION) == TRUE; break;
1562 case lamexp_beep_error: return MessageBeep(MB_ICONHAND) == TRUE; break;
1563 default: return false;
1568 * Play a sound (from resources)
1570 bool lamexp_play_sound(const QString &name, const bool bAsync)
1572 const unsigned char *data = NULL;
1574 //Try to look-up the sound in the cache first
1575 if(!name.isEmpty())
1577 QReadLocker readLock(&g_lamexp_sounds.lock);
1578 if(g_lamexp_sounds.sound_db && g_lamexp_sounds.sound_db->contains(name))
1580 data = g_lamexp_sounds.sound_db->value(name);
1584 //If data not found in cache, try to load from resource!
1585 if((!data) && (!name.isEmpty()))
1587 QResource resource(QString(":/sounds/%1.wav").arg(name));
1588 if(resource.isValid() && (data = resource.data()))
1590 QWriteLocker writeLock(&g_lamexp_sounds.lock);
1591 if(!g_lamexp_sounds.sound_db)
1593 g_lamexp_sounds.sound_db = new QHash<const QString, const unsigned char*>();
1595 g_lamexp_sounds.sound_db->insert(name, data);
1597 else
1599 qWarning("Sound effect \"%s\" not found!", QUTF8(name));
1603 //Play the sound, if availbale
1604 if(data)
1606 return PlaySound(LPCWSTR(data), NULL, (SND_MEMORY | (bAsync ? SND_ASYNC : SND_SYNC))) != FALSE;
1609 return false;
1613 * Play a sound (system alias)
1615 bool lamexp_play_sound_alias(const QString &alias, const bool bAsync)
1617 return PlaySound(QWCHAR(alias), GetModuleHandle(NULL), (SND_ALIAS | (bAsync ? SND_ASYNC : SND_SYNC))) != FALSE;
1621 * Play a sound (from external DLL)
1623 bool lamexp_play_sound_file(const QString &library, const unsigned short uiSoundIdx, const bool bAsync)
1625 bool result = false;
1627 QFileInfo libraryFile(library);
1628 if(!libraryFile.isAbsolute())
1630 const QString &systemDir = lamexp_known_folder(lamexp_folder_systemfolder);
1631 if(!systemDir.isEmpty())
1633 libraryFile.setFile(QDir(systemDir), libraryFile.fileName());
1637 if(libraryFile.exists() && libraryFile.isFile())
1639 if(HMODULE module = LoadLibraryW(QWCHAR(QDir::toNativeSeparators(libraryFile.canonicalFilePath()))))
1641 result = (PlaySound(MAKEINTRESOURCE(uiSoundIdx), module, (SND_RESOURCE | (bAsync ? SND_ASYNC : SND_SYNC))) != FALSE);
1642 FreeLibrary(module);
1645 else
1647 qWarning("PlaySound: File \"%s\" could not be found!", QUTF8(libraryFile.absoluteFilePath()));
1650 return result;
1654 * Open file using the shell
1656 bool lamexp_exec_shell(const QWidget *win, const QString &url, const bool explore)
1658 return lamexp_exec_shell(win, url, QString(), QString(), explore);
1662 * Open file using the shell (with parameters)
1664 bool lamexp_exec_shell(const QWidget *win, const QString &url, const QString &parameters, const QString &directory, const bool explore)
1666 return ((int) ShellExecuteW(((win) ? win->winId() : NULL), (explore ? L"explore" : L"open"), QWCHAR(url), ((!parameters.isEmpty()) ? QWCHAR(parameters) : NULL), ((!directory.isEmpty()) ? QWCHAR(directory) : NULL), SW_SHOW)) > 32;
1670 * Query value of the performance counter
1672 __int64 lamexp_perfcounter_value(void)
1674 LARGE_INTEGER counter;
1675 if(QueryPerformanceCounter(&counter) == TRUE)
1677 return counter.QuadPart;
1679 return -1;
1683 * Query frequency of the performance counter
1685 __int64 lamexp_perfcounter_frequ(void)
1687 LARGE_INTEGER frequency;
1688 if(QueryPerformanceFrequency(&frequency) == TRUE)
1690 return frequency.QuadPart;
1692 return -1;
1696 * Insert entry to the window's system menu
1698 bool lamexp_append_sysmenu(const QWidget *win, const unsigned int identifier, const QString &text)
1700 bool ok = false;
1702 if(HMENU hMenu = GetSystemMenu(win->winId(), FALSE))
1704 ok = (AppendMenuW(hMenu, MF_SEPARATOR, 0, 0) == TRUE);
1705 ok = (AppendMenuW(hMenu, MF_STRING, identifier, QWCHAR(text)) == TRUE);
1708 return ok;
1712 * Insert entry to the window's system menu
1714 bool lamexp_check_sysmenu_msg(void *message, const unsigned int identifier)
1716 return (((MSG*)message)->message == WM_SYSCOMMAND) && ((((MSG*)message)->wParam & 0xFFF0) == identifier);
1720 * Update system menu entry
1722 bool lamexp_update_sysmenu(const QWidget *win, const unsigned int identifier, const QString &text)
1724 bool ok = false;
1726 if(HMENU hMenu = ::GetSystemMenu(win->winId(), FALSE))
1728 ok = (ModifyMenu(hMenu, identifier, MF_STRING | MF_BYCOMMAND, identifier, QWCHAR(text)) == TRUE);
1730 return ok;
1734 * Display the window's close button
1736 bool lamexp_enable_close_button(const QWidget *win, const bool bEnable)
1738 bool ok = false;
1740 if(HMENU hMenu = GetSystemMenu(win->winId(), FALSE))
1742 ok = (EnableMenuItem(hMenu, SC_CLOSE, MF_BYCOMMAND | (bEnable ? MF_ENABLED : MF_GRAYED)) == TRUE);
1745 return ok;
1749 * Check whether ESC key has been pressed since the previous call to this function
1751 bool lamexp_check_escape_state(void)
1753 return (GetAsyncKeyState(VK_ESCAPE) & 0x0001) != 0;
1757 * Set the process priority class for current process
1759 bool lamexp_change_process_priority(const int priority)
1761 return lamexp_change_process_priority(GetCurrentProcess(), priority);
1765 * Set the process priority class for specified process
1767 bool lamexp_change_process_priority(const QProcess *proc, const int priority)
1769 if(Q_PID qPid = proc->pid())
1771 return lamexp_change_process_priority(qPid->hProcess, priority);
1773 else
1775 return false;
1780 * Set the process priority class for specified process
1782 bool lamexp_change_process_priority(void *hProcess, const int priority)
1784 bool ok = false;
1786 switch(qBound(-2, priority, 2))
1788 case 2:
1789 ok = (SetPriorityClass(hProcess, HIGH_PRIORITY_CLASS) == TRUE);
1790 break;
1791 case 1:
1792 if(!(ok = (SetPriorityClass(hProcess, ABOVE_NORMAL_PRIORITY_CLASS) == TRUE)))
1794 ok = (SetPriorityClass(hProcess, HIGH_PRIORITY_CLASS) == TRUE);
1796 break;
1797 case 0:
1798 ok = (SetPriorityClass(hProcess, NORMAL_PRIORITY_CLASS) == TRUE);
1799 break;
1800 case -1:
1801 if(!(ok = (SetPriorityClass(hProcess, BELOW_NORMAL_PRIORITY_CLASS) == TRUE)))
1803 ok = (SetPriorityClass(hProcess, IDLE_PRIORITY_CLASS) == TRUE);
1805 break;
1806 case -2:
1807 ok = (SetPriorityClass(hProcess, IDLE_PRIORITY_CLASS) == TRUE);
1808 break;
1811 return ok;
1815 * Returns the current file time
1817 unsigned __int64 lamexp_current_file_time(void)
1819 FILETIME fileTime;
1820 GetSystemTimeAsFileTime(&fileTime);
1822 ULARGE_INTEGER temp;
1823 temp.HighPart = fileTime.dwHighDateTime;
1824 temp.LowPart = fileTime.dwLowDateTime;
1826 return temp.QuadPart;
1830 * Bring the specifed window to the front
1832 bool lamexp_bring_to_front(const QWidget *window)
1834 bool ret = false;
1836 if(window)
1838 for(int i = 0; (i < 5) && (!ret); i++)
1840 ret = (SetForegroundWindow(window->winId()) != FALSE);
1841 SwitchToThisWindow(window->winId(), TRUE);
1843 LockSetForegroundWindow(LSFW_LOCK);
1846 return ret;
1850 * Bring window of the specifed process to the front (callback)
1852 static BOOL CALLBACK lamexp_bring_process_to_front_helper(HWND hwnd, LPARAM lParam)
1854 DWORD processId = *reinterpret_cast<WORD*>(lParam);
1855 DWORD windowProcessId = NULL;
1856 GetWindowThreadProcessId(hwnd, &windowProcessId);
1857 if(windowProcessId == processId)
1859 SwitchToThisWindow(hwnd, TRUE);
1860 SetForegroundWindow(hwnd);
1861 return FALSE;
1864 return TRUE;
1868 * Bring window of the specifed process to the front
1870 bool lamexp_bring_process_to_front(const unsigned long pid)
1872 return EnumWindows(lamexp_bring_process_to_front_helper, reinterpret_cast<LPARAM>(&pid)) == TRUE;
1876 * Check the network connectivity status
1878 int lamexp_network_status(void)
1880 DWORD dwFlags;
1881 const BOOL ret = IsNetworkAlive(&dwFlags);
1882 if(GetLastError() == 0)
1884 return (ret != FALSE) ? lamexp_network_yes : lamexp_network_non;
1886 return lamexp_network_err;
1890 * Retrun the process ID of the given QProcess
1892 unsigned long lamexp_process_id(const QProcess *proc)
1894 PROCESS_INFORMATION *procInf = proc->pid();
1895 return (procInf) ? procInf->dwProcessId : NULL;
1899 * Convert long path to short path
1901 QString lamexp_path_to_short(const QString &longPath)
1903 QString shortPath;
1904 DWORD buffSize = GetShortPathNameW(reinterpret_cast<const wchar_t*>(longPath.utf16()), NULL, NULL);
1906 if(buffSize > 0)
1908 wchar_t *buffer = new wchar_t[buffSize];
1909 DWORD result = GetShortPathNameW(reinterpret_cast<const wchar_t*>(longPath.utf16()), buffer, buffSize);
1911 if(result > 0 && result < buffSize)
1913 shortPath = QString::fromUtf16(reinterpret_cast<const unsigned short*>(buffer));
1916 delete[] buffer;
1919 return (shortPath.isEmpty() ? longPath : shortPath);
1923 * Open media file in external player
1925 bool lamexp_open_media_file(const QString &mediaFilePath)
1927 const static wchar_t *registryPrefix[2] = { L"SOFTWARE\\", L"SOFTWARE\\Wow6432Node\\" };
1928 const static wchar_t *registryKeys[3] =
1930 L"Microsoft\\Windows\\CurrentVersion\\Uninstall\\{97D341C8-B0D1-4E4A-A49A-C30B52F168E9}",
1931 L"Microsoft\\Windows\\CurrentVersion\\Uninstall\\{DB9E4EAB-2717-499F-8D56-4CC8A644AB60}",
1932 L"foobar2000"
1934 const static wchar_t *appNames[4] = { L"smplayer_portable.exe", L"smplayer.exe", L"MPUI.exe", L"foobar2000.exe" };
1935 const static wchar_t *valueNames[2] = { L"InstallLocation", L"InstallDir" };
1937 for(size_t i = 0; i < 3; i++)
1939 for(size_t j = 0; j < 2; j++)
1941 QString mplayerPath;
1942 HKEY registryKeyHandle = NULL;
1944 const QString currentKey = WCHAR2QSTR(registryPrefix[j]).append(WCHAR2QSTR(registryKeys[i]));
1945 if(RegOpenKeyExW(HKEY_LOCAL_MACHINE, QWCHAR(currentKey), 0, KEY_READ, &registryKeyHandle) == ERROR_SUCCESS)
1947 for(size_t k = 0; k < 2; k++)
1949 wchar_t Buffer[4096];
1950 DWORD BuffSize = sizeof(wchar_t*) * 4096;
1951 DWORD DataType = REG_NONE;
1952 if(RegQueryValueExW(registryKeyHandle, valueNames[k], 0, &DataType, reinterpret_cast<BYTE*>(Buffer), &BuffSize) == ERROR_SUCCESS)
1954 if((DataType == REG_SZ) || (DataType == REG_EXPAND_SZ) || (DataType == REG_LINK))
1956 mplayerPath = WCHAR2QSTR(Buffer);
1957 break;
1961 RegCloseKey(registryKeyHandle);
1964 if(!mplayerPath.isEmpty())
1966 QDir mplayerDir(mplayerPath);
1967 if(mplayerDir.exists())
1969 for(size_t k = 0; k < 4; k++)
1971 if(mplayerDir.exists(WCHAR2QSTR(appNames[k])))
1973 qDebug("Player found at:\n%s\n", QUTF8(mplayerDir.absoluteFilePath(WCHAR2QSTR(appNames[k]))));
1974 QProcess::startDetached(mplayerDir.absoluteFilePath(WCHAR2QSTR(appNames[k])), QStringList() << QDir::toNativeSeparators(mediaFilePath));
1975 return true;
1982 return false;
1985 static void lamexp_init_dwmapi(void)
1987 QReadLocker writeLock(&g_lamexp_dwmapi.lock);
1989 //Not initialized yet?
1990 if(g_lamexp_dwmapi.bInitialized)
1992 return;
1995 //Reset function pointers
1996 g_lamexp_dwmapi.dwmIsCompositionEnabled = NULL;
1997 g_lamexp_dwmapi.dwmExtendFrameIntoClientArea = NULL;
1998 g_lamexp_dwmapi.dwmEnableBlurBehindWindow = NULL;
2000 //Does OS support DWM?
2001 if(lamexp_get_os_version() >= lamexp_winver_vista)
2003 //Load DWMAPI.DLL
2004 g_lamexp_dwmapi.dwmapi_dll = new QLibrary("dwmapi.dll");
2005 if(g_lamexp_dwmapi.dwmapi_dll->load())
2007 //Initialize function pointers
2008 g_lamexp_dwmapi.dwmIsCompositionEnabled = (HRESULT (__stdcall*)(BOOL*)) g_lamexp_dwmapi.dwmapi_dll->resolve("DwmIsCompositionEnabled");
2009 g_lamexp_dwmapi.dwmExtendFrameIntoClientArea = (HRESULT (__stdcall*)(HWND, const MARGINS*)) g_lamexp_dwmapi.dwmapi_dll->resolve("DwmExtendFrameIntoClientArea");
2010 g_lamexp_dwmapi.dwmEnableBlurBehindWindow = (HRESULT (__stdcall*)(HWND, const DWM_BLURBEHIND*)) g_lamexp_dwmapi.dwmapi_dll->resolve("DwmEnableBlurBehindWindow");
2012 else
2014 LAMEXP_DELETE(g_lamexp_dwmapi.dwmapi_dll);
2015 qWarning("Failed to load DWMAPI.DLL on a DWM-enabled system!");
2019 g_lamexp_dwmapi.bInitialized = true;
2023 * Enable "sheet of glass" effect on the given Window
2025 bool lamexp_sheet_of_glass(QWidget *window)
2027 QReadLocker readLock(&g_lamexp_dwmapi.lock);
2029 //Initialize the DWM API
2030 while(!g_lamexp_dwmapi.bInitialized)
2032 readLock.unlock();
2033 lamexp_init_dwmapi();
2034 readLock.relock();
2037 BOOL bCompositionEnabled = FALSE;
2039 //Required functions available?
2040 if((g_lamexp_dwmapi.dwmIsCompositionEnabled != NULL) && (g_lamexp_dwmapi.dwmExtendFrameIntoClientArea != NULL) && (g_lamexp_dwmapi.dwmEnableBlurBehindWindow != NULL))
2042 //Check if composition is currently enabled
2043 if(HRESULT hr = g_lamexp_dwmapi.dwmIsCompositionEnabled(&bCompositionEnabled))
2045 qWarning("DwmIsCompositionEnabled function has failed! (error %d)", hr);
2046 return false;
2050 //All functions available *and* composition enabled?
2051 if(!bCompositionEnabled)
2053 return false;
2056 //Enable the "sheet of glass" effect on this window
2057 MARGINS margins = {-1, -1, -1, -1};
2058 if(HRESULT hr = g_lamexp_dwmapi.dwmExtendFrameIntoClientArea(window->winId(), &margins))
2060 qWarning("DwmExtendFrameIntoClientArea function has failed! (error %d)", hr);
2061 return false;
2064 //Create and populate the Blur Behind structure
2065 DWM_BLURBEHIND bb;
2066 memset(&bb, 0, sizeof(DWM_BLURBEHIND));
2067 bb.fEnable = TRUE;
2068 bb.dwFlags = DWM_BB_ENABLE;
2069 if(HRESULT hr = g_lamexp_dwmapi.dwmEnableBlurBehindWindow(window->winId(), &bb))
2071 qWarning("DwmEnableBlurBehindWindow function has failed! (error %d)", hr);
2072 return false;
2075 //Required for Qt
2076 window->setAutoFillBackground(false);
2077 window->setAttribute(Qt::WA_TranslucentBackground);
2078 window->setAttribute(Qt::WA_NoSystemBackground);
2080 return true;
2084 * Update "sheet of glass" effect on the given Window
2086 bool lamexp_sheet_of_glass_update(QWidget *window)
2088 QReadLocker readLock(&g_lamexp_dwmapi.lock);
2090 //Initialize the DWM API
2091 while(!g_lamexp_dwmapi.bInitialized)
2093 readLock.unlock();
2094 lamexp_init_dwmapi();
2095 readLock.relock();
2098 BOOL bCompositionEnabled = FALSE;
2100 //Required functions available?
2101 if((g_lamexp_dwmapi.dwmIsCompositionEnabled != NULL) && (g_lamexp_dwmapi.dwmEnableBlurBehindWindow != NULL))
2103 //Check if composition is currently enabled
2104 if(HRESULT hr = g_lamexp_dwmapi.dwmIsCompositionEnabled(&bCompositionEnabled))
2106 qWarning("DwmIsCompositionEnabled function has failed! (error %d)", hr);
2107 return false;
2111 //All functions available *and* composition enabled?
2112 if(!bCompositionEnabled)
2114 return false;
2117 //Create and populate the Blur Behind structure
2118 DWM_BLURBEHIND bb;
2119 memset(&bb, 0, sizeof(DWM_BLURBEHIND));
2120 bb.fEnable = TRUE;
2121 bb.dwFlags = DWM_BB_ENABLE;
2122 if(HRESULT hr = g_lamexp_dwmapi.dwmEnableBlurBehindWindow(window->winId(), &bb))
2124 qWarning("DwmEnableBlurBehindWindow function has failed! (error %d)", hr);
2125 return false;
2128 return true;
2132 * Update the window icon
2134 lamexp_icon_t *lamexp_set_window_icon(QWidget *window, const QIcon &icon, const bool bIsBigIcon)
2136 if(!icon.isNull())
2138 const int extend = (bIsBigIcon ? 32 : 16);
2139 if(HICON hIcon = lamexp_qicon2hicon(icon, extend, extend))
2141 SendMessage(window->winId(), WM_SETICON, (bIsBigIcon ? ICON_BIG : ICON_SMALL), LPARAM(hIcon));
2142 return reinterpret_cast<lamexp_icon_t*>(hIcon);
2145 return NULL;
2149 * Free window icon
2151 void lamexp_free_window_icon(lamexp_icon_t *icon)
2153 if(HICON hIcon = reinterpret_cast<HICON>(icon))
2155 DestroyIcon(hIcon);
2160 * Get system color info
2162 QColor lamexp_system_color(const int color_id)
2164 int nIndex = -1;
2166 switch(color_id)
2168 case lamexp_syscolor_text:
2169 nIndex = COLOR_WINDOWTEXT; /*Text in windows*/
2170 break;
2171 case lamexp_syscolor_background:
2172 nIndex = COLOR_WINDOW; /*Window background*/
2173 break;
2174 case lamexp_syscolor_caption:
2175 nIndex = COLOR_CAPTIONTEXT; /*Text in caption, size box, and scroll bar arrow box*/
2176 break;
2177 default:
2178 qWarning("Unknown system color id (%d) specified!", color_id);
2179 nIndex = COLOR_WINDOWTEXT;
2182 const DWORD rgb = GetSysColor(nIndex);
2183 QColor color(GetRValue(rgb), GetGValue(rgb), GetBValue(rgb));
2184 return color;
2188 * Check if the current user is an administartor (helper function)
2190 static bool lamexp_user_is_admin_helper(void)
2192 HANDLE hToken = NULL;
2193 if(!OpenProcessToken(GetCurrentProcess(), TOKEN_QUERY, &hToken))
2195 return false;
2198 DWORD dwSize = 0;
2199 if(!GetTokenInformation(hToken, TokenGroups, NULL, 0, &dwSize))
2201 if(GetLastError() != ERROR_INSUFFICIENT_BUFFER)
2203 CloseHandle(hToken);
2204 return false;
2208 PTOKEN_GROUPS lpGroups = (PTOKEN_GROUPS) malloc(dwSize);
2209 if(!lpGroups)
2211 CloseHandle(hToken);
2212 return false;
2215 if(!GetTokenInformation(hToken, TokenGroups, lpGroups, dwSize, &dwSize))
2217 free(lpGroups);
2218 CloseHandle(hToken);
2219 return false;
2222 PSID lpSid = NULL; SID_IDENTIFIER_AUTHORITY Authority = {SECURITY_NT_AUTHORITY};
2223 if(!AllocateAndInitializeSid(&Authority, 2, SECURITY_BUILTIN_DOMAIN_RID, DOMAIN_ALIAS_RID_ADMINS, 0, 0, 0, 0, 0, 0, &lpSid))
2225 free(lpGroups);
2226 CloseHandle(hToken);
2227 return false;
2230 bool bResult = false;
2231 for(DWORD i = 0; i < lpGroups->GroupCount; i++)
2233 if(EqualSid(lpSid, lpGroups->Groups[i].Sid))
2235 bResult = true;
2236 break;
2240 FreeSid(lpSid);
2241 free(lpGroups);
2242 CloseHandle(hToken);
2243 return bResult;
2247 * Check if the current user is an administartor
2249 bool lamexp_user_is_admin(void)
2251 bool isAdmin = false;
2253 //Check for process elevation and UAC support first!
2254 if(lamexp_process_is_elevated(&isAdmin))
2256 qWarning("Process is elevated -> user is admin!");
2257 return true;
2260 //If not elevated and UAC is not available -> user must be in admin group!
2261 if(!isAdmin)
2263 qDebug("UAC is disabled/unavailable -> checking for Administrators group");
2264 isAdmin = lamexp_user_is_admin_helper();
2267 return isAdmin;
2271 * Check if file is a valid Win32/Win64 executable
2273 bool lamexp_is_executable(const QString &path)
2275 bool bIsExecutable = false;
2276 DWORD binaryType;
2277 if(GetBinaryType(QWCHAR(QDir::toNativeSeparators(path)), &binaryType))
2279 bIsExecutable = (binaryType == SCS_32BIT_BINARY || binaryType == SCS_64BIT_BINARY);
2281 return bIsExecutable;
2285 * Fatal application exit
2287 #pragma intrinsic(_InterlockedExchange)
2288 void lamexp_fatal_exit(const wchar_t* exitMessage, const wchar_t* errorBoxMessage)
2290 static volatile long bFatalFlag = 0L;
2292 if(_InterlockedExchange(&bFatalFlag, 1L) == 0L)
2294 if(GetCurrentThreadId() != g_main_thread_id)
2296 HANDLE mainThread = OpenThread(THREAD_TERMINATE, FALSE, g_main_thread_id);
2297 if(mainThread) TerminateThread(mainThread, ULONG_MAX);
2300 if(errorBoxMessage)
2302 MessageBoxW(NULL, errorBoxMessage, L"LameXP - GURU MEDITATION", MB_ICONERROR | MB_TOPMOST | MB_TASKMODAL);
2305 for(;;)
2307 FatalAppExit(0, exitMessage);
2308 TerminateProcess(GetCurrentProcess(), -1);
2312 TerminateThread(GetCurrentThread(), -1);
2313 Sleep(INFINITE);
2317 * Initialize debug thread
2319 static const HANDLE g_debug_thread1 = LAMEXP_DEBUG ? NULL : lamexp_debug_thread_init();
2322 * Get number private bytes [debug only]
2324 unsigned long lamexp_dbg_private_bytes(void)
2326 #if LAMEXP_DEBUG
2327 for(int i = 0; i < 8; i++) _heapmin();
2328 PROCESS_MEMORY_COUNTERS_EX memoryCounters;
2329 memoryCounters.cb = sizeof(PROCESS_MEMORY_COUNTERS_EX);
2330 GetProcessMemoryInfo(GetCurrentProcess(), (PPROCESS_MEMORY_COUNTERS) &memoryCounters, sizeof(PROCESS_MEMORY_COUNTERS_EX));
2331 return memoryCounters.PrivateUsage;
2332 #else
2333 THROW("Cannot call this function in a non-debug build!");
2334 #endif //LAMEXP_DEBUG
2338 * Output string to debugger [debug only]
2340 void lamexp_dbg_dbg_output_string(const char* format, ...)
2342 #if LAMEXP_DEBUG
2343 char buffer[256];
2344 va_list args;
2345 va_start (args, format);
2346 vsnprintf_s(buffer, 256, _TRUNCATE, format, args);
2347 OutputDebugStringA(buffer);
2348 va_end(args);
2349 #else
2350 THROW("Cannot call this function in a non-debug build!");
2351 #endif //LAMEXP_DEBUG
2354 ///////////////////////////////////////////////////////////////////////////////
2355 // INITIALIZATION
2356 ///////////////////////////////////////////////////////////////////////////////
2358 extern "C" void _lamexp_global_init_win32(void)
2360 if((!LAMEXP_DEBUG) && lamexp_check_for_debugger())
2362 lamexp_fatal_exit(L"Not a debug build. Please unload debugger and try again!");
2365 //Zero *before* constructors are called
2366 LAMEXP_ZERO_MEMORY(g_lamexp_argv);
2367 LAMEXP_ZERO_MEMORY(g_lamexp_known_folder);
2368 LAMEXP_ZERO_MEMORY(g_lamexp_os_version);
2369 LAMEXP_ZERO_MEMORY(g_lamexp_wine);
2370 LAMEXP_ZERO_MEMORY(g_lamexp_themes_enabled);
2371 LAMEXP_ZERO_MEMORY(g_lamexp_dwmapi);
2372 LAMEXP_ZERO_MEMORY(g_lamexp_sounds);
2375 ///////////////////////////////////////////////////////////////////////////////
2376 // FINALIZATION
2377 ///////////////////////////////////////////////////////////////////////////////
2379 extern "C" void _lamexp_global_free_win32(void)
2381 //Clear folder cache
2382 LAMEXP_DELETE(g_lamexp_known_folder.knownFolders);
2384 //Destroy Qt application object
2385 QApplication *application = dynamic_cast<QApplication*>(QApplication::instance());
2386 LAMEXP_DELETE(application);
2388 //Release DWM API
2389 g_lamexp_dwmapi.dwmIsCompositionEnabled = NULL;
2390 g_lamexp_dwmapi.dwmExtendFrameIntoClientArea = NULL;
2391 g_lamexp_dwmapi.dwmEnableBlurBehindWindow = NULL;
2392 LAMEXP_DELETE(g_lamexp_dwmapi.dwmapi_dll);
2394 //Free STDOUT and STDERR buffers
2395 if(g_lamexp_console_attached)
2397 if(std::filebuf *tmp = dynamic_cast<std::filebuf*>(std::cout.rdbuf()))
2399 std::cout.rdbuf(NULL);
2400 LAMEXP_DELETE(tmp);
2402 if(std::filebuf *tmp = dynamic_cast<std::filebuf*>(std::cerr.rdbuf()))
2404 std::cerr.rdbuf(NULL);
2405 LAMEXP_DELETE(tmp);
2409 //Close log file
2410 if(g_lamexp_log_file)
2412 fclose(g_lamexp_log_file);
2413 g_lamexp_log_file = NULL;
2416 //Clear sound cache
2417 LAMEXP_DELETE(g_lamexp_sounds.sound_db);
2419 //Free CLI Arguments
2420 LAMEXP_DELETE(g_lamexp_argv.list);