OSDN Git Service

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