1 ///////////////////////////////////////////////////////////////////////////////
2 // LameXP - Audio Encoder Front-End
3 // Copyright (C) 2004-2013 LoRd_MuldeR <MuldeR2@GMX.de>
5 // This program is free software; you can redistribute it and/or modify
6 // it under the terms of the GNU General Public License as published by
7 // the Free Software Foundation; either version 2 of the License, or
8 // (at your option) any later version.
10 // This program is distributed in the hope that it will be useful,
11 // but WITHOUT ANY WARRANTY; without even the implied warranty of
12 // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 // GNU General Public License for more details.
15 // You should have received a copy of the GNU General Public License along
16 // with this program; if not, write to the Free Software Foundation, Inc.,
17 // 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
19 // http://www.gnu.org/licenses/gpl-2.0.txt
20 ///////////////////////////////////////////////////////////////////////////////
25 #include <QApplication>
26 #include <QMessageBox>
32 #include <QPlastiqueStyle>
33 #include <QImageReader>
34 #include <QSharedMemory>
36 #include <QStringList>
37 #include <QSystemSemaphore>
43 #include <QTranslator>
46 #include <QLibraryInfo>
48 #include <QReadWriteLock>
49 #include <QReadLocker>
50 #include <QWriteLocker>
55 #include "LockedFile.h"
77 //Initialize static Qt plugins
79 #if QT_VERSION < QT_VERSION_CHECK(5,0,0)
83 Q_IMPORT_PLUGIN(QWindowsIntegrationPlugin)
84 Q_IMPORT_PLUGIN(QICOPlugin)
88 #define LAMEXP_ZERO_MEMORY(X) SecureZeroMemory(&X, sizeof(X))
91 #define _LAMEXP_MAKE_STR(STR) #STR
92 #define LAMEXP_MAKE_STR(STR) _LAMEXP_MAKE_STR(STR)
94 ///////////////////////////////////////////////////////////////////////////////
96 ///////////////////////////////////////////////////////////////////////////////
98 static const size_t g_lamexp_ipc_slots = 128;
102 unsigned int command;
103 unsigned int reserved_1;
104 unsigned int reserved_2;
105 char parameter[4096];
111 unsigned int pos_write;
112 unsigned int pos_read;
113 lamexp_ipc_data_t data[g_lamexp_ipc_slots];
117 ///////////////////////////////////////////////////////////////////////////////
119 ///////////////////////////////////////////////////////////////////////////////
124 unsigned int ver_major;
125 unsigned int ver_minor;
126 unsigned int ver_build;
127 char *ver_release_name;
138 static QDate g_lamexp_version_date;
139 static const char *g_lamexp_months[] = {"Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"};
140 static const char *g_lamexp_version_raw_date = __DATE__;
141 static const char *g_lamexp_version_raw_time = __TIME__;
143 //Console attached flag
144 static bool g_lamexp_console_attached = false;
147 //The following code was borrowed from MPC-HC project: http://mpc-hc.sf.net/
148 #if defined(__INTEL_COMPILER)
149 #if (__INTEL_COMPILER >= 1300)
150 static const char *g_lamexp_version_compiler = "ICL 13." LAMEXP_MAKE_STR(__INTEL_COMPILER_BUILD_DATE);
151 #elif (__INTEL_COMPILER >= 1200)
152 static const char *g_lamexp_version_compiler = "ICL 12." LAMEXP_MAKE_STR(__INTEL_COMPILER_BUILD_DATE);
153 #elif (__INTEL_COMPILER >= 1100)
154 static const char *g_lamexp_version_compiler = "ICL 11.x";
155 #elif (__INTEL_COMPILER >= 1000)
156 static const char *g_lamexp_version_compiler = "ICL 10.x";
158 #error Compiler is not supported!
160 #elif defined(_MSC_VER)
161 #if (_MSC_VER == 1700)
162 #if (_MSC_FULL_VER < 170050727)
163 static const char *g_lamexp_version_compiler = "MSVC 2012-Beta";
164 #elif (_MSC_FULL_VER < 170051020)
165 static const char *g_lamexp_version_compiler = "MSVC 2012-RTM";
166 #elif (_MSC_FULL_VER < 170051106)
167 static const char *g_lamexp_version_compiler = "MSVC 2012-U1 CTP";
168 #elif (_MSC_FULL_VER < 170060315)
169 static const char *g_lamexp_version_compiler = "MSVC 2012-U1";
170 #elif (_MSC_FULL_VER == 170060315)
171 static const char *g_lamexp_version_compiler = "MSVC 2012-U2";
173 #error Compiler version is not supported yet!
175 #elif (_MSC_VER == 1600)
176 #if (_MSC_FULL_VER < 160040219)
177 static const char *g_lamexp_version_compiler = "MSVC 2010-RTM";
178 #elif (_MSC_FULL_VER == 160040219)
179 static const char *g_lamexp_version_compiler = "MSVC 2010-SP1";
181 #error Compiler version is not supported yet!
183 #elif (_MSC_VER == 1500)
184 #if (_MSC_FULL_VER >= 150030729)
185 static const char *g_lamexp_version_compiler = "MSVC 2008-SP1";
187 static const char *g_lamexp_version_compiler = "MSVC 2008";
190 #error Compiler is not supported!
193 // Note: /arch:SSE and /arch:SSE2 are only available for the x86 platform
194 #if !defined(_M_X64) && defined(_M_IX86_FP)
195 #if (_M_IX86_FP == 1)
196 LAMEXP_COMPILER_WARNING("SSE instruction set is enabled!")
197 #elif (_M_IX86_FP == 2)
198 LAMEXP_COMPILER_WARNING("SSE2 instruction set is enabled!")
202 #error Compiler is not supported!
205 //Architecture detection
207 static const char *g_lamexp_version_arch = "x64";
208 #elif defined(_M_IX86)
209 static const char *g_lamexp_version_arch = "x86";
211 #error Architecture is not supported!
214 //Official web-site URL
215 static const char *g_lamexp_website_url = "http://lamexp.sourceforge.net/";
216 static const char *g_lamexp_support_url = "http://forum.doom9.org/showthread.php?t=157726";
217 static const char *g_lamexp_mulders_url = "http://muldersoft.com/";
219 //Tool versions (expected versions!)
220 static const unsigned int g_lamexp_toolver_neroaac = VER_LAMEXP_TOOL_NEROAAC;
221 static const unsigned int g_lamexp_toolver_fhgaacenc = VER_LAMEXP_TOOL_FHGAACENC;
222 static const unsigned int g_lamexp_toolver_qaacenc = VER_LAMEXP_TOOL_QAAC;
223 static const unsigned int g_lamexp_toolver_coreaudio = VER_LAMEXP_TOOL_COREAUDIO;
229 QMap<size_t, QString> *knownFolders;
237 QMap<QString, LockedFile*> *registry;
238 QMap<QString, unsigned int> *versions;
239 QMap<QString, QString> *tags;
247 QMap<QString, QString> *files;
248 QMap<QString, QString> *names;
249 QMap<QString, unsigned int> *sysid;
250 QMap<QString, unsigned int> *cntry;
253 g_lamexp_translation;
258 QTranslator *instance;
261 g_lamexp_currentTranslator;
275 lamexp_os_version_t version;
280 //Win32 Theme support
287 g_lamexp_themes_enabled;
293 char *semaphore_read;
294 char *semaphore_read_mutex;
295 char *semaphore_write;
296 char *semaphore_write_mutex;
300 "{21A68A42-6923-43bb-9CF6-64BF151942EE}",
301 "{7A605549-F58C-4d78-B4E5-06EFC34F405B}",
302 "{60AA8D04-F6B8-497d-81EB-0F600F4A65B5}",
303 "{726061D5-1615-4B82-871C-75FD93458E46}",
304 "{1A616023-AA6A-4519-8AF3-F7736E899977}"
308 QSharedMemory *sharedmem;
309 QSystemSemaphore *semaphore_read;
310 QSystemSemaphore *semaphore_read_mutex;
311 QSystemSemaphore *semaphore_write;
312 QSystemSemaphore *semaphore_write_mutex;
318 static const char *g_lamexp_imageformats[] = {"bmp", "png", "jpg", "gif", "ico", "xpm", NULL}; //"svg"
321 static QMutex g_lamexp_message_mutex;
324 static const DWORD g_main_thread_id = GetCurrentThreadId();
327 static FILE *g_lamexp_log_file = NULL;
330 const char* LAMEXP_DEFAULT_LANGID = "en";
331 const char* LAMEXP_DEFAULT_TRANSLATION = "LameXP_EN.qm";
333 ///////////////////////////////////////////////////////////////////////////////
335 ///////////////////////////////////////////////////////////////////////////////
340 unsigned int lamexp_version_major(void) { return g_lamexp_version.ver_major; }
341 unsigned int lamexp_version_minor(void) { return g_lamexp_version.ver_minor; }
342 unsigned int lamexp_version_build(void) { return g_lamexp_version.ver_build; }
343 const char *lamexp_version_release(void) { return g_lamexp_version.ver_release_name; }
344 const char *lamexp_version_time(void) { return g_lamexp_version_raw_time; }
345 const char *lamexp_version_compiler(void) { return g_lamexp_version_compiler; }
346 const char *lamexp_version_arch(void) { return g_lamexp_version_arch; }
347 unsigned int lamexp_toolver_neroaac(void) { return g_lamexp_toolver_neroaac; }
348 unsigned int lamexp_toolver_fhgaacenc(void) { return g_lamexp_toolver_fhgaacenc; }
349 unsigned int lamexp_toolver_qaacenc(void) { return g_lamexp_toolver_qaacenc; }
350 unsigned int lamexp_toolver_coreaudio(void) { return g_lamexp_toolver_coreaudio; }
355 const char *lamexp_website_url(void) { return g_lamexp_website_url; }
356 const char *lamexp_mulders_url(void) { return g_lamexp_mulders_url; }
357 const char *lamexp_support_url(void) { return g_lamexp_support_url; }
360 * Check for Demo (pre-release) version
362 bool lamexp_version_demo(void)
365 bool releaseVersion = false;
366 if(!strncpy_s(buffer, 128, g_lamexp_version.ver_release_name, _TRUNCATE))
368 char *context, *prefix = strtok_s(buffer, "-,; ", &context);
371 releaseVersion = (!_stricmp(prefix, "Final")) || (!_stricmp(prefix, "Hotfix"));
374 return LAMEXP_DEBUG || (!releaseVersion);
378 * Calculate expiration date
380 QDate lamexp_version_expires(void)
382 return lamexp_version_date().addDays(LAMEXP_DEBUG ? 7 : 30);
386 * Get build date date
388 const QDate &lamexp_version_date(void)
390 if(!g_lamexp_version_date.isValid())
392 int date[3] = {0, 0, 0}; char temp[12] = {'\0'};
393 strncpy_s(temp, 12, g_lamexp_version_raw_date, _TRUNCATE);
395 if(strlen(temp) == 11)
397 temp[3] = temp[6] = '\0';
398 date[2] = atoi(&temp[4]);
399 date[0] = atoi(&temp[7]);
401 for(int j = 0; j < 12; j++)
403 if(!_strcmpi(&temp[0], g_lamexp_months[j]))
410 g_lamexp_version_date = QDate(date[0], date[1], date[2]);
413 if(!g_lamexp_version_date.isValid())
415 qFatal("Internal error: Date format could not be recognized!");
419 return g_lamexp_version_date;
423 * Get the native operating system version
425 const lamexp_os_version_t *lamexp_get_os_version(void)
427 QReadLocker readLock(&g_lamexp_os_version.lock);
429 //Already initialized?
430 if(g_lamexp_os_version.bInitialized)
432 return &g_lamexp_os_version.version;
436 QWriteLocker writeLock(&g_lamexp_os_version.lock);
439 if(!g_lamexp_os_version.bInitialized)
441 OSVERSIONINFO osVerInfo;
442 memset(&osVerInfo, 0, sizeof(OSVERSIONINFO));
443 osVerInfo.dwOSVersionInfoSize = sizeof(OSVERSIONINFO);
445 if(GetVersionEx(&osVerInfo) == TRUE)
447 if(osVerInfo.dwPlatformId == VER_PLATFORM_WIN32_NT)
449 g_lamexp_os_version.version.versionMajor = osVerInfo.dwMajorVersion;
450 g_lamexp_os_version.version.versionMinor = osVerInfo.dwMinorVersion;
454 qWarning("lamexp_get_os_version: Not running under Windows NT, this is not supposed to happen!");
455 g_lamexp_os_version.version.versionMajor = 0;
456 g_lamexp_os_version.version.versionMinor = 0;
461 throw "GetVersionEx() has failed. This is not supposed to happen!";
464 g_lamexp_os_version.bInitialized = true;
467 return &g_lamexp_os_version.version;
471 * Check if we are running under wine
473 bool lamexp_detect_wine(void)
475 static bool isWine = false;
476 static bool isWine_initialized = false;
478 if(!isWine_initialized)
480 QLibrary ntdll("ntdll.dll");
483 if(ntdll.resolve("wine_nt_to_unix_file_name") != NULL) isWine = true;
484 if(ntdll.resolve("wine_get_version") != NULL) isWine = true;
487 isWine_initialized = true;
494 * Global exception handler
496 LONG WINAPI lamexp_exception_handler(__in struct _EXCEPTION_POINTERS *ExceptionInfo)
498 lamexp_fatal_exit(L"Unhandeled exception handler invoked, application will exit!");
503 * Invalid parameters handler
505 void lamexp_invalid_param_handler(const wchar_t* exp, const wchar_t* fun, const wchar_t* fil, unsigned int, uintptr_t)
507 lamexp_fatal_exit(L"Invalid parameter handler invoked, application will exit!");
511 * Change console text color
513 static void lamexp_console_color(FILE* file, WORD attributes)
515 const HANDLE hConsole = (HANDLE)(_get_osfhandle(_fileno(file)));
516 if((hConsole != NULL) && (hConsole != INVALID_HANDLE_VALUE))
518 SetConsoleTextAttribute(hConsole, attributes);
525 void lamexp_message_handler(QtMsgType type, const char *msg)
527 static const char *GURU_MEDITATION = "\n\nGURU MEDITATION !!!\n\n";
529 if(msg == NULL) return;
531 QMutexLocker lock(&g_lamexp_message_mutex);
533 if(g_lamexp_log_file)
535 static char prefix[] = "DWCF";
536 int index = qBound(0, static_cast<int>(type), 3);
537 unsigned int timestamp = static_cast<unsigned int>(_time64(NULL) % 3600I64);
538 QString str = QString::fromUtf8(msg).trimmed().replace('\n', '\t');
539 fprintf(g_lamexp_log_file, "[%c][%04u] %s\r\n", prefix[index], timestamp, str.toUtf8().constData());
540 fflush(g_lamexp_log_file);
543 if(g_lamexp_console_attached)
545 UINT oldOutputCP = GetConsoleOutputCP();
546 if(oldOutputCP != CP_UTF8) SetConsoleOutputCP(CP_UTF8);
554 lamexp_console_color(stderr, FOREGROUND_RED | FOREGROUND_INTENSITY);
555 fprintf(stderr, GURU_MEDITATION);
556 fprintf(stderr, "%s\n", msg);
560 lamexp_console_color(stderr, FOREGROUND_GREEN | FOREGROUND_RED | FOREGROUND_INTENSITY);
561 fprintf(stderr, "%s\n", msg);
565 lamexp_console_color(stderr, FOREGROUND_BLUE | FOREGROUND_GREEN | FOREGROUND_RED | FOREGROUND_INTENSITY);
566 fprintf(stderr, "%s\n", msg);
571 lamexp_console_color(stderr, FOREGROUND_BLUE | FOREGROUND_GREEN | FOREGROUND_RED);
572 if(oldOutputCP != CP_UTF8) SetConsoleOutputCP(oldOutputCP);
576 QString temp("[LameXP][%1] %2");
582 temp = temp.arg("C", QString::fromUtf8(msg));
585 temp = temp.arg("W", QString::fromUtf8(msg));
588 temp = temp.arg("I", QString::fromUtf8(msg));
592 temp.replace("\n", "\t").append("\n");
593 OutputDebugStringA(temp.toLatin1().constData());
596 if((type == QtCriticalMsg) || (type == QtFatalMsg))
599 lamexp_fatal_exit(L"The application has encountered a critical error and will exit now!", QWCHAR(QString::fromUtf8(msg)));
604 * Initialize the console
606 void lamexp_init_console(const QStringList &argv)
608 bool enableConsole = lamexp_version_demo();
612 wchar_t *logfile = NULL;
613 size_t logfile_len = 0;
614 if(!_wdupenv_s(&logfile, &logfile_len, L"LAMEXP_LOGFILE"))
616 if(logfile && (logfile_len > 0))
619 if(!_wfopen_s(&temp, logfile, L"wb"))
621 fprintf(temp, "%c%c%c", 0xEF, 0xBB, 0xBF);
622 g_lamexp_log_file = temp;
631 for(int i = 0; i < argv.count(); i++)
633 if(!argv.at(i).compare("--console", Qt::CaseInsensitive))
635 enableConsole = true;
637 else if(!argv.at(i).compare("--no-console", Qt::CaseInsensitive))
639 enableConsole = false;
646 if(!g_lamexp_console_attached)
648 if(AllocConsole() != FALSE)
650 SetConsoleCtrlHandler(NULL, TRUE);
651 SetConsoleTitle(L"LameXP - Audio Encoder Front-End | Debug Console");
652 SetConsoleOutputCP(CP_UTF8);
653 g_lamexp_console_attached = true;
657 if(g_lamexp_console_attached)
659 //-------------------------------------------------------------------
660 //See: http://support.microsoft.com/default.aspx?scid=kb;en-us;105305
661 //-------------------------------------------------------------------
662 const int flags = _O_WRONLY | _O_U8TEXT;
663 int hCrtStdOut = _open_osfhandle((intptr_t) GetStdHandle(STD_OUTPUT_HANDLE), flags);
664 int hCrtStdErr = _open_osfhandle((intptr_t) GetStdHandle(STD_ERROR_HANDLE), flags);
665 FILE *hfStdOut = (hCrtStdOut >= 0) ? _fdopen(hCrtStdOut, "wb") : NULL;
666 FILE *hfStdErr = (hCrtStdErr >= 0) ? _fdopen(hCrtStdErr, "wb") : NULL;
667 if(hfStdOut) { *stdout = *hfStdOut; std::cout.rdbuf(new std::filebuf(hfStdOut)); }
668 if(hfStdErr) { *stderr = *hfStdErr; std::cerr.rdbuf(new std::filebuf(hfStdErr)); }
671 HWND hwndConsole = GetConsoleWindow();
673 if((hwndConsole != NULL) && (hwndConsole != INVALID_HANDLE_VALUE))
675 HMENU hMenu = GetSystemMenu(hwndConsole, 0);
676 EnableMenuItem(hMenu, SC_CLOSE, MF_BYCOMMAND | MF_GRAYED);
677 RemoveMenu(hMenu, SC_CLOSE, MF_BYCOMMAND);
679 SetWindowPos(hwndConsole, HWND_TOP, 0, 0, 0, 0, SWP_NOMOVE|SWP_NOSIZE|SWP_NOZORDER|SWP_FRAMECHANGED);
680 SetWindowLong(hwndConsole, GWL_STYLE, GetWindowLong(hwndConsole, GWL_STYLE) & (~WS_MAXIMIZEBOX) & (~WS_MINIMIZEBOX));
681 SetWindowPos(hwndConsole, HWND_TOP, 0, 0, 0, 0, SWP_NOMOVE|SWP_NOSIZE|SWP_NOZORDER|SWP_FRAMECHANGED);
687 * Detect CPU features
689 lamexp_cpu_t lamexp_detect_cpu_features(const QStringList &argv)
691 typedef BOOL (WINAPI *IsWow64ProcessFun)(__in HANDLE hProcess, __out PBOOL Wow64Process);
692 typedef VOID (WINAPI *GetNativeSystemInfoFun)(__out LPSYSTEM_INFO lpSystemInfo);
694 static IsWow64ProcessFun IsWow64ProcessPtr = NULL;
695 static GetNativeSystemInfoFun GetNativeSystemInfoPtr = NULL;
697 lamexp_cpu_t features;
698 SYSTEM_INFO systemInfo;
699 int CPUInfo[4] = {-1};
700 char CPUIdentificationString[0x40];
701 char CPUBrandString[0x40];
703 memset(&features, 0, sizeof(lamexp_cpu_t));
704 memset(&systemInfo, 0, sizeof(SYSTEM_INFO));
705 memset(CPUIdentificationString, 0, sizeof(CPUIdentificationString));
706 memset(CPUBrandString, 0, sizeof(CPUBrandString));
709 memcpy(CPUIdentificationString, &CPUInfo[1], sizeof(int));
710 memcpy(CPUIdentificationString + 4, &CPUInfo[3], sizeof(int));
711 memcpy(CPUIdentificationString + 8, &CPUInfo[2], sizeof(int));
712 features.intel = (_stricmp(CPUIdentificationString, "GenuineIntel") == 0);
713 strncpy_s(features.vendor, 0x40, CPUIdentificationString, _TRUNCATE);
718 features.mmx = (CPUInfo[3] & 0x800000) || false;
719 features.sse = (CPUInfo[3] & 0x2000000) || false;
720 features.sse2 = (CPUInfo[3] & 0x4000000) || false;
721 features.ssse3 = (CPUInfo[2] & 0x200) || false;
722 features.sse3 = (CPUInfo[2] & 0x1) || false;
723 features.ssse3 = (CPUInfo[2] & 0x200) || false;
724 features.stepping = CPUInfo[0] & 0xf;
725 features.model = ((CPUInfo[0] >> 4) & 0xf) + (((CPUInfo[0] >> 16) & 0xf) << 4);
726 features.family = ((CPUInfo[0] >> 8) & 0xf) + ((CPUInfo[0] >> 20) & 0xff);
729 __cpuid(CPUInfo, 0x80000000);
730 int nExIds = qMax<int>(qMin<int>(CPUInfo[0], 0x80000004), 0x80000000);
732 for(int i = 0x80000002; i <= nExIds; ++i)
738 memcpy(CPUBrandString, CPUInfo, sizeof(CPUInfo));
741 memcpy(CPUBrandString + 16, CPUInfo, sizeof(CPUInfo));
744 memcpy(CPUBrandString + 32, CPUInfo, sizeof(CPUInfo));
749 strncpy_s(features.brand, 0x40, CPUBrandString, _TRUNCATE);
751 if(strlen(features.brand) < 1) strncpy_s(features.brand, 0x40, "Unknown", _TRUNCATE);
752 if(strlen(features.vendor) < 1) strncpy_s(features.vendor, 0x40, "Unknown", _TRUNCATE);
754 #if !defined(_M_X64 ) && !defined(_M_IA64)
755 if(!IsWow64ProcessPtr || !GetNativeSystemInfoPtr)
757 QLibrary Kernel32Lib("kernel32.dll");
758 IsWow64ProcessPtr = (IsWow64ProcessFun) Kernel32Lib.resolve("IsWow64Process");
759 GetNativeSystemInfoPtr = (GetNativeSystemInfoFun) Kernel32Lib.resolve("GetNativeSystemInfo");
761 if(IsWow64ProcessPtr)
764 if(IsWow64ProcessPtr(GetCurrentProcess(), &x64))
769 if(GetNativeSystemInfoPtr)
771 GetNativeSystemInfoPtr(&systemInfo);
775 GetSystemInfo(&systemInfo);
777 features.count = qBound(1UL, systemInfo.dwNumberOfProcessors, 64UL);
779 GetNativeSystemInfo(&systemInfo);
780 features.count = systemInfo.dwNumberOfProcessors;
787 for(int i = 0; i < argv.count(); i++)
789 if(!argv[i].compare("--force-cpu-no-64bit", Qt::CaseInsensitive)) { flag = true; features.x64 = false; }
790 if(!argv[i].compare("--force-cpu-no-sse", Qt::CaseInsensitive)) { flag = true; features.sse = features.sse2 = features.sse3 = features.ssse3 = false; }
791 if(!argv[i].compare("--force-cpu-no-intel", Qt::CaseInsensitive)) { flag = true; features.intel = false; }
793 if(flag) qWarning("CPU flags overwritten by user-defined parameters. Take care!\n");
800 * Check for debugger (detect routine)
802 static __forceinline bool lamexp_check_for_debugger(void)
804 if(IsDebuggerPresent())
811 CloseHandle((HANDLE) 0x7FFFFFFF);
813 __except(EXCEPTION_EXECUTE_HANDLER)
822 __except(EXCEPTION_EXECUTE_HANDLER)
831 * Check for debugger (thread proc)
833 static unsigned int __stdcall lamexp_debug_thread_proc(LPVOID lpParameter)
835 while(!lamexp_check_for_debugger())
839 lamexp_fatal_exit(L"Not a debug build. Please unload debugger and try again!");
844 * Check for debugger (startup routine)
846 static HANDLE lamexp_debug_thread_init(void)
848 if(lamexp_check_for_debugger())
850 lamexp_fatal_exit(L"Not a debug build. Please unload debugger and try again!");
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 lamexp_fatal_exit(L"Not a debug build. Please unload debugger and try again!");
1003 switch(reinterpret_cast<MSG*>(message)->message)
1005 case WM_QUERYENDSESSION:
1006 qWarning("WM_QUERYENDSESSION message received!");
1007 *result = lamexp_broadcast(lamexp_event_queryendsession, false) ? TRUE : FALSE;
1010 qWarning("WM_ENDSESSION message received!");
1011 if(reinterpret_cast<MSG*>(message)->wParam == TRUE)
1013 lamexp_broadcast(lamexp_event_endsession, false);
1014 if(QApplication *app = reinterpret_cast<QApplication*>(QApplication::instance()))
1016 app->closeAllWindows();
1019 lamexp_finalization();
1025 /*ignore this message and let Qt handle it*/
1031 * Check for process elevation
1033 static bool lamexp_check_elevation(void)
1035 typedef enum { lamexp_token_elevationType_class = 18, lamexp_token_elevation_class = 20 } LAMEXP_TOKEN_INFORMATION_CLASS;
1036 typedef enum { lamexp_elevationType_default = 1, lamexp_elevationType_full, lamexp_elevationType_limited } LAMEXP_TOKEN_ELEVATION_TYPE;
1038 HANDLE hToken = NULL;
1039 bool bIsProcessElevated = false;
1041 if(OpenProcessToken(GetCurrentProcess(), TOKEN_QUERY, &hToken))
1043 LAMEXP_TOKEN_ELEVATION_TYPE tokenElevationType;
1045 if(GetTokenInformation(hToken, (TOKEN_INFORMATION_CLASS) lamexp_token_elevationType_class, &tokenElevationType, sizeof(LAMEXP_TOKEN_ELEVATION_TYPE), &returnLength))
1047 if(returnLength == sizeof(LAMEXP_TOKEN_ELEVATION_TYPE))
1049 switch(tokenElevationType)
1051 case lamexp_elevationType_default:
1052 qDebug("Process token elevation type: Default -> UAC is disabled.\n");
1054 case lamexp_elevationType_full:
1055 qWarning("Process token elevation type: Full -> potential security risk!\n");
1056 bIsProcessElevated = true;
1058 case lamexp_elevationType_limited:
1059 qDebug("Process token elevation type: Limited -> not elevated.\n");
1064 CloseHandle(hToken);
1068 qWarning("Failed to open process token!");
1071 return !bIsProcessElevated;
1075 * Initialize Qt framework
1077 bool lamexp_init_qt(int argc, char* argv[])
1079 static bool qt_initialized = false;
1080 typedef BOOL (WINAPI *SetDllDirectoryProc)(WCHAR *lpPathName);
1081 const QStringList &arguments = lamexp_arguments();
1083 //Don't initialized again, if done already
1089 //Secure DLL loading
1090 QLibrary kernel32("kernel32.dll");
1093 SetDllDirectoryProc pSetDllDirectory = (SetDllDirectoryProc) kernel32.resolve("SetDllDirectoryW");
1094 if(pSetDllDirectory != NULL) pSetDllDirectory(L"");
1098 //Extract executable name from argv[] array
1099 QString executableName = QLatin1String("LameXP.exe");
1100 if(arguments.count() > 0)
1102 static const char *delimiters = "\\/:?";
1103 executableName = arguments[0].trimmed();
1104 for(int i = 0; delimiters[i]; i++)
1106 int temp = executableName.lastIndexOf(QChar(delimiters[i]));
1107 if(temp >= 0) executableName = executableName.mid(temp + 1);
1109 executableName = executableName.trimmed();
1110 if(executableName.isEmpty())
1112 executableName = QLatin1String("LameXP.exe");
1118 qDebug("Using Qt v%s [%s], %s, %s", qVersion(), QLibraryInfo::buildDate().toString(Qt::ISODate).toLatin1().constData(), (qSharedBuild() ? "DLL" : "Static"), QLibraryInfo::buildKey().toLatin1().constData());
1119 qDebug("Compiled with Qt v%s [%s], %s\n", QT_VERSION_STR, QT_PACKAGEDATE_STR, QT_BUILD_KEY);
1120 if(_stricmp(qVersion(), QT_VERSION_STR))
1122 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());
1125 if(QLibraryInfo::buildKey().compare(QString::fromLatin1(QT_BUILD_KEY), Qt::CaseInsensitive))
1127 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());
1131 qDebug("Using Qt v%s [%s], %s", qVersion(), QLibraryInfo::buildDate().toString(Qt::ISODate).toLatin1().constData(), (qSharedBuild() ? "DLL" : "Static"));
1132 qDebug("Compiled with Qt v%s [%s]\n", QT_VERSION_STR, QT_PACKAGEDATE_STR);
1135 //Check the Windows version
1136 switch(QSysInfo::windowsVersion() & QSysInfo::WV_NT_based)
1139 case QSysInfo::WV_NT:
1140 qFatal("%s", QApplication::tr("Executable '%1' requires Windows 2000 or later.").arg(executableName).toLatin1().constData());
1142 case QSysInfo::WV_2000:
1143 qDebug("Running on Windows 2000 (not officially supported!).\n");
1144 lamexp_check_compatibility_mode("GetNativeSystemInfo", executableName);
1146 case QSysInfo::WV_XP:
1147 qDebug("Running on Windows XP.\n");
1148 lamexp_check_compatibility_mode("GetLargePageMinimum", executableName);
1150 case QSysInfo::WV_2003:
1151 qDebug("Running on Windows Server 2003 or Windows XP x64-Edition.\n");
1152 lamexp_check_compatibility_mode("GetLocaleInfoEx", executableName);
1154 case QSysInfo::WV_VISTA:
1155 qDebug("Running on Windows Vista or Windows Server 2008.\n");
1156 lamexp_check_compatibility_mode("CreateRemoteThreadEx", executableName);
1158 case QSysInfo::WV_WINDOWS7:
1159 qDebug("Running on Windows 7 or Windows Server 2008 R2.\n");
1160 lamexp_check_compatibility_mode("CreateFile2", executableName);
1164 const lamexp_os_version_t *osVersionNo = lamexp_get_os_version();
1165 if(osVersionNo->versionMajor < 5)
1167 qFatal("%s", QApplication::tr("Executable '%1' requires Windows 2000 or later.").arg(executableName).toLatin1().constData());
1169 else if(LAMEXP_EQL_OS_VER(osVersionNo, 6, 2))
1171 qDebug("Running on Windows 8 or Windows Server 2012\n");
1172 lamexp_check_compatibility_mode(NULL, executableName);
1176 qWarning("Running on an unknown/untested WinNT-based OS (v%u.%u).\n", osVersionNo->versionMajor, osVersionNo->versionMinor);
1183 if(lamexp_detect_wine())
1185 qWarning("It appears we are running under Wine, unexpected things might happen!\n");
1188 //Set text Codec for locale
1189 QTextCodec::setCodecForLocale(QTextCodec::codecForName("UTF-8"));
1191 //Create Qt application instance
1192 QApplication *application = new QApplication(argc, argv);
1194 //Load plugins from application directory
1195 QCoreApplication::setLibraryPaths(QStringList() << QApplication::applicationDirPath());
1196 qDebug("Library Path:\n%s\n", QApplication::libraryPaths().first().toUtf8().constData());
1198 //Set application properties
1199 application->setApplicationName("LameXP - Audio Encoder Front-End");
1200 application->setApplicationVersion(QString().sprintf("%d.%02d.%04d", lamexp_version_major(), lamexp_version_minor(), lamexp_version_build()));
1201 application->setOrganizationName("LoRd_MuldeR");
1202 application->setOrganizationDomain("mulder.at.gg");
1203 application->setWindowIcon(lamexp_app_icon());
1204 application->setEventFilter(lamexp_event_filter);
1206 //Check for supported image formats
1207 QList<QByteArray> supportedFormats = QImageReader::supportedImageFormats();
1208 for(int i = 0; g_lamexp_imageformats[i]; i++)
1210 if(!supportedFormats.contains(g_lamexp_imageformats[i]))
1212 qFatal("Qt initialization error: QImageIOHandler for '%s' missing!", g_lamexp_imageformats[i]);
1217 //Add default translations
1218 QWriteLocker writeLockTranslations(&g_lamexp_translation.lock);
1219 if(!g_lamexp_translation.files) g_lamexp_translation.files = new QMap<QString, QString>();
1220 if(!g_lamexp_translation.names) g_lamexp_translation.names = new QMap<QString, QString>();
1221 g_lamexp_translation.files->insert(LAMEXP_DEFAULT_LANGID, "");
1222 g_lamexp_translation.names->insert(LAMEXP_DEFAULT_LANGID, "English");
1223 writeLockTranslations.unlock();
1225 //Check for process elevation
1226 if((!lamexp_check_elevation()) && (!lamexp_detect_wine()))
1228 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);
1229 messageBox.addButton("Quit Program (Recommended)", QMessageBox::NoRole);
1230 messageBox.addButton("Ignore", QMessageBox::NoRole);
1231 if(messageBox.exec() == 0)
1237 //Update console icon, if a console is attached
1238 #if QT_VERSION < QT_VERSION_CHECK(5,0,0)
1239 if(g_lamexp_console_attached && (!lamexp_detect_wine()))
1241 typedef DWORD (__stdcall *SetConsoleIconFun)(HICON);
1242 QLibrary kernel32("kernel32.dll");
1245 SetConsoleIconFun SetConsoleIconPtr = (SetConsoleIconFun) kernel32.resolve("SetConsoleIcon");
1246 if(SetConsoleIconPtr != NULL) SetConsoleIconPtr(QIcon(":/icons/sound.png").pixmap(16, 16).toWinHICON());
1253 qt_initialized = true;
1260 int lamexp_init_ipc(void)
1262 QWriteLocker writeLock(&g_lamexp_ipc_ptr.lock);
1264 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)
1269 g_lamexp_ipc_ptr.semaphore_read = new QSystemSemaphore(QString(g_lamexp_ipc_uuid.semaphore_read), 0);
1270 g_lamexp_ipc_ptr.semaphore_write = new QSystemSemaphore(QString(g_lamexp_ipc_uuid.semaphore_write), 0);
1271 g_lamexp_ipc_ptr.semaphore_read_mutex = new QSystemSemaphore(QString(g_lamexp_ipc_uuid.semaphore_read_mutex), 0);
1272 g_lamexp_ipc_ptr.semaphore_write_mutex = new QSystemSemaphore(QString(g_lamexp_ipc_uuid.semaphore_write_mutex), 0);
1274 if(g_lamexp_ipc_ptr.semaphore_read->error() != QSystemSemaphore::NoError)
1276 QString errorMessage = g_lamexp_ipc_ptr.semaphore_read->errorString();
1277 LAMEXP_DELETE(g_lamexp_ipc_ptr.semaphore_read);
1278 LAMEXP_DELETE(g_lamexp_ipc_ptr.semaphore_write);
1279 LAMEXP_DELETE(g_lamexp_ipc_ptr.semaphore_read_mutex);
1280 LAMEXP_DELETE(g_lamexp_ipc_ptr.semaphore_write_mutex);
1281 qFatal("Failed to create system smaphore: %s", errorMessage.toUtf8().constData());
1284 if(g_lamexp_ipc_ptr.semaphore_write->error() != QSystemSemaphore::NoError)
1286 QString errorMessage = g_lamexp_ipc_ptr.semaphore_write->errorString();
1287 LAMEXP_DELETE(g_lamexp_ipc_ptr.semaphore_read);
1288 LAMEXP_DELETE(g_lamexp_ipc_ptr.semaphore_write);
1289 LAMEXP_DELETE(g_lamexp_ipc_ptr.semaphore_read_mutex);
1290 LAMEXP_DELETE(g_lamexp_ipc_ptr.semaphore_write_mutex);
1291 qFatal("Failed to create system smaphore: %s", errorMessage.toUtf8().constData());
1294 if(g_lamexp_ipc_ptr.semaphore_read_mutex->error() != QSystemSemaphore::NoError)
1296 QString errorMessage = g_lamexp_ipc_ptr.semaphore_read_mutex->errorString();
1297 LAMEXP_DELETE(g_lamexp_ipc_ptr.semaphore_read);
1298 LAMEXP_DELETE(g_lamexp_ipc_ptr.semaphore_write);
1299 LAMEXP_DELETE(g_lamexp_ipc_ptr.semaphore_read_mutex);
1300 LAMEXP_DELETE(g_lamexp_ipc_ptr.semaphore_write_mutex);
1301 qFatal("Failed to create system smaphore: %s", errorMessage.toUtf8().constData());
1304 if(g_lamexp_ipc_ptr.semaphore_write_mutex->error() != QSystemSemaphore::NoError)
1306 QString errorMessage = g_lamexp_ipc_ptr.semaphore_write_mutex->errorString();
1307 LAMEXP_DELETE(g_lamexp_ipc_ptr.semaphore_read);
1308 LAMEXP_DELETE(g_lamexp_ipc_ptr.semaphore_write);
1309 LAMEXP_DELETE(g_lamexp_ipc_ptr.semaphore_read_mutex);
1310 LAMEXP_DELETE(g_lamexp_ipc_ptr.semaphore_write_mutex);
1311 qFatal("Failed to create system smaphore: %s", errorMessage.toUtf8().constData());
1315 g_lamexp_ipc_ptr.sharedmem = new QSharedMemory(QString(g_lamexp_ipc_uuid.sharedmem), NULL);
1317 if(!g_lamexp_ipc_ptr.sharedmem->create(sizeof(lamexp_ipc_t)))
1319 if(g_lamexp_ipc_ptr.sharedmem->error() == QSharedMemory::AlreadyExists)
1321 g_lamexp_ipc_ptr.sharedmem->attach();
1322 if(g_lamexp_ipc_ptr.sharedmem->error() == QSharedMemory::NoError)
1328 QString errorMessage = g_lamexp_ipc_ptr.sharedmem->errorString();
1329 LAMEXP_DELETE(g_lamexp_ipc_ptr.sharedmem);
1330 qFatal("Failed to attach to shared memory: %s", errorMessage.toUtf8().constData());
1336 QString errorMessage = g_lamexp_ipc_ptr.sharedmem->errorString();
1337 LAMEXP_DELETE(g_lamexp_ipc_ptr.sharedmem);
1338 qFatal("Failed to create shared memory: %s", errorMessage.toUtf8().constData());
1343 memset(g_lamexp_ipc_ptr.sharedmem->data(), 0, sizeof(lamexp_ipc_t));
1344 g_lamexp_ipc_ptr.semaphore_write->release(g_lamexp_ipc_slots);
1345 g_lamexp_ipc_ptr.semaphore_read_mutex->release();
1346 g_lamexp_ipc_ptr.semaphore_write_mutex->release();
1354 void lamexp_ipc_send(unsigned int command, const char* message)
1356 QReadLocker readLock(&g_lamexp_ipc_ptr.lock);
1358 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)
1360 throw "Shared memory for IPC not initialized yet.";
1363 lamexp_ipc_data_t ipc_data;
1364 memset(&ipc_data, 0, sizeof(lamexp_ipc_data_t));
1365 ipc_data.command = command;
1369 strncpy_s(ipc_data.parameter, 4096, message, _TRUNCATE);
1372 if(g_lamexp_ipc_ptr.semaphore_write->acquire())
1374 if(g_lamexp_ipc_ptr.semaphore_write_mutex->acquire())
1376 lamexp_ipc_t *ptr = reinterpret_cast<lamexp_ipc_t*>(g_lamexp_ipc_ptr.sharedmem->data());
1377 memcpy(&ptr->data[ptr->pos_write], &ipc_data, sizeof(lamexp_ipc_data_t));
1378 ptr->pos_write = (ptr->pos_write + 1) % g_lamexp_ipc_slots;
1379 g_lamexp_ipc_ptr.semaphore_read->release();
1380 g_lamexp_ipc_ptr.semaphore_write_mutex->release();
1388 void lamexp_ipc_read(unsigned int *command, char* message, size_t buffSize)
1390 QReadLocker readLock(&g_lamexp_ipc_ptr.lock);
1395 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)
1397 throw "Shared memory for IPC not initialized yet.";
1400 lamexp_ipc_data_t ipc_data;
1401 memset(&ipc_data, 0, sizeof(lamexp_ipc_data_t));
1403 if(g_lamexp_ipc_ptr.semaphore_read->acquire())
1405 if(g_lamexp_ipc_ptr.semaphore_read_mutex->acquire())
1407 lamexp_ipc_t *ptr = reinterpret_cast<lamexp_ipc_t*>(g_lamexp_ipc_ptr.sharedmem->data());
1408 memcpy(&ipc_data, &ptr->data[ptr->pos_read], sizeof(lamexp_ipc_data_t));
1409 ptr->pos_read = (ptr->pos_read + 1) % g_lamexp_ipc_slots;
1410 g_lamexp_ipc_ptr.semaphore_write->release();
1411 g_lamexp_ipc_ptr.semaphore_read_mutex->release();
1413 if(!(ipc_data.reserved_1 || ipc_data.reserved_2))
1415 *command = ipc_data.command;
1416 strncpy_s(message, buffSize, ipc_data.parameter, _TRUNCATE);
1420 qWarning("Malformed IPC message, will be ignored");
1427 * Check for LameXP "portable" mode
1429 bool lamexp_portable_mode(void)
1431 QString baseName = QFileInfo(QApplication::applicationFilePath()).completeBaseName();
1432 int idx1 = baseName.indexOf("lamexp", 0, Qt::CaseInsensitive);
1433 int idx2 = baseName.lastIndexOf("portable", -1, Qt::CaseInsensitive);
1434 return (idx1 >= 0) && (idx2 >= 0) && (idx1 < idx2);
1438 * Get a random string
1440 QString lamexp_rand_str(void)
1442 QRegExp regExp("\\{(\\w+)-(\\w+)-(\\w+)-(\\w+)-(\\w+)\\}");
1443 QString uuid = QUuid::createUuid().toString();
1445 if(regExp.indexIn(uuid) >= 0)
1447 return QString().append(regExp.cap(1)).append(regExp.cap(2)).append(regExp.cap(3)).append(regExp.cap(4)).append(regExp.cap(5));
1450 throw "The RegExp didn't match on the UUID string. This shouldn't happen ;-)";
1454 * Get LameXP temp folder
1456 const QString &lamexp_temp_folder2(void)
1458 QReadLocker readLock(&g_lamexp_folder.lock);
1460 //Already initialized?
1461 if(g_lamexp_folder.temp)
1463 if(!g_lamexp_folder.temp->isEmpty())
1465 if(QDir(*g_lamexp_folder.temp).exists())
1467 return *g_lamexp_folder.temp;
1473 QWriteLocker writeLock(&g_lamexp_folder.lock);
1475 if(!g_lamexp_folder.temp)
1477 g_lamexp_folder.temp = new QString();
1480 g_lamexp_folder.temp->clear();
1482 static const char *TEMP_STR = "Temp";
1483 const QString WRITE_TEST_DATA = lamexp_rand_str();
1484 const QString SUB_FOLDER = lamexp_rand_str();
1486 //Try the %TMP% or %TEMP% directory first
1487 QDir temp = QDir::temp();
1490 temp.mkdir(SUB_FOLDER);
1491 if(temp.cd(SUB_FOLDER) && temp.exists())
1493 QFile testFile(QString("%1/~%2.tmp").arg(temp.canonicalPath(), lamexp_rand_str()));
1494 if(testFile.open(QIODevice::ReadWrite))
1496 if(testFile.write(WRITE_TEST_DATA.toLatin1().constData()) >= strlen(WRITE_TEST_DATA.toLatin1().constData()))
1498 (*g_lamexp_folder.temp) = temp.canonicalPath();
1503 if(!g_lamexp_folder.temp->isEmpty())
1505 return *g_lamexp_folder.temp;
1509 //Create TEMP folder in %LOCALAPPDATA%
1510 QDir localAppData = QDir(lamexp_known_folder(lamexp_folder_localappdata));
1511 if(!localAppData.path().isEmpty())
1513 if(!localAppData.exists())
1515 localAppData.mkpath(".");
1517 if(localAppData.exists())
1519 if(!localAppData.entryList(QDir::AllDirs).contains(TEMP_STR, Qt::CaseInsensitive))
1521 localAppData.mkdir(TEMP_STR);
1523 if(localAppData.cd(TEMP_STR) && localAppData.exists())
1525 localAppData.mkdir(SUB_FOLDER);
1526 if(localAppData.cd(SUB_FOLDER) && localAppData.exists())
1528 QFile testFile(QString("%1/~%2.tmp").arg(localAppData.canonicalPath(), lamexp_rand_str()));
1529 if(testFile.open(QIODevice::ReadWrite))
1531 if(testFile.write(WRITE_TEST_DATA.toLatin1().constData()) >= strlen(WRITE_TEST_DATA.toLatin1().constData()))
1533 (*g_lamexp_folder.temp) = localAppData.canonicalPath();
1540 if(!g_lamexp_folder.temp->isEmpty())
1542 return *g_lamexp_folder.temp;
1546 //Failed to create TEMP folder!
1547 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());
1548 return *g_lamexp_folder.temp;
1554 bool lamexp_clean_folder(const QString &folderPath)
1556 QDir tempFolder(folderPath);
1557 QFileInfoList entryList = tempFolder.entryInfoList(QDir::AllEntries | QDir::NoDotAndDotDot);
1559 for(int i = 0; i < entryList.count(); i++)
1561 if(entryList.at(i).isDir())
1563 lamexp_clean_folder(entryList.at(i).canonicalFilePath());
1567 for(int j = 0; j < 3; j++)
1569 if(lamexp_remove_file(entryList.at(i).canonicalFilePath()))
1577 tempFolder.rmdir(".");
1578 return !tempFolder.exists();
1584 void lamexp_register_tool(const QString &toolName, LockedFile *file, unsigned int version, const QString *tag)
1586 QWriteLocker writeLock(&g_lamexp_tools.lock);
1588 if(!g_lamexp_tools.registry) g_lamexp_tools.registry = new QMap<QString, LockedFile*>();
1589 if(!g_lamexp_tools.versions) g_lamexp_tools.versions = new QMap<QString, unsigned int>();
1590 if(!g_lamexp_tools.tags) g_lamexp_tools.tags = new QMap<QString, QString>();
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);
1599 g_lamexp_tools.tags->insert(toolName.toLower(), (tag) ? (*tag) : QString());
1605 bool lamexp_check_tool(const QString &toolName)
1607 QReadLocker readLock(&g_lamexp_tools.lock);
1608 return (g_lamexp_tools.registry) ? g_lamexp_tools.registry->contains(toolName.toLower()) : false;
1614 const QString lamexp_lookup_tool(const QString &toolName)
1616 QReadLocker readLock(&g_lamexp_tools.lock);
1618 if(g_lamexp_tools.registry)
1620 if(g_lamexp_tools.registry->contains(toolName.toLower()))
1622 return g_lamexp_tools.registry->value(toolName.toLower())->filePath();
1636 * Lookup tool version
1638 unsigned int lamexp_tool_version(const QString &toolName, QString *tag)
1640 QReadLocker readLock(&g_lamexp_tools.lock);
1641 if(tag) tag->clear();
1643 if(g_lamexp_tools.versions)
1645 if(g_lamexp_tools.versions->contains(toolName.toLower()))
1649 if(g_lamexp_tools.tags->contains(toolName.toLower())) *tag = g_lamexp_tools.tags->value(toolName.toLower());
1651 return g_lamexp_tools.versions->value(toolName.toLower());
1665 * Version number to human-readable string
1667 const QString lamexp_version2string(const QString &pattern, unsigned int version, const QString &defaultText, const QString *tag)
1669 if(version == UINT_MAX)
1674 QString result = pattern;
1675 int digits = result.count("?", Qt::CaseInsensitive);
1683 QString versionStr = QString().sprintf(QString().sprintf("%%0%du", digits).toLatin1().constData(), version);
1684 int index = result.indexOf("?", Qt::CaseInsensitive);
1686 while(index >= 0 && pos < versionStr.length())
1688 result[index] = versionStr[pos++];
1689 index = result.indexOf("?", Qt::CaseInsensitive);
1694 result.replace(QChar('#'), *tag, Qt::CaseInsensitive);
1701 * Register a new translation
1703 bool lamexp_translation_register(const QString &langId, const QString &qmFile, const QString &langName, unsigned int &systemId, unsigned int &country)
1705 QWriteLocker writeLockTranslations(&g_lamexp_translation.lock);
1707 if(qmFile.isEmpty() || langName.isEmpty() || systemId < 1)
1712 if(!g_lamexp_translation.files) g_lamexp_translation.files = new QMap<QString, QString>();
1713 if(!g_lamexp_translation.names) g_lamexp_translation.names = new QMap<QString, QString>();
1714 if(!g_lamexp_translation.sysid) g_lamexp_translation.sysid = new QMap<QString, unsigned int>();
1715 if(!g_lamexp_translation.cntry) g_lamexp_translation.cntry = new QMap<QString, unsigned int>();
1717 g_lamexp_translation.files->insert(langId, qmFile);
1718 g_lamexp_translation.names->insert(langId, langName);
1719 g_lamexp_translation.sysid->insert(langId, systemId);
1720 g_lamexp_translation.cntry->insert(langId, country);
1726 * Get list of all translations
1728 QStringList lamexp_query_translations(void)
1730 QReadLocker readLockTranslations(&g_lamexp_translation.lock);
1731 return (g_lamexp_translation.files) ? g_lamexp_translation.files->keys() : QStringList();
1735 * Get translation name
1737 QString lamexp_translation_name(const QString &langId)
1739 QReadLocker readLockTranslations(&g_lamexp_translation.lock);
1740 return (g_lamexp_translation.names) ? g_lamexp_translation.names->value(langId.toLower(), QString()) : QString();
1744 * Get translation system id
1746 unsigned int lamexp_translation_sysid(const QString &langId)
1748 QReadLocker readLockTranslations(&g_lamexp_translation.lock);
1749 return (g_lamexp_translation.sysid) ? g_lamexp_translation.sysid->value(langId.toLower(), 0) : 0;
1753 * Get translation script id
1755 unsigned int lamexp_translation_country(const QString &langId)
1757 QReadLocker readLockTranslations(&g_lamexp_translation.lock);
1758 return (g_lamexp_translation.cntry) ? g_lamexp_translation.cntry->value(langId.toLower(), 0) : 0;
1762 * Install a new translator
1764 bool lamexp_install_translator(const QString &langId)
1766 bool success = false;
1767 const QString qmFileToPath(":/localization/%1");
1769 if(langId.isEmpty() || langId.toLower().compare(LAMEXP_DEFAULT_LANGID) == 0)
1771 success = lamexp_install_translator_from_file(qmFileToPath.arg(LAMEXP_DEFAULT_TRANSLATION));
1775 QReadLocker readLock(&g_lamexp_translation.lock);
1776 QString qmFile = (g_lamexp_translation.files) ? g_lamexp_translation.files->value(langId.toLower(), QString()) : QString();
1779 if(!qmFile.isEmpty())
1781 success = lamexp_install_translator_from_file(qmFileToPath.arg(qmFile));
1785 qWarning("Translation '%s' not available!", langId.toLatin1().constData());
1793 * Install a new translator from file
1795 bool lamexp_install_translator_from_file(const QString &qmFile)
1797 QWriteLocker writeLock(&g_lamexp_currentTranslator.lock);
1798 bool success = false;
1800 if(!g_lamexp_currentTranslator.instance)
1802 g_lamexp_currentTranslator.instance = new QTranslator();
1805 if(!qmFile.isEmpty())
1807 QString qmPath = QFileInfo(qmFile).canonicalFilePath();
1808 QApplication::removeTranslator(g_lamexp_currentTranslator.instance);
1809 if(success = g_lamexp_currentTranslator.instance->load(qmPath))
1811 QApplication::installTranslator(g_lamexp_currentTranslator.instance);
1815 qWarning("Failed to load translation:\n\"%s\"", qmPath.toLatin1().constData());
1820 QApplication::removeTranslator(g_lamexp_currentTranslator.instance);
1827 const QStringList &lamexp_arguments(void)
1829 QReadLocker readLock(&g_lamexp_argv.lock);
1831 if(!g_lamexp_argv.list)
1834 QWriteLocker writeLock(&g_lamexp_argv.lock);
1836 g_lamexp_argv.list = new QStringList;
1839 LPWSTR *szArglist = CommandLineToArgvW(GetCommandLineW(), &nArgs);
1841 if(NULL != szArglist)
1843 for(int i = 0; i < nArgs; i++)
1845 (*g_lamexp_argv.list) << WCHAR2QSTR(szArglist[i]);
1847 LocalFree(szArglist);
1851 qWarning("CommandLineToArgvW() has failed !!!");
1855 return (*g_lamexp_argv.list);
1859 * Locate known folder on local system
1861 const QString &lamexp_known_folder(lamexp_known_folder_t folder_id)
1863 typedef HRESULT (WINAPI *SHGetKnownFolderPathFun)(__in const GUID &rfid, __in DWORD dwFlags, __in HANDLE hToken, __out PWSTR *ppszPath);
1864 typedef HRESULT (WINAPI *SHGetFolderPathFun)(__in HWND hwndOwner, __in int nFolder, __in HANDLE hToken, __in DWORD dwFlags, __out LPWSTR pszPath);
1866 static const int CSIDL_LOCAL_APPDATA = 0x001c;
1867 static const int CSIDL_PROGRAM_FILES = 0x0026;
1868 static const int CSIDL_SYSTEM_FOLDER = 0x0025;
1869 static const GUID GUID_LOCAL_APPDATA = {0xF1B32785,0x6FBA,0x4FCF,{0x9D,0x55,0x7B,0x8E,0x7F,0x15,0x70,0x91}};
1870 static const GUID GUID_LOCAL_APPDATA_LOW = {0xA520A1A4,0x1780,0x4FF6,{0xBD,0x18,0x16,0x73,0x43,0xC5,0xAF,0x16}};
1871 static const GUID GUID_PROGRAM_FILES = {0x905e63b6,0xc1bf,0x494e,{0xb2,0x9c,0x65,0xb7,0x32,0xd3,0xd2,0x1a}};
1872 static const GUID GUID_SYSTEM_FOLDER = {0x1AC14E77,0x02E7,0x4E5D,{0xB7,0x44,0x2E,0xB1,0xAE,0x51,0x98,0xB7}};
1874 QReadLocker readLock(&g_lamexp_folder.lock);
1876 int folderCSIDL = -1;
1877 GUID folderGUID = {0x0000,0x0000,0x0000,{0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00}};
1878 size_t folderCacheId = size_t(-1);
1882 case lamexp_folder_localappdata:
1884 folderCSIDL = CSIDL_LOCAL_APPDATA;
1885 folderGUID = GUID_LOCAL_APPDATA;
1887 case lamexp_folder_programfiles:
1889 folderCSIDL = CSIDL_PROGRAM_FILES;
1890 folderGUID = GUID_PROGRAM_FILES;
1892 case lamexp_folder_systemfolder:
1894 folderCSIDL = CSIDL_SYSTEM_FOLDER;
1895 folderGUID = GUID_SYSTEM_FOLDER;
1898 qWarning("Invalid 'known' folder was requested!");
1899 return *reinterpret_cast<QString*>(NULL);
1904 if(g_lamexp_folder.knownFolders)
1906 if(g_lamexp_folder.knownFolders->contains(folderCacheId))
1908 return (*g_lamexp_folder.knownFolders)[folderCacheId];
1913 QWriteLocker writeLock(&g_lamexp_folder.lock);
1915 static SHGetKnownFolderPathFun SHGetKnownFolderPathPtr = NULL;
1916 static SHGetFolderPathFun SHGetFolderPathPtr = NULL;
1918 if((!SHGetKnownFolderPathPtr) && (!SHGetFolderPathPtr))
1920 QLibrary kernel32Lib("shell32.dll");
1921 if(kernel32Lib.load())
1923 SHGetKnownFolderPathPtr = (SHGetKnownFolderPathFun) kernel32Lib.resolve("SHGetKnownFolderPath");
1924 SHGetFolderPathPtr = (SHGetFolderPathFun) kernel32Lib.resolve("SHGetFolderPathW");
1930 if(SHGetKnownFolderPathPtr)
1933 if(SHGetKnownFolderPathPtr(folderGUID, 0x00008000, NULL, &path) == S_OK)
1935 //MessageBoxW(0, path, L"SHGetKnownFolderPath", MB_TOPMOST);
1936 QDir folderTemp = QDir(QDir::fromNativeSeparators(QString::fromUtf16(reinterpret_cast<const unsigned short*>(path))));
1937 if(!folderTemp.exists())
1939 folderTemp.mkpath(".");
1941 if(folderTemp.exists())
1943 folder = folderTemp.canonicalPath();
1945 CoTaskMemFree(path);
1948 else if(SHGetFolderPathPtr)
1950 WCHAR *path = new WCHAR[4096];
1951 if(SHGetFolderPathPtr(NULL, folderCSIDL, NULL, NULL, path) == S_OK)
1953 //MessageBoxW(0, path, L"SHGetFolderPathW", MB_TOPMOST);
1954 QDir folderTemp = QDir(QDir::fromNativeSeparators(QString::fromUtf16(reinterpret_cast<const unsigned short*>(path))));
1955 if(!folderTemp.exists())
1957 folderTemp.mkpath(".");
1959 if(folderTemp.exists())
1961 folder = folderTemp.canonicalPath();
1968 if(!g_lamexp_folder.knownFolders)
1970 g_lamexp_folder.knownFolders = new QMap<size_t, QString>();
1974 g_lamexp_folder.knownFolders->insert(folderCacheId, folder);
1975 return (*g_lamexp_folder.knownFolders)[folderCacheId];
1979 * Safely remove a file
1981 bool lamexp_remove_file(const QString &filename)
1983 if(!QFileInfo(filename).exists() || !QFileInfo(filename).isFile())
1989 if(!QFile::remove(filename))
1991 DWORD attributes = GetFileAttributesW(QWCHAR(filename));
1992 SetFileAttributesW(QWCHAR(filename), (attributes & (~FILE_ATTRIBUTE_READONLY)));
1993 if(!QFile::remove(filename))
1995 qWarning("Could not delete \"%s\"", filename.toLatin1().constData());
2011 * Check if visual themes are enabled (WinXP and later)
2013 bool lamexp_themes_enabled(void)
2015 typedef int (WINAPI *IsAppThemedFun)(void);
2017 QReadLocker readLock(&g_lamexp_themes_enabled.lock);
2018 if(g_lamexp_themes_enabled.bInitialized)
2020 return g_lamexp_themes_enabled.bThemesEnabled;
2024 QWriteLocker writeLock(&g_lamexp_themes_enabled.lock);
2026 if(!g_lamexp_themes_enabled.bInitialized)
2028 g_lamexp_themes_enabled.bThemesEnabled = false;
2029 const lamexp_os_version_t * osVersion = lamexp_get_os_version();
2030 if(LAMEXP_MIN_OS_VER(osVersion, 5, 1))
2032 IsAppThemedFun IsAppThemedPtr = NULL;
2033 QLibrary uxTheme(QString("%1/UxTheme.dll").arg(lamexp_known_folder(lamexp_folder_systemfolder)));
2036 IsAppThemedPtr = (IsAppThemedFun) uxTheme.resolve("IsAppThemed");
2040 g_lamexp_themes_enabled.bThemesEnabled = IsAppThemedPtr();
2041 if(!g_lamexp_themes_enabled.bThemesEnabled)
2043 qWarning("Theme support is disabled for this process!");
2047 g_lamexp_themes_enabled.bInitialized = true;
2050 return g_lamexp_themes_enabled.bThemesEnabled;
2054 * Get number of free bytes on disk
2056 unsigned __int64 lamexp_free_diskspace(const QString &path, bool *ok)
2058 ULARGE_INTEGER freeBytesAvailable, totalNumberOfBytes, totalNumberOfFreeBytes;
2059 if(GetDiskFreeSpaceExW(reinterpret_cast<const wchar_t*>(QDir::toNativeSeparators(path).utf16()), &freeBytesAvailable, &totalNumberOfBytes, &totalNumberOfFreeBytes))
2062 return freeBytesAvailable.QuadPart;
2072 * Check if computer does support hibernation
2074 bool lamexp_is_hibernation_supported(void)
2076 bool hibernationSupported = false;
2078 SYSTEM_POWER_CAPABILITIES pwrCaps;
2079 SecureZeroMemory(&pwrCaps, sizeof(SYSTEM_POWER_CAPABILITIES));
2081 if(GetPwrCapabilities(&pwrCaps))
2083 hibernationSupported = pwrCaps.SystemS4 && pwrCaps.HiberFilePresent;
2086 return hibernationSupported;
2090 * Shutdown the computer
2092 bool lamexp_shutdown_computer(const QString &message, const unsigned long timeout, const bool forceShutdown, const bool hibernate)
2094 HANDLE hToken = NULL;
2096 if(OpenProcessToken(GetCurrentProcess(), TOKEN_ADJUST_PRIVILEGES | TOKEN_QUERY, &hToken))
2098 TOKEN_PRIVILEGES privileges;
2099 memset(&privileges, 0, sizeof(TOKEN_PRIVILEGES));
2100 privileges.PrivilegeCount = 1;
2101 privileges.Privileges[0].Attributes = SE_PRIVILEGE_ENABLED;
2103 if(LookupPrivilegeValue(NULL, SE_SHUTDOWN_NAME, &privileges.Privileges[0].Luid))
2105 if(AdjustTokenPrivileges(hToken, FALSE, &privileges, NULL, NULL, NULL))
2109 if(SetSuspendState(TRUE, TRUE, TRUE))
2114 const DWORD reason = SHTDN_REASON_MAJOR_APPLICATION | SHTDN_REASON_FLAG_PLANNED;
2115 return InitiateSystemShutdownEx(NULL, const_cast<wchar_t*>(QWCHAR(message)), timeout, forceShutdown ? TRUE : FALSE, FALSE, reason);
2124 * Make a window blink (to draw user's attention)
2126 void lamexp_blink_window(QWidget *poWindow, unsigned int count, unsigned int delay)
2128 static QMutex blinkMutex;
2130 const double maxOpac = 1.0;
2131 const double minOpac = 0.3;
2132 const double delOpac = 0.1;
2134 if(!blinkMutex.tryLock())
2136 qWarning("Blinking is already in progress, skipping!");
2142 const int steps = static_cast<int>(ceil(maxOpac - minOpac) / delOpac);
2143 const int sleep = static_cast<int>(floor(static_cast<double>(delay) / static_cast<double>(steps)));
2144 const double opacity = poWindow->windowOpacity();
2146 for(unsigned int i = 0; i < count; i++)
2148 for(double x = maxOpac; x >= minOpac; x -= delOpac)
2150 poWindow->setWindowOpacity(x);
2151 QApplication::processEvents();
2155 for(double x = minOpac; x <= maxOpac; x += delOpac)
2157 poWindow->setWindowOpacity(x);
2158 QApplication::processEvents();
2163 poWindow->setWindowOpacity(opacity);
2164 QApplication::processEvents();
2165 blinkMutex.unlock();
2169 blinkMutex.unlock();
2170 qWarning("Exception error while blinking!");
2175 * Remove forbidden characters from a filename
2177 const QString lamexp_clean_filename(const QString &str)
2179 QString newStr(str);
2181 newStr.replace("\\", "-");
2182 newStr.replace(" / ", ", ");
2183 newStr.replace("/", ",");
2184 newStr.replace(":", "-");
2185 newStr.replace("*", "x");
2186 newStr.replace("?", "");
2187 newStr.replace("<", "[");
2188 newStr.replace(">", "]");
2189 newStr.replace("|", "!");
2191 return newStr.simplified();
2195 * Remove forbidden characters from a file path
2197 const QString lamexp_clean_filepath(const QString &str)
2199 QStringList parts = QString(str).replace("\\", "/").split("/");
2201 for(int i = 0; i < parts.count(); i++)
2203 parts[i] = lamexp_clean_filename(parts[i]);
2206 return parts.join("/");
2210 * Get a list of all available Qt Text Codecs
2212 QStringList lamexp_available_codepages(bool noAliases)
2214 QStringList codecList;
2216 QList<QByteArray> availableCodecs = QTextCodec::availableCodecs();
2217 while(!availableCodecs.isEmpty())
2219 QByteArray current = availableCodecs.takeFirst();
2220 if(!(current.startsWith("system") || current.startsWith("System")))
2222 codecList << QString::fromLatin1(current.constData(), current.size());
2225 if(QTextCodec *currentCodec = QTextCodec::codecForName(current.constData()))
2228 QList<QByteArray> aliases = currentCodec->aliases();
2229 while(!aliases.isEmpty()) availableCodecs.removeAll(aliases.takeFirst());
2239 * Robert Jenkins' 96 bit Mix Function
2240 * Source: http://www.concentric.net/~Ttwang/tech/inthash.htm
2242 static unsigned int lamexp_mix(const unsigned int x, const unsigned int y, const unsigned int z)
2248 a=a-b; a=a-c; a=a^(c >> 13);
2249 b=b-c; b=b-a; b=b^(a << 8);
2250 c=c-a; c=c-b; c=c^(b >> 13);
2251 a=a-b; a=a-c; a=a^(c >> 12);
2252 b=b-c; b=b-a; b=b^(a << 16);
2253 c=c-a; c=c-b; c=c^(b >> 5);
2254 a=a-b; a=a-c; a=a^(c >> 3);
2255 b=b-c; b=b-a; b=b^(a << 10);
2256 c=c-a; c=c-b; c=c^(b >> 15);
2262 * Seeds the random number generator
2263 * Note: Altough rand_s() doesn't need a seed, this must be called pripr to lamexp_rand(), just to to be sure!
2265 void lamexp_seed_rand(void)
2267 qsrand(lamexp_mix(clock(), time(NULL), _getpid()));
2271 * Returns a randum number
2272 * Note: This function uses rand_s() if available, but falls back to qrand() otherwise
2274 unsigned int lamexp_rand(void)
2276 unsigned int rnd = 0;
2277 if(const lamexp_os_version_t* osVer = lamexp_get_os_version())
2279 if(LAMEXP_MIN_OS_VER(osVer, 5, 1))
2281 if(rand_s(&rnd) == 0)
2287 for(size_t i = 0; i < sizeof(unsigned int); i++)
2289 rnd = (rnd << 8) ^ qrand();
2295 * Determines the current date, resistant against certain manipulations
2297 QDate lamexp_current_date_safe(void)
2299 const DWORD MAX_PROC = 1024;
2300 DWORD *processes = new DWORD[MAX_PROC];
2301 DWORD bytesReturned = 0;
2303 if(!EnumProcesses(processes, sizeof(DWORD) * MAX_PROC, &bytesReturned))
2305 LAMEXP_DELETE_ARRAY(processes);
2306 return QDate::currentDate();
2309 const DWORD procCount = bytesReturned / sizeof(DWORD);
2310 ULARGE_INTEGER lastStartTime;
2311 memset(&lastStartTime, 0, sizeof(ULARGE_INTEGER));
2313 for(DWORD i = 0; i < procCount; i++)
2315 HANDLE hProc = OpenProcess(PROCESS_QUERY_INFORMATION, FALSE, processes[i]);
2318 FILETIME processTime[4];
2319 if(GetProcessTimes(hProc, &processTime[0], &processTime[1], &processTime[2], &processTime[3]))
2321 ULARGE_INTEGER timeCreation;
2322 timeCreation.LowPart = processTime[0].dwLowDateTime;
2323 timeCreation.HighPart = processTime[0].dwHighDateTime;
2324 if(timeCreation.QuadPart > lastStartTime.QuadPart)
2326 lastStartTime.QuadPart = timeCreation.QuadPart;
2333 LAMEXP_DELETE_ARRAY(processes);
2335 FILETIME lastStartTime_fileTime;
2336 lastStartTime_fileTime.dwHighDateTime = lastStartTime.HighPart;
2337 lastStartTime_fileTime.dwLowDateTime = lastStartTime.LowPart;
2339 FILETIME lastStartTime_localTime;
2340 if(!FileTimeToLocalFileTime(&lastStartTime_fileTime, &lastStartTime_localTime))
2342 memcpy(&lastStartTime_localTime, &lastStartTime_fileTime, sizeof(FILETIME));
2345 SYSTEMTIME lastStartTime_system;
2346 if(!FileTimeToSystemTime(&lastStartTime_localTime, &lastStartTime_system))
2348 memset(&lastStartTime_system, 0, sizeof(SYSTEMTIME));
2349 lastStartTime_system.wYear = 1970; lastStartTime_system.wMonth = lastStartTime_system.wDay = 1;
2352 const QDate currentDate = QDate::currentDate();
2353 const QDate processDate = QDate(lastStartTime_system.wYear, lastStartTime_system.wMonth, lastStartTime_system.wDay);
2354 return (currentDate >= processDate) ? currentDate : processDate;
2358 * Entry point checks
2360 static DWORD lamexp_entry_check(void);
2361 static DWORD g_lamexp_entry_check_result = lamexp_entry_check();
2362 static DWORD g_lamexp_entry_check_flag = 0x789E09B2;
2363 static DWORD lamexp_entry_check(void)
2365 volatile DWORD retVal = 0xA199B5AF;
2366 if(g_lamexp_entry_check_flag != 0x8761F64D)
2368 lamexp_fatal_exit(L"Application initialization has failed, take care!");
2374 * Application entry point (runs before static initializers)
2378 int WinMainCRTStartup(void);
2380 int lamexp_entry_point(void)
2382 if((!LAMEXP_DEBUG) && lamexp_check_for_debugger())
2384 lamexp_fatal_exit(L"Not a debug build. Please unload debugger and try again!");
2386 if(g_lamexp_entry_check_flag != 0x789E09B2)
2388 lamexp_fatal_exit(L"Application initialization has failed, take care!");
2391 //Zero *before* constructors are called
2392 LAMEXP_ZERO_MEMORY(g_lamexp_argv);
2393 LAMEXP_ZERO_MEMORY(g_lamexp_tools);
2394 LAMEXP_ZERO_MEMORY(g_lamexp_currentTranslator);
2395 LAMEXP_ZERO_MEMORY(g_lamexp_translation);
2396 LAMEXP_ZERO_MEMORY(g_lamexp_folder);
2397 LAMEXP_ZERO_MEMORY(g_lamexp_ipc_ptr);
2398 LAMEXP_ZERO_MEMORY(g_lamexp_os_version);
2399 LAMEXP_ZERO_MEMORY(g_lamexp_themes_enabled);
2401 //Make sure we will pass the check
2402 g_lamexp_entry_check_flag = ~g_lamexp_entry_check_flag;
2404 //Now initialize the C Runtime library!
2405 return WinMainCRTStartup();
2410 * Fatal application exit
2412 #pragma intrinsic(_InterlockedExchange)
2413 void lamexp_fatal_exit(const wchar_t* exitMessage, const wchar_t* errorBoxMessage)
2415 static volatile long bFatalFlag = 0L;
2417 if(_InterlockedExchange(&bFatalFlag, 1L) == 0L)
2419 if(GetCurrentThreadId() != g_main_thread_id)
2421 HANDLE mainThread = OpenThread(THREAD_TERMINATE, FALSE, g_main_thread_id);
2422 if(mainThread) TerminateThread(mainThread, ULONG_MAX);
2427 MessageBoxW(NULL, errorBoxMessage, L"LameXP - GURU MEDITATION", MB_ICONERROR | MB_TOPMOST | MB_TASKMODAL);
2432 FatalAppExit(0, exitMessage);
2433 TerminateProcess(GetCurrentProcess(), -1);
2437 TerminateThread(GetCurrentThread(), -1);
2442 * Finalization function (final clean-up)
2444 void lamexp_finalization(void)
2446 qDebug("lamexp_finalization()");
2449 if(g_lamexp_tools.registry)
2451 QStringList keys = g_lamexp_tools.registry->keys();
2452 for(int i = 0; i < keys.count(); i++)
2454 LAMEXP_DELETE((*g_lamexp_tools.registry)[keys.at(i)]);
2456 LAMEXP_DELETE(g_lamexp_tools.registry);
2457 LAMEXP_DELETE(g_lamexp_tools.versions);
2458 LAMEXP_DELETE(g_lamexp_tools.tags);
2461 //Delete temporary files
2462 if(g_lamexp_folder.temp)
2464 if(!g_lamexp_folder.temp->isEmpty())
2466 for(int i = 0; i < 100; i++)
2468 if(lamexp_clean_folder(*g_lamexp_folder.temp))
2475 LAMEXP_DELETE(g_lamexp_folder.temp);
2478 //Clear folder cache
2479 LAMEXP_DELETE(g_lamexp_folder.knownFolders);
2482 if(g_lamexp_currentTranslator.instance)
2484 QApplication::removeTranslator(g_lamexp_currentTranslator.instance);
2485 LAMEXP_DELETE(g_lamexp_currentTranslator.instance);
2487 LAMEXP_DELETE(g_lamexp_translation.files);
2488 LAMEXP_DELETE(g_lamexp_translation.names);
2489 LAMEXP_DELETE(g_lamexp_translation.cntry);
2490 LAMEXP_DELETE(g_lamexp_translation.sysid);
2492 //Destroy Qt application object
2493 QApplication *application = dynamic_cast<QApplication*>(QApplication::instance());
2494 LAMEXP_DELETE(application);
2496 //Detach from shared memory
2497 if(g_lamexp_ipc_ptr.sharedmem) g_lamexp_ipc_ptr.sharedmem->detach();
2498 LAMEXP_DELETE(g_lamexp_ipc_ptr.sharedmem);
2499 LAMEXP_DELETE(g_lamexp_ipc_ptr.semaphore_read);
2500 LAMEXP_DELETE(g_lamexp_ipc_ptr.semaphore_write);
2501 LAMEXP_DELETE(g_lamexp_ipc_ptr.semaphore_read_mutex);
2502 LAMEXP_DELETE(g_lamexp_ipc_ptr.semaphore_write_mutex);
2504 //Free STDOUT and STDERR buffers
2505 if(g_lamexp_console_attached)
2507 if(std::filebuf *tmp = dynamic_cast<std::filebuf*>(std::cout.rdbuf()))
2509 std::cout.rdbuf(NULL);
2512 if(std::filebuf *tmp = dynamic_cast<std::filebuf*>(std::cerr.rdbuf()))
2514 std::cerr.rdbuf(NULL);
2520 if(g_lamexp_log_file)
2522 fclose(g_lamexp_log_file);
2523 g_lamexp_log_file = NULL;
2526 //Free CLI Arguments
2527 LAMEXP_DELETE(g_lamexp_argv.list);
2531 * Initialize debug thread
2533 static const HANDLE g_debug_thread = LAMEXP_DEBUG ? NULL : lamexp_debug_thread_init();
2536 * Get number private bytes [debug only]
2538 SIZE_T lamexp_dbg_private_bytes(void)
2541 PROCESS_MEMORY_COUNTERS_EX memoryCounters;
2542 memoryCounters.cb = sizeof(PROCESS_MEMORY_COUNTERS_EX);
2543 GetProcessMemoryInfo(GetCurrentProcess(), (PPROCESS_MEMORY_COUNTERS) &memoryCounters, sizeof(PROCESS_MEMORY_COUNTERS_EX));
2544 return memoryCounters.PrivateUsage;
2546 throw "Cannot call this function in a non-debug build!";
2547 #endif //LAMEXP_DEBUG