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>
47 #include "LockedFile.h"
63 //Static build only macros
65 #pragma warning(disable:4101)
66 #define LAMEXP_INIT_QT_STATIC_PLUGIN(X) Q_IMPORT_PLUGIN(X)
68 #define LAMEXP_INIT_QT_STATIC_PLUGIN(X)
71 ///////////////////////////////////////////////////////////////////////////////
73 ///////////////////////////////////////////////////////////////////////////////
78 unsigned int reserved_1
;
79 unsigned int reserved_2
;
83 ///////////////////////////////////////////////////////////////////////////////
85 ///////////////////////////////////////////////////////////////////////////////
90 unsigned int ver_major
;
91 unsigned int ver_minor
;
92 unsigned int ver_build
;
93 char *ver_release_name
;
104 static QDate g_lamexp_version_date
;
105 static const char *g_lamexp_months
[] = {"Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"};
106 static const char *g_lamexp_version_raw_date
= __DATE__
;
110 static const char *g_lamexp_version_compiler
= "MSVC 8.0";
113 static const char *g_lamexp_version_compiler
= "MSVC 9.0";
116 static const char *g_lamexp_version_compiler
= "MSVC 10.0";
118 static const char *g_lamexp_version_compiler
= "UNKNOWN";
123 //Tool versions (expected)
124 static const unsigned int g_lamexp_toolver_neroaac
= VER_LAMEXP_TOOL_NEROAAC
;
127 static QString g_lamexp_temp_folder
;
130 static QMap
<QString
, LockedFile
*> g_lamexp_tool_registry
;
131 static QMap
<QString
, unsigned int> g_lamexp_tool_versions
;
136 QMap
<QString
, QString
> files
;
137 QMap
<QString
, QString
> names
;
138 QMap
<QString
, unsigned int> sysid
;
140 g_lamexp_translation
;
143 static QTranslator
*g_lamexp_currentTranslator
= NULL
;
149 char *semaphore_read
;
150 char *semaphore_write
;
154 "{21A68A42-6923-43bb-9CF6-64BF151942EE}",
155 "{7A605549-F58C-4d78-B4E5-06EFC34F405B}",
156 "{60AA8D04-F6B8-497d-81EB-0F600F4A65B5}"
160 QSharedMemory
*sharedmem
;
161 QSystemSemaphore
*semaphore_read
;
162 QSystemSemaphore
*semaphore_write
;
170 static const char *g_lamexp_imageformats
[] = {"png", "gif", "ico", "svg", NULL
};
173 static QMutex g_lamexp_message_mutex
;
175 ///////////////////////////////////////////////////////////////////////////////
177 ///////////////////////////////////////////////////////////////////////////////
182 unsigned int lamexp_version_major(void) { return g_lamexp_version
.ver_major
; }
183 unsigned int lamexp_version_minor(void) { return g_lamexp_version
.ver_minor
; }
184 unsigned int lamexp_version_build(void) { return g_lamexp_version
.ver_build
; }
185 const char *lamexp_version_release(void) { return g_lamexp_version
.ver_release_name
; }
186 const char *lamexp_version_compiler(void) {return g_lamexp_version_compiler
; }
187 unsigned int lamexp_toolver_neroaac(void) { return g_lamexp_toolver_neroaac
; }
189 bool lamexp_version_demo(void)
192 return LAMEXP_DEBUG
|| !(strstr(g_lamexp_version
.ver_release_name
, "Final") || strstr(g_lamexp_version
.ver_release_name
, "Hotfix"));
195 QDate
lamexp_version_expires(void)
197 return lamexp_version_date().addDays(30);
201 * Get build date date
203 const QDate
&lamexp_version_date(void)
205 if(!g_lamexp_version_date
.isValid())
210 char *this_token
= NULL
;
211 char *next_token
= NULL
;
213 strcpy_s(temp
, 32, g_lamexp_version_raw_date
);
214 this_token
= strtok_s(temp
, " ", &next_token
);
216 for(int i
= 0; i
< 3; i
++)
221 for(int j
= 0; j
< 12; j
++)
223 if(!_strcmpi(this_token
, g_lamexp_months
[j
]))
231 date
[i
] = atoi(this_token
);
233 this_token
= strtok_s(NULL
, " ", &next_token
);
237 if(date
[0] >= 0 && date
[1] >= 0 && date
[2] >= 0)
239 g_lamexp_version_date
= QDate(date
[2], date
[0], date
[1]);
243 return g_lamexp_version_date
;
249 void lamexp_message_handler(QtMsgType type
, const char *msg
)
251 static HANDLE hConsole
= NULL
;
252 QMutexLocker
lock(&g_lamexp_message_mutex
);
256 hConsole
= CreateFile(L
"CONOUT$", GENERIC_WRITE
, FILE_SHARE_WRITE
| FILE_SHARE_READ
, NULL
, OPEN_EXISTING
, NULL
, NULL
);
257 if(hConsole
== INVALID_HANDLE_VALUE
) hConsole
= NULL
;
260 CONSOLE_SCREEN_BUFFER_INFO bufferInfo
;
261 GetConsoleScreenBufferInfo(hConsole
, &bufferInfo
);
262 SetConsoleOutputCP(CP_UTF8
);
270 SetConsoleTextAttribute(hConsole
, FOREGROUND_RED
| FOREGROUND_INTENSITY
);
271 fwprintf(stderr
, L
"\nGURU MEDITATION !!!\n%S\n\n", msg
);
272 MessageBoxW(NULL
, (wchar_t*) QString::fromUtf8(msg
).utf16(), L
"LameXP - GURU MEDITATION", MB_ICONERROR
| MB_TOPMOST
| MB_TASKMODAL
);
275 SetConsoleTextAttribute(hConsole
, FOREGROUND_GREEN
| FOREGROUND_RED
| FOREGROUND_INTENSITY
);
276 //MessageBoxW(NULL, (wchar_t*) QString::fromUtf8(msg).utf16(), L"LameXP - GURU MEDITATION", MB_ICONWARNING | MB_TOPMOST | MB_TASKMODAL);
277 fwprintf(stderr
, L
"%S\n", msg
);
281 SetConsoleTextAttribute(hConsole
, FOREGROUND_BLUE
| FOREGROUND_GREEN
| FOREGROUND_RED
| FOREGROUND_INTENSITY
);
282 fwprintf(stderr
, L
"%S\n", msg
);
287 SetConsoleTextAttribute(hConsole
, FOREGROUND_BLUE
| FOREGROUND_GREEN
| FOREGROUND_RED
);
289 if(type
== QtCriticalMsg
|| type
== QtFatalMsg
)
292 FatalAppExit(0, L
"The application has encountered a critical error and will exit now!");
293 TerminateProcess(GetCurrentProcess(), -1);
298 * Initialize the console
300 void lamexp_init_console(int argc
, char* argv
[])
302 for(int i
= 0; i
< argc
; i
++)
304 if(lamexp_version_demo() || !_stricmp(argv
[i
], "--console"))
308 //See: http://support.microsoft.com/default.aspx?scid=kb;en-us;105305
309 int hCrtStdOut
= _open_osfhandle((long) GetStdHandle(STD_OUTPUT_HANDLE
), _O_TEXT
);
310 int hCrtStdErr
= _open_osfhandle((long) GetStdHandle(STD_ERROR_HANDLE
), _O_TEXT
);
311 FILE *hfStdOut
= _fdopen(hCrtStdOut
, "w");
312 FILE *hfStderr
= _fdopen(hCrtStdErr
, "w");
315 setvbuf(stdout
, NULL
, _IONBF
, 0);
316 setvbuf(stderr
, NULL
, _IONBF
, 0);
319 HMENU hMenu
= GetSystemMenu(GetConsoleWindow(), 0);
320 EnableMenuItem(hMenu
, SC_CLOSE
, MF_BYCOMMAND
| MF_GRAYED
);
321 RemoveMenu(hMenu
, SC_CLOSE
, MF_BYCOMMAND
);
323 SetConsoleCtrlHandler(NULL
, TRUE
);
324 SetConsoleTitle(L
"LameXP - Audio Encoder Front-End | Debug Console");
325 SetConsoleOutputCP(CP_UTF8
);
333 * Detect CPU features
335 lamexp_cpu_t
lamexp_detect_cpu_features(void)
337 typedef BOOL (WINAPI
*IsWow64ProcessFun
)(__in HANDLE hProcess
, __out PBOOL Wow64Process
);
338 typedef VOID (WINAPI
*GetNativeSystemInfoFun
)(__out LPSYSTEM_INFO lpSystemInfo
);
340 static IsWow64ProcessFun IsWow64ProcessPtr
= NULL
;
341 static GetNativeSystemInfoFun GetNativeSystemInfoPtr
= NULL
;
343 lamexp_cpu_t features
;
344 SYSTEM_INFO systemInfo
;
345 int CPUInfo
[4] = {-1};
346 char CPUIdentificationString
[0x40];
347 char CPUBrandString
[0x40];
349 memset(&features
, 0, sizeof(lamexp_cpu_t
));
350 memset(&systemInfo
, 0, sizeof(SYSTEM_INFO
));
351 memset(CPUIdentificationString
, 0, sizeof(CPUIdentificationString
));
352 memset(CPUBrandString
, 0, sizeof(CPUBrandString
));
355 memcpy(CPUIdentificationString
, &CPUInfo
[1], sizeof(int));
356 memcpy(CPUIdentificationString
+ 4, &CPUInfo
[3], sizeof(int));
357 memcpy(CPUIdentificationString
+ 8, &CPUInfo
[2], sizeof(int));
358 features
.intel
= (_stricmp(CPUIdentificationString
, "GenuineIntel") == 0);
359 strcpy_s(features
.vendor
, 0x40, CPUIdentificationString
);
364 features
.mmx
= (CPUInfo
[3] & 0x800000) || false;
365 features
.sse
= (CPUInfo
[3] & 0x2000000) || false;
366 features
.sse2
= (CPUInfo
[3] & 0x4000000) || false;
367 features
.ssse3
= (CPUInfo
[2] & 0x200) || false;
368 features
.sse3
= (CPUInfo
[2] & 0x1) || false;
369 features
.ssse3
= (CPUInfo
[2] & 0x200) || false;
370 features
.stepping
= CPUInfo
[0] & 0xf;
371 features
.model
= ((CPUInfo
[0] >> 4) & 0xf) + (((CPUInfo
[0] >> 16) & 0xf) << 4);
372 features
.family
= ((CPUInfo
[0] >> 8) & 0xf) + ((CPUInfo
[0] >> 20) & 0xff);
375 __cpuid(CPUInfo
, 0x80000000);
376 int nExIds
= max(min(CPUInfo
[0], 0x80000004), 0x80000000);
378 for(int i
= 0x80000002; i
<= nExIds
; ++i
)
384 memcpy(CPUBrandString
, CPUInfo
, sizeof(CPUInfo
));
387 memcpy(CPUBrandString
+ 16, CPUInfo
, sizeof(CPUInfo
));
390 memcpy(CPUBrandString
+ 32, CPUInfo
, sizeof(CPUInfo
));
395 strcpy_s(features
.brand
, 0x40, CPUBrandString
);
397 if(strlen(features
.brand
) < 1) strcpy_s(features
.brand
, 0x40, "Unknown");
398 if(strlen(features
.vendor
) < 1) strcpy_s(features
.vendor
, 0x40, "Unknown");
400 #if !defined(_M_X64 ) && !defined(_M_IA64)
401 if(!IsWow64ProcessPtr
|| !GetNativeSystemInfoPtr
)
403 QLibrary
Kernel32Lib("kernel32.dll");
404 IsWow64ProcessPtr
= (IsWow64ProcessFun
) Kernel32Lib
.resolve("IsWow64Process");
405 GetNativeSystemInfoPtr
= (GetNativeSystemInfoFun
) Kernel32Lib
.resolve("GetNativeSystemInfo");
407 if(IsWow64ProcessPtr
)
410 if(IsWow64ProcessPtr(GetCurrentProcess(), &x64
))
415 if(GetNativeSystemInfoPtr
)
417 GetNativeSystemInfoPtr(&systemInfo
);
421 GetSystemInfo(&systemInfo
);
423 features
.count
= systemInfo
.dwNumberOfProcessors
;
425 GetNativeSystemInfo(&systemInfo
);
426 features
.count
= systemInfo
.dwNumberOfProcessors
;
436 void WINAPI
debugThreadProc(__in LPVOID lpParameter
)
438 BOOL remoteDebuggerPresent
= FALSE
;
439 //CheckRemoteDebuggerPresent(GetCurrentProcess, &remoteDebuggerPresent);
441 while(!IsDebuggerPresent() && !remoteDebuggerPresent
)
444 //CheckRemoteDebuggerPresent(GetCurrentProcess, &remoteDebuggerPresent);
447 TerminateProcess(GetCurrentProcess(), -1);
451 * Check for compatibility mode
453 static bool lamexp_check_compatibility_mode(const char *exportName
)
455 QLibrary
kernel32("kernel32.dll");
457 if(exportName
!= NULL
)
459 if(kernel32
.resolve(exportName
) != NULL
)
461 qFatal("Windows compatibility mode detected. Program will exit!");
470 * Check for process elevation
472 static bool lamexp_check_elevation(void)
474 typedef enum { lamexp_token_elevationType_class
= 18, lamexp_token_elevation_class
= 20 } LAMEXP_TOKEN_INFORMATION_CLASS
;
475 typedef enum { lamexp_elevationType_default
= 1, lamexp_elevationType_full
, lamexp_elevationType_limited
} LAMEXP_TOKEN_ELEVATION_TYPE
;
477 HANDLE hToken
= NULL
;
478 bool bIsProcessElevated
= false;
480 if(OpenProcessToken(GetCurrentProcess(), TOKEN_QUERY
, &hToken
))
482 LAMEXP_TOKEN_ELEVATION_TYPE tokenElevationType
;
484 if(GetTokenInformation(hToken
, (TOKEN_INFORMATION_CLASS
) lamexp_token_elevationType_class
, &tokenElevationType
, sizeof(LAMEXP_TOKEN_ELEVATION_TYPE
), &returnLength
))
486 if(returnLength
== sizeof(LAMEXP_TOKEN_ELEVATION_TYPE
))
488 switch(tokenElevationType
)
490 case lamexp_elevationType_default
:
491 qDebug("Process token elevation type: Default -> UAC is disabled.\n");
493 case lamexp_elevationType_full
:
494 qWarning("Process token elevation type: Full -> potential security risk!\n");
495 bIsProcessElevated
= true;
497 case lamexp_elevationType_limited
:
498 qDebug("Process token elevation type: Limited -> not elevated.\n");
507 qWarning("Failed to open process token!");
510 return !bIsProcessElevated
;
514 * Initialize Qt framework
516 bool lamexp_init_qt(int argc
, char* argv
[])
518 static bool qt_initialized
= false;
520 //Don't initialized again, if done already
527 qDebug("Using Qt Framework v%s, compiled with Qt v%s", qVersion(), QT_VERSION_STR
);
528 QT_REQUIRE_VERSION(argc
, argv
, QT_VERSION_STR
);
530 //Check the Windows version
531 switch(QSysInfo::windowsVersion() & QSysInfo::WV_NT_based
)
533 case QSysInfo::WV_2000
:
534 qDebug("Running on Windows 2000 (not offically supported!).\n");
535 lamexp_check_compatibility_mode("GetNativeSystemInfo");
537 case QSysInfo::WV_XP
:
538 qDebug("Running on Windows XP.\n");
539 lamexp_check_compatibility_mode("GetLargePageMinimum");
541 case QSysInfo::WV_2003
:
542 qDebug("Running on Windows Server 2003 or Windows XP x64-Edition.\n");
543 lamexp_check_compatibility_mode("GetLocaleInfoEx");
545 case QSysInfo::WV_VISTA
:
546 qDebug("Running on Windows Vista or Windows Server 2008.\n");
547 lamexp_check_compatibility_mode("CreateRemoteThreadEx");
549 case QSysInfo::WV_WINDOWS7
:
550 qDebug("Running on Windows 7 or Windows Server 2008 R2.\n");
551 lamexp_check_compatibility_mode(NULL
);
554 qFatal("Unsupported OS, only Windows 2000 or later is supported!");
558 //Create Qt application instance and setup version info
559 QApplication
*application
= new QApplication(argc
, argv
);
560 application
->setApplicationName("LameXP - Audio Encoder Front-End");
561 application
->setApplicationVersion(QString().sprintf("%d.%02d.%04d", lamexp_version_major(), lamexp_version_minor(), lamexp_version_build()));
562 application
->setOrganizationName("LoRd_MuldeR");
563 application
->setOrganizationDomain("mulder.dummwiedeutsch.de");
564 application
->setWindowIcon(QIcon(":/MainIcon.png"));
566 //Load plugins from application directory
567 QCoreApplication::setLibraryPaths(QStringList() << QApplication::applicationDirPath());
568 qDebug("Library Path:\n%s\n", QApplication::libraryPaths().first().toUtf8().constData());
570 //Init static Qt plugins
571 LAMEXP_INIT_QT_STATIC_PLUGIN(qico
);
572 LAMEXP_INIT_QT_STATIC_PLUGIN(qsvg
);
574 //Check for supported image formats
575 QList
<QByteArray
> supportedFormats
= QImageReader::supportedImageFormats();
576 for(int i
= 0; g_lamexp_imageformats
[i
]; i
++)
578 if(!supportedFormats
.contains(g_lamexp_imageformats
[i
]))
580 qFatal("Qt initialization error: At least one image format plugin is missing! (%s)", g_lamexp_imageformats
[i
]);
585 //Add default translations
586 g_lamexp_translation
.files
.insert(LAMEXP_DEFAULT_LANGID
, "");
587 g_lamexp_translation
.names
.insert(LAMEXP_DEFAULT_LANGID
, "English");
589 //Init language files
590 //lamexp_init_translations();
592 //Check for process elevation
593 if(!lamexp_check_elevation())
595 if(QMessageBox::warning(NULL
, "LameXP", "<nobr>LameXP was started with elevated rights. This is a potential security risk!</nobr>", "Quit Program (Recommended)", "Ignore") == 0)
602 qt_initialized
= true;
609 int lamexp_init_ipc(void)
611 if(g_lamexp_ipc_ptr
.sharedmem
&& g_lamexp_ipc_ptr
.semaphore_read
&& g_lamexp_ipc_ptr
.semaphore_write
)
616 g_lamexp_ipc_ptr
.semaphore_read
= new QSystemSemaphore(QString(g_lamexp_ipc_uuid
.semaphore_read
), 0);
617 g_lamexp_ipc_ptr
.semaphore_write
= new QSystemSemaphore(QString(g_lamexp_ipc_uuid
.semaphore_write
), 0);
619 if(g_lamexp_ipc_ptr
.semaphore_read
->error() != QSystemSemaphore::NoError
)
621 QString errorMessage
= g_lamexp_ipc_ptr
.semaphore_read
->errorString();
622 LAMEXP_DELETE(g_lamexp_ipc_ptr
.semaphore_read
);
623 LAMEXP_DELETE(g_lamexp_ipc_ptr
.semaphore_write
);
624 qFatal("Failed to create system smaphore: %s", errorMessage
.toUtf8().constData());
627 if(g_lamexp_ipc_ptr
.semaphore_write
->error() != QSystemSemaphore::NoError
)
629 QString errorMessage
= g_lamexp_ipc_ptr
.semaphore_write
->errorString();
630 LAMEXP_DELETE(g_lamexp_ipc_ptr
.semaphore_read
);
631 LAMEXP_DELETE(g_lamexp_ipc_ptr
.semaphore_write
);
632 qFatal("Failed to create system smaphore: %s", errorMessage
.toUtf8().constData());
636 g_lamexp_ipc_ptr
.sharedmem
= new QSharedMemory(QString(g_lamexp_ipc_uuid
.sharedmem
), NULL
);
638 if(!g_lamexp_ipc_ptr
.sharedmem
->create(sizeof(lamexp_ipc_t
)))
640 if(g_lamexp_ipc_ptr
.sharedmem
->error() == QSharedMemory::AlreadyExists
)
642 g_lamexp_ipc_ptr
.sharedmem
->attach();
643 if(g_lamexp_ipc_ptr
.sharedmem
->error() == QSharedMemory::NoError
)
649 QString errorMessage
= g_lamexp_ipc_ptr
.sharedmem
->errorString();
650 qFatal("Failed to attach to shared memory: %s", errorMessage
.toUtf8().constData());
656 QString errorMessage
= g_lamexp_ipc_ptr
.sharedmem
->errorString();
657 qFatal("Failed to create shared memory: %s", errorMessage
.toUtf8().constData());
662 memset(g_lamexp_ipc_ptr
.sharedmem
->data(), 0, sizeof(lamexp_ipc_t
));
663 g_lamexp_ipc_ptr
.semaphore_write
->release();
671 void lamexp_ipc_send(unsigned int command
, const char* message
)
673 if(!g_lamexp_ipc_ptr
.sharedmem
|| !g_lamexp_ipc_ptr
.semaphore_read
|| !g_lamexp_ipc_ptr
.semaphore_write
)
675 throw "Shared memory for IPC not initialized yet.";
678 lamexp_ipc_t
*lamexp_ipc
= new lamexp_ipc_t
;
679 memset(lamexp_ipc
, 0, sizeof(lamexp_ipc_t
));
680 lamexp_ipc
->command
= command
;
683 strcpy_s(lamexp_ipc
->parameter
, 4096, message
);
686 if(g_lamexp_ipc_ptr
.semaphore_write
->acquire())
688 memcpy(g_lamexp_ipc_ptr
.sharedmem
->data(), lamexp_ipc
, sizeof(lamexp_ipc_t
));
689 g_lamexp_ipc_ptr
.semaphore_read
->release();
692 LAMEXP_DELETE(lamexp_ipc
);
698 void lamexp_ipc_read(unsigned int *command
, char* message
, size_t buffSize
)
703 if(!g_lamexp_ipc_ptr
.sharedmem
|| !g_lamexp_ipc_ptr
.semaphore_read
|| !g_lamexp_ipc_ptr
.semaphore_write
)
705 throw "Shared memory for IPC not initialized yet.";
708 lamexp_ipc_t
*lamexp_ipc
= new lamexp_ipc_t
;
709 memset(lamexp_ipc
, 0, sizeof(lamexp_ipc_t
));
711 if(g_lamexp_ipc_ptr
.semaphore_read
->acquire())
713 memcpy(lamexp_ipc
, g_lamexp_ipc_ptr
.sharedmem
->data(), sizeof(lamexp_ipc_t
));
714 g_lamexp_ipc_ptr
.semaphore_write
->release();
716 if(!(lamexp_ipc
->reserved_1
|| lamexp_ipc
->reserved_2
))
718 *command
= lamexp_ipc
->command
;
719 strcpy_s(message
, buffSize
, lamexp_ipc
->parameter
);
723 qWarning("Malformed IPC message, will be ignored");
727 LAMEXP_DELETE(lamexp_ipc
);
731 * Check for LameXP "portable" mode
733 bool lamexp_portable_mode(void)
735 QString baseName
= QFileInfo(QApplication::applicationFilePath()).completeBaseName();
736 return baseName
.contains("lamexp", Qt::CaseInsensitive
) && baseName
.contains("portable", Qt::CaseInsensitive
);
740 * Get a random string
742 QString
lamexp_rand_str(void)
744 QRegExp
regExp("\\{(\\w+)-(\\w+)-(\\w+)-(\\w+)-(\\w+)\\}");
745 QString uuid
= QUuid::createUuid().toString();
747 if(regExp
.indexIn(uuid
) >= 0)
749 return QString().append(regExp
.cap(1)).append(regExp
.cap(2)).append(regExp
.cap(3)).append(regExp
.cap(4)).append(regExp
.cap(5));
752 throw "The RegExp didn't match on the UUID string. This shouldn't happen ;-)";
756 * Get LameXP temp folder
758 const QString
&lamexp_temp_folder(void)
760 static const char *TEMP_STR
= "Temp";
762 if(g_lamexp_temp_folder
.isEmpty())
764 QDir temp
= QDir::temp();
765 QDir localAppData
= QDir(lamexp_known_folder(lamexp_folder_localappdata
));
767 if(!localAppData
.path().isEmpty() && localAppData
.exists())
769 if(!localAppData
.entryList(QDir::AllDirs
).contains(TEMP_STR
, Qt::CaseInsensitive
))
771 localAppData
.mkdir(TEMP_STR
);
773 if(localAppData
.cd(TEMP_STR
))
775 temp
.setPath(localAppData
.absolutePath());
784 qFatal("The system's temporary directory does not exist:\n%s", temp
.absolutePath().toUtf8().constData());
785 return g_lamexp_temp_folder
;
789 QString subDir
= QString("%1.tmp").arg(lamexp_rand_str());
790 if(!temp
.mkdir(subDir
))
792 qFatal("Temporary directory could not be created:\n%s", QString("%1/%2").arg(temp
.canonicalPath(), subDir
).toUtf8().constData());
793 return g_lamexp_temp_folder
;
797 qFatal("Temporary directory could not be entered:\n%s", QString("%1/%2").arg(temp
.canonicalPath(), subDir
).toUtf8().constData());
798 return g_lamexp_temp_folder
;
801 QFile
testFile(QString("%1/.%2").arg(temp
.canonicalPath(), lamexp_rand_str()));
802 if(!testFile
.open(QIODevice::ReadWrite
) || testFile
.write("LAMEXP_TEST\n") < 12)
804 qFatal("Write access to temporary directory has been denied:\n%s", temp
.canonicalPath().toUtf8().constData());
805 return g_lamexp_temp_folder
;
809 QFile::remove(testFile
.fileName());
811 g_lamexp_temp_folder
= temp
.canonicalPath();
814 return g_lamexp_temp_folder
;
820 bool lamexp_clean_folder(const QString folderPath
)
822 QDir
tempFolder(folderPath
);
823 QFileInfoList entryList
= tempFolder
.entryInfoList(QDir::AllEntries
| QDir::NoDotAndDotDot
);
825 for(int i
= 0; i
< entryList
.count(); i
++)
827 if(entryList
.at(i
).isDir())
829 lamexp_clean_folder(entryList
.at(i
).canonicalFilePath());
833 for(int j
= 0; j
< 3; j
++)
835 if(lamexp_remove_file(entryList
.at(i
).canonicalFilePath()))
843 tempFolder
.rmdir(".");
844 return !tempFolder
.exists();
850 void lamexp_register_tool(const QString
&toolName
, LockedFile
*file
, unsigned int version
)
852 if(g_lamexp_tool_registry
.contains(toolName
.toLower()))
854 throw "lamexp_register_tool: Tool is already registered!";
857 g_lamexp_tool_registry
.insert(toolName
.toLower(), file
);
858 g_lamexp_tool_versions
.insert(toolName
.toLower(), version
);
864 bool lamexp_check_tool(const QString
&toolName
)
866 return g_lamexp_tool_registry
.contains(toolName
.toLower());
872 const QString
lamexp_lookup_tool(const QString
&toolName
)
874 if(g_lamexp_tool_registry
.contains(toolName
.toLower()))
876 return g_lamexp_tool_registry
.value(toolName
.toLower())->filePath();
885 * Lookup tool version
887 unsigned int lamexp_tool_version(const QString
&toolName
)
889 if(g_lamexp_tool_versions
.contains(toolName
.toLower()))
891 return g_lamexp_tool_versions
.value(toolName
.toLower());
900 * Version number to human-readable string
902 const QString
lamexp_version2string(const QString
&pattern
, unsigned int version
, const QString
&defaultText
)
904 if(version
== UINT_MAX
)
909 QString result
= pattern
;
910 int digits
= result
.count("?", Qt::CaseInsensitive
);
918 QString versionStr
= QString().sprintf(QString().sprintf("%%0%du", digits
).toLatin1().constData(), version
);
919 int index
= result
.indexOf("?", Qt::CaseInsensitive
);
921 while(index
>= 0 && pos
< versionStr
.length())
923 result
[index
] = versionStr
[pos
++];
924 index
= result
.indexOf("?", Qt::CaseInsensitive
);
931 * Register a new translation
933 bool lamexp_translation_register(const QString
&langId
, const QString
&qmFile
, const QString
&langName
, unsigned int &systemId
)
935 if(qmFile
.isEmpty() || langName
.isEmpty() || systemId
< 1)
940 g_lamexp_translation
.files
.insert(langId
, qmFile
);
941 g_lamexp_translation
.names
.insert(langId
, langName
);
942 g_lamexp_translation
.sysid
.insert(langId
, systemId
);
948 * Get list of all translations
950 QStringList
lamexp_query_translations(void)
952 return g_lamexp_translation
.files
.keys();
956 * Get translation name
958 QString
lamexp_translation_name(const QString
&langId
)
960 return g_lamexp_translation
.names
.value(langId
.toLower(), QString());
964 * Get translation system id
966 unsigned int lamexp_translation_sysid(const QString
&langId
)
968 return g_lamexp_translation
.sysid
.value(langId
.toLower(), 0);
972 * Install a new translator
974 bool lamexp_install_translator(const QString
&langId
)
976 bool success
= false;
978 if(langId
.isEmpty() || langId
.toLower().compare(LAMEXP_DEFAULT_LANGID
) == 0)
980 success
= lamexp_install_translator_from_file(QString());
984 QString qmFile
= g_lamexp_translation
.files
.value(langId
.toLower(), QString());
985 if(!qmFile
.isEmpty())
987 success
= lamexp_install_translator_from_file(QString(":/localization/%1").arg(qmFile
));
991 qWarning("Translation '%s' not available!", langId
.toLatin1().constData());
999 * Install a new translator from file
1001 bool lamexp_install_translator_from_file(const QString
&qmFile
)
1003 bool success
= false;
1005 if(!g_lamexp_currentTranslator
)
1007 g_lamexp_currentTranslator
= new QTranslator();
1010 if(!qmFile
.isEmpty())
1012 QString qmPath
= QFileInfo(qmFile
).canonicalFilePath();
1013 QApplication::removeTranslator(g_lamexp_currentTranslator
);
1014 success
= g_lamexp_currentTranslator
->load(qmPath
);
1015 QApplication::installTranslator(g_lamexp_currentTranslator
);
1018 qWarning("Failed to load translation:\n\"%s\"", qmPath
.toLatin1().constData());
1023 QApplication::removeTranslator(g_lamexp_currentTranslator
);
1031 * Locate known folder on local system
1033 QString
lamexp_known_folder(lamexp_known_folder_t folder_id
)
1035 typedef HRESULT (WINAPI
*SHGetKnownFolderPathFun
)(__in
const GUID
&rfid
, __in DWORD dwFlags
, __in HANDLE hToken
, __out PWSTR
*ppszPath
);
1036 typedef HRESULT (WINAPI
*SHGetFolderPathFun
)(__in HWND hwndOwner
, __in
int nFolder
, __in HANDLE hToken
, __in DWORD dwFlags
, __out LPWSTR pszPath
);
1038 static const int CSIDL_LOCAL_APPDATA
= 0x001c;
1039 static const int CSIDL_PROGRAM_FILES
= 0x0026;
1040 static const int CSIDL_SYSTEM_FOLDER
= 0x0025;
1041 static const GUID GUID_LOCAL_APPDATA
= {0xF1B32785,0x6FBA,0x4FCF,{0x9D,0x55,0x7B,0x8E,0x7F,0x15,0x70,0x91}};
1042 static const GUID GUID_LOCAL_APPDATA_LOW
= {0xA520A1A4,0x1780,0x4FF6,{0xBD,0x18,0x16,0x73,0x43,0xC5,0xAF,0x16}};
1043 static const GUID GUID_PROGRAM_FILES
= {0x905e63b6,0xc1bf,0x494e,{0xb2,0x9c,0x65,0xb7,0x32,0xd3,0xd2,0x1a}};
1044 static const GUID GUID_SYSTEM_FOLDER
= {0x1AC14E77,0x02E7,0x4E5D,{0xB7,0x44,0x2E,0xB1,0xAE,0x51,0x98,0xB7}};
1046 static QLibrary
*Kernel32Lib
= NULL
;
1047 static SHGetKnownFolderPathFun SHGetKnownFolderPathPtr
= NULL
;
1048 static SHGetFolderPathFun SHGetFolderPathPtr
= NULL
;
1050 if((!SHGetKnownFolderPathPtr
) && (!SHGetFolderPathPtr
))
1052 if(!Kernel32Lib
) Kernel32Lib
= new QLibrary("shell32.dll");
1053 SHGetKnownFolderPathPtr
= (SHGetKnownFolderPathFun
) Kernel32Lib
->resolve("SHGetKnownFolderPath");
1054 SHGetFolderPathPtr
= (SHGetFolderPathFun
) Kernel32Lib
->resolve("SHGetFolderPathW");
1057 int folderCSIDL
= -1;
1058 GUID folderGUID
= {0x0000,0x0000,0x0000,{0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00}};
1062 case lamexp_folder_localappdata
:
1063 folderCSIDL
= CSIDL_LOCAL_APPDATA
;
1064 folderGUID
= GUID_LOCAL_APPDATA
;
1066 case lamexp_folder_programfiles
:
1067 folderCSIDL
= CSIDL_PROGRAM_FILES
;
1068 folderGUID
= GUID_PROGRAM_FILES
;
1070 case lamexp_folder_systemfolder
:
1071 folderCSIDL
= CSIDL_SYSTEM_FOLDER
;
1072 folderGUID
= GUID_SYSTEM_FOLDER
;
1081 if(SHGetKnownFolderPathPtr
)
1084 if(SHGetKnownFolderPathPtr(folderGUID
, 0x00008000, NULL
, &path
) == S_OK
)
1086 //MessageBoxW(0, path, L"SHGetKnownFolderPath", MB_TOPMOST);
1087 QDir folderTemp
= QDir(QDir::fromNativeSeparators(QString::fromUtf16(reinterpret_cast<const unsigned short*>(path
))));
1088 if(!folderTemp
.exists())
1090 folderTemp
.mkpath(".");
1092 if(folderTemp
.exists())
1094 folder
= folderTemp
.canonicalPath();
1096 CoTaskMemFree(path
);
1099 else if(SHGetFolderPathPtr
)
1101 WCHAR
*path
= new WCHAR
[4096];
1102 if(SHGetFolderPathPtr(NULL
, folderCSIDL
, NULL
, NULL
, path
) == S_OK
)
1104 //MessageBoxW(0, path, L"SHGetFolderPathW", MB_TOPMOST);
1105 QDir folderTemp
= QDir(QDir::fromNativeSeparators(QString::fromUtf16(reinterpret_cast<const unsigned short*>(path
))));
1106 if(!folderTemp
.exists())
1108 folderTemp
.mkpath(".");
1110 if(folderTemp
.exists())
1112 folder
= folderTemp
.canonicalPath();
1122 * Safely remove a file
1124 bool lamexp_remove_file(const QString
&filename
)
1126 if(!QFileInfo(filename
).exists() || !QFileInfo(filename
).isFile())
1132 if(!QFile::remove(filename
))
1134 DWORD attributes
= GetFileAttributesW(reinterpret_cast<const wchar_t*>(filename
.utf16()));
1135 SetFileAttributesW(reinterpret_cast<const wchar_t*>(filename
.utf16()), (attributes
& (~FILE_ATTRIBUTE_READONLY
)));
1136 if(!QFile::remove(filename
))
1138 qWarning("Could not delete \"%s\"", filename
.toLatin1().constData());
1154 * Check if visual themes are enabled (WinXP and later)
1156 bool lamexp_themes_enabled(void)
1158 typedef int (WINAPI
*IsAppThemedFun
)(void);
1160 bool isAppThemed
= false;
1161 QLibrary
uxTheme(QString("%1/UxTheme.dll").arg(lamexp_known_folder(lamexp_folder_systemfolder
)));
1162 IsAppThemedFun IsAppThemedPtr
= (IsAppThemedFun
) uxTheme
.resolve("IsAppThemed");
1166 isAppThemed
= IsAppThemedPtr();
1169 qWarning("Theme support is disabled for this process!");
1177 * Get number of free bytes on disk
1179 __int64
lamexp_free_diskspace(const QString
&path
)
1181 ULARGE_INTEGER freeBytesAvailable
, totalNumberOfBytes
, totalNumberOfFreeBytes
;
1182 if(GetDiskFreeSpaceExW(reinterpret_cast<const wchar_t*>(QDir::toNativeSeparators(path
).utf16()), &freeBytesAvailable
, &totalNumberOfBytes
, &totalNumberOfFreeBytes
))
1184 return freeBytesAvailable
.QuadPart
;
1193 * Finalization function (final clean-up)
1195 void lamexp_finalization(void)
1198 if(!g_lamexp_tool_registry
.isEmpty())
1200 QStringList keys
= g_lamexp_tool_registry
.keys();
1201 for(int i
= 0; i
< keys
.count(); i
++)
1203 LAMEXP_DELETE(g_lamexp_tool_registry
[keys
.at(i
)]);
1205 g_lamexp_tool_registry
.clear();
1206 g_lamexp_tool_versions
.clear();
1209 //Delete temporary files
1210 if(!g_lamexp_temp_folder
.isEmpty())
1212 for(int i
= 0; i
< 100; i
++)
1214 if(lamexp_clean_folder(g_lamexp_temp_folder
))
1220 g_lamexp_temp_folder
.clear();
1224 if(g_lamexp_currentTranslator
)
1226 QApplication::removeTranslator(g_lamexp_currentTranslator
);
1227 LAMEXP_DELETE(g_lamexp_currentTranslator
);
1229 g_lamexp_translation
.files
.clear();
1230 g_lamexp_translation
.names
.clear();
1232 //Destroy Qt application object
1233 QApplication
*application
= dynamic_cast<QApplication
*>(QApplication::instance());
1234 LAMEXP_DELETE(application
);
1236 //Detach from shared memory
1237 if(g_lamexp_ipc_ptr
.sharedmem
) g_lamexp_ipc_ptr
.sharedmem
->detach();
1238 LAMEXP_DELETE(g_lamexp_ipc_ptr
.sharedmem
);
1239 LAMEXP_DELETE(g_lamexp_ipc_ptr
.semaphore_read
);
1240 LAMEXP_DELETE(g_lamexp_ipc_ptr
.semaphore_write
);
1244 * Get number private bytes [debug only]
1246 SIZE_T
lamexp_dbg_private_bytes(void)
1249 PROCESS_MEMORY_COUNTERS_EX memoryCounters
;
1250 memoryCounters
.cb
= sizeof(PROCESS_MEMORY_COUNTERS_EX
);
1251 GetProcessMemoryInfo(GetCurrentProcess(), (PPROCESS_MEMORY_COUNTERS
) &memoryCounters
, sizeof(PROCESS_MEMORY_COUNTERS_EX
));
1252 return memoryCounters
.PrivateUsage
;
1254 throw "Cannot call this function in a non-debug build!";