1 ///////////////////////////////////////////////////////////////////////////////
2 // LameXP - Audio Encoder Front-End
3 // Copyright (C) 2004-2012 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"
79 //Initialize static Qt plugins
81 #if QT_VERSION < QT_VERSION_CHECK(5,0,0)
85 Q_IMPORT_PLUGIN(QWindowsIntegrationPlugin)
86 Q_IMPORT_PLUGIN(QICOPlugin)
90 #define LAMEXP_ZERO_MEMORY(X) SecureZeroMemory(&X, sizeof(X))
93 #define _LAMEXP_MAKE_STR(STR) #STR
94 #define LAMEXP_MAKE_STR(STR) _LAMEXP_MAKE_STR(STR)
96 ///////////////////////////////////////////////////////////////////////////////
98 ///////////////////////////////////////////////////////////////////////////////
100 static const size_t g_lamexp_ipc_slots = 128;
104 unsigned int command;
105 unsigned int reserved_1;
106 unsigned int reserved_2;
107 char parameter[4096];
113 unsigned int pos_write;
114 unsigned int pos_read;
115 lamexp_ipc_data_t data[g_lamexp_ipc_slots];
119 ///////////////////////////////////////////////////////////////////////////////
121 ///////////////////////////////////////////////////////////////////////////////
126 unsigned int ver_major;
127 unsigned int ver_minor;
128 unsigned int ver_build;
129 char *ver_release_name;
140 static QDate g_lamexp_version_date;
141 static const char *g_lamexp_months[] = {"Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"};
142 static const char *g_lamexp_version_raw_date = __DATE__;
143 static const char *g_lamexp_version_raw_time = __TIME__;
145 //Console attached flag
146 static bool g_lamexp_console_attached = false;
149 //The following code was borrowed from MPC-HC project: http://mpc-hc.sf.net/
150 #if defined(__INTEL_COMPILER)
151 #if (__INTEL_COMPILER >= 1300)
152 static const char *g_lamexp_version_compiler = "ICL 13." LAMEXP_MAKE_STR(__INTEL_COMPILER_BUILD_DATE);
153 #elif (__INTEL_COMPILER >= 1200)
154 static const char *g_lamexp_version_compiler = "ICL 12." LAMEXP_MAKE_STR(__INTEL_COMPILER_BUILD_DATE);
155 #elif (__INTEL_COMPILER >= 1100)
156 static const char *g_lamexp_version_compiler = "ICL 11.x";
157 #elif (__INTEL_COMPILER >= 1000)
158 static const char *g_lamexp_version_compiler = "ICL 10.x";
160 #error Compiler is not supported!
162 #elif defined(_MSC_VER)
163 #if (_MSC_VER == 1700)
164 #if (_MSC_FULL_VER < 170050727)
165 static const char *g_lamexp_version_compiler = "MSVC 2012-Beta";
166 #elif (_MSC_FULL_VER < 170051020)
167 static const char *g_lamexp_version_compiler = "MSVC 2012-RTM";
168 #elif (_MSC_FULL_VER < 170051106)
169 static const char *g_lamexp_version_compiler = "MSVC 2012-U1 CTP";
170 #elif (_MSC_FULL_VER == 170051106)
171 static const char *g_lamexp_version_compiler = "MSVC 2012-U1";
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";
218 //Tool versions (expected versions!)
219 static const unsigned int g_lamexp_toolver_neroaac = VER_LAMEXP_TOOL_NEROAAC;
220 static const unsigned int g_lamexp_toolver_fhgaacenc = VER_LAMEXP_TOOL_FHGAACENC;
221 static const unsigned int g_lamexp_toolver_qaacenc = VER_LAMEXP_TOOL_QAAC;
222 static const unsigned int g_lamexp_toolver_coreaudio = VER_LAMEXP_TOOL_COREAUDIO;
228 QMap<size_t, QString> *knownFolders;
236 QMap<QString, LockedFile*> *registry;
237 QMap<QString, unsigned int> *versions;
245 QMap<QString, QString> *files;
246 QMap<QString, QString> *names;
247 QMap<QString, unsigned int> *sysid;
248 QMap<QString, unsigned int> *cntry;
251 g_lamexp_translation;
256 QTranslator *instance;
259 g_lamexp_currentTranslator;
273 lamexp_os_version_t version;
282 char *semaphore_read;
283 char *semaphore_read_mutex;
284 char *semaphore_write;
285 char *semaphore_write_mutex;
289 "{21A68A42-6923-43bb-9CF6-64BF151942EE}",
290 "{7A605549-F58C-4d78-B4E5-06EFC34F405B}",
291 "{60AA8D04-F6B8-497d-81EB-0F600F4A65B5}",
292 "{726061D5-1615-4B82-871C-75FD93458E46}",
293 "{1A616023-AA6A-4519-8AF3-F7736E899977}"
297 QSharedMemory *sharedmem;
298 QSystemSemaphore *semaphore_read;
299 QSystemSemaphore *semaphore_read_mutex;
300 QSystemSemaphore *semaphore_write;
301 QSystemSemaphore *semaphore_write_mutex;
307 static const char *g_lamexp_imageformats[] = {"bmp", "png", "jpg", "gif", "ico", "xpm", NULL}; //"svg"
310 static QMutex g_lamexp_message_mutex;
313 static const DWORD g_main_thread_id = GetCurrentThreadId();
316 static FILE *g_lamexp_log_file = NULL;
318 ///////////////////////////////////////////////////////////////////////////////
320 ///////////////////////////////////////////////////////////////////////////////
325 unsigned int lamexp_version_major(void) { return g_lamexp_version.ver_major; }
326 unsigned int lamexp_version_minor(void) { return g_lamexp_version.ver_minor; }
327 unsigned int lamexp_version_build(void) { return g_lamexp_version.ver_build; }
328 const char *lamexp_version_release(void) { return g_lamexp_version.ver_release_name; }
329 const char *lamexp_version_time(void) { return g_lamexp_version_raw_time; }
330 const char *lamexp_version_compiler(void) { return g_lamexp_version_compiler; }
331 const char *lamexp_version_arch(void) { return g_lamexp_version_arch; }
332 unsigned int lamexp_toolver_neroaac(void) { return g_lamexp_toolver_neroaac; }
333 unsigned int lamexp_toolver_fhgaacenc(void) { return g_lamexp_toolver_fhgaacenc; }
334 unsigned int lamexp_toolver_qaacenc(void) { return g_lamexp_toolver_qaacenc; }
335 unsigned int lamexp_toolver_coreaudio(void) { return g_lamexp_toolver_coreaudio; }
340 const char *lamexp_website_url(void) { return g_lamexp_website_url; }
341 const char *lamexp_support_url(void) { return g_lamexp_support_url; }
344 * Check for Demo (pre-release) version
346 bool lamexp_version_demo(void)
349 bool releaseVersion = false;
350 if(!strncpy_s(buffer, 128, g_lamexp_version.ver_release_name, _TRUNCATE))
352 char *context, *prefix = strtok_s(buffer, "-,; ", &context);
355 releaseVersion = (!_stricmp(prefix, "Final")) || (!_stricmp(prefix, "Hotfix"));
358 return LAMEXP_DEBUG || (!releaseVersion);
362 * Calculate expiration date
364 QDate lamexp_version_expires(void)
366 return lamexp_version_date().addDays(LAMEXP_DEBUG ? 7 : 30);
370 * Get build date date
372 const QDate &lamexp_version_date(void)
374 if(!g_lamexp_version_date.isValid())
376 int date[3] = {0, 0, 0}; char temp[12] = {'\0'};
377 strncpy_s(temp, 12, g_lamexp_version_raw_date, _TRUNCATE);
379 if(strlen(temp) == 11)
381 temp[3] = temp[6] = '\0';
382 date[2] = atoi(&temp[4]);
383 date[0] = atoi(&temp[7]);
385 for(int j = 0; j < 12; j++)
387 if(!_strcmpi(&temp[0], g_lamexp_months[j]))
394 g_lamexp_version_date = QDate(date[0], date[1], date[2]);
397 if(!g_lamexp_version_date.isValid())
399 qFatal("Internal error: Date format could not be recognized!");
403 return g_lamexp_version_date;
407 * Get the native operating system version
409 const lamexp_os_version_t *lamexp_get_os_version(void)
411 QReadLocker readLock(&g_lamexp_os_version.lock);
413 //Already initialized?
414 if(g_lamexp_os_version.bInitialized)
416 return &g_lamexp_os_version.version;
420 QWriteLocker writeLock(&g_lamexp_os_version.lock);
423 if(!g_lamexp_os_version.bInitialized)
425 OSVERSIONINFO osVerInfo;
426 memset(&osVerInfo, 0, sizeof(OSVERSIONINFO));
427 osVerInfo.dwOSVersionInfoSize = sizeof(OSVERSIONINFO);
429 if(GetVersionEx(&osVerInfo) == TRUE)
431 if(osVerInfo.dwPlatformId == VER_PLATFORM_WIN32_NT)
433 g_lamexp_os_version.version.versionMajor = osVerInfo.dwMajorVersion;
434 g_lamexp_os_version.version.versionMinor = osVerInfo.dwMinorVersion;
438 qWarning("lamexp_get_os_version: Not running under Windows NT, this is not supposed to happen!");
439 g_lamexp_os_version.version.versionMajor = 0;
440 g_lamexp_os_version.version.versionMinor = 0;
445 throw "GetVersionEx() has failed. This is not supposed to happen!";
448 g_lamexp_os_version.bInitialized = true;
451 return &g_lamexp_os_version.version;
455 * Check if we are running under wine
457 bool lamexp_detect_wine(void)
459 static bool isWine = false;
460 static bool isWine_initialized = false;
462 if(!isWine_initialized)
464 QLibrary ntdll("ntdll.dll");
467 if(ntdll.resolve("wine_nt_to_unix_file_name") != NULL) isWine = true;
468 if(ntdll.resolve("wine_get_version") != NULL) isWine = true;
471 isWine_initialized = true;
478 * Global exception handler
480 LONG WINAPI lamexp_exception_handler(__in struct _EXCEPTION_POINTERS *ExceptionInfo)
482 if(GetCurrentThreadId() != g_main_thread_id)
484 HANDLE mainThread = OpenThread(THREAD_TERMINATE, FALSE, g_main_thread_id);
485 if(mainThread) TerminateThread(mainThread, ULONG_MAX);
488 FatalAppExit(0, L"Unhandeled exception handler invoked, application will exit!");
489 TerminateProcess(GetCurrentProcess(), -1);
494 * Invalid parameters handler
496 void lamexp_invalid_param_handler(const wchar_t* exp, const wchar_t* fun, const wchar_t* fil, unsigned int, uintptr_t)
498 if(GetCurrentThreadId() != g_main_thread_id)
500 HANDLE mainThread = OpenThread(THREAD_TERMINATE, FALSE, g_main_thread_id);
501 if(mainThread) TerminateThread(mainThread, ULONG_MAX);
505 FatalAppExit(0, L"Invalid parameter handler invoked, application will exit!");
506 TerminateProcess(GetCurrentProcess(), -1);
510 * Change console text color
512 static void lamexp_console_color(FILE* file, WORD attributes)
514 const HANDLE hConsole = (HANDLE)(_get_osfhandle(_fileno(file)));
515 if((hConsole != NULL) && (hConsole != INVALID_HANDLE_VALUE))
517 SetConsoleTextAttribute(hConsole, attributes);
524 void lamexp_message_handler(QtMsgType type, const char *msg)
526 static const char *GURU_MEDITATION = "\n\nGURU MEDITATION !!!\n\n";
528 QMutexLocker lock(&g_lamexp_message_mutex);
530 if(g_lamexp_log_file)
532 static char prefix[] = "DWCF";
533 int index = qBound(0, static_cast<int>(type), 3);
534 unsigned int timestamp = static_cast<unsigned int>(_time64(NULL) % 3600I64);
535 QString str = QString::fromUtf8(msg).trimmed().replace('\n', '\t');
536 fprintf(g_lamexp_log_file, "[%c][%04u] %s\r\n", prefix[index], timestamp, str.toUtf8().constData());
537 fflush(g_lamexp_log_file);
540 if(g_lamexp_console_attached)
542 UINT oldOutputCP = GetConsoleOutputCP();
543 if(oldOutputCP != CP_UTF8) SetConsoleOutputCP(CP_UTF8);
551 lamexp_console_color(stderr, FOREGROUND_RED | FOREGROUND_INTENSITY);
552 fprintf(stderr, GURU_MEDITATION);
553 fprintf(stderr, "%s\n", msg);
557 lamexp_console_color(stderr, FOREGROUND_GREEN | FOREGROUND_RED | FOREGROUND_INTENSITY);
558 fprintf(stderr, "%s\n", msg);
562 lamexp_console_color(stderr, FOREGROUND_BLUE | FOREGROUND_GREEN | FOREGROUND_RED | FOREGROUND_INTENSITY);
563 fprintf(stderr, "%s\n", msg);
568 lamexp_console_color(stderr, FOREGROUND_BLUE | FOREGROUND_GREEN | FOREGROUND_RED);
569 if(oldOutputCP != CP_UTF8) SetConsoleOutputCP(oldOutputCP);
573 QString temp("[LameXP][%1] %2");
579 temp = temp.arg("C", QString::fromUtf8(msg));
582 temp = temp.arg("W", QString::fromUtf8(msg));
585 temp = temp.arg("I", QString::fromUtf8(msg));
589 temp.replace("\n", "\t").append("\n");
590 OutputDebugStringA(temp.toLatin1().constData());
593 if(type == QtCriticalMsg || type == QtFatalMsg)
597 if(GetCurrentThreadId() != g_main_thread_id)
599 HANDLE mainThread = OpenThread(THREAD_TERMINATE, FALSE, g_main_thread_id);
600 if(mainThread) TerminateThread(mainThread, ULONG_MAX);
603 MessageBoxW(NULL, QWCHAR(QString::fromUtf8(msg)), L"LameXP - GURU MEDITATION", MB_ICONERROR | MB_TOPMOST | MB_TASKMODAL);
604 FatalAppExit(0, L"The application has encountered a critical error and will exit now!");
605 TerminateProcess(GetCurrentProcess(), -1);
610 * Initialize the console
612 void lamexp_init_console(const QStringList &argv)
614 bool enableConsole = lamexp_version_demo();
618 wchar_t *logfile = NULL;
619 size_t logfile_len = 0;
620 if(!_wdupenv_s(&logfile, &logfile_len, L"LAMEXP_LOGFILE"))
622 if(logfile && (logfile_len > 0))
625 if(!_wfopen_s(&temp, logfile, L"wb"))
627 fprintf(temp, "%c%c%c", 0xEF, 0xBB, 0xBF);
628 g_lamexp_log_file = temp;
637 for(int i = 0; i < argv.count(); i++)
639 if(!argv.at(i).compare("--console", Qt::CaseInsensitive))
641 enableConsole = true;
643 else if(!argv.at(i).compare("--no-console", Qt::CaseInsensitive))
645 enableConsole = false;
652 if(!g_lamexp_console_attached)
654 if(AllocConsole() != FALSE)
656 SetConsoleCtrlHandler(NULL, TRUE);
657 SetConsoleTitle(L"LameXP - Audio Encoder Front-End | Debug Console");
658 SetConsoleOutputCP(CP_UTF8);
659 g_lamexp_console_attached = true;
663 if(g_lamexp_console_attached)
665 //-------------------------------------------------------------------
666 //See: http://support.microsoft.com/default.aspx?scid=kb;en-us;105305
667 //-------------------------------------------------------------------
668 const int flags = _O_WRONLY | _O_U8TEXT;
669 int hCrtStdOut = _open_osfhandle((intptr_t) GetStdHandle(STD_OUTPUT_HANDLE), flags);
670 int hCrtStdErr = _open_osfhandle((intptr_t) GetStdHandle(STD_ERROR_HANDLE), flags);
671 FILE *hfStdOut = (hCrtStdOut >= 0) ? _fdopen(hCrtStdOut, "wb") : NULL;
672 FILE *hfStdErr = (hCrtStdErr >= 0) ? _fdopen(hCrtStdErr, "wb") : NULL;
673 if(hfStdOut) { *stdout = *hfStdOut; std::cout.rdbuf(new std::filebuf(hfStdOut)); }
674 if(hfStdErr) { *stderr = *hfStdErr; std::cerr.rdbuf(new std::filebuf(hfStdErr)); }
677 HWND hwndConsole = GetConsoleWindow();
679 if((hwndConsole != NULL) && (hwndConsole != INVALID_HANDLE_VALUE))
681 HMENU hMenu = GetSystemMenu(hwndConsole, 0);
682 EnableMenuItem(hMenu, SC_CLOSE, MF_BYCOMMAND | MF_GRAYED);
683 RemoveMenu(hMenu, SC_CLOSE, MF_BYCOMMAND);
685 SetWindowPos(hwndConsole, HWND_TOP, 0, 0, 0, 0, SWP_NOMOVE|SWP_NOSIZE|SWP_NOZORDER|SWP_FRAMECHANGED);
686 SetWindowLong(hwndConsole, GWL_STYLE, GetWindowLong(hwndConsole, GWL_STYLE) & (~WS_MAXIMIZEBOX) & (~WS_MINIMIZEBOX));
687 SetWindowPos(hwndConsole, HWND_TOP, 0, 0, 0, 0, SWP_NOMOVE|SWP_NOSIZE|SWP_NOZORDER|SWP_FRAMECHANGED);
693 * Detect CPU features
695 lamexp_cpu_t lamexp_detect_cpu_features(const QStringList &argv)
697 typedef BOOL (WINAPI *IsWow64ProcessFun)(__in HANDLE hProcess, __out PBOOL Wow64Process);
698 typedef VOID (WINAPI *GetNativeSystemInfoFun)(__out LPSYSTEM_INFO lpSystemInfo);
700 static IsWow64ProcessFun IsWow64ProcessPtr = NULL;
701 static GetNativeSystemInfoFun GetNativeSystemInfoPtr = NULL;
703 lamexp_cpu_t features;
704 SYSTEM_INFO systemInfo;
705 int CPUInfo[4] = {-1};
706 char CPUIdentificationString[0x40];
707 char CPUBrandString[0x40];
709 memset(&features, 0, sizeof(lamexp_cpu_t));
710 memset(&systemInfo, 0, sizeof(SYSTEM_INFO));
711 memset(CPUIdentificationString, 0, sizeof(CPUIdentificationString));
712 memset(CPUBrandString, 0, sizeof(CPUBrandString));
715 memcpy(CPUIdentificationString, &CPUInfo[1], sizeof(int));
716 memcpy(CPUIdentificationString + 4, &CPUInfo[3], sizeof(int));
717 memcpy(CPUIdentificationString + 8, &CPUInfo[2], sizeof(int));
718 features.intel = (_stricmp(CPUIdentificationString, "GenuineIntel") == 0);
719 strncpy_s(features.vendor, 0x40, CPUIdentificationString, _TRUNCATE);
724 features.mmx = (CPUInfo[3] & 0x800000) || false;
725 features.sse = (CPUInfo[3] & 0x2000000) || false;
726 features.sse2 = (CPUInfo[3] & 0x4000000) || false;
727 features.ssse3 = (CPUInfo[2] & 0x200) || false;
728 features.sse3 = (CPUInfo[2] & 0x1) || false;
729 features.ssse3 = (CPUInfo[2] & 0x200) || false;
730 features.stepping = CPUInfo[0] & 0xf;
731 features.model = ((CPUInfo[0] >> 4) & 0xf) + (((CPUInfo[0] >> 16) & 0xf) << 4);
732 features.family = ((CPUInfo[0] >> 8) & 0xf) + ((CPUInfo[0] >> 20) & 0xff);
735 __cpuid(CPUInfo, 0x80000000);
736 int nExIds = qMax<int>(qMin<int>(CPUInfo[0], 0x80000004), 0x80000000);
738 for(int i = 0x80000002; i <= nExIds; ++i)
744 memcpy(CPUBrandString, CPUInfo, sizeof(CPUInfo));
747 memcpy(CPUBrandString + 16, CPUInfo, sizeof(CPUInfo));
750 memcpy(CPUBrandString + 32, CPUInfo, sizeof(CPUInfo));
755 strncpy_s(features.brand, 0x40, CPUBrandString, _TRUNCATE);
757 if(strlen(features.brand) < 1) strncpy_s(features.brand, 0x40, "Unknown", _TRUNCATE);
758 if(strlen(features.vendor) < 1) strncpy_s(features.vendor, 0x40, "Unknown", _TRUNCATE);
760 #if !defined(_M_X64 ) && !defined(_M_IA64)
761 if(!IsWow64ProcessPtr || !GetNativeSystemInfoPtr)
763 QLibrary Kernel32Lib("kernel32.dll");
764 IsWow64ProcessPtr = (IsWow64ProcessFun) Kernel32Lib.resolve("IsWow64Process");
765 GetNativeSystemInfoPtr = (GetNativeSystemInfoFun) Kernel32Lib.resolve("GetNativeSystemInfo");
767 if(IsWow64ProcessPtr)
770 if(IsWow64ProcessPtr(GetCurrentProcess(), &x64))
775 if(GetNativeSystemInfoPtr)
777 GetNativeSystemInfoPtr(&systemInfo);
781 GetSystemInfo(&systemInfo);
783 features.count = qBound(1UL, systemInfo.dwNumberOfProcessors, 64UL);
785 GetNativeSystemInfo(&systemInfo);
786 features.count = systemInfo.dwNumberOfProcessors;
793 for(int i = 0; i < argv.count(); i++)
795 if(!argv[i].compare("--force-cpu-no-64bit", Qt::CaseInsensitive)) { flag = true; features.x64 = false; }
796 if(!argv[i].compare("--force-cpu-no-sse", Qt::CaseInsensitive)) { flag = true; features.sse = features.sse2 = features.sse3 = features.ssse3 = false; }
797 if(!argv[i].compare("--force-cpu-no-intel", Qt::CaseInsensitive)) { flag = true; features.intel = false; }
799 if(flag) qWarning("CPU flags overwritten by user-defined parameters. Take care!\n");
806 * Check for debugger (detect routine)
808 static __forceinline bool lamexp_check_for_debugger(void)
810 if(IsDebuggerPresent())
817 CloseHandle((HANDLE) 0x7FFFFFFF);
819 __except(EXCEPTION_EXECUTE_HANDLER)
828 __except(EXCEPTION_EXECUTE_HANDLER)
837 * Check for debugger (thread proc)
839 static unsigned int __stdcall lamexp_debug_thread_proc(LPVOID lpParameter)
841 while(!lamexp_check_for_debugger())
845 if(HANDLE thrd = OpenThread(THREAD_TERMINATE, FALSE, g_main_thread_id))
847 if(TerminateThread(thrd, -1))
849 FatalAppExit(0, L"Not a debug build. Please unload debugger and try again!");
853 TerminateProcess(GetCurrentProcess(), -1);
858 * Check for debugger (startup routine)
860 static HANDLE lamexp_debug_thread_init(void)
862 if(lamexp_check_for_debugger())
864 FatalAppExit(0, L"Not a debug build. Please unload debugger and try again!");
865 TerminateProcess(GetCurrentProcess(), -1);
868 return (HANDLE) _beginthreadex(NULL, 0, lamexp_debug_thread_proc, NULL, 0, NULL);
872 * Check for compatibility mode
874 static bool lamexp_check_compatibility_mode(const char *exportName, const QString &executableName)
876 QLibrary kernel32("kernel32.dll");
878 if((exportName != NULL) && kernel32.load())
880 if(kernel32.resolve(exportName) != NULL)
882 qWarning("Function '%s' exported from 'kernel32.dll' -> Windows compatibility mode!", exportName);
883 qFatal("%s", QApplication::tr("Executable '%1' doesn't support Windows compatibility mode.").arg(executableName).toLatin1().constData());
892 * Computus according to H. Lichtenberg
894 static bool lamexp_computus(const QDate &date)
899 int M = 15 + (3*K + 3) / 4 - (8*K + 13) / 25;
900 int D = (19*A + M) % 30;
901 int S = 2 - (3*K + 3) / 4;
902 int R = D / 29 + (D / 28 - D / 29) * (A / 11);
904 int SZ = 7 - (X + X / 4 + S) % 7;
905 int OE = 7 - (OG - SZ) % 7;
910 return (date.month() == 4) && (date.day() == (OS - 31));
914 return (date.month() == 3) && (date.day() == OS);
919 * Check for Thanksgiving
921 static bool lamexp_thanksgiving(const QDate &date)
925 switch(QDate(date.year(), 11, 1).dayOfWeek())
927 case 1: day = 25; break;
928 case 2: day = 24; break;
929 case 3: day = 23; break;
930 case 4: day = 22; break;
931 case 5: day = 28; break;
932 case 6: day = 27; break;
933 case 7: day = 26; break;
936 return (date.month() == 11) && (date.day() == day);
940 * Initialize app icon
942 QIcon lamexp_app_icon(const QDate *date, const QTime *time)
944 QDate currentDate = (date) ? QDate(*date) : QDate::currentDate();
945 QTime currentTime = (time) ? QTime(*time) : QTime::currentTime();
947 if(lamexp_thanksgiving(currentDate))
949 return QIcon(":/MainIcon6.png");
951 else if(((currentDate.month() == 12) && (currentDate.day() == 31) && (currentTime.hour() >= 20)) || ((currentDate.month() == 1) && (currentDate.day() == 1) && (currentTime.hour() <= 19)))
953 return QIcon(":/MainIcon5.png");
955 else if(((currentDate.month() == 10) && (currentDate.day() == 31) && (currentTime.hour() >= 12)) || ((currentDate.month() == 11) && (currentDate.day() == 1) && (currentTime.hour() <= 11)))
957 return QIcon(":/MainIcon4.png");
959 else if((currentDate.month() == 12) && (currentDate.day() >= 24) && (currentDate.day() <= 26))
961 return QIcon(":/MainIcon3.png");
963 else if(lamexp_computus(currentDate))
965 return QIcon(":/MainIcon2.png");
969 return QIcon(":/MainIcon1.png");
974 * Broadcast event to all windows
976 static bool lamexp_broadcast(int eventType, bool onlyToVisible)
978 if(QApplication *app = dynamic_cast<QApplication*>(QApplication::instance()))
980 qDebug("Broadcasting %d", eventType);
983 QEvent poEvent(static_cast<QEvent::Type>(eventType));
984 QWidgetList list = app->topLevelWidgets();
986 while(!list.isEmpty())
988 QWidget *widget = list.takeFirst();
989 if(!onlyToVisible || widget->isVisible())
991 if(!app->sendEvent(widget, &poEvent))
998 qDebug("Broadcast %d done (%s)", eventType, (allOk ? "OK" : "Stopped"));
1003 qWarning("Broadcast failed, could not get QApplication instance!");
1011 static bool lamexp_event_filter(void *message, long *result)
1013 if((!(LAMEXP_DEBUG)) && lamexp_check_for_debugger())
1015 FatalAppExit(0, L"Not a debug build. Please unload debugger and try again!");
1016 TerminateProcess(GetCurrentProcess(), -1);
1019 switch(reinterpret_cast<MSG*>(message)->message)
1021 case WM_QUERYENDSESSION:
1022 qWarning("WM_QUERYENDSESSION message received!");
1023 *result = lamexp_broadcast(lamexp_event_queryendsession, false) ? TRUE : FALSE;
1026 qWarning("WM_ENDSESSION message received!");
1027 if(reinterpret_cast<MSG*>(message)->wParam == TRUE)
1029 lamexp_broadcast(lamexp_event_endsession, false);
1030 if(QApplication *app = reinterpret_cast<QApplication*>(QApplication::instance()))
1032 app->closeAllWindows();
1035 lamexp_finalization();
1041 /*ignore this message and let Qt handle it*/
1047 * Check for process elevation
1049 static bool lamexp_check_elevation(void)
1051 typedef enum { lamexp_token_elevationType_class = 18, lamexp_token_elevation_class = 20 } LAMEXP_TOKEN_INFORMATION_CLASS;
1052 typedef enum { lamexp_elevationType_default = 1, lamexp_elevationType_full, lamexp_elevationType_limited } LAMEXP_TOKEN_ELEVATION_TYPE;
1054 HANDLE hToken = NULL;
1055 bool bIsProcessElevated = false;
1057 if(OpenProcessToken(GetCurrentProcess(), TOKEN_QUERY, &hToken))
1059 LAMEXP_TOKEN_ELEVATION_TYPE tokenElevationType;
1061 if(GetTokenInformation(hToken, (TOKEN_INFORMATION_CLASS) lamexp_token_elevationType_class, &tokenElevationType, sizeof(LAMEXP_TOKEN_ELEVATION_TYPE), &returnLength))
1063 if(returnLength == sizeof(LAMEXP_TOKEN_ELEVATION_TYPE))
1065 switch(tokenElevationType)
1067 case lamexp_elevationType_default:
1068 qDebug("Process token elevation type: Default -> UAC is disabled.\n");
1070 case lamexp_elevationType_full:
1071 qWarning("Process token elevation type: Full -> potential security risk!\n");
1072 bIsProcessElevated = true;
1074 case lamexp_elevationType_limited:
1075 qDebug("Process token elevation type: Limited -> not elevated.\n");
1080 CloseHandle(hToken);
1084 qWarning("Failed to open process token!");
1087 return !bIsProcessElevated;
1091 * Initialize Qt framework
1093 bool lamexp_init_qt(int argc, char* argv[])
1095 static bool qt_initialized = false;
1096 typedef BOOL (WINAPI *SetDllDirectoryProc)(WCHAR *lpPathName);
1097 const QStringList &arguments = lamexp_arguments();
1099 //Don't initialized again, if done already
1105 //Secure DLL loading
1106 QLibrary kernel32("kernel32.dll");
1109 SetDllDirectoryProc pSetDllDirectory = (SetDllDirectoryProc) kernel32.resolve("SetDllDirectoryW");
1110 if(pSetDllDirectory != NULL) pSetDllDirectory(L"");
1114 //Extract executable name from argv[] array
1115 QString executableName = QLatin1String("LameXP.exe");
1116 if(arguments.count() > 0)
1118 static const char *delimiters = "\\/:?";
1119 executableName = arguments[0].trimmed();
1120 for(int i = 0; delimiters[i]; i++)
1122 int temp = executableName.lastIndexOf(QChar(delimiters[i]));
1123 if(temp >= 0) executableName = executableName.mid(temp + 1);
1125 executableName = executableName.trimmed();
1126 if(executableName.isEmpty())
1128 executableName = QLatin1String("LameXP.exe");
1134 qDebug("Using Qt v%s [%s], %s, %s", qVersion(), QLibraryInfo::buildDate().toString(Qt::ISODate).toLatin1().constData(), (qSharedBuild() ? "DLL" : "Static"), QLibraryInfo::buildKey().toLatin1().constData());
1135 qDebug("Compiled with Qt v%s [%s], %s\n", QT_VERSION_STR, QT_PACKAGEDATE_STR, QT_BUILD_KEY);
1136 if(_stricmp(qVersion(), QT_VERSION_STR))
1138 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());
1141 if(QLibraryInfo::buildKey().compare(QString::fromLatin1(QT_BUILD_KEY), Qt::CaseInsensitive))
1143 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());
1147 qDebug("Using Qt v%s [%s], %s", qVersion(), QLibraryInfo::buildDate().toString(Qt::ISODate).toLatin1().constData(), (qSharedBuild() ? "DLL" : "Static"));
1148 qDebug("Compiled with Qt v%s [%s]\n", QT_VERSION_STR, QT_PACKAGEDATE_STR);
1151 //Check the Windows version
1152 switch(QSysInfo::windowsVersion() & QSysInfo::WV_NT_based)
1155 case QSysInfo::WV_NT:
1156 qFatal("%s", QApplication::tr("Executable '%1' requires Windows 2000 or later.").arg(executableName).toLatin1().constData());
1158 case QSysInfo::WV_2000:
1159 qDebug("Running on Windows 2000 (not officially supported!).\n");
1160 lamexp_check_compatibility_mode("GetNativeSystemInfo", executableName);
1162 case QSysInfo::WV_XP:
1163 qDebug("Running on Windows XP.\n");
1164 lamexp_check_compatibility_mode("GetLargePageMinimum", executableName);
1166 case QSysInfo::WV_2003:
1167 qDebug("Running on Windows Server 2003 or Windows XP x64-Edition.\n");
1168 lamexp_check_compatibility_mode("GetLocaleInfoEx", executableName);
1170 case QSysInfo::WV_VISTA:
1171 qDebug("Running on Windows Vista or Windows Server 2008.\n");
1172 lamexp_check_compatibility_mode("CreateRemoteThreadEx", executableName);
1174 case QSysInfo::WV_WINDOWS7:
1175 qDebug("Running on Windows 7 or Windows Server 2008 R2.\n");
1176 lamexp_check_compatibility_mode("CreateFile2", executableName);
1180 const lamexp_os_version_t *osVersionNo = lamexp_get_os_version();
1181 if(osVersionNo->versionMajor < 5)
1183 qFatal("%s", QApplication::tr("Executable '%1' requires Windows 2000 or later.").arg(executableName).toLatin1().constData());
1185 else if(LAMEXP_EQL_OS_VER(osVersionNo, 6, 2))
1187 qDebug("Running on Windows 8 or Windows Server 2012\n");
1188 lamexp_check_compatibility_mode(NULL, executableName);
1192 qWarning("Running on an unknown/untested WinNT-based OS (v%u.%u).\n", osVersionNo->versionMajor, osVersionNo->versionMinor);
1199 if(lamexp_detect_wine())
1201 qWarning("It appears we are running under Wine, unexpected things might happen!\n");
1204 //Set text Codec for locale
1205 QTextCodec::setCodecForLocale(QTextCodec::codecForName("UTF-8"));
1207 //Create Qt application instance
1208 QApplication *application = new QApplication(argc, argv);
1210 //Load plugins from application directory
1211 QCoreApplication::setLibraryPaths(QStringList() << QApplication::applicationDirPath());
1212 qDebug("Library Path:\n%s\n", QApplication::libraryPaths().first().toUtf8().constData());
1214 //Set application properties
1215 application->setApplicationName("LameXP - Audio Encoder Front-End");
1216 application->setApplicationVersion(QString().sprintf("%d.%02d.%04d", lamexp_version_major(), lamexp_version_minor(), lamexp_version_build()));
1217 application->setOrganizationName("LoRd_MuldeR");
1218 application->setOrganizationDomain("mulder.at.gg");
1219 application->setWindowIcon(lamexp_app_icon());
1220 application->setEventFilter(lamexp_event_filter);
1222 //Check for supported image formats
1223 QList<QByteArray> supportedFormats = QImageReader::supportedImageFormats();
1224 for(int i = 0; g_lamexp_imageformats[i]; i++)
1226 if(!supportedFormats.contains(g_lamexp_imageformats[i]))
1228 qFatal("Qt initialization error: QImageIOHandler for '%s' missing!", g_lamexp_imageformats[i]);
1233 //Add default translations
1234 QWriteLocker writeLockTranslations(&g_lamexp_translation.lock);
1235 if(!g_lamexp_translation.files) g_lamexp_translation.files = new QMap<QString, QString>();
1236 if(!g_lamexp_translation.names) g_lamexp_translation.names = new QMap<QString, QString>();
1237 g_lamexp_translation.files->insert(LAMEXP_DEFAULT_LANGID, "");
1238 g_lamexp_translation.names->insert(LAMEXP_DEFAULT_LANGID, "English");
1239 writeLockTranslations.unlock();
1241 //Check for process elevation
1242 if((!lamexp_check_elevation()) && (!lamexp_detect_wine()))
1244 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);
1245 messageBox.addButton("Quit Program (Recommended)", QMessageBox::NoRole);
1246 messageBox.addButton("Ignore", QMessageBox::NoRole);
1247 if(messageBox.exec() == 0)
1253 //Update console icon, if a console is attached
1254 #if QT_VERSION < QT_VERSION_CHECK(5,0,0)
1255 if(g_lamexp_console_attached && (!lamexp_detect_wine()))
1257 typedef DWORD (__stdcall *SetConsoleIconFun)(HICON);
1258 QLibrary kernel32("kernel32.dll");
1261 SetConsoleIconFun SetConsoleIconPtr = (SetConsoleIconFun) kernel32.resolve("SetConsoleIcon");
1262 if(SetConsoleIconPtr != NULL) SetConsoleIconPtr(QIcon(":/icons/sound.png").pixmap(16, 16).toWinHICON());
1269 qt_initialized = true;
1276 int lamexp_init_ipc(void)
1278 QWriteLocker writeLock(&g_lamexp_ipc_ptr.lock);
1280 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)
1285 g_lamexp_ipc_ptr.semaphore_read = new QSystemSemaphore(QString(g_lamexp_ipc_uuid.semaphore_read), 0);
1286 g_lamexp_ipc_ptr.semaphore_write = new QSystemSemaphore(QString(g_lamexp_ipc_uuid.semaphore_write), 0);
1287 g_lamexp_ipc_ptr.semaphore_read_mutex = new QSystemSemaphore(QString(g_lamexp_ipc_uuid.semaphore_read_mutex), 0);
1288 g_lamexp_ipc_ptr.semaphore_write_mutex = new QSystemSemaphore(QString(g_lamexp_ipc_uuid.semaphore_write_mutex), 0);
1290 if(g_lamexp_ipc_ptr.semaphore_read->error() != QSystemSemaphore::NoError)
1292 QString errorMessage = g_lamexp_ipc_ptr.semaphore_read->errorString();
1293 LAMEXP_DELETE(g_lamexp_ipc_ptr.semaphore_read);
1294 LAMEXP_DELETE(g_lamexp_ipc_ptr.semaphore_write);
1295 LAMEXP_DELETE(g_lamexp_ipc_ptr.semaphore_read_mutex);
1296 LAMEXP_DELETE(g_lamexp_ipc_ptr.semaphore_write_mutex);
1297 qFatal("Failed to create system smaphore: %s", errorMessage.toUtf8().constData());
1300 if(g_lamexp_ipc_ptr.semaphore_write->error() != QSystemSemaphore::NoError)
1302 QString errorMessage = g_lamexp_ipc_ptr.semaphore_write->errorString();
1303 LAMEXP_DELETE(g_lamexp_ipc_ptr.semaphore_read);
1304 LAMEXP_DELETE(g_lamexp_ipc_ptr.semaphore_write);
1305 LAMEXP_DELETE(g_lamexp_ipc_ptr.semaphore_read_mutex);
1306 LAMEXP_DELETE(g_lamexp_ipc_ptr.semaphore_write_mutex);
1307 qFatal("Failed to create system smaphore: %s", errorMessage.toUtf8().constData());
1310 if(g_lamexp_ipc_ptr.semaphore_read_mutex->error() != QSystemSemaphore::NoError)
1312 QString errorMessage = g_lamexp_ipc_ptr.semaphore_read_mutex->errorString();
1313 LAMEXP_DELETE(g_lamexp_ipc_ptr.semaphore_read);
1314 LAMEXP_DELETE(g_lamexp_ipc_ptr.semaphore_write);
1315 LAMEXP_DELETE(g_lamexp_ipc_ptr.semaphore_read_mutex);
1316 LAMEXP_DELETE(g_lamexp_ipc_ptr.semaphore_write_mutex);
1317 qFatal("Failed to create system smaphore: %s", errorMessage.toUtf8().constData());
1320 if(g_lamexp_ipc_ptr.semaphore_write_mutex->error() != QSystemSemaphore::NoError)
1322 QString errorMessage = g_lamexp_ipc_ptr.semaphore_write_mutex->errorString();
1323 LAMEXP_DELETE(g_lamexp_ipc_ptr.semaphore_read);
1324 LAMEXP_DELETE(g_lamexp_ipc_ptr.semaphore_write);
1325 LAMEXP_DELETE(g_lamexp_ipc_ptr.semaphore_read_mutex);
1326 LAMEXP_DELETE(g_lamexp_ipc_ptr.semaphore_write_mutex);
1327 qFatal("Failed to create system smaphore: %s", errorMessage.toUtf8().constData());
1331 g_lamexp_ipc_ptr.sharedmem = new QSharedMemory(QString(g_lamexp_ipc_uuid.sharedmem), NULL);
1333 if(!g_lamexp_ipc_ptr.sharedmem->create(sizeof(lamexp_ipc_t)))
1335 if(g_lamexp_ipc_ptr.sharedmem->error() == QSharedMemory::AlreadyExists)
1337 g_lamexp_ipc_ptr.sharedmem->attach();
1338 if(g_lamexp_ipc_ptr.sharedmem->error() == QSharedMemory::NoError)
1344 QString errorMessage = g_lamexp_ipc_ptr.sharedmem->errorString();
1345 LAMEXP_DELETE(g_lamexp_ipc_ptr.sharedmem);
1346 qFatal("Failed to attach to shared memory: %s", errorMessage.toUtf8().constData());
1352 QString errorMessage = g_lamexp_ipc_ptr.sharedmem->errorString();
1353 LAMEXP_DELETE(g_lamexp_ipc_ptr.sharedmem);
1354 qFatal("Failed to create shared memory: %s", errorMessage.toUtf8().constData());
1359 memset(g_lamexp_ipc_ptr.sharedmem->data(), 0, sizeof(lamexp_ipc_t));
1360 g_lamexp_ipc_ptr.semaphore_write->release(g_lamexp_ipc_slots);
1361 g_lamexp_ipc_ptr.semaphore_read_mutex->release();
1362 g_lamexp_ipc_ptr.semaphore_write_mutex->release();
1370 void lamexp_ipc_send(unsigned int command, const char* message)
1372 QReadLocker readLock(&g_lamexp_ipc_ptr.lock);
1374 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)
1376 throw "Shared memory for IPC not initialized yet.";
1379 lamexp_ipc_data_t ipc_data;
1380 memset(&ipc_data, 0, sizeof(lamexp_ipc_data_t));
1381 ipc_data.command = command;
1385 strncpy_s(ipc_data.parameter, 4096, message, _TRUNCATE);
1388 if(g_lamexp_ipc_ptr.semaphore_write->acquire())
1390 if(g_lamexp_ipc_ptr.semaphore_write_mutex->acquire())
1392 lamexp_ipc_t *ptr = reinterpret_cast<lamexp_ipc_t*>(g_lamexp_ipc_ptr.sharedmem->data());
1393 memcpy(&ptr->data[ptr->pos_write], &ipc_data, sizeof(lamexp_ipc_data_t));
1394 ptr->pos_write = (ptr->pos_write + 1) % g_lamexp_ipc_slots;
1395 g_lamexp_ipc_ptr.semaphore_read->release();
1396 g_lamexp_ipc_ptr.semaphore_write_mutex->release();
1404 void lamexp_ipc_read(unsigned int *command, char* message, size_t buffSize)
1406 QReadLocker readLock(&g_lamexp_ipc_ptr.lock);
1411 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)
1413 throw "Shared memory for IPC not initialized yet.";
1416 lamexp_ipc_data_t ipc_data;
1417 memset(&ipc_data, 0, sizeof(lamexp_ipc_data_t));
1419 if(g_lamexp_ipc_ptr.semaphore_read->acquire())
1421 if(g_lamexp_ipc_ptr.semaphore_read_mutex->acquire())
1423 lamexp_ipc_t *ptr = reinterpret_cast<lamexp_ipc_t*>(g_lamexp_ipc_ptr.sharedmem->data());
1424 memcpy(&ipc_data, &ptr->data[ptr->pos_read], sizeof(lamexp_ipc_data_t));
1425 ptr->pos_read = (ptr->pos_read + 1) % g_lamexp_ipc_slots;
1426 g_lamexp_ipc_ptr.semaphore_write->release();
1427 g_lamexp_ipc_ptr.semaphore_read_mutex->release();
1429 if(!(ipc_data.reserved_1 || ipc_data.reserved_2))
1431 *command = ipc_data.command;
1432 strncpy_s(message, buffSize, ipc_data.parameter, _TRUNCATE);
1436 qWarning("Malformed IPC message, will be ignored");
1443 * Check for LameXP "portable" mode
1445 bool lamexp_portable_mode(void)
1447 QString baseName = QFileInfo(QApplication::applicationFilePath()).completeBaseName();
1448 int idx1 = baseName.indexOf("lamexp", 0, Qt::CaseInsensitive);
1449 int idx2 = baseName.lastIndexOf("portable", -1, Qt::CaseInsensitive);
1450 return (idx1 >= 0) && (idx2 >= 0) && (idx1 < idx2);
1454 * Get a random string
1456 QString lamexp_rand_str(void)
1458 QRegExp regExp("\\{(\\w+)-(\\w+)-(\\w+)-(\\w+)-(\\w+)\\}");
1459 QString uuid = QUuid::createUuid().toString();
1461 if(regExp.indexIn(uuid) >= 0)
1463 return QString().append(regExp.cap(1)).append(regExp.cap(2)).append(regExp.cap(3)).append(regExp.cap(4)).append(regExp.cap(5));
1466 throw "The RegExp didn't match on the UUID string. This shouldn't happen ;-)";
1470 * Get LameXP temp folder
1472 const QString &lamexp_temp_folder2(void)
1474 QReadLocker readLock(&g_lamexp_folder.lock);
1476 //Already initialized?
1477 if(g_lamexp_folder.temp)
1479 if(!g_lamexp_folder.temp->isEmpty())
1481 if(QDir(*g_lamexp_folder.temp).exists())
1483 return *g_lamexp_folder.temp;
1489 QWriteLocker writeLock(&g_lamexp_folder.lock);
1491 if(!g_lamexp_folder.temp)
1493 g_lamexp_folder.temp = new QString();
1496 g_lamexp_folder.temp->clear();
1498 static const char *TEMP_STR = "Temp";
1499 const QString WRITE_TEST_DATA = lamexp_rand_str();
1500 const QString SUB_FOLDER = lamexp_rand_str();
1502 //Try the %TMP% or %TEMP% directory first
1503 QDir temp = QDir::temp();
1506 temp.mkdir(SUB_FOLDER);
1507 if(temp.cd(SUB_FOLDER) && temp.exists())
1509 QFile testFile(QString("%1/~%2.tmp").arg(temp.canonicalPath(), lamexp_rand_str()));
1510 if(testFile.open(QIODevice::ReadWrite))
1512 if(testFile.write(WRITE_TEST_DATA.toLatin1().constData()) >= strlen(WRITE_TEST_DATA.toLatin1().constData()))
1514 (*g_lamexp_folder.temp) = temp.canonicalPath();
1519 if(!g_lamexp_folder.temp->isEmpty())
1521 return *g_lamexp_folder.temp;
1525 //Create TEMP folder in %LOCALAPPDATA%
1526 QDir localAppData = QDir(lamexp_known_folder(lamexp_folder_localappdata));
1527 if(!localAppData.path().isEmpty())
1529 if(!localAppData.exists())
1531 localAppData.mkpath(".");
1533 if(localAppData.exists())
1535 if(!localAppData.entryList(QDir::AllDirs).contains(TEMP_STR, Qt::CaseInsensitive))
1537 localAppData.mkdir(TEMP_STR);
1539 if(localAppData.cd(TEMP_STR) && localAppData.exists())
1541 localAppData.mkdir(SUB_FOLDER);
1542 if(localAppData.cd(SUB_FOLDER) && localAppData.exists())
1544 QFile testFile(QString("%1/~%2.tmp").arg(localAppData.canonicalPath(), lamexp_rand_str()));
1545 if(testFile.open(QIODevice::ReadWrite))
1547 if(testFile.write(WRITE_TEST_DATA.toLatin1().constData()) >= strlen(WRITE_TEST_DATA.toLatin1().constData()))
1549 (*g_lamexp_folder.temp) = localAppData.canonicalPath();
1556 if(!g_lamexp_folder.temp->isEmpty())
1558 return *g_lamexp_folder.temp;
1562 //Failed to create TEMP folder!
1563 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());
1564 return *g_lamexp_folder.temp;
1570 bool lamexp_clean_folder(const QString &folderPath)
1572 QDir tempFolder(folderPath);
1573 QFileInfoList entryList = tempFolder.entryInfoList(QDir::AllEntries | QDir::NoDotAndDotDot);
1575 for(int i = 0; i < entryList.count(); i++)
1577 if(entryList.at(i).isDir())
1579 lamexp_clean_folder(entryList.at(i).canonicalFilePath());
1583 for(int j = 0; j < 3; j++)
1585 if(lamexp_remove_file(entryList.at(i).canonicalFilePath()))
1593 tempFolder.rmdir(".");
1594 return !tempFolder.exists();
1600 void lamexp_register_tool(const QString &toolName, LockedFile *file, unsigned int version)
1602 QWriteLocker writeLock(&g_lamexp_tools.lock);
1604 if(!g_lamexp_tools.registry) g_lamexp_tools.registry = new QMap<QString, LockedFile*>();
1605 if(!g_lamexp_tools.versions) g_lamexp_tools.versions = new QMap<QString, unsigned int>();
1607 if(g_lamexp_tools.registry->contains(toolName.toLower()))
1609 throw "lamexp_register_tool: Tool is already registered!";
1612 g_lamexp_tools.registry->insert(toolName.toLower(), file);
1613 g_lamexp_tools.versions->insert(toolName.toLower(), version);
1619 bool lamexp_check_tool(const QString &toolName)
1621 QReadLocker readLock(&g_lamexp_tools.lock);
1622 return (g_lamexp_tools.registry) ? g_lamexp_tools.registry->contains(toolName.toLower()) : false;
1628 const QString lamexp_lookup_tool(const QString &toolName)
1630 QReadLocker readLock(&g_lamexp_tools.lock);
1632 if(g_lamexp_tools.registry)
1634 if(g_lamexp_tools.registry->contains(toolName.toLower()))
1636 return g_lamexp_tools.registry->value(toolName.toLower())->filePath();
1650 * Lookup tool version
1652 unsigned int lamexp_tool_version(const QString &toolName)
1654 QReadLocker readLock(&g_lamexp_tools.lock);
1656 if(g_lamexp_tools.versions)
1658 if(g_lamexp_tools.versions->contains(toolName.toLower()))
1660 return g_lamexp_tools.versions->value(toolName.toLower());
1674 * Version number to human-readable string
1676 const QString lamexp_version2string(const QString &pattern, unsigned int version, const QString &defaultText)
1678 if(version == UINT_MAX)
1683 QString result = pattern;
1684 int digits = result.count("?", Qt::CaseInsensitive);
1692 QString versionStr = QString().sprintf(QString().sprintf("%%0%du", digits).toLatin1().constData(), version);
1693 int index = result.indexOf("?", Qt::CaseInsensitive);
1695 while(index >= 0 && pos < versionStr.length())
1697 result[index] = versionStr[pos++];
1698 index = result.indexOf("?", Qt::CaseInsensitive);
1705 * Register a new translation
1707 bool lamexp_translation_register(const QString &langId, const QString &qmFile, const QString &langName, unsigned int &systemId, unsigned int &country)
1709 QWriteLocker writeLockTranslations(&g_lamexp_translation.lock);
1711 if(qmFile.isEmpty() || langName.isEmpty() || systemId < 1)
1716 if(!g_lamexp_translation.files) g_lamexp_translation.files = new QMap<QString, QString>();
1717 if(!g_lamexp_translation.names) g_lamexp_translation.names = new QMap<QString, QString>();
1718 if(!g_lamexp_translation.sysid) g_lamexp_translation.sysid = new QMap<QString, unsigned int>();
1719 if(!g_lamexp_translation.cntry) g_lamexp_translation.cntry = new QMap<QString, unsigned int>();
1721 g_lamexp_translation.files->insert(langId, qmFile);
1722 g_lamexp_translation.names->insert(langId, langName);
1723 g_lamexp_translation.sysid->insert(langId, systemId);
1724 g_lamexp_translation.cntry->insert(langId, country);
1730 * Get list of all translations
1732 QStringList lamexp_query_translations(void)
1734 QReadLocker readLockTranslations(&g_lamexp_translation.lock);
1735 return (g_lamexp_translation.files) ? g_lamexp_translation.files->keys() : QStringList();
1739 * Get translation name
1741 QString lamexp_translation_name(const QString &langId)
1743 QReadLocker readLockTranslations(&g_lamexp_translation.lock);
1744 return (g_lamexp_translation.names) ? g_lamexp_translation.names->value(langId.toLower(), QString()) : QString();
1748 * Get translation system id
1750 unsigned int lamexp_translation_sysid(const QString &langId)
1752 QReadLocker readLockTranslations(&g_lamexp_translation.lock);
1753 return (g_lamexp_translation.sysid) ? g_lamexp_translation.sysid->value(langId.toLower(), 0) : 0;
1757 * Get translation script id
1759 unsigned int lamexp_translation_country(const QString &langId)
1761 QReadLocker readLockTranslations(&g_lamexp_translation.lock);
1762 return (g_lamexp_translation.cntry) ? g_lamexp_translation.cntry->value(langId.toLower(), 0) : 0;
1766 * Install a new translator
1768 bool lamexp_install_translator(const QString &langId)
1770 bool success = false;
1772 if(langId.isEmpty() || langId.toLower().compare(LAMEXP_DEFAULT_LANGID) == 0)
1774 success = lamexp_install_translator_from_file(QString());
1778 QReadLocker readLock(&g_lamexp_translation.lock);
1779 QString qmFile = (g_lamexp_translation.files) ? g_lamexp_translation.files->value(langId.toLower(), QString()) : QString();
1782 if(!qmFile.isEmpty())
1784 success = lamexp_install_translator_from_file(QString(":/localization/%1").arg(qmFile));
1788 qWarning("Translation '%s' not available!", langId.toLatin1().constData());
1796 * Install a new translator from file
1798 bool lamexp_install_translator_from_file(const QString &qmFile)
1800 QWriteLocker writeLock(&g_lamexp_currentTranslator.lock);
1801 bool success = false;
1803 if(!g_lamexp_currentTranslator.instance)
1805 g_lamexp_currentTranslator.instance = new QTranslator();
1808 if(!qmFile.isEmpty())
1810 QString qmPath = QFileInfo(qmFile).canonicalFilePath();
1811 QApplication::removeTranslator(g_lamexp_currentTranslator.instance);
1812 if(success = g_lamexp_currentTranslator.instance->load(qmPath))
1814 QApplication::installTranslator(g_lamexp_currentTranslator.instance);
1818 qWarning("Failed to load translation:\n\"%s\"", qmPath.toLatin1().constData());
1823 QApplication::removeTranslator(g_lamexp_currentTranslator.instance);
1830 const QStringList &lamexp_arguments(void)
1832 QReadLocker readLock(&g_lamexp_argv.lock);
1834 if(!g_lamexp_argv.list)
1837 QWriteLocker writeLock(&g_lamexp_argv.lock);
1839 g_lamexp_argv.list = new QStringList;
1842 LPWSTR *szArglist = CommandLineToArgvW(GetCommandLineW(), &nArgs);
1844 if(NULL != szArglist)
1846 for(int i = 0; i < nArgs; i++)
1848 (*g_lamexp_argv.list) << WCHAR2QSTR(szArglist[i]);
1850 LocalFree(szArglist);
1854 qWarning("CommandLineToArgvW() has failed !!!");
1858 return (*g_lamexp_argv.list);
1862 * Locate known folder on local system
1864 const QString &lamexp_known_folder(lamexp_known_folder_t folder_id)
1866 typedef HRESULT (WINAPI *SHGetKnownFolderPathFun)(__in const GUID &rfid, __in DWORD dwFlags, __in HANDLE hToken, __out PWSTR *ppszPath);
1867 typedef HRESULT (WINAPI *SHGetFolderPathFun)(__in HWND hwndOwner, __in int nFolder, __in HANDLE hToken, __in DWORD dwFlags, __out LPWSTR pszPath);
1869 static const int CSIDL_LOCAL_APPDATA = 0x001c;
1870 static const int CSIDL_PROGRAM_FILES = 0x0026;
1871 static const int CSIDL_SYSTEM_FOLDER = 0x0025;
1872 static const GUID GUID_LOCAL_APPDATA = {0xF1B32785,0x6FBA,0x4FCF,{0x9D,0x55,0x7B,0x8E,0x7F,0x15,0x70,0x91}};
1873 static const GUID GUID_LOCAL_APPDATA_LOW = {0xA520A1A4,0x1780,0x4FF6,{0xBD,0x18,0x16,0x73,0x43,0xC5,0xAF,0x16}};
1874 static const GUID GUID_PROGRAM_FILES = {0x905e63b6,0xc1bf,0x494e,{0xb2,0x9c,0x65,0xb7,0x32,0xd3,0xd2,0x1a}};
1875 static const GUID GUID_SYSTEM_FOLDER = {0x1AC14E77,0x02E7,0x4E5D,{0xB7,0x44,0x2E,0xB1,0xAE,0x51,0x98,0xB7}};
1877 QReadLocker readLock(&g_lamexp_folder.lock);
1879 int folderCSIDL = -1;
1880 GUID folderGUID = {0x0000,0x0000,0x0000,{0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00}};
1881 size_t folderCacheId = size_t(-1);
1885 case lamexp_folder_localappdata:
1887 folderCSIDL = CSIDL_LOCAL_APPDATA;
1888 folderGUID = GUID_LOCAL_APPDATA;
1890 case lamexp_folder_programfiles:
1892 folderCSIDL = CSIDL_PROGRAM_FILES;
1893 folderGUID = GUID_PROGRAM_FILES;
1895 case lamexp_folder_systemfolder:
1897 folderCSIDL = CSIDL_SYSTEM_FOLDER;
1898 folderGUID = GUID_SYSTEM_FOLDER;
1901 qWarning("Invalid 'known' folder was requested!");
1902 return *reinterpret_cast<QString*>(NULL);
1907 if(g_lamexp_folder.knownFolders)
1909 if(g_lamexp_folder.knownFolders->contains(folderCacheId))
1911 return (*g_lamexp_folder.knownFolders)[folderCacheId];
1916 QWriteLocker writeLock(&g_lamexp_folder.lock);
1918 static SHGetKnownFolderPathFun SHGetKnownFolderPathPtr = NULL;
1919 static SHGetFolderPathFun SHGetFolderPathPtr = NULL;
1921 if((!SHGetKnownFolderPathPtr) && (!SHGetFolderPathPtr))
1923 QLibrary kernel32Lib("shell32.dll");
1924 if(kernel32Lib.load())
1926 SHGetKnownFolderPathPtr = (SHGetKnownFolderPathFun) kernel32Lib.resolve("SHGetKnownFolderPath");
1927 SHGetFolderPathPtr = (SHGetFolderPathFun) kernel32Lib.resolve("SHGetFolderPathW");
1933 if(SHGetKnownFolderPathPtr)
1936 if(SHGetKnownFolderPathPtr(folderGUID, 0x00008000, NULL, &path) == S_OK)
1938 //MessageBoxW(0, path, L"SHGetKnownFolderPath", MB_TOPMOST);
1939 QDir folderTemp = QDir(QDir::fromNativeSeparators(QString::fromUtf16(reinterpret_cast<const unsigned short*>(path))));
1940 if(!folderTemp.exists())
1942 folderTemp.mkpath(".");
1944 if(folderTemp.exists())
1946 folder = folderTemp.canonicalPath();
1948 CoTaskMemFree(path);
1951 else if(SHGetFolderPathPtr)
1953 WCHAR *path = new WCHAR[4096];
1954 if(SHGetFolderPathPtr(NULL, folderCSIDL, NULL, NULL, path) == S_OK)
1956 //MessageBoxW(0, path, L"SHGetFolderPathW", MB_TOPMOST);
1957 QDir folderTemp = QDir(QDir::fromNativeSeparators(QString::fromUtf16(reinterpret_cast<const unsigned short*>(path))));
1958 if(!folderTemp.exists())
1960 folderTemp.mkpath(".");
1962 if(folderTemp.exists())
1964 folder = folderTemp.canonicalPath();
1971 if(!g_lamexp_folder.knownFolders)
1973 g_lamexp_folder.knownFolders = new QMap<size_t, QString>();
1977 g_lamexp_folder.knownFolders->insert(folderCacheId, folder);
1978 return (*g_lamexp_folder.knownFolders)[folderCacheId];
1982 * Safely remove a file
1984 bool lamexp_remove_file(const QString &filename)
1986 if(!QFileInfo(filename).exists() || !QFileInfo(filename).isFile())
1992 if(!QFile::remove(filename))
1994 DWORD attributes = GetFileAttributesW(QWCHAR(filename));
1995 SetFileAttributesW(QWCHAR(filename), (attributes & (~FILE_ATTRIBUTE_READONLY)));
1996 if(!QFile::remove(filename))
1998 qWarning("Could not delete \"%s\"", filename.toLatin1().constData());
2014 * Check if visual themes are enabled (WinXP and later)
2016 bool lamexp_themes_enabled(void)
2018 typedef int (WINAPI *IsAppThemedFun)(void);
2020 static bool isAppThemed = false;
2021 static bool isAppThemed_initialized = false;
2023 if(!isAppThemed_initialized)
2025 IsAppThemedFun IsAppThemedPtr = NULL;
2026 QLibrary uxTheme(QString("%1/UxTheme.dll").arg(lamexp_known_folder(lamexp_folder_systemfolder)));
2029 IsAppThemedPtr = (IsAppThemedFun) uxTheme.resolve("IsAppThemed");
2033 isAppThemed = IsAppThemedPtr();
2036 qWarning("Theme support is disabled for this process!");
2039 isAppThemed_initialized = true;
2046 * Get number of free bytes on disk
2048 unsigned __int64 lamexp_free_diskspace(const QString &path, bool *ok)
2050 ULARGE_INTEGER freeBytesAvailable, totalNumberOfBytes, totalNumberOfFreeBytes;
2051 if(GetDiskFreeSpaceExW(reinterpret_cast<const wchar_t*>(QDir::toNativeSeparators(path).utf16()), &freeBytesAvailable, &totalNumberOfBytes, &totalNumberOfFreeBytes))
2054 return freeBytesAvailable.QuadPart;
2064 * Check if computer does support hibernation
2066 bool lamexp_is_hibernation_supported(void)
2068 bool hibernationSupported = false;
2070 SYSTEM_POWER_CAPABILITIES pwrCaps;
2071 SecureZeroMemory(&pwrCaps, sizeof(SYSTEM_POWER_CAPABILITIES));
2073 if(GetPwrCapabilities(&pwrCaps))
2075 hibernationSupported = pwrCaps.SystemS4 && pwrCaps.HiberFilePresent;
2078 return hibernationSupported;
2082 * Shutdown the computer
2084 bool lamexp_shutdown_computer(const QString &message, const unsigned long timeout, const bool forceShutdown, const bool hibernate)
2086 HANDLE hToken = NULL;
2088 if(OpenProcessToken(GetCurrentProcess(), TOKEN_ADJUST_PRIVILEGES | TOKEN_QUERY, &hToken))
2090 TOKEN_PRIVILEGES privileges;
2091 memset(&privileges, 0, sizeof(TOKEN_PRIVILEGES));
2092 privileges.PrivilegeCount = 1;
2093 privileges.Privileges[0].Attributes = SE_PRIVILEGE_ENABLED;
2095 if(LookupPrivilegeValue(NULL, SE_SHUTDOWN_NAME, &privileges.Privileges[0].Luid))
2097 if(AdjustTokenPrivileges(hToken, FALSE, &privileges, NULL, NULL, NULL))
2101 if(SetSuspendState(TRUE, TRUE, TRUE))
2106 const DWORD reason = SHTDN_REASON_MAJOR_APPLICATION | SHTDN_REASON_FLAG_PLANNED;
2107 return InitiateSystemShutdownEx(NULL, const_cast<wchar_t*>(QWCHAR(message)), timeout, forceShutdown ? TRUE : FALSE, FALSE, reason);
2116 * Make a window blink (to draw user's attention)
2118 void lamexp_blink_window(QWidget *poWindow, unsigned int count, unsigned int delay)
2120 static QMutex blinkMutex;
2122 const double maxOpac = 1.0;
2123 const double minOpac = 0.3;
2124 const double delOpac = 0.1;
2126 if(!blinkMutex.tryLock())
2128 qWarning("Blinking is already in progress, skipping!");
2134 const int steps = static_cast<int>(ceil(maxOpac - minOpac) / delOpac);
2135 const int sleep = static_cast<int>(floor(static_cast<double>(delay) / static_cast<double>(steps)));
2136 const double opacity = poWindow->windowOpacity();
2138 for(unsigned int i = 0; i < count; i++)
2140 for(double x = maxOpac; x >= minOpac; x -= delOpac)
2142 poWindow->setWindowOpacity(x);
2143 QApplication::processEvents();
2147 for(double x = minOpac; x <= maxOpac; x += delOpac)
2149 poWindow->setWindowOpacity(x);
2150 QApplication::processEvents();
2155 poWindow->setWindowOpacity(opacity);
2156 QApplication::processEvents();
2157 blinkMutex.unlock();
2161 blinkMutex.unlock();
2162 qWarning("Exception error while blinking!");
2167 * Remove forbidden characters from a filename
2169 const QString lamexp_clean_filename(const QString &str)
2171 QString newStr(str);
2173 newStr.replace("\\", "-");
2174 newStr.replace(" / ", ", ");
2175 newStr.replace("/", ",");
2176 newStr.replace(":", "-");
2177 newStr.replace("*", "x");
2178 newStr.replace("?", "");
2179 newStr.replace("<", "[");
2180 newStr.replace(">", "]");
2181 newStr.replace("|", "!");
2183 return newStr.simplified();
2187 * Remove forbidden characters from a file path
2189 const QString lamexp_clean_filepath(const QString &str)
2191 QStringList parts = QString(str).replace("\\", "/").split("/");
2193 for(int i = 0; i < parts.count(); i++)
2195 parts[i] = lamexp_clean_filename(parts[i]);
2198 return parts.join("/");
2202 * Get a list of all available Qt Text Codecs
2204 QStringList lamexp_available_codepages(bool noAliases)
2206 QStringList codecList;
2208 QList<QByteArray> availableCodecs = QTextCodec::availableCodecs();
2209 while(!availableCodecs.isEmpty())
2211 QByteArray current = availableCodecs.takeFirst();
2212 if(!(current.startsWith("system") || current.startsWith("System")))
2214 codecList << QString::fromLatin1(current.constData(), current.size());
2217 if(QTextCodec *currentCodec = QTextCodec::codecForName(current.constData()))
2220 QList<QByteArray> aliases = currentCodec->aliases();
2221 while(!aliases.isEmpty()) availableCodecs.removeAll(aliases.takeFirst());
2231 * Robert Jenkins' 96 bit Mix Function
2232 * Source: http://www.concentric.net/~Ttwang/tech/inthash.htm
2234 static unsigned int lamexp_mix(const unsigned int x, const unsigned int y, const unsigned int z)
2240 a=a-b; a=a-c; a=a^(c >> 13);
2241 b=b-c; b=b-a; b=b^(a << 8);
2242 c=c-a; c=c-b; c=c^(b >> 13);
2243 a=a-b; a=a-c; a=a^(c >> 12);
2244 b=b-c; b=b-a; b=b^(a << 16);
2245 c=c-a; c=c-b; c=c^(b >> 5);
2246 a=a-b; a=a-c; a=a^(c >> 3);
2247 b=b-c; b=b-a; b=b^(a << 10);
2248 c=c-a; c=c-b; c=c^(b >> 15);
2254 * Seeds the random number generator
2255 * Note: Altough rand_s() doesn't need a seed, this must be called pripr to lamexp_rand(), just to to be sure!
2257 void lamexp_seed_rand(void)
2259 qsrand(lamexp_mix(clock(), time(NULL), _getpid()));
2263 * Returns a randum number
2264 * Note: This function uses rand_s() if available, but falls back to qrand() otherwise
2266 unsigned int lamexp_rand(void)
2268 unsigned int rnd = 0;
2269 if(const lamexp_os_version_t* osVer = lamexp_get_os_version())
2271 if(LAMEXP_MIN_OS_VER(osVer, 5, 1))
2273 if(rand_s(&rnd) == 0)
2279 for(size_t i = 0; i < sizeof(unsigned int); i++)
2281 rnd = (rnd << 8) ^ qrand();
2287 * Entry point checks
2289 static DWORD lamexp_entry_check(void);
2290 static DWORD g_lamexp_entry_check_result = lamexp_entry_check();
2291 static DWORD g_lamexp_entry_check_flag = 0x789E09B2;
2292 static DWORD lamexp_entry_check(void)
2294 volatile DWORD retVal = 0xA199B5AF;
2295 if(g_lamexp_entry_check_flag != 0x8761F64D)
2297 FatalAppExit(0, L"Application initialization has failed, take care!");
2298 TerminateProcess(GetCurrentProcess(), -1);
2304 * Application entry point (runs before static initializers)
2308 int WinMainCRTStartup(void);
2310 int lamexp_entry_point(void)
2312 if((!LAMEXP_DEBUG) && lamexp_check_for_debugger())
2314 FatalAppExit(0, L"Not a debug build. Please unload debugger and try again!");
2315 TerminateProcess(GetCurrentProcess(), -1);
2318 if(g_lamexp_entry_check_flag != 0x789E09B2)
2320 FatalAppExit(0, L"Application initialization has failed, take care!");
2321 TerminateProcess(GetCurrentProcess(), -1);
2324 //Zero *before* constructors are called
2325 LAMEXP_ZERO_MEMORY(g_lamexp_argv);
2326 LAMEXP_ZERO_MEMORY(g_lamexp_tools);
2327 LAMEXP_ZERO_MEMORY(g_lamexp_currentTranslator);
2328 LAMEXP_ZERO_MEMORY(g_lamexp_translation);
2329 LAMEXP_ZERO_MEMORY(g_lamexp_folder);
2330 LAMEXP_ZERO_MEMORY(g_lamexp_ipc_ptr);
2331 LAMEXP_ZERO_MEMORY(g_lamexp_os_version);
2333 //Make sure we will pass the check
2334 g_lamexp_entry_check_flag = ~g_lamexp_entry_check_flag;
2336 //Now initialize the C Runtime library!
2337 return WinMainCRTStartup();
2342 * Finalization function (final clean-up)
2344 void lamexp_finalization(void)
2346 qDebug("lamexp_finalization()");
2349 if(g_lamexp_tools.registry)
2351 QStringList keys = g_lamexp_tools.registry->keys();
2352 for(int i = 0; i < keys.count(); i++)
2354 LAMEXP_DELETE((*g_lamexp_tools.registry)[keys.at(i)]);
2356 LAMEXP_DELETE(g_lamexp_tools.registry);
2357 LAMEXP_DELETE(g_lamexp_tools.versions);
2360 //Delete temporary files
2361 if(g_lamexp_folder.temp)
2363 if(!g_lamexp_folder.temp->isEmpty())
2365 for(int i = 0; i < 100; i++)
2367 if(lamexp_clean_folder(*g_lamexp_folder.temp))
2374 LAMEXP_DELETE(g_lamexp_folder.temp);
2377 //Clear folder cache
2378 LAMEXP_DELETE(g_lamexp_folder.knownFolders);
2381 if(g_lamexp_currentTranslator.instance)
2383 QApplication::removeTranslator(g_lamexp_currentTranslator.instance);
2384 LAMEXP_DELETE(g_lamexp_currentTranslator.instance);
2386 LAMEXP_DELETE(g_lamexp_translation.files);
2387 LAMEXP_DELETE(g_lamexp_translation.names);
2388 LAMEXP_DELETE(g_lamexp_translation.cntry);
2389 LAMEXP_DELETE(g_lamexp_translation.sysid);
2391 //Destroy Qt application object
2392 QApplication *application = dynamic_cast<QApplication*>(QApplication::instance());
2393 LAMEXP_DELETE(application);
2395 //Detach from shared memory
2396 if(g_lamexp_ipc_ptr.sharedmem) g_lamexp_ipc_ptr.sharedmem->detach();
2397 LAMEXP_DELETE(g_lamexp_ipc_ptr.sharedmem);
2398 LAMEXP_DELETE(g_lamexp_ipc_ptr.semaphore_read);
2399 LAMEXP_DELETE(g_lamexp_ipc_ptr.semaphore_write);
2400 LAMEXP_DELETE(g_lamexp_ipc_ptr.semaphore_read_mutex);
2401 LAMEXP_DELETE(g_lamexp_ipc_ptr.semaphore_write_mutex);
2403 //Free STDOUT and STDERR buffers
2404 if(g_lamexp_console_attached)
2406 if(std::filebuf *tmp = dynamic_cast<std::filebuf*>(std::cout.rdbuf()))
2408 std::cout.rdbuf(NULL);
2411 if(std::filebuf *tmp = dynamic_cast<std::filebuf*>(std::cerr.rdbuf()))
2413 std::cerr.rdbuf(NULL);
2419 if(g_lamexp_log_file)
2421 fclose(g_lamexp_log_file);
2422 g_lamexp_log_file = NULL;
2425 //Free CLI Arguments
2426 LAMEXP_DELETE(g_lamexp_argv.list);
2430 * Initialize debug thread
2432 static const HANDLE g_debug_thread = LAMEXP_DEBUG ? NULL : lamexp_debug_thread_init();
2435 * Get number private bytes [debug only]
2437 SIZE_T lamexp_dbg_private_bytes(void)
2440 PROCESS_MEMORY_COUNTERS_EX memoryCounters;
2441 memoryCounters.cb = sizeof(PROCESS_MEMORY_COUNTERS_EX);
2442 GetProcessMemoryInfo(GetCurrentProcess(), (PPROCESS_MEMORY_COUNTERS) &memoryCounters, sizeof(PROCESS_MEMORY_COUNTERS_EX));
2443 return memoryCounters.PrivateUsage;
2445 throw "Cannot call this function in a non-debug build!";
2446 #endif //LAMEXP_DEBUG