OSDN Git Service

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