OSDN Git Service

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