OSDN Git Service

72e0e76229e289b736d11cbde0f2a16b74d14be6
[lamexp/LameXP.git] / src / Global.cpp
1 ///////////////////////////////////////////////////////////////////////////////
2 // LameXP - Audio Encoder Front-End
3 // Copyright (C) 2004-2013 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 #include <QLibraryInfo>
47 #include <QEvent>
48 #include <QReadWriteLock>
49 #include <QReadLocker>
50 #include <QWriteLocker>
51
52 //LameXP includes
53 #include "Resource.h"
54 #include "Config.h"
55 #include "LockedFile.h"
56
57 //CRT includes
58 #include <iostream>
59 #include <fstream>
60 #include <io.h>
61 #include <fcntl.h>
62 #include <intrin.h>
63 #include <math.h>
64 #include <time.h>
65 #include <process.h>
66
67 //Shell API
68 #include <Shellapi.h>
69
70 //COM includes
71 #include <Objbase.h>
72 #include <PowrProf.h>
73
74 //Process API
75 #include <Psapi.h>
76
77 //Initialize static Qt plugins
78 #ifdef QT_NODLL
79 #if QT_VERSION < QT_VERSION_CHECK(5,0,0)
80 Q_IMPORT_PLUGIN(qico)
81 Q_IMPORT_PLUGIN(qsvg)
82 #else
83 Q_IMPORT_PLUGIN(QWindowsIntegrationPlugin)
84 Q_IMPORT_PLUGIN(QICOPlugin)
85 #endif
86 #endif
87
88 #define LAMEXP_ZERO_MEMORY(X) SecureZeroMemory(&X, sizeof(X))
89
90 //Helper macros
91 #define _LAMEXP_MAKE_STR(STR) #STR
92 #define LAMEXP_MAKE_STR(STR) _LAMEXP_MAKE_STR(STR)
93
94 ///////////////////////////////////////////////////////////////////////////////
95 // TYPES
96 ///////////////////////////////////////////////////////////////////////////////
97
98 static const size_t g_lamexp_ipc_slots = 128;
99
100 typedef struct
101 {
102         unsigned int command;
103         unsigned int reserved_1;
104         unsigned int reserved_2;
105         char parameter[4096];
106 }
107 lamexp_ipc_data_t;
108
109 typedef struct
110 {
111         unsigned int pos_write;
112         unsigned int pos_read;
113         lamexp_ipc_data_t data[g_lamexp_ipc_slots];
114 }
115 lamexp_ipc_t;
116
117 ///////////////////////////////////////////////////////////////////////////////
118 // GLOBAL VARS
119 ///////////////////////////////////////////////////////////////////////////////
120
121 //Build version
122 static const struct
123 {
124         unsigned int ver_major;
125         unsigned int ver_minor;
126         unsigned int ver_build;
127         char *ver_release_name;
128 }
129 g_lamexp_version =
130 {
131         VER_LAMEXP_MAJOR,
132         VER_LAMEXP_MINOR,
133         VER_LAMEXP_BUILD,
134         VER_LAMEXP_RNAME
135 };
136
137 //Build date
138 static QDate g_lamexp_version_date;
139 static const char *g_lamexp_months[] = {"Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"};
140 static const char *g_lamexp_version_raw_date = __DATE__;
141 static const char *g_lamexp_version_raw_time = __TIME__;
142
143 //Console attached flag
144 static bool g_lamexp_console_attached = false;
145
146 //Compiler detection
147 //The following code was borrowed from MPC-HC project: http://mpc-hc.sf.net/
148 #if defined(__INTEL_COMPILER)
149         #if (__INTEL_COMPILER >= 1300)
150                 static const char *g_lamexp_version_compiler = "ICL 13." LAMEXP_MAKE_STR(__INTEL_COMPILER_BUILD_DATE);
151         #elif (__INTEL_COMPILER >= 1200)
152                 static const char *g_lamexp_version_compiler = "ICL 12." LAMEXP_MAKE_STR(__INTEL_COMPILER_BUILD_DATE);
153         #elif (__INTEL_COMPILER >= 1100)
154                 static const char *g_lamexp_version_compiler = "ICL 11.x";
155         #elif (__INTEL_COMPILER >= 1000)
156                 static const char *g_lamexp_version_compiler = "ICL 10.x";
157         #else
158                 #error Compiler is not supported!
159         #endif
160 #elif defined(_MSC_VER)
161         #if (_MSC_VER == 1700)
162                 #if (_MSC_FULL_VER < 170050727)
163                         static const char *g_lamexp_version_compiler = "MSVC 2012-Beta";
164                 #elif (_MSC_FULL_VER < 170051020)
165                         static const char *g_lamexp_version_compiler = "MSVC 2012-RTM";
166                 #elif (_MSC_FULL_VER < 170051106)
167                         static const char *g_lamexp_version_compiler = "MSVC 2012-U1 CTP";
168                 #elif (_MSC_FULL_VER < 170060315)
169                         static const char *g_lamexp_version_compiler = "MSVC 2012-U1";
170                 #elif (_MSC_FULL_VER == 170060315)
171                         static const char *g_lamexp_version_compiler = "MSVC 2012-U2";
172                 #else
173                         #error Compiler version is not supported yet!
174                 #endif
175         #elif (_MSC_VER == 1600)
176                 #if (_MSC_FULL_VER < 160040219)
177                         static const char *g_lamexp_version_compiler = "MSVC 2010-RTM";
178                 #elif (_MSC_FULL_VER == 160040219)
179                         static const char *g_lamexp_version_compiler = "MSVC 2010-SP1";
180                 #else
181                         #error Compiler version is not supported yet!
182                 #endif
183         #elif (_MSC_VER == 1500)
184                 #if (_MSC_FULL_VER >= 150030729)
185                         static const char *g_lamexp_version_compiler = "MSVC 2008-SP1";
186                 #else
187                         static const char *g_lamexp_version_compiler = "MSVC 2008";
188                 #endif
189         #else
190                 #error Compiler is not supported!
191         #endif
192
193         // Note: /arch:SSE and /arch:SSE2 are only available for the x86 platform
194         #if !defined(_M_X64) && defined(_M_IX86_FP)
195                 #if (_M_IX86_FP == 1)
196                         LAMEXP_COMPILER_WARNING("SSE instruction set is enabled!")
197                 #elif (_M_IX86_FP == 2)
198                         LAMEXP_COMPILER_WARNING("SSE2 instruction set is enabled!")
199                 #endif
200         #endif
201 #else
202         #error Compiler is not supported!
203 #endif
204
205 //Architecture detection
206 #if defined(_M_X64)
207         static const char *g_lamexp_version_arch = "x64";
208 #elif defined(_M_IX86)
209         static const char *g_lamexp_version_arch = "x86";
210 #else
211         #error Architecture is not supported!
212 #endif
213
214 //Official web-site URL
215 static const char *g_lamexp_website_url = "http://lamexp.sourceforge.net/";
216 static const char *g_lamexp_support_url = "http://forum.doom9.org/showthread.php?t=157726";
217 static const char *g_lamexp_mulders_url = "http://muldersoft.com/";
218
219 //Tool versions (expected versions!)
220 static const unsigned int g_lamexp_toolver_neroaac = VER_LAMEXP_TOOL_NEROAAC;
221 static const unsigned int g_lamexp_toolver_fhgaacenc = VER_LAMEXP_TOOL_FHGAACENC;
222 static const unsigned int g_lamexp_toolver_qaacenc = VER_LAMEXP_TOOL_QAAC;
223 static const unsigned int g_lamexp_toolver_coreaudio = VER_LAMEXP_TOOL_COREAUDIO;
224
225 //Special folders
226 static struct
227 {
228         QString *temp;
229         QMap<size_t, QString> *knownFolders;
230         QReadWriteLock lock;
231 }
232 g_lamexp_folder;
233
234 //Tools
235 static struct
236 {
237         QMap<QString, LockedFile*> *registry;
238         QMap<QString, unsigned int> *versions;
239         QMap<QString, QString> *tags;
240         QReadWriteLock lock;
241 }
242 g_lamexp_tools;
243
244 //Languages
245 static struct
246 {
247         QMap<QString, QString> *files;
248         QMap<QString, QString> *names;
249         QMap<QString, unsigned int> *sysid;
250         QMap<QString, unsigned int> *cntry;
251         QReadWriteLock lock;
252 }
253 g_lamexp_translation;
254
255 //Translator
256 static struct
257 {
258         QTranslator *instance;
259         QReadWriteLock lock;
260 }
261 g_lamexp_currentTranslator;
262
263 //CLI Arguments
264 static struct
265 {
266         QStringList *list;
267         QReadWriteLock lock;
268 }
269 g_lamexp_argv;
270
271 //OS Version
272 static struct
273 {
274         bool bInitialized;
275         lamexp_os_version_t version;
276         QReadWriteLock lock;
277 }
278 g_lamexp_os_version;
279
280 //Portable Mode
281 static struct
282 {
283         bool bInitialized;
284         bool bPortableModeEnabled;
285         QReadWriteLock lock;
286 }
287 g_lamexp_portable;
288
289 //Win32 Theme support
290 static struct
291 {
292         bool bInitialized;
293         bool bThemesEnabled;
294         QReadWriteLock lock;
295 }
296 g_lamexp_themes_enabled;
297
298 //Shared memory
299 static const struct
300 {
301         char *sharedmem;
302         char *semaphore_read;
303         char *semaphore_read_mutex;
304         char *semaphore_write;
305         char *semaphore_write_mutex;
306 }
307 g_lamexp_ipc_uuid =
308 {
309         "{21A68A42-6923-43bb-9CF6-64BF151942EE}",
310         "{7A605549-F58C-4d78-B4E5-06EFC34F405B}",
311         "{60AA8D04-F6B8-497d-81EB-0F600F4A65B5}",
312         "{726061D5-1615-4B82-871C-75FD93458E46}",
313         "{1A616023-AA6A-4519-8AF3-F7736E899977}"
314 };
315 static struct
316 {
317         QSharedMemory *sharedmem;
318         QSystemSemaphore *semaphore_read;
319         QSystemSemaphore *semaphore_read_mutex;
320         QSystemSemaphore *semaphore_write;
321         QSystemSemaphore *semaphore_write_mutex;
322         QReadWriteLock lock;
323 }
324 g_lamexp_ipc_ptr;
325
326 //Image formats
327 static const char *g_lamexp_imageformats[] = {"bmp", "png", "jpg", "gif", "ico", "xpm", NULL}; //"svg"
328
329 //Global locks
330 static QMutex g_lamexp_message_mutex;
331
332 //Main thread ID
333 static const DWORD g_main_thread_id = GetCurrentThreadId();
334
335 //Log file
336 static FILE *g_lamexp_log_file = NULL;
337
338 //Localization
339 const char* LAMEXP_DEFAULT_LANGID = "en";
340 const char* LAMEXP_DEFAULT_TRANSLATION = "LameXP_EN.qm";
341
342 ///////////////////////////////////////////////////////////////////////////////
343 // GLOBAL FUNCTIONS
344 ///////////////////////////////////////////////////////////////////////////////
345
346 /*
347  * Version getters
348  */
349 unsigned int lamexp_version_major(void) { return g_lamexp_version.ver_major; }
350 unsigned int lamexp_version_minor(void) { return g_lamexp_version.ver_minor; }
351 unsigned int lamexp_version_build(void) { return g_lamexp_version.ver_build; }
352 const char *lamexp_version_release(void) { return g_lamexp_version.ver_release_name; }
353 const char *lamexp_version_time(void) { return g_lamexp_version_raw_time; }
354 const char *lamexp_version_compiler(void) { return g_lamexp_version_compiler; }
355 const char *lamexp_version_arch(void) { return g_lamexp_version_arch; }
356 unsigned int lamexp_toolver_neroaac(void) { return g_lamexp_toolver_neroaac; }
357 unsigned int lamexp_toolver_fhgaacenc(void) { return g_lamexp_toolver_fhgaacenc; }
358 unsigned int lamexp_toolver_qaacenc(void) { return g_lamexp_toolver_qaacenc; }
359 unsigned int lamexp_toolver_coreaudio(void) { return g_lamexp_toolver_coreaudio; }
360
361 /*
362  * URL getters
363  */
364 const char *lamexp_website_url(void) { return g_lamexp_website_url; }
365 const char *lamexp_mulders_url(void) { return g_lamexp_mulders_url; }
366 const char *lamexp_support_url(void) { return g_lamexp_support_url; }
367
368 /*
369  * Check for Demo (pre-release) version
370  */
371 bool lamexp_version_demo(void)
372 {
373         char buffer[128];
374         bool releaseVersion = false;
375         if(!strncpy_s(buffer, 128, g_lamexp_version.ver_release_name, _TRUNCATE))
376         {
377                 char *context, *prefix = strtok_s(buffer, "-,; ", &context);
378                 if(prefix)
379                 {
380                         releaseVersion = (!_stricmp(prefix, "Final")) || (!_stricmp(prefix, "Hotfix"));
381                 }
382         }
383         return LAMEXP_DEBUG || (!releaseVersion);
384 }
385
386 /*
387  * Calculate expiration date
388  */
389 QDate lamexp_version_expires(void)
390 {
391         return lamexp_version_date().addDays(LAMEXP_DEBUG ? 7 : 30);
392 }
393
394 /*
395  * Get build date date
396  */
397 const QDate &lamexp_version_date(void)
398 {
399         if(!g_lamexp_version_date.isValid())
400         {
401                 int date[3] = {0, 0, 0}; char temp[12] = {'\0'};
402                 strncpy_s(temp, 12, g_lamexp_version_raw_date, _TRUNCATE);
403
404                 if(strlen(temp) == 11)
405                 {
406                         temp[3] = temp[6] = '\0';
407                         date[2] = atoi(&temp[4]);
408                         date[0] = atoi(&temp[7]);
409                         
410                         for(int j = 0; j < 12; j++)
411                         {
412                                 if(!_strcmpi(&temp[0], g_lamexp_months[j]))
413                                 {
414                                         date[1] = j+1;
415                                         break;
416                                 }
417                         }
418
419                         g_lamexp_version_date = QDate(date[0], date[1], date[2]);
420                 }
421
422                 if(!g_lamexp_version_date.isValid())
423                 {
424                         qFatal("Internal error: Date format could not be recognized!");
425                 }
426         }
427
428         return g_lamexp_version_date;
429 }
430
431 /*
432  * Get the native operating system version
433  */
434 const lamexp_os_version_t *lamexp_get_os_version(void)
435 {
436         QReadLocker readLock(&g_lamexp_os_version.lock);
437
438         //Already initialized?
439         if(g_lamexp_os_version.bInitialized)
440         {
441                 return &g_lamexp_os_version.version;
442         }
443         
444         readLock.unlock();
445         QWriteLocker writeLock(&g_lamexp_os_version.lock);
446
447         //Detect OS version
448         if(!g_lamexp_os_version.bInitialized)
449         {
450                 OSVERSIONINFO osVerInfo;
451                 memset(&osVerInfo, 0, sizeof(OSVERSIONINFO));
452                 osVerInfo.dwOSVersionInfoSize = sizeof(OSVERSIONINFO);
453         
454                 if(GetVersionEx(&osVerInfo) == TRUE)
455                 {
456                         if(osVerInfo.dwPlatformId == VER_PLATFORM_WIN32_NT)
457                         {
458                                 g_lamexp_os_version.version.versionMajor = osVerInfo.dwMajorVersion;
459                                 g_lamexp_os_version.version.versionMinor = osVerInfo.dwMinorVersion;
460                         }
461                         else
462                         {
463                                 qWarning("lamexp_get_os_version: Not running under Windows NT, this is not supposed to happen!");
464                                 g_lamexp_os_version.version.versionMajor = 0;
465                                 g_lamexp_os_version.version.versionMinor = 0;
466                         }
467                 }
468                 else
469                 {
470                         throw "GetVersionEx() has failed. This is not supposed to happen!";
471                 }
472                 
473                 g_lamexp_os_version.bInitialized = true;
474         }
475
476         return  &g_lamexp_os_version.version;
477 }
478
479 /*
480  * Check if we are running under wine
481  */
482 bool lamexp_detect_wine(void)
483 {
484         static bool isWine = false;
485         static bool isWine_initialized = false;
486
487         if(!isWine_initialized)
488         {
489                 QLibrary ntdll("ntdll.dll");
490                 if(ntdll.load())
491                 {
492                         if(ntdll.resolve("wine_nt_to_unix_file_name") != NULL) isWine = true;
493                         if(ntdll.resolve("wine_get_version") != NULL) isWine = true;
494                         ntdll.unload();
495                 }
496                 isWine_initialized = true;
497         }
498
499         return isWine;
500 }
501
502 /*
503  * Global exception handler
504  */
505 LONG WINAPI lamexp_exception_handler(__in struct _EXCEPTION_POINTERS *ExceptionInfo)
506 {
507         lamexp_fatal_exit(L"Unhandeled exception handler invoked, application will exit!");
508         return LONG_MAX;
509 }
510
511 /*
512  * Invalid parameters handler
513  */
514 void lamexp_invalid_param_handler(const wchar_t* exp, const wchar_t* fun, const wchar_t* fil, unsigned int, uintptr_t)
515 {
516         lamexp_fatal_exit(L"Invalid parameter handler invoked, application will exit!");
517 }
518
519 /*
520  * Change console text color
521  */
522 static void lamexp_console_color(FILE* file, WORD attributes)
523 {
524         const HANDLE hConsole = (HANDLE)(_get_osfhandle(_fileno(file)));
525         if((hConsole != NULL) && (hConsole != INVALID_HANDLE_VALUE))
526         {
527                 SetConsoleTextAttribute(hConsole, attributes);
528         }
529 }
530
531 /*
532  * Qt message handler
533  */
534 void lamexp_message_handler(QtMsgType type, const char *msg)
535 {
536         static const char *GURU_MEDITATION = "\n\nGURU MEDITATION !!!\n\n";
537
538         if(msg == NULL) return;
539
540         QMutexLocker lock(&g_lamexp_message_mutex);
541
542         if(g_lamexp_log_file)
543         {
544                 static char prefix[] = "DWCF";
545                 int index = qBound(0, static_cast<int>(type), 3);
546                 unsigned int timestamp = static_cast<unsigned int>(_time64(NULL) % 3600I64);
547                 QString str = QString::fromUtf8(msg).trimmed().replace('\n', '\t');
548                 fprintf(g_lamexp_log_file, "[%c][%04u] %s\r\n", prefix[index], timestamp, str.toUtf8().constData());
549                 fflush(g_lamexp_log_file);
550         }
551
552         if(g_lamexp_console_attached)
553         {
554                 UINT oldOutputCP = GetConsoleOutputCP();
555                 if(oldOutputCP != CP_UTF8) SetConsoleOutputCP(CP_UTF8);
556
557                 switch(type)
558                 {
559                 case QtCriticalMsg:
560                 case QtFatalMsg:
561                         fflush(stdout);
562                         fflush(stderr);
563                         lamexp_console_color(stderr, FOREGROUND_RED | FOREGROUND_INTENSITY);
564                         fprintf(stderr, GURU_MEDITATION);
565                         fprintf(stderr, "%s\n", msg);
566                         fflush(stderr);
567                         break;
568                 case QtWarningMsg:
569                         lamexp_console_color(stderr, FOREGROUND_GREEN | FOREGROUND_RED | FOREGROUND_INTENSITY);
570                         fprintf(stderr, "%s\n", msg);
571                         fflush(stderr);
572                         break;
573                 default:
574                         lamexp_console_color(stderr, FOREGROUND_BLUE | FOREGROUND_GREEN | FOREGROUND_RED | FOREGROUND_INTENSITY);
575                         fprintf(stderr, "%s\n", msg);
576                         fflush(stderr);
577                         break;
578                 }
579         
580                 lamexp_console_color(stderr, FOREGROUND_BLUE | FOREGROUND_GREEN | FOREGROUND_RED);
581                 if(oldOutputCP != CP_UTF8) SetConsoleOutputCP(oldOutputCP);
582         }
583         else
584         {
585                 QString temp("[LameXP][%1] %2");
586                 
587                 switch(type)
588                 {
589                 case QtCriticalMsg:
590                 case QtFatalMsg:
591                         temp = temp.arg("C", QString::fromUtf8(msg));
592                         break;
593                 case QtWarningMsg:
594                         temp = temp.arg("W", QString::fromUtf8(msg));
595                         break;
596                 default:
597                         temp = temp.arg("I", QString::fromUtf8(msg));
598                         break;
599                 }
600
601                 temp.replace("\n", "\t").append("\n");
602                 OutputDebugStringA(temp.toLatin1().constData());
603         }
604
605         if((type == QtCriticalMsg) || (type == QtFatalMsg))
606         {
607                 lock.unlock();
608                 lamexp_fatal_exit(L"The application has encountered a critical error and will exit now!", QWCHAR(QString::fromUtf8(msg)));
609         }
610 }
611
612 /*
613  * Initialize the console
614  */
615 void lamexp_init_console(const QStringList &argv)
616 {
617         bool enableConsole = lamexp_version_demo();
618
619         if(_environ)
620         {
621                 wchar_t *logfile = NULL;
622                 size_t logfile_len = 0;
623                 if(!_wdupenv_s(&logfile, &logfile_len, L"LAMEXP_LOGFILE"))
624                 {
625                         if(logfile && (logfile_len > 0))
626                         {
627                                 FILE *temp = NULL;
628                                 if(!_wfopen_s(&temp, logfile, L"wb"))
629                                 {
630                                         fprintf(temp, "%c%c%c", 0xEF, 0xBB, 0xBF);
631                                         g_lamexp_log_file = temp;
632                                 }
633                                 free(logfile);
634                         }
635                 }
636         }
637
638         if(!LAMEXP_DEBUG)
639         {
640                 for(int i = 0; i < argv.count(); i++)
641                 {
642                         if(!argv.at(i).compare("--console", Qt::CaseInsensitive))
643                         {
644                                 enableConsole = true;
645                         }
646                         else if(!argv.at(i).compare("--no-console", Qt::CaseInsensitive))
647                         {
648                                 enableConsole = false;
649                         }
650                 }
651         }
652
653         if(enableConsole)
654         {
655                 if(!g_lamexp_console_attached)
656                 {
657                         if(AllocConsole() != FALSE)
658                         {
659                                 SetConsoleCtrlHandler(NULL, TRUE);
660                                 SetConsoleTitle(L"LameXP - Audio Encoder Front-End | Debug Console");
661                                 SetConsoleOutputCP(CP_UTF8);
662                                 g_lamexp_console_attached = true;
663                         }
664                 }
665                 
666                 if(g_lamexp_console_attached)
667                 {
668                         //-------------------------------------------------------------------
669                         //See: http://support.microsoft.com/default.aspx?scid=kb;en-us;105305
670                         //-------------------------------------------------------------------
671                         const int flags = _O_WRONLY | _O_U8TEXT;
672                         int hCrtStdOut = _open_osfhandle((intptr_t) GetStdHandle(STD_OUTPUT_HANDLE), flags);
673                         int hCrtStdErr = _open_osfhandle((intptr_t) GetStdHandle(STD_ERROR_HANDLE),  flags);
674                         FILE *hfStdOut = (hCrtStdOut >= 0) ? _fdopen(hCrtStdOut, "wb") : NULL;
675                         FILE *hfStdErr = (hCrtStdErr >= 0) ? _fdopen(hCrtStdErr, "wb") : NULL;
676                         if(hfStdOut) { *stdout = *hfStdOut; std::cout.rdbuf(new std::filebuf(hfStdOut)); }
677                         if(hfStdErr) { *stderr = *hfStdErr; std::cerr.rdbuf(new std::filebuf(hfStdErr)); }
678                 }
679
680                 HWND hwndConsole = GetConsoleWindow();
681
682                 if((hwndConsole != NULL) && (hwndConsole != INVALID_HANDLE_VALUE))
683                 {
684                         HMENU hMenu = GetSystemMenu(hwndConsole, 0);
685                         EnableMenuItem(hMenu, SC_CLOSE, MF_BYCOMMAND | MF_GRAYED);
686                         RemoveMenu(hMenu, SC_CLOSE, MF_BYCOMMAND);
687
688                         SetWindowPos(hwndConsole, HWND_TOP, 0, 0, 0, 0, SWP_NOMOVE|SWP_NOSIZE|SWP_NOZORDER|SWP_FRAMECHANGED);
689                         SetWindowLong(hwndConsole, GWL_STYLE, GetWindowLong(hwndConsole, GWL_STYLE) & (~WS_MAXIMIZEBOX) & (~WS_MINIMIZEBOX));
690                         SetWindowPos(hwndConsole, HWND_TOP, 0, 0, 0, 0, SWP_NOMOVE|SWP_NOSIZE|SWP_NOZORDER|SWP_FRAMECHANGED);
691                 }
692         }
693 }
694
695 /*
696  * Detect CPU features
697  */
698 lamexp_cpu_t lamexp_detect_cpu_features(const QStringList &argv)
699 {
700         typedef BOOL (WINAPI *IsWow64ProcessFun)(__in HANDLE hProcess, __out PBOOL Wow64Process);
701         typedef VOID (WINAPI *GetNativeSystemInfoFun)(__out LPSYSTEM_INFO lpSystemInfo);
702         
703         static IsWow64ProcessFun IsWow64ProcessPtr = NULL;
704         static GetNativeSystemInfoFun GetNativeSystemInfoPtr = NULL;
705
706         lamexp_cpu_t features;
707         SYSTEM_INFO systemInfo;
708         int CPUInfo[4] = {-1};
709         char CPUIdentificationString[0x40];
710         char CPUBrandString[0x40];
711
712         memset(&features, 0, sizeof(lamexp_cpu_t));
713         memset(&systemInfo, 0, sizeof(SYSTEM_INFO));
714         memset(CPUIdentificationString, 0, sizeof(CPUIdentificationString));
715         memset(CPUBrandString, 0, sizeof(CPUBrandString));
716         
717         __cpuid(CPUInfo, 0);
718         memcpy(CPUIdentificationString, &CPUInfo[1], sizeof(int));
719         memcpy(CPUIdentificationString + 4, &CPUInfo[3], sizeof(int));
720         memcpy(CPUIdentificationString + 8, &CPUInfo[2], sizeof(int));
721         features.intel = (_stricmp(CPUIdentificationString, "GenuineIntel") == 0);
722         strncpy_s(features.vendor, 0x40, CPUIdentificationString, _TRUNCATE);
723
724         if(CPUInfo[0] >= 1)
725         {
726                 __cpuid(CPUInfo, 1);
727                 features.mmx = (CPUInfo[3] & 0x800000) || false;
728                 features.sse = (CPUInfo[3] & 0x2000000) || false;
729                 features.sse2 = (CPUInfo[3] & 0x4000000) || false;
730                 features.ssse3 = (CPUInfo[2] & 0x200) || false;
731                 features.sse3 = (CPUInfo[2] & 0x1) || false;
732                 features.ssse3 = (CPUInfo[2] & 0x200) || false;
733                 features.stepping = CPUInfo[0] & 0xf;
734                 features.model = ((CPUInfo[0] >> 4) & 0xf) + (((CPUInfo[0] >> 16) & 0xf) << 4);
735                 features.family = ((CPUInfo[0] >> 8) & 0xf) + ((CPUInfo[0] >> 20) & 0xff);
736         }
737
738         __cpuid(CPUInfo, 0x80000000);
739         int nExIds = qMax<int>(qMin<int>(CPUInfo[0], 0x80000004), 0x80000000);
740
741         for(int i = 0x80000002; i <= nExIds; ++i)
742         {
743                 __cpuid(CPUInfo, i);
744                 switch(i)
745                 {
746                 case 0x80000002:
747                         memcpy(CPUBrandString, CPUInfo, sizeof(CPUInfo));
748                         break;
749                 case 0x80000003:
750                         memcpy(CPUBrandString + 16, CPUInfo, sizeof(CPUInfo));
751                         break;
752                 case 0x80000004:
753                         memcpy(CPUBrandString + 32, CPUInfo, sizeof(CPUInfo));
754                         break;
755                 }
756         }
757
758         strncpy_s(features.brand, 0x40, CPUBrandString, _TRUNCATE);
759
760         if(strlen(features.brand) < 1) strncpy_s(features.brand, 0x40, "Unknown", _TRUNCATE);
761         if(strlen(features.vendor) < 1) strncpy_s(features.vendor, 0x40, "Unknown", _TRUNCATE);
762
763 #if !defined(_M_X64 ) && !defined(_M_IA64)
764         if(!IsWow64ProcessPtr || !GetNativeSystemInfoPtr)
765         {
766                 QLibrary Kernel32Lib("kernel32.dll");
767                 IsWow64ProcessPtr = (IsWow64ProcessFun) Kernel32Lib.resolve("IsWow64Process");
768                 GetNativeSystemInfoPtr = (GetNativeSystemInfoFun) Kernel32Lib.resolve("GetNativeSystemInfo");
769         }
770         if(IsWow64ProcessPtr)
771         {
772                 BOOL x64 = FALSE;
773                 if(IsWow64ProcessPtr(GetCurrentProcess(), &x64))
774                 {
775                         features.x64 = x64;
776                 }
777         }
778         if(GetNativeSystemInfoPtr)
779         {
780                 GetNativeSystemInfoPtr(&systemInfo);
781         }
782         else
783         {
784                 GetSystemInfo(&systemInfo);
785         }
786         features.count = qBound(1UL, systemInfo.dwNumberOfProcessors, 64UL);
787 #else
788         GetNativeSystemInfo(&systemInfo);
789         features.count = systemInfo.dwNumberOfProcessors;
790         features.x64 = true;
791 #endif
792
793         if(argv.count() > 0)
794         {
795                 bool flag = false;
796                 for(int i = 0; i < argv.count(); i++)
797                 {
798                         if(!argv[i].compare("--force-cpu-no-64bit", Qt::CaseInsensitive)) { flag = true; features.x64 = false; }
799                         if(!argv[i].compare("--force-cpu-no-sse", Qt::CaseInsensitive)) { flag = true; features.sse = features.sse2 = features.sse3 = features.ssse3 = false; }
800                         if(!argv[i].compare("--force-cpu-no-intel", Qt::CaseInsensitive)) { flag = true; features.intel = false; }
801                 }
802                 if(flag) qWarning("CPU flags overwritten by user-defined parameters. Take care!\n");
803         }
804
805         return features;
806 }
807
808 /*
809  * Check for debugger (detect routine)
810  */
811 static __forceinline bool lamexp_check_for_debugger(void)
812 {
813         if(IsDebuggerPresent())
814         {
815                 return true;
816         }
817         
818         __try
819         {
820                 CloseHandle((HANDLE) 0x7FFFFFFF);
821         }
822         __except(EXCEPTION_EXECUTE_HANDLER)
823         {
824                 return true;
825         }
826
827         __try 
828         {
829                 DebugBreak();
830         }
831         __except(EXCEPTION_EXECUTE_HANDLER) 
832         {
833                 return false;
834         }
835         
836         return true;
837 }
838
839 /*
840  * Check for debugger (thread proc)
841  */
842 static unsigned int __stdcall lamexp_debug_thread_proc(LPVOID lpParameter)
843 {
844         while(!lamexp_check_for_debugger())
845         {
846                 Sleep(250);
847         }
848         lamexp_fatal_exit(L"Not a debug build. Please unload debugger and try again!");
849         return 666;
850 }
851
852 /*
853  * Check for debugger (startup routine)
854  */
855 static HANDLE lamexp_debug_thread_init(void)
856 {
857         if(lamexp_check_for_debugger())
858         {
859                 lamexp_fatal_exit(L"Not a debug build. Please unload debugger and try again!");
860         }
861
862         return (HANDLE) _beginthreadex(NULL, 0, lamexp_debug_thread_proc, NULL, 0, NULL);
863 }
864
865 /*
866  * Check for compatibility mode
867  */
868 static bool lamexp_check_compatibility_mode(const char *exportName, const QString &executableName)
869 {
870         QLibrary kernel32("kernel32.dll");
871
872         if((exportName != NULL) && kernel32.load())
873         {
874                 if(kernel32.resolve(exportName) != NULL)
875                 {
876                         qWarning("Function '%s' exported from 'kernel32.dll' -> Windows compatibility mode!", exportName);
877                         qFatal("%s", QApplication::tr("Executable '%1' doesn't support Windows compatibility mode.").arg(executableName).toLatin1().constData());
878                         return false;
879                 }
880         }
881
882         return true;
883 }
884
885 /*
886  * Computus according to H. Lichtenberg
887  */
888 static bool lamexp_computus(const QDate &date)
889 {
890         int X = date.year();
891         int A = X % 19;
892         int K = X / 100;
893         int M = 15 + (3*K + 3) / 4 - (8*K + 13) / 25;
894         int D = (19*A + M) % 30;
895         int S = 2 - (3*K + 3) / 4;
896         int R = D / 29 + (D / 28 - D / 29) * (A / 11);
897         int OG = 21 + D - R;
898         int SZ = 7 - (X + X / 4 + S) % 7;
899         int OE = 7 - (OG - SZ) % 7;
900         int OS = (OG + OE);
901
902         if(OS > 31)
903         {
904                 return (date.month() == 4) && (date.day() == (OS - 31));
905         }
906         else
907         {
908                 return (date.month() == 3) && (date.day() == OS);
909         }
910 }
911
912 /*
913  * Check for Thanksgiving
914  */
915 static bool lamexp_thanksgiving(const QDate &date)
916 {
917         int day = 0;
918
919         switch(QDate(date.year(), 11, 1).dayOfWeek())
920         {
921                 case 1: day = 25; break; 
922                 case 2: day = 24; break; 
923                 case 3: day = 23; break; 
924                 case 4: day = 22; break; 
925                 case 5: day = 28; break; 
926                 case 6: day = 27; break; 
927                 case 7: day = 26; break;
928         }
929
930         return (date.month() == 11) && (date.day() == day);
931 }
932
933 /*
934  * Initialize app icon
935  */
936 QIcon lamexp_app_icon(const QDate *date, const QTime *time)
937 {
938         QDate currentDate = (date) ? QDate(*date) : QDate::currentDate();
939         QTime currentTime = (time) ? QTime(*time) : QTime::currentTime();
940         
941         if(lamexp_thanksgiving(currentDate))
942         {
943                 return QIcon(":/MainIcon6.png");
944         }
945         else if(((currentDate.month() == 12) && (currentDate.day() == 31) && (currentTime.hour() >= 20)) || ((currentDate.month() == 1) && (currentDate.day() == 1)  && (currentTime.hour() <= 19)))
946         {
947                 return QIcon(":/MainIcon5.png");
948         }
949         else if(((currentDate.month() == 10) && (currentDate.day() == 31) && (currentTime.hour() >= 12)) || ((currentDate.month() == 11) && (currentDate.day() == 1)  && (currentTime.hour() <= 11)))
950         {
951                 return QIcon(":/MainIcon4.png");
952         }
953         else if((currentDate.month() == 12) && (currentDate.day() >= 24) && (currentDate.day() <= 26))
954         {
955                 return QIcon(":/MainIcon3.png");
956         }
957         else if(lamexp_computus(currentDate))
958         {
959                 return QIcon(":/MainIcon2.png");
960         }
961         else
962         {
963                 return QIcon(":/MainIcon1.png");
964         }
965 }
966
967 /*
968  * Broadcast event to all windows
969  */
970 static bool lamexp_broadcast(int eventType, bool onlyToVisible)
971 {
972         if(QApplication *app = dynamic_cast<QApplication*>(QApplication::instance()))
973         {
974                 qDebug("Broadcasting %d", eventType);
975                 
976                 bool allOk = true;
977                 QEvent poEvent(static_cast<QEvent::Type>(eventType));
978                 QWidgetList list = app->topLevelWidgets();
979
980                 while(!list.isEmpty())
981                 {
982                         QWidget *widget = list.takeFirst();
983                         if(!onlyToVisible || widget->isVisible())
984                         {
985                                 if(!app->sendEvent(widget, &poEvent))
986                                 {
987                                         allOk = false;
988                                 }
989                         }
990                 }
991
992                 qDebug("Broadcast %d done (%s)", eventType, (allOk ? "OK" : "Stopped"));
993                 return allOk;
994         }
995         else
996         {
997                 qWarning("Broadcast failed, could not get QApplication instance!");
998                 return false;
999         }
1000 }
1001
1002 /*
1003  * Qt event filter
1004  */
1005 static bool lamexp_event_filter(void *message, long *result)
1006 {
1007         if((!(LAMEXP_DEBUG)) && lamexp_check_for_debugger())
1008         {
1009                 lamexp_fatal_exit(L"Not a debug build. Please unload debugger and try again!");
1010         }
1011         
1012         switch(reinterpret_cast<MSG*>(message)->message)
1013         {
1014         case WM_QUERYENDSESSION:
1015                 qWarning("WM_QUERYENDSESSION message received!");
1016                 *result = lamexp_broadcast(lamexp_event_queryendsession, false) ? TRUE : FALSE;
1017                 return true;
1018         case WM_ENDSESSION:
1019                 qWarning("WM_ENDSESSION message received!");
1020                 if(reinterpret_cast<MSG*>(message)->wParam == TRUE)
1021                 {
1022                         lamexp_broadcast(lamexp_event_endsession, false);
1023                         if(QApplication *app = reinterpret_cast<QApplication*>(QApplication::instance()))
1024                         {
1025                                 app->closeAllWindows();
1026                                 app->quit();
1027                         }
1028                         lamexp_finalization();
1029                         exit(1);
1030                 }
1031                 *result = 0;
1032                 return true;
1033         default:
1034                 /*ignore this message and let Qt handle it*/
1035                 return false;
1036         }
1037 }
1038
1039 /*
1040  * Check for process elevation
1041  */
1042 static bool lamexp_check_elevation(void)
1043 {
1044         typedef enum { lamexp_token_elevationType_class = 18, lamexp_token_elevation_class = 20 } LAMEXP_TOKEN_INFORMATION_CLASS;
1045         typedef enum { lamexp_elevationType_default = 1, lamexp_elevationType_full, lamexp_elevationType_limited } LAMEXP_TOKEN_ELEVATION_TYPE;
1046
1047         HANDLE hToken = NULL;
1048         bool bIsProcessElevated = false;
1049         
1050         if(OpenProcessToken(GetCurrentProcess(), TOKEN_QUERY, &hToken))
1051         {
1052                 LAMEXP_TOKEN_ELEVATION_TYPE tokenElevationType;
1053                 DWORD returnLength;
1054                 if(GetTokenInformation(hToken, (TOKEN_INFORMATION_CLASS) lamexp_token_elevationType_class, &tokenElevationType, sizeof(LAMEXP_TOKEN_ELEVATION_TYPE), &returnLength))
1055                 {
1056                         if(returnLength == sizeof(LAMEXP_TOKEN_ELEVATION_TYPE))
1057                         {
1058                                 switch(tokenElevationType)
1059                                 {
1060                                 case lamexp_elevationType_default:
1061                                         qDebug("Process token elevation type: Default -> UAC is disabled.\n");
1062                                         break;
1063                                 case lamexp_elevationType_full:
1064                                         qWarning("Process token elevation type: Full -> potential security risk!\n");
1065                                         bIsProcessElevated = true;
1066                                         break;
1067                                 case lamexp_elevationType_limited:
1068                                         qDebug("Process token elevation type: Limited -> not elevated.\n");
1069                                         break;
1070                                 }
1071                         }
1072                 }
1073                 CloseHandle(hToken);
1074         }
1075         else
1076         {
1077                 qWarning("Failed to open process token!");
1078         }
1079
1080         return !bIsProcessElevated;
1081 }
1082
1083 /*
1084  * Initialize Qt framework
1085  */
1086 bool lamexp_init_qt(int argc, char* argv[])
1087 {
1088         static bool qt_initialized = false;
1089         typedef BOOL (WINAPI *SetDllDirectoryProc)(WCHAR *lpPathName);
1090         const QStringList &arguments = lamexp_arguments();
1091
1092         //Don't initialized again, if done already
1093         if(qt_initialized)
1094         {
1095                 return true;
1096         }
1097
1098         //Secure DLL loading
1099         QLibrary kernel32("kernel32.dll");
1100         if(kernel32.load())
1101         {
1102                 SetDllDirectoryProc pSetDllDirectory = (SetDllDirectoryProc) kernel32.resolve("SetDllDirectoryW");
1103                 if(pSetDllDirectory != NULL) pSetDllDirectory(L"");
1104                 kernel32.unload();
1105         }
1106
1107         //Extract executable name from argv[] array
1108         QString executableName = QLatin1String("LameXP.exe");
1109         if(arguments.count() > 0)
1110         {
1111                 static const char *delimiters = "\\/:?";
1112                 executableName = arguments[0].trimmed();
1113                 for(int i = 0; delimiters[i]; i++)
1114                 {
1115                         int temp = executableName.lastIndexOf(QChar(delimiters[i]));
1116                         if(temp >= 0) executableName = executableName.mid(temp + 1);
1117                 }
1118                 executableName = executableName.trimmed();
1119                 if(executableName.isEmpty())
1120                 {
1121                         executableName = QLatin1String("LameXP.exe");
1122                 }
1123         }
1124
1125         //Check Qt version
1126 #ifdef QT_BUILD_KEY
1127         qDebug("Using Qt v%s [%s], %s, %s", qVersion(), QLibraryInfo::buildDate().toString(Qt::ISODate).toLatin1().constData(), (qSharedBuild() ? "DLL" : "Static"), QLibraryInfo::buildKey().toLatin1().constData());
1128         qDebug("Compiled with Qt v%s [%s], %s\n", QT_VERSION_STR, QT_PACKAGEDATE_STR, QT_BUILD_KEY);
1129         if(_stricmp(qVersion(), QT_VERSION_STR))
1130         {
1131                 qFatal("%s", QApplication::tr("Executable '%1' requires Qt v%2, but found Qt v%3.").arg(executableName, QString::fromLatin1(QT_VERSION_STR), QString::fromLatin1(qVersion())).toLatin1().constData());
1132                 return false;
1133         }
1134         if(QLibraryInfo::buildKey().compare(QString::fromLatin1(QT_BUILD_KEY), Qt::CaseInsensitive))
1135         {
1136                 qFatal("%s", QApplication::tr("Executable '%1' was built for Qt '%2', but found Qt '%3'.").arg(executableName, QString::fromLatin1(QT_BUILD_KEY), QLibraryInfo::buildKey()).toLatin1().constData());
1137                 return false;
1138         }
1139 #else
1140         qDebug("Using Qt v%s [%s], %s", qVersion(), QLibraryInfo::buildDate().toString(Qt::ISODate).toLatin1().constData(), (qSharedBuild() ? "DLL" : "Static"));
1141         qDebug("Compiled with Qt v%s [%s]\n", QT_VERSION_STR, QT_PACKAGEDATE_STR);
1142 #endif
1143
1144         //Check the Windows version
1145         switch(QSysInfo::windowsVersion() & QSysInfo::WV_NT_based)
1146         {
1147         case 0:
1148         case QSysInfo::WV_NT:
1149                 qFatal("%s", QApplication::tr("Executable '%1' requires Windows 2000 or later.").arg(executableName).toLatin1().constData());
1150                 break;
1151         case QSysInfo::WV_2000:
1152                 qDebug("Running on Windows 2000 (not officially supported!).\n");
1153                 lamexp_check_compatibility_mode("GetNativeSystemInfo", executableName);
1154                 break;
1155         case QSysInfo::WV_XP:
1156                 qDebug("Running on Windows XP.\n");
1157                 lamexp_check_compatibility_mode("GetLargePageMinimum", executableName);
1158                 break;
1159         case QSysInfo::WV_2003:
1160                 qDebug("Running on Windows Server 2003 or Windows XP x64-Edition.\n");
1161                 lamexp_check_compatibility_mode("GetLocaleInfoEx", executableName);
1162                 break;
1163         case QSysInfo::WV_VISTA:
1164                 qDebug("Running on Windows Vista or Windows Server 2008.\n");
1165                 lamexp_check_compatibility_mode("CreateRemoteThreadEx", executableName);
1166                 break;
1167         case QSysInfo::WV_WINDOWS7:
1168                 qDebug("Running on Windows 7 or Windows Server 2008 R2.\n");
1169                 lamexp_check_compatibility_mode("CreateFile2", executableName);
1170                 break;
1171         default:
1172                 {
1173                         const lamexp_os_version_t *osVersionNo = lamexp_get_os_version();
1174                         if(osVersionNo->versionMajor < 5)
1175                         {
1176                                 qFatal("%s", QApplication::tr("Executable '%1' requires Windows 2000 or later.").arg(executableName).toLatin1().constData());
1177                         }
1178                         else if(LAMEXP_EQL_OS_VER(osVersionNo, 6, 2))
1179                         {
1180                                 qDebug("Running on Windows 8 or Windows Server 2012\n");
1181                                 lamexp_check_compatibility_mode(NULL, executableName);
1182                         }
1183                         else
1184                         {
1185                                 qWarning("Running on an unknown/untested WinNT-based OS (v%u.%u).\n", osVersionNo->versionMajor, osVersionNo->versionMinor);
1186                         }
1187                 }
1188                 break;
1189         }
1190
1191         //Check for Wine
1192         if(lamexp_detect_wine())
1193         {
1194                 qWarning("It appears we are running under Wine, unexpected things might happen!\n");
1195         }
1196
1197         //Set text Codec for locale
1198         QTextCodec::setCodecForLocale(QTextCodec::codecForName("UTF-8"));
1199
1200         //Create Qt application instance
1201         QApplication *application = new QApplication(argc, argv);
1202
1203         //Load plugins from application directory
1204         QCoreApplication::setLibraryPaths(QStringList() << QApplication::applicationDirPath());
1205         qDebug("Library Path:\n%s\n", QApplication::libraryPaths().first().toUtf8().constData());
1206
1207         //Set application properties
1208         application->setApplicationName("LameXP - Audio Encoder Front-End");
1209         application->setApplicationVersion(QString().sprintf("%d.%02d.%04d", lamexp_version_major(), lamexp_version_minor(), lamexp_version_build())); 
1210         application->setOrganizationName("LoRd_MuldeR");
1211         application->setOrganizationDomain("mulder.at.gg");
1212         application->setWindowIcon(lamexp_app_icon());
1213         application->setEventFilter(lamexp_event_filter);
1214
1215         //Check for supported image formats
1216         QList<QByteArray> supportedFormats = QImageReader::supportedImageFormats();
1217         for(int i = 0; g_lamexp_imageformats[i]; i++)
1218         {
1219                 if(!supportedFormats.contains(g_lamexp_imageformats[i]))
1220                 {
1221                         qFatal("Qt initialization error: QImageIOHandler for '%s' missing!", g_lamexp_imageformats[i]);
1222                         return false;
1223                 }
1224         }
1225         
1226         //Add default translations
1227         QWriteLocker writeLockTranslations(&g_lamexp_translation.lock);
1228         if(!g_lamexp_translation.files) g_lamexp_translation.files = new QMap<QString, QString>();
1229         if(!g_lamexp_translation.names) g_lamexp_translation.names = new QMap<QString, QString>();
1230         g_lamexp_translation.files->insert(LAMEXP_DEFAULT_LANGID, "");
1231         g_lamexp_translation.names->insert(LAMEXP_DEFAULT_LANGID, "English");
1232         writeLockTranslations.unlock();
1233
1234         //Check for process elevation
1235         if((!lamexp_check_elevation()) && (!lamexp_detect_wine()))
1236         {
1237                 QMessageBox messageBox(QMessageBox::Warning, "LameXP", "<nobr>LameXP was started with 'elevated' rights, altough LameXP does not need these rights.<br>Running an applications with unnecessary rights is a potential security risk!</nobr>", QMessageBox::NoButton, NULL, Qt::Dialog | Qt::MSWindowsFixedSizeDialogHint | Qt::WindowStaysOnTopHint);
1238                 messageBox.addButton("Quit Program (Recommended)", QMessageBox::NoRole);
1239                 messageBox.addButton("Ignore", QMessageBox::NoRole);
1240                 if(messageBox.exec() == 0)
1241                 {
1242                         return false;
1243                 }
1244         }
1245
1246         //Update console icon, if a console is attached
1247 #if QT_VERSION < QT_VERSION_CHECK(5,0,0)
1248         if(g_lamexp_console_attached && (!lamexp_detect_wine()))
1249         {
1250                 typedef DWORD (__stdcall *SetConsoleIconFun)(HICON);
1251                 QLibrary kernel32("kernel32.dll");
1252                 if(kernel32.load())
1253                 {
1254                         SetConsoleIconFun SetConsoleIconPtr = (SetConsoleIconFun) kernel32.resolve("SetConsoleIcon");
1255                         if(SetConsoleIconPtr != NULL) SetConsoleIconPtr(QIcon(":/icons/sound.png").pixmap(16, 16).toWinHICON());
1256                         kernel32.unload();
1257                 }
1258         }
1259 #endif
1260
1261         //Done
1262         qt_initialized = true;
1263         return true;
1264 }
1265
1266 /*
1267  * Initialize IPC
1268  */
1269 int lamexp_init_ipc(void)
1270 {
1271         QWriteLocker writeLock(&g_lamexp_ipc_ptr.lock);
1272         
1273         if(g_lamexp_ipc_ptr.sharedmem && g_lamexp_ipc_ptr.semaphore_read && g_lamexp_ipc_ptr.semaphore_write && g_lamexp_ipc_ptr.semaphore_read_mutex && g_lamexp_ipc_ptr.semaphore_write_mutex)
1274         {
1275                 return 0;
1276         }
1277
1278         g_lamexp_ipc_ptr.semaphore_read = new QSystemSemaphore(QString(g_lamexp_ipc_uuid.semaphore_read), 0);
1279         g_lamexp_ipc_ptr.semaphore_write = new QSystemSemaphore(QString(g_lamexp_ipc_uuid.semaphore_write), 0);
1280         g_lamexp_ipc_ptr.semaphore_read_mutex = new QSystemSemaphore(QString(g_lamexp_ipc_uuid.semaphore_read_mutex), 0);
1281         g_lamexp_ipc_ptr.semaphore_write_mutex = new QSystemSemaphore(QString(g_lamexp_ipc_uuid.semaphore_write_mutex), 0);
1282
1283         if(g_lamexp_ipc_ptr.semaphore_read->error() != QSystemSemaphore::NoError)
1284         {
1285                 QString errorMessage = g_lamexp_ipc_ptr.semaphore_read->errorString();
1286                 LAMEXP_DELETE(g_lamexp_ipc_ptr.semaphore_read);
1287                 LAMEXP_DELETE(g_lamexp_ipc_ptr.semaphore_write);
1288                 LAMEXP_DELETE(g_lamexp_ipc_ptr.semaphore_read_mutex);
1289                 LAMEXP_DELETE(g_lamexp_ipc_ptr.semaphore_write_mutex);
1290                 qFatal("Failed to create system smaphore: %s", errorMessage.toUtf8().constData());
1291                 return -1;
1292         }
1293         if(g_lamexp_ipc_ptr.semaphore_write->error() != QSystemSemaphore::NoError)
1294         {
1295                 QString errorMessage = g_lamexp_ipc_ptr.semaphore_write->errorString();
1296                 LAMEXP_DELETE(g_lamexp_ipc_ptr.semaphore_read);
1297                 LAMEXP_DELETE(g_lamexp_ipc_ptr.semaphore_write);
1298                 LAMEXP_DELETE(g_lamexp_ipc_ptr.semaphore_read_mutex);
1299                 LAMEXP_DELETE(g_lamexp_ipc_ptr.semaphore_write_mutex);
1300                 qFatal("Failed to create system smaphore: %s", errorMessage.toUtf8().constData());
1301                 return -1;
1302         }
1303         if(g_lamexp_ipc_ptr.semaphore_read_mutex->error() != QSystemSemaphore::NoError)
1304         {
1305                 QString errorMessage = g_lamexp_ipc_ptr.semaphore_read_mutex->errorString();
1306                 LAMEXP_DELETE(g_lamexp_ipc_ptr.semaphore_read);
1307                 LAMEXP_DELETE(g_lamexp_ipc_ptr.semaphore_write);
1308                 LAMEXP_DELETE(g_lamexp_ipc_ptr.semaphore_read_mutex);
1309                 LAMEXP_DELETE(g_lamexp_ipc_ptr.semaphore_write_mutex);
1310                 qFatal("Failed to create system smaphore: %s", errorMessage.toUtf8().constData());
1311                 return -1;
1312         }
1313         if(g_lamexp_ipc_ptr.semaphore_write_mutex->error() != QSystemSemaphore::NoError)
1314         {
1315                 QString errorMessage = g_lamexp_ipc_ptr.semaphore_write_mutex->errorString();
1316                 LAMEXP_DELETE(g_lamexp_ipc_ptr.semaphore_read);
1317                 LAMEXP_DELETE(g_lamexp_ipc_ptr.semaphore_write);
1318                 LAMEXP_DELETE(g_lamexp_ipc_ptr.semaphore_read_mutex);
1319                 LAMEXP_DELETE(g_lamexp_ipc_ptr.semaphore_write_mutex);
1320                 qFatal("Failed to create system smaphore: %s", errorMessage.toUtf8().constData());
1321                 return -1;
1322         }
1323
1324         g_lamexp_ipc_ptr.sharedmem = new QSharedMemory(QString(g_lamexp_ipc_uuid.sharedmem), NULL);
1325         
1326         if(!g_lamexp_ipc_ptr.sharedmem->create(sizeof(lamexp_ipc_t)))
1327         {
1328                 if(g_lamexp_ipc_ptr.sharedmem->error() == QSharedMemory::AlreadyExists)
1329                 {
1330                         g_lamexp_ipc_ptr.sharedmem->attach();
1331                         if(g_lamexp_ipc_ptr.sharedmem->error() == QSharedMemory::NoError)
1332                         {
1333                                 return 1;
1334                         }
1335                         else
1336                         {
1337                                 QString errorMessage = g_lamexp_ipc_ptr.sharedmem->errorString();
1338                                 LAMEXP_DELETE(g_lamexp_ipc_ptr.sharedmem);
1339                                 qFatal("Failed to attach to shared memory: %s", errorMessage.toUtf8().constData());
1340                                 return -1;
1341                         }
1342                 }
1343                 else
1344                 {
1345                         QString errorMessage = g_lamexp_ipc_ptr.sharedmem->errorString();
1346                         LAMEXP_DELETE(g_lamexp_ipc_ptr.sharedmem);
1347                         qFatal("Failed to create shared memory: %s", errorMessage.toUtf8().constData());
1348                         return -1;
1349                 }
1350         }
1351
1352         memset(g_lamexp_ipc_ptr.sharedmem->data(), 0, sizeof(lamexp_ipc_t));
1353         g_lamexp_ipc_ptr.semaphore_write->release(g_lamexp_ipc_slots);
1354         g_lamexp_ipc_ptr.semaphore_read_mutex->release();
1355         g_lamexp_ipc_ptr.semaphore_write_mutex->release();
1356
1357         return 0;
1358 }
1359
1360 /*
1361  * IPC send message
1362  */
1363 void lamexp_ipc_send(unsigned int command, const char* message)
1364 {
1365         QReadLocker readLock(&g_lamexp_ipc_ptr.lock);
1366
1367         if(!g_lamexp_ipc_ptr.sharedmem || !g_lamexp_ipc_ptr.semaphore_read || !g_lamexp_ipc_ptr.semaphore_write || !g_lamexp_ipc_ptr.semaphore_read_mutex || !g_lamexp_ipc_ptr.semaphore_write_mutex)
1368         {
1369                 throw "Shared memory for IPC not initialized yet.";
1370         }
1371
1372         lamexp_ipc_data_t ipc_data;
1373         memset(&ipc_data, 0, sizeof(lamexp_ipc_data_t));
1374         ipc_data.command = command;
1375         
1376         if(message)
1377         {
1378                 strncpy_s(ipc_data.parameter, 4096, message, _TRUNCATE);
1379         }
1380
1381         if(g_lamexp_ipc_ptr.semaphore_write->acquire())
1382         {
1383                 if(g_lamexp_ipc_ptr.semaphore_write_mutex->acquire())
1384                 {
1385                         lamexp_ipc_t *ptr = reinterpret_cast<lamexp_ipc_t*>(g_lamexp_ipc_ptr.sharedmem->data());
1386                         memcpy(&ptr->data[ptr->pos_write], &ipc_data, sizeof(lamexp_ipc_data_t));
1387                         ptr->pos_write = (ptr->pos_write + 1) % g_lamexp_ipc_slots;
1388                         g_lamexp_ipc_ptr.semaphore_read->release();
1389                         g_lamexp_ipc_ptr.semaphore_write_mutex->release();
1390                 }
1391         }
1392 }
1393
1394 /*
1395  * IPC read message
1396  */
1397 void lamexp_ipc_read(unsigned int *command, char* message, size_t buffSize)
1398 {
1399         QReadLocker readLock(&g_lamexp_ipc_ptr.lock);
1400         
1401         *command = 0;
1402         message[0] = '\0';
1403         
1404         if(!g_lamexp_ipc_ptr.sharedmem || !g_lamexp_ipc_ptr.semaphore_read || !g_lamexp_ipc_ptr.semaphore_write || !g_lamexp_ipc_ptr.semaphore_read_mutex || !g_lamexp_ipc_ptr.semaphore_write_mutex)
1405         {
1406                 throw "Shared memory for IPC not initialized yet.";
1407         }
1408
1409         lamexp_ipc_data_t ipc_data;
1410         memset(&ipc_data, 0, sizeof(lamexp_ipc_data_t));
1411
1412         if(g_lamexp_ipc_ptr.semaphore_read->acquire())
1413         {
1414                 if(g_lamexp_ipc_ptr.semaphore_read_mutex->acquire())
1415                 {
1416                         lamexp_ipc_t *ptr = reinterpret_cast<lamexp_ipc_t*>(g_lamexp_ipc_ptr.sharedmem->data());
1417                         memcpy(&ipc_data, &ptr->data[ptr->pos_read], sizeof(lamexp_ipc_data_t));
1418                         ptr->pos_read = (ptr->pos_read + 1) % g_lamexp_ipc_slots;
1419                         g_lamexp_ipc_ptr.semaphore_write->release();
1420                         g_lamexp_ipc_ptr.semaphore_read_mutex->release();
1421
1422                         if(!(ipc_data.reserved_1 || ipc_data.reserved_2))
1423                         {
1424                                 *command = ipc_data.command;
1425                                 strncpy_s(message, buffSize, ipc_data.parameter, _TRUNCATE);
1426                         }
1427                         else
1428                         {
1429                                 qWarning("Malformed IPC message, will be ignored");
1430                         }
1431                 }
1432         }
1433 }
1434
1435 /*
1436  * Check for LameXP "portable" mode
1437  */
1438 bool lamexp_portable_mode(void)
1439 {
1440         QReadLocker readLock(&g_lamexp_portable.lock);
1441
1442         if(g_lamexp_portable.bInitialized)
1443         {
1444                 return g_lamexp_portable.bPortableModeEnabled;
1445         }
1446         
1447         readLock.unlock();
1448         QWriteLocker writeLock(&g_lamexp_portable.lock);
1449
1450         if(!g_lamexp_portable.bInitialized)
1451         {
1452                 if(VER_LAMEXP_PORTABLE_EDITION)
1453                 {
1454                         qWarning("LameXP portable edition!\n");
1455                         g_lamexp_portable.bPortableModeEnabled = true;
1456                 }
1457                 else
1458                 {
1459                         QString baseName = QFileInfo(QApplication::applicationFilePath()).completeBaseName();
1460                         int idx1 = baseName.indexOf("lamexp", 0, Qt::CaseInsensitive);
1461                         int idx2 = baseName.lastIndexOf("portable", -1, Qt::CaseInsensitive);
1462                         g_lamexp_portable.bPortableModeEnabled = (idx1 >= 0) && (idx2 >= 0) && (idx1 < idx2);
1463                 }
1464                 g_lamexp_portable.bInitialized = true;
1465         }
1466         
1467         return g_lamexp_portable.bPortableModeEnabled;
1468 }
1469
1470 /*
1471  * Get a random string
1472  */
1473 QString lamexp_rand_str(void)
1474 {
1475         QRegExp regExp("\\{(\\w+)-(\\w+)-(\\w+)-(\\w+)-(\\w+)\\}");
1476         QString uuid = QUuid::createUuid().toString();
1477
1478         if(regExp.indexIn(uuid) >= 0)
1479         {
1480                 return QString().append(regExp.cap(1)).append(regExp.cap(2)).append(regExp.cap(3)).append(regExp.cap(4)).append(regExp.cap(5));
1481         }
1482
1483         throw "The RegExp didn't match on the UUID string. This shouldn't happen ;-)";
1484 }
1485
1486 /*
1487  * Get LameXP temp folder
1488  */
1489 const QString &lamexp_temp_folder2(void)
1490 {
1491         QReadLocker readLock(&g_lamexp_folder.lock);
1492
1493         //Already initialized?
1494         if(g_lamexp_folder.temp)
1495         {
1496                 if(!g_lamexp_folder.temp->isEmpty())
1497                 {
1498                         if(QDir(*g_lamexp_folder.temp).exists())
1499                         {
1500                                 return *g_lamexp_folder.temp;
1501                         }
1502                 }
1503         }
1504         
1505         readLock.unlock();
1506         QWriteLocker writeLock(&g_lamexp_folder.lock);
1507         
1508         if(!g_lamexp_folder.temp)
1509         {
1510                 g_lamexp_folder.temp = new QString();
1511         }
1512         
1513         g_lamexp_folder.temp->clear();
1514
1515         static const char *TEMP_STR = "Temp";
1516         const QString WRITE_TEST_DATA = lamexp_rand_str();
1517         const QString SUB_FOLDER = lamexp_rand_str();
1518
1519         //Try the %TMP% or %TEMP% directory first
1520         QDir temp = QDir::temp();
1521         if(temp.exists())
1522         {
1523                 temp.mkdir(SUB_FOLDER);
1524                 if(temp.cd(SUB_FOLDER) && temp.exists())
1525                 {
1526                         QFile testFile(QString("%1/~%2.tmp").arg(temp.canonicalPath(), lamexp_rand_str()));
1527                         if(testFile.open(QIODevice::ReadWrite))
1528                         {
1529                                 if(testFile.write(WRITE_TEST_DATA.toLatin1().constData()) >= strlen(WRITE_TEST_DATA.toLatin1().constData()))
1530                                 {
1531                                         (*g_lamexp_folder.temp) = temp.canonicalPath();
1532                                 }
1533                                 testFile.remove();
1534                         }
1535                 }
1536                 if(!g_lamexp_folder.temp->isEmpty())
1537                 {
1538                         return *g_lamexp_folder.temp;
1539                 }
1540         }
1541
1542         //Create TEMP folder in %LOCALAPPDATA%
1543         QDir localAppData = QDir(lamexp_known_folder(lamexp_folder_localappdata));
1544         if(!localAppData.path().isEmpty())
1545         {
1546                 if(!localAppData.exists())
1547                 {
1548                         localAppData.mkpath(".");
1549                 }
1550                 if(localAppData.exists())
1551                 {
1552                         if(!localAppData.entryList(QDir::AllDirs).contains(TEMP_STR, Qt::CaseInsensitive))
1553                         {
1554                                 localAppData.mkdir(TEMP_STR);
1555                         }
1556                         if(localAppData.cd(TEMP_STR) && localAppData.exists())
1557                         {
1558                                 localAppData.mkdir(SUB_FOLDER);
1559                                 if(localAppData.cd(SUB_FOLDER) && localAppData.exists())
1560                                 {
1561                                         QFile testFile(QString("%1/~%2.tmp").arg(localAppData.canonicalPath(), lamexp_rand_str()));
1562                                         if(testFile.open(QIODevice::ReadWrite))
1563                                         {
1564                                                 if(testFile.write(WRITE_TEST_DATA.toLatin1().constData()) >= strlen(WRITE_TEST_DATA.toLatin1().constData()))
1565                                                 {
1566                                                         (*g_lamexp_folder.temp) = localAppData.canonicalPath();
1567                                                 }
1568                                                 testFile.remove();
1569                                         }
1570                                 }
1571                         }
1572                 }
1573                 if(!g_lamexp_folder.temp->isEmpty())
1574                 {
1575                         return *g_lamexp_folder.temp;
1576                 }
1577         }
1578
1579         //Failed to create TEMP folder!
1580         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());
1581         return *g_lamexp_folder.temp;
1582 }
1583
1584 /*
1585  * Clean folder
1586  */
1587 bool lamexp_clean_folder(const QString &folderPath)
1588 {
1589         QDir tempFolder(folderPath);
1590         QFileInfoList entryList = tempFolder.entryInfoList(QDir::AllEntries | QDir::NoDotAndDotDot);
1591
1592         for(int i = 0; i < entryList.count(); i++)
1593         {
1594                 if(entryList.at(i).isDir())
1595                 {
1596                         lamexp_clean_folder(entryList.at(i).canonicalFilePath());
1597                 }
1598                 else
1599                 {
1600                         for(int j = 0; j < 3; j++)
1601                         {
1602                                 if(lamexp_remove_file(entryList.at(i).canonicalFilePath()))
1603                                 {
1604                                         break;
1605                                 }
1606                         }
1607                 }
1608         }
1609         
1610         tempFolder.rmdir(".");
1611         return !tempFolder.exists();
1612 }
1613
1614 /*
1615  * Register tool
1616  */
1617 void lamexp_register_tool(const QString &toolName, LockedFile *file, unsigned int version, const QString *tag)
1618 {
1619         QWriteLocker writeLock(&g_lamexp_tools.lock);
1620         
1621         if(!g_lamexp_tools.registry) g_lamexp_tools.registry = new QMap<QString, LockedFile*>();
1622         if(!g_lamexp_tools.versions) g_lamexp_tools.versions = new QMap<QString, unsigned int>();
1623         if(!g_lamexp_tools.tags) g_lamexp_tools.tags = new QMap<QString, QString>();
1624
1625         if(g_lamexp_tools.registry->contains(toolName.toLower()))
1626         {
1627                 throw "lamexp_register_tool: Tool is already registered!";
1628         }
1629
1630         g_lamexp_tools.registry->insert(toolName.toLower(), file);
1631         g_lamexp_tools.versions->insert(toolName.toLower(), version);
1632         g_lamexp_tools.tags->insert(toolName.toLower(), (tag) ? (*tag) : QString());
1633 }
1634
1635 /*
1636  * Check for tool
1637  */
1638 bool lamexp_check_tool(const QString &toolName)
1639 {
1640         QReadLocker readLock(&g_lamexp_tools.lock);
1641         return (g_lamexp_tools.registry) ? g_lamexp_tools.registry->contains(toolName.toLower()) : false;
1642 }
1643
1644 /*
1645  * Lookup tool path
1646  */
1647 const QString lamexp_lookup_tool(const QString &toolName)
1648 {
1649         QReadLocker readLock(&g_lamexp_tools.lock);
1650
1651         if(g_lamexp_tools.registry)
1652         {
1653                 if(g_lamexp_tools.registry->contains(toolName.toLower()))
1654                 {
1655                         return g_lamexp_tools.registry->value(toolName.toLower())->filePath();
1656                 }
1657                 else
1658                 {
1659                         return QString();
1660                 }
1661         }
1662         else
1663         {
1664                 return QString();
1665         }
1666 }
1667
1668 /*
1669  * Lookup tool version
1670  */
1671 unsigned int lamexp_tool_version(const QString &toolName, QString *tag)
1672 {
1673         QReadLocker readLock(&g_lamexp_tools.lock);
1674         if(tag) tag->clear();
1675
1676         if(g_lamexp_tools.versions)
1677         {
1678                 if(g_lamexp_tools.versions->contains(toolName.toLower()))
1679                 {
1680                         if(tag)
1681                         {
1682                                 if(g_lamexp_tools.tags->contains(toolName.toLower())) *tag = g_lamexp_tools.tags->value(toolName.toLower());
1683                         }
1684                         return g_lamexp_tools.versions->value(toolName.toLower());
1685                 }
1686                 else
1687                 {
1688                         return UINT_MAX;
1689                 }
1690         }
1691         else
1692         {
1693                 return UINT_MAX;
1694         }
1695 }
1696
1697 /*
1698  * Version number to human-readable string
1699  */
1700 const QString lamexp_version2string(const QString &pattern, unsigned int version, const QString &defaultText, const QString *tag)
1701 {
1702         if(version == UINT_MAX)
1703         {
1704                 return defaultText;
1705         }
1706         
1707         QString result = pattern;
1708         int digits = result.count("?", Qt::CaseInsensitive);
1709         
1710         if(digits < 1)
1711         {
1712                 return result;
1713         }
1714         
1715         int pos = 0;
1716         QString versionStr = QString().sprintf(QString().sprintf("%%0%du", digits).toLatin1().constData(), version);
1717         int index = result.indexOf("?", Qt::CaseInsensitive);
1718         
1719         while(index >= 0 && pos < versionStr.length())
1720         {
1721                 result[index] = versionStr[pos++];
1722                 index = result.indexOf("?", Qt::CaseInsensitive);
1723         }
1724
1725         if(tag)
1726         {
1727                 result.replace(QChar('#'), *tag, Qt::CaseInsensitive);
1728         }
1729
1730         return result;
1731 }
1732
1733 /*
1734  * Register a new translation
1735  */
1736 bool lamexp_translation_register(const QString &langId, const QString &qmFile, const QString &langName, unsigned int &systemId, unsigned int &country)
1737 {
1738         QWriteLocker writeLockTranslations(&g_lamexp_translation.lock);
1739
1740         if(qmFile.isEmpty() || langName.isEmpty() || systemId < 1)
1741         {
1742                 return false;
1743         }
1744
1745         if(!g_lamexp_translation.files) g_lamexp_translation.files = new QMap<QString, QString>();
1746         if(!g_lamexp_translation.names) g_lamexp_translation.names = new QMap<QString, QString>();
1747         if(!g_lamexp_translation.sysid) g_lamexp_translation.sysid = new QMap<QString, unsigned int>();
1748         if(!g_lamexp_translation.cntry) g_lamexp_translation.cntry = new QMap<QString, unsigned int>();
1749
1750         g_lamexp_translation.files->insert(langId, qmFile);
1751         g_lamexp_translation.names->insert(langId, langName);
1752         g_lamexp_translation.sysid->insert(langId, systemId);
1753         g_lamexp_translation.cntry->insert(langId, country);
1754
1755         return true;
1756 }
1757
1758 /*
1759  * Get list of all translations
1760  */
1761 QStringList lamexp_query_translations(void)
1762 {
1763         QReadLocker readLockTranslations(&g_lamexp_translation.lock);
1764         return (g_lamexp_translation.files) ? g_lamexp_translation.files->keys() : QStringList();
1765 }
1766
1767 /*
1768  * Get translation name
1769  */
1770 QString lamexp_translation_name(const QString &langId)
1771 {
1772         QReadLocker readLockTranslations(&g_lamexp_translation.lock);
1773         return (g_lamexp_translation.names) ? g_lamexp_translation.names->value(langId.toLower(), QString()) : QString();
1774 }
1775
1776 /*
1777  * Get translation system id
1778  */
1779 unsigned int lamexp_translation_sysid(const QString &langId)
1780 {
1781         QReadLocker readLockTranslations(&g_lamexp_translation.lock);
1782         return (g_lamexp_translation.sysid) ? g_lamexp_translation.sysid->value(langId.toLower(), 0) : 0;
1783 }
1784
1785 /*
1786  * Get translation script id
1787  */
1788 unsigned int lamexp_translation_country(const QString &langId)
1789 {
1790         QReadLocker readLockTranslations(&g_lamexp_translation.lock);
1791         return (g_lamexp_translation.cntry) ? g_lamexp_translation.cntry->value(langId.toLower(), 0) : 0;
1792 }
1793
1794 /*
1795  * Install a new translator
1796  */
1797 bool lamexp_install_translator(const QString &langId)
1798 {
1799         bool success = false;
1800         const QString qmFileToPath(":/localization/%1");
1801
1802         if(langId.isEmpty() || langId.toLower().compare(LAMEXP_DEFAULT_LANGID) == 0)
1803         {
1804                 success = lamexp_install_translator_from_file(qmFileToPath.arg(LAMEXP_DEFAULT_TRANSLATION));
1805         }
1806         else
1807         {
1808                 QReadLocker readLock(&g_lamexp_translation.lock);
1809                 QString qmFile = (g_lamexp_translation.files) ? g_lamexp_translation.files->value(langId.toLower(), QString()) : QString();
1810                 readLock.unlock();
1811
1812                 if(!qmFile.isEmpty())
1813                 {
1814                         success = lamexp_install_translator_from_file(qmFileToPath.arg(qmFile));
1815                 }
1816                 else
1817                 {
1818                         qWarning("Translation '%s' not available!", langId.toLatin1().constData());
1819                 }
1820         }
1821
1822         return success;
1823 }
1824
1825 /*
1826  * Install a new translator from file
1827  */
1828 bool lamexp_install_translator_from_file(const QString &qmFile)
1829 {
1830         QWriteLocker writeLock(&g_lamexp_currentTranslator.lock);
1831         bool success = false;
1832
1833         if(!g_lamexp_currentTranslator.instance)
1834         {
1835                 g_lamexp_currentTranslator.instance = new QTranslator();
1836         }
1837
1838         if(!qmFile.isEmpty())
1839         {
1840                 QString qmPath = QFileInfo(qmFile).canonicalFilePath();
1841                 QApplication::removeTranslator(g_lamexp_currentTranslator.instance);
1842                 if(success = g_lamexp_currentTranslator.instance->load(qmPath))
1843                 {
1844                         QApplication::installTranslator(g_lamexp_currentTranslator.instance);
1845                 }
1846                 else
1847                 {
1848                         qWarning("Failed to load translation:\n\"%s\"", qmPath.toLatin1().constData());
1849                 }
1850         }
1851         else
1852         {
1853                 QApplication::removeTranslator(g_lamexp_currentTranslator.instance);
1854                 success = true;
1855         }
1856
1857         return success;
1858 }
1859
1860 const QStringList &lamexp_arguments(void)
1861 {
1862         QReadLocker readLock(&g_lamexp_argv.lock);
1863
1864         if(!g_lamexp_argv.list)
1865         {
1866                 readLock.unlock();
1867                 QWriteLocker writeLock(&g_lamexp_argv.lock);
1868
1869                 g_lamexp_argv.list = new QStringList;
1870
1871                 int nArgs = 0;
1872                 LPWSTR *szArglist = CommandLineToArgvW(GetCommandLineW(), &nArgs);
1873
1874                 if(NULL != szArglist)
1875                 {
1876                         for(int i = 0; i < nArgs; i++)
1877                         {
1878                                 (*g_lamexp_argv.list) << WCHAR2QSTR(szArglist[i]);
1879                         }
1880                         LocalFree(szArglist);
1881                 }
1882                 else
1883                 {
1884                         qWarning("CommandLineToArgvW() has failed !!!");
1885                 }
1886         }
1887
1888         return (*g_lamexp_argv.list);
1889 }
1890
1891 /*
1892  * Locate known folder on local system
1893  */
1894 const QString &lamexp_known_folder(lamexp_known_folder_t folder_id)
1895 {
1896         typedef HRESULT (WINAPI *SHGetKnownFolderPathFun)(__in const GUID &rfid, __in DWORD dwFlags, __in HANDLE hToken, __out PWSTR *ppszPath);
1897         typedef HRESULT (WINAPI *SHGetFolderPathFun)(__in HWND hwndOwner, __in int nFolder, __in HANDLE hToken, __in DWORD dwFlags, __out LPWSTR pszPath);
1898
1899         static const int CSIDL_LOCAL_APPDATA = 0x001c;
1900         static const int CSIDL_PROGRAM_FILES = 0x0026;
1901         static const int CSIDL_SYSTEM_FOLDER = 0x0025;
1902         static const GUID GUID_LOCAL_APPDATA = {0xF1B32785,0x6FBA,0x4FCF,{0x9D,0x55,0x7B,0x8E,0x7F,0x15,0x70,0x91}};
1903         static const GUID GUID_LOCAL_APPDATA_LOW = {0xA520A1A4,0x1780,0x4FF6,{0xBD,0x18,0x16,0x73,0x43,0xC5,0xAF,0x16}};
1904         static const GUID GUID_PROGRAM_FILES = {0x905e63b6,0xc1bf,0x494e,{0xb2,0x9c,0x65,0xb7,0x32,0xd3,0xd2,0x1a}};
1905         static const GUID GUID_SYSTEM_FOLDER = {0x1AC14E77,0x02E7,0x4E5D,{0xB7,0x44,0x2E,0xB1,0xAE,0x51,0x98,0xB7}};
1906
1907         QReadLocker readLock(&g_lamexp_folder.lock);
1908
1909         int folderCSIDL = -1;
1910         GUID folderGUID = {0x0000,0x0000,0x0000,{0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00}};
1911         size_t folderCacheId = size_t(-1);
1912
1913         switch(folder_id)
1914         {
1915         case lamexp_folder_localappdata:
1916                 folderCacheId = 0;
1917                 folderCSIDL = CSIDL_LOCAL_APPDATA;
1918                 folderGUID = GUID_LOCAL_APPDATA;
1919                 break;
1920         case lamexp_folder_programfiles:
1921                 folderCacheId = 1;
1922                 folderCSIDL = CSIDL_PROGRAM_FILES;
1923                 folderGUID = GUID_PROGRAM_FILES;
1924                 break;
1925         case lamexp_folder_systemfolder:
1926                 folderCacheId = 2;
1927                 folderCSIDL = CSIDL_SYSTEM_FOLDER;
1928                 folderGUID = GUID_SYSTEM_FOLDER;
1929                 break;
1930         default:
1931                 qWarning("Invalid 'known' folder was requested!");
1932                 return *reinterpret_cast<QString*>(NULL);
1933                 break;
1934         }
1935
1936         //Already in cache?
1937         if(g_lamexp_folder.knownFolders)
1938         {
1939                 if(g_lamexp_folder.knownFolders->contains(folderCacheId))
1940                 {
1941                         return (*g_lamexp_folder.knownFolders)[folderCacheId];
1942                 }
1943         }
1944
1945         readLock.unlock();
1946         QWriteLocker writeLock(&g_lamexp_folder.lock);
1947
1948         static SHGetKnownFolderPathFun SHGetKnownFolderPathPtr = NULL;
1949         static SHGetFolderPathFun SHGetFolderPathPtr = NULL;
1950
1951         if((!SHGetKnownFolderPathPtr) && (!SHGetFolderPathPtr))
1952         {
1953                 QLibrary kernel32Lib("shell32.dll");
1954                 if(kernel32Lib.load())
1955                 {
1956                         SHGetKnownFolderPathPtr = (SHGetKnownFolderPathFun) kernel32Lib.resolve("SHGetKnownFolderPath");
1957                         SHGetFolderPathPtr = (SHGetFolderPathFun) kernel32Lib.resolve("SHGetFolderPathW");
1958                 }
1959         }
1960
1961         QString folder;
1962
1963         if(SHGetKnownFolderPathPtr)
1964         {
1965                 WCHAR *path = NULL;
1966                 if(SHGetKnownFolderPathPtr(folderGUID, 0x00008000, NULL, &path) == S_OK)
1967                 {
1968                         //MessageBoxW(0, path, L"SHGetKnownFolderPath", MB_TOPMOST);
1969                         QDir folderTemp = QDir(QDir::fromNativeSeparators(QString::fromUtf16(reinterpret_cast<const unsigned short*>(path))));
1970                         if(!folderTemp.exists())
1971                         {
1972                                 folderTemp.mkpath(".");
1973                         }
1974                         if(folderTemp.exists())
1975                         {
1976                                 folder = folderTemp.canonicalPath();
1977                         }
1978                         CoTaskMemFree(path);
1979                 }
1980         }
1981         else if(SHGetFolderPathPtr)
1982         {
1983                 WCHAR *path = new WCHAR[4096];
1984                 if(SHGetFolderPathPtr(NULL, folderCSIDL, NULL, NULL, path) == S_OK)
1985                 {
1986                         //MessageBoxW(0, path, L"SHGetFolderPathW", MB_TOPMOST);
1987                         QDir folderTemp = QDir(QDir::fromNativeSeparators(QString::fromUtf16(reinterpret_cast<const unsigned short*>(path))));
1988                         if(!folderTemp.exists())
1989                         {
1990                                 folderTemp.mkpath(".");
1991                         }
1992                         if(folderTemp.exists())
1993                         {
1994                                 folder = folderTemp.canonicalPath();
1995                         }
1996                 }
1997                 delete [] path;
1998         }
1999
2000         //Create cache
2001         if(!g_lamexp_folder.knownFolders)
2002         {
2003                 g_lamexp_folder.knownFolders = new QMap<size_t, QString>();
2004         }
2005
2006         //Update cache
2007         g_lamexp_folder.knownFolders->insert(folderCacheId, folder);
2008         return (*g_lamexp_folder.knownFolders)[folderCacheId];
2009 }
2010
2011 /*
2012  * Safely remove a file
2013  */
2014 bool lamexp_remove_file(const QString &filename)
2015 {
2016         if(!QFileInfo(filename).exists() || !QFileInfo(filename).isFile())
2017         {
2018                 return true;
2019         }
2020         else
2021         {
2022                 if(!QFile::remove(filename))
2023                 {
2024                         DWORD attributes = GetFileAttributesW(QWCHAR(filename));
2025                         SetFileAttributesW(QWCHAR(filename), (attributes & (~FILE_ATTRIBUTE_READONLY)));
2026                         if(!QFile::remove(filename))
2027                         {
2028                                 qWarning("Could not delete \"%s\"", filename.toLatin1().constData());
2029                                 return false;
2030                         }
2031                         else
2032                         {
2033                                 return true;
2034                         }
2035                 }
2036                 else
2037                 {
2038                         return true;
2039                 }
2040         }
2041 }
2042
2043 /*
2044  * Check if visual themes are enabled (WinXP and later)
2045  */
2046 bool lamexp_themes_enabled(void)
2047 {
2048         typedef int (WINAPI *IsAppThemedFun)(void);
2049         
2050         QReadLocker readLock(&g_lamexp_themes_enabled.lock);
2051         if(g_lamexp_themes_enabled.bInitialized)
2052         {
2053                 return g_lamexp_themes_enabled.bThemesEnabled;
2054         }
2055
2056         readLock.unlock();
2057         QWriteLocker writeLock(&g_lamexp_themes_enabled.lock);
2058
2059         if(!g_lamexp_themes_enabled.bInitialized)
2060         {
2061                 g_lamexp_themes_enabled.bThemesEnabled = false;
2062                 const lamexp_os_version_t * osVersion = lamexp_get_os_version();
2063                 if(LAMEXP_MIN_OS_VER(osVersion, 5, 1))
2064                 {
2065                         IsAppThemedFun IsAppThemedPtr = NULL;
2066                         QLibrary uxTheme(QString("%1/UxTheme.dll").arg(lamexp_known_folder(lamexp_folder_systemfolder)));
2067                         if(uxTheme.load())
2068                         {
2069                                 IsAppThemedPtr = (IsAppThemedFun) uxTheme.resolve("IsAppThemed");
2070                         }
2071                         if(IsAppThemedPtr)
2072                         {
2073                                 g_lamexp_themes_enabled.bThemesEnabled = IsAppThemedPtr();
2074                                 if(!g_lamexp_themes_enabled.bThemesEnabled)
2075                                 {
2076                                         qWarning("Theme support is disabled for this process!");
2077                                 }
2078                         }
2079                 }
2080                 g_lamexp_themes_enabled.bInitialized = true;
2081         }
2082
2083         return g_lamexp_themes_enabled.bThemesEnabled;
2084 }
2085
2086 /*
2087  * Get number of free bytes on disk
2088  */
2089 unsigned __int64 lamexp_free_diskspace(const QString &path, bool *ok)
2090 {
2091         ULARGE_INTEGER freeBytesAvailable, totalNumberOfBytes, totalNumberOfFreeBytes;
2092         if(GetDiskFreeSpaceExW(reinterpret_cast<const wchar_t*>(QDir::toNativeSeparators(path).utf16()), &freeBytesAvailable, &totalNumberOfBytes, &totalNumberOfFreeBytes))
2093         {
2094                 if(ok) *ok = true;
2095                 return freeBytesAvailable.QuadPart;
2096         }
2097         else
2098         {
2099                 if(ok) *ok = false;
2100                 return 0;
2101         }
2102 }
2103
2104 /*
2105  * Check if computer does support hibernation
2106  */
2107 bool lamexp_is_hibernation_supported(void)
2108 {
2109         bool hibernationSupported = false;
2110
2111         SYSTEM_POWER_CAPABILITIES pwrCaps;
2112         SecureZeroMemory(&pwrCaps, sizeof(SYSTEM_POWER_CAPABILITIES));
2113         
2114         if(GetPwrCapabilities(&pwrCaps))
2115         {
2116                 hibernationSupported = pwrCaps.SystemS4 && pwrCaps.HiberFilePresent;
2117         }
2118
2119         return hibernationSupported;
2120 }
2121
2122 /*
2123  * Shutdown the computer
2124  */
2125 bool lamexp_shutdown_computer(const QString &message, const unsigned long timeout, const bool forceShutdown, const bool hibernate)
2126 {
2127         HANDLE hToken = NULL;
2128
2129         if(OpenProcessToken(GetCurrentProcess(), TOKEN_ADJUST_PRIVILEGES | TOKEN_QUERY, &hToken))
2130         {
2131                 TOKEN_PRIVILEGES privileges;
2132                 memset(&privileges, 0, sizeof(TOKEN_PRIVILEGES));
2133                 privileges.PrivilegeCount = 1;
2134                 privileges.Privileges[0].Attributes = SE_PRIVILEGE_ENABLED;
2135                 
2136                 if(LookupPrivilegeValue(NULL, SE_SHUTDOWN_NAME, &privileges.Privileges[0].Luid))
2137                 {
2138                         if(AdjustTokenPrivileges(hToken, FALSE, &privileges, NULL, NULL, NULL))
2139                         {
2140                                 if(hibernate)
2141                                 {
2142                                         if(SetSuspendState(TRUE, TRUE, TRUE))
2143                                         {
2144                                                 return true;
2145                                         }
2146                                 }
2147                                 const DWORD reason = SHTDN_REASON_MAJOR_APPLICATION | SHTDN_REASON_FLAG_PLANNED;
2148                                 return InitiateSystemShutdownEx(NULL, const_cast<wchar_t*>(QWCHAR(message)), timeout, forceShutdown ? TRUE : FALSE, FALSE, reason);
2149                         }
2150                 }
2151         }
2152         
2153         return false;
2154 }
2155
2156 /*
2157  * Make a window blink (to draw user's attention)
2158  */
2159 void lamexp_blink_window(QWidget *poWindow, unsigned int count, unsigned int delay)
2160 {
2161         static QMutex blinkMutex;
2162
2163         const double maxOpac = 1.0;
2164         const double minOpac = 0.3;
2165         const double delOpac = 0.1;
2166
2167         if(!blinkMutex.tryLock())
2168         {
2169                 qWarning("Blinking is already in progress, skipping!");
2170                 return;
2171         }
2172         
2173         try
2174         {
2175                 const int steps = static_cast<int>(ceil(maxOpac - minOpac) / delOpac);
2176                 const int sleep = static_cast<int>(floor(static_cast<double>(delay) / static_cast<double>(steps)));
2177                 const double opacity = poWindow->windowOpacity();
2178         
2179                 for(unsigned int i = 0; i < count; i++)
2180                 {
2181                         for(double x = maxOpac; x >= minOpac; x -= delOpac)
2182                         {
2183                                 poWindow->setWindowOpacity(x);
2184                                 QApplication::processEvents();
2185                                 Sleep(sleep);
2186                         }
2187
2188                         for(double x = minOpac; x <= maxOpac; x += delOpac)
2189                         {
2190                                 poWindow->setWindowOpacity(x);
2191                                 QApplication::processEvents();
2192                                 Sleep(sleep);
2193                         }
2194                 }
2195
2196                 poWindow->setWindowOpacity(opacity);
2197                 QApplication::processEvents();
2198                 blinkMutex.unlock();
2199         }
2200         catch (...)
2201         {
2202                 blinkMutex.unlock();
2203                 qWarning("Exception error while blinking!");
2204         }
2205 }
2206
2207 /*
2208  * Remove forbidden characters from a filename
2209  */
2210 const QString lamexp_clean_filename(const QString &str)
2211 {
2212         QString newStr(str);
2213         QRegExp rx("\"(.+)\"");
2214         rx.setMinimal(true);
2215
2216         newStr.replace("\\", "-");
2217         newStr.replace(" / ", ", ");
2218         newStr.replace("/", ",");
2219         newStr.replace(":", "-");
2220         newStr.replace("*", "x");
2221         newStr.replace("?", "");
2222         newStr.replace("<", "[");
2223         newStr.replace(">", "]");
2224         newStr.replace("|", "!");
2225         newStr.replace(rx, "`\\1´");
2226         newStr.replace("\"", "'");
2227         
2228         return newStr.simplified();
2229 }
2230
2231 /*
2232  * Remove forbidden characters from a file path
2233  */
2234 const QString lamexp_clean_filepath(const QString &str)
2235 {
2236         QStringList parts = QString(str).replace("\\", "/").split("/");
2237
2238         for(int i = 0; i < parts.count(); i++)
2239         {
2240                 parts[i] = lamexp_clean_filename(parts[i]);
2241         }
2242
2243         return parts.join("/");
2244 }
2245
2246 /*
2247  * Get a list of all available Qt Text Codecs
2248  */
2249 QStringList lamexp_available_codepages(bool noAliases)
2250 {
2251         QStringList codecList;
2252         
2253         QList<QByteArray> availableCodecs = QTextCodec::availableCodecs();
2254         while(!availableCodecs.isEmpty())
2255         {
2256                 QByteArray current = availableCodecs.takeFirst();
2257                 if(!(current.startsWith("system") || current.startsWith("System")))
2258                 {
2259                         codecList << QString::fromLatin1(current.constData(), current.size());
2260                         if(noAliases)
2261                         {
2262                                 if(QTextCodec *currentCodec = QTextCodec::codecForName(current.constData()))
2263                                 {
2264                                         
2265                                         QList<QByteArray> aliases = currentCodec->aliases();
2266                                         while(!aliases.isEmpty()) availableCodecs.removeAll(aliases.takeFirst());
2267                                 }
2268                         }
2269                 }
2270         }
2271
2272         return codecList;
2273 }
2274
2275 /*
2276  * Robert Jenkins' 96 bit Mix Function
2277  * Source: http://www.concentric.net/~Ttwang/tech/inthash.htm
2278  */
2279 static unsigned int lamexp_mix(const unsigned int x, const unsigned int y, const unsigned int z)
2280 {
2281         unsigned int a = x;
2282         unsigned int b = y;
2283         unsigned int c = z;
2284         
2285         a=a-b;  a=a-c;  a=a^(c >> 13);
2286         b=b-c;  b=b-a;  b=b^(a << 8); 
2287         c=c-a;  c=c-b;  c=c^(b >> 13);
2288         a=a-b;  a=a-c;  a=a^(c >> 12);
2289         b=b-c;  b=b-a;  b=b^(a << 16);
2290         c=c-a;  c=c-b;  c=c^(b >> 5);
2291         a=a-b;  a=a-c;  a=a^(c >> 3);
2292         b=b-c;  b=b-a;  b=b^(a << 10);
2293         c=c-a;  c=c-b;  c=c^(b >> 15);
2294
2295         return c;
2296 }
2297
2298 /*
2299  * Seeds the random number generator
2300  * Note: Altough rand_s() doesn't need a seed, this must be called pripr to lamexp_rand(), just to to be sure!
2301  */
2302 void lamexp_seed_rand(void)
2303 {
2304         qsrand(lamexp_mix(clock(), time(NULL), _getpid()));
2305 }
2306
2307 /*
2308  * Returns a randum number
2309  * Note: This function uses rand_s() if available, but falls back to qrand() otherwise
2310  */
2311 unsigned int lamexp_rand(void)
2312 {
2313         unsigned int rnd = 0;
2314         if(const lamexp_os_version_t* osVer = lamexp_get_os_version())
2315         {
2316                 if(LAMEXP_MIN_OS_VER(osVer, 5, 1))
2317                 {
2318                         if(rand_s(&rnd) == 0)
2319                         {
2320                                 return rnd;
2321                         }
2322                 }
2323         }
2324         for(size_t i = 0; i < sizeof(unsigned int); i++)
2325         {
2326                 rnd = (rnd << 8) ^ qrand();
2327         }
2328         return rnd;
2329 }
2330
2331 /*
2332  * Determines the current date, resistant against certain manipulations
2333  */
2334 QDate lamexp_current_date_safe(void)
2335 {
2336         const DWORD MAX_PROC = 1024;
2337         DWORD *processes = new DWORD[MAX_PROC];
2338         DWORD bytesReturned = 0;
2339         
2340         if(!EnumProcesses(processes, sizeof(DWORD) * MAX_PROC, &bytesReturned))
2341         {
2342                 LAMEXP_DELETE_ARRAY(processes);
2343                 return QDate::currentDate();
2344         }
2345
2346         const DWORD procCount = bytesReturned / sizeof(DWORD);
2347         ULARGE_INTEGER lastStartTime;
2348         memset(&lastStartTime, 0, sizeof(ULARGE_INTEGER));
2349
2350         for(DWORD i = 0; i < procCount; i++)
2351         {
2352                 HANDLE hProc = OpenProcess(PROCESS_QUERY_INFORMATION, FALSE, processes[i]);
2353                 if(hProc)
2354                 {
2355                         FILETIME processTime[4];
2356                         if(GetProcessTimes(hProc, &processTime[0], &processTime[1], &processTime[2], &processTime[3]))
2357                         {
2358                                 ULARGE_INTEGER timeCreation;
2359                                 timeCreation.LowPart = processTime[0].dwLowDateTime;
2360                                 timeCreation.HighPart = processTime[0].dwHighDateTime;
2361                                 if(timeCreation.QuadPart > lastStartTime.QuadPart)
2362                                 {
2363                                         lastStartTime.QuadPart = timeCreation.QuadPart;
2364                                 }
2365                         }
2366                         CloseHandle(hProc);
2367                 }
2368         }
2369
2370         LAMEXP_DELETE_ARRAY(processes);
2371         
2372         FILETIME lastStartTime_fileTime;
2373         lastStartTime_fileTime.dwHighDateTime = lastStartTime.HighPart;
2374         lastStartTime_fileTime.dwLowDateTime = lastStartTime.LowPart;
2375
2376         FILETIME lastStartTime_localTime;
2377         if(!FileTimeToLocalFileTime(&lastStartTime_fileTime, &lastStartTime_localTime))
2378         {
2379                 memcpy(&lastStartTime_localTime, &lastStartTime_fileTime, sizeof(FILETIME));
2380         }
2381         
2382         SYSTEMTIME lastStartTime_system;
2383         if(!FileTimeToSystemTime(&lastStartTime_localTime, &lastStartTime_system))
2384         {
2385                 memset(&lastStartTime_system, 0, sizeof(SYSTEMTIME));
2386                 lastStartTime_system.wYear = 1970; lastStartTime_system.wMonth = lastStartTime_system.wDay = 1;
2387         }
2388
2389         const QDate currentDate = QDate::currentDate();
2390         const QDate processDate = QDate(lastStartTime_system.wYear, lastStartTime_system.wMonth, lastStartTime_system.wDay);
2391         return (currentDate >= processDate) ? currentDate : processDate;
2392 }
2393
2394 /*
2395  * Entry point checks
2396  */
2397 static DWORD lamexp_entry_check(void);
2398 static DWORD g_lamexp_entry_check_result = lamexp_entry_check();
2399 static DWORD g_lamexp_entry_check_flag = 0x789E09B2;
2400 static DWORD lamexp_entry_check(void)
2401 {
2402         volatile DWORD retVal = 0xA199B5AF;
2403         if(g_lamexp_entry_check_flag != 0x8761F64D)
2404         {
2405                 lamexp_fatal_exit(L"Application initialization has failed, take care!");
2406         }
2407         return retVal;
2408 }
2409
2410 /*
2411  * Application entry point (runs before static initializers)
2412  */
2413 extern "C"
2414 {
2415         int WinMainCRTStartup(void);
2416         
2417         int lamexp_entry_point(void)
2418         {
2419                 if((!LAMEXP_DEBUG) && lamexp_check_for_debugger())
2420                 {
2421                         lamexp_fatal_exit(L"Not a debug build. Please unload debugger and try again!");
2422                 }
2423                 if(g_lamexp_entry_check_flag != 0x789E09B2)
2424                 {
2425                         lamexp_fatal_exit(L"Application initialization has failed, take care!");
2426                 }
2427
2428                 //Zero *before* constructors are called
2429                 LAMEXP_ZERO_MEMORY(g_lamexp_argv);
2430                 LAMEXP_ZERO_MEMORY(g_lamexp_tools);
2431                 LAMEXP_ZERO_MEMORY(g_lamexp_currentTranslator);
2432                 LAMEXP_ZERO_MEMORY(g_lamexp_translation);
2433                 LAMEXP_ZERO_MEMORY(g_lamexp_folder);
2434                 LAMEXP_ZERO_MEMORY(g_lamexp_ipc_ptr);
2435                 LAMEXP_ZERO_MEMORY(g_lamexp_os_version);
2436                 LAMEXP_ZERO_MEMORY(g_lamexp_themes_enabled);
2437                 LAMEXP_ZERO_MEMORY(g_lamexp_portable);
2438
2439                 //Make sure we will pass the check
2440                 g_lamexp_entry_check_flag = ~g_lamexp_entry_check_flag;
2441
2442                 //Now initialize the C Runtime library!
2443                 return WinMainCRTStartup();
2444         }
2445 }
2446
2447 /*
2448  * Fatal application exit
2449  */
2450 #pragma intrinsic(_InterlockedExchange)
2451 void lamexp_fatal_exit(const wchar_t* exitMessage, const wchar_t* errorBoxMessage)
2452 {
2453         static volatile long bFatalFlag = 0L;
2454
2455         if(_InterlockedExchange(&bFatalFlag, 1L) == 0L)
2456         {
2457                 if(GetCurrentThreadId() != g_main_thread_id)
2458                 {
2459                         HANDLE mainThread = OpenThread(THREAD_TERMINATE, FALSE, g_main_thread_id);
2460                         if(mainThread) TerminateThread(mainThread, ULONG_MAX);
2461                 }
2462         
2463                 if(errorBoxMessage)
2464                 {
2465                         MessageBoxW(NULL, errorBoxMessage, L"LameXP - GURU MEDITATION", MB_ICONERROR | MB_TOPMOST | MB_TASKMODAL);
2466                 }
2467
2468                 for(;;)
2469                 {
2470                         FatalAppExit(0, exitMessage);
2471                         TerminateProcess(GetCurrentProcess(), -1);
2472                 }
2473         }
2474
2475         TerminateThread(GetCurrentThread(), -1);
2476         Sleep(INFINITE);
2477 }
2478
2479 /*
2480  * Finalization function (final clean-up)
2481  */
2482 void lamexp_finalization(void)
2483 {
2484         qDebug("lamexp_finalization()");
2485         
2486         //Free all tools
2487         if(g_lamexp_tools.registry)
2488         {
2489                 QStringList keys = g_lamexp_tools.registry->keys();
2490                 for(int i = 0; i < keys.count(); i++)
2491                 {
2492                         LAMEXP_DELETE((*g_lamexp_tools.registry)[keys.at(i)]);
2493                 }
2494                 LAMEXP_DELETE(g_lamexp_tools.registry);
2495                 LAMEXP_DELETE(g_lamexp_tools.versions);
2496                 LAMEXP_DELETE(g_lamexp_tools.tags);
2497         }
2498         
2499         //Delete temporary files
2500         if(g_lamexp_folder.temp)
2501         {
2502                 if(!g_lamexp_folder.temp->isEmpty())
2503                 {
2504                         for(int i = 0; i < 100; i++)
2505                         {
2506                                 if(lamexp_clean_folder(*g_lamexp_folder.temp))
2507                                 {
2508                                         break;
2509                                 }
2510                                 Sleep(125);
2511                         }
2512                 }
2513                 LAMEXP_DELETE(g_lamexp_folder.temp);
2514         }
2515
2516         //Clear folder cache
2517         LAMEXP_DELETE(g_lamexp_folder.knownFolders);
2518
2519         //Clear languages
2520         if(g_lamexp_currentTranslator.instance)
2521         {
2522                 QApplication::removeTranslator(g_lamexp_currentTranslator.instance);
2523                 LAMEXP_DELETE(g_lamexp_currentTranslator.instance);
2524         }
2525         LAMEXP_DELETE(g_lamexp_translation.files);
2526         LAMEXP_DELETE(g_lamexp_translation.names);
2527         LAMEXP_DELETE(g_lamexp_translation.cntry);
2528         LAMEXP_DELETE(g_lamexp_translation.sysid);
2529
2530         //Destroy Qt application object
2531         QApplication *application = dynamic_cast<QApplication*>(QApplication::instance());
2532         LAMEXP_DELETE(application);
2533
2534         //Detach from shared memory
2535         if(g_lamexp_ipc_ptr.sharedmem) g_lamexp_ipc_ptr.sharedmem->detach();
2536         LAMEXP_DELETE(g_lamexp_ipc_ptr.sharedmem);
2537         LAMEXP_DELETE(g_lamexp_ipc_ptr.semaphore_read);
2538         LAMEXP_DELETE(g_lamexp_ipc_ptr.semaphore_write);
2539         LAMEXP_DELETE(g_lamexp_ipc_ptr.semaphore_read_mutex);
2540         LAMEXP_DELETE(g_lamexp_ipc_ptr.semaphore_write_mutex);
2541
2542         //Free STDOUT and STDERR buffers
2543         if(g_lamexp_console_attached)
2544         {
2545                 if(std::filebuf *tmp = dynamic_cast<std::filebuf*>(std::cout.rdbuf()))
2546                 {
2547                         std::cout.rdbuf(NULL);
2548                         LAMEXP_DELETE(tmp);
2549                 }
2550                 if(std::filebuf *tmp = dynamic_cast<std::filebuf*>(std::cerr.rdbuf()))
2551                 {
2552                         std::cerr.rdbuf(NULL);
2553                         LAMEXP_DELETE(tmp);
2554                 }
2555         }
2556
2557         //Close log file
2558         if(g_lamexp_log_file)
2559         {
2560                 fclose(g_lamexp_log_file);
2561                 g_lamexp_log_file = NULL;
2562         }
2563
2564         //Free CLI Arguments
2565         LAMEXP_DELETE(g_lamexp_argv.list);
2566 }
2567
2568 /*
2569  * Initialize debug thread
2570  */
2571 static const HANDLE g_debug_thread = LAMEXP_DEBUG ? NULL : lamexp_debug_thread_init();
2572
2573 /*
2574  * Get number private bytes [debug only]
2575  */
2576 SIZE_T lamexp_dbg_private_bytes(void)
2577 {
2578 #if LAMEXP_DEBUG
2579         PROCESS_MEMORY_COUNTERS_EX memoryCounters;
2580         memoryCounters.cb = sizeof(PROCESS_MEMORY_COUNTERS_EX);
2581         GetProcessMemoryInfo(GetCurrentProcess(), (PPROCESS_MEMORY_COUNTERS) &memoryCounters, sizeof(PROCESS_MEMORY_COUNTERS_EX));
2582         return memoryCounters.PrivateUsage;
2583 #else
2584         throw "Cannot call this function in a non-debug build!";
2585 #endif //LAMEXP_DEBUG
2586 }