OSDN Git Service

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