OSDN Git Service

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