Updated Ukrainian translation.
[LameXP.git] / src / Global.cpp
blob3605ce3cb92cf42b4aedae7d6d518356ea934e72
1 ///////////////////////////////////////////////////////////////////////////////
2 // LameXP - Audio Encoder Front-End
3 // Copyright (C) 2004-2012 LoRd_MuldeR <MuldeR2@GMX.de>
4 //
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.
9 //
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 ///////////////////////////////////////////////////////////////////////////////
22 #include "Global.h"
24 //Qt includes
25 #include <QApplication>
26 #include <QMessageBox>
27 #include <QDir>
28 #include <QUuid>
29 #include <QMap>
30 #include <QDate>
31 #include <QIcon>
32 #include <QPlastiqueStyle>
33 #include <QImageReader>
34 #include <QSharedMemory>
35 #include <QSysInfo>
36 #include <QStringList>
37 #include <QSystemSemaphore>
38 #include <QMutex>
39 #include <QTextCodec>
40 #include <QLibrary>
41 #include <QRegExp>
42 #include <QResource>
43 #include <QTranslator>
44 #include <QEventLoop>
45 #include <QTimer>
46 #include <QLibraryInfo>
47 #include <QEvent>
48 #include <QReadWriteLock>
49 #include <QReadLocker>
50 #include <QWriteLocker>
52 //LameXP includes
53 #include "Resource.h"
54 #include "Config.h"
55 #include "LockedFile.h"
57 //CRT includes
58 #include <iostream>
59 #include <fstream>
60 #include <io.h>
61 #include <fcntl.h>
62 #include <intrin.h>
63 #include <math.h>
64 #include <time.h>
65 #include <process.h>
67 //Shell API
68 #include <Shellapi.h>
70 //COM includes
71 #include <Objbase.h>
72 #include <PowrProf.h>
74 //Process API
75 #include <Psapi.h>
77 //Initialize static Qt plugins
78 #ifdef QT_NODLL
79 #if QT_VERSION < QT_VERSION_CHECK(5,0,0)
80 Q_IMPORT_PLUGIN(qico)
81 Q_IMPORT_PLUGIN(qsvg)
82 #else
83 Q_IMPORT_PLUGIN(QWindowsIntegrationPlugin)
84 Q_IMPORT_PLUGIN(QICOPlugin)
85 #endif
86 #endif
88 #define LAMEXP_ZERO_MEMORY(X) SecureZeroMemory(&X, sizeof(X))
90 //Helper macros
91 #define _LAMEXP_MAKE_STR(STR) #STR
92 #define LAMEXP_MAKE_STR(STR) _LAMEXP_MAKE_STR(STR)
94 ///////////////////////////////////////////////////////////////////////////////
95 // TYPES
96 ///////////////////////////////////////////////////////////////////////////////
98 static const size_t g_lamexp_ipc_slots = 128;
100 typedef struct
102 unsigned int command;
103 unsigned int reserved_1;
104 unsigned int reserved_2;
105 char parameter[4096];
107 lamexp_ipc_data_t;
109 typedef struct
111 unsigned int pos_write;
112 unsigned int pos_read;
113 lamexp_ipc_data_t data[g_lamexp_ipc_slots];
115 lamexp_ipc_t;
117 ///////////////////////////////////////////////////////////////////////////////
118 // GLOBAL VARS
119 ///////////////////////////////////////////////////////////////////////////////
121 //Build version
122 static const struct
124 unsigned int ver_major;
125 unsigned int ver_minor;
126 unsigned int ver_build;
127 char *ver_release_name;
129 g_lamexp_version =
131 VER_LAMEXP_MAJOR,
132 VER_LAMEXP_MINOR,
133 VER_LAMEXP_BUILD,
134 VER_LAMEXP_RNAME
137 //Build date
138 static QDate g_lamexp_version_date;
139 static const char *g_lamexp_months[] = {"Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"};
140 static const char *g_lamexp_version_raw_date = __DATE__;
141 static const char *g_lamexp_version_raw_time = __TIME__;
143 //Console attached flag
144 static bool g_lamexp_console_attached = false;
146 //Compiler detection
147 //The following code was borrowed from MPC-HC project: http://mpc-hc.sf.net/
148 #if defined(__INTEL_COMPILER)
149 #if (__INTEL_COMPILER >= 1300)
150 static const char *g_lamexp_version_compiler = "ICL 13." LAMEXP_MAKE_STR(__INTEL_COMPILER_BUILD_DATE);
151 #elif (__INTEL_COMPILER >= 1200)
152 static const char *g_lamexp_version_compiler = "ICL 12." LAMEXP_MAKE_STR(__INTEL_COMPILER_BUILD_DATE);
153 #elif (__INTEL_COMPILER >= 1100)
154 static const char *g_lamexp_version_compiler = "ICL 11.x";
155 #elif (__INTEL_COMPILER >= 1000)
156 static const char *g_lamexp_version_compiler = "ICL 10.x";
157 #else
158 #error Compiler is not supported!
159 #endif
160 #elif defined(_MSC_VER)
161 #if (_MSC_VER == 1700)
162 #if (_MSC_FULL_VER < 170050727)
163 static const char *g_lamexp_version_compiler = "MSVC 2012-Beta";
164 #elif (_MSC_FULL_VER < 170051020)
165 static const char *g_lamexp_version_compiler = "MSVC 2012-RTM";
166 #elif (_MSC_FULL_VER < 170051106)
167 static const char *g_lamexp_version_compiler = "MSVC 2012-U1 CTP";
168 #elif (_MSC_FULL_VER == 170051106)
169 static const char *g_lamexp_version_compiler = "MSVC 2012-U1";
170 #else
171 #error Compiler version is not supported yet!
172 #endif
173 #elif (_MSC_VER == 1600)
174 #if (_MSC_FULL_VER < 160040219)
175 static const char *g_lamexp_version_compiler = "MSVC 2010-RTM";
176 #elif (_MSC_FULL_VER == 160040219)
177 static const char *g_lamexp_version_compiler = "MSVC 2010-SP1";
178 #else
179 #error Compiler version is not supported yet!
180 #endif
181 #elif (_MSC_VER == 1500)
182 #if (_MSC_FULL_VER >= 150030729)
183 static const char *g_lamexp_version_compiler = "MSVC 2008-SP1";
184 #else
185 static const char *g_lamexp_version_compiler = "MSVC 2008";
186 #endif
187 #else
188 #error Compiler is not supported!
189 #endif
191 // Note: /arch:SSE and /arch:SSE2 are only available for the x86 platform
192 #if !defined(_M_X64) && defined(_M_IX86_FP)
193 #if (_M_IX86_FP == 1)
194 LAMEXP_COMPILER_WARNING("SSE instruction set is enabled!")
195 #elif (_M_IX86_FP == 2)
196 LAMEXP_COMPILER_WARNING("SSE2 instruction set is enabled!")
197 #endif
198 #endif
199 #else
200 #error Compiler is not supported!
201 #endif
203 //Architecture detection
204 #if defined(_M_X64)
205 static const char *g_lamexp_version_arch = "x64";
206 #elif defined(_M_IX86)
207 static const char *g_lamexp_version_arch = "x86";
208 #else
209 #error Architecture is not supported!
210 #endif
212 //Official web-site URL
213 static const char *g_lamexp_website_url = "http://lamexp.sourceforge.net/";
214 static const char *g_lamexp_support_url = "http://forum.doom9.org/showthread.php?t=157726";
216 //Tool versions (expected versions!)
217 static const unsigned int g_lamexp_toolver_neroaac = VER_LAMEXP_TOOL_NEROAAC;
218 static const unsigned int g_lamexp_toolver_fhgaacenc = VER_LAMEXP_TOOL_FHGAACENC;
219 static const unsigned int g_lamexp_toolver_qaacenc = VER_LAMEXP_TOOL_QAAC;
220 static const unsigned int g_lamexp_toolver_coreaudio = VER_LAMEXP_TOOL_COREAUDIO;
222 //Special folders
223 static struct
225 QString *temp;
226 QMap<size_t, QString> *knownFolders;
227 QReadWriteLock lock;
229 g_lamexp_folder;
231 //Tools
232 static struct
234 QMap<QString, LockedFile*> *registry;
235 QMap<QString, unsigned int> *versions;
236 QReadWriteLock lock;
238 g_lamexp_tools;
240 //Languages
241 static struct
243 QMap<QString, QString> *files;
244 QMap<QString, QString> *names;
245 QMap<QString, unsigned int> *sysid;
246 QMap<QString, unsigned int> *cntry;
247 QReadWriteLock lock;
249 g_lamexp_translation;
251 //Translator
252 static struct
254 QTranslator *instance;
255 QReadWriteLock lock;
257 g_lamexp_currentTranslator;
259 //CLI Arguments
260 static struct
262 QStringList *list;
263 QReadWriteLock lock;
265 g_lamexp_argv;
267 //CLI Arguments
268 static struct
270 bool bInitialized;
271 lamexp_os_version_t version;
272 QReadWriteLock lock;
274 g_lamexp_os_version;
276 //Shared memory
277 static const struct
279 char *sharedmem;
280 char *semaphore_read;
281 char *semaphore_read_mutex;
282 char *semaphore_write;
283 char *semaphore_write_mutex;
285 g_lamexp_ipc_uuid =
287 "{21A68A42-6923-43bb-9CF6-64BF151942EE}",
288 "{7A605549-F58C-4d78-B4E5-06EFC34F405B}",
289 "{60AA8D04-F6B8-497d-81EB-0F600F4A65B5}",
290 "{726061D5-1615-4B82-871C-75FD93458E46}",
291 "{1A616023-AA6A-4519-8AF3-F7736E899977}"
293 static struct
295 QSharedMemory *sharedmem;
296 QSystemSemaphore *semaphore_read;
297 QSystemSemaphore *semaphore_read_mutex;
298 QSystemSemaphore *semaphore_write;
299 QSystemSemaphore *semaphore_write_mutex;
300 QReadWriteLock lock;
302 g_lamexp_ipc_ptr;
304 //Image formats
305 static const char *g_lamexp_imageformats[] = {"bmp", "png", "jpg", "gif", "ico", "xpm", NULL}; //"svg"
307 //Global locks
308 static QMutex g_lamexp_message_mutex;
310 //Main thread ID
311 static const DWORD g_main_thread_id = GetCurrentThreadId();
313 //Log file
314 static FILE *g_lamexp_log_file = NULL;
316 ///////////////////////////////////////////////////////////////////////////////
317 // GLOBAL FUNCTIONS
318 ///////////////////////////////////////////////////////////////////////////////
321 * Version getters
323 unsigned int lamexp_version_major(void) { return g_lamexp_version.ver_major; }
324 unsigned int lamexp_version_minor(void) { return g_lamexp_version.ver_minor; }
325 unsigned int lamexp_version_build(void) { return g_lamexp_version.ver_build; }
326 const char *lamexp_version_release(void) { return g_lamexp_version.ver_release_name; }
327 const char *lamexp_version_time(void) { return g_lamexp_version_raw_time; }
328 const char *lamexp_version_compiler(void) { return g_lamexp_version_compiler; }
329 const char *lamexp_version_arch(void) { return g_lamexp_version_arch; }
330 unsigned int lamexp_toolver_neroaac(void) { return g_lamexp_toolver_neroaac; }
331 unsigned int lamexp_toolver_fhgaacenc(void) { return g_lamexp_toolver_fhgaacenc; }
332 unsigned int lamexp_toolver_qaacenc(void) { return g_lamexp_toolver_qaacenc; }
333 unsigned int lamexp_toolver_coreaudio(void) { return g_lamexp_toolver_coreaudio; }
336 * URL getters
338 const char *lamexp_website_url(void) { return g_lamexp_website_url; }
339 const char *lamexp_support_url(void) { return g_lamexp_support_url; }
342 * Check for Demo (pre-release) version
344 bool lamexp_version_demo(void)
346 char buffer[128];
347 bool releaseVersion = false;
348 if(!strncpy_s(buffer, 128, g_lamexp_version.ver_release_name, _TRUNCATE))
350 char *context, *prefix = strtok_s(buffer, "-,; ", &context);
351 if(prefix)
353 releaseVersion = (!_stricmp(prefix, "Final")) || (!_stricmp(prefix, "Hotfix"));
356 return LAMEXP_DEBUG || (!releaseVersion);
360 * Calculate expiration date
362 QDate lamexp_version_expires(void)
364 return lamexp_version_date().addDays(LAMEXP_DEBUG ? 7 : 30);
368 * Get build date date
370 const QDate &lamexp_version_date(void)
372 if(!g_lamexp_version_date.isValid())
374 int date[3] = {0, 0, 0}; char temp[12] = {'\0'};
375 strncpy_s(temp, 12, g_lamexp_version_raw_date, _TRUNCATE);
377 if(strlen(temp) == 11)
379 temp[3] = temp[6] = '\0';
380 date[2] = atoi(&temp[4]);
381 date[0] = atoi(&temp[7]);
383 for(int j = 0; j < 12; j++)
385 if(!_strcmpi(&temp[0], g_lamexp_months[j]))
387 date[1] = j+1;
388 break;
392 g_lamexp_version_date = QDate(date[0], date[1], date[2]);
395 if(!g_lamexp_version_date.isValid())
397 qFatal("Internal error: Date format could not be recognized!");
401 return g_lamexp_version_date;
405 * Get the native operating system version
407 const lamexp_os_version_t *lamexp_get_os_version(void)
409 QReadLocker readLock(&g_lamexp_os_version.lock);
411 //Already initialized?
412 if(g_lamexp_os_version.bInitialized)
414 return &g_lamexp_os_version.version;
417 readLock.unlock();
418 QWriteLocker writeLock(&g_lamexp_os_version.lock);
420 //Detect OS version
421 if(!g_lamexp_os_version.bInitialized)
423 OSVERSIONINFO osVerInfo;
424 memset(&osVerInfo, 0, sizeof(OSVERSIONINFO));
425 osVerInfo.dwOSVersionInfoSize = sizeof(OSVERSIONINFO);
427 if(GetVersionEx(&osVerInfo) == TRUE)
429 if(osVerInfo.dwPlatformId == VER_PLATFORM_WIN32_NT)
431 g_lamexp_os_version.version.versionMajor = osVerInfo.dwMajorVersion;
432 g_lamexp_os_version.version.versionMinor = osVerInfo.dwMinorVersion;
434 else
436 qWarning("lamexp_get_os_version: Not running under Windows NT, this is not supposed to happen!");
437 g_lamexp_os_version.version.versionMajor = 0;
438 g_lamexp_os_version.version.versionMinor = 0;
441 else
443 throw "GetVersionEx() has failed. This is not supposed to happen!";
446 g_lamexp_os_version.bInitialized = true;
449 return &g_lamexp_os_version.version;
453 * Check if we are running under wine
455 bool lamexp_detect_wine(void)
457 static bool isWine = false;
458 static bool isWine_initialized = false;
460 if(!isWine_initialized)
462 QLibrary ntdll("ntdll.dll");
463 if(ntdll.load())
465 if(ntdll.resolve("wine_nt_to_unix_file_name") != NULL) isWine = true;
466 if(ntdll.resolve("wine_get_version") != NULL) isWine = true;
467 ntdll.unload();
469 isWine_initialized = true;
472 return isWine;
476 * Global exception handler
478 LONG WINAPI lamexp_exception_handler(__in struct _EXCEPTION_POINTERS *ExceptionInfo)
480 lamexp_fatal_exit(L"Unhandeled exception handler invoked, application will exit!");
481 return LONG_MAX;
485 * Invalid parameters handler
487 void lamexp_invalid_param_handler(const wchar_t* exp, const wchar_t* fun, const wchar_t* fil, unsigned int, uintptr_t)
489 lamexp_fatal_exit(L"Invalid parameter handler invoked, application will exit!");
493 * Change console text color
495 static void lamexp_console_color(FILE* file, WORD attributes)
497 const HANDLE hConsole = (HANDLE)(_get_osfhandle(_fileno(file)));
498 if((hConsole != NULL) && (hConsole != INVALID_HANDLE_VALUE))
500 SetConsoleTextAttribute(hConsole, attributes);
505 * Qt message handler
507 void lamexp_message_handler(QtMsgType type, const char *msg)
509 static const char *GURU_MEDITATION = "\n\nGURU MEDITATION !!!\n\n";
511 if(msg == NULL) return;
513 QMutexLocker lock(&g_lamexp_message_mutex);
515 if(g_lamexp_log_file)
517 static char prefix[] = "DWCF";
518 int index = qBound(0, static_cast<int>(type), 3);
519 unsigned int timestamp = static_cast<unsigned int>(_time64(NULL) % 3600I64);
520 QString str = QString::fromUtf8(msg).trimmed().replace('\n', '\t');
521 fprintf(g_lamexp_log_file, "[%c][%04u] %s\r\n", prefix[index], timestamp, str.toUtf8().constData());
522 fflush(g_lamexp_log_file);
525 if(g_lamexp_console_attached)
527 UINT oldOutputCP = GetConsoleOutputCP();
528 if(oldOutputCP != CP_UTF8) SetConsoleOutputCP(CP_UTF8);
530 switch(type)
532 case QtCriticalMsg:
533 case QtFatalMsg:
534 fflush(stdout);
535 fflush(stderr);
536 lamexp_console_color(stderr, FOREGROUND_RED | FOREGROUND_INTENSITY);
537 fprintf(stderr, GURU_MEDITATION);
538 fprintf(stderr, "%s\n", msg);
539 fflush(stderr);
540 break;
541 case QtWarningMsg:
542 lamexp_console_color(stderr, FOREGROUND_GREEN | FOREGROUND_RED | FOREGROUND_INTENSITY);
543 fprintf(stderr, "%s\n", msg);
544 fflush(stderr);
545 break;
546 default:
547 lamexp_console_color(stderr, FOREGROUND_BLUE | FOREGROUND_GREEN | FOREGROUND_RED | FOREGROUND_INTENSITY);
548 fprintf(stderr, "%s\n", msg);
549 fflush(stderr);
550 break;
553 lamexp_console_color(stderr, FOREGROUND_BLUE | FOREGROUND_GREEN | FOREGROUND_RED);
554 if(oldOutputCP != CP_UTF8) SetConsoleOutputCP(oldOutputCP);
556 else
558 QString temp("[LameXP][%1] %2");
560 switch(type)
562 case QtCriticalMsg:
563 case QtFatalMsg:
564 temp = temp.arg("C", QString::fromUtf8(msg));
565 break;
566 case QtWarningMsg:
567 temp = temp.arg("W", QString::fromUtf8(msg));
568 break;
569 default:
570 temp = temp.arg("I", QString::fromUtf8(msg));
571 break;
574 temp.replace("\n", "\t").append("\n");
575 OutputDebugStringA(temp.toLatin1().constData());
578 if((type == QtCriticalMsg) || (type == QtFatalMsg))
580 lock.unlock();
581 lamexp_fatal_exit(L"The application has encountered a critical error and will exit now!", QWCHAR(QString::fromUtf8(msg)));
586 * Initialize the console
588 void lamexp_init_console(const QStringList &argv)
590 bool enableConsole = lamexp_version_demo();
592 if(_environ)
594 wchar_t *logfile = NULL;
595 size_t logfile_len = 0;
596 if(!_wdupenv_s(&logfile, &logfile_len, L"LAMEXP_LOGFILE"))
598 if(logfile && (logfile_len > 0))
600 FILE *temp = NULL;
601 if(!_wfopen_s(&temp, logfile, L"wb"))
603 fprintf(temp, "%c%c%c", 0xEF, 0xBB, 0xBF);
604 g_lamexp_log_file = temp;
606 free(logfile);
611 if(!LAMEXP_DEBUG)
613 for(int i = 0; i < argv.count(); i++)
615 if(!argv.at(i).compare("--console", Qt::CaseInsensitive))
617 enableConsole = true;
619 else if(!argv.at(i).compare("--no-console", Qt::CaseInsensitive))
621 enableConsole = false;
626 if(enableConsole)
628 if(!g_lamexp_console_attached)
630 if(AllocConsole() != FALSE)
632 SetConsoleCtrlHandler(NULL, TRUE);
633 SetConsoleTitle(L"LameXP - Audio Encoder Front-End | Debug Console");
634 SetConsoleOutputCP(CP_UTF8);
635 g_lamexp_console_attached = true;
639 if(g_lamexp_console_attached)
641 //-------------------------------------------------------------------
642 //See: http://support.microsoft.com/default.aspx?scid=kb;en-us;105305
643 //-------------------------------------------------------------------
644 const int flags = _O_WRONLY | _O_U8TEXT;
645 int hCrtStdOut = _open_osfhandle((intptr_t) GetStdHandle(STD_OUTPUT_HANDLE), flags);
646 int hCrtStdErr = _open_osfhandle((intptr_t) GetStdHandle(STD_ERROR_HANDLE), flags);
647 FILE *hfStdOut = (hCrtStdOut >= 0) ? _fdopen(hCrtStdOut, "wb") : NULL;
648 FILE *hfStdErr = (hCrtStdErr >= 0) ? _fdopen(hCrtStdErr, "wb") : NULL;
649 if(hfStdOut) { *stdout = *hfStdOut; std::cout.rdbuf(new std::filebuf(hfStdOut)); }
650 if(hfStdErr) { *stderr = *hfStdErr; std::cerr.rdbuf(new std::filebuf(hfStdErr)); }
653 HWND hwndConsole = GetConsoleWindow();
655 if((hwndConsole != NULL) && (hwndConsole != INVALID_HANDLE_VALUE))
657 HMENU hMenu = GetSystemMenu(hwndConsole, 0);
658 EnableMenuItem(hMenu, SC_CLOSE, MF_BYCOMMAND | MF_GRAYED);
659 RemoveMenu(hMenu, SC_CLOSE, MF_BYCOMMAND);
661 SetWindowPos(hwndConsole, HWND_TOP, 0, 0, 0, 0, SWP_NOMOVE|SWP_NOSIZE|SWP_NOZORDER|SWP_FRAMECHANGED);
662 SetWindowLong(hwndConsole, GWL_STYLE, GetWindowLong(hwndConsole, GWL_STYLE) & (~WS_MAXIMIZEBOX) & (~WS_MINIMIZEBOX));
663 SetWindowPos(hwndConsole, HWND_TOP, 0, 0, 0, 0, SWP_NOMOVE|SWP_NOSIZE|SWP_NOZORDER|SWP_FRAMECHANGED);
669 * Detect CPU features
671 lamexp_cpu_t lamexp_detect_cpu_features(const QStringList &argv)
673 typedef BOOL (WINAPI *IsWow64ProcessFun)(__in HANDLE hProcess, __out PBOOL Wow64Process);
674 typedef VOID (WINAPI *GetNativeSystemInfoFun)(__out LPSYSTEM_INFO lpSystemInfo);
676 static IsWow64ProcessFun IsWow64ProcessPtr = NULL;
677 static GetNativeSystemInfoFun GetNativeSystemInfoPtr = NULL;
679 lamexp_cpu_t features;
680 SYSTEM_INFO systemInfo;
681 int CPUInfo[4] = {-1};
682 char CPUIdentificationString[0x40];
683 char CPUBrandString[0x40];
685 memset(&features, 0, sizeof(lamexp_cpu_t));
686 memset(&systemInfo, 0, sizeof(SYSTEM_INFO));
687 memset(CPUIdentificationString, 0, sizeof(CPUIdentificationString));
688 memset(CPUBrandString, 0, sizeof(CPUBrandString));
690 __cpuid(CPUInfo, 0);
691 memcpy(CPUIdentificationString, &CPUInfo[1], sizeof(int));
692 memcpy(CPUIdentificationString + 4, &CPUInfo[3], sizeof(int));
693 memcpy(CPUIdentificationString + 8, &CPUInfo[2], sizeof(int));
694 features.intel = (_stricmp(CPUIdentificationString, "GenuineIntel") == 0);
695 strncpy_s(features.vendor, 0x40, CPUIdentificationString, _TRUNCATE);
697 if(CPUInfo[0] >= 1)
699 __cpuid(CPUInfo, 1);
700 features.mmx = (CPUInfo[3] & 0x800000) || false;
701 features.sse = (CPUInfo[3] & 0x2000000) || false;
702 features.sse2 = (CPUInfo[3] & 0x4000000) || false;
703 features.ssse3 = (CPUInfo[2] & 0x200) || false;
704 features.sse3 = (CPUInfo[2] & 0x1) || false;
705 features.ssse3 = (CPUInfo[2] & 0x200) || false;
706 features.stepping = CPUInfo[0] & 0xf;
707 features.model = ((CPUInfo[0] >> 4) & 0xf) + (((CPUInfo[0] >> 16) & 0xf) << 4);
708 features.family = ((CPUInfo[0] >> 8) & 0xf) + ((CPUInfo[0] >> 20) & 0xff);
711 __cpuid(CPUInfo, 0x80000000);
712 int nExIds = qMax<int>(qMin<int>(CPUInfo[0], 0x80000004), 0x80000000);
714 for(int i = 0x80000002; i <= nExIds; ++i)
716 __cpuid(CPUInfo, i);
717 switch(i)
719 case 0x80000002:
720 memcpy(CPUBrandString, CPUInfo, sizeof(CPUInfo));
721 break;
722 case 0x80000003:
723 memcpy(CPUBrandString + 16, CPUInfo, sizeof(CPUInfo));
724 break;
725 case 0x80000004:
726 memcpy(CPUBrandString + 32, CPUInfo, sizeof(CPUInfo));
727 break;
731 strncpy_s(features.brand, 0x40, CPUBrandString, _TRUNCATE);
733 if(strlen(features.brand) < 1) strncpy_s(features.brand, 0x40, "Unknown", _TRUNCATE);
734 if(strlen(features.vendor) < 1) strncpy_s(features.vendor, 0x40, "Unknown", _TRUNCATE);
736 #if !defined(_M_X64 ) && !defined(_M_IA64)
737 if(!IsWow64ProcessPtr || !GetNativeSystemInfoPtr)
739 QLibrary Kernel32Lib("kernel32.dll");
740 IsWow64ProcessPtr = (IsWow64ProcessFun) Kernel32Lib.resolve("IsWow64Process");
741 GetNativeSystemInfoPtr = (GetNativeSystemInfoFun) Kernel32Lib.resolve("GetNativeSystemInfo");
743 if(IsWow64ProcessPtr)
745 BOOL x64 = FALSE;
746 if(IsWow64ProcessPtr(GetCurrentProcess(), &x64))
748 features.x64 = x64;
751 if(GetNativeSystemInfoPtr)
753 GetNativeSystemInfoPtr(&systemInfo);
755 else
757 GetSystemInfo(&systemInfo);
759 features.count = qBound(1UL, systemInfo.dwNumberOfProcessors, 64UL);
760 #else
761 GetNativeSystemInfo(&systemInfo);
762 features.count = systemInfo.dwNumberOfProcessors;
763 features.x64 = true;
764 #endif
766 if(argv.count() > 0)
768 bool flag = false;
769 for(int i = 0; i < argv.count(); i++)
771 if(!argv[i].compare("--force-cpu-no-64bit", Qt::CaseInsensitive)) { flag = true; features.x64 = false; }
772 if(!argv[i].compare("--force-cpu-no-sse", Qt::CaseInsensitive)) { flag = true; features.sse = features.sse2 = features.sse3 = features.ssse3 = false; }
773 if(!argv[i].compare("--force-cpu-no-intel", Qt::CaseInsensitive)) { flag = true; features.intel = false; }
775 if(flag) qWarning("CPU flags overwritten by user-defined parameters. Take care!\n");
778 return features;
782 * Check for debugger (detect routine)
784 static __forceinline bool lamexp_check_for_debugger(void)
786 if(IsDebuggerPresent())
788 return true;
791 __try
793 CloseHandle((HANDLE) 0x7FFFFFFF);
795 __except(EXCEPTION_EXECUTE_HANDLER)
797 return true;
800 __try
802 DebugBreak();
804 __except(EXCEPTION_EXECUTE_HANDLER)
806 return false;
809 return true;
813 * Check for debugger (thread proc)
815 static unsigned int __stdcall lamexp_debug_thread_proc(LPVOID lpParameter)
817 while(!lamexp_check_for_debugger())
819 Sleep(250);
821 lamexp_fatal_exit(L"Not a debug build. Please unload debugger and try again!");
822 return 666;
826 * Check for debugger (startup routine)
828 static HANDLE lamexp_debug_thread_init(void)
830 if(lamexp_check_for_debugger())
832 lamexp_fatal_exit(L"Not a debug build. Please unload debugger and try again!");
835 return (HANDLE) _beginthreadex(NULL, 0, lamexp_debug_thread_proc, NULL, 0, NULL);
839 * Check for compatibility mode
841 static bool lamexp_check_compatibility_mode(const char *exportName, const QString &executableName)
843 QLibrary kernel32("kernel32.dll");
845 if((exportName != NULL) && kernel32.load())
847 if(kernel32.resolve(exportName) != NULL)
849 qWarning("Function '%s' exported from 'kernel32.dll' -> Windows compatibility mode!", exportName);
850 qFatal("%s", QApplication::tr("Executable '%1' doesn't support Windows compatibility mode.").arg(executableName).toLatin1().constData());
851 return false;
855 return true;
859 * Computus according to H. Lichtenberg
861 static bool lamexp_computus(const QDate &date)
863 int X = date.year();
864 int A = X % 19;
865 int K = X / 100;
866 int M = 15 + (3*K + 3) / 4 - (8*K + 13) / 25;
867 int D = (19*A + M) % 30;
868 int S = 2 - (3*K + 3) / 4;
869 int R = D / 29 + (D / 28 - D / 29) * (A / 11);
870 int OG = 21 + D - R;
871 int SZ = 7 - (X + X / 4 + S) % 7;
872 int OE = 7 - (OG - SZ) % 7;
873 int OS = (OG + OE);
875 if(OS > 31)
877 return (date.month() == 4) && (date.day() == (OS - 31));
879 else
881 return (date.month() == 3) && (date.day() == OS);
886 * Check for Thanksgiving
888 static bool lamexp_thanksgiving(const QDate &date)
890 int day = 0;
892 switch(QDate(date.year(), 11, 1).dayOfWeek())
894 case 1: day = 25; break;
895 case 2: day = 24; break;
896 case 3: day = 23; break;
897 case 4: day = 22; break;
898 case 5: day = 28; break;
899 case 6: day = 27; break;
900 case 7: day = 26; break;
903 return (date.month() == 11) && (date.day() == day);
907 * Initialize app icon
909 QIcon lamexp_app_icon(const QDate *date, const QTime *time)
911 QDate currentDate = (date) ? QDate(*date) : QDate::currentDate();
912 QTime currentTime = (time) ? QTime(*time) : QTime::currentTime();
914 if(lamexp_thanksgiving(currentDate))
916 return QIcon(":/MainIcon6.png");
918 else if(((currentDate.month() == 12) && (currentDate.day() == 31) && (currentTime.hour() >= 20)) || ((currentDate.month() == 1) && (currentDate.day() == 1) && (currentTime.hour() <= 19)))
920 return QIcon(":/MainIcon5.png");
922 else if(((currentDate.month() == 10) && (currentDate.day() == 31) && (currentTime.hour() >= 12)) || ((currentDate.month() == 11) && (currentDate.day() == 1) && (currentTime.hour() <= 11)))
924 return QIcon(":/MainIcon4.png");
926 else if((currentDate.month() == 12) && (currentDate.day() >= 24) && (currentDate.day() <= 26))
928 return QIcon(":/MainIcon3.png");
930 else if(lamexp_computus(currentDate))
932 return QIcon(":/MainIcon2.png");
934 else
936 return QIcon(":/MainIcon1.png");
941 * Broadcast event to all windows
943 static bool lamexp_broadcast(int eventType, bool onlyToVisible)
945 if(QApplication *app = dynamic_cast<QApplication*>(QApplication::instance()))
947 qDebug("Broadcasting %d", eventType);
949 bool allOk = true;
950 QEvent poEvent(static_cast<QEvent::Type>(eventType));
951 QWidgetList list = app->topLevelWidgets();
953 while(!list.isEmpty())
955 QWidget *widget = list.takeFirst();
956 if(!onlyToVisible || widget->isVisible())
958 if(!app->sendEvent(widget, &poEvent))
960 allOk = false;
965 qDebug("Broadcast %d done (%s)", eventType, (allOk ? "OK" : "Stopped"));
966 return allOk;
968 else
970 qWarning("Broadcast failed, could not get QApplication instance!");
971 return false;
976 * Qt event filter
978 static bool lamexp_event_filter(void *message, long *result)
980 if((!(LAMEXP_DEBUG)) && lamexp_check_for_debugger())
982 lamexp_fatal_exit(L"Not a debug build. Please unload debugger and try again!");
985 switch(reinterpret_cast<MSG*>(message)->message)
987 case WM_QUERYENDSESSION:
988 qWarning("WM_QUERYENDSESSION message received!");
989 *result = lamexp_broadcast(lamexp_event_queryendsession, false) ? TRUE : FALSE;
990 return true;
991 case WM_ENDSESSION:
992 qWarning("WM_ENDSESSION message received!");
993 if(reinterpret_cast<MSG*>(message)->wParam == TRUE)
995 lamexp_broadcast(lamexp_event_endsession, false);
996 if(QApplication *app = reinterpret_cast<QApplication*>(QApplication::instance()))
998 app->closeAllWindows();
999 app->quit();
1001 lamexp_finalization();
1002 exit(1);
1004 *result = 0;
1005 return true;
1006 default:
1007 /*ignore this message and let Qt handle it*/
1008 return false;
1013 * Check for process elevation
1015 static bool lamexp_check_elevation(void)
1017 typedef enum { lamexp_token_elevationType_class = 18, lamexp_token_elevation_class = 20 } LAMEXP_TOKEN_INFORMATION_CLASS;
1018 typedef enum { lamexp_elevationType_default = 1, lamexp_elevationType_full, lamexp_elevationType_limited } LAMEXP_TOKEN_ELEVATION_TYPE;
1020 HANDLE hToken = NULL;
1021 bool bIsProcessElevated = false;
1023 if(OpenProcessToken(GetCurrentProcess(), TOKEN_QUERY, &hToken))
1025 LAMEXP_TOKEN_ELEVATION_TYPE tokenElevationType;
1026 DWORD returnLength;
1027 if(GetTokenInformation(hToken, (TOKEN_INFORMATION_CLASS) lamexp_token_elevationType_class, &tokenElevationType, sizeof(LAMEXP_TOKEN_ELEVATION_TYPE), &returnLength))
1029 if(returnLength == sizeof(LAMEXP_TOKEN_ELEVATION_TYPE))
1031 switch(tokenElevationType)
1033 case lamexp_elevationType_default:
1034 qDebug("Process token elevation type: Default -> UAC is disabled.\n");
1035 break;
1036 case lamexp_elevationType_full:
1037 qWarning("Process token elevation type: Full -> potential security risk!\n");
1038 bIsProcessElevated = true;
1039 break;
1040 case lamexp_elevationType_limited:
1041 qDebug("Process token elevation type: Limited -> not elevated.\n");
1042 break;
1046 CloseHandle(hToken);
1048 else
1050 qWarning("Failed to open process token!");
1053 return !bIsProcessElevated;
1057 * Initialize Qt framework
1059 bool lamexp_init_qt(int argc, char* argv[])
1061 static bool qt_initialized = false;
1062 typedef BOOL (WINAPI *SetDllDirectoryProc)(WCHAR *lpPathName);
1063 const QStringList &arguments = lamexp_arguments();
1065 //Don't initialized again, if done already
1066 if(qt_initialized)
1068 return true;
1071 //Secure DLL loading
1072 QLibrary kernel32("kernel32.dll");
1073 if(kernel32.load())
1075 SetDllDirectoryProc pSetDllDirectory = (SetDllDirectoryProc) kernel32.resolve("SetDllDirectoryW");
1076 if(pSetDllDirectory != NULL) pSetDllDirectory(L"");
1077 kernel32.unload();
1080 //Extract executable name from argv[] array
1081 QString executableName = QLatin1String("LameXP.exe");
1082 if(arguments.count() > 0)
1084 static const char *delimiters = "\\/:?";
1085 executableName = arguments[0].trimmed();
1086 for(int i = 0; delimiters[i]; i++)
1088 int temp = executableName.lastIndexOf(QChar(delimiters[i]));
1089 if(temp >= 0) executableName = executableName.mid(temp + 1);
1091 executableName = executableName.trimmed();
1092 if(executableName.isEmpty())
1094 executableName = QLatin1String("LameXP.exe");
1098 //Check Qt version
1099 #ifdef QT_BUILD_KEY
1100 qDebug("Using Qt v%s [%s], %s, %s", qVersion(), QLibraryInfo::buildDate().toString(Qt::ISODate).toLatin1().constData(), (qSharedBuild() ? "DLL" : "Static"), QLibraryInfo::buildKey().toLatin1().constData());
1101 qDebug("Compiled with Qt v%s [%s], %s\n", QT_VERSION_STR, QT_PACKAGEDATE_STR, QT_BUILD_KEY);
1102 if(_stricmp(qVersion(), QT_VERSION_STR))
1104 qFatal("%s", QApplication::tr("Executable '%1' requires Qt v%2, but found Qt v%3.").arg(executableName, QString::fromLatin1(QT_VERSION_STR), QString::fromLatin1(qVersion())).toLatin1().constData());
1105 return false;
1107 if(QLibraryInfo::buildKey().compare(QString::fromLatin1(QT_BUILD_KEY), Qt::CaseInsensitive))
1109 qFatal("%s", QApplication::tr("Executable '%1' was built for Qt '%2', but found Qt '%3'.").arg(executableName, QString::fromLatin1(QT_BUILD_KEY), QLibraryInfo::buildKey()).toLatin1().constData());
1110 return false;
1112 #else
1113 qDebug("Using Qt v%s [%s], %s", qVersion(), QLibraryInfo::buildDate().toString(Qt::ISODate).toLatin1().constData(), (qSharedBuild() ? "DLL" : "Static"));
1114 qDebug("Compiled with Qt v%s [%s]\n", QT_VERSION_STR, QT_PACKAGEDATE_STR);
1115 #endif
1117 //Check the Windows version
1118 switch(QSysInfo::windowsVersion() & QSysInfo::WV_NT_based)
1120 case 0:
1121 case QSysInfo::WV_NT:
1122 qFatal("%s", QApplication::tr("Executable '%1' requires Windows 2000 or later.").arg(executableName).toLatin1().constData());
1123 break;
1124 case QSysInfo::WV_2000:
1125 qDebug("Running on Windows 2000 (not officially supported!).\n");
1126 lamexp_check_compatibility_mode("GetNativeSystemInfo", executableName);
1127 break;
1128 case QSysInfo::WV_XP:
1129 qDebug("Running on Windows XP.\n");
1130 lamexp_check_compatibility_mode("GetLargePageMinimum", executableName);
1131 break;
1132 case QSysInfo::WV_2003:
1133 qDebug("Running on Windows Server 2003 or Windows XP x64-Edition.\n");
1134 lamexp_check_compatibility_mode("GetLocaleInfoEx", executableName);
1135 break;
1136 case QSysInfo::WV_VISTA:
1137 qDebug("Running on Windows Vista or Windows Server 2008.\n");
1138 lamexp_check_compatibility_mode("CreateRemoteThreadEx", executableName);
1139 break;
1140 case QSysInfo::WV_WINDOWS7:
1141 qDebug("Running on Windows 7 or Windows Server 2008 R2.\n");
1142 lamexp_check_compatibility_mode("CreateFile2", executableName);
1143 break;
1144 default:
1146 const lamexp_os_version_t *osVersionNo = lamexp_get_os_version();
1147 if(osVersionNo->versionMajor < 5)
1149 qFatal("%s", QApplication::tr("Executable '%1' requires Windows 2000 or later.").arg(executableName).toLatin1().constData());
1151 else if(LAMEXP_EQL_OS_VER(osVersionNo, 6, 2))
1153 qDebug("Running on Windows 8 or Windows Server 2012\n");
1154 lamexp_check_compatibility_mode(NULL, executableName);
1156 else
1158 qWarning("Running on an unknown/untested WinNT-based OS (v%u.%u).\n", osVersionNo->versionMajor, osVersionNo->versionMinor);
1161 break;
1164 //Check for Wine
1165 if(lamexp_detect_wine())
1167 qWarning("It appears we are running under Wine, unexpected things might happen!\n");
1170 //Set text Codec for locale
1171 QTextCodec::setCodecForLocale(QTextCodec::codecForName("UTF-8"));
1173 //Create Qt application instance
1174 QApplication *application = new QApplication(argc, argv);
1176 //Load plugins from application directory
1177 QCoreApplication::setLibraryPaths(QStringList() << QApplication::applicationDirPath());
1178 qDebug("Library Path:\n%s\n", QApplication::libraryPaths().first().toUtf8().constData());
1180 //Set application properties
1181 application->setApplicationName("LameXP - Audio Encoder Front-End");
1182 application->setApplicationVersion(QString().sprintf("%d.%02d.%04d", lamexp_version_major(), lamexp_version_minor(), lamexp_version_build()));
1183 application->setOrganizationName("LoRd_MuldeR");
1184 application->setOrganizationDomain("mulder.at.gg");
1185 application->setWindowIcon(lamexp_app_icon());
1186 application->setEventFilter(lamexp_event_filter);
1188 //Check for supported image formats
1189 QList<QByteArray> supportedFormats = QImageReader::supportedImageFormats();
1190 for(int i = 0; g_lamexp_imageformats[i]; i++)
1192 if(!supportedFormats.contains(g_lamexp_imageformats[i]))
1194 qFatal("Qt initialization error: QImageIOHandler for '%s' missing!", g_lamexp_imageformats[i]);
1195 return false;
1199 //Add default translations
1200 QWriteLocker writeLockTranslations(&g_lamexp_translation.lock);
1201 if(!g_lamexp_translation.files) g_lamexp_translation.files = new QMap<QString, QString>();
1202 if(!g_lamexp_translation.names) g_lamexp_translation.names = new QMap<QString, QString>();
1203 g_lamexp_translation.files->insert(LAMEXP_DEFAULT_LANGID, "");
1204 g_lamexp_translation.names->insert(LAMEXP_DEFAULT_LANGID, "English");
1205 writeLockTranslations.unlock();
1207 //Check for process elevation
1208 if((!lamexp_check_elevation()) && (!lamexp_detect_wine()))
1210 QMessageBox messageBox(QMessageBox::Warning, "LameXP", "<nobr>LameXP was started with 'elevated' rights, altough LameXP does not need these rights.<br>Running an applications with unnecessary rights is a potential security risk!</nobr>", QMessageBox::NoButton, NULL, Qt::Dialog | Qt::MSWindowsFixedSizeDialogHint | Qt::WindowStaysOnTopHint);
1211 messageBox.addButton("Quit Program (Recommended)", QMessageBox::NoRole);
1212 messageBox.addButton("Ignore", QMessageBox::NoRole);
1213 if(messageBox.exec() == 0)
1215 return false;
1219 //Update console icon, if a console is attached
1220 #if QT_VERSION < QT_VERSION_CHECK(5,0,0)
1221 if(g_lamexp_console_attached && (!lamexp_detect_wine()))
1223 typedef DWORD (__stdcall *SetConsoleIconFun)(HICON);
1224 QLibrary kernel32("kernel32.dll");
1225 if(kernel32.load())
1227 SetConsoleIconFun SetConsoleIconPtr = (SetConsoleIconFun) kernel32.resolve("SetConsoleIcon");
1228 if(SetConsoleIconPtr != NULL) SetConsoleIconPtr(QIcon(":/icons/sound.png").pixmap(16, 16).toWinHICON());
1229 kernel32.unload();
1232 #endif
1234 //Done
1235 qt_initialized = true;
1236 return true;
1240 * Initialize IPC
1242 int lamexp_init_ipc(void)
1244 QWriteLocker writeLock(&g_lamexp_ipc_ptr.lock);
1246 if(g_lamexp_ipc_ptr.sharedmem && g_lamexp_ipc_ptr.semaphore_read && g_lamexp_ipc_ptr.semaphore_write && g_lamexp_ipc_ptr.semaphore_read_mutex && g_lamexp_ipc_ptr.semaphore_write_mutex)
1248 return 0;
1251 g_lamexp_ipc_ptr.semaphore_read = new QSystemSemaphore(QString(g_lamexp_ipc_uuid.semaphore_read), 0);
1252 g_lamexp_ipc_ptr.semaphore_write = new QSystemSemaphore(QString(g_lamexp_ipc_uuid.semaphore_write), 0);
1253 g_lamexp_ipc_ptr.semaphore_read_mutex = new QSystemSemaphore(QString(g_lamexp_ipc_uuid.semaphore_read_mutex), 0);
1254 g_lamexp_ipc_ptr.semaphore_write_mutex = new QSystemSemaphore(QString(g_lamexp_ipc_uuid.semaphore_write_mutex), 0);
1256 if(g_lamexp_ipc_ptr.semaphore_read->error() != QSystemSemaphore::NoError)
1258 QString errorMessage = g_lamexp_ipc_ptr.semaphore_read->errorString();
1259 LAMEXP_DELETE(g_lamexp_ipc_ptr.semaphore_read);
1260 LAMEXP_DELETE(g_lamexp_ipc_ptr.semaphore_write);
1261 LAMEXP_DELETE(g_lamexp_ipc_ptr.semaphore_read_mutex);
1262 LAMEXP_DELETE(g_lamexp_ipc_ptr.semaphore_write_mutex);
1263 qFatal("Failed to create system smaphore: %s", errorMessage.toUtf8().constData());
1264 return -1;
1266 if(g_lamexp_ipc_ptr.semaphore_write->error() != QSystemSemaphore::NoError)
1268 QString errorMessage = g_lamexp_ipc_ptr.semaphore_write->errorString();
1269 LAMEXP_DELETE(g_lamexp_ipc_ptr.semaphore_read);
1270 LAMEXP_DELETE(g_lamexp_ipc_ptr.semaphore_write);
1271 LAMEXP_DELETE(g_lamexp_ipc_ptr.semaphore_read_mutex);
1272 LAMEXP_DELETE(g_lamexp_ipc_ptr.semaphore_write_mutex);
1273 qFatal("Failed to create system smaphore: %s", errorMessage.toUtf8().constData());
1274 return -1;
1276 if(g_lamexp_ipc_ptr.semaphore_read_mutex->error() != QSystemSemaphore::NoError)
1278 QString errorMessage = g_lamexp_ipc_ptr.semaphore_read_mutex->errorString();
1279 LAMEXP_DELETE(g_lamexp_ipc_ptr.semaphore_read);
1280 LAMEXP_DELETE(g_lamexp_ipc_ptr.semaphore_write);
1281 LAMEXP_DELETE(g_lamexp_ipc_ptr.semaphore_read_mutex);
1282 LAMEXP_DELETE(g_lamexp_ipc_ptr.semaphore_write_mutex);
1283 qFatal("Failed to create system smaphore: %s", errorMessage.toUtf8().constData());
1284 return -1;
1286 if(g_lamexp_ipc_ptr.semaphore_write_mutex->error() != QSystemSemaphore::NoError)
1288 QString errorMessage = g_lamexp_ipc_ptr.semaphore_write_mutex->errorString();
1289 LAMEXP_DELETE(g_lamexp_ipc_ptr.semaphore_read);
1290 LAMEXP_DELETE(g_lamexp_ipc_ptr.semaphore_write);
1291 LAMEXP_DELETE(g_lamexp_ipc_ptr.semaphore_read_mutex);
1292 LAMEXP_DELETE(g_lamexp_ipc_ptr.semaphore_write_mutex);
1293 qFatal("Failed to create system smaphore: %s", errorMessage.toUtf8().constData());
1294 return -1;
1297 g_lamexp_ipc_ptr.sharedmem = new QSharedMemory(QString(g_lamexp_ipc_uuid.sharedmem), NULL);
1299 if(!g_lamexp_ipc_ptr.sharedmem->create(sizeof(lamexp_ipc_t)))
1301 if(g_lamexp_ipc_ptr.sharedmem->error() == QSharedMemory::AlreadyExists)
1303 g_lamexp_ipc_ptr.sharedmem->attach();
1304 if(g_lamexp_ipc_ptr.sharedmem->error() == QSharedMemory::NoError)
1306 return 1;
1308 else
1310 QString errorMessage = g_lamexp_ipc_ptr.sharedmem->errorString();
1311 LAMEXP_DELETE(g_lamexp_ipc_ptr.sharedmem);
1312 qFatal("Failed to attach to shared memory: %s", errorMessage.toUtf8().constData());
1313 return -1;
1316 else
1318 QString errorMessage = g_lamexp_ipc_ptr.sharedmem->errorString();
1319 LAMEXP_DELETE(g_lamexp_ipc_ptr.sharedmem);
1320 qFatal("Failed to create shared memory: %s", errorMessage.toUtf8().constData());
1321 return -1;
1325 memset(g_lamexp_ipc_ptr.sharedmem->data(), 0, sizeof(lamexp_ipc_t));
1326 g_lamexp_ipc_ptr.semaphore_write->release(g_lamexp_ipc_slots);
1327 g_lamexp_ipc_ptr.semaphore_read_mutex->release();
1328 g_lamexp_ipc_ptr.semaphore_write_mutex->release();
1330 return 0;
1334 * IPC send message
1336 void lamexp_ipc_send(unsigned int command, const char* message)
1338 QReadLocker readLock(&g_lamexp_ipc_ptr.lock);
1340 if(!g_lamexp_ipc_ptr.sharedmem || !g_lamexp_ipc_ptr.semaphore_read || !g_lamexp_ipc_ptr.semaphore_write || !g_lamexp_ipc_ptr.semaphore_read_mutex || !g_lamexp_ipc_ptr.semaphore_write_mutex)
1342 throw "Shared memory for IPC not initialized yet.";
1345 lamexp_ipc_data_t ipc_data;
1346 memset(&ipc_data, 0, sizeof(lamexp_ipc_data_t));
1347 ipc_data.command = command;
1349 if(message)
1351 strncpy_s(ipc_data.parameter, 4096, message, _TRUNCATE);
1354 if(g_lamexp_ipc_ptr.semaphore_write->acquire())
1356 if(g_lamexp_ipc_ptr.semaphore_write_mutex->acquire())
1358 lamexp_ipc_t *ptr = reinterpret_cast<lamexp_ipc_t*>(g_lamexp_ipc_ptr.sharedmem->data());
1359 memcpy(&ptr->data[ptr->pos_write], &ipc_data, sizeof(lamexp_ipc_data_t));
1360 ptr->pos_write = (ptr->pos_write + 1) % g_lamexp_ipc_slots;
1361 g_lamexp_ipc_ptr.semaphore_read->release();
1362 g_lamexp_ipc_ptr.semaphore_write_mutex->release();
1368 * IPC read message
1370 void lamexp_ipc_read(unsigned int *command, char* message, size_t buffSize)
1372 QReadLocker readLock(&g_lamexp_ipc_ptr.lock);
1374 *command = 0;
1375 message[0] = '\0';
1377 if(!g_lamexp_ipc_ptr.sharedmem || !g_lamexp_ipc_ptr.semaphore_read || !g_lamexp_ipc_ptr.semaphore_write || !g_lamexp_ipc_ptr.semaphore_read_mutex || !g_lamexp_ipc_ptr.semaphore_write_mutex)
1379 throw "Shared memory for IPC not initialized yet.";
1382 lamexp_ipc_data_t ipc_data;
1383 memset(&ipc_data, 0, sizeof(lamexp_ipc_data_t));
1385 if(g_lamexp_ipc_ptr.semaphore_read->acquire())
1387 if(g_lamexp_ipc_ptr.semaphore_read_mutex->acquire())
1389 lamexp_ipc_t *ptr = reinterpret_cast<lamexp_ipc_t*>(g_lamexp_ipc_ptr.sharedmem->data());
1390 memcpy(&ipc_data, &ptr->data[ptr->pos_read], sizeof(lamexp_ipc_data_t));
1391 ptr->pos_read = (ptr->pos_read + 1) % g_lamexp_ipc_slots;
1392 g_lamexp_ipc_ptr.semaphore_write->release();
1393 g_lamexp_ipc_ptr.semaphore_read_mutex->release();
1395 if(!(ipc_data.reserved_1 || ipc_data.reserved_2))
1397 *command = ipc_data.command;
1398 strncpy_s(message, buffSize, ipc_data.parameter, _TRUNCATE);
1400 else
1402 qWarning("Malformed IPC message, will be ignored");
1409 * Check for LameXP "portable" mode
1411 bool lamexp_portable_mode(void)
1413 QString baseName = QFileInfo(QApplication::applicationFilePath()).completeBaseName();
1414 int idx1 = baseName.indexOf("lamexp", 0, Qt::CaseInsensitive);
1415 int idx2 = baseName.lastIndexOf("portable", -1, Qt::CaseInsensitive);
1416 return (idx1 >= 0) && (idx2 >= 0) && (idx1 < idx2);
1420 * Get a random string
1422 QString lamexp_rand_str(void)
1424 QRegExp regExp("\\{(\\w+)-(\\w+)-(\\w+)-(\\w+)-(\\w+)\\}");
1425 QString uuid = QUuid::createUuid().toString();
1427 if(regExp.indexIn(uuid) >= 0)
1429 return QString().append(regExp.cap(1)).append(regExp.cap(2)).append(regExp.cap(3)).append(regExp.cap(4)).append(regExp.cap(5));
1432 throw "The RegExp didn't match on the UUID string. This shouldn't happen ;-)";
1436 * Get LameXP temp folder
1438 const QString &lamexp_temp_folder2(void)
1440 QReadLocker readLock(&g_lamexp_folder.lock);
1442 //Already initialized?
1443 if(g_lamexp_folder.temp)
1445 if(!g_lamexp_folder.temp->isEmpty())
1447 if(QDir(*g_lamexp_folder.temp).exists())
1449 return *g_lamexp_folder.temp;
1454 readLock.unlock();
1455 QWriteLocker writeLock(&g_lamexp_folder.lock);
1457 if(!g_lamexp_folder.temp)
1459 g_lamexp_folder.temp = new QString();
1462 g_lamexp_folder.temp->clear();
1464 static const char *TEMP_STR = "Temp";
1465 const QString WRITE_TEST_DATA = lamexp_rand_str();
1466 const QString SUB_FOLDER = lamexp_rand_str();
1468 //Try the %TMP% or %TEMP% directory first
1469 QDir temp = QDir::temp();
1470 if(temp.exists())
1472 temp.mkdir(SUB_FOLDER);
1473 if(temp.cd(SUB_FOLDER) && temp.exists())
1475 QFile testFile(QString("%1/~%2.tmp").arg(temp.canonicalPath(), lamexp_rand_str()));
1476 if(testFile.open(QIODevice::ReadWrite))
1478 if(testFile.write(WRITE_TEST_DATA.toLatin1().constData()) >= strlen(WRITE_TEST_DATA.toLatin1().constData()))
1480 (*g_lamexp_folder.temp) = temp.canonicalPath();
1482 testFile.remove();
1485 if(!g_lamexp_folder.temp->isEmpty())
1487 return *g_lamexp_folder.temp;
1491 //Create TEMP folder in %LOCALAPPDATA%
1492 QDir localAppData = QDir(lamexp_known_folder(lamexp_folder_localappdata));
1493 if(!localAppData.path().isEmpty())
1495 if(!localAppData.exists())
1497 localAppData.mkpath(".");
1499 if(localAppData.exists())
1501 if(!localAppData.entryList(QDir::AllDirs).contains(TEMP_STR, Qt::CaseInsensitive))
1503 localAppData.mkdir(TEMP_STR);
1505 if(localAppData.cd(TEMP_STR) && localAppData.exists())
1507 localAppData.mkdir(SUB_FOLDER);
1508 if(localAppData.cd(SUB_FOLDER) && localAppData.exists())
1510 QFile testFile(QString("%1/~%2.tmp").arg(localAppData.canonicalPath(), lamexp_rand_str()));
1511 if(testFile.open(QIODevice::ReadWrite))
1513 if(testFile.write(WRITE_TEST_DATA.toLatin1().constData()) >= strlen(WRITE_TEST_DATA.toLatin1().constData()))
1515 (*g_lamexp_folder.temp) = localAppData.canonicalPath();
1517 testFile.remove();
1522 if(!g_lamexp_folder.temp->isEmpty())
1524 return *g_lamexp_folder.temp;
1528 //Failed to create TEMP folder!
1529 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());
1530 return *g_lamexp_folder.temp;
1534 * Clean folder
1536 bool lamexp_clean_folder(const QString &folderPath)
1538 QDir tempFolder(folderPath);
1539 QFileInfoList entryList = tempFolder.entryInfoList(QDir::AllEntries | QDir::NoDotAndDotDot);
1541 for(int i = 0; i < entryList.count(); i++)
1543 if(entryList.at(i).isDir())
1545 lamexp_clean_folder(entryList.at(i).canonicalFilePath());
1547 else
1549 for(int j = 0; j < 3; j++)
1551 if(lamexp_remove_file(entryList.at(i).canonicalFilePath()))
1553 break;
1559 tempFolder.rmdir(".");
1560 return !tempFolder.exists();
1564 * Register tool
1566 void lamexp_register_tool(const QString &toolName, LockedFile *file, unsigned int version)
1568 QWriteLocker writeLock(&g_lamexp_tools.lock);
1570 if(!g_lamexp_tools.registry) g_lamexp_tools.registry = new QMap<QString, LockedFile*>();
1571 if(!g_lamexp_tools.versions) g_lamexp_tools.versions = new QMap<QString, unsigned int>();
1573 if(g_lamexp_tools.registry->contains(toolName.toLower()))
1575 throw "lamexp_register_tool: Tool is already registered!";
1578 g_lamexp_tools.registry->insert(toolName.toLower(), file);
1579 g_lamexp_tools.versions->insert(toolName.toLower(), version);
1583 * Check for tool
1585 bool lamexp_check_tool(const QString &toolName)
1587 QReadLocker readLock(&g_lamexp_tools.lock);
1588 return (g_lamexp_tools.registry) ? g_lamexp_tools.registry->contains(toolName.toLower()) : false;
1592 * Lookup tool path
1594 const QString lamexp_lookup_tool(const QString &toolName)
1596 QReadLocker readLock(&g_lamexp_tools.lock);
1598 if(g_lamexp_tools.registry)
1600 if(g_lamexp_tools.registry->contains(toolName.toLower()))
1602 return g_lamexp_tools.registry->value(toolName.toLower())->filePath();
1604 else
1606 return QString();
1609 else
1611 return QString();
1616 * Lookup tool version
1618 unsigned int lamexp_tool_version(const QString &toolName)
1620 QReadLocker readLock(&g_lamexp_tools.lock);
1622 if(g_lamexp_tools.versions)
1624 if(g_lamexp_tools.versions->contains(toolName.toLower()))
1626 return g_lamexp_tools.versions->value(toolName.toLower());
1628 else
1630 return UINT_MAX;
1633 else
1635 return UINT_MAX;
1640 * Version number to human-readable string
1642 const QString lamexp_version2string(const QString &pattern, unsigned int version, const QString &defaultText)
1644 if(version == UINT_MAX)
1646 return defaultText;
1649 QString result = pattern;
1650 int digits = result.count("?", Qt::CaseInsensitive);
1652 if(digits < 1)
1654 return result;
1657 int pos = 0;
1658 QString versionStr = QString().sprintf(QString().sprintf("%%0%du", digits).toLatin1().constData(), version);
1659 int index = result.indexOf("?", Qt::CaseInsensitive);
1661 while(index >= 0 && pos < versionStr.length())
1663 result[index] = versionStr[pos++];
1664 index = result.indexOf("?", Qt::CaseInsensitive);
1667 return result;
1671 * Register a new translation
1673 bool lamexp_translation_register(const QString &langId, const QString &qmFile, const QString &langName, unsigned int &systemId, unsigned int &country)
1675 QWriteLocker writeLockTranslations(&g_lamexp_translation.lock);
1677 if(qmFile.isEmpty() || langName.isEmpty() || systemId < 1)
1679 return false;
1682 if(!g_lamexp_translation.files) g_lamexp_translation.files = new QMap<QString, QString>();
1683 if(!g_lamexp_translation.names) g_lamexp_translation.names = new QMap<QString, QString>();
1684 if(!g_lamexp_translation.sysid) g_lamexp_translation.sysid = new QMap<QString, unsigned int>();
1685 if(!g_lamexp_translation.cntry) g_lamexp_translation.cntry = new QMap<QString, unsigned int>();
1687 g_lamexp_translation.files->insert(langId, qmFile);
1688 g_lamexp_translation.names->insert(langId, langName);
1689 g_lamexp_translation.sysid->insert(langId, systemId);
1690 g_lamexp_translation.cntry->insert(langId, country);
1692 return true;
1696 * Get list of all translations
1698 QStringList lamexp_query_translations(void)
1700 QReadLocker readLockTranslations(&g_lamexp_translation.lock);
1701 return (g_lamexp_translation.files) ? g_lamexp_translation.files->keys() : QStringList();
1705 * Get translation name
1707 QString lamexp_translation_name(const QString &langId)
1709 QReadLocker readLockTranslations(&g_lamexp_translation.lock);
1710 return (g_lamexp_translation.names) ? g_lamexp_translation.names->value(langId.toLower(), QString()) : QString();
1714 * Get translation system id
1716 unsigned int lamexp_translation_sysid(const QString &langId)
1718 QReadLocker readLockTranslations(&g_lamexp_translation.lock);
1719 return (g_lamexp_translation.sysid) ? g_lamexp_translation.sysid->value(langId.toLower(), 0) : 0;
1723 * Get translation script id
1725 unsigned int lamexp_translation_country(const QString &langId)
1727 QReadLocker readLockTranslations(&g_lamexp_translation.lock);
1728 return (g_lamexp_translation.cntry) ? g_lamexp_translation.cntry->value(langId.toLower(), 0) : 0;
1732 * Install a new translator
1734 bool lamexp_install_translator(const QString &langId)
1736 bool success = false;
1738 if(langId.isEmpty() || langId.toLower().compare(LAMEXP_DEFAULT_LANGID) == 0)
1740 success = lamexp_install_translator_from_file(QString());
1742 else
1744 QReadLocker readLock(&g_lamexp_translation.lock);
1745 QString qmFile = (g_lamexp_translation.files) ? g_lamexp_translation.files->value(langId.toLower(), QString()) : QString();
1746 readLock.unlock();
1748 if(!qmFile.isEmpty())
1750 success = lamexp_install_translator_from_file(QString(":/localization/%1").arg(qmFile));
1752 else
1754 qWarning("Translation '%s' not available!", langId.toLatin1().constData());
1758 return success;
1762 * Install a new translator from file
1764 bool lamexp_install_translator_from_file(const QString &qmFile)
1766 QWriteLocker writeLock(&g_lamexp_currentTranslator.lock);
1767 bool success = false;
1769 if(!g_lamexp_currentTranslator.instance)
1771 g_lamexp_currentTranslator.instance = new QTranslator();
1774 if(!qmFile.isEmpty())
1776 QString qmPath = QFileInfo(qmFile).canonicalFilePath();
1777 QApplication::removeTranslator(g_lamexp_currentTranslator.instance);
1778 if(success = g_lamexp_currentTranslator.instance->load(qmPath))
1780 QApplication::installTranslator(g_lamexp_currentTranslator.instance);
1782 else
1784 qWarning("Failed to load translation:\n\"%s\"", qmPath.toLatin1().constData());
1787 else
1789 QApplication::removeTranslator(g_lamexp_currentTranslator.instance);
1790 success = true;
1793 return success;
1796 const QStringList &lamexp_arguments(void)
1798 QReadLocker readLock(&g_lamexp_argv.lock);
1800 if(!g_lamexp_argv.list)
1802 readLock.unlock();
1803 QWriteLocker writeLock(&g_lamexp_argv.lock);
1805 g_lamexp_argv.list = new QStringList;
1807 int nArgs = 0;
1808 LPWSTR *szArglist = CommandLineToArgvW(GetCommandLineW(), &nArgs);
1810 if(NULL != szArglist)
1812 for(int i = 0; i < nArgs; i++)
1814 (*g_lamexp_argv.list) << WCHAR2QSTR(szArglist[i]);
1816 LocalFree(szArglist);
1818 else
1820 qWarning("CommandLineToArgvW() has failed !!!");
1824 return (*g_lamexp_argv.list);
1828 * Locate known folder on local system
1830 const QString &lamexp_known_folder(lamexp_known_folder_t folder_id)
1832 typedef HRESULT (WINAPI *SHGetKnownFolderPathFun)(__in const GUID &rfid, __in DWORD dwFlags, __in HANDLE hToken, __out PWSTR *ppszPath);
1833 typedef HRESULT (WINAPI *SHGetFolderPathFun)(__in HWND hwndOwner, __in int nFolder, __in HANDLE hToken, __in DWORD dwFlags, __out LPWSTR pszPath);
1835 static const int CSIDL_LOCAL_APPDATA = 0x001c;
1836 static const int CSIDL_PROGRAM_FILES = 0x0026;
1837 static const int CSIDL_SYSTEM_FOLDER = 0x0025;
1838 static const GUID GUID_LOCAL_APPDATA = {0xF1B32785,0x6FBA,0x4FCF,{0x9D,0x55,0x7B,0x8E,0x7F,0x15,0x70,0x91}};
1839 static const GUID GUID_LOCAL_APPDATA_LOW = {0xA520A1A4,0x1780,0x4FF6,{0xBD,0x18,0x16,0x73,0x43,0xC5,0xAF,0x16}};
1840 static const GUID GUID_PROGRAM_FILES = {0x905e63b6,0xc1bf,0x494e,{0xb2,0x9c,0x65,0xb7,0x32,0xd3,0xd2,0x1a}};
1841 static const GUID GUID_SYSTEM_FOLDER = {0x1AC14E77,0x02E7,0x4E5D,{0xB7,0x44,0x2E,0xB1,0xAE,0x51,0x98,0xB7}};
1843 QReadLocker readLock(&g_lamexp_folder.lock);
1845 int folderCSIDL = -1;
1846 GUID folderGUID = {0x0000,0x0000,0x0000,{0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00}};
1847 size_t folderCacheId = size_t(-1);
1849 switch(folder_id)
1851 case lamexp_folder_localappdata:
1852 folderCacheId = 0;
1853 folderCSIDL = CSIDL_LOCAL_APPDATA;
1854 folderGUID = GUID_LOCAL_APPDATA;
1855 break;
1856 case lamexp_folder_programfiles:
1857 folderCacheId = 1;
1858 folderCSIDL = CSIDL_PROGRAM_FILES;
1859 folderGUID = GUID_PROGRAM_FILES;
1860 break;
1861 case lamexp_folder_systemfolder:
1862 folderCacheId = 2;
1863 folderCSIDL = CSIDL_SYSTEM_FOLDER;
1864 folderGUID = GUID_SYSTEM_FOLDER;
1865 break;
1866 default:
1867 qWarning("Invalid 'known' folder was requested!");
1868 return *reinterpret_cast<QString*>(NULL);
1869 break;
1872 //Already in cache?
1873 if(g_lamexp_folder.knownFolders)
1875 if(g_lamexp_folder.knownFolders->contains(folderCacheId))
1877 return (*g_lamexp_folder.knownFolders)[folderCacheId];
1881 readLock.unlock();
1882 QWriteLocker writeLock(&g_lamexp_folder.lock);
1884 static SHGetKnownFolderPathFun SHGetKnownFolderPathPtr = NULL;
1885 static SHGetFolderPathFun SHGetFolderPathPtr = NULL;
1887 if((!SHGetKnownFolderPathPtr) && (!SHGetFolderPathPtr))
1889 QLibrary kernel32Lib("shell32.dll");
1890 if(kernel32Lib.load())
1892 SHGetKnownFolderPathPtr = (SHGetKnownFolderPathFun) kernel32Lib.resolve("SHGetKnownFolderPath");
1893 SHGetFolderPathPtr = (SHGetFolderPathFun) kernel32Lib.resolve("SHGetFolderPathW");
1897 QString folder;
1899 if(SHGetKnownFolderPathPtr)
1901 WCHAR *path = NULL;
1902 if(SHGetKnownFolderPathPtr(folderGUID, 0x00008000, NULL, &path) == S_OK)
1904 //MessageBoxW(0, path, L"SHGetKnownFolderPath", MB_TOPMOST);
1905 QDir folderTemp = QDir(QDir::fromNativeSeparators(QString::fromUtf16(reinterpret_cast<const unsigned short*>(path))));
1906 if(!folderTemp.exists())
1908 folderTemp.mkpath(".");
1910 if(folderTemp.exists())
1912 folder = folderTemp.canonicalPath();
1914 CoTaskMemFree(path);
1917 else if(SHGetFolderPathPtr)
1919 WCHAR *path = new WCHAR[4096];
1920 if(SHGetFolderPathPtr(NULL, folderCSIDL, NULL, NULL, path) == S_OK)
1922 //MessageBoxW(0, path, L"SHGetFolderPathW", MB_TOPMOST);
1923 QDir folderTemp = QDir(QDir::fromNativeSeparators(QString::fromUtf16(reinterpret_cast<const unsigned short*>(path))));
1924 if(!folderTemp.exists())
1926 folderTemp.mkpath(".");
1928 if(folderTemp.exists())
1930 folder = folderTemp.canonicalPath();
1933 delete [] path;
1936 //Create cache
1937 if(!g_lamexp_folder.knownFolders)
1939 g_lamexp_folder.knownFolders = new QMap<size_t, QString>();
1942 //Update cache
1943 g_lamexp_folder.knownFolders->insert(folderCacheId, folder);
1944 return (*g_lamexp_folder.knownFolders)[folderCacheId];
1948 * Safely remove a file
1950 bool lamexp_remove_file(const QString &filename)
1952 if(!QFileInfo(filename).exists() || !QFileInfo(filename).isFile())
1954 return true;
1956 else
1958 if(!QFile::remove(filename))
1960 DWORD attributes = GetFileAttributesW(QWCHAR(filename));
1961 SetFileAttributesW(QWCHAR(filename), (attributes & (~FILE_ATTRIBUTE_READONLY)));
1962 if(!QFile::remove(filename))
1964 qWarning("Could not delete \"%s\"", filename.toLatin1().constData());
1965 return false;
1967 else
1969 return true;
1972 else
1974 return true;
1980 * Check if visual themes are enabled (WinXP and later)
1982 bool lamexp_themes_enabled(void)
1984 typedef int (WINAPI *IsAppThemedFun)(void);
1986 static bool isAppThemed = false;
1987 static bool isAppThemed_initialized = false;
1989 if(!isAppThemed_initialized)
1991 IsAppThemedFun IsAppThemedPtr = NULL;
1992 QLibrary uxTheme(QString("%1/UxTheme.dll").arg(lamexp_known_folder(lamexp_folder_systemfolder)));
1993 if(uxTheme.load())
1995 IsAppThemedPtr = (IsAppThemedFun) uxTheme.resolve("IsAppThemed");
1997 if(IsAppThemedPtr)
1999 isAppThemed = IsAppThemedPtr();
2000 if(!isAppThemed)
2002 qWarning("Theme support is disabled for this process!");
2005 isAppThemed_initialized = true;
2008 return isAppThemed;
2012 * Get number of free bytes on disk
2014 unsigned __int64 lamexp_free_diskspace(const QString &path, bool *ok)
2016 ULARGE_INTEGER freeBytesAvailable, totalNumberOfBytes, totalNumberOfFreeBytes;
2017 if(GetDiskFreeSpaceExW(reinterpret_cast<const wchar_t*>(QDir::toNativeSeparators(path).utf16()), &freeBytesAvailable, &totalNumberOfBytes, &totalNumberOfFreeBytes))
2019 if(ok) *ok = true;
2020 return freeBytesAvailable.QuadPart;
2022 else
2024 if(ok) *ok = false;
2025 return 0;
2030 * Check if computer does support hibernation
2032 bool lamexp_is_hibernation_supported(void)
2034 bool hibernationSupported = false;
2036 SYSTEM_POWER_CAPABILITIES pwrCaps;
2037 SecureZeroMemory(&pwrCaps, sizeof(SYSTEM_POWER_CAPABILITIES));
2039 if(GetPwrCapabilities(&pwrCaps))
2041 hibernationSupported = pwrCaps.SystemS4 && pwrCaps.HiberFilePresent;
2044 return hibernationSupported;
2048 * Shutdown the computer
2050 bool lamexp_shutdown_computer(const QString &message, const unsigned long timeout, const bool forceShutdown, const bool hibernate)
2052 HANDLE hToken = NULL;
2054 if(OpenProcessToken(GetCurrentProcess(), TOKEN_ADJUST_PRIVILEGES | TOKEN_QUERY, &hToken))
2056 TOKEN_PRIVILEGES privileges;
2057 memset(&privileges, 0, sizeof(TOKEN_PRIVILEGES));
2058 privileges.PrivilegeCount = 1;
2059 privileges.Privileges[0].Attributes = SE_PRIVILEGE_ENABLED;
2061 if(LookupPrivilegeValue(NULL, SE_SHUTDOWN_NAME, &privileges.Privileges[0].Luid))
2063 if(AdjustTokenPrivileges(hToken, FALSE, &privileges, NULL, NULL, NULL))
2065 if(hibernate)
2067 if(SetSuspendState(TRUE, TRUE, TRUE))
2069 return true;
2072 const DWORD reason = SHTDN_REASON_MAJOR_APPLICATION | SHTDN_REASON_FLAG_PLANNED;
2073 return InitiateSystemShutdownEx(NULL, const_cast<wchar_t*>(QWCHAR(message)), timeout, forceShutdown ? TRUE : FALSE, FALSE, reason);
2078 return false;
2082 * Make a window blink (to draw user's attention)
2084 void lamexp_blink_window(QWidget *poWindow, unsigned int count, unsigned int delay)
2086 static QMutex blinkMutex;
2088 const double maxOpac = 1.0;
2089 const double minOpac = 0.3;
2090 const double delOpac = 0.1;
2092 if(!blinkMutex.tryLock())
2094 qWarning("Blinking is already in progress, skipping!");
2095 return;
2100 const int steps = static_cast<int>(ceil(maxOpac - minOpac) / delOpac);
2101 const int sleep = static_cast<int>(floor(static_cast<double>(delay) / static_cast<double>(steps)));
2102 const double opacity = poWindow->windowOpacity();
2104 for(unsigned int i = 0; i < count; i++)
2106 for(double x = maxOpac; x >= minOpac; x -= delOpac)
2108 poWindow->setWindowOpacity(x);
2109 QApplication::processEvents();
2110 Sleep(sleep);
2113 for(double x = minOpac; x <= maxOpac; x += delOpac)
2115 poWindow->setWindowOpacity(x);
2116 QApplication::processEvents();
2117 Sleep(sleep);
2121 poWindow->setWindowOpacity(opacity);
2122 QApplication::processEvents();
2123 blinkMutex.unlock();
2125 catch (...)
2127 blinkMutex.unlock();
2128 qWarning("Exception error while blinking!");
2133 * Remove forbidden characters from a filename
2135 const QString lamexp_clean_filename(const QString &str)
2137 QString newStr(str);
2139 newStr.replace("\\", "-");
2140 newStr.replace(" / ", ", ");
2141 newStr.replace("/", ",");
2142 newStr.replace(":", "-");
2143 newStr.replace("*", "x");
2144 newStr.replace("?", "");
2145 newStr.replace("<", "[");
2146 newStr.replace(">", "]");
2147 newStr.replace("|", "!");
2149 return newStr.simplified();
2153 * Remove forbidden characters from a file path
2155 const QString lamexp_clean_filepath(const QString &str)
2157 QStringList parts = QString(str).replace("\\", "/").split("/");
2159 for(int i = 0; i < parts.count(); i++)
2161 parts[i] = lamexp_clean_filename(parts[i]);
2164 return parts.join("/");
2168 * Get a list of all available Qt Text Codecs
2170 QStringList lamexp_available_codepages(bool noAliases)
2172 QStringList codecList;
2174 QList<QByteArray> availableCodecs = QTextCodec::availableCodecs();
2175 while(!availableCodecs.isEmpty())
2177 QByteArray current = availableCodecs.takeFirst();
2178 if(!(current.startsWith("system") || current.startsWith("System")))
2180 codecList << QString::fromLatin1(current.constData(), current.size());
2181 if(noAliases)
2183 if(QTextCodec *currentCodec = QTextCodec::codecForName(current.constData()))
2186 QList<QByteArray> aliases = currentCodec->aliases();
2187 while(!aliases.isEmpty()) availableCodecs.removeAll(aliases.takeFirst());
2193 return codecList;
2197 * Robert Jenkins' 96 bit Mix Function
2198 * Source: http://www.concentric.net/~Ttwang/tech/inthash.htm
2200 static unsigned int lamexp_mix(const unsigned int x, const unsigned int y, const unsigned int z)
2202 unsigned int a = x;
2203 unsigned int b = y;
2204 unsigned int c = z;
2206 a=a-b; a=a-c; a=a^(c >> 13);
2207 b=b-c; b=b-a; b=b^(a << 8);
2208 c=c-a; c=c-b; c=c^(b >> 13);
2209 a=a-b; a=a-c; a=a^(c >> 12);
2210 b=b-c; b=b-a; b=b^(a << 16);
2211 c=c-a; c=c-b; c=c^(b >> 5);
2212 a=a-b; a=a-c; a=a^(c >> 3);
2213 b=b-c; b=b-a; b=b^(a << 10);
2214 c=c-a; c=c-b; c=c^(b >> 15);
2216 return c;
2220 * Seeds the random number generator
2221 * Note: Altough rand_s() doesn't need a seed, this must be called pripr to lamexp_rand(), just to to be sure!
2223 void lamexp_seed_rand(void)
2225 qsrand(lamexp_mix(clock(), time(NULL), _getpid()));
2229 * Returns a randum number
2230 * Note: This function uses rand_s() if available, but falls back to qrand() otherwise
2232 unsigned int lamexp_rand(void)
2234 unsigned int rnd = 0;
2235 if(const lamexp_os_version_t* osVer = lamexp_get_os_version())
2237 if(LAMEXP_MIN_OS_VER(osVer, 5, 1))
2239 if(rand_s(&rnd) == 0)
2241 return rnd;
2245 for(size_t i = 0; i < sizeof(unsigned int); i++)
2247 rnd = (rnd << 8) ^ qrand();
2249 return rnd;
2253 * Determines the current date, resistant against certain manipulations
2255 QDate lamexp_current_date_safe(void)
2257 const DWORD MAX_PROC = 1024;
2258 DWORD *processes = new DWORD[MAX_PROC];
2259 DWORD bytesReturned = 0;
2261 if(!EnumProcesses(processes, sizeof(DWORD) * MAX_PROC, &bytesReturned))
2263 LAMEXP_DELETE_ARRAY(processes);
2264 return QDate::currentDate();
2267 const DWORD procCount = bytesReturned / sizeof(DWORD);
2268 ULARGE_INTEGER lastStartTime;
2269 memset(&lastStartTime, 0, sizeof(ULARGE_INTEGER));
2271 for(DWORD i = 0; i < procCount; i++)
2273 HANDLE hProc = OpenProcess(PROCESS_QUERY_INFORMATION, FALSE, processes[i]);
2274 if(hProc)
2276 FILETIME processTime[4];
2277 if(GetProcessTimes(hProc, &processTime[0], &processTime[1], &processTime[2], &processTime[3]))
2279 ULARGE_INTEGER timeCreation;
2280 timeCreation.LowPart = processTime[0].dwLowDateTime;
2281 timeCreation.HighPart = processTime[0].dwHighDateTime;
2282 if(timeCreation.QuadPart > lastStartTime.QuadPart)
2284 lastStartTime.QuadPart = timeCreation.QuadPart;
2287 CloseHandle(hProc);
2291 LAMEXP_DELETE_ARRAY(processes);
2293 FILETIME lastStartTime_fileTime;
2294 lastStartTime_fileTime.dwHighDateTime = lastStartTime.HighPart;
2295 lastStartTime_fileTime.dwLowDateTime = lastStartTime.LowPart;
2297 FILETIME lastStartTime_localTime;
2298 if(!FileTimeToLocalFileTime(&lastStartTime_fileTime, &lastStartTime_localTime))
2300 memcpy(&lastStartTime_localTime, &lastStartTime_fileTime, sizeof(FILETIME));
2303 SYSTEMTIME lastStartTime_system;
2304 if(!FileTimeToSystemTime(&lastStartTime_localTime, &lastStartTime_system))
2306 memset(&lastStartTime_system, 0, sizeof(SYSTEMTIME));
2307 lastStartTime_system.wYear = 1970; lastStartTime_system.wMonth = lastStartTime_system.wDay = 1;
2310 const QDate currentDate = QDate::currentDate();
2311 const QDate processDate = QDate(lastStartTime_system.wYear, lastStartTime_system.wMonth, lastStartTime_system.wDay);
2312 return (currentDate >= processDate) ? currentDate : processDate;
2316 * Entry point checks
2318 static DWORD lamexp_entry_check(void);
2319 static DWORD g_lamexp_entry_check_result = lamexp_entry_check();
2320 static DWORD g_lamexp_entry_check_flag = 0x789E09B2;
2321 static DWORD lamexp_entry_check(void)
2323 volatile DWORD retVal = 0xA199B5AF;
2324 if(g_lamexp_entry_check_flag != 0x8761F64D)
2326 lamexp_fatal_exit(L"Application initialization has failed, take care!");
2328 return retVal;
2332 * Application entry point (runs before static initializers)
2334 extern "C"
2336 int WinMainCRTStartup(void);
2338 int lamexp_entry_point(void)
2340 if((!LAMEXP_DEBUG) && lamexp_check_for_debugger())
2342 lamexp_fatal_exit(L"Not a debug build. Please unload debugger and try again!");
2344 if(g_lamexp_entry_check_flag != 0x789E09B2)
2346 lamexp_fatal_exit(L"Application initialization has failed, take care!");
2349 //Zero *before* constructors are called
2350 LAMEXP_ZERO_MEMORY(g_lamexp_argv);
2351 LAMEXP_ZERO_MEMORY(g_lamexp_tools);
2352 LAMEXP_ZERO_MEMORY(g_lamexp_currentTranslator);
2353 LAMEXP_ZERO_MEMORY(g_lamexp_translation);
2354 LAMEXP_ZERO_MEMORY(g_lamexp_folder);
2355 LAMEXP_ZERO_MEMORY(g_lamexp_ipc_ptr);
2356 LAMEXP_ZERO_MEMORY(g_lamexp_os_version);
2358 //Make sure we will pass the check
2359 g_lamexp_entry_check_flag = ~g_lamexp_entry_check_flag;
2361 //Now initialize the C Runtime library!
2362 return WinMainCRTStartup();
2367 * Fatal application exit
2369 #pragma intrinsic(_InterlockedExchange)
2370 void lamexp_fatal_exit(const wchar_t* exitMessage, const wchar_t* errorBoxMessage)
2372 static volatile long bFatalFlag = 0L;
2374 if(_InterlockedExchange(&bFatalFlag, 1L) == 0L)
2376 if(GetCurrentThreadId() != g_main_thread_id)
2378 HANDLE mainThread = OpenThread(THREAD_TERMINATE, FALSE, g_main_thread_id);
2379 if(mainThread) TerminateThread(mainThread, ULONG_MAX);
2382 if(errorBoxMessage)
2384 MessageBoxW(NULL, errorBoxMessage, L"LameXP - GURU MEDITATION", MB_ICONERROR | MB_TOPMOST | MB_TASKMODAL);
2387 for(;;)
2389 FatalAppExit(0, exitMessage);
2390 TerminateProcess(GetCurrentProcess(), -1);
2394 TerminateThread(GetCurrentThread(), -1);
2395 Sleep(INFINITE);
2399 * Finalization function (final clean-up)
2401 void lamexp_finalization(void)
2403 qDebug("lamexp_finalization()");
2405 //Free all tools
2406 if(g_lamexp_tools.registry)
2408 QStringList keys = g_lamexp_tools.registry->keys();
2409 for(int i = 0; i < keys.count(); i++)
2411 LAMEXP_DELETE((*g_lamexp_tools.registry)[keys.at(i)]);
2413 LAMEXP_DELETE(g_lamexp_tools.registry);
2414 LAMEXP_DELETE(g_lamexp_tools.versions);
2417 //Delete temporary files
2418 if(g_lamexp_folder.temp)
2420 if(!g_lamexp_folder.temp->isEmpty())
2422 for(int i = 0; i < 100; i++)
2424 if(lamexp_clean_folder(*g_lamexp_folder.temp))
2426 break;
2428 Sleep(125);
2431 LAMEXP_DELETE(g_lamexp_folder.temp);
2434 //Clear folder cache
2435 LAMEXP_DELETE(g_lamexp_folder.knownFolders);
2437 //Clear languages
2438 if(g_lamexp_currentTranslator.instance)
2440 QApplication::removeTranslator(g_lamexp_currentTranslator.instance);
2441 LAMEXP_DELETE(g_lamexp_currentTranslator.instance);
2443 LAMEXP_DELETE(g_lamexp_translation.files);
2444 LAMEXP_DELETE(g_lamexp_translation.names);
2445 LAMEXP_DELETE(g_lamexp_translation.cntry);
2446 LAMEXP_DELETE(g_lamexp_translation.sysid);
2448 //Destroy Qt application object
2449 QApplication *application = dynamic_cast<QApplication*>(QApplication::instance());
2450 LAMEXP_DELETE(application);
2452 //Detach from shared memory
2453 if(g_lamexp_ipc_ptr.sharedmem) g_lamexp_ipc_ptr.sharedmem->detach();
2454 LAMEXP_DELETE(g_lamexp_ipc_ptr.sharedmem);
2455 LAMEXP_DELETE(g_lamexp_ipc_ptr.semaphore_read);
2456 LAMEXP_DELETE(g_lamexp_ipc_ptr.semaphore_write);
2457 LAMEXP_DELETE(g_lamexp_ipc_ptr.semaphore_read_mutex);
2458 LAMEXP_DELETE(g_lamexp_ipc_ptr.semaphore_write_mutex);
2460 //Free STDOUT and STDERR buffers
2461 if(g_lamexp_console_attached)
2463 if(std::filebuf *tmp = dynamic_cast<std::filebuf*>(std::cout.rdbuf()))
2465 std::cout.rdbuf(NULL);
2466 LAMEXP_DELETE(tmp);
2468 if(std::filebuf *tmp = dynamic_cast<std::filebuf*>(std::cerr.rdbuf()))
2470 std::cerr.rdbuf(NULL);
2471 LAMEXP_DELETE(tmp);
2475 //Close log file
2476 if(g_lamexp_log_file)
2478 fclose(g_lamexp_log_file);
2479 g_lamexp_log_file = NULL;
2482 //Free CLI Arguments
2483 LAMEXP_DELETE(g_lamexp_argv.list);
2487 * Initialize debug thread
2489 static const HANDLE g_debug_thread = LAMEXP_DEBUG ? NULL : lamexp_debug_thread_init();
2492 * Get number private bytes [debug only]
2494 SIZE_T lamexp_dbg_private_bytes(void)
2496 #if LAMEXP_DEBUG
2497 PROCESS_MEMORY_COUNTERS_EX memoryCounters;
2498 memoryCounters.cb = sizeof(PROCESS_MEMORY_COUNTERS_EX);
2499 GetProcessMemoryInfo(GetCurrentProcess(), (PPROCESS_MEMORY_COUNTERS) &memoryCounters, sizeof(PROCESS_MEMORY_COUNTERS_EX));
2500 return memoryCounters.PrivateUsage;
2501 #else
2502 throw "Cannot call this function in a non-debug build!";
2503 #endif //LAMEXP_DEBUG