1 ///////////////////////////////////////////////////////////////////////////////
2 // LameXP - Audio Encoder Front-End
3 // Copyright (C) 2004-2014 LoRd_MuldeR <MuldeR2@GMX.de>
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.
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.
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.
20 // http://www.gnu.org/licenses/gpl-2.0.txt
21 ///////////////////////////////////////////////////////////////////////////////
26 #include "Targetver.h"
28 //Visual Leaks Detector
33 #define WIN32_LEAN_AND_MEAN
44 #include <QApplication>
49 #include <QImageReader>
51 #include <QLibraryInfo>
53 #include <QMessageBox>
55 #include <QPlastiqueStyle>
57 #include <QReadWriteLock>
62 #include <QTranslator>
67 #define LAMEXP_INC_CONFIG
83 //Initialize static Qt plugins
85 #if QT_VERSION < QT_VERSION_CHECK(5,0,0)
89 Q_IMPORT_PLUGIN(QWindowsIntegrationPlugin
)
90 Q_IMPORT_PLUGIN(QICOPlugin
)
94 ///////////////////////////////////////////////////////////////////////////////
96 ///////////////////////////////////////////////////////////////////////////////
98 #define _LAMEXP_MAKE_STR(STR) #STR
99 #define LAMEXP_MAKE_STR(STR) _LAMEXP_MAKE_STR(STR)
102 #define CLEAN_OUTPUT_STRING(STR) do \
104 const char CTRL_CHARS[3] = { '\r', '\n', '\t' }; \
105 for(size_t i = 0; i < 3; i++) \
107 while(char *pos = strchr((STR), CTRL_CHARS[i])) *pos = char(0x20); \
113 #define TRIM_LEFT(STR) do \
115 const char WHITE_SPACE[4] = { char(0x20), '\r', '\n', '\t' }; \
116 for(size_t i = 0; i < 4; i++) \
118 while(*(STR) == WHITE_SPACE[i]) (STR)++; \
123 ///////////////////////////////////////////////////////////////////////////////
125 ///////////////////////////////////////////////////////////////////////////////
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
);
130 ///////////////////////////////////////////////////////////////////////////////
132 ///////////////////////////////////////////////////////////////////////////////
134 //Console attached flag
135 static bool g_lamexp_console_attached
= false;
140 QMap
<size_t, QString
> *knownFolders
;
141 SHGetKnownFolderPath_t getKnownFolderPath
;
142 SHGetFolderPath_t getFolderPath
;
145 g_lamexp_known_folder
;
159 lamexp_os_version_t version
;
173 //Win32 Theme support
180 g_lamexp_themes_enabled
;
182 //Win32 DWM API functions
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
;
197 QHash
<const QString
, const unsigned char*> *sound_db
;
203 static const char *g_lamexp_imageformats
[] = {"bmp", "png", "jpg", "gif", "ico", "xpm", NULL
}; //"svg"
206 static QMutex g_lamexp_message_mutex
;
209 static const DWORD g_main_thread_id
= GetCurrentThreadId();
212 static FILE *g_lamexp_log_file
= NULL
;
215 const char* LAMEXP_DEFAULT_LANGID
= "en";
216 const char* LAMEXP_DEFAULT_TRANSLATION
= "LameXP_EN.qm";
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};
228 static const char *GURU_MEDITATION
= "\n\nGURU MEDITATION !!!\n\n";
230 ///////////////////////////////////////////////////////////////////////////////
232 ///////////////////////////////////////////////////////////////////////////////
235 * Verify a specific Windows version
237 static bool lamexp_verify_os_version(const DWORD major
, const DWORD minor
)
239 OSVERSIONINFOEXW osvi
;
240 DWORDLONG dwlConditionMask
= 0;
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
;
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
);
255 const BOOL ret
= VerifyVersionInfoW(&osvi
, VER_MAJORVERSION
| VER_MINORVERSION
| VER_PLATFORMID
, dwlConditionMask
);
260 if(GetLastError() != ERROR_OLD_WIN_VERSION
)
262 qWarning("VerifyVersionInfo() system call has failed!");
266 return (ret
!= FALSE
);
270 * Determine the *real* Windows version
272 static bool lamexp_get_real_os_version(unsigned int *major
, unsigned int *minor
, bool *pbOverride
)
277 //Initialize local variables
278 OSVERSIONINFOEXW osvi
;
279 memset(&osvi
, 0, sizeof(OSVERSIONINFOEXW
));
280 osvi
.dwOSVersionInfoSize
= sizeof(OSVERSIONINFOEXW
);
282 //Try GetVersionEx() first
283 if(GetVersionExW((LPOSVERSIONINFOW
)&osvi
) == FALSE
)
285 qWarning("GetVersionEx() has failed, cannot detect Windows version!");
289 //Make sure we are running on NT
290 if(osvi
.dwPlatformId
== VER_PLATFORM_WIN32_NT
)
292 *major
= osvi
.dwMajorVersion
;
293 *minor
= osvi
.dwMinorVersion
;
297 qWarning("Not running on Windows NT, unsupported operating system!");
301 //Determine the real *major* version first
304 const DWORD nextMajor
= (*major
) + 1;
305 if(lamexp_verify_os_version(nextMajor
, 0))
315 //Now also determine the real *minor* version
318 const DWORD nextMinor
= (*minor
) + 1;
319 if(lamexp_verify_os_version((*major
), nextMinor
))
332 * Get the native operating system version
334 const lamexp_os_version_t
&lamexp_get_os_version(void)
336 QReadLocker
readLock(&g_lamexp_os_version
.lock
);
338 //Already initialized?
339 if(g_lamexp_os_version
.bInitialized
)
341 return g_lamexp_os_version
.version
;
345 QWriteLocker
writeLock(&g_lamexp_os_version
.lock
);
348 if(!g_lamexp_os_version
.bInitialized
)
350 unsigned int major
, minor
; bool oflag
;
351 if(lamexp_get_real_os_version(&major
, &minor
, &oflag
))
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;
360 qWarning("Failed to determin the operating system version!");
364 return g_lamexp_os_version
.version
;
368 * Check if we are running under wine
370 bool lamexp_detect_wine(void)
372 QReadLocker
readLock(&g_lamexp_wine
.lock
);
374 //Already initialized?
375 if(g_lamexp_wine
.bInitialized
)
377 return g_lamexp_wine
.bIsWine
;
381 QWriteLocker
writeLock(&g_lamexp_wine
.lock
);
383 if(!g_lamexp_wine
.bInitialized
)
385 g_lamexp_wine
.bIsWine
= false;
386 QLibrary
ntdll("ntdll.dll");
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;
393 g_lamexp_wine
.bInitialized
= true;
396 return g_lamexp_wine
.bIsWine
;
400 * Change console text color
402 static void lamexp_console_color(FILE* file
, WORD attributes
)
404 const HANDLE hConsole
= (HANDLE
)(_get_osfhandle(_fileno(file
)));
405 if((hConsole
!= NULL
) && (hConsole
!= INVALID_HANDLE_VALUE
))
407 SetConsoleTextAttribute(hConsole
, attributes
);
412 * Output logging message to console
414 static void lamexp_write_console(const int type
, const char *msg
)
418 if(_isatty(_fileno(stderr
)))
420 UINT oldOutputCP
= GetConsoleOutputCP();
421 if(oldOutputCP
!= CP_UTF8
) SetConsoleOutputCP(CP_UTF8
);
427 lamexp_console_color(stderr
, FOREGROUND_RED
| FOREGROUND_INTENSITY
);
428 fprintf(stderr
, GURU_MEDITATION
);
429 fprintf(stderr
, "%s\n", msg
);
433 lamexp_console_color(stderr
, FOREGROUND_GREEN
| FOREGROUND_RED
| FOREGROUND_INTENSITY
);
434 fprintf(stderr
, "%s\n", msg
);
438 lamexp_console_color(stderr
, FOREGROUND_BLUE
| FOREGROUND_GREEN
| FOREGROUND_RED
| FOREGROUND_INTENSITY
);
439 fprintf(stderr
, "%s\n", msg
);
444 lamexp_console_color(stderr
, FOREGROUND_BLUE
| FOREGROUND_GREEN
| FOREGROUND_RED
);
445 if(oldOutputCP
!= CP_UTF8
) SetConsoleOutputCP(oldOutputCP
);
450 /*ignore any exception that might occur here!*/
455 * Output logging message to debugger
457 static void lamexp_write_dbg_out(const int type
, const char *msg
)
459 const char *FORMAT
= "[LameXP][%c] %s\n";
464 const char* input
= msg
;
471 _snprintf_s(buffer
, 512, _TRUNCATE
, FORMAT
, 'C', input
);
474 _snprintf_s(buffer
, 512, _TRUNCATE
, FORMAT
, 'W', input
);
477 _snprintf_s(buffer
, 512, _TRUNCATE
, FORMAT
, 'I', input
);
481 char *temp
= &buffer
[0];
482 CLEAN_OUTPUT_STRING(temp
);
483 OutputDebugStringA(temp
);
487 /*ignore any exception that might occur here!*/
492 * Output logging message to logfile
494 static void lamexp_write_logfile(const int type
, const char *msg
)
496 const char *FORMAT
= "[%c][%04u] %s\r\n";
500 if(g_lamexp_log_file
)
503 strncpy_s(buffer
, 512, msg
, _TRUNCATE
);
505 char *temp
= &buffer
[0];
507 CLEAN_OUTPUT_STRING(temp
);
509 const unsigned int timestamp
= static_cast<unsigned int>(_time64(NULL
) % 3600I64
);
515 fprintf(g_lamexp_log_file
, FORMAT
, 'C', timestamp
, temp
);
518 fprintf(g_lamexp_log_file
, FORMAT
, 'W', timestamp
, temp
);
521 fprintf(g_lamexp_log_file
, FORMAT
, 'I', timestamp
, temp
);
525 fflush(g_lamexp_log_file
);
530 /*ignore any exception that might occur here!*/
537 void lamexp_message_handler(QtMsgType type
, const char *msg
)
539 if((!msg
) || (!(msg
[0])))
544 QMutexLocker
lock(&g_lamexp_message_mutex
);
546 if(g_lamexp_log_file
)
548 lamexp_write_logfile(type
, msg
);
551 if(g_lamexp_console_attached
)
553 lamexp_write_console(type
, msg
);
557 lamexp_write_dbg_out(type
, msg
);
560 if((type
== QtCriticalMsg
) || (type
== QtFatalMsg
))
563 lamexp_fatal_exit(L
"The application has encountered a critical error and will exit now!", QWCHAR(QString::fromUtf8(msg
)));
568 * Invalid parameters handler
570 static void lamexp_invalid_param_handler(const wchar_t* exp
, const wchar_t* fun
, const wchar_t* fil
, unsigned int, uintptr_t)
572 lamexp_fatal_exit(L
"Invalid parameter handler invoked, application will exit!");
578 static void lamexp_signal_handler(int signal_num
)
580 signal(signal_num
, lamexp_signal_handler
);
581 lamexp_fatal_exit(L
"Signal handler invoked, application will exit!");
585 * Global exception handler
587 static LONG WINAPI
lamexp_exception_handler(struct _EXCEPTION_POINTERS
*ExceptionInfo
)
589 lamexp_fatal_exit(L
"Unhandeled exception handler invoked, application will exit!");
594 * Initialize error handlers
596 void lamexp_init_error_handlers(void)
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
);
603 static const int signal_num
[6] = { SIGABRT
, SIGFPE
, SIGILL
, SIGINT
, SIGSEGV
, SIGTERM
};
605 for(size_t i
= 0; i
< 6; i
++)
607 signal(signal_num
[i
], lamexp_signal_handler
);
612 * Initialize the console
614 void lamexp_init_console(const QStringList
&argv
)
616 bool enableConsole
= (LAMEXP_DEBUG
) || ((VER_LAMEXP_CONSOLE_ENABLED
) && lamexp_version_demo());
620 wchar_t *logfile
= NULL
;
621 size_t logfile_len
= 0;
622 if(!_wdupenv_s(&logfile
, &logfile_len
, L
"LAMEXP_LOGFILE"))
624 if(logfile
&& (logfile_len
> 0))
627 if(!_wfopen_s(&temp
, logfile
, L
"wb"))
629 fprintf(temp
, "%c%c%c", char(0xEF), char(0xBB), char(0xBF));
630 g_lamexp_log_file
= temp
;
639 for(int i
= 0; i
< argv
.count(); i
++)
641 if(!argv
.at(i
).compare("--console", Qt::CaseInsensitive
))
643 enableConsole
= true;
645 else if(!argv
.at(i
).compare("--no-console", Qt::CaseInsensitive
))
647 enableConsole
= false;
654 if(!g_lamexp_console_attached
)
656 if(AllocConsole() != FALSE
)
658 SetConsoleCtrlHandler(NULL
, TRUE
);
659 SetConsoleTitle(L
"LameXP - Audio Encoder Front-End | Debug Console");
660 SetConsoleOutputCP(CP_UTF8
);
661 g_lamexp_console_attached
= true;
665 if(g_lamexp_console_attached
)
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
)); }
679 HWND hwndConsole
= GetConsoleWindow();
681 if((hwndConsole
!= NULL
) && (hwndConsole
!= INVALID_HANDLE_VALUE
))
683 HMENU hMenu
= GetSystemMenu(hwndConsole
, 0);
684 EnableMenuItem(hMenu
, SC_CLOSE
, MF_BYCOMMAND
| MF_GRAYED
);
685 RemoveMenu(hMenu
, SC_CLOSE
, MF_BYCOMMAND
);
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
);
695 * Detect CPU features
697 lamexp_cpu_t
lamexp_detect_cpu_features(const QStringList
&argv
)
699 typedef BOOL (WINAPI
*IsWow64ProcessFun
)(__in HANDLE hProcess
, __out PBOOL Wow64Process
);
701 lamexp_cpu_t features
;
702 SYSTEM_INFO systemInfo
;
703 int CPUInfo
[4] = {-1};
704 char CPUIdentificationString
[0x40];
705 char CPUBrandString
[0x40];
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
));
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
);
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);
733 __cpuid(CPUInfo
, 0x80000000);
734 int nExIds
= qMax
<int>(qMin
<int>(CPUInfo
[0], 0x80000004), 0x80000000);
736 for(int i
= 0x80000002; i
<= nExIds
; ++i
)
742 memcpy(CPUBrandString
, CPUInfo
, sizeof(CPUInfo
));
745 memcpy(CPUBrandString
+ 16, CPUInfo
, sizeof(CPUInfo
));
748 memcpy(CPUBrandString
+ 32, CPUInfo
, sizeof(CPUInfo
));
753 strncpy_s(features
.brand
, 0x40, CPUBrandString
, _TRUNCATE
);
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
);
758 #if (!(defined(_M_X64) || defined(_M_IA64)))
759 QLibrary
Kernel32Lib("kernel32.dll");
760 if(IsWow64ProcessFun IsWow64ProcessPtr
= (IsWow64ProcessFun
) Kernel32Lib
.resolve("IsWow64Process"))
762 BOOL x64flag
= FALSE
;
763 if(IsWow64ProcessPtr(GetCurrentProcess(), &x64flag
))
765 features
.x64
= (x64flag
== TRUE
);
772 DWORD_PTR procAffinity
, sysAffinity
;
773 if(GetProcessAffinityMask(GetCurrentProcess(), &procAffinity
, &sysAffinity
))
775 for(DWORD_PTR mask
= 1; mask
; mask
<<= 1)
777 features
.count
+= ((sysAffinity
& mask
) ? (1) : (0));
780 if(features
.count
< 1)
782 GetNativeSystemInfo(&systemInfo
);
783 features
.count
= qBound(1UL, systemInfo
.dwNumberOfProcessors
, 64UL);
789 for(int i
= 0; i
< argv
.count(); i
++)
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; }
795 if(flag
) qWarning("CPU flags overwritten by user-defined parameters. Take care!\n");
802 * Check for debugger (detect routine)
804 static __forceinline
bool lamexp_check_for_debugger(void)
808 CloseHandle((HANDLE
)((DWORD_PTR
)-3));
820 return IsDebuggerPresent();
826 * Check for debugger (thread proc)
828 static unsigned int __stdcall
lamexp_debug_thread_proc(LPVOID lpParameter
)
830 SetThreadPriority(GetCurrentThread(), THREAD_PRIORITY_LOWEST
);
833 if(lamexp_check_for_debugger())
835 lamexp_fatal_exit(L
"Not a debug build. Please unload debugger and try again!");
843 * Check for debugger (startup routine)
845 static HANDLE
lamexp_debug_thread_init()
847 if(lamexp_check_for_debugger())
849 lamexp_fatal_exit(L
"Not a debug build. Please unload debugger and try again!");
851 const uintptr_t h
= _beginthreadex(NULL
, 0, lamexp_debug_thread_proc
, NULL
, 0, NULL
);
852 return (HANDLE
)(h
^0xdeadbeef);
858 static bool lamexp_event_filter(void *message
, long *result
)
860 if((!(LAMEXP_DEBUG
)) && lamexp_check_for_debugger())
862 lamexp_fatal_exit(L
"Not a debug build. Please unload debugger and try again!");
865 switch(reinterpret_cast<MSG
*>(message
)->message
)
867 case WM_QUERYENDSESSION
:
868 qWarning("WM_QUERYENDSESSION message received!");
869 *result
= lamexp_broadcast(lamexp_event_queryendsession
, false) ? TRUE
: FALSE
;
872 qWarning("WM_ENDSESSION message received!");
873 if(reinterpret_cast<MSG
*>(message
)->wParam
== TRUE
)
875 lamexp_broadcast(lamexp_event_endsession
, false);
876 if(QApplication
*app
= reinterpret_cast<QApplication
*>(QApplication::instance()))
878 app
->closeAllWindows();
881 lamexp_finalization();
887 /*ignore this message and let Qt handle it*/
893 * Check for process elevation
895 static bool lamexp_process_is_elevated(bool *bIsUacEnabled
= NULL
)
897 bool bIsProcessElevated
= false;
898 if(bIsUacEnabled
) *bIsUacEnabled
= false;
899 HANDLE hToken
= NULL
;
901 if(OpenProcessToken(GetCurrentProcess(), TOKEN_QUERY
, &hToken
))
903 TOKEN_ELEVATION_TYPE tokenElevationType
;
905 if(GetTokenInformation(hToken
, TokenElevationType
, &tokenElevationType
, sizeof(TOKEN_ELEVATION_TYPE
), &returnLength
))
907 if(returnLength
== sizeof(TOKEN_ELEVATION_TYPE
))
909 switch(tokenElevationType
)
911 case TokenElevationTypeDefault
:
912 qDebug("Process token elevation type: Default -> UAC is disabled.\n");
914 case TokenElevationTypeFull
:
915 qWarning("Process token elevation type: Full -> potential security risk!\n");
916 bIsProcessElevated
= true;
917 if(bIsUacEnabled
) *bIsUacEnabled
= true;
919 case TokenElevationTypeLimited
:
920 qDebug("Process token elevation type: Limited -> not elevated.\n");
921 if(bIsUacEnabled
) *bIsUacEnabled
= true;
924 qWarning("Unknown tokenElevationType value: %d", tokenElevationType
);
930 qWarning("GetTokenInformation() return an unexpected size!");
937 qWarning("Failed to open process token!");
940 return bIsProcessElevated
;
944 * Convert QIcon to HICON -> caller is responsible for destroying the HICON!
946 static HICON
lamexp_qicon2hicon(const QIcon
&icon
, const int w
, const int h
)
950 QPixmap pixmap
= icon
.pixmap(w
, h
);
953 return pixmap
.toWinHICON();
960 * Initialize Qt framework
962 bool lamexp_init_qt(int argc
, char* argv
[])
964 static bool qt_initialized
= false;
965 typedef BOOL (WINAPI
*SetDllDirectoryProc
)(WCHAR
*lpPathName
);
966 const QStringList
&arguments
= lamexp_arguments();
968 //Don't initialized again, if done already
975 QLibrary
kernel32("kernel32.dll");
978 SetDllDirectoryProc pSetDllDirectory
= (SetDllDirectoryProc
) kernel32
.resolve("SetDllDirectoryW");
979 if(pSetDllDirectory
!= NULL
) pSetDllDirectory(L
"");
982 //Extract executable name from argv[] array
983 QString executableName
= QLatin1String("LameXP.exe");
984 if(arguments
.count() > 0)
986 static const char *delimiters
= "\\/:?";
987 executableName
= arguments
[0].trimmed();
988 for(int i
= 0; delimiters
[i
]; i
++)
990 int temp
= executableName
.lastIndexOf(QChar(delimiters
[i
]));
991 if(temp
>= 0) executableName
= executableName
.mid(temp
+ 1);
993 executableName
= executableName
.trimmed();
994 if(executableName
.isEmpty())
996 executableName
= QLatin1String("LameXP.exe");
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
))
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());
1009 if(QLibraryInfo::buildKey().compare(QString::fromLatin1(QT_BUILD_KEY
), Qt::CaseInsensitive
))
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());
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
);
1019 //Check the Windows version
1020 const lamexp_os_version_t
&osVersionNo
= lamexp_get_os_version();
1021 if(osVersionNo
< lamexp_winver_winxp
)
1023 qFatal("%s", QApplication::tr("Executable '%1' requires Windows XP or later.").arg(executableName
).toLatin1().constData());
1026 //Supported Windows version?
1027 if(osVersionNo
== lamexp_winver_winxp
)
1029 qDebug("Running on Windows XP or Windows XP Media Center Edition.\n"); //lamexp_check_compatibility_mode("GetLargePageMinimum", executableName);
1031 else if(osVersionNo
== lamexp_winver_xpx64
)
1033 qDebug("Running on Windows Server 2003, Windows Server 2003 R2 or Windows XP x64.\n"); //lamexp_check_compatibility_mode("GetLocaleInfoEx", executableName);
1035 else if(osVersionNo
== lamexp_winver_vista
)
1037 qDebug("Running on Windows Vista or Windows Server 2008.\n"); //lamexp_check_compatibility_mode("CreateRemoteThreadEx", executableName*/);
1039 else if(osVersionNo
== lamexp_winver_win70
)
1041 qDebug("Running on Windows 7 or Windows Server 2008 R2.\n"); //lamexp_check_compatibility_mode("CreateFile2", executableName);
1043 else if(osVersionNo
== lamexp_winver_win80
)
1045 qDebug("Running on Windows 8 or Windows Server 2012.\n"); //lamexp_check_compatibility_mode("FindPackagesByPackageFamily", executableName);
1047 else if(osVersionNo
== lamexp_winver_win81
)
1049 qDebug("Running on Windows 8.1 or Windows Server 2012 R2.\n"); //lamexp_check_compatibility_mode(NULL, executableName);
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
);
1058 //Check for compat mode
1059 if(osVersionNo
.overrideFlag
&& (osVersionNo
<= lamexp_winver_win81
))
1061 qWarning("Windows compatibility mode detected!");
1062 if(!arguments
.contains("--ignore-compat-mode", Qt::CaseInsensitive
))
1064 qFatal("%s", QApplication::tr("Executable '%1' doesn't support Windows compatibility mode.").arg(executableName
).toLatin1().constData());
1070 if(lamexp_detect_wine())
1072 qWarning("It appears we are running under Wine, unexpected things might happen!\n");
1075 //Set text Codec for locale
1076 QTextCodec::setCodecForLocale(QTextCodec::codecForName("UTF-8"));
1078 //Create Qt application instance
1079 QApplication
*application
= new QApplication(argc
, argv
);
1081 //Load plugins from application directory
1082 QCoreApplication::setLibraryPaths(QStringList() << QApplication::applicationDirPath());
1083 qDebug("Library Path:\n%s\n", QUTF8(QApplication::libraryPaths().first()));
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
);
1093 //Check for supported image formats
1094 QList
<QByteArray
> supportedFormats
= QImageReader::supportedImageFormats();
1095 for(int i
= 0; g_lamexp_imageformats
[i
]; i
++)
1097 if(!supportedFormats
.contains(g_lamexp_imageformats
[i
]))
1099 qFatal("Qt initialization error: QImageIOHandler for '%s' missing!", g_lamexp_imageformats
[i
]);
1104 //Enable larger/smaller font size
1105 double fontScaleFactor
= 1.0;
1106 if(arguments
.contains("--huge-font", Qt::CaseInsensitive
)) fontScaleFactor
= 1.500;
1107 if(arguments
.contains("--big-font", Qt::CaseInsensitive
)) fontScaleFactor
= 1.250;
1108 if(arguments
.contains("--small-font", Qt::CaseInsensitive
)) fontScaleFactor
= 0.875;
1109 if(arguments
.contains("--tiny-font", Qt::CaseInsensitive
)) fontScaleFactor
= 0.750;
1110 if(!qFuzzyCompare(fontScaleFactor
, 1.0))
1112 qWarning("Application font scale factor set to: %.3f\n", fontScaleFactor
);
1113 QFont appFont
= application
->font();
1114 appFont
.setPointSizeF(appFont
.pointSizeF() * fontScaleFactor
);
1115 application
->setFont(appFont
);
1118 //Add the default translations
1119 lamexp_translation_init();
1121 //Check for process elevation
1122 if(lamexp_process_is_elevated() && (!lamexp_detect_wine()))
1124 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
);
1125 messageBox
.addButton("Quit Program (Recommended)", QMessageBox::NoRole
);
1126 messageBox
.addButton("Ignore", QMessageBox::NoRole
);
1127 if(messageBox
.exec() == 0)
1133 //Update console icon, if a console is attached
1134 #if QT_VERSION < QT_VERSION_CHECK(5,0,0)
1135 if(g_lamexp_console_attached
&& (!lamexp_detect_wine()))
1137 QLibrary
kernel32("kernel32.dll");
1140 typedef DWORD (__stdcall
*SetConsoleIconFun
)(HICON
);
1141 if(SetConsoleIconFun SetConsoleIconPtr
= (SetConsoleIconFun
) kernel32
.resolve("SetConsoleIcon"))
1143 if(HICON hIcon
= lamexp_qicon2hicon(QIcon(":/icons/sound.png"), 16, 16))
1145 SetConsoleIconPtr(hIcon
);
1154 qt_initialized
= true;
1158 const QStringList
&lamexp_arguments(void)
1160 QReadLocker
readLock(&g_lamexp_argv
.lock
);
1162 if(!g_lamexp_argv
.list
)
1165 QWriteLocker
writeLock(&g_lamexp_argv
.lock
);
1167 g_lamexp_argv
.list
= new QStringList
;
1170 LPWSTR
*szArglist
= CommandLineToArgvW(GetCommandLineW(), &nArgs
);
1172 if(NULL
!= szArglist
)
1174 for(int i
= 0; i
< nArgs
; i
++)
1176 (*g_lamexp_argv
.list
) << WCHAR2QSTR(szArglist
[i
]);
1178 LocalFree(szArglist
);
1182 qWarning("CommandLineToArgvW() has failed !!!");
1186 return (*g_lamexp_argv
.list
);
1190 * Locate known folder on local system
1192 const QString
&lamexp_known_folder(lamexp_known_folder_t folder_id
)
1194 static const int CSIDL_FLAG_CREATE
= 0x8000;
1195 typedef enum { KF_FLAG_CREATE
= 0x00008000 } kf_flags_t
;
1202 static s_folders
[] =
1204 { 0x001c, {0xF1B32785,0x6FBA,0x4FCF,{0x9D,0x55,0x7B,0x8E,0x7F,0x15,0x70,0x91}} }, //CSIDL_LOCAL_APPDATA
1205 { 0x0026, {0x905e63b6,0xc1bf,0x494e,{0xb2,0x9c,0x65,0xb7,0x32,0xd3,0xd2,0x1a}} }, //CSIDL_PROGRAM_FILES
1206 { 0x0024, {0xF38BF404,0x1D43,0x42F2,{0x93,0x05,0x67,0xDE,0x0B,0x28,0xFC,0x23}} }, //CSIDL_WINDOWS_FOLDER
1207 { 0x0025, {0x1AC14E77,0x02E7,0x4E5D,{0xB7,0x44,0x2E,0xB1,0xAE,0x51,0x98,0xB7}} }, //CSIDL_SYSTEM_FOLDER
1210 size_t folderId
= size_t(-1);
1214 case lamexp_folder_localappdata
: folderId
= 0; break;
1215 case lamexp_folder_programfiles
: folderId
= 1; break;
1216 case lamexp_folder_systroot_dir
: folderId
= 2; break;
1217 case lamexp_folder_systemfolder
: folderId
= 3; break;
1220 if(folderId
== size_t(-1))
1222 qWarning("Invalid 'known' folder was requested!");
1223 return *reinterpret_cast<QString
*>(NULL
);
1226 QReadLocker
readLock(&g_lamexp_known_folder
.lock
);
1229 if(g_lamexp_known_folder
.knownFolders
)
1231 if(g_lamexp_known_folder
.knownFolders
->contains(folderId
))
1233 return (*g_lamexp_known_folder
.knownFolders
)[folderId
];
1237 //Obtain write lock to initialize
1239 QWriteLocker
writeLock(&g_lamexp_known_folder
.lock
);
1241 //Still not in cache?
1242 if(g_lamexp_known_folder
.knownFolders
)
1244 if(g_lamexp_known_folder
.knownFolders
->contains(folderId
))
1246 return (*g_lamexp_known_folder
.knownFolders
)[folderId
];
1250 //Initialize on first call
1251 if(!g_lamexp_known_folder
.knownFolders
)
1253 QLibrary
shell32("shell32.dll");
1256 g_lamexp_known_folder
.getFolderPath
= (SHGetFolderPath_t
) shell32
.resolve("SHGetFolderPathW");
1257 g_lamexp_known_folder
.getKnownFolderPath
= (SHGetKnownFolderPath_t
) shell32
.resolve("SHGetKnownFolderPath");
1259 g_lamexp_known_folder
.knownFolders
= new QMap
<size_t, QString
>();
1264 //Now try to get the folder path!
1265 if(g_lamexp_known_folder
.getKnownFolderPath
)
1268 if(g_lamexp_known_folder
.getKnownFolderPath(s_folders
[folderId
].guid
, KF_FLAG_CREATE
, NULL
, &path
) == S_OK
)
1270 //MessageBoxW(0, path, L"SHGetKnownFolderPath", MB_TOPMOST);
1271 QDir folderTemp
= QDir(QDir::fromNativeSeparators(QString::fromUtf16(reinterpret_cast<const unsigned short*>(path
))));
1272 if(folderTemp
.exists())
1274 folderPath
= folderTemp
.canonicalPath();
1276 CoTaskMemFree(path
);
1279 else if(g_lamexp_known_folder
.getFolderPath
)
1281 WCHAR
*path
= new WCHAR
[4096];
1282 if(g_lamexp_known_folder
.getFolderPath(NULL
, s_folders
[folderId
].csidl
| CSIDL_FLAG_CREATE
, NULL
, NULL
, path
) == S_OK
)
1284 //MessageBoxW(0, path, L"SHGetFolderPathW", MB_TOPMOST);
1285 QDir folderTemp
= QDir(QDir::fromNativeSeparators(QString::fromUtf16(reinterpret_cast<const unsigned short*>(path
))));
1286 if(folderTemp
.exists())
1288 folderPath
= folderTemp
.canonicalPath();
1291 LAMEXP_DELETE_ARRAY(path
);
1295 g_lamexp_known_folder
.knownFolders
->insert(folderId
, folderPath
);
1296 return (*g_lamexp_known_folder
.knownFolders
)[folderId
];
1300 * Safely remove a file
1302 bool lamexp_remove_file(const QString
&filename
)
1304 if(!QFileInfo(filename
).exists() || !QFileInfo(filename
).isFile())
1310 if(!QFile::remove(filename
))
1312 static const DWORD attrMask
= FILE_ATTRIBUTE_READONLY
| FILE_ATTRIBUTE_HIDDEN
| FILE_ATTRIBUTE_SYSTEM
;
1313 const DWORD attributes
= GetFileAttributesW(QWCHAR(filename
));
1314 if(attributes
& attrMask
)
1316 SetFileAttributesW(QWCHAR(filename
), FILE_ATTRIBUTE_NORMAL
);
1318 if(!QFile::remove(filename
))
1320 qWarning("Could not delete \"%s\"", filename
.toLatin1().constData());
1336 * Check if visual themes are enabled (WinXP and later)
1338 bool lamexp_themes_enabled(void)
1340 typedef int (WINAPI
*IsAppThemedFun
)(void);
1342 QReadLocker
readLock(&g_lamexp_themes_enabled
.lock
);
1343 if(g_lamexp_themes_enabled
.bInitialized
)
1345 return g_lamexp_themes_enabled
.bThemesEnabled
;
1349 QWriteLocker
writeLock(&g_lamexp_themes_enabled
.lock
);
1351 if(!g_lamexp_themes_enabled
.bInitialized
)
1353 g_lamexp_themes_enabled
.bThemesEnabled
= false;
1354 const lamexp_os_version_t
&osVersion
= lamexp_get_os_version();
1355 if(osVersion
>= lamexp_winver_winxp
)
1357 IsAppThemedFun IsAppThemedPtr
= NULL
;
1358 QLibrary
uxTheme(QString("%1/UxTheme.dll").arg(lamexp_known_folder(lamexp_folder_systemfolder
)));
1361 IsAppThemedPtr
= (IsAppThemedFun
) uxTheme
.resolve("IsAppThemed");
1365 g_lamexp_themes_enabled
.bThemesEnabled
= IsAppThemedPtr();
1366 if(!g_lamexp_themes_enabled
.bThemesEnabled
)
1368 qWarning("Theme support is disabled for this process!");
1372 g_lamexp_themes_enabled
.bInitialized
= true;
1375 return g_lamexp_themes_enabled
.bThemesEnabled
;
1379 * Get number of free bytes on disk
1381 unsigned __int64
lamexp_free_diskspace(const QString
&path
, bool *ok
)
1383 ULARGE_INTEGER freeBytesAvailable
, totalNumberOfBytes
, totalNumberOfFreeBytes
;
1384 if(GetDiskFreeSpaceExW(reinterpret_cast<const wchar_t*>(QDir::toNativeSeparators(path
).utf16()), &freeBytesAvailable
, &totalNumberOfBytes
, &totalNumberOfFreeBytes
))
1387 return freeBytesAvailable
.QuadPart
;
1397 * Check if computer does support hibernation
1399 bool lamexp_is_hibernation_supported(void)
1401 bool hibernationSupported
= false;
1403 SYSTEM_POWER_CAPABILITIES pwrCaps
;
1404 SecureZeroMemory(&pwrCaps
, sizeof(SYSTEM_POWER_CAPABILITIES
));
1406 if(GetPwrCapabilities(&pwrCaps
))
1408 hibernationSupported
= pwrCaps
.SystemS4
&& pwrCaps
.HiberFilePresent
;
1411 return hibernationSupported
;
1415 * Shutdown the computer
1417 bool lamexp_shutdown_computer(const QString
&message
, const unsigned long timeout
, const bool forceShutdown
, const bool hibernate
)
1419 HANDLE hToken
= NULL
;
1421 if(OpenProcessToken(GetCurrentProcess(), TOKEN_ADJUST_PRIVILEGES
| TOKEN_QUERY
, &hToken
))
1423 TOKEN_PRIVILEGES privileges
;
1424 memset(&privileges
, 0, sizeof(TOKEN_PRIVILEGES
));
1425 privileges
.PrivilegeCount
= 1;
1426 privileges
.Privileges
[0].Attributes
= SE_PRIVILEGE_ENABLED
;
1428 if(LookupPrivilegeValue(NULL
, SE_SHUTDOWN_NAME
, &privileges
.Privileges
[0].Luid
))
1430 if(AdjustTokenPrivileges(hToken
, FALSE
, &privileges
, NULL
, NULL
, NULL
))
1434 if(SetSuspendState(TRUE
, TRUE
, TRUE
))
1439 const DWORD reason
= SHTDN_REASON_MAJOR_APPLICATION
| SHTDN_REASON_FLAG_PLANNED
;
1440 return InitiateSystemShutdownEx(NULL
, const_cast<wchar_t*>(QWCHAR(message
)), timeout
, forceShutdown
? TRUE
: FALSE
, FALSE
, reason
);
1449 * Determines the current date, resistant against certain manipulations
1451 QDate
lamexp_current_date_safe(void)
1453 const DWORD MAX_PROC
= 1024;
1454 DWORD
*processes
= new DWORD
[MAX_PROC
];
1455 DWORD bytesReturned
= 0;
1457 if(!EnumProcesses(processes
, sizeof(DWORD
) * MAX_PROC
, &bytesReturned
))
1459 LAMEXP_DELETE_ARRAY(processes
);
1460 return QDate::currentDate();
1463 const DWORD procCount
= bytesReturned
/ sizeof(DWORD
);
1464 ULARGE_INTEGER lastStartTime
;
1465 memset(&lastStartTime
, 0, sizeof(ULARGE_INTEGER
));
1467 for(DWORD i
= 0; i
< procCount
; i
++)
1469 HANDLE hProc
= OpenProcess(PROCESS_QUERY_INFORMATION
, FALSE
, processes
[i
]);
1472 FILETIME processTime
[4];
1473 if(GetProcessTimes(hProc
, &processTime
[0], &processTime
[1], &processTime
[2], &processTime
[3]))
1475 ULARGE_INTEGER timeCreation
;
1476 timeCreation
.LowPart
= processTime
[0].dwLowDateTime
;
1477 timeCreation
.HighPart
= processTime
[0].dwHighDateTime
;
1478 if(timeCreation
.QuadPart
> lastStartTime
.QuadPart
)
1480 lastStartTime
.QuadPart
= timeCreation
.QuadPart
;
1487 LAMEXP_DELETE_ARRAY(processes
);
1489 FILETIME lastStartTime_fileTime
;
1490 lastStartTime_fileTime
.dwHighDateTime
= lastStartTime
.HighPart
;
1491 lastStartTime_fileTime
.dwLowDateTime
= lastStartTime
.LowPart
;
1493 FILETIME lastStartTime_localTime
;
1494 if(!FileTimeToLocalFileTime(&lastStartTime_fileTime
, &lastStartTime_localTime
))
1496 memcpy(&lastStartTime_localTime
, &lastStartTime_fileTime
, sizeof(FILETIME
));
1499 SYSTEMTIME lastStartTime_system
;
1500 if(!FileTimeToSystemTime(&lastStartTime_localTime
, &lastStartTime_system
))
1502 memset(&lastStartTime_system
, 0, sizeof(SYSTEMTIME
));
1503 lastStartTime_system
.wYear
= 1970; lastStartTime_system
.wMonth
= lastStartTime_system
.wDay
= 1;
1506 const QDate currentDate
= QDate::currentDate();
1507 const QDate processDate
= QDate(lastStartTime_system
.wYear
, lastStartTime_system
.wMonth
, lastStartTime_system
.wDay
);
1508 return (currentDate
>= processDate
) ? currentDate
: processDate
;
1512 * Show system message box
1514 int lamexp_system_message(const wchar_t *text
, int beepType
)
1516 UINT flags
= MB_OK
| MB_TOPMOST
;
1520 case lamexp_beep_info
: flags
= flags
| MB_ICONASTERISK
;
1521 case lamexp_beep_warning
: flags
= flags
| MB_ICONEXCLAMATION
;
1522 case lamexp_beep_error
: flags
= flags
| MB_ICONHAND
;
1525 return MessageBoxW(NULL
, text
, L
"LameXP", flags
);
1529 * Block window "move" message
1531 bool lamexp_block_window_move(void *message
)
1535 MSG
*msg
= reinterpret_cast<MSG
*>(message
);
1536 if((msg
->message
== WM_SYSCOMMAND
) && (msg
->wParam
== SC_MOVE
))
1540 if((msg
->message
== WM_NCLBUTTONDOWN
) && (msg
->wParam
== HTCAPTION
))
1549 * Suspend calling thread for N milliseconds
1551 inline void lamexp_sleep(const unsigned int delay
)
1556 bool lamexp_beep(int beepType
)
1560 case lamexp_beep_info
: return MessageBeep(MB_ICONASTERISK
) == TRUE
; break;
1561 case lamexp_beep_warning
: return MessageBeep(MB_ICONEXCLAMATION
) == TRUE
; break;
1562 case lamexp_beep_error
: return MessageBeep(MB_ICONHAND
) == TRUE
; break;
1563 default: return false;
1568 * Play a sound (from resources)
1570 bool lamexp_play_sound(const QString
&name
, const bool bAsync
)
1572 const unsigned char *data
= NULL
;
1574 //Try to look-up the sound in the cache first
1577 QReadLocker
readLock(&g_lamexp_sounds
.lock
);
1578 if(g_lamexp_sounds
.sound_db
&& g_lamexp_sounds
.sound_db
->contains(name
))
1580 data
= g_lamexp_sounds
.sound_db
->value(name
);
1584 //If data not found in cache, try to load from resource!
1585 if((!data
) && (!name
.isEmpty()))
1587 QResource
resource(QString(":/sounds/%1.wav").arg(name
));
1588 if(resource
.isValid() && (data
= resource
.data()))
1590 QWriteLocker
writeLock(&g_lamexp_sounds
.lock
);
1591 if(!g_lamexp_sounds
.sound_db
)
1593 g_lamexp_sounds
.sound_db
= new QHash
<const QString
, const unsigned char*>();
1595 g_lamexp_sounds
.sound_db
->insert(name
, data
);
1599 qWarning("Sound effect \"%s\" not found!", QUTF8(name
));
1603 //Play the sound, if availbale
1606 return PlaySound(LPCWSTR(data
), NULL
, (SND_MEMORY
| (bAsync
? SND_ASYNC
: SND_SYNC
))) != FALSE
;
1613 * Play a sound (system alias)
1615 bool lamexp_play_sound_alias(const QString
&alias
, const bool bAsync
)
1617 return PlaySound(QWCHAR(alias
), GetModuleHandle(NULL
), (SND_ALIAS
| (bAsync
? SND_ASYNC
: SND_SYNC
))) != FALSE
;
1621 * Play a sound (from external DLL)
1623 bool lamexp_play_sound_file(const QString
&library
, const unsigned short uiSoundIdx
, const bool bAsync
)
1625 bool result
= false;
1627 QFileInfo
libraryFile(library
);
1628 if(!libraryFile
.isAbsolute())
1630 const QString
&systemDir
= lamexp_known_folder(lamexp_folder_systemfolder
);
1631 if(!systemDir
.isEmpty())
1633 libraryFile
.setFile(QDir(systemDir
), libraryFile
.fileName());
1637 if(libraryFile
.exists() && libraryFile
.isFile())
1639 if(HMODULE module
= LoadLibraryW(QWCHAR(QDir::toNativeSeparators(libraryFile
.canonicalFilePath()))))
1641 result
= (PlaySound(MAKEINTRESOURCE(uiSoundIdx
), module
, (SND_RESOURCE
| (bAsync
? SND_ASYNC
: SND_SYNC
))) != FALSE
);
1642 FreeLibrary(module
);
1647 qWarning("PlaySound: File \"%s\" could not be found!", QUTF8(libraryFile
.absoluteFilePath()));
1654 * Open file using the shell
1656 bool lamexp_exec_shell(const QWidget
*win
, const QString
&url
, const bool explore
)
1658 return lamexp_exec_shell(win
, url
, QString(), QString(), explore
);
1662 * Open file using the shell (with parameters)
1664 bool lamexp_exec_shell(const QWidget
*win
, const QString
&url
, const QString
¶meters
, const QString
&directory
, const bool explore
)
1666 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;
1670 * Query value of the performance counter
1672 __int64
lamexp_perfcounter_value(void)
1674 LARGE_INTEGER counter
;
1675 if(QueryPerformanceCounter(&counter
) == TRUE
)
1677 return counter
.QuadPart
;
1683 * Query frequency of the performance counter
1685 __int64
lamexp_perfcounter_frequ(void)
1687 LARGE_INTEGER frequency
;
1688 if(QueryPerformanceFrequency(&frequency
) == TRUE
)
1690 return frequency
.QuadPart
;
1696 * Insert entry to the window's system menu
1698 bool lamexp_append_sysmenu(const QWidget
*win
, const unsigned int identifier
, const QString
&text
)
1702 if(HMENU hMenu
= GetSystemMenu(win
->winId(), FALSE
))
1704 ok
= (AppendMenuW(hMenu
, MF_SEPARATOR
, 0, 0) == TRUE
);
1705 ok
= (AppendMenuW(hMenu
, MF_STRING
, identifier
, QWCHAR(text
)) == TRUE
);
1712 * Insert entry to the window's system menu
1714 bool lamexp_check_sysmenu_msg(void *message
, const unsigned int identifier
)
1716 return (((MSG
*)message
)->message
== WM_SYSCOMMAND
) && ((((MSG
*)message
)->wParam
& 0xFFF0) == identifier
);
1720 * Update system menu entry
1722 bool lamexp_update_sysmenu(const QWidget
*win
, const unsigned int identifier
, const QString
&text
)
1726 if(HMENU hMenu
= ::GetSystemMenu(win
->winId(), FALSE
))
1728 ok
= (ModifyMenu(hMenu
, identifier
, MF_STRING
| MF_BYCOMMAND
, identifier
, QWCHAR(text
)) == TRUE
);
1734 * Display the window's close button
1736 bool lamexp_enable_close_button(const QWidget
*win
, const bool bEnable
)
1740 if(HMENU hMenu
= GetSystemMenu(win
->winId(), FALSE
))
1742 ok
= (EnableMenuItem(hMenu
, SC_CLOSE
, MF_BYCOMMAND
| (bEnable
? MF_ENABLED
: MF_GRAYED
)) == TRUE
);
1749 * Check whether ESC key has been pressed since the previous call to this function
1751 bool lamexp_check_escape_state(void)
1753 return (GetAsyncKeyState(VK_ESCAPE
) & 0x0001) != 0;
1757 * Set the process priority class for current process
1759 bool lamexp_change_process_priority(const int priority
)
1761 return lamexp_change_process_priority(GetCurrentProcess(), priority
);
1765 * Set the process priority class for specified process
1767 bool lamexp_change_process_priority(const QProcess
*proc
, const int priority
)
1769 if(Q_PID qPid
= proc
->pid())
1771 return lamexp_change_process_priority(qPid
->hProcess
, priority
);
1780 * Set the process priority class for specified process
1782 bool lamexp_change_process_priority(void *hProcess
, const int priority
)
1786 switch(qBound(-2, priority
, 2))
1789 ok
= (SetPriorityClass(hProcess
, HIGH_PRIORITY_CLASS
) == TRUE
);
1792 if(!(ok
= (SetPriorityClass(hProcess
, ABOVE_NORMAL_PRIORITY_CLASS
) == TRUE
)))
1794 ok
= (SetPriorityClass(hProcess
, HIGH_PRIORITY_CLASS
) == TRUE
);
1798 ok
= (SetPriorityClass(hProcess
, NORMAL_PRIORITY_CLASS
) == TRUE
);
1801 if(!(ok
= (SetPriorityClass(hProcess
, BELOW_NORMAL_PRIORITY_CLASS
) == TRUE
)))
1803 ok
= (SetPriorityClass(hProcess
, IDLE_PRIORITY_CLASS
) == TRUE
);
1807 ok
= (SetPriorityClass(hProcess
, IDLE_PRIORITY_CLASS
) == TRUE
);
1815 * Returns the current file time
1817 unsigned __int64
lamexp_current_file_time(void)
1820 GetSystemTimeAsFileTime(&fileTime
);
1822 ULARGE_INTEGER temp
;
1823 temp
.HighPart
= fileTime
.dwHighDateTime
;
1824 temp
.LowPart
= fileTime
.dwLowDateTime
;
1826 return temp
.QuadPart
;
1830 * Bring the specifed window to the front
1832 bool lamexp_bring_to_front(const QWidget
*window
)
1838 for(int i
= 0; (i
< 5) && (!ret
); i
++)
1840 ret
= (SetForegroundWindow(window
->winId()) != FALSE
);
1841 SwitchToThisWindow(window
->winId(), TRUE
);
1843 LockSetForegroundWindow(LSFW_LOCK
);
1850 * Bring window of the specifed process to the front (callback)
1852 static BOOL CALLBACK
lamexp_bring_process_to_front_helper(HWND hwnd
, LPARAM lParam
)
1854 DWORD processId
= *reinterpret_cast<WORD
*>(lParam
);
1855 DWORD windowProcessId
= NULL
;
1856 GetWindowThreadProcessId(hwnd
, &windowProcessId
);
1857 if(windowProcessId
== processId
)
1859 SwitchToThisWindow(hwnd
, TRUE
);
1860 SetForegroundWindow(hwnd
);
1868 * Bring window of the specifed process to the front
1870 bool lamexp_bring_process_to_front(const unsigned long pid
)
1872 return EnumWindows(lamexp_bring_process_to_front_helper
, reinterpret_cast<LPARAM
>(&pid
)) == TRUE
;
1876 * Check the network connectivity status
1878 int lamexp_network_status(void)
1881 const BOOL ret
= IsNetworkAlive(&dwFlags
);
1882 if(GetLastError() == 0)
1884 return (ret
!= FALSE
) ? lamexp_network_yes
: lamexp_network_non
;
1886 return lamexp_network_err
;
1890 * Retrun the process ID of the given QProcess
1892 unsigned long lamexp_process_id(const QProcess
*proc
)
1894 PROCESS_INFORMATION
*procInf
= proc
->pid();
1895 return (procInf
) ? procInf
->dwProcessId
: NULL
;
1899 * Convert long path to short path
1901 QString
lamexp_path_to_short(const QString
&longPath
)
1904 DWORD buffSize
= GetShortPathNameW(reinterpret_cast<const wchar_t*>(longPath
.utf16()), NULL
, NULL
);
1908 wchar_t *buffer
= new wchar_t[buffSize
];
1909 DWORD result
= GetShortPathNameW(reinterpret_cast<const wchar_t*>(longPath
.utf16()), buffer
, buffSize
);
1911 if(result
> 0 && result
< buffSize
)
1913 shortPath
= QString::fromUtf16(reinterpret_cast<const unsigned short*>(buffer
));
1919 return (shortPath
.isEmpty() ? longPath
: shortPath
);
1923 * Open media file in external player
1925 bool lamexp_open_media_file(const QString
&mediaFilePath
)
1927 const static wchar_t *registryPrefix
[2] = { L
"SOFTWARE\\", L
"SOFTWARE\\Wow6432Node\\" };
1928 const static wchar_t *registryKeys
[3] =
1930 L
"Microsoft\\Windows\\CurrentVersion\\Uninstall\\{97D341C8-B0D1-4E4A-A49A-C30B52F168E9}",
1931 L
"Microsoft\\Windows\\CurrentVersion\\Uninstall\\{DB9E4EAB-2717-499F-8D56-4CC8A644AB60}",
1934 const static wchar_t *appNames
[4] = { L
"smplayer_portable.exe", L
"smplayer.exe", L
"MPUI.exe", L
"foobar2000.exe" };
1935 const static wchar_t *valueNames
[2] = { L
"InstallLocation", L
"InstallDir" };
1937 for(size_t i
= 0; i
< 3; i
++)
1939 for(size_t j
= 0; j
< 2; j
++)
1941 QString mplayerPath
;
1942 HKEY registryKeyHandle
= NULL
;
1944 const QString currentKey
= WCHAR2QSTR(registryPrefix
[j
]).append(WCHAR2QSTR(registryKeys
[i
]));
1945 if(RegOpenKeyExW(HKEY_LOCAL_MACHINE
, QWCHAR(currentKey
), 0, KEY_READ
, ®istryKeyHandle
) == ERROR_SUCCESS
)
1947 for(size_t k
= 0; k
< 2; k
++)
1949 wchar_t Buffer
[4096];
1950 DWORD BuffSize
= sizeof(wchar_t*) * 4096;
1951 DWORD DataType
= REG_NONE
;
1952 if(RegQueryValueExW(registryKeyHandle
, valueNames
[k
], 0, &DataType
, reinterpret_cast<BYTE
*>(Buffer
), &BuffSize
) == ERROR_SUCCESS
)
1954 if((DataType
== REG_SZ
) || (DataType
== REG_EXPAND_SZ
) || (DataType
== REG_LINK
))
1956 mplayerPath
= WCHAR2QSTR(Buffer
);
1961 RegCloseKey(registryKeyHandle
);
1964 if(!mplayerPath
.isEmpty())
1966 QDir
mplayerDir(mplayerPath
);
1967 if(mplayerDir
.exists())
1969 for(size_t k
= 0; k
< 4; k
++)
1971 if(mplayerDir
.exists(WCHAR2QSTR(appNames
[k
])))
1973 qDebug("Player found at:\n%s\n", QUTF8(mplayerDir
.absoluteFilePath(WCHAR2QSTR(appNames
[k
]))));
1974 QProcess::startDetached(mplayerDir
.absoluteFilePath(WCHAR2QSTR(appNames
[k
])), QStringList() << QDir::toNativeSeparators(mediaFilePath
));
1985 static void lamexp_init_dwmapi(void)
1987 QReadLocker
writeLock(&g_lamexp_dwmapi
.lock
);
1989 //Not initialized yet?
1990 if(g_lamexp_dwmapi
.bInitialized
)
1995 //Reset function pointers
1996 g_lamexp_dwmapi
.dwmIsCompositionEnabled
= NULL
;
1997 g_lamexp_dwmapi
.dwmExtendFrameIntoClientArea
= NULL
;
1998 g_lamexp_dwmapi
.dwmEnableBlurBehindWindow
= NULL
;
2000 //Does OS support DWM?
2001 if(lamexp_get_os_version() >= lamexp_winver_vista
)
2004 g_lamexp_dwmapi
.dwmapi_dll
= new QLibrary("dwmapi.dll");
2005 if(g_lamexp_dwmapi
.dwmapi_dll
->load())
2007 //Initialize function pointers
2008 g_lamexp_dwmapi
.dwmIsCompositionEnabled
= (HRESULT (__stdcall
*)(BOOL
*)) g_lamexp_dwmapi
.dwmapi_dll
->resolve("DwmIsCompositionEnabled");
2009 g_lamexp_dwmapi
.dwmExtendFrameIntoClientArea
= (HRESULT (__stdcall
*)(HWND
, const MARGINS
*)) g_lamexp_dwmapi
.dwmapi_dll
->resolve("DwmExtendFrameIntoClientArea");
2010 g_lamexp_dwmapi
.dwmEnableBlurBehindWindow
= (HRESULT (__stdcall
*)(HWND
, const DWM_BLURBEHIND
*)) g_lamexp_dwmapi
.dwmapi_dll
->resolve("DwmEnableBlurBehindWindow");
2014 LAMEXP_DELETE(g_lamexp_dwmapi
.dwmapi_dll
);
2015 qWarning("Failed to load DWMAPI.DLL on a DWM-enabled system!");
2019 g_lamexp_dwmapi
.bInitialized
= true;
2023 * Enable "sheet of glass" effect on the given Window
2025 bool lamexp_sheet_of_glass(QWidget
*window
)
2027 QReadLocker
readLock(&g_lamexp_dwmapi
.lock
);
2029 //Initialize the DWM API
2030 while(!g_lamexp_dwmapi
.bInitialized
)
2033 lamexp_init_dwmapi();
2037 BOOL bCompositionEnabled
= FALSE
;
2039 //Required functions available?
2040 if((g_lamexp_dwmapi
.dwmIsCompositionEnabled
!= NULL
) && (g_lamexp_dwmapi
.dwmExtendFrameIntoClientArea
!= NULL
) && (g_lamexp_dwmapi
.dwmEnableBlurBehindWindow
!= NULL
))
2042 //Check if composition is currently enabled
2043 if(HRESULT hr
= g_lamexp_dwmapi
.dwmIsCompositionEnabled(&bCompositionEnabled
))
2045 qWarning("DwmIsCompositionEnabled function has failed! (error %d)", hr
);
2050 //All functions available *and* composition enabled?
2051 if(!bCompositionEnabled
)
2056 //Enable the "sheet of glass" effect on this window
2057 MARGINS margins
= {-1, -1, -1, -1};
2058 if(HRESULT hr
= g_lamexp_dwmapi
.dwmExtendFrameIntoClientArea(window
->winId(), &margins
))
2060 qWarning("DwmExtendFrameIntoClientArea function has failed! (error %d)", hr
);
2064 //Create and populate the Blur Behind structure
2066 memset(&bb
, 0, sizeof(DWM_BLURBEHIND
));
2068 bb
.dwFlags
= DWM_BB_ENABLE
;
2069 if(HRESULT hr
= g_lamexp_dwmapi
.dwmEnableBlurBehindWindow(window
->winId(), &bb
))
2071 qWarning("DwmEnableBlurBehindWindow function has failed! (error %d)", hr
);
2076 window
->setAutoFillBackground(false);
2077 window
->setAttribute(Qt::WA_TranslucentBackground
);
2078 window
->setAttribute(Qt::WA_NoSystemBackground
);
2084 * Update "sheet of glass" effect on the given Window
2086 bool lamexp_sheet_of_glass_update(QWidget
*window
)
2088 QReadLocker
readLock(&g_lamexp_dwmapi
.lock
);
2090 //Initialize the DWM API
2091 while(!g_lamexp_dwmapi
.bInitialized
)
2094 lamexp_init_dwmapi();
2098 BOOL bCompositionEnabled
= FALSE
;
2100 //Required functions available?
2101 if((g_lamexp_dwmapi
.dwmIsCompositionEnabled
!= NULL
) && (g_lamexp_dwmapi
.dwmEnableBlurBehindWindow
!= NULL
))
2103 //Check if composition is currently enabled
2104 if(HRESULT hr
= g_lamexp_dwmapi
.dwmIsCompositionEnabled(&bCompositionEnabled
))
2106 qWarning("DwmIsCompositionEnabled function has failed! (error %d)", hr
);
2111 //All functions available *and* composition enabled?
2112 if(!bCompositionEnabled
)
2117 //Create and populate the Blur Behind structure
2119 memset(&bb
, 0, sizeof(DWM_BLURBEHIND
));
2121 bb
.dwFlags
= DWM_BB_ENABLE
;
2122 if(HRESULT hr
= g_lamexp_dwmapi
.dwmEnableBlurBehindWindow(window
->winId(), &bb
))
2124 qWarning("DwmEnableBlurBehindWindow function has failed! (error %d)", hr
);
2132 * Update the window icon
2134 lamexp_icon_t
*lamexp_set_window_icon(QWidget
*window
, const QIcon
&icon
, const bool bIsBigIcon
)
2138 const int extend
= (bIsBigIcon
? 32 : 16);
2139 if(HICON hIcon
= lamexp_qicon2hicon(icon
, extend
, extend
))
2141 SendMessage(window
->winId(), WM_SETICON
, (bIsBigIcon
? ICON_BIG
: ICON_SMALL
), LPARAM(hIcon
));
2142 return reinterpret_cast<lamexp_icon_t
*>(hIcon
);
2151 void lamexp_free_window_icon(lamexp_icon_t
*icon
)
2153 if(HICON hIcon
= reinterpret_cast<HICON
>(icon
))
2160 * Get system color info
2162 QColor
lamexp_system_color(const int color_id
)
2168 case lamexp_syscolor_text
:
2169 nIndex
= COLOR_WINDOWTEXT
; /*Text in windows*/
2171 case lamexp_syscolor_background
:
2172 nIndex
= COLOR_WINDOW
; /*Window background*/
2174 case lamexp_syscolor_caption
:
2175 nIndex
= COLOR_CAPTIONTEXT
; /*Text in caption, size box, and scroll bar arrow box*/
2178 qWarning("Unknown system color id (%d) specified!", color_id
);
2179 nIndex
= COLOR_WINDOWTEXT
;
2182 const DWORD rgb
= GetSysColor(nIndex
);
2183 QColor
color(GetRValue(rgb
), GetGValue(rgb
), GetBValue(rgb
));
2188 * Check if the current user is an administartor (helper function)
2190 static bool lamexp_user_is_admin_helper(void)
2192 HANDLE hToken
= NULL
;
2193 if(!OpenProcessToken(GetCurrentProcess(), TOKEN_QUERY
, &hToken
))
2199 if(!GetTokenInformation(hToken
, TokenGroups
, NULL
, 0, &dwSize
))
2201 if(GetLastError() != ERROR_INSUFFICIENT_BUFFER
)
2203 CloseHandle(hToken
);
2208 PTOKEN_GROUPS lpGroups
= (PTOKEN_GROUPS
) malloc(dwSize
);
2211 CloseHandle(hToken
);
2215 if(!GetTokenInformation(hToken
, TokenGroups
, lpGroups
, dwSize
, &dwSize
))
2218 CloseHandle(hToken
);
2222 PSID lpSid
= NULL
; SID_IDENTIFIER_AUTHORITY Authority
= {SECURITY_NT_AUTHORITY
};
2223 if(!AllocateAndInitializeSid(&Authority
, 2, SECURITY_BUILTIN_DOMAIN_RID
, DOMAIN_ALIAS_RID_ADMINS
, 0, 0, 0, 0, 0, 0, &lpSid
))
2226 CloseHandle(hToken
);
2230 bool bResult
= false;
2231 for(DWORD i
= 0; i
< lpGroups
->GroupCount
; i
++)
2233 if(EqualSid(lpSid
, lpGroups
->Groups
[i
].Sid
))
2242 CloseHandle(hToken
);
2247 * Check if the current user is an administartor
2249 bool lamexp_user_is_admin(void)
2251 bool isAdmin
= false;
2253 //Check for process elevation and UAC support first!
2254 if(lamexp_process_is_elevated(&isAdmin
))
2256 qWarning("Process is elevated -> user is admin!");
2260 //If not elevated and UAC is not available -> user must be in admin group!
2263 qDebug("UAC is disabled/unavailable -> checking for Administrators group");
2264 isAdmin
= lamexp_user_is_admin_helper();
2271 * Check if file is a valid Win32/Win64 executable
2273 bool lamexp_is_executable(const QString
&path
)
2275 bool bIsExecutable
= false;
2277 if(GetBinaryType(QWCHAR(QDir::toNativeSeparators(path
)), &binaryType
))
2279 bIsExecutable
= (binaryType
== SCS_32BIT_BINARY
|| binaryType
== SCS_64BIT_BINARY
);
2281 return bIsExecutable
;
2285 * Fatal application exit
2287 #pragma intrinsic(_InterlockedExchange)
2288 void lamexp_fatal_exit(const wchar_t* exitMessage
, const wchar_t* errorBoxMessage
)
2290 static volatile long bFatalFlag
= 0L;
2292 if(_InterlockedExchange(&bFatalFlag
, 1L) == 0L)
2294 if(GetCurrentThreadId() != g_main_thread_id
)
2296 HANDLE mainThread
= OpenThread(THREAD_TERMINATE
, FALSE
, g_main_thread_id
);
2297 if(mainThread
) TerminateThread(mainThread
, ULONG_MAX
);
2302 MessageBoxW(NULL
, errorBoxMessage
, L
"LameXP - GURU MEDITATION", MB_ICONERROR
| MB_TOPMOST
| MB_TASKMODAL
);
2307 FatalAppExit(0, exitMessage
);
2308 TerminateProcess(GetCurrentProcess(), -1);
2312 TerminateThread(GetCurrentThread(), -1);
2317 * Initialize debug thread
2319 static const HANDLE g_debug_thread1
= LAMEXP_DEBUG
? NULL
: lamexp_debug_thread_init();
2322 * Get number private bytes [debug only]
2324 unsigned long lamexp_dbg_private_bytes(void)
2327 for(int i
= 0; i
< 8; i
++) _heapmin();
2328 PROCESS_MEMORY_COUNTERS_EX memoryCounters
;
2329 memoryCounters
.cb
= sizeof(PROCESS_MEMORY_COUNTERS_EX
);
2330 GetProcessMemoryInfo(GetCurrentProcess(), (PPROCESS_MEMORY_COUNTERS
) &memoryCounters
, sizeof(PROCESS_MEMORY_COUNTERS_EX
));
2331 return memoryCounters
.PrivateUsage
;
2333 THROW("Cannot call this function in a non-debug build!");
2334 #endif //LAMEXP_DEBUG
2338 * Output string to debugger [debug only]
2340 void lamexp_dbg_dbg_output_string(const char* format
, ...)
2345 va_start (args
, format
);
2346 vsnprintf_s(buffer
, 256, _TRUNCATE
, format
, args
);
2347 OutputDebugStringA(buffer
);
2350 THROW("Cannot call this function in a non-debug build!");
2351 #endif //LAMEXP_DEBUG
2354 ///////////////////////////////////////////////////////////////////////////////
2356 ///////////////////////////////////////////////////////////////////////////////
2358 extern "C" void _lamexp_global_init_win32(void)
2360 if((!LAMEXP_DEBUG
) && lamexp_check_for_debugger())
2362 lamexp_fatal_exit(L
"Not a debug build. Please unload debugger and try again!");
2365 //Zero *before* constructors are called
2366 LAMEXP_ZERO_MEMORY(g_lamexp_argv
);
2367 LAMEXP_ZERO_MEMORY(g_lamexp_known_folder
);
2368 LAMEXP_ZERO_MEMORY(g_lamexp_os_version
);
2369 LAMEXP_ZERO_MEMORY(g_lamexp_wine
);
2370 LAMEXP_ZERO_MEMORY(g_lamexp_themes_enabled
);
2371 LAMEXP_ZERO_MEMORY(g_lamexp_dwmapi
);
2372 LAMEXP_ZERO_MEMORY(g_lamexp_sounds
);
2375 ///////////////////////////////////////////////////////////////////////////////
2377 ///////////////////////////////////////////////////////////////////////////////
2379 extern "C" void _lamexp_global_free_win32(void)
2381 //Clear folder cache
2382 LAMEXP_DELETE(g_lamexp_known_folder
.knownFolders
);
2384 //Destroy Qt application object
2385 QApplication
*application
= dynamic_cast<QApplication
*>(QApplication::instance());
2386 LAMEXP_DELETE(application
);
2389 g_lamexp_dwmapi
.dwmIsCompositionEnabled
= NULL
;
2390 g_lamexp_dwmapi
.dwmExtendFrameIntoClientArea
= NULL
;
2391 g_lamexp_dwmapi
.dwmEnableBlurBehindWindow
= NULL
;
2392 LAMEXP_DELETE(g_lamexp_dwmapi
.dwmapi_dll
);
2394 //Free STDOUT and STDERR buffers
2395 if(g_lamexp_console_attached
)
2397 if(std::filebuf
*tmp
= dynamic_cast<std::filebuf
*>(std::cout
.rdbuf()))
2399 std::cout
.rdbuf(NULL
);
2402 if(std::filebuf
*tmp
= dynamic_cast<std::filebuf
*>(std::cerr
.rdbuf()))
2404 std::cerr
.rdbuf(NULL
);
2410 if(g_lamexp_log_file
)
2412 fclose(g_lamexp_log_file
);
2413 g_lamexp_log_file
= NULL
;
2417 LAMEXP_DELETE(g_lamexp_sounds
.sound_db
);
2419 //Free CLI Arguments
2420 LAMEXP_DELETE(g_lamexp_argv
.list
);