OSDN Git Service

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