1 ///////////////////////////////////////////////////////////////////////////////
2 // LameXP - Audio Encoder Front-End
3 // Copyright (C) 2004-2011 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>
49 #include "LockedFile.h"
65 //Initialize static Qt plugins
72 ///////////////////////////////////////////////////////////////////////////////
74 ///////////////////////////////////////////////////////////////////////////////
79 unsigned int reserved_1
;
80 unsigned int reserved_2
;
84 ///////////////////////////////////////////////////////////////////////////////
86 ///////////////////////////////////////////////////////////////////////////////
91 unsigned int ver_major
;
92 unsigned int ver_minor
;
93 unsigned int ver_build
;
94 char *ver_release_name
;
105 static QDate g_lamexp_version_date
;
106 static const char *g_lamexp_months
[] = {"Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"};
107 static const char *g_lamexp_version_raw_date
= __DATE__
;
108 static const char *g_lamexp_version_raw_time
= __TIME__
;
110 //Console attached flag
111 static bool g_lamexp_console_attached
= false;
114 //The following code was borrowed from MPC-HC project: http://mpc-hc.sf.net/
115 #if defined(__INTEL_COMPILER)
116 #if (__INTEL_COMPILER >= 1200)
117 static const char *g_lamexp_version_compiler
= "ICL 12.x";
118 #elif (__INTEL_COMPILER >= 1100)
119 static const char *g_lamexp_version_compiler
= = "ICL 11.x";
120 #elif (__INTEL_COMPILER >= 1000)
121 static const char *g_lamexp_version_compiler
= = "ICL 10.x";
123 #error Compiler is not supported!
125 #elif defined(_MSC_VER)
126 #if (_MSC_VER == 1600)
127 #if (_MSC_FULL_VER >= 160040219)
128 static const char *g_lamexp_version_compiler
= "MSVC 2010-SP1";
130 static const char *g_lamexp_version_compiler
= "MSVC 2010";
132 #elif (_MSC_VER == 1500)
133 #if (_MSC_FULL_VER >= 150030729)
134 static const char *g_lamexp_version_compiler
= "MSVC 2008-SP1";
136 static const char *g_lamexp_version_compiler
= "MSVC 2008";
139 #error Compiler is not supported!
142 // Note: /arch:SSE and /arch:SSE2 are only available for the x86 platform
143 #if !defined(_M_X64) && defined(_M_IX86_FP)
144 #if (_M_IX86_FP == 1)
145 LAMEXP_COMPILER_WARNING("SSE instruction set is enabled!")
146 #elif (_M_IX86_FP == 2)
147 LAMEXP_COMPILER_WARNING("SSE2 instruction set is enabled!")
151 #error Compiler is not supported!
154 //Architecture detection
156 static const char *g_lamexp_version_arch
= "x64";
157 #elif defined(_M_IX86)
158 static const char *g_lamexp_version_arch
= "x86";
160 #error Architecture is not supported!
163 //Official web-site URL
164 static const char *g_lamexp_website_url
= "http://lamexp.sourceforge.net/";
165 static const char *g_lamexp_support_url
= "http://forum.doom9.org/showthread.php?t=157726";
167 //Tool versions (expected versions!)
168 static const unsigned int g_lamexp_toolver_neroaac
= VER_LAMEXP_TOOL_NEROAAC
;
169 static const unsigned int g_lamexp_toolver_fhgaacenc
= VER_LAMEXP_TOOL_FHGAACENC
;
172 static QString g_lamexp_temp_folder
;
175 static QMap
<QString
, LockedFile
*> g_lamexp_tool_registry
;
176 static QMap
<QString
, unsigned int> g_lamexp_tool_versions
;
181 QMap
<QString
, QString
> files
;
182 QMap
<QString
, QString
> names
;
183 QMap
<QString
, unsigned int> sysid
;
185 g_lamexp_translation
;
188 static QTranslator
*g_lamexp_currentTranslator
= NULL
;
194 char *semaphore_read
;
195 char *semaphore_write
;
199 "{21A68A42-6923-43bb-9CF6-64BF151942EE}",
200 "{7A605549-F58C-4d78-B4E5-06EFC34F405B}",
201 "{60AA8D04-F6B8-497d-81EB-0F600F4A65B5}"
205 QSharedMemory
*sharedmem
;
206 QSystemSemaphore
*semaphore_read
;
207 QSystemSemaphore
*semaphore_write
;
215 static const char *g_lamexp_imageformats
[] = {"png", "jpg", "gif", "ico", "svg", NULL
};
218 static QMutex g_lamexp_message_mutex
;
221 static const DWORD g_main_thread_id
= GetCurrentThreadId();
224 ///////////////////////////////////////////////////////////////////////////////
226 ///////////////////////////////////////////////////////////////////////////////
231 unsigned int lamexp_version_major(void) { return g_lamexp_version
.ver_major
; }
232 unsigned int lamexp_version_minor(void) { return g_lamexp_version
.ver_minor
; }
233 unsigned int lamexp_version_build(void) { return g_lamexp_version
.ver_build
; }
234 const char *lamexp_version_release(void) { return g_lamexp_version
.ver_release_name
; }
235 const char *lamexp_version_time(void) { return g_lamexp_version_raw_time
; }
236 const char *lamexp_version_compiler(void) { return g_lamexp_version_compiler
; }
237 const char *lamexp_version_arch(void) { return g_lamexp_version_arch
; }
238 unsigned int lamexp_toolver_neroaac(void) { return g_lamexp_toolver_neroaac
; }
239 unsigned int lamexp_toolver_fhgaacenc(void) { return g_lamexp_toolver_fhgaacenc
; }
244 const char *lamexp_website_url(void) { return g_lamexp_website_url
; }
245 const char *lamexp_support_url(void) { return g_lamexp_support_url
; }
248 * Check for Demo (pre-release) version
250 bool lamexp_version_demo(void)
253 bool releaseVersion
= false;
254 if(!strncpy_s(buffer
, 128, g_lamexp_version
.ver_release_name
, _TRUNCATE
))
256 char *context
, *prefix
= strtok_s(buffer
, "-,; ", &context
);
259 releaseVersion
= (!_stricmp(prefix
, "Final")) || (!_stricmp(prefix
, "Hotfix"));
262 return LAMEXP_DEBUG
|| (!releaseVersion
);
266 * Calculate expiration date
268 QDate
lamexp_version_expires(void)
270 return lamexp_version_date().addDays(LAMEXP_DEBUG
? 2 : 30);
274 * Get build date date
276 const QDate
&lamexp_version_date(void)
278 if(!g_lamexp_version_date
.isValid())
283 char *this_token
= NULL
;
284 char *next_token
= NULL
;
286 strncpy_s(temp
, 32, g_lamexp_version_raw_date
, _TRUNCATE
);
287 this_token
= strtok_s(temp
, " ", &next_token
);
289 for(int i
= 0; i
< 3; i
++)
294 for(int j
= 0; j
< 12; j
++)
296 if(!_strcmpi(this_token
, g_lamexp_months
[j
]))
304 date
[i
] = atoi(this_token
);
306 this_token
= strtok_s(NULL
, " ", &next_token
);
310 if(date
[0] >= 0 && date
[1] >= 0 && date
[2] >= 0)
312 g_lamexp_version_date
= QDate(date
[2], date
[0], date
[1]);
316 return g_lamexp_version_date
;
320 * Global exception handler
322 LONG WINAPI
lamexp_exception_handler(__in
struct _EXCEPTION_POINTERS
*ExceptionInfo
)
324 if(GetCurrentThreadId() != g_main_thread_id
)
326 HANDLE mainThread
= OpenThread(THREAD_TERMINATE
, FALSE
, g_main_thread_id
);
327 if(mainThread
) TerminateThread(mainThread
, ULONG_MAX
);
330 FatalAppExit(0, L
"Unhandeled exception handler invoked, application will exit!");
331 TerminateProcess(GetCurrentProcess(), -1);
336 * Invalid parameters handler
338 void lamexp_invalid_param_handler(const wchar_t*, const wchar_t*, const wchar_t*, unsigned int, uintptr_t)
340 if(GetCurrentThreadId() != g_main_thread_id
)
342 HANDLE mainThread
= OpenThread(THREAD_TERMINATE
, FALSE
, g_main_thread_id
);
343 if(mainThread
) TerminateThread(mainThread
, ULONG_MAX
);
347 FatalAppExit(0, L
"Invalid parameter handler invoked, application will exit!");
348 TerminateProcess(GetCurrentProcess(), -1);
352 * Change console text color
354 static void lamexp_console_color(FILE* file
, WORD attributes
)
356 const HANDLE hConsole
= (HANDLE
)(_get_osfhandle(_fileno(file
)));
357 if((hConsole
!= NULL
) && (hConsole
!= INVALID_HANDLE_VALUE
))
359 SetConsoleTextAttribute(hConsole
, attributes
);
366 void lamexp_message_handler(QtMsgType type
, const char *msg
)
368 static const char *GURU_MEDITATION
= "\n\nGURU MEDITATION !!!\n\n";
370 const char *text
= msg
;
371 const char *buffer
= NULL
;
373 QMutexLocker
lock(&g_lamexp_message_mutex
);
375 if((strlen(msg
) > 8) && (_strnicmp(msg
, "@BASE64@", 8) == 0))
377 buffer
= _strdup(QByteArray::fromBase64(msg
+ 8).constData());
378 if(buffer
) text
= buffer
;
381 if(g_lamexp_console_attached
)
383 UINT oldOutputCP
= GetConsoleOutputCP();
384 if(oldOutputCP
!= CP_UTF8
) SetConsoleOutputCP(CP_UTF8
);
392 lamexp_console_color(stderr
, FOREGROUND_RED
| FOREGROUND_INTENSITY
);
393 fprintf(stderr
, GURU_MEDITATION
);
394 fprintf(stderr
, "%s\n", text
);
398 lamexp_console_color(stderr
, FOREGROUND_GREEN
| FOREGROUND_RED
| FOREGROUND_INTENSITY
);
399 fprintf(stderr
, "%s\n", text
);
403 lamexp_console_color(stderr
, FOREGROUND_BLUE
| FOREGROUND_GREEN
| FOREGROUND_RED
| FOREGROUND_INTENSITY
);
404 fprintf(stderr
, "%s\n", text
);
409 lamexp_console_color(stderr
, FOREGROUND_BLUE
| FOREGROUND_GREEN
| FOREGROUND_RED
);
410 if(oldOutputCP
!= CP_UTF8
) SetConsoleOutputCP(oldOutputCP
);
414 char temp
[1024] = {'\0'};
420 _snprintf_s(temp
, 1024, _TRUNCATE
, "[LameXP][C] %s", text
);
423 _snprintf_s(temp
, 1024, _TRUNCATE
, "[LameXP][C] %s", text
);
426 _snprintf_s(temp
, 1024, _TRUNCATE
, "[LameXP][C] %s", text
);
430 char *ptr
= strchr(temp
, '\n');
434 ptr
= strchr(temp
, '\n');
437 strncat_s(temp
, 1024, "\n", _TRUNCATE
);
438 OutputDebugStringA(temp
);
441 if(type
== QtCriticalMsg
|| type
== QtFatalMsg
)
444 MessageBoxW(NULL
, QWCHAR(QString::fromUtf8(text
)), L
"LameXP - GURU MEDITATION", MB_ICONERROR
| MB_TOPMOST
| MB_TASKMODAL
);
445 FatalAppExit(0, L
"The application has encountered a critical error and will exit now!");
446 TerminateProcess(GetCurrentProcess(), -1);
449 LAMEXP_SAFE_FREE(buffer
);
453 * Initialize the console
455 void lamexp_init_console(int argc
, char* argv
[])
457 bool enableConsole
= lamexp_version_demo();
461 for(int i
= 0; i
< argc
; i
++)
463 if(!_stricmp(argv
[i
], "--console"))
465 enableConsole
= true;
467 else if(!_stricmp(argv
[i
], "--no-console"))
469 enableConsole
= false;
476 if(!g_lamexp_console_attached
)
478 if(AllocConsole() != FALSE
)
480 SetConsoleCtrlHandler(NULL
, TRUE
);
481 SetConsoleTitle(L
"LameXP - Audio Encoder Front-End | Debug Console");
482 SetConsoleOutputCP(CP_UTF8
);
483 g_lamexp_console_attached
= true;
487 if(g_lamexp_console_attached
)
489 //-------------------------------------------------------------------
490 //See: http://support.microsoft.com/default.aspx?scid=kb;en-us;105305
491 //-------------------------------------------------------------------
492 const int flags
= _O_WRONLY
| _O_U8TEXT
;
493 int hCrtStdOut
= _open_osfhandle((intptr_t) GetStdHandle(STD_OUTPUT_HANDLE
), flags
);
494 int hCrtStdErr
= _open_osfhandle((intptr_t) GetStdHandle(STD_ERROR_HANDLE
), flags
);
495 FILE *hfStdOut
= (hCrtStdOut
>= 0) ? _fdopen(hCrtStdOut
, "w") : NULL
;
496 FILE *hfStderr
= (hCrtStdErr
>= 0) ? _fdopen(hCrtStdErr
, "w") : NULL
;
497 if(hfStdOut
) *stdout
= *hfStdOut
;
498 if(hfStderr
) *stderr
= *hfStderr
;
501 HWND hwndConsole
= GetConsoleWindow();
503 if((hwndConsole
!= NULL
) && (hwndConsole
!= INVALID_HANDLE_VALUE
))
505 HMENU hMenu
= GetSystemMenu(hwndConsole
, 0);
506 EnableMenuItem(hMenu
, SC_CLOSE
, MF_BYCOMMAND
| MF_GRAYED
);
507 RemoveMenu(hMenu
, SC_CLOSE
, MF_BYCOMMAND
);
509 SetWindowPos(hwndConsole
, HWND_TOP
, 0, 0, 0, 0, SWP_NOMOVE
|SWP_NOSIZE
|SWP_NOZORDER
|SWP_FRAMECHANGED
);
510 SetWindowLong(hwndConsole
, GWL_STYLE
, GetWindowLong(hwndConsole
, GWL_STYLE
) & (~WS_MAXIMIZEBOX
) & (~WS_MINIMIZEBOX
));
511 SetWindowPos(hwndConsole
, HWND_TOP
, 0, 0, 0, 0, SWP_NOMOVE
|SWP_NOSIZE
|SWP_NOZORDER
|SWP_FRAMECHANGED
);
517 * Detect CPU features
519 lamexp_cpu_t
lamexp_detect_cpu_features(int argc
, char **argv
)
521 typedef BOOL (WINAPI
*IsWow64ProcessFun
)(__in HANDLE hProcess
, __out PBOOL Wow64Process
);
522 typedef VOID (WINAPI
*GetNativeSystemInfoFun
)(__out LPSYSTEM_INFO lpSystemInfo
);
524 static IsWow64ProcessFun IsWow64ProcessPtr
= NULL
;
525 static GetNativeSystemInfoFun GetNativeSystemInfoPtr
= NULL
;
527 lamexp_cpu_t features
;
528 SYSTEM_INFO systemInfo
;
529 int CPUInfo
[4] = {-1};
530 char CPUIdentificationString
[0x40];
531 char CPUBrandString
[0x40];
533 memset(&features
, 0, sizeof(lamexp_cpu_t
));
534 memset(&systemInfo
, 0, sizeof(SYSTEM_INFO
));
535 memset(CPUIdentificationString
, 0, sizeof(CPUIdentificationString
));
536 memset(CPUBrandString
, 0, sizeof(CPUBrandString
));
539 memcpy(CPUIdentificationString
, &CPUInfo
[1], sizeof(int));
540 memcpy(CPUIdentificationString
+ 4, &CPUInfo
[3], sizeof(int));
541 memcpy(CPUIdentificationString
+ 8, &CPUInfo
[2], sizeof(int));
542 features
.intel
= (_stricmp(CPUIdentificationString
, "GenuineIntel") == 0);
543 strncpy_s(features
.vendor
, 0x40, CPUIdentificationString
, _TRUNCATE
);
548 features
.mmx
= (CPUInfo
[3] & 0x800000) || false;
549 features
.sse
= (CPUInfo
[3] & 0x2000000) || false;
550 features
.sse2
= (CPUInfo
[3] & 0x4000000) || false;
551 features
.ssse3
= (CPUInfo
[2] & 0x200) || false;
552 features
.sse3
= (CPUInfo
[2] & 0x1) || false;
553 features
.ssse3
= (CPUInfo
[2] & 0x200) || false;
554 features
.stepping
= CPUInfo
[0] & 0xf;
555 features
.model
= ((CPUInfo
[0] >> 4) & 0xf) + (((CPUInfo
[0] >> 16) & 0xf) << 4);
556 features
.family
= ((CPUInfo
[0] >> 8) & 0xf) + ((CPUInfo
[0] >> 20) & 0xff);
559 __cpuid(CPUInfo
, 0x80000000);
560 int nExIds
= max(min(CPUInfo
[0], 0x80000004), 0x80000000);
562 for(int i
= 0x80000002; i
<= nExIds
; ++i
)
568 memcpy(CPUBrandString
, CPUInfo
, sizeof(CPUInfo
));
571 memcpy(CPUBrandString
+ 16, CPUInfo
, sizeof(CPUInfo
));
574 memcpy(CPUBrandString
+ 32, CPUInfo
, sizeof(CPUInfo
));
579 strncpy_s(features
.brand
, 0x40, CPUBrandString
, _TRUNCATE
);
581 if(strlen(features
.brand
) < 1) strncpy_s(features
.brand
, 0x40, "Unknown", _TRUNCATE
);
582 if(strlen(features
.vendor
) < 1) strncpy_s(features
.vendor
, 0x40, "Unknown", _TRUNCATE
);
584 #if !defined(_M_X64 ) && !defined(_M_IA64)
585 if(!IsWow64ProcessPtr
|| !GetNativeSystemInfoPtr
)
587 QLibrary
Kernel32Lib("kernel32.dll");
588 IsWow64ProcessPtr
= (IsWow64ProcessFun
) Kernel32Lib
.resolve("IsWow64Process");
589 GetNativeSystemInfoPtr
= (GetNativeSystemInfoFun
) Kernel32Lib
.resolve("GetNativeSystemInfo");
591 if(IsWow64ProcessPtr
)
594 if(IsWow64ProcessPtr(GetCurrentProcess(), &x64
))
599 if(GetNativeSystemInfoPtr
)
601 GetNativeSystemInfoPtr(&systemInfo
);
605 GetSystemInfo(&systemInfo
);
607 features
.count
= systemInfo
.dwNumberOfProcessors
;
609 GetNativeSystemInfo(&systemInfo
);
610 features
.count
= systemInfo
.dwNumberOfProcessors
;
616 for(int i
= 0; i
< argc
; i
++)
618 if(!_stricmp("--force-cpu-no-64bit", argv
[i
])) features
.x64
= false;
619 if(!_stricmp("--force-cpu-no-sse", argv
[i
])) features
.sse
= features
.sse2
= features
.sse3
= features
.ssse3
= false;
620 if(!_stricmp("--force-cpu-no-intel", argv
[i
])) features
.intel
= false;
628 * Check for debugger (detect routine)
630 static bool lamexp_check_for_debugger(void)
636 __except(GetExceptionCode() == EXCEPTION_BREAKPOINT
? EXCEPTION_EXECUTE_HANDLER
: EXCEPTION_CONTINUE_SEARCH
)
644 * Check for debugger (thread proc)
646 static void WINAPI
lamexp_debug_thread_proc(__in LPVOID lpParameter
)
648 while(!(IsDebuggerPresent() || lamexp_check_for_debugger()))
652 TerminateProcess(GetCurrentProcess(), -1);
656 * Check for debugger (startup routine)
658 static HANDLE
lamexp_debug_thread_init(void)
660 if(IsDebuggerPresent() || lamexp_check_for_debugger())
662 FatalAppExit(0, L
"Not a debug build. Please unload debugger and try again!");
663 TerminateProcess(GetCurrentProcess(), -1);
666 return CreateThread(NULL
, NULL
, reinterpret_cast<LPTHREAD_START_ROUTINE
>(&lamexp_debug_thread_proc
), NULL
, NULL
, NULL
);
670 * Check for compatibility mode
672 static bool lamexp_check_compatibility_mode(const char *exportName
, const char *executableName
)
674 QLibrary
kernel32("kernel32.dll");
676 if(exportName
!= NULL
)
678 if(kernel32
.resolve(exportName
) != NULL
)
680 qWarning("Function '%s' exported from 'kernel32.dll' -> Windows compatibility mode!", exportName
);
681 qFatal("%s", QApplication::tr("Executable '%1' doesn't support Windows compatibility mode.").arg(QString::fromLatin1(executableName
)).toLatin1().constData());
690 * Check for process elevation
692 static bool lamexp_check_elevation(void)
694 typedef enum { lamexp_token_elevationType_class
= 18, lamexp_token_elevation_class
= 20 } LAMEXP_TOKEN_INFORMATION_CLASS
;
695 typedef enum { lamexp_elevationType_default
= 1, lamexp_elevationType_full
, lamexp_elevationType_limited
} LAMEXP_TOKEN_ELEVATION_TYPE
;
697 HANDLE hToken
= NULL
;
698 bool bIsProcessElevated
= false;
700 if(OpenProcessToken(GetCurrentProcess(), TOKEN_QUERY
, &hToken
))
702 LAMEXP_TOKEN_ELEVATION_TYPE tokenElevationType
;
704 if(GetTokenInformation(hToken
, (TOKEN_INFORMATION_CLASS
) lamexp_token_elevationType_class
, &tokenElevationType
, sizeof(LAMEXP_TOKEN_ELEVATION_TYPE
), &returnLength
))
706 if(returnLength
== sizeof(LAMEXP_TOKEN_ELEVATION_TYPE
))
708 switch(tokenElevationType
)
710 case lamexp_elevationType_default
:
711 qDebug("Process token elevation type: Default -> UAC is disabled.\n");
713 case lamexp_elevationType_full
:
714 qWarning("Process token elevation type: Full -> potential security risk!\n");
715 bIsProcessElevated
= true;
717 case lamexp_elevationType_limited
:
718 qDebug("Process token elevation type: Limited -> not elevated.\n");
727 qWarning("Failed to open process token!");
730 return !bIsProcessElevated
;
734 * Initialize Qt framework
736 bool lamexp_init_qt(int argc
, char* argv
[])
738 static bool qt_initialized
= false;
740 typedef BOOL (WINAPI
*SetDllDirectoryProc
)(WCHAR
*lpPathName
);
742 //Don't initialized again, if done already
749 QLibrary
kernel32("kernel32.dll");
752 SetDllDirectoryProc pSetDllDirectory
= (SetDllDirectoryProc
) kernel32
.resolve("SetDllDirectoryW");
753 if(pSetDllDirectory
!= NULL
) pSetDllDirectory(L
"");
757 //Extract executable name from argv[] array
758 char *executableName
= argv
[0];
759 while(char *temp
= strpbrk(executableName
, "\\/:?"))
761 executableName
= temp
+ 1;
765 qDebug("Using Qt Framework v%s, compiled with Qt v%s [%s]", qVersion(), QT_VERSION_STR
, QT_PACKAGEDATE_STR
);
766 if(_stricmp(qVersion(), QT_VERSION_STR
))
768 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());
772 //Check the Windows version
773 switch(QSysInfo::windowsVersion() & QSysInfo::WV_NT_based
)
776 case QSysInfo::WV_NT
:
777 qFatal("%s", QApplication::tr("Executable '%1' requires Windows 2000 or later.").arg(QString::fromLatin1(executableName
)).toLatin1().constData());
779 case QSysInfo::WV_2000
:
780 qDebug("Running on Windows 2000 (not officially supported!).\n");
781 lamexp_check_compatibility_mode("GetNativeSystemInfo", executableName
);
783 case QSysInfo::WV_XP
:
784 qDebug("Running on Windows XP.\n");
785 lamexp_check_compatibility_mode("GetLargePageMinimum", executableName
);
787 case QSysInfo::WV_2003
:
788 qDebug("Running on Windows Server 2003 or Windows XP x64-Edition.\n");
789 lamexp_check_compatibility_mode("GetLocaleInfoEx", executableName
);
791 case QSysInfo::WV_VISTA
:
792 qDebug("Running on Windows Vista or Windows Server 2008.\n");
793 lamexp_check_compatibility_mode("CreateRemoteThreadEx", executableName
);
795 case QSysInfo::WV_WINDOWS7
:
796 qDebug("Running on Windows 7 or Windows Server 2008 R2.\n");
797 lamexp_check_compatibility_mode(NULL
, executableName
);
800 qWarning("Running on an unknown/untested WinNT-based OS.\n");
805 QLibrary
ntdll("ntdll.dll");
808 if(ntdll
.resolve("wine_nt_to_unix_file_name") != NULL
) isWine
= true;
809 if(ntdll
.resolve("wine_get_version") != NULL
) isWine
= true;
810 if(isWine
) qWarning("It appears we are running under Wine, unexpected things might happen!\n");
814 //Create Qt application instance and setup version info
815 QDate date
= QDate::currentDate();
816 QApplication
*application
= new QApplication(argc
, argv
);
817 application
->setApplicationName("LameXP - Audio Encoder Front-End");
818 application
->setApplicationVersion(QString().sprintf("%d.%02d.%04d", lamexp_version_major(), lamexp_version_minor(), lamexp_version_build()));
819 application
->setOrganizationName("LoRd_MuldeR");
820 application
->setOrganizationDomain("mulder.at.gg");
821 application
->setWindowIcon((date
.month() == 12 && date
.day() >= 24 && date
.day() <= 26) ? QIcon(":/MainIcon2.png") : QIcon(":/MainIcon.png"));
823 //Load plugins from application directory
824 QCoreApplication::setLibraryPaths(QStringList() << QApplication::applicationDirPath());
825 qDebug("Library Path:\n%s\n", QApplication::libraryPaths().first().toUtf8().constData());
827 //Check for supported image formats
828 QList
<QByteArray
> supportedFormats
= QImageReader::supportedImageFormats();
829 for(int i
= 0; g_lamexp_imageformats
[i
]; i
++)
831 if(!supportedFormats
.contains(g_lamexp_imageformats
[i
]))
833 qFatal("Qt initialization error: QImageIOHandler for '%s' missing!", g_lamexp_imageformats
[i
]);
838 //Add default translations
839 g_lamexp_translation
.files
.insert(LAMEXP_DEFAULT_LANGID
, "");
840 g_lamexp_translation
.names
.insert(LAMEXP_DEFAULT_LANGID
, "English");
842 //Check for process elevation
843 if(!lamexp_check_elevation())
845 if(QMessageBox::warning(NULL
, "LameXP", "<nobr>LameXP was started with elevated rights. This is a potential security risk!</nobr>", "Quit Program (Recommended)", "Ignore") == 0)
851 //Update console icon, if a console is attached
852 if(g_lamexp_console_attached
&& !isWine
)
854 typedef DWORD (__stdcall
*SetConsoleIconFun
)(HICON
);
855 QLibrary
kernel32("kernel32.dll");
858 SetConsoleIconFun SetConsoleIconPtr
= (SetConsoleIconFun
) kernel32
.resolve("SetConsoleIcon");
859 if(SetConsoleIconPtr
!= NULL
) SetConsoleIconPtr(QIcon(":/icons/sound.png").pixmap(16, 16).toWinHICON());
865 qt_initialized
= true;
872 int lamexp_init_ipc(void)
874 if(g_lamexp_ipc_ptr
.sharedmem
&& g_lamexp_ipc_ptr
.semaphore_read
&& g_lamexp_ipc_ptr
.semaphore_write
)
879 g_lamexp_ipc_ptr
.semaphore_read
= new QSystemSemaphore(QString(g_lamexp_ipc_uuid
.semaphore_read
), 0);
880 g_lamexp_ipc_ptr
.semaphore_write
= new QSystemSemaphore(QString(g_lamexp_ipc_uuid
.semaphore_write
), 0);
882 if(g_lamexp_ipc_ptr
.semaphore_read
->error() != QSystemSemaphore::NoError
)
884 QString errorMessage
= g_lamexp_ipc_ptr
.semaphore_read
->errorString();
885 LAMEXP_DELETE(g_lamexp_ipc_ptr
.semaphore_read
);
886 LAMEXP_DELETE(g_lamexp_ipc_ptr
.semaphore_write
);
887 qFatal("Failed to create system smaphore: %s", errorMessage
.toUtf8().constData());
890 if(g_lamexp_ipc_ptr
.semaphore_write
->error() != QSystemSemaphore::NoError
)
892 QString errorMessage
= g_lamexp_ipc_ptr
.semaphore_write
->errorString();
893 LAMEXP_DELETE(g_lamexp_ipc_ptr
.semaphore_read
);
894 LAMEXP_DELETE(g_lamexp_ipc_ptr
.semaphore_write
);
895 qFatal("Failed to create system smaphore: %s", errorMessage
.toUtf8().constData());
899 g_lamexp_ipc_ptr
.sharedmem
= new QSharedMemory(QString(g_lamexp_ipc_uuid
.sharedmem
), NULL
);
901 if(!g_lamexp_ipc_ptr
.sharedmem
->create(sizeof(lamexp_ipc_t
)))
903 if(g_lamexp_ipc_ptr
.sharedmem
->error() == QSharedMemory::AlreadyExists
)
905 g_lamexp_ipc_ptr
.sharedmem
->attach();
906 if(g_lamexp_ipc_ptr
.sharedmem
->error() == QSharedMemory::NoError
)
912 QString errorMessage
= g_lamexp_ipc_ptr
.sharedmem
->errorString();
913 qFatal("Failed to attach to shared memory: %s", errorMessage
.toUtf8().constData());
919 QString errorMessage
= g_lamexp_ipc_ptr
.sharedmem
->errorString();
920 qFatal("Failed to create shared memory: %s", errorMessage
.toUtf8().constData());
925 memset(g_lamexp_ipc_ptr
.sharedmem
->data(), 0, sizeof(lamexp_ipc_t
));
926 g_lamexp_ipc_ptr
.semaphore_write
->release();
934 void lamexp_ipc_send(unsigned int command
, const char* message
)
936 if(!g_lamexp_ipc_ptr
.sharedmem
|| !g_lamexp_ipc_ptr
.semaphore_read
|| !g_lamexp_ipc_ptr
.semaphore_write
)
938 throw "Shared memory for IPC not initialized yet.";
941 lamexp_ipc_t
*lamexp_ipc
= new lamexp_ipc_t
;
942 memset(lamexp_ipc
, 0, sizeof(lamexp_ipc_t
));
943 lamexp_ipc
->command
= command
;
946 strncpy_s(lamexp_ipc
->parameter
, 4096, message
, _TRUNCATE
);
949 if(g_lamexp_ipc_ptr
.semaphore_write
->acquire())
951 memcpy(g_lamexp_ipc_ptr
.sharedmem
->data(), lamexp_ipc
, sizeof(lamexp_ipc_t
));
952 g_lamexp_ipc_ptr
.semaphore_read
->release();
955 LAMEXP_DELETE(lamexp_ipc
);
961 void lamexp_ipc_read(unsigned int *command
, char* message
, size_t buffSize
)
966 if(!g_lamexp_ipc_ptr
.sharedmem
|| !g_lamexp_ipc_ptr
.semaphore_read
|| !g_lamexp_ipc_ptr
.semaphore_write
)
968 throw "Shared memory for IPC not initialized yet.";
971 lamexp_ipc_t
*lamexp_ipc
= new lamexp_ipc_t
;
972 memset(lamexp_ipc
, 0, sizeof(lamexp_ipc_t
));
974 if(g_lamexp_ipc_ptr
.semaphore_read
->acquire())
976 memcpy(lamexp_ipc
, g_lamexp_ipc_ptr
.sharedmem
->data(), sizeof(lamexp_ipc_t
));
977 g_lamexp_ipc_ptr
.semaphore_write
->release();
979 if(!(lamexp_ipc
->reserved_1
|| lamexp_ipc
->reserved_2
))
981 *command
= lamexp_ipc
->command
;
982 strncpy_s(message
, buffSize
, lamexp_ipc
->parameter
, _TRUNCATE
);
986 qWarning("Malformed IPC message, will be ignored");
990 LAMEXP_DELETE(lamexp_ipc
);
994 * Check for LameXP "portable" mode
996 bool lamexp_portable_mode(void)
998 QString baseName
= QFileInfo(QApplication::applicationFilePath()).completeBaseName();
999 int idx1
= baseName
.indexOf("lamexp", 0, Qt::CaseInsensitive
);
1000 int idx2
= baseName
.lastIndexOf("portable", -1, Qt::CaseInsensitive
);
1001 return (idx1
>= 0) && (idx2
>= 0) && (idx1
< idx2
);
1005 * Get a random string
1007 QString
lamexp_rand_str(void)
1009 QRegExp
regExp("\\{(\\w+)-(\\w+)-(\\w+)-(\\w+)-(\\w+)\\}");
1010 QString uuid
= QUuid::createUuid().toString();
1012 if(regExp
.indexIn(uuid
) >= 0)
1014 return QString().append(regExp
.cap(1)).append(regExp
.cap(2)).append(regExp
.cap(3)).append(regExp
.cap(4)).append(regExp
.cap(5));
1017 throw "The RegExp didn't match on the UUID string. This shouldn't happen ;-)";
1021 * Get LameXP temp folder
1023 const QString
&lamexp_temp_folder2(void)
1025 static const char *TEMP_STR
= "Temp";
1026 const QString WRITE_TEST_DATA
= lamexp_rand_str();
1027 const QString SUB_FOLDER
= lamexp_rand_str();
1029 //Already initialized?
1030 if(!g_lamexp_temp_folder
.isEmpty())
1032 if(QDir(g_lamexp_temp_folder
).exists())
1034 return g_lamexp_temp_folder
;
1038 g_lamexp_temp_folder
.clear();
1042 //Try the %TMP% or %TEMP% directory first
1043 QDir temp
= QDir::temp();
1046 temp
.mkdir(SUB_FOLDER
);
1047 if(temp
.cd(SUB_FOLDER
) && temp
.exists())
1049 QFile
testFile(QString("%1/~%2.tmp").arg(temp
.canonicalPath(), lamexp_rand_str()));
1050 if(testFile
.open(QIODevice::ReadWrite
))
1052 if(testFile
.write(WRITE_TEST_DATA
.toLatin1().constData()) >= strlen(WRITE_TEST_DATA
.toLatin1().constData()))
1054 g_lamexp_temp_folder
= temp
.canonicalPath();
1059 if(!g_lamexp_temp_folder
.isEmpty())
1061 return g_lamexp_temp_folder
;
1065 //Create TEMP folder in %LOCALAPPDATA%
1066 QDir localAppData
= QDir(lamexp_known_folder(lamexp_folder_localappdata
));
1067 if(!localAppData
.path().isEmpty())
1069 if(!localAppData
.exists())
1071 localAppData
.mkpath(".");
1073 if(localAppData
.exists())
1075 if(!localAppData
.entryList(QDir::AllDirs
).contains(TEMP_STR
, Qt::CaseInsensitive
))
1077 localAppData
.mkdir(TEMP_STR
);
1079 if(localAppData
.cd(TEMP_STR
) && localAppData
.exists())
1081 localAppData
.mkdir(SUB_FOLDER
);
1082 if(localAppData
.cd(SUB_FOLDER
) && localAppData
.exists())
1084 QFile
testFile(QString("%1/~%2.tmp").arg(localAppData
.canonicalPath(), lamexp_rand_str()));
1085 if(testFile
.open(QIODevice::ReadWrite
))
1087 if(testFile
.write(WRITE_TEST_DATA
.toLatin1().constData()) >= strlen(WRITE_TEST_DATA
.toLatin1().constData()))
1089 g_lamexp_temp_folder
= localAppData
.canonicalPath();
1096 if(!g_lamexp_temp_folder
.isEmpty())
1098 return g_lamexp_temp_folder
;
1102 //Failed to create TEMP folder!
1103 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());
1104 return g_lamexp_temp_folder
;
1110 bool lamexp_clean_folder(const QString
&folderPath
)
1112 QDir
tempFolder(folderPath
);
1113 QFileInfoList entryList
= tempFolder
.entryInfoList(QDir::AllEntries
| QDir::NoDotAndDotDot
);
1115 for(int i
= 0; i
< entryList
.count(); i
++)
1117 if(entryList
.at(i
).isDir())
1119 lamexp_clean_folder(entryList
.at(i
).canonicalFilePath());
1123 for(int j
= 0; j
< 3; j
++)
1125 if(lamexp_remove_file(entryList
.at(i
).canonicalFilePath()))
1133 tempFolder
.rmdir(".");
1134 return !tempFolder
.exists();
1140 void lamexp_register_tool(const QString
&toolName
, LockedFile
*file
, unsigned int version
)
1142 if(g_lamexp_tool_registry
.contains(toolName
.toLower()))
1144 throw "lamexp_register_tool: Tool is already registered!";
1147 g_lamexp_tool_registry
.insert(toolName
.toLower(), file
);
1148 g_lamexp_tool_versions
.insert(toolName
.toLower(), version
);
1154 bool lamexp_check_tool(const QString
&toolName
)
1156 return g_lamexp_tool_registry
.contains(toolName
.toLower());
1162 const QString
lamexp_lookup_tool(const QString
&toolName
)
1164 if(g_lamexp_tool_registry
.contains(toolName
.toLower()))
1166 return g_lamexp_tool_registry
.value(toolName
.toLower())->filePath();
1175 * Lookup tool version
1177 unsigned int lamexp_tool_version(const QString
&toolName
)
1179 if(g_lamexp_tool_versions
.contains(toolName
.toLower()))
1181 return g_lamexp_tool_versions
.value(toolName
.toLower());
1190 * Version number to human-readable string
1192 const QString
lamexp_version2string(const QString
&pattern
, unsigned int version
, const QString
&defaultText
)
1194 if(version
== UINT_MAX
)
1199 QString result
= pattern
;
1200 int digits
= result
.count("?", Qt::CaseInsensitive
);
1208 QString versionStr
= QString().sprintf(QString().sprintf("%%0%du", digits
).toLatin1().constData(), version
);
1209 int index
= result
.indexOf("?", Qt::CaseInsensitive
);
1211 while(index
>= 0 && pos
< versionStr
.length())
1213 result
[index
] = versionStr
[pos
++];
1214 index
= result
.indexOf("?", Qt::CaseInsensitive
);
1221 * Register a new translation
1223 bool lamexp_translation_register(const QString
&langId
, const QString
&qmFile
, const QString
&langName
, unsigned int &systemId
)
1225 if(qmFile
.isEmpty() || langName
.isEmpty() || systemId
< 1)
1230 g_lamexp_translation
.files
.insert(langId
, qmFile
);
1231 g_lamexp_translation
.names
.insert(langId
, langName
);
1232 g_lamexp_translation
.sysid
.insert(langId
, systemId
);
1238 * Get list of all translations
1240 QStringList
lamexp_query_translations(void)
1242 return g_lamexp_translation
.files
.keys();
1246 * Get translation name
1248 QString
lamexp_translation_name(const QString
&langId
)
1250 return g_lamexp_translation
.names
.value(langId
.toLower(), QString());
1254 * Get translation system id
1256 unsigned int lamexp_translation_sysid(const QString
&langId
)
1258 return g_lamexp_translation
.sysid
.value(langId
.toLower(), 0);
1262 * Install a new translator
1264 bool lamexp_install_translator(const QString
&langId
)
1266 bool success
= false;
1268 if(langId
.isEmpty() || langId
.toLower().compare(LAMEXP_DEFAULT_LANGID
) == 0)
1270 success
= lamexp_install_translator_from_file(QString());
1274 QString qmFile
= g_lamexp_translation
.files
.value(langId
.toLower(), QString());
1275 if(!qmFile
.isEmpty())
1277 success
= lamexp_install_translator_from_file(QString(":/localization/%1").arg(qmFile
));
1281 qWarning("Translation '%s' not available!", langId
.toLatin1().constData());
1289 * Install a new translator from file
1291 bool lamexp_install_translator_from_file(const QString
&qmFile
)
1293 bool success
= false;
1295 if(!g_lamexp_currentTranslator
)
1297 g_lamexp_currentTranslator
= new QTranslator();
1300 if(!qmFile
.isEmpty())
1302 QString qmPath
= QFileInfo(qmFile
).canonicalFilePath();
1303 QApplication::removeTranslator(g_lamexp_currentTranslator
);
1304 success
= g_lamexp_currentTranslator
->load(qmPath
);
1305 QApplication::installTranslator(g_lamexp_currentTranslator
);
1308 qWarning("Failed to load translation:\n\"%s\"", qmPath
.toLatin1().constData());
1313 QApplication::removeTranslator(g_lamexp_currentTranslator
);
1321 * Locate known folder on local system
1323 QString
lamexp_known_folder(lamexp_known_folder_t folder_id
)
1325 typedef HRESULT (WINAPI
*SHGetKnownFolderPathFun
)(__in
const GUID
&rfid
, __in DWORD dwFlags
, __in HANDLE hToken
, __out PWSTR
*ppszPath
);
1326 typedef HRESULT (WINAPI
*SHGetFolderPathFun
)(__in HWND hwndOwner
, __in
int nFolder
, __in HANDLE hToken
, __in DWORD dwFlags
, __out LPWSTR pszPath
);
1328 static const int CSIDL_LOCAL_APPDATA
= 0x001c;
1329 static const int CSIDL_PROGRAM_FILES
= 0x0026;
1330 static const int CSIDL_SYSTEM_FOLDER
= 0x0025;
1331 static const GUID GUID_LOCAL_APPDATA
= {0xF1B32785,0x6FBA,0x4FCF,{0x9D,0x55,0x7B,0x8E,0x7F,0x15,0x70,0x91}};
1332 static const GUID GUID_LOCAL_APPDATA_LOW
= {0xA520A1A4,0x1780,0x4FF6,{0xBD,0x18,0x16,0x73,0x43,0xC5,0xAF,0x16}};
1333 static const GUID GUID_PROGRAM_FILES
= {0x905e63b6,0xc1bf,0x494e,{0xb2,0x9c,0x65,0xb7,0x32,0xd3,0xd2,0x1a}};
1334 static const GUID GUID_SYSTEM_FOLDER
= {0x1AC14E77,0x02E7,0x4E5D,{0xB7,0x44,0x2E,0xB1,0xAE,0x51,0x98,0xB7}};
1336 static QLibrary
*Kernel32Lib
= NULL
;
1337 static SHGetKnownFolderPathFun SHGetKnownFolderPathPtr
= NULL
;
1338 static SHGetFolderPathFun SHGetFolderPathPtr
= NULL
;
1340 if((!SHGetKnownFolderPathPtr
) && (!SHGetFolderPathPtr
))
1342 if(!Kernel32Lib
) Kernel32Lib
= new QLibrary("shell32.dll");
1343 SHGetKnownFolderPathPtr
= (SHGetKnownFolderPathFun
) Kernel32Lib
->resolve("SHGetKnownFolderPath");
1344 SHGetFolderPathPtr
= (SHGetFolderPathFun
) Kernel32Lib
->resolve("SHGetFolderPathW");
1347 int folderCSIDL
= -1;
1348 GUID folderGUID
= {0x0000,0x0000,0x0000,{0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00}};
1352 case lamexp_folder_localappdata
:
1353 folderCSIDL
= CSIDL_LOCAL_APPDATA
;
1354 folderGUID
= GUID_LOCAL_APPDATA
;
1356 case lamexp_folder_programfiles
:
1357 folderCSIDL
= CSIDL_PROGRAM_FILES
;
1358 folderGUID
= GUID_PROGRAM_FILES
;
1360 case lamexp_folder_systemfolder
:
1361 folderCSIDL
= CSIDL_SYSTEM_FOLDER
;
1362 folderGUID
= GUID_SYSTEM_FOLDER
;
1371 if(SHGetKnownFolderPathPtr
)
1374 if(SHGetKnownFolderPathPtr(folderGUID
, 0x00008000, NULL
, &path
) == S_OK
)
1376 //MessageBoxW(0, path, L"SHGetKnownFolderPath", MB_TOPMOST);
1377 QDir folderTemp
= QDir(QDir::fromNativeSeparators(QString::fromUtf16(reinterpret_cast<const unsigned short*>(path
))));
1378 if(!folderTemp
.exists())
1380 folderTemp
.mkpath(".");
1382 if(folderTemp
.exists())
1384 folder
= folderTemp
.canonicalPath();
1386 CoTaskMemFree(path
);
1389 else if(SHGetFolderPathPtr
)
1391 WCHAR
*path
= new WCHAR
[4096];
1392 if(SHGetFolderPathPtr(NULL
, folderCSIDL
, NULL
, NULL
, path
) == S_OK
)
1394 //MessageBoxW(0, path, L"SHGetFolderPathW", MB_TOPMOST);
1395 QDir folderTemp
= QDir(QDir::fromNativeSeparators(QString::fromUtf16(reinterpret_cast<const unsigned short*>(path
))));
1396 if(!folderTemp
.exists())
1398 folderTemp
.mkpath(".");
1400 if(folderTemp
.exists())
1402 folder
= folderTemp
.canonicalPath();
1412 * Safely remove a file
1414 bool lamexp_remove_file(const QString
&filename
)
1416 if(!QFileInfo(filename
).exists() || !QFileInfo(filename
).isFile())
1422 if(!QFile::remove(filename
))
1424 DWORD attributes
= GetFileAttributesW(QWCHAR(filename
));
1425 SetFileAttributesW(QWCHAR(filename
), (attributes
& (~FILE_ATTRIBUTE_READONLY
)));
1426 if(!QFile::remove(filename
))
1428 qWarning("Could not delete \"%s\"", filename
.toLatin1().constData());
1444 * Check if visual themes are enabled (WinXP and later)
1446 bool lamexp_themes_enabled(void)
1448 typedef int (WINAPI
*IsAppThemedFun
)(void);
1450 bool isAppThemed
= false;
1451 QLibrary
uxTheme(QString("%1/UxTheme.dll").arg(lamexp_known_folder(lamexp_folder_systemfolder
)));
1452 IsAppThemedFun IsAppThemedPtr
= (IsAppThemedFun
) uxTheme
.resolve("IsAppThemed");
1456 isAppThemed
= IsAppThemedPtr();
1459 qWarning("Theme support is disabled for this process!");
1467 * Get number of free bytes on disk
1469 __int64
lamexp_free_diskspace(const QString
&path
)
1471 ULARGE_INTEGER freeBytesAvailable
, totalNumberOfBytes
, totalNumberOfFreeBytes
;
1472 if(GetDiskFreeSpaceExW(reinterpret_cast<const wchar_t*>(QDir::toNativeSeparators(path
).utf16()), &freeBytesAvailable
, &totalNumberOfBytes
, &totalNumberOfFreeBytes
))
1474 return freeBytesAvailable
.QuadPart
;
1483 * Shutdown the computer
1485 bool lamexp_shutdown_computer(const QString
&message
, const unsigned long timeout
, const bool forceShutdown
)
1487 HANDLE hToken
= NULL
;
1489 if(OpenProcessToken(GetCurrentProcess(), TOKEN_ADJUST_PRIVILEGES
| TOKEN_QUERY
, &hToken
))
1491 TOKEN_PRIVILEGES privileges
;
1492 memset(&privileges
, 0, sizeof(TOKEN_PRIVILEGES
));
1493 privileges
.PrivilegeCount
= 1;
1494 privileges
.Privileges
[0].Attributes
= SE_PRIVILEGE_ENABLED
;
1496 if(LookupPrivilegeValue(NULL
, SE_SHUTDOWN_NAME
, &privileges
.Privileges
[0].Luid
))
1498 if(AdjustTokenPrivileges(hToken
, FALSE
, &privileges
, NULL
, NULL
, NULL
))
1500 const DWORD reason
= SHTDN_REASON_MAJOR_APPLICATION
| SHTDN_REASON_FLAG_PLANNED
;
1501 return InitiateSystemShutdownEx(NULL
, const_cast<wchar_t*>(QWCHAR(message
)), timeout
, forceShutdown
, FALSE
, reason
);
1510 * Make a window blink (to draw user's attention)
1512 void lamexp_blink_window(QWidget
*poWindow
, unsigned int count
, unsigned int delay
)
1514 static QMutex blinkMutex
;
1516 const double maxOpac
= 1.0;
1517 const double minOpac
= 0.3;
1518 const double delOpac
= 0.1;
1520 if(!blinkMutex
.tryLock())
1522 qWarning("Blinking is already in progress, skipping!");
1528 const int steps
= static_cast<int>(ceil(maxOpac
- minOpac
) / delOpac
);
1529 const int sleep
= static_cast<int>(floor(static_cast<double>(delay
) / static_cast<double>(steps
)));
1530 const double opacity
= poWindow
->windowOpacity();
1532 for(unsigned int i
= 0; i
< count
; i
++)
1534 for(double x
= maxOpac
; x
>= minOpac
; x
-= delOpac
)
1536 poWindow
->setWindowOpacity(x
);
1537 QApplication::processEvents();
1541 for(double x
= minOpac
; x
<= maxOpac
; x
+= delOpac
)
1543 poWindow
->setWindowOpacity(x
);
1544 QApplication::processEvents();
1549 poWindow
->setWindowOpacity(opacity
);
1550 QApplication::processEvents();
1551 blinkMutex
.unlock();
1555 blinkMutex
.unlock();
1556 qWarning("Exception error while blinking!");
1561 * Remove forbidden characters from a filename
1563 const QString
lamexp_clean_filename(const QString
&str
)
1565 QString
newStr(str
);
1567 newStr
.replace("\\", "-");
1568 newStr
.replace(" / ", ", ");
1569 newStr
.replace("/", ",");
1570 newStr
.replace(":", "-");
1571 newStr
.replace("*", "x");
1572 newStr
.replace("?", "");
1573 newStr
.replace("<", "[");
1574 newStr
.replace(">", "]");
1575 newStr
.replace("|", "!");
1577 return newStr
.simplified();
1581 * Remove forbidden characters from a file path
1583 const QString
lamexp_clean_filepath(const QString
&str
)
1585 QStringList parts
= QString(str
).replace("\\", "/").split("/");
1587 for(int i
= 0; i
< parts
.count(); i
++)
1589 parts
[i
] = lamexp_clean_filename(parts
[i
]);
1592 return parts
.join("/");
1596 * Finalization function (final clean-up)
1598 void lamexp_finalization(void)
1601 if(!g_lamexp_tool_registry
.isEmpty())
1603 QStringList keys
= g_lamexp_tool_registry
.keys();
1604 for(int i
= 0; i
< keys
.count(); i
++)
1606 LAMEXP_DELETE(g_lamexp_tool_registry
[keys
.at(i
)]);
1608 g_lamexp_tool_registry
.clear();
1609 g_lamexp_tool_versions
.clear();
1612 //Delete temporary files
1613 if(!g_lamexp_temp_folder
.isEmpty())
1615 for(int i
= 0; i
< 100; i
++)
1617 if(lamexp_clean_folder(g_lamexp_temp_folder
))
1623 g_lamexp_temp_folder
.clear();
1627 if(g_lamexp_currentTranslator
)
1629 QApplication::removeTranslator(g_lamexp_currentTranslator
);
1630 LAMEXP_DELETE(g_lamexp_currentTranslator
);
1632 g_lamexp_translation
.files
.clear();
1633 g_lamexp_translation
.names
.clear();
1635 //Destroy Qt application object
1636 QApplication
*application
= dynamic_cast<QApplication
*>(QApplication::instance());
1637 LAMEXP_DELETE(application
);
1639 //Detach from shared memory
1640 if(g_lamexp_ipc_ptr
.sharedmem
) g_lamexp_ipc_ptr
.sharedmem
->detach();
1641 LAMEXP_DELETE(g_lamexp_ipc_ptr
.sharedmem
);
1642 LAMEXP_DELETE(g_lamexp_ipc_ptr
.semaphore_read
);
1643 LAMEXP_DELETE(g_lamexp_ipc_ptr
.semaphore_write
);
1647 * Initialize debug thread
1649 static const HANDLE g_debug_thread
= LAMEXP_DEBUG
? NULL
: lamexp_debug_thread_init();
1652 * Get number private bytes [debug only]
1654 SIZE_T
lamexp_dbg_private_bytes(void)
1657 PROCESS_MEMORY_COUNTERS_EX memoryCounters
;
1658 memoryCounters
.cb
= sizeof(PROCESS_MEMORY_COUNTERS_EX
);
1659 GetProcessMemoryInfo(GetCurrentProcess(), (PPROCESS_MEMORY_COUNTERS
) &memoryCounters
, sizeof(PROCESS_MEMORY_COUNTERS_EX
));
1660 return memoryCounters
.PrivateUsage
;
1662 throw "Cannot call this function in a non-debug build!";
1663 #endif //LAMEXP_DEBUG