Implemented a very basic Cue Sheet parser.
[LameXP.git] / src / Global.cpp
blobf6ee3dc9901d377de18f1bea82ddcd54c4b3b80e
1 ///////////////////////////////////////////////////////////////////////////////
2 // LameXP - Audio Encoder Front-End
3 // Copyright (C) 2004-2011 LoRd_MuldeR <MuldeR2@GMX.de>
4 //
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.
9 //
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 ///////////////////////////////////////////////////////////////////////////////
22 #include "Global.h"
24 //Qt includes
25 #include <QApplication>
26 #include <QMessageBox>
27 #include <QDir>
28 #include <QUuid>
29 #include <QMap>
30 #include <QDate>
31 #include <QIcon>
32 #include <QPlastiqueStyle>
33 #include <QImageReader>
34 #include <QSharedMemory>
35 #include <QSysInfo>
36 #include <QStringList>
37 #include <QSystemSemaphore>
38 #include <QMutex>
39 #include <QTextCodec>
40 #include <QLibrary>
41 #include <QRegExp>
42 #include <QResource>
43 #include <QTranslator>
44 #include <QEventLoop>
45 #include <QTimer>
47 //LameXP includes
48 #include "Resource.h"
49 #include "LockedFile.h"
51 //CRT includes
52 #include <io.h>
53 #include <fcntl.h>
54 #include <intrin.h>
56 //COM includes
57 #include <Objbase.h>
59 //Debug only includes
60 #if LAMEXP_DEBUG
61 #include <Psapi.h>
62 #endif
64 //Initialize static Qt plugins
65 #ifdef QT_NODLL
66 Q_IMPORT_PLUGIN(qgif)
67 Q_IMPORT_PLUGIN(qico)
68 Q_IMPORT_PLUGIN(qsvg)
69 #endif
71 ///////////////////////////////////////////////////////////////////////////////
72 // TYPES
73 ///////////////////////////////////////////////////////////////////////////////
75 typedef struct
77 unsigned int command;
78 unsigned int reserved_1;
79 unsigned int reserved_2;
80 char parameter[4096];
81 } lamexp_ipc_t;
83 ///////////////////////////////////////////////////////////////////////////////
84 // GLOBAL VARS
85 ///////////////////////////////////////////////////////////////////////////////
87 //Build version
88 static const struct
90 unsigned int ver_major;
91 unsigned int ver_minor;
92 unsigned int ver_build;
93 char *ver_release_name;
95 g_lamexp_version =
97 VER_LAMEXP_MAJOR,
98 VER_LAMEXP_MINOR,
99 VER_LAMEXP_BUILD,
100 VER_LAMEXP_RNAME
103 //Build date
104 static QDate g_lamexp_version_date;
105 static const char *g_lamexp_months[] = {"Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"};
106 static const char *g_lamexp_version_raw_date = __DATE__;
108 //Console attached flag
109 static bool g_lamexp_console_attached = false;
111 //Compiler detection
112 //The following code was borrowed from MPC-HC project: http://mpc-hc.sf.net/
113 #if defined(__INTEL_COMPILER)
114 #if (__INTEL_COMPILER >= 1200)
115 static const char *g_lamexp_version_compiler = "ICL 12.x";
116 #elif (__INTEL_COMPILER >= 1100)
117 static const char *g_lamexp_version_compiler = = "ICL 11.x";
118 #elif (__INTEL_COMPILER >= 1000)
119 static const char *g_lamexp_version_compiler = = "ICL 10.x";
120 #else
121 #error Compiler is not supported!
122 #endif
123 #elif defined(_MSC_VER)
124 #if (_MSC_VER == 1600)
125 #if (_MSC_FULL_VER >= 160040219)
126 static const char *g_lamexp_version_compiler = "MSVC 2010-SP1";
127 #else
128 static const char *g_lamexp_version_compiler = "MSVC 2010";
129 #endif
130 #elif (_MSC_VER == 1500)
131 #if (_MSC_FULL_VER >= 150030729)
132 static const char *g_lamexp_version_compiler = "MSVC 2008-SP1";
133 #else
134 static const char *g_lamexp_version_compiler = "MSVC 2008";
135 #endif
136 #else
137 #error Compiler is not supported!
138 #endif
140 // Note: /arch:SSE and /arch:SSE2 are only available for the x86 platform
141 #if !defined(_M_X64) && defined(_M_IX86_FP)
142 #if (_M_IX86_FP == 1)
143 LAMEXP_COMPILER_WARNING("SSE instruction set is enabled!")
144 #elif (_M_IX86_FP == 2)
145 LAMEXP_COMPILER_WARNING("SSE2 instruction set is enabled!")
146 #endif
147 #endif
148 #else
149 #error Compiler is not supported!
150 #endif
152 //Official web-site URL
153 static const char *g_lamexp_website_url = "http://mulder.dummwiedeutsch.de/";
154 static const char *g_lamexp_support_url = "http://forum.doom9.org/showthread.php?t=157726";
156 //Tool versions (expected)
157 static const unsigned int g_lamexp_toolver_neroaac = VER_LAMEXP_TOOL_NEROAAC;
159 //Special folders
160 static QString g_lamexp_temp_folder;
162 //Tools
163 static QMap<QString, LockedFile*> g_lamexp_tool_registry;
164 static QMap<QString, unsigned int> g_lamexp_tool_versions;
166 //Languages
167 static struct
169 QMap<QString, QString> files;
170 QMap<QString, QString> names;
171 QMap<QString, unsigned int> sysid;
173 g_lamexp_translation;
175 //Translator
176 static QTranslator *g_lamexp_currentTranslator = NULL;
178 //Shared memory
179 static const struct
181 char *sharedmem;
182 char *semaphore_read;
183 char *semaphore_write;
185 g_lamexp_ipc_uuid =
187 "{21A68A42-6923-43bb-9CF6-64BF151942EE}",
188 "{7A605549-F58C-4d78-B4E5-06EFC34F405B}",
189 "{60AA8D04-F6B8-497d-81EB-0F600F4A65B5}"
191 static struct
193 QSharedMemory *sharedmem;
194 QSystemSemaphore *semaphore_read;
195 QSystemSemaphore *semaphore_write;
197 g_lamexp_ipc_ptr =
199 NULL, NULL, NULL
202 //Image formats
203 static const char *g_lamexp_imageformats[] = {"png", "jpg", "gif", "ico", "svg", NULL};
205 //Global locks
206 static QMutex g_lamexp_message_mutex;
208 //Main thread ID
209 static const DWORD g_main_thread_id = GetCurrentThreadId();
212 ///////////////////////////////////////////////////////////////////////////////
213 // GLOBAL FUNCTIONS
214 ///////////////////////////////////////////////////////////////////////////////
217 * Version getters
219 unsigned int lamexp_version_major(void) { return g_lamexp_version.ver_major; }
220 unsigned int lamexp_version_minor(void) { return g_lamexp_version.ver_minor; }
221 unsigned int lamexp_version_build(void) { return g_lamexp_version.ver_build; }
222 const char *lamexp_version_release(void) { return g_lamexp_version.ver_release_name; }
223 const char *lamexp_version_compiler(void) {return g_lamexp_version_compiler; }
224 unsigned int lamexp_toolver_neroaac(void) { return g_lamexp_toolver_neroaac; }
227 * URL getters
229 const char *lamexp_website_url(void) { return g_lamexp_website_url; }
230 const char *lamexp_support_url(void) { return g_lamexp_support_url; }
233 * Check for Demo (pre-release) version
235 bool lamexp_version_demo(void)
237 char buffer[128];
238 bool releaseVersion = false;
239 if(!strcpy_s(buffer, 128, g_lamexp_version.ver_release_name))
241 char *context, *prefix = strtok_s(buffer, "-,; ", &context);
242 if(prefix)
244 releaseVersion = (!_stricmp(prefix, "Final")) || (!_stricmp(prefix, "Hotfix"));
247 return LAMEXP_DEBUG || (!releaseVersion);
251 * Calculate expiration date
253 QDate lamexp_version_expires(void)
255 return lamexp_version_date().addDays(LAMEXP_DEBUG ? 2 : 30);
259 * Get build date date
261 const QDate &lamexp_version_date(void)
263 if(!g_lamexp_version_date.isValid())
265 char temp[32];
266 int date[3];
268 char *this_token = NULL;
269 char *next_token = NULL;
271 strcpy_s(temp, 32, g_lamexp_version_raw_date);
272 this_token = strtok_s(temp, " ", &next_token);
274 for(int i = 0; i < 3; i++)
276 date[i] = -1;
277 if(this_token)
279 for(int j = 0; j < 12; j++)
281 if(!_strcmpi(this_token, g_lamexp_months[j]))
283 date[i] = j+1;
284 break;
287 if(date[i] < 0)
289 date[i] = atoi(this_token);
291 this_token = strtok_s(NULL, " ", &next_token);
295 if(date[0] >= 0 && date[1] >= 0 && date[2] >= 0)
297 g_lamexp_version_date = QDate(date[2], date[0], date[1]);
301 return g_lamexp_version_date;
305 * Global exception handler
307 LONG WINAPI lamexp_exception_handler(__in struct _EXCEPTION_POINTERS *ExceptionInfo)
309 if(GetCurrentThreadId() != g_main_thread_id)
311 HANDLE mainThread = OpenThread(THREAD_TERMINATE, FALSE, g_main_thread_id);
312 if(mainThread) TerminateThread(mainThread, ULONG_MAX);
316 FatalAppExit(0, L"Unhandeled exception error, application will exit!");
317 TerminateProcess(GetCurrentProcess(), -1);
318 return LONG_MAX;
322 * Qt message handler
324 void lamexp_message_handler(QtMsgType type, const char *msg)
326 static HANDLE hConsole = NULL;
327 static const char *GURU_MEDITATION = "\n\nGURU MEDITATION !!!\n\n";
328 const char *buffer = NULL, *text = msg;
329 char temp[1024];
331 QMutexLocker lock(&g_lamexp_message_mutex);
333 if(!strncmp(msg, "@BASE64@", 8))
335 buffer = _strdup(QByteArray::fromBase64(msg + 8).constData());
336 if(buffer) text = buffer;
339 if(!hConsole)
341 if(g_lamexp_console_attached)
343 hConsole = CreateFile(L"CONOUT$", GENERIC_WRITE, FILE_SHARE_WRITE | FILE_SHARE_READ, NULL, OPEN_EXISTING, NULL, NULL);
344 if(hConsole == INVALID_HANDLE_VALUE) hConsole = NULL;
348 if(hConsole)
350 int len = sprintf_s(temp, 1024, "%s\n", text);
352 CONSOLE_SCREEN_BUFFER_INFO bufferInfo;
353 GetConsoleScreenBufferInfo(hConsole, &bufferInfo);
354 SetConsoleOutputCP(CP_UTF8);
356 switch(type)
358 case QtCriticalMsg:
359 case QtFatalMsg:
360 fflush(stdout);
361 fflush(stderr);
362 SetConsoleTextAttribute(hConsole, FOREGROUND_RED | FOREGROUND_INTENSITY);
363 WriteFile(hConsole, GURU_MEDITATION, strlen(GURU_MEDITATION), NULL, NULL);
364 WriteFile(hConsole, temp, len, NULL, NULL);
365 FlushFileBuffers(hConsole);
366 break;
367 case QtWarningMsg:
368 SetConsoleTextAttribute(hConsole, FOREGROUND_GREEN | FOREGROUND_RED | FOREGROUND_INTENSITY);
369 WriteFile(hConsole, temp, len, NULL, NULL);
370 FlushFileBuffers(hConsole);
371 break;
372 default:
373 SetConsoleTextAttribute(hConsole, FOREGROUND_BLUE | FOREGROUND_GREEN | FOREGROUND_RED | FOREGROUND_INTENSITY);
374 WriteFile(hConsole, temp, len, NULL, NULL);
375 FlushFileBuffers(hConsole);
376 break;
379 SetConsoleTextAttribute(hConsole, FOREGROUND_BLUE | FOREGROUND_GREEN | FOREGROUND_RED);
381 else
383 switch(type)
385 case QtCriticalMsg:
386 case QtFatalMsg:
387 sprintf_s(temp, 1024, "[LameXP][C] %s", text);
388 break;
389 case QtWarningMsg:
390 sprintf_s(temp, 1024, "[LameXP][W] %s", text);
391 break;
392 default:
393 sprintf_s(temp, 1024, "[LameXP][I] %s", text);
394 break;
397 while(char *ptr = strchr(temp, '\n')) *ptr = '\t';
398 strcat_s(temp, 1024, "\n");
399 OutputDebugStringA(temp);
402 if(type == QtCriticalMsg || type == QtFatalMsg)
404 lock.unlock();
405 MessageBoxW(NULL, QWCHAR(QString::fromUtf8(text)), L"LameXP - GURU MEDITATION", MB_ICONERROR | MB_TOPMOST | MB_TASKMODAL);
406 FatalAppExit(0, L"The application has encountered a critical error and will exit now!");
407 TerminateProcess(GetCurrentProcess(), -1);
410 if(buffer) free((void*) buffer);
414 * Initialize the console
416 void lamexp_init_console(int argc, char* argv[])
418 bool enableConsole = lamexp_version_demo();
420 if(!LAMEXP_DEBUG)
422 for(int i = 0; i < argc; i++)
424 if(!_stricmp(argv[i], "--console"))
426 enableConsole = true;
428 else if(!_stricmp(argv[i], "--no-console"))
430 enableConsole = false;
435 if(enableConsole)
437 if(!g_lamexp_console_attached)
439 g_lamexp_console_attached = AllocConsole();
442 if(g_lamexp_console_attached)
444 //-------------------------------------------------------------------
445 //See: http://support.microsoft.com/default.aspx?scid=kb;en-us;105305
446 //-------------------------------------------------------------------
447 int hCrtStdOut = _open_osfhandle((long) GetStdHandle(STD_OUTPUT_HANDLE), _O_TEXT);
448 int hCrtStdErr = _open_osfhandle((long) GetStdHandle(STD_ERROR_HANDLE), _O_TEXT);
449 FILE *hfStdOut = _fdopen(hCrtStdOut, "w");
450 FILE *hfStderr = _fdopen(hCrtStdErr, "w");
451 *stdout = *hfStdOut;
452 *stderr = *hfStderr;
453 setvbuf(stdout, NULL, _IONBF, 0);
454 setvbuf(stderr, NULL, _IONBF, 0);
457 if(HWND hwndConsole = GetConsoleWindow())
459 HMENU hMenu = GetSystemMenu(hwndConsole, 0);
460 EnableMenuItem(hMenu, SC_CLOSE, MF_BYCOMMAND | MF_GRAYED);
461 RemoveMenu(hMenu, SC_CLOSE, MF_BYCOMMAND);
463 SetWindowLong(hwndConsole, GWL_STYLE, GetWindowLong(hwndConsole, GWL_STYLE) & (~WS_MAXIMIZEBOX));
464 SetWindowLong(hwndConsole, GWL_STYLE, GetWindowLong(hwndConsole, GWL_STYLE) & (~WS_MINIMIZEBOX));
466 SetConsoleCtrlHandler(NULL, TRUE);
467 SetConsoleTitle(L"LameXP - Audio Encoder Front-End | Debug Console");
468 SetConsoleOutputCP(CP_UTF8);
474 * Detect CPU features
476 lamexp_cpu_t lamexp_detect_cpu_features(void)
478 typedef BOOL (WINAPI *IsWow64ProcessFun)(__in HANDLE hProcess, __out PBOOL Wow64Process);
479 typedef VOID (WINAPI *GetNativeSystemInfoFun)(__out LPSYSTEM_INFO lpSystemInfo);
481 static IsWow64ProcessFun IsWow64ProcessPtr = NULL;
482 static GetNativeSystemInfoFun GetNativeSystemInfoPtr = NULL;
484 lamexp_cpu_t features;
485 SYSTEM_INFO systemInfo;
486 int CPUInfo[4] = {-1};
487 char CPUIdentificationString[0x40];
488 char CPUBrandString[0x40];
490 memset(&features, 0, sizeof(lamexp_cpu_t));
491 memset(&systemInfo, 0, sizeof(SYSTEM_INFO));
492 memset(CPUIdentificationString, 0, sizeof(CPUIdentificationString));
493 memset(CPUBrandString, 0, sizeof(CPUBrandString));
495 __cpuid(CPUInfo, 0);
496 memcpy(CPUIdentificationString, &CPUInfo[1], sizeof(int));
497 memcpy(CPUIdentificationString + 4, &CPUInfo[3], sizeof(int));
498 memcpy(CPUIdentificationString + 8, &CPUInfo[2], sizeof(int));
499 features.intel = (_stricmp(CPUIdentificationString, "GenuineIntel") == 0);
500 strcpy_s(features.vendor, 0x40, CPUIdentificationString);
502 if(CPUInfo[0] >= 1)
504 __cpuid(CPUInfo, 1);
505 features.mmx = (CPUInfo[3] & 0x800000) || false;
506 features.sse = (CPUInfo[3] & 0x2000000) || false;
507 features.sse2 = (CPUInfo[3] & 0x4000000) || false;
508 features.ssse3 = (CPUInfo[2] & 0x200) || false;
509 features.sse3 = (CPUInfo[2] & 0x1) || false;
510 features.ssse3 = (CPUInfo[2] & 0x200) || false;
511 features.stepping = CPUInfo[0] & 0xf;
512 features.model = ((CPUInfo[0] >> 4) & 0xf) + (((CPUInfo[0] >> 16) & 0xf) << 4);
513 features.family = ((CPUInfo[0] >> 8) & 0xf) + ((CPUInfo[0] >> 20) & 0xff);
516 __cpuid(CPUInfo, 0x80000000);
517 int nExIds = max(min(CPUInfo[0], 0x80000004), 0x80000000);
519 for(int i = 0x80000002; i <= nExIds; ++i)
521 __cpuid(CPUInfo, i);
522 switch(i)
524 case 0x80000002:
525 memcpy(CPUBrandString, CPUInfo, sizeof(CPUInfo));
526 break;
527 case 0x80000003:
528 memcpy(CPUBrandString + 16, CPUInfo, sizeof(CPUInfo));
529 break;
530 case 0x80000004:
531 memcpy(CPUBrandString + 32, CPUInfo, sizeof(CPUInfo));
532 break;
536 strcpy_s(features.brand, 0x40, CPUBrandString);
538 if(strlen(features.brand) < 1) strcpy_s(features.brand, 0x40, "Unknown");
539 if(strlen(features.vendor) < 1) strcpy_s(features.vendor, 0x40, "Unknown");
541 #if !defined(_M_X64 ) && !defined(_M_IA64)
542 if(!IsWow64ProcessPtr || !GetNativeSystemInfoPtr)
544 QLibrary Kernel32Lib("kernel32.dll");
545 IsWow64ProcessPtr = (IsWow64ProcessFun) Kernel32Lib.resolve("IsWow64Process");
546 GetNativeSystemInfoPtr = (GetNativeSystemInfoFun) Kernel32Lib.resolve("GetNativeSystemInfo");
548 if(IsWow64ProcessPtr)
550 BOOL x64 = FALSE;
551 if(IsWow64ProcessPtr(GetCurrentProcess(), &x64))
553 features.x64 = x64;
556 if(GetNativeSystemInfoPtr)
558 GetNativeSystemInfoPtr(&systemInfo);
560 else
562 GetSystemInfo(&systemInfo);
564 features.count = systemInfo.dwNumberOfProcessors;
565 #else
566 GetNativeSystemInfo(&systemInfo);
567 features.count = systemInfo.dwNumberOfProcessors;
568 features.x64 = true;
569 #endif
571 return features;
575 * Check for debugger (thread proc)
577 static void WINAPI lamexp_debug_thread_proc(__in LPVOID lpParameter)
579 while(!IsDebuggerPresent())
581 Sleep(333);
583 TerminateProcess(GetCurrentProcess(), -1);
587 * Check for debugger (startup routine)
589 static HANDLE lamexp_debug_thread_init(void)
591 if(IsDebuggerPresent())
593 FatalAppExit(0, L"Not a debug build. Please unload debugger and try again!");
594 TerminateProcess(GetCurrentProcess(), -1);
596 return CreateThread(NULL, NULL, reinterpret_cast<LPTHREAD_START_ROUTINE>(&lamexp_debug_thread_proc), NULL, NULL, NULL);
600 * Check for compatibility mode
602 static bool lamexp_check_compatibility_mode(const char *exportName, const char *executableName)
604 QLibrary kernel32("kernel32.dll");
606 if(exportName != NULL)
608 if(kernel32.resolve(exportName) != NULL)
610 qWarning("Function '%s' exported from 'kernel32.dll' -> Windows compatibility mode!", exportName);
611 qFatal("%s", QApplication::tr("Executable '%1' doesn't support Windows compatibility mode.").arg(QString::fromLatin1(executableName)).toLatin1().constData());
612 return false;
616 return true;
620 * Check for process elevation
622 static bool lamexp_check_elevation(void)
624 typedef enum { lamexp_token_elevationType_class = 18, lamexp_token_elevation_class = 20 } LAMEXP_TOKEN_INFORMATION_CLASS;
625 typedef enum { lamexp_elevationType_default = 1, lamexp_elevationType_full, lamexp_elevationType_limited } LAMEXP_TOKEN_ELEVATION_TYPE;
627 HANDLE hToken = NULL;
628 bool bIsProcessElevated = false;
630 if(OpenProcessToken(GetCurrentProcess(), TOKEN_QUERY, &hToken))
632 LAMEXP_TOKEN_ELEVATION_TYPE tokenElevationType;
633 DWORD returnLength;
634 if(GetTokenInformation(hToken, (TOKEN_INFORMATION_CLASS) lamexp_token_elevationType_class, &tokenElevationType, sizeof(LAMEXP_TOKEN_ELEVATION_TYPE), &returnLength))
636 if(returnLength == sizeof(LAMEXP_TOKEN_ELEVATION_TYPE))
638 switch(tokenElevationType)
640 case lamexp_elevationType_default:
641 qDebug("Process token elevation type: Default -> UAC is disabled.\n");
642 break;
643 case lamexp_elevationType_full:
644 qWarning("Process token elevation type: Full -> potential security risk!\n");
645 bIsProcessElevated = true;
646 break;
647 case lamexp_elevationType_limited:
648 qDebug("Process token elevation type: Limited -> not elevated.\n");
649 break;
653 CloseHandle(hToken);
655 else
657 qWarning("Failed to open process token!");
660 return !bIsProcessElevated;
664 * Initialize Qt framework
666 bool lamexp_init_qt(int argc, char* argv[])
668 static bool qt_initialized = false;
670 //Don't initialized again, if done already
671 if(qt_initialized)
673 return true;
676 //Extract executable name from argv[] array
677 char *executableName = argv[0];
678 while(char *temp = strpbrk(executableName, "\\/:?"))
680 executableName = temp + 1;
683 //Check Qt version
684 qDebug("Using Qt Framework v%s, compiled with Qt v%s [%s]", qVersion(), QT_VERSION_STR, QT_PACKAGEDATE_STR);
685 if(_stricmp(qVersion(), QT_VERSION_STR))
687 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());
688 return false;
691 //Check the Windows version
692 switch(QSysInfo::windowsVersion() & QSysInfo::WV_NT_based)
694 case QSysInfo::WV_XP:
695 qDebug("Running on Windows XP.\n");
696 lamexp_check_compatibility_mode("GetLargePageMinimum", executableName);
697 break;
698 case QSysInfo::WV_2003:
699 qDebug("Running on Windows Server 2003 or Windows XP x64-Edition.\n");
700 lamexp_check_compatibility_mode("GetLocaleInfoEx", executableName);
701 break;
702 case QSysInfo::WV_VISTA:
703 qDebug("Running on Windows Vista or Windows Server 2008.\n");
704 lamexp_check_compatibility_mode("CreateRemoteThreadEx", executableName);
705 break;
706 case QSysInfo::WV_WINDOWS7:
707 qDebug("Running on Windows 7 or Windows Server 2008 R2.\n");
708 lamexp_check_compatibility_mode(NULL, executableName);
709 break;
710 default:
711 qFatal("%s", QApplication::tr("Executable '%1' requires Windows XP or later.").arg(QString::fromLatin1(executableName)).toLatin1().constData());
712 break;
715 //Check for Wine
716 QLibrary ntdll("ntdll.dll");
717 bool isWine = (ntdll.resolve("wine_get_version") != NULL) || (ntdll.resolve("wine_nt_to_unix_file_name") != NULL);
718 if(isWine) qWarning("It appears we are running under Wine, unexpected things might happen!\n");
720 //Create Qt application instance and setup version info
721 QDate date = QDate::currentDate();
722 QApplication *application = new QApplication(argc, argv);
723 application->setApplicationName("LameXP - Audio Encoder Front-End");
724 application->setApplicationVersion(QString().sprintf("%d.%02d.%04d", lamexp_version_major(), lamexp_version_minor(), lamexp_version_build()));
725 application->setOrganizationName("LoRd_MuldeR");
726 application->setOrganizationDomain("mulder.dummwiedeutsch.de");
727 application->setWindowIcon((date.month() == 12 && date.day() >= 24 && date.day() <= 26) ? QIcon(":/MainIcon2.png") : QIcon(":/MainIcon.png"));
729 //Load plugins from application directory
730 QCoreApplication::setLibraryPaths(QStringList() << QApplication::applicationDirPath());
731 qDebug("Library Path:\n%s\n", QApplication::libraryPaths().first().toUtf8().constData());
733 //Check for supported image formats
734 QList<QByteArray> supportedFormats = QImageReader::supportedImageFormats();
735 for(int i = 0; g_lamexp_imageformats[i]; i++)
737 if(!supportedFormats.contains(g_lamexp_imageformats[i]))
739 qFatal("Qt initialization error: QImageIOHandler for '%s' missing!", g_lamexp_imageformats[i]);
740 return false;
744 //Add default translations
745 g_lamexp_translation.files.insert(LAMEXP_DEFAULT_LANGID, "");
746 g_lamexp_translation.names.insert(LAMEXP_DEFAULT_LANGID, "English");
748 //Check for process elevation
749 if(!lamexp_check_elevation())
751 if(QMessageBox::warning(NULL, "LameXP", "<nobr>LameXP was started with elevated rights. This is a potential security risk!</nobr>", "Quit Program (Recommended)", "Ignore") == 0)
753 return false;
757 //Update console icon, if a console is attached
758 if(g_lamexp_console_attached && !isWine)
760 typedef DWORD (__stdcall *SetConsoleIconFun)(HICON);
761 QLibrary kernel32("kernel32.dll");
762 SetConsoleIconFun SetConsoleIconPtr = (SetConsoleIconFun) kernel32.resolve("SetConsoleIcon");
763 if(SetConsoleIconPtr)
765 SetConsoleIconPtr(QIcon(":/icons/sound.png").pixmap(16, 16).toWinHICON());
769 //Done
770 qt_initialized = true;
771 return true;
775 * Initialize IPC
777 int lamexp_init_ipc(void)
779 if(g_lamexp_ipc_ptr.sharedmem && g_lamexp_ipc_ptr.semaphore_read && g_lamexp_ipc_ptr.semaphore_write)
781 return 0;
784 g_lamexp_ipc_ptr.semaphore_read = new QSystemSemaphore(QString(g_lamexp_ipc_uuid.semaphore_read), 0);
785 g_lamexp_ipc_ptr.semaphore_write = new QSystemSemaphore(QString(g_lamexp_ipc_uuid.semaphore_write), 0);
787 if(g_lamexp_ipc_ptr.semaphore_read->error() != QSystemSemaphore::NoError)
789 QString errorMessage = g_lamexp_ipc_ptr.semaphore_read->errorString();
790 LAMEXP_DELETE(g_lamexp_ipc_ptr.semaphore_read);
791 LAMEXP_DELETE(g_lamexp_ipc_ptr.semaphore_write);
792 qFatal("Failed to create system smaphore: %s", errorMessage.toUtf8().constData());
793 return -1;
795 if(g_lamexp_ipc_ptr.semaphore_write->error() != QSystemSemaphore::NoError)
797 QString errorMessage = g_lamexp_ipc_ptr.semaphore_write->errorString();
798 LAMEXP_DELETE(g_lamexp_ipc_ptr.semaphore_read);
799 LAMEXP_DELETE(g_lamexp_ipc_ptr.semaphore_write);
800 qFatal("Failed to create system smaphore: %s", errorMessage.toUtf8().constData());
801 return -1;
804 g_lamexp_ipc_ptr.sharedmem = new QSharedMemory(QString(g_lamexp_ipc_uuid.sharedmem), NULL);
806 if(!g_lamexp_ipc_ptr.sharedmem->create(sizeof(lamexp_ipc_t)))
808 if(g_lamexp_ipc_ptr.sharedmem->error() == QSharedMemory::AlreadyExists)
810 g_lamexp_ipc_ptr.sharedmem->attach();
811 if(g_lamexp_ipc_ptr.sharedmem->error() == QSharedMemory::NoError)
813 return 1;
815 else
817 QString errorMessage = g_lamexp_ipc_ptr.sharedmem->errorString();
818 qFatal("Failed to attach to shared memory: %s", errorMessage.toUtf8().constData());
819 return -1;
822 else
824 QString errorMessage = g_lamexp_ipc_ptr.sharedmem->errorString();
825 qFatal("Failed to create shared memory: %s", errorMessage.toUtf8().constData());
826 return -1;
830 memset(g_lamexp_ipc_ptr.sharedmem->data(), 0, sizeof(lamexp_ipc_t));
831 g_lamexp_ipc_ptr.semaphore_write->release();
833 return 0;
837 * IPC send message
839 void lamexp_ipc_send(unsigned int command, const char* message)
841 if(!g_lamexp_ipc_ptr.sharedmem || !g_lamexp_ipc_ptr.semaphore_read || !g_lamexp_ipc_ptr.semaphore_write)
843 throw "Shared memory for IPC not initialized yet.";
846 lamexp_ipc_t *lamexp_ipc = new lamexp_ipc_t;
847 memset(lamexp_ipc, 0, sizeof(lamexp_ipc_t));
848 lamexp_ipc->command = command;
849 if(message)
851 strcpy_s(lamexp_ipc->parameter, 4096, message);
854 if(g_lamexp_ipc_ptr.semaphore_write->acquire())
856 memcpy(g_lamexp_ipc_ptr.sharedmem->data(), lamexp_ipc, sizeof(lamexp_ipc_t));
857 g_lamexp_ipc_ptr.semaphore_read->release();
860 LAMEXP_DELETE(lamexp_ipc);
864 * IPC read message
866 void lamexp_ipc_read(unsigned int *command, char* message, size_t buffSize)
868 *command = 0;
869 message[0] = '\0';
871 if(!g_lamexp_ipc_ptr.sharedmem || !g_lamexp_ipc_ptr.semaphore_read || !g_lamexp_ipc_ptr.semaphore_write)
873 throw "Shared memory for IPC not initialized yet.";
876 lamexp_ipc_t *lamexp_ipc = new lamexp_ipc_t;
877 memset(lamexp_ipc, 0, sizeof(lamexp_ipc_t));
879 if(g_lamexp_ipc_ptr.semaphore_read->acquire())
881 memcpy(lamexp_ipc, g_lamexp_ipc_ptr.sharedmem->data(), sizeof(lamexp_ipc_t));
882 g_lamexp_ipc_ptr.semaphore_write->release();
884 if(!(lamexp_ipc->reserved_1 || lamexp_ipc->reserved_2))
886 *command = lamexp_ipc->command;
887 strcpy_s(message, buffSize, lamexp_ipc->parameter);
889 else
891 qWarning("Malformed IPC message, will be ignored");
895 LAMEXP_DELETE(lamexp_ipc);
899 * Check for LameXP "portable" mode
901 bool lamexp_portable_mode(void)
903 QString baseName = QFileInfo(QApplication::applicationFilePath()).completeBaseName();
904 return baseName.contains("lamexp", Qt::CaseInsensitive) && baseName.contains("portable", Qt::CaseInsensitive);
908 * Get a random string
910 QString lamexp_rand_str(void)
912 QRegExp regExp("\\{(\\w+)-(\\w+)-(\\w+)-(\\w+)-(\\w+)\\}");
913 QString uuid = QUuid::createUuid().toString();
915 if(regExp.indexIn(uuid) >= 0)
917 return QString().append(regExp.cap(1)).append(regExp.cap(2)).append(regExp.cap(3)).append(regExp.cap(4)).append(regExp.cap(5));
920 throw "The RegExp didn't match on the UUID string. This shouldn't happen ;-)";
924 * Get LameXP temp folder
926 const QString &lamexp_temp_folder2(void)
928 static const char *TEMP_STR = "Temp";
929 const QString WRITE_TEST_DATA = lamexp_rand_str();
930 const QString SUB_FOLDER = lamexp_rand_str();
932 //Already initialized?
933 if(!g_lamexp_temp_folder.isEmpty())
935 if(QDir(g_lamexp_temp_folder).exists())
937 return g_lamexp_temp_folder;
939 else
941 g_lamexp_temp_folder.clear();
945 //Try the %TMP% or %TEMP% directory first
946 QDir temp = QDir::temp();
947 if(temp.exists())
949 temp.mkdir(SUB_FOLDER);
950 if(temp.cd(SUB_FOLDER) && temp.exists())
952 QFile testFile(QString("%1/~%2.tmp").arg(temp.canonicalPath(), lamexp_rand_str()));
953 if(testFile.open(QIODevice::ReadWrite))
955 if(testFile.write(WRITE_TEST_DATA.toLatin1().constData()) >= strlen(WRITE_TEST_DATA.toLatin1().constData()))
957 g_lamexp_temp_folder = temp.canonicalPath();
959 testFile.remove();
962 if(!g_lamexp_temp_folder.isEmpty())
964 return g_lamexp_temp_folder;
968 //Create TEMP folder in %LOCALAPPDATA%
969 QDir localAppData = QDir(lamexp_known_folder(lamexp_folder_localappdata));
970 if(!localAppData.path().isEmpty())
972 if(!localAppData.exists())
974 localAppData.mkpath(".");
976 if(localAppData.exists())
978 if(!localAppData.entryList(QDir::AllDirs).contains(TEMP_STR, Qt::CaseInsensitive))
980 localAppData.mkdir(TEMP_STR);
982 if(localAppData.cd(TEMP_STR) && localAppData.exists())
984 localAppData.mkdir(SUB_FOLDER);
985 if(localAppData.cd(SUB_FOLDER) && localAppData.exists())
987 QFile testFile(QString("%1/~%2.tmp").arg(localAppData.canonicalPath(), lamexp_rand_str()));
988 if(testFile.open(QIODevice::ReadWrite))
990 if(testFile.write(WRITE_TEST_DATA.toLatin1().constData()) >= strlen(WRITE_TEST_DATA.toLatin1().constData()))
992 g_lamexp_temp_folder = localAppData.canonicalPath();
994 testFile.remove();
999 if(!g_lamexp_temp_folder.isEmpty())
1001 return g_lamexp_temp_folder;
1005 //Failed to create TEMP folder!
1006 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());
1007 return g_lamexp_temp_folder;
1011 * Clean folder
1013 bool lamexp_clean_folder(const QString &folderPath)
1015 QDir tempFolder(folderPath);
1016 QFileInfoList entryList = tempFolder.entryInfoList(QDir::AllEntries | QDir::NoDotAndDotDot);
1018 for(int i = 0; i < entryList.count(); i++)
1020 if(entryList.at(i).isDir())
1022 lamexp_clean_folder(entryList.at(i).canonicalFilePath());
1024 else
1026 for(int j = 0; j < 3; j++)
1028 if(lamexp_remove_file(entryList.at(i).canonicalFilePath()))
1030 break;
1036 tempFolder.rmdir(".");
1037 return !tempFolder.exists();
1041 * Register tool
1043 void lamexp_register_tool(const QString &toolName, LockedFile *file, unsigned int version)
1045 if(g_lamexp_tool_registry.contains(toolName.toLower()))
1047 throw "lamexp_register_tool: Tool is already registered!";
1050 g_lamexp_tool_registry.insert(toolName.toLower(), file);
1051 g_lamexp_tool_versions.insert(toolName.toLower(), version);
1055 * Check for tool
1057 bool lamexp_check_tool(const QString &toolName)
1059 return g_lamexp_tool_registry.contains(toolName.toLower());
1063 * Lookup tool path
1065 const QString lamexp_lookup_tool(const QString &toolName)
1067 if(g_lamexp_tool_registry.contains(toolName.toLower()))
1069 return g_lamexp_tool_registry.value(toolName.toLower())->filePath();
1071 else
1073 return QString();
1078 * Lookup tool version
1080 unsigned int lamexp_tool_version(const QString &toolName)
1082 if(g_lamexp_tool_versions.contains(toolName.toLower()))
1084 return g_lamexp_tool_versions.value(toolName.toLower());
1086 else
1088 return UINT_MAX;
1093 * Version number to human-readable string
1095 const QString lamexp_version2string(const QString &pattern, unsigned int version, const QString &defaultText)
1097 if(version == UINT_MAX)
1099 return defaultText;
1102 QString result = pattern;
1103 int digits = result.count("?", Qt::CaseInsensitive);
1105 if(digits < 1)
1107 return result;
1110 int pos = 0;
1111 QString versionStr = QString().sprintf(QString().sprintf("%%0%du", digits).toLatin1().constData(), version);
1112 int index = result.indexOf("?", Qt::CaseInsensitive);
1114 while(index >= 0 && pos < versionStr.length())
1116 result[index] = versionStr[pos++];
1117 index = result.indexOf("?", Qt::CaseInsensitive);
1120 return result;
1124 * Register a new translation
1126 bool lamexp_translation_register(const QString &langId, const QString &qmFile, const QString &langName, unsigned int &systemId)
1128 if(qmFile.isEmpty() || langName.isEmpty() || systemId < 1)
1130 return false;
1133 g_lamexp_translation.files.insert(langId, qmFile);
1134 g_lamexp_translation.names.insert(langId, langName);
1135 g_lamexp_translation.sysid.insert(langId, systemId);
1137 return true;
1141 * Get list of all translations
1143 QStringList lamexp_query_translations(void)
1145 return g_lamexp_translation.files.keys();
1149 * Get translation name
1151 QString lamexp_translation_name(const QString &langId)
1153 return g_lamexp_translation.names.value(langId.toLower(), QString());
1157 * Get translation system id
1159 unsigned int lamexp_translation_sysid(const QString &langId)
1161 return g_lamexp_translation.sysid.value(langId.toLower(), 0);
1165 * Install a new translator
1167 bool lamexp_install_translator(const QString &langId)
1169 bool success = false;
1171 if(langId.isEmpty() || langId.toLower().compare(LAMEXP_DEFAULT_LANGID) == 0)
1173 success = lamexp_install_translator_from_file(QString());
1175 else
1177 QString qmFile = g_lamexp_translation.files.value(langId.toLower(), QString());
1178 if(!qmFile.isEmpty())
1180 success = lamexp_install_translator_from_file(QString(":/localization/%1").arg(qmFile));
1182 else
1184 qWarning("Translation '%s' not available!", langId.toLatin1().constData());
1188 return success;
1192 * Install a new translator from file
1194 bool lamexp_install_translator_from_file(const QString &qmFile)
1196 bool success = false;
1198 if(!g_lamexp_currentTranslator)
1200 g_lamexp_currentTranslator = new QTranslator();
1203 if(!qmFile.isEmpty())
1205 QString qmPath = QFileInfo(qmFile).canonicalFilePath();
1206 QApplication::removeTranslator(g_lamexp_currentTranslator);
1207 success = g_lamexp_currentTranslator->load(qmPath);
1208 QApplication::installTranslator(g_lamexp_currentTranslator);
1209 if(!success)
1211 qWarning("Failed to load translation:\n\"%s\"", qmPath.toLatin1().constData());
1214 else
1216 QApplication::removeTranslator(g_lamexp_currentTranslator);
1217 success = true;
1220 return success;
1224 * Locate known folder on local system
1226 QString lamexp_known_folder(lamexp_known_folder_t folder_id)
1228 typedef HRESULT (WINAPI *SHGetKnownFolderPathFun)(__in const GUID &rfid, __in DWORD dwFlags, __in HANDLE hToken, __out PWSTR *ppszPath);
1229 typedef HRESULT (WINAPI *SHGetFolderPathFun)(__in HWND hwndOwner, __in int nFolder, __in HANDLE hToken, __in DWORD dwFlags, __out LPWSTR pszPath);
1231 static const int CSIDL_LOCAL_APPDATA = 0x001c;
1232 static const int CSIDL_PROGRAM_FILES = 0x0026;
1233 static const int CSIDL_SYSTEM_FOLDER = 0x0025;
1234 static const GUID GUID_LOCAL_APPDATA = {0xF1B32785,0x6FBA,0x4FCF,{0x9D,0x55,0x7B,0x8E,0x7F,0x15,0x70,0x91}};
1235 static const GUID GUID_LOCAL_APPDATA_LOW = {0xA520A1A4,0x1780,0x4FF6,{0xBD,0x18,0x16,0x73,0x43,0xC5,0xAF,0x16}};
1236 static const GUID GUID_PROGRAM_FILES = {0x905e63b6,0xc1bf,0x494e,{0xb2,0x9c,0x65,0xb7,0x32,0xd3,0xd2,0x1a}};
1237 static const GUID GUID_SYSTEM_FOLDER = {0x1AC14E77,0x02E7,0x4E5D,{0xB7,0x44,0x2E,0xB1,0xAE,0x51,0x98,0xB7}};
1239 static QLibrary *Kernel32Lib = NULL;
1240 static SHGetKnownFolderPathFun SHGetKnownFolderPathPtr = NULL;
1241 static SHGetFolderPathFun SHGetFolderPathPtr = NULL;
1243 if((!SHGetKnownFolderPathPtr) && (!SHGetFolderPathPtr))
1245 if(!Kernel32Lib) Kernel32Lib = new QLibrary("shell32.dll");
1246 SHGetKnownFolderPathPtr = (SHGetKnownFolderPathFun) Kernel32Lib->resolve("SHGetKnownFolderPath");
1247 SHGetFolderPathPtr = (SHGetFolderPathFun) Kernel32Lib->resolve("SHGetFolderPathW");
1250 int folderCSIDL = -1;
1251 GUID folderGUID = {0x0000,0x0000,0x0000,{0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00}};
1253 switch(folder_id)
1255 case lamexp_folder_localappdata:
1256 folderCSIDL = CSIDL_LOCAL_APPDATA;
1257 folderGUID = GUID_LOCAL_APPDATA;
1258 break;
1259 case lamexp_folder_programfiles:
1260 folderCSIDL = CSIDL_PROGRAM_FILES;
1261 folderGUID = GUID_PROGRAM_FILES;
1262 break;
1263 case lamexp_folder_systemfolder:
1264 folderCSIDL = CSIDL_SYSTEM_FOLDER;
1265 folderGUID = GUID_SYSTEM_FOLDER;
1266 break;
1267 default:
1268 return QString();
1269 break;
1272 QString folder;
1274 if(SHGetKnownFolderPathPtr)
1276 WCHAR *path = NULL;
1277 if(SHGetKnownFolderPathPtr(folderGUID, 0x00008000, NULL, &path) == S_OK)
1279 //MessageBoxW(0, path, L"SHGetKnownFolderPath", MB_TOPMOST);
1280 QDir folderTemp = QDir(QDir::fromNativeSeparators(QString::fromUtf16(reinterpret_cast<const unsigned short*>(path))));
1281 if(!folderTemp.exists())
1283 folderTemp.mkpath(".");
1285 if(folderTemp.exists())
1287 folder = folderTemp.canonicalPath();
1289 CoTaskMemFree(path);
1292 else if(SHGetFolderPathPtr)
1294 WCHAR *path = new WCHAR[4096];
1295 if(SHGetFolderPathPtr(NULL, folderCSIDL, NULL, NULL, path) == S_OK)
1297 //MessageBoxW(0, path, L"SHGetFolderPathW", MB_TOPMOST);
1298 QDir folderTemp = QDir(QDir::fromNativeSeparators(QString::fromUtf16(reinterpret_cast<const unsigned short*>(path))));
1299 if(!folderTemp.exists())
1301 folderTemp.mkpath(".");
1303 if(folderTemp.exists())
1305 folder = folderTemp.canonicalPath();
1308 delete [] path;
1311 return folder;
1315 * Safely remove a file
1317 bool lamexp_remove_file(const QString &filename)
1319 if(!QFileInfo(filename).exists() || !QFileInfo(filename).isFile())
1321 return true;
1323 else
1325 if(!QFile::remove(filename))
1327 DWORD attributes = GetFileAttributesW(QWCHAR(filename));
1328 SetFileAttributesW(QWCHAR(filename), (attributes & (~FILE_ATTRIBUTE_READONLY)));
1329 if(!QFile::remove(filename))
1331 qWarning("Could not delete \"%s\"", filename.toLatin1().constData());
1332 return false;
1334 else
1336 return true;
1339 else
1341 return true;
1347 * Check if visual themes are enabled (WinXP and later)
1349 bool lamexp_themes_enabled(void)
1351 typedef int (WINAPI *IsAppThemedFun)(void);
1353 bool isAppThemed = false;
1354 QLibrary uxTheme(QString("%1/UxTheme.dll").arg(lamexp_known_folder(lamexp_folder_systemfolder)));
1355 IsAppThemedFun IsAppThemedPtr = (IsAppThemedFun) uxTheme.resolve("IsAppThemed");
1357 if(IsAppThemedPtr)
1359 isAppThemed = IsAppThemedPtr();
1360 if(!isAppThemed)
1362 qWarning("Theme support is disabled for this process!");
1366 return isAppThemed;
1370 * Get number of free bytes on disk
1372 __int64 lamexp_free_diskspace(const QString &path)
1374 ULARGE_INTEGER freeBytesAvailable, totalNumberOfBytes, totalNumberOfFreeBytes;
1375 if(GetDiskFreeSpaceExW(reinterpret_cast<const wchar_t*>(QDir::toNativeSeparators(path).utf16()), &freeBytesAvailable, &totalNumberOfBytes, &totalNumberOfFreeBytes))
1377 return freeBytesAvailable.QuadPart;
1379 else
1381 return 0;
1386 * Shutdown the computer
1388 bool lamexp_shutdown_computer(const QString &message, const unsigned long timeout, const bool forceShutdown)
1390 HANDLE hToken = NULL;
1392 if(OpenProcessToken(GetCurrentProcess(), TOKEN_ADJUST_PRIVILEGES | TOKEN_QUERY, &hToken))
1394 TOKEN_PRIVILEGES privileges;
1395 memset(&privileges, 0, sizeof(TOKEN_PRIVILEGES));
1396 privileges.PrivilegeCount = 1;
1397 privileges.Privileges[0].Attributes = SE_PRIVILEGE_ENABLED;
1399 if(LookupPrivilegeValue(NULL, SE_SHUTDOWN_NAME, &privileges.Privileges[0].Luid))
1401 if(AdjustTokenPrivileges(hToken, FALSE, &privileges, NULL, NULL, NULL))
1403 const DWORD reason = SHTDN_REASON_MAJOR_APPLICATION | SHTDN_REASON_FLAG_PLANNED;
1404 return InitiateSystemShutdownEx(NULL, const_cast<wchar_t*>(QWCHAR(message)), timeout, forceShutdown, FALSE, reason);
1409 return false;
1413 * Make a window blink (to draw user's attention)
1415 void lamexp_blink_window(QWidget *poWindow, unsigned int count, unsigned int delay)
1417 static QMutex blinkMutex;
1419 const double maxOpac = 1.0;
1420 const double minOpac = 0.3;
1421 const double delOpac = 0.1;
1423 if(!blinkMutex.tryLock())
1425 qWarning("Blinking is already in progress, skipping!");
1426 return;
1431 const int steps = static_cast<int>(ceil(maxOpac - minOpac) / delOpac);
1432 const int sleep = static_cast<int>(floor(static_cast<double>(delay) / static_cast<double>(steps)));
1433 const double opacity = poWindow->windowOpacity();
1435 for(unsigned int i = 0; i < count; i++)
1437 for(double x = maxOpac; x >= minOpac; x -= delOpac)
1439 poWindow->setWindowOpacity(x);
1440 QApplication::processEvents();
1441 Sleep(sleep);
1444 for(double x = minOpac; x <= maxOpac; x += delOpac)
1446 poWindow->setWindowOpacity(x);
1447 QApplication::processEvents();
1448 Sleep(sleep);
1452 poWindow->setWindowOpacity(opacity);
1453 QApplication::processEvents();
1454 blinkMutex.unlock();
1456 catch (...)
1458 blinkMutex.unlock();
1459 qWarning("Exception error while blinking!");
1464 * Finalization function (final clean-up)
1466 void lamexp_finalization(void)
1468 //Free all tools
1469 if(!g_lamexp_tool_registry.isEmpty())
1471 QStringList keys = g_lamexp_tool_registry.keys();
1472 for(int i = 0; i < keys.count(); i++)
1474 LAMEXP_DELETE(g_lamexp_tool_registry[keys.at(i)]);
1476 g_lamexp_tool_registry.clear();
1477 g_lamexp_tool_versions.clear();
1480 //Delete temporary files
1481 if(!g_lamexp_temp_folder.isEmpty())
1483 for(int i = 0; i < 100; i++)
1485 if(lamexp_clean_folder(g_lamexp_temp_folder))
1487 break;
1489 Sleep(125);
1491 g_lamexp_temp_folder.clear();
1494 //Clear languages
1495 if(g_lamexp_currentTranslator)
1497 QApplication::removeTranslator(g_lamexp_currentTranslator);
1498 LAMEXP_DELETE(g_lamexp_currentTranslator);
1500 g_lamexp_translation.files.clear();
1501 g_lamexp_translation.names.clear();
1503 //Destroy Qt application object
1504 QApplication *application = dynamic_cast<QApplication*>(QApplication::instance());
1505 LAMEXP_DELETE(application);
1507 //Detach from shared memory
1508 if(g_lamexp_ipc_ptr.sharedmem) g_lamexp_ipc_ptr.sharedmem->detach();
1509 LAMEXP_DELETE(g_lamexp_ipc_ptr.sharedmem);
1510 LAMEXP_DELETE(g_lamexp_ipc_ptr.semaphore_read);
1511 LAMEXP_DELETE(g_lamexp_ipc_ptr.semaphore_write);
1515 * Initialize debug thread
1517 static const HANDLE g_debug_thread = LAMEXP_DEBUG ? NULL : lamexp_debug_thread_init();
1520 * Get number private bytes [debug only]
1522 SIZE_T lamexp_dbg_private_bytes(void)
1524 #if LAMEXP_DEBUG
1525 PROCESS_MEMORY_COUNTERS_EX memoryCounters;
1526 memoryCounters.cb = sizeof(PROCESS_MEMORY_COUNTERS_EX);
1527 GetProcessMemoryInfo(GetCurrentProcess(), (PPROCESS_MEMORY_COUNTERS) &memoryCounters, sizeof(PROCESS_MEMORY_COUNTERS_EX));
1528 return memoryCounters.PrivateUsage;
1529 #else
1530 throw "Cannot call this function in a non-debug build!";
1531 #endif //LAMEXP_DEBUG