OSDN Git Service

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