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 ///////////////////////////////////////////////////////////////////////////////
25 #include <QApplication>
26 #include <QMessageBox>
32 #include <QPlastiqueStyle>
33 #include <QImageReader>
34 #include <QSharedMemory>
36 #include <QStringList>
37 #include <QSystemSemaphore>
43 #include <QTranslator>
46 #include <QLibraryInfo>
48 #include <QReadWriteLock>
49 #include <QReadLocker>
50 #include <QWriteLocker>
55 #include "LockedFile.h"
77 //Initialize static Qt plugins
79 #if QT_VERSION < QT_VERSION_CHECK(5,0,0)
83 Q_IMPORT_PLUGIN(QWindowsIntegrationPlugin)
84 Q_IMPORT_PLUGIN(QICOPlugin)
88 #define LAMEXP_ZERO_MEMORY(X) SecureZeroMemory(&X, sizeof(X))
91 #define _LAMEXP_MAKE_STR(STR) #STR
92 #define LAMEXP_MAKE_STR(STR) _LAMEXP_MAKE_STR(STR)
94 ///////////////////////////////////////////////////////////////////////////////
96 ///////////////////////////////////////////////////////////////////////////////
98 static const size_t g_lamexp_ipc_slots = 128;
102 unsigned int command;
103 unsigned int reserved_1;
104 unsigned int reserved_2;
105 char parameter[4096];
111 unsigned int pos_write;
112 unsigned int pos_read;
113 lamexp_ipc_data_t data[g_lamexp_ipc_slots];
117 ///////////////////////////////////////////////////////////////////////////////
119 ///////////////////////////////////////////////////////////////////////////////
124 unsigned int ver_major;
125 unsigned int ver_minor;
126 unsigned int ver_build;
127 char *ver_release_name;
138 static QDate g_lamexp_version_date;
139 static const char *g_lamexp_months[] = {"Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"};
140 static const char *g_lamexp_version_raw_date = __DATE__;
141 static const char *g_lamexp_version_raw_time = __TIME__;
143 //Console attached flag
144 static bool g_lamexp_console_attached = false;
147 //The following code was borrowed from MPC-HC project: http://mpc-hc.sf.net/
148 #if defined(__INTEL_COMPILER)
149 #if (__INTEL_COMPILER >= 1300)
150 static const char *g_lamexp_version_compiler = "ICL 13." LAMEXP_MAKE_STR(__INTEL_COMPILER_BUILD_DATE);
151 #elif (__INTEL_COMPILER >= 1200)
152 static const char *g_lamexp_version_compiler = "ICL 12." LAMEXP_MAKE_STR(__INTEL_COMPILER_BUILD_DATE);
153 #elif (__INTEL_COMPILER >= 1100)
154 static const char *g_lamexp_version_compiler = "ICL 11.x";
155 #elif (__INTEL_COMPILER >= 1000)
156 static const char *g_lamexp_version_compiler = "ICL 10.x";
158 #error Compiler is not supported!
160 #elif defined(_MSC_VER)
161 #if (_MSC_VER == 1700)
162 #if (_MSC_FULL_VER < 170050727)
163 static const char *g_lamexp_version_compiler = "MSVC 2012-Beta";
164 #elif (_MSC_FULL_VER < 170051020)
165 static const char *g_lamexp_version_compiler = "MSVC 2012-RTM";
166 #elif (_MSC_FULL_VER < 170051106)
167 static const char *g_lamexp_version_compiler = "MSVC 2012-U1 CTP";
168 #elif (_MSC_FULL_VER < 170060315)
169 static const char *g_lamexp_version_compiler = "MSVC 2012-U1";
170 #elif (_MSC_FULL_VER == 170060315)
171 static const char *g_lamexp_version_compiler = "MSVC 2012-U2";
173 #error Compiler version is not supported yet!
175 #elif (_MSC_VER == 1600)
176 #if (_MSC_FULL_VER < 160040219)
177 static const char *g_lamexp_version_compiler = "MSVC 2010-RTM";
178 #elif (_MSC_FULL_VER == 160040219)
179 static const char *g_lamexp_version_compiler = "MSVC 2010-SP1";
181 #error Compiler version is not supported yet!
183 #elif (_MSC_VER == 1500)
184 #if (_MSC_FULL_VER >= 150030729)
185 static const char *g_lamexp_version_compiler = "MSVC 2008-SP1";
187 static const char *g_lamexp_version_compiler = "MSVC 2008";
190 #error Compiler is not supported!
193 // Note: /arch:SSE and /arch:SSE2 are only available for the x86 platform
194 #if !defined(_M_X64) && defined(_M_IX86_FP)
195 #if (_M_IX86_FP == 1)
196 LAMEXP_COMPILER_WARNING("SSE instruction set is enabled!")
197 #elif (_M_IX86_FP == 2)
198 LAMEXP_COMPILER_WARNING("SSE2 instruction set is enabled!")
202 #error Compiler is not supported!
205 //Architecture detection
207 static const char *g_lamexp_version_arch = "x64";
208 #elif defined(_M_IX86)
209 static const char *g_lamexp_version_arch = "x86";
211 #error Architecture is not supported!
214 //Official web-site URL
215 static const char *g_lamexp_website_url = "http://lamexp.sourceforge.net/";
216 static const char *g_lamexp_support_url = "http://forum.doom9.org/showthread.php?t=157726";
217 static const char *g_lamexp_mulders_url = "http://muldersoft.com/";
219 //Tool versions (expected versions!)
220 static const unsigned int g_lamexp_toolver_neroaac = VER_LAMEXP_TOOL_NEROAAC;
221 static const unsigned int g_lamexp_toolver_fhgaacenc = VER_LAMEXP_TOOL_FHGAACENC;
222 static const unsigned int g_lamexp_toolver_qaacenc = VER_LAMEXP_TOOL_QAAC;
223 static const unsigned int g_lamexp_toolver_coreaudio = VER_LAMEXP_TOOL_COREAUDIO;
229 QMap<size_t, QString> *knownFolders;
237 QMap<QString, LockedFile*> *registry;
238 QMap<QString, unsigned int> *versions;
239 QMap<QString, QString> *tags;
247 QMap<QString, QString> *files;
248 QMap<QString, QString> *names;
249 QMap<QString, unsigned int> *sysid;
250 QMap<QString, unsigned int> *cntry;
253 g_lamexp_translation;
258 QTranslator *instance;
261 g_lamexp_currentTranslator;
275 lamexp_os_version_t version;
284 bool bPortableModeEnabled;
289 //Win32 Theme support
296 g_lamexp_themes_enabled;
302 char *semaphore_read;
303 char *semaphore_read_mutex;
304 char *semaphore_write;
305 char *semaphore_write_mutex;
309 "{21A68A42-6923-43bb-9CF6-64BF151942EE}",
310 "{7A605549-F58C-4d78-B4E5-06EFC34F405B}",
311 "{60AA8D04-F6B8-497d-81EB-0F600F4A65B5}",
312 "{726061D5-1615-4B82-871C-75FD93458E46}",
313 "{1A616023-AA6A-4519-8AF3-F7736E899977}"
317 QSharedMemory *sharedmem;
318 QSystemSemaphore *semaphore_read;
319 QSystemSemaphore *semaphore_read_mutex;
320 QSystemSemaphore *semaphore_write;
321 QSystemSemaphore *semaphore_write_mutex;
327 static const char *g_lamexp_imageformats[] = {"bmp", "png", "jpg", "gif", "ico", "xpm", NULL}; //"svg"
330 static QMutex g_lamexp_message_mutex;
333 static const DWORD g_main_thread_id = GetCurrentThreadId();
336 static FILE *g_lamexp_log_file = NULL;
339 const char* LAMEXP_DEFAULT_LANGID = "en";
340 const char* LAMEXP_DEFAULT_TRANSLATION = "LameXP_EN.qm";
342 ///////////////////////////////////////////////////////////////////////////////
344 ///////////////////////////////////////////////////////////////////////////////
349 unsigned int lamexp_version_major(void) { return g_lamexp_version.ver_major; }
350 unsigned int lamexp_version_minor(void) { return g_lamexp_version.ver_minor; }
351 unsigned int lamexp_version_build(void) { return g_lamexp_version.ver_build; }
352 const char *lamexp_version_release(void) { return g_lamexp_version.ver_release_name; }
353 const char *lamexp_version_time(void) { return g_lamexp_version_raw_time; }
354 const char *lamexp_version_compiler(void) { return g_lamexp_version_compiler; }
355 const char *lamexp_version_arch(void) { return g_lamexp_version_arch; }
356 unsigned int lamexp_toolver_neroaac(void) { return g_lamexp_toolver_neroaac; }
357 unsigned int lamexp_toolver_fhgaacenc(void) { return g_lamexp_toolver_fhgaacenc; }
358 unsigned int lamexp_toolver_qaacenc(void) { return g_lamexp_toolver_qaacenc; }
359 unsigned int lamexp_toolver_coreaudio(void) { return g_lamexp_toolver_coreaudio; }
364 const char *lamexp_website_url(void) { return g_lamexp_website_url; }
365 const char *lamexp_mulders_url(void) { return g_lamexp_mulders_url; }
366 const char *lamexp_support_url(void) { return g_lamexp_support_url; }
369 * Check for Demo (pre-release) version
371 bool lamexp_version_demo(void)
374 bool releaseVersion = false;
375 if(!strncpy_s(buffer, 128, g_lamexp_version.ver_release_name, _TRUNCATE))
377 char *context, *prefix = strtok_s(buffer, "-,; ", &context);
380 releaseVersion = (!_stricmp(prefix, "Final")) || (!_stricmp(prefix, "Hotfix"));
383 return LAMEXP_DEBUG || (!releaseVersion);
387 * Calculate expiration date
389 QDate lamexp_version_expires(void)
391 return lamexp_version_date().addDays(LAMEXP_DEBUG ? 7 : 30);
395 * Get build date date
397 const QDate &lamexp_version_date(void)
399 if(!g_lamexp_version_date.isValid())
401 int date[3] = {0, 0, 0}; char temp[12] = {'\0'};
402 strncpy_s(temp, 12, g_lamexp_version_raw_date, _TRUNCATE);
404 if(strlen(temp) == 11)
406 temp[3] = temp[6] = '\0';
407 date[2] = atoi(&temp[4]);
408 date[0] = atoi(&temp[7]);
410 for(int j = 0; j < 12; j++)
412 if(!_strcmpi(&temp[0], g_lamexp_months[j]))
419 g_lamexp_version_date = QDate(date[0], date[1], date[2]);
422 if(!g_lamexp_version_date.isValid())
424 qFatal("Internal error: Date format could not be recognized!");
428 return g_lamexp_version_date;
432 * Get the native operating system version
434 const lamexp_os_version_t *lamexp_get_os_version(void)
436 QReadLocker readLock(&g_lamexp_os_version.lock);
438 //Already initialized?
439 if(g_lamexp_os_version.bInitialized)
441 return &g_lamexp_os_version.version;
445 QWriteLocker writeLock(&g_lamexp_os_version.lock);
448 if(!g_lamexp_os_version.bInitialized)
450 OSVERSIONINFO osVerInfo;
451 memset(&osVerInfo, 0, sizeof(OSVERSIONINFO));
452 osVerInfo.dwOSVersionInfoSize = sizeof(OSVERSIONINFO);
454 if(GetVersionEx(&osVerInfo) == TRUE)
456 if(osVerInfo.dwPlatformId == VER_PLATFORM_WIN32_NT)
458 g_lamexp_os_version.version.versionMajor = osVerInfo.dwMajorVersion;
459 g_lamexp_os_version.version.versionMinor = osVerInfo.dwMinorVersion;
463 qWarning("lamexp_get_os_version: Not running under Windows NT, this is not supposed to happen!");
464 g_lamexp_os_version.version.versionMajor = 0;
465 g_lamexp_os_version.version.versionMinor = 0;
470 throw "GetVersionEx() has failed. This is not supposed to happen!";
473 g_lamexp_os_version.bInitialized = true;
476 return &g_lamexp_os_version.version;
480 * Check if we are running under wine
482 bool lamexp_detect_wine(void)
484 static bool isWine = false;
485 static bool isWine_initialized = false;
487 if(!isWine_initialized)
489 QLibrary ntdll("ntdll.dll");
492 if(ntdll.resolve("wine_nt_to_unix_file_name") != NULL) isWine = true;
493 if(ntdll.resolve("wine_get_version") != NULL) isWine = true;
496 isWine_initialized = true;
503 * Global exception handler
505 LONG WINAPI lamexp_exception_handler(__in struct _EXCEPTION_POINTERS *ExceptionInfo)
507 lamexp_fatal_exit(L"Unhandeled exception handler invoked, application will exit!");
512 * Invalid parameters handler
514 void lamexp_invalid_param_handler(const wchar_t* exp, const wchar_t* fun, const wchar_t* fil, unsigned int, uintptr_t)
516 lamexp_fatal_exit(L"Invalid parameter handler invoked, application will exit!");
520 * Change console text color
522 static void lamexp_console_color(FILE* file, WORD attributes)
524 const HANDLE hConsole = (HANDLE)(_get_osfhandle(_fileno(file)));
525 if((hConsole != NULL) && (hConsole != INVALID_HANDLE_VALUE))
527 SetConsoleTextAttribute(hConsole, attributes);
534 void lamexp_message_handler(QtMsgType type, const char *msg)
536 static const char *GURU_MEDITATION = "\n\nGURU MEDITATION !!!\n\n";
538 if(msg == NULL) return;
540 QMutexLocker lock(&g_lamexp_message_mutex);
542 if(g_lamexp_log_file)
544 static char prefix[] = "DWCF";
545 int index = qBound(0, static_cast<int>(type), 3);
546 unsigned int timestamp = static_cast<unsigned int>(_time64(NULL) % 3600I64);
547 QString str = QString::fromUtf8(msg).trimmed().replace('\n', '\t');
548 fprintf(g_lamexp_log_file, "[%c][%04u] %s\r\n", prefix[index], timestamp, str.toUtf8().constData());
549 fflush(g_lamexp_log_file);
552 if(g_lamexp_console_attached)
554 UINT oldOutputCP = GetConsoleOutputCP();
555 if(oldOutputCP != CP_UTF8) SetConsoleOutputCP(CP_UTF8);
563 lamexp_console_color(stderr, FOREGROUND_RED | FOREGROUND_INTENSITY);
564 fprintf(stderr, GURU_MEDITATION);
565 fprintf(stderr, "%s\n", msg);
569 lamexp_console_color(stderr, FOREGROUND_GREEN | FOREGROUND_RED | FOREGROUND_INTENSITY);
570 fprintf(stderr, "%s\n", msg);
574 lamexp_console_color(stderr, FOREGROUND_BLUE | FOREGROUND_GREEN | FOREGROUND_RED | FOREGROUND_INTENSITY);
575 fprintf(stderr, "%s\n", msg);
580 lamexp_console_color(stderr, FOREGROUND_BLUE | FOREGROUND_GREEN | FOREGROUND_RED);
581 if(oldOutputCP != CP_UTF8) SetConsoleOutputCP(oldOutputCP);
585 QString temp("[LameXP][%1] %2");
591 temp = temp.arg("C", QString::fromUtf8(msg));
594 temp = temp.arg("W", QString::fromUtf8(msg));
597 temp = temp.arg("I", QString::fromUtf8(msg));
601 temp.replace("\n", "\t").append("\n");
602 OutputDebugStringA(temp.toLatin1().constData());
605 if((type == QtCriticalMsg) || (type == QtFatalMsg))
608 lamexp_fatal_exit(L"The application has encountered a critical error and will exit now!", QWCHAR(QString::fromUtf8(msg)));
613 * Initialize the console
615 void lamexp_init_console(const QStringList &argv)
617 bool enableConsole = lamexp_version_demo();
621 wchar_t *logfile = NULL;
622 size_t logfile_len = 0;
623 if(!_wdupenv_s(&logfile, &logfile_len, L"LAMEXP_LOGFILE"))
625 if(logfile && (logfile_len > 0))
628 if(!_wfopen_s(&temp, logfile, L"wb"))
630 fprintf(temp, "%c%c%c", 0xEF, 0xBB, 0xBF);
631 g_lamexp_log_file = temp;
640 for(int i = 0; i < argv.count(); i++)
642 if(!argv.at(i).compare("--console", Qt::CaseInsensitive))
644 enableConsole = true;
646 else if(!argv.at(i).compare("--no-console", Qt::CaseInsensitive))
648 enableConsole = false;
655 if(!g_lamexp_console_attached)
657 if(AllocConsole() != FALSE)
659 SetConsoleCtrlHandler(NULL, TRUE);
660 SetConsoleTitle(L"LameXP - Audio Encoder Front-End | Debug Console");
661 SetConsoleOutputCP(CP_UTF8);
662 g_lamexp_console_attached = true;
666 if(g_lamexp_console_attached)
668 //-------------------------------------------------------------------
669 //See: http://support.microsoft.com/default.aspx?scid=kb;en-us;105305
670 //-------------------------------------------------------------------
671 const int flags = _O_WRONLY | _O_U8TEXT;
672 int hCrtStdOut = _open_osfhandle((intptr_t) GetStdHandle(STD_OUTPUT_HANDLE), flags);
673 int hCrtStdErr = _open_osfhandle((intptr_t) GetStdHandle(STD_ERROR_HANDLE), flags);
674 FILE *hfStdOut = (hCrtStdOut >= 0) ? _fdopen(hCrtStdOut, "wb") : NULL;
675 FILE *hfStdErr = (hCrtStdErr >= 0) ? _fdopen(hCrtStdErr, "wb") : NULL;
676 if(hfStdOut) { *stdout = *hfStdOut; std::cout.rdbuf(new std::filebuf(hfStdOut)); }
677 if(hfStdErr) { *stderr = *hfStdErr; std::cerr.rdbuf(new std::filebuf(hfStdErr)); }
680 HWND hwndConsole = GetConsoleWindow();
682 if((hwndConsole != NULL) && (hwndConsole != INVALID_HANDLE_VALUE))
684 HMENU hMenu = GetSystemMenu(hwndConsole, 0);
685 EnableMenuItem(hMenu, SC_CLOSE, MF_BYCOMMAND | MF_GRAYED);
686 RemoveMenu(hMenu, SC_CLOSE, MF_BYCOMMAND);
688 SetWindowPos(hwndConsole, HWND_TOP, 0, 0, 0, 0, SWP_NOMOVE|SWP_NOSIZE|SWP_NOZORDER|SWP_FRAMECHANGED);
689 SetWindowLong(hwndConsole, GWL_STYLE, GetWindowLong(hwndConsole, GWL_STYLE) & (~WS_MAXIMIZEBOX) & (~WS_MINIMIZEBOX));
690 SetWindowPos(hwndConsole, HWND_TOP, 0, 0, 0, 0, SWP_NOMOVE|SWP_NOSIZE|SWP_NOZORDER|SWP_FRAMECHANGED);
696 * Detect CPU features
698 lamexp_cpu_t lamexp_detect_cpu_features(const QStringList &argv)
700 typedef BOOL (WINAPI *IsWow64ProcessFun)(__in HANDLE hProcess, __out PBOOL Wow64Process);
701 typedef VOID (WINAPI *GetNativeSystemInfoFun)(__out LPSYSTEM_INFO lpSystemInfo);
703 static IsWow64ProcessFun IsWow64ProcessPtr = NULL;
704 static GetNativeSystemInfoFun GetNativeSystemInfoPtr = NULL;
706 lamexp_cpu_t features;
707 SYSTEM_INFO systemInfo;
708 int CPUInfo[4] = {-1};
709 char CPUIdentificationString[0x40];
710 char CPUBrandString[0x40];
712 memset(&features, 0, sizeof(lamexp_cpu_t));
713 memset(&systemInfo, 0, sizeof(SYSTEM_INFO));
714 memset(CPUIdentificationString, 0, sizeof(CPUIdentificationString));
715 memset(CPUBrandString, 0, sizeof(CPUBrandString));
718 memcpy(CPUIdentificationString, &CPUInfo[1], sizeof(int));
719 memcpy(CPUIdentificationString + 4, &CPUInfo[3], sizeof(int));
720 memcpy(CPUIdentificationString + 8, &CPUInfo[2], sizeof(int));
721 features.intel = (_stricmp(CPUIdentificationString, "GenuineIntel") == 0);
722 strncpy_s(features.vendor, 0x40, CPUIdentificationString, _TRUNCATE);
727 features.mmx = (CPUInfo[3] & 0x800000) || false;
728 features.sse = (CPUInfo[3] & 0x2000000) || false;
729 features.sse2 = (CPUInfo[3] & 0x4000000) || false;
730 features.ssse3 = (CPUInfo[2] & 0x200) || false;
731 features.sse3 = (CPUInfo[2] & 0x1) || false;
732 features.ssse3 = (CPUInfo[2] & 0x200) || false;
733 features.stepping = CPUInfo[0] & 0xf;
734 features.model = ((CPUInfo[0] >> 4) & 0xf) + (((CPUInfo[0] >> 16) & 0xf) << 4);
735 features.family = ((CPUInfo[0] >> 8) & 0xf) + ((CPUInfo[0] >> 20) & 0xff);
738 __cpuid(CPUInfo, 0x80000000);
739 int nExIds = qMax<int>(qMin<int>(CPUInfo[0], 0x80000004), 0x80000000);
741 for(int i = 0x80000002; i <= nExIds; ++i)
747 memcpy(CPUBrandString, CPUInfo, sizeof(CPUInfo));
750 memcpy(CPUBrandString + 16, CPUInfo, sizeof(CPUInfo));
753 memcpy(CPUBrandString + 32, CPUInfo, sizeof(CPUInfo));
758 strncpy_s(features.brand, 0x40, CPUBrandString, _TRUNCATE);
760 if(strlen(features.brand) < 1) strncpy_s(features.brand, 0x40, "Unknown", _TRUNCATE);
761 if(strlen(features.vendor) < 1) strncpy_s(features.vendor, 0x40, "Unknown", _TRUNCATE);
763 #if !defined(_M_X64 ) && !defined(_M_IA64)
764 if(!IsWow64ProcessPtr || !GetNativeSystemInfoPtr)
766 QLibrary Kernel32Lib("kernel32.dll");
767 IsWow64ProcessPtr = (IsWow64ProcessFun) Kernel32Lib.resolve("IsWow64Process");
768 GetNativeSystemInfoPtr = (GetNativeSystemInfoFun) Kernel32Lib.resolve("GetNativeSystemInfo");
770 if(IsWow64ProcessPtr)
773 if(IsWow64ProcessPtr(GetCurrentProcess(), &x64))
778 if(GetNativeSystemInfoPtr)
780 GetNativeSystemInfoPtr(&systemInfo);
784 GetSystemInfo(&systemInfo);
786 features.count = qBound(1UL, systemInfo.dwNumberOfProcessors, 64UL);
788 GetNativeSystemInfo(&systemInfo);
789 features.count = systemInfo.dwNumberOfProcessors;
796 for(int i = 0; i < argv.count(); i++)
798 if(!argv[i].compare("--force-cpu-no-64bit", Qt::CaseInsensitive)) { flag = true; features.x64 = false; }
799 if(!argv[i].compare("--force-cpu-no-sse", Qt::CaseInsensitive)) { flag = true; features.sse = features.sse2 = features.sse3 = features.ssse3 = false; }
800 if(!argv[i].compare("--force-cpu-no-intel", Qt::CaseInsensitive)) { flag = true; features.intel = false; }
802 if(flag) qWarning("CPU flags overwritten by user-defined parameters. Take care!\n");
809 * Check for debugger (detect routine)
811 static __forceinline bool lamexp_check_for_debugger(void)
813 if(IsDebuggerPresent())
820 CloseHandle((HANDLE) 0x7FFFFFFF);
822 __except(EXCEPTION_EXECUTE_HANDLER)
831 __except(EXCEPTION_EXECUTE_HANDLER)
840 * Check for debugger (thread proc)
842 static unsigned int __stdcall lamexp_debug_thread_proc(LPVOID lpParameter)
844 while(!lamexp_check_for_debugger())
848 lamexp_fatal_exit(L"Not a debug build. Please unload debugger and try again!");
853 * Check for debugger (startup routine)
855 static HANDLE lamexp_debug_thread_init(void)
857 if(lamexp_check_for_debugger())
859 lamexp_fatal_exit(L"Not a debug build. Please unload debugger and try again!");
862 return (HANDLE) _beginthreadex(NULL, 0, lamexp_debug_thread_proc, NULL, 0, NULL);
866 * Check for compatibility mode
868 static bool lamexp_check_compatibility_mode(const char *exportName, const QString &executableName)
870 QLibrary kernel32("kernel32.dll");
872 if((exportName != NULL) && kernel32.load())
874 if(kernel32.resolve(exportName) != NULL)
876 qWarning("Function '%s' exported from 'kernel32.dll' -> Windows compatibility mode!", exportName);
877 qFatal("%s", QApplication::tr("Executable '%1' doesn't support Windows compatibility mode.").arg(executableName).toLatin1().constData());
886 * Computus according to H. Lichtenberg
888 static bool lamexp_computus(const QDate &date)
893 int M = 15 + (3*K + 3) / 4 - (8*K + 13) / 25;
894 int D = (19*A + M) % 30;
895 int S = 2 - (3*K + 3) / 4;
896 int R = D / 29 + (D / 28 - D / 29) * (A / 11);
898 int SZ = 7 - (X + X / 4 + S) % 7;
899 int OE = 7 - (OG - SZ) % 7;
904 return (date.month() == 4) && (date.day() == (OS - 31));
908 return (date.month() == 3) && (date.day() == OS);
913 * Check for Thanksgiving
915 static bool lamexp_thanksgiving(const QDate &date)
919 switch(QDate(date.year(), 11, 1).dayOfWeek())
921 case 1: day = 25; break;
922 case 2: day = 24; break;
923 case 3: day = 23; break;
924 case 4: day = 22; break;
925 case 5: day = 28; break;
926 case 6: day = 27; break;
927 case 7: day = 26; break;
930 return (date.month() == 11) && (date.day() == day);
934 * Initialize app icon
936 QIcon lamexp_app_icon(const QDate *date, const QTime *time)
938 QDate currentDate = (date) ? QDate(*date) : QDate::currentDate();
939 QTime currentTime = (time) ? QTime(*time) : QTime::currentTime();
941 if(lamexp_thanksgiving(currentDate))
943 return QIcon(":/MainIcon6.png");
945 else if(((currentDate.month() == 12) && (currentDate.day() == 31) && (currentTime.hour() >= 20)) || ((currentDate.month() == 1) && (currentDate.day() == 1) && (currentTime.hour() <= 19)))
947 return QIcon(":/MainIcon5.png");
949 else if(((currentDate.month() == 10) && (currentDate.day() == 31) && (currentTime.hour() >= 12)) || ((currentDate.month() == 11) && (currentDate.day() == 1) && (currentTime.hour() <= 11)))
951 return QIcon(":/MainIcon4.png");
953 else if((currentDate.month() == 12) && (currentDate.day() >= 24) && (currentDate.day() <= 26))
955 return QIcon(":/MainIcon3.png");
957 else if(lamexp_computus(currentDate))
959 return QIcon(":/MainIcon2.png");
963 return QIcon(":/MainIcon1.png");
968 * Broadcast event to all windows
970 static bool lamexp_broadcast(int eventType, bool onlyToVisible)
972 if(QApplication *app = dynamic_cast<QApplication*>(QApplication::instance()))
974 qDebug("Broadcasting %d", eventType);
977 QEvent poEvent(static_cast<QEvent::Type>(eventType));
978 QWidgetList list = app->topLevelWidgets();
980 while(!list.isEmpty())
982 QWidget *widget = list.takeFirst();
983 if(!onlyToVisible || widget->isVisible())
985 if(!app->sendEvent(widget, &poEvent))
992 qDebug("Broadcast %d done (%s)", eventType, (allOk ? "OK" : "Stopped"));
997 qWarning("Broadcast failed, could not get QApplication instance!");
1005 static bool lamexp_event_filter(void *message, long *result)
1007 if((!(LAMEXP_DEBUG)) && lamexp_check_for_debugger())
1009 lamexp_fatal_exit(L"Not a debug build. Please unload debugger and try again!");
1012 switch(reinterpret_cast<MSG*>(message)->message)
1014 case WM_QUERYENDSESSION:
1015 qWarning("WM_QUERYENDSESSION message received!");
1016 *result = lamexp_broadcast(lamexp_event_queryendsession, false) ? TRUE : FALSE;
1019 qWarning("WM_ENDSESSION message received!");
1020 if(reinterpret_cast<MSG*>(message)->wParam == TRUE)
1022 lamexp_broadcast(lamexp_event_endsession, false);
1023 if(QApplication *app = reinterpret_cast<QApplication*>(QApplication::instance()))
1025 app->closeAllWindows();
1028 lamexp_finalization();
1034 /*ignore this message and let Qt handle it*/
1040 * Check for process elevation
1042 static bool lamexp_check_elevation(void)
1044 typedef enum { lamexp_token_elevationType_class = 18, lamexp_token_elevation_class = 20 } LAMEXP_TOKEN_INFORMATION_CLASS;
1045 typedef enum { lamexp_elevationType_default = 1, lamexp_elevationType_full, lamexp_elevationType_limited } LAMEXP_TOKEN_ELEVATION_TYPE;
1047 HANDLE hToken = NULL;
1048 bool bIsProcessElevated = false;
1050 if(OpenProcessToken(GetCurrentProcess(), TOKEN_QUERY, &hToken))
1052 LAMEXP_TOKEN_ELEVATION_TYPE tokenElevationType;
1054 if(GetTokenInformation(hToken, (TOKEN_INFORMATION_CLASS) lamexp_token_elevationType_class, &tokenElevationType, sizeof(LAMEXP_TOKEN_ELEVATION_TYPE), &returnLength))
1056 if(returnLength == sizeof(LAMEXP_TOKEN_ELEVATION_TYPE))
1058 switch(tokenElevationType)
1060 case lamexp_elevationType_default:
1061 qDebug("Process token elevation type: Default -> UAC is disabled.\n");
1063 case lamexp_elevationType_full:
1064 qWarning("Process token elevation type: Full -> potential security risk!\n");
1065 bIsProcessElevated = true;
1067 case lamexp_elevationType_limited:
1068 qDebug("Process token elevation type: Limited -> not elevated.\n");
1073 CloseHandle(hToken);
1077 qWarning("Failed to open process token!");
1080 return !bIsProcessElevated;
1084 * Initialize Qt framework
1086 bool lamexp_init_qt(int argc, char* argv[])
1088 static bool qt_initialized = false;
1089 typedef BOOL (WINAPI *SetDllDirectoryProc)(WCHAR *lpPathName);
1090 const QStringList &arguments = lamexp_arguments();
1092 //Don't initialized again, if done already
1098 //Secure DLL loading
1099 QLibrary kernel32("kernel32.dll");
1102 SetDllDirectoryProc pSetDllDirectory = (SetDllDirectoryProc) kernel32.resolve("SetDllDirectoryW");
1103 if(pSetDllDirectory != NULL) pSetDllDirectory(L"");
1107 //Extract executable name from argv[] array
1108 QString executableName = QLatin1String("LameXP.exe");
1109 if(arguments.count() > 0)
1111 static const char *delimiters = "\\/:?";
1112 executableName = arguments[0].trimmed();
1113 for(int i = 0; delimiters[i]; i++)
1115 int temp = executableName.lastIndexOf(QChar(delimiters[i]));
1116 if(temp >= 0) executableName = executableName.mid(temp + 1);
1118 executableName = executableName.trimmed();
1119 if(executableName.isEmpty())
1121 executableName = QLatin1String("LameXP.exe");
1127 qDebug("Using Qt v%s [%s], %s, %s", qVersion(), QLibraryInfo::buildDate().toString(Qt::ISODate).toLatin1().constData(), (qSharedBuild() ? "DLL" : "Static"), QLibraryInfo::buildKey().toLatin1().constData());
1128 qDebug("Compiled with Qt v%s [%s], %s\n", QT_VERSION_STR, QT_PACKAGEDATE_STR, QT_BUILD_KEY);
1129 if(_stricmp(qVersion(), QT_VERSION_STR))
1131 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());
1134 if(QLibraryInfo::buildKey().compare(QString::fromLatin1(QT_BUILD_KEY), Qt::CaseInsensitive))
1136 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());
1140 qDebug("Using Qt v%s [%s], %s", qVersion(), QLibraryInfo::buildDate().toString(Qt::ISODate).toLatin1().constData(), (qSharedBuild() ? "DLL" : "Static"));
1141 qDebug("Compiled with Qt v%s [%s]\n", QT_VERSION_STR, QT_PACKAGEDATE_STR);
1144 //Check the Windows version
1145 switch(QSysInfo::windowsVersion() & QSysInfo::WV_NT_based)
1148 case QSysInfo::WV_NT:
1149 qFatal("%s", QApplication::tr("Executable '%1' requires Windows 2000 or later.").arg(executableName).toLatin1().constData());
1151 case QSysInfo::WV_2000:
1152 qDebug("Running on Windows 2000 (not officially supported!).\n");
1153 lamexp_check_compatibility_mode("GetNativeSystemInfo", executableName);
1155 case QSysInfo::WV_XP:
1156 qDebug("Running on Windows XP.\n");
1157 lamexp_check_compatibility_mode("GetLargePageMinimum", executableName);
1159 case QSysInfo::WV_2003:
1160 qDebug("Running on Windows Server 2003 or Windows XP x64-Edition.\n");
1161 lamexp_check_compatibility_mode("GetLocaleInfoEx", executableName);
1163 case QSysInfo::WV_VISTA:
1164 qDebug("Running on Windows Vista or Windows Server 2008.\n");
1165 lamexp_check_compatibility_mode("CreateRemoteThreadEx", executableName);
1167 case QSysInfo::WV_WINDOWS7:
1168 qDebug("Running on Windows 7 or Windows Server 2008 R2.\n");
1169 lamexp_check_compatibility_mode("CreateFile2", executableName);
1173 const lamexp_os_version_t *osVersionNo = lamexp_get_os_version();
1174 if(osVersionNo->versionMajor < 5)
1176 qFatal("%s", QApplication::tr("Executable '%1' requires Windows 2000 or later.").arg(executableName).toLatin1().constData());
1178 else if(LAMEXP_EQL_OS_VER(osVersionNo, 6, 2))
1180 qDebug("Running on Windows 8 or Windows Server 2012\n");
1181 lamexp_check_compatibility_mode(NULL, executableName);
1185 qWarning("Running on an unknown/untested WinNT-based OS (v%u.%u).\n", osVersionNo->versionMajor, osVersionNo->versionMinor);
1192 if(lamexp_detect_wine())
1194 qWarning("It appears we are running under Wine, unexpected things might happen!\n");
1197 //Set text Codec for locale
1198 QTextCodec::setCodecForLocale(QTextCodec::codecForName("UTF-8"));
1200 //Create Qt application instance
1201 QApplication *application = new QApplication(argc, argv);
1203 //Load plugins from application directory
1204 QCoreApplication::setLibraryPaths(QStringList() << QApplication::applicationDirPath());
1205 qDebug("Library Path:\n%s\n", QApplication::libraryPaths().first().toUtf8().constData());
1207 //Set application properties
1208 application->setApplicationName("LameXP - Audio Encoder Front-End");
1209 application->setApplicationVersion(QString().sprintf("%d.%02d.%04d", lamexp_version_major(), lamexp_version_minor(), lamexp_version_build()));
1210 application->setOrganizationName("LoRd_MuldeR");
1211 application->setOrganizationDomain("mulder.at.gg");
1212 application->setWindowIcon(lamexp_app_icon());
1213 application->setEventFilter(lamexp_event_filter);
1215 //Check for supported image formats
1216 QList<QByteArray> supportedFormats = QImageReader::supportedImageFormats();
1217 for(int i = 0; g_lamexp_imageformats[i]; i++)
1219 if(!supportedFormats.contains(g_lamexp_imageformats[i]))
1221 qFatal("Qt initialization error: QImageIOHandler for '%s' missing!", g_lamexp_imageformats[i]);
1226 //Add default translations
1227 QWriteLocker writeLockTranslations(&g_lamexp_translation.lock);
1228 if(!g_lamexp_translation.files) g_lamexp_translation.files = new QMap<QString, QString>();
1229 if(!g_lamexp_translation.names) g_lamexp_translation.names = new QMap<QString, QString>();
1230 g_lamexp_translation.files->insert(LAMEXP_DEFAULT_LANGID, "");
1231 g_lamexp_translation.names->insert(LAMEXP_DEFAULT_LANGID, "English");
1232 writeLockTranslations.unlock();
1234 //Check for process elevation
1235 if((!lamexp_check_elevation()) && (!lamexp_detect_wine()))
1237 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);
1238 messageBox.addButton("Quit Program (Recommended)", QMessageBox::NoRole);
1239 messageBox.addButton("Ignore", QMessageBox::NoRole);
1240 if(messageBox.exec() == 0)
1246 //Update console icon, if a console is attached
1247 #if QT_VERSION < QT_VERSION_CHECK(5,0,0)
1248 if(g_lamexp_console_attached && (!lamexp_detect_wine()))
1250 typedef DWORD (__stdcall *SetConsoleIconFun)(HICON);
1251 QLibrary kernel32("kernel32.dll");
1254 SetConsoleIconFun SetConsoleIconPtr = (SetConsoleIconFun) kernel32.resolve("SetConsoleIcon");
1255 if(SetConsoleIconPtr != NULL) SetConsoleIconPtr(QIcon(":/icons/sound.png").pixmap(16, 16).toWinHICON());
1262 qt_initialized = true;
1269 int lamexp_init_ipc(void)
1271 QWriteLocker writeLock(&g_lamexp_ipc_ptr.lock);
1273 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)
1278 g_lamexp_ipc_ptr.semaphore_read = new QSystemSemaphore(QString(g_lamexp_ipc_uuid.semaphore_read), 0);
1279 g_lamexp_ipc_ptr.semaphore_write = new QSystemSemaphore(QString(g_lamexp_ipc_uuid.semaphore_write), 0);
1280 g_lamexp_ipc_ptr.semaphore_read_mutex = new QSystemSemaphore(QString(g_lamexp_ipc_uuid.semaphore_read_mutex), 0);
1281 g_lamexp_ipc_ptr.semaphore_write_mutex = new QSystemSemaphore(QString(g_lamexp_ipc_uuid.semaphore_write_mutex), 0);
1283 if(g_lamexp_ipc_ptr.semaphore_read->error() != QSystemSemaphore::NoError)
1285 QString errorMessage = g_lamexp_ipc_ptr.semaphore_read->errorString();
1286 LAMEXP_DELETE(g_lamexp_ipc_ptr.semaphore_read);
1287 LAMEXP_DELETE(g_lamexp_ipc_ptr.semaphore_write);
1288 LAMEXP_DELETE(g_lamexp_ipc_ptr.semaphore_read_mutex);
1289 LAMEXP_DELETE(g_lamexp_ipc_ptr.semaphore_write_mutex);
1290 qFatal("Failed to create system smaphore: %s", errorMessage.toUtf8().constData());
1293 if(g_lamexp_ipc_ptr.semaphore_write->error() != QSystemSemaphore::NoError)
1295 QString errorMessage = g_lamexp_ipc_ptr.semaphore_write->errorString();
1296 LAMEXP_DELETE(g_lamexp_ipc_ptr.semaphore_read);
1297 LAMEXP_DELETE(g_lamexp_ipc_ptr.semaphore_write);
1298 LAMEXP_DELETE(g_lamexp_ipc_ptr.semaphore_read_mutex);
1299 LAMEXP_DELETE(g_lamexp_ipc_ptr.semaphore_write_mutex);
1300 qFatal("Failed to create system smaphore: %s", errorMessage.toUtf8().constData());
1303 if(g_lamexp_ipc_ptr.semaphore_read_mutex->error() != QSystemSemaphore::NoError)
1305 QString errorMessage = g_lamexp_ipc_ptr.semaphore_read_mutex->errorString();
1306 LAMEXP_DELETE(g_lamexp_ipc_ptr.semaphore_read);
1307 LAMEXP_DELETE(g_lamexp_ipc_ptr.semaphore_write);
1308 LAMEXP_DELETE(g_lamexp_ipc_ptr.semaphore_read_mutex);
1309 LAMEXP_DELETE(g_lamexp_ipc_ptr.semaphore_write_mutex);
1310 qFatal("Failed to create system smaphore: %s", errorMessage.toUtf8().constData());
1313 if(g_lamexp_ipc_ptr.semaphore_write_mutex->error() != QSystemSemaphore::NoError)
1315 QString errorMessage = g_lamexp_ipc_ptr.semaphore_write_mutex->errorString();
1316 LAMEXP_DELETE(g_lamexp_ipc_ptr.semaphore_read);
1317 LAMEXP_DELETE(g_lamexp_ipc_ptr.semaphore_write);
1318 LAMEXP_DELETE(g_lamexp_ipc_ptr.semaphore_read_mutex);
1319 LAMEXP_DELETE(g_lamexp_ipc_ptr.semaphore_write_mutex);
1320 qFatal("Failed to create system smaphore: %s", errorMessage.toUtf8().constData());
1324 g_lamexp_ipc_ptr.sharedmem = new QSharedMemory(QString(g_lamexp_ipc_uuid.sharedmem), NULL);
1326 if(!g_lamexp_ipc_ptr.sharedmem->create(sizeof(lamexp_ipc_t)))
1328 if(g_lamexp_ipc_ptr.sharedmem->error() == QSharedMemory::AlreadyExists)
1330 g_lamexp_ipc_ptr.sharedmem->attach();
1331 if(g_lamexp_ipc_ptr.sharedmem->error() == QSharedMemory::NoError)
1337 QString errorMessage = g_lamexp_ipc_ptr.sharedmem->errorString();
1338 LAMEXP_DELETE(g_lamexp_ipc_ptr.sharedmem);
1339 qFatal("Failed to attach to shared memory: %s", errorMessage.toUtf8().constData());
1345 QString errorMessage = g_lamexp_ipc_ptr.sharedmem->errorString();
1346 LAMEXP_DELETE(g_lamexp_ipc_ptr.sharedmem);
1347 qFatal("Failed to create shared memory: %s", errorMessage.toUtf8().constData());
1352 memset(g_lamexp_ipc_ptr.sharedmem->data(), 0, sizeof(lamexp_ipc_t));
1353 g_lamexp_ipc_ptr.semaphore_write->release(g_lamexp_ipc_slots);
1354 g_lamexp_ipc_ptr.semaphore_read_mutex->release();
1355 g_lamexp_ipc_ptr.semaphore_write_mutex->release();
1363 void lamexp_ipc_send(unsigned int command, const char* message)
1365 QReadLocker readLock(&g_lamexp_ipc_ptr.lock);
1367 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)
1369 throw "Shared memory for IPC not initialized yet.";
1372 lamexp_ipc_data_t ipc_data;
1373 memset(&ipc_data, 0, sizeof(lamexp_ipc_data_t));
1374 ipc_data.command = command;
1378 strncpy_s(ipc_data.parameter, 4096, message, _TRUNCATE);
1381 if(g_lamexp_ipc_ptr.semaphore_write->acquire())
1383 if(g_lamexp_ipc_ptr.semaphore_write_mutex->acquire())
1385 lamexp_ipc_t *ptr = reinterpret_cast<lamexp_ipc_t*>(g_lamexp_ipc_ptr.sharedmem->data());
1386 memcpy(&ptr->data[ptr->pos_write], &ipc_data, sizeof(lamexp_ipc_data_t));
1387 ptr->pos_write = (ptr->pos_write + 1) % g_lamexp_ipc_slots;
1388 g_lamexp_ipc_ptr.semaphore_read->release();
1389 g_lamexp_ipc_ptr.semaphore_write_mutex->release();
1397 void lamexp_ipc_read(unsigned int *command, char* message, size_t buffSize)
1399 QReadLocker readLock(&g_lamexp_ipc_ptr.lock);
1404 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)
1406 throw "Shared memory for IPC not initialized yet.";
1409 lamexp_ipc_data_t ipc_data;
1410 memset(&ipc_data, 0, sizeof(lamexp_ipc_data_t));
1412 if(g_lamexp_ipc_ptr.semaphore_read->acquire())
1414 if(g_lamexp_ipc_ptr.semaphore_read_mutex->acquire())
1416 lamexp_ipc_t *ptr = reinterpret_cast<lamexp_ipc_t*>(g_lamexp_ipc_ptr.sharedmem->data());
1417 memcpy(&ipc_data, &ptr->data[ptr->pos_read], sizeof(lamexp_ipc_data_t));
1418 ptr->pos_read = (ptr->pos_read + 1) % g_lamexp_ipc_slots;
1419 g_lamexp_ipc_ptr.semaphore_write->release();
1420 g_lamexp_ipc_ptr.semaphore_read_mutex->release();
1422 if(!(ipc_data.reserved_1 || ipc_data.reserved_2))
1424 *command = ipc_data.command;
1425 strncpy_s(message, buffSize, ipc_data.parameter, _TRUNCATE);
1429 qWarning("Malformed IPC message, will be ignored");
1436 * Check for LameXP "portable" mode
1438 bool lamexp_portable_mode(void)
1440 QReadLocker readLock(&g_lamexp_portable.lock);
1442 if(g_lamexp_portable.bInitialized)
1444 return g_lamexp_portable.bPortableModeEnabled;
1448 QWriteLocker writeLock(&g_lamexp_portable.lock);
1450 if(!g_lamexp_portable.bInitialized)
1452 if(VER_LAMEXP_PORTABLE_EDITION)
1454 qWarning("LameXP portable edition!\n");
1455 g_lamexp_portable.bPortableModeEnabled = true;
1459 QString baseName = QFileInfo(QApplication::applicationFilePath()).completeBaseName();
1460 int idx1 = baseName.indexOf("lamexp", 0, Qt::CaseInsensitive);
1461 int idx2 = baseName.lastIndexOf("portable", -1, Qt::CaseInsensitive);
1462 g_lamexp_portable.bPortableModeEnabled = (idx1 >= 0) && (idx2 >= 0) && (idx1 < idx2);
1464 g_lamexp_portable.bInitialized = true;
1467 return g_lamexp_portable.bPortableModeEnabled;
1471 * Get a random string
1473 QString lamexp_rand_str(void)
1475 QRegExp regExp("\\{(\\w+)-(\\w+)-(\\w+)-(\\w+)-(\\w+)\\}");
1476 QString uuid = QUuid::createUuid().toString();
1478 if(regExp.indexIn(uuid) >= 0)
1480 return QString().append(regExp.cap(1)).append(regExp.cap(2)).append(regExp.cap(3)).append(regExp.cap(4)).append(regExp.cap(5));
1483 throw "The RegExp didn't match on the UUID string. This shouldn't happen ;-)";
1487 * Get LameXP temp folder
1489 const QString &lamexp_temp_folder2(void)
1491 QReadLocker readLock(&g_lamexp_folder.lock);
1493 //Already initialized?
1494 if(g_lamexp_folder.temp)
1496 if(!g_lamexp_folder.temp->isEmpty())
1498 if(QDir(*g_lamexp_folder.temp).exists())
1500 return *g_lamexp_folder.temp;
1506 QWriteLocker writeLock(&g_lamexp_folder.lock);
1508 if(!g_lamexp_folder.temp)
1510 g_lamexp_folder.temp = new QString();
1513 g_lamexp_folder.temp->clear();
1515 static const char *TEMP_STR = "Temp";
1516 const QString WRITE_TEST_DATA = lamexp_rand_str();
1517 const QString SUB_FOLDER = lamexp_rand_str();
1519 //Try the %TMP% or %TEMP% directory first
1520 QDir temp = QDir::temp();
1523 temp.mkdir(SUB_FOLDER);
1524 if(temp.cd(SUB_FOLDER) && temp.exists())
1526 QFile testFile(QString("%1/~%2.tmp").arg(temp.canonicalPath(), lamexp_rand_str()));
1527 if(testFile.open(QIODevice::ReadWrite))
1529 if(testFile.write(WRITE_TEST_DATA.toLatin1().constData()) >= strlen(WRITE_TEST_DATA.toLatin1().constData()))
1531 (*g_lamexp_folder.temp) = temp.canonicalPath();
1536 if(!g_lamexp_folder.temp->isEmpty())
1538 return *g_lamexp_folder.temp;
1542 //Create TEMP folder in %LOCALAPPDATA%
1543 QDir localAppData = QDir(lamexp_known_folder(lamexp_folder_localappdata));
1544 if(!localAppData.path().isEmpty())
1546 if(!localAppData.exists())
1548 localAppData.mkpath(".");
1550 if(localAppData.exists())
1552 if(!localAppData.entryList(QDir::AllDirs).contains(TEMP_STR, Qt::CaseInsensitive))
1554 localAppData.mkdir(TEMP_STR);
1556 if(localAppData.cd(TEMP_STR) && localAppData.exists())
1558 localAppData.mkdir(SUB_FOLDER);
1559 if(localAppData.cd(SUB_FOLDER) && localAppData.exists())
1561 QFile testFile(QString("%1/~%2.tmp").arg(localAppData.canonicalPath(), lamexp_rand_str()));
1562 if(testFile.open(QIODevice::ReadWrite))
1564 if(testFile.write(WRITE_TEST_DATA.toLatin1().constData()) >= strlen(WRITE_TEST_DATA.toLatin1().constData()))
1566 (*g_lamexp_folder.temp) = localAppData.canonicalPath();
1573 if(!g_lamexp_folder.temp->isEmpty())
1575 return *g_lamexp_folder.temp;
1579 //Failed to create TEMP folder!
1580 qFatal("Temporary directory could not be initialized!\n\nFirst attempt:\n%s\n\nSecond attempt:\n%s", temp.canonicalPath().toUtf8().constData(), localAppData.canonicalPath().toUtf8().constData());
1581 return *g_lamexp_folder.temp;
1587 bool lamexp_clean_folder(const QString &folderPath)
1589 QDir tempFolder(folderPath);
1590 QFileInfoList entryList = tempFolder.entryInfoList(QDir::AllEntries | QDir::NoDotAndDotDot);
1592 for(int i = 0; i < entryList.count(); i++)
1594 if(entryList.at(i).isDir())
1596 lamexp_clean_folder(entryList.at(i).canonicalFilePath());
1600 for(int j = 0; j < 3; j++)
1602 if(lamexp_remove_file(entryList.at(i).canonicalFilePath()))
1610 tempFolder.rmdir(".");
1611 return !tempFolder.exists();
1617 void lamexp_register_tool(const QString &toolName, LockedFile *file, unsigned int version, const QString *tag)
1619 QWriteLocker writeLock(&g_lamexp_tools.lock);
1621 if(!g_lamexp_tools.registry) g_lamexp_tools.registry = new QMap<QString, LockedFile*>();
1622 if(!g_lamexp_tools.versions) g_lamexp_tools.versions = new QMap<QString, unsigned int>();
1623 if(!g_lamexp_tools.tags) g_lamexp_tools.tags = new QMap<QString, QString>();
1625 if(g_lamexp_tools.registry->contains(toolName.toLower()))
1627 throw "lamexp_register_tool: Tool is already registered!";
1630 g_lamexp_tools.registry->insert(toolName.toLower(), file);
1631 g_lamexp_tools.versions->insert(toolName.toLower(), version);
1632 g_lamexp_tools.tags->insert(toolName.toLower(), (tag) ? (*tag) : QString());
1638 bool lamexp_check_tool(const QString &toolName)
1640 QReadLocker readLock(&g_lamexp_tools.lock);
1641 return (g_lamexp_tools.registry) ? g_lamexp_tools.registry->contains(toolName.toLower()) : false;
1647 const QString lamexp_lookup_tool(const QString &toolName)
1649 QReadLocker readLock(&g_lamexp_tools.lock);
1651 if(g_lamexp_tools.registry)
1653 if(g_lamexp_tools.registry->contains(toolName.toLower()))
1655 return g_lamexp_tools.registry->value(toolName.toLower())->filePath();
1669 * Lookup tool version
1671 unsigned int lamexp_tool_version(const QString &toolName, QString *tag)
1673 QReadLocker readLock(&g_lamexp_tools.lock);
1674 if(tag) tag->clear();
1676 if(g_lamexp_tools.versions)
1678 if(g_lamexp_tools.versions->contains(toolName.toLower()))
1682 if(g_lamexp_tools.tags->contains(toolName.toLower())) *tag = g_lamexp_tools.tags->value(toolName.toLower());
1684 return g_lamexp_tools.versions->value(toolName.toLower());
1698 * Version number to human-readable string
1700 const QString lamexp_version2string(const QString &pattern, unsigned int version, const QString &defaultText, const QString *tag)
1702 if(version == UINT_MAX)
1707 QString result = pattern;
1708 int digits = result.count("?", Qt::CaseInsensitive);
1716 QString versionStr = QString().sprintf(QString().sprintf("%%0%du", digits).toLatin1().constData(), version);
1717 int index = result.indexOf("?", Qt::CaseInsensitive);
1719 while(index >= 0 && pos < versionStr.length())
1721 result[index] = versionStr[pos++];
1722 index = result.indexOf("?", Qt::CaseInsensitive);
1727 result.replace(QChar('#'), *tag, Qt::CaseInsensitive);
1734 * Register a new translation
1736 bool lamexp_translation_register(const QString &langId, const QString &qmFile, const QString &langName, unsigned int &systemId, unsigned int &country)
1738 QWriteLocker writeLockTranslations(&g_lamexp_translation.lock);
1740 if(qmFile.isEmpty() || langName.isEmpty() || systemId < 1)
1745 if(!g_lamexp_translation.files) g_lamexp_translation.files = new QMap<QString, QString>();
1746 if(!g_lamexp_translation.names) g_lamexp_translation.names = new QMap<QString, QString>();
1747 if(!g_lamexp_translation.sysid) g_lamexp_translation.sysid = new QMap<QString, unsigned int>();
1748 if(!g_lamexp_translation.cntry) g_lamexp_translation.cntry = new QMap<QString, unsigned int>();
1750 g_lamexp_translation.files->insert(langId, qmFile);
1751 g_lamexp_translation.names->insert(langId, langName);
1752 g_lamexp_translation.sysid->insert(langId, systemId);
1753 g_lamexp_translation.cntry->insert(langId, country);
1759 * Get list of all translations
1761 QStringList lamexp_query_translations(void)
1763 QReadLocker readLockTranslations(&g_lamexp_translation.lock);
1764 return (g_lamexp_translation.files) ? g_lamexp_translation.files->keys() : QStringList();
1768 * Get translation name
1770 QString lamexp_translation_name(const QString &langId)
1772 QReadLocker readLockTranslations(&g_lamexp_translation.lock);
1773 return (g_lamexp_translation.names) ? g_lamexp_translation.names->value(langId.toLower(), QString()) : QString();
1777 * Get translation system id
1779 unsigned int lamexp_translation_sysid(const QString &langId)
1781 QReadLocker readLockTranslations(&g_lamexp_translation.lock);
1782 return (g_lamexp_translation.sysid) ? g_lamexp_translation.sysid->value(langId.toLower(), 0) : 0;
1786 * Get translation script id
1788 unsigned int lamexp_translation_country(const QString &langId)
1790 QReadLocker readLockTranslations(&g_lamexp_translation.lock);
1791 return (g_lamexp_translation.cntry) ? g_lamexp_translation.cntry->value(langId.toLower(), 0) : 0;
1795 * Install a new translator
1797 bool lamexp_install_translator(const QString &langId)
1799 bool success = false;
1800 const QString qmFileToPath(":/localization/%1");
1802 if(langId.isEmpty() || langId.toLower().compare(LAMEXP_DEFAULT_LANGID) == 0)
1804 success = lamexp_install_translator_from_file(qmFileToPath.arg(LAMEXP_DEFAULT_TRANSLATION));
1808 QReadLocker readLock(&g_lamexp_translation.lock);
1809 QString qmFile = (g_lamexp_translation.files) ? g_lamexp_translation.files->value(langId.toLower(), QString()) : QString();
1812 if(!qmFile.isEmpty())
1814 success = lamexp_install_translator_from_file(qmFileToPath.arg(qmFile));
1818 qWarning("Translation '%s' not available!", langId.toLatin1().constData());
1826 * Install a new translator from file
1828 bool lamexp_install_translator_from_file(const QString &qmFile)
1830 QWriteLocker writeLock(&g_lamexp_currentTranslator.lock);
1831 bool success = false;
1833 if(!g_lamexp_currentTranslator.instance)
1835 g_lamexp_currentTranslator.instance = new QTranslator();
1838 if(!qmFile.isEmpty())
1840 QString qmPath = QFileInfo(qmFile).canonicalFilePath();
1841 QApplication::removeTranslator(g_lamexp_currentTranslator.instance);
1842 if(success = g_lamexp_currentTranslator.instance->load(qmPath))
1844 QApplication::installTranslator(g_lamexp_currentTranslator.instance);
1848 qWarning("Failed to load translation:\n\"%s\"", qmPath.toLatin1().constData());
1853 QApplication::removeTranslator(g_lamexp_currentTranslator.instance);
1860 const QStringList &lamexp_arguments(void)
1862 QReadLocker readLock(&g_lamexp_argv.lock);
1864 if(!g_lamexp_argv.list)
1867 QWriteLocker writeLock(&g_lamexp_argv.lock);
1869 g_lamexp_argv.list = new QStringList;
1872 LPWSTR *szArglist = CommandLineToArgvW(GetCommandLineW(), &nArgs);
1874 if(NULL != szArglist)
1876 for(int i = 0; i < nArgs; i++)
1878 (*g_lamexp_argv.list) << WCHAR2QSTR(szArglist[i]);
1880 LocalFree(szArglist);
1884 qWarning("CommandLineToArgvW() has failed !!!");
1888 return (*g_lamexp_argv.list);
1892 * Locate known folder on local system
1894 const QString &lamexp_known_folder(lamexp_known_folder_t folder_id)
1896 typedef HRESULT (WINAPI *SHGetKnownFolderPathFun)(__in const GUID &rfid, __in DWORD dwFlags, __in HANDLE hToken, __out PWSTR *ppszPath);
1897 typedef HRESULT (WINAPI *SHGetFolderPathFun)(__in HWND hwndOwner, __in int nFolder, __in HANDLE hToken, __in DWORD dwFlags, __out LPWSTR pszPath);
1899 static const int CSIDL_LOCAL_APPDATA = 0x001c;
1900 static const int CSIDL_PROGRAM_FILES = 0x0026;
1901 static const int CSIDL_SYSTEM_FOLDER = 0x0025;
1902 static const GUID GUID_LOCAL_APPDATA = {0xF1B32785,0x6FBA,0x4FCF,{0x9D,0x55,0x7B,0x8E,0x7F,0x15,0x70,0x91}};
1903 static const GUID GUID_LOCAL_APPDATA_LOW = {0xA520A1A4,0x1780,0x4FF6,{0xBD,0x18,0x16,0x73,0x43,0xC5,0xAF,0x16}};
1904 static const GUID GUID_PROGRAM_FILES = {0x905e63b6,0xc1bf,0x494e,{0xb2,0x9c,0x65,0xb7,0x32,0xd3,0xd2,0x1a}};
1905 static const GUID GUID_SYSTEM_FOLDER = {0x1AC14E77,0x02E7,0x4E5D,{0xB7,0x44,0x2E,0xB1,0xAE,0x51,0x98,0xB7}};
1907 QReadLocker readLock(&g_lamexp_folder.lock);
1909 int folderCSIDL = -1;
1910 GUID folderGUID = {0x0000,0x0000,0x0000,{0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00}};
1911 size_t folderCacheId = size_t(-1);
1915 case lamexp_folder_localappdata:
1917 folderCSIDL = CSIDL_LOCAL_APPDATA;
1918 folderGUID = GUID_LOCAL_APPDATA;
1920 case lamexp_folder_programfiles:
1922 folderCSIDL = CSIDL_PROGRAM_FILES;
1923 folderGUID = GUID_PROGRAM_FILES;
1925 case lamexp_folder_systemfolder:
1927 folderCSIDL = CSIDL_SYSTEM_FOLDER;
1928 folderGUID = GUID_SYSTEM_FOLDER;
1931 qWarning("Invalid 'known' folder was requested!");
1932 return *reinterpret_cast<QString*>(NULL);
1937 if(g_lamexp_folder.knownFolders)
1939 if(g_lamexp_folder.knownFolders->contains(folderCacheId))
1941 return (*g_lamexp_folder.knownFolders)[folderCacheId];
1946 QWriteLocker writeLock(&g_lamexp_folder.lock);
1948 static SHGetKnownFolderPathFun SHGetKnownFolderPathPtr = NULL;
1949 static SHGetFolderPathFun SHGetFolderPathPtr = NULL;
1951 if((!SHGetKnownFolderPathPtr) && (!SHGetFolderPathPtr))
1953 QLibrary kernel32Lib("shell32.dll");
1954 if(kernel32Lib.load())
1956 SHGetKnownFolderPathPtr = (SHGetKnownFolderPathFun) kernel32Lib.resolve("SHGetKnownFolderPath");
1957 SHGetFolderPathPtr = (SHGetFolderPathFun) kernel32Lib.resolve("SHGetFolderPathW");
1963 if(SHGetKnownFolderPathPtr)
1966 if(SHGetKnownFolderPathPtr(folderGUID, 0x00008000, NULL, &path) == S_OK)
1968 //MessageBoxW(0, path, L"SHGetKnownFolderPath", MB_TOPMOST);
1969 QDir folderTemp = QDir(QDir::fromNativeSeparators(QString::fromUtf16(reinterpret_cast<const unsigned short*>(path))));
1970 if(!folderTemp.exists())
1972 folderTemp.mkpath(".");
1974 if(folderTemp.exists())
1976 folder = folderTemp.canonicalPath();
1978 CoTaskMemFree(path);
1981 else if(SHGetFolderPathPtr)
1983 WCHAR *path = new WCHAR[4096];
1984 if(SHGetFolderPathPtr(NULL, folderCSIDL, NULL, NULL, path) == S_OK)
1986 //MessageBoxW(0, path, L"SHGetFolderPathW", MB_TOPMOST);
1987 QDir folderTemp = QDir(QDir::fromNativeSeparators(QString::fromUtf16(reinterpret_cast<const unsigned short*>(path))));
1988 if(!folderTemp.exists())
1990 folderTemp.mkpath(".");
1992 if(folderTemp.exists())
1994 folder = folderTemp.canonicalPath();
2001 if(!g_lamexp_folder.knownFolders)
2003 g_lamexp_folder.knownFolders = new QMap<size_t, QString>();
2007 g_lamexp_folder.knownFolders->insert(folderCacheId, folder);
2008 return (*g_lamexp_folder.knownFolders)[folderCacheId];
2012 * Safely remove a file
2014 bool lamexp_remove_file(const QString &filename)
2016 if(!QFileInfo(filename).exists() || !QFileInfo(filename).isFile())
2022 if(!QFile::remove(filename))
2024 DWORD attributes = GetFileAttributesW(QWCHAR(filename));
2025 SetFileAttributesW(QWCHAR(filename), (attributes & (~FILE_ATTRIBUTE_READONLY)));
2026 if(!QFile::remove(filename))
2028 qWarning("Could not delete \"%s\"", filename.toLatin1().constData());
2044 * Check if visual themes are enabled (WinXP and later)
2046 bool lamexp_themes_enabled(void)
2048 typedef int (WINAPI *IsAppThemedFun)(void);
2050 QReadLocker readLock(&g_lamexp_themes_enabled.lock);
2051 if(g_lamexp_themes_enabled.bInitialized)
2053 return g_lamexp_themes_enabled.bThemesEnabled;
2057 QWriteLocker writeLock(&g_lamexp_themes_enabled.lock);
2059 if(!g_lamexp_themes_enabled.bInitialized)
2061 g_lamexp_themes_enabled.bThemesEnabled = false;
2062 const lamexp_os_version_t * osVersion = lamexp_get_os_version();
2063 if(LAMEXP_MIN_OS_VER(osVersion, 5, 1))
2065 IsAppThemedFun IsAppThemedPtr = NULL;
2066 QLibrary uxTheme(QString("%1/UxTheme.dll").arg(lamexp_known_folder(lamexp_folder_systemfolder)));
2069 IsAppThemedPtr = (IsAppThemedFun) uxTheme.resolve("IsAppThemed");
2073 g_lamexp_themes_enabled.bThemesEnabled = IsAppThemedPtr();
2074 if(!g_lamexp_themes_enabled.bThemesEnabled)
2076 qWarning("Theme support is disabled for this process!");
2080 g_lamexp_themes_enabled.bInitialized = true;
2083 return g_lamexp_themes_enabled.bThemesEnabled;
2087 * Get number of free bytes on disk
2089 unsigned __int64 lamexp_free_diskspace(const QString &path, bool *ok)
2091 ULARGE_INTEGER freeBytesAvailable, totalNumberOfBytes, totalNumberOfFreeBytes;
2092 if(GetDiskFreeSpaceExW(reinterpret_cast<const wchar_t*>(QDir::toNativeSeparators(path).utf16()), &freeBytesAvailable, &totalNumberOfBytes, &totalNumberOfFreeBytes))
2095 return freeBytesAvailable.QuadPart;
2105 * Check if computer does support hibernation
2107 bool lamexp_is_hibernation_supported(void)
2109 bool hibernationSupported = false;
2111 SYSTEM_POWER_CAPABILITIES pwrCaps;
2112 SecureZeroMemory(&pwrCaps, sizeof(SYSTEM_POWER_CAPABILITIES));
2114 if(GetPwrCapabilities(&pwrCaps))
2116 hibernationSupported = pwrCaps.SystemS4 && pwrCaps.HiberFilePresent;
2119 return hibernationSupported;
2123 * Shutdown the computer
2125 bool lamexp_shutdown_computer(const QString &message, const unsigned long timeout, const bool forceShutdown, const bool hibernate)
2127 HANDLE hToken = NULL;
2129 if(OpenProcessToken(GetCurrentProcess(), TOKEN_ADJUST_PRIVILEGES | TOKEN_QUERY, &hToken))
2131 TOKEN_PRIVILEGES privileges;
2132 memset(&privileges, 0, sizeof(TOKEN_PRIVILEGES));
2133 privileges.PrivilegeCount = 1;
2134 privileges.Privileges[0].Attributes = SE_PRIVILEGE_ENABLED;
2136 if(LookupPrivilegeValue(NULL, SE_SHUTDOWN_NAME, &privileges.Privileges[0].Luid))
2138 if(AdjustTokenPrivileges(hToken, FALSE, &privileges, NULL, NULL, NULL))
2142 if(SetSuspendState(TRUE, TRUE, TRUE))
2147 const DWORD reason = SHTDN_REASON_MAJOR_APPLICATION | SHTDN_REASON_FLAG_PLANNED;
2148 return InitiateSystemShutdownEx(NULL, const_cast<wchar_t*>(QWCHAR(message)), timeout, forceShutdown ? TRUE : FALSE, FALSE, reason);
2157 * Make a window blink (to draw user's attention)
2159 void lamexp_blink_window(QWidget *poWindow, unsigned int count, unsigned int delay)
2161 static QMutex blinkMutex;
2163 const double maxOpac = 1.0;
2164 const double minOpac = 0.3;
2165 const double delOpac = 0.1;
2167 if(!blinkMutex.tryLock())
2169 qWarning("Blinking is already in progress, skipping!");
2175 const int steps = static_cast<int>(ceil(maxOpac - minOpac) / delOpac);
2176 const int sleep = static_cast<int>(floor(static_cast<double>(delay) / static_cast<double>(steps)));
2177 const double opacity = poWindow->windowOpacity();
2179 for(unsigned int i = 0; i < count; i++)
2181 for(double x = maxOpac; x >= minOpac; x -= delOpac)
2183 poWindow->setWindowOpacity(x);
2184 QApplication::processEvents();
2188 for(double x = minOpac; x <= maxOpac; x += delOpac)
2190 poWindow->setWindowOpacity(x);
2191 QApplication::processEvents();
2196 poWindow->setWindowOpacity(opacity);
2197 QApplication::processEvents();
2198 blinkMutex.unlock();
2202 blinkMutex.unlock();
2203 qWarning("Exception error while blinking!");
2208 * Remove forbidden characters from a filename
2210 const QString lamexp_clean_filename(const QString &str)
2212 QString newStr(str);
2213 QRegExp rx("\"(.+)\"");
2214 rx.setMinimal(true);
2216 newStr.replace("\\", "-");
2217 newStr.replace(" / ", ", ");
2218 newStr.replace("/", ",");
2219 newStr.replace(":", "-");
2220 newStr.replace("*", "x");
2221 newStr.replace("?", "");
2222 newStr.replace("<", "[");
2223 newStr.replace(">", "]");
2224 newStr.replace("|", "!");
2225 newStr.replace(rx, "`\\1´");
2226 newStr.replace("\"", "'");
2228 return newStr.simplified();
2232 * Remove forbidden characters from a file path
2234 const QString lamexp_clean_filepath(const QString &str)
2236 QStringList parts = QString(str).replace("\\", "/").split("/");
2238 for(int i = 0; i < parts.count(); i++)
2240 parts[i] = lamexp_clean_filename(parts[i]);
2243 return parts.join("/");
2247 * Get a list of all available Qt Text Codecs
2249 QStringList lamexp_available_codepages(bool noAliases)
2251 QStringList codecList;
2253 QList<QByteArray> availableCodecs = QTextCodec::availableCodecs();
2254 while(!availableCodecs.isEmpty())
2256 QByteArray current = availableCodecs.takeFirst();
2257 if(!(current.startsWith("system") || current.startsWith("System")))
2259 codecList << QString::fromLatin1(current.constData(), current.size());
2262 if(QTextCodec *currentCodec = QTextCodec::codecForName(current.constData()))
2265 QList<QByteArray> aliases = currentCodec->aliases();
2266 while(!aliases.isEmpty()) availableCodecs.removeAll(aliases.takeFirst());
2276 * Robert Jenkins' 96 bit Mix Function
2277 * Source: http://www.concentric.net/~Ttwang/tech/inthash.htm
2279 static unsigned int lamexp_mix(const unsigned int x, const unsigned int y, const unsigned int z)
2285 a=a-b; a=a-c; a=a^(c >> 13);
2286 b=b-c; b=b-a; b=b^(a << 8);
2287 c=c-a; c=c-b; c=c^(b >> 13);
2288 a=a-b; a=a-c; a=a^(c >> 12);
2289 b=b-c; b=b-a; b=b^(a << 16);
2290 c=c-a; c=c-b; c=c^(b >> 5);
2291 a=a-b; a=a-c; a=a^(c >> 3);
2292 b=b-c; b=b-a; b=b^(a << 10);
2293 c=c-a; c=c-b; c=c^(b >> 15);
2299 * Seeds the random number generator
2300 * Note: Altough rand_s() doesn't need a seed, this must be called pripr to lamexp_rand(), just to to be sure!
2302 void lamexp_seed_rand(void)
2304 qsrand(lamexp_mix(clock(), time(NULL), _getpid()));
2308 * Returns a randum number
2309 * Note: This function uses rand_s() if available, but falls back to qrand() otherwise
2311 unsigned int lamexp_rand(void)
2313 unsigned int rnd = 0;
2314 if(const lamexp_os_version_t* osVer = lamexp_get_os_version())
2316 if(LAMEXP_MIN_OS_VER(osVer, 5, 1))
2318 if(rand_s(&rnd) == 0)
2324 for(size_t i = 0; i < sizeof(unsigned int); i++)
2326 rnd = (rnd << 8) ^ qrand();
2332 * Determines the current date, resistant against certain manipulations
2334 QDate lamexp_current_date_safe(void)
2336 const DWORD MAX_PROC = 1024;
2337 DWORD *processes = new DWORD[MAX_PROC];
2338 DWORD bytesReturned = 0;
2340 if(!EnumProcesses(processes, sizeof(DWORD) * MAX_PROC, &bytesReturned))
2342 LAMEXP_DELETE_ARRAY(processes);
2343 return QDate::currentDate();
2346 const DWORD procCount = bytesReturned / sizeof(DWORD);
2347 ULARGE_INTEGER lastStartTime;
2348 memset(&lastStartTime, 0, sizeof(ULARGE_INTEGER));
2350 for(DWORD i = 0; i < procCount; i++)
2352 HANDLE hProc = OpenProcess(PROCESS_QUERY_INFORMATION, FALSE, processes[i]);
2355 FILETIME processTime[4];
2356 if(GetProcessTimes(hProc, &processTime[0], &processTime[1], &processTime[2], &processTime[3]))
2358 ULARGE_INTEGER timeCreation;
2359 timeCreation.LowPart = processTime[0].dwLowDateTime;
2360 timeCreation.HighPart = processTime[0].dwHighDateTime;
2361 if(timeCreation.QuadPart > lastStartTime.QuadPart)
2363 lastStartTime.QuadPart = timeCreation.QuadPart;
2370 LAMEXP_DELETE_ARRAY(processes);
2372 FILETIME lastStartTime_fileTime;
2373 lastStartTime_fileTime.dwHighDateTime = lastStartTime.HighPart;
2374 lastStartTime_fileTime.dwLowDateTime = lastStartTime.LowPart;
2376 FILETIME lastStartTime_localTime;
2377 if(!FileTimeToLocalFileTime(&lastStartTime_fileTime, &lastStartTime_localTime))
2379 memcpy(&lastStartTime_localTime, &lastStartTime_fileTime, sizeof(FILETIME));
2382 SYSTEMTIME lastStartTime_system;
2383 if(!FileTimeToSystemTime(&lastStartTime_localTime, &lastStartTime_system))
2385 memset(&lastStartTime_system, 0, sizeof(SYSTEMTIME));
2386 lastStartTime_system.wYear = 1970; lastStartTime_system.wMonth = lastStartTime_system.wDay = 1;
2389 const QDate currentDate = QDate::currentDate();
2390 const QDate processDate = QDate(lastStartTime_system.wYear, lastStartTime_system.wMonth, lastStartTime_system.wDay);
2391 return (currentDate >= processDate) ? currentDate : processDate;
2395 * Entry point checks
2397 static DWORD lamexp_entry_check(void);
2398 static DWORD g_lamexp_entry_check_result = lamexp_entry_check();
2399 static DWORD g_lamexp_entry_check_flag = 0x789E09B2;
2400 static DWORD lamexp_entry_check(void)
2402 volatile DWORD retVal = 0xA199B5AF;
2403 if(g_lamexp_entry_check_flag != 0x8761F64D)
2405 lamexp_fatal_exit(L"Application initialization has failed, take care!");
2411 * Application entry point (runs before static initializers)
2415 int WinMainCRTStartup(void);
2417 int lamexp_entry_point(void)
2419 if((!LAMEXP_DEBUG) && lamexp_check_for_debugger())
2421 lamexp_fatal_exit(L"Not a debug build. Please unload debugger and try again!");
2423 if(g_lamexp_entry_check_flag != 0x789E09B2)
2425 lamexp_fatal_exit(L"Application initialization has failed, take care!");
2428 //Zero *before* constructors are called
2429 LAMEXP_ZERO_MEMORY(g_lamexp_argv);
2430 LAMEXP_ZERO_MEMORY(g_lamexp_tools);
2431 LAMEXP_ZERO_MEMORY(g_lamexp_currentTranslator);
2432 LAMEXP_ZERO_MEMORY(g_lamexp_translation);
2433 LAMEXP_ZERO_MEMORY(g_lamexp_folder);
2434 LAMEXP_ZERO_MEMORY(g_lamexp_ipc_ptr);
2435 LAMEXP_ZERO_MEMORY(g_lamexp_os_version);
2436 LAMEXP_ZERO_MEMORY(g_lamexp_themes_enabled);
2437 LAMEXP_ZERO_MEMORY(g_lamexp_portable);
2439 //Make sure we will pass the check
2440 g_lamexp_entry_check_flag = ~g_lamexp_entry_check_flag;
2442 //Now initialize the C Runtime library!
2443 return WinMainCRTStartup();
2448 * Fatal application exit
2450 #pragma intrinsic(_InterlockedExchange)
2451 void lamexp_fatal_exit(const wchar_t* exitMessage, const wchar_t* errorBoxMessage)
2453 static volatile long bFatalFlag = 0L;
2455 if(_InterlockedExchange(&bFatalFlag, 1L) == 0L)
2457 if(GetCurrentThreadId() != g_main_thread_id)
2459 HANDLE mainThread = OpenThread(THREAD_TERMINATE, FALSE, g_main_thread_id);
2460 if(mainThread) TerminateThread(mainThread, ULONG_MAX);
2465 MessageBoxW(NULL, errorBoxMessage, L"LameXP - GURU MEDITATION", MB_ICONERROR | MB_TOPMOST | MB_TASKMODAL);
2470 FatalAppExit(0, exitMessage);
2471 TerminateProcess(GetCurrentProcess(), -1);
2475 TerminateThread(GetCurrentThread(), -1);
2480 * Finalization function (final clean-up)
2482 void lamexp_finalization(void)
2484 qDebug("lamexp_finalization()");
2487 if(g_lamexp_tools.registry)
2489 QStringList keys = g_lamexp_tools.registry->keys();
2490 for(int i = 0; i < keys.count(); i++)
2492 LAMEXP_DELETE((*g_lamexp_tools.registry)[keys.at(i)]);
2494 LAMEXP_DELETE(g_lamexp_tools.registry);
2495 LAMEXP_DELETE(g_lamexp_tools.versions);
2496 LAMEXP_DELETE(g_lamexp_tools.tags);
2499 //Delete temporary files
2500 if(g_lamexp_folder.temp)
2502 if(!g_lamexp_folder.temp->isEmpty())
2504 for(int i = 0; i < 100; i++)
2506 if(lamexp_clean_folder(*g_lamexp_folder.temp))
2513 LAMEXP_DELETE(g_lamexp_folder.temp);
2516 //Clear folder cache
2517 LAMEXP_DELETE(g_lamexp_folder.knownFolders);
2520 if(g_lamexp_currentTranslator.instance)
2522 QApplication::removeTranslator(g_lamexp_currentTranslator.instance);
2523 LAMEXP_DELETE(g_lamexp_currentTranslator.instance);
2525 LAMEXP_DELETE(g_lamexp_translation.files);
2526 LAMEXP_DELETE(g_lamexp_translation.names);
2527 LAMEXP_DELETE(g_lamexp_translation.cntry);
2528 LAMEXP_DELETE(g_lamexp_translation.sysid);
2530 //Destroy Qt application object
2531 QApplication *application = dynamic_cast<QApplication*>(QApplication::instance());
2532 LAMEXP_DELETE(application);
2534 //Detach from shared memory
2535 if(g_lamexp_ipc_ptr.sharedmem) g_lamexp_ipc_ptr.sharedmem->detach();
2536 LAMEXP_DELETE(g_lamexp_ipc_ptr.sharedmem);
2537 LAMEXP_DELETE(g_lamexp_ipc_ptr.semaphore_read);
2538 LAMEXP_DELETE(g_lamexp_ipc_ptr.semaphore_write);
2539 LAMEXP_DELETE(g_lamexp_ipc_ptr.semaphore_read_mutex);
2540 LAMEXP_DELETE(g_lamexp_ipc_ptr.semaphore_write_mutex);
2542 //Free STDOUT and STDERR buffers
2543 if(g_lamexp_console_attached)
2545 if(std::filebuf *tmp = dynamic_cast<std::filebuf*>(std::cout.rdbuf()))
2547 std::cout.rdbuf(NULL);
2550 if(std::filebuf *tmp = dynamic_cast<std::filebuf*>(std::cerr.rdbuf()))
2552 std::cerr.rdbuf(NULL);
2558 if(g_lamexp_log_file)
2560 fclose(g_lamexp_log_file);
2561 g_lamexp_log_file = NULL;
2564 //Free CLI Arguments
2565 LAMEXP_DELETE(g_lamexp_argv.list);
2569 * Initialize debug thread
2571 static const HANDLE g_debug_thread = LAMEXP_DEBUG ? NULL : lamexp_debug_thread_init();
2574 * Get number private bytes [debug only]
2576 SIZE_T lamexp_dbg_private_bytes(void)
2579 PROCESS_MEMORY_COUNTERS_EX memoryCounters;
2580 memoryCounters.cb = sizeof(PROCESS_MEMORY_COUNTERS_EX);
2581 GetProcessMemoryInfo(GetCurrentProcess(), (PPROCESS_MEMORY_COUNTERS) &memoryCounters, sizeof(PROCESS_MEMORY_COUNTERS_EX));
2582 return memoryCounters.PrivateUsage;
2584 throw "Cannot call this function in a non-debug build!";
2585 #endif //LAMEXP_DEBUG