OSDN Git Service

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