OSDN Git Service

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