1 ///////////////////////////////////////////////////////////////////////////////
2 // LameXP - Audio Encoder Front-End
3 // Copyright (C) 2004-2014 LoRd_MuldeR <MuldeR2@GMX.de>
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 ///////////////////////////////////////////////////////////////////////////////
26 #include "Targetver.h"
28 //Visual Leaks Detector
33 #define WIN32_LEAN_AND_MEAN
44 #include <QApplication>
49 #include <QImageReader>
51 #include <QLibraryInfo>
53 #include <QMessageBox>
55 #include <QPlastiqueStyle>
57 #include <QReadWriteLock>
62 #include <QTranslator>
67 #define LAMEXP_INC_CONFIG
83 //Initialize static Qt plugins
85 #if QT_VERSION < QT_VERSION_CHECK(5,0,0)
89 Q_IMPORT_PLUGIN(QWindowsIntegrationPlugin)
90 Q_IMPORT_PLUGIN(QICOPlugin)
94 ///////////////////////////////////////////////////////////////////////////////
96 ///////////////////////////////////////////////////////////////////////////////
98 #define _LAMEXP_MAKE_STR(STR) #STR
99 #define LAMEXP_MAKE_STR(STR) _LAMEXP_MAKE_STR(STR)
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); \
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)++; \
123 ///////////////////////////////////////////////////////////////////////////////
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 ///////////////////////////////////////////////////////////////////////////////
132 ///////////////////////////////////////////////////////////////////////////////
134 //Console attached flag
135 static bool g_lamexp_console_attached = false;
140 QMap<size_t, QString> *knownFolders;
141 SHGetKnownFolderPath_t getKnownFolderPath;
142 SHGetFolderPath_t getFolderPath;
145 g_lamexp_known_folder;
159 lamexp_os_version_t version;
173 //Win32 Theme support
180 g_lamexp_themes_enabled;
182 //Win32 DWM API functions
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;
197 QHash<const QString, const unsigned char*> *sound_db;
203 static const char *g_lamexp_imageformats[] = {"bmp", "png", "jpg", "gif", "ico", "xpm", NULL}; //"svg"
206 static QMutex g_lamexp_message_mutex;
209 static const DWORD g_main_thread_id = GetCurrentThreadId();
212 static FILE *g_lamexp_log_file = NULL;
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};
228 static const char *GURU_MEDITATION = "\n\nGURU MEDITATION !!!\n\n";
230 ///////////////////////////////////////////////////////////////////////////////
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);
255 const BOOL ret = VerifyVersionInfoW(&osvi, VER_MAJORVERSION | VER_MINORVERSION | VER_PLATFORMID, dwlConditionMask);
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)
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!");
289 //Make sure we are running on NT
290 if(osvi.dwPlatformId == VER_PLATFORM_WIN32_NT)
292 *major = osvi.dwMajorVersion;
293 *minor = osvi.dwMinorVersion;
297 qWarning("Not running on Windows NT, unsupported operating system!");
301 //Determine the real *major* version first
304 const DWORD nextMajor = (*major) + 1;
305 if(lamexp_verify_os_version(nextMajor, 0))
315 //Now also determine the real *minor* version
318 const DWORD nextMinor = (*minor) + 1;
319 if(lamexp_verify_os_version((*major), nextMinor))
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;
345 QWriteLocker writeLock(&g_lamexp_os_version.lock);
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;
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;
381 QWriteLocker writeLock(&g_lamexp_wine.lock);
383 if(!g_lamexp_wine.bInitialized)
385 g_lamexp_wine.bIsWine = false;
386 QLibrary ntdll("ntdll.dll");
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;
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)
418 if(_isatty(_fileno(stderr)))
420 UINT oldOutputCP = GetConsoleOutputCP();
421 if(oldOutputCP != CP_UTF8) SetConsoleOutputCP(CP_UTF8);
427 lamexp_console_color(stderr, FOREGROUND_RED | FOREGROUND_INTENSITY);
428 fprintf(stderr, GURU_MEDITATION);
429 fprintf(stderr, "%s\n", msg);
433 lamexp_console_color(stderr, FOREGROUND_GREEN | FOREGROUND_RED | FOREGROUND_INTENSITY);
434 fprintf(stderr, "%s\n", msg);
438 lamexp_console_color(stderr, FOREGROUND_BLUE | FOREGROUND_GREEN | FOREGROUND_RED | FOREGROUND_INTENSITY);
439 fprintf(stderr, "%s\n", msg);
444 lamexp_console_color(stderr, FOREGROUND_BLUE | FOREGROUND_GREEN | FOREGROUND_RED);
445 if(oldOutputCP != CP_UTF8) SetConsoleOutputCP(oldOutputCP);
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";
464 const char* input = msg;
471 _snprintf_s(buffer, 512, _TRUNCATE, FORMAT, 'C', input);
474 _snprintf_s(buffer, 512, _TRUNCATE, FORMAT, 'W', input);
477 _snprintf_s(buffer, 512, _TRUNCATE, FORMAT, 'I', input);
481 char *temp = &buffer[0];
482 CLEAN_OUTPUT_STRING(temp);
483 OutputDebugStringA(temp);
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";
500 if(g_lamexp_log_file)
503 strncpy_s(buffer, 512, msg, _TRUNCATE);
505 char *temp = &buffer[0];
507 CLEAN_OUTPUT_STRING(temp);
509 const unsigned int timestamp = static_cast<unsigned int>(_time64(NULL) % 3600I64);
515 fprintf(g_lamexp_log_file, FORMAT, 'C', timestamp, temp);
518 fprintf(g_lamexp_log_file, FORMAT, 'W', timestamp, temp);
521 fprintf(g_lamexp_log_file, FORMAT, 'I', timestamp, temp);
525 fflush(g_lamexp_log_file);
530 /*ignore any exception that might occur here!*/
537 void lamexp_message_handler(QtMsgType type, const char *msg)
539 if((!msg) || (!(msg[0])))
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);
557 lamexp_write_dbg_out(type, msg);
560 if((type == QtCriticalMsg) || (type == QtFatalMsg))
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!");
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!");
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());
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))
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;
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;
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));
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);
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)
742 memcpy(CPUBrandString, CPUInfo, sizeof(CPUInfo));
745 memcpy(CPUBrandString + 16, CPUInfo, sizeof(CPUInfo));
748 memcpy(CPUBrandString + 32, CPUInfo, sizeof(CPUInfo));
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);
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);
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");
802 * Check for debugger (detect routine)
804 static __forceinline bool lamexp_check_for_debugger(void)
808 CloseHandle((HANDLE)((DWORD_PTR)-3));
815 BOOL bHaveDebugger = FALSE;
816 if(CheckRemoteDebuggerPresent(GetCurrentProcess(), &bHaveDebugger))
818 if(bHaveDebugger) return true;
821 return IsDebuggerPresent();
825 * Check for debugger (thread proc)
827 static unsigned int __stdcall lamexp_debug_thread_proc(LPVOID lpParameter)
829 SetThreadPriority(GetCurrentThread(), THREAD_PRIORITY_LOWEST);
832 if(lamexp_check_for_debugger())
834 lamexp_fatal_exit(L"Not a debug build. Please unload debugger and try again!");
842 * Check for debugger (startup routine)
844 static HANDLE lamexp_debug_thread_init()
846 if(lamexp_check_for_debugger())
848 lamexp_fatal_exit(L"Not a debug build. Please unload debugger and try again!");
850 const uintptr_t h = _beginthreadex(NULL, 0, lamexp_debug_thread_proc, NULL, 0, NULL);
851 return (HANDLE)(h^0xdeadbeef);
857 static bool lamexp_event_filter(void *message, long *result)
859 if((!(LAMEXP_DEBUG)) && lamexp_check_for_debugger())
861 lamexp_fatal_exit(L"Not a debug build. Please unload debugger and try again!");
864 switch(reinterpret_cast<MSG*>(message)->message)
866 case WM_QUERYENDSESSION:
867 qWarning("WM_QUERYENDSESSION message received!");
868 *result = lamexp_broadcast(lamexp_event_queryendsession, false) ? TRUE : FALSE;
871 qWarning("WM_ENDSESSION message received!");
872 if(reinterpret_cast<MSG*>(message)->wParam == TRUE)
874 lamexp_broadcast(lamexp_event_endsession, false);
875 if(QApplication *app = reinterpret_cast<QApplication*>(QApplication::instance()))
877 app->closeAllWindows();
880 lamexp_finalization();
886 /*ignore this message and let Qt handle it*/
892 * Check for process elevation
894 static bool lamexp_process_is_elevated(bool *bIsUacEnabled = NULL)
896 bool bIsProcessElevated = false;
897 if(bIsUacEnabled) *bIsUacEnabled = false;
898 HANDLE hToken = NULL;
900 if(OpenProcessToken(GetCurrentProcess(), TOKEN_QUERY, &hToken))
902 TOKEN_ELEVATION_TYPE tokenElevationType;
904 if(GetTokenInformation(hToken, TokenElevationType, &tokenElevationType, sizeof(TOKEN_ELEVATION_TYPE), &returnLength))
906 if(returnLength == sizeof(TOKEN_ELEVATION_TYPE))
908 switch(tokenElevationType)
910 case TokenElevationTypeDefault:
911 qDebug("Process token elevation type: Default -> UAC is disabled.\n");
913 case TokenElevationTypeFull:
914 qWarning("Process token elevation type: Full -> potential security risk!\n");
915 bIsProcessElevated = true;
916 if(bIsUacEnabled) *bIsUacEnabled = true;
918 case TokenElevationTypeLimited:
919 qDebug("Process token elevation type: Limited -> not elevated.\n");
920 if(bIsUacEnabled) *bIsUacEnabled = true;
923 qWarning("Unknown tokenElevationType value: %d", tokenElevationType);
929 qWarning("GetTokenInformation() return an unexpected size!");
936 qWarning("Failed to open process token!");
939 return bIsProcessElevated;
943 * Convert QIcon to HICON -> caller is responsible for destroying the HICON!
945 static HICON lamexp_qicon2hicon(const QIcon &icon, const int w, const int h)
949 QPixmap pixmap = icon.pixmap(w, h);
952 return pixmap.toWinHICON();
959 * Initialize Qt framework
961 bool lamexp_init_qt(int argc, char* argv[])
963 static bool qt_initialized = false;
964 typedef BOOL (WINAPI *SetDllDirectoryProc)(WCHAR *lpPathName);
965 const QStringList &arguments = lamexp_arguments();
967 //Don't initialized again, if done already
974 QLibrary kernel32("kernel32.dll");
977 SetDllDirectoryProc pSetDllDirectory = (SetDllDirectoryProc) kernel32.resolve("SetDllDirectoryW");
978 if(pSetDllDirectory != NULL) pSetDllDirectory(L"");
981 //Extract executable name from argv[] array
982 QString executableName = QLatin1String("LameXP.exe");
983 if(arguments.count() > 0)
985 static const char *delimiters = "\\/:?";
986 executableName = arguments[0].trimmed();
987 for(int i = 0; delimiters[i]; i++)
989 int temp = executableName.lastIndexOf(QChar(delimiters[i]));
990 if(temp >= 0) executableName = executableName.mid(temp + 1);
992 executableName = executableName.trimmed();
993 if(executableName.isEmpty())
995 executableName = QLatin1String("LameXP.exe");
1001 qDebug("Using Qt v%s [%s], %s, %s", qVersion(), QLibraryInfo::buildDate().toString(Qt::ISODate).toLatin1().constData(), (qSharedBuild() ? "DLL" : "Static"), QLibraryInfo::buildKey().toLatin1().constData());
1002 qDebug("Compiled with Qt v%s [%s], %s\n", QT_VERSION_STR, QT_PACKAGEDATE_STR, QT_BUILD_KEY);
1003 if(_stricmp(qVersion(), QT_VERSION_STR))
1005 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());
1008 if(QLibraryInfo::buildKey().compare(QString::fromLatin1(QT_BUILD_KEY), Qt::CaseInsensitive))
1010 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());
1014 qDebug("Using Qt v%s [%s], %s", qVersion(), QLibraryInfo::buildDate().toString(Qt::ISODate).toLatin1().constData(), (qSharedBuild() ? "DLL" : "Static"));
1015 qDebug("Compiled with Qt v%s [%s]\n", QT_VERSION_STR, QT_PACKAGEDATE_STR);
1018 //Check the Windows version
1019 const lamexp_os_version_t &osVersionNo = lamexp_get_os_version();
1020 if(osVersionNo < lamexp_winver_winxp)
1022 qFatal("%s", QApplication::tr("Executable '%1' requires Windows XP or later.").arg(executableName).toLatin1().constData());
1025 //Supported Windows version?
1026 if(osVersionNo == lamexp_winver_winxp)
1028 qDebug("Running on Windows XP or Windows XP Media Center Edition.\n"); //lamexp_check_compatibility_mode("GetLargePageMinimum", executableName);
1030 else if(osVersionNo == lamexp_winver_xpx64)
1032 qDebug("Running on Windows Server 2003, Windows Server 2003 R2 or Windows XP x64.\n"); //lamexp_check_compatibility_mode("GetLocaleInfoEx", executableName);
1034 else if(osVersionNo == lamexp_winver_vista)
1036 qDebug("Running on Windows Vista or Windows Server 2008.\n"); //lamexp_check_compatibility_mode("CreateRemoteThreadEx", executableName*/);
1038 else if(osVersionNo == lamexp_winver_win70)
1040 qDebug("Running on Windows 7 or Windows Server 2008 R2.\n"); //lamexp_check_compatibility_mode("CreateFile2", executableName);
1042 else if(osVersionNo == lamexp_winver_win80)
1044 qDebug("Running on Windows 8 or Windows Server 2012.\n"); //lamexp_check_compatibility_mode("FindPackagesByPackageFamily", executableName);
1046 else if(osVersionNo == lamexp_winver_win81)
1048 qDebug("Running on Windows 8.1 or Windows Server 2012 R2.\n"); //lamexp_check_compatibility_mode(NULL, executableName);
1052 const QString message = QString().sprintf("Running on an unknown WindowsNT-based system (v%u.%u).", osVersionNo.versionMajor, osVersionNo.versionMinor);
1053 qWarning("%s\n", QUTF8(message));
1054 MessageBoxW(NULL, QWCHAR(message), L"LameXP", MB_OK | MB_TOPMOST | MB_ICONWARNING);
1057 //Check for compat mode
1058 if(osVersionNo.overrideFlag && (osVersionNo <= lamexp_winver_win81))
1060 qWarning("Windows compatibility mode detected!");
1061 if(!arguments.contains("--ignore-compat-mode", Qt::CaseInsensitive))
1063 qFatal("%s", QApplication::tr("Executable '%1' doesn't support Windows compatibility mode.").arg(executableName).toLatin1().constData());
1069 if(lamexp_detect_wine())
1071 qWarning("It appears we are running under Wine, unexpected things might happen!\n");
1074 //Set text Codec for locale
1075 QTextCodec::setCodecForLocale(QTextCodec::codecForName("UTF-8"));
1077 //Create Qt application instance
1078 QApplication *application = new QApplication(argc, argv);
1080 //Load plugins from application directory
1081 QCoreApplication::setLibraryPaths(QStringList() << QApplication::applicationDirPath());
1082 qDebug("Library Path:\n%s\n", QUTF8(QApplication::libraryPaths().first()));
1084 //Set application properties
1085 application->setApplicationName("LameXP - Audio Encoder Front-End");
1086 application->setApplicationVersion(QString().sprintf("%d.%02d.%04d", lamexp_version_major(), lamexp_version_minor(), lamexp_version_build()));
1087 application->setOrganizationName("LoRd_MuldeR");
1088 application->setOrganizationDomain("mulder.at.gg");
1089 application->setWindowIcon(lamexp_app_icon());
1090 application->setEventFilter(lamexp_event_filter);
1092 //Check for supported image formats
1093 QList<QByteArray> supportedFormats = QImageReader::supportedImageFormats();
1094 for(int i = 0; g_lamexp_imageformats[i]; i++)
1096 if(!supportedFormats.contains(g_lamexp_imageformats[i]))
1098 qFatal("Qt initialization error: QImageIOHandler for '%s' missing!", g_lamexp_imageformats[i]);
1103 //Enable larger/smaller font size
1104 double fontScaleFactor = 1.0;
1105 if(arguments.contains("--huge-font", Qt::CaseInsensitive)) fontScaleFactor = 1.500;
1106 if(arguments.contains("--big-font", Qt::CaseInsensitive)) fontScaleFactor = 1.250;
1107 if(arguments.contains("--small-font", Qt::CaseInsensitive)) fontScaleFactor = 0.875;
1108 if(arguments.contains("--tiny-font", Qt::CaseInsensitive)) fontScaleFactor = 0.750;
1109 if(!qFuzzyCompare(fontScaleFactor, 1.0))
1111 qWarning("Application font scale factor set to: %.3f\n", fontScaleFactor);
1112 QFont appFont = application->font();
1113 appFont.setPointSizeF(appFont.pointSizeF() * fontScaleFactor);
1114 application->setFont(appFont);
1117 //Add the default translations
1118 lamexp_translation_init();
1120 //Check for process elevation
1121 if(lamexp_process_is_elevated() && (!lamexp_detect_wine()))
1123 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);
1124 messageBox.addButton("Quit Program (Recommended)", QMessageBox::NoRole);
1125 messageBox.addButton("Ignore", QMessageBox::NoRole);
1126 if(messageBox.exec() == 0)
1132 //Update console icon, if a console is attached
1133 #if QT_VERSION < QT_VERSION_CHECK(5,0,0)
1134 if(g_lamexp_console_attached && (!lamexp_detect_wine()))
1136 QLibrary kernel32("kernel32.dll");
1139 typedef DWORD (__stdcall *SetConsoleIconFun)(HICON);
1140 if(SetConsoleIconFun SetConsoleIconPtr = (SetConsoleIconFun) kernel32.resolve("SetConsoleIcon"))
1142 if(HICON hIcon = lamexp_qicon2hicon(QIcon(":/icons/sound.png"), 16, 16))
1144 SetConsoleIconPtr(hIcon);
1153 qt_initialized = true;
1157 const QStringList &lamexp_arguments(void)
1159 QReadLocker readLock(&g_lamexp_argv.lock);
1161 if(!g_lamexp_argv.list)
1164 QWriteLocker writeLock(&g_lamexp_argv.lock);
1166 g_lamexp_argv.list = new QStringList;
1169 LPWSTR *szArglist = CommandLineToArgvW(GetCommandLineW(), &nArgs);
1171 if(NULL != szArglist)
1173 for(int i = 0; i < nArgs; i++)
1175 (*g_lamexp_argv.list) << WCHAR2QSTR(szArglist[i]);
1177 LocalFree(szArglist);
1181 qWarning("CommandLineToArgvW() has failed !!!");
1185 return (*g_lamexp_argv.list);
1189 * Locate known folder on local system
1191 const QString &lamexp_known_folder(lamexp_known_folder_t folder_id)
1193 static const int CSIDL_FLAG_CREATE = 0x8000;
1194 typedef enum { KF_FLAG_CREATE = 0x00008000 } kf_flags_t;
1201 static s_folders[] =
1203 { 0x001c, {0xF1B32785,0x6FBA,0x4FCF,{0x9D,0x55,0x7B,0x8E,0x7F,0x15,0x70,0x91}} }, //CSIDL_LOCAL_APPDATA
1204 { 0x0026, {0x905e63b6,0xc1bf,0x494e,{0xb2,0x9c,0x65,0xb7,0x32,0xd3,0xd2,0x1a}} }, //CSIDL_PROGRAM_FILES
1205 { 0x0024, {0xF38BF404,0x1D43,0x42F2,{0x93,0x05,0x67,0xDE,0x0B,0x28,0xFC,0x23}} }, //CSIDL_WINDOWS_FOLDER
1206 { 0x0025, {0x1AC14E77,0x02E7,0x4E5D,{0xB7,0x44,0x2E,0xB1,0xAE,0x51,0x98,0xB7}} }, //CSIDL_SYSTEM_FOLDER
1209 size_t folderId = size_t(-1);
1213 case lamexp_folder_localappdata: folderId = 0; break;
1214 case lamexp_folder_programfiles: folderId = 1; break;
1215 case lamexp_folder_systroot_dir: folderId = 2; break;
1216 case lamexp_folder_systemfolder: folderId = 3; break;
1219 if(folderId == size_t(-1))
1221 qWarning("Invalid 'known' folder was requested!");
1222 return *reinterpret_cast<QString*>(NULL);
1225 QReadLocker readLock(&g_lamexp_known_folder.lock);
1228 if(g_lamexp_known_folder.knownFolders)
1230 if(g_lamexp_known_folder.knownFolders->contains(folderId))
1232 return (*g_lamexp_known_folder.knownFolders)[folderId];
1236 //Obtain write lock to initialize
1238 QWriteLocker writeLock(&g_lamexp_known_folder.lock);
1240 //Still not in cache?
1241 if(g_lamexp_known_folder.knownFolders)
1243 if(g_lamexp_known_folder.knownFolders->contains(folderId))
1245 return (*g_lamexp_known_folder.knownFolders)[folderId];
1249 //Initialize on first call
1250 if(!g_lamexp_known_folder.knownFolders)
1252 QLibrary shell32("shell32.dll");
1255 g_lamexp_known_folder.getFolderPath = (SHGetFolderPath_t) shell32.resolve("SHGetFolderPathW");
1256 g_lamexp_known_folder.getKnownFolderPath = (SHGetKnownFolderPath_t) shell32.resolve("SHGetKnownFolderPath");
1258 g_lamexp_known_folder.knownFolders = new QMap<size_t, QString>();
1263 //Now try to get the folder path!
1264 if(g_lamexp_known_folder.getKnownFolderPath)
1267 if(g_lamexp_known_folder.getKnownFolderPath(s_folders[folderId].guid, KF_FLAG_CREATE, NULL, &path) == S_OK)
1269 //MessageBoxW(0, path, L"SHGetKnownFolderPath", MB_TOPMOST);
1270 QDir folderTemp = QDir(QDir::fromNativeSeparators(QString::fromUtf16(reinterpret_cast<const unsigned short*>(path))));
1271 if(folderTemp.exists())
1273 folderPath = folderTemp.canonicalPath();
1275 CoTaskMemFree(path);
1278 else if(g_lamexp_known_folder.getFolderPath)
1280 WCHAR *path = new WCHAR[4096];
1281 if(g_lamexp_known_folder.getFolderPath(NULL, s_folders[folderId].csidl | CSIDL_FLAG_CREATE, NULL, NULL, path) == S_OK)
1283 //MessageBoxW(0, path, L"SHGetFolderPathW", MB_TOPMOST);
1284 QDir folderTemp = QDir(QDir::fromNativeSeparators(QString::fromUtf16(reinterpret_cast<const unsigned short*>(path))));
1285 if(folderTemp.exists())
1287 folderPath = folderTemp.canonicalPath();
1290 LAMEXP_DELETE_ARRAY(path);
1294 g_lamexp_known_folder.knownFolders->insert(folderId, folderPath);
1295 return (*g_lamexp_known_folder.knownFolders)[folderId];
1299 * Safely remove a file
1301 bool lamexp_remove_file(const QString &filename)
1303 if(!QFileInfo(filename).exists() || !QFileInfo(filename).isFile())
1309 if(!QFile::remove(filename))
1311 static const DWORD attrMask = FILE_ATTRIBUTE_READONLY | FILE_ATTRIBUTE_HIDDEN | FILE_ATTRIBUTE_SYSTEM;
1312 const DWORD attributes = GetFileAttributesW(QWCHAR(filename));
1313 if(attributes & attrMask)
1315 SetFileAttributesW(QWCHAR(filename), FILE_ATTRIBUTE_NORMAL);
1317 if(!QFile::remove(filename))
1319 qWarning("Could not delete \"%s\"", filename.toLatin1().constData());
1335 * Check if visual themes are enabled (WinXP and later)
1337 bool lamexp_themes_enabled(void)
1339 typedef int (WINAPI *IsAppThemedFun)(void);
1341 QReadLocker readLock(&g_lamexp_themes_enabled.lock);
1342 if(g_lamexp_themes_enabled.bInitialized)
1344 return g_lamexp_themes_enabled.bThemesEnabled;
1348 QWriteLocker writeLock(&g_lamexp_themes_enabled.lock);
1350 if(!g_lamexp_themes_enabled.bInitialized)
1352 g_lamexp_themes_enabled.bThemesEnabled = false;
1353 const lamexp_os_version_t &osVersion = lamexp_get_os_version();
1354 if(osVersion >= lamexp_winver_winxp)
1356 IsAppThemedFun IsAppThemedPtr = NULL;
1357 QLibrary uxTheme(QString("%1/UxTheme.dll").arg(lamexp_known_folder(lamexp_folder_systemfolder)));
1360 IsAppThemedPtr = (IsAppThemedFun) uxTheme.resolve("IsAppThemed");
1364 g_lamexp_themes_enabled.bThemesEnabled = IsAppThemedPtr();
1365 if(!g_lamexp_themes_enabled.bThemesEnabled)
1367 qWarning("Theme support is disabled for this process!");
1371 g_lamexp_themes_enabled.bInitialized = true;
1374 return g_lamexp_themes_enabled.bThemesEnabled;
1378 * Get number of free bytes on disk
1380 unsigned __int64 lamexp_free_diskspace(const QString &path, bool *ok)
1382 ULARGE_INTEGER freeBytesAvailable, totalNumberOfBytes, totalNumberOfFreeBytes;
1383 if(GetDiskFreeSpaceExW(reinterpret_cast<const wchar_t*>(QDir::toNativeSeparators(path).utf16()), &freeBytesAvailable, &totalNumberOfBytes, &totalNumberOfFreeBytes))
1386 return freeBytesAvailable.QuadPart;
1396 * Check if computer does support hibernation
1398 bool lamexp_is_hibernation_supported(void)
1400 bool hibernationSupported = false;
1402 SYSTEM_POWER_CAPABILITIES pwrCaps;
1403 SecureZeroMemory(&pwrCaps, sizeof(SYSTEM_POWER_CAPABILITIES));
1405 if(GetPwrCapabilities(&pwrCaps))
1407 hibernationSupported = pwrCaps.SystemS4 && pwrCaps.HiberFilePresent;
1410 return hibernationSupported;
1414 * Shutdown the computer
1416 bool lamexp_shutdown_computer(const QString &message, const unsigned long timeout, const bool forceShutdown, const bool hibernate)
1418 HANDLE hToken = NULL;
1420 if(OpenProcessToken(GetCurrentProcess(), TOKEN_ADJUST_PRIVILEGES | TOKEN_QUERY, &hToken))
1422 TOKEN_PRIVILEGES privileges;
1423 memset(&privileges, 0, sizeof(TOKEN_PRIVILEGES));
1424 privileges.PrivilegeCount = 1;
1425 privileges.Privileges[0].Attributes = SE_PRIVILEGE_ENABLED;
1427 if(LookupPrivilegeValue(NULL, SE_SHUTDOWN_NAME, &privileges.Privileges[0].Luid))
1429 if(AdjustTokenPrivileges(hToken, FALSE, &privileges, NULL, NULL, NULL))
1433 if(SetSuspendState(TRUE, TRUE, TRUE))
1438 const DWORD reason = SHTDN_REASON_MAJOR_APPLICATION | SHTDN_REASON_FLAG_PLANNED;
1439 return InitiateSystemShutdownEx(NULL, const_cast<wchar_t*>(QWCHAR(message)), timeout, forceShutdown ? TRUE : FALSE, FALSE, reason);
1448 * Determines the current date, resistant against certain manipulations
1450 QDate lamexp_current_date_safe(void)
1452 const DWORD MAX_PROC = 1024;
1453 DWORD *processes = new DWORD[MAX_PROC];
1454 DWORD bytesReturned = 0;
1456 if(!EnumProcesses(processes, sizeof(DWORD) * MAX_PROC, &bytesReturned))
1458 LAMEXP_DELETE_ARRAY(processes);
1459 return QDate::currentDate();
1462 const DWORD procCount = bytesReturned / sizeof(DWORD);
1463 ULARGE_INTEGER lastStartTime;
1464 memset(&lastStartTime, 0, sizeof(ULARGE_INTEGER));
1466 for(DWORD i = 0; i < procCount; i++)
1468 HANDLE hProc = OpenProcess(PROCESS_QUERY_INFORMATION, FALSE, processes[i]);
1471 FILETIME processTime[4];
1472 if(GetProcessTimes(hProc, &processTime[0], &processTime[1], &processTime[2], &processTime[3]))
1474 ULARGE_INTEGER timeCreation;
1475 timeCreation.LowPart = processTime[0].dwLowDateTime;
1476 timeCreation.HighPart = processTime[0].dwHighDateTime;
1477 if(timeCreation.QuadPart > lastStartTime.QuadPart)
1479 lastStartTime.QuadPart = timeCreation.QuadPart;
1486 LAMEXP_DELETE_ARRAY(processes);
1488 FILETIME lastStartTime_fileTime;
1489 lastStartTime_fileTime.dwHighDateTime = lastStartTime.HighPart;
1490 lastStartTime_fileTime.dwLowDateTime = lastStartTime.LowPart;
1492 FILETIME lastStartTime_localTime;
1493 if(!FileTimeToLocalFileTime(&lastStartTime_fileTime, &lastStartTime_localTime))
1495 memcpy(&lastStartTime_localTime, &lastStartTime_fileTime, sizeof(FILETIME));
1498 SYSTEMTIME lastStartTime_system;
1499 if(!FileTimeToSystemTime(&lastStartTime_localTime, &lastStartTime_system))
1501 memset(&lastStartTime_system, 0, sizeof(SYSTEMTIME));
1502 lastStartTime_system.wYear = 1970; lastStartTime_system.wMonth = lastStartTime_system.wDay = 1;
1505 const QDate currentDate = QDate::currentDate();
1506 const QDate processDate = QDate(lastStartTime_system.wYear, lastStartTime_system.wMonth, lastStartTime_system.wDay);
1507 return (currentDate >= processDate) ? currentDate : processDate;
1511 * Show system message box
1513 int lamexp_system_message(const wchar_t *text, int beepType)
1515 UINT flags = MB_OK | MB_TOPMOST;
1519 case lamexp_beep_info: flags = flags | MB_ICONASTERISK;
1520 case lamexp_beep_warning: flags = flags | MB_ICONEXCLAMATION;
1521 case lamexp_beep_error: flags = flags | MB_ICONHAND;
1524 return MessageBoxW(NULL, text, L"LameXP", flags);
1528 * Block window "move" message
1530 bool lamexp_block_window_move(void *message)
1534 MSG *msg = reinterpret_cast<MSG*>(message);
1535 if((msg->message == WM_SYSCOMMAND) && (msg->wParam == SC_MOVE))
1539 if((msg->message == WM_NCLBUTTONDOWN) && (msg->wParam == HTCAPTION))
1548 * Suspend calling thread for N milliseconds
1550 inline void lamexp_sleep(const unsigned int delay)
1555 bool lamexp_beep(int beepType)
1559 case lamexp_beep_info: return MessageBeep(MB_ICONASTERISK) == TRUE; break;
1560 case lamexp_beep_warning: return MessageBeep(MB_ICONEXCLAMATION) == TRUE; break;
1561 case lamexp_beep_error: return MessageBeep(MB_ICONHAND) == TRUE; break;
1562 default: return false;
1567 * Play a sound (from resources)
1569 bool lamexp_play_sound(const QString &name, const bool bAsync)
1571 const unsigned char *data = NULL;
1573 //Try to look-up the sound in the cache first
1576 QReadLocker readLock(&g_lamexp_sounds.lock);
1577 if(g_lamexp_sounds.sound_db && g_lamexp_sounds.sound_db->contains(name))
1579 data = g_lamexp_sounds.sound_db->value(name);
1583 //If data not found in cache, try to load from resource!
1584 if((!data) && (!name.isEmpty()))
1586 QResource resource(QString(":/sounds/%1.wav").arg(name));
1587 if(resource.isValid() && (data = resource.data()))
1589 QWriteLocker writeLock(&g_lamexp_sounds.lock);
1590 if(!g_lamexp_sounds.sound_db)
1592 g_lamexp_sounds.sound_db = new QHash<const QString, const unsigned char*>();
1594 g_lamexp_sounds.sound_db->insert(name, data);
1598 qWarning("Sound effect \"%s\" not found!", QUTF8(name));
1602 //Play the sound, if availbale
1605 return PlaySound(LPCWSTR(data), NULL, (SND_MEMORY | (bAsync ? SND_ASYNC : SND_SYNC))) != FALSE;
1612 * Play a sound (system alias)
1614 bool lamexp_play_sound_alias(const QString &alias, const bool bAsync)
1616 return PlaySound(QWCHAR(alias), GetModuleHandle(NULL), (SND_ALIAS | (bAsync ? SND_ASYNC : SND_SYNC))) != FALSE;
1620 * Play a sound (from external DLL)
1622 bool lamexp_play_sound_file(const QString &library, const unsigned short uiSoundIdx, const bool bAsync)
1624 bool result = false;
1626 QFileInfo libraryFile(library);
1627 if(!libraryFile.isAbsolute())
1629 const QString &systemDir = lamexp_known_folder(lamexp_folder_systemfolder);
1630 if(!systemDir.isEmpty())
1632 libraryFile.setFile(QDir(systemDir), libraryFile.fileName());
1636 if(libraryFile.exists() && libraryFile.isFile())
1638 if(HMODULE module = LoadLibraryW(QWCHAR(QDir::toNativeSeparators(libraryFile.canonicalFilePath()))))
1640 result = (PlaySound(MAKEINTRESOURCE(uiSoundIdx), module, (SND_RESOURCE | (bAsync ? SND_ASYNC : SND_SYNC))) != FALSE);
1641 FreeLibrary(module);
1646 qWarning("PlaySound: File \"%s\" could not be found!", QUTF8(libraryFile.absoluteFilePath()));
1653 * Open file using the shell
1655 bool lamexp_exec_shell(const QWidget *win, const QString &url, const bool explore)
1657 return lamexp_exec_shell(win, url, QString(), QString(), explore);
1661 * Open file using the shell (with parameters)
1663 bool lamexp_exec_shell(const QWidget *win, const QString &url, const QString ¶meters, const QString &directory, const bool explore)
1665 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;
1669 * Query value of the performance counter
1671 __int64 lamexp_perfcounter_value(void)
1673 LARGE_INTEGER counter;
1674 if(QueryPerformanceCounter(&counter) == TRUE)
1676 return counter.QuadPart;
1682 * Query frequency of the performance counter
1684 __int64 lamexp_perfcounter_frequ(void)
1686 LARGE_INTEGER frequency;
1687 if(QueryPerformanceFrequency(&frequency) == TRUE)
1689 return frequency.QuadPart;
1695 * Insert entry to the window's system menu
1697 bool lamexp_append_sysmenu(const QWidget *win, const unsigned int identifier, const QString &text)
1701 if(HMENU hMenu = GetSystemMenu(win->winId(), FALSE))
1703 ok = (AppendMenuW(hMenu, MF_SEPARATOR, 0, 0) == TRUE);
1704 ok = (AppendMenuW(hMenu, MF_STRING, identifier, QWCHAR(text)) == TRUE);
1711 * Insert entry to the window's system menu
1713 bool lamexp_check_sysmenu_msg(void *message, const unsigned int identifier)
1715 return (((MSG*)message)->message == WM_SYSCOMMAND) && ((((MSG*)message)->wParam & 0xFFF0) == identifier);
1719 * Update system menu entry
1721 bool lamexp_update_sysmenu(const QWidget *win, const unsigned int identifier, const QString &text)
1725 if(HMENU hMenu = ::GetSystemMenu(win->winId(), FALSE))
1727 ok = (ModifyMenu(hMenu, identifier, MF_STRING | MF_BYCOMMAND, identifier, QWCHAR(text)) == TRUE);
1733 * Display the window's close button
1735 bool lamexp_enable_close_button(const QWidget *win, const bool bEnable)
1739 if(HMENU hMenu = GetSystemMenu(win->winId(), FALSE))
1741 ok = (EnableMenuItem(hMenu, SC_CLOSE, MF_BYCOMMAND | (bEnable ? MF_ENABLED : MF_GRAYED)) == TRUE);
1748 * Check whether ESC key has been pressed since the previous call to this function
1750 bool lamexp_check_escape_state(void)
1752 return (GetAsyncKeyState(VK_ESCAPE) & 0x0001) != 0;
1756 * Set the process priority class for current process
1758 bool lamexp_change_process_priority(const int priority)
1760 return lamexp_change_process_priority(GetCurrentProcess(), priority);
1764 * Set the process priority class for specified process
1766 bool lamexp_change_process_priority(const QProcess *proc, const int priority)
1768 if(Q_PID qPid = proc->pid())
1770 return lamexp_change_process_priority(qPid->hProcess, priority);
1779 * Set the process priority class for specified process
1781 bool lamexp_change_process_priority(void *hProcess, const int priority)
1785 switch(qBound(-2, priority, 2))
1788 ok = (SetPriorityClass(hProcess, HIGH_PRIORITY_CLASS) == TRUE);
1791 if(!(ok = (SetPriorityClass(hProcess, ABOVE_NORMAL_PRIORITY_CLASS) == TRUE)))
1793 ok = (SetPriorityClass(hProcess, HIGH_PRIORITY_CLASS) == TRUE);
1797 ok = (SetPriorityClass(hProcess, NORMAL_PRIORITY_CLASS) == TRUE);
1800 if(!(ok = (SetPriorityClass(hProcess, BELOW_NORMAL_PRIORITY_CLASS) == TRUE)))
1802 ok = (SetPriorityClass(hProcess, IDLE_PRIORITY_CLASS) == TRUE);
1806 ok = (SetPriorityClass(hProcess, IDLE_PRIORITY_CLASS) == TRUE);
1814 * Returns the current file time
1816 unsigned __int64 lamexp_current_file_time(void)
1819 GetSystemTimeAsFileTime(&fileTime);
1821 ULARGE_INTEGER temp;
1822 temp.HighPart = fileTime.dwHighDateTime;
1823 temp.LowPart = fileTime.dwLowDateTime;
1825 return temp.QuadPart;
1829 * Bring the specifed window to the front
1831 bool lamexp_bring_to_front(const QWidget *window)
1837 for(int i = 0; (i < 5) && (!ret); i++)
1839 ret = (SetForegroundWindow(window->winId()) != FALSE);
1840 SwitchToThisWindow(window->winId(), TRUE);
1842 LockSetForegroundWindow(LSFW_LOCK);
1849 * Bring window of the specifed process to the front (callback)
1851 static BOOL CALLBACK lamexp_bring_process_to_front_helper(HWND hwnd, LPARAM lParam)
1853 DWORD processId = *reinterpret_cast<WORD*>(lParam);
1854 DWORD windowProcessId = NULL;
1855 GetWindowThreadProcessId(hwnd, &windowProcessId);
1856 if(windowProcessId == processId)
1858 SwitchToThisWindow(hwnd, TRUE);
1859 SetForegroundWindow(hwnd);
1867 * Bring window of the specifed process to the front
1869 bool lamexp_bring_process_to_front(const unsigned long pid)
1871 return EnumWindows(lamexp_bring_process_to_front_helper, reinterpret_cast<LPARAM>(&pid)) == TRUE;
1875 * Check the network connectivity status
1877 int lamexp_network_status(void)
1880 const BOOL ret = IsNetworkAlive(&dwFlags);
1881 if(GetLastError() == 0)
1883 return (ret != FALSE) ? lamexp_network_yes : lamexp_network_non;
1885 return lamexp_network_err;
1889 * Retrun the process ID of the given QProcess
1891 unsigned long lamexp_process_id(const QProcess *proc)
1893 PROCESS_INFORMATION *procInf = proc->pid();
1894 return (procInf) ? procInf->dwProcessId : NULL;
1898 * Convert long path to short path
1900 QString lamexp_path_to_short(const QString &longPath)
1903 DWORD buffSize = GetShortPathNameW(reinterpret_cast<const wchar_t*>(longPath.utf16()), NULL, NULL);
1907 wchar_t *buffer = new wchar_t[buffSize];
1908 DWORD result = GetShortPathNameW(reinterpret_cast<const wchar_t*>(longPath.utf16()), buffer, buffSize);
1910 if(result > 0 && result < buffSize)
1912 shortPath = QString::fromUtf16(reinterpret_cast<const unsigned short*>(buffer));
1918 return (shortPath.isEmpty() ? longPath : shortPath);
1922 * Open media file in external player
1924 bool lamexp_open_media_file(const QString &mediaFilePath)
1926 const static wchar_t *registryPrefix[2] = { L"SOFTWARE\\", L"SOFTWARE\\Wow6432Node\\" };
1927 const static wchar_t *registryKeys[3] =
1929 L"Microsoft\\Windows\\CurrentVersion\\Uninstall\\{97D341C8-B0D1-4E4A-A49A-C30B52F168E9}",
1930 L"Microsoft\\Windows\\CurrentVersion\\Uninstall\\{DB9E4EAB-2717-499F-8D56-4CC8A644AB60}",
1933 const static wchar_t *appNames[4] = { L"smplayer_portable.exe", L"smplayer.exe", L"MPUI.exe", L"foobar2000.exe" };
1934 const static wchar_t *valueNames[2] = { L"InstallLocation", L"InstallDir" };
1936 for(size_t i = 0; i < 3; i++)
1938 for(size_t j = 0; j < 2; j++)
1940 QString mplayerPath;
1941 HKEY registryKeyHandle = NULL;
1943 const QString currentKey = WCHAR2QSTR(registryPrefix[j]).append(WCHAR2QSTR(registryKeys[i]));
1944 if(RegOpenKeyExW(HKEY_LOCAL_MACHINE, QWCHAR(currentKey), 0, KEY_READ, ®istryKeyHandle) == ERROR_SUCCESS)
1946 for(size_t k = 0; k < 2; k++)
1948 wchar_t Buffer[4096];
1949 DWORD BuffSize = sizeof(wchar_t*) * 4096;
1950 DWORD DataType = REG_NONE;
1951 if(RegQueryValueExW(registryKeyHandle, valueNames[k], 0, &DataType, reinterpret_cast<BYTE*>(Buffer), &BuffSize) == ERROR_SUCCESS)
1953 if((DataType == REG_SZ) || (DataType == REG_EXPAND_SZ) || (DataType == REG_LINK))
1955 mplayerPath = WCHAR2QSTR(Buffer);
1960 RegCloseKey(registryKeyHandle);
1963 if(!mplayerPath.isEmpty())
1965 QDir mplayerDir(mplayerPath);
1966 if(mplayerDir.exists())
1968 for(size_t k = 0; k < 4; k++)
1970 if(mplayerDir.exists(WCHAR2QSTR(appNames[k])))
1972 qDebug("Player found at:\n%s\n", QUTF8(mplayerDir.absoluteFilePath(WCHAR2QSTR(appNames[k]))));
1973 QProcess::startDetached(mplayerDir.absoluteFilePath(WCHAR2QSTR(appNames[k])), QStringList() << QDir::toNativeSeparators(mediaFilePath));
1984 static void lamexp_init_dwmapi(void)
1986 QReadLocker writeLock(&g_lamexp_dwmapi.lock);
1988 //Not initialized yet?
1989 if(g_lamexp_dwmapi.bInitialized)
1994 //Reset function pointers
1995 g_lamexp_dwmapi.dwmIsCompositionEnabled = NULL;
1996 g_lamexp_dwmapi.dwmExtendFrameIntoClientArea = NULL;
1997 g_lamexp_dwmapi.dwmEnableBlurBehindWindow = NULL;
1999 //Does OS support DWM?
2000 if(lamexp_get_os_version() >= lamexp_winver_vista)
2003 g_lamexp_dwmapi.dwmapi_dll = new QLibrary("dwmapi.dll");
2004 if(g_lamexp_dwmapi.dwmapi_dll->load())
2006 //Initialize function pointers
2007 g_lamexp_dwmapi.dwmIsCompositionEnabled = (HRESULT (__stdcall*)(BOOL*)) g_lamexp_dwmapi.dwmapi_dll->resolve("DwmIsCompositionEnabled");
2008 g_lamexp_dwmapi.dwmExtendFrameIntoClientArea = (HRESULT (__stdcall*)(HWND, const MARGINS*)) g_lamexp_dwmapi.dwmapi_dll->resolve("DwmExtendFrameIntoClientArea");
2009 g_lamexp_dwmapi.dwmEnableBlurBehindWindow = (HRESULT (__stdcall*)(HWND, const DWM_BLURBEHIND*)) g_lamexp_dwmapi.dwmapi_dll->resolve("DwmEnableBlurBehindWindow");
2013 LAMEXP_DELETE(g_lamexp_dwmapi.dwmapi_dll);
2014 qWarning("Failed to load DWMAPI.DLL on a DWM-enabled system!");
2018 g_lamexp_dwmapi.bInitialized = true;
2022 * Enable "sheet of glass" effect on the given Window
2024 bool lamexp_sheet_of_glass(QWidget *window)
2026 QReadLocker readLock(&g_lamexp_dwmapi.lock);
2028 //Initialize the DWM API
2029 while(!g_lamexp_dwmapi.bInitialized)
2032 lamexp_init_dwmapi();
2036 BOOL bCompositionEnabled = FALSE;
2038 //Required functions available?
2039 if((g_lamexp_dwmapi.dwmIsCompositionEnabled != NULL) && (g_lamexp_dwmapi.dwmExtendFrameIntoClientArea != NULL) && (g_lamexp_dwmapi.dwmEnableBlurBehindWindow != NULL))
2041 //Check if composition is currently enabled
2042 if(HRESULT hr = g_lamexp_dwmapi.dwmIsCompositionEnabled(&bCompositionEnabled))
2044 qWarning("DwmIsCompositionEnabled function has failed! (error %d)", hr);
2049 //All functions available *and* composition enabled?
2050 if(!bCompositionEnabled)
2055 //Enable the "sheet of glass" effect on this window
2056 MARGINS margins = {-1, -1, -1, -1};
2057 if(HRESULT hr = g_lamexp_dwmapi.dwmExtendFrameIntoClientArea(window->winId(), &margins))
2059 qWarning("DwmExtendFrameIntoClientArea function has failed! (error %d)", hr);
2063 //Create and populate the Blur Behind structure
2065 memset(&bb, 0, sizeof(DWM_BLURBEHIND));
2067 bb.dwFlags = DWM_BB_ENABLE;
2068 if(HRESULT hr = g_lamexp_dwmapi.dwmEnableBlurBehindWindow(window->winId(), &bb))
2070 qWarning("DwmEnableBlurBehindWindow function has failed! (error %d)", hr);
2075 window->setAutoFillBackground(false);
2076 window->setAttribute(Qt::WA_TranslucentBackground);
2077 window->setAttribute(Qt::WA_NoSystemBackground);
2083 * Update "sheet of glass" effect on the given Window
2085 bool lamexp_sheet_of_glass_update(QWidget *window)
2087 QReadLocker readLock(&g_lamexp_dwmapi.lock);
2089 //Initialize the DWM API
2090 while(!g_lamexp_dwmapi.bInitialized)
2093 lamexp_init_dwmapi();
2097 BOOL bCompositionEnabled = FALSE;
2099 //Required functions available?
2100 if((g_lamexp_dwmapi.dwmIsCompositionEnabled != NULL) && (g_lamexp_dwmapi.dwmEnableBlurBehindWindow != NULL))
2102 //Check if composition is currently enabled
2103 if(HRESULT hr = g_lamexp_dwmapi.dwmIsCompositionEnabled(&bCompositionEnabled))
2105 qWarning("DwmIsCompositionEnabled function has failed! (error %d)", hr);
2110 //All functions available *and* composition enabled?
2111 if(!bCompositionEnabled)
2116 //Create and populate the Blur Behind structure
2118 memset(&bb, 0, sizeof(DWM_BLURBEHIND));
2120 bb.dwFlags = DWM_BB_ENABLE;
2121 if(HRESULT hr = g_lamexp_dwmapi.dwmEnableBlurBehindWindow(window->winId(), &bb))
2123 qWarning("DwmEnableBlurBehindWindow function has failed! (error %d)", hr);
2131 * Update the window icon
2133 lamexp_icon_t *lamexp_set_window_icon(QWidget *window, const QIcon &icon, const bool bIsBigIcon)
2137 const int extend = (bIsBigIcon ? 32 : 16);
2138 if(HICON hIcon = lamexp_qicon2hicon(icon, extend, extend))
2140 SendMessage(window->winId(), WM_SETICON, (bIsBigIcon ? ICON_BIG : ICON_SMALL), LPARAM(hIcon));
2141 return reinterpret_cast<lamexp_icon_t*>(hIcon);
2150 void lamexp_free_window_icon(lamexp_icon_t *icon)
2152 if(HICON hIcon = reinterpret_cast<HICON>(icon))
2159 * Get system color info
2161 QColor lamexp_system_color(const int color_id)
2167 case lamexp_syscolor_text:
2168 nIndex = COLOR_WINDOWTEXT; /*Text in windows*/
2170 case lamexp_syscolor_background:
2171 nIndex = COLOR_WINDOW; /*Window background*/
2173 case lamexp_syscolor_caption:
2174 nIndex = COLOR_CAPTIONTEXT; /*Text in caption, size box, and scroll bar arrow box*/
2177 qWarning("Unknown system color id (%d) specified!", color_id);
2178 nIndex = COLOR_WINDOWTEXT;
2181 const DWORD rgb = GetSysColor(nIndex);
2182 QColor color(GetRValue(rgb), GetGValue(rgb), GetBValue(rgb));
2187 * Check if the current user is an administartor (helper function)
2189 static bool lamexp_user_is_admin_helper(void)
2191 HANDLE hToken = NULL;
2192 if(!OpenProcessToken(GetCurrentProcess(), TOKEN_QUERY, &hToken))
2198 if(!GetTokenInformation(hToken, TokenGroups, NULL, 0, &dwSize))
2200 if(GetLastError() != ERROR_INSUFFICIENT_BUFFER)
2202 CloseHandle(hToken);
2207 PTOKEN_GROUPS lpGroups = (PTOKEN_GROUPS) malloc(dwSize);
2210 CloseHandle(hToken);
2214 if(!GetTokenInformation(hToken, TokenGroups, lpGroups, dwSize, &dwSize))
2217 CloseHandle(hToken);
2221 PSID lpSid = NULL; SID_IDENTIFIER_AUTHORITY Authority = {SECURITY_NT_AUTHORITY};
2222 if(!AllocateAndInitializeSid(&Authority, 2, SECURITY_BUILTIN_DOMAIN_RID, DOMAIN_ALIAS_RID_ADMINS, 0, 0, 0, 0, 0, 0, &lpSid))
2225 CloseHandle(hToken);
2229 bool bResult = false;
2230 for(DWORD i = 0; i < lpGroups->GroupCount; i++)
2232 if(EqualSid(lpSid, lpGroups->Groups[i].Sid))
2241 CloseHandle(hToken);
2246 * Check if the current user is an administartor
2248 bool lamexp_user_is_admin(void)
2250 bool isAdmin = false;
2252 //Check for process elevation and UAC support first!
2253 if(lamexp_process_is_elevated(&isAdmin))
2255 qWarning("Process is elevated -> user is admin!");
2259 //If not elevated and UAC is not available -> user must be in admin group!
2262 qDebug("UAC is disabled/unavailable -> checking for Administrators group");
2263 isAdmin = lamexp_user_is_admin_helper();
2270 * Check if file is a valid Win32/Win64 executable
2272 bool lamexp_is_executable(const QString &path)
2274 bool bIsExecutable = false;
2276 if(GetBinaryType(QWCHAR(QDir::toNativeSeparators(path)), &binaryType))
2278 bIsExecutable = (binaryType == SCS_32BIT_BINARY || binaryType == SCS_64BIT_BINARY);
2280 return bIsExecutable;
2284 * Fatal application exit
2286 #pragma intrinsic(_InterlockedExchange)
2287 void lamexp_fatal_exit(const wchar_t* exitMessage, const wchar_t* errorBoxMessage)
2289 static volatile long bFatalFlag = 0L;
2291 if(_InterlockedExchange(&bFatalFlag, 1L) == 0L)
2293 if(GetCurrentThreadId() != g_main_thread_id)
2295 HANDLE mainThread = OpenThread(THREAD_TERMINATE, FALSE, g_main_thread_id);
2296 if(mainThread) TerminateThread(mainThread, ULONG_MAX);
2301 MessageBoxW(NULL, errorBoxMessage, L"LameXP - GURU MEDITATION", MB_ICONERROR | MB_TOPMOST | MB_TASKMODAL);
2306 FatalAppExit(0, exitMessage);
2307 TerminateProcess(GetCurrentProcess(), -1);
2311 TerminateThread(GetCurrentThread(), -1);
2316 * Initialize debug thread
2318 static const HANDLE g_debug_thread1 = LAMEXP_DEBUG ? NULL : lamexp_debug_thread_init();
2321 * Get number private bytes [debug only]
2323 unsigned long lamexp_dbg_private_bytes(void)
2326 for(int i = 0; i < 8; i++) _heapmin();
2327 PROCESS_MEMORY_COUNTERS_EX memoryCounters;
2328 memoryCounters.cb = sizeof(PROCESS_MEMORY_COUNTERS_EX);
2329 GetProcessMemoryInfo(GetCurrentProcess(), (PPROCESS_MEMORY_COUNTERS) &memoryCounters, sizeof(PROCESS_MEMORY_COUNTERS_EX));
2330 return memoryCounters.PrivateUsage;
2332 THROW("Cannot call this function in a non-debug build!");
2333 #endif //LAMEXP_DEBUG
2337 * Output string to debugger [debug only]
2339 void lamexp_dbg_dbg_output_string(const char* format, ...)
2344 va_start (args, format);
2345 vsnprintf_s(buffer, 256, _TRUNCATE, format, args);
2346 OutputDebugStringA(buffer);
2349 THROW("Cannot call this function in a non-debug build!");
2350 #endif //LAMEXP_DEBUG
2353 ///////////////////////////////////////////////////////////////////////////////
2355 ///////////////////////////////////////////////////////////////////////////////
2357 extern "C" void _lamexp_global_init_win32(void)
2359 if((!LAMEXP_DEBUG) && lamexp_check_for_debugger())
2361 lamexp_fatal_exit(L"Not a debug build. Please unload debugger and try again!");
2364 //Zero *before* constructors are called
2365 LAMEXP_ZERO_MEMORY(g_lamexp_argv);
2366 LAMEXP_ZERO_MEMORY(g_lamexp_known_folder);
2367 LAMEXP_ZERO_MEMORY(g_lamexp_os_version);
2368 LAMEXP_ZERO_MEMORY(g_lamexp_wine);
2369 LAMEXP_ZERO_MEMORY(g_lamexp_themes_enabled);
2370 LAMEXP_ZERO_MEMORY(g_lamexp_dwmapi);
2371 LAMEXP_ZERO_MEMORY(g_lamexp_sounds);
2374 ///////////////////////////////////////////////////////////////////////////////
2376 ///////////////////////////////////////////////////////////////////////////////
2378 extern "C" void _lamexp_global_free_win32(void)
2380 //Clear folder cache
2381 LAMEXP_DELETE(g_lamexp_known_folder.knownFolders);
2383 //Destroy Qt application object
2384 QApplication *application = dynamic_cast<QApplication*>(QApplication::instance());
2385 LAMEXP_DELETE(application);
2388 g_lamexp_dwmapi.dwmIsCompositionEnabled = NULL;
2389 g_lamexp_dwmapi.dwmExtendFrameIntoClientArea = NULL;
2390 g_lamexp_dwmapi.dwmEnableBlurBehindWindow = NULL;
2391 LAMEXP_DELETE(g_lamexp_dwmapi.dwmapi_dll);
2393 //Free STDOUT and STDERR buffers
2394 if(g_lamexp_console_attached)
2396 if(std::filebuf *tmp = dynamic_cast<std::filebuf*>(std::cout.rdbuf()))
2398 std::cout.rdbuf(NULL);
2401 if(std::filebuf *tmp = dynamic_cast<std::filebuf*>(std::cerr.rdbuf()))
2403 std::cerr.rdbuf(NULL);
2409 if(g_lamexp_log_file)
2411 fclose(g_lamexp_log_file);
2412 g_lamexp_log_file = NULL;
2416 LAMEXP_DELETE(g_lamexp_sounds.sound_db);
2418 //Free CLI Arguments
2419 LAMEXP_DELETE(g_lamexp_argv.list);