Updated MediaInfo binary to v0.7.48 (2011-08-17), compiled with MSVC 10.0
[LameXP.git] / src / Global.cpp
blob522c3e89c56ee819afff29a8456e1d5792a08df4
1 ///////////////////////////////////////////////////////////////////////////////
2 // LameXP - Audio Encoder Front-End
3 // Copyright (C) 2004-2011 LoRd_MuldeR <MuldeR2@GMX.de>
4 //
5 // This program is free software; you can redistribute it and/or modify
6 // it under the terms of the GNU General Public License as published by
7 // the Free Software Foundation; either version 2 of the License, or
8 // (at your option) any later version.
9 //
10 // This program is distributed in the hope that it will be useful,
11 // but WITHOUT ANY WARRANTY; without even the implied warranty of
12 // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 // GNU General Public License for more details.
15 // You should have received a copy of the GNU General Public License along
16 // with this program; if not, write to the Free Software Foundation, Inc.,
17 // 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
19 // http://www.gnu.org/licenses/gpl-2.0.txt
20 ///////////////////////////////////////////////////////////////////////////////
22 #include "Global.h"
24 //Qt includes
25 #include <QApplication>
26 #include <QMessageBox>
27 #include <QDir>
28 #include <QUuid>
29 #include <QMap>
30 #include <QDate>
31 #include <QIcon>
32 #include <QPlastiqueStyle>
33 #include <QImageReader>
34 #include <QSharedMemory>
35 #include <QSysInfo>
36 #include <QStringList>
37 #include <QSystemSemaphore>
38 #include <QMutex>
39 #include <QTextCodec>
40 #include <QLibrary>
41 #include <QRegExp>
42 #include <QResource>
43 #include <QTranslator>
44 #include <QEventLoop>
45 #include <QTimer>
47 //LameXP includes
48 #include "Resource.h"
49 #include "LockedFile.h"
51 //CRT includes
52 #include <io.h>
53 #include <fcntl.h>
54 #include <intrin.h>
55 #include <math.h>
57 //COM includes
58 #include <Objbase.h>
60 //Debug only includes
61 #if LAMEXP_DEBUG
62 #include <Psapi.h>
63 #endif
65 //Initialize static Qt plugins
66 #ifdef QT_NODLL
67 Q_IMPORT_PLUGIN(qgif)
68 Q_IMPORT_PLUGIN(qico)
69 Q_IMPORT_PLUGIN(qsvg)
70 #endif
72 ///////////////////////////////////////////////////////////////////////////////
73 // TYPES
74 ///////////////////////////////////////////////////////////////////////////////
76 typedef struct
78 unsigned int command;
79 unsigned int reserved_1;
80 unsigned int reserved_2;
81 char parameter[4096];
82 } lamexp_ipc_t;
84 ///////////////////////////////////////////////////////////////////////////////
85 // GLOBAL VARS
86 ///////////////////////////////////////////////////////////////////////////////
88 //Build version
89 static const struct
91 unsigned int ver_major;
92 unsigned int ver_minor;
93 unsigned int ver_build;
94 char *ver_release_name;
96 g_lamexp_version =
98 VER_LAMEXP_MAJOR,
99 VER_LAMEXP_MINOR,
100 VER_LAMEXP_BUILD,
101 VER_LAMEXP_RNAME
104 //Build date
105 static QDate g_lamexp_version_date;
106 static const char *g_lamexp_months[] = {"Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"};
107 static const char *g_lamexp_version_raw_date = __DATE__;
108 static const char *g_lamexp_version_raw_time = __TIME__;
110 //Console attached flag
111 static bool g_lamexp_console_attached = false;
113 //Compiler detection
114 //The following code was borrowed from MPC-HC project: http://mpc-hc.sf.net/
115 #if defined(__INTEL_COMPILER)
116 #if (__INTEL_COMPILER >= 1200)
117 static const char *g_lamexp_version_compiler = "ICL 12.x";
118 #elif (__INTEL_COMPILER >= 1100)
119 static const char *g_lamexp_version_compiler = = "ICL 11.x";
120 #elif (__INTEL_COMPILER >= 1000)
121 static const char *g_lamexp_version_compiler = = "ICL 10.x";
122 #else
123 #error Compiler is not supported!
124 #endif
125 #elif defined(_MSC_VER)
126 #if (_MSC_VER == 1600)
127 #if (_MSC_FULL_VER >= 160040219)
128 static const char *g_lamexp_version_compiler = "MSVC 2010-SP1";
129 #else
130 static const char *g_lamexp_version_compiler = "MSVC 2010";
131 #endif
132 #elif (_MSC_VER == 1500)
133 #if (_MSC_FULL_VER >= 150030729)
134 static const char *g_lamexp_version_compiler = "MSVC 2008-SP1";
135 #else
136 static const char *g_lamexp_version_compiler = "MSVC 2008";
137 #endif
138 #else
139 #error Compiler is not supported!
140 #endif
142 // Note: /arch:SSE and /arch:SSE2 are only available for the x86 platform
143 #if !defined(_M_X64) && defined(_M_IX86_FP)
144 #if (_M_IX86_FP == 1)
145 LAMEXP_COMPILER_WARNING("SSE instruction set is enabled!")
146 #elif (_M_IX86_FP == 2)
147 LAMEXP_COMPILER_WARNING("SSE2 instruction set is enabled!")
148 #endif
149 #endif
150 #else
151 #error Compiler is not supported!
152 #endif
154 //Architecture detection
155 #if defined(_M_X64)
156 static const char *g_lamexp_version_arch = "x64";
157 #elif defined(_M_IX86)
158 static const char *g_lamexp_version_arch = "x86";
159 #else
160 #error Architecture is not supported!
161 #endif
163 //Official web-site URL
164 static const char *g_lamexp_website_url = "http://lamexp.sourceforge.net/";
165 static const char *g_lamexp_support_url = "http://forum.doom9.org/showthread.php?t=157726";
167 //Tool versions (expected)
168 static const unsigned int g_lamexp_toolver_neroaac = VER_LAMEXP_TOOL_NEROAAC;
170 //Special folders
171 static QString g_lamexp_temp_folder;
173 //Tools
174 static QMap<QString, LockedFile*> g_lamexp_tool_registry;
175 static QMap<QString, unsigned int> g_lamexp_tool_versions;
177 //Languages
178 static struct
180 QMap<QString, QString> files;
181 QMap<QString, QString> names;
182 QMap<QString, unsigned int> sysid;
184 g_lamexp_translation;
186 //Translator
187 static QTranslator *g_lamexp_currentTranslator = NULL;
189 //Shared memory
190 static const struct
192 char *sharedmem;
193 char *semaphore_read;
194 char *semaphore_write;
196 g_lamexp_ipc_uuid =
198 "{21A68A42-6923-43bb-9CF6-64BF151942EE}",
199 "{7A605549-F58C-4d78-B4E5-06EFC34F405B}",
200 "{60AA8D04-F6B8-497d-81EB-0F600F4A65B5}"
202 static struct
204 QSharedMemory *sharedmem;
205 QSystemSemaphore *semaphore_read;
206 QSystemSemaphore *semaphore_write;
208 g_lamexp_ipc_ptr =
210 NULL, NULL, NULL
213 //Image formats
214 static const char *g_lamexp_imageformats[] = {"png", "jpg", "gif", "ico", "svg", NULL};
216 //Global locks
217 static QMutex g_lamexp_message_mutex;
219 //Main thread ID
220 static const DWORD g_main_thread_id = GetCurrentThreadId();
223 ///////////////////////////////////////////////////////////////////////////////
224 // GLOBAL FUNCTIONS
225 ///////////////////////////////////////////////////////////////////////////////
228 * Version getters
230 unsigned int lamexp_version_major(void) { return g_lamexp_version.ver_major; }
231 unsigned int lamexp_version_minor(void) { return g_lamexp_version.ver_minor; }
232 unsigned int lamexp_version_build(void) { return g_lamexp_version.ver_build; }
233 const char *lamexp_version_release(void) { return g_lamexp_version.ver_release_name; }
234 const char *lamexp_version_time(void) { return g_lamexp_version_raw_time; }
235 const char *lamexp_version_compiler(void) { return g_lamexp_version_compiler; }
236 const char *lamexp_version_arch(void) { return g_lamexp_version_arch; }
237 unsigned int lamexp_toolver_neroaac(void) { return g_lamexp_toolver_neroaac; }
240 * URL getters
242 const char *lamexp_website_url(void) { return g_lamexp_website_url; }
243 const char *lamexp_support_url(void) { return g_lamexp_support_url; }
246 * Check for Demo (pre-release) version
248 bool lamexp_version_demo(void)
250 char buffer[128];
251 bool releaseVersion = false;
252 if(!strncpy_s(buffer, 128, g_lamexp_version.ver_release_name, _TRUNCATE))
254 char *context, *prefix = strtok_s(buffer, "-,; ", &context);
255 if(prefix)
257 releaseVersion = (!_stricmp(prefix, "Final")) || (!_stricmp(prefix, "Hotfix"));
260 return LAMEXP_DEBUG || (!releaseVersion);
264 * Calculate expiration date
266 QDate lamexp_version_expires(void)
268 return lamexp_version_date().addDays(LAMEXP_DEBUG ? 2 : 30);
272 * Get build date date
274 const QDate &lamexp_version_date(void)
276 if(!g_lamexp_version_date.isValid())
278 char temp[32];
279 int date[3];
281 char *this_token = NULL;
282 char *next_token = NULL;
284 strncpy_s(temp, 32, g_lamexp_version_raw_date, _TRUNCATE);
285 this_token = strtok_s(temp, " ", &next_token);
287 for(int i = 0; i < 3; i++)
289 date[i] = -1;
290 if(this_token)
292 for(int j = 0; j < 12; j++)
294 if(!_strcmpi(this_token, g_lamexp_months[j]))
296 date[i] = j+1;
297 break;
300 if(date[i] < 0)
302 date[i] = atoi(this_token);
304 this_token = strtok_s(NULL, " ", &next_token);
308 if(date[0] >= 0 && date[1] >= 0 && date[2] >= 0)
310 g_lamexp_version_date = QDate(date[2], date[0], date[1]);
314 return g_lamexp_version_date;
318 * Global exception handler
320 LONG WINAPI lamexp_exception_handler(__in struct _EXCEPTION_POINTERS *ExceptionInfo)
322 if(GetCurrentThreadId() != g_main_thread_id)
324 HANDLE mainThread = OpenThread(THREAD_TERMINATE, FALSE, g_main_thread_id);
325 if(mainThread) TerminateThread(mainThread, ULONG_MAX);
328 FatalAppExit(0, L"Unhandeled exception error, application will exit!");
329 TerminateProcess(GetCurrentProcess(), -1);
330 return LONG_MAX;
334 * Invalid parameters handler
336 void lamexp_invalid_param_handler(const wchar_t*, const wchar_t*, const wchar_t*, unsigned int, uintptr_t)
338 if(GetCurrentThreadId() != g_main_thread_id)
340 HANDLE mainThread = OpenThread(THREAD_TERMINATE, FALSE, g_main_thread_id);
341 if(mainThread) TerminateThread(mainThread, ULONG_MAX);
345 FatalAppExit(0, L"Invalid parameter handler invoked, application will exit!");
346 TerminateProcess(GetCurrentProcess(), -1);
350 * Change console text color
352 static void lamexp_console_color(FILE* file, WORD attributes)
354 const HANDLE hConsole = (HANDLE)(_get_osfhandle(_fileno(file)));
355 if((hConsole != NULL) && (hConsole != INVALID_HANDLE_VALUE))
357 SetConsoleTextAttribute(hConsole, attributes);
362 * Qt message handler
364 void lamexp_message_handler(QtMsgType type, const char *msg)
366 static const char *GURU_MEDITATION = "\n\nGURU MEDITATION !!!\n\n";
368 const char *text = msg;
369 const char *buffer = NULL;
371 QMutexLocker lock(&g_lamexp_message_mutex);
373 if((strlen(msg) > 8) && (_strnicmp(msg, "@BASE64@", 8) == 0))
375 buffer = _strdup(QByteArray::fromBase64(msg + 8).constData());
376 if(buffer) text = buffer;
379 if(g_lamexp_console_attached)
381 UINT oldOutputCP = GetConsoleOutputCP();
382 if(oldOutputCP != CP_UTF8) SetConsoleOutputCP(CP_UTF8);
384 switch(type)
386 case QtCriticalMsg:
387 case QtFatalMsg:
388 fflush(stdout);
389 fflush(stderr);
390 lamexp_console_color(stderr, FOREGROUND_RED | FOREGROUND_INTENSITY);
391 fprintf(stderr, GURU_MEDITATION);
392 fprintf(stderr, "%s\n", text);
393 fflush(stderr);
394 break;
395 case QtWarningMsg:
396 lamexp_console_color(stderr, FOREGROUND_GREEN | FOREGROUND_RED | FOREGROUND_INTENSITY);
397 fprintf(stderr, "%s\n", text);
398 fflush(stderr);
399 break;
400 default:
401 lamexp_console_color(stderr, FOREGROUND_BLUE | FOREGROUND_GREEN | FOREGROUND_RED | FOREGROUND_INTENSITY);
402 fprintf(stderr, "%s\n", text);
403 fflush(stderr);
404 break;
407 lamexp_console_color(stderr, FOREGROUND_BLUE | FOREGROUND_GREEN | FOREGROUND_RED);
408 if(oldOutputCP != CP_UTF8) SetConsoleOutputCP(oldOutputCP);
410 else
412 char temp[1024] = {'\0'};
414 switch(type)
416 case QtCriticalMsg:
417 case QtFatalMsg:
418 _snprintf_s(temp, 1024, _TRUNCATE, "[LameXP][C] %s", text);
419 break;
420 case QtWarningMsg:
421 _snprintf_s(temp, 1024, _TRUNCATE, "[LameXP][C] %s", text);
422 break;
423 default:
424 _snprintf_s(temp, 1024, _TRUNCATE, "[LameXP][C] %s", text);
425 break;
428 char *ptr = strchr(temp, '\n');
429 while(ptr != NULL)
431 *ptr = '\t';
432 ptr = strchr(temp, '\n');
435 strncat_s(temp, 1024, "\n", _TRUNCATE);
436 OutputDebugStringA(temp);
439 if(type == QtCriticalMsg || type == QtFatalMsg)
441 lock.unlock();
442 MessageBoxW(NULL, QWCHAR(QString::fromUtf8(text)), L"LameXP - GURU MEDITATION", MB_ICONERROR | MB_TOPMOST | MB_TASKMODAL);
443 FatalAppExit(0, L"The application has encountered a critical error and will exit now!");
444 TerminateProcess(GetCurrentProcess(), -1);
447 LAMEXP_SAFE_FREE(buffer);
451 * Initialize the console
453 void lamexp_init_console(int argc, char* argv[])
455 bool enableConsole = lamexp_version_demo();
457 if(!LAMEXP_DEBUG)
459 for(int i = 0; i < argc; i++)
461 if(!_stricmp(argv[i], "--console"))
463 enableConsole = true;
465 else if(!_stricmp(argv[i], "--no-console"))
467 enableConsole = false;
472 if(enableConsole)
474 if(!g_lamexp_console_attached)
476 if(AllocConsole() != FALSE)
478 SetConsoleCtrlHandler(NULL, TRUE);
479 SetConsoleTitle(L"LameXP - Audio Encoder Front-End | Debug Console");
480 SetConsoleOutputCP(CP_UTF8);
481 g_lamexp_console_attached = true;
485 if(g_lamexp_console_attached)
487 //-------------------------------------------------------------------
488 //See: http://support.microsoft.com/default.aspx?scid=kb;en-us;105305
489 //-------------------------------------------------------------------
490 const int flags = _O_WRONLY | _O_U8TEXT;
491 int hCrtStdOut = _open_osfhandle((intptr_t) GetStdHandle(STD_OUTPUT_HANDLE), flags);
492 int hCrtStdErr = _open_osfhandle((intptr_t) GetStdHandle(STD_ERROR_HANDLE), flags);
493 FILE *hfStdOut = _fdopen(hCrtStdOut, "w");
494 FILE *hfStderr = _fdopen(hCrtStdErr, "w");
495 if(hfStdOut) *stdout = *hfStdOut;
496 if(hfStderr) *stderr = *hfStderr;
499 HWND hwndConsole = GetConsoleWindow();
501 if((hwndConsole != NULL) && (hwndConsole != INVALID_HANDLE_VALUE))
503 HMENU hMenu = GetSystemMenu(hwndConsole, 0);
504 EnableMenuItem(hMenu, SC_CLOSE, MF_BYCOMMAND | MF_GRAYED);
505 RemoveMenu(hMenu, SC_CLOSE, MF_BYCOMMAND);
507 SetWindowLong(hwndConsole, GWL_STYLE, GetWindowLong(hwndConsole, GWL_STYLE) & (~WS_MAXIMIZEBOX));
508 SetWindowLong(hwndConsole, GWL_STYLE, GetWindowLong(hwndConsole, GWL_STYLE) & (~WS_MINIMIZEBOX));
514 * Detect CPU features
516 lamexp_cpu_t lamexp_detect_cpu_features(void)
518 typedef BOOL (WINAPI *IsWow64ProcessFun)(__in HANDLE hProcess, __out PBOOL Wow64Process);
519 typedef VOID (WINAPI *GetNativeSystemInfoFun)(__out LPSYSTEM_INFO lpSystemInfo);
521 static IsWow64ProcessFun IsWow64ProcessPtr = NULL;
522 static GetNativeSystemInfoFun GetNativeSystemInfoPtr = NULL;
524 lamexp_cpu_t features;
525 SYSTEM_INFO systemInfo;
526 int CPUInfo[4] = {-1};
527 char CPUIdentificationString[0x40];
528 char CPUBrandString[0x40];
530 memset(&features, 0, sizeof(lamexp_cpu_t));
531 memset(&systemInfo, 0, sizeof(SYSTEM_INFO));
532 memset(CPUIdentificationString, 0, sizeof(CPUIdentificationString));
533 memset(CPUBrandString, 0, sizeof(CPUBrandString));
535 __cpuid(CPUInfo, 0);
536 memcpy(CPUIdentificationString, &CPUInfo[1], sizeof(int));
537 memcpy(CPUIdentificationString + 4, &CPUInfo[3], sizeof(int));
538 memcpy(CPUIdentificationString + 8, &CPUInfo[2], sizeof(int));
539 features.intel = (_stricmp(CPUIdentificationString, "GenuineIntel") == 0);
540 strncpy_s(features.vendor, 0x40, CPUIdentificationString, _TRUNCATE);
542 if(CPUInfo[0] >= 1)
544 __cpuid(CPUInfo, 1);
545 features.mmx = (CPUInfo[3] & 0x800000) || false;
546 features.sse = (CPUInfo[3] & 0x2000000) || false;
547 features.sse2 = (CPUInfo[3] & 0x4000000) || false;
548 features.ssse3 = (CPUInfo[2] & 0x200) || false;
549 features.sse3 = (CPUInfo[2] & 0x1) || false;
550 features.ssse3 = (CPUInfo[2] & 0x200) || false;
551 features.stepping = CPUInfo[0] & 0xf;
552 features.model = ((CPUInfo[0] >> 4) & 0xf) + (((CPUInfo[0] >> 16) & 0xf) << 4);
553 features.family = ((CPUInfo[0] >> 8) & 0xf) + ((CPUInfo[0] >> 20) & 0xff);
556 __cpuid(CPUInfo, 0x80000000);
557 int nExIds = max(min(CPUInfo[0], 0x80000004), 0x80000000);
559 for(int i = 0x80000002; i <= nExIds; ++i)
561 __cpuid(CPUInfo, i);
562 switch(i)
564 case 0x80000002:
565 memcpy(CPUBrandString, CPUInfo, sizeof(CPUInfo));
566 break;
567 case 0x80000003:
568 memcpy(CPUBrandString + 16, CPUInfo, sizeof(CPUInfo));
569 break;
570 case 0x80000004:
571 memcpy(CPUBrandString + 32, CPUInfo, sizeof(CPUInfo));
572 break;
576 strncpy_s(features.brand, 0x40, CPUBrandString, _TRUNCATE);
578 if(strlen(features.brand) < 1) strncpy_s(features.brand, 0x40, "Unknown", _TRUNCATE);
579 if(strlen(features.vendor) < 1) strncpy_s(features.vendor, 0x40, "Unknown", _TRUNCATE);
581 #if !defined(_M_X64 ) && !defined(_M_IA64)
582 if(!IsWow64ProcessPtr || !GetNativeSystemInfoPtr)
584 QLibrary Kernel32Lib("kernel32.dll");
585 IsWow64ProcessPtr = (IsWow64ProcessFun) Kernel32Lib.resolve("IsWow64Process");
586 GetNativeSystemInfoPtr = (GetNativeSystemInfoFun) Kernel32Lib.resolve("GetNativeSystemInfo");
588 if(IsWow64ProcessPtr)
590 BOOL x64 = FALSE;
591 if(IsWow64ProcessPtr(GetCurrentProcess(), &x64))
593 features.x64 = x64;
596 if(GetNativeSystemInfoPtr)
598 GetNativeSystemInfoPtr(&systemInfo);
600 else
602 GetSystemInfo(&systemInfo);
604 features.count = systemInfo.dwNumberOfProcessors;
605 #else
606 GetNativeSystemInfo(&systemInfo);
607 features.count = systemInfo.dwNumberOfProcessors;
608 features.x64 = true;
609 #endif
611 return features;
615 * Check for debugger (detect routine)
617 static bool lamexp_check_for_debugger(void)
619 __try
621 DebugBreak();
623 __except(GetExceptionCode() == EXCEPTION_BREAKPOINT ? EXCEPTION_EXECUTE_HANDLER : EXCEPTION_CONTINUE_SEARCH)
625 return false;
627 return true;
631 * Check for debugger (thread proc)
633 static void WINAPI lamexp_debug_thread_proc(__in LPVOID lpParameter)
635 while(!(IsDebuggerPresent() || lamexp_check_for_debugger()))
637 Sleep(333);
639 TerminateProcess(GetCurrentProcess(), -1);
643 * Check for debugger (startup routine)
645 static HANDLE lamexp_debug_thread_init(void)
647 if(IsDebuggerPresent() || lamexp_check_for_debugger())
649 FatalAppExit(0, L"Not a debug build. Please unload debugger and try again!");
650 TerminateProcess(GetCurrentProcess(), -1);
653 return CreateThread(NULL, NULL, reinterpret_cast<LPTHREAD_START_ROUTINE>(&lamexp_debug_thread_proc), NULL, NULL, NULL);
657 * Check for compatibility mode
659 static bool lamexp_check_compatibility_mode(const char *exportName, const char *executableName)
661 QLibrary kernel32("kernel32.dll");
663 if(exportName != NULL)
665 if(kernel32.resolve(exportName) != NULL)
667 qWarning("Function '%s' exported from 'kernel32.dll' -> Windows compatibility mode!", exportName);
668 qFatal("%s", QApplication::tr("Executable '%1' doesn't support Windows compatibility mode.").arg(QString::fromLatin1(executableName)).toLatin1().constData());
669 return false;
673 return true;
677 * Check for process elevation
679 static bool lamexp_check_elevation(void)
681 typedef enum { lamexp_token_elevationType_class = 18, lamexp_token_elevation_class = 20 } LAMEXP_TOKEN_INFORMATION_CLASS;
682 typedef enum { lamexp_elevationType_default = 1, lamexp_elevationType_full, lamexp_elevationType_limited } LAMEXP_TOKEN_ELEVATION_TYPE;
684 HANDLE hToken = NULL;
685 bool bIsProcessElevated = false;
687 if(OpenProcessToken(GetCurrentProcess(), TOKEN_QUERY, &hToken))
689 LAMEXP_TOKEN_ELEVATION_TYPE tokenElevationType;
690 DWORD returnLength;
691 if(GetTokenInformation(hToken, (TOKEN_INFORMATION_CLASS) lamexp_token_elevationType_class, &tokenElevationType, sizeof(LAMEXP_TOKEN_ELEVATION_TYPE), &returnLength))
693 if(returnLength == sizeof(LAMEXP_TOKEN_ELEVATION_TYPE))
695 switch(tokenElevationType)
697 case lamexp_elevationType_default:
698 qDebug("Process token elevation type: Default -> UAC is disabled.\n");
699 break;
700 case lamexp_elevationType_full:
701 qWarning("Process token elevation type: Full -> potential security risk!\n");
702 bIsProcessElevated = true;
703 break;
704 case lamexp_elevationType_limited:
705 qDebug("Process token elevation type: Limited -> not elevated.\n");
706 break;
710 CloseHandle(hToken);
712 else
714 qWarning("Failed to open process token!");
717 return !bIsProcessElevated;
721 * Initialize Qt framework
723 bool lamexp_init_qt(int argc, char* argv[])
725 static bool qt_initialized = false;
726 bool isWine = false;
727 typedef BOOL (WINAPI *SetDllDirectoryProc)(WCHAR *lpPathName);
729 //Don't initialized again, if done already
730 if(qt_initialized)
732 return true;
735 //Secure DLL loading
736 QLibrary kernel32("kernel32.dll");
737 if(kernel32.load())
739 SetDllDirectoryProc pSetDllDirectory = (SetDllDirectoryProc) kernel32.resolve("SetDllDirectoryW");
740 if(pSetDllDirectory != NULL) pSetDllDirectory(L"");
741 kernel32.unload();
744 //Extract executable name from argv[] array
745 char *executableName = argv[0];
746 while(char *temp = strpbrk(executableName, "\\/:?"))
748 executableName = temp + 1;
751 //Check Qt version
752 qDebug("Using Qt Framework v%s, compiled with Qt v%s [%s]", qVersion(), QT_VERSION_STR, QT_PACKAGEDATE_STR);
753 if(_stricmp(qVersion(), QT_VERSION_STR))
755 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());
756 return false;
759 //Check the Windows version
760 switch(QSysInfo::windowsVersion() & QSysInfo::WV_NT_based)
762 case QSysInfo::WV_2000:
763 qDebug("Running on Windows 2000 (not officially supported!).\n");
764 lamexp_check_compatibility_mode("GetNativeSystemInfo", executableName);
765 break;
766 case QSysInfo::WV_XP:
767 qDebug("Running on Windows XP.\n");
768 lamexp_check_compatibility_mode("GetLargePageMinimum", executableName);
769 break;
770 case QSysInfo::WV_2003:
771 qDebug("Running on Windows Server 2003 or Windows XP x64-Edition.\n");
772 lamexp_check_compatibility_mode("GetLocaleInfoEx", executableName);
773 break;
774 case QSysInfo::WV_VISTA:
775 qDebug("Running on Windows Vista or Windows Server 2008.\n");
776 lamexp_check_compatibility_mode("CreateRemoteThreadEx", executableName);
777 break;
778 case QSysInfo::WV_WINDOWS7:
779 qDebug("Running on Windows 7 or Windows Server 2008 R2.\n");
780 lamexp_check_compatibility_mode(NULL, executableName);
781 break;
782 default:
783 qFatal("%s", QApplication::tr("Executable '%1' requires Windows 2000 or later.").arg(QString::fromLatin1(executableName)).toLatin1().constData());
784 break;
787 //Check for Wine
788 QLibrary ntdll("ntdll.dll");
789 if(ntdll.load())
791 if(ntdll.resolve("wine_nt_to_unix_file_name") != NULL) isWine = true;
792 if(ntdll.resolve("wine_get_version") != NULL) isWine = true;
793 if(isWine) qWarning("It appears we are running under Wine, unexpected things might happen!\n");
794 ntdll.unload();
797 //Create Qt application instance and setup version info
798 QDate date = QDate::currentDate();
799 QApplication *application = new QApplication(argc, argv);
800 application->setApplicationName("LameXP - Audio Encoder Front-End");
801 application->setApplicationVersion(QString().sprintf("%d.%02d.%04d", lamexp_version_major(), lamexp_version_minor(), lamexp_version_build()));
802 application->setOrganizationName("LoRd_MuldeR");
803 application->setOrganizationDomain("mulder.dummwiedeutsch.de");
804 application->setWindowIcon((date.month() == 12 && date.day() >= 24 && date.day() <= 26) ? QIcon(":/MainIcon2.png") : QIcon(":/MainIcon.png"));
806 //Load plugins from application directory
807 QCoreApplication::setLibraryPaths(QStringList() << QApplication::applicationDirPath());
808 qDebug("Library Path:\n%s\n", QApplication::libraryPaths().first().toUtf8().constData());
810 //Check for supported image formats
811 QList<QByteArray> supportedFormats = QImageReader::supportedImageFormats();
812 for(int i = 0; g_lamexp_imageformats[i]; i++)
814 if(!supportedFormats.contains(g_lamexp_imageformats[i]))
816 qFatal("Qt initialization error: QImageIOHandler for '%s' missing!", g_lamexp_imageformats[i]);
817 return false;
821 //Add default translations
822 g_lamexp_translation.files.insert(LAMEXP_DEFAULT_LANGID, "");
823 g_lamexp_translation.names.insert(LAMEXP_DEFAULT_LANGID, "English");
825 //Check for process elevation
826 if(!lamexp_check_elevation())
828 if(QMessageBox::warning(NULL, "LameXP", "<nobr>LameXP was started with elevated rights. This is a potential security risk!</nobr>", "Quit Program (Recommended)", "Ignore") == 0)
830 return false;
834 //Update console icon, if a console is attached
835 if(g_lamexp_console_attached && !isWine)
837 typedef DWORD (__stdcall *SetConsoleIconFun)(HICON);
838 QLibrary kernel32("kernel32.dll");
839 if(kernel32.load())
841 SetConsoleIconFun SetConsoleIconPtr = (SetConsoleIconFun) kernel32.resolve("SetConsoleIcon");
842 if(SetConsoleIconPtr != NULL) SetConsoleIconPtr(QIcon(":/icons/sound.png").pixmap(16, 16).toWinHICON());
843 kernel32.unload();
847 //Done
848 qt_initialized = true;
849 return true;
853 * Initialize IPC
855 int lamexp_init_ipc(void)
857 if(g_lamexp_ipc_ptr.sharedmem && g_lamexp_ipc_ptr.semaphore_read && g_lamexp_ipc_ptr.semaphore_write)
859 return 0;
862 g_lamexp_ipc_ptr.semaphore_read = new QSystemSemaphore(QString(g_lamexp_ipc_uuid.semaphore_read), 0);
863 g_lamexp_ipc_ptr.semaphore_write = new QSystemSemaphore(QString(g_lamexp_ipc_uuid.semaphore_write), 0);
865 if(g_lamexp_ipc_ptr.semaphore_read->error() != QSystemSemaphore::NoError)
867 QString errorMessage = g_lamexp_ipc_ptr.semaphore_read->errorString();
868 LAMEXP_DELETE(g_lamexp_ipc_ptr.semaphore_read);
869 LAMEXP_DELETE(g_lamexp_ipc_ptr.semaphore_write);
870 qFatal("Failed to create system smaphore: %s", errorMessage.toUtf8().constData());
871 return -1;
873 if(g_lamexp_ipc_ptr.semaphore_write->error() != QSystemSemaphore::NoError)
875 QString errorMessage = g_lamexp_ipc_ptr.semaphore_write->errorString();
876 LAMEXP_DELETE(g_lamexp_ipc_ptr.semaphore_read);
877 LAMEXP_DELETE(g_lamexp_ipc_ptr.semaphore_write);
878 qFatal("Failed to create system smaphore: %s", errorMessage.toUtf8().constData());
879 return -1;
882 g_lamexp_ipc_ptr.sharedmem = new QSharedMemory(QString(g_lamexp_ipc_uuid.sharedmem), NULL);
884 if(!g_lamexp_ipc_ptr.sharedmem->create(sizeof(lamexp_ipc_t)))
886 if(g_lamexp_ipc_ptr.sharedmem->error() == QSharedMemory::AlreadyExists)
888 g_lamexp_ipc_ptr.sharedmem->attach();
889 if(g_lamexp_ipc_ptr.sharedmem->error() == QSharedMemory::NoError)
891 return 1;
893 else
895 QString errorMessage = g_lamexp_ipc_ptr.sharedmem->errorString();
896 qFatal("Failed to attach to shared memory: %s", errorMessage.toUtf8().constData());
897 return -1;
900 else
902 QString errorMessage = g_lamexp_ipc_ptr.sharedmem->errorString();
903 qFatal("Failed to create shared memory: %s", errorMessage.toUtf8().constData());
904 return -1;
908 memset(g_lamexp_ipc_ptr.sharedmem->data(), 0, sizeof(lamexp_ipc_t));
909 g_lamexp_ipc_ptr.semaphore_write->release();
911 return 0;
915 * IPC send message
917 void lamexp_ipc_send(unsigned int command, const char* message)
919 if(!g_lamexp_ipc_ptr.sharedmem || !g_lamexp_ipc_ptr.semaphore_read || !g_lamexp_ipc_ptr.semaphore_write)
921 throw "Shared memory for IPC not initialized yet.";
924 lamexp_ipc_t *lamexp_ipc = new lamexp_ipc_t;
925 memset(lamexp_ipc, 0, sizeof(lamexp_ipc_t));
926 lamexp_ipc->command = command;
927 if(message)
929 strncpy_s(lamexp_ipc->parameter, 4096, message, _TRUNCATE);
932 if(g_lamexp_ipc_ptr.semaphore_write->acquire())
934 memcpy(g_lamexp_ipc_ptr.sharedmem->data(), lamexp_ipc, sizeof(lamexp_ipc_t));
935 g_lamexp_ipc_ptr.semaphore_read->release();
938 LAMEXP_DELETE(lamexp_ipc);
942 * IPC read message
944 void lamexp_ipc_read(unsigned int *command, char* message, size_t buffSize)
946 *command = 0;
947 message[0] = '\0';
949 if(!g_lamexp_ipc_ptr.sharedmem || !g_lamexp_ipc_ptr.semaphore_read || !g_lamexp_ipc_ptr.semaphore_write)
951 throw "Shared memory for IPC not initialized yet.";
954 lamexp_ipc_t *lamexp_ipc = new lamexp_ipc_t;
955 memset(lamexp_ipc, 0, sizeof(lamexp_ipc_t));
957 if(g_lamexp_ipc_ptr.semaphore_read->acquire())
959 memcpy(lamexp_ipc, g_lamexp_ipc_ptr.sharedmem->data(), sizeof(lamexp_ipc_t));
960 g_lamexp_ipc_ptr.semaphore_write->release();
962 if(!(lamexp_ipc->reserved_1 || lamexp_ipc->reserved_2))
964 *command = lamexp_ipc->command;
965 strncpy_s(message, buffSize, lamexp_ipc->parameter, _TRUNCATE);
967 else
969 qWarning("Malformed IPC message, will be ignored");
973 LAMEXP_DELETE(lamexp_ipc);
977 * Check for LameXP "portable" mode
979 bool lamexp_portable_mode(void)
981 QString baseName = QFileInfo(QApplication::applicationFilePath()).completeBaseName();
982 return baseName.contains("lamexp", Qt::CaseInsensitive) && baseName.contains("portable", Qt::CaseInsensitive);
986 * Get a random string
988 QString lamexp_rand_str(void)
990 QRegExp regExp("\\{(\\w+)-(\\w+)-(\\w+)-(\\w+)-(\\w+)\\}");
991 QString uuid = QUuid::createUuid().toString();
993 if(regExp.indexIn(uuid) >= 0)
995 return QString().append(regExp.cap(1)).append(regExp.cap(2)).append(regExp.cap(3)).append(regExp.cap(4)).append(regExp.cap(5));
998 throw "The RegExp didn't match on the UUID string. This shouldn't happen ;-)";
1002 * Get LameXP temp folder
1004 const QString &lamexp_temp_folder2(void)
1006 static const char *TEMP_STR = "Temp";
1007 const QString WRITE_TEST_DATA = lamexp_rand_str();
1008 const QString SUB_FOLDER = lamexp_rand_str();
1010 //Already initialized?
1011 if(!g_lamexp_temp_folder.isEmpty())
1013 if(QDir(g_lamexp_temp_folder).exists())
1015 return g_lamexp_temp_folder;
1017 else
1019 g_lamexp_temp_folder.clear();
1023 //Try the %TMP% or %TEMP% directory first
1024 QDir temp = QDir::temp();
1025 if(temp.exists())
1027 temp.mkdir(SUB_FOLDER);
1028 if(temp.cd(SUB_FOLDER) && temp.exists())
1030 QFile testFile(QString("%1/~%2.tmp").arg(temp.canonicalPath(), lamexp_rand_str()));
1031 if(testFile.open(QIODevice::ReadWrite))
1033 if(testFile.write(WRITE_TEST_DATA.toLatin1().constData()) >= strlen(WRITE_TEST_DATA.toLatin1().constData()))
1035 g_lamexp_temp_folder = temp.canonicalPath();
1037 testFile.remove();
1040 if(!g_lamexp_temp_folder.isEmpty())
1042 return g_lamexp_temp_folder;
1046 //Create TEMP folder in %LOCALAPPDATA%
1047 QDir localAppData = QDir(lamexp_known_folder(lamexp_folder_localappdata));
1048 if(!localAppData.path().isEmpty())
1050 if(!localAppData.exists())
1052 localAppData.mkpath(".");
1054 if(localAppData.exists())
1056 if(!localAppData.entryList(QDir::AllDirs).contains(TEMP_STR, Qt::CaseInsensitive))
1058 localAppData.mkdir(TEMP_STR);
1060 if(localAppData.cd(TEMP_STR) && localAppData.exists())
1062 localAppData.mkdir(SUB_FOLDER);
1063 if(localAppData.cd(SUB_FOLDER) && localAppData.exists())
1065 QFile testFile(QString("%1/~%2.tmp").arg(localAppData.canonicalPath(), lamexp_rand_str()));
1066 if(testFile.open(QIODevice::ReadWrite))
1068 if(testFile.write(WRITE_TEST_DATA.toLatin1().constData()) >= strlen(WRITE_TEST_DATA.toLatin1().constData()))
1070 g_lamexp_temp_folder = localAppData.canonicalPath();
1072 testFile.remove();
1077 if(!g_lamexp_temp_folder.isEmpty())
1079 return g_lamexp_temp_folder;
1083 //Failed to create TEMP folder!
1084 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());
1085 return g_lamexp_temp_folder;
1089 * Clean folder
1091 bool lamexp_clean_folder(const QString &folderPath)
1093 QDir tempFolder(folderPath);
1094 QFileInfoList entryList = tempFolder.entryInfoList(QDir::AllEntries | QDir::NoDotAndDotDot);
1096 for(int i = 0; i < entryList.count(); i++)
1098 if(entryList.at(i).isDir())
1100 lamexp_clean_folder(entryList.at(i).canonicalFilePath());
1102 else
1104 for(int j = 0; j < 3; j++)
1106 if(lamexp_remove_file(entryList.at(i).canonicalFilePath()))
1108 break;
1114 tempFolder.rmdir(".");
1115 return !tempFolder.exists();
1119 * Register tool
1121 void lamexp_register_tool(const QString &toolName, LockedFile *file, unsigned int version)
1123 if(g_lamexp_tool_registry.contains(toolName.toLower()))
1125 throw "lamexp_register_tool: Tool is already registered!";
1128 g_lamexp_tool_registry.insert(toolName.toLower(), file);
1129 g_lamexp_tool_versions.insert(toolName.toLower(), version);
1133 * Check for tool
1135 bool lamexp_check_tool(const QString &toolName)
1137 return g_lamexp_tool_registry.contains(toolName.toLower());
1141 * Lookup tool path
1143 const QString lamexp_lookup_tool(const QString &toolName)
1145 if(g_lamexp_tool_registry.contains(toolName.toLower()))
1147 return g_lamexp_tool_registry.value(toolName.toLower())->filePath();
1149 else
1151 return QString();
1156 * Lookup tool version
1158 unsigned int lamexp_tool_version(const QString &toolName)
1160 if(g_lamexp_tool_versions.contains(toolName.toLower()))
1162 return g_lamexp_tool_versions.value(toolName.toLower());
1164 else
1166 return UINT_MAX;
1171 * Version number to human-readable string
1173 const QString lamexp_version2string(const QString &pattern, unsigned int version, const QString &defaultText)
1175 if(version == UINT_MAX)
1177 return defaultText;
1180 QString result = pattern;
1181 int digits = result.count("?", Qt::CaseInsensitive);
1183 if(digits < 1)
1185 return result;
1188 int pos = 0;
1189 QString versionStr = QString().sprintf(QString().sprintf("%%0%du", digits).toLatin1().constData(), version);
1190 int index = result.indexOf("?", Qt::CaseInsensitive);
1192 while(index >= 0 && pos < versionStr.length())
1194 result[index] = versionStr[pos++];
1195 index = result.indexOf("?", Qt::CaseInsensitive);
1198 return result;
1202 * Register a new translation
1204 bool lamexp_translation_register(const QString &langId, const QString &qmFile, const QString &langName, unsigned int &systemId)
1206 if(qmFile.isEmpty() || langName.isEmpty() || systemId < 1)
1208 return false;
1211 g_lamexp_translation.files.insert(langId, qmFile);
1212 g_lamexp_translation.names.insert(langId, langName);
1213 g_lamexp_translation.sysid.insert(langId, systemId);
1215 return true;
1219 * Get list of all translations
1221 QStringList lamexp_query_translations(void)
1223 return g_lamexp_translation.files.keys();
1227 * Get translation name
1229 QString lamexp_translation_name(const QString &langId)
1231 return g_lamexp_translation.names.value(langId.toLower(), QString());
1235 * Get translation system id
1237 unsigned int lamexp_translation_sysid(const QString &langId)
1239 return g_lamexp_translation.sysid.value(langId.toLower(), 0);
1243 * Install a new translator
1245 bool lamexp_install_translator(const QString &langId)
1247 bool success = false;
1249 if(langId.isEmpty() || langId.toLower().compare(LAMEXP_DEFAULT_LANGID) == 0)
1251 success = lamexp_install_translator_from_file(QString());
1253 else
1255 QString qmFile = g_lamexp_translation.files.value(langId.toLower(), QString());
1256 if(!qmFile.isEmpty())
1258 success = lamexp_install_translator_from_file(QString(":/localization/%1").arg(qmFile));
1260 else
1262 qWarning("Translation '%s' not available!", langId.toLatin1().constData());
1266 return success;
1270 * Install a new translator from file
1272 bool lamexp_install_translator_from_file(const QString &qmFile)
1274 bool success = false;
1276 if(!g_lamexp_currentTranslator)
1278 g_lamexp_currentTranslator = new QTranslator();
1281 if(!qmFile.isEmpty())
1283 QString qmPath = QFileInfo(qmFile).canonicalFilePath();
1284 QApplication::removeTranslator(g_lamexp_currentTranslator);
1285 success = g_lamexp_currentTranslator->load(qmPath);
1286 QApplication::installTranslator(g_lamexp_currentTranslator);
1287 if(!success)
1289 qWarning("Failed to load translation:\n\"%s\"", qmPath.toLatin1().constData());
1292 else
1294 QApplication::removeTranslator(g_lamexp_currentTranslator);
1295 success = true;
1298 return success;
1302 * Locate known folder on local system
1304 QString lamexp_known_folder(lamexp_known_folder_t folder_id)
1306 typedef HRESULT (WINAPI *SHGetKnownFolderPathFun)(__in const GUID &rfid, __in DWORD dwFlags, __in HANDLE hToken, __out PWSTR *ppszPath);
1307 typedef HRESULT (WINAPI *SHGetFolderPathFun)(__in HWND hwndOwner, __in int nFolder, __in HANDLE hToken, __in DWORD dwFlags, __out LPWSTR pszPath);
1309 static const int CSIDL_LOCAL_APPDATA = 0x001c;
1310 static const int CSIDL_PROGRAM_FILES = 0x0026;
1311 static const int CSIDL_SYSTEM_FOLDER = 0x0025;
1312 static const GUID GUID_LOCAL_APPDATA = {0xF1B32785,0x6FBA,0x4FCF,{0x9D,0x55,0x7B,0x8E,0x7F,0x15,0x70,0x91}};
1313 static const GUID GUID_LOCAL_APPDATA_LOW = {0xA520A1A4,0x1780,0x4FF6,{0xBD,0x18,0x16,0x73,0x43,0xC5,0xAF,0x16}};
1314 static const GUID GUID_PROGRAM_FILES = {0x905e63b6,0xc1bf,0x494e,{0xb2,0x9c,0x65,0xb7,0x32,0xd3,0xd2,0x1a}};
1315 static const GUID GUID_SYSTEM_FOLDER = {0x1AC14E77,0x02E7,0x4E5D,{0xB7,0x44,0x2E,0xB1,0xAE,0x51,0x98,0xB7}};
1317 static QLibrary *Kernel32Lib = NULL;
1318 static SHGetKnownFolderPathFun SHGetKnownFolderPathPtr = NULL;
1319 static SHGetFolderPathFun SHGetFolderPathPtr = NULL;
1321 if((!SHGetKnownFolderPathPtr) && (!SHGetFolderPathPtr))
1323 if(!Kernel32Lib) Kernel32Lib = new QLibrary("shell32.dll");
1324 SHGetKnownFolderPathPtr = (SHGetKnownFolderPathFun) Kernel32Lib->resolve("SHGetKnownFolderPath");
1325 SHGetFolderPathPtr = (SHGetFolderPathFun) Kernel32Lib->resolve("SHGetFolderPathW");
1328 int folderCSIDL = -1;
1329 GUID folderGUID = {0x0000,0x0000,0x0000,{0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00}};
1331 switch(folder_id)
1333 case lamexp_folder_localappdata:
1334 folderCSIDL = CSIDL_LOCAL_APPDATA;
1335 folderGUID = GUID_LOCAL_APPDATA;
1336 break;
1337 case lamexp_folder_programfiles:
1338 folderCSIDL = CSIDL_PROGRAM_FILES;
1339 folderGUID = GUID_PROGRAM_FILES;
1340 break;
1341 case lamexp_folder_systemfolder:
1342 folderCSIDL = CSIDL_SYSTEM_FOLDER;
1343 folderGUID = GUID_SYSTEM_FOLDER;
1344 break;
1345 default:
1346 return QString();
1347 break;
1350 QString folder;
1352 if(SHGetKnownFolderPathPtr)
1354 WCHAR *path = NULL;
1355 if(SHGetKnownFolderPathPtr(folderGUID, 0x00008000, NULL, &path) == S_OK)
1357 //MessageBoxW(0, path, L"SHGetKnownFolderPath", MB_TOPMOST);
1358 QDir folderTemp = QDir(QDir::fromNativeSeparators(QString::fromUtf16(reinterpret_cast<const unsigned short*>(path))));
1359 if(!folderTemp.exists())
1361 folderTemp.mkpath(".");
1363 if(folderTemp.exists())
1365 folder = folderTemp.canonicalPath();
1367 CoTaskMemFree(path);
1370 else if(SHGetFolderPathPtr)
1372 WCHAR *path = new WCHAR[4096];
1373 if(SHGetFolderPathPtr(NULL, folderCSIDL, NULL, NULL, path) == S_OK)
1375 //MessageBoxW(0, path, L"SHGetFolderPathW", MB_TOPMOST);
1376 QDir folderTemp = QDir(QDir::fromNativeSeparators(QString::fromUtf16(reinterpret_cast<const unsigned short*>(path))));
1377 if(!folderTemp.exists())
1379 folderTemp.mkpath(".");
1381 if(folderTemp.exists())
1383 folder = folderTemp.canonicalPath();
1386 delete [] path;
1389 return folder;
1393 * Safely remove a file
1395 bool lamexp_remove_file(const QString &filename)
1397 if(!QFileInfo(filename).exists() || !QFileInfo(filename).isFile())
1399 return true;
1401 else
1403 if(!QFile::remove(filename))
1405 DWORD attributes = GetFileAttributesW(QWCHAR(filename));
1406 SetFileAttributesW(QWCHAR(filename), (attributes & (~FILE_ATTRIBUTE_READONLY)));
1407 if(!QFile::remove(filename))
1409 qWarning("Could not delete \"%s\"", filename.toLatin1().constData());
1410 return false;
1412 else
1414 return true;
1417 else
1419 return true;
1425 * Check if visual themes are enabled (WinXP and later)
1427 bool lamexp_themes_enabled(void)
1429 typedef int (WINAPI *IsAppThemedFun)(void);
1431 bool isAppThemed = false;
1432 QLibrary uxTheme(QString("%1/UxTheme.dll").arg(lamexp_known_folder(lamexp_folder_systemfolder)));
1433 IsAppThemedFun IsAppThemedPtr = (IsAppThemedFun) uxTheme.resolve("IsAppThemed");
1435 if(IsAppThemedPtr)
1437 isAppThemed = IsAppThemedPtr();
1438 if(!isAppThemed)
1440 qWarning("Theme support is disabled for this process!");
1444 return isAppThemed;
1448 * Get number of free bytes on disk
1450 __int64 lamexp_free_diskspace(const QString &path)
1452 ULARGE_INTEGER freeBytesAvailable, totalNumberOfBytes, totalNumberOfFreeBytes;
1453 if(GetDiskFreeSpaceExW(reinterpret_cast<const wchar_t*>(QDir::toNativeSeparators(path).utf16()), &freeBytesAvailable, &totalNumberOfBytes, &totalNumberOfFreeBytes))
1455 return freeBytesAvailable.QuadPart;
1457 else
1459 return 0;
1464 * Shutdown the computer
1466 bool lamexp_shutdown_computer(const QString &message, const unsigned long timeout, const bool forceShutdown)
1468 HANDLE hToken = NULL;
1470 if(OpenProcessToken(GetCurrentProcess(), TOKEN_ADJUST_PRIVILEGES | TOKEN_QUERY, &hToken))
1472 TOKEN_PRIVILEGES privileges;
1473 memset(&privileges, 0, sizeof(TOKEN_PRIVILEGES));
1474 privileges.PrivilegeCount = 1;
1475 privileges.Privileges[0].Attributes = SE_PRIVILEGE_ENABLED;
1477 if(LookupPrivilegeValue(NULL, SE_SHUTDOWN_NAME, &privileges.Privileges[0].Luid))
1479 if(AdjustTokenPrivileges(hToken, FALSE, &privileges, NULL, NULL, NULL))
1481 const DWORD reason = SHTDN_REASON_MAJOR_APPLICATION | SHTDN_REASON_FLAG_PLANNED;
1482 return InitiateSystemShutdownEx(NULL, const_cast<wchar_t*>(QWCHAR(message)), timeout, forceShutdown, FALSE, reason);
1487 return false;
1491 * Make a window blink (to draw user's attention)
1493 void lamexp_blink_window(QWidget *poWindow, unsigned int count, unsigned int delay)
1495 static QMutex blinkMutex;
1497 const double maxOpac = 1.0;
1498 const double minOpac = 0.3;
1499 const double delOpac = 0.1;
1501 if(!blinkMutex.tryLock())
1503 qWarning("Blinking is already in progress, skipping!");
1504 return;
1509 const int steps = static_cast<int>(ceil(maxOpac - minOpac) / delOpac);
1510 const int sleep = static_cast<int>(floor(static_cast<double>(delay) / static_cast<double>(steps)));
1511 const double opacity = poWindow->windowOpacity();
1513 for(unsigned int i = 0; i < count; i++)
1515 for(double x = maxOpac; x >= minOpac; x -= delOpac)
1517 poWindow->setWindowOpacity(x);
1518 QApplication::processEvents();
1519 Sleep(sleep);
1522 for(double x = minOpac; x <= maxOpac; x += delOpac)
1524 poWindow->setWindowOpacity(x);
1525 QApplication::processEvents();
1526 Sleep(sleep);
1530 poWindow->setWindowOpacity(opacity);
1531 QApplication::processEvents();
1532 blinkMutex.unlock();
1534 catch (...)
1536 blinkMutex.unlock();
1537 qWarning("Exception error while blinking!");
1542 * Remove forbidden characters from a filename
1544 const QString lamexp_clean_filename(const QString &str)
1546 QString newStr(str);
1547 newStr.replace("\\", "-");
1548 newStr.replace(" / ", ", ");
1549 newStr.replace("/", ",");
1550 newStr.replace(":", "-");
1551 newStr.replace("*", "x");
1552 newStr.replace("?", "");
1553 newStr.replace("<", "[");
1554 newStr.replace(">", "]");
1555 newStr.replace("|", "!");
1556 return newStr;
1560 * Remove forbidden characters from a file path
1562 const QString lamexp_clean_filepath(const QString &str)
1564 QStringList parts = QString(str).replace("\\", "/").split("/");
1566 for(int i = 0; i < parts.count(); i++)
1568 parts[i] = lamexp_clean_filename(parts[i]);
1571 return parts.join("/");
1575 * Finalization function (final clean-up)
1577 void lamexp_finalization(void)
1579 //Free all tools
1580 if(!g_lamexp_tool_registry.isEmpty())
1582 QStringList keys = g_lamexp_tool_registry.keys();
1583 for(int i = 0; i < keys.count(); i++)
1585 LAMEXP_DELETE(g_lamexp_tool_registry[keys.at(i)]);
1587 g_lamexp_tool_registry.clear();
1588 g_lamexp_tool_versions.clear();
1591 //Delete temporary files
1592 if(!g_lamexp_temp_folder.isEmpty())
1594 for(int i = 0; i < 100; i++)
1596 if(lamexp_clean_folder(g_lamexp_temp_folder))
1598 break;
1600 Sleep(125);
1602 g_lamexp_temp_folder.clear();
1605 //Clear languages
1606 if(g_lamexp_currentTranslator)
1608 QApplication::removeTranslator(g_lamexp_currentTranslator);
1609 LAMEXP_DELETE(g_lamexp_currentTranslator);
1611 g_lamexp_translation.files.clear();
1612 g_lamexp_translation.names.clear();
1614 //Destroy Qt application object
1615 QApplication *application = dynamic_cast<QApplication*>(QApplication::instance());
1616 LAMEXP_DELETE(application);
1618 //Detach from shared memory
1619 if(g_lamexp_ipc_ptr.sharedmem) g_lamexp_ipc_ptr.sharedmem->detach();
1620 LAMEXP_DELETE(g_lamexp_ipc_ptr.sharedmem);
1621 LAMEXP_DELETE(g_lamexp_ipc_ptr.semaphore_read);
1622 LAMEXP_DELETE(g_lamexp_ipc_ptr.semaphore_write);
1626 * Initialize debug thread
1628 static const HANDLE g_debug_thread = LAMEXP_DEBUG ? NULL : lamexp_debug_thread_init();
1631 * Get number private bytes [debug only]
1633 SIZE_T lamexp_dbg_private_bytes(void)
1635 #if LAMEXP_DEBUG
1636 PROCESS_MEMORY_COUNTERS_EX memoryCounters;
1637 memoryCounters.cb = sizeof(PROCESS_MEMORY_COUNTERS_EX);
1638 GetProcessMemoryInfo(GetCurrentProcess(), (PPROCESS_MEMORY_COUNTERS) &memoryCounters, sizeof(PROCESS_MEMORY_COUNTERS_EX));
1639 return memoryCounters.PrivateUsage;
1640 #else
1641 throw "Cannot call this function in a non-debug build!";
1642 #endif //LAMEXP_DEBUG