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>
54 #include "LockedFile.h"
78 //Initialize static Qt plugins
80 #if QT_VERSION < QT_VERSION_CHECK(5,0,0)
84 Q_IMPORT_PLUGIN(QWindowsIntegrationPlugin)
85 Q_IMPORT_PLUGIN(QICOPlugin)
89 #define LAMEXP_ZERO_MEMORY(X) SecureZeroMemory(&X, sizeof(X))
91 ///////////////////////////////////////////////////////////////////////////////
93 ///////////////////////////////////////////////////////////////////////////////
95 static const size_t g_lamexp_ipc_slots = 128;
100 unsigned int reserved_1;
101 unsigned int reserved_2;
102 char parameter[4096];
108 unsigned int pos_write;
109 unsigned int pos_read;
110 lamexp_ipc_data_t data[g_lamexp_ipc_slots];
114 ///////////////////////////////////////////////////////////////////////////////
116 ///////////////////////////////////////////////////////////////////////////////
121 unsigned int ver_major;
122 unsigned int ver_minor;
123 unsigned int ver_build;
124 char *ver_release_name;
135 static QDate g_lamexp_version_date;
136 static const char *g_lamexp_months[] = {"Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"};
137 static const char *g_lamexp_version_raw_date = __DATE__;
138 static const char *g_lamexp_version_raw_time = __TIME__;
140 //Console attached flag
141 static bool g_lamexp_console_attached = false;
144 //The following code was borrowed from MPC-HC project: http://mpc-hc.sf.net/
145 #if defined(__INTEL_COMPILER)
146 #if (__INTEL_COMPILER >= 1200)
147 static const char *g_lamexp_version_compiler = "ICL 12.x";
148 #elif (__INTEL_COMPILER >= 1100)
149 static const char *g_lamexp_version_compiler = "ICL 11.x";
150 #elif (__INTEL_COMPILER >= 1000)
151 static const char *g_lamexp_version_compiler = "ICL 10.x";
153 #error Compiler is not supported!
155 #elif defined(_MSC_VER)
156 #if (_MSC_VER == 1700)
157 #if (_MSC_FULL_VER < 170050727)
158 static const char *g_lamexp_version_compiler = "MSVC 2012-Beta";
160 static const char *g_lamexp_version_compiler = "MSVC 2012";
162 #elif (_MSC_VER == 1600)
163 #if (_MSC_FULL_VER >= 160040219)
164 static const char *g_lamexp_version_compiler = "MSVC 2010-SP1";
166 static const char *g_lamexp_version_compiler = "MSVC 2010";
168 #elif (_MSC_VER == 1500)
169 #if (_MSC_FULL_VER >= 150030729)
170 static const char *g_lamexp_version_compiler = "MSVC 2008-SP1";
172 static const char *g_lamexp_version_compiler = "MSVC 2008";
175 #error Compiler is not supported!
178 // Note: /arch:SSE and /arch:SSE2 are only available for the x86 platform
179 #if !defined(_M_X64) && defined(_M_IX86_FP)
180 #if (_M_IX86_FP == 1)
181 LAMEXP_COMPILER_WARNING("SSE instruction set is enabled!")
182 #elif (_M_IX86_FP == 2)
183 LAMEXP_COMPILER_WARNING("SSE2 instruction set is enabled!")
187 #error Compiler is not supported!
190 //Architecture detection
192 static const char *g_lamexp_version_arch = "x64";
193 #elif defined(_M_IX86)
194 static const char *g_lamexp_version_arch = "x86";
196 #error Architecture is not supported!
199 //Official web-site URL
200 static const char *g_lamexp_website_url = "http://lamexp.sourceforge.net/";
201 static const char *g_lamexp_support_url = "http://forum.doom9.org/showthread.php?t=157726";
203 //Tool versions (expected versions!)
204 static const unsigned int g_lamexp_toolver_neroaac = VER_LAMEXP_TOOL_NEROAAC;
205 static const unsigned int g_lamexp_toolver_fhgaacenc = VER_LAMEXP_TOOL_FHGAACENC;
206 static const unsigned int g_lamexp_toolver_qaacenc = VER_LAMEXP_TOOL_QAAC;
207 static const unsigned int g_lamexp_toolver_coreaudio = VER_LAMEXP_TOOL_COREAUDIO;
213 QMap<size_t, QString> *knownFolders;
221 QMap<QString, LockedFile*> *registry;
222 QMap<QString, unsigned int> *versions;
230 QMap<QString, QString> *files;
231 QMap<QString, QString> *names;
232 QMap<QString, unsigned int> *sysid;
233 QMap<QString, unsigned int> *cntry;
236 g_lamexp_translation;
241 QTranslator *instance;
244 g_lamexp_currentTranslator;
258 lamexp_os_version_t version;
267 char *semaphore_read;
268 char *semaphore_read_mutex;
269 char *semaphore_write;
270 char *semaphore_write_mutex;
274 "{21A68A42-6923-43bb-9CF6-64BF151942EE}",
275 "{7A605549-F58C-4d78-B4E5-06EFC34F405B}",
276 "{60AA8D04-F6B8-497d-81EB-0F600F4A65B5}",
277 "{726061D5-1615-4B82-871C-75FD93458E46}",
278 "{1A616023-AA6A-4519-8AF3-F7736E899977}"
282 QSharedMemory *sharedmem;
283 QSystemSemaphore *semaphore_read;
284 QSystemSemaphore *semaphore_read_mutex;
285 QSystemSemaphore *semaphore_write;
286 QSystemSemaphore *semaphore_write_mutex;
292 static const char *g_lamexp_imageformats[] = {"bmp", "png", "jpg", "gif", "ico", "xpm", NULL}; //"svg"
295 static QMutex g_lamexp_message_mutex;
298 static const DWORD g_main_thread_id = GetCurrentThreadId();
301 static FILE *g_lamexp_log_file = NULL;
303 ///////////////////////////////////////////////////////////////////////////////
305 ///////////////////////////////////////////////////////////////////////////////
310 unsigned int lamexp_version_major(void) { return g_lamexp_version.ver_major; }
311 unsigned int lamexp_version_minor(void) { return g_lamexp_version.ver_minor; }
312 unsigned int lamexp_version_build(void) { return g_lamexp_version.ver_build; }
313 const char *lamexp_version_release(void) { return g_lamexp_version.ver_release_name; }
314 const char *lamexp_version_time(void) { return g_lamexp_version_raw_time; }
315 const char *lamexp_version_compiler(void) { return g_lamexp_version_compiler; }
316 const char *lamexp_version_arch(void) { return g_lamexp_version_arch; }
317 unsigned int lamexp_toolver_neroaac(void) { return g_lamexp_toolver_neroaac; }
318 unsigned int lamexp_toolver_fhgaacenc(void) { return g_lamexp_toolver_fhgaacenc; }
319 unsigned int lamexp_toolver_qaacenc(void) { return g_lamexp_toolver_qaacenc; }
320 unsigned int lamexp_toolver_coreaudio(void) { return g_lamexp_toolver_coreaudio; }
325 const char *lamexp_website_url(void) { return g_lamexp_website_url; }
326 const char *lamexp_support_url(void) { return g_lamexp_support_url; }
329 * Check for Demo (pre-release) version
331 bool lamexp_version_demo(void)
334 bool releaseVersion = false;
335 if(!strncpy_s(buffer, 128, g_lamexp_version.ver_release_name, _TRUNCATE))
337 char *context, *prefix = strtok_s(buffer, "-,; ", &context);
340 releaseVersion = (!_stricmp(prefix, "Final")) || (!_stricmp(prefix, "Hotfix"));
343 return LAMEXP_DEBUG || (!releaseVersion);
347 * Calculate expiration date
349 QDate lamexp_version_expires(void)
351 return lamexp_version_date().addDays(LAMEXP_DEBUG ? 7 : 30);
355 * Get build date date
357 const QDate &lamexp_version_date(void)
359 if(!g_lamexp_version_date.isValid())
361 int date[3] = {0, 0, 0}; char temp[12] = {'\0'};
362 strncpy_s(temp, 12, g_lamexp_version_raw_date, _TRUNCATE);
364 if(strlen(temp) == 11)
366 temp[3] = temp[6] = '\0';
367 date[2] = atoi(&temp[4]);
368 date[0] = atoi(&temp[7]);
370 for(int j = 0; j < 12; j++)
372 if(!_strcmpi(&temp[0], g_lamexp_months[j]))
379 g_lamexp_version_date = QDate(date[0], date[1], date[2]);
382 if(!g_lamexp_version_date.isValid())
384 qFatal("Internal error: Date format could not be recognized!");
388 return g_lamexp_version_date;
392 * Get the native operating system version
394 const lamexp_os_version_t *lamexp_get_os_version(void)
396 QReadLocker readLock(&g_lamexp_os_version.lock);
398 //Already initialized?
399 if(g_lamexp_os_version.bInitialized)
401 return &g_lamexp_os_version.version;
405 QWriteLocker writeLock(&g_lamexp_os_version.lock);
408 if(!g_lamexp_os_version.bInitialized)
410 OSVERSIONINFO osVerInfo;
411 memset(&osVerInfo, 0, sizeof(OSVERSIONINFO));
412 osVerInfo.dwOSVersionInfoSize = sizeof(OSVERSIONINFO);
414 if(GetVersionEx(&osVerInfo) == TRUE)
416 if(osVerInfo.dwPlatformId == VER_PLATFORM_WIN32_NT)
418 g_lamexp_os_version.version.versionMajor = osVerInfo.dwMajorVersion;
419 g_lamexp_os_version.version.versionMinor = osVerInfo.dwMinorVersion;
423 qWarning("lamexp_get_os_version: Not running under Windows NT, this is not supposed to happen!");
424 g_lamexp_os_version.version.versionMajor = 0;
425 g_lamexp_os_version.version.versionMinor = 0;
430 throw "GetVersionEx() has failed. This is not supposed to happen!";
433 g_lamexp_os_version.bInitialized = true;
436 return &g_lamexp_os_version.version;
440 * Check if we are running under wine
442 bool lamexp_detect_wine(void)
444 static bool isWine = false;
445 static bool isWine_initialized = false;
447 if(!isWine_initialized)
449 QLibrary ntdll("ntdll.dll");
452 if(ntdll.resolve("wine_nt_to_unix_file_name") != NULL) isWine = true;
453 if(ntdll.resolve("wine_get_version") != NULL) isWine = true;
456 isWine_initialized = true;
463 * Global exception handler
465 LONG WINAPI lamexp_exception_handler(__in struct _EXCEPTION_POINTERS *ExceptionInfo)
467 if(GetCurrentThreadId() != g_main_thread_id)
469 HANDLE mainThread = OpenThread(THREAD_TERMINATE, FALSE, g_main_thread_id);
470 if(mainThread) TerminateThread(mainThread, ULONG_MAX);
473 FatalAppExit(0, L"Unhandeled exception handler invoked, application will exit!");
474 TerminateProcess(GetCurrentProcess(), -1);
479 * Invalid parameters handler
481 void lamexp_invalid_param_handler(const wchar_t* exp, const wchar_t* fun, const wchar_t* fil, unsigned int, uintptr_t)
483 if(GetCurrentThreadId() != g_main_thread_id)
485 HANDLE mainThread = OpenThread(THREAD_TERMINATE, FALSE, g_main_thread_id);
486 if(mainThread) TerminateThread(mainThread, ULONG_MAX);
490 FatalAppExit(0, L"Invalid parameter handler invoked, application will exit!");
491 TerminateProcess(GetCurrentProcess(), -1);
495 * Change console text color
497 static void lamexp_console_color(FILE* file, WORD attributes)
499 const HANDLE hConsole = (HANDLE)(_get_osfhandle(_fileno(file)));
500 if((hConsole != NULL) && (hConsole != INVALID_HANDLE_VALUE))
502 SetConsoleTextAttribute(hConsole, attributes);
509 void lamexp_message_handler(QtMsgType type, const char *msg)
511 static const char *GURU_MEDITATION = "\n\nGURU MEDITATION !!!\n\n";
513 QMutexLocker lock(&g_lamexp_message_mutex);
515 if(g_lamexp_log_file)
517 static char prefix[] = "DWCF";
518 int index = qBound(0, static_cast<int>(type), 3);
519 unsigned int timestamp = static_cast<unsigned int>(_time64(NULL) % 3600I64);
520 QString str = QString::fromUtf8(msg).trimmed().replace('\n', '\t');
521 fprintf(g_lamexp_log_file, "[%c][%04u] %s\r\n", prefix[index], timestamp, str.toUtf8().constData());
522 fflush(g_lamexp_log_file);
525 if(g_lamexp_console_attached)
527 UINT oldOutputCP = GetConsoleOutputCP();
528 if(oldOutputCP != CP_UTF8) SetConsoleOutputCP(CP_UTF8);
536 lamexp_console_color(stderr, FOREGROUND_RED | FOREGROUND_INTENSITY);
537 fprintf(stderr, GURU_MEDITATION);
538 fprintf(stderr, "%s\n", msg);
542 lamexp_console_color(stderr, FOREGROUND_GREEN | FOREGROUND_RED | FOREGROUND_INTENSITY);
543 fprintf(stderr, "%s\n", msg);
547 lamexp_console_color(stderr, FOREGROUND_BLUE | FOREGROUND_GREEN | FOREGROUND_RED | FOREGROUND_INTENSITY);
548 fprintf(stderr, "%s\n", msg);
553 lamexp_console_color(stderr, FOREGROUND_BLUE | FOREGROUND_GREEN | FOREGROUND_RED);
554 if(oldOutputCP != CP_UTF8) SetConsoleOutputCP(oldOutputCP);
558 QString temp("[LameXP][%1] %2");
564 temp = temp.arg("C", QString::fromUtf8(msg));
567 temp = temp.arg("W", QString::fromUtf8(msg));
570 temp = temp.arg("I", QString::fromUtf8(msg));
574 temp.replace("\n", "\t").append("\n");
575 OutputDebugStringA(temp.toLatin1().constData());
578 if(type == QtCriticalMsg || type == QtFatalMsg)
582 if(GetCurrentThreadId() != g_main_thread_id)
584 HANDLE mainThread = OpenThread(THREAD_TERMINATE, FALSE, g_main_thread_id);
585 if(mainThread) TerminateThread(mainThread, ULONG_MAX);
588 MessageBoxW(NULL, QWCHAR(QString::fromUtf8(msg)), L"LameXP - GURU MEDITATION", MB_ICONERROR | MB_TOPMOST | MB_TASKMODAL);
589 FatalAppExit(0, L"The application has encountered a critical error and will exit now!");
590 TerminateProcess(GetCurrentProcess(), -1);
595 * Initialize the console
597 void lamexp_init_console(const QStringList &argv)
599 bool enableConsole = lamexp_version_demo();
603 wchar_t *logfile = NULL;
604 size_t logfile_len = 0;
605 if(!_wdupenv_s(&logfile, &logfile_len, L"LAMEXP_LOGFILE"))
607 if(logfile && (logfile_len > 0))
610 if(!_wfopen_s(&temp, logfile, L"wb"))
612 fprintf(temp, "%c%c%c", 0xEF, 0xBB, 0xBF);
613 g_lamexp_log_file = temp;
622 for(int i = 0; i < argv.count(); i++)
624 if(!argv.at(i).compare("--console", Qt::CaseInsensitive))
626 enableConsole = true;
628 else if(!argv.at(i).compare("--no-console", Qt::CaseInsensitive))
630 enableConsole = false;
637 if(!g_lamexp_console_attached)
639 if(AllocConsole() != FALSE)
641 SetConsoleCtrlHandler(NULL, TRUE);
642 SetConsoleTitle(L"LameXP - Audio Encoder Front-End | Debug Console");
643 SetConsoleOutputCP(CP_UTF8);
644 g_lamexp_console_attached = true;
648 if(g_lamexp_console_attached)
650 //-------------------------------------------------------------------
651 //See: http://support.microsoft.com/default.aspx?scid=kb;en-us;105305
652 //-------------------------------------------------------------------
653 const int flags = _O_WRONLY | _O_U8TEXT;
654 int hCrtStdOut = _open_osfhandle((intptr_t) GetStdHandle(STD_OUTPUT_HANDLE), flags);
655 int hCrtStdErr = _open_osfhandle((intptr_t) GetStdHandle(STD_ERROR_HANDLE), flags);
656 FILE *hfStdOut = (hCrtStdOut >= 0) ? _fdopen(hCrtStdOut, "wb") : NULL;
657 FILE *hfStdErr = (hCrtStdErr >= 0) ? _fdopen(hCrtStdErr, "wb") : NULL;
658 if(hfStdOut) { *stdout = *hfStdOut; std::cout.rdbuf(new std::filebuf(hfStdOut)); }
659 if(hfStdErr) { *stderr = *hfStdErr; std::cerr.rdbuf(new std::filebuf(hfStdErr)); }
662 HWND hwndConsole = GetConsoleWindow();
664 if((hwndConsole != NULL) && (hwndConsole != INVALID_HANDLE_VALUE))
666 HMENU hMenu = GetSystemMenu(hwndConsole, 0);
667 EnableMenuItem(hMenu, SC_CLOSE, MF_BYCOMMAND | MF_GRAYED);
668 RemoveMenu(hMenu, SC_CLOSE, MF_BYCOMMAND);
670 SetWindowPos(hwndConsole, HWND_TOP, 0, 0, 0, 0, SWP_NOMOVE|SWP_NOSIZE|SWP_NOZORDER|SWP_FRAMECHANGED);
671 SetWindowLong(hwndConsole, GWL_STYLE, GetWindowLong(hwndConsole, GWL_STYLE) & (~WS_MAXIMIZEBOX) & (~WS_MINIMIZEBOX));
672 SetWindowPos(hwndConsole, HWND_TOP, 0, 0, 0, 0, SWP_NOMOVE|SWP_NOSIZE|SWP_NOZORDER|SWP_FRAMECHANGED);
678 * Detect CPU features
680 lamexp_cpu_t lamexp_detect_cpu_features(const QStringList &argv)
682 typedef BOOL (WINAPI *IsWow64ProcessFun)(__in HANDLE hProcess, __out PBOOL Wow64Process);
683 typedef VOID (WINAPI *GetNativeSystemInfoFun)(__out LPSYSTEM_INFO lpSystemInfo);
685 static IsWow64ProcessFun IsWow64ProcessPtr = NULL;
686 static GetNativeSystemInfoFun GetNativeSystemInfoPtr = NULL;
688 lamexp_cpu_t features;
689 SYSTEM_INFO systemInfo;
690 int CPUInfo[4] = {-1};
691 char CPUIdentificationString[0x40];
692 char CPUBrandString[0x40];
694 memset(&features, 0, sizeof(lamexp_cpu_t));
695 memset(&systemInfo, 0, sizeof(SYSTEM_INFO));
696 memset(CPUIdentificationString, 0, sizeof(CPUIdentificationString));
697 memset(CPUBrandString, 0, sizeof(CPUBrandString));
700 memcpy(CPUIdentificationString, &CPUInfo[1], sizeof(int));
701 memcpy(CPUIdentificationString + 4, &CPUInfo[3], sizeof(int));
702 memcpy(CPUIdentificationString + 8, &CPUInfo[2], sizeof(int));
703 features.intel = (_stricmp(CPUIdentificationString, "GenuineIntel") == 0);
704 strncpy_s(features.vendor, 0x40, CPUIdentificationString, _TRUNCATE);
709 features.mmx = (CPUInfo[3] & 0x800000) || false;
710 features.sse = (CPUInfo[3] & 0x2000000) || false;
711 features.sse2 = (CPUInfo[3] & 0x4000000) || false;
712 features.ssse3 = (CPUInfo[2] & 0x200) || false;
713 features.sse3 = (CPUInfo[2] & 0x1) || false;
714 features.ssse3 = (CPUInfo[2] & 0x200) || false;
715 features.stepping = CPUInfo[0] & 0xf;
716 features.model = ((CPUInfo[0] >> 4) & 0xf) + (((CPUInfo[0] >> 16) & 0xf) << 4);
717 features.family = ((CPUInfo[0] >> 8) & 0xf) + ((CPUInfo[0] >> 20) & 0xff);
720 __cpuid(CPUInfo, 0x80000000);
721 int nExIds = qMax<int>(qMin<int>(CPUInfo[0], 0x80000004), 0x80000000);
723 for(int i = 0x80000002; i <= nExIds; ++i)
729 memcpy(CPUBrandString, CPUInfo, sizeof(CPUInfo));
732 memcpy(CPUBrandString + 16, CPUInfo, sizeof(CPUInfo));
735 memcpy(CPUBrandString + 32, CPUInfo, sizeof(CPUInfo));
740 strncpy_s(features.brand, 0x40, CPUBrandString, _TRUNCATE);
742 if(strlen(features.brand) < 1) strncpy_s(features.brand, 0x40, "Unknown", _TRUNCATE);
743 if(strlen(features.vendor) < 1) strncpy_s(features.vendor, 0x40, "Unknown", _TRUNCATE);
745 #if !defined(_M_X64 ) && !defined(_M_IA64)
746 if(!IsWow64ProcessPtr || !GetNativeSystemInfoPtr)
748 QLibrary Kernel32Lib("kernel32.dll");
749 IsWow64ProcessPtr = (IsWow64ProcessFun) Kernel32Lib.resolve("IsWow64Process");
750 GetNativeSystemInfoPtr = (GetNativeSystemInfoFun) Kernel32Lib.resolve("GetNativeSystemInfo");
752 if(IsWow64ProcessPtr)
755 if(IsWow64ProcessPtr(GetCurrentProcess(), &x64))
760 if(GetNativeSystemInfoPtr)
762 GetNativeSystemInfoPtr(&systemInfo);
766 GetSystemInfo(&systemInfo);
768 features.count = qBound(1UL, systemInfo.dwNumberOfProcessors, 64UL);
770 GetNativeSystemInfo(&systemInfo);
771 features.count = systemInfo.dwNumberOfProcessors;
778 for(int i = 0; i < argv.count(); i++)
780 if(!argv[i].compare("--force-cpu-no-64bit", Qt::CaseInsensitive)) { flag = true; features.x64 = false; }
781 if(!argv[i].compare("--force-cpu-no-sse", Qt::CaseInsensitive)) { flag = true; features.sse = features.sse2 = features.sse3 = features.ssse3 = false; }
782 if(!argv[i].compare("--force-cpu-no-intel", Qt::CaseInsensitive)) { flag = true; features.intel = false; }
784 if(flag) qWarning("CPU flags overwritten by user-defined parameters. Take care!\n");
791 * Check for debugger (detect routine)
793 static __forceinline bool lamexp_check_for_debugger(void)
795 if(IsDebuggerPresent())
802 CloseHandle((HANDLE) 0x7FFFFFFF);
804 __except(EXCEPTION_EXECUTE_HANDLER)
813 __except(EXCEPTION_EXECUTE_HANDLER)
822 * Check for debugger (thread proc)
824 static unsigned int __stdcall lamexp_debug_thread_proc(LPVOID lpParameter)
826 while(!lamexp_check_for_debugger())
830 if(HANDLE thrd = OpenThread(THREAD_TERMINATE, FALSE, g_main_thread_id))
832 if(TerminateThread(thrd, -1))
834 FatalAppExit(0, L"Not a debug build. Please unload debugger and try again!");
838 TerminateProcess(GetCurrentProcess(), -1);
843 * Check for debugger (startup routine)
845 static HANDLE lamexp_debug_thread_init(void)
847 if(lamexp_check_for_debugger())
849 FatalAppExit(0, L"Not a debug build. Please unload debugger and try again!");
850 TerminateProcess(GetCurrentProcess(), -1);
853 return (HANDLE) _beginthreadex(NULL, 0, lamexp_debug_thread_proc, NULL, 0, NULL);
857 * Check for compatibility mode
859 static bool lamexp_check_compatibility_mode(const char *exportName, const QString &executableName)
861 QLibrary kernel32("kernel32.dll");
863 if((exportName != NULL) && kernel32.load())
865 if(kernel32.resolve(exportName) != NULL)
867 qWarning("Function '%s' exported from 'kernel32.dll' -> Windows compatibility mode!", exportName);
868 qFatal("%s", QApplication::tr("Executable '%1' doesn't support Windows compatibility mode.").arg(executableName).toLatin1().constData());
877 * Computus according to H. Lichtenberg
879 static bool lamexp_computus(const QDate &date)
884 int M = 15 + (3*K + 3) / 4 - (8*K + 13) / 25;
885 int D = (19*A + M) % 30;
886 int S = 2 - (3*K + 3) / 4;
887 int R = D / 29 + (D / 28 - D / 29) * (A / 11);
889 int SZ = 7 - (X + X / 4 + S) % 7;
890 int OE = 7 - (OG - SZ) % 7;
895 return (date.month() == 4) && (date.day() == (OS - 31));
899 return (date.month() == 3) && (date.day() == OS);
904 * Check for Thanksgiving
906 static bool lamexp_thanksgiving(const QDate &date)
910 switch(QDate(date.year(), 11, 1).dayOfWeek())
912 case 1: day = 25; break;
913 case 2: day = 24; break;
914 case 3: day = 23; break;
915 case 4: day = 22; break;
916 case 5: day = 28; break;
917 case 6: day = 27; break;
918 case 7: day = 26; break;
921 return (date.month() == 11) && (date.day() == day);
925 * Initialize app icon
927 QIcon lamexp_app_icon(const QDate *date, const QTime *time)
929 QDate currentDate = (date) ? QDate(*date) : QDate::currentDate();
930 QTime currentTime = (time) ? QTime(*time) : QTime::currentTime();
932 if(lamexp_thanksgiving(currentDate))
934 return QIcon(":/MainIcon6.png");
936 else if(((currentDate.month() == 12) && (currentDate.day() == 31) && (currentTime.hour() >= 20)) || ((currentDate.month() == 1) && (currentDate.day() == 1) && (currentTime.hour() <= 19)))
938 return QIcon(":/MainIcon5.png");
940 else if(((currentDate.month() == 10) && (currentDate.day() == 31) && (currentTime.hour() >= 12)) || ((currentDate.month() == 11) && (currentDate.day() == 1) && (currentTime.hour() <= 11)))
942 return QIcon(":/MainIcon4.png");
944 else if((currentDate.month() == 12) && (currentDate.day() >= 24) && (currentDate.day() <= 26))
946 return QIcon(":/MainIcon3.png");
948 else if(lamexp_computus(currentDate))
950 return QIcon(":/MainIcon2.png");
954 return QIcon(":/MainIcon1.png");
959 * Broadcast event to all windows
961 static bool lamexp_broadcast(int eventType, bool onlyToVisible)
963 if(QApplication *app = dynamic_cast<QApplication*>(QApplication::instance()))
965 qDebug("Broadcasting %d", eventType);
968 QEvent poEvent(static_cast<QEvent::Type>(eventType));
969 QWidgetList list = app->topLevelWidgets();
971 while(!list.isEmpty())
973 QWidget *widget = list.takeFirst();
974 if(!onlyToVisible || widget->isVisible())
976 if(!app->sendEvent(widget, &poEvent))
983 qDebug("Broadcast %d done (%s)", eventType, (allOk ? "OK" : "Stopped"));
988 qWarning("Broadcast failed, could not get QApplication instance!");
996 static bool lamexp_event_filter(void *message, long *result)
998 if((!(LAMEXP_DEBUG)) && lamexp_check_for_debugger())
1000 FatalAppExit(0, L"Not a debug build. Please unload debugger and try again!");
1001 TerminateProcess(GetCurrentProcess(), -1);
1004 switch(reinterpret_cast<MSG*>(message)->message)
1006 case WM_QUERYENDSESSION:
1007 qWarning("WM_QUERYENDSESSION message received!");
1008 *result = lamexp_broadcast(lamexp_event_queryendsession, false) ? TRUE : FALSE;
1011 qWarning("WM_ENDSESSION message received!");
1012 if(reinterpret_cast<MSG*>(message)->wParam == TRUE)
1014 lamexp_broadcast(lamexp_event_endsession, false);
1015 if(QApplication *app = reinterpret_cast<QApplication*>(QApplication::instance()))
1017 app->closeAllWindows();
1020 lamexp_finalization();
1026 /*ignore this message and let Qt handle it*/
1032 * Check for process elevation
1034 static bool lamexp_check_elevation(void)
1036 typedef enum { lamexp_token_elevationType_class = 18, lamexp_token_elevation_class = 20 } LAMEXP_TOKEN_INFORMATION_CLASS;
1037 typedef enum { lamexp_elevationType_default = 1, lamexp_elevationType_full, lamexp_elevationType_limited } LAMEXP_TOKEN_ELEVATION_TYPE;
1039 HANDLE hToken = NULL;
1040 bool bIsProcessElevated = false;
1042 if(OpenProcessToken(GetCurrentProcess(), TOKEN_QUERY, &hToken))
1044 LAMEXP_TOKEN_ELEVATION_TYPE tokenElevationType;
1046 if(GetTokenInformation(hToken, (TOKEN_INFORMATION_CLASS) lamexp_token_elevationType_class, &tokenElevationType, sizeof(LAMEXP_TOKEN_ELEVATION_TYPE), &returnLength))
1048 if(returnLength == sizeof(LAMEXP_TOKEN_ELEVATION_TYPE))
1050 switch(tokenElevationType)
1052 case lamexp_elevationType_default:
1053 qDebug("Process token elevation type: Default -> UAC is disabled.\n");
1055 case lamexp_elevationType_full:
1056 qWarning("Process token elevation type: Full -> potential security risk!\n");
1057 bIsProcessElevated = true;
1059 case lamexp_elevationType_limited:
1060 qDebug("Process token elevation type: Limited -> not elevated.\n");
1065 CloseHandle(hToken);
1069 qWarning("Failed to open process token!");
1072 return !bIsProcessElevated;
1076 * Initialize Qt framework
1078 bool lamexp_init_qt(int argc, char* argv[])
1080 static bool qt_initialized = false;
1081 typedef BOOL (WINAPI *SetDllDirectoryProc)(WCHAR *lpPathName);
1082 const QStringList &arguments = lamexp_arguments();
1084 //Don't initialized again, if done already
1090 //Secure DLL loading
1091 QLibrary kernel32("kernel32.dll");
1094 SetDllDirectoryProc pSetDllDirectory = (SetDllDirectoryProc) kernel32.resolve("SetDllDirectoryW");
1095 if(pSetDllDirectory != NULL) pSetDllDirectory(L"");
1099 //Extract executable name from argv[] array
1100 QString executableName = QLatin1String("LameXP.exe");
1101 if(arguments.count() > 0)
1103 static const char *delimiters = "\\/:?";
1104 executableName = arguments[0].trimmed();
1105 for(int i = 0; delimiters[i]; i++)
1107 int temp = executableName.lastIndexOf(QChar(delimiters[i]));
1108 if(temp >= 0) executableName = executableName.mid(temp + 1);
1110 executableName = executableName.trimmed();
1111 if(executableName.isEmpty())
1113 executableName = QLatin1String("LameXP.exe");
1119 qDebug("Using Qt v%s [%s], %s, %s", qVersion(), QLibraryInfo::buildDate().toString(Qt::ISODate).toLatin1().constData(), (qSharedBuild() ? "DLL" : "Static"), QLibraryInfo::buildKey().toLatin1().constData());
1120 qDebug("Compiled with Qt v%s [%s], %s\n", QT_VERSION_STR, QT_PACKAGEDATE_STR, QT_BUILD_KEY);
1121 if(_stricmp(qVersion(), QT_VERSION_STR))
1123 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());
1126 if(QLibraryInfo::buildKey().compare(QString::fromLatin1(QT_BUILD_KEY), Qt::CaseInsensitive))
1128 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());
1132 qDebug("Using Qt v%s [%s], %s", qVersion(), QLibraryInfo::buildDate().toString(Qt::ISODate).toLatin1().constData(), (qSharedBuild() ? "DLL" : "Static"));
1133 qDebug("Compiled with Qt v%s [%s]\n", QT_VERSION_STR, QT_PACKAGEDATE_STR);
1136 //Check the Windows version
1137 switch(QSysInfo::windowsVersion() & QSysInfo::WV_NT_based)
1140 case QSysInfo::WV_NT:
1141 qFatal("%s", QApplication::tr("Executable '%1' requires Windows 2000 or later.").arg(executableName).toLatin1().constData());
1143 case QSysInfo::WV_2000:
1144 qDebug("Running on Windows 2000 (not officially supported!).\n");
1145 lamexp_check_compatibility_mode("GetNativeSystemInfo", executableName);
1147 case QSysInfo::WV_XP:
1148 qDebug("Running on Windows XP.\n");
1149 lamexp_check_compatibility_mode("GetLargePageMinimum", executableName);
1151 case QSysInfo::WV_2003:
1152 qDebug("Running on Windows Server 2003 or Windows XP x64-Edition.\n");
1153 lamexp_check_compatibility_mode("GetLocaleInfoEx", executableName);
1155 case QSysInfo::WV_VISTA:
1156 qDebug("Running on Windows Vista or Windows Server 2008.\n");
1157 lamexp_check_compatibility_mode("CreateRemoteThreadEx", executableName);
1159 case QSysInfo::WV_WINDOWS7:
1160 qDebug("Running on Windows 7 or Windows Server 2008 R2.\n");
1161 lamexp_check_compatibility_mode("CreateFile2", executableName);
1165 const lamexp_os_version_t *osVersionNo = lamexp_get_os_version();
1166 if(osVersionNo->versionMajor < 5)
1168 qFatal("%s", QApplication::tr("Executable '%1' requires Windows 2000 or later.").arg(executableName).toLatin1().constData());
1170 else if(LAMEXP_EQL_OS_VER(osVersionNo, 6, 2))
1172 qDebug("Running on Windows 8 or Windows Server 2012\n");
1173 lamexp_check_compatibility_mode(NULL, executableName);
1177 qWarning("Running on an unknown/untested WinNT-based OS (v%u.%u).\n", osVersionNo->versionMajor, osVersionNo->versionMinor);
1184 if(lamexp_detect_wine())
1186 qWarning("It appears we are running under Wine, unexpected things might happen!\n");
1189 //Set text Codec for locale
1190 QTextCodec::setCodecForLocale(QTextCodec::codecForName("UTF-8"));
1192 //Create Qt application instance
1193 QApplication *application = new QApplication(argc, argv);
1195 //Load plugins from application directory
1196 QCoreApplication::setLibraryPaths(QStringList() << QApplication::applicationDirPath());
1197 qDebug("Library Path:\n%s\n", QApplication::libraryPaths().first().toUtf8().constData());
1199 //Set application properties
1200 application->setApplicationName("LameXP - Audio Encoder Front-End");
1201 application->setApplicationVersion(QString().sprintf("%d.%02d.%04d", lamexp_version_major(), lamexp_version_minor(), lamexp_version_build()));
1202 application->setOrganizationName("LoRd_MuldeR");
1203 application->setOrganizationDomain("mulder.at.gg");
1204 application->setWindowIcon(lamexp_app_icon());
1205 application->setEventFilter(lamexp_event_filter);
1207 //Check for supported image formats
1208 QList<QByteArray> supportedFormats = QImageReader::supportedImageFormats();
1209 for(int i = 0; g_lamexp_imageformats[i]; i++)
1211 if(!supportedFormats.contains(g_lamexp_imageformats[i]))
1213 qFatal("Qt initialization error: QImageIOHandler for '%s' missing!", g_lamexp_imageformats[i]);
1218 //Add default translations
1219 QWriteLocker writeLockTranslations(&g_lamexp_translation.lock);
1220 if(!g_lamexp_translation.files) g_lamexp_translation.files = new QMap<QString, QString>();
1221 if(!g_lamexp_translation.names) g_lamexp_translation.names = new QMap<QString, QString>();
1222 g_lamexp_translation.files->insert(LAMEXP_DEFAULT_LANGID, "");
1223 g_lamexp_translation.names->insert(LAMEXP_DEFAULT_LANGID, "English");
1224 writeLockTranslations.unlock();
1226 //Check for process elevation
1227 if((!lamexp_check_elevation()) && (!lamexp_detect_wine()))
1229 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);
1230 messageBox.addButton("Quit Program (Recommended)", QMessageBox::NoRole);
1231 messageBox.addButton("Ignore", QMessageBox::NoRole);
1232 if(messageBox.exec() == 0)
1238 //Update console icon, if a console is attached
1239 #if QT_VERSION < QT_VERSION_CHECK(5,0,0)
1240 if(g_lamexp_console_attached && (!lamexp_detect_wine()))
1242 typedef DWORD (__stdcall *SetConsoleIconFun)(HICON);
1243 QLibrary kernel32("kernel32.dll");
1246 SetConsoleIconFun SetConsoleIconPtr = (SetConsoleIconFun) kernel32.resolve("SetConsoleIcon");
1247 if(SetConsoleIconPtr != NULL) SetConsoleIconPtr(QIcon(":/icons/sound.png").pixmap(16, 16).toWinHICON());
1254 qt_initialized = true;
1261 int lamexp_init_ipc(void)
1263 QWriteLocker writeLock(&g_lamexp_ipc_ptr.lock);
1265 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)
1270 g_lamexp_ipc_ptr.semaphore_read = new QSystemSemaphore(QString(g_lamexp_ipc_uuid.semaphore_read), 0);
1271 g_lamexp_ipc_ptr.semaphore_write = new QSystemSemaphore(QString(g_lamexp_ipc_uuid.semaphore_write), 0);
1272 g_lamexp_ipc_ptr.semaphore_read_mutex = new QSystemSemaphore(QString(g_lamexp_ipc_uuid.semaphore_read_mutex), 0);
1273 g_lamexp_ipc_ptr.semaphore_write_mutex = new QSystemSemaphore(QString(g_lamexp_ipc_uuid.semaphore_write_mutex), 0);
1275 if(g_lamexp_ipc_ptr.semaphore_read->error() != QSystemSemaphore::NoError)
1277 QString errorMessage = g_lamexp_ipc_ptr.semaphore_read->errorString();
1278 LAMEXP_DELETE(g_lamexp_ipc_ptr.semaphore_read);
1279 LAMEXP_DELETE(g_lamexp_ipc_ptr.semaphore_write);
1280 LAMEXP_DELETE(g_lamexp_ipc_ptr.semaphore_read_mutex);
1281 LAMEXP_DELETE(g_lamexp_ipc_ptr.semaphore_write_mutex);
1282 qFatal("Failed to create system smaphore: %s", errorMessage.toUtf8().constData());
1285 if(g_lamexp_ipc_ptr.semaphore_write->error() != QSystemSemaphore::NoError)
1287 QString errorMessage = g_lamexp_ipc_ptr.semaphore_write->errorString();
1288 LAMEXP_DELETE(g_lamexp_ipc_ptr.semaphore_read);
1289 LAMEXP_DELETE(g_lamexp_ipc_ptr.semaphore_write);
1290 LAMEXP_DELETE(g_lamexp_ipc_ptr.semaphore_read_mutex);
1291 LAMEXP_DELETE(g_lamexp_ipc_ptr.semaphore_write_mutex);
1292 qFatal("Failed to create system smaphore: %s", errorMessage.toUtf8().constData());
1295 if(g_lamexp_ipc_ptr.semaphore_read_mutex->error() != QSystemSemaphore::NoError)
1297 QString errorMessage = g_lamexp_ipc_ptr.semaphore_read_mutex->errorString();
1298 LAMEXP_DELETE(g_lamexp_ipc_ptr.semaphore_read);
1299 LAMEXP_DELETE(g_lamexp_ipc_ptr.semaphore_write);
1300 LAMEXP_DELETE(g_lamexp_ipc_ptr.semaphore_read_mutex);
1301 LAMEXP_DELETE(g_lamexp_ipc_ptr.semaphore_write_mutex);
1302 qFatal("Failed to create system smaphore: %s", errorMessage.toUtf8().constData());
1305 if(g_lamexp_ipc_ptr.semaphore_write_mutex->error() != QSystemSemaphore::NoError)
1307 QString errorMessage = g_lamexp_ipc_ptr.semaphore_write_mutex->errorString();
1308 LAMEXP_DELETE(g_lamexp_ipc_ptr.semaphore_read);
1309 LAMEXP_DELETE(g_lamexp_ipc_ptr.semaphore_write);
1310 LAMEXP_DELETE(g_lamexp_ipc_ptr.semaphore_read_mutex);
1311 LAMEXP_DELETE(g_lamexp_ipc_ptr.semaphore_write_mutex);
1312 qFatal("Failed to create system smaphore: %s", errorMessage.toUtf8().constData());
1316 g_lamexp_ipc_ptr.sharedmem = new QSharedMemory(QString(g_lamexp_ipc_uuid.sharedmem), NULL);
1318 if(!g_lamexp_ipc_ptr.sharedmem->create(sizeof(lamexp_ipc_t)))
1320 if(g_lamexp_ipc_ptr.sharedmem->error() == QSharedMemory::AlreadyExists)
1322 g_lamexp_ipc_ptr.sharedmem->attach();
1323 if(g_lamexp_ipc_ptr.sharedmem->error() == QSharedMemory::NoError)
1329 QString errorMessage = g_lamexp_ipc_ptr.sharedmem->errorString();
1330 LAMEXP_DELETE(g_lamexp_ipc_ptr.sharedmem);
1331 qFatal("Failed to attach to shared memory: %s", errorMessage.toUtf8().constData());
1337 QString errorMessage = g_lamexp_ipc_ptr.sharedmem->errorString();
1338 LAMEXP_DELETE(g_lamexp_ipc_ptr.sharedmem);
1339 qFatal("Failed to create shared memory: %s", errorMessage.toUtf8().constData());
1344 memset(g_lamexp_ipc_ptr.sharedmem->data(), 0, sizeof(lamexp_ipc_t));
1345 g_lamexp_ipc_ptr.semaphore_write->release(g_lamexp_ipc_slots);
1346 g_lamexp_ipc_ptr.semaphore_read_mutex->release();
1347 g_lamexp_ipc_ptr.semaphore_write_mutex->release();
1355 void lamexp_ipc_send(unsigned int command, const char* message)
1357 QReadLocker readLock(&g_lamexp_ipc_ptr.lock);
1359 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)
1361 throw "Shared memory for IPC not initialized yet.";
1364 lamexp_ipc_data_t ipc_data;
1365 memset(&ipc_data, 0, sizeof(lamexp_ipc_data_t));
1366 ipc_data.command = command;
1370 strncpy_s(ipc_data.parameter, 4096, message, _TRUNCATE);
1373 if(g_lamexp_ipc_ptr.semaphore_write->acquire())
1375 if(g_lamexp_ipc_ptr.semaphore_write_mutex->acquire())
1377 lamexp_ipc_t *ptr = reinterpret_cast<lamexp_ipc_t*>(g_lamexp_ipc_ptr.sharedmem->data());
1378 memcpy(&ptr->data[ptr->pos_write], &ipc_data, sizeof(lamexp_ipc_data_t));
1379 ptr->pos_write = (ptr->pos_write + 1) % g_lamexp_ipc_slots;
1380 g_lamexp_ipc_ptr.semaphore_read->release();
1381 g_lamexp_ipc_ptr.semaphore_write_mutex->release();
1389 void lamexp_ipc_read(unsigned int *command, char* message, size_t buffSize)
1391 QReadLocker readLock(&g_lamexp_ipc_ptr.lock);
1396 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)
1398 throw "Shared memory for IPC not initialized yet.";
1401 lamexp_ipc_data_t ipc_data;
1402 memset(&ipc_data, 0, sizeof(lamexp_ipc_data_t));
1404 if(g_lamexp_ipc_ptr.semaphore_read->acquire())
1406 if(g_lamexp_ipc_ptr.semaphore_read_mutex->acquire())
1408 lamexp_ipc_t *ptr = reinterpret_cast<lamexp_ipc_t*>(g_lamexp_ipc_ptr.sharedmem->data());
1409 memcpy(&ipc_data, &ptr->data[ptr->pos_read], sizeof(lamexp_ipc_data_t));
1410 ptr->pos_read = (ptr->pos_read + 1) % g_lamexp_ipc_slots;
1411 g_lamexp_ipc_ptr.semaphore_write->release();
1412 g_lamexp_ipc_ptr.semaphore_read_mutex->release();
1414 if(!(ipc_data.reserved_1 || ipc_data.reserved_2))
1416 *command = ipc_data.command;
1417 strncpy_s(message, buffSize, ipc_data.parameter, _TRUNCATE);
1421 qWarning("Malformed IPC message, will be ignored");
1428 * Check for LameXP "portable" mode
1430 bool lamexp_portable_mode(void)
1432 QString baseName = QFileInfo(QApplication::applicationFilePath()).completeBaseName();
1433 int idx1 = baseName.indexOf("lamexp", 0, Qt::CaseInsensitive);
1434 int idx2 = baseName.lastIndexOf("portable", -1, Qt::CaseInsensitive);
1435 return (idx1 >= 0) && (idx2 >= 0) && (idx1 < idx2);
1439 * Get a random string
1441 QString lamexp_rand_str(void)
1443 QRegExp regExp("\\{(\\w+)-(\\w+)-(\\w+)-(\\w+)-(\\w+)\\}");
1444 QString uuid = QUuid::createUuid().toString();
1446 if(regExp.indexIn(uuid) >= 0)
1448 return QString().append(regExp.cap(1)).append(regExp.cap(2)).append(regExp.cap(3)).append(regExp.cap(4)).append(regExp.cap(5));
1451 throw "The RegExp didn't match on the UUID string. This shouldn't happen ;-)";
1455 * Get LameXP temp folder
1457 const QString &lamexp_temp_folder2(void)
1459 QReadLocker readLock(&g_lamexp_folder.lock);
1461 //Already initialized?
1462 if(g_lamexp_folder.temp)
1464 if(!g_lamexp_folder.temp->isEmpty())
1466 if(QDir(*g_lamexp_folder.temp).exists())
1468 return *g_lamexp_folder.temp;
1474 QWriteLocker writeLock(&g_lamexp_folder.lock);
1476 if(!g_lamexp_folder.temp)
1478 g_lamexp_folder.temp = new QString();
1481 g_lamexp_folder.temp->clear();
1483 static const char *TEMP_STR = "Temp";
1484 const QString WRITE_TEST_DATA = lamexp_rand_str();
1485 const QString SUB_FOLDER = lamexp_rand_str();
1487 //Try the %TMP% or %TEMP% directory first
1488 QDir temp = QDir::temp();
1491 temp.mkdir(SUB_FOLDER);
1492 if(temp.cd(SUB_FOLDER) && temp.exists())
1494 QFile testFile(QString("%1/~%2.tmp").arg(temp.canonicalPath(), lamexp_rand_str()));
1495 if(testFile.open(QIODevice::ReadWrite))
1497 if(testFile.write(WRITE_TEST_DATA.toLatin1().constData()) >= strlen(WRITE_TEST_DATA.toLatin1().constData()))
1499 (*g_lamexp_folder.temp) = temp.canonicalPath();
1504 if(!g_lamexp_folder.temp->isEmpty())
1506 return *g_lamexp_folder.temp;
1510 //Create TEMP folder in %LOCALAPPDATA%
1511 QDir localAppData = QDir(lamexp_known_folder(lamexp_folder_localappdata));
1512 if(!localAppData.path().isEmpty())
1514 if(!localAppData.exists())
1516 localAppData.mkpath(".");
1518 if(localAppData.exists())
1520 if(!localAppData.entryList(QDir::AllDirs).contains(TEMP_STR, Qt::CaseInsensitive))
1522 localAppData.mkdir(TEMP_STR);
1524 if(localAppData.cd(TEMP_STR) && localAppData.exists())
1526 localAppData.mkdir(SUB_FOLDER);
1527 if(localAppData.cd(SUB_FOLDER) && localAppData.exists())
1529 QFile testFile(QString("%1/~%2.tmp").arg(localAppData.canonicalPath(), lamexp_rand_str()));
1530 if(testFile.open(QIODevice::ReadWrite))
1532 if(testFile.write(WRITE_TEST_DATA.toLatin1().constData()) >= strlen(WRITE_TEST_DATA.toLatin1().constData()))
1534 (*g_lamexp_folder.temp) = localAppData.canonicalPath();
1541 if(!g_lamexp_folder.temp->isEmpty())
1543 return *g_lamexp_folder.temp;
1547 //Failed to create TEMP folder!
1548 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());
1549 return *g_lamexp_folder.temp;
1555 bool lamexp_clean_folder(const QString &folderPath)
1557 QDir tempFolder(folderPath);
1558 QFileInfoList entryList = tempFolder.entryInfoList(QDir::AllEntries | QDir::NoDotAndDotDot);
1560 for(int i = 0; i < entryList.count(); i++)
1562 if(entryList.at(i).isDir())
1564 lamexp_clean_folder(entryList.at(i).canonicalFilePath());
1568 for(int j = 0; j < 3; j++)
1570 if(lamexp_remove_file(entryList.at(i).canonicalFilePath()))
1578 tempFolder.rmdir(".");
1579 return !tempFolder.exists();
1585 void lamexp_register_tool(const QString &toolName, LockedFile *file, unsigned int version)
1587 QWriteLocker writeLock(&g_lamexp_tools.lock);
1589 if(!g_lamexp_tools.registry) g_lamexp_tools.registry = new QMap<QString, LockedFile*>();
1590 if(!g_lamexp_tools.versions) g_lamexp_tools.versions = new QMap<QString, unsigned int>();
1592 if(g_lamexp_tools.registry->contains(toolName.toLower()))
1594 throw "lamexp_register_tool: Tool is already registered!";
1597 g_lamexp_tools.registry->insert(toolName.toLower(), file);
1598 g_lamexp_tools.versions->insert(toolName.toLower(), version);
1604 bool lamexp_check_tool(const QString &toolName)
1606 QReadLocker readLock(&g_lamexp_tools.lock);
1607 return (g_lamexp_tools.registry) ? g_lamexp_tools.registry->contains(toolName.toLower()) : false;
1613 const QString lamexp_lookup_tool(const QString &toolName)
1615 QReadLocker readLock(&g_lamexp_tools.lock);
1617 if(g_lamexp_tools.registry)
1619 if(g_lamexp_tools.registry->contains(toolName.toLower()))
1621 return g_lamexp_tools.registry->value(toolName.toLower())->filePath();
1635 * Lookup tool version
1637 unsigned int lamexp_tool_version(const QString &toolName)
1639 QReadLocker readLock(&g_lamexp_tools.lock);
1641 if(g_lamexp_tools.versions)
1643 if(g_lamexp_tools.versions->contains(toolName.toLower()))
1645 return g_lamexp_tools.versions->value(toolName.toLower());
1659 * Version number to human-readable string
1661 const QString lamexp_version2string(const QString &pattern, unsigned int version, const QString &defaultText)
1663 if(version == UINT_MAX)
1668 QString result = pattern;
1669 int digits = result.count("?", Qt::CaseInsensitive);
1677 QString versionStr = QString().sprintf(QString().sprintf("%%0%du", digits).toLatin1().constData(), version);
1678 int index = result.indexOf("?", Qt::CaseInsensitive);
1680 while(index >= 0 && pos < versionStr.length())
1682 result[index] = versionStr[pos++];
1683 index = result.indexOf("?", Qt::CaseInsensitive);
1690 * Register a new translation
1692 bool lamexp_translation_register(const QString &langId, const QString &qmFile, const QString &langName, unsigned int &systemId, unsigned int &country)
1694 QWriteLocker writeLockTranslations(&g_lamexp_translation.lock);
1696 if(qmFile.isEmpty() || langName.isEmpty() || systemId < 1)
1701 if(!g_lamexp_translation.files) g_lamexp_translation.files = new QMap<QString, QString>();
1702 if(!g_lamexp_translation.names) g_lamexp_translation.names = new QMap<QString, QString>();
1703 if(!g_lamexp_translation.sysid) g_lamexp_translation.sysid = new QMap<QString, unsigned int>();
1704 if(!g_lamexp_translation.cntry) g_lamexp_translation.cntry = new QMap<QString, unsigned int>();
1706 g_lamexp_translation.files->insert(langId, qmFile);
1707 g_lamexp_translation.names->insert(langId, langName);
1708 g_lamexp_translation.sysid->insert(langId, systemId);
1709 g_lamexp_translation.cntry->insert(langId, country);
1715 * Get list of all translations
1717 QStringList lamexp_query_translations(void)
1719 QReadLocker readLockTranslations(&g_lamexp_translation.lock);
1720 return (g_lamexp_translation.files) ? g_lamexp_translation.files->keys() : QStringList();
1724 * Get translation name
1726 QString lamexp_translation_name(const QString &langId)
1728 QReadLocker readLockTranslations(&g_lamexp_translation.lock);
1729 return (g_lamexp_translation.names) ? g_lamexp_translation.names->value(langId.toLower(), QString()) : QString();
1733 * Get translation system id
1735 unsigned int lamexp_translation_sysid(const QString &langId)
1737 QReadLocker readLockTranslations(&g_lamexp_translation.lock);
1738 return (g_lamexp_translation.sysid) ? g_lamexp_translation.sysid->value(langId.toLower(), 0) : 0;
1742 * Get translation script id
1744 unsigned int lamexp_translation_country(const QString &langId)
1746 QReadLocker readLockTranslations(&g_lamexp_translation.lock);
1747 return (g_lamexp_translation.cntry) ? g_lamexp_translation.cntry->value(langId.toLower(), 0) : 0;
1751 * Install a new translator
1753 bool lamexp_install_translator(const QString &langId)
1755 bool success = false;
1757 if(langId.isEmpty() || langId.toLower().compare(LAMEXP_DEFAULT_LANGID) == 0)
1759 success = lamexp_install_translator_from_file(QString());
1763 QReadLocker readLock(&g_lamexp_translation.lock);
1764 QString qmFile = (g_lamexp_translation.files) ? g_lamexp_translation.files->value(langId.toLower(), QString()) : QString();
1767 if(!qmFile.isEmpty())
1769 success = lamexp_install_translator_from_file(QString(":/localization/%1").arg(qmFile));
1773 qWarning("Translation '%s' not available!", langId.toLatin1().constData());
1781 * Install a new translator from file
1783 bool lamexp_install_translator_from_file(const QString &qmFile)
1785 QWriteLocker writeLock(&g_lamexp_currentTranslator.lock);
1786 bool success = false;
1788 if(!g_lamexp_currentTranslator.instance)
1790 g_lamexp_currentTranslator.instance = new QTranslator();
1793 if(!qmFile.isEmpty())
1795 QString qmPath = QFileInfo(qmFile).canonicalFilePath();
1796 QApplication::removeTranslator(g_lamexp_currentTranslator.instance);
1797 if(success = g_lamexp_currentTranslator.instance->load(qmPath))
1799 QApplication::installTranslator(g_lamexp_currentTranslator.instance);
1803 qWarning("Failed to load translation:\n\"%s\"", qmPath.toLatin1().constData());
1808 QApplication::removeTranslator(g_lamexp_currentTranslator.instance);
1815 const QStringList &lamexp_arguments(void)
1817 QReadLocker readLock(&g_lamexp_argv.lock);
1819 if(!g_lamexp_argv.list)
1822 QWriteLocker writeLock(&g_lamexp_argv.lock);
1824 g_lamexp_argv.list = new QStringList;
1827 LPWSTR *szArglist = CommandLineToArgvW(GetCommandLineW(), &nArgs);
1829 if(NULL != szArglist)
1831 for(int i = 0; i < nArgs; i++)
1833 (*g_lamexp_argv.list) << WCHAR2QSTR(szArglist[i]);
1835 LocalFree(szArglist);
1839 qWarning("CommandLineToArgvW() has failed !!!");
1843 return (*g_lamexp_argv.list);
1847 * Locate known folder on local system
1849 const QString &lamexp_known_folder(lamexp_known_folder_t folder_id)
1851 typedef HRESULT (WINAPI *SHGetKnownFolderPathFun)(__in const GUID &rfid, __in DWORD dwFlags, __in HANDLE hToken, __out PWSTR *ppszPath);
1852 typedef HRESULT (WINAPI *SHGetFolderPathFun)(__in HWND hwndOwner, __in int nFolder, __in HANDLE hToken, __in DWORD dwFlags, __out LPWSTR pszPath);
1854 static const int CSIDL_LOCAL_APPDATA = 0x001c;
1855 static const int CSIDL_PROGRAM_FILES = 0x0026;
1856 static const int CSIDL_SYSTEM_FOLDER = 0x0025;
1857 static const GUID GUID_LOCAL_APPDATA = {0xF1B32785,0x6FBA,0x4FCF,{0x9D,0x55,0x7B,0x8E,0x7F,0x15,0x70,0x91}};
1858 static const GUID GUID_LOCAL_APPDATA_LOW = {0xA520A1A4,0x1780,0x4FF6,{0xBD,0x18,0x16,0x73,0x43,0xC5,0xAF,0x16}};
1859 static const GUID GUID_PROGRAM_FILES = {0x905e63b6,0xc1bf,0x494e,{0xb2,0x9c,0x65,0xb7,0x32,0xd3,0xd2,0x1a}};
1860 static const GUID GUID_SYSTEM_FOLDER = {0x1AC14E77,0x02E7,0x4E5D,{0xB7,0x44,0x2E,0xB1,0xAE,0x51,0x98,0xB7}};
1862 QReadLocker readLock(&g_lamexp_folder.lock);
1864 int folderCSIDL = -1;
1865 GUID folderGUID = {0x0000,0x0000,0x0000,{0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00}};
1866 size_t folderCacheId = size_t(-1);
1870 case lamexp_folder_localappdata:
1872 folderCSIDL = CSIDL_LOCAL_APPDATA;
1873 folderGUID = GUID_LOCAL_APPDATA;
1875 case lamexp_folder_programfiles:
1877 folderCSIDL = CSIDL_PROGRAM_FILES;
1878 folderGUID = GUID_PROGRAM_FILES;
1880 case lamexp_folder_systemfolder:
1882 folderCSIDL = CSIDL_SYSTEM_FOLDER;
1883 folderGUID = GUID_SYSTEM_FOLDER;
1886 qWarning("Invalid 'known' folder was requested!");
1887 return *reinterpret_cast<QString*>(NULL);
1892 if(g_lamexp_folder.knownFolders)
1894 if(g_lamexp_folder.knownFolders->contains(folderCacheId))
1896 return (*g_lamexp_folder.knownFolders)[folderCacheId];
1901 QWriteLocker writeLock(&g_lamexp_folder.lock);
1903 static SHGetKnownFolderPathFun SHGetKnownFolderPathPtr = NULL;
1904 static SHGetFolderPathFun SHGetFolderPathPtr = NULL;
1906 if((!SHGetKnownFolderPathPtr) && (!SHGetFolderPathPtr))
1908 QLibrary kernel32Lib("shell32.dll");
1909 if(kernel32Lib.load())
1911 SHGetKnownFolderPathPtr = (SHGetKnownFolderPathFun) kernel32Lib.resolve("SHGetKnownFolderPath");
1912 SHGetFolderPathPtr = (SHGetFolderPathFun) kernel32Lib.resolve("SHGetFolderPathW");
1918 if(SHGetKnownFolderPathPtr)
1921 if(SHGetKnownFolderPathPtr(folderGUID, 0x00008000, NULL, &path) == S_OK)
1923 //MessageBoxW(0, path, L"SHGetKnownFolderPath", MB_TOPMOST);
1924 QDir folderTemp = QDir(QDir::fromNativeSeparators(QString::fromUtf16(reinterpret_cast<const unsigned short*>(path))));
1925 if(!folderTemp.exists())
1927 folderTemp.mkpath(".");
1929 if(folderTemp.exists())
1931 folder = folderTemp.canonicalPath();
1933 CoTaskMemFree(path);
1936 else if(SHGetFolderPathPtr)
1938 WCHAR *path = new WCHAR[4096];
1939 if(SHGetFolderPathPtr(NULL, folderCSIDL, NULL, NULL, path) == S_OK)
1941 //MessageBoxW(0, path, L"SHGetFolderPathW", MB_TOPMOST);
1942 QDir folderTemp = QDir(QDir::fromNativeSeparators(QString::fromUtf16(reinterpret_cast<const unsigned short*>(path))));
1943 if(!folderTemp.exists())
1945 folderTemp.mkpath(".");
1947 if(folderTemp.exists())
1949 folder = folderTemp.canonicalPath();
1956 if(!g_lamexp_folder.knownFolders)
1958 g_lamexp_folder.knownFolders = new QMap<size_t, QString>();
1962 g_lamexp_folder.knownFolders->insert(folderCacheId, folder);
1963 return (*g_lamexp_folder.knownFolders)[folderCacheId];
1967 * Safely remove a file
1969 bool lamexp_remove_file(const QString &filename)
1971 if(!QFileInfo(filename).exists() || !QFileInfo(filename).isFile())
1977 if(!QFile::remove(filename))
1979 DWORD attributes = GetFileAttributesW(QWCHAR(filename));
1980 SetFileAttributesW(QWCHAR(filename), (attributes & (~FILE_ATTRIBUTE_READONLY)));
1981 if(!QFile::remove(filename))
1983 qWarning("Could not delete \"%s\"", filename.toLatin1().constData());
1999 * Check if visual themes are enabled (WinXP and later)
2001 bool lamexp_themes_enabled(void)
2003 typedef int (WINAPI *IsAppThemedFun)(void);
2005 static bool isAppThemed = false;
2006 static bool isAppThemed_initialized = false;
2008 if(!isAppThemed_initialized)
2010 IsAppThemedFun IsAppThemedPtr = NULL;
2011 QLibrary uxTheme(QString("%1/UxTheme.dll").arg(lamexp_known_folder(lamexp_folder_systemfolder)));
2014 IsAppThemedPtr = (IsAppThemedFun) uxTheme.resolve("IsAppThemed");
2018 isAppThemed = IsAppThemedPtr();
2021 qWarning("Theme support is disabled for this process!");
2024 isAppThemed_initialized = true;
2031 * Get number of free bytes on disk
2033 unsigned __int64 lamexp_free_diskspace(const QString &path, bool *ok)
2035 ULARGE_INTEGER freeBytesAvailable, totalNumberOfBytes, totalNumberOfFreeBytes;
2036 if(GetDiskFreeSpaceExW(reinterpret_cast<const wchar_t*>(QDir::toNativeSeparators(path).utf16()), &freeBytesAvailable, &totalNumberOfBytes, &totalNumberOfFreeBytes))
2039 return freeBytesAvailable.QuadPart;
2049 * Check if computer does support hibernation
2051 bool lamexp_is_hibernation_supported(void)
2053 bool hibernationSupported = false;
2055 SYSTEM_POWER_CAPABILITIES pwrCaps;
2056 SecureZeroMemory(&pwrCaps, sizeof(SYSTEM_POWER_CAPABILITIES));
2058 if(GetPwrCapabilities(&pwrCaps))
2060 hibernationSupported = pwrCaps.SystemS4 && pwrCaps.HiberFilePresent;
2063 return hibernationSupported;
2067 * Shutdown the computer
2069 bool lamexp_shutdown_computer(const QString &message, const unsigned long timeout, const bool forceShutdown, const bool hibernate)
2071 HANDLE hToken = NULL;
2073 if(OpenProcessToken(GetCurrentProcess(), TOKEN_ADJUST_PRIVILEGES | TOKEN_QUERY, &hToken))
2075 TOKEN_PRIVILEGES privileges;
2076 memset(&privileges, 0, sizeof(TOKEN_PRIVILEGES));
2077 privileges.PrivilegeCount = 1;
2078 privileges.Privileges[0].Attributes = SE_PRIVILEGE_ENABLED;
2080 if(LookupPrivilegeValue(NULL, SE_SHUTDOWN_NAME, &privileges.Privileges[0].Luid))
2082 if(AdjustTokenPrivileges(hToken, FALSE, &privileges, NULL, NULL, NULL))
2086 if(SetSuspendState(TRUE, TRUE, TRUE))
2091 const DWORD reason = SHTDN_REASON_MAJOR_APPLICATION | SHTDN_REASON_FLAG_PLANNED;
2092 return InitiateSystemShutdownEx(NULL, const_cast<wchar_t*>(QWCHAR(message)), timeout, forceShutdown ? TRUE : FALSE, FALSE, reason);
2101 * Make a window blink (to draw user's attention)
2103 void lamexp_blink_window(QWidget *poWindow, unsigned int count, unsigned int delay)
2105 static QMutex blinkMutex;
2107 const double maxOpac = 1.0;
2108 const double minOpac = 0.3;
2109 const double delOpac = 0.1;
2111 if(!blinkMutex.tryLock())
2113 qWarning("Blinking is already in progress, skipping!");
2119 const int steps = static_cast<int>(ceil(maxOpac - minOpac) / delOpac);
2120 const int sleep = static_cast<int>(floor(static_cast<double>(delay) / static_cast<double>(steps)));
2121 const double opacity = poWindow->windowOpacity();
2123 for(unsigned int i = 0; i < count; i++)
2125 for(double x = maxOpac; x >= minOpac; x -= delOpac)
2127 poWindow->setWindowOpacity(x);
2128 QApplication::processEvents();
2132 for(double x = minOpac; x <= maxOpac; x += delOpac)
2134 poWindow->setWindowOpacity(x);
2135 QApplication::processEvents();
2140 poWindow->setWindowOpacity(opacity);
2141 QApplication::processEvents();
2142 blinkMutex.unlock();
2146 blinkMutex.unlock();
2147 qWarning("Exception error while blinking!");
2152 * Remove forbidden characters from a filename
2154 const QString lamexp_clean_filename(const QString &str)
2156 QString newStr(str);
2158 newStr.replace("\\", "-");
2159 newStr.replace(" / ", ", ");
2160 newStr.replace("/", ",");
2161 newStr.replace(":", "-");
2162 newStr.replace("*", "x");
2163 newStr.replace("?", "");
2164 newStr.replace("<", "[");
2165 newStr.replace(">", "]");
2166 newStr.replace("|", "!");
2168 return newStr.simplified();
2172 * Remove forbidden characters from a file path
2174 const QString lamexp_clean_filepath(const QString &str)
2176 QStringList parts = QString(str).replace("\\", "/").split("/");
2178 for(int i = 0; i < parts.count(); i++)
2180 parts[i] = lamexp_clean_filename(parts[i]);
2183 return parts.join("/");
2187 * Get a list of all available Qt Text Codecs
2189 QStringList lamexp_available_codepages(bool noAliases)
2191 QStringList codecList;
2193 QList<QByteArray> availableCodecs = QTextCodec::availableCodecs();
2194 while(!availableCodecs.isEmpty())
2196 QByteArray current = availableCodecs.takeFirst();
2197 if(!(current.startsWith("system") || current.startsWith("System")))
2199 codecList << QString::fromLatin1(current.constData(), current.size());
2202 if(QTextCodec *currentCodec = QTextCodec::codecForName(current.constData()))
2205 QList<QByteArray> aliases = currentCodec->aliases();
2206 while(!aliases.isEmpty()) availableCodecs.removeAll(aliases.takeFirst());
2216 * Robert Jenkins' 96 bit Mix Function
2217 * Source: http://www.concentric.net/~Ttwang/tech/inthash.htm
2219 static unsigned int lamexp_mix(const unsigned int x, const unsigned int y, const unsigned int z)
2225 a=a-b; a=a-c; a=a^(c >> 13);
2226 b=b-c; b=b-a; b=b^(a << 8);
2227 c=c-a; c=c-b; c=c^(b >> 13);
2228 a=a-b; a=a-c; a=a^(c >> 12);
2229 b=b-c; b=b-a; b=b^(a << 16);
2230 c=c-a; c=c-b; c=c^(b >> 5);
2231 a=a-b; a=a-c; a=a^(c >> 3);
2232 b=b-c; b=b-a; b=b^(a << 10);
2233 c=c-a; c=c-b; c=c^(b >> 15);
2239 * Seeds the random number generator
2240 * Note: Altough rand_s() doesn't need a seed, this must be called pripr to lamexp_rand(), just to to be sure!
2242 void lamexp_seed_rand(void)
2244 qsrand(lamexp_mix(clock(), time(NULL), _getpid()));
2248 * Returns a randum number
2249 * Note: This function uses rand_s() if available, but falls back to qrand() otherwise
2251 unsigned int lamexp_rand(void)
2253 unsigned int rnd = 0;
2254 if(const lamexp_os_version_t* osVer = lamexp_get_os_version())
2256 if(LAMEXP_MIN_OS_VER(osVer, 5, 1))
2258 if(rand_s(&rnd) == 0)
2264 for(size_t i = 0; i < sizeof(unsigned int); i++)
2266 rnd = (rnd << 8) ^ qrand();
2272 * Entry point checks
2274 static DWORD lamexp_entry_check(void);
2275 static DWORD g_lamexp_entry_check_result = lamexp_entry_check();
2276 static DWORD g_lamexp_entry_check_flag = 0x789E09B2;
2277 static DWORD lamexp_entry_check(void)
2279 volatile DWORD retVal = 0xA199B5AF;
2280 if(g_lamexp_entry_check_flag != 0x8761F64D)
2282 FatalAppExit(0, L"Application initialization has failed, take care!");
2283 TerminateProcess(GetCurrentProcess(), -1);
2289 * Application entry point (runs before static initializers)
2293 int WinMainCRTStartup(void);
2295 int lamexp_entry_point(void)
2297 if((!LAMEXP_DEBUG) && lamexp_check_for_debugger())
2299 FatalAppExit(0, L"Not a debug build. Please unload debugger and try again!");
2300 TerminateProcess(GetCurrentProcess(), -1);
2303 if(g_lamexp_entry_check_flag != 0x789E09B2)
2305 FatalAppExit(0, L"Application initialization has failed, take care!");
2306 TerminateProcess(GetCurrentProcess(), -1);
2309 //Zero *before* constructors are called
2310 LAMEXP_ZERO_MEMORY(g_lamexp_argv);
2311 LAMEXP_ZERO_MEMORY(g_lamexp_tools);
2312 LAMEXP_ZERO_MEMORY(g_lamexp_currentTranslator);
2313 LAMEXP_ZERO_MEMORY(g_lamexp_translation);
2314 LAMEXP_ZERO_MEMORY(g_lamexp_folder);
2315 LAMEXP_ZERO_MEMORY(g_lamexp_ipc_ptr);
2316 LAMEXP_ZERO_MEMORY(g_lamexp_os_version);
2318 //Make sure we will pass the check
2319 g_lamexp_entry_check_flag = ~g_lamexp_entry_check_flag;
2321 //Now initialize the C Runtime library!
2322 return WinMainCRTStartup();
2327 * Finalization function (final clean-up)
2329 void lamexp_finalization(void)
2331 qDebug("lamexp_finalization()");
2334 if(g_lamexp_tools.registry)
2336 QStringList keys = g_lamexp_tools.registry->keys();
2337 for(int i = 0; i < keys.count(); i++)
2339 LAMEXP_DELETE((*g_lamexp_tools.registry)[keys.at(i)]);
2341 LAMEXP_DELETE(g_lamexp_tools.registry);
2342 LAMEXP_DELETE(g_lamexp_tools.versions);
2345 //Delete temporary files
2346 if(g_lamexp_folder.temp)
2348 if(!g_lamexp_folder.temp->isEmpty())
2350 for(int i = 0; i < 100; i++)
2352 if(lamexp_clean_folder(*g_lamexp_folder.temp))
2359 LAMEXP_DELETE(g_lamexp_folder.temp);
2362 //Clear folder cache
2363 LAMEXP_DELETE(g_lamexp_folder.knownFolders);
2366 if(g_lamexp_currentTranslator.instance)
2368 QApplication::removeTranslator(g_lamexp_currentTranslator.instance);
2369 LAMEXP_DELETE(g_lamexp_currentTranslator.instance);
2371 LAMEXP_DELETE(g_lamexp_translation.files);
2372 LAMEXP_DELETE(g_lamexp_translation.names);
2373 LAMEXP_DELETE(g_lamexp_translation.cntry);
2374 LAMEXP_DELETE(g_lamexp_translation.sysid);
2376 //Destroy Qt application object
2377 QApplication *application = dynamic_cast<QApplication*>(QApplication::instance());
2378 LAMEXP_DELETE(application);
2380 //Detach from shared memory
2381 if(g_lamexp_ipc_ptr.sharedmem) g_lamexp_ipc_ptr.sharedmem->detach();
2382 LAMEXP_DELETE(g_lamexp_ipc_ptr.sharedmem);
2383 LAMEXP_DELETE(g_lamexp_ipc_ptr.semaphore_read);
2384 LAMEXP_DELETE(g_lamexp_ipc_ptr.semaphore_write);
2385 LAMEXP_DELETE(g_lamexp_ipc_ptr.semaphore_read_mutex);
2386 LAMEXP_DELETE(g_lamexp_ipc_ptr.semaphore_write_mutex);
2388 //Free STDOUT and STDERR buffers
2389 if(g_lamexp_console_attached)
2391 if(std::filebuf *tmp = dynamic_cast<std::filebuf*>(std::cout.rdbuf()))
2393 std::cout.rdbuf(NULL);
2396 if(std::filebuf *tmp = dynamic_cast<std::filebuf*>(std::cerr.rdbuf()))
2398 std::cerr.rdbuf(NULL);
2404 if(g_lamexp_log_file)
2406 fclose(g_lamexp_log_file);
2407 g_lamexp_log_file = NULL;
2410 //Free CLI Arguments
2411 LAMEXP_DELETE(g_lamexp_argv.list);
2415 * Initialize debug thread
2417 static const HANDLE g_debug_thread = LAMEXP_DEBUG ? NULL : lamexp_debug_thread_init();
2420 * Get number private bytes [debug only]
2422 SIZE_T lamexp_dbg_private_bytes(void)
2425 PROCESS_MEMORY_COUNTERS_EX memoryCounters;
2426 memoryCounters.cb = sizeof(PROCESS_MEMORY_COUNTERS_EX);
2427 GetProcessMemoryInfo(GetCurrentProcess(), (PPROCESS_MEMORY_COUNTERS) &memoryCounters, sizeof(PROCESS_MEMORY_COUNTERS_EX));
2428 return memoryCounters.PrivateUsage;
2430 throw "Cannot call this function in a non-debug build!";
2431 #endif //LAMEXP_DEBUG