OSDN Git Service

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