OSDN Git Service

Updated the QAAC add-in for LameXP to QAAC v2.33 (2014-01-14), compiled with MSVC...
[lamexp/LameXP.git] / src / Global_Win32.cpp
1 ///////////////////////////////////////////////////////////////////////////////
2 // LameXP - Audio Encoder Front-End
3 // Copyright (C) 2004-2014 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, but always including the *additional*
9 // restrictions defined in the "License.txt" file.
10 //
11 // This program is distributed in the hope that it will be useful,
12 // but WITHOUT ANY WARRANTY; without even the implied warranty of
13 // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
14 // GNU General Public License for more details.
15 //
16 // You should have received a copy of the GNU General Public License along
17 // with this program; if not, write to the Free Software Foundation, Inc.,
18 // 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
19 //
20 // http://www.gnu.org/licenses/gpl-2.0.txt
21 ///////////////////////////////////////////////////////////////////////////////
22
23 #include "Global.h"
24
25 //Target version
26 #include "Targetver.h"
27
28 //Visual Leaks Detector
29 #include <vld.h>
30
31 //Windows includes
32 #define NOMINMAX
33 #define WIN32_LEAN_AND_MEAN
34 #include <Windows.h>
35 #include <MMSystem.h>
36 #include <ShellAPI.h>
37 #include <SensAPI.h>
38 #include <Objbase.h>
39 #include <PowrProf.h>
40 #include <Psapi.h>
41 #include <dwmapi.h>
42
43 //Qt includes
44 #include <QApplication>
45 #include <QDate>
46 #include <QDir>
47 #include <QEvent>
48 #include <QIcon>
49 #include <QImageReader>
50 #include <QLibrary>
51 #include <QLibraryInfo>
52 #include <QMap>
53 #include <QMessageBox>
54 #include <QMutex>
55 #include <QPlastiqueStyle>
56 #include <QProcess>
57 #include <QReadWriteLock>
58 #include <QRegExp>
59 #include <QSysInfo>
60 #include <QTextCodec>
61 #include <QTimer>
62 #include <QTranslator>
63 #include <QUuid>
64 #include <QResource>
65
66 //LameXP includes
67 #define LAMEXP_INC_CONFIG
68 #include "Resource.h"
69 #include "Config.h"
70
71 //CRT includes
72 #include <cstdio>
73 #include <iostream>
74 #include <fstream>
75 #include <io.h>
76 #include <fcntl.h>
77 #include <intrin.h>
78 #include <cmath>
79 #include <ctime>
80 #include <process.h>
81 #include <csignal>
82
83 //Initialize static Qt plugins
84 #ifdef QT_NODLL
85 #if QT_VERSION < QT_VERSION_CHECK(5,0,0)
86 Q_IMPORT_PLUGIN(qico)
87 Q_IMPORT_PLUGIN(qsvg)
88 #else
89 Q_IMPORT_PLUGIN(QWindowsIntegrationPlugin)
90 Q_IMPORT_PLUGIN(QICOPlugin)
91 #endif
92 #endif
93
94 ///////////////////////////////////////////////////////////////////////////////
95 // HELPER MACROS
96 ///////////////////////////////////////////////////////////////////////////////
97
98 #define _LAMEXP_MAKE_STR(STR) #STR
99 #define LAMEXP_MAKE_STR(STR) _LAMEXP_MAKE_STR(STR)
100
101 //String helper
102 #define CLEAN_OUTPUT_STRING(STR) do \
103 { \
104         const char CTRL_CHARS[3] = { '\r', '\n', '\t' }; \
105         for(size_t i = 0; i < 3; i++) \
106         { \
107                 while(char *pos = strchr((STR), CTRL_CHARS[i])) *pos = char(0x20); \
108         } \
109 } \
110 while(0)
111
112 //String helper
113 #define TRIM_LEFT(STR) do \
114 { \
115         const char WHITE_SPACE[4] = { char(0x20), '\r', '\n', '\t' }; \
116         for(size_t i = 0; i < 4; i++) \
117         { \
118                 while(*(STR) == WHITE_SPACE[i]) (STR)++; \
119         } \
120 } \
121 while(0)
122
123 ///////////////////////////////////////////////////////////////////////////////
124 // GLOBAL TYPES
125 ///////////////////////////////////////////////////////////////////////////////
126
127 typedef HRESULT (WINAPI *SHGetKnownFolderPath_t)(const GUID &rfid, DWORD dwFlags, HANDLE hToken, PWSTR *ppszPath);
128 typedef HRESULT (WINAPI *SHGetFolderPath_t)(HWND hwndOwner, int nFolder, HANDLE hToken, DWORD dwFlags, LPWSTR pszPath);
129
130 ///////////////////////////////////////////////////////////////////////////////
131 // GLOBAL VARS
132 ///////////////////////////////////////////////////////////////////////////////
133
134 //Console attached flag
135 static bool g_lamexp_console_attached = false;
136
137 //Special folders
138 static struct
139 {
140         QMap<size_t, QString> *knownFolders;
141         SHGetKnownFolderPath_t getKnownFolderPath;
142         SHGetFolderPath_t getFolderPath;
143         QReadWriteLock lock;
144 }
145 g_lamexp_known_folder;
146
147 //CLI Arguments
148 static struct
149 {
150         QStringList *list;
151         QReadWriteLock lock;
152 }
153 g_lamexp_argv;
154
155 //OS Version
156 static struct
157 {
158         bool bInitialized;
159         lamexp_os_version_t version;
160         QReadWriteLock lock;
161 }
162 g_lamexp_os_version;
163
164 //Wine detection
165 static struct
166 {
167         bool bInitialized;
168         bool bIsWine;
169         QReadWriteLock lock;
170 }
171 g_lamexp_wine;
172
173 //Win32 Theme support
174 static struct
175 {
176         bool bInitialized;
177         bool bThemesEnabled;
178         QReadWriteLock lock;
179 }
180 g_lamexp_themes_enabled;
181
182 //Win32 DWM API functions
183 static struct
184 {
185         bool bInitialized;
186         HRESULT (__stdcall *dwmIsCompositionEnabled)(BOOL *bEnabled);
187         HRESULT (__stdcall *dwmExtendFrameIntoClientArea)(HWND hWnd, const MARGINS* pMarInset);
188         HRESULT (__stdcall *dwmEnableBlurBehindWindow)(HWND hWnd, const DWM_BLURBEHIND* pBlurBehind);
189         QLibrary *dwmapi_dll;
190         QReadWriteLock lock;
191 }
192 g_lamexp_dwmapi;
193
194 //Sound file cache
195 static struct
196 {
197         QHash<const QString, const unsigned char*> *sound_db;
198         QReadWriteLock lock;
199 }
200 g_lamexp_sounds;
201
202 //Image formats
203 static const char *g_lamexp_imageformats[] = {"bmp", "png", "jpg", "gif", "ico", "xpm", NULL}; //"svg"
204
205 //Global locks
206 static QMutex g_lamexp_message_mutex;
207
208 //Main thread ID
209 static const DWORD g_main_thread_id = GetCurrentThreadId();
210
211 //Log file
212 static FILE *g_lamexp_log_file = NULL;
213
214 //Localization
215 const char* LAMEXP_DEFAULT_LANGID = "en";
216 const char* LAMEXP_DEFAULT_TRANSLATION = "LameXP_EN.qm";
217
218 //Known Windows versions - maps marketing names to the actual Windows NT versions
219 const lamexp_os_version_t lamexp_winver_win2k = {5,0};
220 const lamexp_os_version_t lamexp_winver_winxp = {5,1};
221 const lamexp_os_version_t lamexp_winver_xpx64 = {5,2};
222 const lamexp_os_version_t lamexp_winver_vista = {6,0};
223 const lamexp_os_version_t lamexp_winver_win70 = {6,1};
224 const lamexp_os_version_t lamexp_winver_win80 = {6,2};
225 const lamexp_os_version_t lamexp_winver_win81 = {6,3};
226
227 //GURU MEDITATION
228 static const char *GURU_MEDITATION = "\n\nGURU MEDITATION !!!\n\n";
229
230 ///////////////////////////////////////////////////////////////////////////////
231 // GLOBAL FUNCTIONS
232 ///////////////////////////////////////////////////////////////////////////////
233
234 /*
235  * Verify a specific Windows version
236  */
237 static bool lamexp_verify_os_version(const DWORD major, const DWORD minor)
238 {
239         OSVERSIONINFOEXW osvi;
240         DWORDLONG dwlConditionMask = 0;
241
242         //Initialize the OSVERSIONINFOEX structure
243         memset(&osvi, 0, sizeof(OSVERSIONINFOEXW));
244         osvi.dwOSVersionInfoSize = sizeof(OSVERSIONINFOEXW);
245         osvi.dwMajorVersion = major;
246         osvi.dwMinorVersion = minor;
247         osvi.dwPlatformId = VER_PLATFORM_WIN32_NT;
248
249         //Initialize the condition mask
250         VER_SET_CONDITION(dwlConditionMask, VER_MAJORVERSION, VER_GREATER_EQUAL);
251         VER_SET_CONDITION(dwlConditionMask, VER_MINORVERSION, VER_GREATER_EQUAL);
252         VER_SET_CONDITION(dwlConditionMask, VER_PLATFORMID, VER_EQUAL);
253
254         // Perform the test
255         const BOOL ret = VerifyVersionInfoW(&osvi, VER_MAJORVERSION | VER_MINORVERSION | VER_PLATFORMID, dwlConditionMask);
256
257         //Error checking
258         if(!ret)
259         {
260                 if(GetLastError() != ERROR_OLD_WIN_VERSION)
261                 {
262                         qWarning("VerifyVersionInfo() system call has failed!");
263                 }
264         }
265
266         return (ret != FALSE);
267 }
268
269 /*
270  * Determine the *real* Windows version
271  */
272 static bool lamexp_get_real_os_version(unsigned int *major, unsigned int *minor, bool *pbOverride)
273 {
274         *major = *minor = 0;
275         *pbOverride = false;
276         
277         //Initialize local variables
278         OSVERSIONINFOEXW osvi;
279         memset(&osvi, 0, sizeof(OSVERSIONINFOEXW));
280         osvi.dwOSVersionInfoSize = sizeof(OSVERSIONINFOEXW);
281
282         //Try GetVersionEx() first
283         if(GetVersionExW((LPOSVERSIONINFOW)&osvi) == FALSE)
284         {
285                 qWarning("GetVersionEx() has failed, cannot detect Windows version!");
286                 return false;
287         }
288
289         //Make sure we are running on NT
290         if(osvi.dwPlatformId == VER_PLATFORM_WIN32_NT)
291         {
292                 *major = osvi.dwMajorVersion;
293                 *minor = osvi.dwMinorVersion;
294         }
295         else
296         {
297                 qWarning("Not running on Windows NT, unsupported operating system!");
298                 return false;
299         }
300
301         //Determine the real *major* version first
302         forever
303         {
304                 const DWORD nextMajor = (*major) + 1;
305                 if(lamexp_verify_os_version(nextMajor, 0))
306                 {
307                         *pbOverride = true;
308                         *major = nextMajor;
309                         *minor = 0;
310                         continue;
311                 }
312                 break;
313         }
314
315         //Now also determine the real *minor* version
316         forever
317         {
318                 const DWORD nextMinor = (*minor) + 1;
319                 if(lamexp_verify_os_version((*major), nextMinor))
320                 {
321                         *pbOverride = true;
322                         *minor = nextMinor;
323                         continue;
324                 }
325                 break;
326         }
327
328         return true;
329 }
330
331 /*
332  * Get the native operating system version
333  */
334 const lamexp_os_version_t &lamexp_get_os_version(void)
335 {
336         QReadLocker readLock(&g_lamexp_os_version.lock);
337
338         //Already initialized?
339         if(g_lamexp_os_version.bInitialized)
340         {
341                 return g_lamexp_os_version.version;
342         }
343         
344         readLock.unlock();
345         QWriteLocker writeLock(&g_lamexp_os_version.lock);
346
347         //Detect OS version
348         if(!g_lamexp_os_version.bInitialized)
349         {
350                 unsigned int major, minor; bool oflag;
351                 if(lamexp_get_real_os_version(&major, &minor, &oflag))
352                 {
353                         g_lamexp_os_version.version.versionMajor = major;
354                         g_lamexp_os_version.version.versionMinor = minor;
355                         g_lamexp_os_version.version.overrideFlag = oflag;
356                         g_lamexp_os_version.bInitialized = true;
357                 }
358                 else
359                 {
360                         qWarning("Failed to determin the operating system version!");
361                 }
362         }
363
364         return g_lamexp_os_version.version;
365 }
366
367 /*
368  * Check if we are running under wine
369  */
370 bool lamexp_detect_wine(void)
371 {
372         QReadLocker readLock(&g_lamexp_wine.lock);
373
374         //Already initialized?
375         if(g_lamexp_wine.bInitialized)
376         {
377                 return g_lamexp_wine.bIsWine;
378         }
379         
380         readLock.unlock();
381         QWriteLocker writeLock(&g_lamexp_wine.lock);
382
383         if(!g_lamexp_wine.bInitialized)
384         {
385                 g_lamexp_wine.bIsWine = false;
386                 QLibrary ntdll("ntdll.dll");
387                 if(ntdll.load())
388                 {
389                         if(ntdll.resolve("wine_nt_to_unix_file_name") != NULL) g_lamexp_wine.bIsWine = true;
390                         if(ntdll.resolve("wine_get_version") != NULL) g_lamexp_wine.bIsWine = true;
391                         ntdll.unload();
392                 }
393                 g_lamexp_wine.bInitialized = true;
394         }
395
396         return g_lamexp_wine.bIsWine;
397 }
398
399 /*
400  * Change console text color
401  */
402 static void lamexp_console_color(FILE* file, WORD attributes)
403 {
404         const HANDLE hConsole = (HANDLE)(_get_osfhandle(_fileno(file)));
405         if((hConsole != NULL) && (hConsole != INVALID_HANDLE_VALUE))
406         {
407                 SetConsoleTextAttribute(hConsole, attributes);
408         }
409 }
410
411 /*
412  * Output logging message to console
413  */
414 static void lamexp_write_console(const int type, const char *msg)
415 {       
416         __try
417         {
418                 if(_isatty(_fileno(stderr)))
419                 {
420                         UINT oldOutputCP = GetConsoleOutputCP();
421                         if(oldOutputCP != CP_UTF8) SetConsoleOutputCP(CP_UTF8);
422
423                         switch(type)
424                         {
425                         case QtCriticalMsg:
426                         case QtFatalMsg:
427                                 lamexp_console_color(stderr, FOREGROUND_RED | FOREGROUND_INTENSITY);
428                                 fprintf(stderr, GURU_MEDITATION);
429                                 fprintf(stderr, "%s\n", msg);
430                                 fflush(stderr);
431                                 break;
432                         case QtWarningMsg:
433                                 lamexp_console_color(stderr, FOREGROUND_GREEN | FOREGROUND_RED | FOREGROUND_INTENSITY);
434                                 fprintf(stderr, "%s\n", msg);
435                                 fflush(stderr);
436                                 break;
437                         default:
438                                 lamexp_console_color(stderr, FOREGROUND_BLUE | FOREGROUND_GREEN | FOREGROUND_RED | FOREGROUND_INTENSITY);
439                                 fprintf(stderr, "%s\n", msg);
440                                 fflush(stderr);
441                                 break;
442                         }
443         
444                         lamexp_console_color(stderr, FOREGROUND_BLUE | FOREGROUND_GREEN | FOREGROUND_RED);
445                         if(oldOutputCP != CP_UTF8) SetConsoleOutputCP(oldOutputCP);
446                 }
447         }
448         __except(1)
449         {
450                 /*ignore any exception that might occur here!*/
451         }
452 }
453
454 /*
455  * Output logging message to debugger
456  */
457 static void lamexp_write_dbg_out(const int type, const char *msg)
458 {       
459         const char *FORMAT = "[LameXP][%c] %s\n";
460
461         __try
462         {
463                 char buffer[512];
464                 const char* input = msg;
465                 TRIM_LEFT(input);
466                 
467                 switch(type)
468                 {
469                 case QtCriticalMsg:
470                 case QtFatalMsg:
471                         _snprintf_s(buffer, 512, _TRUNCATE, FORMAT, 'C', input);
472                         break;
473                 case QtWarningMsg:
474                         _snprintf_s(buffer, 512, _TRUNCATE, FORMAT, 'W', input);
475                         break;
476                 default:
477                         _snprintf_s(buffer, 512, _TRUNCATE, FORMAT, 'I', input);
478                         break;
479                 }
480
481                 char *temp = &buffer[0];
482                 CLEAN_OUTPUT_STRING(temp);
483                 OutputDebugStringA(temp);
484         }
485         __except(1)
486         {
487                 /*ignore any exception that might occur here!*/
488         }
489 }
490
491 /*
492  * Output logging message to logfile
493  */
494 static void lamexp_write_logfile(const int type, const char *msg)
495 {       
496         const char *FORMAT = "[%c][%04u] %s\r\n";
497
498         __try
499         {
500                 if(g_lamexp_log_file)
501                 {
502                         char buffer[512];
503                         strncpy_s(buffer, 512, msg, _TRUNCATE);
504
505                         char *temp = &buffer[0];
506                         TRIM_LEFT(temp);
507                         CLEAN_OUTPUT_STRING(temp);
508                         
509                         const unsigned int timestamp = static_cast<unsigned int>(_time64(NULL) % 3600I64);
510
511                         switch(type)
512                         {
513                         case QtCriticalMsg:
514                         case QtFatalMsg:
515                                 fprintf(g_lamexp_log_file, FORMAT, 'C', timestamp, temp);
516                                 break;
517                         case QtWarningMsg:
518                                 fprintf(g_lamexp_log_file, FORMAT, 'W', timestamp, temp);
519                                 break;
520                         default:
521                                 fprintf(g_lamexp_log_file, FORMAT, 'I', timestamp, temp);
522                                 break;
523                         }
524
525                         fflush(g_lamexp_log_file);
526                 }
527         }
528         __except(1)
529         {
530                 /*ignore any exception that might occur here!*/
531         }
532 }
533
534 /*
535  * Qt message handler
536  */
537 void lamexp_message_handler(QtMsgType type, const char *msg)
538 {
539         if((!msg) || (!(msg[0])))
540         {
541                 return;
542         }
543
544         QMutexLocker lock(&g_lamexp_message_mutex);
545
546         if(g_lamexp_log_file)
547         {
548                 lamexp_write_logfile(type, msg);
549         }
550
551         if(g_lamexp_console_attached)
552         {
553                 lamexp_write_console(type, msg);
554         }
555         else
556         {
557                 lamexp_write_dbg_out(type, msg);
558         }
559
560         if((type == QtCriticalMsg) || (type == QtFatalMsg))
561         {
562                 lock.unlock();
563                 lamexp_fatal_exit(L"The application has encountered a critical error and will exit now!", QWCHAR(QString::fromUtf8(msg)));
564         }
565 }
566
567 /*
568  * Invalid parameters handler
569  */
570 static void lamexp_invalid_param_handler(const wchar_t* exp, const wchar_t* fun, const wchar_t* fil, unsigned int, uintptr_t)
571 {
572         lamexp_fatal_exit(L"Invalid parameter handler invoked, application will exit!");
573 }
574
575 /*
576  * Signal handler
577  */
578 static void lamexp_signal_handler(int signal_num)
579 {
580         signal(signal_num, lamexp_signal_handler);
581         lamexp_fatal_exit(L"Signal handler invoked, application will exit!");
582 }
583
584 /*
585  * Global exception handler
586  */
587 static LONG WINAPI lamexp_exception_handler(struct _EXCEPTION_POINTERS *ExceptionInfo)
588 {
589         lamexp_fatal_exit(L"Unhandeled exception handler invoked, application will exit!");
590         return LONG_MAX;
591 }
592
593 /*
594  * Initialize error handlers
595  */
596 void lamexp_init_error_handlers(void)
597 {
598         SetErrorMode(SEM_FAILCRITICALERRORS | SEM_NOOPENFILEERRORBOX);
599         SetUnhandledExceptionFilter(lamexp_exception_handler);
600         SetThreadPriority(GetCurrentThread(), THREAD_PRIORITY_ABOVE_NORMAL);
601         _set_invalid_parameter_handler(lamexp_invalid_param_handler);
602         
603         static const int signal_num[6] = { SIGABRT, SIGFPE, SIGILL, SIGINT, SIGSEGV, SIGTERM };
604
605         for(size_t i = 0; i < 6; i++)
606         {
607                 signal(signal_num[i], lamexp_signal_handler);
608         }
609 }
610
611 /*
612  * Initialize the console
613  */
614 void lamexp_init_console(const QStringList &argv)
615 {
616         bool enableConsole = (LAMEXP_DEBUG) || ((VER_LAMEXP_CONSOLE_ENABLED) && lamexp_version_demo());
617
618         if(_environ)
619         {
620                 wchar_t *logfile = NULL;
621                 size_t logfile_len = 0;
622                 if(!_wdupenv_s(&logfile, &logfile_len, L"LAMEXP_LOGFILE"))
623                 {
624                         if(logfile && (logfile_len > 0))
625                         {
626                                 FILE *temp = NULL;
627                                 if(!_wfopen_s(&temp, logfile, L"wb"))
628                                 {
629                                         fprintf(temp, "%c%c%c", char(0xEF), char(0xBB), char(0xBF));
630                                         g_lamexp_log_file = temp;
631                                 }
632                                 free(logfile);
633                         }
634                 }
635         }
636
637         if(!LAMEXP_DEBUG)
638         {
639                 for(int i = 0; i < argv.count(); i++)
640                 {
641                         if(!argv.at(i).compare("--console", Qt::CaseInsensitive))
642                         {
643                                 enableConsole = true;
644                         }
645                         else if(!argv.at(i).compare("--no-console", Qt::CaseInsensitive))
646                         {
647                                 enableConsole = false;
648                         }
649                 }
650         }
651
652         if(enableConsole)
653         {
654                 if(!g_lamexp_console_attached)
655                 {
656                         if(AllocConsole() != FALSE)
657                         {
658                                 SetConsoleCtrlHandler(NULL, TRUE);
659                                 SetConsoleTitle(L"LameXP - Audio Encoder Front-End | Debug Console");
660                                 SetConsoleOutputCP(CP_UTF8);
661                                 g_lamexp_console_attached = true;
662                         }
663                 }
664                 
665                 if(g_lamexp_console_attached)
666                 {
667                         //-------------------------------------------------------------------
668                         //See: http://support.microsoft.com/default.aspx?scid=kb;en-us;105305
669                         //-------------------------------------------------------------------
670                         const int flags = _O_WRONLY | _O_U8TEXT;
671                         int hCrtStdOut = _open_osfhandle((intptr_t) GetStdHandle(STD_OUTPUT_HANDLE), flags);
672                         int hCrtStdErr = _open_osfhandle((intptr_t) GetStdHandle(STD_ERROR_HANDLE),  flags);
673                         FILE *hfStdOut = (hCrtStdOut >= 0) ? _fdopen(hCrtStdOut, "wb") : NULL;
674                         FILE *hfStdErr = (hCrtStdErr >= 0) ? _fdopen(hCrtStdErr, "wb") : NULL;
675                         if(hfStdOut) { *stdout = *hfStdOut; std::cout.rdbuf(new std::filebuf(hfStdOut)); }
676                         if(hfStdErr) { *stderr = *hfStdErr; std::cerr.rdbuf(new std::filebuf(hfStdErr)); }
677                 }
678
679                 HWND hwndConsole = GetConsoleWindow();
680
681                 if((hwndConsole != NULL) && (hwndConsole != INVALID_HANDLE_VALUE))
682                 {
683                         HMENU hMenu = GetSystemMenu(hwndConsole, 0);
684                         EnableMenuItem(hMenu, SC_CLOSE, MF_BYCOMMAND | MF_GRAYED);
685                         RemoveMenu(hMenu, SC_CLOSE, MF_BYCOMMAND);
686
687                         SetWindowPos(hwndConsole, HWND_TOP, 0, 0, 0, 0, SWP_NOMOVE|SWP_NOSIZE|SWP_NOZORDER|SWP_FRAMECHANGED);
688                         SetWindowLong(hwndConsole, GWL_STYLE, GetWindowLong(hwndConsole, GWL_STYLE) & (~WS_MAXIMIZEBOX) & (~WS_MINIMIZEBOX));
689                         SetWindowPos(hwndConsole, HWND_TOP, 0, 0, 0, 0, SWP_NOMOVE|SWP_NOSIZE|SWP_NOZORDER|SWP_FRAMECHANGED);
690                 }
691         }
692 }
693
694 /*
695  * Detect CPU features
696  */
697 lamexp_cpu_t lamexp_detect_cpu_features(const QStringList &argv)
698 {
699         typedef BOOL (WINAPI *IsWow64ProcessFun)(__in HANDLE hProcess, __out PBOOL Wow64Process);
700
701         lamexp_cpu_t features;
702         SYSTEM_INFO systemInfo;
703         int CPUInfo[4] = {-1};
704         char CPUIdentificationString[0x40];
705         char CPUBrandString[0x40];
706
707         memset(&features, 0, sizeof(lamexp_cpu_t));
708         memset(&systemInfo, 0, sizeof(SYSTEM_INFO));
709         memset(CPUIdentificationString, 0, sizeof(CPUIdentificationString));
710         memset(CPUBrandString, 0, sizeof(CPUBrandString));
711         
712         __cpuid(CPUInfo, 0);
713         memcpy(CPUIdentificationString, &CPUInfo[1], sizeof(int));
714         memcpy(CPUIdentificationString + 4, &CPUInfo[3], sizeof(int));
715         memcpy(CPUIdentificationString + 8, &CPUInfo[2], sizeof(int));
716         features.intel = (_stricmp(CPUIdentificationString, "GenuineIntel") == 0);
717         strncpy_s(features.vendor, 0x40, CPUIdentificationString, _TRUNCATE);
718
719         if(CPUInfo[0] >= 1)
720         {
721                 __cpuid(CPUInfo, 1);
722                 features.mmx = (CPUInfo[3] & 0x800000) || false;
723                 features.sse = (CPUInfo[3] & 0x2000000) || false;
724                 features.sse2 = (CPUInfo[3] & 0x4000000) || false;
725                 features.ssse3 = (CPUInfo[2] & 0x200) || false;
726                 features.sse3 = (CPUInfo[2] & 0x1) || false;
727                 features.ssse3 = (CPUInfo[2] & 0x200) || false;
728                 features.stepping = CPUInfo[0] & 0xf;
729                 features.model = ((CPUInfo[0] >> 4) & 0xf) + (((CPUInfo[0] >> 16) & 0xf) << 4);
730                 features.family = ((CPUInfo[0] >> 8) & 0xf) + ((CPUInfo[0] >> 20) & 0xff);
731         }
732
733         __cpuid(CPUInfo, 0x80000000);
734         int nExIds = qMax<int>(qMin<int>(CPUInfo[0], 0x80000004), 0x80000000);
735
736         for(int i = 0x80000002; i <= nExIds; ++i)
737         {
738                 __cpuid(CPUInfo, i);
739                 switch(i)
740                 {
741                 case 0x80000002:
742                         memcpy(CPUBrandString, CPUInfo, sizeof(CPUInfo));
743                         break;
744                 case 0x80000003:
745                         memcpy(CPUBrandString + 16, CPUInfo, sizeof(CPUInfo));
746                         break;
747                 case 0x80000004:
748                         memcpy(CPUBrandString + 32, CPUInfo, sizeof(CPUInfo));
749                         break;
750                 }
751         }
752
753         strncpy_s(features.brand, 0x40, CPUBrandString, _TRUNCATE);
754
755         if(strlen(features.brand) < 1) strncpy_s(features.brand, 0x40, "Unknown", _TRUNCATE);
756         if(strlen(features.vendor) < 1) strncpy_s(features.vendor, 0x40, "Unknown", _TRUNCATE);
757
758 #if (!(defined(_M_X64) || defined(_M_IA64)))
759         QLibrary Kernel32Lib("kernel32.dll");
760         if(IsWow64ProcessFun IsWow64ProcessPtr = (IsWow64ProcessFun) Kernel32Lib.resolve("IsWow64Process"))
761         {
762                 BOOL x64flag = FALSE;
763                 if(IsWow64ProcessPtr(GetCurrentProcess(), &x64flag))
764                 {
765                         features.x64 = (x64flag == TRUE);
766                 }
767         }
768 #else
769         features.x64 = true;
770 #endif
771
772         DWORD_PTR procAffinity, sysAffinity;
773         if(GetProcessAffinityMask(GetCurrentProcess(), &procAffinity, &sysAffinity))
774         {
775                 for(DWORD_PTR mask = 1; mask; mask <<= 1)
776                 {
777                         features.count += ((sysAffinity & mask) ? (1) : (0));
778                 }
779         }
780         if(features.count < 1)
781         {
782                 GetNativeSystemInfo(&systemInfo);
783                 features.count = qBound(1UL, systemInfo.dwNumberOfProcessors, 64UL);
784         }
785
786         if(argv.count() > 0)
787         {
788                 bool flag = false;
789                 for(int i = 0; i < argv.count(); i++)
790                 {
791                         if(!argv[i].compare("--force-cpu-no-64bit", Qt::CaseInsensitive)) { flag = true; features.x64 = false; }
792                         if(!argv[i].compare("--force-cpu-no-sse", Qt::CaseInsensitive)) { flag = true; features.sse = features.sse2 = features.sse3 = features.ssse3 = false; }
793                         if(!argv[i].compare("--force-cpu-no-intel", Qt::CaseInsensitive)) { flag = true; features.intel = false; }
794                 }
795                 if(flag) qWarning("CPU flags overwritten by user-defined parameters. Take care!\n");
796         }
797
798         return features;
799 }
800
801 /*
802  * Check for debugger (detect routine)
803  */
804 static __forceinline bool lamexp_check_for_debugger(void)
805 {
806         __try
807         {
808                 CloseHandle((HANDLE)((DWORD_PTR)-3));
809         }
810         __except(1)
811         {
812                 return true;
813         }
814         __try 
815         {
816                 __debugbreak();
817         }
818         __except(1) 
819         {
820                 return IsDebuggerPresent();
821         }
822         return true;
823 }
824
825 /*
826  * Check for debugger (thread proc)
827  */
828 static unsigned int __stdcall lamexp_debug_thread_proc(LPVOID lpParameter)
829 {
830         SetThreadPriority(GetCurrentThread(), THREAD_PRIORITY_LOWEST);
831         forever
832         {
833                 if(lamexp_check_for_debugger())
834                 {
835                         lamexp_fatal_exit(L"Not a debug build. Please unload debugger and try again!");
836                         return 666;
837                 }
838                 lamexp_sleep(100);
839         }
840 }
841
842 /*
843  * Check for debugger (startup routine)
844  */
845 static HANDLE lamexp_debug_thread_init()
846 {
847         if(lamexp_check_for_debugger())
848         {
849                 lamexp_fatal_exit(L"Not a debug build. Please unload debugger and try again!");
850         }
851         const uintptr_t h = _beginthreadex(NULL, 0, lamexp_debug_thread_proc, NULL, 0, NULL);
852         return (HANDLE)(h^0xdeadbeef);
853 }
854
855 /*
856  * Qt event filter
857  */
858 static bool lamexp_event_filter(void *message, long *result)
859
860         if((!(LAMEXP_DEBUG)) && lamexp_check_for_debugger())
861         {
862                 lamexp_fatal_exit(L"Not a debug build. Please unload debugger and try again!");
863         }
864         
865         switch(reinterpret_cast<MSG*>(message)->message)
866         {
867         case WM_QUERYENDSESSION:
868                 qWarning("WM_QUERYENDSESSION message received!");
869                 *result = lamexp_broadcast(lamexp_event_queryendsession, false) ? TRUE : FALSE;
870                 return true;
871         case WM_ENDSESSION:
872                 qWarning("WM_ENDSESSION message received!");
873                 if(reinterpret_cast<MSG*>(message)->wParam == TRUE)
874                 {
875                         lamexp_broadcast(lamexp_event_endsession, false);
876                         if(QApplication *app = reinterpret_cast<QApplication*>(QApplication::instance()))
877                         {
878                                 app->closeAllWindows();
879                                 app->quit();
880                         }
881                         lamexp_finalization();
882                         exit(1);
883                 }
884                 *result = 0;
885                 return true;
886         default:
887                 /*ignore this message and let Qt handle it*/
888                 return false;
889         }
890 }
891
892 /*
893  * Check for process elevation
894  */
895 static bool lamexp_process_is_elevated(bool *bIsUacEnabled = NULL)
896 {
897         bool bIsProcessElevated = false;
898         if(bIsUacEnabled) *bIsUacEnabled = false;
899         HANDLE hToken = NULL;
900         
901         if(OpenProcessToken(GetCurrentProcess(), TOKEN_QUERY, &hToken))
902         {
903                 TOKEN_ELEVATION_TYPE tokenElevationType;
904                 DWORD returnLength;
905                 if(GetTokenInformation(hToken, TokenElevationType, &tokenElevationType, sizeof(TOKEN_ELEVATION_TYPE), &returnLength))
906                 {
907                         if(returnLength == sizeof(TOKEN_ELEVATION_TYPE))
908                         {
909                                 switch(tokenElevationType)
910                                 {
911                                 case TokenElevationTypeDefault:
912                                         qDebug("Process token elevation type: Default -> UAC is disabled.\n");
913                                         break;
914                                 case TokenElevationTypeFull:
915                                         qWarning("Process token elevation type: Full -> potential security risk!\n");
916                                         bIsProcessElevated = true;
917                                         if(bIsUacEnabled) *bIsUacEnabled = true;
918                                         break;
919                                 case TokenElevationTypeLimited:
920                                         qDebug("Process token elevation type: Limited -> not elevated.\n");
921                                         if(bIsUacEnabled) *bIsUacEnabled = true;
922                                         break;
923                                 default:
924                                         qWarning("Unknown tokenElevationType value: %d", tokenElevationType);
925                                         break;
926                                 }
927                         }
928                         else
929                         {
930                                 qWarning("GetTokenInformation() return an unexpected size!");
931                         }
932                 }
933                 CloseHandle(hToken);
934         }
935         else
936         {
937                 qWarning("Failed to open process token!");
938         }
939
940         return bIsProcessElevated;
941 }
942
943 /*
944  * Convert QIcon to HICON -> caller is responsible for destroying the HICON!
945  */
946 static HICON lamexp_qicon2hicon(const QIcon &icon, const int w, const int h)
947 {
948         if(!icon.isNull())
949         {
950                 QPixmap pixmap = icon.pixmap(w, h);
951                 if(!pixmap.isNull())
952                 {
953                         return pixmap.toWinHICON();
954                 }
955         }
956         return NULL;
957 }
958
959 /*
960  * Initialize Qt framework
961  */
962 bool lamexp_init_qt(int argc, char* argv[])
963 {
964         static bool qt_initialized = false;
965         typedef BOOL (WINAPI *SetDllDirectoryProc)(WCHAR *lpPathName);
966         const QStringList &arguments = lamexp_arguments();
967
968         //Don't initialized again, if done already
969         if(qt_initialized)
970         {
971                 return true;
972         }
973
974         //Secure DLL loading
975         QLibrary kernel32("kernel32.dll");
976         if(kernel32.load())
977         {
978                 SetDllDirectoryProc pSetDllDirectory = (SetDllDirectoryProc) kernel32.resolve("SetDllDirectoryW");
979                 if(pSetDllDirectory != NULL) pSetDllDirectory(L"");
980         }
981
982         //Extract executable name from argv[] array
983         QString executableName = QLatin1String("LameXP.exe");
984         if(arguments.count() > 0)
985         {
986                 static const char *delimiters = "\\/:?";
987                 executableName = arguments[0].trimmed();
988                 for(int i = 0; delimiters[i]; i++)
989                 {
990                         int temp = executableName.lastIndexOf(QChar(delimiters[i]));
991                         if(temp >= 0) executableName = executableName.mid(temp + 1);
992                 }
993                 executableName = executableName.trimmed();
994                 if(executableName.isEmpty())
995                 {
996                         executableName = QLatin1String("LameXP.exe");
997                 }
998         }
999
1000         //Check Qt version
1001 #ifdef QT_BUILD_KEY
1002         qDebug("Using Qt v%s [%s], %s, %s", qVersion(), QLibraryInfo::buildDate().toString(Qt::ISODate).toLatin1().constData(), (qSharedBuild() ? "DLL" : "Static"), QLibraryInfo::buildKey().toLatin1().constData());
1003         qDebug("Compiled with Qt v%s [%s], %s\n", QT_VERSION_STR, QT_PACKAGEDATE_STR, QT_BUILD_KEY);
1004         if(_stricmp(qVersion(), QT_VERSION_STR))
1005         {
1006                 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());
1007                 return false;
1008         }
1009         if(QLibraryInfo::buildKey().compare(QString::fromLatin1(QT_BUILD_KEY), Qt::CaseInsensitive))
1010         {
1011                 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());
1012                 return false;
1013         }
1014 #else
1015         qDebug("Using Qt v%s [%s], %s", qVersion(), QLibraryInfo::buildDate().toString(Qt::ISODate).toLatin1().constData(), (qSharedBuild() ? "DLL" : "Static"));
1016         qDebug("Compiled with Qt v%s [%s]\n", QT_VERSION_STR, QT_PACKAGEDATE_STR);
1017 #endif
1018
1019         //Check the Windows version
1020         const lamexp_os_version_t &osVersionNo = lamexp_get_os_version();
1021         if(osVersionNo < lamexp_winver_winxp)
1022         {
1023                 qFatal("%s", QApplication::tr("Executable '%1' requires Windows XP or later.").arg(executableName).toLatin1().constData());
1024         }
1025
1026         //Supported Windows version?
1027         if(osVersionNo == lamexp_winver_winxp)
1028         {
1029                 qDebug("Running on Windows XP or Windows XP Media Center Edition.\n");                                          //lamexp_check_compatibility_mode("GetLargePageMinimum", executableName);
1030         }
1031         else if(osVersionNo == lamexp_winver_xpx64)
1032         {
1033                 qDebug("Running on Windows Server 2003, Windows Server 2003 R2 or Windows XP x64.\n");          //lamexp_check_compatibility_mode("GetLocaleInfoEx", executableName);
1034         }
1035         else if(osVersionNo == lamexp_winver_vista)
1036         {
1037                 qDebug("Running on Windows Vista or Windows Server 2008.\n");                                                           //lamexp_check_compatibility_mode("CreateRemoteThreadEx", executableName*/);
1038         }
1039         else if(osVersionNo == lamexp_winver_win70)
1040         {
1041                 qDebug("Running on Windows 7 or Windows Server 2008 R2.\n");                                                            //lamexp_check_compatibility_mode("CreateFile2", executableName);
1042         }
1043         else if(osVersionNo == lamexp_winver_win80)
1044         {
1045                 qDebug("Running on Windows 8 or Windows Server 2012.\n");                                                                       //lamexp_check_compatibility_mode("FindPackagesByPackageFamily", executableName);
1046         }
1047         else if(osVersionNo == lamexp_winver_win81)
1048         {
1049                 qDebug("Running on Windows 8.1 or Windows Server 2012 R2.\n");                                                          //lamexp_check_compatibility_mode(NULL, executableName);
1050         }
1051         else
1052         {
1053                 const QString message = QString().sprintf("Running on an unknown WindowsNT-based system (v%u.%u).", osVersionNo.versionMajor, osVersionNo.versionMinor);
1054                 qWarning("%s\n", QUTF8(message));
1055                 MessageBoxW(NULL, QWCHAR(message), L"LameXP", MB_OK | MB_TOPMOST | MB_ICONWARNING);
1056         }
1057
1058         //Check for compat mode
1059         if(osVersionNo.overrideFlag && (osVersionNo <= lamexp_winver_win81))
1060         {
1061                 qWarning("Windows compatibility mode detected!");
1062                 if(!arguments.contains("--ignore-compat-mode", Qt::CaseInsensitive))
1063                 {
1064                         qFatal("%s", QApplication::tr("Executable '%1' doesn't support Windows compatibility mode.").arg(executableName).toLatin1().constData());
1065                         return false;
1066                 }
1067         }
1068
1069         //Check for Wine
1070         if(lamexp_detect_wine())
1071         {
1072                 qWarning("It appears we are running under Wine, unexpected things might happen!\n");
1073         }
1074
1075         //Set text Codec for locale
1076         QTextCodec::setCodecForLocale(QTextCodec::codecForName("UTF-8"));
1077
1078         //Create Qt application instance
1079         QApplication *application = new QApplication(argc, argv);
1080
1081         //Load plugins from application directory
1082         QCoreApplication::setLibraryPaths(QStringList() << QApplication::applicationDirPath());
1083         qDebug("Library Path:\n%s\n", QUTF8(QApplication::libraryPaths().first()));
1084
1085         //Set application properties
1086         application->setApplicationName("LameXP - Audio Encoder Front-End");
1087         application->setApplicationVersion(QString().sprintf("%d.%02d.%04d", lamexp_version_major(), lamexp_version_minor(), lamexp_version_build())); 
1088         application->setOrganizationName("LoRd_MuldeR");
1089         application->setOrganizationDomain("mulder.at.gg");
1090         application->setWindowIcon(lamexp_app_icon());
1091         application->setEventFilter(lamexp_event_filter);
1092
1093         //Check for supported image formats
1094         QList<QByteArray> supportedFormats = QImageReader::supportedImageFormats();
1095         for(int i = 0; g_lamexp_imageformats[i]; i++)
1096         {
1097                 if(!supportedFormats.contains(g_lamexp_imageformats[i]))
1098                 {
1099                         qFatal("Qt initialization error: QImageIOHandler for '%s' missing!", g_lamexp_imageformats[i]);
1100                         return false;
1101                 }
1102         }
1103         
1104         //Add the default translations
1105         lamexp_translation_init();
1106
1107         //Check for process elevation
1108         if(lamexp_process_is_elevated() && (!lamexp_detect_wine()))
1109         {
1110                 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);
1111                 messageBox.addButton("Quit Program (Recommended)", QMessageBox::NoRole);
1112                 messageBox.addButton("Ignore", QMessageBox::NoRole);
1113                 if(messageBox.exec() == 0)
1114                 {
1115                         return false;
1116                 }
1117         }
1118
1119         //Update console icon, if a console is attached
1120 #if QT_VERSION < QT_VERSION_CHECK(5,0,0)
1121         if(g_lamexp_console_attached && (!lamexp_detect_wine()))
1122         {
1123                 QLibrary kernel32("kernel32.dll");
1124                 if(kernel32.load())
1125                 {
1126                         typedef DWORD (__stdcall *SetConsoleIconFun)(HICON);
1127                         if(SetConsoleIconFun SetConsoleIconPtr = (SetConsoleIconFun) kernel32.resolve("SetConsoleIcon"))
1128                         {
1129                                 if(HICON hIcon = lamexp_qicon2hicon(QIcon(":/icons/sound.png"), 16, 16))
1130                                 {
1131                                         SetConsoleIconPtr(hIcon);
1132                                         DestroyIcon(hIcon);
1133                                 }
1134                         }
1135                 }
1136         }
1137 #endif
1138
1139         //Done
1140         qt_initialized = true;
1141         return true;
1142 }
1143
1144 const QStringList &lamexp_arguments(void)
1145 {
1146         QReadLocker readLock(&g_lamexp_argv.lock);
1147
1148         if(!g_lamexp_argv.list)
1149         {
1150                 readLock.unlock();
1151                 QWriteLocker writeLock(&g_lamexp_argv.lock);
1152
1153                 g_lamexp_argv.list = new QStringList;
1154
1155                 int nArgs = 0;
1156                 LPWSTR *szArglist = CommandLineToArgvW(GetCommandLineW(), &nArgs);
1157
1158                 if(NULL != szArglist)
1159                 {
1160                         for(int i = 0; i < nArgs; i++)
1161                         {
1162                                 (*g_lamexp_argv.list) << WCHAR2QSTR(szArglist[i]);
1163                         }
1164                         LocalFree(szArglist);
1165                 }
1166                 else
1167                 {
1168                         qWarning("CommandLineToArgvW() has failed !!!");
1169                 }
1170         }
1171
1172         return (*g_lamexp_argv.list);
1173 }
1174
1175 /*
1176  * Locate known folder on local system
1177  */
1178 const QString &lamexp_known_folder(lamexp_known_folder_t folder_id)
1179 {
1180         static const int CSIDL_FLAG_CREATE = 0x8000;
1181         typedef enum { KF_FLAG_CREATE = 0x00008000 } kf_flags_t;
1182         
1183         struct
1184         {
1185                 const int csidl;
1186                 const GUID guid;
1187         }
1188         static s_folders[] =
1189         {
1190                 { 0x001c, {0xF1B32785,0x6FBA,0x4FCF,{0x9D,0x55,0x7B,0x8E,0x7F,0x15,0x70,0x91}} },  //CSIDL_LOCAL_APPDATA
1191                 { 0x0026, {0x905e63b6,0xc1bf,0x494e,{0xb2,0x9c,0x65,0xb7,0x32,0xd3,0xd2,0x1a}} },  //CSIDL_PROGRAM_FILES
1192                 { 0x0024, {0xF38BF404,0x1D43,0x42F2,{0x93,0x05,0x67,0xDE,0x0B,0x28,0xFC,0x23}} },  //CSIDL_WINDOWS_FOLDER
1193                 { 0x0025, {0x1AC14E77,0x02E7,0x4E5D,{0xB7,0x44,0x2E,0xB1,0xAE,0x51,0x98,0xB7}} },  //CSIDL_SYSTEM_FOLDER
1194         };
1195
1196         size_t folderId = size_t(-1);
1197
1198         switch(folder_id)
1199         {
1200                 case lamexp_folder_localappdata: folderId = 0; break;
1201                 case lamexp_folder_programfiles: folderId = 1; break;
1202                 case lamexp_folder_systroot_dir: folderId = 2; break;
1203                 case lamexp_folder_systemfolder: folderId = 3; break;
1204         }
1205
1206         if(folderId == size_t(-1))
1207         {
1208                 qWarning("Invalid 'known' folder was requested!");
1209                 return *reinterpret_cast<QString*>(NULL);
1210         }
1211
1212         QReadLocker readLock(&g_lamexp_known_folder.lock);
1213
1214         //Already in cache?
1215         if(g_lamexp_known_folder.knownFolders)
1216         {
1217                 if(g_lamexp_known_folder.knownFolders->contains(folderId))
1218                 {
1219                         return (*g_lamexp_known_folder.knownFolders)[folderId];
1220                 }
1221         }
1222
1223         //Obtain write lock to initialize
1224         readLock.unlock();
1225         QWriteLocker writeLock(&g_lamexp_known_folder.lock);
1226
1227         //Still not in cache?
1228         if(g_lamexp_known_folder.knownFolders)
1229         {
1230                 if(g_lamexp_known_folder.knownFolders->contains(folderId))
1231                 {
1232                         return (*g_lamexp_known_folder.knownFolders)[folderId];
1233                 }
1234         }
1235
1236         //Initialize on first call
1237         if(!g_lamexp_known_folder.knownFolders)
1238         {
1239                 QLibrary shell32("shell32.dll");
1240                 if(shell32.load())
1241                 {
1242                         g_lamexp_known_folder.getFolderPath =      (SHGetFolderPath_t)      shell32.resolve("SHGetFolderPathW");
1243                         g_lamexp_known_folder.getKnownFolderPath = (SHGetKnownFolderPath_t) shell32.resolve("SHGetKnownFolderPath");
1244                 }
1245                 g_lamexp_known_folder.knownFolders = new QMap<size_t, QString>();
1246         }
1247
1248         QString folderPath;
1249
1250         //Now try to get the folder path!
1251         if(g_lamexp_known_folder.getKnownFolderPath)
1252         {
1253                 WCHAR *path = NULL;
1254                 if(g_lamexp_known_folder.getKnownFolderPath(s_folders[folderId].guid, KF_FLAG_CREATE, NULL, &path) == S_OK)
1255                 {
1256                         //MessageBoxW(0, path, L"SHGetKnownFolderPath", MB_TOPMOST);
1257                         QDir folderTemp = QDir(QDir::fromNativeSeparators(QString::fromUtf16(reinterpret_cast<const unsigned short*>(path))));
1258                         if(folderTemp.exists())
1259                         {
1260                                 folderPath = folderTemp.canonicalPath();
1261                         }
1262                         CoTaskMemFree(path);
1263                 }
1264         }
1265         else if(g_lamexp_known_folder.getFolderPath)
1266         {
1267                 WCHAR *path = new WCHAR[4096];
1268                 if(g_lamexp_known_folder.getFolderPath(NULL, s_folders[folderId].csidl | CSIDL_FLAG_CREATE, NULL, NULL, path) == S_OK)
1269                 {
1270                         //MessageBoxW(0, path, L"SHGetFolderPathW", MB_TOPMOST);
1271                         QDir folderTemp = QDir(QDir::fromNativeSeparators(QString::fromUtf16(reinterpret_cast<const unsigned short*>(path))));
1272                         if(folderTemp.exists())
1273                         {
1274                                 folderPath = folderTemp.canonicalPath();
1275                         }
1276                 }
1277                 LAMEXP_DELETE_ARRAY(path);
1278         }
1279
1280         //Update cache
1281         g_lamexp_known_folder.knownFolders->insert(folderId, folderPath);
1282         return (*g_lamexp_known_folder.knownFolders)[folderId];
1283 }
1284
1285 /*
1286  * Safely remove a file
1287  */
1288 bool lamexp_remove_file(const QString &filename)
1289 {
1290         if(!QFileInfo(filename).exists() || !QFileInfo(filename).isFile())
1291         {
1292                 return true;
1293         }
1294         else
1295         {
1296                 if(!QFile::remove(filename))
1297                 {
1298                         static const DWORD attrMask = FILE_ATTRIBUTE_READONLY | FILE_ATTRIBUTE_HIDDEN | FILE_ATTRIBUTE_SYSTEM;
1299                         const DWORD attributes = GetFileAttributesW(QWCHAR(filename));
1300                         if(attributes & attrMask)
1301                         {
1302                                 SetFileAttributesW(QWCHAR(filename), FILE_ATTRIBUTE_NORMAL);
1303                         }
1304                         if(!QFile::remove(filename))
1305                         {
1306                                 qWarning("Could not delete \"%s\"", filename.toLatin1().constData());
1307                                 return false;
1308                         }
1309                         else
1310                         {
1311                                 return true;
1312                         }
1313                 }
1314                 else
1315                 {
1316                         return true;
1317                 }
1318         }
1319 }
1320
1321 /*
1322  * Check if visual themes are enabled (WinXP and later)
1323  */
1324 bool lamexp_themes_enabled(void)
1325 {
1326         typedef int (WINAPI *IsAppThemedFun)(void);
1327         
1328         QReadLocker readLock(&g_lamexp_themes_enabled.lock);
1329         if(g_lamexp_themes_enabled.bInitialized)
1330         {
1331                 return g_lamexp_themes_enabled.bThemesEnabled;
1332         }
1333
1334         readLock.unlock();
1335         QWriteLocker writeLock(&g_lamexp_themes_enabled.lock);
1336
1337         if(!g_lamexp_themes_enabled.bInitialized)
1338         {
1339                 g_lamexp_themes_enabled.bThemesEnabled = false;
1340                 const lamexp_os_version_t &osVersion = lamexp_get_os_version();
1341                 if(osVersion >= lamexp_winver_winxp)
1342                 {
1343                         IsAppThemedFun IsAppThemedPtr = NULL;
1344                         QLibrary uxTheme(QString("%1/UxTheme.dll").arg(lamexp_known_folder(lamexp_folder_systemfolder)));
1345                         if(uxTheme.load())
1346                         {
1347                                 IsAppThemedPtr = (IsAppThemedFun) uxTheme.resolve("IsAppThemed");
1348                         }
1349                         if(IsAppThemedPtr)
1350                         {
1351                                 g_lamexp_themes_enabled.bThemesEnabled = IsAppThemedPtr();
1352                                 if(!g_lamexp_themes_enabled.bThemesEnabled)
1353                                 {
1354                                         qWarning("Theme support is disabled for this process!");
1355                                 }
1356                         }
1357                 }
1358                 g_lamexp_themes_enabled.bInitialized = true;
1359         }
1360
1361         return g_lamexp_themes_enabled.bThemesEnabled;
1362 }
1363
1364 /*
1365  * Get number of free bytes on disk
1366  */
1367 unsigned __int64 lamexp_free_diskspace(const QString &path, bool *ok)
1368 {
1369         ULARGE_INTEGER freeBytesAvailable, totalNumberOfBytes, totalNumberOfFreeBytes;
1370         if(GetDiskFreeSpaceExW(reinterpret_cast<const wchar_t*>(QDir::toNativeSeparators(path).utf16()), &freeBytesAvailable, &totalNumberOfBytes, &totalNumberOfFreeBytes))
1371         {
1372                 if(ok) *ok = true;
1373                 return freeBytesAvailable.QuadPart;
1374         }
1375         else
1376         {
1377                 if(ok) *ok = false;
1378                 return 0;
1379         }
1380 }
1381
1382 /*
1383  * Check if computer does support hibernation
1384  */
1385 bool lamexp_is_hibernation_supported(void)
1386 {
1387         bool hibernationSupported = false;
1388
1389         SYSTEM_POWER_CAPABILITIES pwrCaps;
1390         SecureZeroMemory(&pwrCaps, sizeof(SYSTEM_POWER_CAPABILITIES));
1391         
1392         if(GetPwrCapabilities(&pwrCaps))
1393         {
1394                 hibernationSupported = pwrCaps.SystemS4 && pwrCaps.HiberFilePresent;
1395         }
1396
1397         return hibernationSupported;
1398 }
1399
1400 /*
1401  * Shutdown the computer
1402  */
1403 bool lamexp_shutdown_computer(const QString &message, const unsigned long timeout, const bool forceShutdown, const bool hibernate)
1404 {
1405         HANDLE hToken = NULL;
1406
1407         if(OpenProcessToken(GetCurrentProcess(), TOKEN_ADJUST_PRIVILEGES | TOKEN_QUERY, &hToken))
1408         {
1409                 TOKEN_PRIVILEGES privileges;
1410                 memset(&privileges, 0, sizeof(TOKEN_PRIVILEGES));
1411                 privileges.PrivilegeCount = 1;
1412                 privileges.Privileges[0].Attributes = SE_PRIVILEGE_ENABLED;
1413                 
1414                 if(LookupPrivilegeValue(NULL, SE_SHUTDOWN_NAME, &privileges.Privileges[0].Luid))
1415                 {
1416                         if(AdjustTokenPrivileges(hToken, FALSE, &privileges, NULL, NULL, NULL))
1417                         {
1418                                 if(hibernate)
1419                                 {
1420                                         if(SetSuspendState(TRUE, TRUE, TRUE))
1421                                         {
1422                                                 return true;
1423                                         }
1424                                 }
1425                                 const DWORD reason = SHTDN_REASON_MAJOR_APPLICATION | SHTDN_REASON_FLAG_PLANNED;
1426                                 return InitiateSystemShutdownEx(NULL, const_cast<wchar_t*>(QWCHAR(message)), timeout, forceShutdown ? TRUE : FALSE, FALSE, reason);
1427                         }
1428                 }
1429         }
1430         
1431         return false;
1432 }
1433
1434 /*
1435  * Determines the current date, resistant against certain manipulations
1436  */
1437 QDate lamexp_current_date_safe(void)
1438 {
1439         const DWORD MAX_PROC = 1024;
1440         DWORD *processes = new DWORD[MAX_PROC];
1441         DWORD bytesReturned = 0;
1442         
1443         if(!EnumProcesses(processes, sizeof(DWORD) * MAX_PROC, &bytesReturned))
1444         {
1445                 LAMEXP_DELETE_ARRAY(processes);
1446                 return QDate::currentDate();
1447         }
1448
1449         const DWORD procCount = bytesReturned / sizeof(DWORD);
1450         ULARGE_INTEGER lastStartTime;
1451         memset(&lastStartTime, 0, sizeof(ULARGE_INTEGER));
1452
1453         for(DWORD i = 0; i < procCount; i++)
1454         {
1455                 HANDLE hProc = OpenProcess(PROCESS_QUERY_INFORMATION, FALSE, processes[i]);
1456                 if(hProc)
1457                 {
1458                         FILETIME processTime[4];
1459                         if(GetProcessTimes(hProc, &processTime[0], &processTime[1], &processTime[2], &processTime[3]))
1460                         {
1461                                 ULARGE_INTEGER timeCreation;
1462                                 timeCreation.LowPart = processTime[0].dwLowDateTime;
1463                                 timeCreation.HighPart = processTime[0].dwHighDateTime;
1464                                 if(timeCreation.QuadPart > lastStartTime.QuadPart)
1465                                 {
1466                                         lastStartTime.QuadPart = timeCreation.QuadPart;
1467                                 }
1468                         }
1469                         CloseHandle(hProc);
1470                 }
1471         }
1472
1473         LAMEXP_DELETE_ARRAY(processes);
1474         
1475         FILETIME lastStartTime_fileTime;
1476         lastStartTime_fileTime.dwHighDateTime = lastStartTime.HighPart;
1477         lastStartTime_fileTime.dwLowDateTime = lastStartTime.LowPart;
1478
1479         FILETIME lastStartTime_localTime;
1480         if(!FileTimeToLocalFileTime(&lastStartTime_fileTime, &lastStartTime_localTime))
1481         {
1482                 memcpy(&lastStartTime_localTime, &lastStartTime_fileTime, sizeof(FILETIME));
1483         }
1484         
1485         SYSTEMTIME lastStartTime_system;
1486         if(!FileTimeToSystemTime(&lastStartTime_localTime, &lastStartTime_system))
1487         {
1488                 memset(&lastStartTime_system, 0, sizeof(SYSTEMTIME));
1489                 lastStartTime_system.wYear = 1970; lastStartTime_system.wMonth = lastStartTime_system.wDay = 1;
1490         }
1491
1492         const QDate currentDate = QDate::currentDate();
1493         const QDate processDate = QDate(lastStartTime_system.wYear, lastStartTime_system.wMonth, lastStartTime_system.wDay);
1494         return (currentDate >= processDate) ? currentDate : processDate;
1495 }
1496
1497 /*
1498  * Show system message box
1499  */
1500 int lamexp_system_message(const wchar_t *text, int beepType)
1501 {
1502         UINT flags = MB_OK | MB_TOPMOST;
1503
1504         switch(beepType)
1505         {
1506                 case lamexp_beep_info:    flags = flags | MB_ICONASTERISK;
1507                 case lamexp_beep_warning: flags = flags | MB_ICONEXCLAMATION;
1508                 case lamexp_beep_error:   flags = flags | MB_ICONHAND;
1509         }
1510
1511         return MessageBoxW(NULL, text, L"LameXP", flags);
1512 }
1513
1514 /*
1515  * Block window "move" message
1516  */
1517 bool lamexp_block_window_move(void *message)
1518 {
1519         if(message)
1520         {
1521                 MSG *msg = reinterpret_cast<MSG*>(message);
1522                 if((msg->message == WM_SYSCOMMAND) && (msg->wParam == SC_MOVE))
1523                 {
1524                         return true;
1525                 }
1526                 if((msg->message == WM_NCLBUTTONDOWN) && (msg->wParam == HTCAPTION))
1527                 {
1528                         return true;
1529                 }
1530         }
1531         return false;
1532 }
1533
1534 /*
1535  * Suspend calling thread for N milliseconds
1536  */
1537 inline void lamexp_sleep(const unsigned int delay)
1538 {
1539         Sleep(delay);
1540 }
1541
1542 bool lamexp_beep(int beepType)
1543 {
1544         switch(beepType)
1545         {
1546                 case lamexp_beep_info:    return MessageBeep(MB_ICONASTERISK) == TRUE;    break;
1547                 case lamexp_beep_warning: return MessageBeep(MB_ICONEXCLAMATION) == TRUE; break;
1548                 case lamexp_beep_error:   return MessageBeep(MB_ICONHAND) == TRUE;        break;
1549                 default: return false;
1550         }
1551 }
1552
1553 /*
1554  * Play a sound (from resources)
1555  */
1556 bool lamexp_play_sound(const QString &name, const bool bAsync)
1557 {
1558         const unsigned char *data = NULL;
1559         
1560         //Try to look-up the sound in the cache first
1561         if(!name.isEmpty())
1562         {
1563                 QReadLocker readLock(&g_lamexp_sounds.lock);
1564                 if(g_lamexp_sounds.sound_db && g_lamexp_sounds.sound_db->contains(name))
1565                 {
1566                         data = g_lamexp_sounds.sound_db->value(name);
1567                 }
1568         }
1569         
1570         //If data not found in cache, try to load from resource!
1571         if((!data) && (!name.isEmpty()))
1572         {
1573                 QResource resource(QString(":/sounds/%1.wav").arg(name));
1574                 if(resource.isValid() && (data = resource.data()))
1575                 {
1576                         QWriteLocker writeLock(&g_lamexp_sounds.lock);
1577                         if(!g_lamexp_sounds.sound_db)
1578                         {
1579                                 g_lamexp_sounds.sound_db = new QHash<const QString, const unsigned char*>();
1580                         }
1581                         g_lamexp_sounds.sound_db->insert(name, data);
1582                 }
1583                 else
1584                 {
1585                         qWarning("Sound effect \"%s\" not found!", QUTF8(name));
1586                 }
1587         }
1588
1589         //Play the sound, if availbale
1590         if(data)
1591         {
1592                 return PlaySound(LPCWSTR(data), NULL, (SND_MEMORY | (bAsync ? SND_ASYNC : SND_SYNC))) != FALSE;
1593         }
1594
1595         return false;
1596 }
1597
1598 /*
1599  * Play a sound (system alias)
1600  */
1601 bool lamexp_play_sound_alias(const QString &alias, const bool bAsync)
1602 {
1603         return PlaySound(QWCHAR(alias), GetModuleHandle(NULL), (SND_ALIAS | (bAsync ? SND_ASYNC : SND_SYNC))) != FALSE;
1604 }
1605
1606 /*
1607  * Play a sound (from external DLL)
1608  */
1609 bool lamexp_play_sound_file(const QString &library, const unsigned short uiSoundIdx, const bool bAsync)
1610 {
1611         bool result = false;
1612
1613         QFileInfo libraryFile(library);
1614         if(!libraryFile.isAbsolute())
1615         {
1616                 const QString &systemDir = lamexp_known_folder(lamexp_folder_systemfolder);
1617                 if(!systemDir.isEmpty())
1618                 {
1619                         libraryFile.setFile(QDir(systemDir), libraryFile.fileName());
1620                 }
1621         }
1622
1623         if(libraryFile.exists() && libraryFile.isFile())
1624         {
1625                 if(HMODULE module = LoadLibraryW(QWCHAR(QDir::toNativeSeparators(libraryFile.canonicalFilePath()))))
1626                 {
1627                         result = (PlaySound(MAKEINTRESOURCE(uiSoundIdx), module, (SND_RESOURCE | (bAsync ? SND_ASYNC : SND_SYNC))) != FALSE);
1628                         FreeLibrary(module);
1629                 }
1630         }
1631         else
1632         {
1633                 qWarning("PlaySound: File \"%s\" could not be found!", QUTF8(libraryFile.absoluteFilePath()));
1634         }
1635
1636         return result;
1637 }
1638
1639 /*
1640  * Open file using the shell
1641  */
1642 bool lamexp_exec_shell(const QWidget *win, const QString &url, const bool explore)
1643 {
1644         return lamexp_exec_shell(win, url, QString(), QString(), explore);
1645 }
1646
1647 /*
1648  * Open file using the shell (with parameters)
1649  */
1650 bool lamexp_exec_shell(const QWidget *win, const QString &url, const QString &parameters, const QString &directory, const bool explore)
1651 {
1652         return ((int) ShellExecuteW(((win) ? win->winId() : NULL), (explore ? L"explore" : L"open"), QWCHAR(url), ((!parameters.isEmpty()) ? QWCHAR(parameters) : NULL), ((!directory.isEmpty()) ? QWCHAR(directory) : NULL), SW_SHOW)) > 32;
1653 }
1654
1655         /*
1656  * Query value of the performance counter
1657  */
1658 __int64 lamexp_perfcounter_value(void)
1659 {
1660         LARGE_INTEGER counter;
1661         if(QueryPerformanceCounter(&counter) == TRUE)
1662         {
1663                 return counter.QuadPart;
1664         }
1665         return -1;
1666 }
1667
1668 /*
1669  * Query frequency of the performance counter
1670  */
1671 __int64 lamexp_perfcounter_frequ(void)
1672 {
1673         LARGE_INTEGER frequency;
1674         if(QueryPerformanceFrequency(&frequency) == TRUE)
1675         {
1676                 return frequency.QuadPart;
1677         }
1678         return -1;
1679 }
1680
1681 /*
1682  * Insert entry to the window's system menu
1683  */
1684 bool lamexp_append_sysmenu(const QWidget *win, const unsigned int identifier, const QString &text)
1685 {
1686         bool ok = false;
1687         
1688         if(HMENU hMenu = GetSystemMenu(win->winId(), FALSE))
1689         {
1690                 ok = (AppendMenuW(hMenu, MF_SEPARATOR, 0, 0) == TRUE);
1691                 ok = (AppendMenuW(hMenu, MF_STRING, identifier, QWCHAR(text)) == TRUE);
1692         }
1693
1694         return ok;
1695 }
1696
1697 /*
1698  * Insert entry to the window's system menu
1699  */
1700 bool lamexp_check_sysmenu_msg(void *message, const unsigned int identifier)
1701 {
1702         return (((MSG*)message)->message == WM_SYSCOMMAND) && ((((MSG*)message)->wParam & 0xFFF0) == identifier);
1703 }
1704
1705 /*
1706  * Update system menu entry
1707  */
1708 bool lamexp_update_sysmenu(const QWidget *win, const unsigned int identifier, const QString &text)
1709 {
1710         bool ok = false;
1711         
1712         if(HMENU hMenu = ::GetSystemMenu(win->winId(), FALSE))
1713         {
1714                 ok = (ModifyMenu(hMenu, identifier, MF_STRING | MF_BYCOMMAND, identifier, QWCHAR(text)) == TRUE);
1715         }
1716         return ok;
1717 }
1718
1719 /*
1720  * Display the window's close button
1721  */
1722 bool lamexp_enable_close_button(const QWidget *win, const bool bEnable)
1723 {
1724         bool ok = false;
1725
1726         if(HMENU hMenu = GetSystemMenu(win->winId(), FALSE))
1727         {
1728                 ok = (EnableMenuItem(hMenu, SC_CLOSE, MF_BYCOMMAND | (bEnable ? MF_ENABLED : MF_GRAYED)) == TRUE);
1729         }
1730
1731         return ok;
1732 }
1733
1734 /*
1735  * Check whether ESC key has been pressed since the previous call to this function
1736  */
1737 bool lamexp_check_escape_state(void)
1738 {
1739         return (GetAsyncKeyState(VK_ESCAPE) & 0x0001) != 0;
1740 }
1741
1742 /*
1743  * Set the process priority class for current process
1744  */
1745 bool lamexp_change_process_priority(const int priority)
1746 {
1747         return lamexp_change_process_priority(GetCurrentProcess(), priority);
1748 }
1749
1750 /*
1751  * Set the process priority class for specified process
1752  */
1753 bool lamexp_change_process_priority(const QProcess *proc, const int priority)
1754 {
1755         if(Q_PID qPid = proc->pid())
1756         {
1757                 return lamexp_change_process_priority(qPid->hProcess, priority);
1758         }
1759         else
1760         {
1761                 return false;
1762         }
1763 }
1764
1765 /*
1766  * Set the process priority class for specified process
1767  */
1768 bool lamexp_change_process_priority(void *hProcess, const int priority)
1769 {
1770         bool ok = false;
1771
1772         switch(qBound(-2, priority, 2))
1773         {
1774         case 2:
1775                 ok = (SetPriorityClass(hProcess, HIGH_PRIORITY_CLASS) == TRUE);
1776                 break;
1777         case 1:
1778                 if(!(ok = (SetPriorityClass(hProcess, ABOVE_NORMAL_PRIORITY_CLASS) == TRUE)))
1779                 {
1780                         ok = (SetPriorityClass(hProcess, HIGH_PRIORITY_CLASS) == TRUE);
1781                 }
1782                 break;
1783         case 0:
1784                 ok = (SetPriorityClass(hProcess, NORMAL_PRIORITY_CLASS) == TRUE);
1785                 break;
1786         case -1:
1787                 if(!(ok = (SetPriorityClass(hProcess, BELOW_NORMAL_PRIORITY_CLASS) == TRUE)))
1788                 {
1789                         ok = (SetPriorityClass(hProcess, IDLE_PRIORITY_CLASS) == TRUE);
1790                 }
1791                 break;
1792         case -2:
1793                 ok = (SetPriorityClass(hProcess, IDLE_PRIORITY_CLASS) == TRUE);
1794                 break;
1795         }
1796
1797         return ok;
1798 }
1799
1800 /*
1801  * Returns the current file time
1802  */
1803 unsigned __int64 lamexp_current_file_time(void)
1804 {
1805         FILETIME fileTime;
1806         GetSystemTimeAsFileTime(&fileTime);
1807
1808         ULARGE_INTEGER temp;
1809         temp.HighPart = fileTime.dwHighDateTime;
1810         temp.LowPart = fileTime.dwLowDateTime;
1811
1812         return temp.QuadPart;
1813 }
1814
1815 /*
1816  * Bring the specifed window to the front
1817  */
1818 bool lamexp_bring_to_front(const QWidget *window)
1819 {
1820         bool ret = false;
1821         
1822         if(window)
1823         {
1824                 for(int i = 0; (i < 5) && (!ret); i++)
1825                 {
1826                         ret = (SetForegroundWindow(window->winId()) != FALSE);
1827                         SwitchToThisWindow(window->winId(), TRUE);
1828                 }
1829                 LockSetForegroundWindow(LSFW_LOCK);
1830         }
1831
1832         return ret;
1833 }
1834
1835 /*
1836  * Bring window of the specifed process to the front (callback)
1837  */
1838 static BOOL CALLBACK lamexp_bring_process_to_front_helper(HWND hwnd, LPARAM lParam)
1839 {
1840         DWORD processId = *reinterpret_cast<WORD*>(lParam);
1841         DWORD windowProcessId = NULL;
1842         GetWindowThreadProcessId(hwnd, &windowProcessId);
1843         if(windowProcessId == processId)
1844         {
1845                 SwitchToThisWindow(hwnd, TRUE);
1846                 SetForegroundWindow(hwnd);
1847                 return FALSE;
1848         }
1849
1850         return TRUE;
1851 }
1852
1853 /*
1854  * Bring window of the specifed process to the front
1855  */
1856 bool lamexp_bring_process_to_front(const unsigned long pid)
1857 {
1858         return EnumWindows(lamexp_bring_process_to_front_helper, reinterpret_cast<LPARAM>(&pid)) == TRUE;
1859 }
1860
1861 /*
1862  * Check the network connectivity status
1863  */
1864 int lamexp_network_status(void)
1865 {
1866         DWORD dwFlags;
1867         const BOOL ret = IsNetworkAlive(&dwFlags);
1868         if(GetLastError() == 0)
1869         {
1870                 return (ret != FALSE) ? lamexp_network_yes : lamexp_network_non;
1871         }
1872         return lamexp_network_err;
1873 }
1874
1875 /*
1876  * Retrun the process ID of the given QProcess
1877  */
1878 unsigned long lamexp_process_id(const QProcess *proc)
1879 {
1880         PROCESS_INFORMATION *procInf = proc->pid();
1881         return (procInf) ? procInf->dwProcessId : NULL;
1882 }
1883
1884 /*
1885  * Convert long path to short path
1886  */
1887 QString lamexp_path_to_short(const QString &longPath)
1888 {
1889         QString shortPath;
1890         DWORD buffSize = GetShortPathNameW(reinterpret_cast<const wchar_t*>(longPath.utf16()), NULL, NULL);
1891         
1892         if(buffSize > 0)
1893         {
1894                 wchar_t *buffer = new wchar_t[buffSize];
1895                 DWORD result = GetShortPathNameW(reinterpret_cast<const wchar_t*>(longPath.utf16()), buffer, buffSize);
1896
1897                 if(result > 0 && result < buffSize)
1898                 {
1899                         shortPath = QString::fromUtf16(reinterpret_cast<const unsigned short*>(buffer));
1900                 }
1901
1902                 delete[] buffer;
1903         }
1904
1905         return (shortPath.isEmpty() ? longPath : shortPath);
1906 }
1907
1908 /*
1909  * Open media file in external player
1910  */
1911 bool lamexp_open_media_file(const QString &mediaFilePath)
1912 {
1913         const static wchar_t *registryPrefix[2] = { L"SOFTWARE\\", L"SOFTWARE\\Wow6432Node\\" };
1914         const static wchar_t *registryKeys[3] = 
1915         {
1916                 L"Microsoft\\Windows\\CurrentVersion\\Uninstall\\{97D341C8-B0D1-4E4A-A49A-C30B52F168E9}",
1917                 L"Microsoft\\Windows\\CurrentVersion\\Uninstall\\{DB9E4EAB-2717-499F-8D56-4CC8A644AB60}",
1918                 L"foobar2000"
1919         };
1920         const static wchar_t *appNames[4] = { L"smplayer_portable.exe", L"smplayer.exe", L"MPUI.exe", L"foobar2000.exe" };
1921         const static wchar_t *valueNames[2] = { L"InstallLocation", L"InstallDir" };
1922
1923         for(size_t i = 0; i < 3; i++)
1924         {
1925                 for(size_t j = 0; j < 2; j++)
1926                 {
1927                         QString mplayerPath;
1928                         HKEY registryKeyHandle = NULL;
1929
1930                         const QString currentKey = WCHAR2QSTR(registryPrefix[j]).append(WCHAR2QSTR(registryKeys[i]));
1931                         if(RegOpenKeyExW(HKEY_LOCAL_MACHINE, QWCHAR(currentKey), 0, KEY_READ, &registryKeyHandle) == ERROR_SUCCESS)
1932                         {
1933                                 for(size_t k = 0; k < 2; k++)
1934                                 {
1935                                         wchar_t Buffer[4096];
1936                                         DWORD BuffSize = sizeof(wchar_t*) * 4096;
1937                                         DWORD DataType = REG_NONE;
1938                                         if(RegQueryValueExW(registryKeyHandle, valueNames[k], 0, &DataType, reinterpret_cast<BYTE*>(Buffer), &BuffSize) == ERROR_SUCCESS)
1939                                         {
1940                                                 if((DataType == REG_SZ) || (DataType == REG_EXPAND_SZ) || (DataType == REG_LINK))
1941                                                 {
1942                                                         mplayerPath = WCHAR2QSTR(Buffer);
1943                                                         break;
1944                                                 }
1945                                         }
1946                                 }
1947                                 RegCloseKey(registryKeyHandle);
1948                         }
1949
1950                         if(!mplayerPath.isEmpty())
1951                         {
1952                                 QDir mplayerDir(mplayerPath);
1953                                 if(mplayerDir.exists())
1954                                 {
1955                                         for(size_t k = 0; k < 4; k++)
1956                                         {
1957                                                 if(mplayerDir.exists(WCHAR2QSTR(appNames[k])))
1958                                                 {
1959                                                         qDebug("Player found at:\n%s\n", QUTF8(mplayerDir.absoluteFilePath(WCHAR2QSTR(appNames[k]))));
1960                                                         QProcess::startDetached(mplayerDir.absoluteFilePath(WCHAR2QSTR(appNames[k])), QStringList() << QDir::toNativeSeparators(mediaFilePath));
1961                                                         return true;
1962                                                 }
1963                                         }
1964                                 }
1965                         }
1966                 }
1967         }
1968         return false;
1969 }
1970
1971 static void lamexp_init_dwmapi(void)
1972 {
1973         QReadLocker writeLock(&g_lamexp_dwmapi.lock);
1974
1975         //Not initialized yet?
1976         if(g_lamexp_dwmapi.bInitialized)
1977         {
1978                 return;
1979         }
1980         
1981         //Reset function pointers
1982         g_lamexp_dwmapi.dwmIsCompositionEnabled = NULL;
1983         g_lamexp_dwmapi.dwmExtendFrameIntoClientArea = NULL;
1984         g_lamexp_dwmapi.dwmEnableBlurBehindWindow = NULL;
1985                         
1986         //Does OS support DWM?
1987         if(lamexp_get_os_version() >= lamexp_winver_vista)
1988         {
1989                 //Load DWMAPI.DLL
1990                 g_lamexp_dwmapi.dwmapi_dll = new QLibrary("dwmapi.dll");
1991                 if(g_lamexp_dwmapi.dwmapi_dll->load())
1992                 {
1993                         //Initialize function pointers
1994                         g_lamexp_dwmapi.dwmIsCompositionEnabled      = (HRESULT (__stdcall*)(BOOL*))                       g_lamexp_dwmapi.dwmapi_dll->resolve("DwmIsCompositionEnabled");
1995                         g_lamexp_dwmapi.dwmExtendFrameIntoClientArea = (HRESULT (__stdcall*)(HWND, const MARGINS*))        g_lamexp_dwmapi.dwmapi_dll->resolve("DwmExtendFrameIntoClientArea");
1996                         g_lamexp_dwmapi.dwmEnableBlurBehindWindow    = (HRESULT (__stdcall*)(HWND, const DWM_BLURBEHIND*)) g_lamexp_dwmapi.dwmapi_dll->resolve("DwmEnableBlurBehindWindow");
1997                 }
1998                 else
1999                 {
2000                         LAMEXP_DELETE(g_lamexp_dwmapi.dwmapi_dll);
2001                         qWarning("Failed to load DWMAPI.DLL on a DWM-enabled system!");
2002                 }
2003         }
2004
2005         g_lamexp_dwmapi.bInitialized = true;
2006 }
2007
2008 /*
2009  * Enable "sheet of glass" effect on the given Window
2010  */
2011 bool lamexp_sheet_of_glass(QWidget *window)
2012 {
2013         QReadLocker readLock(&g_lamexp_dwmapi.lock);
2014
2015         //Initialize the DWM API
2016         while(!g_lamexp_dwmapi.bInitialized)
2017         {
2018                 readLock.unlock();
2019                 lamexp_init_dwmapi();
2020                 readLock.relock();
2021         }
2022
2023         BOOL bCompositionEnabled = FALSE;
2024
2025         //Required functions available?
2026         if((g_lamexp_dwmapi.dwmIsCompositionEnabled != NULL) && (g_lamexp_dwmapi.dwmExtendFrameIntoClientArea != NULL) && (g_lamexp_dwmapi.dwmEnableBlurBehindWindow != NULL))
2027         {
2028                 //Check if composition is currently enabled
2029                 if(HRESULT hr = g_lamexp_dwmapi.dwmIsCompositionEnabled(&bCompositionEnabled))
2030                 {
2031                         qWarning("DwmIsCompositionEnabled function has failed! (error %d)", hr);
2032                         return false;
2033                 }
2034         }
2035         
2036         //All functions available *and* composition enabled?
2037         if(!bCompositionEnabled)
2038         {
2039                 return false;
2040         }
2041
2042         //Enable the "sheet of glass" effect on this window
2043         MARGINS margins = {-1, -1, -1, -1};
2044         if(HRESULT hr = g_lamexp_dwmapi.dwmExtendFrameIntoClientArea(window->winId(), &margins))
2045         {
2046                 qWarning("DwmExtendFrameIntoClientArea function has failed! (error %d)", hr);
2047                 return false;
2048         }
2049
2050         //Create and populate the Blur Behind structure
2051         DWM_BLURBEHIND bb;
2052         memset(&bb, 0, sizeof(DWM_BLURBEHIND));
2053         bb.fEnable = TRUE;
2054         bb.dwFlags = DWM_BB_ENABLE;
2055         if(HRESULT hr = g_lamexp_dwmapi.dwmEnableBlurBehindWindow(window->winId(), &bb))
2056         {
2057                 qWarning("DwmEnableBlurBehindWindow function has failed! (error %d)", hr);
2058                 return false;
2059         }
2060
2061         //Required for Qt
2062         window->setAutoFillBackground(false);
2063         window->setAttribute(Qt::WA_TranslucentBackground);
2064         window->setAttribute(Qt::WA_NoSystemBackground);
2065
2066         return true;
2067 }
2068
2069 /*
2070  * Update "sheet of glass" effect on the given Window
2071  */
2072 bool lamexp_sheet_of_glass_update(QWidget *window)
2073 {
2074         QReadLocker readLock(&g_lamexp_dwmapi.lock);
2075
2076         //Initialize the DWM API
2077         while(!g_lamexp_dwmapi.bInitialized)
2078         {
2079                 readLock.unlock();
2080                 lamexp_init_dwmapi();
2081                 readLock.relock();
2082         }
2083
2084         BOOL bCompositionEnabled = FALSE;
2085
2086         //Required functions available?
2087         if((g_lamexp_dwmapi.dwmIsCompositionEnabled != NULL) && (g_lamexp_dwmapi.dwmEnableBlurBehindWindow != NULL))
2088         {
2089                 //Check if composition is currently enabled
2090                 if(HRESULT hr = g_lamexp_dwmapi.dwmIsCompositionEnabled(&bCompositionEnabled))
2091                 {
2092                         qWarning("DwmIsCompositionEnabled function has failed! (error %d)", hr);
2093                         return false;
2094                 }
2095         }
2096         
2097         //All functions available *and* composition enabled?
2098         if(!bCompositionEnabled)
2099         {
2100                 return false;
2101         }
2102
2103         //Create and populate the Blur Behind structure
2104         DWM_BLURBEHIND bb;
2105         memset(&bb, 0, sizeof(DWM_BLURBEHIND));
2106         bb.fEnable = TRUE;
2107         bb.dwFlags = DWM_BB_ENABLE;
2108         if(HRESULT hr = g_lamexp_dwmapi.dwmEnableBlurBehindWindow(window->winId(), &bb))
2109         {
2110                 qWarning("DwmEnableBlurBehindWindow function has failed! (error %d)", hr);
2111                 return false;
2112         }
2113
2114         return true;
2115 }
2116
2117 /*
2118  * Update the window icon
2119  */
2120 lamexp_icon_t *lamexp_set_window_icon(QWidget *window, const QIcon &icon, const bool bIsBigIcon)
2121 {
2122         if(!icon.isNull())
2123         {
2124                 const int extend = (bIsBigIcon ? 32 : 16);
2125                 if(HICON hIcon = lamexp_qicon2hicon(icon, extend, extend))
2126                 {
2127                         SendMessage(window->winId(), WM_SETICON, (bIsBigIcon ? ICON_BIG : ICON_SMALL), LPARAM(hIcon));
2128                         return reinterpret_cast<lamexp_icon_t*>(hIcon);
2129                 }
2130         }
2131         return NULL;
2132 }
2133
2134 /*
2135  * Free window icon
2136  */
2137 void lamexp_free_window_icon(lamexp_icon_t *icon)
2138 {
2139         if(HICON hIcon = reinterpret_cast<HICON>(icon))
2140         {
2141                 DestroyIcon(hIcon);
2142         }
2143 }
2144
2145 /*
2146  * Get system color info
2147  */
2148 QColor lamexp_system_color(const int color_id)
2149 {
2150         int nIndex = -1;
2151
2152         switch(color_id)
2153         {
2154         case lamexp_syscolor_text:
2155                 nIndex = COLOR_WINDOWTEXT;       /*Text in windows*/
2156                 break;
2157         case lamexp_syscolor_background:
2158                 nIndex = COLOR_WINDOW;           /*Window background*/
2159                 break;
2160         case lamexp_syscolor_caption:
2161                 nIndex = COLOR_CAPTIONTEXT;      /*Text in caption, size box, and scroll bar arrow box*/
2162                 break;
2163         default:
2164                 qWarning("Unknown system color id (%d) specified!", color_id);
2165                 nIndex = COLOR_WINDOWTEXT;
2166         }
2167         
2168         const DWORD rgb = GetSysColor(nIndex);
2169         QColor color(GetRValue(rgb), GetGValue(rgb), GetBValue(rgb));
2170         return color;
2171 }
2172
2173 /*
2174  * Check if the current user is an administartor (helper function)
2175  */
2176 static bool lamexp_user_is_admin_helper(void)
2177 {
2178         HANDLE hToken = NULL;
2179         if(!OpenProcessToken(GetCurrentProcess(), TOKEN_QUERY, &hToken))
2180         {
2181                 return false;
2182         }
2183
2184         DWORD dwSize = 0;
2185         if(!GetTokenInformation(hToken, TokenGroups, NULL, 0, &dwSize))
2186         {
2187                 if(GetLastError() != ERROR_INSUFFICIENT_BUFFER)
2188                 {
2189                         CloseHandle(hToken);
2190                         return false;
2191                 }
2192         }
2193
2194         PTOKEN_GROUPS lpGroups = (PTOKEN_GROUPS) malloc(dwSize);
2195         if(!lpGroups)
2196         {
2197                 CloseHandle(hToken);
2198                 return false;
2199         }
2200
2201         if(!GetTokenInformation(hToken, TokenGroups, lpGroups, dwSize, &dwSize))
2202         {
2203                 free(lpGroups);
2204                 CloseHandle(hToken);
2205                 return false;
2206         }
2207
2208         PSID lpSid = NULL; SID_IDENTIFIER_AUTHORITY Authority = {SECURITY_NT_AUTHORITY};
2209         if(!AllocateAndInitializeSid(&Authority, 2, SECURITY_BUILTIN_DOMAIN_RID, DOMAIN_ALIAS_RID_ADMINS, 0, 0, 0, 0, 0, 0, &lpSid))
2210         {
2211                 free(lpGroups);
2212                 CloseHandle(hToken);
2213                 return false;
2214         }
2215
2216         bool bResult = false;
2217         for(DWORD i = 0; i < lpGroups->GroupCount; i++)
2218         {
2219                 if(EqualSid(lpSid, lpGroups->Groups[i].Sid))
2220                 {
2221                         bResult = true;
2222                         break;
2223                 }
2224         }
2225
2226         FreeSid(lpSid);
2227         free(lpGroups);
2228         CloseHandle(hToken);
2229         return bResult;
2230 }
2231
2232 /*
2233  * Check if the current user is an administartor
2234  */
2235 bool lamexp_user_is_admin(void)
2236 {
2237         bool isAdmin = false;
2238
2239         //Check for process elevation and UAC support first!
2240         if(lamexp_process_is_elevated(&isAdmin))
2241         {
2242                 qWarning("Process is elevated -> user is admin!");
2243                 return true;
2244         }
2245         
2246         //If not elevated and UAC is not available -> user must be in admin group!
2247         if(!isAdmin)
2248         {
2249                 qDebug("UAC is disabled/unavailable -> checking for Administrators group");
2250                 isAdmin = lamexp_user_is_admin_helper();
2251         }
2252
2253         return isAdmin;
2254 }
2255
2256 /*
2257  * Check if file is a valid Win32/Win64 executable
2258  */
2259 bool lamexp_is_executable(const QString &path)
2260 {
2261         bool bIsExecutable = false;
2262         DWORD binaryType;
2263         if(GetBinaryType(QWCHAR(QDir::toNativeSeparators(path)), &binaryType))
2264         {
2265                 bIsExecutable = (binaryType == SCS_32BIT_BINARY || binaryType == SCS_64BIT_BINARY);
2266         }
2267         return bIsExecutable;
2268 }
2269
2270 /*
2271  * Fatal application exit
2272  */
2273 #pragma intrinsic(_InterlockedExchange)
2274 void lamexp_fatal_exit(const wchar_t* exitMessage, const wchar_t* errorBoxMessage)
2275 {
2276         static volatile long bFatalFlag = 0L;
2277
2278         if(_InterlockedExchange(&bFatalFlag, 1L) == 0L)
2279         {
2280                 if(GetCurrentThreadId() != g_main_thread_id)
2281                 {
2282                         HANDLE mainThread = OpenThread(THREAD_TERMINATE, FALSE, g_main_thread_id);
2283                         if(mainThread) TerminateThread(mainThread, ULONG_MAX);
2284                 }
2285         
2286                 if(errorBoxMessage)
2287                 {
2288                         MessageBoxW(NULL, errorBoxMessage, L"LameXP - GURU MEDITATION", MB_ICONERROR | MB_TOPMOST | MB_TASKMODAL);
2289                 }
2290
2291                 for(;;)
2292                 {
2293                         FatalAppExit(0, exitMessage);
2294                         TerminateProcess(GetCurrentProcess(), -1);
2295                 }
2296         }
2297
2298         TerminateThread(GetCurrentThread(), -1);
2299         Sleep(INFINITE);
2300 }
2301
2302 /*
2303  * Initialize debug thread
2304  */
2305 static const HANDLE g_debug_thread1 = LAMEXP_DEBUG ? NULL : lamexp_debug_thread_init();
2306
2307 /*
2308  * Get number private bytes [debug only]
2309  */
2310 unsigned long lamexp_dbg_private_bytes(void)
2311 {
2312 #if LAMEXP_DEBUG
2313         for(int i = 0; i < 8; i++) _heapmin();
2314         PROCESS_MEMORY_COUNTERS_EX memoryCounters;
2315         memoryCounters.cb = sizeof(PROCESS_MEMORY_COUNTERS_EX);
2316         GetProcessMemoryInfo(GetCurrentProcess(), (PPROCESS_MEMORY_COUNTERS) &memoryCounters, sizeof(PROCESS_MEMORY_COUNTERS_EX));
2317         return memoryCounters.PrivateUsage;
2318 #else
2319         THROW("Cannot call this function in a non-debug build!");
2320 #endif //LAMEXP_DEBUG
2321 }
2322
2323 /*
2324  * Output string to debugger [debug only]
2325  */
2326 void lamexp_dbg_dbg_output_string(const char* format, ...)
2327 {
2328 #if LAMEXP_DEBUG
2329         char buffer[256];
2330         va_list args;
2331         va_start (args, format);
2332         vsnprintf_s(buffer, 256, _TRUNCATE, format, args);
2333         OutputDebugStringA(buffer);
2334         va_end(args);
2335 #else
2336         THROW("Cannot call this function in a non-debug build!");
2337 #endif //LAMEXP_DEBUG
2338 }
2339
2340 ///////////////////////////////////////////////////////////////////////////////
2341 // INITIALIZATION
2342 ///////////////////////////////////////////////////////////////////////////////
2343
2344 extern "C" void _lamexp_global_init_win32(void)
2345 {
2346         if((!LAMEXP_DEBUG) && lamexp_check_for_debugger())
2347         {
2348                 lamexp_fatal_exit(L"Not a debug build. Please unload debugger and try again!");
2349         }
2350
2351         //Zero *before* constructors are called
2352         LAMEXP_ZERO_MEMORY(g_lamexp_argv);
2353         LAMEXP_ZERO_MEMORY(g_lamexp_known_folder);
2354         LAMEXP_ZERO_MEMORY(g_lamexp_os_version);
2355         LAMEXP_ZERO_MEMORY(g_lamexp_wine);
2356         LAMEXP_ZERO_MEMORY(g_lamexp_themes_enabled);
2357         LAMEXP_ZERO_MEMORY(g_lamexp_dwmapi);
2358         LAMEXP_ZERO_MEMORY(g_lamexp_sounds);
2359 }
2360
2361 ///////////////////////////////////////////////////////////////////////////////
2362 // FINALIZATION
2363 ///////////////////////////////////////////////////////////////////////////////
2364
2365 extern "C" void _lamexp_global_free_win32(void)
2366 {
2367         //Clear folder cache
2368         LAMEXP_DELETE(g_lamexp_known_folder.knownFolders);
2369
2370         //Destroy Qt application object
2371         QApplication *application = dynamic_cast<QApplication*>(QApplication::instance());
2372         LAMEXP_DELETE(application);
2373
2374         //Release DWM API
2375         g_lamexp_dwmapi.dwmIsCompositionEnabled = NULL;
2376         g_lamexp_dwmapi.dwmExtendFrameIntoClientArea = NULL;
2377         g_lamexp_dwmapi.dwmEnableBlurBehindWindow = NULL;
2378         LAMEXP_DELETE(g_lamexp_dwmapi.dwmapi_dll);
2379
2380         //Free STDOUT and STDERR buffers
2381         if(g_lamexp_console_attached)
2382         {
2383                 if(std::filebuf *tmp = dynamic_cast<std::filebuf*>(std::cout.rdbuf()))
2384                 {
2385                         std::cout.rdbuf(NULL);
2386                         LAMEXP_DELETE(tmp);
2387                 }
2388                 if(std::filebuf *tmp = dynamic_cast<std::filebuf*>(std::cerr.rdbuf()))
2389                 {
2390                         std::cerr.rdbuf(NULL);
2391                         LAMEXP_DELETE(tmp);
2392                 }
2393         }
2394
2395         //Close log file
2396         if(g_lamexp_log_file)
2397         {
2398                 fclose(g_lamexp_log_file);
2399                 g_lamexp_log_file = NULL;
2400         }
2401
2402         //Clear sound cache
2403         LAMEXP_DELETE(g_lamexp_sounds.sound_db);
2404
2405         //Free CLI Arguments
2406         LAMEXP_DELETE(g_lamexp_argv.list);
2407 }