1 ///////////////////////////////////////////////////////////////////////////////
2 // LameXP - Audio Encoder Front-End
3 // Copyright (C) 2004-2012 LoRd_MuldeR <MuldeR2@GMX.de>
5 // This program is free software; you can redistribute it and/or modify
6 // it under the terms of the GNU General Public License as published by
7 // the Free Software Foundation; either version 2 of the License, or
8 // (at your option) any later version.
10 // This program is distributed in the hope that it will be useful,
11 // but WITHOUT ANY WARRANTY; without even the implied warranty of
12 // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 // GNU General Public License for more details.
15 // You should have received a copy of the GNU General Public License along
16 // with this program; if not, write to the Free Software Foundation, Inc.,
17 // 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
19 // http://www.gnu.org/licenses/gpl-2.0.txt
20 ///////////////////////////////////////////////////////////////////////////////
25 #include <QApplication>
26 #include <QMessageBox>
32 #include <QPlastiqueStyle>
33 #include <QImageReader>
34 #include <QSharedMemory>
36 #include <QStringList>
37 #include <QSystemSemaphore>
43 #include <QTranslator>
46 #include <QLibraryInfo>
51 #include "LockedFile.h"
71 //Initialize static Qt plugins
77 ///////////////////////////////////////////////////////////////////////////////
79 ///////////////////////////////////////////////////////////////////////////////
81 static const size_t g_lamexp_ipc_slots = 128;
86 unsigned int reserved_1;
87 unsigned int reserved_2;
94 unsigned int pos_write;
95 unsigned int pos_read;
96 lamexp_ipc_data_t data[g_lamexp_ipc_slots];
100 ///////////////////////////////////////////////////////////////////////////////
102 ///////////////////////////////////////////////////////////////////////////////
107 unsigned int ver_major;
108 unsigned int ver_minor;
109 unsigned int ver_build;
110 char *ver_release_name;
121 static QDate g_lamexp_version_date;
122 static const char *g_lamexp_months[] = {"Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"};
123 static const char *g_lamexp_version_raw_date = __DATE__;
124 static const char *g_lamexp_version_raw_time = __TIME__;
126 //Console attached flag
127 static bool g_lamexp_console_attached = false;
130 //The following code was borrowed from MPC-HC project: http://mpc-hc.sf.net/
131 #if defined(__INTEL_COMPILER)
132 #if (__INTEL_COMPILER >= 1200)
133 static const char *g_lamexp_version_compiler = "ICL 12.x";
134 #elif (__INTEL_COMPILER >= 1100)
135 static const char *g_lamexp_version_compiler = = "ICL 11.x";
136 #elif (__INTEL_COMPILER >= 1000)
137 static const char *g_lamexp_version_compiler = = "ICL 10.x";
139 #error Compiler is not supported!
141 #elif defined(_MSC_VER)
142 #if (_MSC_VER == 1600)
143 #if (_MSC_FULL_VER >= 160040219)
144 static const char *g_lamexp_version_compiler = "MSVC 2010-SP1";
146 static const char *g_lamexp_version_compiler = "MSVC 2010";
148 #elif (_MSC_VER == 1500)
149 #if (_MSC_FULL_VER >= 150030729)
150 static const char *g_lamexp_version_compiler = "MSVC 2008-SP1";
152 static const char *g_lamexp_version_compiler = "MSVC 2008";
155 #error Compiler is not supported!
158 // Note: /arch:SSE and /arch:SSE2 are only available for the x86 platform
159 #if !defined(_M_X64) && defined(_M_IX86_FP)
160 #if (_M_IX86_FP == 1)
161 LAMEXP_COMPILER_WARNING("SSE instruction set is enabled!")
162 #elif (_M_IX86_FP == 2)
163 LAMEXP_COMPILER_WARNING("SSE2 instruction set is enabled!")
167 #error Compiler is not supported!
170 //Architecture detection
172 static const char *g_lamexp_version_arch = "x64";
173 #elif defined(_M_IX86)
174 static const char *g_lamexp_version_arch = "x86";
176 #error Architecture is not supported!
179 //Official web-site URL
180 static const char *g_lamexp_website_url = "http://lamexp.sourceforge.net/";
181 static const char *g_lamexp_support_url = "http://forum.doom9.org/showthread.php?t=157726";
183 //Tool versions (expected versions!)
184 static const unsigned int g_lamexp_toolver_neroaac = VER_LAMEXP_TOOL_NEROAAC;
185 static const unsigned int g_lamexp_toolver_fhgaacenc = VER_LAMEXP_TOOL_FHGAACENC;
186 static const unsigned int g_lamexp_toolver_qaacenc = VER_LAMEXP_TOOL_QAAC;
187 static const unsigned int g_lamexp_toolver_coreaudio = VER_LAMEXP_TOOL_COREAUDIO;
190 static QString g_lamexp_temp_folder;
193 static QMap<QString, LockedFile*> g_lamexp_tool_registry;
194 static QMap<QString, unsigned int> g_lamexp_tool_versions;
199 QMap<QString, QString> files;
200 QMap<QString, QString> names;
201 QMap<QString, unsigned int> sysid;
202 QMap<QString, unsigned int> cntry;
204 g_lamexp_translation;
207 static QTranslator *g_lamexp_currentTranslator = NULL;
213 char *semaphore_read;
214 char *semaphore_read_mutex;
215 char *semaphore_write;
216 char *semaphore_write_mutex;
220 "{21A68A42-6923-43bb-9CF6-64BF151942EE}",
221 "{7A605549-F58C-4d78-B4E5-06EFC34F405B}",
222 "{60AA8D04-F6B8-497d-81EB-0F600F4A65B5}",
223 "{726061D5-1615-4B82-871C-75FD93458E46}",
224 "{1A616023-AA6A-4519-8AF3-F7736E899977}"
228 QSharedMemory *sharedmem;
229 QSystemSemaphore *semaphore_read;
230 QSystemSemaphore *semaphore_read_mutex;
231 QSystemSemaphore *semaphore_write;
232 QSystemSemaphore *semaphore_write_mutex;
240 static const char *g_lamexp_imageformats[] = {"png", "jpg", "gif", "ico", "svg", NULL};
243 static QMutex g_lamexp_message_mutex;
246 static const DWORD g_main_thread_id = GetCurrentThreadId();
249 static FILE *g_lamexp_log_file = NULL;
251 ///////////////////////////////////////////////////////////////////////////////
253 ///////////////////////////////////////////////////////////////////////////////
258 unsigned int lamexp_version_major(void) { return g_lamexp_version.ver_major; }
259 unsigned int lamexp_version_minor(void) { return g_lamexp_version.ver_minor; }
260 unsigned int lamexp_version_build(void) { return g_lamexp_version.ver_build; }
261 const char *lamexp_version_release(void) { return g_lamexp_version.ver_release_name; }
262 const char *lamexp_version_time(void) { return g_lamexp_version_raw_time; }
263 const char *lamexp_version_compiler(void) { return g_lamexp_version_compiler; }
264 const char *lamexp_version_arch(void) { return g_lamexp_version_arch; }
265 unsigned int lamexp_toolver_neroaac(void) { return g_lamexp_toolver_neroaac; }
266 unsigned int lamexp_toolver_fhgaacenc(void) { return g_lamexp_toolver_fhgaacenc; }
267 unsigned int lamexp_toolver_qaacenc(void) { return g_lamexp_toolver_qaacenc; }
268 unsigned int lamexp_toolver_coreaudio(void) { return g_lamexp_toolver_coreaudio; }
273 const char *lamexp_website_url(void) { return g_lamexp_website_url; }
274 const char *lamexp_support_url(void) { return g_lamexp_support_url; }
277 * Check for Demo (pre-release) version
279 bool lamexp_version_demo(void)
282 bool releaseVersion = false;
283 if(!strncpy_s(buffer, 128, g_lamexp_version.ver_release_name, _TRUNCATE))
285 char *context, *prefix = strtok_s(buffer, "-,; ", &context);
288 releaseVersion = (!_stricmp(prefix, "Final")) || (!_stricmp(prefix, "Hotfix"));
291 return LAMEXP_DEBUG || (!releaseVersion);
295 * Calculate expiration date
297 QDate lamexp_version_expires(void)
299 return lamexp_version_date().addDays(LAMEXP_DEBUG ? 2 : 30);
303 * Get build date date
305 const QDate &lamexp_version_date(void)
307 if(!g_lamexp_version_date.isValid())
309 int date[3] = {0, 0, 0}; char temp[12] = {'\0'};
310 strncpy_s(temp, 12, g_lamexp_version_raw_date, _TRUNCATE);
312 if(strlen(temp) == 11)
314 temp[3] = temp[6] = '\0';
315 date[2] = atoi(&temp[4]);
316 date[0] = atoi(&temp[7]);
318 for(int j = 0; j < 12; j++)
320 if(!_strcmpi(&temp[0], g_lamexp_months[j]))
327 g_lamexp_version_date = QDate(date[0], date[1], date[2]);
330 if(!g_lamexp_version_date.isValid())
332 qFatal("Internal error: Date format could not be recognized!");
336 return g_lamexp_version_date;
340 * Get the native operating system version
342 DWORD lamexp_get_os_version(void)
344 OSVERSIONINFO osVerInfo;
345 memset(&osVerInfo, 0, sizeof(OSVERSIONINFO));
346 osVerInfo.dwOSVersionInfoSize = sizeof(OSVERSIONINFO);
349 if(GetVersionEx(&osVerInfo) == TRUE)
351 if(osVerInfo.dwPlatformId != VER_PLATFORM_WIN32_NT)
353 throw "Ouuups: Not running under Windows NT. This is not supposed to happen!";
355 version = (DWORD)((osVerInfo.dwMajorVersion << 16) | (osVerInfo.dwMinorVersion & 0xffff));
362 * Global exception handler
364 LONG WINAPI lamexp_exception_handler(__in struct _EXCEPTION_POINTERS *ExceptionInfo)
366 if(GetCurrentThreadId() != g_main_thread_id)
368 HANDLE mainThread = OpenThread(THREAD_TERMINATE, FALSE, g_main_thread_id);
369 if(mainThread) TerminateThread(mainThread, ULONG_MAX);
372 FatalAppExit(0, L"Unhandeled exception handler invoked, application will exit!");
373 TerminateProcess(GetCurrentProcess(), -1);
378 * Invalid parameters handler
380 void lamexp_invalid_param_handler(const wchar_t*, const wchar_t*, const wchar_t*, unsigned int, uintptr_t)
382 if(GetCurrentThreadId() != g_main_thread_id)
384 HANDLE mainThread = OpenThread(THREAD_TERMINATE, FALSE, g_main_thread_id);
385 if(mainThread) TerminateThread(mainThread, ULONG_MAX);
389 FatalAppExit(0, L"Invalid parameter handler invoked, application will exit!");
390 TerminateProcess(GetCurrentProcess(), -1);
394 * Change console text color
396 static void lamexp_console_color(FILE* file, WORD attributes)
398 const HANDLE hConsole = (HANDLE)(_get_osfhandle(_fileno(file)));
399 if((hConsole != NULL) && (hConsole != INVALID_HANDLE_VALUE))
401 SetConsoleTextAttribute(hConsole, attributes);
408 void lamexp_message_handler(QtMsgType type, const char *msg)
410 static const char *GURU_MEDITATION = "\n\nGURU MEDITATION !!!\n\n";
412 QMutexLocker lock(&g_lamexp_message_mutex);
414 if(g_lamexp_log_file)
416 static char prefix[] = "DWCF";
417 int index = qBound(0, static_cast<int>(type), 3);
418 unsigned int timestamp = static_cast<unsigned int>(_time64(NULL) % 3600I64);
419 QString str = QString::fromUtf8(msg).trimmed().replace('\n', '\t');
420 fprintf(g_lamexp_log_file, "[%c][%04u] %s\r\n", prefix[index], timestamp, str.toUtf8().constData());
421 fflush(g_lamexp_log_file);
424 if(g_lamexp_console_attached)
426 UINT oldOutputCP = GetConsoleOutputCP();
427 if(oldOutputCP != CP_UTF8) SetConsoleOutputCP(CP_UTF8);
435 lamexp_console_color(stderr, FOREGROUND_RED | FOREGROUND_INTENSITY);
436 fprintf(stderr, GURU_MEDITATION);
437 fprintf(stderr, "%s\n", msg);
441 lamexp_console_color(stderr, FOREGROUND_GREEN | FOREGROUND_RED | FOREGROUND_INTENSITY);
442 fprintf(stderr, "%s\n", msg);
446 lamexp_console_color(stderr, FOREGROUND_BLUE | FOREGROUND_GREEN | FOREGROUND_RED | FOREGROUND_INTENSITY);
447 fprintf(stderr, "%s\n", msg);
452 lamexp_console_color(stderr, FOREGROUND_BLUE | FOREGROUND_GREEN | FOREGROUND_RED);
453 if(oldOutputCP != CP_UTF8) SetConsoleOutputCP(oldOutputCP);
457 QString temp("[LameXP][%1] %2");
463 temp = temp.arg("C", QString::fromUtf8(msg));
466 temp = temp.arg("W", QString::fromUtf8(msg));
469 temp = temp.arg("I", QString::fromUtf8(msg));
473 temp.replace("\n", "\t").append("\n");
474 OutputDebugStringA(temp.toLatin1().constData());
477 if(type == QtCriticalMsg || type == QtFatalMsg)
480 MessageBoxW(NULL, QWCHAR(QString::fromUtf8(msg)), L"LameXP - GURU MEDITATION", MB_ICONERROR | MB_TOPMOST | MB_TASKMODAL);
481 FatalAppExit(0, L"The application has encountered a critical error and will exit now!");
482 TerminateProcess(GetCurrentProcess(), -1);
487 * Initialize the console
489 void lamexp_init_console(int argc, char* argv[])
491 bool enableConsole = lamexp_version_demo();
495 wchar_t *logfile = NULL;
496 size_t logfile_len = 0;
497 if(!_wdupenv_s(&logfile, &logfile_len, L"LAMEXP_LOGFILE"))
499 if(logfile && (logfile_len > 0))
502 if(!_wfopen_s(&temp, logfile, L"wb"))
504 fprintf(temp, "%c%c%c", 0xEF, 0xBB, 0xBF);
505 g_lamexp_log_file = temp;
514 for(int i = 0; i < argc; i++)
516 if(!_stricmp(argv[i], "--console"))
518 enableConsole = true;
520 else if(!_stricmp(argv[i], "--no-console"))
522 enableConsole = false;
529 if(!g_lamexp_console_attached)
531 if(AllocConsole() != FALSE)
533 SetConsoleCtrlHandler(NULL, TRUE);
534 SetConsoleTitle(L"LameXP - Audio Encoder Front-End | Debug Console");
535 SetConsoleOutputCP(CP_UTF8);
536 g_lamexp_console_attached = true;
540 if(g_lamexp_console_attached)
542 //-------------------------------------------------------------------
543 //See: http://support.microsoft.com/default.aspx?scid=kb;en-us;105305
544 //-------------------------------------------------------------------
545 const int flags = _O_WRONLY | _O_U8TEXT;
546 int hCrtStdOut = _open_osfhandle((intptr_t) GetStdHandle(STD_OUTPUT_HANDLE), flags);
547 int hCrtStdErr = _open_osfhandle((intptr_t) GetStdHandle(STD_ERROR_HANDLE), flags);
548 FILE *hfStdOut = (hCrtStdOut >= 0) ? _fdopen(hCrtStdOut, "wb") : NULL;
549 FILE *hfStdErr = (hCrtStdErr >= 0) ? _fdopen(hCrtStdErr, "wb") : NULL;
550 if(hfStdOut) { *stdout = *hfStdOut; std::cout.rdbuf(new std::filebuf(hfStdOut)); }
551 if(hfStdErr) { *stderr = *hfStdErr; std::cerr.rdbuf(new std::filebuf(hfStdErr)); }
554 HWND hwndConsole = GetConsoleWindow();
556 if((hwndConsole != NULL) && (hwndConsole != INVALID_HANDLE_VALUE))
558 HMENU hMenu = GetSystemMenu(hwndConsole, 0);
559 EnableMenuItem(hMenu, SC_CLOSE, MF_BYCOMMAND | MF_GRAYED);
560 RemoveMenu(hMenu, SC_CLOSE, MF_BYCOMMAND);
562 SetWindowPos(hwndConsole, HWND_TOP, 0, 0, 0, 0, SWP_NOMOVE|SWP_NOSIZE|SWP_NOZORDER|SWP_FRAMECHANGED);
563 SetWindowLong(hwndConsole, GWL_STYLE, GetWindowLong(hwndConsole, GWL_STYLE) & (~WS_MAXIMIZEBOX) & (~WS_MINIMIZEBOX));
564 SetWindowPos(hwndConsole, HWND_TOP, 0, 0, 0, 0, SWP_NOMOVE|SWP_NOSIZE|SWP_NOZORDER|SWP_FRAMECHANGED);
570 * Detect CPU features
572 lamexp_cpu_t lamexp_detect_cpu_features(int argc, char **argv)
574 typedef BOOL (WINAPI *IsWow64ProcessFun)(__in HANDLE hProcess, __out PBOOL Wow64Process);
575 typedef VOID (WINAPI *GetNativeSystemInfoFun)(__out LPSYSTEM_INFO lpSystemInfo);
577 static IsWow64ProcessFun IsWow64ProcessPtr = NULL;
578 static GetNativeSystemInfoFun GetNativeSystemInfoPtr = NULL;
580 lamexp_cpu_t features;
581 SYSTEM_INFO systemInfo;
582 int CPUInfo[4] = {-1};
583 char CPUIdentificationString[0x40];
584 char CPUBrandString[0x40];
586 memset(&features, 0, sizeof(lamexp_cpu_t));
587 memset(&systemInfo, 0, sizeof(SYSTEM_INFO));
588 memset(CPUIdentificationString, 0, sizeof(CPUIdentificationString));
589 memset(CPUBrandString, 0, sizeof(CPUBrandString));
592 memcpy(CPUIdentificationString, &CPUInfo[1], sizeof(int));
593 memcpy(CPUIdentificationString + 4, &CPUInfo[3], sizeof(int));
594 memcpy(CPUIdentificationString + 8, &CPUInfo[2], sizeof(int));
595 features.intel = (_stricmp(CPUIdentificationString, "GenuineIntel") == 0);
596 strncpy_s(features.vendor, 0x40, CPUIdentificationString, _TRUNCATE);
601 features.mmx = (CPUInfo[3] & 0x800000) || false;
602 features.sse = (CPUInfo[3] & 0x2000000) || false;
603 features.sse2 = (CPUInfo[3] & 0x4000000) || false;
604 features.ssse3 = (CPUInfo[2] & 0x200) || false;
605 features.sse3 = (CPUInfo[2] & 0x1) || false;
606 features.ssse3 = (CPUInfo[2] & 0x200) || false;
607 features.stepping = CPUInfo[0] & 0xf;
608 features.model = ((CPUInfo[0] >> 4) & 0xf) + (((CPUInfo[0] >> 16) & 0xf) << 4);
609 features.family = ((CPUInfo[0] >> 8) & 0xf) + ((CPUInfo[0] >> 20) & 0xff);
612 __cpuid(CPUInfo, 0x80000000);
613 int nExIds = qMax<int>(qMin<int>(CPUInfo[0], 0x80000004), 0x80000000);
615 for(int i = 0x80000002; i <= nExIds; ++i)
621 memcpy(CPUBrandString, CPUInfo, sizeof(CPUInfo));
624 memcpy(CPUBrandString + 16, CPUInfo, sizeof(CPUInfo));
627 memcpy(CPUBrandString + 32, CPUInfo, sizeof(CPUInfo));
632 strncpy_s(features.brand, 0x40, CPUBrandString, _TRUNCATE);
634 if(strlen(features.brand) < 1) strncpy_s(features.brand, 0x40, "Unknown", _TRUNCATE);
635 if(strlen(features.vendor) < 1) strncpy_s(features.vendor, 0x40, "Unknown", _TRUNCATE);
637 #if !defined(_M_X64 ) && !defined(_M_IA64)
638 if(!IsWow64ProcessPtr || !GetNativeSystemInfoPtr)
640 QLibrary Kernel32Lib("kernel32.dll");
641 IsWow64ProcessPtr = (IsWow64ProcessFun) Kernel32Lib.resolve("IsWow64Process");
642 GetNativeSystemInfoPtr = (GetNativeSystemInfoFun) Kernel32Lib.resolve("GetNativeSystemInfo");
644 if(IsWow64ProcessPtr)
647 if(IsWow64ProcessPtr(GetCurrentProcess(), &x64))
652 if(GetNativeSystemInfoPtr)
654 GetNativeSystemInfoPtr(&systemInfo);
658 GetSystemInfo(&systemInfo);
660 features.count = qBound(1UL, systemInfo.dwNumberOfProcessors, 64UL);
662 GetNativeSystemInfo(&systemInfo);
663 features.count = systemInfo.dwNumberOfProcessors;
667 if((argv != NULL) && (argc > 0))
670 for(int i = 0; i < argc; i++)
672 if(!_stricmp("--force-cpu-no-64bit", argv[i])) { flag = true; features.x64 = false; }
673 if(!_stricmp("--force-cpu-no-sse", argv[i])) { flag = true; features.sse = features.sse2 = features.sse3 = features.ssse3 = false; }
674 if(!_stricmp("--force-cpu-no-intel", argv[i])) { flag = true; features.intel = false; }
676 if(flag) qWarning("CPU flags overwritten by user-defined parameters. Take care!\n");
683 * Check for debugger (detect routine)
685 static bool lamexp_check_for_debugger(void)
691 __except(GetExceptionCode() == EXCEPTION_BREAKPOINT ? EXCEPTION_EXECUTE_HANDLER : EXCEPTION_CONTINUE_SEARCH)
699 * Check for debugger (thread proc)
701 static void WINAPI lamexp_debug_thread_proc(__in LPVOID lpParameter)
703 while(!(IsDebuggerPresent() || lamexp_check_for_debugger()))
707 TerminateProcess(GetCurrentProcess(), -1);
711 * Check for debugger (startup routine)
713 static HANDLE lamexp_debug_thread_init(void)
715 if(IsDebuggerPresent() || lamexp_check_for_debugger())
717 FatalAppExit(0, L"Not a debug build. Please unload debugger and try again!");
718 TerminateProcess(GetCurrentProcess(), -1);
721 return CreateThread(NULL, NULL, reinterpret_cast<LPTHREAD_START_ROUTINE>(&lamexp_debug_thread_proc), NULL, NULL, NULL);
725 * Check for compatibility mode
727 static bool lamexp_check_compatibility_mode(const char *exportName, const char *executableName)
729 QLibrary kernel32("kernel32.dll");
731 if(exportName != NULL)
733 if(kernel32.resolve(exportName) != NULL)
735 qWarning("Function '%s' exported from 'kernel32.dll' -> Windows compatibility mode!", exportName);
736 qFatal("%s", QApplication::tr("Executable '%1' doesn't support Windows compatibility mode.").arg(QString::fromLatin1(executableName)).toLatin1().constData());
745 * Computus according to H. Lichtenberg
747 static bool lamexp_computus(const QDate &date)
752 int M = 15 + (3*K + 3) / 4 - (8*K + 13) / 25;
753 int D = (19*A + M) % 30;
754 int S = 2 - (3*K + 3) / 4;
755 int R = D / 29 + (D / 28 - D / 29) * (A / 11);
757 int SZ = 7 - (X + X / 4 + S) % 7;
758 int OE = 7 - (OG - SZ) % 7;
763 return (date.month() == 4) && (date.day() == (OS - 31));
767 return (date.month() == 3) && (date.day() == OS);
772 * Check for Thanksgiving
774 static bool lamexp_thanksgiving(const QDate &date)
778 switch(QDate(date.year(), 11, 1).dayOfWeek())
780 case 1: day = 25; break;
781 case 2: day = 24; break;
782 case 3: day = 23; break;
783 case 4: day = 22; break;
784 case 5: day = 28; break;
785 case 6: day = 27; break;
786 case 7: day = 26; break;
789 return (date.month() == 11) && (date.day() == day);
793 * Initialize app icon
795 QIcon lamexp_app_icon(const QDate *date, const QTime *time)
797 QDate currentDate = (date) ? QDate(*date) : QDate::currentDate();
798 QTime currentTime = (time) ? QTime(*time) : QTime::currentTime();
800 if(lamexp_thanksgiving(currentDate))
802 return QIcon(":/MainIcon6.png");
804 else if(((currentDate.month() == 12) && (currentDate.day() == 31) && (currentTime.hour() >= 20)) || ((currentDate.month() == 1) && (currentDate.day() == 1) && (currentTime.hour() <= 19)))
806 return QIcon(":/MainIcon5.png");
808 else if(((currentDate.month() == 10) && (currentDate.day() == 31) && (currentTime.hour() >= 12)) || ((currentDate.month() == 11) && (currentDate.day() == 1) && (currentTime.hour() <= 11)))
810 return QIcon(":/MainIcon4.png");
812 else if((currentDate.month() == 12) && (currentDate.day() >= 24) && (currentDate.day() <= 26))
814 return QIcon(":/MainIcon3.png");
816 else if(lamexp_computus(currentDate))
818 return QIcon(":/MainIcon2.png");
822 return QIcon(":/MainIcon1.png");
827 * Broadcast event to all windows
829 static bool lamexp_broadcast(int eventType, bool onlyToVisible)
831 if(QApplication *app = dynamic_cast<QApplication*>(QApplication::instance()))
833 qDebug("Broadcasting %d", eventType);
836 QEvent poEvent(static_cast<QEvent::Type>(eventType));
837 QWidgetList list = app->topLevelWidgets();
839 while(!list.isEmpty())
841 QWidget *widget = list.takeFirst();
842 if(!onlyToVisible || widget->isVisible())
844 if(!app->sendEvent(widget, &poEvent))
851 qDebug("Broadcast %d done (%s)", eventType, (allOk ? "OK" : "Stopped"));
856 qWarning("Broadcast failed, could not get QApplication instance!");
864 static bool lamexp_event_filter(void *message, long *result)
866 switch(reinterpret_cast<MSG*>(message)->message)
868 case WM_QUERYENDSESSION:
869 qWarning("WM_QUERYENDSESSION message received!");
870 *result = lamexp_broadcast(lamexp_event_queryendsession, false) ? TRUE : FALSE;
873 qWarning("WM_ENDSESSION message received!");
874 if(reinterpret_cast<MSG*>(message)->wParam == TRUE)
876 lamexp_broadcast(lamexp_event_endsession, false);
877 if(QApplication *app = reinterpret_cast<QApplication*>(QApplication::instance()))
879 app->closeAllWindows();
882 lamexp_finalization();
888 /*ignore this message and let Qt handle it*/
894 * Check for process elevation
896 static bool lamexp_check_elevation(void)
898 typedef enum { lamexp_token_elevationType_class = 18, lamexp_token_elevation_class = 20 } LAMEXP_TOKEN_INFORMATION_CLASS;
899 typedef enum { lamexp_elevationType_default = 1, lamexp_elevationType_full, lamexp_elevationType_limited } LAMEXP_TOKEN_ELEVATION_TYPE;
901 HANDLE hToken = NULL;
902 bool bIsProcessElevated = false;
904 if(OpenProcessToken(GetCurrentProcess(), TOKEN_QUERY, &hToken))
906 LAMEXP_TOKEN_ELEVATION_TYPE tokenElevationType;
908 if(GetTokenInformation(hToken, (TOKEN_INFORMATION_CLASS) lamexp_token_elevationType_class, &tokenElevationType, sizeof(LAMEXP_TOKEN_ELEVATION_TYPE), &returnLength))
910 if(returnLength == sizeof(LAMEXP_TOKEN_ELEVATION_TYPE))
912 switch(tokenElevationType)
914 case lamexp_elevationType_default:
915 qDebug("Process token elevation type: Default -> UAC is disabled.\n");
917 case lamexp_elevationType_full:
918 qWarning("Process token elevation type: Full -> potential security risk!\n");
919 bIsProcessElevated = true;
921 case lamexp_elevationType_limited:
922 qDebug("Process token elevation type: Limited -> not elevated.\n");
931 qWarning("Failed to open process token!");
934 return !bIsProcessElevated;
938 * Initialize Qt framework
940 bool lamexp_init_qt(int argc, char* argv[])
942 static bool qt_initialized = false;
944 typedef BOOL (WINAPI *SetDllDirectoryProc)(WCHAR *lpPathName);
946 //Don't initialized again, if done already
953 QLibrary kernel32("kernel32.dll");
956 SetDllDirectoryProc pSetDllDirectory = (SetDllDirectoryProc) kernel32.resolve("SetDllDirectoryW");
957 if(pSetDllDirectory != NULL) pSetDllDirectory(L"");
961 //Extract executable name from argv[] array
962 char *executableName = argv[0];
963 while(char *temp = strpbrk(executableName, "\\/:?"))
965 executableName = temp + 1;
969 qDebug("Using Qt v%s [%s], %s, %s", qVersion(), QLibraryInfo::buildDate().toString(Qt::ISODate).toLatin1().constData(), (qSharedBuild() ? "DLL" : "Static"), QLibraryInfo::buildKey().toLatin1().constData());
970 qDebug("Compiled with Qt v%s [%s], %s\n", QT_VERSION_STR, QT_PACKAGEDATE_STR, QT_BUILD_KEY);
971 if(_stricmp(qVersion(), QT_VERSION_STR))
973 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());
976 if(QLibraryInfo::buildKey().compare(QString::fromLatin1(QT_BUILD_KEY), Qt::CaseInsensitive))
978 qFatal("%s", QApplication::tr("Executable '%1' was built for Qt '%2', but found Qt '%3'.").arg(QString::fromLatin1(executableName), QString::fromLatin1(QT_BUILD_KEY), QLibraryInfo::buildKey()).toLatin1().constData());
982 //Check the Windows version
983 switch(QSysInfo::windowsVersion() & QSysInfo::WV_NT_based)
986 case QSysInfo::WV_NT:
987 qFatal("%s", QApplication::tr("Executable '%1' requires Windows 2000 or later.").arg(QString::fromLatin1(executableName)).toLatin1().constData());
989 case QSysInfo::WV_2000:
990 qDebug("Running on Windows 2000 (not officially supported!).\n");
991 lamexp_check_compatibility_mode("GetNativeSystemInfo", executableName);
993 case QSysInfo::WV_XP:
994 qDebug("Running on Windows XP.\n");
995 lamexp_check_compatibility_mode("GetLargePageMinimum", executableName);
997 case QSysInfo::WV_2003:
998 qDebug("Running on Windows Server 2003 or Windows XP x64-Edition.\n");
999 lamexp_check_compatibility_mode("GetLocaleInfoEx", executableName);
1001 case QSysInfo::WV_VISTA:
1002 qDebug("Running on Windows Vista or Windows Server 2008.\n");
1003 lamexp_check_compatibility_mode("CreateRemoteThreadEx", executableName);
1005 case QSysInfo::WV_WINDOWS7:
1006 qDebug("Running on Windows 7 or Windows Server 2008 R2.\n");
1007 lamexp_check_compatibility_mode(NULL, executableName);
1011 DWORD osVersionNo = lamexp_get_os_version();
1012 qWarning("Running on an unknown/untested WinNT-based OS (v%u.%u).\n", HIWORD(osVersionNo), LOWORD(osVersionNo));
1018 QLibrary ntdll("ntdll.dll");
1021 if(ntdll.resolve("wine_nt_to_unix_file_name") != NULL) isWine = true;
1022 if(ntdll.resolve("wine_get_version") != NULL) isWine = true;
1023 if(isWine) qWarning("It appears we are running under Wine, unexpected things might happen!\n");
1027 //Create Qt application instance and setup version info
1028 QApplication *application = new QApplication(argc, argv);
1029 application->setApplicationName("LameXP - Audio Encoder Front-End");
1030 application->setApplicationVersion(QString().sprintf("%d.%02d.%04d", lamexp_version_major(), lamexp_version_minor(), lamexp_version_build()));
1031 application->setOrganizationName("LoRd_MuldeR");
1032 application->setOrganizationDomain("mulder.at.gg");
1033 application->setWindowIcon(lamexp_app_icon());
1034 application->setEventFilter(lamexp_event_filter);
1036 //Set text Codec for locale
1037 QTextCodec::setCodecForLocale(QTextCodec::codecForName("UTF-8"));
1039 //Load plugins from application directory
1040 QCoreApplication::setLibraryPaths(QStringList() << QApplication::applicationDirPath());
1041 qDebug("Library Path:\n%s\n", QApplication::libraryPaths().first().toUtf8().constData());
1043 //Check for supported image formats
1044 QList<QByteArray> supportedFormats = QImageReader::supportedImageFormats();
1045 for(int i = 0; g_lamexp_imageformats[i]; i++)
1047 if(!supportedFormats.contains(g_lamexp_imageformats[i]))
1049 qFatal("Qt initialization error: QImageIOHandler for '%s' missing!", g_lamexp_imageformats[i]);
1054 //Add default translations
1055 g_lamexp_translation.files.insert(LAMEXP_DEFAULT_LANGID, "");
1056 g_lamexp_translation.names.insert(LAMEXP_DEFAULT_LANGID, "English");
1058 //Check for process elevation
1059 if(!lamexp_check_elevation())
1061 if(QMessageBox::warning(NULL, "LameXP", "<nobr>LameXP was started with elevated rights. This is a potential security risk!</nobr>", "Quit Program (Recommended)", "Ignore") == 0)
1067 //Update console icon, if a console is attached
1068 if(g_lamexp_console_attached && !isWine)
1070 typedef DWORD (__stdcall *SetConsoleIconFun)(HICON);
1071 QLibrary kernel32("kernel32.dll");
1074 SetConsoleIconFun SetConsoleIconPtr = (SetConsoleIconFun) kernel32.resolve("SetConsoleIcon");
1075 if(SetConsoleIconPtr != NULL) SetConsoleIconPtr(QIcon(":/icons/sound.png").pixmap(16, 16).toWinHICON());
1081 qt_initialized = true;
1088 int lamexp_init_ipc(void)
1090 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)
1095 g_lamexp_ipc_ptr.semaphore_read = new QSystemSemaphore(QString(g_lamexp_ipc_uuid.semaphore_read), 0);
1096 g_lamexp_ipc_ptr.semaphore_write = new QSystemSemaphore(QString(g_lamexp_ipc_uuid.semaphore_write), 0);
1097 g_lamexp_ipc_ptr.semaphore_read_mutex = new QSystemSemaphore(QString(g_lamexp_ipc_uuid.semaphore_read_mutex), 0);
1098 g_lamexp_ipc_ptr.semaphore_write_mutex = new QSystemSemaphore(QString(g_lamexp_ipc_uuid.semaphore_write_mutex), 0);
1100 if(g_lamexp_ipc_ptr.semaphore_read->error() != QSystemSemaphore::NoError)
1102 QString errorMessage = g_lamexp_ipc_ptr.semaphore_read->errorString();
1103 LAMEXP_DELETE(g_lamexp_ipc_ptr.semaphore_read);
1104 LAMEXP_DELETE(g_lamexp_ipc_ptr.semaphore_write);
1105 LAMEXP_DELETE(g_lamexp_ipc_ptr.semaphore_read_mutex);
1106 LAMEXP_DELETE(g_lamexp_ipc_ptr.semaphore_write_mutex);
1107 qFatal("Failed to create system smaphore: %s", errorMessage.toUtf8().constData());
1110 if(g_lamexp_ipc_ptr.semaphore_write->error() != QSystemSemaphore::NoError)
1112 QString errorMessage = g_lamexp_ipc_ptr.semaphore_write->errorString();
1113 LAMEXP_DELETE(g_lamexp_ipc_ptr.semaphore_read);
1114 LAMEXP_DELETE(g_lamexp_ipc_ptr.semaphore_write);
1115 LAMEXP_DELETE(g_lamexp_ipc_ptr.semaphore_read_mutex);
1116 LAMEXP_DELETE(g_lamexp_ipc_ptr.semaphore_write_mutex);
1117 qFatal("Failed to create system smaphore: %s", errorMessage.toUtf8().constData());
1120 if(g_lamexp_ipc_ptr.semaphore_read_mutex->error() != QSystemSemaphore::NoError)
1122 QString errorMessage = g_lamexp_ipc_ptr.semaphore_read_mutex->errorString();
1123 LAMEXP_DELETE(g_lamexp_ipc_ptr.semaphore_read);
1124 LAMEXP_DELETE(g_lamexp_ipc_ptr.semaphore_write);
1125 LAMEXP_DELETE(g_lamexp_ipc_ptr.semaphore_read_mutex);
1126 LAMEXP_DELETE(g_lamexp_ipc_ptr.semaphore_write_mutex);
1127 qFatal("Failed to create system smaphore: %s", errorMessage.toUtf8().constData());
1130 if(g_lamexp_ipc_ptr.semaphore_write_mutex->error() != QSystemSemaphore::NoError)
1132 QString errorMessage = g_lamexp_ipc_ptr.semaphore_write_mutex->errorString();
1133 LAMEXP_DELETE(g_lamexp_ipc_ptr.semaphore_read);
1134 LAMEXP_DELETE(g_lamexp_ipc_ptr.semaphore_write);
1135 LAMEXP_DELETE(g_lamexp_ipc_ptr.semaphore_read_mutex);
1136 LAMEXP_DELETE(g_lamexp_ipc_ptr.semaphore_write_mutex);
1137 qFatal("Failed to create system smaphore: %s", errorMessage.toUtf8().constData());
1141 g_lamexp_ipc_ptr.sharedmem = new QSharedMemory(QString(g_lamexp_ipc_uuid.sharedmem), NULL);
1143 if(!g_lamexp_ipc_ptr.sharedmem->create(sizeof(lamexp_ipc_t)))
1145 if(g_lamexp_ipc_ptr.sharedmem->error() == QSharedMemory::AlreadyExists)
1147 g_lamexp_ipc_ptr.sharedmem->attach();
1148 if(g_lamexp_ipc_ptr.sharedmem->error() == QSharedMemory::NoError)
1154 QString errorMessage = g_lamexp_ipc_ptr.sharedmem->errorString();
1155 LAMEXP_DELETE(g_lamexp_ipc_ptr.sharedmem);
1156 qFatal("Failed to attach to shared memory: %s", errorMessage.toUtf8().constData());
1162 QString errorMessage = g_lamexp_ipc_ptr.sharedmem->errorString();
1163 LAMEXP_DELETE(g_lamexp_ipc_ptr.sharedmem);
1164 qFatal("Failed to create shared memory: %s", errorMessage.toUtf8().constData());
1169 memset(g_lamexp_ipc_ptr.sharedmem->data(), 0, sizeof(lamexp_ipc_t));
1170 g_lamexp_ipc_ptr.semaphore_write->release(g_lamexp_ipc_slots);
1171 g_lamexp_ipc_ptr.semaphore_read_mutex->release();
1172 g_lamexp_ipc_ptr.semaphore_write_mutex->release();
1180 void lamexp_ipc_send(unsigned int command, const char* message)
1182 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)
1184 throw "Shared memory for IPC not initialized yet.";
1187 lamexp_ipc_data_t ipc_data;
1188 memset(&ipc_data, 0, sizeof(lamexp_ipc_data_t));
1189 ipc_data.command = command;
1193 strncpy_s(ipc_data.parameter, 4096, message, _TRUNCATE);
1196 if(g_lamexp_ipc_ptr.semaphore_write->acquire())
1198 if(g_lamexp_ipc_ptr.semaphore_write_mutex->acquire())
1200 lamexp_ipc_t *ptr = reinterpret_cast<lamexp_ipc_t*>(g_lamexp_ipc_ptr.sharedmem->data());
1201 memcpy(&ptr->data[ptr->pos_write], &ipc_data, sizeof(lamexp_ipc_data_t));
1202 ptr->pos_write = (ptr->pos_write + 1) % g_lamexp_ipc_slots;
1203 g_lamexp_ipc_ptr.semaphore_read->release();
1204 g_lamexp_ipc_ptr.semaphore_write_mutex->release();
1212 void lamexp_ipc_read(unsigned int *command, char* message, size_t buffSize)
1217 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)
1219 throw "Shared memory for IPC not initialized yet.";
1222 lamexp_ipc_data_t ipc_data;
1223 memset(&ipc_data, 0, sizeof(lamexp_ipc_data_t));
1225 if(g_lamexp_ipc_ptr.semaphore_read->acquire())
1227 if(g_lamexp_ipc_ptr.semaphore_read_mutex->acquire())
1229 lamexp_ipc_t *ptr = reinterpret_cast<lamexp_ipc_t*>(g_lamexp_ipc_ptr.sharedmem->data());
1230 memcpy(&ipc_data, &ptr->data[ptr->pos_read], sizeof(lamexp_ipc_data_t));
1231 ptr->pos_read = (ptr->pos_read + 1) % g_lamexp_ipc_slots;
1232 g_lamexp_ipc_ptr.semaphore_write->release();
1233 g_lamexp_ipc_ptr.semaphore_read_mutex->release();
1235 if(!(ipc_data.reserved_1 || ipc_data.reserved_2))
1237 *command = ipc_data.command;
1238 strncpy_s(message, buffSize, ipc_data.parameter, _TRUNCATE);
1242 qWarning("Malformed IPC message, will be ignored");
1249 * Check for LameXP "portable" mode
1251 bool lamexp_portable_mode(void)
1253 QString baseName = QFileInfo(QApplication::applicationFilePath()).completeBaseName();
1254 int idx1 = baseName.indexOf("lamexp", 0, Qt::CaseInsensitive);
1255 int idx2 = baseName.lastIndexOf("portable", -1, Qt::CaseInsensitive);
1256 return (idx1 >= 0) && (idx2 >= 0) && (idx1 < idx2);
1260 * Get a random string
1262 QString lamexp_rand_str(void)
1264 QRegExp regExp("\\{(\\w+)-(\\w+)-(\\w+)-(\\w+)-(\\w+)\\}");
1265 QString uuid = QUuid::createUuid().toString();
1267 if(regExp.indexIn(uuid) >= 0)
1269 return QString().append(regExp.cap(1)).append(regExp.cap(2)).append(regExp.cap(3)).append(regExp.cap(4)).append(regExp.cap(5));
1272 throw "The RegExp didn't match on the UUID string. This shouldn't happen ;-)";
1276 * Get LameXP temp folder
1278 const QString &lamexp_temp_folder2(void)
1280 static const char *TEMP_STR = "Temp";
1281 const QString WRITE_TEST_DATA = lamexp_rand_str();
1282 const QString SUB_FOLDER = lamexp_rand_str();
1284 //Already initialized?
1285 if(!g_lamexp_temp_folder.isEmpty())
1287 if(QDir(g_lamexp_temp_folder).exists())
1289 return g_lamexp_temp_folder;
1293 g_lamexp_temp_folder.clear();
1297 //Try the %TMP% or %TEMP% directory first
1298 QDir temp = QDir::temp();
1301 temp.mkdir(SUB_FOLDER);
1302 if(temp.cd(SUB_FOLDER) && temp.exists())
1304 QFile testFile(QString("%1/~%2.tmp").arg(temp.canonicalPath(), lamexp_rand_str()));
1305 if(testFile.open(QIODevice::ReadWrite))
1307 if(testFile.write(WRITE_TEST_DATA.toLatin1().constData()) >= strlen(WRITE_TEST_DATA.toLatin1().constData()))
1309 g_lamexp_temp_folder = temp.canonicalPath();
1314 if(!g_lamexp_temp_folder.isEmpty())
1316 return g_lamexp_temp_folder;
1320 //Create TEMP folder in %LOCALAPPDATA%
1321 QDir localAppData = QDir(lamexp_known_folder(lamexp_folder_localappdata));
1322 if(!localAppData.path().isEmpty())
1324 if(!localAppData.exists())
1326 localAppData.mkpath(".");
1328 if(localAppData.exists())
1330 if(!localAppData.entryList(QDir::AllDirs).contains(TEMP_STR, Qt::CaseInsensitive))
1332 localAppData.mkdir(TEMP_STR);
1334 if(localAppData.cd(TEMP_STR) && localAppData.exists())
1336 localAppData.mkdir(SUB_FOLDER);
1337 if(localAppData.cd(SUB_FOLDER) && localAppData.exists())
1339 QFile testFile(QString("%1/~%2.tmp").arg(localAppData.canonicalPath(), lamexp_rand_str()));
1340 if(testFile.open(QIODevice::ReadWrite))
1342 if(testFile.write(WRITE_TEST_DATA.toLatin1().constData()) >= strlen(WRITE_TEST_DATA.toLatin1().constData()))
1344 g_lamexp_temp_folder = localAppData.canonicalPath();
1351 if(!g_lamexp_temp_folder.isEmpty())
1353 return g_lamexp_temp_folder;
1357 //Failed to create TEMP folder!
1358 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());
1359 return g_lamexp_temp_folder;
1365 bool lamexp_clean_folder(const QString &folderPath)
1367 QDir tempFolder(folderPath);
1368 QFileInfoList entryList = tempFolder.entryInfoList(QDir::AllEntries | QDir::NoDotAndDotDot);
1370 for(int i = 0; i < entryList.count(); i++)
1372 if(entryList.at(i).isDir())
1374 lamexp_clean_folder(entryList.at(i).canonicalFilePath());
1378 for(int j = 0; j < 3; j++)
1380 if(lamexp_remove_file(entryList.at(i).canonicalFilePath()))
1388 tempFolder.rmdir(".");
1389 return !tempFolder.exists();
1395 void lamexp_register_tool(const QString &toolName, LockedFile *file, unsigned int version)
1397 if(g_lamexp_tool_registry.contains(toolName.toLower()))
1399 throw "lamexp_register_tool: Tool is already registered!";
1402 g_lamexp_tool_registry.insert(toolName.toLower(), file);
1403 g_lamexp_tool_versions.insert(toolName.toLower(), version);
1409 bool lamexp_check_tool(const QString &toolName)
1411 return g_lamexp_tool_registry.contains(toolName.toLower());
1417 const QString lamexp_lookup_tool(const QString &toolName)
1419 if(g_lamexp_tool_registry.contains(toolName.toLower()))
1421 return g_lamexp_tool_registry.value(toolName.toLower())->filePath();
1430 * Lookup tool version
1432 unsigned int lamexp_tool_version(const QString &toolName)
1434 if(g_lamexp_tool_versions.contains(toolName.toLower()))
1436 return g_lamexp_tool_versions.value(toolName.toLower());
1445 * Version number to human-readable string
1447 const QString lamexp_version2string(const QString &pattern, unsigned int version, const QString &defaultText)
1449 if(version == UINT_MAX)
1454 QString result = pattern;
1455 int digits = result.count("?", Qt::CaseInsensitive);
1463 QString versionStr = QString().sprintf(QString().sprintf("%%0%du", digits).toLatin1().constData(), version);
1464 int index = result.indexOf("?", Qt::CaseInsensitive);
1466 while(index >= 0 && pos < versionStr.length())
1468 result[index] = versionStr[pos++];
1469 index = result.indexOf("?", Qt::CaseInsensitive);
1476 * Register a new translation
1478 bool lamexp_translation_register(const QString &langId, const QString &qmFile, const QString &langName, unsigned int &systemId, unsigned int &country)
1480 if(qmFile.isEmpty() || langName.isEmpty() || systemId < 1)
1485 g_lamexp_translation.files.insert(langId, qmFile);
1486 g_lamexp_translation.names.insert(langId, langName);
1487 g_lamexp_translation.sysid.insert(langId, systemId);
1488 g_lamexp_translation.cntry.insert(langId, country);
1494 * Get list of all translations
1496 QStringList lamexp_query_translations(void)
1498 return g_lamexp_translation.files.keys();
1502 * Get translation name
1504 QString lamexp_translation_name(const QString &langId)
1506 return g_lamexp_translation.names.value(langId.toLower(), QString());
1510 * Get translation system id
1512 unsigned int lamexp_translation_sysid(const QString &langId)
1514 return g_lamexp_translation.sysid.value(langId.toLower(), 0);
1518 * Get translation script id
1520 unsigned int lamexp_translation_country(const QString &langId)
1522 return g_lamexp_translation.cntry.value(langId.toLower(), 0);
1526 * Install a new translator
1528 bool lamexp_install_translator(const QString &langId)
1530 bool success = false;
1532 if(langId.isEmpty() || langId.toLower().compare(LAMEXP_DEFAULT_LANGID) == 0)
1534 success = lamexp_install_translator_from_file(QString());
1538 QString qmFile = g_lamexp_translation.files.value(langId.toLower(), QString());
1539 if(!qmFile.isEmpty())
1541 success = lamexp_install_translator_from_file(QString(":/localization/%1").arg(qmFile));
1545 qWarning("Translation '%s' not available!", langId.toLatin1().constData());
1553 * Install a new translator from file
1555 bool lamexp_install_translator_from_file(const QString &qmFile)
1557 bool success = false;
1559 if(!g_lamexp_currentTranslator)
1561 g_lamexp_currentTranslator = new QTranslator();
1564 if(!qmFile.isEmpty())
1566 QString qmPath = QFileInfo(qmFile).canonicalFilePath();
1567 QApplication::removeTranslator(g_lamexp_currentTranslator);
1568 success = g_lamexp_currentTranslator->load(qmPath);
1569 QApplication::installTranslator(g_lamexp_currentTranslator);
1572 qWarning("Failed to load translation:\n\"%s\"", qmPath.toLatin1().constData());
1577 QApplication::removeTranslator(g_lamexp_currentTranslator);
1585 * Locate known folder on local system
1587 QString lamexp_known_folder(lamexp_known_folder_t folder_id)
1589 typedef HRESULT (WINAPI *SHGetKnownFolderPathFun)(__in const GUID &rfid, __in DWORD dwFlags, __in HANDLE hToken, __out PWSTR *ppszPath);
1590 typedef HRESULT (WINAPI *SHGetFolderPathFun)(__in HWND hwndOwner, __in int nFolder, __in HANDLE hToken, __in DWORD dwFlags, __out LPWSTR pszPath);
1592 static const int CSIDL_LOCAL_APPDATA = 0x001c;
1593 static const int CSIDL_PROGRAM_FILES = 0x0026;
1594 static const int CSIDL_SYSTEM_FOLDER = 0x0025;
1595 static const GUID GUID_LOCAL_APPDATA = {0xF1B32785,0x6FBA,0x4FCF,{0x9D,0x55,0x7B,0x8E,0x7F,0x15,0x70,0x91}};
1596 static const GUID GUID_LOCAL_APPDATA_LOW = {0xA520A1A4,0x1780,0x4FF6,{0xBD,0x18,0x16,0x73,0x43,0xC5,0xAF,0x16}};
1597 static const GUID GUID_PROGRAM_FILES = {0x905e63b6,0xc1bf,0x494e,{0xb2,0x9c,0x65,0xb7,0x32,0xd3,0xd2,0x1a}};
1598 static const GUID GUID_SYSTEM_FOLDER = {0x1AC14E77,0x02E7,0x4E5D,{0xB7,0x44,0x2E,0xB1,0xAE,0x51,0x98,0xB7}};
1600 static QLibrary *Kernel32Lib = NULL;
1601 static SHGetKnownFolderPathFun SHGetKnownFolderPathPtr = NULL;
1602 static SHGetFolderPathFun SHGetFolderPathPtr = NULL;
1604 if((!SHGetKnownFolderPathPtr) && (!SHGetFolderPathPtr))
1606 if(!Kernel32Lib) Kernel32Lib = new QLibrary("shell32.dll");
1607 SHGetKnownFolderPathPtr = (SHGetKnownFolderPathFun) Kernel32Lib->resolve("SHGetKnownFolderPath");
1608 SHGetFolderPathPtr = (SHGetFolderPathFun) Kernel32Lib->resolve("SHGetFolderPathW");
1611 int folderCSIDL = -1;
1612 GUID folderGUID = {0x0000,0x0000,0x0000,{0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00}};
1616 case lamexp_folder_localappdata:
1617 folderCSIDL = CSIDL_LOCAL_APPDATA;
1618 folderGUID = GUID_LOCAL_APPDATA;
1620 case lamexp_folder_programfiles:
1621 folderCSIDL = CSIDL_PROGRAM_FILES;
1622 folderGUID = GUID_PROGRAM_FILES;
1624 case lamexp_folder_systemfolder:
1625 folderCSIDL = CSIDL_SYSTEM_FOLDER;
1626 folderGUID = GUID_SYSTEM_FOLDER;
1635 if(SHGetKnownFolderPathPtr)
1638 if(SHGetKnownFolderPathPtr(folderGUID, 0x00008000, NULL, &path) == S_OK)
1640 //MessageBoxW(0, path, L"SHGetKnownFolderPath", MB_TOPMOST);
1641 QDir folderTemp = QDir(QDir::fromNativeSeparators(QString::fromUtf16(reinterpret_cast<const unsigned short*>(path))));
1642 if(!folderTemp.exists())
1644 folderTemp.mkpath(".");
1646 if(folderTemp.exists())
1648 folder = folderTemp.canonicalPath();
1650 CoTaskMemFree(path);
1653 else if(SHGetFolderPathPtr)
1655 WCHAR *path = new WCHAR[4096];
1656 if(SHGetFolderPathPtr(NULL, folderCSIDL, NULL, NULL, path) == S_OK)
1658 //MessageBoxW(0, path, L"SHGetFolderPathW", MB_TOPMOST);
1659 QDir folderTemp = QDir(QDir::fromNativeSeparators(QString::fromUtf16(reinterpret_cast<const unsigned short*>(path))));
1660 if(!folderTemp.exists())
1662 folderTemp.mkpath(".");
1664 if(folderTemp.exists())
1666 folder = folderTemp.canonicalPath();
1676 * Safely remove a file
1678 bool lamexp_remove_file(const QString &filename)
1680 if(!QFileInfo(filename).exists() || !QFileInfo(filename).isFile())
1686 if(!QFile::remove(filename))
1688 DWORD attributes = GetFileAttributesW(QWCHAR(filename));
1689 SetFileAttributesW(QWCHAR(filename), (attributes & (~FILE_ATTRIBUTE_READONLY)));
1690 if(!QFile::remove(filename))
1692 qWarning("Could not delete \"%s\"", filename.toLatin1().constData());
1708 * Check if visual themes are enabled (WinXP and later)
1710 bool lamexp_themes_enabled(void)
1712 typedef int (WINAPI *IsAppThemedFun)(void);
1714 bool isAppThemed = false;
1715 QLibrary uxTheme(QString("%1/UxTheme.dll").arg(lamexp_known_folder(lamexp_folder_systemfolder)));
1716 IsAppThemedFun IsAppThemedPtr = (IsAppThemedFun) uxTheme.resolve("IsAppThemed");
1720 isAppThemed = IsAppThemedPtr();
1723 qWarning("Theme support is disabled for this process!");
1731 * Get number of free bytes on disk
1733 unsigned __int64 lamexp_free_diskspace(const QString &path, bool *ok)
1735 ULARGE_INTEGER freeBytesAvailable, totalNumberOfBytes, totalNumberOfFreeBytes;
1736 if(GetDiskFreeSpaceExW(reinterpret_cast<const wchar_t*>(QDir::toNativeSeparators(path).utf16()), &freeBytesAvailable, &totalNumberOfBytes, &totalNumberOfFreeBytes))
1739 return freeBytesAvailable.QuadPart;
1749 * Check if computer does support hibernation
1751 bool lamexp_is_hibernation_supported(void)
1753 bool hibernationSupported = false;
1755 SYSTEM_POWER_CAPABILITIES pwrCaps;
1756 SecureZeroMemory(&pwrCaps, sizeof(SYSTEM_POWER_CAPABILITIES));
1758 if(GetPwrCapabilities(&pwrCaps))
1760 hibernationSupported = pwrCaps.SystemS4 && pwrCaps.HiberFilePresent;
1763 return hibernationSupported;
1767 * Shutdown the computer
1769 bool lamexp_shutdown_computer(const QString &message, const unsigned long timeout, const bool forceShutdown, const bool hibernate)
1771 HANDLE hToken = NULL;
1773 if(OpenProcessToken(GetCurrentProcess(), TOKEN_ADJUST_PRIVILEGES | TOKEN_QUERY, &hToken))
1775 TOKEN_PRIVILEGES privileges;
1776 memset(&privileges, 0, sizeof(TOKEN_PRIVILEGES));
1777 privileges.PrivilegeCount = 1;
1778 privileges.Privileges[0].Attributes = SE_PRIVILEGE_ENABLED;
1780 if(LookupPrivilegeValue(NULL, SE_SHUTDOWN_NAME, &privileges.Privileges[0].Luid))
1782 if(AdjustTokenPrivileges(hToken, FALSE, &privileges, NULL, NULL, NULL))
1786 if(SetSuspendState(TRUE, TRUE, TRUE))
1791 const DWORD reason = SHTDN_REASON_MAJOR_APPLICATION | SHTDN_REASON_FLAG_PLANNED;
1792 return InitiateSystemShutdownEx(NULL, const_cast<wchar_t*>(QWCHAR(message)), timeout, forceShutdown ? TRUE : FALSE, FALSE, reason);
1801 * Make a window blink (to draw user's attention)
1803 void lamexp_blink_window(QWidget *poWindow, unsigned int count, unsigned int delay)
1805 static QMutex blinkMutex;
1807 const double maxOpac = 1.0;
1808 const double minOpac = 0.3;
1809 const double delOpac = 0.1;
1811 if(!blinkMutex.tryLock())
1813 qWarning("Blinking is already in progress, skipping!");
1819 const int steps = static_cast<int>(ceil(maxOpac - minOpac) / delOpac);
1820 const int sleep = static_cast<int>(floor(static_cast<double>(delay) / static_cast<double>(steps)));
1821 const double opacity = poWindow->windowOpacity();
1823 for(unsigned int i = 0; i < count; i++)
1825 for(double x = maxOpac; x >= minOpac; x -= delOpac)
1827 poWindow->setWindowOpacity(x);
1828 QApplication::processEvents();
1832 for(double x = minOpac; x <= maxOpac; x += delOpac)
1834 poWindow->setWindowOpacity(x);
1835 QApplication::processEvents();
1840 poWindow->setWindowOpacity(opacity);
1841 QApplication::processEvents();
1842 blinkMutex.unlock();
1846 blinkMutex.unlock();
1847 qWarning("Exception error while blinking!");
1852 * Remove forbidden characters from a filename
1854 const QString lamexp_clean_filename(const QString &str)
1856 QString newStr(str);
1858 newStr.replace("\\", "-");
1859 newStr.replace(" / ", ", ");
1860 newStr.replace("/", ",");
1861 newStr.replace(":", "-");
1862 newStr.replace("*", "x");
1863 newStr.replace("?", "");
1864 newStr.replace("<", "[");
1865 newStr.replace(">", "]");
1866 newStr.replace("|", "!");
1868 return newStr.simplified();
1872 * Remove forbidden characters from a file path
1874 const QString lamexp_clean_filepath(const QString &str)
1876 QStringList parts = QString(str).replace("\\", "/").split("/");
1878 for(int i = 0; i < parts.count(); i++)
1880 parts[i] = lamexp_clean_filename(parts[i]);
1883 return parts.join("/");
1887 * Get a list of all available Qt Text Codecs
1889 QStringList lamexp_available_codepages(bool noAliases)
1891 QStringList codecList;
1893 QList<QByteArray> availableCodecs = QTextCodec::availableCodecs();
1894 while(!availableCodecs.isEmpty())
1896 QByteArray current = availableCodecs.takeFirst();
1897 if(!(current.startsWith("system") || current.startsWith("System")))
1899 codecList << QString::fromLatin1(current.constData(), current.size());
1902 if(QTextCodec *currentCodec = QTextCodec::codecForName(current.constData()))
1905 QList<QByteArray> aliases = currentCodec->aliases();
1906 while(!aliases.isEmpty()) availableCodecs.removeAll(aliases.takeFirst());
1916 * Finalization function (final clean-up)
1918 void lamexp_finalization(void)
1920 qDebug("lamexp_finalization()");
1923 if(!g_lamexp_tool_registry.isEmpty())
1925 QStringList keys = g_lamexp_tool_registry.keys();
1926 for(int i = 0; i < keys.count(); i++)
1928 LAMEXP_DELETE(g_lamexp_tool_registry[keys.at(i)]);
1930 g_lamexp_tool_registry.clear();
1931 g_lamexp_tool_versions.clear();
1934 //Delete temporary files
1935 if(!g_lamexp_temp_folder.isEmpty())
1937 for(int i = 0; i < 100; i++)
1939 if(lamexp_clean_folder(g_lamexp_temp_folder))
1945 g_lamexp_temp_folder.clear();
1949 if(g_lamexp_currentTranslator)
1951 QApplication::removeTranslator(g_lamexp_currentTranslator);
1952 LAMEXP_DELETE(g_lamexp_currentTranslator);
1954 g_lamexp_translation.files.clear();
1955 g_lamexp_translation.names.clear();
1957 //Destroy Qt application object
1958 QApplication *application = dynamic_cast<QApplication*>(QApplication::instance());
1959 LAMEXP_DELETE(application);
1961 //Detach from shared memory
1962 if(g_lamexp_ipc_ptr.sharedmem) g_lamexp_ipc_ptr.sharedmem->detach();
1963 LAMEXP_DELETE(g_lamexp_ipc_ptr.sharedmem);
1964 LAMEXP_DELETE(g_lamexp_ipc_ptr.semaphore_read);
1965 LAMEXP_DELETE(g_lamexp_ipc_ptr.semaphore_write);
1968 if(g_lamexp_log_file)
1970 fclose(g_lamexp_log_file);
1971 g_lamexp_log_file = NULL;
1976 * Initialize debug thread
1978 static const HANDLE g_debug_thread = LAMEXP_DEBUG ? NULL : lamexp_debug_thread_init();
1981 * Get number private bytes [debug only]
1983 SIZE_T lamexp_dbg_private_bytes(void)
1986 PROCESS_MEMORY_COUNTERS_EX memoryCounters;
1987 memoryCounters.cb = sizeof(PROCESS_MEMORY_COUNTERS_EX);
1988 GetProcessMemoryInfo(GetCurrentProcess(), (PPROCESS_MEMORY_COUNTERS) &memoryCounters, sizeof(PROCESS_MEMORY_COUNTERS_EX));
1989 return memoryCounters.PrivateUsage;
1991 throw "Cannot call this function in a non-debug build!";
1992 #endif //LAMEXP_DEBUG