OSDN Git Service

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