1 ///////////////////////////////////////////////////////////////////////////////
2 // LameXP - Audio Encoder Front-End
3 // Copyright (C) 2004-2012 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.
10 // This program is distributed in the hope that it will be useful,
11 // but WITHOUT ANY WARRANTY; without even the implied warranty of
12 // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 // GNU General Public License for more details.
15 // You should have received a copy of the GNU General Public License along
16 // with this program; if not, write to the Free Software Foundation, Inc.,
17 // 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
19 // http://www.gnu.org/licenses/gpl-2.0.txt
20 ///////////////////////////////////////////////////////////////////////////////
25 #include <QApplication>
26 #include <QMessageBox>
32 #include <QPlastiqueStyle>
33 #include <QImageReader>
34 #include <QSharedMemory>
36 #include <QStringList>
37 #include <QSystemSemaphore>
43 #include <QTranslator>
46 #include <QLibraryInfo>
48 #include <QReadWriteLock>
49 #include <QReadLocker>
50 #include <QWriteLocker>
54 #include "LockedFile.h"
78 //Initialize static Qt plugins
80 #if QT_VERSION < QT_VERSION_CHECK(5,0,0)
84 Q_IMPORT_PLUGIN(QWindowsIntegrationPlugin
)
85 Q_IMPORT_PLUGIN(QICOPlugin
)
89 #define LAMEXP_ZERO_MEMORY(X) SecureZeroMemory(&X, sizeof(X))
91 ///////////////////////////////////////////////////////////////////////////////
93 ///////////////////////////////////////////////////////////////////////////////
95 static const size_t g_lamexp_ipc_slots
= 128;
100 unsigned int reserved_1
;
101 unsigned int reserved_2
;
102 char parameter
[4096];
108 unsigned int pos_write
;
109 unsigned int pos_read
;
110 lamexp_ipc_data_t data
[g_lamexp_ipc_slots
];
114 ///////////////////////////////////////////////////////////////////////////////
116 ///////////////////////////////////////////////////////////////////////////////
121 unsigned int ver_major
;
122 unsigned int ver_minor
;
123 unsigned int ver_build
;
124 char *ver_release_name
;
135 static QDate g_lamexp_version_date
;
136 static const char *g_lamexp_months
[] = {"Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"};
137 static const char *g_lamexp_version_raw_date
= __DATE__
;
138 static const char *g_lamexp_version_raw_time
= __TIME__
;
140 //Console attached flag
141 static bool g_lamexp_console_attached
= false;
144 //The following code was borrowed from MPC-HC project: http://mpc-hc.sf.net/
145 #if defined(__INTEL_COMPILER)
146 #if (__INTEL_COMPILER >= 1200)
147 static const char *g_lamexp_version_compiler
= "ICL 12.x";
148 #elif (__INTEL_COMPILER >= 1100)
149 static const char *g_lamexp_version_compiler
= "ICL 11.x";
150 #elif (__INTEL_COMPILER >= 1000)
151 static const char *g_lamexp_version_compiler
= "ICL 10.x";
153 #error Compiler is not supported!
155 #elif defined(_MSC_VER)
156 #if (_MSC_VER == 1600)
157 #if (_MSC_FULL_VER >= 160040219)
158 static const char *g_lamexp_version_compiler
= "MSVC 2010-SP1";
160 static const char *g_lamexp_version_compiler
= "MSVC 2010";
162 #elif (_MSC_VER == 1500)
163 #if (_MSC_FULL_VER >= 150030729)
164 static const char *g_lamexp_version_compiler
= "MSVC 2008-SP1";
166 static const char *g_lamexp_version_compiler
= "MSVC 2008";
169 #error Compiler is not supported!
172 // Note: /arch:SSE and /arch:SSE2 are only available for the x86 platform
173 #if !defined(_M_X64) && defined(_M_IX86_FP)
174 #if (_M_IX86_FP == 1)
175 LAMEXP_COMPILER_WARNING("SSE instruction set is enabled!")
176 #elif (_M_IX86_FP == 2)
177 LAMEXP_COMPILER_WARNING("SSE2 instruction set is enabled!")
181 #error Compiler is not supported!
184 //Architecture detection
186 static const char *g_lamexp_version_arch
= "x64";
187 #elif defined(_M_IX86)
188 static const char *g_lamexp_version_arch
= "x86";
190 #error Architecture is not supported!
193 //Official web-site URL
194 static const char *g_lamexp_website_url
= "http://lamexp.sourceforge.net/";
195 static const char *g_lamexp_support_url
= "http://forum.doom9.org/showthread.php?t=157726";
197 //Tool versions (expected versions!)
198 static const unsigned int g_lamexp_toolver_neroaac
= VER_LAMEXP_TOOL_NEROAAC
;
199 static const unsigned int g_lamexp_toolver_fhgaacenc
= VER_LAMEXP_TOOL_FHGAACENC
;
200 static const unsigned int g_lamexp_toolver_qaacenc
= VER_LAMEXP_TOOL_QAAC
;
201 static const unsigned int g_lamexp_toolver_coreaudio
= VER_LAMEXP_TOOL_COREAUDIO
;
207 QMap
<size_t, QString
> *knownFolders
;
215 QMap
<QString
, LockedFile
*> *registry
;
216 QMap
<QString
, unsigned int> *versions
;
224 QMap
<QString
, QString
> *files
;
225 QMap
<QString
, QString
> *names
;
226 QMap
<QString
, unsigned int> *sysid
;
227 QMap
<QString
, unsigned int> *cntry
;
230 g_lamexp_translation
;
235 QTranslator
*instance
;
238 g_lamexp_currentTranslator
;
252 char *semaphore_read
;
253 char *semaphore_read_mutex
;
254 char *semaphore_write
;
255 char *semaphore_write_mutex
;
259 "{21A68A42-6923-43bb-9CF6-64BF151942EE}",
260 "{7A605549-F58C-4d78-B4E5-06EFC34F405B}",
261 "{60AA8D04-F6B8-497d-81EB-0F600F4A65B5}",
262 "{726061D5-1615-4B82-871C-75FD93458E46}",
263 "{1A616023-AA6A-4519-8AF3-F7736E899977}"
267 QSharedMemory
*sharedmem
;
268 QSystemSemaphore
*semaphore_read
;
269 QSystemSemaphore
*semaphore_read_mutex
;
270 QSystemSemaphore
*semaphore_write
;
271 QSystemSemaphore
*semaphore_write_mutex
;
277 static const char *g_lamexp_imageformats
[] = {"bmp", "png", "jpg", "gif", "ico", "xpm", NULL
}; //"svg"
280 static QMutex g_lamexp_message_mutex
;
283 static const DWORD g_main_thread_id
= GetCurrentThreadId();
286 static FILE *g_lamexp_log_file
= NULL
;
288 ///////////////////////////////////////////////////////////////////////////////
290 ///////////////////////////////////////////////////////////////////////////////
295 unsigned int lamexp_version_major(void) { return g_lamexp_version
.ver_major
; }
296 unsigned int lamexp_version_minor(void) { return g_lamexp_version
.ver_minor
; }
297 unsigned int lamexp_version_build(void) { return g_lamexp_version
.ver_build
; }
298 const char *lamexp_version_release(void) { return g_lamexp_version
.ver_release_name
; }
299 const char *lamexp_version_time(void) { return g_lamexp_version_raw_time
; }
300 const char *lamexp_version_compiler(void) { return g_lamexp_version_compiler
; }
301 const char *lamexp_version_arch(void) { return g_lamexp_version_arch
; }
302 unsigned int lamexp_toolver_neroaac(void) { return g_lamexp_toolver_neroaac
; }
303 unsigned int lamexp_toolver_fhgaacenc(void) { return g_lamexp_toolver_fhgaacenc
; }
304 unsigned int lamexp_toolver_qaacenc(void) { return g_lamexp_toolver_qaacenc
; }
305 unsigned int lamexp_toolver_coreaudio(void) { return g_lamexp_toolver_coreaudio
; }
310 const char *lamexp_website_url(void) { return g_lamexp_website_url
; }
311 const char *lamexp_support_url(void) { return g_lamexp_support_url
; }
314 * Check for Demo (pre-release) version
316 bool lamexp_version_demo(void)
319 bool releaseVersion
= false;
320 if(!strncpy_s(buffer
, 128, g_lamexp_version
.ver_release_name
, _TRUNCATE
))
322 char *context
, *prefix
= strtok_s(buffer
, "-,; ", &context
);
325 releaseVersion
= (!_stricmp(prefix
, "Final")) || (!_stricmp(prefix
, "Hotfix"));
328 return LAMEXP_DEBUG
|| (!releaseVersion
);
332 * Calculate expiration date
334 QDate
lamexp_version_expires(void)
336 return lamexp_version_date().addDays(LAMEXP_DEBUG
? 7 : 30);
340 * Get build date date
342 const QDate
&lamexp_version_date(void)
344 if(!g_lamexp_version_date
.isValid())
346 int date
[3] = {0, 0, 0}; char temp
[12] = {'\0'};
347 strncpy_s(temp
, 12, g_lamexp_version_raw_date
, _TRUNCATE
);
349 if(strlen(temp
) == 11)
351 temp
[3] = temp
[6] = '\0';
352 date
[2] = atoi(&temp
[4]);
353 date
[0] = atoi(&temp
[7]);
355 for(int j
= 0; j
< 12; j
++)
357 if(!_strcmpi(&temp
[0], g_lamexp_months
[j
]))
364 g_lamexp_version_date
= QDate(date
[0], date
[1], date
[2]);
367 if(!g_lamexp_version_date
.isValid())
369 qFatal("Internal error: Date format could not be recognized!");
373 return g_lamexp_version_date
;
377 * Get the native operating system version
379 DWORD
lamexp_get_os_version(void)
381 static DWORD osVersion
= 0;
385 OSVERSIONINFO osVerInfo
;
386 memset(&osVerInfo
, 0, sizeof(OSVERSIONINFO
));
387 osVerInfo
.dwOSVersionInfoSize
= sizeof(OSVERSIONINFO
);
389 if(GetVersionEx(&osVerInfo
) == TRUE
)
391 if(osVerInfo
.dwPlatformId
!= VER_PLATFORM_WIN32_NT
)
393 throw "Ouuups: Not running under Windows NT. This is not supposed to happen!";
395 const DWORD osVerHi
= (DWORD
)(((DWORD
)(osVerInfo
.dwMajorVersion
)) << 16);
396 const DWORD osVerLo
= (DWORD
)(((DWORD
)(osVerInfo
.dwMinorVersion
)) & ((DWORD
)(0xffff)));
397 osVersion
= (DWORD
)(((DWORD
)(osVerHi
)) | ((DWORD
)(osVerLo
)));
401 throw "GetVersionEx() has failed. This is not supposed to happen!";
409 * Check if we are running under wine
411 bool lamexp_detect_wine(void)
413 static bool isWine
= false;
414 static bool isWine_initialized
= false;
416 if(!isWine_initialized
)
418 QLibrary
ntdll("ntdll.dll");
421 if(ntdll
.resolve("wine_nt_to_unix_file_name") != NULL
) isWine
= true;
422 if(ntdll
.resolve("wine_get_version") != NULL
) isWine
= true;
425 isWine_initialized
= true;
432 * Global exception handler
434 LONG WINAPI
lamexp_exception_handler(__in
struct _EXCEPTION_POINTERS
*ExceptionInfo
)
436 if(GetCurrentThreadId() != g_main_thread_id
)
438 HANDLE mainThread
= OpenThread(THREAD_TERMINATE
, FALSE
, g_main_thread_id
);
439 if(mainThread
) TerminateThread(mainThread
, ULONG_MAX
);
442 FatalAppExit(0, L
"Unhandeled exception handler invoked, application will exit!");
443 TerminateProcess(GetCurrentProcess(), -1);
448 * Invalid parameters handler
450 void lamexp_invalid_param_handler(const wchar_t*, const wchar_t*, const wchar_t*, unsigned int, uintptr_t)
452 if(GetCurrentThreadId() != g_main_thread_id
)
454 HANDLE mainThread
= OpenThread(THREAD_TERMINATE
, FALSE
, g_main_thread_id
);
455 if(mainThread
) TerminateThread(mainThread
, ULONG_MAX
);
459 FatalAppExit(0, L
"Invalid parameter handler invoked, application will exit!");
460 TerminateProcess(GetCurrentProcess(), -1);
464 * Change console text color
466 static void lamexp_console_color(FILE* file
, WORD attributes
)
468 const HANDLE hConsole
= (HANDLE
)(_get_osfhandle(_fileno(file
)));
469 if((hConsole
!= NULL
) && (hConsole
!= INVALID_HANDLE_VALUE
))
471 SetConsoleTextAttribute(hConsole
, attributes
);
478 void lamexp_message_handler(QtMsgType type
, const char *msg
)
480 static const char *GURU_MEDITATION
= "\n\nGURU MEDITATION !!!\n\n";
482 QMutexLocker
lock(&g_lamexp_message_mutex
);
484 if(g_lamexp_log_file
)
486 static char prefix
[] = "DWCF";
487 int index
= qBound(0, static_cast<int>(type
), 3);
488 unsigned int timestamp
= static_cast<unsigned int>(_time64(NULL
) % 3600I64
);
489 QString str
= QString::fromUtf8(msg
).trimmed().replace('\n', '\t');
490 fprintf(g_lamexp_log_file
, "[%c][%04u] %s\r\n", prefix
[index
], timestamp
, str
.toUtf8().constData());
491 fflush(g_lamexp_log_file
);
494 if(g_lamexp_console_attached
)
496 UINT oldOutputCP
= GetConsoleOutputCP();
497 if(oldOutputCP
!= CP_UTF8
) SetConsoleOutputCP(CP_UTF8
);
505 lamexp_console_color(stderr
, FOREGROUND_RED
| FOREGROUND_INTENSITY
);
506 fprintf(stderr
, GURU_MEDITATION
);
507 fprintf(stderr
, "%s\n", msg
);
511 lamexp_console_color(stderr
, FOREGROUND_GREEN
| FOREGROUND_RED
| FOREGROUND_INTENSITY
);
512 fprintf(stderr
, "%s\n", msg
);
516 lamexp_console_color(stderr
, FOREGROUND_BLUE
| FOREGROUND_GREEN
| FOREGROUND_RED
| FOREGROUND_INTENSITY
);
517 fprintf(stderr
, "%s\n", msg
);
522 lamexp_console_color(stderr
, FOREGROUND_BLUE
| FOREGROUND_GREEN
| FOREGROUND_RED
);
523 if(oldOutputCP
!= CP_UTF8
) SetConsoleOutputCP(oldOutputCP
);
527 QString
temp("[LameXP][%1] %2");
533 temp
= temp
.arg("C", QString::fromUtf8(msg
));
536 temp
= temp
.arg("W", QString::fromUtf8(msg
));
539 temp
= temp
.arg("I", QString::fromUtf8(msg
));
543 temp
.replace("\n", "\t").append("\n");
544 OutputDebugStringA(temp
.toLatin1().constData());
547 if(type
== QtCriticalMsg
|| type
== QtFatalMsg
)
551 if(GetCurrentThreadId() != g_main_thread_id
)
553 HANDLE mainThread
= OpenThread(THREAD_TERMINATE
, FALSE
, g_main_thread_id
);
554 if(mainThread
) TerminateThread(mainThread
, ULONG_MAX
);
557 MessageBoxW(NULL
, QWCHAR(QString::fromUtf8(msg
)), L
"LameXP - GURU MEDITATION", MB_ICONERROR
| MB_TOPMOST
| MB_TASKMODAL
);
558 FatalAppExit(0, L
"The application has encountered a critical error and will exit now!");
559 TerminateProcess(GetCurrentProcess(), -1);
564 * Initialize the console
566 void lamexp_init_console(const QStringList
&argv
)
568 bool enableConsole
= lamexp_version_demo();
572 wchar_t *logfile
= NULL
;
573 size_t logfile_len
= 0;
574 if(!_wdupenv_s(&logfile
, &logfile_len
, L
"LAMEXP_LOGFILE"))
576 if(logfile
&& (logfile_len
> 0))
579 if(!_wfopen_s(&temp
, logfile
, L
"wb"))
581 fprintf(temp
, "%c%c%c", 0xEF, 0xBB, 0xBF);
582 g_lamexp_log_file
= temp
;
591 for(int i
= 0; i
< argv
.count(); i
++)
593 if(!argv
.at(i
).compare("--console", Qt::CaseInsensitive
))
595 enableConsole
= true;
597 else if(!argv
.at(i
).compare("--no-console", Qt::CaseInsensitive
))
599 enableConsole
= false;
606 if(!g_lamexp_console_attached
)
608 if(AllocConsole() != FALSE
)
610 SetConsoleCtrlHandler(NULL
, TRUE
);
611 SetConsoleTitle(L
"LameXP - Audio Encoder Front-End | Debug Console");
612 SetConsoleOutputCP(CP_UTF8
);
613 g_lamexp_console_attached
= true;
617 if(g_lamexp_console_attached
)
619 //-------------------------------------------------------------------
620 //See: http://support.microsoft.com/default.aspx?scid=kb;en-us;105305
621 //-------------------------------------------------------------------
622 const int flags
= _O_WRONLY
| _O_U8TEXT
;
623 int hCrtStdOut
= _open_osfhandle((intptr_t) GetStdHandle(STD_OUTPUT_HANDLE
), flags
);
624 int hCrtStdErr
= _open_osfhandle((intptr_t) GetStdHandle(STD_ERROR_HANDLE
), flags
);
625 FILE *hfStdOut
= (hCrtStdOut
>= 0) ? _fdopen(hCrtStdOut
, "wb") : NULL
;
626 FILE *hfStdErr
= (hCrtStdErr
>= 0) ? _fdopen(hCrtStdErr
, "wb") : NULL
;
627 if(hfStdOut
) { *stdout
= *hfStdOut
; std::cout
.rdbuf(new std::filebuf(hfStdOut
)); }
628 if(hfStdErr
) { *stderr
= *hfStdErr
; std::cerr
.rdbuf(new std::filebuf(hfStdErr
)); }
631 HWND hwndConsole
= GetConsoleWindow();
633 if((hwndConsole
!= NULL
) && (hwndConsole
!= INVALID_HANDLE_VALUE
))
635 HMENU hMenu
= GetSystemMenu(hwndConsole
, 0);
636 EnableMenuItem(hMenu
, SC_CLOSE
, MF_BYCOMMAND
| MF_GRAYED
);
637 RemoveMenu(hMenu
, SC_CLOSE
, MF_BYCOMMAND
);
639 SetWindowPos(hwndConsole
, HWND_TOP
, 0, 0, 0, 0, SWP_NOMOVE
|SWP_NOSIZE
|SWP_NOZORDER
|SWP_FRAMECHANGED
);
640 SetWindowLong(hwndConsole
, GWL_STYLE
, GetWindowLong(hwndConsole
, GWL_STYLE
) & (~WS_MAXIMIZEBOX
) & (~WS_MINIMIZEBOX
));
641 SetWindowPos(hwndConsole
, HWND_TOP
, 0, 0, 0, 0, SWP_NOMOVE
|SWP_NOSIZE
|SWP_NOZORDER
|SWP_FRAMECHANGED
);
647 * Detect CPU features
649 lamexp_cpu_t
lamexp_detect_cpu_features(const QStringList
&argv
)
651 typedef BOOL (WINAPI
*IsWow64ProcessFun
)(__in HANDLE hProcess
, __out PBOOL Wow64Process
);
652 typedef VOID (WINAPI
*GetNativeSystemInfoFun
)(__out LPSYSTEM_INFO lpSystemInfo
);
654 static IsWow64ProcessFun IsWow64ProcessPtr
= NULL
;
655 static GetNativeSystemInfoFun GetNativeSystemInfoPtr
= NULL
;
657 lamexp_cpu_t features
;
658 SYSTEM_INFO systemInfo
;
659 int CPUInfo
[4] = {-1};
660 char CPUIdentificationString
[0x40];
661 char CPUBrandString
[0x40];
663 memset(&features
, 0, sizeof(lamexp_cpu_t
));
664 memset(&systemInfo
, 0, sizeof(SYSTEM_INFO
));
665 memset(CPUIdentificationString
, 0, sizeof(CPUIdentificationString
));
666 memset(CPUBrandString
, 0, sizeof(CPUBrandString
));
669 memcpy(CPUIdentificationString
, &CPUInfo
[1], sizeof(int));
670 memcpy(CPUIdentificationString
+ 4, &CPUInfo
[3], sizeof(int));
671 memcpy(CPUIdentificationString
+ 8, &CPUInfo
[2], sizeof(int));
672 features
.intel
= (_stricmp(CPUIdentificationString
, "GenuineIntel") == 0);
673 strncpy_s(features
.vendor
, 0x40, CPUIdentificationString
, _TRUNCATE
);
678 features
.mmx
= (CPUInfo
[3] & 0x800000) || false;
679 features
.sse
= (CPUInfo
[3] & 0x2000000) || false;
680 features
.sse2
= (CPUInfo
[3] & 0x4000000) || false;
681 features
.ssse3
= (CPUInfo
[2] & 0x200) || false;
682 features
.sse3
= (CPUInfo
[2] & 0x1) || false;
683 features
.ssse3
= (CPUInfo
[2] & 0x200) || false;
684 features
.stepping
= CPUInfo
[0] & 0xf;
685 features
.model
= ((CPUInfo
[0] >> 4) & 0xf) + (((CPUInfo
[0] >> 16) & 0xf) << 4);
686 features
.family
= ((CPUInfo
[0] >> 8) & 0xf) + ((CPUInfo
[0] >> 20) & 0xff);
689 __cpuid(CPUInfo
, 0x80000000);
690 int nExIds
= qMax
<int>(qMin
<int>(CPUInfo
[0], 0x80000004), 0x80000000);
692 for(int i
= 0x80000002; i
<= nExIds
; ++i
)
698 memcpy(CPUBrandString
, CPUInfo
, sizeof(CPUInfo
));
701 memcpy(CPUBrandString
+ 16, CPUInfo
, sizeof(CPUInfo
));
704 memcpy(CPUBrandString
+ 32, CPUInfo
, sizeof(CPUInfo
));
709 strncpy_s(features
.brand
, 0x40, CPUBrandString
, _TRUNCATE
);
711 if(strlen(features
.brand
) < 1) strncpy_s(features
.brand
, 0x40, "Unknown", _TRUNCATE
);
712 if(strlen(features
.vendor
) < 1) strncpy_s(features
.vendor
, 0x40, "Unknown", _TRUNCATE
);
714 #if !defined(_M_X64 ) && !defined(_M_IA64)
715 if(!IsWow64ProcessPtr
|| !GetNativeSystemInfoPtr
)
717 QLibrary
Kernel32Lib("kernel32.dll");
718 IsWow64ProcessPtr
= (IsWow64ProcessFun
) Kernel32Lib
.resolve("IsWow64Process");
719 GetNativeSystemInfoPtr
= (GetNativeSystemInfoFun
) Kernel32Lib
.resolve("GetNativeSystemInfo");
721 if(IsWow64ProcessPtr
)
724 if(IsWow64ProcessPtr(GetCurrentProcess(), &x64
))
729 if(GetNativeSystemInfoPtr
)
731 GetNativeSystemInfoPtr(&systemInfo
);
735 GetSystemInfo(&systemInfo
);
737 features
.count
= qBound(1UL, systemInfo
.dwNumberOfProcessors
, 64UL);
739 GetNativeSystemInfo(&systemInfo
);
740 features
.count
= systemInfo
.dwNumberOfProcessors
;
747 for(int i
= 0; i
< argv
.count(); i
++)
749 if(!argv
[i
].compare("--force-cpu-no-64bit", Qt::CaseInsensitive
)) { flag
= true; features
.x64
= false; }
750 if(!argv
[i
].compare("--force-cpu-no-sse", Qt::CaseInsensitive
)) { flag
= true; features
.sse
= features
.sse2
= features
.sse3
= features
.ssse3
= false; }
751 if(!argv
[i
].compare("--force-cpu-no-intel", Qt::CaseInsensitive
)) { flag
= true; features
.intel
= false; }
753 if(flag
) qWarning("CPU flags overwritten by user-defined parameters. Take care!\n");
760 * Check for debugger (detect routine)
762 static __forceinline
bool lamexp_check_for_debugger(void)
764 if(IsDebuggerPresent())
771 CloseHandle((HANDLE
) 0x7FFFFFFF);
773 __except(EXCEPTION_EXECUTE_HANDLER
)
782 __except(EXCEPTION_EXECUTE_HANDLER
)
791 * Check for debugger (thread proc)
793 static unsigned int __stdcall
lamexp_debug_thread_proc(LPVOID lpParameter
)
795 while(!lamexp_check_for_debugger())
799 if(HANDLE thrd
= OpenThread(THREAD_TERMINATE
, FALSE
, g_main_thread_id
))
801 if(TerminateThread(thrd
, -1))
803 FatalAppExit(0, L
"Not a debug build. Please unload debugger and try again!");
807 TerminateProcess(GetCurrentProcess(), -1);
812 * Check for debugger (startup routine)
814 static HANDLE
lamexp_debug_thread_init(void)
816 if(lamexp_check_for_debugger())
818 FatalAppExit(0, L
"Not a debug build. Please unload debugger and try again!");
819 TerminateProcess(GetCurrentProcess(), -1);
822 return (HANDLE
) _beginthreadex(NULL
, 0, lamexp_debug_thread_proc
, NULL
, 0, NULL
);
826 * Check for compatibility mode
828 static bool lamexp_check_compatibility_mode(const char *exportName
, const QString
&executableName
)
830 QLibrary
kernel32("kernel32.dll");
832 if((exportName
!= NULL
) && kernel32
.load())
834 if(kernel32
.resolve(exportName
) != NULL
)
836 qWarning("Function '%s' exported from 'kernel32.dll' -> Windows compatibility mode!", exportName
);
837 qFatal("%s", QApplication::tr("Executable '%1' doesn't support Windows compatibility mode.").arg(executableName
).toLatin1().constData());
846 * Computus according to H. Lichtenberg
848 static bool lamexp_computus(const QDate
&date
)
853 int M
= 15 + (3*K
+ 3) / 4 - (8*K
+ 13) / 25;
854 int D
= (19*A
+ M
) % 30;
855 int S
= 2 - (3*K
+ 3) / 4;
856 int R
= D
/ 29 + (D
/ 28 - D
/ 29) * (A
/ 11);
858 int SZ
= 7 - (X
+ X
/ 4 + S
) % 7;
859 int OE
= 7 - (OG
- SZ
) % 7;
864 return (date
.month() == 4) && (date
.day() == (OS
- 31));
868 return (date
.month() == 3) && (date
.day() == OS
);
873 * Check for Thanksgiving
875 static bool lamexp_thanksgiving(const QDate
&date
)
879 switch(QDate(date
.year(), 11, 1).dayOfWeek())
881 case 1: day
= 25; break;
882 case 2: day
= 24; break;
883 case 3: day
= 23; break;
884 case 4: day
= 22; break;
885 case 5: day
= 28; break;
886 case 6: day
= 27; break;
887 case 7: day
= 26; break;
890 return (date
.month() == 11) && (date
.day() == day
);
894 * Initialize app icon
896 QIcon
lamexp_app_icon(const QDate
*date
, const QTime
*time
)
898 QDate currentDate
= (date
) ? QDate(*date
) : QDate::currentDate();
899 QTime currentTime
= (time
) ? QTime(*time
) : QTime::currentTime();
901 if(lamexp_thanksgiving(currentDate
))
903 return QIcon(":/MainIcon6.png");
905 else if(((currentDate
.month() == 12) && (currentDate
.day() == 31) && (currentTime
.hour() >= 20)) || ((currentDate
.month() == 1) && (currentDate
.day() == 1) && (currentTime
.hour() <= 19)))
907 return QIcon(":/MainIcon5.png");
909 else if(((currentDate
.month() == 10) && (currentDate
.day() == 31) && (currentTime
.hour() >= 12)) || ((currentDate
.month() == 11) && (currentDate
.day() == 1) && (currentTime
.hour() <= 11)))
911 return QIcon(":/MainIcon4.png");
913 else if((currentDate
.month() == 12) && (currentDate
.day() >= 24) && (currentDate
.day() <= 26))
915 return QIcon(":/MainIcon3.png");
917 else if(lamexp_computus(currentDate
))
919 return QIcon(":/MainIcon2.png");
923 return QIcon(":/MainIcon1.png");
928 * Broadcast event to all windows
930 static bool lamexp_broadcast(int eventType
, bool onlyToVisible
)
932 if(QApplication
*app
= dynamic_cast<QApplication
*>(QApplication::instance()))
934 qDebug("Broadcasting %d", eventType
);
937 QEvent
poEvent(static_cast<QEvent::Type
>(eventType
));
938 QWidgetList list
= app
->topLevelWidgets();
940 while(!list
.isEmpty())
942 QWidget
*widget
= list
.takeFirst();
943 if(!onlyToVisible
|| widget
->isVisible())
945 if(!app
->sendEvent(widget
, &poEvent
))
952 qDebug("Broadcast %d done (%s)", eventType
, (allOk
? "OK" : "Stopped"));
957 qWarning("Broadcast failed, could not get QApplication instance!");
965 static bool lamexp_event_filter(void *message
, long *result
)
967 if((!(LAMEXP_DEBUG
)) && lamexp_check_for_debugger())
969 FatalAppExit(0, L
"Not a debug build. Please unload debugger and try again!");
970 TerminateProcess(GetCurrentProcess(), -1);
973 switch(reinterpret_cast<MSG
*>(message
)->message
)
975 case WM_QUERYENDSESSION
:
976 qWarning("WM_QUERYENDSESSION message received!");
977 *result
= lamexp_broadcast(lamexp_event_queryendsession
, false) ? TRUE
: FALSE
;
980 qWarning("WM_ENDSESSION message received!");
981 if(reinterpret_cast<MSG
*>(message
)->wParam
== TRUE
)
983 lamexp_broadcast(lamexp_event_endsession
, false);
984 if(QApplication
*app
= reinterpret_cast<QApplication
*>(QApplication::instance()))
986 app
->closeAllWindows();
989 lamexp_finalization();
995 /*ignore this message and let Qt handle it*/
1001 * Check for process elevation
1003 static bool lamexp_check_elevation(void)
1005 typedef enum { lamexp_token_elevationType_class
= 18, lamexp_token_elevation_class
= 20 } LAMEXP_TOKEN_INFORMATION_CLASS
;
1006 typedef enum { lamexp_elevationType_default
= 1, lamexp_elevationType_full
, lamexp_elevationType_limited
} LAMEXP_TOKEN_ELEVATION_TYPE
;
1008 HANDLE hToken
= NULL
;
1009 bool bIsProcessElevated
= false;
1011 if(OpenProcessToken(GetCurrentProcess(), TOKEN_QUERY
, &hToken
))
1013 LAMEXP_TOKEN_ELEVATION_TYPE tokenElevationType
;
1015 if(GetTokenInformation(hToken
, (TOKEN_INFORMATION_CLASS
) lamexp_token_elevationType_class
, &tokenElevationType
, sizeof(LAMEXP_TOKEN_ELEVATION_TYPE
), &returnLength
))
1017 if(returnLength
== sizeof(LAMEXP_TOKEN_ELEVATION_TYPE
))
1019 switch(tokenElevationType
)
1021 case lamexp_elevationType_default
:
1022 qDebug("Process token elevation type: Default -> UAC is disabled.\n");
1024 case lamexp_elevationType_full
:
1025 qWarning("Process token elevation type: Full -> potential security risk!\n");
1026 bIsProcessElevated
= true;
1028 case lamexp_elevationType_limited
:
1029 qDebug("Process token elevation type: Limited -> not elevated.\n");
1034 CloseHandle(hToken
);
1038 qWarning("Failed to open process token!");
1041 return !bIsProcessElevated
;
1045 * Initialize Qt framework
1047 bool lamexp_init_qt(int argc
, char* argv
[])
1049 static bool qt_initialized
= false;
1050 typedef BOOL (WINAPI
*SetDllDirectoryProc
)(WCHAR
*lpPathName
);
1051 const QStringList
&arguments
= lamexp_arguments();
1053 //Don't initialized again, if done already
1059 //Secure DLL loading
1060 QLibrary
kernel32("kernel32.dll");
1063 SetDllDirectoryProc pSetDllDirectory
= (SetDllDirectoryProc
) kernel32
.resolve("SetDllDirectoryW");
1064 if(pSetDllDirectory
!= NULL
) pSetDllDirectory(L
"");
1068 //Extract executable name from argv[] array
1069 QString executableName
= QLatin1String("LameXP.exe");
1070 if(arguments
.count() > 0)
1072 static const char *delimiters
= "\\/:?";
1073 executableName
= arguments
[0].trimmed();
1074 for(int i
= 0; delimiters
[i
]; i
++)
1076 int temp
= executableName
.lastIndexOf(QChar(delimiters
[i
]));
1077 if(temp
>= 0) executableName
= executableName
.mid(temp
+ 1);
1079 executableName
= executableName
.trimmed();
1080 if(executableName
.isEmpty())
1082 executableName
= QLatin1String("LameXP.exe");
1088 qDebug("Using Qt v%s [%s], %s, %s", qVersion(), QLibraryInfo::buildDate().toString(Qt::ISODate
).toLatin1().constData(), (qSharedBuild() ? "DLL" : "Static"), QLibraryInfo::buildKey().toLatin1().constData());
1089 qDebug("Compiled with Qt v%s [%s], %s\n", QT_VERSION_STR
, QT_PACKAGEDATE_STR
, QT_BUILD_KEY
);
1090 if(_stricmp(qVersion(), QT_VERSION_STR
))
1092 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());
1095 if(QLibraryInfo::buildKey().compare(QString::fromLatin1(QT_BUILD_KEY
), Qt::CaseInsensitive
))
1097 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());
1101 qDebug("Using Qt v%s [%s], %s", qVersion(), QLibraryInfo::buildDate().toString(Qt::ISODate
).toLatin1().constData(), (qSharedBuild() ? "DLL" : "Static"));
1102 qDebug("Compiled with Qt v%s [%s]\n", QT_VERSION_STR
, QT_PACKAGEDATE_STR
);
1105 //Check the Windows version
1106 switch(QSysInfo::windowsVersion() & QSysInfo::WV_NT_based
)
1109 case QSysInfo::WV_NT
:
1110 qFatal("%s", QApplication::tr("Executable '%1' requires Windows 2000 or later.").arg(executableName
).toLatin1().constData());
1112 case QSysInfo::WV_2000
:
1113 qDebug("Running on Windows 2000 (not officially supported!).\n");
1114 lamexp_check_compatibility_mode("GetNativeSystemInfo", executableName
);
1116 case QSysInfo::WV_XP
:
1117 qDebug("Running on Windows XP.\n");
1118 lamexp_check_compatibility_mode("GetLargePageMinimum", executableName
);
1120 case QSysInfo::WV_2003
:
1121 qDebug("Running on Windows Server 2003 or Windows XP x64-Edition.\n");
1122 lamexp_check_compatibility_mode("GetLocaleInfoEx", executableName
);
1124 case QSysInfo::WV_VISTA
:
1125 qDebug("Running on Windows Vista or Windows Server 2008.\n");
1126 lamexp_check_compatibility_mode("CreateRemoteThreadEx", executableName
);
1128 case QSysInfo::WV_WINDOWS7
:
1129 qDebug("Running on Windows 7 or Windows Server 2008 R2.\n");
1130 lamexp_check_compatibility_mode("CreateFile2", executableName
);
1134 DWORD osVersionNo
= lamexp_get_os_version();
1135 if(LAMEXP_EQL_OS_VER(osVersionNo
, 6, 2))
1137 qDebug("Running on Windows 8 or Windows Server 2012\n");
1138 lamexp_check_compatibility_mode(NULL
, executableName
);
1142 qWarning("Running on an unknown/untested WinNT-based OS (v%u.%u).\n", HIWORD(osVersionNo
), LOWORD(osVersionNo
));
1149 if(lamexp_detect_wine())
1151 qWarning("It appears we are running under Wine, unexpected things might happen!\n");
1154 //Set text Codec for locale
1155 QTextCodec::setCodecForLocale(QTextCodec::codecForName("UTF-8"));
1157 //Create Qt application instance
1158 QApplication
*application
= new QApplication(argc
, argv
);
1160 //Load plugins from application directory
1161 QCoreApplication::setLibraryPaths(QStringList() << QApplication::applicationDirPath());
1162 qDebug("Library Path:\n%s\n", QApplication::libraryPaths().first().toUtf8().constData());
1164 //Set application properties
1165 application
->setApplicationName("LameXP - Audio Encoder Front-End");
1166 application
->setApplicationVersion(QString().sprintf("%d.%02d.%04d", lamexp_version_major(), lamexp_version_minor(), lamexp_version_build()));
1167 application
->setOrganizationName("LoRd_MuldeR");
1168 application
->setOrganizationDomain("mulder.at.gg");
1169 application
->setWindowIcon(lamexp_app_icon());
1170 application
->setEventFilter(lamexp_event_filter
);
1172 //Check for supported image formats
1173 QList
<QByteArray
> supportedFormats
= QImageReader::supportedImageFormats();
1174 for(int i
= 0; g_lamexp_imageformats
[i
]; i
++)
1176 if(!supportedFormats
.contains(g_lamexp_imageformats
[i
]))
1178 qFatal("Qt initialization error: QImageIOHandler for '%s' missing!", g_lamexp_imageformats
[i
]);
1183 //Add default translations
1184 QWriteLocker
writeLockTranslations(&g_lamexp_translation
.lock
);
1185 if(!g_lamexp_translation
.files
) g_lamexp_translation
.files
= new QMap
<QString
, QString
>();
1186 if(!g_lamexp_translation
.names
) g_lamexp_translation
.names
= new QMap
<QString
, QString
>();
1187 g_lamexp_translation
.files
->insert(LAMEXP_DEFAULT_LANGID
, "");
1188 g_lamexp_translation
.names
->insert(LAMEXP_DEFAULT_LANGID
, "English");
1189 writeLockTranslations
.unlock();
1191 //Check for process elevation
1192 if((!lamexp_check_elevation()) && (!lamexp_detect_wine()))
1194 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
);
1195 messageBox
.addButton("Quit Program (Recommended)", QMessageBox::NoRole
);
1196 messageBox
.addButton("Ignore", QMessageBox::NoRole
);
1197 if(messageBox
.exec() == 0)
1203 //Update console icon, if a console is attached
1204 #if QT_VERSION < QT_VERSION_CHECK(5,0,0)
1205 if(g_lamexp_console_attached
&& (!lamexp_detect_wine()))
1207 typedef DWORD (__stdcall
*SetConsoleIconFun
)(HICON
);
1208 QLibrary
kernel32("kernel32.dll");
1211 SetConsoleIconFun SetConsoleIconPtr
= (SetConsoleIconFun
) kernel32
.resolve("SetConsoleIcon");
1212 if(SetConsoleIconPtr
!= NULL
) SetConsoleIconPtr(QIcon(":/icons/sound.png").pixmap(16, 16).toWinHICON());
1219 qt_initialized
= true;
1226 int lamexp_init_ipc(void)
1228 QWriteLocker
writeLock(&g_lamexp_ipc_ptr
.lock
);
1230 if(g_lamexp_ipc_ptr
.sharedmem
&& g_lamexp_ipc_ptr
.semaphore_read
&& g_lamexp_ipc_ptr
.semaphore_write
&& g_lamexp_ipc_ptr
.semaphore_read_mutex
&& g_lamexp_ipc_ptr
.semaphore_write_mutex
)
1235 g_lamexp_ipc_ptr
.semaphore_read
= new QSystemSemaphore(QString(g_lamexp_ipc_uuid
.semaphore_read
), 0);
1236 g_lamexp_ipc_ptr
.semaphore_write
= new QSystemSemaphore(QString(g_lamexp_ipc_uuid
.semaphore_write
), 0);
1237 g_lamexp_ipc_ptr
.semaphore_read_mutex
= new QSystemSemaphore(QString(g_lamexp_ipc_uuid
.semaphore_read_mutex
), 0);
1238 g_lamexp_ipc_ptr
.semaphore_write_mutex
= new QSystemSemaphore(QString(g_lamexp_ipc_uuid
.semaphore_write_mutex
), 0);
1240 if(g_lamexp_ipc_ptr
.semaphore_read
->error() != QSystemSemaphore::NoError
)
1242 QString errorMessage
= g_lamexp_ipc_ptr
.semaphore_read
->errorString();
1243 LAMEXP_DELETE(g_lamexp_ipc_ptr
.semaphore_read
);
1244 LAMEXP_DELETE(g_lamexp_ipc_ptr
.semaphore_write
);
1245 LAMEXP_DELETE(g_lamexp_ipc_ptr
.semaphore_read_mutex
);
1246 LAMEXP_DELETE(g_lamexp_ipc_ptr
.semaphore_write_mutex
);
1247 qFatal("Failed to create system smaphore: %s", errorMessage
.toUtf8().constData());
1250 if(g_lamexp_ipc_ptr
.semaphore_write
->error() != QSystemSemaphore::NoError
)
1252 QString errorMessage
= g_lamexp_ipc_ptr
.semaphore_write
->errorString();
1253 LAMEXP_DELETE(g_lamexp_ipc_ptr
.semaphore_read
);
1254 LAMEXP_DELETE(g_lamexp_ipc_ptr
.semaphore_write
);
1255 LAMEXP_DELETE(g_lamexp_ipc_ptr
.semaphore_read_mutex
);
1256 LAMEXP_DELETE(g_lamexp_ipc_ptr
.semaphore_write_mutex
);
1257 qFatal("Failed to create system smaphore: %s", errorMessage
.toUtf8().constData());
1260 if(g_lamexp_ipc_ptr
.semaphore_read_mutex
->error() != QSystemSemaphore::NoError
)
1262 QString errorMessage
= g_lamexp_ipc_ptr
.semaphore_read_mutex
->errorString();
1263 LAMEXP_DELETE(g_lamexp_ipc_ptr
.semaphore_read
);
1264 LAMEXP_DELETE(g_lamexp_ipc_ptr
.semaphore_write
);
1265 LAMEXP_DELETE(g_lamexp_ipc_ptr
.semaphore_read_mutex
);
1266 LAMEXP_DELETE(g_lamexp_ipc_ptr
.semaphore_write_mutex
);
1267 qFatal("Failed to create system smaphore: %s", errorMessage
.toUtf8().constData());
1270 if(g_lamexp_ipc_ptr
.semaphore_write_mutex
->error() != QSystemSemaphore::NoError
)
1272 QString errorMessage
= g_lamexp_ipc_ptr
.semaphore_write_mutex
->errorString();
1273 LAMEXP_DELETE(g_lamexp_ipc_ptr
.semaphore_read
);
1274 LAMEXP_DELETE(g_lamexp_ipc_ptr
.semaphore_write
);
1275 LAMEXP_DELETE(g_lamexp_ipc_ptr
.semaphore_read_mutex
);
1276 LAMEXP_DELETE(g_lamexp_ipc_ptr
.semaphore_write_mutex
);
1277 qFatal("Failed to create system smaphore: %s", errorMessage
.toUtf8().constData());
1281 g_lamexp_ipc_ptr
.sharedmem
= new QSharedMemory(QString(g_lamexp_ipc_uuid
.sharedmem
), NULL
);
1283 if(!g_lamexp_ipc_ptr
.sharedmem
->create(sizeof(lamexp_ipc_t
)))
1285 if(g_lamexp_ipc_ptr
.sharedmem
->error() == QSharedMemory::AlreadyExists
)
1287 g_lamexp_ipc_ptr
.sharedmem
->attach();
1288 if(g_lamexp_ipc_ptr
.sharedmem
->error() == QSharedMemory::NoError
)
1294 QString errorMessage
= g_lamexp_ipc_ptr
.sharedmem
->errorString();
1295 LAMEXP_DELETE(g_lamexp_ipc_ptr
.sharedmem
);
1296 qFatal("Failed to attach to shared memory: %s", errorMessage
.toUtf8().constData());
1302 QString errorMessage
= g_lamexp_ipc_ptr
.sharedmem
->errorString();
1303 LAMEXP_DELETE(g_lamexp_ipc_ptr
.sharedmem
);
1304 qFatal("Failed to create shared memory: %s", errorMessage
.toUtf8().constData());
1309 memset(g_lamexp_ipc_ptr
.sharedmem
->data(), 0, sizeof(lamexp_ipc_t
));
1310 g_lamexp_ipc_ptr
.semaphore_write
->release(g_lamexp_ipc_slots
);
1311 g_lamexp_ipc_ptr
.semaphore_read_mutex
->release();
1312 g_lamexp_ipc_ptr
.semaphore_write_mutex
->release();
1320 void lamexp_ipc_send(unsigned int command
, const char* message
)
1322 QReadLocker
readLock(&g_lamexp_ipc_ptr
.lock
);
1324 if(!g_lamexp_ipc_ptr
.sharedmem
|| !g_lamexp_ipc_ptr
.semaphore_read
|| !g_lamexp_ipc_ptr
.semaphore_write
|| !g_lamexp_ipc_ptr
.semaphore_read_mutex
|| !g_lamexp_ipc_ptr
.semaphore_write_mutex
)
1326 throw "Shared memory for IPC not initialized yet.";
1329 lamexp_ipc_data_t ipc_data
;
1330 memset(&ipc_data
, 0, sizeof(lamexp_ipc_data_t
));
1331 ipc_data
.command
= command
;
1335 strncpy_s(ipc_data
.parameter
, 4096, message
, _TRUNCATE
);
1338 if(g_lamexp_ipc_ptr
.semaphore_write
->acquire())
1340 if(g_lamexp_ipc_ptr
.semaphore_write_mutex
->acquire())
1342 lamexp_ipc_t
*ptr
= reinterpret_cast<lamexp_ipc_t
*>(g_lamexp_ipc_ptr
.sharedmem
->data());
1343 memcpy(&ptr
->data
[ptr
->pos_write
], &ipc_data
, sizeof(lamexp_ipc_data_t
));
1344 ptr
->pos_write
= (ptr
->pos_write
+ 1) % g_lamexp_ipc_slots
;
1345 g_lamexp_ipc_ptr
.semaphore_read
->release();
1346 g_lamexp_ipc_ptr
.semaphore_write_mutex
->release();
1354 void lamexp_ipc_read(unsigned int *command
, char* message
, size_t buffSize
)
1356 QReadLocker
readLock(&g_lamexp_ipc_ptr
.lock
);
1361 if(!g_lamexp_ipc_ptr
.sharedmem
|| !g_lamexp_ipc_ptr
.semaphore_read
|| !g_lamexp_ipc_ptr
.semaphore_write
|| !g_lamexp_ipc_ptr
.semaphore_read_mutex
|| !g_lamexp_ipc_ptr
.semaphore_write_mutex
)
1363 throw "Shared memory for IPC not initialized yet.";
1366 lamexp_ipc_data_t ipc_data
;
1367 memset(&ipc_data
, 0, sizeof(lamexp_ipc_data_t
));
1369 if(g_lamexp_ipc_ptr
.semaphore_read
->acquire())
1371 if(g_lamexp_ipc_ptr
.semaphore_read_mutex
->acquire())
1373 lamexp_ipc_t
*ptr
= reinterpret_cast<lamexp_ipc_t
*>(g_lamexp_ipc_ptr
.sharedmem
->data());
1374 memcpy(&ipc_data
, &ptr
->data
[ptr
->pos_read
], sizeof(lamexp_ipc_data_t
));
1375 ptr
->pos_read
= (ptr
->pos_read
+ 1) % g_lamexp_ipc_slots
;
1376 g_lamexp_ipc_ptr
.semaphore_write
->release();
1377 g_lamexp_ipc_ptr
.semaphore_read_mutex
->release();
1379 if(!(ipc_data
.reserved_1
|| ipc_data
.reserved_2
))
1381 *command
= ipc_data
.command
;
1382 strncpy_s(message
, buffSize
, ipc_data
.parameter
, _TRUNCATE
);
1386 qWarning("Malformed IPC message, will be ignored");
1393 * Check for LameXP "portable" mode
1395 bool lamexp_portable_mode(void)
1397 QString baseName
= QFileInfo(QApplication::applicationFilePath()).completeBaseName();
1398 int idx1
= baseName
.indexOf("lamexp", 0, Qt::CaseInsensitive
);
1399 int idx2
= baseName
.lastIndexOf("portable", -1, Qt::CaseInsensitive
);
1400 return (idx1
>= 0) && (idx2
>= 0) && (idx1
< idx2
);
1404 * Get a random string
1406 QString
lamexp_rand_str(void)
1408 QRegExp
regExp("\\{(\\w+)-(\\w+)-(\\w+)-(\\w+)-(\\w+)\\}");
1409 QString uuid
= QUuid::createUuid().toString();
1411 if(regExp
.indexIn(uuid
) >= 0)
1413 return QString().append(regExp
.cap(1)).append(regExp
.cap(2)).append(regExp
.cap(3)).append(regExp
.cap(4)).append(regExp
.cap(5));
1416 throw "The RegExp didn't match on the UUID string. This shouldn't happen ;-)";
1420 * Get LameXP temp folder
1422 const QString
&lamexp_temp_folder2(void)
1424 QReadLocker
readLock(&g_lamexp_folder
.lock
);
1426 //Already initialized?
1427 if(g_lamexp_folder
.temp
)
1429 if(!g_lamexp_folder
.temp
->isEmpty())
1431 if(QDir(*g_lamexp_folder
.temp
).exists())
1433 return *g_lamexp_folder
.temp
;
1439 QWriteLocker
writeLock(&g_lamexp_folder
.lock
);
1441 if(!g_lamexp_folder
.temp
)
1443 g_lamexp_folder
.temp
= new QString();
1446 g_lamexp_folder
.temp
->clear();
1448 static const char *TEMP_STR
= "Temp";
1449 const QString WRITE_TEST_DATA
= lamexp_rand_str();
1450 const QString SUB_FOLDER
= lamexp_rand_str();
1452 //Try the %TMP% or %TEMP% directory first
1453 QDir temp
= QDir::temp();
1456 temp
.mkdir(SUB_FOLDER
);
1457 if(temp
.cd(SUB_FOLDER
) && temp
.exists())
1459 QFile
testFile(QString("%1/~%2.tmp").arg(temp
.canonicalPath(), lamexp_rand_str()));
1460 if(testFile
.open(QIODevice::ReadWrite
))
1462 if(testFile
.write(WRITE_TEST_DATA
.toLatin1().constData()) >= strlen(WRITE_TEST_DATA
.toLatin1().constData()))
1464 (*g_lamexp_folder
.temp
) = temp
.canonicalPath();
1469 if(!g_lamexp_folder
.temp
->isEmpty())
1471 return *g_lamexp_folder
.temp
;
1475 //Create TEMP folder in %LOCALAPPDATA%
1476 QDir localAppData
= QDir(lamexp_known_folder(lamexp_folder_localappdata
));
1477 if(!localAppData
.path().isEmpty())
1479 if(!localAppData
.exists())
1481 localAppData
.mkpath(".");
1483 if(localAppData
.exists())
1485 if(!localAppData
.entryList(QDir::AllDirs
).contains(TEMP_STR
, Qt::CaseInsensitive
))
1487 localAppData
.mkdir(TEMP_STR
);
1489 if(localAppData
.cd(TEMP_STR
) && localAppData
.exists())
1491 localAppData
.mkdir(SUB_FOLDER
);
1492 if(localAppData
.cd(SUB_FOLDER
) && localAppData
.exists())
1494 QFile
testFile(QString("%1/~%2.tmp").arg(localAppData
.canonicalPath(), lamexp_rand_str()));
1495 if(testFile
.open(QIODevice::ReadWrite
))
1497 if(testFile
.write(WRITE_TEST_DATA
.toLatin1().constData()) >= strlen(WRITE_TEST_DATA
.toLatin1().constData()))
1499 (*g_lamexp_folder
.temp
) = localAppData
.canonicalPath();
1506 if(!g_lamexp_folder
.temp
->isEmpty())
1508 return *g_lamexp_folder
.temp
;
1512 //Failed to create TEMP folder!
1513 qFatal("Temporary directory could not be initialized!\n\nFirst attempt:\n%s\n\nSecond attempt:\n%s", temp
.canonicalPath().toUtf8().constData(), localAppData
.canonicalPath().toUtf8().constData());
1514 return *g_lamexp_folder
.temp
;
1520 bool lamexp_clean_folder(const QString
&folderPath
)
1522 QDir
tempFolder(folderPath
);
1523 QFileInfoList entryList
= tempFolder
.entryInfoList(QDir::AllEntries
| QDir::NoDotAndDotDot
);
1525 for(int i
= 0; i
< entryList
.count(); i
++)
1527 if(entryList
.at(i
).isDir())
1529 lamexp_clean_folder(entryList
.at(i
).canonicalFilePath());
1533 for(int j
= 0; j
< 3; j
++)
1535 if(lamexp_remove_file(entryList
.at(i
).canonicalFilePath()))
1543 tempFolder
.rmdir(".");
1544 return !tempFolder
.exists();
1550 void lamexp_register_tool(const QString
&toolName
, LockedFile
*file
, unsigned int version
)
1552 QWriteLocker
writeLock(&g_lamexp_tools
.lock
);
1554 if(!g_lamexp_tools
.registry
) g_lamexp_tools
.registry
= new QMap
<QString
, LockedFile
*>();
1555 if(!g_lamexp_tools
.versions
) g_lamexp_tools
.versions
= new QMap
<QString
, unsigned int>();
1557 if(g_lamexp_tools
.registry
->contains(toolName
.toLower()))
1559 throw "lamexp_register_tool: Tool is already registered!";
1562 g_lamexp_tools
.registry
->insert(toolName
.toLower(), file
);
1563 g_lamexp_tools
.versions
->insert(toolName
.toLower(), version
);
1569 bool lamexp_check_tool(const QString
&toolName
)
1571 QReadLocker
readLock(&g_lamexp_tools
.lock
);
1572 return (g_lamexp_tools
.registry
) ? g_lamexp_tools
.registry
->contains(toolName
.toLower()) : false;
1578 const QString
lamexp_lookup_tool(const QString
&toolName
)
1580 QReadLocker
readLock(&g_lamexp_tools
.lock
);
1582 if(g_lamexp_tools
.registry
)
1584 if(g_lamexp_tools
.registry
->contains(toolName
.toLower()))
1586 return g_lamexp_tools
.registry
->value(toolName
.toLower())->filePath();
1600 * Lookup tool version
1602 unsigned int lamexp_tool_version(const QString
&toolName
)
1604 QReadLocker
readLock(&g_lamexp_tools
.lock
);
1606 if(g_lamexp_tools
.versions
)
1608 if(g_lamexp_tools
.versions
->contains(toolName
.toLower()))
1610 return g_lamexp_tools
.versions
->value(toolName
.toLower());
1624 * Version number to human-readable string
1626 const QString
lamexp_version2string(const QString
&pattern
, unsigned int version
, const QString
&defaultText
)
1628 if(version
== UINT_MAX
)
1633 QString result
= pattern
;
1634 int digits
= result
.count("?", Qt::CaseInsensitive
);
1642 QString versionStr
= QString().sprintf(QString().sprintf("%%0%du", digits
).toLatin1().constData(), version
);
1643 int index
= result
.indexOf("?", Qt::CaseInsensitive
);
1645 while(index
>= 0 && pos
< versionStr
.length())
1647 result
[index
] = versionStr
[pos
++];
1648 index
= result
.indexOf("?", Qt::CaseInsensitive
);
1655 * Register a new translation
1657 bool lamexp_translation_register(const QString
&langId
, const QString
&qmFile
, const QString
&langName
, unsigned int &systemId
, unsigned int &country
)
1659 QWriteLocker
writeLockTranslations(&g_lamexp_translation
.lock
);
1661 if(qmFile
.isEmpty() || langName
.isEmpty() || systemId
< 1)
1666 if(!g_lamexp_translation
.files
) g_lamexp_translation
.files
= new QMap
<QString
, QString
>();
1667 if(!g_lamexp_translation
.names
) g_lamexp_translation
.names
= new QMap
<QString
, QString
>();
1668 if(!g_lamexp_translation
.sysid
) g_lamexp_translation
.sysid
= new QMap
<QString
, unsigned int>();
1669 if(!g_lamexp_translation
.cntry
) g_lamexp_translation
.cntry
= new QMap
<QString
, unsigned int>();
1671 g_lamexp_translation
.files
->insert(langId
, qmFile
);
1672 g_lamexp_translation
.names
->insert(langId
, langName
);
1673 g_lamexp_translation
.sysid
->insert(langId
, systemId
);
1674 g_lamexp_translation
.cntry
->insert(langId
, country
);
1680 * Get list of all translations
1682 QStringList
lamexp_query_translations(void)
1684 QReadLocker
readLockTranslations(&g_lamexp_translation
.lock
);
1685 return (g_lamexp_translation
.files
) ? g_lamexp_translation
.files
->keys() : QStringList();
1689 * Get translation name
1691 QString
lamexp_translation_name(const QString
&langId
)
1693 QReadLocker
readLockTranslations(&g_lamexp_translation
.lock
);
1694 return (g_lamexp_translation
.names
) ? g_lamexp_translation
.names
->value(langId
.toLower(), QString()) : QString();
1698 * Get translation system id
1700 unsigned int lamexp_translation_sysid(const QString
&langId
)
1702 QReadLocker
readLockTranslations(&g_lamexp_translation
.lock
);
1703 return (g_lamexp_translation
.sysid
) ? g_lamexp_translation
.sysid
->value(langId
.toLower(), 0) : 0;
1707 * Get translation script id
1709 unsigned int lamexp_translation_country(const QString
&langId
)
1711 QReadLocker
readLockTranslations(&g_lamexp_translation
.lock
);
1712 return (g_lamexp_translation
.cntry
) ? g_lamexp_translation
.cntry
->value(langId
.toLower(), 0) : 0;
1716 * Install a new translator
1718 bool lamexp_install_translator(const QString
&langId
)
1720 bool success
= false;
1722 if(langId
.isEmpty() || langId
.toLower().compare(LAMEXP_DEFAULT_LANGID
) == 0)
1724 success
= lamexp_install_translator_from_file(QString());
1728 QReadLocker
readLock(&g_lamexp_translation
.lock
);
1729 QString qmFile
= (g_lamexp_translation
.files
) ? g_lamexp_translation
.files
->value(langId
.toLower(), QString()) : QString();
1732 if(!qmFile
.isEmpty())
1734 success
= lamexp_install_translator_from_file(QString(":/localization/%1").arg(qmFile
));
1738 qWarning("Translation '%s' not available!", langId
.toLatin1().constData());
1746 * Install a new translator from file
1748 bool lamexp_install_translator_from_file(const QString
&qmFile
)
1750 QWriteLocker
writeLock(&g_lamexp_currentTranslator
.lock
);
1751 bool success
= false;
1753 if(!g_lamexp_currentTranslator
.instance
)
1755 g_lamexp_currentTranslator
.instance
= new QTranslator();
1758 if(!qmFile
.isEmpty())
1760 QString qmPath
= QFileInfo(qmFile
).canonicalFilePath();
1761 QApplication::removeTranslator(g_lamexp_currentTranslator
.instance
);
1762 if(success
= g_lamexp_currentTranslator
.instance
->load(qmPath
))
1764 QApplication::installTranslator(g_lamexp_currentTranslator
.instance
);
1768 qWarning("Failed to load translation:\n\"%s\"", qmPath
.toLatin1().constData());
1773 QApplication::removeTranslator(g_lamexp_currentTranslator
.instance
);
1780 const QStringList
&lamexp_arguments(void)
1782 QReadLocker
readLock(&g_lamexp_argv
.lock
);
1784 if(!g_lamexp_argv
.list
)
1787 QWriteLocker
writeLock(&g_lamexp_argv
.lock
);
1789 g_lamexp_argv
.list
= new QStringList
;
1792 LPWSTR
*szArglist
= CommandLineToArgvW(GetCommandLineW(), &nArgs
);
1794 if(NULL
!= szArglist
)
1796 for(int i
= 0; i
< nArgs
; i
++)
1798 (*g_lamexp_argv
.list
) << WCHAR2QSTR(szArglist
[i
]);
1800 LocalFree(szArglist
);
1804 qWarning("CommandLineToArgvW() has failed !!!");
1808 return (*g_lamexp_argv
.list
);
1812 * Locate known folder on local system
1814 const QString
&lamexp_known_folder(lamexp_known_folder_t folder_id
)
1816 typedef HRESULT (WINAPI
*SHGetKnownFolderPathFun
)(__in
const GUID
&rfid
, __in DWORD dwFlags
, __in HANDLE hToken
, __out PWSTR
*ppszPath
);
1817 typedef HRESULT (WINAPI
*SHGetFolderPathFun
)(__in HWND hwndOwner
, __in
int nFolder
, __in HANDLE hToken
, __in DWORD dwFlags
, __out LPWSTR pszPath
);
1819 static const int CSIDL_LOCAL_APPDATA
= 0x001c;
1820 static const int CSIDL_PROGRAM_FILES
= 0x0026;
1821 static const int CSIDL_SYSTEM_FOLDER
= 0x0025;
1822 static const GUID GUID_LOCAL_APPDATA
= {0xF1B32785,0x6FBA,0x4FCF,{0x9D,0x55,0x7B,0x8E,0x7F,0x15,0x70,0x91}};
1823 static const GUID GUID_LOCAL_APPDATA_LOW
= {0xA520A1A4,0x1780,0x4FF6,{0xBD,0x18,0x16,0x73,0x43,0xC5,0xAF,0x16}};
1824 static const GUID GUID_PROGRAM_FILES
= {0x905e63b6,0xc1bf,0x494e,{0xb2,0x9c,0x65,0xb7,0x32,0xd3,0xd2,0x1a}};
1825 static const GUID GUID_SYSTEM_FOLDER
= {0x1AC14E77,0x02E7,0x4E5D,{0xB7,0x44,0x2E,0xB1,0xAE,0x51,0x98,0xB7}};
1827 QReadLocker
readLock(&g_lamexp_folder
.lock
);
1829 int folderCSIDL
= -1;
1830 GUID folderGUID
= {0x0000,0x0000,0x0000,{0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00}};
1831 size_t folderCacheId
= size_t(-1);
1835 case lamexp_folder_localappdata
:
1837 folderCSIDL
= CSIDL_LOCAL_APPDATA
;
1838 folderGUID
= GUID_LOCAL_APPDATA
;
1840 case lamexp_folder_programfiles
:
1842 folderCSIDL
= CSIDL_PROGRAM_FILES
;
1843 folderGUID
= GUID_PROGRAM_FILES
;
1845 case lamexp_folder_systemfolder
:
1847 folderCSIDL
= CSIDL_SYSTEM_FOLDER
;
1848 folderGUID
= GUID_SYSTEM_FOLDER
;
1851 qWarning("Invalid 'known' folder was requested!");
1852 return *reinterpret_cast<QString
*>(NULL
);
1857 if(g_lamexp_folder
.knownFolders
)
1859 if(g_lamexp_folder
.knownFolders
->contains(folderCacheId
))
1861 return (*g_lamexp_folder
.knownFolders
)[folderCacheId
];
1866 QWriteLocker
writeLock(&g_lamexp_folder
.lock
);
1868 static SHGetKnownFolderPathFun SHGetKnownFolderPathPtr
= NULL
;
1869 static SHGetFolderPathFun SHGetFolderPathPtr
= NULL
;
1871 if((!SHGetKnownFolderPathPtr
) && (!SHGetFolderPathPtr
))
1873 QLibrary
kernel32Lib("shell32.dll");
1874 if(kernel32Lib
.load())
1876 SHGetKnownFolderPathPtr
= (SHGetKnownFolderPathFun
) kernel32Lib
.resolve("SHGetKnownFolderPath");
1877 SHGetFolderPathPtr
= (SHGetFolderPathFun
) kernel32Lib
.resolve("SHGetFolderPathW");
1883 if(SHGetKnownFolderPathPtr
)
1886 if(SHGetKnownFolderPathPtr(folderGUID
, 0x00008000, NULL
, &path
) == S_OK
)
1888 //MessageBoxW(0, path, L"SHGetKnownFolderPath", MB_TOPMOST);
1889 QDir folderTemp
= QDir(QDir::fromNativeSeparators(QString::fromUtf16(reinterpret_cast<const unsigned short*>(path
))));
1890 if(!folderTemp
.exists())
1892 folderTemp
.mkpath(".");
1894 if(folderTemp
.exists())
1896 folder
= folderTemp
.canonicalPath();
1898 CoTaskMemFree(path
);
1901 else if(SHGetFolderPathPtr
)
1903 WCHAR
*path
= new WCHAR
[4096];
1904 if(SHGetFolderPathPtr(NULL
, folderCSIDL
, NULL
, NULL
, path
) == S_OK
)
1906 //MessageBoxW(0, path, L"SHGetFolderPathW", MB_TOPMOST);
1907 QDir folderTemp
= QDir(QDir::fromNativeSeparators(QString::fromUtf16(reinterpret_cast<const unsigned short*>(path
))));
1908 if(!folderTemp
.exists())
1910 folderTemp
.mkpath(".");
1912 if(folderTemp
.exists())
1914 folder
= folderTemp
.canonicalPath();
1921 if(!g_lamexp_folder
.knownFolders
)
1923 g_lamexp_folder
.knownFolders
= new QMap
<size_t, QString
>();
1927 g_lamexp_folder
.knownFolders
->insert(folderCacheId
, folder
);
1928 return (*g_lamexp_folder
.knownFolders
)[folderCacheId
];
1932 * Safely remove a file
1934 bool lamexp_remove_file(const QString
&filename
)
1936 if(!QFileInfo(filename
).exists() || !QFileInfo(filename
).isFile())
1942 if(!QFile::remove(filename
))
1944 DWORD attributes
= GetFileAttributesW(QWCHAR(filename
));
1945 SetFileAttributesW(QWCHAR(filename
), (attributes
& (~FILE_ATTRIBUTE_READONLY
)));
1946 if(!QFile::remove(filename
))
1948 qWarning("Could not delete \"%s\"", filename
.toLatin1().constData());
1964 * Check if visual themes are enabled (WinXP and later)
1966 bool lamexp_themes_enabled(void)
1968 typedef int (WINAPI
*IsAppThemedFun
)(void);
1970 static bool isAppThemed
= false;
1971 static bool isAppThemed_initialized
= false;
1973 if(!isAppThemed_initialized
)
1975 IsAppThemedFun IsAppThemedPtr
= NULL
;
1976 QLibrary
uxTheme(QString("%1/UxTheme.dll").arg(lamexp_known_folder(lamexp_folder_systemfolder
)));
1979 IsAppThemedPtr
= (IsAppThemedFun
) uxTheme
.resolve("IsAppThemed");
1983 isAppThemed
= IsAppThemedPtr();
1986 qWarning("Theme support is disabled for this process!");
1989 isAppThemed_initialized
= true;
1996 * Get number of free bytes on disk
1998 unsigned __int64
lamexp_free_diskspace(const QString
&path
, bool *ok
)
2000 ULARGE_INTEGER freeBytesAvailable
, totalNumberOfBytes
, totalNumberOfFreeBytes
;
2001 if(GetDiskFreeSpaceExW(reinterpret_cast<const wchar_t*>(QDir::toNativeSeparators(path
).utf16()), &freeBytesAvailable
, &totalNumberOfBytes
, &totalNumberOfFreeBytes
))
2004 return freeBytesAvailable
.QuadPart
;
2014 * Check if computer does support hibernation
2016 bool lamexp_is_hibernation_supported(void)
2018 bool hibernationSupported
= false;
2020 SYSTEM_POWER_CAPABILITIES pwrCaps
;
2021 SecureZeroMemory(&pwrCaps
, sizeof(SYSTEM_POWER_CAPABILITIES
));
2023 if(GetPwrCapabilities(&pwrCaps
))
2025 hibernationSupported
= pwrCaps
.SystemS4
&& pwrCaps
.HiberFilePresent
;
2028 return hibernationSupported
;
2032 * Shutdown the computer
2034 bool lamexp_shutdown_computer(const QString
&message
, const unsigned long timeout
, const bool forceShutdown
, const bool hibernate
)
2036 HANDLE hToken
= NULL
;
2038 if(OpenProcessToken(GetCurrentProcess(), TOKEN_ADJUST_PRIVILEGES
| TOKEN_QUERY
, &hToken
))
2040 TOKEN_PRIVILEGES privileges
;
2041 memset(&privileges
, 0, sizeof(TOKEN_PRIVILEGES
));
2042 privileges
.PrivilegeCount
= 1;
2043 privileges
.Privileges
[0].Attributes
= SE_PRIVILEGE_ENABLED
;
2045 if(LookupPrivilegeValue(NULL
, SE_SHUTDOWN_NAME
, &privileges
.Privileges
[0].Luid
))
2047 if(AdjustTokenPrivileges(hToken
, FALSE
, &privileges
, NULL
, NULL
, NULL
))
2051 if(SetSuspendState(TRUE
, TRUE
, TRUE
))
2056 const DWORD reason
= SHTDN_REASON_MAJOR_APPLICATION
| SHTDN_REASON_FLAG_PLANNED
;
2057 return InitiateSystemShutdownEx(NULL
, const_cast<wchar_t*>(QWCHAR(message
)), timeout
, forceShutdown
? TRUE
: FALSE
, FALSE
, reason
);
2066 * Make a window blink (to draw user's attention)
2068 void lamexp_blink_window(QWidget
*poWindow
, unsigned int count
, unsigned int delay
)
2070 static QMutex blinkMutex
;
2072 const double maxOpac
= 1.0;
2073 const double minOpac
= 0.3;
2074 const double delOpac
= 0.1;
2076 if(!blinkMutex
.tryLock())
2078 qWarning("Blinking is already in progress, skipping!");
2084 const int steps
= static_cast<int>(ceil(maxOpac
- minOpac
) / delOpac
);
2085 const int sleep
= static_cast<int>(floor(static_cast<double>(delay
) / static_cast<double>(steps
)));
2086 const double opacity
= poWindow
->windowOpacity();
2088 for(unsigned int i
= 0; i
< count
; i
++)
2090 for(double x
= maxOpac
; x
>= minOpac
; x
-= delOpac
)
2092 poWindow
->setWindowOpacity(x
);
2093 QApplication::processEvents();
2097 for(double x
= minOpac
; x
<= maxOpac
; x
+= delOpac
)
2099 poWindow
->setWindowOpacity(x
);
2100 QApplication::processEvents();
2105 poWindow
->setWindowOpacity(opacity
);
2106 QApplication::processEvents();
2107 blinkMutex
.unlock();
2111 blinkMutex
.unlock();
2112 qWarning("Exception error while blinking!");
2117 * Remove forbidden characters from a filename
2119 const QString
lamexp_clean_filename(const QString
&str
)
2121 QString
newStr(str
);
2123 newStr
.replace("\\", "-");
2124 newStr
.replace(" / ", ", ");
2125 newStr
.replace("/", ",");
2126 newStr
.replace(":", "-");
2127 newStr
.replace("*", "x");
2128 newStr
.replace("?", "");
2129 newStr
.replace("<", "[");
2130 newStr
.replace(">", "]");
2131 newStr
.replace("|", "!");
2133 return newStr
.simplified();
2137 * Remove forbidden characters from a file path
2139 const QString
lamexp_clean_filepath(const QString
&str
)
2141 QStringList parts
= QString(str
).replace("\\", "/").split("/");
2143 for(int i
= 0; i
< parts
.count(); i
++)
2145 parts
[i
] = lamexp_clean_filename(parts
[i
]);
2148 return parts
.join("/");
2152 * Get a list of all available Qt Text Codecs
2154 QStringList
lamexp_available_codepages(bool noAliases
)
2156 QStringList codecList
;
2158 QList
<QByteArray
> availableCodecs
= QTextCodec::availableCodecs();
2159 while(!availableCodecs
.isEmpty())
2161 QByteArray current
= availableCodecs
.takeFirst();
2162 if(!(current
.startsWith("system") || current
.startsWith("System")))
2164 codecList
<< QString::fromLatin1(current
.constData(), current
.size());
2167 if(QTextCodec
*currentCodec
= QTextCodec::codecForName(current
.constData()))
2170 QList
<QByteArray
> aliases
= currentCodec
->aliases();
2171 while(!aliases
.isEmpty()) availableCodecs
.removeAll(aliases
.takeFirst());
2181 * Entry point checks
2183 static DWORD
lamexp_entry_check(void);
2184 static DWORD g_lamexp_entry_check_result
= lamexp_entry_check();
2185 static DWORD g_lamexp_entry_check_flag
= 0x789E09B2;
2186 static DWORD
lamexp_entry_check(void)
2188 volatile DWORD retVal
= 0xA199B5AF;
2189 if(g_lamexp_entry_check_flag
!= 0x8761F64D)
2191 FatalAppExit(0, L
"Application initialization has failed, take care!");
2192 TerminateProcess(GetCurrentProcess(), -1);
2198 * Application entry point (runs before static initializers)
2202 int WinMainCRTStartup(void);
2204 int lamexp_entry_point(void)
2206 if((!LAMEXP_DEBUG
) && lamexp_check_for_debugger())
2208 FatalAppExit(0, L
"Not a debug build. Please unload debugger and try again!");
2209 TerminateProcess(GetCurrentProcess(), -1);
2212 if(g_lamexp_entry_check_flag
!= 0x789E09B2)
2214 FatalAppExit(0, L
"Application initialization has failed, take care!");
2215 TerminateProcess(GetCurrentProcess(), -1);
2218 //Zero *before* constructors are called
2219 LAMEXP_ZERO_MEMORY(g_lamexp_argv
);
2220 LAMEXP_ZERO_MEMORY(g_lamexp_tools
);
2221 LAMEXP_ZERO_MEMORY(g_lamexp_currentTranslator
);
2222 LAMEXP_ZERO_MEMORY(g_lamexp_translation
);
2223 LAMEXP_ZERO_MEMORY(g_lamexp_folder
);
2224 LAMEXP_ZERO_MEMORY(g_lamexp_ipc_ptr
);
2226 //Make sure we will pass the check
2227 g_lamexp_entry_check_flag
= ~g_lamexp_entry_check_flag
;
2229 //Now initialize the C Runtime library!
2230 return WinMainCRTStartup();
2235 * Finalization function (final clean-up)
2237 void lamexp_finalization(void)
2239 qDebug("lamexp_finalization()");
2242 if(g_lamexp_tools
.registry
)
2244 QStringList keys
= g_lamexp_tools
.registry
->keys();
2245 for(int i
= 0; i
< keys
.count(); i
++)
2247 LAMEXP_DELETE((*g_lamexp_tools
.registry
)[keys
.at(i
)]);
2249 LAMEXP_DELETE(g_lamexp_tools
.registry
);
2250 LAMEXP_DELETE(g_lamexp_tools
.versions
);
2253 //Delete temporary files
2254 if(g_lamexp_folder
.temp
)
2256 if(!g_lamexp_folder
.temp
->isEmpty())
2258 for(int i
= 0; i
< 100; i
++)
2260 if(lamexp_clean_folder(*g_lamexp_folder
.temp
))
2267 LAMEXP_DELETE(g_lamexp_folder
.temp
);
2270 //Clear folder cache
2271 LAMEXP_DELETE(g_lamexp_folder
.knownFolders
);
2274 if(g_lamexp_currentTranslator
.instance
)
2276 QApplication::removeTranslator(g_lamexp_currentTranslator
.instance
);
2277 LAMEXP_DELETE(g_lamexp_currentTranslator
.instance
);
2279 LAMEXP_DELETE(g_lamexp_translation
.files
);
2280 LAMEXP_DELETE(g_lamexp_translation
.names
);
2281 LAMEXP_DELETE(g_lamexp_translation
.cntry
);
2282 LAMEXP_DELETE(g_lamexp_translation
.sysid
);
2284 //Destroy Qt application object
2285 QApplication
*application
= dynamic_cast<QApplication
*>(QApplication::instance());
2286 LAMEXP_DELETE(application
);
2288 //Detach from shared memory
2289 if(g_lamexp_ipc_ptr
.sharedmem
) g_lamexp_ipc_ptr
.sharedmem
->detach();
2290 LAMEXP_DELETE(g_lamexp_ipc_ptr
.sharedmem
);
2291 LAMEXP_DELETE(g_lamexp_ipc_ptr
.semaphore_read
);
2292 LAMEXP_DELETE(g_lamexp_ipc_ptr
.semaphore_write
);
2293 LAMEXP_DELETE(g_lamexp_ipc_ptr
.semaphore_read_mutex
);
2294 LAMEXP_DELETE(g_lamexp_ipc_ptr
.semaphore_write_mutex
);
2296 //Free STDOUT and STDERR buffers
2297 if(g_lamexp_console_attached
)
2299 if(std::filebuf
*tmp
= dynamic_cast<std::filebuf
*>(std::cout
.rdbuf()))
2301 std::cout
.rdbuf(NULL
);
2304 if(std::filebuf
*tmp
= dynamic_cast<std::filebuf
*>(std::cerr
.rdbuf()))
2306 std::cerr
.rdbuf(NULL
);
2312 if(g_lamexp_log_file
)
2314 fclose(g_lamexp_log_file
);
2315 g_lamexp_log_file
= NULL
;
2318 //Free CLI Arguments
2319 LAMEXP_DELETE(g_lamexp_argv
.list
);
2323 * Initialize debug thread
2325 static const HANDLE g_debug_thread
= LAMEXP_DEBUG
? NULL
: lamexp_debug_thread_init();
2328 * Get number private bytes [debug only]
2330 SIZE_T
lamexp_dbg_private_bytes(void)
2333 PROCESS_MEMORY_COUNTERS_EX memoryCounters
;
2334 memoryCounters
.cb
= sizeof(PROCESS_MEMORY_COUNTERS_EX
);
2335 GetProcessMemoryInfo(GetCurrentProcess(), (PPROCESS_MEMORY_COUNTERS
) &memoryCounters
, sizeof(PROCESS_MEMORY_COUNTERS_EX
));
2336 return memoryCounters
.PrivateUsage
;
2338 throw "Cannot call this function in a non-debug build!";
2339 #endif //LAMEXP_DEBUG