More reliable method to detect QAAC and make sure the required CoreAudioToolbox libra...
[LameXP.git] / src / Global.cpp
blob35b66144f9e81959d633d624e8a25e3e383d06e8
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 <iostream>
53 #include <fstream>
54 #include <io.h>
55 #include <fcntl.h>
56 #include <intrin.h>
57 #include <math.h>
59 //COM includes
60 #include <Objbase.h>
61 #include <PowrProf.h>
63 //Debug only includes
64 #if LAMEXP_DEBUG
65 #include <Psapi.h>
66 #endif
68 //Initialize static Qt plugins
69 #ifdef QT_NODLL
70 Q_IMPORT_PLUGIN(qico)
71 Q_IMPORT_PLUGIN(qsvg)
72 #endif
74 ///////////////////////////////////////////////////////////////////////////////
75 // TYPES
76 ///////////////////////////////////////////////////////////////////////////////
78 typedef struct
80 unsigned int command;
81 unsigned int reserved_1;
82 unsigned int reserved_2;
83 char parameter[4096];
84 } lamexp_ipc_t;
86 ///////////////////////////////////////////////////////////////////////////////
87 // GLOBAL VARS
88 ///////////////////////////////////////////////////////////////////////////////
90 //Build version
91 static const struct
93 unsigned int ver_major;
94 unsigned int ver_minor;
95 unsigned int ver_build;
96 char *ver_release_name;
98 g_lamexp_version =
100 VER_LAMEXP_MAJOR,
101 VER_LAMEXP_MINOR,
102 VER_LAMEXP_BUILD,
103 VER_LAMEXP_RNAME
106 //Build date
107 static QDate g_lamexp_version_date;
108 static const char *g_lamexp_months[] = {"Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"};
109 static const char *g_lamexp_version_raw_date = __DATE__;
110 static const char *g_lamexp_version_raw_time = __TIME__;
112 //Console attached flag
113 static bool g_lamexp_console_attached = false;
115 //Compiler detection
116 //The following code was borrowed from MPC-HC project: http://mpc-hc.sf.net/
117 #if defined(__INTEL_COMPILER)
118 #if (__INTEL_COMPILER >= 1200)
119 static const char *g_lamexp_version_compiler = "ICL 12.x";
120 #elif (__INTEL_COMPILER >= 1100)
121 static const char *g_lamexp_version_compiler = = "ICL 11.x";
122 #elif (__INTEL_COMPILER >= 1000)
123 static const char *g_lamexp_version_compiler = = "ICL 10.x";
124 #else
125 #error Compiler is not supported!
126 #endif
127 #elif defined(_MSC_VER)
128 #if (_MSC_VER == 1600)
129 #if (_MSC_FULL_VER >= 160040219)
130 static const char *g_lamexp_version_compiler = "MSVC 2010-SP1";
131 #else
132 static const char *g_lamexp_version_compiler = "MSVC 2010";
133 #endif
134 #elif (_MSC_VER == 1500)
135 #if (_MSC_FULL_VER >= 150030729)
136 static const char *g_lamexp_version_compiler = "MSVC 2008-SP1";
137 #else
138 static const char *g_lamexp_version_compiler = "MSVC 2008";
139 #endif
140 #else
141 #error Compiler is not supported!
142 #endif
144 // Note: /arch:SSE and /arch:SSE2 are only available for the x86 platform
145 #if !defined(_M_X64) && defined(_M_IX86_FP)
146 #if (_M_IX86_FP == 1)
147 LAMEXP_COMPILER_WARNING("SSE instruction set is enabled!")
148 #elif (_M_IX86_FP == 2)
149 LAMEXP_COMPILER_WARNING("SSE2 instruction set is enabled!")
150 #endif
151 #endif
152 #else
153 #error Compiler is not supported!
154 #endif
156 //Architecture detection
157 #if defined(_M_X64)
158 static const char *g_lamexp_version_arch = "x64";
159 #elif defined(_M_IX86)
160 static const char *g_lamexp_version_arch = "x86";
161 #else
162 #error Architecture is not supported!
163 #endif
165 //Official web-site URL
166 static const char *g_lamexp_website_url = "http://lamexp.sourceforge.net/";
167 static const char *g_lamexp_support_url = "http://forum.doom9.org/showthread.php?t=157726";
169 //Tool versions (expected versions!)
170 static const unsigned int g_lamexp_toolver_neroaac = VER_LAMEXP_TOOL_NEROAAC;
171 static const unsigned int g_lamexp_toolver_fhgaacenc = VER_LAMEXP_TOOL_FHGAACENC;
172 static const unsigned int g_lamexp_toolver_qaacenc = VER_LAMEXP_TOOL_QAAC;
173 static const unsigned int g_lamexp_toolver_coreaudio = VER_LAMEXP_TOOL_COREAUDIO;
175 //Special folders
176 static QString g_lamexp_temp_folder;
178 //Tools
179 static QMap<QString, LockedFile*> g_lamexp_tool_registry;
180 static QMap<QString, unsigned int> g_lamexp_tool_versions;
182 //Languages
183 static struct
185 QMap<QString, QString> files;
186 QMap<QString, QString> names;
187 QMap<QString, unsigned int> sysid;
189 g_lamexp_translation;
191 //Translator
192 static QTranslator *g_lamexp_currentTranslator = NULL;
194 //Shared memory
195 static const struct
197 char *sharedmem;
198 char *semaphore_read;
199 char *semaphore_write;
201 g_lamexp_ipc_uuid =
203 "{21A68A42-6923-43bb-9CF6-64BF151942EE}",
204 "{7A605549-F58C-4d78-B4E5-06EFC34F405B}",
205 "{60AA8D04-F6B8-497d-81EB-0F600F4A65B5}"
207 static struct
209 QSharedMemory *sharedmem;
210 QSystemSemaphore *semaphore_read;
211 QSystemSemaphore *semaphore_write;
213 g_lamexp_ipc_ptr =
215 NULL, NULL, NULL
218 //Image formats
219 static const char *g_lamexp_imageformats[] = {"png", "jpg", "gif", "ico", "svg", NULL};
221 //Global locks
222 static QMutex g_lamexp_message_mutex;
224 //Main thread ID
225 static const DWORD g_main_thread_id = GetCurrentThreadId();
228 ///////////////////////////////////////////////////////////////////////////////
229 // GLOBAL FUNCTIONS
230 ///////////////////////////////////////////////////////////////////////////////
233 * Version getters
235 unsigned int lamexp_version_major(void) { return g_lamexp_version.ver_major; }
236 unsigned int lamexp_version_minor(void) { return g_lamexp_version.ver_minor; }
237 unsigned int lamexp_version_build(void) { return g_lamexp_version.ver_build; }
238 const char *lamexp_version_release(void) { return g_lamexp_version.ver_release_name; }
239 const char *lamexp_version_time(void) { return g_lamexp_version_raw_time; }
240 const char *lamexp_version_compiler(void) { return g_lamexp_version_compiler; }
241 const char *lamexp_version_arch(void) { return g_lamexp_version_arch; }
242 unsigned int lamexp_toolver_neroaac(void) { return g_lamexp_toolver_neroaac; }
243 unsigned int lamexp_toolver_fhgaacenc(void) { return g_lamexp_toolver_fhgaacenc; }
244 unsigned int lamexp_toolver_qaacenc(void) { return g_lamexp_toolver_qaacenc; }
245 unsigned int lamexp_toolver_coreaudio(void) { return g_lamexp_toolver_coreaudio; }
248 * URL getters
250 const char *lamexp_website_url(void) { return g_lamexp_website_url; }
251 const char *lamexp_support_url(void) { return g_lamexp_support_url; }
254 * Check for Demo (pre-release) version
256 bool lamexp_version_demo(void)
258 char buffer[128];
259 bool releaseVersion = false;
260 if(!strncpy_s(buffer, 128, g_lamexp_version.ver_release_name, _TRUNCATE))
262 char *context, *prefix = strtok_s(buffer, "-,; ", &context);
263 if(prefix)
265 releaseVersion = (!_stricmp(prefix, "Final")) || (!_stricmp(prefix, "Hotfix"));
268 return LAMEXP_DEBUG || (!releaseVersion);
272 * Calculate expiration date
274 QDate lamexp_version_expires(void)
276 return lamexp_version_date().addDays(LAMEXP_DEBUG ? 2 : 30);
280 * Get build date date
282 const QDate &lamexp_version_date(void)
284 if(!g_lamexp_version_date.isValid())
286 char temp[32];
287 int date[3];
289 char *this_token = NULL;
290 char *next_token = NULL;
292 strncpy_s(temp, 32, g_lamexp_version_raw_date, _TRUNCATE);
293 this_token = strtok_s(temp, " ", &next_token);
295 for(int i = 0; i < 3; i++)
297 date[i] = -1;
298 if(this_token)
300 for(int j = 0; j < 12; j++)
302 if(!_strcmpi(this_token, g_lamexp_months[j]))
304 date[i] = j+1;
305 break;
308 if(date[i] < 0)
310 date[i] = atoi(this_token);
312 this_token = strtok_s(NULL, " ", &next_token);
316 if(date[0] >= 0 && date[1] >= 0 && date[2] >= 0)
318 g_lamexp_version_date = QDate(date[2], date[0], date[1]);
322 return g_lamexp_version_date;
326 * Get the native operating system version
328 DWORD lamexp_get_os_version(void)
330 OSVERSIONINFO osVerInfo;
331 memset(&osVerInfo, 0, sizeof(OSVERSIONINFO));
332 osVerInfo.dwOSVersionInfoSize = sizeof(OSVERSIONINFO);
333 DWORD version = 0;
335 if(GetVersionEx(&osVerInfo) == TRUE)
337 if(osVerInfo.dwPlatformId != VER_PLATFORM_WIN32_NT)
339 throw "Ouuups: Not running under Windows NT. This is not supposed to happen!";
341 version = (DWORD)((osVerInfo.dwMajorVersion << 16) | (osVerInfo.dwMinorVersion & 0xffff));
344 return version;
348 * Global exception handler
350 LONG WINAPI lamexp_exception_handler(__in struct _EXCEPTION_POINTERS *ExceptionInfo)
352 if(GetCurrentThreadId() != g_main_thread_id)
354 HANDLE mainThread = OpenThread(THREAD_TERMINATE, FALSE, g_main_thread_id);
355 if(mainThread) TerminateThread(mainThread, ULONG_MAX);
358 FatalAppExit(0, L"Unhandeled exception handler invoked, application will exit!");
359 TerminateProcess(GetCurrentProcess(), -1);
360 return LONG_MAX;
364 * Invalid parameters handler
366 void lamexp_invalid_param_handler(const wchar_t*, const wchar_t*, const wchar_t*, unsigned int, uintptr_t)
368 if(GetCurrentThreadId() != g_main_thread_id)
370 HANDLE mainThread = OpenThread(THREAD_TERMINATE, FALSE, g_main_thread_id);
371 if(mainThread) TerminateThread(mainThread, ULONG_MAX);
375 FatalAppExit(0, L"Invalid parameter handler invoked, application will exit!");
376 TerminateProcess(GetCurrentProcess(), -1);
380 * Change console text color
382 static void lamexp_console_color(FILE* file, WORD attributes)
384 const HANDLE hConsole = (HANDLE)(_get_osfhandle(_fileno(file)));
385 if((hConsole != NULL) && (hConsole != INVALID_HANDLE_VALUE))
387 SetConsoleTextAttribute(hConsole, attributes);
392 * Qt message handler
394 void lamexp_message_handler(QtMsgType type, const char *msg)
396 static const char *GURU_MEDITATION = "\n\nGURU MEDITATION !!!\n\n";
398 QMutexLocker lock(&g_lamexp_message_mutex);
400 //if((strlen(msg) > 8) && (_strnicmp(msg, "@BASE64@", 8) == 0))
402 // buffer = _strdup(QByteArray::fromBase64(msg + 8).constData());
403 // if(buffer) text = buffer;
406 if(g_lamexp_console_attached)
408 UINT oldOutputCP = GetConsoleOutputCP();
409 if(oldOutputCP != CP_UTF8) SetConsoleOutputCP(CP_UTF8);
411 switch(type)
413 case QtCriticalMsg:
414 case QtFatalMsg:
415 fflush(stdout);
416 fflush(stderr);
417 lamexp_console_color(stderr, FOREGROUND_RED | FOREGROUND_INTENSITY);
418 fprintf(stderr, GURU_MEDITATION);
419 fprintf(stderr, "%s\n", msg);
420 fflush(stderr);
421 break;
422 case QtWarningMsg:
423 lamexp_console_color(stderr, FOREGROUND_GREEN | FOREGROUND_RED | FOREGROUND_INTENSITY);
424 fprintf(stderr, "%s\n", msg);
425 fflush(stderr);
426 break;
427 default:
428 lamexp_console_color(stderr, FOREGROUND_BLUE | FOREGROUND_GREEN | FOREGROUND_RED | FOREGROUND_INTENSITY);
429 fprintf(stderr, "%s\n", msg);
430 fflush(stderr);
431 break;
434 lamexp_console_color(stderr, FOREGROUND_BLUE | FOREGROUND_GREEN | FOREGROUND_RED);
435 if(oldOutputCP != CP_UTF8) SetConsoleOutputCP(oldOutputCP);
437 else
439 QString temp("[LameXP][%1] %2");
441 switch(type)
443 case QtCriticalMsg:
444 case QtFatalMsg:
445 temp = temp.arg("C", QString::fromUtf8(msg));
446 break;
447 case QtWarningMsg:
448 temp = temp.arg("W", QString::fromUtf8(msg));
449 break;
450 default:
451 temp = temp.arg("I", QString::fromUtf8(msg));
452 break;
455 temp.replace("\n", "\t").append("\n");
456 OutputDebugStringA(temp.toLatin1().constData());
459 if(type == QtCriticalMsg || type == QtFatalMsg)
461 lock.unlock();
462 MessageBoxW(NULL, QWCHAR(QString::fromUtf8(msg)), L"LameXP - GURU MEDITATION", MB_ICONERROR | MB_TOPMOST | MB_TASKMODAL);
463 FatalAppExit(0, L"The application has encountered a critical error and will exit now!");
464 TerminateProcess(GetCurrentProcess(), -1);
469 * Initialize the console
471 void lamexp_init_console(int argc, char* argv[])
473 bool enableConsole = lamexp_version_demo();
475 if(!LAMEXP_DEBUG)
477 for(int i = 0; i < argc; i++)
479 if(!_stricmp(argv[i], "--console"))
481 enableConsole = true;
483 else if(!_stricmp(argv[i], "--no-console"))
485 enableConsole = false;
490 if(enableConsole)
492 if(!g_lamexp_console_attached)
494 if(AllocConsole() != FALSE)
496 SetConsoleCtrlHandler(NULL, TRUE);
497 SetConsoleTitle(L"LameXP - Audio Encoder Front-End | Debug Console");
498 SetConsoleOutputCP(CP_UTF8);
499 g_lamexp_console_attached = true;
503 if(g_lamexp_console_attached)
505 //-------------------------------------------------------------------
506 //See: http://support.microsoft.com/default.aspx?scid=kb;en-us;105305
507 //-------------------------------------------------------------------
508 const int flags = _O_WRONLY | _O_U8TEXT;
509 int hCrtStdOut = _open_osfhandle((intptr_t) GetStdHandle(STD_OUTPUT_HANDLE), flags);
510 int hCrtStdErr = _open_osfhandle((intptr_t) GetStdHandle(STD_ERROR_HANDLE), flags);
511 FILE *hfStdOut = (hCrtStdOut >= 0) ? _fdopen(hCrtStdOut, "wb") : NULL;
512 FILE *hfStdErr = (hCrtStdErr >= 0) ? _fdopen(hCrtStdErr, "wb") : NULL;
513 if(hfStdOut) { *stdout = *hfStdOut; std::cout.rdbuf(new std::filebuf(hfStdOut)); }
514 if(hfStdErr) { *stderr = *hfStdErr; std::cerr.rdbuf(new std::filebuf(hfStdErr)); }
517 HWND hwndConsole = GetConsoleWindow();
519 if((hwndConsole != NULL) && (hwndConsole != INVALID_HANDLE_VALUE))
521 HMENU hMenu = GetSystemMenu(hwndConsole, 0);
522 EnableMenuItem(hMenu, SC_CLOSE, MF_BYCOMMAND | MF_GRAYED);
523 RemoveMenu(hMenu, SC_CLOSE, MF_BYCOMMAND);
525 SetWindowPos(hwndConsole, HWND_TOP, 0, 0, 0, 0, SWP_NOMOVE|SWP_NOSIZE|SWP_NOZORDER|SWP_FRAMECHANGED);
526 SetWindowLong(hwndConsole, GWL_STYLE, GetWindowLong(hwndConsole, GWL_STYLE) & (~WS_MAXIMIZEBOX) & (~WS_MINIMIZEBOX));
527 SetWindowPos(hwndConsole, HWND_TOP, 0, 0, 0, 0, SWP_NOMOVE|SWP_NOSIZE|SWP_NOZORDER|SWP_FRAMECHANGED);
533 * Detect CPU features
535 lamexp_cpu_t lamexp_detect_cpu_features(int argc, char **argv)
537 typedef BOOL (WINAPI *IsWow64ProcessFun)(__in HANDLE hProcess, __out PBOOL Wow64Process);
538 typedef VOID (WINAPI *GetNativeSystemInfoFun)(__out LPSYSTEM_INFO lpSystemInfo);
540 static IsWow64ProcessFun IsWow64ProcessPtr = NULL;
541 static GetNativeSystemInfoFun GetNativeSystemInfoPtr = NULL;
543 lamexp_cpu_t features;
544 SYSTEM_INFO systemInfo;
545 int CPUInfo[4] = {-1};
546 char CPUIdentificationString[0x40];
547 char CPUBrandString[0x40];
549 memset(&features, 0, sizeof(lamexp_cpu_t));
550 memset(&systemInfo, 0, sizeof(SYSTEM_INFO));
551 memset(CPUIdentificationString, 0, sizeof(CPUIdentificationString));
552 memset(CPUBrandString, 0, sizeof(CPUBrandString));
554 __cpuid(CPUInfo, 0);
555 memcpy(CPUIdentificationString, &CPUInfo[1], sizeof(int));
556 memcpy(CPUIdentificationString + 4, &CPUInfo[3], sizeof(int));
557 memcpy(CPUIdentificationString + 8, &CPUInfo[2], sizeof(int));
558 features.intel = (_stricmp(CPUIdentificationString, "GenuineIntel") == 0);
559 strncpy_s(features.vendor, 0x40, CPUIdentificationString, _TRUNCATE);
561 if(CPUInfo[0] >= 1)
563 __cpuid(CPUInfo, 1);
564 features.mmx = (CPUInfo[3] & 0x800000) || false;
565 features.sse = (CPUInfo[3] & 0x2000000) || false;
566 features.sse2 = (CPUInfo[3] & 0x4000000) || false;
567 features.ssse3 = (CPUInfo[2] & 0x200) || false;
568 features.sse3 = (CPUInfo[2] & 0x1) || false;
569 features.ssse3 = (CPUInfo[2] & 0x200) || false;
570 features.stepping = CPUInfo[0] & 0xf;
571 features.model = ((CPUInfo[0] >> 4) & 0xf) + (((CPUInfo[0] >> 16) & 0xf) << 4);
572 features.family = ((CPUInfo[0] >> 8) & 0xf) + ((CPUInfo[0] >> 20) & 0xff);
575 __cpuid(CPUInfo, 0x80000000);
576 int nExIds = qMax<int>(qMin<int>(CPUInfo[0], 0x80000004), 0x80000000);
578 for(int i = 0x80000002; i <= nExIds; ++i)
580 __cpuid(CPUInfo, i);
581 switch(i)
583 case 0x80000002:
584 memcpy(CPUBrandString, CPUInfo, sizeof(CPUInfo));
585 break;
586 case 0x80000003:
587 memcpy(CPUBrandString + 16, CPUInfo, sizeof(CPUInfo));
588 break;
589 case 0x80000004:
590 memcpy(CPUBrandString + 32, CPUInfo, sizeof(CPUInfo));
591 break;
595 strncpy_s(features.brand, 0x40, CPUBrandString, _TRUNCATE);
597 if(strlen(features.brand) < 1) strncpy_s(features.brand, 0x40, "Unknown", _TRUNCATE);
598 if(strlen(features.vendor) < 1) strncpy_s(features.vendor, 0x40, "Unknown", _TRUNCATE);
600 #if !defined(_M_X64 ) && !defined(_M_IA64)
601 if(!IsWow64ProcessPtr || !GetNativeSystemInfoPtr)
603 QLibrary Kernel32Lib("kernel32.dll");
604 IsWow64ProcessPtr = (IsWow64ProcessFun) Kernel32Lib.resolve("IsWow64Process");
605 GetNativeSystemInfoPtr = (GetNativeSystemInfoFun) Kernel32Lib.resolve("GetNativeSystemInfo");
607 if(IsWow64ProcessPtr)
609 BOOL x64 = FALSE;
610 if(IsWow64ProcessPtr(GetCurrentProcess(), &x64))
612 features.x64 = x64;
615 if(GetNativeSystemInfoPtr)
617 GetNativeSystemInfoPtr(&systemInfo);
619 else
621 GetSystemInfo(&systemInfo);
623 features.count = qBound(1UL, systemInfo.dwNumberOfProcessors, 64UL);
624 #else
625 GetNativeSystemInfo(&systemInfo);
626 features.count = systemInfo.dwNumberOfProcessors;
627 features.x64 = true;
628 #endif
630 if((argv != NULL) && (argc > 0))
632 bool flag = false;
633 for(int i = 0; i < argc; i++)
635 if(!_stricmp("--force-cpu-no-64bit", argv[i])) { flag = true; features.x64 = false; }
636 if(!_stricmp("--force-cpu-no-sse", argv[i])) { flag = true; features.sse = features.sse2 = features.sse3 = features.ssse3 = false; }
637 if(!_stricmp("--force-cpu-no-intel", argv[i])) { flag = true; features.intel = false; }
639 if(flag) qWarning("CPU flags overwritten by user-defined parameters. Take care!\n");
642 return features;
646 * Check for debugger (detect routine)
648 static bool lamexp_check_for_debugger(void)
650 __try
652 DebugBreak();
654 __except(GetExceptionCode() == EXCEPTION_BREAKPOINT ? EXCEPTION_EXECUTE_HANDLER : EXCEPTION_CONTINUE_SEARCH)
656 return false;
658 return true;
662 * Check for debugger (thread proc)
664 static void WINAPI lamexp_debug_thread_proc(__in LPVOID lpParameter)
666 while(!(IsDebuggerPresent() || lamexp_check_for_debugger()))
668 Sleep(333);
670 TerminateProcess(GetCurrentProcess(), -1);
674 * Check for debugger (startup routine)
676 static HANDLE lamexp_debug_thread_init(void)
678 if(IsDebuggerPresent() || lamexp_check_for_debugger())
680 FatalAppExit(0, L"Not a debug build. Please unload debugger and try again!");
681 TerminateProcess(GetCurrentProcess(), -1);
684 return CreateThread(NULL, NULL, reinterpret_cast<LPTHREAD_START_ROUTINE>(&lamexp_debug_thread_proc), NULL, NULL, NULL);
688 * Check for compatibility mode
690 static bool lamexp_check_compatibility_mode(const char *exportName, const char *executableName)
692 QLibrary kernel32("kernel32.dll");
694 if(exportName != NULL)
696 if(kernel32.resolve(exportName) != NULL)
698 qWarning("Function '%s' exported from 'kernel32.dll' -> Windows compatibility mode!", exportName);
699 qFatal("%s", QApplication::tr("Executable '%1' doesn't support Windows compatibility mode.").arg(QString::fromLatin1(executableName)).toLatin1().constData());
700 return false;
704 return true;
708 * Check for process elevation
710 static bool lamexp_check_elevation(void)
712 typedef enum { lamexp_token_elevationType_class = 18, lamexp_token_elevation_class = 20 } LAMEXP_TOKEN_INFORMATION_CLASS;
713 typedef enum { lamexp_elevationType_default = 1, lamexp_elevationType_full, lamexp_elevationType_limited } LAMEXP_TOKEN_ELEVATION_TYPE;
715 HANDLE hToken = NULL;
716 bool bIsProcessElevated = false;
718 if(OpenProcessToken(GetCurrentProcess(), TOKEN_QUERY, &hToken))
720 LAMEXP_TOKEN_ELEVATION_TYPE tokenElevationType;
721 DWORD returnLength;
722 if(GetTokenInformation(hToken, (TOKEN_INFORMATION_CLASS) lamexp_token_elevationType_class, &tokenElevationType, sizeof(LAMEXP_TOKEN_ELEVATION_TYPE), &returnLength))
724 if(returnLength == sizeof(LAMEXP_TOKEN_ELEVATION_TYPE))
726 switch(tokenElevationType)
728 case lamexp_elevationType_default:
729 qDebug("Process token elevation type: Default -> UAC is disabled.\n");
730 break;
731 case lamexp_elevationType_full:
732 qWarning("Process token elevation type: Full -> potential security risk!\n");
733 bIsProcessElevated = true;
734 break;
735 case lamexp_elevationType_limited:
736 qDebug("Process token elevation type: Limited -> not elevated.\n");
737 break;
741 CloseHandle(hToken);
743 else
745 qWarning("Failed to open process token!");
748 return !bIsProcessElevated;
752 * Initialize Qt framework
754 bool lamexp_init_qt(int argc, char* argv[])
756 static bool qt_initialized = false;
757 bool isWine = false;
758 typedef BOOL (WINAPI *SetDllDirectoryProc)(WCHAR *lpPathName);
760 //Don't initialized again, if done already
761 if(qt_initialized)
763 return true;
766 //Secure DLL loading
767 QLibrary kernel32("kernel32.dll");
768 if(kernel32.load())
770 SetDllDirectoryProc pSetDllDirectory = (SetDllDirectoryProc) kernel32.resolve("SetDllDirectoryW");
771 if(pSetDllDirectory != NULL) pSetDllDirectory(L"");
772 kernel32.unload();
775 //Extract executable name from argv[] array
776 char *executableName = argv[0];
777 while(char *temp = strpbrk(executableName, "\\/:?"))
779 executableName = temp + 1;
782 //Check Qt version
783 qDebug("Using Qt Framework v%s (%s), compiled with Qt v%s [%s]", qVersion(), (qSharedBuild() ? "DLL" : "Static"), QT_VERSION_STR, QT_PACKAGEDATE_STR);
784 if(_stricmp(qVersion(), QT_VERSION_STR))
786 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());
787 return false;
790 //Check the Windows version
791 switch(QSysInfo::windowsVersion() & QSysInfo::WV_NT_based)
793 case 0:
794 case QSysInfo::WV_NT:
795 qFatal("%s", QApplication::tr("Executable '%1' requires Windows 2000 or later.").arg(QString::fromLatin1(executableName)).toLatin1().constData());
796 break;
797 case QSysInfo::WV_2000:
798 qDebug("Running on Windows 2000 (not officially supported!).\n");
799 lamexp_check_compatibility_mode("GetNativeSystemInfo", executableName);
800 break;
801 case QSysInfo::WV_XP:
802 qDebug("Running on Windows XP.\n");
803 lamexp_check_compatibility_mode("GetLargePageMinimum", executableName);
804 break;
805 case QSysInfo::WV_2003:
806 qDebug("Running on Windows Server 2003 or Windows XP x64-Edition.\n");
807 lamexp_check_compatibility_mode("GetLocaleInfoEx", executableName);
808 break;
809 case QSysInfo::WV_VISTA:
810 qDebug("Running on Windows Vista or Windows Server 2008.\n");
811 lamexp_check_compatibility_mode("CreateRemoteThreadEx", executableName);
812 break;
813 case QSysInfo::WV_WINDOWS7:
814 qDebug("Running on Windows 7 or Windows Server 2008 R2.\n");
815 lamexp_check_compatibility_mode(NULL, executableName);
816 break;
817 default:
819 DWORD osVersionNo = lamexp_get_os_version();
820 qWarning("Running on an unknown/untested WinNT-based OS (v%u.%u).\n", HIWORD(osVersionNo), LOWORD(osVersionNo));
822 break;
825 //Check for Wine
826 QLibrary ntdll("ntdll.dll");
827 if(ntdll.load())
829 if(ntdll.resolve("wine_nt_to_unix_file_name") != NULL) isWine = true;
830 if(ntdll.resolve("wine_get_version") != NULL) isWine = true;
831 if(isWine) qWarning("It appears we are running under Wine, unexpected things might happen!\n");
832 ntdll.unload();
835 //Create Qt application instance and setup version info
836 QDate date = QDate::currentDate();
837 QApplication *application = new QApplication(argc, argv);
838 application->setApplicationName("LameXP - Audio Encoder Front-End");
839 application->setApplicationVersion(QString().sprintf("%d.%02d.%04d", lamexp_version_major(), lamexp_version_minor(), lamexp_version_build()));
840 application->setOrganizationName("LoRd_MuldeR");
841 application->setOrganizationDomain("mulder.at.gg");
842 application->setWindowIcon((date.month() == 12 && date.day() >= 24 && date.day() <= 26) ? QIcon(":/MainIcon2.png") : QIcon(":/MainIcon.png"));
844 //Set text Codec for locale
845 QTextCodec::setCodecForLocale(QTextCodec::codecForName("UTF-8"));
847 //Load plugins from application directory
848 QCoreApplication::setLibraryPaths(QStringList() << QApplication::applicationDirPath());
849 qDebug("Library Path:\n%s\n", QApplication::libraryPaths().first().toUtf8().constData());
851 //Check for supported image formats
852 QList<QByteArray> supportedFormats = QImageReader::supportedImageFormats();
853 for(int i = 0; g_lamexp_imageformats[i]; i++)
855 if(!supportedFormats.contains(g_lamexp_imageformats[i]))
857 qFatal("Qt initialization error: QImageIOHandler for '%s' missing!", g_lamexp_imageformats[i]);
858 return false;
862 //Add default translations
863 g_lamexp_translation.files.insert(LAMEXP_DEFAULT_LANGID, "");
864 g_lamexp_translation.names.insert(LAMEXP_DEFAULT_LANGID, "English");
866 //Check for process elevation
867 if(!lamexp_check_elevation())
869 if(QMessageBox::warning(NULL, "LameXP", "<nobr>LameXP was started with elevated rights. This is a potential security risk!</nobr>", "Quit Program (Recommended)", "Ignore") == 0)
871 return false;
875 //Update console icon, if a console is attached
876 if(g_lamexp_console_attached && !isWine)
878 typedef DWORD (__stdcall *SetConsoleIconFun)(HICON);
879 QLibrary kernel32("kernel32.dll");
880 if(kernel32.load())
882 SetConsoleIconFun SetConsoleIconPtr = (SetConsoleIconFun) kernel32.resolve("SetConsoleIcon");
883 if(SetConsoleIconPtr != NULL) SetConsoleIconPtr(QIcon(":/icons/sound.png").pixmap(16, 16).toWinHICON());
884 kernel32.unload();
888 //Done
889 qt_initialized = true;
890 return true;
894 * Initialize IPC
896 int lamexp_init_ipc(void)
898 if(g_lamexp_ipc_ptr.sharedmem && g_lamexp_ipc_ptr.semaphore_read && g_lamexp_ipc_ptr.semaphore_write)
900 return 0;
903 g_lamexp_ipc_ptr.semaphore_read = new QSystemSemaphore(QString(g_lamexp_ipc_uuid.semaphore_read), 0);
904 g_lamexp_ipc_ptr.semaphore_write = new QSystemSemaphore(QString(g_lamexp_ipc_uuid.semaphore_write), 0);
906 if(g_lamexp_ipc_ptr.semaphore_read->error() != QSystemSemaphore::NoError)
908 QString errorMessage = g_lamexp_ipc_ptr.semaphore_read->errorString();
909 LAMEXP_DELETE(g_lamexp_ipc_ptr.semaphore_read);
910 LAMEXP_DELETE(g_lamexp_ipc_ptr.semaphore_write);
911 qFatal("Failed to create system smaphore: %s", errorMessage.toUtf8().constData());
912 return -1;
914 if(g_lamexp_ipc_ptr.semaphore_write->error() != QSystemSemaphore::NoError)
916 QString errorMessage = g_lamexp_ipc_ptr.semaphore_write->errorString();
917 LAMEXP_DELETE(g_lamexp_ipc_ptr.semaphore_read);
918 LAMEXP_DELETE(g_lamexp_ipc_ptr.semaphore_write);
919 qFatal("Failed to create system smaphore: %s", errorMessage.toUtf8().constData());
920 return -1;
923 g_lamexp_ipc_ptr.sharedmem = new QSharedMemory(QString(g_lamexp_ipc_uuid.sharedmem), NULL);
925 if(!g_lamexp_ipc_ptr.sharedmem->create(sizeof(lamexp_ipc_t)))
927 if(g_lamexp_ipc_ptr.sharedmem->error() == QSharedMemory::AlreadyExists)
929 g_lamexp_ipc_ptr.sharedmem->attach();
930 if(g_lamexp_ipc_ptr.sharedmem->error() == QSharedMemory::NoError)
932 return 1;
934 else
936 QString errorMessage = g_lamexp_ipc_ptr.sharedmem->errorString();
937 qFatal("Failed to attach to shared memory: %s", errorMessage.toUtf8().constData());
938 return -1;
941 else
943 QString errorMessage = g_lamexp_ipc_ptr.sharedmem->errorString();
944 qFatal("Failed to create shared memory: %s", errorMessage.toUtf8().constData());
945 return -1;
949 memset(g_lamexp_ipc_ptr.sharedmem->data(), 0, sizeof(lamexp_ipc_t));
950 g_lamexp_ipc_ptr.semaphore_write->release();
952 return 0;
956 * IPC send message
958 void lamexp_ipc_send(unsigned int command, const char* message)
960 if(!g_lamexp_ipc_ptr.sharedmem || !g_lamexp_ipc_ptr.semaphore_read || !g_lamexp_ipc_ptr.semaphore_write)
962 throw "Shared memory for IPC not initialized yet.";
965 lamexp_ipc_t *lamexp_ipc = new lamexp_ipc_t;
966 memset(lamexp_ipc, 0, sizeof(lamexp_ipc_t));
967 lamexp_ipc->command = command;
968 if(message)
970 strncpy_s(lamexp_ipc->parameter, 4096, message, _TRUNCATE);
973 if(g_lamexp_ipc_ptr.semaphore_write->acquire())
975 memcpy(g_lamexp_ipc_ptr.sharedmem->data(), lamexp_ipc, sizeof(lamexp_ipc_t));
976 g_lamexp_ipc_ptr.semaphore_read->release();
979 LAMEXP_DELETE(lamexp_ipc);
983 * IPC read message
985 void lamexp_ipc_read(unsigned int *command, char* message, size_t buffSize)
987 *command = 0;
988 message[0] = '\0';
990 if(!g_lamexp_ipc_ptr.sharedmem || !g_lamexp_ipc_ptr.semaphore_read || !g_lamexp_ipc_ptr.semaphore_write)
992 throw "Shared memory for IPC not initialized yet.";
995 lamexp_ipc_t *lamexp_ipc = new lamexp_ipc_t;
996 memset(lamexp_ipc, 0, sizeof(lamexp_ipc_t));
998 if(g_lamexp_ipc_ptr.semaphore_read->acquire())
1000 memcpy(lamexp_ipc, g_lamexp_ipc_ptr.sharedmem->data(), sizeof(lamexp_ipc_t));
1001 g_lamexp_ipc_ptr.semaphore_write->release();
1003 if(!(lamexp_ipc->reserved_1 || lamexp_ipc->reserved_2))
1005 *command = lamexp_ipc->command;
1006 strncpy_s(message, buffSize, lamexp_ipc->parameter, _TRUNCATE);
1008 else
1010 qWarning("Malformed IPC message, will be ignored");
1014 LAMEXP_DELETE(lamexp_ipc);
1018 * Check for LameXP "portable" mode
1020 bool lamexp_portable_mode(void)
1022 QString baseName = QFileInfo(QApplication::applicationFilePath()).completeBaseName();
1023 int idx1 = baseName.indexOf("lamexp", 0, Qt::CaseInsensitive);
1024 int idx2 = baseName.lastIndexOf("portable", -1, Qt::CaseInsensitive);
1025 return (idx1 >= 0) && (idx2 >= 0) && (idx1 < idx2);
1029 * Get a random string
1031 QString lamexp_rand_str(void)
1033 QRegExp regExp("\\{(\\w+)-(\\w+)-(\\w+)-(\\w+)-(\\w+)\\}");
1034 QString uuid = QUuid::createUuid().toString();
1036 if(regExp.indexIn(uuid) >= 0)
1038 return QString().append(regExp.cap(1)).append(regExp.cap(2)).append(regExp.cap(3)).append(regExp.cap(4)).append(regExp.cap(5));
1041 throw "The RegExp didn't match on the UUID string. This shouldn't happen ;-)";
1045 * Get LameXP temp folder
1047 const QString &lamexp_temp_folder2(void)
1049 static const char *TEMP_STR = "Temp";
1050 const QString WRITE_TEST_DATA = lamexp_rand_str();
1051 const QString SUB_FOLDER = lamexp_rand_str();
1053 //Already initialized?
1054 if(!g_lamexp_temp_folder.isEmpty())
1056 if(QDir(g_lamexp_temp_folder).exists())
1058 return g_lamexp_temp_folder;
1060 else
1062 g_lamexp_temp_folder.clear();
1066 //Try the %TMP% or %TEMP% directory first
1067 QDir temp = QDir::temp();
1068 if(temp.exists())
1070 temp.mkdir(SUB_FOLDER);
1071 if(temp.cd(SUB_FOLDER) && temp.exists())
1073 QFile testFile(QString("%1/~%2.tmp").arg(temp.canonicalPath(), lamexp_rand_str()));
1074 if(testFile.open(QIODevice::ReadWrite))
1076 if(testFile.write(WRITE_TEST_DATA.toLatin1().constData()) >= strlen(WRITE_TEST_DATA.toLatin1().constData()))
1078 g_lamexp_temp_folder = temp.canonicalPath();
1080 testFile.remove();
1083 if(!g_lamexp_temp_folder.isEmpty())
1085 return g_lamexp_temp_folder;
1089 //Create TEMP folder in %LOCALAPPDATA%
1090 QDir localAppData = QDir(lamexp_known_folder(lamexp_folder_localappdata));
1091 if(!localAppData.path().isEmpty())
1093 if(!localAppData.exists())
1095 localAppData.mkpath(".");
1097 if(localAppData.exists())
1099 if(!localAppData.entryList(QDir::AllDirs).contains(TEMP_STR, Qt::CaseInsensitive))
1101 localAppData.mkdir(TEMP_STR);
1103 if(localAppData.cd(TEMP_STR) && localAppData.exists())
1105 localAppData.mkdir(SUB_FOLDER);
1106 if(localAppData.cd(SUB_FOLDER) && localAppData.exists())
1108 QFile testFile(QString("%1/~%2.tmp").arg(localAppData.canonicalPath(), lamexp_rand_str()));
1109 if(testFile.open(QIODevice::ReadWrite))
1111 if(testFile.write(WRITE_TEST_DATA.toLatin1().constData()) >= strlen(WRITE_TEST_DATA.toLatin1().constData()))
1113 g_lamexp_temp_folder = localAppData.canonicalPath();
1115 testFile.remove();
1120 if(!g_lamexp_temp_folder.isEmpty())
1122 return g_lamexp_temp_folder;
1126 //Failed to create TEMP folder!
1127 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());
1128 return g_lamexp_temp_folder;
1132 * Clean folder
1134 bool lamexp_clean_folder(const QString &folderPath)
1136 QDir tempFolder(folderPath);
1137 QFileInfoList entryList = tempFolder.entryInfoList(QDir::AllEntries | QDir::NoDotAndDotDot);
1139 for(int i = 0; i < entryList.count(); i++)
1141 if(entryList.at(i).isDir())
1143 lamexp_clean_folder(entryList.at(i).canonicalFilePath());
1145 else
1147 for(int j = 0; j < 3; j++)
1149 if(lamexp_remove_file(entryList.at(i).canonicalFilePath()))
1151 break;
1157 tempFolder.rmdir(".");
1158 return !tempFolder.exists();
1162 * Register tool
1164 void lamexp_register_tool(const QString &toolName, LockedFile *file, unsigned int version)
1166 if(g_lamexp_tool_registry.contains(toolName.toLower()))
1168 throw "lamexp_register_tool: Tool is already registered!";
1171 g_lamexp_tool_registry.insert(toolName.toLower(), file);
1172 g_lamexp_tool_versions.insert(toolName.toLower(), version);
1176 * Check for tool
1178 bool lamexp_check_tool(const QString &toolName)
1180 return g_lamexp_tool_registry.contains(toolName.toLower());
1184 * Lookup tool path
1186 const QString lamexp_lookup_tool(const QString &toolName)
1188 if(g_lamexp_tool_registry.contains(toolName.toLower()))
1190 return g_lamexp_tool_registry.value(toolName.toLower())->filePath();
1192 else
1194 return QString();
1199 * Lookup tool version
1201 unsigned int lamexp_tool_version(const QString &toolName)
1203 if(g_lamexp_tool_versions.contains(toolName.toLower()))
1205 return g_lamexp_tool_versions.value(toolName.toLower());
1207 else
1209 return UINT_MAX;
1214 * Version number to human-readable string
1216 const QString lamexp_version2string(const QString &pattern, unsigned int version, const QString &defaultText)
1218 if(version == UINT_MAX)
1220 return defaultText;
1223 QString result = pattern;
1224 int digits = result.count("?", Qt::CaseInsensitive);
1226 if(digits < 1)
1228 return result;
1231 int pos = 0;
1232 QString versionStr = QString().sprintf(QString().sprintf("%%0%du", digits).toLatin1().constData(), version);
1233 int index = result.indexOf("?", Qt::CaseInsensitive);
1235 while(index >= 0 && pos < versionStr.length())
1237 result[index] = versionStr[pos++];
1238 index = result.indexOf("?", Qt::CaseInsensitive);
1241 return result;
1245 * Register a new translation
1247 bool lamexp_translation_register(const QString &langId, const QString &qmFile, const QString &langName, unsigned int &systemId)
1249 if(qmFile.isEmpty() || langName.isEmpty() || systemId < 1)
1251 return false;
1254 g_lamexp_translation.files.insert(langId, qmFile);
1255 g_lamexp_translation.names.insert(langId, langName);
1256 g_lamexp_translation.sysid.insert(langId, systemId);
1258 return true;
1262 * Get list of all translations
1264 QStringList lamexp_query_translations(void)
1266 return g_lamexp_translation.files.keys();
1270 * Get translation name
1272 QString lamexp_translation_name(const QString &langId)
1274 return g_lamexp_translation.names.value(langId.toLower(), QString());
1278 * Get translation system id
1280 unsigned int lamexp_translation_sysid(const QString &langId)
1282 return g_lamexp_translation.sysid.value(langId.toLower(), 0);
1286 * Install a new translator
1288 bool lamexp_install_translator(const QString &langId)
1290 bool success = false;
1292 if(langId.isEmpty() || langId.toLower().compare(LAMEXP_DEFAULT_LANGID) == 0)
1294 success = lamexp_install_translator_from_file(QString());
1296 else
1298 QString qmFile = g_lamexp_translation.files.value(langId.toLower(), QString());
1299 if(!qmFile.isEmpty())
1301 success = lamexp_install_translator_from_file(QString(":/localization/%1").arg(qmFile));
1303 else
1305 qWarning("Translation '%s' not available!", langId.toLatin1().constData());
1309 return success;
1313 * Install a new translator from file
1315 bool lamexp_install_translator_from_file(const QString &qmFile)
1317 bool success = false;
1319 if(!g_lamexp_currentTranslator)
1321 g_lamexp_currentTranslator = new QTranslator();
1324 if(!qmFile.isEmpty())
1326 QString qmPath = QFileInfo(qmFile).canonicalFilePath();
1327 QApplication::removeTranslator(g_lamexp_currentTranslator);
1328 success = g_lamexp_currentTranslator->load(qmPath);
1329 QApplication::installTranslator(g_lamexp_currentTranslator);
1330 if(!success)
1332 qWarning("Failed to load translation:\n\"%s\"", qmPath.toLatin1().constData());
1335 else
1337 QApplication::removeTranslator(g_lamexp_currentTranslator);
1338 success = true;
1341 return success;
1345 * Locate known folder on local system
1347 QString lamexp_known_folder(lamexp_known_folder_t folder_id)
1349 typedef HRESULT (WINAPI *SHGetKnownFolderPathFun)(__in const GUID &rfid, __in DWORD dwFlags, __in HANDLE hToken, __out PWSTR *ppszPath);
1350 typedef HRESULT (WINAPI *SHGetFolderPathFun)(__in HWND hwndOwner, __in int nFolder, __in HANDLE hToken, __in DWORD dwFlags, __out LPWSTR pszPath);
1352 static const int CSIDL_LOCAL_APPDATA = 0x001c;
1353 static const int CSIDL_PROGRAM_FILES = 0x0026;
1354 static const int CSIDL_SYSTEM_FOLDER = 0x0025;
1355 static const GUID GUID_LOCAL_APPDATA = {0xF1B32785,0x6FBA,0x4FCF,{0x9D,0x55,0x7B,0x8E,0x7F,0x15,0x70,0x91}};
1356 static const GUID GUID_LOCAL_APPDATA_LOW = {0xA520A1A4,0x1780,0x4FF6,{0xBD,0x18,0x16,0x73,0x43,0xC5,0xAF,0x16}};
1357 static const GUID GUID_PROGRAM_FILES = {0x905e63b6,0xc1bf,0x494e,{0xb2,0x9c,0x65,0xb7,0x32,0xd3,0xd2,0x1a}};
1358 static const GUID GUID_SYSTEM_FOLDER = {0x1AC14E77,0x02E7,0x4E5D,{0xB7,0x44,0x2E,0xB1,0xAE,0x51,0x98,0xB7}};
1360 static QLibrary *Kernel32Lib = NULL;
1361 static SHGetKnownFolderPathFun SHGetKnownFolderPathPtr = NULL;
1362 static SHGetFolderPathFun SHGetFolderPathPtr = NULL;
1364 if((!SHGetKnownFolderPathPtr) && (!SHGetFolderPathPtr))
1366 if(!Kernel32Lib) Kernel32Lib = new QLibrary("shell32.dll");
1367 SHGetKnownFolderPathPtr = (SHGetKnownFolderPathFun) Kernel32Lib->resolve("SHGetKnownFolderPath");
1368 SHGetFolderPathPtr = (SHGetFolderPathFun) Kernel32Lib->resolve("SHGetFolderPathW");
1371 int folderCSIDL = -1;
1372 GUID folderGUID = {0x0000,0x0000,0x0000,{0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00}};
1374 switch(folder_id)
1376 case lamexp_folder_localappdata:
1377 folderCSIDL = CSIDL_LOCAL_APPDATA;
1378 folderGUID = GUID_LOCAL_APPDATA;
1379 break;
1380 case lamexp_folder_programfiles:
1381 folderCSIDL = CSIDL_PROGRAM_FILES;
1382 folderGUID = GUID_PROGRAM_FILES;
1383 break;
1384 case lamexp_folder_systemfolder:
1385 folderCSIDL = CSIDL_SYSTEM_FOLDER;
1386 folderGUID = GUID_SYSTEM_FOLDER;
1387 break;
1388 default:
1389 return QString();
1390 break;
1393 QString folder;
1395 if(SHGetKnownFolderPathPtr)
1397 WCHAR *path = NULL;
1398 if(SHGetKnownFolderPathPtr(folderGUID, 0x00008000, NULL, &path) == S_OK)
1400 //MessageBoxW(0, path, L"SHGetKnownFolderPath", MB_TOPMOST);
1401 QDir folderTemp = QDir(QDir::fromNativeSeparators(QString::fromUtf16(reinterpret_cast<const unsigned short*>(path))));
1402 if(!folderTemp.exists())
1404 folderTemp.mkpath(".");
1406 if(folderTemp.exists())
1408 folder = folderTemp.canonicalPath();
1410 CoTaskMemFree(path);
1413 else if(SHGetFolderPathPtr)
1415 WCHAR *path = new WCHAR[4096];
1416 if(SHGetFolderPathPtr(NULL, folderCSIDL, NULL, NULL, path) == S_OK)
1418 //MessageBoxW(0, path, L"SHGetFolderPathW", MB_TOPMOST);
1419 QDir folderTemp = QDir(QDir::fromNativeSeparators(QString::fromUtf16(reinterpret_cast<const unsigned short*>(path))));
1420 if(!folderTemp.exists())
1422 folderTemp.mkpath(".");
1424 if(folderTemp.exists())
1426 folder = folderTemp.canonicalPath();
1429 delete [] path;
1432 return folder;
1436 * Safely remove a file
1438 bool lamexp_remove_file(const QString &filename)
1440 if(!QFileInfo(filename).exists() || !QFileInfo(filename).isFile())
1442 return true;
1444 else
1446 if(!QFile::remove(filename))
1448 DWORD attributes = GetFileAttributesW(QWCHAR(filename));
1449 SetFileAttributesW(QWCHAR(filename), (attributes & (~FILE_ATTRIBUTE_READONLY)));
1450 if(!QFile::remove(filename))
1452 qWarning("Could not delete \"%s\"", filename.toLatin1().constData());
1453 return false;
1455 else
1457 return true;
1460 else
1462 return true;
1468 * Check if visual themes are enabled (WinXP and later)
1470 bool lamexp_themes_enabled(void)
1472 typedef int (WINAPI *IsAppThemedFun)(void);
1474 bool isAppThemed = false;
1475 QLibrary uxTheme(QString("%1/UxTheme.dll").arg(lamexp_known_folder(lamexp_folder_systemfolder)));
1476 IsAppThemedFun IsAppThemedPtr = (IsAppThemedFun) uxTheme.resolve("IsAppThemed");
1478 if(IsAppThemedPtr)
1480 isAppThemed = IsAppThemedPtr();
1481 if(!isAppThemed)
1483 qWarning("Theme support is disabled for this process!");
1487 return isAppThemed;
1491 * Get number of free bytes on disk
1493 unsigned __int64 lamexp_free_diskspace(const QString &path, bool *ok)
1495 ULARGE_INTEGER freeBytesAvailable, totalNumberOfBytes, totalNumberOfFreeBytes;
1496 if(GetDiskFreeSpaceExW(reinterpret_cast<const wchar_t*>(QDir::toNativeSeparators(path).utf16()), &freeBytesAvailable, &totalNumberOfBytes, &totalNumberOfFreeBytes))
1498 if(ok) *ok = true;
1499 return freeBytesAvailable.QuadPart;
1501 else
1503 if(ok) *ok = false;
1504 return 0;
1509 * Check if computer does support hibernation
1511 bool lamexp_is_hibernation_supported(void)
1513 bool hibernationSupported = false;
1515 SYSTEM_POWER_CAPABILITIES pwrCaps;
1516 SecureZeroMemory(&pwrCaps, sizeof(SYSTEM_POWER_CAPABILITIES));
1518 if(GetPwrCapabilities(&pwrCaps))
1520 hibernationSupported = pwrCaps.SystemS4 && pwrCaps.HiberFilePresent;
1523 return hibernationSupported;
1527 * Shutdown the computer
1529 bool lamexp_shutdown_computer(const QString &message, const unsigned long timeout, const bool forceShutdown, const bool hibernate)
1531 HANDLE hToken = NULL;
1533 if(OpenProcessToken(GetCurrentProcess(), TOKEN_ADJUST_PRIVILEGES | TOKEN_QUERY, &hToken))
1535 TOKEN_PRIVILEGES privileges;
1536 memset(&privileges, 0, sizeof(TOKEN_PRIVILEGES));
1537 privileges.PrivilegeCount = 1;
1538 privileges.Privileges[0].Attributes = SE_PRIVILEGE_ENABLED;
1540 if(LookupPrivilegeValue(NULL, SE_SHUTDOWN_NAME, &privileges.Privileges[0].Luid))
1542 if(AdjustTokenPrivileges(hToken, FALSE, &privileges, NULL, NULL, NULL))
1544 if(hibernate)
1546 if(SetSuspendState(TRUE, TRUE, TRUE))
1548 return true;
1551 const DWORD reason = SHTDN_REASON_MAJOR_APPLICATION | SHTDN_REASON_FLAG_PLANNED;
1552 return InitiateSystemShutdownEx(NULL, const_cast<wchar_t*>(QWCHAR(message)), timeout, forceShutdown ? TRUE : FALSE, FALSE, reason);
1557 return false;
1561 * Make a window blink (to draw user's attention)
1563 void lamexp_blink_window(QWidget *poWindow, unsigned int count, unsigned int delay)
1565 static QMutex blinkMutex;
1567 const double maxOpac = 1.0;
1568 const double minOpac = 0.3;
1569 const double delOpac = 0.1;
1571 if(!blinkMutex.tryLock())
1573 qWarning("Blinking is already in progress, skipping!");
1574 return;
1579 const int steps = static_cast<int>(ceil(maxOpac - minOpac) / delOpac);
1580 const int sleep = static_cast<int>(floor(static_cast<double>(delay) / static_cast<double>(steps)));
1581 const double opacity = poWindow->windowOpacity();
1583 for(unsigned int i = 0; i < count; i++)
1585 for(double x = maxOpac; x >= minOpac; x -= delOpac)
1587 poWindow->setWindowOpacity(x);
1588 QApplication::processEvents();
1589 Sleep(sleep);
1592 for(double x = minOpac; x <= maxOpac; x += delOpac)
1594 poWindow->setWindowOpacity(x);
1595 QApplication::processEvents();
1596 Sleep(sleep);
1600 poWindow->setWindowOpacity(opacity);
1601 QApplication::processEvents();
1602 blinkMutex.unlock();
1604 catch (...)
1606 blinkMutex.unlock();
1607 qWarning("Exception error while blinking!");
1612 * Remove forbidden characters from a filename
1614 const QString lamexp_clean_filename(const QString &str)
1616 QString newStr(str);
1618 newStr.replace("\\", "-");
1619 newStr.replace(" / ", ", ");
1620 newStr.replace("/", ",");
1621 newStr.replace(":", "-");
1622 newStr.replace("*", "x");
1623 newStr.replace("?", "");
1624 newStr.replace("<", "[");
1625 newStr.replace(">", "]");
1626 newStr.replace("|", "!");
1628 return newStr.simplified();
1632 * Remove forbidden characters from a file path
1634 const QString lamexp_clean_filepath(const QString &str)
1636 QStringList parts = QString(str).replace("\\", "/").split("/");
1638 for(int i = 0; i < parts.count(); i++)
1640 parts[i] = lamexp_clean_filename(parts[i]);
1643 return parts.join("/");
1647 * Finalization function (final clean-up)
1649 void lamexp_finalization(void)
1651 //Free all tools
1652 if(!g_lamexp_tool_registry.isEmpty())
1654 QStringList keys = g_lamexp_tool_registry.keys();
1655 for(int i = 0; i < keys.count(); i++)
1657 LAMEXP_DELETE(g_lamexp_tool_registry[keys.at(i)]);
1659 g_lamexp_tool_registry.clear();
1660 g_lamexp_tool_versions.clear();
1663 //Delete temporary files
1664 if(!g_lamexp_temp_folder.isEmpty())
1666 for(int i = 0; i < 100; i++)
1668 if(lamexp_clean_folder(g_lamexp_temp_folder))
1670 break;
1672 Sleep(125);
1674 g_lamexp_temp_folder.clear();
1677 //Clear languages
1678 if(g_lamexp_currentTranslator)
1680 QApplication::removeTranslator(g_lamexp_currentTranslator);
1681 LAMEXP_DELETE(g_lamexp_currentTranslator);
1683 g_lamexp_translation.files.clear();
1684 g_lamexp_translation.names.clear();
1686 //Destroy Qt application object
1687 QApplication *application = dynamic_cast<QApplication*>(QApplication::instance());
1688 LAMEXP_DELETE(application);
1690 //Detach from shared memory
1691 if(g_lamexp_ipc_ptr.sharedmem) g_lamexp_ipc_ptr.sharedmem->detach();
1692 LAMEXP_DELETE(g_lamexp_ipc_ptr.sharedmem);
1693 LAMEXP_DELETE(g_lamexp_ipc_ptr.semaphore_read);
1694 LAMEXP_DELETE(g_lamexp_ipc_ptr.semaphore_write);
1698 * Initialize debug thread
1700 static const HANDLE g_debug_thread = LAMEXP_DEBUG ? NULL : lamexp_debug_thread_init();
1703 * Get number private bytes [debug only]
1705 SIZE_T lamexp_dbg_private_bytes(void)
1707 #if LAMEXP_DEBUG
1708 PROCESS_MEMORY_COUNTERS_EX memoryCounters;
1709 memoryCounters.cb = sizeof(PROCESS_MEMORY_COUNTERS_EX);
1710 GetProcessMemoryInfo(GetCurrentProcess(), (PPROCESS_MEMORY_COUNTERS) &memoryCounters, sizeof(PROCESS_MEMORY_COUNTERS_EX));
1711 return memoryCounters.PrivateUsage;
1712 #else
1713 throw "Cannot call this function in a non-debug build!";
1714 #endif //LAMEXP_DEBUG