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>
46 #include <QLibraryInfo>
50 #include "LockedFile.h"
69 //Initialize static Qt plugins
75 ///////////////////////////////////////////////////////////////////////////////
77 ///////////////////////////////////////////////////////////////////////////////
82 unsigned int reserved_1
;
83 unsigned int reserved_2
;
87 ///////////////////////////////////////////////////////////////////////////////
89 ///////////////////////////////////////////////////////////////////////////////
94 unsigned int ver_major
;
95 unsigned int ver_minor
;
96 unsigned int ver_build
;
97 char *ver_release_name
;
108 static QDate g_lamexp_version_date
;
109 static const char *g_lamexp_months
[] = {"Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"};
110 static const char *g_lamexp_version_raw_date
= __DATE__
;
111 static const char *g_lamexp_version_raw_time
= __TIME__
;
113 //Console attached flag
114 static bool g_lamexp_console_attached
= false;
117 //The following code was borrowed from MPC-HC project: http://mpc-hc.sf.net/
118 #if defined(__INTEL_COMPILER)
119 #if (__INTEL_COMPILER >= 1200)
120 static const char *g_lamexp_version_compiler
= "ICL 12.x";
121 #elif (__INTEL_COMPILER >= 1100)
122 static const char *g_lamexp_version_compiler
= = "ICL 11.x";
123 #elif (__INTEL_COMPILER >= 1000)
124 static const char *g_lamexp_version_compiler
= = "ICL 10.x";
126 #error Compiler is not supported!
128 #elif defined(_MSC_VER)
129 #if (_MSC_VER == 1600)
130 #if (_MSC_FULL_VER >= 160040219)
131 static const char *g_lamexp_version_compiler
= "MSVC 2010-SP1";
133 static const char *g_lamexp_version_compiler
= "MSVC 2010";
135 #elif (_MSC_VER == 1500)
136 #if (_MSC_FULL_VER >= 150030729)
137 static const char *g_lamexp_version_compiler
= "MSVC 2008-SP1";
139 static const char *g_lamexp_version_compiler
= "MSVC 2008";
142 #error Compiler is not supported!
145 // Note: /arch:SSE and /arch:SSE2 are only available for the x86 platform
146 #if !defined(_M_X64) && defined(_M_IX86_FP)
147 #if (_M_IX86_FP == 1)
148 LAMEXP_COMPILER_WARNING("SSE instruction set is enabled!")
149 #elif (_M_IX86_FP == 2)
150 LAMEXP_COMPILER_WARNING("SSE2 instruction set is enabled!")
154 #error Compiler is not supported!
157 //Architecture detection
159 static const char *g_lamexp_version_arch
= "x64";
160 #elif defined(_M_IX86)
161 static const char *g_lamexp_version_arch
= "x86";
163 #error Architecture is not supported!
166 //Official web-site URL
167 static const char *g_lamexp_website_url
= "http://lamexp.sourceforge.net/";
168 static const char *g_lamexp_support_url
= "http://forum.doom9.org/showthread.php?t=157726";
170 //Tool versions (expected versions!)
171 static const unsigned int g_lamexp_toolver_neroaac
= VER_LAMEXP_TOOL_NEROAAC
;
172 static const unsigned int g_lamexp_toolver_fhgaacenc
= VER_LAMEXP_TOOL_FHGAACENC
;
173 static const unsigned int g_lamexp_toolver_qaacenc
= VER_LAMEXP_TOOL_QAAC
;
174 static const unsigned int g_lamexp_toolver_coreaudio
= VER_LAMEXP_TOOL_COREAUDIO
;
177 static QString g_lamexp_temp_folder
;
180 static QMap
<QString
, LockedFile
*> g_lamexp_tool_registry
;
181 static QMap
<QString
, unsigned int> g_lamexp_tool_versions
;
186 QMap
<QString
, QString
> files
;
187 QMap
<QString
, QString
> names
;
188 QMap
<QString
, unsigned int> sysid
;
189 QMap
<QString
, unsigned int> cntry
;
191 g_lamexp_translation
;
194 static QTranslator
*g_lamexp_currentTranslator
= NULL
;
200 char *semaphore_read
;
201 char *semaphore_write
;
205 "{21A68A42-6923-43bb-9CF6-64BF151942EE}",
206 "{7A605549-F58C-4d78-B4E5-06EFC34F405B}",
207 "{60AA8D04-F6B8-497d-81EB-0F600F4A65B5}"
211 QSharedMemory
*sharedmem
;
212 QSystemSemaphore
*semaphore_read
;
213 QSystemSemaphore
*semaphore_write
;
221 static const char *g_lamexp_imageformats
[] = {"png", "jpg", "gif", "ico", "svg", NULL
};
224 static QMutex g_lamexp_message_mutex
;
227 static const DWORD g_main_thread_id
= GetCurrentThreadId();
230 ///////////////////////////////////////////////////////////////////////////////
232 ///////////////////////////////////////////////////////////////////////////////
237 unsigned int lamexp_version_major(void) { return g_lamexp_version
.ver_major
; }
238 unsigned int lamexp_version_minor(void) { return g_lamexp_version
.ver_minor
; }
239 unsigned int lamexp_version_build(void) { return g_lamexp_version
.ver_build
; }
240 const char *lamexp_version_release(void) { return g_lamexp_version
.ver_release_name
; }
241 const char *lamexp_version_time(void) { return g_lamexp_version_raw_time
; }
242 const char *lamexp_version_compiler(void) { return g_lamexp_version_compiler
; }
243 const char *lamexp_version_arch(void) { return g_lamexp_version_arch
; }
244 unsigned int lamexp_toolver_neroaac(void) { return g_lamexp_toolver_neroaac
; }
245 unsigned int lamexp_toolver_fhgaacenc(void) { return g_lamexp_toolver_fhgaacenc
; }
246 unsigned int lamexp_toolver_qaacenc(void) { return g_lamexp_toolver_qaacenc
; }
247 unsigned int lamexp_toolver_coreaudio(void) { return g_lamexp_toolver_coreaudio
; }
252 const char *lamexp_website_url(void) { return g_lamexp_website_url
; }
253 const char *lamexp_support_url(void) { return g_lamexp_support_url
; }
256 * Check for Demo (pre-release) version
258 bool lamexp_version_demo(void)
261 bool releaseVersion
= false;
262 if(!strncpy_s(buffer
, 128, g_lamexp_version
.ver_release_name
, _TRUNCATE
))
264 char *context
, *prefix
= strtok_s(buffer
, "-,; ", &context
);
267 releaseVersion
= (!_stricmp(prefix
, "Final")) || (!_stricmp(prefix
, "Hotfix"));
270 return LAMEXP_DEBUG
|| (!releaseVersion
);
274 * Calculate expiration date
276 QDate
lamexp_version_expires(void)
278 return lamexp_version_date().addDays(LAMEXP_DEBUG
? 2 : 30);
282 * Get build date date
284 const QDate
&lamexp_version_date(void)
286 if(!g_lamexp_version_date
.isValid())
291 char *this_token
= NULL
;
292 char *next_token
= NULL
;
294 strncpy_s(temp
, 32, g_lamexp_version_raw_date
, _TRUNCATE
);
295 this_token
= strtok_s(temp
, " ", &next_token
);
297 for(int i
= 0; i
< 3; i
++)
302 for(int j
= 0; j
< 12; j
++)
304 if(!_strcmpi(this_token
, g_lamexp_months
[j
]))
312 date
[i
] = atoi(this_token
);
314 this_token
= strtok_s(NULL
, " ", &next_token
);
318 if(date
[0] >= 0 && date
[1] >= 0 && date
[2] >= 0)
320 g_lamexp_version_date
= QDate(date
[2], date
[0], date
[1]);
324 return g_lamexp_version_date
;
328 * Get the native operating system version
330 DWORD
lamexp_get_os_version(void)
332 OSVERSIONINFO osVerInfo
;
333 memset(&osVerInfo
, 0, sizeof(OSVERSIONINFO
));
334 osVerInfo
.dwOSVersionInfoSize
= sizeof(OSVERSIONINFO
);
337 if(GetVersionEx(&osVerInfo
) == TRUE
)
339 if(osVerInfo
.dwPlatformId
!= VER_PLATFORM_WIN32_NT
)
341 throw "Ouuups: Not running under Windows NT. This is not supposed to happen!";
343 version
= (DWORD
)((osVerInfo
.dwMajorVersion
<< 16) | (osVerInfo
.dwMinorVersion
& 0xffff));
350 * Global exception handler
352 LONG WINAPI
lamexp_exception_handler(__in
struct _EXCEPTION_POINTERS
*ExceptionInfo
)
354 if(GetCurrentThreadId() != g_main_thread_id
)
356 HANDLE mainThread
= OpenThread(THREAD_TERMINATE
, FALSE
, g_main_thread_id
);
357 if(mainThread
) TerminateThread(mainThread
, ULONG_MAX
);
360 FatalAppExit(0, L
"Unhandeled exception handler invoked, application will exit!");
361 TerminateProcess(GetCurrentProcess(), -1);
366 * Invalid parameters handler
368 void lamexp_invalid_param_handler(const wchar_t*, const wchar_t*, const wchar_t*, unsigned int, uintptr_t)
370 if(GetCurrentThreadId() != g_main_thread_id
)
372 HANDLE mainThread
= OpenThread(THREAD_TERMINATE
, FALSE
, g_main_thread_id
);
373 if(mainThread
) TerminateThread(mainThread
, ULONG_MAX
);
377 FatalAppExit(0, L
"Invalid parameter handler invoked, application will exit!");
378 TerminateProcess(GetCurrentProcess(), -1);
382 * Change console text color
384 static void lamexp_console_color(FILE* file
, WORD attributes
)
386 const HANDLE hConsole
= (HANDLE
)(_get_osfhandle(_fileno(file
)));
387 if((hConsole
!= NULL
) && (hConsole
!= INVALID_HANDLE_VALUE
))
389 SetConsoleTextAttribute(hConsole
, attributes
);
396 void lamexp_message_handler(QtMsgType type
, const char *msg
)
398 static const char *GURU_MEDITATION
= "\n\nGURU MEDITATION !!!\n\n";
400 QMutexLocker
lock(&g_lamexp_message_mutex
);
402 //if((strlen(msg) > 8) && (_strnicmp(msg, "@BASE64@", 8) == 0))
404 // buffer = _strdup(QByteArray::fromBase64(msg + 8).constData());
405 // if(buffer) text = buffer;
408 if(g_lamexp_console_attached
)
410 UINT oldOutputCP
= GetConsoleOutputCP();
411 if(oldOutputCP
!= CP_UTF8
) SetConsoleOutputCP(CP_UTF8
);
419 lamexp_console_color(stderr
, FOREGROUND_RED
| FOREGROUND_INTENSITY
);
420 fprintf(stderr
, GURU_MEDITATION
);
421 fprintf(stderr
, "%s\n", msg
);
425 lamexp_console_color(stderr
, FOREGROUND_GREEN
| FOREGROUND_RED
| FOREGROUND_INTENSITY
);
426 fprintf(stderr
, "%s\n", msg
);
430 lamexp_console_color(stderr
, FOREGROUND_BLUE
| FOREGROUND_GREEN
| FOREGROUND_RED
| FOREGROUND_INTENSITY
);
431 fprintf(stderr
, "%s\n", msg
);
436 lamexp_console_color(stderr
, FOREGROUND_BLUE
| FOREGROUND_GREEN
| FOREGROUND_RED
);
437 if(oldOutputCP
!= CP_UTF8
) SetConsoleOutputCP(oldOutputCP
);
441 QString
temp("[LameXP][%1] %2");
447 temp
= temp
.arg("C", QString::fromUtf8(msg
));
450 temp
= temp
.arg("W", QString::fromUtf8(msg
));
453 temp
= temp
.arg("I", QString::fromUtf8(msg
));
457 temp
.replace("\n", "\t").append("\n");
458 OutputDebugStringA(temp
.toLatin1().constData());
461 if(type
== QtCriticalMsg
|| type
== QtFatalMsg
)
464 MessageBoxW(NULL
, QWCHAR(QString::fromUtf8(msg
)), L
"LameXP - GURU MEDITATION", MB_ICONERROR
| MB_TOPMOST
| MB_TASKMODAL
);
465 FatalAppExit(0, L
"The application has encountered a critical error and will exit now!");
466 TerminateProcess(GetCurrentProcess(), -1);
471 * Initialize the console
473 void lamexp_init_console(int argc
, char* argv
[])
475 bool enableConsole
= lamexp_version_demo();
479 for(int i
= 0; i
< argc
; i
++)
481 if(!_stricmp(argv
[i
], "--console"))
483 enableConsole
= true;
485 else if(!_stricmp(argv
[i
], "--no-console"))
487 enableConsole
= false;
494 if(!g_lamexp_console_attached
)
496 if(AllocConsole() != FALSE
)
498 SetConsoleCtrlHandler(NULL
, TRUE
);
499 SetConsoleTitle(L
"LameXP - Audio Encoder Front-End | Debug Console");
500 SetConsoleOutputCP(CP_UTF8
);
501 g_lamexp_console_attached
= true;
505 if(g_lamexp_console_attached
)
507 //-------------------------------------------------------------------
508 //See: http://support.microsoft.com/default.aspx?scid=kb;en-us;105305
509 //-------------------------------------------------------------------
510 const int flags
= _O_WRONLY
| _O_U8TEXT
;
511 int hCrtStdOut
= _open_osfhandle((intptr_t) GetStdHandle(STD_OUTPUT_HANDLE
), flags
);
512 int hCrtStdErr
= _open_osfhandle((intptr_t) GetStdHandle(STD_ERROR_HANDLE
), flags
);
513 FILE *hfStdOut
= (hCrtStdOut
>= 0) ? _fdopen(hCrtStdOut
, "wb") : NULL
;
514 FILE *hfStdErr
= (hCrtStdErr
>= 0) ? _fdopen(hCrtStdErr
, "wb") : NULL
;
515 if(hfStdOut
) { *stdout
= *hfStdOut
; std::cout
.rdbuf(new std::filebuf(hfStdOut
)); }
516 if(hfStdErr
) { *stderr
= *hfStdErr
; std::cerr
.rdbuf(new std::filebuf(hfStdErr
)); }
519 HWND hwndConsole
= GetConsoleWindow();
521 if((hwndConsole
!= NULL
) && (hwndConsole
!= INVALID_HANDLE_VALUE
))
523 HMENU hMenu
= GetSystemMenu(hwndConsole
, 0);
524 EnableMenuItem(hMenu
, SC_CLOSE
, MF_BYCOMMAND
| MF_GRAYED
);
525 RemoveMenu(hMenu
, SC_CLOSE
, MF_BYCOMMAND
);
527 SetWindowPos(hwndConsole
, HWND_TOP
, 0, 0, 0, 0, SWP_NOMOVE
|SWP_NOSIZE
|SWP_NOZORDER
|SWP_FRAMECHANGED
);
528 SetWindowLong(hwndConsole
, GWL_STYLE
, GetWindowLong(hwndConsole
, GWL_STYLE
) & (~WS_MAXIMIZEBOX
) & (~WS_MINIMIZEBOX
));
529 SetWindowPos(hwndConsole
, HWND_TOP
, 0, 0, 0, 0, SWP_NOMOVE
|SWP_NOSIZE
|SWP_NOZORDER
|SWP_FRAMECHANGED
);
535 * Detect CPU features
537 lamexp_cpu_t
lamexp_detect_cpu_features(int argc
, char **argv
)
539 typedef BOOL (WINAPI
*IsWow64ProcessFun
)(__in HANDLE hProcess
, __out PBOOL Wow64Process
);
540 typedef VOID (WINAPI
*GetNativeSystemInfoFun
)(__out LPSYSTEM_INFO lpSystemInfo
);
542 static IsWow64ProcessFun IsWow64ProcessPtr
= NULL
;
543 static GetNativeSystemInfoFun GetNativeSystemInfoPtr
= NULL
;
545 lamexp_cpu_t features
;
546 SYSTEM_INFO systemInfo
;
547 int CPUInfo
[4] = {-1};
548 char CPUIdentificationString
[0x40];
549 char CPUBrandString
[0x40];
551 memset(&features
, 0, sizeof(lamexp_cpu_t
));
552 memset(&systemInfo
, 0, sizeof(SYSTEM_INFO
));
553 memset(CPUIdentificationString
, 0, sizeof(CPUIdentificationString
));
554 memset(CPUBrandString
, 0, sizeof(CPUBrandString
));
557 memcpy(CPUIdentificationString
, &CPUInfo
[1], sizeof(int));
558 memcpy(CPUIdentificationString
+ 4, &CPUInfo
[3], sizeof(int));
559 memcpy(CPUIdentificationString
+ 8, &CPUInfo
[2], sizeof(int));
560 features
.intel
= (_stricmp(CPUIdentificationString
, "GenuineIntel") == 0);
561 strncpy_s(features
.vendor
, 0x40, CPUIdentificationString
, _TRUNCATE
);
566 features
.mmx
= (CPUInfo
[3] & 0x800000) || false;
567 features
.sse
= (CPUInfo
[3] & 0x2000000) || false;
568 features
.sse2
= (CPUInfo
[3] & 0x4000000) || false;
569 features
.ssse3
= (CPUInfo
[2] & 0x200) || false;
570 features
.sse3
= (CPUInfo
[2] & 0x1) || false;
571 features
.ssse3
= (CPUInfo
[2] & 0x200) || false;
572 features
.stepping
= CPUInfo
[0] & 0xf;
573 features
.model
= ((CPUInfo
[0] >> 4) & 0xf) + (((CPUInfo
[0] >> 16) & 0xf) << 4);
574 features
.family
= ((CPUInfo
[0] >> 8) & 0xf) + ((CPUInfo
[0] >> 20) & 0xff);
577 __cpuid(CPUInfo
, 0x80000000);
578 int nExIds
= qMax
<int>(qMin
<int>(CPUInfo
[0], 0x80000004), 0x80000000);
580 for(int i
= 0x80000002; i
<= nExIds
; ++i
)
586 memcpy(CPUBrandString
, CPUInfo
, sizeof(CPUInfo
));
589 memcpy(CPUBrandString
+ 16, CPUInfo
, sizeof(CPUInfo
));
592 memcpy(CPUBrandString
+ 32, CPUInfo
, sizeof(CPUInfo
));
597 strncpy_s(features
.brand
, 0x40, CPUBrandString
, _TRUNCATE
);
599 if(strlen(features
.brand
) < 1) strncpy_s(features
.brand
, 0x40, "Unknown", _TRUNCATE
);
600 if(strlen(features
.vendor
) < 1) strncpy_s(features
.vendor
, 0x40, "Unknown", _TRUNCATE
);
602 #if !defined(_M_X64 ) && !defined(_M_IA64)
603 if(!IsWow64ProcessPtr
|| !GetNativeSystemInfoPtr
)
605 QLibrary
Kernel32Lib("kernel32.dll");
606 IsWow64ProcessPtr
= (IsWow64ProcessFun
) Kernel32Lib
.resolve("IsWow64Process");
607 GetNativeSystemInfoPtr
= (GetNativeSystemInfoFun
) Kernel32Lib
.resolve("GetNativeSystemInfo");
609 if(IsWow64ProcessPtr
)
612 if(IsWow64ProcessPtr(GetCurrentProcess(), &x64
))
617 if(GetNativeSystemInfoPtr
)
619 GetNativeSystemInfoPtr(&systemInfo
);
623 GetSystemInfo(&systemInfo
);
625 features
.count
= qBound(1UL, systemInfo
.dwNumberOfProcessors
, 64UL);
627 GetNativeSystemInfo(&systemInfo
);
628 features
.count
= systemInfo
.dwNumberOfProcessors
;
632 if((argv
!= NULL
) && (argc
> 0))
635 for(int i
= 0; i
< argc
; i
++)
637 if(!_stricmp("--force-cpu-no-64bit", argv
[i
])) { flag
= true; features
.x64
= false; }
638 if(!_stricmp("--force-cpu-no-sse", argv
[i
])) { flag
= true; features
.sse
= features
.sse2
= features
.sse3
= features
.ssse3
= false; }
639 if(!_stricmp("--force-cpu-no-intel", argv
[i
])) { flag
= true; features
.intel
= false; }
641 if(flag
) qWarning("CPU flags overwritten by user-defined parameters. Take care!\n");
648 * Check for debugger (detect routine)
650 static bool lamexp_check_for_debugger(void)
656 __except(GetExceptionCode() == EXCEPTION_BREAKPOINT
? EXCEPTION_EXECUTE_HANDLER
: EXCEPTION_CONTINUE_SEARCH
)
664 * Check for debugger (thread proc)
666 static void WINAPI
lamexp_debug_thread_proc(__in LPVOID lpParameter
)
668 while(!(IsDebuggerPresent() || lamexp_check_for_debugger()))
672 TerminateProcess(GetCurrentProcess(), -1);
676 * Check for debugger (startup routine)
678 static HANDLE
lamexp_debug_thread_init(void)
680 if(IsDebuggerPresent() || lamexp_check_for_debugger())
682 FatalAppExit(0, L
"Not a debug build. Please unload debugger and try again!");
683 TerminateProcess(GetCurrentProcess(), -1);
686 return CreateThread(NULL
, NULL
, reinterpret_cast<LPTHREAD_START_ROUTINE
>(&lamexp_debug_thread_proc
), NULL
, NULL
, NULL
);
690 * Check for compatibility mode
692 static bool lamexp_check_compatibility_mode(const char *exportName
, const char *executableName
)
694 QLibrary
kernel32("kernel32.dll");
696 if(exportName
!= NULL
)
698 if(kernel32
.resolve(exportName
) != NULL
)
700 qWarning("Function '%s' exported from 'kernel32.dll' -> Windows compatibility mode!", exportName
);
701 qFatal("%s", QApplication::tr("Executable '%1' doesn't support Windows compatibility mode.").arg(QString::fromLatin1(executableName
)).toLatin1().constData());
710 * Check for process elevation
712 static bool lamexp_check_elevation(void)
714 typedef enum { lamexp_token_elevationType_class
= 18, lamexp_token_elevation_class
= 20 } LAMEXP_TOKEN_INFORMATION_CLASS
;
715 typedef enum { lamexp_elevationType_default
= 1, lamexp_elevationType_full
, lamexp_elevationType_limited
} LAMEXP_TOKEN_ELEVATION_TYPE
;
717 HANDLE hToken
= NULL
;
718 bool bIsProcessElevated
= false;
720 if(OpenProcessToken(GetCurrentProcess(), TOKEN_QUERY
, &hToken
))
722 LAMEXP_TOKEN_ELEVATION_TYPE tokenElevationType
;
724 if(GetTokenInformation(hToken
, (TOKEN_INFORMATION_CLASS
) lamexp_token_elevationType_class
, &tokenElevationType
, sizeof(LAMEXP_TOKEN_ELEVATION_TYPE
), &returnLength
))
726 if(returnLength
== sizeof(LAMEXP_TOKEN_ELEVATION_TYPE
))
728 switch(tokenElevationType
)
730 case lamexp_elevationType_default
:
731 qDebug("Process token elevation type: Default -> UAC is disabled.\n");
733 case lamexp_elevationType_full
:
734 qWarning("Process token elevation type: Full -> potential security risk!\n");
735 bIsProcessElevated
= true;
737 case lamexp_elevationType_limited
:
738 qDebug("Process token elevation type: Limited -> not elevated.\n");
747 qWarning("Failed to open process token!");
750 return !bIsProcessElevated
;
754 * Initialize Qt framework
756 bool lamexp_init_qt(int argc
, char* argv
[])
758 static bool qt_initialized
= false;
760 typedef BOOL (WINAPI
*SetDllDirectoryProc
)(WCHAR
*lpPathName
);
762 //Don't initialized again, if done already
769 QLibrary
kernel32("kernel32.dll");
772 SetDllDirectoryProc pSetDllDirectory
= (SetDllDirectoryProc
) kernel32
.resolve("SetDllDirectoryW");
773 if(pSetDllDirectory
!= NULL
) pSetDllDirectory(L
"");
777 //Extract executable name from argv[] array
778 char *executableName
= argv
[0];
779 while(char *temp
= strpbrk(executableName
, "\\/:?"))
781 executableName
= temp
+ 1;
785 qDebug("Using Qt v%s [%s], %s, %s", qVersion(), QLibraryInfo::buildDate().toString(Qt::ISODate
).toLatin1().constData(), (qSharedBuild() ? "DLL" : "Static"), QLibraryInfo::buildKey().toLatin1().constData());
786 qDebug("Compiled with Qt v%s [%s], %s\n", QT_VERSION_STR
, QT_PACKAGEDATE_STR
, QT_BUILD_KEY
);
787 if(_stricmp(qVersion(), QT_VERSION_STR
))
789 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());
792 if(QLibraryInfo::buildKey().compare(QString::fromLatin1(QT_BUILD_KEY
), Qt::CaseInsensitive
))
794 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());
798 //Check the Windows version
799 switch(QSysInfo::windowsVersion() & QSysInfo::WV_NT_based
)
802 case QSysInfo::WV_NT
:
803 qFatal("%s", QApplication::tr("Executable '%1' requires Windows 2000 or later.").arg(QString::fromLatin1(executableName
)).toLatin1().constData());
805 case QSysInfo::WV_2000
:
806 qDebug("Running on Windows 2000 (not officially supported!).\n");
807 lamexp_check_compatibility_mode("GetNativeSystemInfo", executableName
);
809 case QSysInfo::WV_XP
:
810 qDebug("Running on Windows XP.\n");
811 lamexp_check_compatibility_mode("GetLargePageMinimum", executableName
);
813 case QSysInfo::WV_2003
:
814 qDebug("Running on Windows Server 2003 or Windows XP x64-Edition.\n");
815 lamexp_check_compatibility_mode("GetLocaleInfoEx", executableName
);
817 case QSysInfo::WV_VISTA
:
818 qDebug("Running on Windows Vista or Windows Server 2008.\n");
819 lamexp_check_compatibility_mode("CreateRemoteThreadEx", executableName
);
821 case QSysInfo::WV_WINDOWS7
:
822 qDebug("Running on Windows 7 or Windows Server 2008 R2.\n");
823 lamexp_check_compatibility_mode(NULL
, executableName
);
827 DWORD osVersionNo
= lamexp_get_os_version();
828 qWarning("Running on an unknown/untested WinNT-based OS (v%u.%u).\n", HIWORD(osVersionNo
), LOWORD(osVersionNo
));
834 QLibrary
ntdll("ntdll.dll");
837 if(ntdll
.resolve("wine_nt_to_unix_file_name") != NULL
) isWine
= true;
838 if(ntdll
.resolve("wine_get_version") != NULL
) isWine
= true;
839 if(isWine
) qWarning("It appears we are running under Wine, unexpected things might happen!\n");
843 //Create Qt application instance and setup version info
844 QDate date
= QDate::currentDate();
845 QApplication
*application
= new QApplication(argc
, argv
);
846 application
->setApplicationName("LameXP - Audio Encoder Front-End");
847 application
->setApplicationVersion(QString().sprintf("%d.%02d.%04d", lamexp_version_major(), lamexp_version_minor(), lamexp_version_build()));
848 application
->setOrganizationName("LoRd_MuldeR");
849 application
->setOrganizationDomain("mulder.at.gg");
850 application
->setWindowIcon((date
.month() == 12 && date
.day() >= 24 && date
.day() <= 26) ? QIcon(":/MainIcon2.png") : QIcon(":/MainIcon.png"));
852 //Set text Codec for locale
853 QTextCodec::setCodecForLocale(QTextCodec::codecForName("UTF-8"));
855 //Load plugins from application directory
856 QCoreApplication::setLibraryPaths(QStringList() << QApplication::applicationDirPath());
857 qDebug("Library Path:\n%s\n", QApplication::libraryPaths().first().toUtf8().constData());
859 //Check for supported image formats
860 QList
<QByteArray
> supportedFormats
= QImageReader::supportedImageFormats();
861 for(int i
= 0; g_lamexp_imageformats
[i
]; i
++)
863 if(!supportedFormats
.contains(g_lamexp_imageformats
[i
]))
865 qFatal("Qt initialization error: QImageIOHandler for '%s' missing!", g_lamexp_imageformats
[i
]);
870 //Add default translations
871 g_lamexp_translation
.files
.insert(LAMEXP_DEFAULT_LANGID
, "");
872 g_lamexp_translation
.names
.insert(LAMEXP_DEFAULT_LANGID
, "English");
874 //Check for process elevation
875 if(!lamexp_check_elevation())
877 if(QMessageBox::warning(NULL
, "LameXP", "<nobr>LameXP was started with elevated rights. This is a potential security risk!</nobr>", "Quit Program (Recommended)", "Ignore") == 0)
883 //Update console icon, if a console is attached
884 if(g_lamexp_console_attached
&& !isWine
)
886 typedef DWORD (__stdcall
*SetConsoleIconFun
)(HICON
);
887 QLibrary
kernel32("kernel32.dll");
890 SetConsoleIconFun SetConsoleIconPtr
= (SetConsoleIconFun
) kernel32
.resolve("SetConsoleIcon");
891 if(SetConsoleIconPtr
!= NULL
) SetConsoleIconPtr(QIcon(":/icons/sound.png").pixmap(16, 16).toWinHICON());
897 qt_initialized
= true;
904 int lamexp_init_ipc(void)
906 if(g_lamexp_ipc_ptr
.sharedmem
&& g_lamexp_ipc_ptr
.semaphore_read
&& g_lamexp_ipc_ptr
.semaphore_write
)
911 g_lamexp_ipc_ptr
.semaphore_read
= new QSystemSemaphore(QString(g_lamexp_ipc_uuid
.semaphore_read
), 0);
912 g_lamexp_ipc_ptr
.semaphore_write
= new QSystemSemaphore(QString(g_lamexp_ipc_uuid
.semaphore_write
), 0);
914 if(g_lamexp_ipc_ptr
.semaphore_read
->error() != QSystemSemaphore::NoError
)
916 QString errorMessage
= g_lamexp_ipc_ptr
.semaphore_read
->errorString();
917 LAMEXP_DELETE(g_lamexp_ipc_ptr
.semaphore_read
);
918 LAMEXP_DELETE(g_lamexp_ipc_ptr
.semaphore_write
);
919 qFatal("Failed to create system smaphore: %s", errorMessage
.toUtf8().constData());
922 if(g_lamexp_ipc_ptr
.semaphore_write
->error() != QSystemSemaphore::NoError
)
924 QString errorMessage
= g_lamexp_ipc_ptr
.semaphore_write
->errorString();
925 LAMEXP_DELETE(g_lamexp_ipc_ptr
.semaphore_read
);
926 LAMEXP_DELETE(g_lamexp_ipc_ptr
.semaphore_write
);
927 qFatal("Failed to create system smaphore: %s", errorMessage
.toUtf8().constData());
931 g_lamexp_ipc_ptr
.sharedmem
= new QSharedMemory(QString(g_lamexp_ipc_uuid
.sharedmem
), NULL
);
933 if(!g_lamexp_ipc_ptr
.sharedmem
->create(sizeof(lamexp_ipc_t
)))
935 if(g_lamexp_ipc_ptr
.sharedmem
->error() == QSharedMemory::AlreadyExists
)
937 g_lamexp_ipc_ptr
.sharedmem
->attach();
938 if(g_lamexp_ipc_ptr
.sharedmem
->error() == QSharedMemory::NoError
)
944 QString errorMessage
= g_lamexp_ipc_ptr
.sharedmem
->errorString();
945 qFatal("Failed to attach to shared memory: %s", errorMessage
.toUtf8().constData());
951 QString errorMessage
= g_lamexp_ipc_ptr
.sharedmem
->errorString();
952 qFatal("Failed to create shared memory: %s", errorMessage
.toUtf8().constData());
957 memset(g_lamexp_ipc_ptr
.sharedmem
->data(), 0, sizeof(lamexp_ipc_t
));
958 g_lamexp_ipc_ptr
.semaphore_write
->release();
966 void lamexp_ipc_send(unsigned int command
, const char* message
)
968 if(!g_lamexp_ipc_ptr
.sharedmem
|| !g_lamexp_ipc_ptr
.semaphore_read
|| !g_lamexp_ipc_ptr
.semaphore_write
)
970 throw "Shared memory for IPC not initialized yet.";
973 lamexp_ipc_t
*lamexp_ipc
= new lamexp_ipc_t
;
974 memset(lamexp_ipc
, 0, sizeof(lamexp_ipc_t
));
975 lamexp_ipc
->command
= command
;
978 strncpy_s(lamexp_ipc
->parameter
, 4096, message
, _TRUNCATE
);
981 if(g_lamexp_ipc_ptr
.semaphore_write
->acquire())
983 memcpy(g_lamexp_ipc_ptr
.sharedmem
->data(), lamexp_ipc
, sizeof(lamexp_ipc_t
));
984 g_lamexp_ipc_ptr
.semaphore_read
->release();
987 LAMEXP_DELETE(lamexp_ipc
);
993 void lamexp_ipc_read(unsigned int *command
, char* message
, size_t buffSize
)
998 if(!g_lamexp_ipc_ptr
.sharedmem
|| !g_lamexp_ipc_ptr
.semaphore_read
|| !g_lamexp_ipc_ptr
.semaphore_write
)
1000 throw "Shared memory for IPC not initialized yet.";
1003 lamexp_ipc_t
*lamexp_ipc
= new lamexp_ipc_t
;
1004 memset(lamexp_ipc
, 0, sizeof(lamexp_ipc_t
));
1006 if(g_lamexp_ipc_ptr
.semaphore_read
->acquire())
1008 memcpy(lamexp_ipc
, g_lamexp_ipc_ptr
.sharedmem
->data(), sizeof(lamexp_ipc_t
));
1009 g_lamexp_ipc_ptr
.semaphore_write
->release();
1011 if(!(lamexp_ipc
->reserved_1
|| lamexp_ipc
->reserved_2
))
1013 *command
= lamexp_ipc
->command
;
1014 strncpy_s(message
, buffSize
, lamexp_ipc
->parameter
, _TRUNCATE
);
1018 qWarning("Malformed IPC message, will be ignored");
1022 LAMEXP_DELETE(lamexp_ipc
);
1026 * Check for LameXP "portable" mode
1028 bool lamexp_portable_mode(void)
1030 QString baseName
= QFileInfo(QApplication::applicationFilePath()).completeBaseName();
1031 int idx1
= baseName
.indexOf("lamexp", 0, Qt::CaseInsensitive
);
1032 int idx2
= baseName
.lastIndexOf("portable", -1, Qt::CaseInsensitive
);
1033 return (idx1
>= 0) && (idx2
>= 0) && (idx1
< idx2
);
1037 * Get a random string
1039 QString
lamexp_rand_str(void)
1041 QRegExp
regExp("\\{(\\w+)-(\\w+)-(\\w+)-(\\w+)-(\\w+)\\}");
1042 QString uuid
= QUuid::createUuid().toString();
1044 if(regExp
.indexIn(uuid
) >= 0)
1046 return QString().append(regExp
.cap(1)).append(regExp
.cap(2)).append(regExp
.cap(3)).append(regExp
.cap(4)).append(regExp
.cap(5));
1049 throw "The RegExp didn't match on the UUID string. This shouldn't happen ;-)";
1053 * Get LameXP temp folder
1055 const QString
&lamexp_temp_folder2(void)
1057 static const char *TEMP_STR
= "Temp";
1058 const QString WRITE_TEST_DATA
= lamexp_rand_str();
1059 const QString SUB_FOLDER
= lamexp_rand_str();
1061 //Already initialized?
1062 if(!g_lamexp_temp_folder
.isEmpty())
1064 if(QDir(g_lamexp_temp_folder
).exists())
1066 return g_lamexp_temp_folder
;
1070 g_lamexp_temp_folder
.clear();
1074 //Try the %TMP% or %TEMP% directory first
1075 QDir temp
= QDir::temp();
1078 temp
.mkdir(SUB_FOLDER
);
1079 if(temp
.cd(SUB_FOLDER
) && temp
.exists())
1081 QFile
testFile(QString("%1/~%2.tmp").arg(temp
.canonicalPath(), lamexp_rand_str()));
1082 if(testFile
.open(QIODevice::ReadWrite
))
1084 if(testFile
.write(WRITE_TEST_DATA
.toLatin1().constData()) >= strlen(WRITE_TEST_DATA
.toLatin1().constData()))
1086 g_lamexp_temp_folder
= temp
.canonicalPath();
1091 if(!g_lamexp_temp_folder
.isEmpty())
1093 return g_lamexp_temp_folder
;
1097 //Create TEMP folder in %LOCALAPPDATA%
1098 QDir localAppData
= QDir(lamexp_known_folder(lamexp_folder_localappdata
));
1099 if(!localAppData
.path().isEmpty())
1101 if(!localAppData
.exists())
1103 localAppData
.mkpath(".");
1105 if(localAppData
.exists())
1107 if(!localAppData
.entryList(QDir::AllDirs
).contains(TEMP_STR
, Qt::CaseInsensitive
))
1109 localAppData
.mkdir(TEMP_STR
);
1111 if(localAppData
.cd(TEMP_STR
) && localAppData
.exists())
1113 localAppData
.mkdir(SUB_FOLDER
);
1114 if(localAppData
.cd(SUB_FOLDER
) && localAppData
.exists())
1116 QFile
testFile(QString("%1/~%2.tmp").arg(localAppData
.canonicalPath(), lamexp_rand_str()));
1117 if(testFile
.open(QIODevice::ReadWrite
))
1119 if(testFile
.write(WRITE_TEST_DATA
.toLatin1().constData()) >= strlen(WRITE_TEST_DATA
.toLatin1().constData()))
1121 g_lamexp_temp_folder
= localAppData
.canonicalPath();
1128 if(!g_lamexp_temp_folder
.isEmpty())
1130 return g_lamexp_temp_folder
;
1134 //Failed to create TEMP folder!
1135 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());
1136 return g_lamexp_temp_folder
;
1142 bool lamexp_clean_folder(const QString
&folderPath
)
1144 QDir
tempFolder(folderPath
);
1145 QFileInfoList entryList
= tempFolder
.entryInfoList(QDir::AllEntries
| QDir::NoDotAndDotDot
);
1147 for(int i
= 0; i
< entryList
.count(); i
++)
1149 if(entryList
.at(i
).isDir())
1151 lamexp_clean_folder(entryList
.at(i
).canonicalFilePath());
1155 for(int j
= 0; j
< 3; j
++)
1157 if(lamexp_remove_file(entryList
.at(i
).canonicalFilePath()))
1165 tempFolder
.rmdir(".");
1166 return !tempFolder
.exists();
1172 void lamexp_register_tool(const QString
&toolName
, LockedFile
*file
, unsigned int version
)
1174 if(g_lamexp_tool_registry
.contains(toolName
.toLower()))
1176 throw "lamexp_register_tool: Tool is already registered!";
1179 g_lamexp_tool_registry
.insert(toolName
.toLower(), file
);
1180 g_lamexp_tool_versions
.insert(toolName
.toLower(), version
);
1186 bool lamexp_check_tool(const QString
&toolName
)
1188 return g_lamexp_tool_registry
.contains(toolName
.toLower());
1194 const QString
lamexp_lookup_tool(const QString
&toolName
)
1196 if(g_lamexp_tool_registry
.contains(toolName
.toLower()))
1198 return g_lamexp_tool_registry
.value(toolName
.toLower())->filePath();
1207 * Lookup tool version
1209 unsigned int lamexp_tool_version(const QString
&toolName
)
1211 if(g_lamexp_tool_versions
.contains(toolName
.toLower()))
1213 return g_lamexp_tool_versions
.value(toolName
.toLower());
1222 * Version number to human-readable string
1224 const QString
lamexp_version2string(const QString
&pattern
, unsigned int version
, const QString
&defaultText
)
1226 if(version
== UINT_MAX
)
1231 QString result
= pattern
;
1232 int digits
= result
.count("?", Qt::CaseInsensitive
);
1240 QString versionStr
= QString().sprintf(QString().sprintf("%%0%du", digits
).toLatin1().constData(), version
);
1241 int index
= result
.indexOf("?", Qt::CaseInsensitive
);
1243 while(index
>= 0 && pos
< versionStr
.length())
1245 result
[index
] = versionStr
[pos
++];
1246 index
= result
.indexOf("?", Qt::CaseInsensitive
);
1253 * Register a new translation
1255 bool lamexp_translation_register(const QString
&langId
, const QString
&qmFile
, const QString
&langName
, unsigned int &systemId
, unsigned int &country
)
1257 if(qmFile
.isEmpty() || langName
.isEmpty() || systemId
< 1)
1262 g_lamexp_translation
.files
.insert(langId
, qmFile
);
1263 g_lamexp_translation
.names
.insert(langId
, langName
);
1264 g_lamexp_translation
.sysid
.insert(langId
, systemId
);
1265 g_lamexp_translation
.cntry
.insert(langId
, country
);
1271 * Get list of all translations
1273 QStringList
lamexp_query_translations(void)
1275 return g_lamexp_translation
.files
.keys();
1279 * Get translation name
1281 QString
lamexp_translation_name(const QString
&langId
)
1283 return g_lamexp_translation
.names
.value(langId
.toLower(), QString());
1287 * Get translation system id
1289 unsigned int lamexp_translation_sysid(const QString
&langId
)
1291 return g_lamexp_translation
.sysid
.value(langId
.toLower(), 0);
1295 * Get translation script id
1297 unsigned int lamexp_translation_country(const QString
&langId
)
1299 return g_lamexp_translation
.cntry
.value(langId
.toLower(), 0);
1303 * Install a new translator
1305 bool lamexp_install_translator(const QString
&langId
)
1307 bool success
= false;
1309 if(langId
.isEmpty() || langId
.toLower().compare(LAMEXP_DEFAULT_LANGID
) == 0)
1311 success
= lamexp_install_translator_from_file(QString());
1315 QString qmFile
= g_lamexp_translation
.files
.value(langId
.toLower(), QString());
1316 if(!qmFile
.isEmpty())
1318 success
= lamexp_install_translator_from_file(QString(":/localization/%1").arg(qmFile
));
1322 qWarning("Translation '%s' not available!", langId
.toLatin1().constData());
1330 * Install a new translator from file
1332 bool lamexp_install_translator_from_file(const QString
&qmFile
)
1334 bool success
= false;
1336 if(!g_lamexp_currentTranslator
)
1338 g_lamexp_currentTranslator
= new QTranslator();
1341 if(!qmFile
.isEmpty())
1343 QString qmPath
= QFileInfo(qmFile
).canonicalFilePath();
1344 QApplication::removeTranslator(g_lamexp_currentTranslator
);
1345 success
= g_lamexp_currentTranslator
->load(qmPath
);
1346 QApplication::installTranslator(g_lamexp_currentTranslator
);
1349 qWarning("Failed to load translation:\n\"%s\"", qmPath
.toLatin1().constData());
1354 QApplication::removeTranslator(g_lamexp_currentTranslator
);
1362 * Locate known folder on local system
1364 QString
lamexp_known_folder(lamexp_known_folder_t folder_id
)
1366 typedef HRESULT (WINAPI
*SHGetKnownFolderPathFun
)(__in
const GUID
&rfid
, __in DWORD dwFlags
, __in HANDLE hToken
, __out PWSTR
*ppszPath
);
1367 typedef HRESULT (WINAPI
*SHGetFolderPathFun
)(__in HWND hwndOwner
, __in
int nFolder
, __in HANDLE hToken
, __in DWORD dwFlags
, __out LPWSTR pszPath
);
1369 static const int CSIDL_LOCAL_APPDATA
= 0x001c;
1370 static const int CSIDL_PROGRAM_FILES
= 0x0026;
1371 static const int CSIDL_SYSTEM_FOLDER
= 0x0025;
1372 static const GUID GUID_LOCAL_APPDATA
= {0xF1B32785,0x6FBA,0x4FCF,{0x9D,0x55,0x7B,0x8E,0x7F,0x15,0x70,0x91}};
1373 static const GUID GUID_LOCAL_APPDATA_LOW
= {0xA520A1A4,0x1780,0x4FF6,{0xBD,0x18,0x16,0x73,0x43,0xC5,0xAF,0x16}};
1374 static const GUID GUID_PROGRAM_FILES
= {0x905e63b6,0xc1bf,0x494e,{0xb2,0x9c,0x65,0xb7,0x32,0xd3,0xd2,0x1a}};
1375 static const GUID GUID_SYSTEM_FOLDER
= {0x1AC14E77,0x02E7,0x4E5D,{0xB7,0x44,0x2E,0xB1,0xAE,0x51,0x98,0xB7}};
1377 static QLibrary
*Kernel32Lib
= NULL
;
1378 static SHGetKnownFolderPathFun SHGetKnownFolderPathPtr
= NULL
;
1379 static SHGetFolderPathFun SHGetFolderPathPtr
= NULL
;
1381 if((!SHGetKnownFolderPathPtr
) && (!SHGetFolderPathPtr
))
1383 if(!Kernel32Lib
) Kernel32Lib
= new QLibrary("shell32.dll");
1384 SHGetKnownFolderPathPtr
= (SHGetKnownFolderPathFun
) Kernel32Lib
->resolve("SHGetKnownFolderPath");
1385 SHGetFolderPathPtr
= (SHGetFolderPathFun
) Kernel32Lib
->resolve("SHGetFolderPathW");
1388 int folderCSIDL
= -1;
1389 GUID folderGUID
= {0x0000,0x0000,0x0000,{0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00}};
1393 case lamexp_folder_localappdata
:
1394 folderCSIDL
= CSIDL_LOCAL_APPDATA
;
1395 folderGUID
= GUID_LOCAL_APPDATA
;
1397 case lamexp_folder_programfiles
:
1398 folderCSIDL
= CSIDL_PROGRAM_FILES
;
1399 folderGUID
= GUID_PROGRAM_FILES
;
1401 case lamexp_folder_systemfolder
:
1402 folderCSIDL
= CSIDL_SYSTEM_FOLDER
;
1403 folderGUID
= GUID_SYSTEM_FOLDER
;
1412 if(SHGetKnownFolderPathPtr
)
1415 if(SHGetKnownFolderPathPtr(folderGUID
, 0x00008000, NULL
, &path
) == S_OK
)
1417 //MessageBoxW(0, path, L"SHGetKnownFolderPath", MB_TOPMOST);
1418 QDir folderTemp
= QDir(QDir::fromNativeSeparators(QString::fromUtf16(reinterpret_cast<const unsigned short*>(path
))));
1419 if(!folderTemp
.exists())
1421 folderTemp
.mkpath(".");
1423 if(folderTemp
.exists())
1425 folder
= folderTemp
.canonicalPath();
1427 CoTaskMemFree(path
);
1430 else if(SHGetFolderPathPtr
)
1432 WCHAR
*path
= new WCHAR
[4096];
1433 if(SHGetFolderPathPtr(NULL
, folderCSIDL
, NULL
, NULL
, path
) == S_OK
)
1435 //MessageBoxW(0, path, L"SHGetFolderPathW", MB_TOPMOST);
1436 QDir folderTemp
= QDir(QDir::fromNativeSeparators(QString::fromUtf16(reinterpret_cast<const unsigned short*>(path
))));
1437 if(!folderTemp
.exists())
1439 folderTemp
.mkpath(".");
1441 if(folderTemp
.exists())
1443 folder
= folderTemp
.canonicalPath();
1453 * Safely remove a file
1455 bool lamexp_remove_file(const QString
&filename
)
1457 if(!QFileInfo(filename
).exists() || !QFileInfo(filename
).isFile())
1463 if(!QFile::remove(filename
))
1465 DWORD attributes
= GetFileAttributesW(QWCHAR(filename
));
1466 SetFileAttributesW(QWCHAR(filename
), (attributes
& (~FILE_ATTRIBUTE_READONLY
)));
1467 if(!QFile::remove(filename
))
1469 qWarning("Could not delete \"%s\"", filename
.toLatin1().constData());
1485 * Check if visual themes are enabled (WinXP and later)
1487 bool lamexp_themes_enabled(void)
1489 typedef int (WINAPI
*IsAppThemedFun
)(void);
1491 bool isAppThemed
= false;
1492 QLibrary
uxTheme(QString("%1/UxTheme.dll").arg(lamexp_known_folder(lamexp_folder_systemfolder
)));
1493 IsAppThemedFun IsAppThemedPtr
= (IsAppThemedFun
) uxTheme
.resolve("IsAppThemed");
1497 isAppThemed
= IsAppThemedPtr();
1500 qWarning("Theme support is disabled for this process!");
1508 * Get number of free bytes on disk
1510 unsigned __int64
lamexp_free_diskspace(const QString
&path
, bool *ok
)
1512 ULARGE_INTEGER freeBytesAvailable
, totalNumberOfBytes
, totalNumberOfFreeBytes
;
1513 if(GetDiskFreeSpaceExW(reinterpret_cast<const wchar_t*>(QDir::toNativeSeparators(path
).utf16()), &freeBytesAvailable
, &totalNumberOfBytes
, &totalNumberOfFreeBytes
))
1516 return freeBytesAvailable
.QuadPart
;
1526 * Check if computer does support hibernation
1528 bool lamexp_is_hibernation_supported(void)
1530 bool hibernationSupported
= false;
1532 SYSTEM_POWER_CAPABILITIES pwrCaps
;
1533 SecureZeroMemory(&pwrCaps
, sizeof(SYSTEM_POWER_CAPABILITIES
));
1535 if(GetPwrCapabilities(&pwrCaps
))
1537 hibernationSupported
= pwrCaps
.SystemS4
&& pwrCaps
.HiberFilePresent
;
1540 return hibernationSupported
;
1544 * Shutdown the computer
1546 bool lamexp_shutdown_computer(const QString
&message
, const unsigned long timeout
, const bool forceShutdown
, const bool hibernate
)
1548 HANDLE hToken
= NULL
;
1550 if(OpenProcessToken(GetCurrentProcess(), TOKEN_ADJUST_PRIVILEGES
| TOKEN_QUERY
, &hToken
))
1552 TOKEN_PRIVILEGES privileges
;
1553 memset(&privileges
, 0, sizeof(TOKEN_PRIVILEGES
));
1554 privileges
.PrivilegeCount
= 1;
1555 privileges
.Privileges
[0].Attributes
= SE_PRIVILEGE_ENABLED
;
1557 if(LookupPrivilegeValue(NULL
, SE_SHUTDOWN_NAME
, &privileges
.Privileges
[0].Luid
))
1559 if(AdjustTokenPrivileges(hToken
, FALSE
, &privileges
, NULL
, NULL
, NULL
))
1563 if(SetSuspendState(TRUE
, TRUE
, TRUE
))
1568 const DWORD reason
= SHTDN_REASON_MAJOR_APPLICATION
| SHTDN_REASON_FLAG_PLANNED
;
1569 return InitiateSystemShutdownEx(NULL
, const_cast<wchar_t*>(QWCHAR(message
)), timeout
, forceShutdown
? TRUE
: FALSE
, FALSE
, reason
);
1578 * Make a window blink (to draw user's attention)
1580 void lamexp_blink_window(QWidget
*poWindow
, unsigned int count
, unsigned int delay
)
1582 static QMutex blinkMutex
;
1584 const double maxOpac
= 1.0;
1585 const double minOpac
= 0.3;
1586 const double delOpac
= 0.1;
1588 if(!blinkMutex
.tryLock())
1590 qWarning("Blinking is already in progress, skipping!");
1596 const int steps
= static_cast<int>(ceil(maxOpac
- minOpac
) / delOpac
);
1597 const int sleep
= static_cast<int>(floor(static_cast<double>(delay
) / static_cast<double>(steps
)));
1598 const double opacity
= poWindow
->windowOpacity();
1600 for(unsigned int i
= 0; i
< count
; i
++)
1602 for(double x
= maxOpac
; x
>= minOpac
; x
-= delOpac
)
1604 poWindow
->setWindowOpacity(x
);
1605 QApplication::processEvents();
1609 for(double x
= minOpac
; x
<= maxOpac
; x
+= delOpac
)
1611 poWindow
->setWindowOpacity(x
);
1612 QApplication::processEvents();
1617 poWindow
->setWindowOpacity(opacity
);
1618 QApplication::processEvents();
1619 blinkMutex
.unlock();
1623 blinkMutex
.unlock();
1624 qWarning("Exception error while blinking!");
1629 * Remove forbidden characters from a filename
1631 const QString
lamexp_clean_filename(const QString
&str
)
1633 QString
newStr(str
);
1635 newStr
.replace("\\", "-");
1636 newStr
.replace(" / ", ", ");
1637 newStr
.replace("/", ",");
1638 newStr
.replace(":", "-");
1639 newStr
.replace("*", "x");
1640 newStr
.replace("?", "");
1641 newStr
.replace("<", "[");
1642 newStr
.replace(">", "]");
1643 newStr
.replace("|", "!");
1645 return newStr
.simplified();
1649 * Remove forbidden characters from a file path
1651 const QString
lamexp_clean_filepath(const QString
&str
)
1653 QStringList parts
= QString(str
).replace("\\", "/").split("/");
1655 for(int i
= 0; i
< parts
.count(); i
++)
1657 parts
[i
] = lamexp_clean_filename(parts
[i
]);
1660 return parts
.join("/");
1664 * Get a list of all available Qt Text Codecs
1666 QStringList
lamexp_available_codepages(bool noAliases
)
1668 QStringList codecList
;
1670 QList
<QByteArray
> availableCodecs
= QTextCodec::availableCodecs();
1671 while(!availableCodecs
.isEmpty())
1673 QByteArray current
= availableCodecs
.takeFirst();
1674 if(!(current
.startsWith("system") || current
.startsWith("System")))
1676 codecList
<< QString::fromLatin1(current
.constData(), current
.size());
1679 if(QTextCodec
*currentCodec
= QTextCodec::codecForName(current
.constData()))
1682 QList
<QByteArray
> aliases
= currentCodec
->aliases();
1683 while(!aliases
.isEmpty()) availableCodecs
.removeAll(aliases
.takeFirst());
1693 * Finalization function (final clean-up)
1695 void lamexp_finalization(void)
1698 if(!g_lamexp_tool_registry
.isEmpty())
1700 QStringList keys
= g_lamexp_tool_registry
.keys();
1701 for(int i
= 0; i
< keys
.count(); i
++)
1703 LAMEXP_DELETE(g_lamexp_tool_registry
[keys
.at(i
)]);
1705 g_lamexp_tool_registry
.clear();
1706 g_lamexp_tool_versions
.clear();
1709 //Delete temporary files
1710 if(!g_lamexp_temp_folder
.isEmpty())
1712 for(int i
= 0; i
< 100; i
++)
1714 if(lamexp_clean_folder(g_lamexp_temp_folder
))
1720 g_lamexp_temp_folder
.clear();
1724 if(g_lamexp_currentTranslator
)
1726 QApplication::removeTranslator(g_lamexp_currentTranslator
);
1727 LAMEXP_DELETE(g_lamexp_currentTranslator
);
1729 g_lamexp_translation
.files
.clear();
1730 g_lamexp_translation
.names
.clear();
1732 //Destroy Qt application object
1733 QApplication
*application
= dynamic_cast<QApplication
*>(QApplication::instance());
1734 LAMEXP_DELETE(application
);
1736 //Detach from shared memory
1737 if(g_lamexp_ipc_ptr
.sharedmem
) g_lamexp_ipc_ptr
.sharedmem
->detach();
1738 LAMEXP_DELETE(g_lamexp_ipc_ptr
.sharedmem
);
1739 LAMEXP_DELETE(g_lamexp_ipc_ptr
.semaphore_read
);
1740 LAMEXP_DELETE(g_lamexp_ipc_ptr
.semaphore_write
);
1744 * Initialize debug thread
1746 static const HANDLE g_debug_thread
= LAMEXP_DEBUG
? NULL
: lamexp_debug_thread_init();
1749 * Get number private bytes [debug only]
1751 SIZE_T
lamexp_dbg_private_bytes(void)
1754 PROCESS_MEMORY_COUNTERS_EX memoryCounters
;
1755 memoryCounters
.cb
= sizeof(PROCESS_MEMORY_COUNTERS_EX
);
1756 GetProcessMemoryInfo(GetCurrentProcess(), (PPROCESS_MEMORY_COUNTERS
) &memoryCounters
, sizeof(PROCESS_MEMORY_COUNTERS_EX
));
1757 return memoryCounters
.PrivateUsage
;
1759 throw "Cannot call this function in a non-debug build!";
1760 #endif //LAMEXP_DEBUG