OSDN Git Service

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