OSDN Git Service

Added warnings when LAME algorithm quality is set to "extreme" values.
[lamexp/LameXP.git] / src / Global.cpp
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.
14 //
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.
18 //
19 // http://www.gnu.org/licenses/gpl-2.0.txt
20 ///////////////////////////////////////////////////////////////////////////////
21
22 #include "Global.h"
23
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>
46
47 //LameXP includes
48 #include "Resource.h"
49 #include "LockedFile.h"
50
51 //CRT includes
52 #include <io.h>
53 #include <fcntl.h>
54 #include <intrin.h>
55 #include <math.h>
56
57 //COM includes
58 #include <Objbase.h>
59
60 //Debug only includes
61 #if LAMEXP_DEBUG
62 #include <Psapi.h>
63 #endif
64
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
71
72 ///////////////////////////////////////////////////////////////////////////////
73 // TYPES
74 ///////////////////////////////////////////////////////////////////////////////
75
76 typedef struct
77 {
78         unsigned int command;
79         unsigned int reserved_1;
80         unsigned int reserved_2;
81         char parameter[4096];
82 } lamexp_ipc_t;
83
84 ///////////////////////////////////////////////////////////////////////////////
85 // GLOBAL VARS
86 ///////////////////////////////////////////////////////////////////////////////
87
88 //Build version
89 static const struct
90 {
91         unsigned int ver_major;
92         unsigned int ver_minor;
93         unsigned int ver_build;
94         char *ver_release_name;
95 }
96 g_lamexp_version =
97 {
98         VER_LAMEXP_MAJOR,
99         VER_LAMEXP_MINOR,
100         VER_LAMEXP_BUILD,
101         VER_LAMEXP_RNAME
102 };
103
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__;
109
110 //Console attached flag
111 static bool g_lamexp_console_attached = false;
112
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
141
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
153
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
162
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";
166
167 //Tool versions (expected versions!)
168 static const unsigned int g_lamexp_toolver_neroaac = VER_LAMEXP_TOOL_NEROAAC;
169 static const unsigned int g_lamexp_toolver_fhgaacenc = VER_LAMEXP_TOOL_FHGAACENC;
170
171 //Special folders
172 static QString g_lamexp_temp_folder;
173
174 //Tools
175 static QMap<QString, LockedFile*> g_lamexp_tool_registry;
176 static QMap<QString, unsigned int> g_lamexp_tool_versions;
177
178 //Languages
179 static struct
180 {
181         QMap<QString, QString> files;
182         QMap<QString, QString> names;
183         QMap<QString, unsigned int> sysid;
184 }
185 g_lamexp_translation;
186
187 //Translator
188 static QTranslator *g_lamexp_currentTranslator = NULL;
189
190 //Shared memory
191 static const struct
192 {
193         char *sharedmem;
194         char *semaphore_read;
195         char *semaphore_write;
196 }
197 g_lamexp_ipc_uuid =
198 {
199         "{21A68A42-6923-43bb-9CF6-64BF151942EE}",
200         "{7A605549-F58C-4d78-B4E5-06EFC34F405B}",
201         "{60AA8D04-F6B8-497d-81EB-0F600F4A65B5}"
202 };
203 static struct
204 {
205         QSharedMemory *sharedmem;
206         QSystemSemaphore *semaphore_read;
207         QSystemSemaphore *semaphore_write;
208 }
209 g_lamexp_ipc_ptr =
210 {
211         NULL, NULL, NULL
212 };
213
214 //Image formats
215 static const char *g_lamexp_imageformats[] = {"png", "jpg", "gif", "ico", "svg", NULL};
216
217 //Global locks
218 static QMutex g_lamexp_message_mutex;
219
220 //Main thread ID
221 static const DWORD g_main_thread_id = GetCurrentThreadId();
222
223
224 ///////////////////////////////////////////////////////////////////////////////
225 // GLOBAL FUNCTIONS
226 ///////////////////////////////////////////////////////////////////////////////
227
228 /*
229  * Version getters
230  */
231 unsigned int lamexp_version_major(void) { return g_lamexp_version.ver_major; }
232 unsigned int lamexp_version_minor(void) { return g_lamexp_version.ver_minor; }
233 unsigned int lamexp_version_build(void) { return g_lamexp_version.ver_build; }
234 const char *lamexp_version_release(void) { return g_lamexp_version.ver_release_name; }
235 const char *lamexp_version_time(void) { return g_lamexp_version_raw_time; }
236 const char *lamexp_version_compiler(void) { return g_lamexp_version_compiler; }
237 const char *lamexp_version_arch(void) { return g_lamexp_version_arch; }
238 unsigned int lamexp_toolver_neroaac(void) { return g_lamexp_toolver_neroaac; }
239 unsigned int lamexp_toolver_fhgaacenc(void) { return g_lamexp_toolver_fhgaacenc; }
240
241 /*
242  * URL getters
243  */
244 const char *lamexp_website_url(void) { return g_lamexp_website_url; }
245 const char *lamexp_support_url(void) { return g_lamexp_support_url; }
246
247 /*
248  * Check for Demo (pre-release) version
249  */
250 bool lamexp_version_demo(void)
251 {
252         char buffer[128];
253         bool releaseVersion = false;
254         if(!strncpy_s(buffer, 128, g_lamexp_version.ver_release_name, _TRUNCATE))
255         {
256                 char *context, *prefix = strtok_s(buffer, "-,; ", &context);
257                 if(prefix)
258                 {
259                         releaseVersion = (!_stricmp(prefix, "Final")) || (!_stricmp(prefix, "Hotfix"));
260                 }
261         }
262         return LAMEXP_DEBUG || (!releaseVersion);
263 }
264
265 /*
266  * Calculate expiration date
267  */
268 QDate lamexp_version_expires(void)
269 {
270         return lamexp_version_date().addDays(LAMEXP_DEBUG ? 2 : 30);
271 }
272
273 /*
274  * Get build date date
275  */
276 const QDate &lamexp_version_date(void)
277 {
278         if(!g_lamexp_version_date.isValid())
279         {
280                 char temp[32];
281                 int date[3];
282
283                 char *this_token = NULL;
284                 char *next_token = NULL;
285
286                 strncpy_s(temp, 32, g_lamexp_version_raw_date, _TRUNCATE);
287                 this_token = strtok_s(temp, " ", &next_token);
288
289                 for(int i = 0; i < 3; i++)
290                 {
291                         date[i] = -1;
292                         if(this_token)
293                         {
294                                 for(int j = 0; j < 12; j++)
295                                 {
296                                         if(!_strcmpi(this_token, g_lamexp_months[j]))
297                                         {
298                                                 date[i] = j+1;
299                                                 break;
300                                         }
301                                 }
302                                 if(date[i] < 0)
303                                 {
304                                         date[i] = atoi(this_token);
305                                 }
306                                 this_token = strtok_s(NULL, " ", &next_token);
307                         }
308                 }
309
310                 if(date[0] >= 0 && date[1] >= 0 && date[2] >= 0)
311                 {
312                         g_lamexp_version_date = QDate(date[2], date[0], date[1]);
313                 }
314         }
315
316         return g_lamexp_version_date;
317 }
318
319 /*
320  * Global exception handler
321  */
322 LONG WINAPI lamexp_exception_handler(__in struct _EXCEPTION_POINTERS *ExceptionInfo)
323 {
324         if(GetCurrentThreadId() != g_main_thread_id)
325         {
326                 HANDLE mainThread = OpenThread(THREAD_TERMINATE, FALSE, g_main_thread_id);
327                 if(mainThread) TerminateThread(mainThread, ULONG_MAX);
328         }
329         
330         FatalAppExit(0, L"Unhandeled exception handler invoked, application will exit!");
331         TerminateProcess(GetCurrentProcess(), -1);
332         return LONG_MAX;
333 }
334
335 /*
336  * Invalid parameters handler
337  */
338 void lamexp_invalid_param_handler(const wchar_t*, const wchar_t*, const wchar_t*, unsigned int, uintptr_t)
339 {
340         if(GetCurrentThreadId() != g_main_thread_id)
341         {
342                 HANDLE mainThread = OpenThread(THREAD_TERMINATE, FALSE, g_main_thread_id);
343                 if(mainThread) TerminateThread(mainThread, ULONG_MAX);
344                 
345         }
346         
347         FatalAppExit(0, L"Invalid parameter handler invoked, application will exit!");
348         TerminateProcess(GetCurrentProcess(), -1);
349 }
350
351 /*
352  * Change console text color
353  */
354 static void lamexp_console_color(FILE* file, WORD attributes)
355 {
356         const HANDLE hConsole = (HANDLE)(_get_osfhandle(_fileno(file)));
357         if((hConsole != NULL) && (hConsole != INVALID_HANDLE_VALUE))
358         {
359                 SetConsoleTextAttribute(hConsole, attributes);
360         }
361 }
362
363 /*
364  * Qt message handler
365  */
366 void lamexp_message_handler(QtMsgType type, const char *msg)
367 {
368         static const char *GURU_MEDITATION = "\n\nGURU MEDITATION !!!\n\n";
369
370         const char *text = msg;
371         const char *buffer = NULL;
372         
373         QMutexLocker lock(&g_lamexp_message_mutex);
374
375         if((strlen(msg) > 8) && (_strnicmp(msg, "@BASE64@", 8) == 0))
376         {
377                 buffer = _strdup(QByteArray::fromBase64(msg + 8).constData());
378                 if(buffer) text = buffer;
379         }
380
381         if(g_lamexp_console_attached)
382         {
383                 UINT oldOutputCP = GetConsoleOutputCP();
384                 if(oldOutputCP != CP_UTF8) SetConsoleOutputCP(CP_UTF8);
385
386                 switch(type)
387                 {
388                 case QtCriticalMsg:
389                 case QtFatalMsg:
390                         fflush(stdout);
391                         fflush(stderr);
392                         lamexp_console_color(stderr, FOREGROUND_RED | FOREGROUND_INTENSITY);
393                         fprintf(stderr, GURU_MEDITATION);
394                         fprintf(stderr, "%s\n", text);
395                         fflush(stderr);
396                         break;
397                 case QtWarningMsg:
398                         lamexp_console_color(stderr, FOREGROUND_GREEN | FOREGROUND_RED | FOREGROUND_INTENSITY);
399                         fprintf(stderr, "%s\n", text);
400                         fflush(stderr);
401                         break;
402                 default:
403                         lamexp_console_color(stderr, FOREGROUND_BLUE | FOREGROUND_GREEN | FOREGROUND_RED | FOREGROUND_INTENSITY);
404                         fprintf(stderr, "%s\n", text);
405                         fflush(stderr);
406                         break;
407                 }
408         
409                 lamexp_console_color(stderr, FOREGROUND_BLUE | FOREGROUND_GREEN | FOREGROUND_RED);
410                 if(oldOutputCP != CP_UTF8) SetConsoleOutputCP(oldOutputCP);
411         }
412         else
413         {
414                 char temp[1024] = {'\0'};
415                 
416                 switch(type)
417                 {
418                 case QtCriticalMsg:
419                 case QtFatalMsg:
420                         _snprintf_s(temp, 1024, _TRUNCATE, "[LameXP][C] %s", text);
421                         break;
422                 case QtWarningMsg:
423                         _snprintf_s(temp, 1024, _TRUNCATE, "[LameXP][C] %s", text);
424                         break;
425                 default:
426                         _snprintf_s(temp, 1024, _TRUNCATE, "[LameXP][C] %s", text);
427                         break;
428                 }
429
430                 char *ptr = strchr(temp, '\n');
431                 while(ptr != NULL)
432                 {
433                         *ptr = '\t';
434                         ptr = strchr(temp, '\n');
435                 }
436                 
437                 strncat_s(temp, 1024, "\n", _TRUNCATE);
438                 OutputDebugStringA(temp);
439         }
440
441         if(type == QtCriticalMsg || type == QtFatalMsg)
442         {
443                 lock.unlock();
444                 MessageBoxW(NULL, QWCHAR(QString::fromUtf8(text)), L"LameXP - GURU MEDITATION", MB_ICONERROR | MB_TOPMOST | MB_TASKMODAL);
445                 FatalAppExit(0, L"The application has encountered a critical error and will exit now!");
446                 TerminateProcess(GetCurrentProcess(), -1);
447         }
448
449         LAMEXP_SAFE_FREE(buffer);
450 }
451
452 /*
453  * Initialize the console
454  */
455 void lamexp_init_console(int argc, char* argv[])
456 {
457         bool enableConsole = lamexp_version_demo();
458
459         if(!LAMEXP_DEBUG)
460         {
461                 for(int i = 0; i < argc; i++)
462                 {
463                         if(!_stricmp(argv[i], "--console"))
464                         {
465                                 enableConsole = true;
466                         }
467                         else if(!_stricmp(argv[i], "--no-console"))
468                         {
469                                 enableConsole = false;
470                         }
471                 }
472         }
473
474         if(enableConsole)
475         {
476                 if(!g_lamexp_console_attached)
477                 {
478                         if(AllocConsole() != FALSE)
479                         {
480                                 SetConsoleCtrlHandler(NULL, TRUE);
481                                 SetConsoleTitle(L"LameXP - Audio Encoder Front-End | Debug Console");
482                                 SetConsoleOutputCP(CP_UTF8);
483                                 g_lamexp_console_attached = true;
484                         }
485                 }
486                 
487                 if(g_lamexp_console_attached)
488                 {
489                         //-------------------------------------------------------------------
490                         //See: http://support.microsoft.com/default.aspx?scid=kb;en-us;105305
491                         //-------------------------------------------------------------------
492                         const int flags = _O_WRONLY | _O_U8TEXT;
493                         int hCrtStdOut = _open_osfhandle((intptr_t) GetStdHandle(STD_OUTPUT_HANDLE), flags);
494                         int hCrtStdErr = _open_osfhandle((intptr_t) GetStdHandle(STD_ERROR_HANDLE), flags);
495                         FILE *hfStdOut = _fdopen(hCrtStdOut, "w");
496                         FILE *hfStderr = _fdopen(hCrtStdErr, "w");
497                         if(hfStdOut) *stdout = *hfStdOut;
498                         if(hfStderr) *stderr = *hfStderr;
499                 }
500
501                 HWND hwndConsole = GetConsoleWindow();
502
503                 if((hwndConsole != NULL) && (hwndConsole != INVALID_HANDLE_VALUE))
504                 {
505                         HMENU hMenu = GetSystemMenu(hwndConsole, 0);
506                         EnableMenuItem(hMenu, SC_CLOSE, MF_BYCOMMAND | MF_GRAYED);
507                         RemoveMenu(hMenu, SC_CLOSE, MF_BYCOMMAND);
508
509                         SetWindowLong(hwndConsole, GWL_STYLE, GetWindowLong(hwndConsole, GWL_STYLE) & (~WS_MAXIMIZEBOX));
510                         SetWindowLong(hwndConsole, GWL_STYLE, GetWindowLong(hwndConsole, GWL_STYLE) & (~WS_MINIMIZEBOX));
511                 }
512         }
513 }
514
515 /*
516  * Detect CPU features
517  */
518 lamexp_cpu_t lamexp_detect_cpu_features(void)
519 {
520         typedef BOOL (WINAPI *IsWow64ProcessFun)(__in HANDLE hProcess, __out PBOOL Wow64Process);
521         typedef VOID (WINAPI *GetNativeSystemInfoFun)(__out LPSYSTEM_INFO lpSystemInfo);
522         
523         static IsWow64ProcessFun IsWow64ProcessPtr = NULL;
524         static GetNativeSystemInfoFun GetNativeSystemInfoPtr = NULL;
525
526         lamexp_cpu_t features;
527         SYSTEM_INFO systemInfo;
528         int CPUInfo[4] = {-1};
529         char CPUIdentificationString[0x40];
530         char CPUBrandString[0x40];
531
532         memset(&features, 0, sizeof(lamexp_cpu_t));
533         memset(&systemInfo, 0, sizeof(SYSTEM_INFO));
534         memset(CPUIdentificationString, 0, sizeof(CPUIdentificationString));
535         memset(CPUBrandString, 0, sizeof(CPUBrandString));
536         
537         __cpuid(CPUInfo, 0);
538         memcpy(CPUIdentificationString, &CPUInfo[1], sizeof(int));
539         memcpy(CPUIdentificationString + 4, &CPUInfo[3], sizeof(int));
540         memcpy(CPUIdentificationString + 8, &CPUInfo[2], sizeof(int));
541         features.intel = (_stricmp(CPUIdentificationString, "GenuineIntel") == 0);
542         strncpy_s(features.vendor, 0x40, CPUIdentificationString, _TRUNCATE);
543
544         if(CPUInfo[0] >= 1)
545         {
546                 __cpuid(CPUInfo, 1);
547                 features.mmx = (CPUInfo[3] & 0x800000) || false;
548                 features.sse = (CPUInfo[3] & 0x2000000) || false;
549                 features.sse2 = (CPUInfo[3] & 0x4000000) || false;
550                 features.ssse3 = (CPUInfo[2] & 0x200) || false;
551                 features.sse3 = (CPUInfo[2] & 0x1) || false;
552                 features.ssse3 = (CPUInfo[2] & 0x200) || false;
553                 features.stepping = CPUInfo[0] & 0xf;
554                 features.model = ((CPUInfo[0] >> 4) & 0xf) + (((CPUInfo[0] >> 16) & 0xf) << 4);
555                 features.family = ((CPUInfo[0] >> 8) & 0xf) + ((CPUInfo[0] >> 20) & 0xff);
556         }
557
558         __cpuid(CPUInfo, 0x80000000);
559         int nExIds = max(min(CPUInfo[0], 0x80000004), 0x80000000);
560
561         for(int i = 0x80000002; i <= nExIds; ++i)
562         {
563                 __cpuid(CPUInfo, i);
564                 switch(i)
565                 {
566                 case 0x80000002:
567                         memcpy(CPUBrandString, CPUInfo, sizeof(CPUInfo));
568                         break;
569                 case 0x80000003:
570                         memcpy(CPUBrandString + 16, CPUInfo, sizeof(CPUInfo));
571                         break;
572                 case 0x80000004:
573                         memcpy(CPUBrandString + 32, CPUInfo, sizeof(CPUInfo));
574                         break;
575                 }
576         }
577
578         strncpy_s(features.brand, 0x40, CPUBrandString, _TRUNCATE);
579
580         if(strlen(features.brand) < 1) strncpy_s(features.brand, 0x40, "Unknown", _TRUNCATE);
581         if(strlen(features.vendor) < 1) strncpy_s(features.vendor, 0x40, "Unknown", _TRUNCATE);
582
583 #if !defined(_M_X64 ) && !defined(_M_IA64)
584         if(!IsWow64ProcessPtr || !GetNativeSystemInfoPtr)
585         {
586                 QLibrary Kernel32Lib("kernel32.dll");
587                 IsWow64ProcessPtr = (IsWow64ProcessFun) Kernel32Lib.resolve("IsWow64Process");
588                 GetNativeSystemInfoPtr = (GetNativeSystemInfoFun) Kernel32Lib.resolve("GetNativeSystemInfo");
589         }
590         if(IsWow64ProcessPtr)
591         {
592                 BOOL x64 = FALSE;
593                 if(IsWow64ProcessPtr(GetCurrentProcess(), &x64))
594                 {
595                         features.x64 = x64;
596                 }
597         }
598         if(GetNativeSystemInfoPtr)
599         {
600                 GetNativeSystemInfoPtr(&systemInfo);
601         }
602         else
603         {
604                 GetSystemInfo(&systemInfo);
605         }
606         features.count = systemInfo.dwNumberOfProcessors;
607 #else
608         GetNativeSystemInfo(&systemInfo);
609         features.count = systemInfo.dwNumberOfProcessors;
610         features.x64 = true;
611 #endif
612
613         return features;
614 }
615
616 /*
617  * Check for debugger (detect routine)
618  */
619 static bool lamexp_check_for_debugger(void)
620 {
621         __try 
622         {
623                 DebugBreak();
624         }
625         __except(GetExceptionCode() == EXCEPTION_BREAKPOINT ? EXCEPTION_EXECUTE_HANDLER : EXCEPTION_CONTINUE_SEARCH) 
626         {
627                 return false;
628         }
629         return true;
630 }
631
632 /*
633  * Check for debugger (thread proc)
634  */
635 static void WINAPI lamexp_debug_thread_proc(__in LPVOID lpParameter)
636 {
637         while(!(IsDebuggerPresent() || lamexp_check_for_debugger()))
638         {
639                 Sleep(333);
640         }
641         TerminateProcess(GetCurrentProcess(), -1);
642 }
643
644 /*
645  * Check for debugger (startup routine)
646  */
647 static HANDLE lamexp_debug_thread_init(void)
648 {
649         if(IsDebuggerPresent() || lamexp_check_for_debugger())
650         {
651                 FatalAppExit(0, L"Not a debug build. Please unload debugger and try again!");
652                 TerminateProcess(GetCurrentProcess(), -1);
653         }
654
655         return CreateThread(NULL, NULL, reinterpret_cast<LPTHREAD_START_ROUTINE>(&lamexp_debug_thread_proc), NULL, NULL, NULL);
656 }
657
658 /*
659  * Check for compatibility mode
660  */
661 static bool lamexp_check_compatibility_mode(const char *exportName, const char *executableName)
662 {
663         QLibrary kernel32("kernel32.dll");
664
665         if(exportName != NULL)
666         {
667                 if(kernel32.resolve(exportName) != NULL)
668                 {
669                         qWarning("Function '%s' exported from 'kernel32.dll' -> Windows compatibility mode!", exportName);
670                         qFatal("%s", QApplication::tr("Executable '%1' doesn't support Windows compatibility mode.").arg(QString::fromLatin1(executableName)).toLatin1().constData());
671                         return false;
672                 }
673         }
674
675         return true;
676 }
677
678 /*
679  * Check for process elevation
680  */
681 static bool lamexp_check_elevation(void)
682 {
683         typedef enum { lamexp_token_elevationType_class = 18, lamexp_token_elevation_class = 20 } LAMEXP_TOKEN_INFORMATION_CLASS;
684         typedef enum { lamexp_elevationType_default = 1, lamexp_elevationType_full, lamexp_elevationType_limited } LAMEXP_TOKEN_ELEVATION_TYPE;
685
686         HANDLE hToken = NULL;
687         bool bIsProcessElevated = false;
688         
689         if(OpenProcessToken(GetCurrentProcess(), TOKEN_QUERY, &hToken))
690         {
691                 LAMEXP_TOKEN_ELEVATION_TYPE tokenElevationType;
692                 DWORD returnLength;
693                 if(GetTokenInformation(hToken, (TOKEN_INFORMATION_CLASS) lamexp_token_elevationType_class, &tokenElevationType, sizeof(LAMEXP_TOKEN_ELEVATION_TYPE), &returnLength))
694                 {
695                         if(returnLength == sizeof(LAMEXP_TOKEN_ELEVATION_TYPE))
696                         {
697                                 switch(tokenElevationType)
698                                 {
699                                 case lamexp_elevationType_default:
700                                         qDebug("Process token elevation type: Default -> UAC is disabled.\n");
701                                         break;
702                                 case lamexp_elevationType_full:
703                                         qWarning("Process token elevation type: Full -> potential security risk!\n");
704                                         bIsProcessElevated = true;
705                                         break;
706                                 case lamexp_elevationType_limited:
707                                         qDebug("Process token elevation type: Limited -> not elevated.\n");
708                                         break;
709                                 }
710                         }
711                 }
712                 CloseHandle(hToken);
713         }
714         else
715         {
716                 qWarning("Failed to open process token!");
717         }
718
719         return !bIsProcessElevated;
720 }
721
722 /*
723  * Initialize Qt framework
724  */
725 bool lamexp_init_qt(int argc, char* argv[])
726 {
727         static bool qt_initialized = false;
728         bool isWine = false;
729         typedef BOOL (WINAPI *SetDllDirectoryProc)(WCHAR *lpPathName);
730
731         //Don't initialized again, if done already
732         if(qt_initialized)
733         {
734                 return true;
735         }
736         
737         //Secure DLL loading
738         QLibrary kernel32("kernel32.dll");
739         if(kernel32.load())
740         {
741                 SetDllDirectoryProc pSetDllDirectory = (SetDllDirectoryProc) kernel32.resolve("SetDllDirectoryW");
742                 if(pSetDllDirectory != NULL) pSetDllDirectory(L"");
743                 kernel32.unload();
744         }
745
746         //Extract executable name from argv[] array
747         char *executableName = argv[0];
748         while(char *temp = strpbrk(executableName, "\\/:?"))
749         {
750                 executableName = temp + 1;
751         }
752
753         //Check Qt version
754         qDebug("Using Qt Framework v%s, compiled with Qt v%s [%s]", qVersion(), QT_VERSION_STR, QT_PACKAGEDATE_STR);
755         if(_stricmp(qVersion(), QT_VERSION_STR))
756         {
757                 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());
758                 return false;
759         }
760
761         //Check the Windows version
762         switch(QSysInfo::windowsVersion() & QSysInfo::WV_NT_based)
763         {
764         case QSysInfo::WV_2000:
765                 qDebug("Running on Windows 2000 (not officially supported!).\n");
766                 lamexp_check_compatibility_mode("GetNativeSystemInfo", executableName);
767                 break;
768         case QSysInfo::WV_XP:
769                 qDebug("Running on Windows XP.\n");
770                 lamexp_check_compatibility_mode("GetLargePageMinimum", executableName);
771                 break;
772         case QSysInfo::WV_2003:
773                 qDebug("Running on Windows Server 2003 or Windows XP x64-Edition.\n");
774                 lamexp_check_compatibility_mode("GetLocaleInfoEx", executableName);
775                 break;
776         case QSysInfo::WV_VISTA:
777                 qDebug("Running on Windows Vista or Windows Server 2008.\n");
778                 lamexp_check_compatibility_mode("CreateRemoteThreadEx", executableName);
779                 break;
780         case QSysInfo::WV_WINDOWS7:
781                 qDebug("Running on Windows 7 or Windows Server 2008 R2.\n");
782                 lamexp_check_compatibility_mode(NULL, executableName);
783                 break;
784         default:
785                 qWarning("%s", QApplication::tr("Executable '%1' requires Windows 2000 or later.").arg(QString::fromLatin1(executableName)).toLatin1().constData());
786                 break;
787         }
788
789         //Check for Wine
790         QLibrary ntdll("ntdll.dll");
791         if(ntdll.load())
792         {
793                 if(ntdll.resolve("wine_nt_to_unix_file_name") != NULL) isWine = true;
794                 if(ntdll.resolve("wine_get_version") != NULL) isWine = true;
795                 if(isWine) qWarning("It appears we are running under Wine, unexpected things might happen!\n");
796                 ntdll.unload();
797         }
798
799         //Create Qt application instance and setup version info
800         QDate date = QDate::currentDate();
801         QApplication *application = new QApplication(argc, argv);
802         application->setApplicationName("LameXP - Audio Encoder Front-End");
803         application->setApplicationVersion(QString().sprintf("%d.%02d.%04d", lamexp_version_major(), lamexp_version_minor(), lamexp_version_build())); 
804         application->setOrganizationName("LoRd_MuldeR");
805         application->setOrganizationDomain("mulder.dummwiedeutsch.de");
806         application->setWindowIcon((date.month() == 12 && date.day() >= 24 && date.day() <= 26) ? QIcon(":/MainIcon2.png") : QIcon(":/MainIcon.png"));
807         
808         //Load plugins from application directory
809         QCoreApplication::setLibraryPaths(QStringList() << QApplication::applicationDirPath());
810         qDebug("Library Path:\n%s\n", QApplication::libraryPaths().first().toUtf8().constData());
811
812         //Check for supported image formats
813         QList<QByteArray> supportedFormats = QImageReader::supportedImageFormats();
814         for(int i = 0; g_lamexp_imageformats[i]; i++)
815         {
816                 if(!supportedFormats.contains(g_lamexp_imageformats[i]))
817                 {
818                         qFatal("Qt initialization error: QImageIOHandler for '%s' missing!", g_lamexp_imageformats[i]);
819                         return false;
820                 }
821         }
822
823         //Add default translations
824         g_lamexp_translation.files.insert(LAMEXP_DEFAULT_LANGID, "");
825         g_lamexp_translation.names.insert(LAMEXP_DEFAULT_LANGID, "English");
826
827         //Check for process elevation
828         if(!lamexp_check_elevation())
829         {
830                 if(QMessageBox::warning(NULL, "LameXP", "<nobr>LameXP was started with elevated rights. This is a potential security risk!</nobr>", "Quit Program (Recommended)", "Ignore") == 0)
831                 {
832                         return false;
833                 }
834         }
835
836         //Update console icon, if a console is attached
837         if(g_lamexp_console_attached && !isWine)
838         {
839                 typedef DWORD (__stdcall *SetConsoleIconFun)(HICON);
840                 QLibrary kernel32("kernel32.dll");
841                 if(kernel32.load())
842                 {
843                         SetConsoleIconFun SetConsoleIconPtr = (SetConsoleIconFun) kernel32.resolve("SetConsoleIcon");
844                         if(SetConsoleIconPtr != NULL) SetConsoleIconPtr(QIcon(":/icons/sound.png").pixmap(16, 16).toWinHICON());
845                         kernel32.unload();
846                 }
847         }
848
849         //Done
850         qt_initialized = true;
851         return true;
852 }
853
854 /*
855  * Initialize IPC
856  */
857 int lamexp_init_ipc(void)
858 {
859         if(g_lamexp_ipc_ptr.sharedmem && g_lamexp_ipc_ptr.semaphore_read && g_lamexp_ipc_ptr.semaphore_write)
860         {
861                 return 0;
862         }
863
864         g_lamexp_ipc_ptr.semaphore_read = new QSystemSemaphore(QString(g_lamexp_ipc_uuid.semaphore_read), 0);
865         g_lamexp_ipc_ptr.semaphore_write = new QSystemSemaphore(QString(g_lamexp_ipc_uuid.semaphore_write), 0);
866
867         if(g_lamexp_ipc_ptr.semaphore_read->error() != QSystemSemaphore::NoError)
868         {
869                 QString errorMessage = g_lamexp_ipc_ptr.semaphore_read->errorString();
870                 LAMEXP_DELETE(g_lamexp_ipc_ptr.semaphore_read);
871                 LAMEXP_DELETE(g_lamexp_ipc_ptr.semaphore_write);
872                 qFatal("Failed to create system smaphore: %s", errorMessage.toUtf8().constData());
873                 return -1;
874         }
875         if(g_lamexp_ipc_ptr.semaphore_write->error() != QSystemSemaphore::NoError)
876         {
877                 QString errorMessage = g_lamexp_ipc_ptr.semaphore_write->errorString();
878                 LAMEXP_DELETE(g_lamexp_ipc_ptr.semaphore_read);
879                 LAMEXP_DELETE(g_lamexp_ipc_ptr.semaphore_write);
880                 qFatal("Failed to create system smaphore: %s", errorMessage.toUtf8().constData());
881                 return -1;
882         }
883
884         g_lamexp_ipc_ptr.sharedmem = new QSharedMemory(QString(g_lamexp_ipc_uuid.sharedmem), NULL);
885         
886         if(!g_lamexp_ipc_ptr.sharedmem->create(sizeof(lamexp_ipc_t)))
887         {
888                 if(g_lamexp_ipc_ptr.sharedmem->error() == QSharedMemory::AlreadyExists)
889                 {
890                         g_lamexp_ipc_ptr.sharedmem->attach();
891                         if(g_lamexp_ipc_ptr.sharedmem->error() == QSharedMemory::NoError)
892                         {
893                                 return 1;
894                         }
895                         else
896                         {
897                                 QString errorMessage = g_lamexp_ipc_ptr.sharedmem->errorString();
898                                 qFatal("Failed to attach to shared memory: %s", errorMessage.toUtf8().constData());
899                                 return -1;
900                         }
901                 }
902                 else
903                 {
904                         QString errorMessage = g_lamexp_ipc_ptr.sharedmem->errorString();
905                         qFatal("Failed to create shared memory: %s", errorMessage.toUtf8().constData());
906                         return -1;
907                 }
908         }
909
910         memset(g_lamexp_ipc_ptr.sharedmem->data(), 0, sizeof(lamexp_ipc_t));
911         g_lamexp_ipc_ptr.semaphore_write->release();
912
913         return 0;
914 }
915
916 /*
917  * IPC send message
918  */
919 void lamexp_ipc_send(unsigned int command, const char* message)
920 {
921         if(!g_lamexp_ipc_ptr.sharedmem || !g_lamexp_ipc_ptr.semaphore_read || !g_lamexp_ipc_ptr.semaphore_write)
922         {
923                 throw "Shared memory for IPC not initialized yet.";
924         }
925
926         lamexp_ipc_t *lamexp_ipc = new lamexp_ipc_t;
927         memset(lamexp_ipc, 0, sizeof(lamexp_ipc_t));
928         lamexp_ipc->command = command;
929         if(message)
930         {
931                 strncpy_s(lamexp_ipc->parameter, 4096, message, _TRUNCATE);
932         }
933
934         if(g_lamexp_ipc_ptr.semaphore_write->acquire())
935         {
936                 memcpy(g_lamexp_ipc_ptr.sharedmem->data(), lamexp_ipc, sizeof(lamexp_ipc_t));
937                 g_lamexp_ipc_ptr.semaphore_read->release();
938         }
939
940         LAMEXP_DELETE(lamexp_ipc);
941 }
942
943 /*
944  * IPC read message
945  */
946 void lamexp_ipc_read(unsigned int *command, char* message, size_t buffSize)
947 {
948         *command = 0;
949         message[0] = '\0';
950         
951         if(!g_lamexp_ipc_ptr.sharedmem || !g_lamexp_ipc_ptr.semaphore_read || !g_lamexp_ipc_ptr.semaphore_write)
952         {
953                 throw "Shared memory for IPC not initialized yet.";
954         }
955
956         lamexp_ipc_t *lamexp_ipc = new lamexp_ipc_t;
957         memset(lamexp_ipc, 0, sizeof(lamexp_ipc_t));
958
959         if(g_lamexp_ipc_ptr.semaphore_read->acquire())
960         {
961                 memcpy(lamexp_ipc, g_lamexp_ipc_ptr.sharedmem->data(), sizeof(lamexp_ipc_t));
962                 g_lamexp_ipc_ptr.semaphore_write->release();
963
964                 if(!(lamexp_ipc->reserved_1 || lamexp_ipc->reserved_2))
965                 {
966                         *command = lamexp_ipc->command;
967                         strncpy_s(message, buffSize, lamexp_ipc->parameter, _TRUNCATE);
968                 }
969                 else
970                 {
971                         qWarning("Malformed IPC message, will be ignored");
972                 }
973         }
974
975         LAMEXP_DELETE(lamexp_ipc);
976 }
977
978 /*
979  * Check for LameXP "portable" mode
980  */
981 bool lamexp_portable_mode(void)
982 {
983         QString baseName = QFileInfo(QApplication::applicationFilePath()).completeBaseName();
984         return baseName.contains("lamexp", Qt::CaseInsensitive) && baseName.contains("portable", Qt::CaseInsensitive);
985 }
986
987 /*
988  * Get a random string
989  */
990 QString lamexp_rand_str(void)
991 {
992         QRegExp regExp("\\{(\\w+)-(\\w+)-(\\w+)-(\\w+)-(\\w+)\\}");
993         QString uuid = QUuid::createUuid().toString();
994
995         if(regExp.indexIn(uuid) >= 0)
996         {
997                 return QString().append(regExp.cap(1)).append(regExp.cap(2)).append(regExp.cap(3)).append(regExp.cap(4)).append(regExp.cap(5));
998         }
999
1000         throw "The RegExp didn't match on the UUID string. This shouldn't happen ;-)";
1001 }
1002
1003 /*
1004  * Get LameXP temp folder
1005  */
1006 const QString &lamexp_temp_folder2(void)
1007 {
1008         static const char *TEMP_STR = "Temp";
1009         const QString WRITE_TEST_DATA = lamexp_rand_str();
1010         const QString SUB_FOLDER = lamexp_rand_str();
1011
1012         //Already initialized?
1013         if(!g_lamexp_temp_folder.isEmpty())
1014         {
1015                 if(QDir(g_lamexp_temp_folder).exists())
1016                 {
1017                         return g_lamexp_temp_folder;
1018                 }
1019                 else
1020                 {
1021                         g_lamexp_temp_folder.clear();
1022                 }
1023         }
1024         
1025         //Try the %TMP% or %TEMP% directory first
1026         QDir temp = QDir::temp();
1027         if(temp.exists())
1028         {
1029                 temp.mkdir(SUB_FOLDER);
1030                 if(temp.cd(SUB_FOLDER) && temp.exists())
1031                 {
1032                         QFile testFile(QString("%1/~%2.tmp").arg(temp.canonicalPath(), lamexp_rand_str()));
1033                         if(testFile.open(QIODevice::ReadWrite))
1034                         {
1035                                 if(testFile.write(WRITE_TEST_DATA.toLatin1().constData()) >= strlen(WRITE_TEST_DATA.toLatin1().constData()))
1036                                 {
1037                                         g_lamexp_temp_folder = temp.canonicalPath();
1038                                 }
1039                                 testFile.remove();
1040                         }
1041                 }
1042                 if(!g_lamexp_temp_folder.isEmpty())
1043                 {
1044                         return g_lamexp_temp_folder;
1045                 }
1046         }
1047
1048         //Create TEMP folder in %LOCALAPPDATA%
1049         QDir localAppData = QDir(lamexp_known_folder(lamexp_folder_localappdata));
1050         if(!localAppData.path().isEmpty())
1051         {
1052                 if(!localAppData.exists())
1053                 {
1054                         localAppData.mkpath(".");
1055                 }
1056                 if(localAppData.exists())
1057                 {
1058                         if(!localAppData.entryList(QDir::AllDirs).contains(TEMP_STR, Qt::CaseInsensitive))
1059                         {
1060                                 localAppData.mkdir(TEMP_STR);
1061                         }
1062                         if(localAppData.cd(TEMP_STR) && localAppData.exists())
1063                         {
1064                                 localAppData.mkdir(SUB_FOLDER);
1065                                 if(localAppData.cd(SUB_FOLDER) && localAppData.exists())
1066                                 {
1067                                         QFile testFile(QString("%1/~%2.tmp").arg(localAppData.canonicalPath(), lamexp_rand_str()));
1068                                         if(testFile.open(QIODevice::ReadWrite))
1069                                         {
1070                                                 if(testFile.write(WRITE_TEST_DATA.toLatin1().constData()) >= strlen(WRITE_TEST_DATA.toLatin1().constData()))
1071                                                 {
1072                                                         g_lamexp_temp_folder = localAppData.canonicalPath();
1073                                                 }
1074                                                 testFile.remove();
1075                                         }
1076                                 }
1077                         }
1078                 }
1079                 if(!g_lamexp_temp_folder.isEmpty())
1080                 {
1081                         return g_lamexp_temp_folder;
1082                 }
1083         }
1084
1085         //Failed to create TEMP folder!
1086         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());
1087         return g_lamexp_temp_folder;
1088 }
1089
1090 /*
1091  * Clean folder
1092  */
1093 bool lamexp_clean_folder(const QString &folderPath)
1094 {
1095         QDir tempFolder(folderPath);
1096         QFileInfoList entryList = tempFolder.entryInfoList(QDir::AllEntries | QDir::NoDotAndDotDot);
1097
1098         for(int i = 0; i < entryList.count(); i++)
1099         {
1100                 if(entryList.at(i).isDir())
1101                 {
1102                         lamexp_clean_folder(entryList.at(i).canonicalFilePath());
1103                 }
1104                 else
1105                 {
1106                         for(int j = 0; j < 3; j++)
1107                         {
1108                                 if(lamexp_remove_file(entryList.at(i).canonicalFilePath()))
1109                                 {
1110                                         break;
1111                                 }
1112                         }
1113                 }
1114         }
1115         
1116         tempFolder.rmdir(".");
1117         return !tempFolder.exists();
1118 }
1119
1120 /*
1121  * Register tool
1122  */
1123 void lamexp_register_tool(const QString &toolName, LockedFile *file, unsigned int version)
1124 {
1125         if(g_lamexp_tool_registry.contains(toolName.toLower()))
1126         {
1127                 throw "lamexp_register_tool: Tool is already registered!";
1128         }
1129
1130         g_lamexp_tool_registry.insert(toolName.toLower(), file);
1131         g_lamexp_tool_versions.insert(toolName.toLower(), version);
1132 }
1133
1134 /*
1135  * Check for tool
1136  */
1137 bool lamexp_check_tool(const QString &toolName)
1138 {
1139         return g_lamexp_tool_registry.contains(toolName.toLower());
1140 }
1141
1142 /*
1143  * Lookup tool path
1144  */
1145 const QString lamexp_lookup_tool(const QString &toolName)
1146 {
1147         if(g_lamexp_tool_registry.contains(toolName.toLower()))
1148         {
1149                 return g_lamexp_tool_registry.value(toolName.toLower())->filePath();
1150         }
1151         else
1152         {
1153                 return QString();
1154         }
1155 }
1156
1157 /*
1158  * Lookup tool version
1159  */
1160 unsigned int lamexp_tool_version(const QString &toolName)
1161 {
1162         if(g_lamexp_tool_versions.contains(toolName.toLower()))
1163         {
1164                 return g_lamexp_tool_versions.value(toolName.toLower());
1165         }
1166         else
1167         {
1168                 return UINT_MAX;
1169         }
1170 }
1171
1172 /*
1173  * Version number to human-readable string
1174  */
1175 const QString lamexp_version2string(const QString &pattern, unsigned int version, const QString &defaultText)
1176 {
1177         if(version == UINT_MAX)
1178         {
1179                 return defaultText;
1180         }
1181         
1182         QString result = pattern;
1183         int digits = result.count("?", Qt::CaseInsensitive);
1184         
1185         if(digits < 1)
1186         {
1187                 return result;
1188         }
1189         
1190         int pos = 0;
1191         QString versionStr = QString().sprintf(QString().sprintf("%%0%du", digits).toLatin1().constData(), version);
1192         int index = result.indexOf("?", Qt::CaseInsensitive);
1193         
1194         while(index >= 0 && pos < versionStr.length())
1195         {
1196                 result[index] = versionStr[pos++];
1197                 index = result.indexOf("?", Qt::CaseInsensitive);
1198         }
1199
1200         return result;
1201 }
1202
1203 /*
1204  * Register a new translation
1205  */
1206 bool lamexp_translation_register(const QString &langId, const QString &qmFile, const QString &langName, unsigned int &systemId)
1207 {
1208         if(qmFile.isEmpty() || langName.isEmpty() || systemId < 1)
1209         {
1210                 return false;
1211         }
1212
1213         g_lamexp_translation.files.insert(langId, qmFile);
1214         g_lamexp_translation.names.insert(langId, langName);
1215         g_lamexp_translation.sysid.insert(langId, systemId);
1216
1217         return true;
1218 }
1219
1220 /*
1221  * Get list of all translations
1222  */
1223 QStringList lamexp_query_translations(void)
1224 {
1225         return g_lamexp_translation.files.keys();
1226 }
1227
1228 /*
1229  * Get translation name
1230  */
1231 QString lamexp_translation_name(const QString &langId)
1232 {
1233         return g_lamexp_translation.names.value(langId.toLower(), QString());
1234 }
1235
1236 /*
1237  * Get translation system id
1238  */
1239 unsigned int lamexp_translation_sysid(const QString &langId)
1240 {
1241         return g_lamexp_translation.sysid.value(langId.toLower(), 0);
1242 }
1243
1244 /*
1245  * Install a new translator
1246  */
1247 bool lamexp_install_translator(const QString &langId)
1248 {
1249         bool success = false;
1250
1251         if(langId.isEmpty() || langId.toLower().compare(LAMEXP_DEFAULT_LANGID) == 0)
1252         {
1253                 success = lamexp_install_translator_from_file(QString());
1254         }
1255         else
1256         {
1257                 QString qmFile = g_lamexp_translation.files.value(langId.toLower(), QString());
1258                 if(!qmFile.isEmpty())
1259                 {
1260                         success = lamexp_install_translator_from_file(QString(":/localization/%1").arg(qmFile));
1261                 }
1262                 else
1263                 {
1264                         qWarning("Translation '%s' not available!", langId.toLatin1().constData());
1265                 }
1266         }
1267
1268         return success;
1269 }
1270
1271 /*
1272  * Install a new translator from file
1273  */
1274 bool lamexp_install_translator_from_file(const QString &qmFile)
1275 {
1276         bool success = false;
1277
1278         if(!g_lamexp_currentTranslator)
1279         {
1280                 g_lamexp_currentTranslator = new QTranslator();
1281         }
1282
1283         if(!qmFile.isEmpty())
1284         {
1285                 QString qmPath = QFileInfo(qmFile).canonicalFilePath();
1286                 QApplication::removeTranslator(g_lamexp_currentTranslator);
1287                 success = g_lamexp_currentTranslator->load(qmPath);
1288                 QApplication::installTranslator(g_lamexp_currentTranslator);
1289                 if(!success)
1290                 {
1291                         qWarning("Failed to load translation:\n\"%s\"", qmPath.toLatin1().constData());
1292                 }
1293         }
1294         else
1295         {
1296                 QApplication::removeTranslator(g_lamexp_currentTranslator);
1297                 success = true;
1298         }
1299
1300         return success;
1301 }
1302
1303 /*
1304  * Locate known folder on local system
1305  */
1306 QString lamexp_known_folder(lamexp_known_folder_t folder_id)
1307 {
1308         typedef HRESULT (WINAPI *SHGetKnownFolderPathFun)(__in const GUID &rfid, __in DWORD dwFlags, __in HANDLE hToken, __out PWSTR *ppszPath);
1309         typedef HRESULT (WINAPI *SHGetFolderPathFun)(__in HWND hwndOwner, __in int nFolder, __in HANDLE hToken, __in DWORD dwFlags, __out LPWSTR pszPath);
1310
1311         static const int CSIDL_LOCAL_APPDATA = 0x001c;
1312         static const int CSIDL_PROGRAM_FILES = 0x0026;
1313         static const int CSIDL_SYSTEM_FOLDER = 0x0025;
1314         static const GUID GUID_LOCAL_APPDATA = {0xF1B32785,0x6FBA,0x4FCF,{0x9D,0x55,0x7B,0x8E,0x7F,0x15,0x70,0x91}};
1315         static const GUID GUID_LOCAL_APPDATA_LOW = {0xA520A1A4,0x1780,0x4FF6,{0xBD,0x18,0x16,0x73,0x43,0xC5,0xAF,0x16}};
1316         static const GUID GUID_PROGRAM_FILES = {0x905e63b6,0xc1bf,0x494e,{0xb2,0x9c,0x65,0xb7,0x32,0xd3,0xd2,0x1a}};
1317         static const GUID GUID_SYSTEM_FOLDER = {0x1AC14E77,0x02E7,0x4E5D,{0xB7,0x44,0x2E,0xB1,0xAE,0x51,0x98,0xB7}};
1318
1319         static QLibrary *Kernel32Lib = NULL;
1320         static SHGetKnownFolderPathFun SHGetKnownFolderPathPtr = NULL;
1321         static SHGetFolderPathFun SHGetFolderPathPtr = NULL;
1322
1323         if((!SHGetKnownFolderPathPtr) && (!SHGetFolderPathPtr))
1324         {
1325                 if(!Kernel32Lib) Kernel32Lib = new QLibrary("shell32.dll");
1326                 SHGetKnownFolderPathPtr = (SHGetKnownFolderPathFun) Kernel32Lib->resolve("SHGetKnownFolderPath");
1327                 SHGetFolderPathPtr = (SHGetFolderPathFun) Kernel32Lib->resolve("SHGetFolderPathW");
1328         }
1329
1330         int folderCSIDL = -1;
1331         GUID folderGUID = {0x0000,0x0000,0x0000,{0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00}};
1332
1333         switch(folder_id)
1334         {
1335         case lamexp_folder_localappdata:
1336                 folderCSIDL = CSIDL_LOCAL_APPDATA;
1337                 folderGUID = GUID_LOCAL_APPDATA;
1338                 break;
1339         case lamexp_folder_programfiles:
1340                 folderCSIDL = CSIDL_PROGRAM_FILES;
1341                 folderGUID = GUID_PROGRAM_FILES;
1342                 break;
1343         case lamexp_folder_systemfolder:
1344                 folderCSIDL = CSIDL_SYSTEM_FOLDER;
1345                 folderGUID = GUID_SYSTEM_FOLDER;
1346                 break;
1347         default:
1348                 return QString();
1349                 break;
1350         }
1351
1352         QString folder;
1353
1354         if(SHGetKnownFolderPathPtr)
1355         {
1356                 WCHAR *path = NULL;
1357                 if(SHGetKnownFolderPathPtr(folderGUID, 0x00008000, NULL, &path) == S_OK)
1358                 {
1359                         //MessageBoxW(0, path, L"SHGetKnownFolderPath", MB_TOPMOST);
1360                         QDir folderTemp = QDir(QDir::fromNativeSeparators(QString::fromUtf16(reinterpret_cast<const unsigned short*>(path))));
1361                         if(!folderTemp.exists())
1362                         {
1363                                 folderTemp.mkpath(".");
1364                         }
1365                         if(folderTemp.exists())
1366                         {
1367                                 folder = folderTemp.canonicalPath();
1368                         }
1369                         CoTaskMemFree(path);
1370                 }
1371         }
1372         else if(SHGetFolderPathPtr)
1373         {
1374                 WCHAR *path = new WCHAR[4096];
1375                 if(SHGetFolderPathPtr(NULL, folderCSIDL, NULL, NULL, path) == S_OK)
1376                 {
1377                         //MessageBoxW(0, path, L"SHGetFolderPathW", MB_TOPMOST);
1378                         QDir folderTemp = QDir(QDir::fromNativeSeparators(QString::fromUtf16(reinterpret_cast<const unsigned short*>(path))));
1379                         if(!folderTemp.exists())
1380                         {
1381                                 folderTemp.mkpath(".");
1382                         }
1383                         if(folderTemp.exists())
1384                         {
1385                                 folder = folderTemp.canonicalPath();
1386                         }
1387                 }
1388                 delete [] path;
1389         }
1390
1391         return folder;
1392 }
1393
1394 /*
1395  * Safely remove a file
1396  */
1397 bool lamexp_remove_file(const QString &filename)
1398 {
1399         if(!QFileInfo(filename).exists() || !QFileInfo(filename).isFile())
1400         {
1401                 return true;
1402         }
1403         else
1404         {
1405                 if(!QFile::remove(filename))
1406                 {
1407                         DWORD attributes = GetFileAttributesW(QWCHAR(filename));
1408                         SetFileAttributesW(QWCHAR(filename), (attributes & (~FILE_ATTRIBUTE_READONLY)));
1409                         if(!QFile::remove(filename))
1410                         {
1411                                 qWarning("Could not delete \"%s\"", filename.toLatin1().constData());
1412                                 return false;
1413                         }
1414                         else
1415                         {
1416                                 return true;
1417                         }
1418                 }
1419                 else
1420                 {
1421                         return true;
1422                 }
1423         }
1424 }
1425
1426 /*
1427  * Check if visual themes are enabled (WinXP and later)
1428  */
1429 bool lamexp_themes_enabled(void)
1430 {
1431         typedef int (WINAPI *IsAppThemedFun)(void);
1432         
1433         bool isAppThemed = false;
1434         QLibrary uxTheme(QString("%1/UxTheme.dll").arg(lamexp_known_folder(lamexp_folder_systemfolder)));
1435         IsAppThemedFun IsAppThemedPtr = (IsAppThemedFun) uxTheme.resolve("IsAppThemed");
1436
1437         if(IsAppThemedPtr)
1438         {
1439                 isAppThemed = IsAppThemedPtr();
1440                 if(!isAppThemed)
1441                 {
1442                         qWarning("Theme support is disabled for this process!");
1443                 }
1444         }
1445
1446         return isAppThemed;
1447 }
1448
1449 /*
1450  * Get number of free bytes on disk
1451  */
1452 __int64 lamexp_free_diskspace(const QString &path)
1453 {
1454         ULARGE_INTEGER freeBytesAvailable, totalNumberOfBytes, totalNumberOfFreeBytes;
1455         if(GetDiskFreeSpaceExW(reinterpret_cast<const wchar_t*>(QDir::toNativeSeparators(path).utf16()), &freeBytesAvailable, &totalNumberOfBytes, &totalNumberOfFreeBytes))
1456         {
1457                 return freeBytesAvailable.QuadPart;
1458         }
1459         else
1460         {
1461                 return 0;
1462         }
1463 }
1464
1465 /*
1466  * Shutdown the computer
1467  */
1468 bool lamexp_shutdown_computer(const QString &message, const unsigned long timeout, const bool forceShutdown)
1469 {
1470         HANDLE hToken = NULL;
1471
1472         if(OpenProcessToken(GetCurrentProcess(), TOKEN_ADJUST_PRIVILEGES | TOKEN_QUERY, &hToken))
1473         {
1474                 TOKEN_PRIVILEGES privileges;
1475                 memset(&privileges, 0, sizeof(TOKEN_PRIVILEGES));
1476                 privileges.PrivilegeCount = 1;
1477                 privileges.Privileges[0].Attributes = SE_PRIVILEGE_ENABLED;
1478                 
1479                 if(LookupPrivilegeValue(NULL, SE_SHUTDOWN_NAME, &privileges.Privileges[0].Luid))
1480                 {
1481                         if(AdjustTokenPrivileges(hToken, FALSE, &privileges, NULL, NULL, NULL))
1482                         {
1483                                 const DWORD reason = SHTDN_REASON_MAJOR_APPLICATION | SHTDN_REASON_FLAG_PLANNED;
1484                                 return InitiateSystemShutdownEx(NULL, const_cast<wchar_t*>(QWCHAR(message)), timeout, forceShutdown, FALSE, reason);
1485                         }
1486                 }
1487         }
1488         
1489         return false;
1490 }
1491
1492 /*
1493  * Make a window blink (to draw user's attention)
1494  */
1495 void lamexp_blink_window(QWidget *poWindow, unsigned int count, unsigned int delay)
1496 {
1497         static QMutex blinkMutex;
1498
1499         const double maxOpac = 1.0;
1500         const double minOpac = 0.3;
1501         const double delOpac = 0.1;
1502
1503         if(!blinkMutex.tryLock())
1504         {
1505                 qWarning("Blinking is already in progress, skipping!");
1506                 return;
1507         }
1508         
1509         try
1510         {
1511                 const int steps = static_cast<int>(ceil(maxOpac - minOpac) / delOpac);
1512                 const int sleep = static_cast<int>(floor(static_cast<double>(delay) / static_cast<double>(steps)));
1513                 const double opacity = poWindow->windowOpacity();
1514         
1515                 for(unsigned int i = 0; i < count; i++)
1516                 {
1517                         for(double x = maxOpac; x >= minOpac; x -= delOpac)
1518                         {
1519                                 poWindow->setWindowOpacity(x);
1520                                 QApplication::processEvents();
1521                                 Sleep(sleep);
1522                         }
1523
1524                         for(double x = minOpac; x <= maxOpac; x += delOpac)
1525                         {
1526                                 poWindow->setWindowOpacity(x);
1527                                 QApplication::processEvents();
1528                                 Sleep(sleep);
1529                         }
1530                 }
1531
1532                 poWindow->setWindowOpacity(opacity);
1533                 QApplication::processEvents();
1534                 blinkMutex.unlock();
1535         }
1536         catch (...)
1537         {
1538                 blinkMutex.unlock();
1539                 qWarning("Exception error while blinking!");
1540         }
1541 }
1542
1543 /*
1544  * Remove forbidden characters from a filename
1545  */
1546 const QString lamexp_clean_filename(const QString &str)
1547 {
1548         QString newStr(str);
1549         newStr.replace("\\", "-");
1550         newStr.replace(" / ", ", ");
1551         newStr.replace("/", ",");
1552         newStr.replace(":", "-");
1553         newStr.replace("*", "x");
1554         newStr.replace("?", "");
1555         newStr.replace("<", "[");
1556         newStr.replace(">", "]");
1557         newStr.replace("|", "!");
1558         return newStr;
1559 }
1560
1561 /*
1562  * Remove forbidden characters from a file path
1563  */
1564 const QString lamexp_clean_filepath(const QString &str)
1565 {
1566         QStringList parts = QString(str).replace("\\", "/").split("/");
1567
1568         for(int i = 0; i < parts.count(); i++)
1569         {
1570                 parts[i] = lamexp_clean_filename(parts[i]);
1571         }
1572
1573         return parts.join("/");
1574 }
1575
1576 /*
1577  * Finalization function (final clean-up)
1578  */
1579 void lamexp_finalization(void)
1580 {
1581         //Free all tools
1582         if(!g_lamexp_tool_registry.isEmpty())
1583         {
1584                 QStringList keys = g_lamexp_tool_registry.keys();
1585                 for(int i = 0; i < keys.count(); i++)
1586                 {
1587                         LAMEXP_DELETE(g_lamexp_tool_registry[keys.at(i)]);
1588                 }
1589                 g_lamexp_tool_registry.clear();
1590                 g_lamexp_tool_versions.clear();
1591         }
1592         
1593         //Delete temporary files
1594         if(!g_lamexp_temp_folder.isEmpty())
1595         {
1596                 for(int i = 0; i < 100; i++)
1597                 {
1598                         if(lamexp_clean_folder(g_lamexp_temp_folder))
1599                         {
1600                                 break;
1601                         }
1602                         Sleep(125);
1603                 }
1604                 g_lamexp_temp_folder.clear();
1605         }
1606
1607         //Clear languages
1608         if(g_lamexp_currentTranslator)
1609         {
1610                 QApplication::removeTranslator(g_lamexp_currentTranslator);
1611                 LAMEXP_DELETE(g_lamexp_currentTranslator);
1612         }
1613         g_lamexp_translation.files.clear();
1614         g_lamexp_translation.names.clear();
1615
1616         //Destroy Qt application object
1617         QApplication *application = dynamic_cast<QApplication*>(QApplication::instance());
1618         LAMEXP_DELETE(application);
1619
1620         //Detach from shared memory
1621         if(g_lamexp_ipc_ptr.sharedmem) g_lamexp_ipc_ptr.sharedmem->detach();
1622         LAMEXP_DELETE(g_lamexp_ipc_ptr.sharedmem);
1623         LAMEXP_DELETE(g_lamexp_ipc_ptr.semaphore_read);
1624         LAMEXP_DELETE(g_lamexp_ipc_ptr.semaphore_write);
1625 }
1626
1627 /*
1628  * Initialize debug thread
1629  */
1630 static const HANDLE g_debug_thread = LAMEXP_DEBUG ? NULL : lamexp_debug_thread_init();
1631
1632 /*
1633  * Get number private bytes [debug only]
1634  */
1635 SIZE_T lamexp_dbg_private_bytes(void)
1636 {
1637 #if LAMEXP_DEBUG
1638         PROCESS_MEMORY_COUNTERS_EX memoryCounters;
1639         memoryCounters.cb = sizeof(PROCESS_MEMORY_COUNTERS_EX);
1640         GetProcessMemoryInfo(GetCurrentProcess(), (PPROCESS_MEMORY_COUNTERS) &memoryCounters, sizeof(PROCESS_MEMORY_COUNTERS_EX));
1641         return memoryCounters.PrivateUsage;
1642 #else
1643         throw "Cannot call this function in a non-debug build!";
1644 #endif //LAMEXP_DEBUG
1645 }