1 ///////////////////////////////////////////////////////////////////////////////
2 // LameXP - Audio Encoder Front-End
3 // Copyright (C) 2004-2011 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>
49 #include "LockedFile.h"
67 //Initialize static Qt plugins
74 ///////////////////////////////////////////////////////////////////////////////
76 ///////////////////////////////////////////////////////////////////////////////
81 unsigned int reserved_1;
82 unsigned int reserved_2;
86 ///////////////////////////////////////////////////////////////////////////////
88 ///////////////////////////////////////////////////////////////////////////////
93 unsigned int ver_major;
94 unsigned int ver_minor;
95 unsigned int ver_build;
96 char *ver_release_name;
107 static QDate g_lamexp_version_date;
108 static const char *g_lamexp_months[] = {"Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"};
109 static const char *g_lamexp_version_raw_date = __DATE__;
110 static const char *g_lamexp_version_raw_time = __TIME__;
112 //Console attached flag
113 static bool g_lamexp_console_attached = false;
116 //The following code was borrowed from MPC-HC project: http://mpc-hc.sf.net/
117 #if defined(__INTEL_COMPILER)
118 #if (__INTEL_COMPILER >= 1200)
119 static const char *g_lamexp_version_compiler = "ICL 12.x";
120 #elif (__INTEL_COMPILER >= 1100)
121 static const char *g_lamexp_version_compiler = = "ICL 11.x";
122 #elif (__INTEL_COMPILER >= 1000)
123 static const char *g_lamexp_version_compiler = = "ICL 10.x";
125 #error Compiler is not supported!
127 #elif defined(_MSC_VER)
128 #if (_MSC_VER == 1600)
129 #if (_MSC_FULL_VER >= 160040219)
130 static const char *g_lamexp_version_compiler = "MSVC 2010-SP1";
132 static const char *g_lamexp_version_compiler = "MSVC 2010";
134 #elif (_MSC_VER == 1500)
135 #if (_MSC_FULL_VER >= 150030729)
136 static const char *g_lamexp_version_compiler = "MSVC 2008-SP1";
138 static const char *g_lamexp_version_compiler = "MSVC 2008";
141 #error Compiler is not supported!
144 // Note: /arch:SSE and /arch:SSE2 are only available for the x86 platform
145 #if !defined(_M_X64) && defined(_M_IX86_FP)
146 #if (_M_IX86_FP == 1)
147 LAMEXP_COMPILER_WARNING("SSE instruction set is enabled!")
148 #elif (_M_IX86_FP == 2)
149 LAMEXP_COMPILER_WARNING("SSE2 instruction set is enabled!")
153 #error Compiler is not supported!
156 //Architecture detection
158 static const char *g_lamexp_version_arch = "x64";
159 #elif defined(_M_IX86)
160 static const char *g_lamexp_version_arch = "x86";
162 #error Architecture is not supported!
165 //Official web-site URL
166 static const char *g_lamexp_website_url = "http://lamexp.sourceforge.net/";
167 static const char *g_lamexp_support_url = "http://forum.doom9.org/showthread.php?t=157726";
169 //Tool versions (expected versions!)
170 static const unsigned int g_lamexp_toolver_neroaac = VER_LAMEXP_TOOL_NEROAAC;
171 static const unsigned int g_lamexp_toolver_fhgaacenc = VER_LAMEXP_TOOL_FHGAACENC;
174 static QString g_lamexp_temp_folder;
177 static QMap<QString, LockedFile*> g_lamexp_tool_registry;
178 static QMap<QString, unsigned int> g_lamexp_tool_versions;
183 QMap<QString, QString> files;
184 QMap<QString, QString> names;
185 QMap<QString, unsigned int> sysid;
187 g_lamexp_translation;
190 static QTranslator *g_lamexp_currentTranslator = NULL;
196 char *semaphore_read;
197 char *semaphore_write;
201 "{21A68A42-6923-43bb-9CF6-64BF151942EE}",
202 "{7A605549-F58C-4d78-B4E5-06EFC34F405B}",
203 "{60AA8D04-F6B8-497d-81EB-0F600F4A65B5}"
207 QSharedMemory *sharedmem;
208 QSystemSemaphore *semaphore_read;
209 QSystemSemaphore *semaphore_write;
217 static const char *g_lamexp_imageformats[] = {"png", "jpg", "gif", "ico", "svg", NULL};
220 static QMutex g_lamexp_message_mutex;
223 static const DWORD g_main_thread_id = GetCurrentThreadId();
226 ///////////////////////////////////////////////////////////////////////////////
228 ///////////////////////////////////////////////////////////////////////////////
233 unsigned int lamexp_version_major(void) { return g_lamexp_version.ver_major; }
234 unsigned int lamexp_version_minor(void) { return g_lamexp_version.ver_minor; }
235 unsigned int lamexp_version_build(void) { return g_lamexp_version.ver_build; }
236 const char *lamexp_version_release(void) { return g_lamexp_version.ver_release_name; }
237 const char *lamexp_version_time(void) { return g_lamexp_version_raw_time; }
238 const char *lamexp_version_compiler(void) { return g_lamexp_version_compiler; }
239 const char *lamexp_version_arch(void) { return g_lamexp_version_arch; }
240 unsigned int lamexp_toolver_neroaac(void) { return g_lamexp_toolver_neroaac; }
241 unsigned int lamexp_toolver_fhgaacenc(void) { return g_lamexp_toolver_fhgaacenc; }
246 const char *lamexp_website_url(void) { return g_lamexp_website_url; }
247 const char *lamexp_support_url(void) { return g_lamexp_support_url; }
250 * Check for Demo (pre-release) version
252 bool lamexp_version_demo(void)
255 bool releaseVersion = false;
256 if(!strncpy_s(buffer, 128, g_lamexp_version.ver_release_name, _TRUNCATE))
258 char *context, *prefix = strtok_s(buffer, "-,; ", &context);
261 releaseVersion = (!_stricmp(prefix, "Final")) || (!_stricmp(prefix, "Hotfix"));
264 return LAMEXP_DEBUG || (!releaseVersion);
268 * Calculate expiration date
270 QDate lamexp_version_expires(void)
272 return lamexp_version_date().addDays(LAMEXP_DEBUG ? 2 : 30);
276 * Get build date date
278 const QDate &lamexp_version_date(void)
280 if(!g_lamexp_version_date.isValid())
285 char *this_token = NULL;
286 char *next_token = NULL;
288 strncpy_s(temp, 32, g_lamexp_version_raw_date, _TRUNCATE);
289 this_token = strtok_s(temp, " ", &next_token);
291 for(int i = 0; i < 3; i++)
296 for(int j = 0; j < 12; j++)
298 if(!_strcmpi(this_token, g_lamexp_months[j]))
306 date[i] = atoi(this_token);
308 this_token = strtok_s(NULL, " ", &next_token);
312 if(date[0] >= 0 && date[1] >= 0 && date[2] >= 0)
314 g_lamexp_version_date = QDate(date[2], date[0], date[1]);
318 return g_lamexp_version_date;
322 * Global exception handler
324 LONG WINAPI lamexp_exception_handler(__in struct _EXCEPTION_POINTERS *ExceptionInfo)
326 if(GetCurrentThreadId() != g_main_thread_id)
328 HANDLE mainThread = OpenThread(THREAD_TERMINATE, FALSE, g_main_thread_id);
329 if(mainThread) TerminateThread(mainThread, ULONG_MAX);
332 FatalAppExit(0, L"Unhandeled exception handler invoked, application will exit!");
333 TerminateProcess(GetCurrentProcess(), -1);
338 * Invalid parameters handler
340 void lamexp_invalid_param_handler(const wchar_t*, const wchar_t*, const wchar_t*, unsigned int, uintptr_t)
342 if(GetCurrentThreadId() != g_main_thread_id)
344 HANDLE mainThread = OpenThread(THREAD_TERMINATE, FALSE, g_main_thread_id);
345 if(mainThread) TerminateThread(mainThread, ULONG_MAX);
349 FatalAppExit(0, L"Invalid parameter handler invoked, application will exit!");
350 TerminateProcess(GetCurrentProcess(), -1);
354 * Change console text color
356 static void lamexp_console_color(FILE* file, WORD attributes)
358 const HANDLE hConsole = (HANDLE)(_get_osfhandle(_fileno(file)));
359 if((hConsole != NULL) && (hConsole != INVALID_HANDLE_VALUE))
361 SetConsoleTextAttribute(hConsole, attributes);
368 void lamexp_message_handler(QtMsgType type, const char *msg)
370 static const char *GURU_MEDITATION = "\n\nGURU MEDITATION !!!\n\n";
372 QMutexLocker lock(&g_lamexp_message_mutex);
374 //if((strlen(msg) > 8) && (_strnicmp(msg, "@BASE64@", 8) == 0))
376 // buffer = _strdup(QByteArray::fromBase64(msg + 8).constData());
377 // if(buffer) text = buffer;
380 if(g_lamexp_console_attached)
382 UINT oldOutputCP = GetConsoleOutputCP();
383 if(oldOutputCP != CP_UTF8) SetConsoleOutputCP(CP_UTF8);
391 lamexp_console_color(stderr, FOREGROUND_RED | FOREGROUND_INTENSITY);
392 fprintf(stderr, GURU_MEDITATION);
393 fprintf(stderr, "%s\n", msg);
397 lamexp_console_color(stderr, FOREGROUND_GREEN | FOREGROUND_RED | FOREGROUND_INTENSITY);
398 fprintf(stderr, "%s\n", msg);
402 lamexp_console_color(stderr, FOREGROUND_BLUE | FOREGROUND_GREEN | FOREGROUND_RED | FOREGROUND_INTENSITY);
403 fprintf(stderr, "%s\n", msg);
408 lamexp_console_color(stderr, FOREGROUND_BLUE | FOREGROUND_GREEN | FOREGROUND_RED);
409 if(oldOutputCP != CP_UTF8) SetConsoleOutputCP(oldOutputCP);
413 QString temp("[LameXP][%1] %2");
419 temp = temp.arg("C", QString::fromUtf8(msg));
422 temp = temp.arg("W", QString::fromUtf8(msg));
425 temp = temp.arg("I", QString::fromUtf8(msg));
429 temp.replace("\n", "\t").append("\n");
430 OutputDebugStringA(temp.toLatin1().constData());
433 if(type == QtCriticalMsg || type == QtFatalMsg)
436 MessageBoxW(NULL, QWCHAR(QString::fromUtf8(msg)), L"LameXP - GURU MEDITATION", MB_ICONERROR | MB_TOPMOST | MB_TASKMODAL);
437 FatalAppExit(0, L"The application has encountered a critical error and will exit now!");
438 TerminateProcess(GetCurrentProcess(), -1);
443 * Initialize the console
445 void lamexp_init_console(int argc, char* argv[])
447 bool enableConsole = lamexp_version_demo();
451 for(int i = 0; i < argc; i++)
453 if(!_stricmp(argv[i], "--console"))
455 enableConsole = true;
457 else if(!_stricmp(argv[i], "--no-console"))
459 enableConsole = false;
466 if(!g_lamexp_console_attached)
468 if(AllocConsole() != FALSE)
470 SetConsoleCtrlHandler(NULL, TRUE);
471 SetConsoleTitle(L"LameXP - Audio Encoder Front-End | Debug Console");
472 SetConsoleOutputCP(CP_UTF8);
473 g_lamexp_console_attached = true;
477 if(g_lamexp_console_attached)
479 //-------------------------------------------------------------------
480 //See: http://support.microsoft.com/default.aspx?scid=kb;en-us;105305
481 //-------------------------------------------------------------------
482 const int flags = _O_WRONLY | _O_U8TEXT;
483 int hCrtStdOut = _open_osfhandle((intptr_t) GetStdHandle(STD_OUTPUT_HANDLE), flags);
484 int hCrtStdErr = _open_osfhandle((intptr_t) GetStdHandle(STD_ERROR_HANDLE), flags);
485 FILE *hfStdOut = (hCrtStdOut >= 0) ? _fdopen(hCrtStdOut, "wb") : NULL;
486 FILE *hfStdErr = (hCrtStdErr >= 0) ? _fdopen(hCrtStdErr, "wb") : NULL;
487 if(hfStdOut) { *stdout = *hfStdOut; std::cout.rdbuf(new std::filebuf(hfStdOut)); }
488 if(hfStdErr) { *stderr = *hfStdErr; std::cerr.rdbuf(new std::filebuf(hfStdErr)); }
491 HWND hwndConsole = GetConsoleWindow();
493 if((hwndConsole != NULL) && (hwndConsole != INVALID_HANDLE_VALUE))
495 HMENU hMenu = GetSystemMenu(hwndConsole, 0);
496 EnableMenuItem(hMenu, SC_CLOSE, MF_BYCOMMAND | MF_GRAYED);
497 RemoveMenu(hMenu, SC_CLOSE, MF_BYCOMMAND);
499 SetWindowPos(hwndConsole, HWND_TOP, 0, 0, 0, 0, SWP_NOMOVE|SWP_NOSIZE|SWP_NOZORDER|SWP_FRAMECHANGED);
500 SetWindowLong(hwndConsole, GWL_STYLE, GetWindowLong(hwndConsole, GWL_STYLE) & (~WS_MAXIMIZEBOX) & (~WS_MINIMIZEBOX));
501 SetWindowPos(hwndConsole, HWND_TOP, 0, 0, 0, 0, SWP_NOMOVE|SWP_NOSIZE|SWP_NOZORDER|SWP_FRAMECHANGED);
507 * Detect CPU features
509 lamexp_cpu_t lamexp_detect_cpu_features(int argc, char **argv)
511 typedef BOOL (WINAPI *IsWow64ProcessFun)(__in HANDLE hProcess, __out PBOOL Wow64Process);
512 typedef VOID (WINAPI *GetNativeSystemInfoFun)(__out LPSYSTEM_INFO lpSystemInfo);
514 static IsWow64ProcessFun IsWow64ProcessPtr = NULL;
515 static GetNativeSystemInfoFun GetNativeSystemInfoPtr = NULL;
517 lamexp_cpu_t features;
518 SYSTEM_INFO systemInfo;
519 int CPUInfo[4] = {-1};
520 char CPUIdentificationString[0x40];
521 char CPUBrandString[0x40];
523 memset(&features, 0, sizeof(lamexp_cpu_t));
524 memset(&systemInfo, 0, sizeof(SYSTEM_INFO));
525 memset(CPUIdentificationString, 0, sizeof(CPUIdentificationString));
526 memset(CPUBrandString, 0, sizeof(CPUBrandString));
529 memcpy(CPUIdentificationString, &CPUInfo[1], sizeof(int));
530 memcpy(CPUIdentificationString + 4, &CPUInfo[3], sizeof(int));
531 memcpy(CPUIdentificationString + 8, &CPUInfo[2], sizeof(int));
532 features.intel = (_stricmp(CPUIdentificationString, "GenuineIntel") == 0);
533 strncpy_s(features.vendor, 0x40, CPUIdentificationString, _TRUNCATE);
538 features.mmx = (CPUInfo[3] & 0x800000) || false;
539 features.sse = (CPUInfo[3] & 0x2000000) || false;
540 features.sse2 = (CPUInfo[3] & 0x4000000) || false;
541 features.ssse3 = (CPUInfo[2] & 0x200) || false;
542 features.sse3 = (CPUInfo[2] & 0x1) || false;
543 features.ssse3 = (CPUInfo[2] & 0x200) || false;
544 features.stepping = CPUInfo[0] & 0xf;
545 features.model = ((CPUInfo[0] >> 4) & 0xf) + (((CPUInfo[0] >> 16) & 0xf) << 4);
546 features.family = ((CPUInfo[0] >> 8) & 0xf) + ((CPUInfo[0] >> 20) & 0xff);
549 __cpuid(CPUInfo, 0x80000000);
550 int nExIds = max(min(CPUInfo[0], 0x80000004), 0x80000000);
552 for(int i = 0x80000002; i <= nExIds; ++i)
558 memcpy(CPUBrandString, CPUInfo, sizeof(CPUInfo));
561 memcpy(CPUBrandString + 16, CPUInfo, sizeof(CPUInfo));
564 memcpy(CPUBrandString + 32, CPUInfo, sizeof(CPUInfo));
569 strncpy_s(features.brand, 0x40, CPUBrandString, _TRUNCATE);
571 if(strlen(features.brand) < 1) strncpy_s(features.brand, 0x40, "Unknown", _TRUNCATE);
572 if(strlen(features.vendor) < 1) strncpy_s(features.vendor, 0x40, "Unknown", _TRUNCATE);
574 #if !defined(_M_X64 ) && !defined(_M_IA64)
575 if(!IsWow64ProcessPtr || !GetNativeSystemInfoPtr)
577 QLibrary Kernel32Lib("kernel32.dll");
578 IsWow64ProcessPtr = (IsWow64ProcessFun) Kernel32Lib.resolve("IsWow64Process");
579 GetNativeSystemInfoPtr = (GetNativeSystemInfoFun) Kernel32Lib.resolve("GetNativeSystemInfo");
581 if(IsWow64ProcessPtr)
584 if(IsWow64ProcessPtr(GetCurrentProcess(), &x64))
589 if(GetNativeSystemInfoPtr)
591 GetNativeSystemInfoPtr(&systemInfo);
595 GetSystemInfo(&systemInfo);
597 features.count = systemInfo.dwNumberOfProcessors;
599 GetNativeSystemInfo(&systemInfo);
600 features.count = systemInfo.dwNumberOfProcessors;
606 for(int i = 0; i < argc; i++)
608 if(!_stricmp("--force-cpu-no-64bit", argv[i])) features.x64 = false;
609 if(!_stricmp("--force-cpu-no-sse", argv[i])) features.sse = features.sse2 = features.sse3 = features.ssse3 = false;
610 if(!_stricmp("--force-cpu-no-intel", argv[i])) features.intel = false;
618 * Check for debugger (detect routine)
620 static bool lamexp_check_for_debugger(void)
626 __except(GetExceptionCode() == EXCEPTION_BREAKPOINT ? EXCEPTION_EXECUTE_HANDLER : EXCEPTION_CONTINUE_SEARCH)
634 * Check for debugger (thread proc)
636 static void WINAPI lamexp_debug_thread_proc(__in LPVOID lpParameter)
638 while(!(IsDebuggerPresent() || lamexp_check_for_debugger()))
642 TerminateProcess(GetCurrentProcess(), -1);
646 * Check for debugger (startup routine)
648 static HANDLE lamexp_debug_thread_init(void)
650 if(IsDebuggerPresent() || lamexp_check_for_debugger())
652 FatalAppExit(0, L"Not a debug build. Please unload debugger and try again!");
653 TerminateProcess(GetCurrentProcess(), -1);
656 return CreateThread(NULL, NULL, reinterpret_cast<LPTHREAD_START_ROUTINE>(&lamexp_debug_thread_proc), NULL, NULL, NULL);
660 * Check for compatibility mode
662 static bool lamexp_check_compatibility_mode(const char *exportName, const char *executableName)
664 QLibrary kernel32("kernel32.dll");
666 if(exportName != NULL)
668 if(kernel32.resolve(exportName) != NULL)
670 qWarning("Function '%s' exported from 'kernel32.dll' -> Windows compatibility mode!", exportName);
671 qFatal("%s", QApplication::tr("Executable '%1' doesn't support Windows compatibility mode.").arg(QString::fromLatin1(executableName)).toLatin1().constData());
680 * Check for process elevation
682 static bool lamexp_check_elevation(void)
684 typedef enum { lamexp_token_elevationType_class = 18, lamexp_token_elevation_class = 20 } LAMEXP_TOKEN_INFORMATION_CLASS;
685 typedef enum { lamexp_elevationType_default = 1, lamexp_elevationType_full, lamexp_elevationType_limited } LAMEXP_TOKEN_ELEVATION_TYPE;
687 HANDLE hToken = NULL;
688 bool bIsProcessElevated = false;
690 if(OpenProcessToken(GetCurrentProcess(), TOKEN_QUERY, &hToken))
692 LAMEXP_TOKEN_ELEVATION_TYPE tokenElevationType;
694 if(GetTokenInformation(hToken, (TOKEN_INFORMATION_CLASS) lamexp_token_elevationType_class, &tokenElevationType, sizeof(LAMEXP_TOKEN_ELEVATION_TYPE), &returnLength))
696 if(returnLength == sizeof(LAMEXP_TOKEN_ELEVATION_TYPE))
698 switch(tokenElevationType)
700 case lamexp_elevationType_default:
701 qDebug("Process token elevation type: Default -> UAC is disabled.\n");
703 case lamexp_elevationType_full:
704 qWarning("Process token elevation type: Full -> potential security risk!\n");
705 bIsProcessElevated = true;
707 case lamexp_elevationType_limited:
708 qDebug("Process token elevation type: Limited -> not elevated.\n");
717 qWarning("Failed to open process token!");
720 return !bIsProcessElevated;
724 * Initialize Qt framework
726 bool lamexp_init_qt(int argc, char* argv[])
728 static bool qt_initialized = false;
730 typedef BOOL (WINAPI *SetDllDirectoryProc)(WCHAR *lpPathName);
732 //Don't initialized again, if done already
739 QLibrary kernel32("kernel32.dll");
742 SetDllDirectoryProc pSetDllDirectory = (SetDllDirectoryProc) kernel32.resolve("SetDllDirectoryW");
743 if(pSetDllDirectory != NULL) pSetDllDirectory(L"");
747 //Extract executable name from argv[] array
748 char *executableName = argv[0];
749 while(char *temp = strpbrk(executableName, "\\/:?"))
751 executableName = temp + 1;
755 qDebug("Using Qt Framework v%s, compiled with Qt v%s [%s]", qVersion(), QT_VERSION_STR, QT_PACKAGEDATE_STR);
756 if(_stricmp(qVersion(), QT_VERSION_STR))
758 qFatal("%s", QApplication::tr("Executable '%1' requires Qt v%2, but found Qt v%3.").arg(QString::fromLatin1(executableName), QString::fromLatin1(QT_VERSION_STR), QString::fromLatin1(qVersion())).toLatin1().constData());
762 //Check the Windows version
763 switch(QSysInfo::windowsVersion() & QSysInfo::WV_NT_based)
766 case QSysInfo::WV_NT:
767 qFatal("%s", QApplication::tr("Executable '%1' requires Windows 2000 or later.").arg(QString::fromLatin1(executableName)).toLatin1().constData());
769 case QSysInfo::WV_2000:
770 qDebug("Running on Windows 2000 (not officially supported!).\n");
771 lamexp_check_compatibility_mode("GetNativeSystemInfo", executableName);
773 case QSysInfo::WV_XP:
774 qDebug("Running on Windows XP.\n");
775 lamexp_check_compatibility_mode("GetLargePageMinimum", executableName);
777 case QSysInfo::WV_2003:
778 qDebug("Running on Windows Server 2003 or Windows XP x64-Edition.\n");
779 lamexp_check_compatibility_mode("GetLocaleInfoEx", executableName);
781 case QSysInfo::WV_VISTA:
782 qDebug("Running on Windows Vista or Windows Server 2008.\n");
783 lamexp_check_compatibility_mode("CreateRemoteThreadEx", executableName);
785 case QSysInfo::WV_WINDOWS7:
786 qDebug("Running on Windows 7 or Windows Server 2008 R2.\n");
787 lamexp_check_compatibility_mode(NULL, executableName);
790 qWarning("Running on an unknown/untested WinNT-based OS.\n");
795 QLibrary ntdll("ntdll.dll");
798 if(ntdll.resolve("wine_nt_to_unix_file_name") != NULL) isWine = true;
799 if(ntdll.resolve("wine_get_version") != NULL) isWine = true;
800 if(isWine) qWarning("It appears we are running under Wine, unexpected things might happen!\n");
804 //Create Qt application instance and setup version info
805 QDate date = QDate::currentDate();
806 QApplication *application = new QApplication(argc, argv);
807 application->setApplicationName("LameXP - Audio Encoder Front-End");
808 application->setApplicationVersion(QString().sprintf("%d.%02d.%04d", lamexp_version_major(), lamexp_version_minor(), lamexp_version_build()));
809 application->setOrganizationName("LoRd_MuldeR");
810 application->setOrganizationDomain("mulder.at.gg");
811 application->setWindowIcon((date.month() == 12 && date.day() >= 24 && date.day() <= 26) ? QIcon(":/MainIcon2.png") : QIcon(":/MainIcon.png"));
813 //Set text Codec for locale
814 QTextCodec::setCodecForLocale(QTextCodec::codecForName("UTF-8"));
816 //Load plugins from application directory
817 QCoreApplication::setLibraryPaths(QStringList() << QApplication::applicationDirPath());
818 qDebug("Library Path:\n%s\n", QApplication::libraryPaths().first().toUtf8().constData());
820 //Check for supported image formats
821 QList<QByteArray> supportedFormats = QImageReader::supportedImageFormats();
822 for(int i = 0; g_lamexp_imageformats[i]; i++)
824 if(!supportedFormats.contains(g_lamexp_imageformats[i]))
826 qFatal("Qt initialization error: QImageIOHandler for '%s' missing!", g_lamexp_imageformats[i]);
831 //Add default translations
832 g_lamexp_translation.files.insert(LAMEXP_DEFAULT_LANGID, "");
833 g_lamexp_translation.names.insert(LAMEXP_DEFAULT_LANGID, "English");
835 //Check for process elevation
836 if(!lamexp_check_elevation())
838 if(QMessageBox::warning(NULL, "LameXP", "<nobr>LameXP was started with elevated rights. This is a potential security risk!</nobr>", "Quit Program (Recommended)", "Ignore") == 0)
844 //Update console icon, if a console is attached
845 if(g_lamexp_console_attached && !isWine)
847 typedef DWORD (__stdcall *SetConsoleIconFun)(HICON);
848 QLibrary kernel32("kernel32.dll");
851 SetConsoleIconFun SetConsoleIconPtr = (SetConsoleIconFun) kernel32.resolve("SetConsoleIcon");
852 if(SetConsoleIconPtr != NULL) SetConsoleIconPtr(QIcon(":/icons/sound.png").pixmap(16, 16).toWinHICON());
858 qt_initialized = true;
865 int lamexp_init_ipc(void)
867 if(g_lamexp_ipc_ptr.sharedmem && g_lamexp_ipc_ptr.semaphore_read && g_lamexp_ipc_ptr.semaphore_write)
872 g_lamexp_ipc_ptr.semaphore_read = new QSystemSemaphore(QString(g_lamexp_ipc_uuid.semaphore_read), 0);
873 g_lamexp_ipc_ptr.semaphore_write = new QSystemSemaphore(QString(g_lamexp_ipc_uuid.semaphore_write), 0);
875 if(g_lamexp_ipc_ptr.semaphore_read->error() != QSystemSemaphore::NoError)
877 QString errorMessage = g_lamexp_ipc_ptr.semaphore_read->errorString();
878 LAMEXP_DELETE(g_lamexp_ipc_ptr.semaphore_read);
879 LAMEXP_DELETE(g_lamexp_ipc_ptr.semaphore_write);
880 qFatal("Failed to create system smaphore: %s", errorMessage.toUtf8().constData());
883 if(g_lamexp_ipc_ptr.semaphore_write->error() != QSystemSemaphore::NoError)
885 QString errorMessage = g_lamexp_ipc_ptr.semaphore_write->errorString();
886 LAMEXP_DELETE(g_lamexp_ipc_ptr.semaphore_read);
887 LAMEXP_DELETE(g_lamexp_ipc_ptr.semaphore_write);
888 qFatal("Failed to create system smaphore: %s", errorMessage.toUtf8().constData());
892 g_lamexp_ipc_ptr.sharedmem = new QSharedMemory(QString(g_lamexp_ipc_uuid.sharedmem), NULL);
894 if(!g_lamexp_ipc_ptr.sharedmem->create(sizeof(lamexp_ipc_t)))
896 if(g_lamexp_ipc_ptr.sharedmem->error() == QSharedMemory::AlreadyExists)
898 g_lamexp_ipc_ptr.sharedmem->attach();
899 if(g_lamexp_ipc_ptr.sharedmem->error() == QSharedMemory::NoError)
905 QString errorMessage = g_lamexp_ipc_ptr.sharedmem->errorString();
906 qFatal("Failed to attach to shared memory: %s", errorMessage.toUtf8().constData());
912 QString errorMessage = g_lamexp_ipc_ptr.sharedmem->errorString();
913 qFatal("Failed to create shared memory: %s", errorMessage.toUtf8().constData());
918 memset(g_lamexp_ipc_ptr.sharedmem->data(), 0, sizeof(lamexp_ipc_t));
919 g_lamexp_ipc_ptr.semaphore_write->release();
927 void lamexp_ipc_send(unsigned int command, const char* message)
929 if(!g_lamexp_ipc_ptr.sharedmem || !g_lamexp_ipc_ptr.semaphore_read || !g_lamexp_ipc_ptr.semaphore_write)
931 throw "Shared memory for IPC not initialized yet.";
934 lamexp_ipc_t *lamexp_ipc = new lamexp_ipc_t;
935 memset(lamexp_ipc, 0, sizeof(lamexp_ipc_t));
936 lamexp_ipc->command = command;
939 strncpy_s(lamexp_ipc->parameter, 4096, message, _TRUNCATE);
942 if(g_lamexp_ipc_ptr.semaphore_write->acquire())
944 memcpy(g_lamexp_ipc_ptr.sharedmem->data(), lamexp_ipc, sizeof(lamexp_ipc_t));
945 g_lamexp_ipc_ptr.semaphore_read->release();
948 LAMEXP_DELETE(lamexp_ipc);
954 void lamexp_ipc_read(unsigned int *command, char* message, size_t buffSize)
959 if(!g_lamexp_ipc_ptr.sharedmem || !g_lamexp_ipc_ptr.semaphore_read || !g_lamexp_ipc_ptr.semaphore_write)
961 throw "Shared memory for IPC not initialized yet.";
964 lamexp_ipc_t *lamexp_ipc = new lamexp_ipc_t;
965 memset(lamexp_ipc, 0, sizeof(lamexp_ipc_t));
967 if(g_lamexp_ipc_ptr.semaphore_read->acquire())
969 memcpy(lamexp_ipc, g_lamexp_ipc_ptr.sharedmem->data(), sizeof(lamexp_ipc_t));
970 g_lamexp_ipc_ptr.semaphore_write->release();
972 if(!(lamexp_ipc->reserved_1 || lamexp_ipc->reserved_2))
974 *command = lamexp_ipc->command;
975 strncpy_s(message, buffSize, lamexp_ipc->parameter, _TRUNCATE);
979 qWarning("Malformed IPC message, will be ignored");
983 LAMEXP_DELETE(lamexp_ipc);
987 * Check for LameXP "portable" mode
989 bool lamexp_portable_mode(void)
991 QString baseName = QFileInfo(QApplication::applicationFilePath()).completeBaseName();
992 int idx1 = baseName.indexOf("lamexp", 0, Qt::CaseInsensitive);
993 int idx2 = baseName.lastIndexOf("portable", -1, Qt::CaseInsensitive);
994 return (idx1 >= 0) && (idx2 >= 0) && (idx1 < idx2);
998 * Get a random string
1000 QString lamexp_rand_str(void)
1002 QRegExp regExp("\\{(\\w+)-(\\w+)-(\\w+)-(\\w+)-(\\w+)\\}");
1003 QString uuid = QUuid::createUuid().toString();
1005 if(regExp.indexIn(uuid) >= 0)
1007 return QString().append(regExp.cap(1)).append(regExp.cap(2)).append(regExp.cap(3)).append(regExp.cap(4)).append(regExp.cap(5));
1010 throw "The RegExp didn't match on the UUID string. This shouldn't happen ;-)";
1014 * Get LameXP temp folder
1016 const QString &lamexp_temp_folder2(void)
1018 static const char *TEMP_STR = "Temp";
1019 const QString WRITE_TEST_DATA = lamexp_rand_str();
1020 const QString SUB_FOLDER = lamexp_rand_str();
1022 //Already initialized?
1023 if(!g_lamexp_temp_folder.isEmpty())
1025 if(QDir(g_lamexp_temp_folder).exists())
1027 return g_lamexp_temp_folder;
1031 g_lamexp_temp_folder.clear();
1035 //Try the %TMP% or %TEMP% directory first
1036 QDir temp = QDir::temp();
1039 temp.mkdir(SUB_FOLDER);
1040 if(temp.cd(SUB_FOLDER) && temp.exists())
1042 QFile testFile(QString("%1/~%2.tmp").arg(temp.canonicalPath(), lamexp_rand_str()));
1043 if(testFile.open(QIODevice::ReadWrite))
1045 if(testFile.write(WRITE_TEST_DATA.toLatin1().constData()) >= strlen(WRITE_TEST_DATA.toLatin1().constData()))
1047 g_lamexp_temp_folder = temp.canonicalPath();
1052 if(!g_lamexp_temp_folder.isEmpty())
1054 return g_lamexp_temp_folder;
1058 //Create TEMP folder in %LOCALAPPDATA%
1059 QDir localAppData = QDir(lamexp_known_folder(lamexp_folder_localappdata));
1060 if(!localAppData.path().isEmpty())
1062 if(!localAppData.exists())
1064 localAppData.mkpath(".");
1066 if(localAppData.exists())
1068 if(!localAppData.entryList(QDir::AllDirs).contains(TEMP_STR, Qt::CaseInsensitive))
1070 localAppData.mkdir(TEMP_STR);
1072 if(localAppData.cd(TEMP_STR) && localAppData.exists())
1074 localAppData.mkdir(SUB_FOLDER);
1075 if(localAppData.cd(SUB_FOLDER) && localAppData.exists())
1077 QFile testFile(QString("%1/~%2.tmp").arg(localAppData.canonicalPath(), lamexp_rand_str()));
1078 if(testFile.open(QIODevice::ReadWrite))
1080 if(testFile.write(WRITE_TEST_DATA.toLatin1().constData()) >= strlen(WRITE_TEST_DATA.toLatin1().constData()))
1082 g_lamexp_temp_folder = localAppData.canonicalPath();
1089 if(!g_lamexp_temp_folder.isEmpty())
1091 return g_lamexp_temp_folder;
1095 //Failed to create TEMP folder!
1096 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());
1097 return g_lamexp_temp_folder;
1103 bool lamexp_clean_folder(const QString &folderPath)
1105 QDir tempFolder(folderPath);
1106 QFileInfoList entryList = tempFolder.entryInfoList(QDir::AllEntries | QDir::NoDotAndDotDot);
1108 for(int i = 0; i < entryList.count(); i++)
1110 if(entryList.at(i).isDir())
1112 lamexp_clean_folder(entryList.at(i).canonicalFilePath());
1116 for(int j = 0; j < 3; j++)
1118 if(lamexp_remove_file(entryList.at(i).canonicalFilePath()))
1126 tempFolder.rmdir(".");
1127 return !tempFolder.exists();
1133 void lamexp_register_tool(const QString &toolName, LockedFile *file, unsigned int version)
1135 if(g_lamexp_tool_registry.contains(toolName.toLower()))
1137 throw "lamexp_register_tool: Tool is already registered!";
1140 g_lamexp_tool_registry.insert(toolName.toLower(), file);
1141 g_lamexp_tool_versions.insert(toolName.toLower(), version);
1147 bool lamexp_check_tool(const QString &toolName)
1149 return g_lamexp_tool_registry.contains(toolName.toLower());
1155 const QString lamexp_lookup_tool(const QString &toolName)
1157 if(g_lamexp_tool_registry.contains(toolName.toLower()))
1159 return g_lamexp_tool_registry.value(toolName.toLower())->filePath();
1168 * Lookup tool version
1170 unsigned int lamexp_tool_version(const QString &toolName)
1172 if(g_lamexp_tool_versions.contains(toolName.toLower()))
1174 return g_lamexp_tool_versions.value(toolName.toLower());
1183 * Version number to human-readable string
1185 const QString lamexp_version2string(const QString &pattern, unsigned int version, const QString &defaultText)
1187 if(version == UINT_MAX)
1192 QString result = pattern;
1193 int digits = result.count("?", Qt::CaseInsensitive);
1201 QString versionStr = QString().sprintf(QString().sprintf("%%0%du", digits).toLatin1().constData(), version);
1202 int index = result.indexOf("?", Qt::CaseInsensitive);
1204 while(index >= 0 && pos < versionStr.length())
1206 result[index] = versionStr[pos++];
1207 index = result.indexOf("?", Qt::CaseInsensitive);
1214 * Register a new translation
1216 bool lamexp_translation_register(const QString &langId, const QString &qmFile, const QString &langName, unsigned int &systemId)
1218 if(qmFile.isEmpty() || langName.isEmpty() || systemId < 1)
1223 g_lamexp_translation.files.insert(langId, qmFile);
1224 g_lamexp_translation.names.insert(langId, langName);
1225 g_lamexp_translation.sysid.insert(langId, systemId);
1231 * Get list of all translations
1233 QStringList lamexp_query_translations(void)
1235 return g_lamexp_translation.files.keys();
1239 * Get translation name
1241 QString lamexp_translation_name(const QString &langId)
1243 return g_lamexp_translation.names.value(langId.toLower(), QString());
1247 * Get translation system id
1249 unsigned int lamexp_translation_sysid(const QString &langId)
1251 return g_lamexp_translation.sysid.value(langId.toLower(), 0);
1255 * Install a new translator
1257 bool lamexp_install_translator(const QString &langId)
1259 bool success = false;
1261 if(langId.isEmpty() || langId.toLower().compare(LAMEXP_DEFAULT_LANGID) == 0)
1263 success = lamexp_install_translator_from_file(QString());
1267 QString qmFile = g_lamexp_translation.files.value(langId.toLower(), QString());
1268 if(!qmFile.isEmpty())
1270 success = lamexp_install_translator_from_file(QString(":/localization/%1").arg(qmFile));
1274 qWarning("Translation '%s' not available!", langId.toLatin1().constData());
1282 * Install a new translator from file
1284 bool lamexp_install_translator_from_file(const QString &qmFile)
1286 bool success = false;
1288 if(!g_lamexp_currentTranslator)
1290 g_lamexp_currentTranslator = new QTranslator();
1293 if(!qmFile.isEmpty())
1295 QString qmPath = QFileInfo(qmFile).canonicalFilePath();
1296 QApplication::removeTranslator(g_lamexp_currentTranslator);
1297 success = g_lamexp_currentTranslator->load(qmPath);
1298 QApplication::installTranslator(g_lamexp_currentTranslator);
1301 qWarning("Failed to load translation:\n\"%s\"", qmPath.toLatin1().constData());
1306 QApplication::removeTranslator(g_lamexp_currentTranslator);
1314 * Locate known folder on local system
1316 QString lamexp_known_folder(lamexp_known_folder_t folder_id)
1318 typedef HRESULT (WINAPI *SHGetKnownFolderPathFun)(__in const GUID &rfid, __in DWORD dwFlags, __in HANDLE hToken, __out PWSTR *ppszPath);
1319 typedef HRESULT (WINAPI *SHGetFolderPathFun)(__in HWND hwndOwner, __in int nFolder, __in HANDLE hToken, __in DWORD dwFlags, __out LPWSTR pszPath);
1321 static const int CSIDL_LOCAL_APPDATA = 0x001c;
1322 static const int CSIDL_PROGRAM_FILES = 0x0026;
1323 static const int CSIDL_SYSTEM_FOLDER = 0x0025;
1324 static const GUID GUID_LOCAL_APPDATA = {0xF1B32785,0x6FBA,0x4FCF,{0x9D,0x55,0x7B,0x8E,0x7F,0x15,0x70,0x91}};
1325 static const GUID GUID_LOCAL_APPDATA_LOW = {0xA520A1A4,0x1780,0x4FF6,{0xBD,0x18,0x16,0x73,0x43,0xC5,0xAF,0x16}};
1326 static const GUID GUID_PROGRAM_FILES = {0x905e63b6,0xc1bf,0x494e,{0xb2,0x9c,0x65,0xb7,0x32,0xd3,0xd2,0x1a}};
1327 static const GUID GUID_SYSTEM_FOLDER = {0x1AC14E77,0x02E7,0x4E5D,{0xB7,0x44,0x2E,0xB1,0xAE,0x51,0x98,0xB7}};
1329 static QLibrary *Kernel32Lib = NULL;
1330 static SHGetKnownFolderPathFun SHGetKnownFolderPathPtr = NULL;
1331 static SHGetFolderPathFun SHGetFolderPathPtr = NULL;
1333 if((!SHGetKnownFolderPathPtr) && (!SHGetFolderPathPtr))
1335 if(!Kernel32Lib) Kernel32Lib = new QLibrary("shell32.dll");
1336 SHGetKnownFolderPathPtr = (SHGetKnownFolderPathFun) Kernel32Lib->resolve("SHGetKnownFolderPath");
1337 SHGetFolderPathPtr = (SHGetFolderPathFun) Kernel32Lib->resolve("SHGetFolderPathW");
1340 int folderCSIDL = -1;
1341 GUID folderGUID = {0x0000,0x0000,0x0000,{0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00}};
1345 case lamexp_folder_localappdata:
1346 folderCSIDL = CSIDL_LOCAL_APPDATA;
1347 folderGUID = GUID_LOCAL_APPDATA;
1349 case lamexp_folder_programfiles:
1350 folderCSIDL = CSIDL_PROGRAM_FILES;
1351 folderGUID = GUID_PROGRAM_FILES;
1353 case lamexp_folder_systemfolder:
1354 folderCSIDL = CSIDL_SYSTEM_FOLDER;
1355 folderGUID = GUID_SYSTEM_FOLDER;
1364 if(SHGetKnownFolderPathPtr)
1367 if(SHGetKnownFolderPathPtr(folderGUID, 0x00008000, NULL, &path) == S_OK)
1369 //MessageBoxW(0, path, L"SHGetKnownFolderPath", MB_TOPMOST);
1370 QDir folderTemp = QDir(QDir::fromNativeSeparators(QString::fromUtf16(reinterpret_cast<const unsigned short*>(path))));
1371 if(!folderTemp.exists())
1373 folderTemp.mkpath(".");
1375 if(folderTemp.exists())
1377 folder = folderTemp.canonicalPath();
1379 CoTaskMemFree(path);
1382 else if(SHGetFolderPathPtr)
1384 WCHAR *path = new WCHAR[4096];
1385 if(SHGetFolderPathPtr(NULL, folderCSIDL, NULL, NULL, path) == S_OK)
1387 //MessageBoxW(0, path, L"SHGetFolderPathW", MB_TOPMOST);
1388 QDir folderTemp = QDir(QDir::fromNativeSeparators(QString::fromUtf16(reinterpret_cast<const unsigned short*>(path))));
1389 if(!folderTemp.exists())
1391 folderTemp.mkpath(".");
1393 if(folderTemp.exists())
1395 folder = folderTemp.canonicalPath();
1405 * Safely remove a file
1407 bool lamexp_remove_file(const QString &filename)
1409 if(!QFileInfo(filename).exists() || !QFileInfo(filename).isFile())
1415 if(!QFile::remove(filename))
1417 DWORD attributes = GetFileAttributesW(QWCHAR(filename));
1418 SetFileAttributesW(QWCHAR(filename), (attributes & (~FILE_ATTRIBUTE_READONLY)));
1419 if(!QFile::remove(filename))
1421 qWarning("Could not delete \"%s\"", filename.toLatin1().constData());
1437 * Check if visual themes are enabled (WinXP and later)
1439 bool lamexp_themes_enabled(void)
1441 typedef int (WINAPI *IsAppThemedFun)(void);
1443 bool isAppThemed = false;
1444 QLibrary uxTheme(QString("%1/UxTheme.dll").arg(lamexp_known_folder(lamexp_folder_systemfolder)));
1445 IsAppThemedFun IsAppThemedPtr = (IsAppThemedFun) uxTheme.resolve("IsAppThemed");
1449 isAppThemed = IsAppThemedPtr();
1452 qWarning("Theme support is disabled for this process!");
1460 * Get number of free bytes on disk
1462 __int64 lamexp_free_diskspace(const QString &path)
1464 ULARGE_INTEGER freeBytesAvailable, totalNumberOfBytes, totalNumberOfFreeBytes;
1465 if(GetDiskFreeSpaceExW(reinterpret_cast<const wchar_t*>(QDir::toNativeSeparators(path).utf16()), &freeBytesAvailable, &totalNumberOfBytes, &totalNumberOfFreeBytes))
1467 return freeBytesAvailable.QuadPart;
1476 * Shutdown the computer
1478 bool lamexp_shutdown_computer(const QString &message, const unsigned long timeout, const bool forceShutdown)
1480 HANDLE hToken = NULL;
1482 if(OpenProcessToken(GetCurrentProcess(), TOKEN_ADJUST_PRIVILEGES | TOKEN_QUERY, &hToken))
1484 TOKEN_PRIVILEGES privileges;
1485 memset(&privileges, 0, sizeof(TOKEN_PRIVILEGES));
1486 privileges.PrivilegeCount = 1;
1487 privileges.Privileges[0].Attributes = SE_PRIVILEGE_ENABLED;
1489 if(LookupPrivilegeValue(NULL, SE_SHUTDOWN_NAME, &privileges.Privileges[0].Luid))
1491 if(AdjustTokenPrivileges(hToken, FALSE, &privileges, NULL, NULL, NULL))
1493 const DWORD reason = SHTDN_REASON_MAJOR_APPLICATION | SHTDN_REASON_FLAG_PLANNED;
1494 return InitiateSystemShutdownEx(NULL, const_cast<wchar_t*>(QWCHAR(message)), timeout, forceShutdown, FALSE, reason);
1503 * Make a window blink (to draw user's attention)
1505 void lamexp_blink_window(QWidget *poWindow, unsigned int count, unsigned int delay)
1507 static QMutex blinkMutex;
1509 const double maxOpac = 1.0;
1510 const double minOpac = 0.3;
1511 const double delOpac = 0.1;
1513 if(!blinkMutex.tryLock())
1515 qWarning("Blinking is already in progress, skipping!");
1521 const int steps = static_cast<int>(ceil(maxOpac - minOpac) / delOpac);
1522 const int sleep = static_cast<int>(floor(static_cast<double>(delay) / static_cast<double>(steps)));
1523 const double opacity = poWindow->windowOpacity();
1525 for(unsigned int i = 0; i < count; i++)
1527 for(double x = maxOpac; x >= minOpac; x -= delOpac)
1529 poWindow->setWindowOpacity(x);
1530 QApplication::processEvents();
1534 for(double x = minOpac; x <= maxOpac; x += delOpac)
1536 poWindow->setWindowOpacity(x);
1537 QApplication::processEvents();
1542 poWindow->setWindowOpacity(opacity);
1543 QApplication::processEvents();
1544 blinkMutex.unlock();
1548 blinkMutex.unlock();
1549 qWarning("Exception error while blinking!");
1554 * Remove forbidden characters from a filename
1556 const QString lamexp_clean_filename(const QString &str)
1558 QString newStr(str);
1560 newStr.replace("\\", "-");
1561 newStr.replace(" / ", ", ");
1562 newStr.replace("/", ",");
1563 newStr.replace(":", "-");
1564 newStr.replace("*", "x");
1565 newStr.replace("?", "");
1566 newStr.replace("<", "[");
1567 newStr.replace(">", "]");
1568 newStr.replace("|", "!");
1570 return newStr.simplified();
1574 * Remove forbidden characters from a file path
1576 const QString lamexp_clean_filepath(const QString &str)
1578 QStringList parts = QString(str).replace("\\", "/").split("/");
1580 for(int i = 0; i < parts.count(); i++)
1582 parts[i] = lamexp_clean_filename(parts[i]);
1585 return parts.join("/");
1589 * Finalization function (final clean-up)
1591 void lamexp_finalization(void)
1594 if(!g_lamexp_tool_registry.isEmpty())
1596 QStringList keys = g_lamexp_tool_registry.keys();
1597 for(int i = 0; i < keys.count(); i++)
1599 LAMEXP_DELETE(g_lamexp_tool_registry[keys.at(i)]);
1601 g_lamexp_tool_registry.clear();
1602 g_lamexp_tool_versions.clear();
1605 //Delete temporary files
1606 if(!g_lamexp_temp_folder.isEmpty())
1608 for(int i = 0; i < 100; i++)
1610 if(lamexp_clean_folder(g_lamexp_temp_folder))
1616 g_lamexp_temp_folder.clear();
1620 if(g_lamexp_currentTranslator)
1622 QApplication::removeTranslator(g_lamexp_currentTranslator);
1623 LAMEXP_DELETE(g_lamexp_currentTranslator);
1625 g_lamexp_translation.files.clear();
1626 g_lamexp_translation.names.clear();
1628 //Destroy Qt application object
1629 QApplication *application = dynamic_cast<QApplication*>(QApplication::instance());
1630 LAMEXP_DELETE(application);
1632 //Detach from shared memory
1633 if(g_lamexp_ipc_ptr.sharedmem) g_lamexp_ipc_ptr.sharedmem->detach();
1634 LAMEXP_DELETE(g_lamexp_ipc_ptr.sharedmem);
1635 LAMEXP_DELETE(g_lamexp_ipc_ptr.semaphore_read);
1636 LAMEXP_DELETE(g_lamexp_ipc_ptr.semaphore_write);
1640 * Initialize debug thread
1642 static const HANDLE g_debug_thread = LAMEXP_DEBUG ? NULL : lamexp_debug_thread_init();
1645 * Get number private bytes [debug only]
1647 SIZE_T lamexp_dbg_private_bytes(void)
1650 PROCESS_MEMORY_COUNTERS_EX memoryCounters;
1651 memoryCounters.cb = sizeof(PROCESS_MEMORY_COUNTERS_EX);
1652 GetProcessMemoryInfo(GetCurrentProcess(), (PPROCESS_MEMORY_COUNTERS) &memoryCounters, sizeof(PROCESS_MEMORY_COUNTERS_EX));
1653 return memoryCounters.PrivateUsage;
1655 throw "Cannot call this function in a non-debug build!";
1656 #endif //LAMEXP_DEBUG