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.
10 // This program is distributed in the hope that it will be useful,
11 // but WITHOUT ANY WARRANTY; without even the implied warranty of
12 // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 // GNU General Public License for more details.
15 // You should have received a copy of the GNU General Public License along
16 // with this program; if not, write to the Free Software Foundation, Inc.,
17 // 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
19 // http://www.gnu.org/licenses/gpl-2.0.txt
20 ///////////////////////////////////////////////////////////////////////////////
26 #define WIN32_LEAN_AND_MEAN
33 #include <QApplication>
34 #include <QMessageBox>
40 #include <QPlastiqueStyle>
41 #include <QImageReader>
42 #include <QSharedMemory>
44 #include <QStringList>
45 #include <QSystemSemaphore>
51 #include <QTranslator>
54 #include <QLibraryInfo>
56 #include <QReadWriteLock>
57 #include <QReadLocker>
58 #include <QWriteLocker>
62 #define LAMEXP_INC_CONFIG
65 #include "LockedFile.h"
66 #include "strnatcmp.h"
88 //Initialize static Qt plugins
90 #if QT_VERSION < QT_VERSION_CHECK(5,0,0)
94 Q_IMPORT_PLUGIN(QWindowsIntegrationPlugin)
95 Q_IMPORT_PLUGIN(QICOPlugin)
99 #define LAMEXP_ZERO_MEMORY(X) SecureZeroMemory(&X, sizeof(X))
102 #define _LAMEXP_MAKE_STR(STR) #STR
103 #define LAMEXP_MAKE_STR(STR) _LAMEXP_MAKE_STR(STR)
105 ///////////////////////////////////////////////////////////////////////////////
107 ///////////////////////////////////////////////////////////////////////////////
109 static const size_t g_lamexp_ipc_slots = 128;
113 unsigned int command;
114 unsigned int reserved_1;
115 unsigned int reserved_2;
116 char parameter[4096];
122 unsigned int pos_write;
123 unsigned int pos_read;
124 lamexp_ipc_data_t data[g_lamexp_ipc_slots];
128 ///////////////////////////////////////////////////////////////////////////////
130 ///////////////////////////////////////////////////////////////////////////////
135 unsigned int ver_major;
136 unsigned int ver_minor;
137 unsigned int ver_build;
138 unsigned int ver_confg;
139 char *ver_release_name;
144 (10 * VER_LAMEXP_MINOR_HI) + VER_LAMEXP_MINOR_LO,
151 static QDate g_lamexp_version_date;
152 static const char *g_lamexp_months[] = {"Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"};
153 static const char *g_lamexp_version_raw_date = __DATE__;
154 static const char *g_lamexp_version_raw_time = __TIME__;
156 //Console attached flag
157 static bool g_lamexp_console_attached = false;
160 //The following code was borrowed from MPC-HC project: http://mpc-hc.sf.net/
161 #if defined(__INTEL_COMPILER)
162 #if (__INTEL_COMPILER >= 1300)
163 static const char *g_lamexp_version_compiler = "ICL 13." LAMEXP_MAKE_STR(__INTEL_COMPILER_BUILD_DATE);
164 #elif (__INTEL_COMPILER >= 1200)
165 static const char *g_lamexp_version_compiler = "ICL 12." LAMEXP_MAKE_STR(__INTEL_COMPILER_BUILD_DATE);
166 #elif (__INTEL_COMPILER >= 1100)
167 static const char *g_lamexp_version_compiler = "ICL 11.x";
168 #elif (__INTEL_COMPILER >= 1000)
169 static const char *g_lamexp_version_compiler = "ICL 10.x";
171 #error Compiler is not supported!
173 #elif defined(_MSC_VER)
174 #if (_MSC_VER == 1700)
175 #if (_MSC_FULL_VER < 170050727)
176 static const char *g_lamexp_version_compiler = "MSVC 2012-Beta";
177 #elif (_MSC_FULL_VER < 170051020)
178 static const char *g_lamexp_version_compiler = "MSVC 2012-RTM";
179 #elif (_MSC_FULL_VER < 170051106)
180 static const char *g_lamexp_version_compiler = "MSVC 2012-U1 CTP";
181 #elif (_MSC_FULL_VER < 170060315)
182 static const char *g_lamexp_version_compiler = "MSVC 2012-U1";
183 #elif (_MSC_FULL_VER < 170060610)
184 static const char *g_lamexp_version_compiler = "MSVC 2012-U2";
185 #elif (_MSC_FULL_VER == 170060610)
186 static const char *g_lamexp_version_compiler = "MSVC 2012-U3";
188 #error Compiler version is not supported yet!
190 #elif (_MSC_VER == 1600)
191 #if (_MSC_FULL_VER < 160040219)
192 static const char *g_lamexp_version_compiler = "MSVC 2010-RTM";
193 #elif (_MSC_FULL_VER == 160040219)
194 static const char *g_lamexp_version_compiler = "MSVC 2010-SP1";
196 #error Compiler version is not supported yet!
198 #elif (_MSC_VER == 1500)
199 #if (_MSC_FULL_VER >= 150030729)
200 static const char *g_lamexp_version_compiler = "MSVC 2008-SP1";
202 static const char *g_lamexp_version_compiler = "MSVC 2008";
205 #error Compiler is not supported!
208 // Note: /arch:SSE and /arch:SSE2 are only available for the x86 platform
209 #if !defined(_M_X64) && defined(_M_IX86_FP)
210 #if (_M_IX86_FP == 1)
211 LAMEXP_COMPILER_WARNING("SSE instruction set is enabled!")
212 #elif (_M_IX86_FP == 2)
213 LAMEXP_COMPILER_WARNING("SSE2 instruction set is enabled!")
217 #error Compiler is not supported!
220 //Architecture detection
222 static const char *g_lamexp_version_arch = "x64";
223 #elif defined(_M_IX86)
224 static const char *g_lamexp_version_arch = "x86";
226 #error Architecture is not supported!
229 //Official web-site URL
230 static const char *g_lamexp_website_url = "http://lamexp.sourceforge.net/";
231 static const char *g_lamexp_support_url = "http://forum.doom9.org/showthread.php?t=157726";
232 static const char *g_lamexp_mulders_url = "http://muldersoft.com/";
234 //Tool versions (expected versions!)
235 static const unsigned int g_lamexp_toolver_neroaac = VER_LAMEXP_TOOL_NEROAAC;
236 static const unsigned int g_lamexp_toolver_fhgaacenc = VER_LAMEXP_TOOL_FHGAACENC;
237 static const unsigned int g_lamexp_toolver_qaacenc = VER_LAMEXP_TOOL_QAAC;
238 static const unsigned int g_lamexp_toolver_coreaudio = VER_LAMEXP_TOOL_COREAUDIO;
243 QMap<size_t, QString> *knownFolders;
246 g_lamexp_known_folder;
254 g_lamexp_temp_folder;
259 QMap<QString, LockedFile*> *registry;
260 QMap<QString, unsigned int> *versions;
261 QMap<QString, QString> *tags;
269 QMap<QString, QString> *files;
270 QMap<QString, QString> *names;
271 QMap<QString, unsigned int> *sysid;
272 QMap<QString, unsigned int> *cntry;
275 g_lamexp_translation;
280 QTranslator *instance;
283 g_lamexp_currentTranslator;
297 lamexp_os_version_t version;
306 bool bPortableModeEnabled;
311 //Win32 Theme support
318 g_lamexp_themes_enabled;
324 char *semaphore_read;
325 char *semaphore_read_mutex;
326 char *semaphore_write;
327 char *semaphore_write_mutex;
331 "{21A68A42-6923-43bb-9CF6-64BF151942EE}",
332 "{7A605549-F58C-4d78-B4E5-06EFC34F405B}",
333 "{60AA8D04-F6B8-497d-81EB-0F600F4A65B5}",
334 "{726061D5-1615-4B82-871C-75FD93458E46}",
335 "{1A616023-AA6A-4519-8AF3-F7736E899977}"
339 QSharedMemory *sharedmem;
340 QSystemSemaphore *semaphore_read;
341 QSystemSemaphore *semaphore_read_mutex;
342 QSystemSemaphore *semaphore_write;
343 QSystemSemaphore *semaphore_write_mutex;
349 static const char *g_lamexp_imageformats[] = {"bmp", "png", "jpg", "gif", "ico", "xpm", NULL}; //"svg"
352 static QMutex g_lamexp_message_mutex;
355 static const DWORD g_main_thread_id = GetCurrentThreadId();
358 static FILE *g_lamexp_log_file = NULL;
361 const char* LAMEXP_DEFAULT_LANGID = "en";
362 const char* LAMEXP_DEFAULT_TRANSLATION = "LameXP_EN.qm";
364 ///////////////////////////////////////////////////////////////////////////////
366 ///////////////////////////////////////////////////////////////////////////////
371 unsigned int lamexp_version_major(void) { return g_lamexp_version.ver_major; }
372 unsigned int lamexp_version_minor(void) { return g_lamexp_version.ver_minor; }
373 unsigned int lamexp_version_build(void) { return g_lamexp_version.ver_build; }
374 unsigned int lamexp_version_confg(void) { return g_lamexp_version.ver_confg; }
375 const char *lamexp_version_release(void) { return g_lamexp_version.ver_release_name; }
376 const char *lamexp_version_time(void) { return g_lamexp_version_raw_time; }
377 const char *lamexp_version_compiler(void) { return g_lamexp_version_compiler; }
378 const char *lamexp_version_arch(void) { return g_lamexp_version_arch; }
379 unsigned int lamexp_toolver_neroaac(void) { return g_lamexp_toolver_neroaac; }
380 unsigned int lamexp_toolver_fhgaacenc(void) { return g_lamexp_toolver_fhgaacenc; }
381 unsigned int lamexp_toolver_qaacenc(void) { return g_lamexp_toolver_qaacenc; }
382 unsigned int lamexp_toolver_coreaudio(void) { return g_lamexp_toolver_coreaudio; }
387 const char *lamexp_website_url(void) { return g_lamexp_website_url; }
388 const char *lamexp_mulders_url(void) { return g_lamexp_mulders_url; }
389 const char *lamexp_support_url(void) { return g_lamexp_support_url; }
392 * Check for Demo (pre-release) version
394 bool lamexp_version_demo(void)
397 bool releaseVersion = false;
398 if(!strncpy_s(buffer, 128, g_lamexp_version.ver_release_name, _TRUNCATE))
400 char *context, *prefix = strtok_s(buffer, "-,; ", &context);
403 releaseVersion = (!_stricmp(prefix, "Final")) || (!_stricmp(prefix, "Hotfix"));
406 return (!releaseVersion);
410 * Calculate expiration date
412 QDate lamexp_version_expires(void)
414 return lamexp_version_date().addDays(LAMEXP_DEBUG ? 7 : 30);
418 * Get build date date
420 const QDate &lamexp_version_date(void)
422 if(!g_lamexp_version_date.isValid())
424 int date[3] = {0, 0, 0}; char temp[12] = {'\0'};
425 strncpy_s(temp, 12, g_lamexp_version_raw_date, _TRUNCATE);
427 if(strlen(temp) == 11)
429 temp[3] = temp[6] = '\0';
430 date[2] = atoi(&temp[4]);
431 date[0] = atoi(&temp[7]);
433 for(int j = 0; j < 12; j++)
435 if(!_strcmpi(&temp[0], g_lamexp_months[j]))
442 g_lamexp_version_date = QDate(date[0], date[1], date[2]);
445 if(!g_lamexp_version_date.isValid())
447 qFatal("Internal error: Date format could not be recognized!");
451 return g_lamexp_version_date;
455 * Get the native operating system version
457 const lamexp_os_version_t *lamexp_get_os_version(void)
459 QReadLocker readLock(&g_lamexp_os_version.lock);
461 //Already initialized?
462 if(g_lamexp_os_version.bInitialized)
464 return &g_lamexp_os_version.version;
468 QWriteLocker writeLock(&g_lamexp_os_version.lock);
471 if(!g_lamexp_os_version.bInitialized)
473 OSVERSIONINFO osVerInfo;
474 memset(&osVerInfo, 0, sizeof(OSVERSIONINFO));
475 osVerInfo.dwOSVersionInfoSize = sizeof(OSVERSIONINFO);
477 if(GetVersionEx(&osVerInfo) == TRUE)
479 if(osVerInfo.dwPlatformId == VER_PLATFORM_WIN32_NT)
481 g_lamexp_os_version.version.versionMajor = osVerInfo.dwMajorVersion;
482 g_lamexp_os_version.version.versionMinor = osVerInfo.dwMinorVersion;
486 qWarning("lamexp_get_os_version: Not running under Windows NT, this is not supposed to happen!");
487 g_lamexp_os_version.version.versionMajor = 0;
488 g_lamexp_os_version.version.versionMinor = 0;
493 throw "GetVersionEx() has failed. This is not supposed to happen!";
496 g_lamexp_os_version.bInitialized = true;
499 return &g_lamexp_os_version.version;
503 * Check if we are running under wine
505 bool lamexp_detect_wine(void)
507 static bool isWine = false;
508 static bool isWine_initialized = false;
510 if(!isWine_initialized)
512 QLibrary ntdll("ntdll.dll");
515 if(ntdll.resolve("wine_nt_to_unix_file_name") != NULL) isWine = true;
516 if(ntdll.resolve("wine_get_version") != NULL) isWine = true;
519 isWine_initialized = true;
526 * Global exception handler
528 LONG WINAPI lamexp_exception_handler(__in struct _EXCEPTION_POINTERS *ExceptionInfo)
530 lamexp_fatal_exit(L"Unhandeled exception handler invoked, application will exit!");
535 * Invalid parameters handler
537 void lamexp_invalid_param_handler(const wchar_t* exp, const wchar_t* fun, const wchar_t* fil, unsigned int, uintptr_t)
539 lamexp_fatal_exit(L"Invalid parameter handler invoked, application will exit!");
543 * Change console text color
545 static void lamexp_console_color(FILE* file, WORD attributes)
547 const HANDLE hConsole = (HANDLE)(_get_osfhandle(_fileno(file)));
548 if((hConsole != NULL) && (hConsole != INVALID_HANDLE_VALUE))
550 SetConsoleTextAttribute(hConsole, attributes);
557 void lamexp_message_handler(QtMsgType type, const char *msg)
559 static const char *GURU_MEDITATION = "\n\nGURU MEDITATION !!!\n\n";
561 if(msg == NULL) return;
563 QMutexLocker lock(&g_lamexp_message_mutex);
565 if(g_lamexp_log_file)
567 static char prefix[] = "DWCF";
568 int index = qBound(0, static_cast<int>(type), 3);
569 unsigned int timestamp = static_cast<unsigned int>(_time64(NULL) % 3600I64);
570 QString str = QString::fromUtf8(msg).trimmed().replace('\n', '\t');
571 fprintf(g_lamexp_log_file, "[%c][%04u] %s\r\n", prefix[index], timestamp, str.toUtf8().constData());
572 fflush(g_lamexp_log_file);
575 if(g_lamexp_console_attached)
577 UINT oldOutputCP = GetConsoleOutputCP();
578 if(oldOutputCP != CP_UTF8) SetConsoleOutputCP(CP_UTF8);
586 lamexp_console_color(stderr, FOREGROUND_RED | FOREGROUND_INTENSITY);
587 fprintf(stderr, GURU_MEDITATION);
588 fprintf(stderr, "%s\n", msg);
592 lamexp_console_color(stderr, FOREGROUND_GREEN | FOREGROUND_RED | FOREGROUND_INTENSITY);
593 fprintf(stderr, "%s\n", msg);
597 lamexp_console_color(stderr, FOREGROUND_BLUE | FOREGROUND_GREEN | FOREGROUND_RED | FOREGROUND_INTENSITY);
598 fprintf(stderr, "%s\n", msg);
603 lamexp_console_color(stderr, FOREGROUND_BLUE | FOREGROUND_GREEN | FOREGROUND_RED);
604 if(oldOutputCP != CP_UTF8) SetConsoleOutputCP(oldOutputCP);
608 QString temp("[LameXP][%1] %2");
614 temp = temp.arg("C", QString::fromUtf8(msg));
617 temp = temp.arg("W", QString::fromUtf8(msg));
620 temp = temp.arg("I", QString::fromUtf8(msg));
624 temp.replace("\n", "\t").append("\n");
625 OutputDebugStringA(temp.toLatin1().constData());
628 if((type == QtCriticalMsg) || (type == QtFatalMsg))
631 lamexp_fatal_exit(L"The application has encountered a critical error and will exit now!", QWCHAR(QString::fromUtf8(msg)));
636 * Initialize the console
638 void lamexp_init_console(const QStringList &argv)
640 bool enableConsole = (LAMEXP_DEBUG) || ((VER_LAMEXP_CONSOLE_ENABLED) && lamexp_version_demo());
644 wchar_t *logfile = NULL;
645 size_t logfile_len = 0;
646 if(!_wdupenv_s(&logfile, &logfile_len, L"LAMEXP_LOGFILE"))
648 if(logfile && (logfile_len > 0))
651 if(!_wfopen_s(&temp, logfile, L"wb"))
653 fprintf(temp, "%c%c%c", 0xEF, 0xBB, 0xBF);
654 g_lamexp_log_file = temp;
663 for(int i = 0; i < argv.count(); i++)
665 if(!argv.at(i).compare("--console", Qt::CaseInsensitive))
667 enableConsole = true;
669 else if(!argv.at(i).compare("--no-console", Qt::CaseInsensitive))
671 enableConsole = false;
678 if(!g_lamexp_console_attached)
680 if(AllocConsole() != FALSE)
682 SetConsoleCtrlHandler(NULL, TRUE);
683 SetConsoleTitle(L"LameXP - Audio Encoder Front-End | Debug Console");
684 SetConsoleOutputCP(CP_UTF8);
685 g_lamexp_console_attached = true;
689 if(g_lamexp_console_attached)
691 //-------------------------------------------------------------------
692 //See: http://support.microsoft.com/default.aspx?scid=kb;en-us;105305
693 //-------------------------------------------------------------------
694 const int flags = _O_WRONLY | _O_U8TEXT;
695 int hCrtStdOut = _open_osfhandle((intptr_t) GetStdHandle(STD_OUTPUT_HANDLE), flags);
696 int hCrtStdErr = _open_osfhandle((intptr_t) GetStdHandle(STD_ERROR_HANDLE), flags);
697 FILE *hfStdOut = (hCrtStdOut >= 0) ? _fdopen(hCrtStdOut, "wb") : NULL;
698 FILE *hfStdErr = (hCrtStdErr >= 0) ? _fdopen(hCrtStdErr, "wb") : NULL;
699 if(hfStdOut) { *stdout = *hfStdOut; std::cout.rdbuf(new std::filebuf(hfStdOut)); }
700 if(hfStdErr) { *stderr = *hfStdErr; std::cerr.rdbuf(new std::filebuf(hfStdErr)); }
703 HWND hwndConsole = GetConsoleWindow();
705 if((hwndConsole != NULL) && (hwndConsole != INVALID_HANDLE_VALUE))
707 HMENU hMenu = GetSystemMenu(hwndConsole, 0);
708 EnableMenuItem(hMenu, SC_CLOSE, MF_BYCOMMAND | MF_GRAYED);
709 RemoveMenu(hMenu, SC_CLOSE, MF_BYCOMMAND);
711 SetWindowPos(hwndConsole, HWND_TOP, 0, 0, 0, 0, SWP_NOMOVE|SWP_NOSIZE|SWP_NOZORDER|SWP_FRAMECHANGED);
712 SetWindowLong(hwndConsole, GWL_STYLE, GetWindowLong(hwndConsole, GWL_STYLE) & (~WS_MAXIMIZEBOX) & (~WS_MINIMIZEBOX));
713 SetWindowPos(hwndConsole, HWND_TOP, 0, 0, 0, 0, SWP_NOMOVE|SWP_NOSIZE|SWP_NOZORDER|SWP_FRAMECHANGED);
719 * Detect CPU features
721 lamexp_cpu_t lamexp_detect_cpu_features(const QStringList &argv)
723 typedef BOOL (WINAPI *IsWow64ProcessFun)(__in HANDLE hProcess, __out PBOOL Wow64Process);
724 typedef VOID (WINAPI *GetNativeSystemInfoFun)(__out LPSYSTEM_INFO lpSystemInfo);
726 static IsWow64ProcessFun IsWow64ProcessPtr = NULL;
727 static GetNativeSystemInfoFun GetNativeSystemInfoPtr = NULL;
729 lamexp_cpu_t features;
730 SYSTEM_INFO systemInfo;
731 int CPUInfo[4] = {-1};
732 char CPUIdentificationString[0x40];
733 char CPUBrandString[0x40];
735 memset(&features, 0, sizeof(lamexp_cpu_t));
736 memset(&systemInfo, 0, sizeof(SYSTEM_INFO));
737 memset(CPUIdentificationString, 0, sizeof(CPUIdentificationString));
738 memset(CPUBrandString, 0, sizeof(CPUBrandString));
741 memcpy(CPUIdentificationString, &CPUInfo[1], sizeof(int));
742 memcpy(CPUIdentificationString + 4, &CPUInfo[3], sizeof(int));
743 memcpy(CPUIdentificationString + 8, &CPUInfo[2], sizeof(int));
744 features.intel = (_stricmp(CPUIdentificationString, "GenuineIntel") == 0);
745 strncpy_s(features.vendor, 0x40, CPUIdentificationString, _TRUNCATE);
750 features.mmx = (CPUInfo[3] & 0x800000) || false;
751 features.sse = (CPUInfo[3] & 0x2000000) || false;
752 features.sse2 = (CPUInfo[3] & 0x4000000) || false;
753 features.ssse3 = (CPUInfo[2] & 0x200) || false;
754 features.sse3 = (CPUInfo[2] & 0x1) || false;
755 features.ssse3 = (CPUInfo[2] & 0x200) || false;
756 features.stepping = CPUInfo[0] & 0xf;
757 features.model = ((CPUInfo[0] >> 4) & 0xf) + (((CPUInfo[0] >> 16) & 0xf) << 4);
758 features.family = ((CPUInfo[0] >> 8) & 0xf) + ((CPUInfo[0] >> 20) & 0xff);
761 __cpuid(CPUInfo, 0x80000000);
762 int nExIds = qMax<int>(qMin<int>(CPUInfo[0], 0x80000004), 0x80000000);
764 for(int i = 0x80000002; i <= nExIds; ++i)
770 memcpy(CPUBrandString, CPUInfo, sizeof(CPUInfo));
773 memcpy(CPUBrandString + 16, CPUInfo, sizeof(CPUInfo));
776 memcpy(CPUBrandString + 32, CPUInfo, sizeof(CPUInfo));
781 strncpy_s(features.brand, 0x40, CPUBrandString, _TRUNCATE);
783 if(strlen(features.brand) < 1) strncpy_s(features.brand, 0x40, "Unknown", _TRUNCATE);
784 if(strlen(features.vendor) < 1) strncpy_s(features.vendor, 0x40, "Unknown", _TRUNCATE);
786 #if !defined(_M_X64 ) && !defined(_M_IA64)
787 if(!IsWow64ProcessPtr || !GetNativeSystemInfoPtr)
789 QLibrary Kernel32Lib("kernel32.dll");
790 IsWow64ProcessPtr = (IsWow64ProcessFun) Kernel32Lib.resolve("IsWow64Process");
791 GetNativeSystemInfoPtr = (GetNativeSystemInfoFun) Kernel32Lib.resolve("GetNativeSystemInfo");
793 if(IsWow64ProcessPtr)
796 if(IsWow64ProcessPtr(GetCurrentProcess(), &x64))
801 if(GetNativeSystemInfoPtr)
803 GetNativeSystemInfoPtr(&systemInfo);
807 GetSystemInfo(&systemInfo);
809 features.count = qBound(1UL, systemInfo.dwNumberOfProcessors, 64UL);
811 GetNativeSystemInfo(&systemInfo);
812 features.count = systemInfo.dwNumberOfProcessors;
819 for(int i = 0; i < argv.count(); i++)
821 if(!argv[i].compare("--force-cpu-no-64bit", Qt::CaseInsensitive)) { flag = true; features.x64 = false; }
822 if(!argv[i].compare("--force-cpu-no-sse", Qt::CaseInsensitive)) { flag = true; features.sse = features.sse2 = features.sse3 = features.ssse3 = false; }
823 if(!argv[i].compare("--force-cpu-no-intel", Qt::CaseInsensitive)) { flag = true; features.intel = false; }
825 if(flag) qWarning("CPU flags overwritten by user-defined parameters. Take care!\n");
832 * Check for debugger (detect routine)
834 static __forceinline bool lamexp_check_for_debugger(void)
836 if(IsDebuggerPresent())
843 CloseHandle((HANDLE) 0x7FFFFFFF);
845 __except(EXCEPTION_EXECUTE_HANDLER)
854 __except(EXCEPTION_EXECUTE_HANDLER)
863 * Check for debugger (thread proc)
865 static unsigned int __stdcall lamexp_debug_thread_proc(LPVOID lpParameter)
867 while(!lamexp_check_for_debugger())
871 lamexp_fatal_exit(L"Not a debug build. Please unload debugger and try again!");
876 * Check for debugger (startup routine)
878 static HANDLE lamexp_debug_thread_init(void)
880 if(lamexp_check_for_debugger())
882 lamexp_fatal_exit(L"Not a debug build. Please unload debugger and try again!");
885 return (HANDLE) _beginthreadex(NULL, 0, lamexp_debug_thread_proc, NULL, 0, NULL);
889 * Check for compatibility mode
891 static bool lamexp_check_compatibility_mode(const char *exportName, const QString &executableName)
893 QLibrary kernel32("kernel32.dll");
895 if((exportName != NULL) && kernel32.load())
897 if(kernel32.resolve(exportName) != NULL)
899 qWarning("Function '%s' exported from 'kernel32.dll' -> Windows compatibility mode!", exportName);
900 qFatal("%s", QApplication::tr("Executable '%1' doesn't support Windows compatibility mode.").arg(executableName).toLatin1().constData());
909 * Computus according to H. Lichtenberg
911 static bool lamexp_computus(const QDate &date)
916 int M = 15 + (3*K + 3) / 4 - (8*K + 13) / 25;
917 int D = (19*A + M) % 30;
918 int S = 2 - (3*K + 3) / 4;
919 int R = D / 29 + (D / 28 - D / 29) * (A / 11);
921 int SZ = 7 - (X + X / 4 + S) % 7;
922 int OE = 7 - (OG - SZ) % 7;
927 return (date.month() == 4) && (date.day() == (OS - 31));
931 return (date.month() == 3) && (date.day() == OS);
936 * Check for Thanksgiving
938 static bool lamexp_thanksgiving(const QDate &date)
942 switch(QDate(date.year(), 11, 1).dayOfWeek())
944 case 1: day = 25; break;
945 case 2: day = 24; break;
946 case 3: day = 23; break;
947 case 4: day = 22; break;
948 case 5: day = 28; break;
949 case 6: day = 27; break;
950 case 7: day = 26; break;
953 return (date.month() == 11) && (date.day() == day);
957 * Initialize app icon
959 QIcon lamexp_app_icon(const QDate *date, const QTime *time)
961 QDate currentDate = (date) ? QDate(*date) : QDate::currentDate();
962 QTime currentTime = (time) ? QTime(*time) : QTime::currentTime();
964 if(lamexp_thanksgiving(currentDate))
966 return QIcon(":/MainIcon6.png");
968 else if(((currentDate.month() == 12) && (currentDate.day() == 31) && (currentTime.hour() >= 20)) || ((currentDate.month() == 1) && (currentDate.day() == 1) && (currentTime.hour() <= 19)))
970 return QIcon(":/MainIcon5.png");
972 else if(((currentDate.month() == 10) && (currentDate.day() == 31) && (currentTime.hour() >= 12)) || ((currentDate.month() == 11) && (currentDate.day() == 1) && (currentTime.hour() <= 11)))
974 return QIcon(":/MainIcon4.png");
976 else if((currentDate.month() == 12) && (currentDate.day() >= 24) && (currentDate.day() <= 26))
978 return QIcon(":/MainIcon3.png");
980 else if(lamexp_computus(currentDate))
982 return QIcon(":/MainIcon2.png");
986 return QIcon(":/MainIcon1.png");
991 * Broadcast event to all windows
993 static bool lamexp_broadcast(int eventType, bool onlyToVisible)
995 if(QApplication *app = dynamic_cast<QApplication*>(QApplication::instance()))
997 qDebug("Broadcasting %d", eventType);
1000 QEvent poEvent(static_cast<QEvent::Type>(eventType));
1001 QWidgetList list = app->topLevelWidgets();
1003 while(!list.isEmpty())
1005 QWidget *widget = list.takeFirst();
1006 if(!onlyToVisible || widget->isVisible())
1008 if(!app->sendEvent(widget, &poEvent))
1015 qDebug("Broadcast %d done (%s)", eventType, (allOk ? "OK" : "Stopped"));
1020 qWarning("Broadcast failed, could not get QApplication instance!");
1028 static bool lamexp_event_filter(void *message, long *result)
1030 if((!(LAMEXP_DEBUG)) && lamexp_check_for_debugger())
1032 lamexp_fatal_exit(L"Not a debug build. Please unload debugger and try again!");
1035 switch(reinterpret_cast<MSG*>(message)->message)
1037 case WM_QUERYENDSESSION:
1038 qWarning("WM_QUERYENDSESSION message received!");
1039 *result = lamexp_broadcast(lamexp_event_queryendsession, false) ? TRUE : FALSE;
1042 qWarning("WM_ENDSESSION message received!");
1043 if(reinterpret_cast<MSG*>(message)->wParam == TRUE)
1045 lamexp_broadcast(lamexp_event_endsession, false);
1046 if(QApplication *app = reinterpret_cast<QApplication*>(QApplication::instance()))
1048 app->closeAllWindows();
1051 lamexp_finalization();
1057 /*ignore this message and let Qt handle it*/
1063 * Check for process elevation
1065 static bool lamexp_check_elevation(void)
1067 typedef enum { lamexp_token_elevationType_class = 18, lamexp_token_elevation_class = 20 } LAMEXP_TOKEN_INFORMATION_CLASS;
1068 typedef enum { lamexp_elevationType_default = 1, lamexp_elevationType_full, lamexp_elevationType_limited } LAMEXP_TOKEN_ELEVATION_TYPE;
1070 HANDLE hToken = NULL;
1071 bool bIsProcessElevated = false;
1073 if(OpenProcessToken(GetCurrentProcess(), TOKEN_QUERY, &hToken))
1075 LAMEXP_TOKEN_ELEVATION_TYPE tokenElevationType;
1077 if(GetTokenInformation(hToken, (TOKEN_INFORMATION_CLASS) lamexp_token_elevationType_class, &tokenElevationType, sizeof(LAMEXP_TOKEN_ELEVATION_TYPE), &returnLength))
1079 if(returnLength == sizeof(LAMEXP_TOKEN_ELEVATION_TYPE))
1081 switch(tokenElevationType)
1083 case lamexp_elevationType_default:
1084 qDebug("Process token elevation type: Default -> UAC is disabled.\n");
1086 case lamexp_elevationType_full:
1087 qWarning("Process token elevation type: Full -> potential security risk!\n");
1088 bIsProcessElevated = true;
1090 case lamexp_elevationType_limited:
1091 qDebug("Process token elevation type: Limited -> not elevated.\n");
1096 CloseHandle(hToken);
1100 qWarning("Failed to open process token!");
1103 return !bIsProcessElevated;
1107 * Initialize Qt framework
1109 bool lamexp_init_qt(int argc, char* argv[])
1111 static bool qt_initialized = false;
1112 typedef BOOL (WINAPI *SetDllDirectoryProc)(WCHAR *lpPathName);
1113 const QStringList &arguments = lamexp_arguments();
1115 //Don't initialized again, if done already
1121 //Secure DLL loading
1122 QLibrary kernel32("kernel32.dll");
1125 SetDllDirectoryProc pSetDllDirectory = (SetDllDirectoryProc) kernel32.resolve("SetDllDirectoryW");
1126 if(pSetDllDirectory != NULL) pSetDllDirectory(L"");
1130 //Extract executable name from argv[] array
1131 QString executableName = QLatin1String("LameXP.exe");
1132 if(arguments.count() > 0)
1134 static const char *delimiters = "\\/:?";
1135 executableName = arguments[0].trimmed();
1136 for(int i = 0; delimiters[i]; i++)
1138 int temp = executableName.lastIndexOf(QChar(delimiters[i]));
1139 if(temp >= 0) executableName = executableName.mid(temp + 1);
1141 executableName = executableName.trimmed();
1142 if(executableName.isEmpty())
1144 executableName = QLatin1String("LameXP.exe");
1150 qDebug("Using Qt v%s [%s], %s, %s", qVersion(), QLibraryInfo::buildDate().toString(Qt::ISODate).toLatin1().constData(), (qSharedBuild() ? "DLL" : "Static"), QLibraryInfo::buildKey().toLatin1().constData());
1151 qDebug("Compiled with Qt v%s [%s], %s\n", QT_VERSION_STR, QT_PACKAGEDATE_STR, QT_BUILD_KEY);
1152 if(_stricmp(qVersion(), QT_VERSION_STR))
1154 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());
1157 if(QLibraryInfo::buildKey().compare(QString::fromLatin1(QT_BUILD_KEY), Qt::CaseInsensitive))
1159 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());
1163 qDebug("Using Qt v%s [%s], %s", qVersion(), QLibraryInfo::buildDate().toString(Qt::ISODate).toLatin1().constData(), (qSharedBuild() ? "DLL" : "Static"));
1164 qDebug("Compiled with Qt v%s [%s]\n", QT_VERSION_STR, QT_PACKAGEDATE_STR);
1167 //Check the Windows version
1168 switch(QSysInfo::windowsVersion() & QSysInfo::WV_NT_based)
1171 case QSysInfo::WV_NT:
1172 qFatal("%s", QApplication::tr("Executable '%1' requires Windows 2000 or later.").arg(executableName).toLatin1().constData());
1174 case QSysInfo::WV_2000:
1175 qDebug("Running on Windows 2000 (not officially supported!).\n");
1176 lamexp_check_compatibility_mode("GetNativeSystemInfo", executableName);
1178 case QSysInfo::WV_XP:
1179 qDebug("Running on Windows XP.\n");
1180 lamexp_check_compatibility_mode("GetLargePageMinimum", executableName);
1182 case QSysInfo::WV_2003:
1183 qDebug("Running on Windows Server 2003 or Windows XP x64-Edition.\n");
1184 lamexp_check_compatibility_mode("GetLocaleInfoEx", executableName);
1186 case QSysInfo::WV_VISTA:
1187 qDebug("Running on Windows Vista or Windows Server 2008.\n");
1188 lamexp_check_compatibility_mode("CreateRemoteThreadEx", executableName);
1190 case QSysInfo::WV_WINDOWS7:
1191 qDebug("Running on Windows 7 or Windows Server 2008 R2.\n");
1192 lamexp_check_compatibility_mode("CreateFile2", executableName);
1196 const lamexp_os_version_t *osVersionNo = lamexp_get_os_version();
1197 if(osVersionNo->versionMajor < 5)
1199 qFatal("%s", QApplication::tr("Executable '%1' requires Windows 2000 or later.").arg(executableName).toLatin1().constData());
1201 else if(LAMEXP_EQL_OS_VER(osVersionNo, 6, 2))
1203 qDebug("Running on Windows 8 or Windows Server 2012\n");
1204 lamexp_check_compatibility_mode(NULL, executableName);
1208 qWarning("Running on an unknown/untested WinNT-based OS (v%u.%u).\n", osVersionNo->versionMajor, osVersionNo->versionMinor);
1215 if(lamexp_detect_wine())
1217 qWarning("It appears we are running under Wine, unexpected things might happen!\n");
1220 //Set text Codec for locale
1221 QTextCodec::setCodecForLocale(QTextCodec::codecForName("UTF-8"));
1223 //Create Qt application instance
1224 QApplication *application = new QApplication(argc, argv);
1226 //Load plugins from application directory
1227 QCoreApplication::setLibraryPaths(QStringList() << QApplication::applicationDirPath());
1228 qDebug("Library Path:\n%s\n", QApplication::libraryPaths().first().toUtf8().constData());
1230 //Set application properties
1231 application->setApplicationName("LameXP - Audio Encoder Front-End");
1232 application->setApplicationVersion(QString().sprintf("%d.%02d.%04d", lamexp_version_major(), lamexp_version_minor(), lamexp_version_build()));
1233 application->setOrganizationName("LoRd_MuldeR");
1234 application->setOrganizationDomain("mulder.at.gg");
1235 application->setWindowIcon(lamexp_app_icon());
1236 application->setEventFilter(lamexp_event_filter);
1238 //Check for supported image formats
1239 QList<QByteArray> supportedFormats = QImageReader::supportedImageFormats();
1240 for(int i = 0; g_lamexp_imageformats[i]; i++)
1242 if(!supportedFormats.contains(g_lamexp_imageformats[i]))
1244 qFatal("Qt initialization error: QImageIOHandler for '%s' missing!", g_lamexp_imageformats[i]);
1249 //Add default translations
1250 QWriteLocker writeLockTranslations(&g_lamexp_translation.lock);
1251 if(!g_lamexp_translation.files) g_lamexp_translation.files = new QMap<QString, QString>();
1252 if(!g_lamexp_translation.names) g_lamexp_translation.names = new QMap<QString, QString>();
1253 g_lamexp_translation.files->insert(LAMEXP_DEFAULT_LANGID, "");
1254 g_lamexp_translation.names->insert(LAMEXP_DEFAULT_LANGID, "English");
1255 writeLockTranslations.unlock();
1257 //Check for process elevation
1258 if((!lamexp_check_elevation()) && (!lamexp_detect_wine()))
1260 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);
1261 messageBox.addButton("Quit Program (Recommended)", QMessageBox::NoRole);
1262 messageBox.addButton("Ignore", QMessageBox::NoRole);
1263 if(messageBox.exec() == 0)
1269 //Update console icon, if a console is attached
1270 #if QT_VERSION < QT_VERSION_CHECK(5,0,0)
1271 if(g_lamexp_console_attached && (!lamexp_detect_wine()))
1273 typedef DWORD (__stdcall *SetConsoleIconFun)(HICON);
1274 QLibrary kernel32("kernel32.dll");
1277 SetConsoleIconFun SetConsoleIconPtr = (SetConsoleIconFun) kernel32.resolve("SetConsoleIcon");
1278 if(SetConsoleIconPtr != NULL) SetConsoleIconPtr(QIcon(":/icons/sound.png").pixmap(16, 16).toWinHICON());
1285 qt_initialized = true;
1292 int lamexp_init_ipc(void)
1294 QWriteLocker writeLock(&g_lamexp_ipc_ptr.lock);
1296 if(g_lamexp_ipc_ptr.sharedmem && g_lamexp_ipc_ptr.semaphore_read && g_lamexp_ipc_ptr.semaphore_write && g_lamexp_ipc_ptr.semaphore_read_mutex && g_lamexp_ipc_ptr.semaphore_write_mutex)
1301 g_lamexp_ipc_ptr.semaphore_read = new QSystemSemaphore(QString(g_lamexp_ipc_uuid.semaphore_read), 0);
1302 g_lamexp_ipc_ptr.semaphore_write = new QSystemSemaphore(QString(g_lamexp_ipc_uuid.semaphore_write), 0);
1303 g_lamexp_ipc_ptr.semaphore_read_mutex = new QSystemSemaphore(QString(g_lamexp_ipc_uuid.semaphore_read_mutex), 0);
1304 g_lamexp_ipc_ptr.semaphore_write_mutex = new QSystemSemaphore(QString(g_lamexp_ipc_uuid.semaphore_write_mutex), 0);
1306 if(g_lamexp_ipc_ptr.semaphore_read->error() != QSystemSemaphore::NoError)
1308 QString errorMessage = g_lamexp_ipc_ptr.semaphore_read->errorString();
1309 LAMEXP_DELETE(g_lamexp_ipc_ptr.semaphore_read);
1310 LAMEXP_DELETE(g_lamexp_ipc_ptr.semaphore_write);
1311 LAMEXP_DELETE(g_lamexp_ipc_ptr.semaphore_read_mutex);
1312 LAMEXP_DELETE(g_lamexp_ipc_ptr.semaphore_write_mutex);
1313 qFatal("Failed to create system smaphore: %s", errorMessage.toUtf8().constData());
1316 if(g_lamexp_ipc_ptr.semaphore_write->error() != QSystemSemaphore::NoError)
1318 QString errorMessage = g_lamexp_ipc_ptr.semaphore_write->errorString();
1319 LAMEXP_DELETE(g_lamexp_ipc_ptr.semaphore_read);
1320 LAMEXP_DELETE(g_lamexp_ipc_ptr.semaphore_write);
1321 LAMEXP_DELETE(g_lamexp_ipc_ptr.semaphore_read_mutex);
1322 LAMEXP_DELETE(g_lamexp_ipc_ptr.semaphore_write_mutex);
1323 qFatal("Failed to create system smaphore: %s", errorMessage.toUtf8().constData());
1326 if(g_lamexp_ipc_ptr.semaphore_read_mutex->error() != QSystemSemaphore::NoError)
1328 QString errorMessage = g_lamexp_ipc_ptr.semaphore_read_mutex->errorString();
1329 LAMEXP_DELETE(g_lamexp_ipc_ptr.semaphore_read);
1330 LAMEXP_DELETE(g_lamexp_ipc_ptr.semaphore_write);
1331 LAMEXP_DELETE(g_lamexp_ipc_ptr.semaphore_read_mutex);
1332 LAMEXP_DELETE(g_lamexp_ipc_ptr.semaphore_write_mutex);
1333 qFatal("Failed to create system smaphore: %s", errorMessage.toUtf8().constData());
1336 if(g_lamexp_ipc_ptr.semaphore_write_mutex->error() != QSystemSemaphore::NoError)
1338 QString errorMessage = g_lamexp_ipc_ptr.semaphore_write_mutex->errorString();
1339 LAMEXP_DELETE(g_lamexp_ipc_ptr.semaphore_read);
1340 LAMEXP_DELETE(g_lamexp_ipc_ptr.semaphore_write);
1341 LAMEXP_DELETE(g_lamexp_ipc_ptr.semaphore_read_mutex);
1342 LAMEXP_DELETE(g_lamexp_ipc_ptr.semaphore_write_mutex);
1343 qFatal("Failed to create system smaphore: %s", errorMessage.toUtf8().constData());
1347 g_lamexp_ipc_ptr.sharedmem = new QSharedMemory(QString(g_lamexp_ipc_uuid.sharedmem), NULL);
1349 if(!g_lamexp_ipc_ptr.sharedmem->create(sizeof(lamexp_ipc_t)))
1351 if(g_lamexp_ipc_ptr.sharedmem->error() == QSharedMemory::AlreadyExists)
1353 g_lamexp_ipc_ptr.sharedmem->attach();
1354 if(g_lamexp_ipc_ptr.sharedmem->error() == QSharedMemory::NoError)
1360 QString errorMessage = g_lamexp_ipc_ptr.sharedmem->errorString();
1361 LAMEXP_DELETE(g_lamexp_ipc_ptr.sharedmem);
1362 qFatal("Failed to attach to shared memory: %s", errorMessage.toUtf8().constData());
1368 QString errorMessage = g_lamexp_ipc_ptr.sharedmem->errorString();
1369 LAMEXP_DELETE(g_lamexp_ipc_ptr.sharedmem);
1370 qFatal("Failed to create shared memory: %s", errorMessage.toUtf8().constData());
1375 memset(g_lamexp_ipc_ptr.sharedmem->data(), 0, sizeof(lamexp_ipc_t));
1376 g_lamexp_ipc_ptr.semaphore_write->release(g_lamexp_ipc_slots);
1377 g_lamexp_ipc_ptr.semaphore_read_mutex->release();
1378 g_lamexp_ipc_ptr.semaphore_write_mutex->release();
1386 void lamexp_ipc_send(unsigned int command, const char* message)
1388 QReadLocker readLock(&g_lamexp_ipc_ptr.lock);
1390 if(!g_lamexp_ipc_ptr.sharedmem || !g_lamexp_ipc_ptr.semaphore_read || !g_lamexp_ipc_ptr.semaphore_write || !g_lamexp_ipc_ptr.semaphore_read_mutex || !g_lamexp_ipc_ptr.semaphore_write_mutex)
1392 throw "Shared memory for IPC not initialized yet.";
1395 lamexp_ipc_data_t ipc_data;
1396 memset(&ipc_data, 0, sizeof(lamexp_ipc_data_t));
1397 ipc_data.command = command;
1401 strncpy_s(ipc_data.parameter, 4096, message, _TRUNCATE);
1404 if(g_lamexp_ipc_ptr.semaphore_write->acquire())
1406 if(g_lamexp_ipc_ptr.semaphore_write_mutex->acquire())
1408 lamexp_ipc_t *ptr = reinterpret_cast<lamexp_ipc_t*>(g_lamexp_ipc_ptr.sharedmem->data());
1409 memcpy(&ptr->data[ptr->pos_write], &ipc_data, sizeof(lamexp_ipc_data_t));
1410 ptr->pos_write = (ptr->pos_write + 1) % g_lamexp_ipc_slots;
1411 g_lamexp_ipc_ptr.semaphore_read->release();
1412 g_lamexp_ipc_ptr.semaphore_write_mutex->release();
1420 void lamexp_ipc_read(unsigned int *command, char* message, size_t buffSize)
1422 QReadLocker readLock(&g_lamexp_ipc_ptr.lock);
1427 if(!g_lamexp_ipc_ptr.sharedmem || !g_lamexp_ipc_ptr.semaphore_read || !g_lamexp_ipc_ptr.semaphore_write || !g_lamexp_ipc_ptr.semaphore_read_mutex || !g_lamexp_ipc_ptr.semaphore_write_mutex)
1429 throw "Shared memory for IPC not initialized yet.";
1432 lamexp_ipc_data_t ipc_data;
1433 memset(&ipc_data, 0, sizeof(lamexp_ipc_data_t));
1435 if(g_lamexp_ipc_ptr.semaphore_read->acquire())
1437 if(g_lamexp_ipc_ptr.semaphore_read_mutex->acquire())
1439 lamexp_ipc_t *ptr = reinterpret_cast<lamexp_ipc_t*>(g_lamexp_ipc_ptr.sharedmem->data());
1440 memcpy(&ipc_data, &ptr->data[ptr->pos_read], sizeof(lamexp_ipc_data_t));
1441 ptr->pos_read = (ptr->pos_read + 1) % g_lamexp_ipc_slots;
1442 g_lamexp_ipc_ptr.semaphore_write->release();
1443 g_lamexp_ipc_ptr.semaphore_read_mutex->release();
1445 if(!(ipc_data.reserved_1 || ipc_data.reserved_2))
1447 *command = ipc_data.command;
1448 strncpy_s(message, buffSize, ipc_data.parameter, _TRUNCATE);
1452 qWarning("Malformed IPC message, will be ignored");
1459 * Check for LameXP "portable" mode
1461 bool lamexp_portable_mode(void)
1463 QReadLocker readLock(&g_lamexp_portable.lock);
1465 if(g_lamexp_portable.bInitialized)
1467 return g_lamexp_portable.bPortableModeEnabled;
1471 QWriteLocker writeLock(&g_lamexp_portable.lock);
1473 if(!g_lamexp_portable.bInitialized)
1475 if(VER_LAMEXP_PORTABLE_EDITION)
1477 qWarning("LameXP portable edition!\n");
1478 g_lamexp_portable.bPortableModeEnabled = true;
1482 QString baseName = QFileInfo(QApplication::applicationFilePath()).completeBaseName();
1483 int idx1 = baseName.indexOf("lamexp", 0, Qt::CaseInsensitive);
1484 int idx2 = baseName.lastIndexOf("portable", -1, Qt::CaseInsensitive);
1485 g_lamexp_portable.bPortableModeEnabled = (idx1 >= 0) && (idx2 >= 0) && (idx1 < idx2);
1487 g_lamexp_portable.bInitialized = true;
1490 return g_lamexp_portable.bPortableModeEnabled;
1494 * Get a random string
1496 QString lamexp_rand_str(const bool bLong)
1498 const QUuid uuid = QUuid::createUuid().toString();
1500 const unsigned int u1 = uuid.data1;
1501 const unsigned int u2 = (((unsigned int)(uuid.data2)) << 16) | ((unsigned int)(uuid.data3));
1502 const unsigned int u3 = (((unsigned int)(uuid.data4[0])) << 24) | (((unsigned int)(uuid.data4[1])) << 16) | (((unsigned int)(uuid.data4[2])) << 8) | ((unsigned int)(uuid.data4[3]));
1503 const unsigned int u4 = (((unsigned int)(uuid.data4[4])) << 24) | (((unsigned int)(uuid.data4[5])) << 16) | (((unsigned int)(uuid.data4[6])) << 8) | ((unsigned int)(uuid.data4[7]));
1505 return bLong ? QString().sprintf("%08x%08x%08x%08x", u1, u2, u3, u4) : QString().sprintf("%08x%08x", (u1 ^ u2), (u3 ^ u4));
1510 * Try to initialize the folder (with *write* access)
1512 static QString lamexp_try_init_folder(const QString &folderPath)
1514 bool success = false;
1516 const QFileInfo folderInfo(folderPath);
1517 const QDir folderDir(folderInfo.absoluteFilePath());
1519 //Create folder, if it does *not* exist yet
1520 if(!folderDir.exists())
1522 folderDir.mkpath(".");
1525 //Make sure folder exists now *and* is writable
1526 if(folderDir.exists())
1528 QFile testFile(folderDir.absoluteFilePath(QString("~%1.tmp").arg(lamexp_rand_str())));
1529 if(testFile.open(QIODevice::ReadWrite))
1531 const QByteArray testData = QByteArray("Lorem ipsum dolor sit amet, consectetur, adipisci velit!");
1532 if(testFile.write(testData) >= strlen(testData))
1541 return (success ? folderDir.canonicalPath() : QString());
1545 * Initialize LameXP temp folder
1547 #define INIT_TEMP_FOLDER(OUT,TMP) do \
1549 (OUT) = lamexp_try_init_folder(QString("%1/%2").arg((TMP), lamexp_rand_str())); \
1554 * Get LameXP temp folder
1556 const QString &lamexp_temp_folder2(void)
1558 QReadLocker readLock(&g_lamexp_temp_folder.lock);
1560 //Already initialized?
1561 if(g_lamexp_temp_folder.path && (!g_lamexp_temp_folder.path->isEmpty()))
1563 if(QDir(*g_lamexp_temp_folder.path).exists())
1565 return *g_lamexp_temp_folder.path;
1569 //Obtain the write lock to initilaize
1571 QWriteLocker writeLock(&g_lamexp_temp_folder.lock);
1573 //Still uninitilaized?
1574 if(g_lamexp_temp_folder.path && (!g_lamexp_temp_folder.path->isEmpty()))
1576 if(QDir(*g_lamexp_temp_folder.path).exists())
1578 return *g_lamexp_temp_folder.path;
1582 //Create the string, if not done yet
1583 if(!g_lamexp_temp_folder.path)
1585 g_lamexp_temp_folder.path = new QString();
1588 g_lamexp_temp_folder.path->clear();
1590 //Try the %TMP% or %TEMP% directory first
1591 QString tempPath = lamexp_try_init_folder(QDir::temp().absolutePath());
1592 if(!tempPath.isEmpty())
1594 INIT_TEMP_FOLDER(*g_lamexp_temp_folder.path, tempPath);
1597 //Otherwise create TEMP folder in %LOCALAPPDATA%
1598 if(g_lamexp_temp_folder.path->isEmpty())
1600 tempPath = lamexp_try_init_folder(QString("%1/Temp").arg(lamexp_known_folder(lamexp_folder_localappdata)));
1601 if(!tempPath.isEmpty())
1603 INIT_TEMP_FOLDER(*g_lamexp_temp_folder.path, tempPath);
1607 //Failed to create TEMP folder?
1608 if(g_lamexp_temp_folder.path->isEmpty())
1610 qFatal("Temporary directory could not be initialized !!!");
1613 return *g_lamexp_temp_folder.path;
1619 bool lamexp_clean_folder(const QString &folderPath)
1621 QDir tempFolder(folderPath);
1622 QFileInfoList entryList = tempFolder.entryInfoList(QDir::AllEntries | QDir::NoDotAndDotDot);
1624 for(int i = 0; i < entryList.count(); i++)
1626 if(entryList.at(i).isDir())
1628 lamexp_clean_folder(entryList.at(i).canonicalFilePath());
1632 for(int j = 0; j < 3; j++)
1634 if(lamexp_remove_file(entryList.at(i).canonicalFilePath()))
1642 tempFolder.rmdir(".");
1643 return !tempFolder.exists();
1649 void lamexp_register_tool(const QString &toolName, LockedFile *file, unsigned int version, const QString *tag)
1651 QWriteLocker writeLock(&g_lamexp_tools.lock);
1653 if(!g_lamexp_tools.registry) g_lamexp_tools.registry = new QMap<QString, LockedFile*>();
1654 if(!g_lamexp_tools.versions) g_lamexp_tools.versions = new QMap<QString, unsigned int>();
1655 if(!g_lamexp_tools.tags) g_lamexp_tools.tags = new QMap<QString, QString>();
1657 if(g_lamexp_tools.registry->contains(toolName.toLower()))
1659 throw "lamexp_register_tool: Tool is already registered!";
1662 g_lamexp_tools.registry->insert(toolName.toLower(), file);
1663 g_lamexp_tools.versions->insert(toolName.toLower(), version);
1664 g_lamexp_tools.tags->insert(toolName.toLower(), (tag) ? (*tag) : QString());
1670 bool lamexp_check_tool(const QString &toolName)
1672 QReadLocker readLock(&g_lamexp_tools.lock);
1673 return (g_lamexp_tools.registry) ? g_lamexp_tools.registry->contains(toolName.toLower()) : false;
1679 const QString lamexp_lookup_tool(const QString &toolName)
1681 QReadLocker readLock(&g_lamexp_tools.lock);
1683 if(g_lamexp_tools.registry)
1685 if(g_lamexp_tools.registry->contains(toolName.toLower()))
1687 return g_lamexp_tools.registry->value(toolName.toLower())->filePath();
1701 * Lookup tool version
1703 unsigned int lamexp_tool_version(const QString &toolName, QString *tag)
1705 QReadLocker readLock(&g_lamexp_tools.lock);
1706 if(tag) tag->clear();
1708 if(g_lamexp_tools.versions)
1710 if(g_lamexp_tools.versions->contains(toolName.toLower()))
1714 if(g_lamexp_tools.tags->contains(toolName.toLower())) *tag = g_lamexp_tools.tags->value(toolName.toLower());
1716 return g_lamexp_tools.versions->value(toolName.toLower());
1730 * Version number to human-readable string
1732 const QString lamexp_version2string(const QString &pattern, unsigned int version, const QString &defaultText, const QString *tag)
1734 if(version == UINT_MAX)
1739 QString result = pattern;
1740 int digits = result.count("?", Qt::CaseInsensitive);
1748 QString versionStr = QString().sprintf(QString().sprintf("%%0%du", digits).toLatin1().constData(), version);
1749 int index = result.indexOf("?", Qt::CaseInsensitive);
1751 while(index >= 0 && pos < versionStr.length())
1753 result[index] = versionStr[pos++];
1754 index = result.indexOf("?", Qt::CaseInsensitive);
1759 result.replace(QChar('#'), *tag, Qt::CaseInsensitive);
1766 * Register a new translation
1768 bool lamexp_translation_register(const QString &langId, const QString &qmFile, const QString &langName, unsigned int &systemId, unsigned int &country)
1770 QWriteLocker writeLockTranslations(&g_lamexp_translation.lock);
1772 if(qmFile.isEmpty() || langName.isEmpty() || systemId < 1)
1777 if(!g_lamexp_translation.files) g_lamexp_translation.files = new QMap<QString, QString>();
1778 if(!g_lamexp_translation.names) g_lamexp_translation.names = new QMap<QString, QString>();
1779 if(!g_lamexp_translation.sysid) g_lamexp_translation.sysid = new QMap<QString, unsigned int>();
1780 if(!g_lamexp_translation.cntry) g_lamexp_translation.cntry = new QMap<QString, unsigned int>();
1782 g_lamexp_translation.files->insert(langId, qmFile);
1783 g_lamexp_translation.names->insert(langId, langName);
1784 g_lamexp_translation.sysid->insert(langId, systemId);
1785 g_lamexp_translation.cntry->insert(langId, country);
1791 * Get list of all translations
1793 QStringList lamexp_query_translations(void)
1795 QReadLocker readLockTranslations(&g_lamexp_translation.lock);
1796 return (g_lamexp_translation.files) ? g_lamexp_translation.files->keys() : QStringList();
1800 * Get translation name
1802 QString lamexp_translation_name(const QString &langId)
1804 QReadLocker readLockTranslations(&g_lamexp_translation.lock);
1805 return (g_lamexp_translation.names) ? g_lamexp_translation.names->value(langId.toLower(), QString()) : QString();
1809 * Get translation system id
1811 unsigned int lamexp_translation_sysid(const QString &langId)
1813 QReadLocker readLockTranslations(&g_lamexp_translation.lock);
1814 return (g_lamexp_translation.sysid) ? g_lamexp_translation.sysid->value(langId.toLower(), 0) : 0;
1818 * Get translation script id
1820 unsigned int lamexp_translation_country(const QString &langId)
1822 QReadLocker readLockTranslations(&g_lamexp_translation.lock);
1823 return (g_lamexp_translation.cntry) ? g_lamexp_translation.cntry->value(langId.toLower(), 0) : 0;
1827 * Install a new translator
1829 bool lamexp_install_translator(const QString &langId)
1831 bool success = false;
1832 const QString qmFileToPath(":/localization/%1");
1834 if(langId.isEmpty() || langId.toLower().compare(LAMEXP_DEFAULT_LANGID) == 0)
1836 success = lamexp_install_translator_from_file(qmFileToPath.arg(LAMEXP_DEFAULT_TRANSLATION));
1840 QReadLocker readLock(&g_lamexp_translation.lock);
1841 QString qmFile = (g_lamexp_translation.files) ? g_lamexp_translation.files->value(langId.toLower(), QString()) : QString();
1844 if(!qmFile.isEmpty())
1846 success = lamexp_install_translator_from_file(qmFileToPath.arg(qmFile));
1850 qWarning("Translation '%s' not available!", langId.toLatin1().constData());
1858 * Install a new translator from file
1860 bool lamexp_install_translator_from_file(const QString &qmFile)
1862 QWriteLocker writeLock(&g_lamexp_currentTranslator.lock);
1863 bool success = false;
1865 if(!g_lamexp_currentTranslator.instance)
1867 g_lamexp_currentTranslator.instance = new QTranslator();
1870 if(!qmFile.isEmpty())
1872 QString qmPath = QFileInfo(qmFile).canonicalFilePath();
1873 QApplication::removeTranslator(g_lamexp_currentTranslator.instance);
1874 if(success = g_lamexp_currentTranslator.instance->load(qmPath))
1876 QApplication::installTranslator(g_lamexp_currentTranslator.instance);
1880 qWarning("Failed to load translation:\n\"%s\"", qmPath.toLatin1().constData());
1885 QApplication::removeTranslator(g_lamexp_currentTranslator.instance);
1892 const QStringList &lamexp_arguments(void)
1894 QReadLocker readLock(&g_lamexp_argv.lock);
1896 if(!g_lamexp_argv.list)
1899 QWriteLocker writeLock(&g_lamexp_argv.lock);
1901 g_lamexp_argv.list = new QStringList;
1904 LPWSTR *szArglist = CommandLineToArgvW(GetCommandLineW(), &nArgs);
1906 if(NULL != szArglist)
1908 for(int i = 0; i < nArgs; i++)
1910 (*g_lamexp_argv.list) << WCHAR2QSTR(szArglist[i]);
1912 LocalFree(szArglist);
1916 qWarning("CommandLineToArgvW() has failed !!!");
1920 return (*g_lamexp_argv.list);
1924 * Locate known folder on local system
1926 const QString &lamexp_known_folder(lamexp_known_folder_t folder_id)
1928 typedef HRESULT (WINAPI *SHGetKnownFolderPathFun)(__in const GUID &rfid, __in DWORD dwFlags, __in HANDLE hToken, __out PWSTR *ppszPath);
1929 typedef HRESULT (WINAPI *SHGetFolderPathFun)(__in HWND hwndOwner, __in int nFolder, __in HANDLE hToken, __in DWORD dwFlags, __out LPWSTR pszPath);
1931 static const int CSIDL_LOCAL_APPDATA = 0x001c;
1932 static const int CSIDL_PROGRAM_FILES = 0x0026;
1933 static const int CSIDL_SYSTEM_FOLDER = 0x0025;
1934 static const GUID GUID_LOCAL_APPDATA = {0xF1B32785,0x6FBA,0x4FCF,{0x9D,0x55,0x7B,0x8E,0x7F,0x15,0x70,0x91}};
1935 static const GUID GUID_LOCAL_APPDATA_LOW = {0xA520A1A4,0x1780,0x4FF6,{0xBD,0x18,0x16,0x73,0x43,0xC5,0xAF,0x16}};
1936 static const GUID GUID_PROGRAM_FILES = {0x905e63b6,0xc1bf,0x494e,{0xb2,0x9c,0x65,0xb7,0x32,0xd3,0xd2,0x1a}};
1937 static const GUID GUID_SYSTEM_FOLDER = {0x1AC14E77,0x02E7,0x4E5D,{0xB7,0x44,0x2E,0xB1,0xAE,0x51,0x98,0xB7}};
1939 QReadLocker readLock(&g_lamexp_known_folder.lock);
1941 int folderCSIDL = -1;
1942 GUID folderGUID = {0x0000,0x0000,0x0000,{0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00}};
1943 size_t folderCacheId = size_t(-1);
1947 case lamexp_folder_localappdata:
1949 folderCSIDL = CSIDL_LOCAL_APPDATA;
1950 folderGUID = GUID_LOCAL_APPDATA;
1952 case lamexp_folder_programfiles:
1954 folderCSIDL = CSIDL_PROGRAM_FILES;
1955 folderGUID = GUID_PROGRAM_FILES;
1957 case lamexp_folder_systemfolder:
1959 folderCSIDL = CSIDL_SYSTEM_FOLDER;
1960 folderGUID = GUID_SYSTEM_FOLDER;
1963 qWarning("Invalid 'known' folder was requested!");
1964 return *reinterpret_cast<QString*>(NULL);
1969 if(g_lamexp_known_folder.knownFolders)
1971 if(g_lamexp_known_folder.knownFolders->contains(folderCacheId))
1973 return (*g_lamexp_known_folder.knownFolders)[folderCacheId];
1977 //Obtain write lock to initialize
1979 QWriteLocker writeLock(&g_lamexp_known_folder.lock);
1981 //Still not in cache?
1982 if(g_lamexp_known_folder.knownFolders)
1984 if(g_lamexp_known_folder.knownFolders->contains(folderCacheId))
1986 return (*g_lamexp_known_folder.knownFolders)[folderCacheId];
1990 static SHGetKnownFolderPathFun SHGetKnownFolderPathPtr = NULL;
1991 static SHGetFolderPathFun SHGetFolderPathPtr = NULL;
1994 if((!SHGetKnownFolderPathPtr) && (!SHGetFolderPathPtr))
1996 QLibrary kernel32Lib("shell32.dll");
1997 if(kernel32Lib.load())
1999 SHGetKnownFolderPathPtr = (SHGetKnownFolderPathFun) kernel32Lib.resolve("SHGetKnownFolderPath");
2000 SHGetFolderPathPtr = (SHGetFolderPathFun) kernel32Lib.resolve("SHGetFolderPathW");
2006 //Now try to get the folder path!
2007 if(SHGetKnownFolderPathPtr)
2010 if(SHGetKnownFolderPathPtr(folderGUID, 0x00008000, NULL, &path) == S_OK)
2012 //MessageBoxW(0, path, L"SHGetKnownFolderPath", MB_TOPMOST);
2013 QDir folderTemp = QDir(QDir::fromNativeSeparators(QString::fromUtf16(reinterpret_cast<const unsigned short*>(path))));
2014 if(!folderTemp.exists())
2016 folderTemp.mkpath(".");
2018 if(folderTemp.exists())
2020 folder = folderTemp.canonicalPath();
2022 CoTaskMemFree(path);
2025 else if(SHGetFolderPathPtr)
2027 WCHAR *path = new WCHAR[4096];
2028 if(SHGetFolderPathPtr(NULL, folderCSIDL, NULL, NULL, path) == S_OK)
2030 //MessageBoxW(0, path, L"SHGetFolderPathW", MB_TOPMOST);
2031 QDir folderTemp = QDir(QDir::fromNativeSeparators(QString::fromUtf16(reinterpret_cast<const unsigned short*>(path))));
2032 if(!folderTemp.exists())
2034 folderTemp.mkpath(".");
2036 if(folderTemp.exists())
2038 folder = folderTemp.canonicalPath();
2045 if(!g_lamexp_known_folder.knownFolders)
2047 g_lamexp_known_folder.knownFolders = new QMap<size_t, QString>();
2051 g_lamexp_known_folder.knownFolders->insert(folderCacheId, folder);
2052 return (*g_lamexp_known_folder.knownFolders)[folderCacheId];
2056 * Safely remove a file
2058 bool lamexp_remove_file(const QString &filename)
2060 if(!QFileInfo(filename).exists() || !QFileInfo(filename).isFile())
2066 if(!QFile::remove(filename))
2068 DWORD attributes = GetFileAttributesW(QWCHAR(filename));
2069 SetFileAttributesW(QWCHAR(filename), (attributes & (~FILE_ATTRIBUTE_READONLY)));
2070 if(!QFile::remove(filename))
2072 qWarning("Could not delete \"%s\"", filename.toLatin1().constData());
2088 * Check if visual themes are enabled (WinXP and later)
2090 bool lamexp_themes_enabled(void)
2092 typedef int (WINAPI *IsAppThemedFun)(void);
2094 QReadLocker readLock(&g_lamexp_themes_enabled.lock);
2095 if(g_lamexp_themes_enabled.bInitialized)
2097 return g_lamexp_themes_enabled.bThemesEnabled;
2101 QWriteLocker writeLock(&g_lamexp_themes_enabled.lock);
2103 if(!g_lamexp_themes_enabled.bInitialized)
2105 g_lamexp_themes_enabled.bThemesEnabled = false;
2106 const lamexp_os_version_t * osVersion = lamexp_get_os_version();
2107 if(LAMEXP_MIN_OS_VER(osVersion, 5, 1))
2109 IsAppThemedFun IsAppThemedPtr = NULL;
2110 QLibrary uxTheme(QString("%1/UxTheme.dll").arg(lamexp_known_folder(lamexp_folder_systemfolder)));
2113 IsAppThemedPtr = (IsAppThemedFun) uxTheme.resolve("IsAppThemed");
2117 g_lamexp_themes_enabled.bThemesEnabled = IsAppThemedPtr();
2118 if(!g_lamexp_themes_enabled.bThemesEnabled)
2120 qWarning("Theme support is disabled for this process!");
2124 g_lamexp_themes_enabled.bInitialized = true;
2127 return g_lamexp_themes_enabled.bThemesEnabled;
2131 * Get number of free bytes on disk
2133 unsigned __int64 lamexp_free_diskspace(const QString &path, bool *ok)
2135 ULARGE_INTEGER freeBytesAvailable, totalNumberOfBytes, totalNumberOfFreeBytes;
2136 if(GetDiskFreeSpaceExW(reinterpret_cast<const wchar_t*>(QDir::toNativeSeparators(path).utf16()), &freeBytesAvailable, &totalNumberOfBytes, &totalNumberOfFreeBytes))
2139 return freeBytesAvailable.QuadPart;
2149 * Check if computer does support hibernation
2151 bool lamexp_is_hibernation_supported(void)
2153 bool hibernationSupported = false;
2155 SYSTEM_POWER_CAPABILITIES pwrCaps;
2156 SecureZeroMemory(&pwrCaps, sizeof(SYSTEM_POWER_CAPABILITIES));
2158 if(GetPwrCapabilities(&pwrCaps))
2160 hibernationSupported = pwrCaps.SystemS4 && pwrCaps.HiberFilePresent;
2163 return hibernationSupported;
2167 * Shutdown the computer
2169 bool lamexp_shutdown_computer(const QString &message, const unsigned long timeout, const bool forceShutdown, const bool hibernate)
2171 HANDLE hToken = NULL;
2173 if(OpenProcessToken(GetCurrentProcess(), TOKEN_ADJUST_PRIVILEGES | TOKEN_QUERY, &hToken))
2175 TOKEN_PRIVILEGES privileges;
2176 memset(&privileges, 0, sizeof(TOKEN_PRIVILEGES));
2177 privileges.PrivilegeCount = 1;
2178 privileges.Privileges[0].Attributes = SE_PRIVILEGE_ENABLED;
2180 if(LookupPrivilegeValue(NULL, SE_SHUTDOWN_NAME, &privileges.Privileges[0].Luid))
2182 if(AdjustTokenPrivileges(hToken, FALSE, &privileges, NULL, NULL, NULL))
2186 if(SetSuspendState(TRUE, TRUE, TRUE))
2191 const DWORD reason = SHTDN_REASON_MAJOR_APPLICATION | SHTDN_REASON_FLAG_PLANNED;
2192 return InitiateSystemShutdownEx(NULL, const_cast<wchar_t*>(QWCHAR(message)), timeout, forceShutdown ? TRUE : FALSE, FALSE, reason);
2201 * Make a window blink (to draw user's attention)
2203 void lamexp_blink_window(QWidget *poWindow, unsigned int count, unsigned int delay)
2205 static QMutex blinkMutex;
2207 const double maxOpac = 1.0;
2208 const double minOpac = 0.3;
2209 const double delOpac = 0.1;
2211 if(!blinkMutex.tryLock())
2213 qWarning("Blinking is already in progress, skipping!");
2219 const int steps = static_cast<int>(ceil(maxOpac - minOpac) / delOpac);
2220 const int sleep = static_cast<int>(floor(static_cast<double>(delay) / static_cast<double>(steps)));
2221 const double opacity = poWindow->windowOpacity();
2223 for(unsigned int i = 0; i < count; i++)
2225 for(double x = maxOpac; x >= minOpac; x -= delOpac)
2227 poWindow->setWindowOpacity(x);
2228 QApplication::processEvents();
2232 for(double x = minOpac; x <= maxOpac; x += delOpac)
2234 poWindow->setWindowOpacity(x);
2235 QApplication::processEvents();
2240 poWindow->setWindowOpacity(opacity);
2241 QApplication::processEvents();
2242 blinkMutex.unlock();
2246 blinkMutex.unlock();
2247 qWarning("Exception error while blinking!");
2252 * Remove forbidden characters from a filename
2254 const QString lamexp_clean_filename(const QString &str)
2256 QString newStr(str);
2257 QRegExp rx("\"(.+)\"");
2258 rx.setMinimal(true);
2260 newStr.replace("\\", "-");
2261 newStr.replace(" / ", ", ");
2262 newStr.replace("/", ",");
2263 newStr.replace(":", "-");
2264 newStr.replace("*", "x");
2265 newStr.replace("?", "");
2266 newStr.replace("<", "[");
2267 newStr.replace(">", "]");
2268 newStr.replace("|", "!");
2269 newStr.replace(rx, "`\\1´");
2270 newStr.replace("\"", "'");
2272 return newStr.simplified();
2276 * Remove forbidden characters from a file path
2278 const QString lamexp_clean_filepath(const QString &str)
2280 QStringList parts = QString(str).replace("\\", "/").split("/");
2282 for(int i = 0; i < parts.count(); i++)
2284 parts[i] = lamexp_clean_filename(parts[i]);
2287 return parts.join("/");
2291 * Get a list of all available Qt Text Codecs
2293 QStringList lamexp_available_codepages(bool noAliases)
2295 QStringList codecList;
2297 QList<QByteArray> availableCodecs = QTextCodec::availableCodecs();
2298 while(!availableCodecs.isEmpty())
2300 QByteArray current = availableCodecs.takeFirst();
2301 if(!(current.startsWith("system") || current.startsWith("System")))
2303 codecList << QString::fromLatin1(current.constData(), current.size());
2306 if(QTextCodec *currentCodec = QTextCodec::codecForName(current.constData()))
2309 QList<QByteArray> aliases = currentCodec->aliases();
2310 while(!aliases.isEmpty()) availableCodecs.removeAll(aliases.takeFirst());
2320 * Robert Jenkins' 96 bit Mix Function
2321 * Source: http://www.concentric.net/~Ttwang/tech/inthash.htm
2323 static unsigned int lamexp_mix(const unsigned int x, const unsigned int y, const unsigned int z)
2329 a=a-b; a=a-c; a=a^(c >> 13);
2330 b=b-c; b=b-a; b=b^(a << 8);
2331 c=c-a; c=c-b; c=c^(b >> 13);
2332 a=a-b; a=a-c; a=a^(c >> 12);
2333 b=b-c; b=b-a; b=b^(a << 16);
2334 c=c-a; c=c-b; c=c^(b >> 5);
2335 a=a-b; a=a-c; a=a^(c >> 3);
2336 b=b-c; b=b-a; b=b^(a << 10);
2337 c=c-a; c=c-b; c=c^(b >> 15);
2343 * Seeds the random number generator
2344 * Note: Altough rand_s() doesn't need a seed, this must be called pripr to lamexp_rand(), just to to be sure!
2346 void lamexp_seed_rand(void)
2348 qsrand(lamexp_mix(clock(), time(NULL), _getpid()));
2352 * Returns a randum number
2353 * Note: This function uses rand_s() if available, but falls back to qrand() otherwise
2355 unsigned int lamexp_rand(void)
2357 unsigned int rnd = 0;
2358 if(const lamexp_os_version_t* osVer = lamexp_get_os_version())
2360 if(LAMEXP_MIN_OS_VER(osVer, 5, 1))
2362 if(rand_s(&rnd) == 0)
2368 for(size_t i = 0; i < sizeof(unsigned int); i++)
2370 rnd = (rnd << 8) ^ qrand();
2376 * Determines the current date, resistant against certain manipulations
2378 QDate lamexp_current_date_safe(void)
2380 const DWORD MAX_PROC = 1024;
2381 DWORD *processes = new DWORD[MAX_PROC];
2382 DWORD bytesReturned = 0;
2384 if(!EnumProcesses(processes, sizeof(DWORD) * MAX_PROC, &bytesReturned))
2386 LAMEXP_DELETE_ARRAY(processes);
2387 return QDate::currentDate();
2390 const DWORD procCount = bytesReturned / sizeof(DWORD);
2391 ULARGE_INTEGER lastStartTime;
2392 memset(&lastStartTime, 0, sizeof(ULARGE_INTEGER));
2394 for(DWORD i = 0; i < procCount; i++)
2396 HANDLE hProc = OpenProcess(PROCESS_QUERY_INFORMATION, FALSE, processes[i]);
2399 FILETIME processTime[4];
2400 if(GetProcessTimes(hProc, &processTime[0], &processTime[1], &processTime[2], &processTime[3]))
2402 ULARGE_INTEGER timeCreation;
2403 timeCreation.LowPart = processTime[0].dwLowDateTime;
2404 timeCreation.HighPart = processTime[0].dwHighDateTime;
2405 if(timeCreation.QuadPart > lastStartTime.QuadPart)
2407 lastStartTime.QuadPart = timeCreation.QuadPart;
2414 LAMEXP_DELETE_ARRAY(processes);
2416 FILETIME lastStartTime_fileTime;
2417 lastStartTime_fileTime.dwHighDateTime = lastStartTime.HighPart;
2418 lastStartTime_fileTime.dwLowDateTime = lastStartTime.LowPart;
2420 FILETIME lastStartTime_localTime;
2421 if(!FileTimeToLocalFileTime(&lastStartTime_fileTime, &lastStartTime_localTime))
2423 memcpy(&lastStartTime_localTime, &lastStartTime_fileTime, sizeof(FILETIME));
2426 SYSTEMTIME lastStartTime_system;
2427 if(!FileTimeToSystemTime(&lastStartTime_localTime, &lastStartTime_system))
2429 memset(&lastStartTime_system, 0, sizeof(SYSTEMTIME));
2430 lastStartTime_system.wYear = 1970; lastStartTime_system.wMonth = lastStartTime_system.wDay = 1;
2433 const QDate currentDate = QDate::currentDate();
2434 const QDate processDate = QDate(lastStartTime_system.wYear, lastStartTime_system.wMonth, lastStartTime_system.wDay);
2435 return (currentDate >= processDate) ? currentDate : processDate;
2440 * Natural Order String Comparison - the 'lessThan' helper function
2442 static bool lamexp_natural_string_sort_helper(const QString &str1, const QString &str2)
2444 return (strnatcmp(QWCHAR(str1), QWCHAR(str2)) < 0);
2448 * Natural Order String Comparison - the 'lessThan' helper function *with* case folding
2450 static bool lamexp_natural_string_sort_helper_fold_case(const QString &str1, const QString &str2)
2452 return (strnatcasecmp(QWCHAR(str1), QWCHAR(str2)) < 0);
2456 * Natural Order String Comparison - the main sorting function
2458 void lamexp_natural_string_sort(QStringList &list, const bool bIgnoreCase)
2460 qSort(list.begin(), list.end(), bIgnoreCase ? lamexp_natural_string_sort_helper_fold_case : lamexp_natural_string_sort_helper);
2464 * Suspend calling thread for N milliseconds
2466 void lamexp_sleep(const unsigned int delay)
2471 bool lamexp_beep(int beepType)
2475 case lamexp_beep_info: return MessageBeep(MB_ICONASTERISK) == TRUE; break;
2476 case lamexp_beep_warning: return MessageBeep(MB_ICONEXCLAMATION) == TRUE; break;
2477 case lamexp_beep_error: return MessageBeep(MB_ICONHAND) == TRUE; break;
2478 default: return false;
2483 * Play a sound (from resources)
2485 bool lamexp_play_sound(const unsigned short uiSoundIdx, const bool bAsync, const wchar_t *alias)
2489 return PlaySound(alias, GetModuleHandle(NULL), (SND_ALIAS | (bAsync ? SND_ASYNC : SND_SYNC))) == TRUE;
2493 return PlaySound(MAKEINTRESOURCE(uiSoundIdx), GetModuleHandle(NULL), (SND_RESOURCE | (bAsync ? SND_ASYNC : SND_SYNC))) == TRUE;
2498 * Play a sound (from resources)
2500 bool lamexp_play_sound_file(const QString &library, const unsigned short uiSoundIdx, const bool bAsync)
2502 bool result = false;
2503 HMODULE module = NULL;
2505 QFileInfo libraryFile(library);
2506 if(!libraryFile.isAbsolute())
2508 unsigned int buffSize = GetSystemDirectoryW(NULL, NULL) + 1;
2509 wchar_t *buffer = (wchar_t*) _malloca(buffSize * sizeof(wchar_t));
2510 unsigned int result = GetSystemDirectory(buffer, buffSize);
2511 if(result > 0 && result < buffSize)
2513 libraryFile.setFile(QString("%1/%2").arg(QDir::fromNativeSeparators(QString::fromUtf16(reinterpret_cast<const unsigned short*>(buffer))), library));
2518 module = LoadLibraryW(QWCHAR(QDir::toNativeSeparators(libraryFile.absoluteFilePath())));
2521 result = (PlaySound(MAKEINTRESOURCE(uiSoundIdx), module, (SND_RESOURCE | (bAsync ? SND_ASYNC : SND_SYNC))) == TRUE);
2522 FreeLibrary(module);
2529 * Open file using the shell
2531 bool lamexp_exec_shell(const QWidget *win, const QString &url, const bool explore)
2533 return lamexp_exec_shell(win, url, QString(), QString(), explore);
2537 * Open file using the shell (with parameters)
2539 bool lamexp_exec_shell(const QWidget *win, const QString &url, const QString ¶meters, const QString &directory, const bool explore)
2541 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;
2545 * Query value of the performance counter
2547 __int64 lamexp_perfcounter_value(void)
2549 LARGE_INTEGER counter;
2550 if(QueryPerformanceCounter(&counter) == TRUE)
2552 return counter.QuadPart;
2558 * Query frequency of the performance counter
2560 __int64 lamexp_perfcounter_frequ(void)
2562 LARGE_INTEGER frequency;
2563 if(QueryPerformanceFrequency(&frequency) == TRUE)
2565 return frequency.QuadPart;
2571 * Insert entry to the window's system menu
2573 bool lamexp_append_sysmenu(const QWidget *win, const unsigned int identifier, const QString &text)
2577 if(HMENU hMenu = GetSystemMenu(win->winId(), FALSE))
2579 ok = (AppendMenuW(hMenu, MF_SEPARATOR, 0, 0) == TRUE);
2580 ok = (AppendMenuW(hMenu, MF_STRING, identifier, QWCHAR(text)) == TRUE);
2587 * Insert entry to the window's system menu
2589 bool lamexp_check_sysmenu_msg(void *message, const unsigned int identifier)
2591 return (((MSG*)message)->message == WM_SYSCOMMAND) && ((((MSG*)message)->wParam & 0xFFF0) == identifier);
2595 * Update system menu entry
2597 bool lamexp_update_sysmenu(const QWidget *win, const unsigned int identifier, const QString &text)
2601 if(HMENU hMenu = ::GetSystemMenu(win->winId(), FALSE))
2603 ok = (ModifyMenu(hMenu, identifier, MF_STRING | MF_BYCOMMAND, identifier, QWCHAR(text)) == TRUE);
2609 * Display the window's close button
2611 bool lamexp_enable_close_button(const QWidget *win, const bool bEnable)
2615 if(HMENU hMenu = GetSystemMenu(win->winId(), FALSE))
2617 ok = (EnableMenuItem(hMenu, SC_CLOSE, MF_BYCOMMAND | (bEnable ? MF_ENABLED : MF_GRAYED)) == TRUE);
2624 * Check whether ESC key has been pressed since the previous call to this function
2626 bool lamexp_check_escape_state(void)
2628 return (GetAsyncKeyState(VK_ESCAPE) & 0x0001) != 0;
2632 * Set the process priority class for current process
2634 bool lamexp_change_process_priority(const int priority)
2636 return lamexp_change_process_priority(GetCurrentProcess(), priority);
2640 * Set the process priority class for specified process
2642 bool lamexp_change_process_priority(const QProcess *proc, const int priority)
2644 return lamexp_change_process_priority(proc->pid()->hProcess, priority);
2648 * Set the process priority class for specified process
2650 bool lamexp_change_process_priority(void *hProcess, const int priority)
2654 switch(qBound(-2, priority, 2))
2657 ok = (SetPriorityClass(hProcess, HIGH_PRIORITY_CLASS) == TRUE);
2660 if(!(ok = (SetPriorityClass(hProcess, ABOVE_NORMAL_PRIORITY_CLASS) == TRUE)))
2662 ok = (SetPriorityClass(hProcess, HIGH_PRIORITY_CLASS) == TRUE);
2666 ok = (SetPriorityClass(hProcess, NORMAL_PRIORITY_CLASS) == TRUE);
2669 if(!(ok = (SetPriorityClass(hProcess, BELOW_NORMAL_PRIORITY_CLASS) == TRUE)))
2671 ok = (SetPriorityClass(hProcess, IDLE_PRIORITY_CLASS) == TRUE);
2675 ok = (SetPriorityClass(hProcess, IDLE_PRIORITY_CLASS) == TRUE);
2683 * Returns the current file time
2685 unsigned __int64 lamexp_current_file_time(void)
2688 GetSystemTimeAsFileTime(&fileTime);
2690 ULARGE_INTEGER temp;
2691 temp.HighPart = fileTime.dwHighDateTime;
2692 temp.LowPart = fileTime.dwLowDateTime;
2694 return temp.QuadPart;
2698 * Bring the specifed window to the front
2700 bool lamexp_bring_to_front(const QWidget *win)
2702 const bool ret = (SetForegroundWindow(win->winId()) == TRUE);
2703 SwitchToThisWindow(win->winId(), TRUE);
2708 * Bring window of the specifed process to the front (callback)
2710 static BOOL CALLBACK lamexp_bring_process_to_front_helper(HWND hwnd, LPARAM lParam)
2712 DWORD processId = *reinterpret_cast<WORD*>(lParam);
2713 DWORD windowProcessId = NULL;
2714 GetWindowThreadProcessId(hwnd, &windowProcessId);
2715 if(windowProcessId == processId)
2717 SwitchToThisWindow(hwnd, TRUE);
2718 SetForegroundWindow(hwnd);
2726 * Bring window of the specifed process to the front
2728 bool lamexp_bring_process_to_front(const unsigned long pid)
2730 return EnumWindows(lamexp_bring_process_to_front_helper, reinterpret_cast<LPARAM>(&pid)) == TRUE;
2734 * Check the Internet connection status
2736 bool lamexp_get_connection_state(void)
2738 DWORD lpdwFlags = NULL;
2739 BOOL result = InternetGetConnectedState(&lpdwFlags, NULL);
2740 return result == TRUE;
2744 * Retrun the process ID of the given QProcess
2746 unsigned long lamexp_process_id(const QProcess *proc)
2748 PROCESS_INFORMATION *procInf = proc->pid();
2749 return (procInf) ? procInf->dwProcessId : NULL;
2753 * Convert long path to short path
2755 QString lamexp_path_to_short(const QString &longPath)
2758 DWORD buffSize = GetShortPathNameW(reinterpret_cast<const wchar_t*>(longPath.utf16()), NULL, NULL);
2762 wchar_t *buffer = new wchar_t[buffSize];
2763 DWORD result = GetShortPathNameW(reinterpret_cast<const wchar_t*>(longPath.utf16()), buffer, buffSize);
2765 if(result > 0 && result < buffSize)
2767 shortPath = QString::fromUtf16(reinterpret_cast<const unsigned short*>(buffer));
2773 return (shortPath.isEmpty() ? longPath : shortPath);
2777 * Open media file in external player
2779 bool lamexp_open_media_file(const QString &mediaFilePath)
2781 const static wchar_t *registryPrefix[2] = { L"SOFTWARE\\", L"SOFTWARE\\Wow6432Node\\" };
2782 const static wchar_t *registryKeys[3] =
2784 L"Microsoft\\Windows\\CurrentVersion\\Uninstall\\{97D341C8-B0D1-4E4A-A49A-C30B52F168E9}",
2785 L"Microsoft\\Windows\\CurrentVersion\\Uninstall\\{DB9E4EAB-2717-499F-8D56-4CC8A644AB60}",
2788 const static wchar_t *appNames[4] = { L"smplayer_portable.exe", L"smplayer.exe", L"MPUI.exe", L"foobar2000.exe" };
2789 const static wchar_t *valueNames[2] = { L"InstallLocation", L"InstallDir" };
2791 for(size_t i = 0; i < 3; i++)
2793 for(size_t j = 0; j < 2; j++)
2795 QString mplayerPath;
2796 HKEY registryKeyHandle = NULL;
2798 const QString currentKey = WCHAR2QSTR(registryPrefix[j]).append(WCHAR2QSTR(registryKeys[i]));
2799 if(RegOpenKeyExW(HKEY_LOCAL_MACHINE, QWCHAR(currentKey), 0, KEY_READ, ®istryKeyHandle) == ERROR_SUCCESS)
2801 for(size_t k = 0; k < 2; k++)
2803 wchar_t Buffer[4096];
2804 DWORD BuffSize = sizeof(wchar_t*) * 4096;
2805 DWORD DataType = REG_NONE;
2806 if(RegQueryValueExW(registryKeyHandle, valueNames[k], 0, &DataType, reinterpret_cast<BYTE*>(Buffer), &BuffSize) == ERROR_SUCCESS)
2808 if((DataType == REG_SZ) || (DataType == REG_EXPAND_SZ) || (DataType == REG_LINK))
2810 mplayerPath = WCHAR2QSTR(Buffer);
2815 RegCloseKey(registryKeyHandle);
2818 if(!mplayerPath.isEmpty())
2820 QDir mplayerDir(mplayerPath);
2821 if(mplayerDir.exists())
2823 for(size_t k = 0; k < 4; k++)
2825 if(mplayerDir.exists(WCHAR2QSTR(appNames[k])))
2827 qDebug("Player found at:\n%s\n", mplayerDir.absoluteFilePath(WCHAR2QSTR(appNames[k])).toUtf8().constData());
2828 QProcess::startDetached(mplayerDir.absoluteFilePath(WCHAR2QSTR(appNames[k])), QStringList() << QDir::toNativeSeparators(mediaFilePath));
2840 * Entry point checks
2842 static DWORD lamexp_entry_check(void);
2843 static DWORD g_lamexp_entry_check_result = lamexp_entry_check();
2844 static DWORD g_lamexp_entry_check_flag = 0x789E09B2;
2845 static DWORD lamexp_entry_check(void)
2847 volatile DWORD retVal = 0xA199B5AF;
2848 if(g_lamexp_entry_check_flag != 0x8761F64D)
2850 lamexp_fatal_exit(L"Application initialization has failed, take care!");
2856 * Application entry point (runs before static initializers)
2860 int WinMainCRTStartup(void);
2862 int lamexp_entry_point(void)
2864 if((!LAMEXP_DEBUG) && lamexp_check_for_debugger())
2866 lamexp_fatal_exit(L"Not a debug build. Please unload debugger and try again!");
2868 if(g_lamexp_entry_check_flag != 0x789E09B2)
2870 lamexp_fatal_exit(L"Application initialization has failed, take care!");
2873 //Zero *before* constructors are called
2874 LAMEXP_ZERO_MEMORY(g_lamexp_argv);
2875 LAMEXP_ZERO_MEMORY(g_lamexp_tools);
2876 LAMEXP_ZERO_MEMORY(g_lamexp_currentTranslator);
2877 LAMEXP_ZERO_MEMORY(g_lamexp_translation);
2878 LAMEXP_ZERO_MEMORY(g_lamexp_known_folder);
2879 LAMEXP_ZERO_MEMORY(g_lamexp_temp_folder);
2880 LAMEXP_ZERO_MEMORY(g_lamexp_ipc_ptr);
2881 LAMEXP_ZERO_MEMORY(g_lamexp_os_version);
2882 LAMEXP_ZERO_MEMORY(g_lamexp_themes_enabled);
2883 LAMEXP_ZERO_MEMORY(g_lamexp_portable);
2885 //Make sure we will pass the check
2886 g_lamexp_entry_check_flag = ~g_lamexp_entry_check_flag;
2888 //Now initialize the C Runtime library!
2889 return WinMainCRTStartup();
2894 * Fatal application exit
2896 #pragma intrinsic(_InterlockedExchange)
2897 void lamexp_fatal_exit(const wchar_t* exitMessage, const wchar_t* errorBoxMessage)
2899 static volatile long bFatalFlag = 0L;
2901 if(_InterlockedExchange(&bFatalFlag, 1L) == 0L)
2903 if(GetCurrentThreadId() != g_main_thread_id)
2905 HANDLE mainThread = OpenThread(THREAD_TERMINATE, FALSE, g_main_thread_id);
2906 if(mainThread) TerminateThread(mainThread, ULONG_MAX);
2911 MessageBoxW(NULL, errorBoxMessage, L"LameXP - GURU MEDITATION", MB_ICONERROR | MB_TOPMOST | MB_TASKMODAL);
2916 FatalAppExit(0, exitMessage);
2917 TerminateProcess(GetCurrentProcess(), -1);
2921 TerminateThread(GetCurrentThread(), -1);
2926 * Finalization function (final clean-up)
2928 void lamexp_finalization(void)
2930 qDebug("lamexp_finalization()");
2933 if(g_lamexp_tools.registry)
2935 QStringList keys = g_lamexp_tools.registry->keys();
2936 for(int i = 0; i < keys.count(); i++)
2938 LAMEXP_DELETE((*g_lamexp_tools.registry)[keys.at(i)]);
2940 LAMEXP_DELETE(g_lamexp_tools.registry);
2941 LAMEXP_DELETE(g_lamexp_tools.versions);
2942 LAMEXP_DELETE(g_lamexp_tools.tags);
2945 //Delete temporary files
2946 if(g_lamexp_temp_folder.path)
2948 if(!g_lamexp_temp_folder.path->isEmpty())
2950 for(int i = 0; i < 100; i++)
2952 if(lamexp_clean_folder(*g_lamexp_temp_folder.path))
2959 LAMEXP_DELETE(g_lamexp_temp_folder.path);
2962 //Clear folder cache
2963 LAMEXP_DELETE(g_lamexp_known_folder.knownFolders);
2966 if(g_lamexp_currentTranslator.instance)
2968 QApplication::removeTranslator(g_lamexp_currentTranslator.instance);
2969 LAMEXP_DELETE(g_lamexp_currentTranslator.instance);
2971 LAMEXP_DELETE(g_lamexp_translation.files);
2972 LAMEXP_DELETE(g_lamexp_translation.names);
2973 LAMEXP_DELETE(g_lamexp_translation.cntry);
2974 LAMEXP_DELETE(g_lamexp_translation.sysid);
2976 //Destroy Qt application object
2977 QApplication *application = dynamic_cast<QApplication*>(QApplication::instance());
2978 LAMEXP_DELETE(application);
2980 //Detach from shared memory
2981 if(g_lamexp_ipc_ptr.sharedmem) g_lamexp_ipc_ptr.sharedmem->detach();
2982 LAMEXP_DELETE(g_lamexp_ipc_ptr.sharedmem);
2983 LAMEXP_DELETE(g_lamexp_ipc_ptr.semaphore_read);
2984 LAMEXP_DELETE(g_lamexp_ipc_ptr.semaphore_write);
2985 LAMEXP_DELETE(g_lamexp_ipc_ptr.semaphore_read_mutex);
2986 LAMEXP_DELETE(g_lamexp_ipc_ptr.semaphore_write_mutex);
2988 //Free STDOUT and STDERR buffers
2989 if(g_lamexp_console_attached)
2991 if(std::filebuf *tmp = dynamic_cast<std::filebuf*>(std::cout.rdbuf()))
2993 std::cout.rdbuf(NULL);
2996 if(std::filebuf *tmp = dynamic_cast<std::filebuf*>(std::cerr.rdbuf()))
2998 std::cerr.rdbuf(NULL);
3004 if(g_lamexp_log_file)
3006 fclose(g_lamexp_log_file);
3007 g_lamexp_log_file = NULL;
3010 //Free CLI Arguments
3011 LAMEXP_DELETE(g_lamexp_argv.list);
3015 * Initialize debug thread
3017 static const HANDLE g_debug_thread = LAMEXP_DEBUG ? NULL : lamexp_debug_thread_init();
3020 * Get number private bytes [debug only]
3022 unsigned long lamexp_dbg_private_bytes(void)
3025 for(int i = 0; i < 8; i++) _heapmin();
3026 PROCESS_MEMORY_COUNTERS_EX memoryCounters;
3027 memoryCounters.cb = sizeof(PROCESS_MEMORY_COUNTERS_EX);
3028 GetProcessMemoryInfo(GetCurrentProcess(), (PPROCESS_MEMORY_COUNTERS) &memoryCounters, sizeof(PROCESS_MEMORY_COUNTERS_EX));
3029 return memoryCounters.PrivateUsage;
3031 throw "Cannot call this function in a non-debug build!";
3032 #endif //LAMEXP_DEBUG