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"
75 //Initialize static Qt plugins
77 #if QT_VERSION < QT_VERSION_CHECK(5,0,0)
81 Q_IMPORT_PLUGIN(QWindowsIntegrationPlugin
)
82 Q_IMPORT_PLUGIN(QICOPlugin
)
86 ///////////////////////////////////////////////////////////////////////////////
88 ///////////////////////////////////////////////////////////////////////////////
90 static const size_t g_lamexp_ipc_slots
= 128;
95 unsigned int reserved_1
;
96 unsigned int reserved_2
;
103 unsigned int pos_write
;
104 unsigned int pos_read
;
105 lamexp_ipc_data_t data
[g_lamexp_ipc_slots
];
109 ///////////////////////////////////////////////////////////////////////////////
111 ///////////////////////////////////////////////////////////////////////////////
116 unsigned int ver_major
;
117 unsigned int ver_minor
;
118 unsigned int ver_build
;
119 char *ver_release_name
;
130 static QDate g_lamexp_version_date
;
131 static const char *g_lamexp_months
[] = {"Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"};
132 static const char *g_lamexp_version_raw_date
= __DATE__
;
133 static const char *g_lamexp_version_raw_time
= __TIME__
;
135 //Console attached flag
136 static bool g_lamexp_console_attached
= false;
139 //The following code was borrowed from MPC-HC project: http://mpc-hc.sf.net/
140 #if defined(__INTEL_COMPILER)
141 #if (__INTEL_COMPILER >= 1200)
142 static const char *g_lamexp_version_compiler
= "ICL 12.x";
143 #elif (__INTEL_COMPILER >= 1100)
144 static const char *g_lamexp_version_compiler
= "ICL 11.x";
145 #elif (__INTEL_COMPILER >= 1000)
146 static const char *g_lamexp_version_compiler
= "ICL 10.x";
148 #error Compiler is not supported!
150 #elif defined(_MSC_VER)
151 #if (_MSC_VER == 1600)
152 #if (_MSC_FULL_VER >= 160040219)
153 static const char *g_lamexp_version_compiler
= "MSVC 2010-SP1";
155 static const char *g_lamexp_version_compiler
= "MSVC 2010";
157 #elif (_MSC_VER == 1500)
158 #if (_MSC_FULL_VER >= 150030729)
159 static const char *g_lamexp_version_compiler
= "MSVC 2008-SP1";
161 static const char *g_lamexp_version_compiler
= "MSVC 2008";
164 #error Compiler is not supported!
167 // Note: /arch:SSE and /arch:SSE2 are only available for the x86 platform
168 #if !defined(_M_X64) && defined(_M_IX86_FP)
169 #if (_M_IX86_FP == 1)
170 LAMEXP_COMPILER_WARNING("SSE instruction set is enabled!")
171 #elif (_M_IX86_FP == 2)
172 LAMEXP_COMPILER_WARNING("SSE2 instruction set is enabled!")
176 #error Compiler is not supported!
179 //Architecture detection
181 static const char *g_lamexp_version_arch
= "x64";
182 #elif defined(_M_IX86)
183 static const char *g_lamexp_version_arch
= "x86";
185 #error Architecture is not supported!
188 //Official web-site URL
189 static const char *g_lamexp_website_url
= "http://lamexp.sourceforge.net/";
190 static const char *g_lamexp_support_url
= "http://forum.doom9.org/showthread.php?t=157726";
192 //Tool versions (expected versions!)
193 static const unsigned int g_lamexp_toolver_neroaac
= VER_LAMEXP_TOOL_NEROAAC
;
194 static const unsigned int g_lamexp_toolver_fhgaacenc
= VER_LAMEXP_TOOL_FHGAACENC
;
195 static const unsigned int g_lamexp_toolver_qaacenc
= VER_LAMEXP_TOOL_QAAC
;
196 static const unsigned int g_lamexp_toolver_coreaudio
= VER_LAMEXP_TOOL_COREAUDIO
;
199 static QString g_lamexp_temp_folder
;
202 static QMap
<QString
, LockedFile
*> g_lamexp_tool_registry
;
203 static QMap
<QString
, unsigned int> g_lamexp_tool_versions
;
204 static QReadWriteLock g_lamexp_tool_lock
;
209 QMap
<QString
, QString
> files
;
210 QMap
<QString
, QString
> names
;
211 QMap
<QString
, unsigned int> sysid
;
212 QMap
<QString
, unsigned int> cntry
;
214 g_lamexp_translation
;
217 static QTranslator
*g_lamexp_currentTranslator
= NULL
;
223 char *semaphore_read
;
224 char *semaphore_read_mutex
;
225 char *semaphore_write
;
226 char *semaphore_write_mutex
;
230 "{21A68A42-6923-43bb-9CF6-64BF151942EE}",
231 "{7A605549-F58C-4d78-B4E5-06EFC34F405B}",
232 "{60AA8D04-F6B8-497d-81EB-0F600F4A65B5}",
233 "{726061D5-1615-4B82-871C-75FD93458E46}",
234 "{1A616023-AA6A-4519-8AF3-F7736E899977}"
238 QSharedMemory
*sharedmem
;
239 QSystemSemaphore
*semaphore_read
;
240 QSystemSemaphore
*semaphore_read_mutex
;
241 QSystemSemaphore
*semaphore_write
;
242 QSystemSemaphore
*semaphore_write_mutex
;
250 static const char *g_lamexp_imageformats
[] = {"bmp", "png", "jpg", "gif", "ico", "xpm", NULL
}; //"svg"
253 static QMutex g_lamexp_message_mutex
;
256 static const DWORD g_main_thread_id
= GetCurrentThreadId();
259 static FILE *g_lamexp_log_file
= NULL
;
261 ///////////////////////////////////////////////////////////////////////////////
263 ///////////////////////////////////////////////////////////////////////////////
268 unsigned int lamexp_version_major(void) { return g_lamexp_version
.ver_major
; }
269 unsigned int lamexp_version_minor(void) { return g_lamexp_version
.ver_minor
; }
270 unsigned int lamexp_version_build(void) { return g_lamexp_version
.ver_build
; }
271 const char *lamexp_version_release(void) { return g_lamexp_version
.ver_release_name
; }
272 const char *lamexp_version_time(void) { return g_lamexp_version_raw_time
; }
273 const char *lamexp_version_compiler(void) { return g_lamexp_version_compiler
; }
274 const char *lamexp_version_arch(void) { return g_lamexp_version_arch
; }
275 unsigned int lamexp_toolver_neroaac(void) { return g_lamexp_toolver_neroaac
; }
276 unsigned int lamexp_toolver_fhgaacenc(void) { return g_lamexp_toolver_fhgaacenc
; }
277 unsigned int lamexp_toolver_qaacenc(void) { return g_lamexp_toolver_qaacenc
; }
278 unsigned int lamexp_toolver_coreaudio(void) { return g_lamexp_toolver_coreaudio
; }
283 const char *lamexp_website_url(void) { return g_lamexp_website_url
; }
284 const char *lamexp_support_url(void) { return g_lamexp_support_url
; }
287 * Check for Demo (pre-release) version
289 bool lamexp_version_demo(void)
292 bool releaseVersion
= false;
293 if(!strncpy_s(buffer
, 128, g_lamexp_version
.ver_release_name
, _TRUNCATE
))
295 char *context
, *prefix
= strtok_s(buffer
, "-,; ", &context
);
298 releaseVersion
= (!_stricmp(prefix
, "Final")) || (!_stricmp(prefix
, "Hotfix"));
301 return LAMEXP_DEBUG
|| (!releaseVersion
);
305 * Calculate expiration date
307 QDate
lamexp_version_expires(void)
309 return lamexp_version_date().addDays(LAMEXP_DEBUG
? 7 : 30);
313 * Get build date date
315 const QDate
&lamexp_version_date(void)
317 if(!g_lamexp_version_date
.isValid())
319 int date
[3] = {0, 0, 0}; char temp
[12] = {'\0'};
320 strncpy_s(temp
, 12, g_lamexp_version_raw_date
, _TRUNCATE
);
322 if(strlen(temp
) == 11)
324 temp
[3] = temp
[6] = '\0';
325 date
[2] = atoi(&temp
[4]);
326 date
[0] = atoi(&temp
[7]);
328 for(int j
= 0; j
< 12; j
++)
330 if(!_strcmpi(&temp
[0], g_lamexp_months
[j
]))
337 g_lamexp_version_date
= QDate(date
[0], date
[1], date
[2]);
340 if(!g_lamexp_version_date
.isValid())
342 qFatal("Internal error: Date format could not be recognized!");
346 return g_lamexp_version_date
;
350 * Get the native operating system version
352 DWORD
lamexp_get_os_version(void)
354 static DWORD osVersion
= 0;
358 OSVERSIONINFO osVerInfo
;
359 memset(&osVerInfo
, 0, sizeof(OSVERSIONINFO
));
360 osVerInfo
.dwOSVersionInfoSize
= sizeof(OSVERSIONINFO
);
362 if(GetVersionEx(&osVerInfo
) == TRUE
)
364 if(osVerInfo
.dwPlatformId
!= VER_PLATFORM_WIN32_NT
)
366 throw "Ouuups: Not running under Windows NT. This is not supposed to happen!";
368 const DWORD osVerHi
= (DWORD
)(((DWORD
)(osVerInfo
.dwMajorVersion
)) << 16);
369 const DWORD osVerLo
= (DWORD
)(((DWORD
)(osVerInfo
.dwMinorVersion
)) & ((DWORD
)(0xffff)));
370 osVersion
= (DWORD
)(((DWORD
)(osVerHi
)) | ((DWORD
)(osVerLo
)));
374 throw "GetVersionEx() has failed. This is not supposed to happen!";
382 * Check if we are running under wine
384 bool lamexp_detect_wine(void)
386 static bool isWine
= false;
387 static bool isWine_initialized
= false;
389 if(!isWine_initialized
)
391 QLibrary
ntdll("ntdll.dll");
394 if(ntdll
.resolve("wine_nt_to_unix_file_name") != NULL
) isWine
= true;
395 if(ntdll
.resolve("wine_get_version") != NULL
) isWine
= true;
398 isWine_initialized
= true;
405 * Global exception handler
407 LONG WINAPI
lamexp_exception_handler(__in
struct _EXCEPTION_POINTERS
*ExceptionInfo
)
409 if(GetCurrentThreadId() != g_main_thread_id
)
411 HANDLE mainThread
= OpenThread(THREAD_TERMINATE
, FALSE
, g_main_thread_id
);
412 if(mainThread
) TerminateThread(mainThread
, ULONG_MAX
);
415 FatalAppExit(0, L
"Unhandeled exception handler invoked, application will exit!");
416 TerminateProcess(GetCurrentProcess(), -1);
421 * Invalid parameters handler
423 void lamexp_invalid_param_handler(const wchar_t*, const wchar_t*, const wchar_t*, unsigned int, uintptr_t)
425 if(GetCurrentThreadId() != g_main_thread_id
)
427 HANDLE mainThread
= OpenThread(THREAD_TERMINATE
, FALSE
, g_main_thread_id
);
428 if(mainThread
) TerminateThread(mainThread
, ULONG_MAX
);
432 FatalAppExit(0, L
"Invalid parameter handler invoked, application will exit!");
433 TerminateProcess(GetCurrentProcess(), -1);
437 * Change console text color
439 static void lamexp_console_color(FILE* file
, WORD attributes
)
441 const HANDLE hConsole
= (HANDLE
)(_get_osfhandle(_fileno(file
)));
442 if((hConsole
!= NULL
) && (hConsole
!= INVALID_HANDLE_VALUE
))
444 SetConsoleTextAttribute(hConsole
, attributes
);
451 void lamexp_message_handler(QtMsgType type
, const char *msg
)
453 static const char *GURU_MEDITATION
= "\n\nGURU MEDITATION !!!\n\n";
455 QMutexLocker
lock(&g_lamexp_message_mutex
);
457 if(g_lamexp_log_file
)
459 static char prefix
[] = "DWCF";
460 int index
= qBound(0, static_cast<int>(type
), 3);
461 unsigned int timestamp
= static_cast<unsigned int>(_time64(NULL
) % 3600I64
);
462 QString str
= QString::fromUtf8(msg
).trimmed().replace('\n', '\t');
463 fprintf(g_lamexp_log_file
, "[%c][%04u] %s\r\n", prefix
[index
], timestamp
, str
.toUtf8().constData());
464 fflush(g_lamexp_log_file
);
467 if(g_lamexp_console_attached
)
469 UINT oldOutputCP
= GetConsoleOutputCP();
470 if(oldOutputCP
!= CP_UTF8
) SetConsoleOutputCP(CP_UTF8
);
478 lamexp_console_color(stderr
, FOREGROUND_RED
| FOREGROUND_INTENSITY
);
479 fprintf(stderr
, GURU_MEDITATION
);
480 fprintf(stderr
, "%s\n", msg
);
484 lamexp_console_color(stderr
, FOREGROUND_GREEN
| FOREGROUND_RED
| FOREGROUND_INTENSITY
);
485 fprintf(stderr
, "%s\n", msg
);
489 lamexp_console_color(stderr
, FOREGROUND_BLUE
| FOREGROUND_GREEN
| FOREGROUND_RED
| FOREGROUND_INTENSITY
);
490 fprintf(stderr
, "%s\n", msg
);
495 lamexp_console_color(stderr
, FOREGROUND_BLUE
| FOREGROUND_GREEN
| FOREGROUND_RED
);
496 if(oldOutputCP
!= CP_UTF8
) SetConsoleOutputCP(oldOutputCP
);
500 QString
temp("[LameXP][%1] %2");
506 temp
= temp
.arg("C", QString::fromUtf8(msg
));
509 temp
= temp
.arg("W", QString::fromUtf8(msg
));
512 temp
= temp
.arg("I", QString::fromUtf8(msg
));
516 temp
.replace("\n", "\t").append("\n");
517 OutputDebugStringA(temp
.toLatin1().constData());
520 if(type
== QtCriticalMsg
|| type
== QtFatalMsg
)
524 if(GetCurrentThreadId() != g_main_thread_id
)
526 HANDLE mainThread
= OpenThread(THREAD_TERMINATE
, FALSE
, g_main_thread_id
);
527 if(mainThread
) TerminateThread(mainThread
, ULONG_MAX
);
530 MessageBoxW(NULL
, QWCHAR(QString::fromUtf8(msg
)), L
"LameXP - GURU MEDITATION", MB_ICONERROR
| MB_TOPMOST
| MB_TASKMODAL
);
531 FatalAppExit(0, L
"The application has encountered a critical error and will exit now!");
532 TerminateProcess(GetCurrentProcess(), -1);
537 * Initialize the console
539 void lamexp_init_console(int argc
, char* argv
[])
541 bool enableConsole
= lamexp_version_demo();
545 wchar_t *logfile
= NULL
;
546 size_t logfile_len
= 0;
547 if(!_wdupenv_s(&logfile
, &logfile_len
, L
"LAMEXP_LOGFILE"))
549 if(logfile
&& (logfile_len
> 0))
552 if(!_wfopen_s(&temp
, logfile
, L
"wb"))
554 fprintf(temp
, "%c%c%c", 0xEF, 0xBB, 0xBF);
555 g_lamexp_log_file
= temp
;
564 for(int i
= 0; i
< argc
; i
++)
566 if(!_stricmp(argv
[i
], "--console"))
568 enableConsole
= true;
570 else if(!_stricmp(argv
[i
], "--no-console"))
572 enableConsole
= false;
579 if(!g_lamexp_console_attached
)
581 if(AllocConsole() != FALSE
)
583 SetConsoleCtrlHandler(NULL
, TRUE
);
584 SetConsoleTitle(L
"LameXP - Audio Encoder Front-End | Debug Console");
585 SetConsoleOutputCP(CP_UTF8
);
586 g_lamexp_console_attached
= true;
590 if(g_lamexp_console_attached
)
592 //-------------------------------------------------------------------
593 //See: http://support.microsoft.com/default.aspx?scid=kb;en-us;105305
594 //-------------------------------------------------------------------
595 const int flags
= _O_WRONLY
| _O_U8TEXT
;
596 int hCrtStdOut
= _open_osfhandle((intptr_t) GetStdHandle(STD_OUTPUT_HANDLE
), flags
);
597 int hCrtStdErr
= _open_osfhandle((intptr_t) GetStdHandle(STD_ERROR_HANDLE
), flags
);
598 FILE *hfStdOut
= (hCrtStdOut
>= 0) ? _fdopen(hCrtStdOut
, "wb") : NULL
;
599 FILE *hfStdErr
= (hCrtStdErr
>= 0) ? _fdopen(hCrtStdErr
, "wb") : NULL
;
600 if(hfStdOut
) { *stdout
= *hfStdOut
; std::cout
.rdbuf(new std::filebuf(hfStdOut
)); }
601 if(hfStdErr
) { *stderr
= *hfStdErr
; std::cerr
.rdbuf(new std::filebuf(hfStdErr
)); }
604 HWND hwndConsole
= GetConsoleWindow();
606 if((hwndConsole
!= NULL
) && (hwndConsole
!= INVALID_HANDLE_VALUE
))
608 HMENU hMenu
= GetSystemMenu(hwndConsole
, 0);
609 EnableMenuItem(hMenu
, SC_CLOSE
, MF_BYCOMMAND
| MF_GRAYED
);
610 RemoveMenu(hMenu
, SC_CLOSE
, MF_BYCOMMAND
);
612 SetWindowPos(hwndConsole
, HWND_TOP
, 0, 0, 0, 0, SWP_NOMOVE
|SWP_NOSIZE
|SWP_NOZORDER
|SWP_FRAMECHANGED
);
613 SetWindowLong(hwndConsole
, GWL_STYLE
, GetWindowLong(hwndConsole
, GWL_STYLE
) & (~WS_MAXIMIZEBOX
) & (~WS_MINIMIZEBOX
));
614 SetWindowPos(hwndConsole
, HWND_TOP
, 0, 0, 0, 0, SWP_NOMOVE
|SWP_NOSIZE
|SWP_NOZORDER
|SWP_FRAMECHANGED
);
620 * Detect CPU features
622 lamexp_cpu_t
lamexp_detect_cpu_features(int argc
, char **argv
)
624 typedef BOOL (WINAPI
*IsWow64ProcessFun
)(__in HANDLE hProcess
, __out PBOOL Wow64Process
);
625 typedef VOID (WINAPI
*GetNativeSystemInfoFun
)(__out LPSYSTEM_INFO lpSystemInfo
);
627 static IsWow64ProcessFun IsWow64ProcessPtr
= NULL
;
628 static GetNativeSystemInfoFun GetNativeSystemInfoPtr
= NULL
;
630 lamexp_cpu_t features
;
631 SYSTEM_INFO systemInfo
;
632 int CPUInfo
[4] = {-1};
633 char CPUIdentificationString
[0x40];
634 char CPUBrandString
[0x40];
636 memset(&features
, 0, sizeof(lamexp_cpu_t
));
637 memset(&systemInfo
, 0, sizeof(SYSTEM_INFO
));
638 memset(CPUIdentificationString
, 0, sizeof(CPUIdentificationString
));
639 memset(CPUBrandString
, 0, sizeof(CPUBrandString
));
642 memcpy(CPUIdentificationString
, &CPUInfo
[1], sizeof(int));
643 memcpy(CPUIdentificationString
+ 4, &CPUInfo
[3], sizeof(int));
644 memcpy(CPUIdentificationString
+ 8, &CPUInfo
[2], sizeof(int));
645 features
.intel
= (_stricmp(CPUIdentificationString
, "GenuineIntel") == 0);
646 strncpy_s(features
.vendor
, 0x40, CPUIdentificationString
, _TRUNCATE
);
651 features
.mmx
= (CPUInfo
[3] & 0x800000) || false;
652 features
.sse
= (CPUInfo
[3] & 0x2000000) || false;
653 features
.sse2
= (CPUInfo
[3] & 0x4000000) || false;
654 features
.ssse3
= (CPUInfo
[2] & 0x200) || false;
655 features
.sse3
= (CPUInfo
[2] & 0x1) || false;
656 features
.ssse3
= (CPUInfo
[2] & 0x200) || false;
657 features
.stepping
= CPUInfo
[0] & 0xf;
658 features
.model
= ((CPUInfo
[0] >> 4) & 0xf) + (((CPUInfo
[0] >> 16) & 0xf) << 4);
659 features
.family
= ((CPUInfo
[0] >> 8) & 0xf) + ((CPUInfo
[0] >> 20) & 0xff);
662 __cpuid(CPUInfo
, 0x80000000);
663 int nExIds
= qMax
<int>(qMin
<int>(CPUInfo
[0], 0x80000004), 0x80000000);
665 for(int i
= 0x80000002; i
<= nExIds
; ++i
)
671 memcpy(CPUBrandString
, CPUInfo
, sizeof(CPUInfo
));
674 memcpy(CPUBrandString
+ 16, CPUInfo
, sizeof(CPUInfo
));
677 memcpy(CPUBrandString
+ 32, CPUInfo
, sizeof(CPUInfo
));
682 strncpy_s(features
.brand
, 0x40, CPUBrandString
, _TRUNCATE
);
684 if(strlen(features
.brand
) < 1) strncpy_s(features
.brand
, 0x40, "Unknown", _TRUNCATE
);
685 if(strlen(features
.vendor
) < 1) strncpy_s(features
.vendor
, 0x40, "Unknown", _TRUNCATE
);
687 #if !defined(_M_X64 ) && !defined(_M_IA64)
688 if(!IsWow64ProcessPtr
|| !GetNativeSystemInfoPtr
)
690 QLibrary
Kernel32Lib("kernel32.dll");
691 IsWow64ProcessPtr
= (IsWow64ProcessFun
) Kernel32Lib
.resolve("IsWow64Process");
692 GetNativeSystemInfoPtr
= (GetNativeSystemInfoFun
) Kernel32Lib
.resolve("GetNativeSystemInfo");
694 if(IsWow64ProcessPtr
)
697 if(IsWow64ProcessPtr(GetCurrentProcess(), &x64
))
702 if(GetNativeSystemInfoPtr
)
704 GetNativeSystemInfoPtr(&systemInfo
);
708 GetSystemInfo(&systemInfo
);
710 features
.count
= qBound(1UL, systemInfo
.dwNumberOfProcessors
, 64UL);
712 GetNativeSystemInfo(&systemInfo
);
713 features
.count
= systemInfo
.dwNumberOfProcessors
;
717 if((argv
!= NULL
) && (argc
> 0))
720 for(int i
= 0; i
< argc
; i
++)
722 if(!_stricmp("--force-cpu-no-64bit", argv
[i
])) { flag
= true; features
.x64
= false; }
723 if(!_stricmp("--force-cpu-no-sse", argv
[i
])) { flag
= true; features
.sse
= features
.sse2
= features
.sse3
= features
.ssse3
= false; }
724 if(!_stricmp("--force-cpu-no-intel", argv
[i
])) { flag
= true; features
.intel
= false; }
726 if(flag
) qWarning("CPU flags overwritten by user-defined parameters. Take care!\n");
733 * Check for debugger (detect routine)
735 static __forceinline
bool lamexp_check_for_debugger(void)
737 if(IsDebuggerPresent())
744 CloseHandle((HANDLE
) 0x7FFFFFFF);
746 __except(EXCEPTION_EXECUTE_HANDLER
)
755 __except(EXCEPTION_EXECUTE_HANDLER
)
764 * Check for debugger (thread proc)
766 static unsigned int __stdcall
lamexp_debug_thread_proc(LPVOID lpParameter
)
768 while(!lamexp_check_for_debugger())
772 if(HANDLE thrd
= OpenThread(THREAD_TERMINATE
, FALSE
, g_main_thread_id
))
774 if(TerminateThread(thrd
, -1))
776 FatalAppExit(0, L
"Not a debug build. Please unload debugger and try again!");
780 TerminateProcess(GetCurrentProcess(), -1);
785 * Check for debugger (startup routine)
787 static HANDLE
lamexp_debug_thread_init(void)
789 if(lamexp_check_for_debugger())
791 FatalAppExit(0, L
"Not a debug build. Please unload debugger and try again!");
792 TerminateProcess(GetCurrentProcess(), -1);
795 return (HANDLE
) _beginthreadex(NULL
, 0, lamexp_debug_thread_proc
, NULL
, 0, NULL
);
799 * Check for compatibility mode
801 static bool lamexp_check_compatibility_mode(const char *exportName
, const char *executableName
)
803 QLibrary
kernel32("kernel32.dll");
805 if((exportName
!= NULL
) && kernel32
.load())
807 if(kernel32
.resolve(exportName
) != NULL
)
809 qWarning("Function '%s' exported from 'kernel32.dll' -> Windows compatibility mode!", exportName
);
810 qFatal("%s", QApplication::tr("Executable '%1' doesn't support Windows compatibility mode.").arg(QString::fromLatin1(executableName
)).toLatin1().constData());
819 * Computus according to H. Lichtenberg
821 static bool lamexp_computus(const QDate
&date
)
826 int M
= 15 + (3*K
+ 3) / 4 - (8*K
+ 13) / 25;
827 int D
= (19*A
+ M
) % 30;
828 int S
= 2 - (3*K
+ 3) / 4;
829 int R
= D
/ 29 + (D
/ 28 - D
/ 29) * (A
/ 11);
831 int SZ
= 7 - (X
+ X
/ 4 + S
) % 7;
832 int OE
= 7 - (OG
- SZ
) % 7;
837 return (date
.month() == 4) && (date
.day() == (OS
- 31));
841 return (date
.month() == 3) && (date
.day() == OS
);
846 * Check for Thanksgiving
848 static bool lamexp_thanksgiving(const QDate
&date
)
852 switch(QDate(date
.year(), 11, 1).dayOfWeek())
854 case 1: day
= 25; break;
855 case 2: day
= 24; break;
856 case 3: day
= 23; break;
857 case 4: day
= 22; break;
858 case 5: day
= 28; break;
859 case 6: day
= 27; break;
860 case 7: day
= 26; break;
863 return (date
.month() == 11) && (date
.day() == day
);
867 * Initialize app icon
869 QIcon
lamexp_app_icon(const QDate
*date
, const QTime
*time
)
871 QDate currentDate
= (date
) ? QDate(*date
) : QDate::currentDate();
872 QTime currentTime
= (time
) ? QTime(*time
) : QTime::currentTime();
874 if(lamexp_thanksgiving(currentDate
))
876 return QIcon(":/MainIcon6.png");
878 else if(((currentDate
.month() == 12) && (currentDate
.day() == 31) && (currentTime
.hour() >= 20)) || ((currentDate
.month() == 1) && (currentDate
.day() == 1) && (currentTime
.hour() <= 19)))
880 return QIcon(":/MainIcon5.png");
882 else if(((currentDate
.month() == 10) && (currentDate
.day() == 31) && (currentTime
.hour() >= 12)) || ((currentDate
.month() == 11) && (currentDate
.day() == 1) && (currentTime
.hour() <= 11)))
884 return QIcon(":/MainIcon4.png");
886 else if((currentDate
.month() == 12) && (currentDate
.day() >= 24) && (currentDate
.day() <= 26))
888 return QIcon(":/MainIcon3.png");
890 else if(lamexp_computus(currentDate
))
892 return QIcon(":/MainIcon2.png");
896 return QIcon(":/MainIcon1.png");
901 * Broadcast event to all windows
903 static bool lamexp_broadcast(int eventType
, bool onlyToVisible
)
905 if(QApplication
*app
= dynamic_cast<QApplication
*>(QApplication::instance()))
907 qDebug("Broadcasting %d", eventType
);
910 QEvent
poEvent(static_cast<QEvent::Type
>(eventType
));
911 QWidgetList list
= app
->topLevelWidgets();
913 while(!list
.isEmpty())
915 QWidget
*widget
= list
.takeFirst();
916 if(!onlyToVisible
|| widget
->isVisible())
918 if(!app
->sendEvent(widget
, &poEvent
))
925 qDebug("Broadcast %d done (%s)", eventType
, (allOk
? "OK" : "Stopped"));
930 qWarning("Broadcast failed, could not get QApplication instance!");
938 static bool lamexp_event_filter(void *message
, long *result
)
940 if((!(LAMEXP_DEBUG
)) && lamexp_check_for_debugger())
942 FatalAppExit(0, L
"Not a debug build. Please unload debugger and try again!");
943 TerminateProcess(GetCurrentProcess(), -1);
946 switch(reinterpret_cast<MSG
*>(message
)->message
)
948 case WM_QUERYENDSESSION
:
949 qWarning("WM_QUERYENDSESSION message received!");
950 *result
= lamexp_broadcast(lamexp_event_queryendsession
, false) ? TRUE
: FALSE
;
953 qWarning("WM_ENDSESSION message received!");
954 if(reinterpret_cast<MSG
*>(message
)->wParam
== TRUE
)
956 lamexp_broadcast(lamexp_event_endsession
, false);
957 if(QApplication
*app
= reinterpret_cast<QApplication
*>(QApplication::instance()))
959 app
->closeAllWindows();
962 lamexp_finalization();
968 /*ignore this message and let Qt handle it*/
974 * Check for process elevation
976 static bool lamexp_check_elevation(void)
978 typedef enum { lamexp_token_elevationType_class
= 18, lamexp_token_elevation_class
= 20 } LAMEXP_TOKEN_INFORMATION_CLASS
;
979 typedef enum { lamexp_elevationType_default
= 1, lamexp_elevationType_full
, lamexp_elevationType_limited
} LAMEXP_TOKEN_ELEVATION_TYPE
;
981 HANDLE hToken
= NULL
;
982 bool bIsProcessElevated
= false;
984 if(OpenProcessToken(GetCurrentProcess(), TOKEN_QUERY
, &hToken
))
986 LAMEXP_TOKEN_ELEVATION_TYPE tokenElevationType
;
988 if(GetTokenInformation(hToken
, (TOKEN_INFORMATION_CLASS
) lamexp_token_elevationType_class
, &tokenElevationType
, sizeof(LAMEXP_TOKEN_ELEVATION_TYPE
), &returnLength
))
990 if(returnLength
== sizeof(LAMEXP_TOKEN_ELEVATION_TYPE
))
992 switch(tokenElevationType
)
994 case lamexp_elevationType_default
:
995 qDebug("Process token elevation type: Default -> UAC is disabled.\n");
997 case lamexp_elevationType_full
:
998 qWarning("Process token elevation type: Full -> potential security risk!\n");
999 bIsProcessElevated
= true;
1001 case lamexp_elevationType_limited
:
1002 qDebug("Process token elevation type: Limited -> not elevated.\n");
1007 CloseHandle(hToken
);
1011 qWarning("Failed to open process token!");
1014 return !bIsProcessElevated
;
1018 * Initialize Qt framework
1020 bool lamexp_init_qt(int argc
, char* argv
[])
1022 static bool qt_initialized
= false;
1023 typedef BOOL (WINAPI
*SetDllDirectoryProc
)(WCHAR
*lpPathName
);
1025 //Don't initialized again, if done already
1031 //Secure DLL loading
1032 QLibrary
kernel32("kernel32.dll");
1035 SetDllDirectoryProc pSetDllDirectory
= (SetDllDirectoryProc
) kernel32
.resolve("SetDllDirectoryW");
1036 if(pSetDllDirectory
!= NULL
) pSetDllDirectory(L
"");
1040 //Extract executable name from argv[] array
1041 char *executableName
= argv
[0];
1042 while(char *temp
= strpbrk(executableName
, "\\/:?"))
1044 executableName
= temp
+ 1;
1049 qDebug("Using Qt v%s [%s], %s, %s", qVersion(), QLibraryInfo::buildDate().toString(Qt::ISODate
).toLatin1().constData(), (qSharedBuild() ? "DLL" : "Static"), QLibraryInfo::buildKey().toLatin1().constData());
1050 qDebug("Compiled with Qt v%s [%s], %s\n", QT_VERSION_STR
, QT_PACKAGEDATE_STR
, QT_BUILD_KEY
);
1051 if(_stricmp(qVersion(), QT_VERSION_STR
))
1053 qFatal("%s", QApplication::tr("Executable '%1' requires Qt v%2, but found Qt v%3.").arg(QString::fromLatin1(executableName
), QString::fromLatin1(QT_VERSION_STR
), QString::fromLatin1(qVersion())).toLatin1().constData());
1056 if(QLibraryInfo::buildKey().compare(QString::fromLatin1(QT_BUILD_KEY
), Qt::CaseInsensitive
))
1058 qFatal("%s", QApplication::tr("Executable '%1' was built for Qt '%2', but found Qt '%3'.").arg(QString::fromLatin1(executableName
), QString::fromLatin1(QT_BUILD_KEY
), QLibraryInfo::buildKey()).toLatin1().constData());
1062 qDebug("Using Qt v%s [%s], %s", qVersion(), QLibraryInfo::buildDate().toString(Qt::ISODate
).toLatin1().constData(), (qSharedBuild() ? "DLL" : "Static"));
1063 qDebug("Compiled with Qt v%s [%s]\n", QT_VERSION_STR
, QT_PACKAGEDATE_STR
);
1066 //Check the Windows version
1067 switch(QSysInfo::windowsVersion() & QSysInfo::WV_NT_based
)
1070 case QSysInfo::WV_NT
:
1071 qFatal("%s", QApplication::tr("Executable '%1' requires Windows 2000 or later.").arg(QString::fromLatin1(executableName
)).toLatin1().constData());
1073 case QSysInfo::WV_2000
:
1074 qDebug("Running on Windows 2000 (not officially supported!).\n");
1075 lamexp_check_compatibility_mode("GetNativeSystemInfo", executableName
);
1077 case QSysInfo::WV_XP
:
1078 qDebug("Running on Windows XP.\n");
1079 lamexp_check_compatibility_mode("GetLargePageMinimum", executableName
);
1081 case QSysInfo::WV_2003
:
1082 qDebug("Running on Windows Server 2003 or Windows XP x64-Edition.\n");
1083 lamexp_check_compatibility_mode("GetLocaleInfoEx", executableName
);
1085 case QSysInfo::WV_VISTA
:
1086 qDebug("Running on Windows Vista or Windows Server 2008.\n");
1087 lamexp_check_compatibility_mode("CreateRemoteThreadEx", executableName
);
1089 case QSysInfo::WV_WINDOWS7
:
1090 qDebug("Running on Windows 7 or Windows Server 2008 R2.\n");
1091 lamexp_check_compatibility_mode("CreateFile2", executableName
);
1095 DWORD osVersionNo
= lamexp_get_os_version();
1096 if(LAMEXP_EQL_OS_VER(osVersionNo
, 6, 2))
1098 qDebug("Running on Windows 8 (still experimental!)\n");
1099 lamexp_check_compatibility_mode(NULL
, executableName
);
1103 qWarning("Running on an unknown/untested WinNT-based OS (v%u.%u).\n", HIWORD(osVersionNo
), LOWORD(osVersionNo
));
1110 if(lamexp_detect_wine())
1112 qWarning("It appears we are running under Wine, unexpected things might happen!\n");
1115 //Set text Codec for locale
1116 QTextCodec::setCodecForLocale(QTextCodec::codecForName("UTF-8"));
1118 //Create Qt application instance
1119 QApplication
*application
= new QApplication(argc
, argv
);
1121 //Load plugins from application directory
1122 QCoreApplication::setLibraryPaths(QStringList() << QApplication::applicationDirPath());
1123 qDebug("Library Path:\n%s\n", QApplication::libraryPaths().first().toUtf8().constData());
1125 //Set application properties
1126 application
->setApplicationName("LameXP - Audio Encoder Front-End");
1127 application
->setApplicationVersion(QString().sprintf("%d.%02d.%04d", lamexp_version_major(), lamexp_version_minor(), lamexp_version_build()));
1128 application
->setOrganizationName("LoRd_MuldeR");
1129 application
->setOrganizationDomain("mulder.at.gg");
1130 application
->setWindowIcon(lamexp_app_icon());
1131 application
->setEventFilter(lamexp_event_filter
);
1133 //Check for supported image formats
1134 QList
<QByteArray
> supportedFormats
= QImageReader::supportedImageFormats();
1135 for(int i
= 0; g_lamexp_imageformats
[i
]; i
++)
1137 if(!supportedFormats
.contains(g_lamexp_imageformats
[i
]))
1139 qFatal("Qt initialization error: QImageIOHandler for '%s' missing!", g_lamexp_imageformats
[i
]);
1144 //Add default translations
1145 g_lamexp_translation
.files
.insert(LAMEXP_DEFAULT_LANGID
, "");
1146 g_lamexp_translation
.names
.insert(LAMEXP_DEFAULT_LANGID
, "English");
1148 //Check for process elevation
1149 if((!lamexp_check_elevation()) && (!lamexp_detect_wine()))
1151 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
);
1152 messageBox
.addButton("Quit Program (Recommended)", QMessageBox::NoRole
);
1153 messageBox
.addButton("Ignore", QMessageBox::NoRole
);
1154 if(messageBox
.exec() == 0)
1160 //Update console icon, if a console is attached
1161 #if QT_VERSION < QT_VERSION_CHECK(5,0,0)
1162 if(g_lamexp_console_attached
&& (!lamexp_detect_wine()))
1164 typedef DWORD (__stdcall
*SetConsoleIconFun
)(HICON
);
1165 QLibrary
kernel32("kernel32.dll");
1168 SetConsoleIconFun SetConsoleIconPtr
= (SetConsoleIconFun
) kernel32
.resolve("SetConsoleIcon");
1169 if(SetConsoleIconPtr
!= NULL
) SetConsoleIconPtr(QIcon(":/icons/sound.png").pixmap(16, 16).toWinHICON());
1176 qt_initialized
= true;
1183 int lamexp_init_ipc(void)
1185 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
)
1190 g_lamexp_ipc_ptr
.semaphore_read
= new QSystemSemaphore(QString(g_lamexp_ipc_uuid
.semaphore_read
), 0);
1191 g_lamexp_ipc_ptr
.semaphore_write
= new QSystemSemaphore(QString(g_lamexp_ipc_uuid
.semaphore_write
), 0);
1192 g_lamexp_ipc_ptr
.semaphore_read_mutex
= new QSystemSemaphore(QString(g_lamexp_ipc_uuid
.semaphore_read_mutex
), 0);
1193 g_lamexp_ipc_ptr
.semaphore_write_mutex
= new QSystemSemaphore(QString(g_lamexp_ipc_uuid
.semaphore_write_mutex
), 0);
1195 if(g_lamexp_ipc_ptr
.semaphore_read
->error() != QSystemSemaphore::NoError
)
1197 QString errorMessage
= g_lamexp_ipc_ptr
.semaphore_read
->errorString();
1198 LAMEXP_DELETE(g_lamexp_ipc_ptr
.semaphore_read
);
1199 LAMEXP_DELETE(g_lamexp_ipc_ptr
.semaphore_write
);
1200 LAMEXP_DELETE(g_lamexp_ipc_ptr
.semaphore_read_mutex
);
1201 LAMEXP_DELETE(g_lamexp_ipc_ptr
.semaphore_write_mutex
);
1202 qFatal("Failed to create system smaphore: %s", errorMessage
.toUtf8().constData());
1205 if(g_lamexp_ipc_ptr
.semaphore_write
->error() != QSystemSemaphore::NoError
)
1207 QString errorMessage
= g_lamexp_ipc_ptr
.semaphore_write
->errorString();
1208 LAMEXP_DELETE(g_lamexp_ipc_ptr
.semaphore_read
);
1209 LAMEXP_DELETE(g_lamexp_ipc_ptr
.semaphore_write
);
1210 LAMEXP_DELETE(g_lamexp_ipc_ptr
.semaphore_read_mutex
);
1211 LAMEXP_DELETE(g_lamexp_ipc_ptr
.semaphore_write_mutex
);
1212 qFatal("Failed to create system smaphore: %s", errorMessage
.toUtf8().constData());
1215 if(g_lamexp_ipc_ptr
.semaphore_read_mutex
->error() != QSystemSemaphore::NoError
)
1217 QString errorMessage
= g_lamexp_ipc_ptr
.semaphore_read_mutex
->errorString();
1218 LAMEXP_DELETE(g_lamexp_ipc_ptr
.semaphore_read
);
1219 LAMEXP_DELETE(g_lamexp_ipc_ptr
.semaphore_write
);
1220 LAMEXP_DELETE(g_lamexp_ipc_ptr
.semaphore_read_mutex
);
1221 LAMEXP_DELETE(g_lamexp_ipc_ptr
.semaphore_write_mutex
);
1222 qFatal("Failed to create system smaphore: %s", errorMessage
.toUtf8().constData());
1225 if(g_lamexp_ipc_ptr
.semaphore_write_mutex
->error() != QSystemSemaphore::NoError
)
1227 QString errorMessage
= g_lamexp_ipc_ptr
.semaphore_write_mutex
->errorString();
1228 LAMEXP_DELETE(g_lamexp_ipc_ptr
.semaphore_read
);
1229 LAMEXP_DELETE(g_lamexp_ipc_ptr
.semaphore_write
);
1230 LAMEXP_DELETE(g_lamexp_ipc_ptr
.semaphore_read_mutex
);
1231 LAMEXP_DELETE(g_lamexp_ipc_ptr
.semaphore_write_mutex
);
1232 qFatal("Failed to create system smaphore: %s", errorMessage
.toUtf8().constData());
1236 g_lamexp_ipc_ptr
.sharedmem
= new QSharedMemory(QString(g_lamexp_ipc_uuid
.sharedmem
), NULL
);
1238 if(!g_lamexp_ipc_ptr
.sharedmem
->create(sizeof(lamexp_ipc_t
)))
1240 if(g_lamexp_ipc_ptr
.sharedmem
->error() == QSharedMemory::AlreadyExists
)
1242 g_lamexp_ipc_ptr
.sharedmem
->attach();
1243 if(g_lamexp_ipc_ptr
.sharedmem
->error() == QSharedMemory::NoError
)
1249 QString errorMessage
= g_lamexp_ipc_ptr
.sharedmem
->errorString();
1250 LAMEXP_DELETE(g_lamexp_ipc_ptr
.sharedmem
);
1251 qFatal("Failed to attach to shared memory: %s", errorMessage
.toUtf8().constData());
1257 QString errorMessage
= g_lamexp_ipc_ptr
.sharedmem
->errorString();
1258 LAMEXP_DELETE(g_lamexp_ipc_ptr
.sharedmem
);
1259 qFatal("Failed to create shared memory: %s", errorMessage
.toUtf8().constData());
1264 memset(g_lamexp_ipc_ptr
.sharedmem
->data(), 0, sizeof(lamexp_ipc_t
));
1265 g_lamexp_ipc_ptr
.semaphore_write
->release(g_lamexp_ipc_slots
);
1266 g_lamexp_ipc_ptr
.semaphore_read_mutex
->release();
1267 g_lamexp_ipc_ptr
.semaphore_write_mutex
->release();
1275 void lamexp_ipc_send(unsigned int command
, const char* message
)
1277 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
)
1279 throw "Shared memory for IPC not initialized yet.";
1282 lamexp_ipc_data_t ipc_data
;
1283 memset(&ipc_data
, 0, sizeof(lamexp_ipc_data_t
));
1284 ipc_data
.command
= command
;
1288 strncpy_s(ipc_data
.parameter
, 4096, message
, _TRUNCATE
);
1291 if(g_lamexp_ipc_ptr
.semaphore_write
->acquire())
1293 if(g_lamexp_ipc_ptr
.semaphore_write_mutex
->acquire())
1295 lamexp_ipc_t
*ptr
= reinterpret_cast<lamexp_ipc_t
*>(g_lamexp_ipc_ptr
.sharedmem
->data());
1296 memcpy(&ptr
->data
[ptr
->pos_write
], &ipc_data
, sizeof(lamexp_ipc_data_t
));
1297 ptr
->pos_write
= (ptr
->pos_write
+ 1) % g_lamexp_ipc_slots
;
1298 g_lamexp_ipc_ptr
.semaphore_read
->release();
1299 g_lamexp_ipc_ptr
.semaphore_write_mutex
->release();
1307 void lamexp_ipc_read(unsigned int *command
, char* message
, size_t buffSize
)
1312 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
)
1314 throw "Shared memory for IPC not initialized yet.";
1317 lamexp_ipc_data_t ipc_data
;
1318 memset(&ipc_data
, 0, sizeof(lamexp_ipc_data_t
));
1320 if(g_lamexp_ipc_ptr
.semaphore_read
->acquire())
1322 if(g_lamexp_ipc_ptr
.semaphore_read_mutex
->acquire())
1324 lamexp_ipc_t
*ptr
= reinterpret_cast<lamexp_ipc_t
*>(g_lamexp_ipc_ptr
.sharedmem
->data());
1325 memcpy(&ipc_data
, &ptr
->data
[ptr
->pos_read
], sizeof(lamexp_ipc_data_t
));
1326 ptr
->pos_read
= (ptr
->pos_read
+ 1) % g_lamexp_ipc_slots
;
1327 g_lamexp_ipc_ptr
.semaphore_write
->release();
1328 g_lamexp_ipc_ptr
.semaphore_read_mutex
->release();
1330 if(!(ipc_data
.reserved_1
|| ipc_data
.reserved_2
))
1332 *command
= ipc_data
.command
;
1333 strncpy_s(message
, buffSize
, ipc_data
.parameter
, _TRUNCATE
);
1337 qWarning("Malformed IPC message, will be ignored");
1344 * Check for LameXP "portable" mode
1346 bool lamexp_portable_mode(void)
1348 QString baseName
= QFileInfo(QApplication::applicationFilePath()).completeBaseName();
1349 int idx1
= baseName
.indexOf("lamexp", 0, Qt::CaseInsensitive
);
1350 int idx2
= baseName
.lastIndexOf("portable", -1, Qt::CaseInsensitive
);
1351 return (idx1
>= 0) && (idx2
>= 0) && (idx1
< idx2
);
1355 * Get a random string
1357 QString
lamexp_rand_str(void)
1359 QRegExp
regExp("\\{(\\w+)-(\\w+)-(\\w+)-(\\w+)-(\\w+)\\}");
1360 QString uuid
= QUuid::createUuid().toString();
1362 if(regExp
.indexIn(uuid
) >= 0)
1364 return QString().append(regExp
.cap(1)).append(regExp
.cap(2)).append(regExp
.cap(3)).append(regExp
.cap(4)).append(regExp
.cap(5));
1367 throw "The RegExp didn't match on the UUID string. This shouldn't happen ;-)";
1371 * Get LameXP temp folder
1373 const QString
&lamexp_temp_folder2(void)
1375 static const char *TEMP_STR
= "Temp";
1376 const QString WRITE_TEST_DATA
= lamexp_rand_str();
1377 const QString SUB_FOLDER
= lamexp_rand_str();
1379 //Already initialized?
1380 if(!g_lamexp_temp_folder
.isEmpty())
1382 if(QDir(g_lamexp_temp_folder
).exists())
1384 return g_lamexp_temp_folder
;
1388 g_lamexp_temp_folder
.clear();
1392 //Try the %TMP% or %TEMP% directory first
1393 QDir temp
= QDir::temp();
1396 temp
.mkdir(SUB_FOLDER
);
1397 if(temp
.cd(SUB_FOLDER
) && temp
.exists())
1399 QFile
testFile(QString("%1/~%2.tmp").arg(temp
.canonicalPath(), lamexp_rand_str()));
1400 if(testFile
.open(QIODevice::ReadWrite
))
1402 if(testFile
.write(WRITE_TEST_DATA
.toLatin1().constData()) >= strlen(WRITE_TEST_DATA
.toLatin1().constData()))
1404 g_lamexp_temp_folder
= temp
.canonicalPath();
1409 if(!g_lamexp_temp_folder
.isEmpty())
1411 return g_lamexp_temp_folder
;
1415 //Create TEMP folder in %LOCALAPPDATA%
1416 QDir localAppData
= QDir(lamexp_known_folder(lamexp_folder_localappdata
));
1417 if(!localAppData
.path().isEmpty())
1419 if(!localAppData
.exists())
1421 localAppData
.mkpath(".");
1423 if(localAppData
.exists())
1425 if(!localAppData
.entryList(QDir::AllDirs
).contains(TEMP_STR
, Qt::CaseInsensitive
))
1427 localAppData
.mkdir(TEMP_STR
);
1429 if(localAppData
.cd(TEMP_STR
) && localAppData
.exists())
1431 localAppData
.mkdir(SUB_FOLDER
);
1432 if(localAppData
.cd(SUB_FOLDER
) && localAppData
.exists())
1434 QFile
testFile(QString("%1/~%2.tmp").arg(localAppData
.canonicalPath(), lamexp_rand_str()));
1435 if(testFile
.open(QIODevice::ReadWrite
))
1437 if(testFile
.write(WRITE_TEST_DATA
.toLatin1().constData()) >= strlen(WRITE_TEST_DATA
.toLatin1().constData()))
1439 g_lamexp_temp_folder
= localAppData
.canonicalPath();
1446 if(!g_lamexp_temp_folder
.isEmpty())
1448 return g_lamexp_temp_folder
;
1452 //Failed to create TEMP folder!
1453 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());
1454 return g_lamexp_temp_folder
;
1460 bool lamexp_clean_folder(const QString
&folderPath
)
1462 QDir
tempFolder(folderPath
);
1463 QFileInfoList entryList
= tempFolder
.entryInfoList(QDir::AllEntries
| QDir::NoDotAndDotDot
);
1465 for(int i
= 0; i
< entryList
.count(); i
++)
1467 if(entryList
.at(i
).isDir())
1469 lamexp_clean_folder(entryList
.at(i
).canonicalFilePath());
1473 for(int j
= 0; j
< 3; j
++)
1475 if(lamexp_remove_file(entryList
.at(i
).canonicalFilePath()))
1483 tempFolder
.rmdir(".");
1484 return !tempFolder
.exists();
1490 void lamexp_register_tool(const QString
&toolName
, LockedFile
*file
, unsigned int version
)
1492 QWriteLocker
writeLock(&g_lamexp_tool_lock
);
1494 if(g_lamexp_tool_registry
.contains(toolName
.toLower()))
1496 throw "lamexp_register_tool: Tool is already registered!";
1499 g_lamexp_tool_registry
.insert(toolName
.toLower(), file
);
1500 g_lamexp_tool_versions
.insert(toolName
.toLower(), version
);
1506 bool lamexp_check_tool(const QString
&toolName
)
1508 QReadLocker
readLock(&g_lamexp_tool_lock
);
1509 return g_lamexp_tool_registry
.contains(toolName
.toLower());
1515 const QString
lamexp_lookup_tool(const QString
&toolName
)
1517 QReadLocker
readLock(&g_lamexp_tool_lock
);
1519 if(g_lamexp_tool_registry
.contains(toolName
.toLower()))
1521 return g_lamexp_tool_registry
.value(toolName
.toLower())->filePath();
1530 * Lookup tool version
1532 unsigned int lamexp_tool_version(const QString
&toolName
)
1534 QReadLocker
readLock(&g_lamexp_tool_lock
);
1536 if(g_lamexp_tool_versions
.contains(toolName
.toLower()))
1538 return g_lamexp_tool_versions
.value(toolName
.toLower());
1547 * Version number to human-readable string
1549 const QString
lamexp_version2string(const QString
&pattern
, unsigned int version
, const QString
&defaultText
)
1551 if(version
== UINT_MAX
)
1556 QString result
= pattern
;
1557 int digits
= result
.count("?", Qt::CaseInsensitive
);
1565 QString versionStr
= QString().sprintf(QString().sprintf("%%0%du", digits
).toLatin1().constData(), version
);
1566 int index
= result
.indexOf("?", Qt::CaseInsensitive
);
1568 while(index
>= 0 && pos
< versionStr
.length())
1570 result
[index
] = versionStr
[pos
++];
1571 index
= result
.indexOf("?", Qt::CaseInsensitive
);
1578 * Register a new translation
1580 bool lamexp_translation_register(const QString
&langId
, const QString
&qmFile
, const QString
&langName
, unsigned int &systemId
, unsigned int &country
)
1582 if(qmFile
.isEmpty() || langName
.isEmpty() || systemId
< 1)
1587 g_lamexp_translation
.files
.insert(langId
, qmFile
);
1588 g_lamexp_translation
.names
.insert(langId
, langName
);
1589 g_lamexp_translation
.sysid
.insert(langId
, systemId
);
1590 g_lamexp_translation
.cntry
.insert(langId
, country
);
1596 * Get list of all translations
1598 QStringList
lamexp_query_translations(void)
1600 return g_lamexp_translation
.files
.keys();
1604 * Get translation name
1606 QString
lamexp_translation_name(const QString
&langId
)
1608 return g_lamexp_translation
.names
.value(langId
.toLower(), QString());
1612 * Get translation system id
1614 unsigned int lamexp_translation_sysid(const QString
&langId
)
1616 return g_lamexp_translation
.sysid
.value(langId
.toLower(), 0);
1620 * Get translation script id
1622 unsigned int lamexp_translation_country(const QString
&langId
)
1624 return g_lamexp_translation
.cntry
.value(langId
.toLower(), 0);
1628 * Install a new translator
1630 bool lamexp_install_translator(const QString
&langId
)
1632 bool success
= false;
1634 if(langId
.isEmpty() || langId
.toLower().compare(LAMEXP_DEFAULT_LANGID
) == 0)
1636 success
= lamexp_install_translator_from_file(QString());
1640 QString qmFile
= g_lamexp_translation
.files
.value(langId
.toLower(), QString());
1641 if(!qmFile
.isEmpty())
1643 success
= lamexp_install_translator_from_file(QString(":/localization/%1").arg(qmFile
));
1647 qWarning("Translation '%s' not available!", langId
.toLatin1().constData());
1655 * Install a new translator from file
1657 bool lamexp_install_translator_from_file(const QString
&qmFile
)
1659 bool success
= false;
1661 if(!g_lamexp_currentTranslator
)
1663 g_lamexp_currentTranslator
= new QTranslator();
1666 if(!qmFile
.isEmpty())
1668 QString qmPath
= QFileInfo(qmFile
).canonicalFilePath();
1669 QApplication::removeTranslator(g_lamexp_currentTranslator
);
1670 success
= g_lamexp_currentTranslator
->load(qmPath
);
1671 QApplication::installTranslator(g_lamexp_currentTranslator
);
1674 qWarning("Failed to load translation:\n\"%s\"", qmPath
.toLatin1().constData());
1679 QApplication::removeTranslator(g_lamexp_currentTranslator
);
1687 * Locate known folder on local system
1689 QString
lamexp_known_folder(lamexp_known_folder_t folder_id
)
1691 typedef HRESULT (WINAPI
*SHGetKnownFolderPathFun
)(__in
const GUID
&rfid
, __in DWORD dwFlags
, __in HANDLE hToken
, __out PWSTR
*ppszPath
);
1692 typedef HRESULT (WINAPI
*SHGetFolderPathFun
)(__in HWND hwndOwner
, __in
int nFolder
, __in HANDLE hToken
, __in DWORD dwFlags
, __out LPWSTR pszPath
);
1694 static const int CSIDL_LOCAL_APPDATA
= 0x001c;
1695 static const int CSIDL_PROGRAM_FILES
= 0x0026;
1696 static const int CSIDL_SYSTEM_FOLDER
= 0x0025;
1697 static const GUID GUID_LOCAL_APPDATA
= {0xF1B32785,0x6FBA,0x4FCF,{0x9D,0x55,0x7B,0x8E,0x7F,0x15,0x70,0x91}};
1698 static const GUID GUID_LOCAL_APPDATA_LOW
= {0xA520A1A4,0x1780,0x4FF6,{0xBD,0x18,0x16,0x73,0x43,0xC5,0xAF,0x16}};
1699 static const GUID GUID_PROGRAM_FILES
= {0x905e63b6,0xc1bf,0x494e,{0xb2,0x9c,0x65,0xb7,0x32,0xd3,0xd2,0x1a}};
1700 static const GUID GUID_SYSTEM_FOLDER
= {0x1AC14E77,0x02E7,0x4E5D,{0xB7,0x44,0x2E,0xB1,0xAE,0x51,0x98,0xB7}};
1702 static SHGetKnownFolderPathFun SHGetKnownFolderPathPtr
= NULL
;
1703 static SHGetFolderPathFun SHGetFolderPathPtr
= NULL
;
1705 if((!SHGetKnownFolderPathPtr
) && (!SHGetFolderPathPtr
))
1707 QLibrary
kernel32Lib("shell32.dll");
1708 if(kernel32Lib
.load())
1710 SHGetKnownFolderPathPtr
= (SHGetKnownFolderPathFun
) kernel32Lib
.resolve("SHGetKnownFolderPath");
1711 SHGetFolderPathPtr
= (SHGetFolderPathFun
) kernel32Lib
.resolve("SHGetFolderPathW");
1715 int folderCSIDL
= -1;
1716 GUID folderGUID
= {0x0000,0x0000,0x0000,{0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00}};
1720 case lamexp_folder_localappdata
:
1721 folderCSIDL
= CSIDL_LOCAL_APPDATA
;
1722 folderGUID
= GUID_LOCAL_APPDATA
;
1724 case lamexp_folder_programfiles
:
1725 folderCSIDL
= CSIDL_PROGRAM_FILES
;
1726 folderGUID
= GUID_PROGRAM_FILES
;
1728 case lamexp_folder_systemfolder
:
1729 folderCSIDL
= CSIDL_SYSTEM_FOLDER
;
1730 folderGUID
= GUID_SYSTEM_FOLDER
;
1739 if(SHGetKnownFolderPathPtr
)
1742 if(SHGetKnownFolderPathPtr(folderGUID
, 0x00008000, NULL
, &path
) == S_OK
)
1744 //MessageBoxW(0, path, L"SHGetKnownFolderPath", MB_TOPMOST);
1745 QDir folderTemp
= QDir(QDir::fromNativeSeparators(QString::fromUtf16(reinterpret_cast<const unsigned short*>(path
))));
1746 if(!folderTemp
.exists())
1748 folderTemp
.mkpath(".");
1750 if(folderTemp
.exists())
1752 folder
= folderTemp
.canonicalPath();
1754 CoTaskMemFree(path
);
1757 else if(SHGetFolderPathPtr
)
1759 WCHAR
*path
= new WCHAR
[4096];
1760 if(SHGetFolderPathPtr(NULL
, folderCSIDL
, NULL
, NULL
, path
) == S_OK
)
1762 //MessageBoxW(0, path, L"SHGetFolderPathW", MB_TOPMOST);
1763 QDir folderTemp
= QDir(QDir::fromNativeSeparators(QString::fromUtf16(reinterpret_cast<const unsigned short*>(path
))));
1764 if(!folderTemp
.exists())
1766 folderTemp
.mkpath(".");
1768 if(folderTemp
.exists())
1770 folder
= folderTemp
.canonicalPath();
1780 * Safely remove a file
1782 bool lamexp_remove_file(const QString
&filename
)
1784 if(!QFileInfo(filename
).exists() || !QFileInfo(filename
).isFile())
1790 if(!QFile::remove(filename
))
1792 DWORD attributes
= GetFileAttributesW(QWCHAR(filename
));
1793 SetFileAttributesW(QWCHAR(filename
), (attributes
& (~FILE_ATTRIBUTE_READONLY
)));
1794 if(!QFile::remove(filename
))
1796 qWarning("Could not delete \"%s\"", filename
.toLatin1().constData());
1812 * Check if visual themes are enabled (WinXP and later)
1814 bool lamexp_themes_enabled(void)
1816 typedef int (WINAPI
*IsAppThemedFun
)(void);
1818 static bool isAppThemed
= false;
1819 static bool isAppThemed_initialized
= false;
1821 if(!isAppThemed_initialized
)
1823 IsAppThemedFun IsAppThemedPtr
= NULL
;
1824 QLibrary
uxTheme(QString("%1/UxTheme.dll").arg(lamexp_known_folder(lamexp_folder_systemfolder
)));
1827 IsAppThemedPtr
= (IsAppThemedFun
) uxTheme
.resolve("IsAppThemed");
1831 isAppThemed
= IsAppThemedPtr();
1834 qWarning("Theme support is disabled for this process!");
1837 isAppThemed_initialized
= true;
1844 * Get number of free bytes on disk
1846 unsigned __int64
lamexp_free_diskspace(const QString
&path
, bool *ok
)
1848 ULARGE_INTEGER freeBytesAvailable
, totalNumberOfBytes
, totalNumberOfFreeBytes
;
1849 if(GetDiskFreeSpaceExW(reinterpret_cast<const wchar_t*>(QDir::toNativeSeparators(path
).utf16()), &freeBytesAvailable
, &totalNumberOfBytes
, &totalNumberOfFreeBytes
))
1852 return freeBytesAvailable
.QuadPart
;
1862 * Check if computer does support hibernation
1864 bool lamexp_is_hibernation_supported(void)
1866 bool hibernationSupported
= false;
1868 SYSTEM_POWER_CAPABILITIES pwrCaps
;
1869 SecureZeroMemory(&pwrCaps
, sizeof(SYSTEM_POWER_CAPABILITIES
));
1871 if(GetPwrCapabilities(&pwrCaps
))
1873 hibernationSupported
= pwrCaps
.SystemS4
&& pwrCaps
.HiberFilePresent
;
1876 return hibernationSupported
;
1880 * Shutdown the computer
1882 bool lamexp_shutdown_computer(const QString
&message
, const unsigned long timeout
, const bool forceShutdown
, const bool hibernate
)
1884 HANDLE hToken
= NULL
;
1886 if(OpenProcessToken(GetCurrentProcess(), TOKEN_ADJUST_PRIVILEGES
| TOKEN_QUERY
, &hToken
))
1888 TOKEN_PRIVILEGES privileges
;
1889 memset(&privileges
, 0, sizeof(TOKEN_PRIVILEGES
));
1890 privileges
.PrivilegeCount
= 1;
1891 privileges
.Privileges
[0].Attributes
= SE_PRIVILEGE_ENABLED
;
1893 if(LookupPrivilegeValue(NULL
, SE_SHUTDOWN_NAME
, &privileges
.Privileges
[0].Luid
))
1895 if(AdjustTokenPrivileges(hToken
, FALSE
, &privileges
, NULL
, NULL
, NULL
))
1899 if(SetSuspendState(TRUE
, TRUE
, TRUE
))
1904 const DWORD reason
= SHTDN_REASON_MAJOR_APPLICATION
| SHTDN_REASON_FLAG_PLANNED
;
1905 return InitiateSystemShutdownEx(NULL
, const_cast<wchar_t*>(QWCHAR(message
)), timeout
, forceShutdown
? TRUE
: FALSE
, FALSE
, reason
);
1914 * Make a window blink (to draw user's attention)
1916 void lamexp_blink_window(QWidget
*poWindow
, unsigned int count
, unsigned int delay
)
1918 static QMutex blinkMutex
;
1920 const double maxOpac
= 1.0;
1921 const double minOpac
= 0.3;
1922 const double delOpac
= 0.1;
1924 if(!blinkMutex
.tryLock())
1926 qWarning("Blinking is already in progress, skipping!");
1932 const int steps
= static_cast<int>(ceil(maxOpac
- minOpac
) / delOpac
);
1933 const int sleep
= static_cast<int>(floor(static_cast<double>(delay
) / static_cast<double>(steps
)));
1934 const double opacity
= poWindow
->windowOpacity();
1936 for(unsigned int i
= 0; i
< count
; i
++)
1938 for(double x
= maxOpac
; x
>= minOpac
; x
-= delOpac
)
1940 poWindow
->setWindowOpacity(x
);
1941 QApplication::processEvents();
1945 for(double x
= minOpac
; x
<= maxOpac
; x
+= delOpac
)
1947 poWindow
->setWindowOpacity(x
);
1948 QApplication::processEvents();
1953 poWindow
->setWindowOpacity(opacity
);
1954 QApplication::processEvents();
1955 blinkMutex
.unlock();
1959 blinkMutex
.unlock();
1960 qWarning("Exception error while blinking!");
1965 * Remove forbidden characters from a filename
1967 const QString
lamexp_clean_filename(const QString
&str
)
1969 QString
newStr(str
);
1971 newStr
.replace("\\", "-");
1972 newStr
.replace(" / ", ", ");
1973 newStr
.replace("/", ",");
1974 newStr
.replace(":", "-");
1975 newStr
.replace("*", "x");
1976 newStr
.replace("?", "");
1977 newStr
.replace("<", "[");
1978 newStr
.replace(">", "]");
1979 newStr
.replace("|", "!");
1981 return newStr
.simplified();
1985 * Remove forbidden characters from a file path
1987 const QString
lamexp_clean_filepath(const QString
&str
)
1989 QStringList parts
= QString(str
).replace("\\", "/").split("/");
1991 for(int i
= 0; i
< parts
.count(); i
++)
1993 parts
[i
] = lamexp_clean_filename(parts
[i
]);
1996 return parts
.join("/");
2000 * Get a list of all available Qt Text Codecs
2002 QStringList
lamexp_available_codepages(bool noAliases
)
2004 QStringList codecList
;
2006 QList
<QByteArray
> availableCodecs
= QTextCodec::availableCodecs();
2007 while(!availableCodecs
.isEmpty())
2009 QByteArray current
= availableCodecs
.takeFirst();
2010 if(!(current
.startsWith("system") || current
.startsWith("System")))
2012 codecList
<< QString::fromLatin1(current
.constData(), current
.size());
2015 if(QTextCodec
*currentCodec
= QTextCodec::codecForName(current
.constData()))
2018 QList
<QByteArray
> aliases
= currentCodec
->aliases();
2019 while(!aliases
.isEmpty()) availableCodecs
.removeAll(aliases
.takeFirst());
2029 * Finalization function (final clean-up)
2031 void lamexp_finalization(void)
2033 qDebug("lamexp_finalization()");
2036 if(!g_lamexp_tool_registry
.isEmpty())
2038 QStringList keys
= g_lamexp_tool_registry
.keys();
2039 for(int i
= 0; i
< keys
.count(); i
++)
2041 LAMEXP_DELETE(g_lamexp_tool_registry
[keys
.at(i
)]);
2043 g_lamexp_tool_registry
.clear();
2044 g_lamexp_tool_versions
.clear();
2047 //Delete temporary files
2048 if(!g_lamexp_temp_folder
.isEmpty())
2050 for(int i
= 0; i
< 100; i
++)
2052 if(lamexp_clean_folder(g_lamexp_temp_folder
))
2058 g_lamexp_temp_folder
.clear();
2062 if(g_lamexp_currentTranslator
)
2064 QApplication::removeTranslator(g_lamexp_currentTranslator
);
2065 LAMEXP_DELETE(g_lamexp_currentTranslator
);
2067 g_lamexp_translation
.files
.clear();
2068 g_lamexp_translation
.names
.clear();
2070 //Destroy Qt application object
2071 QApplication
*application
= dynamic_cast<QApplication
*>(QApplication::instance());
2072 LAMEXP_DELETE(application
);
2074 //Detach from shared memory
2075 if(g_lamexp_ipc_ptr
.sharedmem
) g_lamexp_ipc_ptr
.sharedmem
->detach();
2076 LAMEXP_DELETE(g_lamexp_ipc_ptr
.sharedmem
);
2077 LAMEXP_DELETE(g_lamexp_ipc_ptr
.semaphore_read
);
2078 LAMEXP_DELETE(g_lamexp_ipc_ptr
.semaphore_write
);
2079 LAMEXP_DELETE(g_lamexp_ipc_ptr
.semaphore_read_mutex
);
2080 LAMEXP_DELETE(g_lamexp_ipc_ptr
.semaphore_write_mutex
);
2082 //Free STDOUT and STDERR buffers
2083 if(g_lamexp_console_attached
)
2085 if(std::filebuf
*tmp
= dynamic_cast<std::filebuf
*>(std::cout
.rdbuf()))
2087 std::cout
.rdbuf(NULL
);
2090 if(std::filebuf
*tmp
= dynamic_cast<std::filebuf
*>(std::cerr
.rdbuf()))
2092 std::cerr
.rdbuf(NULL
);
2098 if(g_lamexp_log_file
)
2100 fclose(g_lamexp_log_file
);
2101 g_lamexp_log_file
= NULL
;
2106 * Initialize debug thread
2108 static const HANDLE g_debug_thread
= LAMEXP_DEBUG
? NULL
: lamexp_debug_thread_init();
2111 * Get number private bytes [debug only]
2113 SIZE_T
lamexp_dbg_private_bytes(void)
2116 PROCESS_MEMORY_COUNTERS_EX memoryCounters
;
2117 memoryCounters
.cb
= sizeof(PROCESS_MEMORY_COUNTERS_EX
);
2118 GetProcessMemoryInfo(GetCurrentProcess(), (PPROCESS_MEMORY_COUNTERS
) &memoryCounters
, sizeof(PROCESS_MEMORY_COUNTERS_EX
));
2119 return memoryCounters
.PrivateUsage
;
2121 throw "Cannot call this function in a non-debug build!";
2122 #endif //LAMEXP_DEBUG