OSDN Git Service

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