OSDN Git Service

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