1 ///////////////////////////////////////////////////////////////////////////////
2 // LameXP - Audio Encoder Front-End
3 // Copyright (C) 2004-2013 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>
66 #define LAMEXP_INC_CONFIG
82 //Initialize static Qt plugins
84 #if QT_VERSION < QT_VERSION_CHECK(5,0,0)
88 Q_IMPORT_PLUGIN(QWindowsIntegrationPlugin)
89 Q_IMPORT_PLUGIN(QICOPlugin)
93 ///////////////////////////////////////////////////////////////////////////////
95 ///////////////////////////////////////////////////////////////////////////////
97 #define _LAMEXP_MAKE_STR(STR) #STR
98 #define LAMEXP_MAKE_STR(STR) _LAMEXP_MAKE_STR(STR)
101 #define CLEAN_OUTPUT_STRING(STR) do \
103 const char CTRL_CHARS[3] = { '\r', '\n', '\t' }; \
104 for(size_t i = 0; i < 3; i++) \
106 while(char *pos = strchr((STR), CTRL_CHARS[i])) *pos = char(0x20); \
112 #define TRIM_LEFT(STR) do \
114 const char WHITE_SPACE[4] = { char(0x20), '\r', '\n', '\t' }; \
115 for(size_t i = 0; i < 4; i++) \
117 while(*(STR) == WHITE_SPACE[i]) (STR)++; \
122 ///////////////////////////////////////////////////////////////////////////////
124 ///////////////////////////////////////////////////////////////////////////////
126 //Console attached flag
127 static bool g_lamexp_console_attached = false;
132 QMap<size_t, QString> *knownFolders;
135 g_lamexp_known_folder;
149 lamexp_os_version_t version;
163 //Win32 Theme support
170 g_lamexp_themes_enabled;
173 static const char *g_lamexp_imageformats[] = {"bmp", "png", "jpg", "gif", "ico", "xpm", NULL}; //"svg"
176 static QMutex g_lamexp_message_mutex;
179 static const DWORD g_main_thread_id = GetCurrentThreadId();
182 static FILE *g_lamexp_log_file = NULL;
185 const char* LAMEXP_DEFAULT_LANGID = "en";
186 const char* LAMEXP_DEFAULT_TRANSLATION = "LameXP_EN.qm";
188 //Known Windows versions - maps marketing names to the actual Windows NT versions
189 const lamexp_os_version_t lamexp_winver_win2k = {5,0};
190 const lamexp_os_version_t lamexp_winver_winxp = {5,1};
191 const lamexp_os_version_t lamexp_winver_xpx64 = {5,2};
192 const lamexp_os_version_t lamexp_winver_vista = {6,0};
193 const lamexp_os_version_t lamexp_winver_win70 = {6,1};
194 const lamexp_os_version_t lamexp_winver_win80 = {6,2};
195 const lamexp_os_version_t lamexp_winver_win81 = {6,3};
198 static const char *GURU_MEDITATION = "\n\nGURU MEDITATION !!!\n\n";
200 ///////////////////////////////////////////////////////////////////////////////
202 ///////////////////////////////////////////////////////////////////////////////
205 * Verify a specific Windows version
207 static bool lamexp_verify_os_version(const DWORD major, const DWORD minor)
209 OSVERSIONINFOEXW osvi;
210 DWORDLONG dwlConditionMask = 0;
212 //Initialize the OSVERSIONINFOEX structure
213 memset(&osvi, 0, sizeof(OSVERSIONINFOEXW));
214 osvi.dwOSVersionInfoSize = sizeof(OSVERSIONINFOEXW);
215 osvi.dwMajorVersion = major;
216 osvi.dwMinorVersion = minor;
217 osvi.dwPlatformId = VER_PLATFORM_WIN32_NT;
219 //Initialize the condition mask
220 VER_SET_CONDITION(dwlConditionMask, VER_MAJORVERSION, VER_GREATER_EQUAL);
221 VER_SET_CONDITION(dwlConditionMask, VER_MINORVERSION, VER_GREATER_EQUAL);
222 VER_SET_CONDITION(dwlConditionMask, VER_PLATFORMID, VER_EQUAL);
225 const BOOL ret = VerifyVersionInfoW(&osvi, VER_MAJORVERSION | VER_MINORVERSION | VER_PLATFORMID, dwlConditionMask);
230 if(GetLastError() != ERROR_OLD_WIN_VERSION)
232 qWarning("VerifyVersionInfo() system call has failed!");
236 return (ret != FALSE);
240 * Determine the *real* Windows version
242 static bool lamexp_get_real_os_version(unsigned int *major, unsigned int *minor, bool *pbOverride)
247 //Initialize local variables
248 OSVERSIONINFOEXW osvi;
249 memset(&osvi, 0, sizeof(OSVERSIONINFOEXW));
250 osvi.dwOSVersionInfoSize = sizeof(OSVERSIONINFOEXW);
252 //Try GetVersionEx() first
253 if(GetVersionExW((LPOSVERSIONINFOW)&osvi) == FALSE)
255 qWarning("GetVersionEx() has failed, cannot detect Windows version!");
259 //Make sure we are running on NT
260 if(osvi.dwPlatformId == VER_PLATFORM_WIN32_NT)
262 *major = osvi.dwMajorVersion;
263 *minor = osvi.dwMinorVersion;
267 qWarning("Not running on Windows NT, unsupported operating system!");
271 //Determine the real *major* version first
274 const DWORD nextMajor = (*major) + 1;
275 if(lamexp_verify_os_version(nextMajor, 0))
285 //Now also determine the real *minor* version
288 const DWORD nextMinor = (*minor) + 1;
289 if(lamexp_verify_os_version((*major), nextMinor))
302 * Get the native operating system version
304 const lamexp_os_version_t &lamexp_get_os_version(void)
306 QReadLocker readLock(&g_lamexp_os_version.lock);
308 //Already initialized?
309 if(g_lamexp_os_version.bInitialized)
311 return g_lamexp_os_version.version;
315 QWriteLocker writeLock(&g_lamexp_os_version.lock);
318 if(!g_lamexp_os_version.bInitialized)
320 unsigned int major, minor; bool oflag;
321 if(lamexp_get_real_os_version(&major, &minor, &oflag))
323 g_lamexp_os_version.version.versionMajor = major;
324 g_lamexp_os_version.version.versionMinor = minor;
325 g_lamexp_os_version.version.overrideFlag = oflag;
326 g_lamexp_os_version.bInitialized = true;
330 qWarning("Failed to determin the operating system version!");
334 return g_lamexp_os_version.version;
338 * Check if we are running under wine
340 bool lamexp_detect_wine(void)
342 QReadLocker readLock(&g_lamexp_wine.lock);
344 //Already initialized?
345 if(g_lamexp_wine.bInitialized)
347 return g_lamexp_wine.bIsWine;
351 QWriteLocker writeLock(&g_lamexp_wine.lock);
353 if(!g_lamexp_wine.bInitialized)
355 g_lamexp_wine.bIsWine = false;
356 QLibrary ntdll("ntdll.dll");
359 if(ntdll.resolve("wine_nt_to_unix_file_name") != NULL) g_lamexp_wine.bIsWine = true;
360 if(ntdll.resolve("wine_get_version") != NULL) g_lamexp_wine.bIsWine = true;
363 g_lamexp_wine.bInitialized = true;
366 return g_lamexp_wine.bIsWine;
370 * Change console text color
372 static void lamexp_console_color(FILE* file, WORD attributes)
374 const HANDLE hConsole = (HANDLE)(_get_osfhandle(_fileno(file)));
375 if((hConsole != NULL) && (hConsole != INVALID_HANDLE_VALUE))
377 SetConsoleTextAttribute(hConsole, attributes);
382 * Output logging message to console
384 static void lamexp_write_console(const int type, const char *msg)
388 if(_isatty(_fileno(stderr)))
390 UINT oldOutputCP = GetConsoleOutputCP();
391 if(oldOutputCP != CP_UTF8) SetConsoleOutputCP(CP_UTF8);
397 lamexp_console_color(stderr, FOREGROUND_RED | FOREGROUND_INTENSITY);
398 fprintf(stderr, GURU_MEDITATION);
399 fprintf(stderr, "%s\n", msg);
403 lamexp_console_color(stderr, FOREGROUND_GREEN | FOREGROUND_RED | FOREGROUND_INTENSITY);
404 fprintf(stderr, "%s\n", msg);
408 lamexp_console_color(stderr, FOREGROUND_BLUE | FOREGROUND_GREEN | FOREGROUND_RED | FOREGROUND_INTENSITY);
409 fprintf(stderr, "%s\n", msg);
414 lamexp_console_color(stderr, FOREGROUND_BLUE | FOREGROUND_GREEN | FOREGROUND_RED);
415 if(oldOutputCP != CP_UTF8) SetConsoleOutputCP(oldOutputCP);
420 /*ignore any exception that might occur here!*/
425 * Output logging message to debugger
427 static void lamexp_write_dbg_out(const int type, const char *msg)
429 const char *FORMAT = "[LameXP][%c] %s\n";
434 const char* input = msg;
441 _snprintf_s(buffer, 512, _TRUNCATE, FORMAT, 'C', input);
444 _snprintf_s(buffer, 512, _TRUNCATE, FORMAT, 'W', input);
447 _snprintf_s(buffer, 512, _TRUNCATE, FORMAT, 'I', input);
451 char *temp = &buffer[0];
452 CLEAN_OUTPUT_STRING(temp);
453 OutputDebugStringA(temp);
457 /*ignore any exception that might occur here!*/
462 * Output logging message to logfile
464 static void lamexp_write_logfile(const int type, const char *msg)
466 const char *FORMAT = "[%c][%04u] %s\r\n";
470 if(g_lamexp_log_file)
473 strncpy_s(buffer, 512, msg, _TRUNCATE);
475 char *temp = &buffer[0];
477 CLEAN_OUTPUT_STRING(temp);
479 const unsigned int timestamp = static_cast<unsigned int>(_time64(NULL) % 3600I64);
485 fprintf(g_lamexp_log_file, FORMAT, 'C', timestamp, temp);
488 fprintf(g_lamexp_log_file, FORMAT, 'W', timestamp, temp);
491 fprintf(g_lamexp_log_file, FORMAT, 'I', timestamp, temp);
495 fflush(g_lamexp_log_file);
500 /*ignore any exception that might occur here!*/
507 void lamexp_message_handler(QtMsgType type, const char *msg)
509 if((!msg) || (!(msg[0])))
514 QMutexLocker lock(&g_lamexp_message_mutex);
516 if(g_lamexp_log_file)
518 lamexp_write_logfile(type, msg);
521 if(g_lamexp_console_attached)
523 lamexp_write_console(type, msg);
527 lamexp_write_dbg_out(type, msg);
530 if((type == QtCriticalMsg) || (type == QtFatalMsg))
533 lamexp_fatal_exit(L"The application has encountered a critical error and will exit now!", QWCHAR(QString::fromUtf8(msg)));
538 * Invalid parameters handler
540 static void lamexp_invalid_param_handler(const wchar_t* exp, const wchar_t* fun, const wchar_t* fil, unsigned int, uintptr_t)
542 lamexp_fatal_exit(L"Invalid parameter handler invoked, application will exit!");
548 static void lamexp_signal_handler(int signal_num)
550 signal(signal_num, lamexp_signal_handler);
551 lamexp_fatal_exit(L"Signal handler invoked, application will exit!");
555 * Global exception handler
557 static LONG WINAPI lamexp_exception_handler(struct _EXCEPTION_POINTERS *ExceptionInfo)
559 lamexp_fatal_exit(L"Unhandeled exception handler invoked, application will exit!");
564 * Initialize error handlers
566 void lamexp_init_error_handlers(void)
568 SetErrorMode(SEM_FAILCRITICALERRORS | SEM_NOOPENFILEERRORBOX);
569 SetUnhandledExceptionFilter(lamexp_exception_handler);
570 SetThreadPriority(GetCurrentThread(), THREAD_PRIORITY_ABOVE_NORMAL);
571 _set_invalid_parameter_handler(lamexp_invalid_param_handler);
573 static const int signal_num[6] = { SIGABRT, SIGFPE, SIGILL, SIGINT, SIGSEGV, SIGTERM };
575 for(size_t i = 0; i < 6; i++)
577 signal(signal_num[i], lamexp_signal_handler);
582 * Initialize the console
584 void lamexp_init_console(const QStringList &argv)
586 bool enableConsole = (LAMEXP_DEBUG) || ((VER_LAMEXP_CONSOLE_ENABLED) && lamexp_version_demo());
590 wchar_t *logfile = NULL;
591 size_t logfile_len = 0;
592 if(!_wdupenv_s(&logfile, &logfile_len, L"LAMEXP_LOGFILE"))
594 if(logfile && (logfile_len > 0))
597 if(!_wfopen_s(&temp, logfile, L"wb"))
599 fprintf(temp, "%c%c%c", char(0xEF), char(0xBB), char(0xBF));
600 g_lamexp_log_file = temp;
609 for(int i = 0; i < argv.count(); i++)
611 if(!argv.at(i).compare("--console", Qt::CaseInsensitive))
613 enableConsole = true;
615 else if(!argv.at(i).compare("--no-console", Qt::CaseInsensitive))
617 enableConsole = false;
624 if(!g_lamexp_console_attached)
626 if(AllocConsole() != FALSE)
628 SetConsoleCtrlHandler(NULL, TRUE);
629 SetConsoleTitle(L"LameXP - Audio Encoder Front-End | Debug Console");
630 SetConsoleOutputCP(CP_UTF8);
631 g_lamexp_console_attached = true;
635 if(g_lamexp_console_attached)
637 //-------------------------------------------------------------------
638 //See: http://support.microsoft.com/default.aspx?scid=kb;en-us;105305
639 //-------------------------------------------------------------------
640 const int flags = _O_WRONLY | _O_U8TEXT;
641 int hCrtStdOut = _open_osfhandle((intptr_t) GetStdHandle(STD_OUTPUT_HANDLE), flags);
642 int hCrtStdErr = _open_osfhandle((intptr_t) GetStdHandle(STD_ERROR_HANDLE), flags);
643 FILE *hfStdOut = (hCrtStdOut >= 0) ? _fdopen(hCrtStdOut, "wb") : NULL;
644 FILE *hfStdErr = (hCrtStdErr >= 0) ? _fdopen(hCrtStdErr, "wb") : NULL;
645 if(hfStdOut) { *stdout = *hfStdOut; std::cout.rdbuf(new std::filebuf(hfStdOut)); }
646 if(hfStdErr) { *stderr = *hfStdErr; std::cerr.rdbuf(new std::filebuf(hfStdErr)); }
649 HWND hwndConsole = GetConsoleWindow();
651 if((hwndConsole != NULL) && (hwndConsole != INVALID_HANDLE_VALUE))
653 HMENU hMenu = GetSystemMenu(hwndConsole, 0);
654 EnableMenuItem(hMenu, SC_CLOSE, MF_BYCOMMAND | MF_GRAYED);
655 RemoveMenu(hMenu, SC_CLOSE, MF_BYCOMMAND);
657 SetWindowPos(hwndConsole, HWND_TOP, 0, 0, 0, 0, SWP_NOMOVE|SWP_NOSIZE|SWP_NOZORDER|SWP_FRAMECHANGED);
658 SetWindowLong(hwndConsole, GWL_STYLE, GetWindowLong(hwndConsole, GWL_STYLE) & (~WS_MAXIMIZEBOX) & (~WS_MINIMIZEBOX));
659 SetWindowPos(hwndConsole, HWND_TOP, 0, 0, 0, 0, SWP_NOMOVE|SWP_NOSIZE|SWP_NOZORDER|SWP_FRAMECHANGED);
665 * Detect CPU features
667 lamexp_cpu_t lamexp_detect_cpu_features(const QStringList &argv)
669 typedef BOOL (WINAPI *IsWow64ProcessFun)(__in HANDLE hProcess, __out PBOOL Wow64Process);
671 lamexp_cpu_t features;
672 SYSTEM_INFO systemInfo;
673 int CPUInfo[4] = {-1};
674 char CPUIdentificationString[0x40];
675 char CPUBrandString[0x40];
677 memset(&features, 0, sizeof(lamexp_cpu_t));
678 memset(&systemInfo, 0, sizeof(SYSTEM_INFO));
679 memset(CPUIdentificationString, 0, sizeof(CPUIdentificationString));
680 memset(CPUBrandString, 0, sizeof(CPUBrandString));
683 memcpy(CPUIdentificationString, &CPUInfo[1], sizeof(int));
684 memcpy(CPUIdentificationString + 4, &CPUInfo[3], sizeof(int));
685 memcpy(CPUIdentificationString + 8, &CPUInfo[2], sizeof(int));
686 features.intel = (_stricmp(CPUIdentificationString, "GenuineIntel") == 0);
687 strncpy_s(features.vendor, 0x40, CPUIdentificationString, _TRUNCATE);
692 features.mmx = (CPUInfo[3] & 0x800000) || false;
693 features.sse = (CPUInfo[3] & 0x2000000) || false;
694 features.sse2 = (CPUInfo[3] & 0x4000000) || false;
695 features.ssse3 = (CPUInfo[2] & 0x200) || false;
696 features.sse3 = (CPUInfo[2] & 0x1) || false;
697 features.ssse3 = (CPUInfo[2] & 0x200) || false;
698 features.stepping = CPUInfo[0] & 0xf;
699 features.model = ((CPUInfo[0] >> 4) & 0xf) + (((CPUInfo[0] >> 16) & 0xf) << 4);
700 features.family = ((CPUInfo[0] >> 8) & 0xf) + ((CPUInfo[0] >> 20) & 0xff);
703 __cpuid(CPUInfo, 0x80000000);
704 int nExIds = qMax<int>(qMin<int>(CPUInfo[0], 0x80000004), 0x80000000);
706 for(int i = 0x80000002; i <= nExIds; ++i)
712 memcpy(CPUBrandString, CPUInfo, sizeof(CPUInfo));
715 memcpy(CPUBrandString + 16, CPUInfo, sizeof(CPUInfo));
718 memcpy(CPUBrandString + 32, CPUInfo, sizeof(CPUInfo));
723 strncpy_s(features.brand, 0x40, CPUBrandString, _TRUNCATE);
725 if(strlen(features.brand) < 1) strncpy_s(features.brand, 0x40, "Unknown", _TRUNCATE);
726 if(strlen(features.vendor) < 1) strncpy_s(features.vendor, 0x40, "Unknown", _TRUNCATE);
728 #if (!(defined(_M_X64) || defined(_M_IA64)))
729 QLibrary Kernel32Lib("kernel32.dll");
730 if(IsWow64ProcessFun IsWow64ProcessPtr = (IsWow64ProcessFun) Kernel32Lib.resolve("IsWow64Process"))
732 BOOL x64flag = FALSE;
733 if(IsWow64ProcessPtr(GetCurrentProcess(), &x64flag))
735 features.x64 = (x64flag == TRUE);
742 DWORD_PTR procAffinity, sysAffinity;
743 if(GetProcessAffinityMask(GetCurrentProcess(), &procAffinity, &sysAffinity))
745 for(DWORD_PTR mask = 1; mask; mask <<= 1)
747 features.count += ((sysAffinity & mask) ? (1) : (0));
750 if(features.count < 1)
752 GetNativeSystemInfo(&systemInfo);
753 features.count = qBound(1UL, systemInfo.dwNumberOfProcessors, 64UL);
759 for(int i = 0; i < argv.count(); i++)
761 if(!argv[i].compare("--force-cpu-no-64bit", Qt::CaseInsensitive)) { flag = true; features.x64 = false; }
762 if(!argv[i].compare("--force-cpu-no-sse", Qt::CaseInsensitive)) { flag = true; features.sse = features.sse2 = features.sse3 = features.ssse3 = false; }
763 if(!argv[i].compare("--force-cpu-no-intel", Qt::CaseInsensitive)) { flag = true; features.intel = false; }
765 if(flag) qWarning("CPU flags overwritten by user-defined parameters. Take care!\n");
772 * Check for debugger (detect routine)
774 static __forceinline bool lamexp_check_for_debugger(void)
778 CloseHandle((HANDLE)((DWORD_PTR)-3));
790 return IsDebuggerPresent();
796 * Check for debugger (thread proc)
798 static unsigned int __stdcall lamexp_debug_thread_proc(LPVOID lpParameter)
800 SetThreadPriority(GetCurrentThread(), THREAD_PRIORITY_LOWEST);
803 if(lamexp_check_for_debugger())
805 lamexp_fatal_exit(L"Not a debug build. Please unload debugger and try again!");
813 * Check for debugger (startup routine)
815 static HANDLE lamexp_debug_thread_init()
817 if(lamexp_check_for_debugger())
819 lamexp_fatal_exit(L"Not a debug build. Please unload debugger and try again!");
821 const uintptr_t h = _beginthreadex(NULL, 0, lamexp_debug_thread_proc, NULL, 0, NULL);
822 return (HANDLE)(h^0xdeadbeef);
828 static bool lamexp_event_filter(void *message, long *result)
830 if((!(LAMEXP_DEBUG)) && lamexp_check_for_debugger())
832 lamexp_fatal_exit(L"Not a debug build. Please unload debugger and try again!");
835 switch(reinterpret_cast<MSG*>(message)->message)
837 case WM_QUERYENDSESSION:
838 qWarning("WM_QUERYENDSESSION message received!");
839 *result = lamexp_broadcast(lamexp_event_queryendsession, false) ? TRUE : FALSE;
842 qWarning("WM_ENDSESSION message received!");
843 if(reinterpret_cast<MSG*>(message)->wParam == TRUE)
845 lamexp_broadcast(lamexp_event_endsession, false);
846 if(QApplication *app = reinterpret_cast<QApplication*>(QApplication::instance()))
848 app->closeAllWindows();
851 lamexp_finalization();
857 /*ignore this message and let Qt handle it*/
863 * Check for process elevation
865 static bool lamexp_check_elevation(void)
867 typedef enum { lamexp_token_elevationType_class = 18, lamexp_token_elevation_class = 20 } LAMEXP_TOKEN_INFORMATION_CLASS;
868 typedef enum { lamexp_elevationType_default = 1, lamexp_elevationType_full, lamexp_elevationType_limited } LAMEXP_TOKEN_ELEVATION_TYPE;
870 HANDLE hToken = NULL;
871 bool bIsProcessElevated = false;
873 if(OpenProcessToken(GetCurrentProcess(), TOKEN_QUERY, &hToken))
875 LAMEXP_TOKEN_ELEVATION_TYPE tokenElevationType;
877 if(GetTokenInformation(hToken, (TOKEN_INFORMATION_CLASS) lamexp_token_elevationType_class, &tokenElevationType, sizeof(LAMEXP_TOKEN_ELEVATION_TYPE), &returnLength))
879 if(returnLength == sizeof(LAMEXP_TOKEN_ELEVATION_TYPE))
881 switch(tokenElevationType)
883 case lamexp_elevationType_default:
884 qDebug("Process token elevation type: Default -> UAC is disabled.\n");
886 case lamexp_elevationType_full:
887 qWarning("Process token elevation type: Full -> potential security risk!\n");
888 bIsProcessElevated = true;
890 case lamexp_elevationType_limited:
891 qDebug("Process token elevation type: Limited -> not elevated.\n");
900 qWarning("Failed to open process token!");
903 return !bIsProcessElevated;
907 * Initialize Qt framework
909 bool lamexp_init_qt(int argc, char* argv[])
911 static bool qt_initialized = false;
912 typedef BOOL (WINAPI *SetDllDirectoryProc)(WCHAR *lpPathName);
913 const QStringList &arguments = lamexp_arguments();
915 //Don't initialized again, if done already
922 QLibrary kernel32("kernel32.dll");
925 SetDllDirectoryProc pSetDllDirectory = (SetDllDirectoryProc) kernel32.resolve("SetDllDirectoryW");
926 if(pSetDllDirectory != NULL) pSetDllDirectory(L"");
929 //Extract executable name from argv[] array
930 QString executableName = QLatin1String("LameXP.exe");
931 if(arguments.count() > 0)
933 static const char *delimiters = "\\/:?";
934 executableName = arguments[0].trimmed();
935 for(int i = 0; delimiters[i]; i++)
937 int temp = executableName.lastIndexOf(QChar(delimiters[i]));
938 if(temp >= 0) executableName = executableName.mid(temp + 1);
940 executableName = executableName.trimmed();
941 if(executableName.isEmpty())
943 executableName = QLatin1String("LameXP.exe");
949 qDebug("Using Qt v%s [%s], %s, %s", qVersion(), QLibraryInfo::buildDate().toString(Qt::ISODate).toLatin1().constData(), (qSharedBuild() ? "DLL" : "Static"), QLibraryInfo::buildKey().toLatin1().constData());
950 qDebug("Compiled with Qt v%s [%s], %s\n", QT_VERSION_STR, QT_PACKAGEDATE_STR, QT_BUILD_KEY);
951 if(_stricmp(qVersion(), QT_VERSION_STR))
953 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());
956 if(QLibraryInfo::buildKey().compare(QString::fromLatin1(QT_BUILD_KEY), Qt::CaseInsensitive))
958 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());
962 qDebug("Using Qt v%s [%s], %s", qVersion(), QLibraryInfo::buildDate().toString(Qt::ISODate).toLatin1().constData(), (qSharedBuild() ? "DLL" : "Static"));
963 qDebug("Compiled with Qt v%s [%s]\n", QT_VERSION_STR, QT_PACKAGEDATE_STR);
966 //Check the Windows version
967 const lamexp_os_version_t &osVersionNo = lamexp_get_os_version();
968 if(osVersionNo < lamexp_winver_winxp)
970 qFatal("%s", QApplication::tr("Executable '%1' requires Windows XP or later.").arg(executableName).toLatin1().constData());
973 //Supported Windows version?
974 if(osVersionNo == lamexp_winver_winxp)
976 qDebug("Running on Windows XP or Windows XP Media Center Edition.\n"); //lamexp_check_compatibility_mode("GetLargePageMinimum", executableName);
978 else if(osVersionNo == lamexp_winver_xpx64)
980 qDebug("Running on Windows Server 2003, Windows Server 2003 R2 or Windows XP x64.\n"); //lamexp_check_compatibility_mode("GetLocaleInfoEx", executableName);
982 else if(osVersionNo == lamexp_winver_vista)
984 qDebug("Running on Windows Vista or Windows Server 2008.\n"); //lamexp_check_compatibility_mode("CreateRemoteThreadEx", executableName*/);
986 else if(osVersionNo == lamexp_winver_win70)
988 qDebug("Running on Windows 7 or Windows Server 2008 R2.\n"); //lamexp_check_compatibility_mode("CreateFile2", executableName);
990 else if(osVersionNo == lamexp_winver_win80)
992 qDebug("Running on Windows 8 or Windows Server 2012.\n"); //lamexp_check_compatibility_mode("FindPackagesByPackageFamily", executableName);
994 else if(osVersionNo == lamexp_winver_win81)
996 qDebug("Running on Windows 8.1 or Windows Server 2012 R2.\n"); //lamexp_check_compatibility_mode(NULL, executableName);
1000 const QString message = QString().sprintf("Running on an unknown WindowsNT-based system (v%u.%u).", osVersionNo.versionMajor, osVersionNo.versionMinor);
1001 qWarning("%s\n", QUTF8(message));
1002 MessageBoxW(NULL, QWCHAR(message), L"LameXP", MB_OK | MB_TOPMOST | MB_ICONWARNING);
1005 //Check for compat mode
1006 if(osVersionNo.overrideFlag && (osVersionNo <= lamexp_winver_win81))
1008 qWarning("Windows compatibility mode detected!");
1009 if(!arguments.contains("--ignore-compat-mode", Qt::CaseInsensitive))
1011 qFatal("%s", QApplication::tr("Executable '%1' doesn't support Windows compatibility mode.").arg(executableName).toLatin1().constData());
1017 if(lamexp_detect_wine())
1019 qWarning("It appears we are running under Wine, unexpected things might happen!\n");
1022 //Set text Codec for locale
1023 QTextCodec::setCodecForLocale(QTextCodec::codecForName("UTF-8"));
1025 //Create Qt application instance
1026 QApplication *application = new QApplication(argc, argv);
1028 //Load plugins from application directory
1029 QCoreApplication::setLibraryPaths(QStringList() << QApplication::applicationDirPath());
1030 qDebug("Library Path:\n%s\n", QUTF8(QApplication::libraryPaths().first()));
1032 //Set application properties
1033 application->setApplicationName("LameXP - Audio Encoder Front-End");
1034 application->setApplicationVersion(QString().sprintf("%d.%02d.%04d", lamexp_version_major(), lamexp_version_minor(), lamexp_version_build()));
1035 application->setOrganizationName("LoRd_MuldeR");
1036 application->setOrganizationDomain("mulder.at.gg");
1037 application->setWindowIcon(lamexp_app_icon());
1038 application->setEventFilter(lamexp_event_filter);
1040 //Check for supported image formats
1041 QList<QByteArray> supportedFormats = QImageReader::supportedImageFormats();
1042 for(int i = 0; g_lamexp_imageformats[i]; i++)
1044 if(!supportedFormats.contains(g_lamexp_imageformats[i]))
1046 qFatal("Qt initialization error: QImageIOHandler for '%s' missing!", g_lamexp_imageformats[i]);
1051 //Add the default translations
1052 lamexp_translation_init();
1054 //Check for process elevation
1055 if((!lamexp_check_elevation()) && (!lamexp_detect_wine()))
1057 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);
1058 messageBox.addButton("Quit Program (Recommended)", QMessageBox::NoRole);
1059 messageBox.addButton("Ignore", QMessageBox::NoRole);
1060 if(messageBox.exec() == 0)
1066 //Update console icon, if a console is attached
1067 #if QT_VERSION < QT_VERSION_CHECK(5,0,0)
1068 if(g_lamexp_console_attached && (!lamexp_detect_wine()))
1070 typedef DWORD (__stdcall *SetConsoleIconFun)(HICON);
1071 QLibrary kernel32("kernel32.dll");
1074 SetConsoleIconFun SetConsoleIconPtr = (SetConsoleIconFun) kernel32.resolve("SetConsoleIcon");
1075 QPixmap pixmap = QIcon(":/icons/sound.png").pixmap(16, 16);
1076 if((SetConsoleIconPtr != NULL) && (!pixmap.isNull())) SetConsoleIconPtr(pixmap.toWinHICON());
1083 qt_initialized = true;
1087 const QStringList &lamexp_arguments(void)
1089 QReadLocker readLock(&g_lamexp_argv.lock);
1091 if(!g_lamexp_argv.list)
1094 QWriteLocker writeLock(&g_lamexp_argv.lock);
1096 g_lamexp_argv.list = new QStringList;
1099 LPWSTR *szArglist = CommandLineToArgvW(GetCommandLineW(), &nArgs);
1101 if(NULL != szArglist)
1103 for(int i = 0; i < nArgs; i++)
1105 (*g_lamexp_argv.list) << WCHAR2QSTR(szArglist[i]);
1107 LocalFree(szArglist);
1111 qWarning("CommandLineToArgvW() has failed !!!");
1115 return (*g_lamexp_argv.list);
1119 * Locate known folder on local system
1121 const QString &lamexp_known_folder(lamexp_known_folder_t folder_id)
1123 typedef HRESULT (WINAPI *SHGetKnownFolderPathFun)(__in const GUID &rfid, __in DWORD dwFlags, __in HANDLE hToken, __out PWSTR *ppszPath);
1124 typedef HRESULT (WINAPI *SHGetFolderPathFun)(__in HWND hwndOwner, __in int nFolder, __in HANDLE hToken, __in DWORD dwFlags, __out LPWSTR pszPath);
1126 static const int CSIDL_LOCAL_APPDATA = 0x001c;
1127 static const int CSIDL_PROGRAM_FILES = 0x0026;
1128 static const int CSIDL_SYSTEM_FOLDER = 0x0025;
1129 static const GUID GUID_LOCAL_APPDATA = {0xF1B32785,0x6FBA,0x4FCF,{0x9D,0x55,0x7B,0x8E,0x7F,0x15,0x70,0x91}};
1130 static const GUID GUID_LOCAL_APPDATA_LOW = {0xA520A1A4,0x1780,0x4FF6,{0xBD,0x18,0x16,0x73,0x43,0xC5,0xAF,0x16}};
1131 static const GUID GUID_PROGRAM_FILES = {0x905e63b6,0xc1bf,0x494e,{0xb2,0x9c,0x65,0xb7,0x32,0xd3,0xd2,0x1a}};
1132 static const GUID GUID_SYSTEM_FOLDER = {0x1AC14E77,0x02E7,0x4E5D,{0xB7,0x44,0x2E,0xB1,0xAE,0x51,0x98,0xB7}};
1134 QReadLocker readLock(&g_lamexp_known_folder.lock);
1136 int folderCSIDL = -1;
1137 GUID folderGUID = {0x0000,0x0000,0x0000,{0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00}};
1138 size_t folderCacheId = size_t(-1);
1142 case lamexp_folder_localappdata:
1144 folderCSIDL = CSIDL_LOCAL_APPDATA;
1145 folderGUID = GUID_LOCAL_APPDATA;
1147 case lamexp_folder_programfiles:
1149 folderCSIDL = CSIDL_PROGRAM_FILES;
1150 folderGUID = GUID_PROGRAM_FILES;
1152 case lamexp_folder_systemfolder:
1154 folderCSIDL = CSIDL_SYSTEM_FOLDER;
1155 folderGUID = GUID_SYSTEM_FOLDER;
1158 qWarning("Invalid 'known' folder was requested!");
1159 return *reinterpret_cast<QString*>(NULL);
1164 if(g_lamexp_known_folder.knownFolders)
1166 if(g_lamexp_known_folder.knownFolders->contains(folderCacheId))
1168 return (*g_lamexp_known_folder.knownFolders)[folderCacheId];
1172 //Obtain write lock to initialize
1174 QWriteLocker writeLock(&g_lamexp_known_folder.lock);
1176 //Still not in cache?
1177 if(g_lamexp_known_folder.knownFolders)
1179 if(g_lamexp_known_folder.knownFolders->contains(folderCacheId))
1181 return (*g_lamexp_known_folder.knownFolders)[folderCacheId];
1185 static SHGetKnownFolderPathFun SHGetKnownFolderPathPtr = NULL;
1186 static SHGetFolderPathFun SHGetFolderPathPtr = NULL;
1189 if((!SHGetKnownFolderPathPtr) && (!SHGetFolderPathPtr))
1191 QLibrary kernel32Lib("shell32.dll");
1192 if(kernel32Lib.load())
1194 SHGetKnownFolderPathPtr = (SHGetKnownFolderPathFun) kernel32Lib.resolve("SHGetKnownFolderPath");
1195 SHGetFolderPathPtr = (SHGetFolderPathFun) kernel32Lib.resolve("SHGetFolderPathW");
1201 //Now try to get the folder path!
1202 if(SHGetKnownFolderPathPtr)
1205 if(SHGetKnownFolderPathPtr(folderGUID, 0x00008000, NULL, &path) == S_OK)
1207 //MessageBoxW(0, path, L"SHGetKnownFolderPath", MB_TOPMOST);
1208 QDir folderTemp = QDir(QDir::fromNativeSeparators(QString::fromUtf16(reinterpret_cast<const unsigned short*>(path))));
1209 if(!folderTemp.exists())
1211 folderTemp.mkpath(".");
1213 if(folderTemp.exists())
1215 folder = folderTemp.canonicalPath();
1217 CoTaskMemFree(path);
1220 else if(SHGetFolderPathPtr)
1222 WCHAR *path = new WCHAR[4096];
1223 if(SHGetFolderPathPtr(NULL, folderCSIDL, NULL, NULL, path) == S_OK)
1225 //MessageBoxW(0, path, L"SHGetFolderPathW", MB_TOPMOST);
1226 QDir folderTemp = QDir(QDir::fromNativeSeparators(QString::fromUtf16(reinterpret_cast<const unsigned short*>(path))));
1227 if(!folderTemp.exists())
1229 folderTemp.mkpath(".");
1231 if(folderTemp.exists())
1233 folder = folderTemp.canonicalPath();
1240 if(!g_lamexp_known_folder.knownFolders)
1242 g_lamexp_known_folder.knownFolders = new QMap<size_t, QString>();
1246 g_lamexp_known_folder.knownFolders->insert(folderCacheId, folder);
1247 return (*g_lamexp_known_folder.knownFolders)[folderCacheId];
1251 * Safely remove a file
1253 bool lamexp_remove_file(const QString &filename)
1255 if(!QFileInfo(filename).exists() || !QFileInfo(filename).isFile())
1261 if(!QFile::remove(filename))
1263 static const DWORD attrMask = FILE_ATTRIBUTE_READONLY | FILE_ATTRIBUTE_HIDDEN | FILE_ATTRIBUTE_SYSTEM;
1264 const DWORD attributes = GetFileAttributesW(QWCHAR(filename));
1265 if(attributes & attrMask)
1267 SetFileAttributesW(QWCHAR(filename), FILE_ATTRIBUTE_NORMAL);
1269 if(!QFile::remove(filename))
1271 qWarning("Could not delete \"%s\"", filename.toLatin1().constData());
1287 * Check if visual themes are enabled (WinXP and later)
1289 bool lamexp_themes_enabled(void)
1291 typedef int (WINAPI *IsAppThemedFun)(void);
1293 QReadLocker readLock(&g_lamexp_themes_enabled.lock);
1294 if(g_lamexp_themes_enabled.bInitialized)
1296 return g_lamexp_themes_enabled.bThemesEnabled;
1300 QWriteLocker writeLock(&g_lamexp_themes_enabled.lock);
1302 if(!g_lamexp_themes_enabled.bInitialized)
1304 g_lamexp_themes_enabled.bThemesEnabled = false;
1305 const lamexp_os_version_t &osVersion = lamexp_get_os_version();
1306 if(osVersion >= lamexp_winver_winxp)
1308 IsAppThemedFun IsAppThemedPtr = NULL;
1309 QLibrary uxTheme(QString("%1/UxTheme.dll").arg(lamexp_known_folder(lamexp_folder_systemfolder)));
1312 IsAppThemedPtr = (IsAppThemedFun) uxTheme.resolve("IsAppThemed");
1316 g_lamexp_themes_enabled.bThemesEnabled = IsAppThemedPtr();
1317 if(!g_lamexp_themes_enabled.bThemesEnabled)
1319 qWarning("Theme support is disabled for this process!");
1323 g_lamexp_themes_enabled.bInitialized = true;
1326 return g_lamexp_themes_enabled.bThemesEnabled;
1330 * Get number of free bytes on disk
1332 unsigned __int64 lamexp_free_diskspace(const QString &path, bool *ok)
1334 ULARGE_INTEGER freeBytesAvailable, totalNumberOfBytes, totalNumberOfFreeBytes;
1335 if(GetDiskFreeSpaceExW(reinterpret_cast<const wchar_t*>(QDir::toNativeSeparators(path).utf16()), &freeBytesAvailable, &totalNumberOfBytes, &totalNumberOfFreeBytes))
1338 return freeBytesAvailable.QuadPart;
1348 * Check if computer does support hibernation
1350 bool lamexp_is_hibernation_supported(void)
1352 bool hibernationSupported = false;
1354 SYSTEM_POWER_CAPABILITIES pwrCaps;
1355 SecureZeroMemory(&pwrCaps, sizeof(SYSTEM_POWER_CAPABILITIES));
1357 if(GetPwrCapabilities(&pwrCaps))
1359 hibernationSupported = pwrCaps.SystemS4 && pwrCaps.HiberFilePresent;
1362 return hibernationSupported;
1366 * Shutdown the computer
1368 bool lamexp_shutdown_computer(const QString &message, const unsigned long timeout, const bool forceShutdown, const bool hibernate)
1370 HANDLE hToken = NULL;
1372 if(OpenProcessToken(GetCurrentProcess(), TOKEN_ADJUST_PRIVILEGES | TOKEN_QUERY, &hToken))
1374 TOKEN_PRIVILEGES privileges;
1375 memset(&privileges, 0, sizeof(TOKEN_PRIVILEGES));
1376 privileges.PrivilegeCount = 1;
1377 privileges.Privileges[0].Attributes = SE_PRIVILEGE_ENABLED;
1379 if(LookupPrivilegeValue(NULL, SE_SHUTDOWN_NAME, &privileges.Privileges[0].Luid))
1381 if(AdjustTokenPrivileges(hToken, FALSE, &privileges, NULL, NULL, NULL))
1385 if(SetSuspendState(TRUE, TRUE, TRUE))
1390 const DWORD reason = SHTDN_REASON_MAJOR_APPLICATION | SHTDN_REASON_FLAG_PLANNED;
1391 return InitiateSystemShutdownEx(NULL, const_cast<wchar_t*>(QWCHAR(message)), timeout, forceShutdown ? TRUE : FALSE, FALSE, reason);
1400 * Determines the current date, resistant against certain manipulations
1402 QDate lamexp_current_date_safe(void)
1404 const DWORD MAX_PROC = 1024;
1405 DWORD *processes = new DWORD[MAX_PROC];
1406 DWORD bytesReturned = 0;
1408 if(!EnumProcesses(processes, sizeof(DWORD) * MAX_PROC, &bytesReturned))
1410 LAMEXP_DELETE_ARRAY(processes);
1411 return QDate::currentDate();
1414 const DWORD procCount = bytesReturned / sizeof(DWORD);
1415 ULARGE_INTEGER lastStartTime;
1416 memset(&lastStartTime, 0, sizeof(ULARGE_INTEGER));
1418 for(DWORD i = 0; i < procCount; i++)
1420 HANDLE hProc = OpenProcess(PROCESS_QUERY_INFORMATION, FALSE, processes[i]);
1423 FILETIME processTime[4];
1424 if(GetProcessTimes(hProc, &processTime[0], &processTime[1], &processTime[2], &processTime[3]))
1426 ULARGE_INTEGER timeCreation;
1427 timeCreation.LowPart = processTime[0].dwLowDateTime;
1428 timeCreation.HighPart = processTime[0].dwHighDateTime;
1429 if(timeCreation.QuadPart > lastStartTime.QuadPart)
1431 lastStartTime.QuadPart = timeCreation.QuadPart;
1438 LAMEXP_DELETE_ARRAY(processes);
1440 FILETIME lastStartTime_fileTime;
1441 lastStartTime_fileTime.dwHighDateTime = lastStartTime.HighPart;
1442 lastStartTime_fileTime.dwLowDateTime = lastStartTime.LowPart;
1444 FILETIME lastStartTime_localTime;
1445 if(!FileTimeToLocalFileTime(&lastStartTime_fileTime, &lastStartTime_localTime))
1447 memcpy(&lastStartTime_localTime, &lastStartTime_fileTime, sizeof(FILETIME));
1450 SYSTEMTIME lastStartTime_system;
1451 if(!FileTimeToSystemTime(&lastStartTime_localTime, &lastStartTime_system))
1453 memset(&lastStartTime_system, 0, sizeof(SYSTEMTIME));
1454 lastStartTime_system.wYear = 1970; lastStartTime_system.wMonth = lastStartTime_system.wDay = 1;
1457 const QDate currentDate = QDate::currentDate();
1458 const QDate processDate = QDate(lastStartTime_system.wYear, lastStartTime_system.wMonth, lastStartTime_system.wDay);
1459 return (currentDate >= processDate) ? currentDate : processDate;
1463 * Suspend calling thread for N milliseconds
1465 inline void lamexp_sleep(const unsigned int delay)
1470 bool lamexp_beep(int beepType)
1474 case lamexp_beep_info: return MessageBeep(MB_ICONASTERISK) == TRUE; break;
1475 case lamexp_beep_warning: return MessageBeep(MB_ICONEXCLAMATION) == TRUE; break;
1476 case lamexp_beep_error: return MessageBeep(MB_ICONHAND) == TRUE; break;
1477 default: return false;
1482 * Play a sound (from resources)
1484 bool lamexp_play_sound(const unsigned short uiSoundIdx, const bool bAsync, const wchar_t *alias)
1488 return PlaySound(alias, GetModuleHandle(NULL), (SND_ALIAS | (bAsync ? SND_ASYNC : SND_SYNC))) == TRUE;
1492 return PlaySound(MAKEINTRESOURCE(uiSoundIdx), GetModuleHandle(NULL), (SND_RESOURCE | (bAsync ? SND_ASYNC : SND_SYNC))) == TRUE;
1497 * Play a sound (from resources)
1499 bool lamexp_play_sound_file(const QString &library, const unsigned short uiSoundIdx, const bool bAsync)
1501 bool result = false;
1502 HMODULE module = NULL;
1504 QFileInfo libraryFile(library);
1505 if(!libraryFile.isAbsolute())
1507 unsigned int buffSize = GetSystemDirectoryW(NULL, NULL) + 1;
1508 wchar_t *buffer = (wchar_t*) _malloca(buffSize * sizeof(wchar_t));
1509 unsigned int result = GetSystemDirectory(buffer, buffSize);
1510 if(result > 0 && result < buffSize)
1512 libraryFile.setFile(QString("%1/%2").arg(QDir::fromNativeSeparators(QString::fromUtf16(reinterpret_cast<const unsigned short*>(buffer))), library));
1517 module = LoadLibraryW(QWCHAR(QDir::toNativeSeparators(libraryFile.absoluteFilePath())));
1520 result = (PlaySound(MAKEINTRESOURCE(uiSoundIdx), module, (SND_RESOURCE | (bAsync ? SND_ASYNC : SND_SYNC))) == TRUE);
1521 FreeLibrary(module);
1528 * Open file using the shell
1530 bool lamexp_exec_shell(const QWidget *win, const QString &url, const bool explore)
1532 return lamexp_exec_shell(win, url, QString(), QString(), explore);
1536 * Open file using the shell (with parameters)
1538 bool lamexp_exec_shell(const QWidget *win, const QString &url, const QString ¶meters, const QString &directory, const bool explore)
1540 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;
1544 * Query value of the performance counter
1546 __int64 lamexp_perfcounter_value(void)
1548 LARGE_INTEGER counter;
1549 if(QueryPerformanceCounter(&counter) == TRUE)
1551 return counter.QuadPart;
1557 * Query frequency of the performance counter
1559 __int64 lamexp_perfcounter_frequ(void)
1561 LARGE_INTEGER frequency;
1562 if(QueryPerformanceFrequency(&frequency) == TRUE)
1564 return frequency.QuadPart;
1570 * Insert entry to the window's system menu
1572 bool lamexp_append_sysmenu(const QWidget *win, const unsigned int identifier, const QString &text)
1576 if(HMENU hMenu = GetSystemMenu(win->winId(), FALSE))
1578 ok = (AppendMenuW(hMenu, MF_SEPARATOR, 0, 0) == TRUE);
1579 ok = (AppendMenuW(hMenu, MF_STRING, identifier, QWCHAR(text)) == TRUE);
1586 * Insert entry to the window's system menu
1588 bool lamexp_check_sysmenu_msg(void *message, const unsigned int identifier)
1590 return (((MSG*)message)->message == WM_SYSCOMMAND) && ((((MSG*)message)->wParam & 0xFFF0) == identifier);
1594 * Update system menu entry
1596 bool lamexp_update_sysmenu(const QWidget *win, const unsigned int identifier, const QString &text)
1600 if(HMENU hMenu = ::GetSystemMenu(win->winId(), FALSE))
1602 ok = (ModifyMenu(hMenu, identifier, MF_STRING | MF_BYCOMMAND, identifier, QWCHAR(text)) == TRUE);
1608 * Display the window's close button
1610 bool lamexp_enable_close_button(const QWidget *win, const bool bEnable)
1614 if(HMENU hMenu = GetSystemMenu(win->winId(), FALSE))
1616 ok = (EnableMenuItem(hMenu, SC_CLOSE, MF_BYCOMMAND | (bEnable ? MF_ENABLED : MF_GRAYED)) == TRUE);
1623 * Check whether ESC key has been pressed since the previous call to this function
1625 bool lamexp_check_escape_state(void)
1627 return (GetAsyncKeyState(VK_ESCAPE) & 0x0001) != 0;
1631 * Set the process priority class for current process
1633 bool lamexp_change_process_priority(const int priority)
1635 return lamexp_change_process_priority(GetCurrentProcess(), priority);
1639 * Set the process priority class for specified process
1641 bool lamexp_change_process_priority(const QProcess *proc, const int priority)
1643 if(Q_PID qPid = proc->pid())
1645 return lamexp_change_process_priority(qPid->hProcess, priority);
1654 * Set the process priority class for specified process
1656 bool lamexp_change_process_priority(void *hProcess, const int priority)
1660 switch(qBound(-2, priority, 2))
1663 ok = (SetPriorityClass(hProcess, HIGH_PRIORITY_CLASS) == TRUE);
1666 if(!(ok = (SetPriorityClass(hProcess, ABOVE_NORMAL_PRIORITY_CLASS) == TRUE)))
1668 ok = (SetPriorityClass(hProcess, HIGH_PRIORITY_CLASS) == TRUE);
1672 ok = (SetPriorityClass(hProcess, NORMAL_PRIORITY_CLASS) == TRUE);
1675 if(!(ok = (SetPriorityClass(hProcess, BELOW_NORMAL_PRIORITY_CLASS) == TRUE)))
1677 ok = (SetPriorityClass(hProcess, IDLE_PRIORITY_CLASS) == TRUE);
1681 ok = (SetPriorityClass(hProcess, IDLE_PRIORITY_CLASS) == TRUE);
1689 * Returns the current file time
1691 unsigned __int64 lamexp_current_file_time(void)
1694 GetSystemTimeAsFileTime(&fileTime);
1696 ULARGE_INTEGER temp;
1697 temp.HighPart = fileTime.dwHighDateTime;
1698 temp.LowPart = fileTime.dwLowDateTime;
1700 return temp.QuadPart;
1704 * Bring the specifed window to the front
1706 bool lamexp_bring_to_front(const QWidget *win)
1708 const bool ret = (SetForegroundWindow(win->winId()) == TRUE);
1709 SwitchToThisWindow(win->winId(), TRUE);
1714 * Bring window of the specifed process to the front (callback)
1716 static BOOL CALLBACK lamexp_bring_process_to_front_helper(HWND hwnd, LPARAM lParam)
1718 DWORD processId = *reinterpret_cast<WORD*>(lParam);
1719 DWORD windowProcessId = NULL;
1720 GetWindowThreadProcessId(hwnd, &windowProcessId);
1721 if(windowProcessId == processId)
1723 SwitchToThisWindow(hwnd, TRUE);
1724 SetForegroundWindow(hwnd);
1732 * Bring window of the specifed process to the front
1734 bool lamexp_bring_process_to_front(const unsigned long pid)
1736 return EnumWindows(lamexp_bring_process_to_front_helper, reinterpret_cast<LPARAM>(&pid)) == TRUE;
1740 * Check the network connection status
1742 int lamexp_network_status(void)
1745 const BOOL ret = (IsNetworkAlive(&dwFlags) == TRUE);
1746 if(GetLastError() == 0)
1748 return (ret == TRUE) ? lamexp_network_yes : lamexp_network_non;
1750 return lamexp_network_err;
1754 * Retrun the process ID of the given QProcess
1756 unsigned long lamexp_process_id(const QProcess *proc)
1758 PROCESS_INFORMATION *procInf = proc->pid();
1759 return (procInf) ? procInf->dwProcessId : NULL;
1763 * Convert long path to short path
1765 QString lamexp_path_to_short(const QString &longPath)
1768 DWORD buffSize = GetShortPathNameW(reinterpret_cast<const wchar_t*>(longPath.utf16()), NULL, NULL);
1772 wchar_t *buffer = new wchar_t[buffSize];
1773 DWORD result = GetShortPathNameW(reinterpret_cast<const wchar_t*>(longPath.utf16()), buffer, buffSize);
1775 if(result > 0 && result < buffSize)
1777 shortPath = QString::fromUtf16(reinterpret_cast<const unsigned short*>(buffer));
1783 return (shortPath.isEmpty() ? longPath : shortPath);
1787 * Open media file in external player
1789 bool lamexp_open_media_file(const QString &mediaFilePath)
1791 const static wchar_t *registryPrefix[2] = { L"SOFTWARE\\", L"SOFTWARE\\Wow6432Node\\" };
1792 const static wchar_t *registryKeys[3] =
1794 L"Microsoft\\Windows\\CurrentVersion\\Uninstall\\{97D341C8-B0D1-4E4A-A49A-C30B52F168E9}",
1795 L"Microsoft\\Windows\\CurrentVersion\\Uninstall\\{DB9E4EAB-2717-499F-8D56-4CC8A644AB60}",
1798 const static wchar_t *appNames[4] = { L"smplayer_portable.exe", L"smplayer.exe", L"MPUI.exe", L"foobar2000.exe" };
1799 const static wchar_t *valueNames[2] = { L"InstallLocation", L"InstallDir" };
1801 for(size_t i = 0; i < 3; i++)
1803 for(size_t j = 0; j < 2; j++)
1805 QString mplayerPath;
1806 HKEY registryKeyHandle = NULL;
1808 const QString currentKey = WCHAR2QSTR(registryPrefix[j]).append(WCHAR2QSTR(registryKeys[i]));
1809 if(RegOpenKeyExW(HKEY_LOCAL_MACHINE, QWCHAR(currentKey), 0, KEY_READ, ®istryKeyHandle) == ERROR_SUCCESS)
1811 for(size_t k = 0; k < 2; k++)
1813 wchar_t Buffer[4096];
1814 DWORD BuffSize = sizeof(wchar_t*) * 4096;
1815 DWORD DataType = REG_NONE;
1816 if(RegQueryValueExW(registryKeyHandle, valueNames[k], 0, &DataType, reinterpret_cast<BYTE*>(Buffer), &BuffSize) == ERROR_SUCCESS)
1818 if((DataType == REG_SZ) || (DataType == REG_EXPAND_SZ) || (DataType == REG_LINK))
1820 mplayerPath = WCHAR2QSTR(Buffer);
1825 RegCloseKey(registryKeyHandle);
1828 if(!mplayerPath.isEmpty())
1830 QDir mplayerDir(mplayerPath);
1831 if(mplayerDir.exists())
1833 for(size_t k = 0; k < 4; k++)
1835 if(mplayerDir.exists(WCHAR2QSTR(appNames[k])))
1837 qDebug("Player found at:\n%s\n", QUTF8(mplayerDir.absoluteFilePath(WCHAR2QSTR(appNames[k]))));
1838 QProcess::startDetached(mplayerDir.absoluteFilePath(WCHAR2QSTR(appNames[k])), QStringList() << QDir::toNativeSeparators(mediaFilePath));
1849 bool lamexp_sheet_of_glass(QWidget *window)
1851 typedef HRESULT (__stdcall *dwmExtendFrameIntoClientArea_t)(HWND hWnd, const MARGINS* pMarInset);
1852 typedef HRESULT (__stdcall *dwmEnableBlurBehindWindow_t)(HWND hWnd, const DWM_BLURBEHIND* pBlurBehind);
1854 //Does OS support DWM?
1855 if(lamexp_get_os_version() < lamexp_winver_vista)
1861 QLibrary libDwm("dwmapi.dll");
1864 qWarning("Failed to load DWMAPI.DLL on a DWM-enabled system!");
1868 //Lookup required functions
1869 dwmExtendFrameIntoClientArea_t dwmExtendFrameIntoClientArea = (dwmExtendFrameIntoClientArea_t) libDwm.resolve("DwmExtendFrameIntoClientArea");
1870 dwmEnableBlurBehindWindow_t dwmEnableBlurBehindWindow = (dwmEnableBlurBehindWindow_t) libDwm.resolve("DwmEnableBlurBehindWindow");
1872 //Check function pointers
1873 if((dwmExtendFrameIntoClientArea == NULL) || (dwmEnableBlurBehindWindow == NULL))
1875 qWarning("Required functions are missing from DWMAPI.DLL on a DWM-enabled system!");
1879 //Enable the "sheet of glass" effect on this window
1880 MARGINS margins = {-1, -1, -1, -1};
1881 if(HRESULT hr = dwmExtendFrameIntoClientArea(window->winId(), &margins))
1883 qWarning("DwmExtendFrameIntoClientArea function has failed! (error %d)", hr);
1887 //Create and populate the Blur Behind structure
1889 memset(&bb, 0, sizeof(DWM_BLURBEHIND));
1891 bb.dwFlags = DWM_BB_ENABLE;
1892 if(HRESULT hr = dwmEnableBlurBehindWindow(window->winId(), &bb))
1894 qWarning("DwmEnableBlurBehindWindow function has failed! (error %d)", hr);
1899 window->setAttribute(Qt::WA_TranslucentBackground);
1900 window->setAttribute(Qt::WA_NoSystemBackground);
1906 * Fatal application exit
1908 #pragma intrinsic(_InterlockedExchange)
1909 void lamexp_fatal_exit(const wchar_t* exitMessage, const wchar_t* errorBoxMessage)
1911 static volatile long bFatalFlag = 0L;
1913 if(_InterlockedExchange(&bFatalFlag, 1L) == 0L)
1915 if(GetCurrentThreadId() != g_main_thread_id)
1917 HANDLE mainThread = OpenThread(THREAD_TERMINATE, FALSE, g_main_thread_id);
1918 if(mainThread) TerminateThread(mainThread, ULONG_MAX);
1923 MessageBoxW(NULL, errorBoxMessage, L"LameXP - GURU MEDITATION", MB_ICONERROR | MB_TOPMOST | MB_TASKMODAL);
1928 FatalAppExit(0, exitMessage);
1929 TerminateProcess(GetCurrentProcess(), -1);
1933 TerminateThread(GetCurrentThread(), -1);
1938 * Finalization function (final clean-up)
1940 void lamexp_finalization(void)
1942 qDebug("lamexp_finalization()");
1945 lamexp_clean_all_tools();
1947 //Delete temporary files
1948 const QString &tempFolder = lamexp_temp_folder2();
1949 if(!tempFolder.isEmpty())
1951 bool success = false;
1952 for(int i = 0; i < 100; i++)
1954 if(lamexp_clean_folder(tempFolder))
1963 MessageBoxW(NULL, L"Sorry, LameXP was unable to clean up all temporary files. Some residual files in your TEMP directory may require manual deletion!", L"LameXP", MB_ICONEXCLAMATION|MB_TOPMOST);
1964 lamexp_exec_shell(NULL, tempFolder, QString(), QString(), true);
1968 //Clear folder cache
1969 LAMEXP_DELETE(g_lamexp_known_folder.knownFolders);
1972 lamexp_clean_all_translations();
1974 //Destroy Qt application object
1975 QApplication *application = dynamic_cast<QApplication*>(QApplication::instance());
1976 LAMEXP_DELETE(application);
1978 //Detach from shared memory
1981 //Free STDOUT and STDERR buffers
1982 if(g_lamexp_console_attached)
1984 if(std::filebuf *tmp = dynamic_cast<std::filebuf*>(std::cout.rdbuf()))
1986 std::cout.rdbuf(NULL);
1989 if(std::filebuf *tmp = dynamic_cast<std::filebuf*>(std::cerr.rdbuf()))
1991 std::cerr.rdbuf(NULL);
1997 if(g_lamexp_log_file)
1999 fclose(g_lamexp_log_file);
2000 g_lamexp_log_file = NULL;
2003 //Free CLI Arguments
2004 LAMEXP_DELETE(g_lamexp_argv.list);
2007 lamexp_temp_folder_clear();
2011 * Initialize debug thread
2013 static const HANDLE g_debug_thread1 = LAMEXP_DEBUG ? NULL : lamexp_debug_thread_init();
2016 * Get number private bytes [debug only]
2018 unsigned long lamexp_dbg_private_bytes(void)
2021 for(int i = 0; i < 8; i++) _heapmin();
2022 PROCESS_MEMORY_COUNTERS_EX memoryCounters;
2023 memoryCounters.cb = sizeof(PROCESS_MEMORY_COUNTERS_EX);
2024 GetProcessMemoryInfo(GetCurrentProcess(), (PPROCESS_MEMORY_COUNTERS) &memoryCounters, sizeof(PROCESS_MEMORY_COUNTERS_EX));
2025 return memoryCounters.PrivateUsage;
2027 THROW("Cannot call this function in a non-debug build!");
2028 #endif //LAMEXP_DEBUG
2032 * Output string to debugger [debug only]
2034 void lamexp_dbg_dbg_output_string(const char* format, ...)
2039 va_start (args, format);
2040 vsnprintf_s(buffer, 256, _TRUNCATE, format, args);
2041 OutputDebugStringA(buffer);
2044 THROW("Cannot call this function in a non-debug build!");
2045 #endif //LAMEXP_DEBUG
2048 ///////////////////////////////////////////////////////////////////////////////
2050 ///////////////////////////////////////////////////////////////////////////////
2052 extern "C" void _lamexp_global_init_win32(void)
2054 if((!LAMEXP_DEBUG) && lamexp_check_for_debugger())
2056 lamexp_fatal_exit(L"Not a debug build. Please unload debugger and try again!");
2059 //Zero *before* constructors are called
2060 LAMEXP_ZERO_MEMORY(g_lamexp_argv);
2061 LAMEXP_ZERO_MEMORY(g_lamexp_known_folder);
2062 LAMEXP_ZERO_MEMORY(g_lamexp_os_version);
2063 LAMEXP_ZERO_MEMORY(g_lamexp_wine);
2064 LAMEXP_ZERO_MEMORY(g_lamexp_themes_enabled);