OSDN Git Service

Small optimization of lamexp_themes_enabled().
[lamexp/LameXP.git] / src / Global.cpp
index be5c8c0..2cc2ff9 100644 (file)
@@ -1,6 +1,6 @@
 ///////////////////////////////////////////////////////////////////////////////
 // LameXP - Audio Encoder Front-End
-// Copyright (C) 2004-2011 LoRd_MuldeR <MuldeR2@GMX.de>
+// Copyright (C) 2004-2012 LoRd_MuldeR <MuldeR2@GMX.de>
 //
 // This program is free software; you can redistribute it and/or modify
 // it under the terms of the GNU General Public License as published by
@@ -44,6 +44,7 @@
 #include <QEventLoop>
 #include <QTimer>
 #include <QLibraryInfo>
+#include <QEvent>
 
 //LameXP includes
 #include "Resource.h"
@@ -56,6 +57,8 @@
 #include <fcntl.h>
 #include <intrin.h>
 #include <math.h>
+#include <time.h>
+#include <process.h>
 
 //COM includes
 #include <Objbase.h>
@@ -76,13 +79,24 @@ Q_IMPORT_PLUGIN(qsvg)
 // TYPES
 ///////////////////////////////////////////////////////////////////////////////
 
+static const size_t g_lamexp_ipc_slots = 128;
+
 typedef struct
 {
        unsigned int command;
        unsigned int reserved_1;
        unsigned int reserved_2;
        char parameter[4096];
-} lamexp_ipc_t;
+}
+lamexp_ipc_data_t;
+
+typedef struct
+{
+       unsigned int pos_write;
+       unsigned int pos_read;
+       lamexp_ipc_data_t data[g_lamexp_ipc_slots];
+}
+lamexp_ipc_t;
 
 ///////////////////////////////////////////////////////////////////////////////
 // GLOBAL VARS
@@ -119,9 +133,9 @@ static bool g_lamexp_console_attached = false;
        #if (__INTEL_COMPILER >= 1200)
                static const char *g_lamexp_version_compiler = "ICL 12.x";
        #elif (__INTEL_COMPILER >= 1100)
-               static const char *g_lamexp_version_compiler = "ICL 11.x";
+               static const char *g_lamexp_version_compiler = "ICL 11.x";
        #elif (__INTEL_COMPILER >= 1000)
-               static const char *g_lamexp_version_compiler = "ICL 10.x";
+               static const char *g_lamexp_version_compiler = "ICL 10.x";
        #else
                #error Compiler is not supported!
        #endif
@@ -198,19 +212,25 @@ static const struct
 {
        char *sharedmem;
        char *semaphore_read;
+       char *semaphore_read_mutex;
        char *semaphore_write;
+       char *semaphore_write_mutex;
 }
 g_lamexp_ipc_uuid =
 {
        "{21A68A42-6923-43bb-9CF6-64BF151942EE}",
        "{7A605549-F58C-4d78-B4E5-06EFC34F405B}",
-       "{60AA8D04-F6B8-497d-81EB-0F600F4A65B5}"
+       "{60AA8D04-F6B8-497d-81EB-0F600F4A65B5}",
+       "{726061D5-1615-4B82-871C-75FD93458E46}",
+       "{1A616023-AA6A-4519-8AF3-F7736E899977}"
 };
 static struct
 {
        QSharedMemory *sharedmem;
        QSystemSemaphore *semaphore_read;
+       QSystemSemaphore *semaphore_read_mutex;
        QSystemSemaphore *semaphore_write;
+       QSystemSemaphore *semaphore_write_mutex;
 }
 g_lamexp_ipc_ptr =
 {
@@ -226,6 +246,8 @@ static QMutex g_lamexp_message_mutex;
 //Main thread ID
 static const DWORD g_main_thread_id = GetCurrentThreadId();
 
+//Log file
+static FILE *g_lamexp_log_file = NULL;
 
 ///////////////////////////////////////////////////////////////////////////////
 // GLOBAL FUNCTIONS
@@ -285,39 +307,30 @@ const QDate &lamexp_version_date(void)
 {
        if(!g_lamexp_version_date.isValid())
        {
-               char temp[32];
-               int date[3];
+               int date[3] = {0, 0, 0}; char temp[12] = {'\0'};
+               strncpy_s(temp, 12, g_lamexp_version_raw_date, _TRUNCATE);
 
-               char *this_token = NULL;
-               char *next_token = NULL;
-
-               strncpy_s(temp, 32, g_lamexp_version_raw_date, _TRUNCATE);
-               this_token = strtok_s(temp, " ", &next_token);
-
-               for(int i = 0; i < 3; i++)
+               if(strlen(temp) == 11)
                {
-                       date[i] = -1;
-                       if(this_token)
+                       temp[3] = temp[6] = '\0';
+                       date[2] = atoi(&temp[4]);
+                       date[0] = atoi(&temp[7]);
+                       
+                       for(int j = 0; j < 12; j++)
                        {
-                               for(int j = 0; j < 12; j++)
-                               {
-                                       if(!_strcmpi(this_token, g_lamexp_months[j]))
-                                       {
-                                               date[i] = j+1;
-                                               break;
-                                       }
-                               }
-                               if(date[i] < 0)
+                               if(!_strcmpi(&temp[0], g_lamexp_months[j]))
                                {
-                                       date[i] = atoi(this_token);
+                                       date[1] = j+1;
+                                       break;
                                }
-                               this_token = strtok_s(NULL, " ", &next_token);
                        }
+
+                       g_lamexp_version_date = QDate(date[0], date[1], date[2]);
                }
 
-               if(date[0] >= 0 && date[1] >= 0 && date[2] >= 0)
+               if(!g_lamexp_version_date.isValid())
                {
-                       g_lamexp_version_date = QDate(date[2], date[0], date[1]);
+                       qFatal("Internal error: Date format could not be recognized!");
                }
        }
 
@@ -329,21 +342,48 @@ const QDate &lamexp_version_date(void)
  */
 DWORD lamexp_get_os_version(void)
 {
-       OSVERSIONINFO osVerInfo;
-       memset(&osVerInfo, 0, sizeof(OSVERSIONINFO));
-       osVerInfo.dwOSVersionInfoSize = sizeof(OSVERSIONINFO);
-       DWORD version = 0;
+       static DWORD osVersion = 0;
+       
+       if(!osVersion)
+       {
+               OSVERSIONINFO osVerInfo;
+               memset(&osVerInfo, 0, sizeof(OSVERSIONINFO));
+               osVerInfo.dwOSVersionInfoSize = sizeof(OSVERSIONINFO);
        
-       if(GetVersionEx(&osVerInfo) == TRUE)
+               if(GetVersionEx(&osVerInfo) == TRUE)
+               {
+                       if(osVerInfo.dwPlatformId != VER_PLATFORM_WIN32_NT)
+                       {
+                               throw "Ouuups: Not running under Windows NT. This is not supposed to happen!";
+                       }
+                       osVersion = (DWORD)((osVerInfo.dwMajorVersion << 16) | (osVerInfo.dwMinorVersion & 0xffff));
+               }
+       }
+
+       return osVersion;
+}
+
+/*
+ * Check if we are running under wine
+ */
+bool lamexp_detect_wine(void)
+{
+       static bool isWine = false;
+       static bool isWine_initialized = false;
+
+       if(!isWine_initialized)
        {
-               if(osVerInfo.dwPlatformId != VER_PLATFORM_WIN32_NT)
+               QLibrary ntdll("ntdll.dll");
+               if(ntdll.load())
                {
-                       throw "Ouuups: Not running under Windows NT. This is not supposed to happen!";
+                       if(ntdll.resolve("wine_nt_to_unix_file_name") != NULL) isWine = true;
+                       if(ntdll.resolve("wine_get_version") != NULL) isWine = true;
+                       ntdll.unload();
                }
-               version = (DWORD)((osVerInfo.dwMajorVersion << 16) | (osVerInfo.dwMinorVersion & 0xffff));
+               isWine_initialized = true;
        }
 
-       return version;
+       return isWine;
 }
 
 /*
@@ -399,11 +439,15 @@ void lamexp_message_handler(QtMsgType type, const char *msg)
        
        QMutexLocker lock(&g_lamexp_message_mutex);
 
-       //if((strlen(msg) > 8) && (_strnicmp(msg, "@BASE64@", 8) == 0))
-       //{
-       //      buffer = _strdup(QByteArray::fromBase64(msg + 8).constData());
-       //      if(buffer) text = buffer;
-       //}
+       if(g_lamexp_log_file)
+       {
+               static char prefix[] = "DWCF";
+               int index = qBound(0, static_cast<int>(type), 3);
+               unsigned int timestamp = static_cast<unsigned int>(_time64(NULL) % 3600I64);
+               QString str = QString::fromUtf8(msg).trimmed().replace('\n', '\t');
+               fprintf(g_lamexp_log_file, "[%c][%04u] %s\r\n", prefix[index], timestamp, str.toUtf8().constData());
+               fflush(g_lamexp_log_file);
+       }
 
        if(g_lamexp_console_attached)
        {
@@ -461,6 +505,13 @@ void lamexp_message_handler(QtMsgType type, const char *msg)
        if(type == QtCriticalMsg || type == QtFatalMsg)
        {
                lock.unlock();
+
+               if(GetCurrentThreadId() != g_main_thread_id)
+               {
+                       HANDLE mainThread = OpenThread(THREAD_TERMINATE, FALSE, g_main_thread_id);
+                       if(mainThread) TerminateThread(mainThread, ULONG_MAX);
+               }
+
                MessageBoxW(NULL, QWCHAR(QString::fromUtf8(msg)), L"LameXP - GURU MEDITATION", MB_ICONERROR | MB_TOPMOST | MB_TASKMODAL);
                FatalAppExit(0, L"The application has encountered a critical error and will exit now!");
                TerminateProcess(GetCurrentProcess(), -1);
@@ -474,6 +525,25 @@ void lamexp_init_console(int argc, char* argv[])
 {
        bool enableConsole = lamexp_version_demo();
 
+       if(_environ)
+       {
+               wchar_t *logfile = NULL;
+               size_t logfile_len = 0;
+               if(!_wdupenv_s(&logfile, &logfile_len, L"LAMEXP_LOGFILE"))
+               {
+                       if(logfile && (logfile_len > 0))
+                       {
+                               FILE *temp = NULL;
+                               if(!_wfopen_s(&temp, logfile, L"wb"))
+                               {
+                                       fprintf(temp, "%c%c%c", 0xEF, 0xBB, 0xBF);
+                                       g_lamexp_log_file = temp;
+                               }
+                               free(logfile);
+                       }
+               }
+       }
+
        if(!LAMEXP_DEBUG)
        {
                for(int i = 0; i < argc; i++)
@@ -647,29 +717,53 @@ lamexp_cpu_t lamexp_detect_cpu_features(int argc, char **argv)
 /*
  * Check for debugger (detect routine)
  */
-static bool lamexp_check_for_debugger(void)
+static __forceinline bool lamexp_check_for_debugger(void)
 {
+       if(IsDebuggerPresent())
+       {
+               return true;
+       }
+       
+       __try
+       {
+               CloseHandle((HANDLE) 0x7FFFFFFF);
+       }
+       __except(EXCEPTION_EXECUTE_HANDLER)
+       {
+               return true;
+       }
+
        __try 
        {
                DebugBreak();
        }
-       __except(GetExceptionCode() == EXCEPTION_BREAKPOINT ? EXCEPTION_EXECUTE_HANDLER : EXCEPTION_CONTINUE_SEARCH
+       __except(EXCEPTION_EXECUTE_HANDLER
        {
                return false;
        }
+       
        return true;
 }
 
 /*
  * Check for debugger (thread proc)
  */
-static void WINAPI lamexp_debug_thread_proc(__in LPVOID lpParameter)
+static unsigned int __stdcall lamexp_debug_thread_proc(LPVOID lpParameter)
 {
-       while(!(IsDebuggerPresent() || lamexp_check_for_debugger()))
+       while(!lamexp_check_for_debugger())
+       {
+               Sleep(32);
+       }
+       if(HANDLE thrd = OpenThread(THREAD_TERMINATE, FALSE, g_main_thread_id))
        {
-               Sleep(333);
+               if(TerminateThread(thrd, -1))
+               {
+                       FatalAppExit(0, L"Not a debug build. Please unload debugger and try again!");
+               }
+               CloseHandle(thrd);
        }
        TerminateProcess(GetCurrentProcess(), -1);
+       return 666;
 }
 
 /*
@@ -677,13 +771,13 @@ static void WINAPI lamexp_debug_thread_proc(__in LPVOID lpParameter)
  */
 static HANDLE lamexp_debug_thread_init(void)
 {
-       if(IsDebuggerPresent() || lamexp_check_for_debugger())
+       if(lamexp_check_for_debugger())
        {
                FatalAppExit(0, L"Not a debug build. Please unload debugger and try again!");
                TerminateProcess(GetCurrentProcess(), -1);
        }
 
-       return CreateThread(NULL, NULL, reinterpret_cast<LPTHREAD_START_ROUTINE>(&lamexp_debug_thread_proc), NULL, NULL, NULL);
+       return (HANDLE) _beginthreadex(NULL, 0, lamexp_debug_thread_proc, NULL, 0, NULL);
 }
 
 /*
@@ -707,6 +801,161 @@ static bool lamexp_check_compatibility_mode(const char *exportName, const char *
 }
 
 /*
+ * Computus according to H. Lichtenberg
+ */
+static bool lamexp_computus(const QDate &date)
+{
+       int X = date.year();
+       int A = X % 19;
+       int K = X / 100;
+       int M = 15 + (3*K + 3) / 4 - (8*K + 13) / 25;
+       int D = (19*A + M) % 30;
+       int S = 2 - (3*K + 3) / 4;
+       int R = D / 29 + (D / 28 - D / 29) * (A / 11);
+       int OG = 21 + D - R;
+       int SZ = 7 - (X + X / 4 + S) % 7;
+       int OE = 7 - (OG - SZ) % 7;
+       int OS = (OG + OE);
+
+       if(OS > 31)
+       {
+               return (date.month() == 4) && (date.day() == (OS - 31));
+       }
+       else
+       {
+               return (date.month() == 3) && (date.day() == OS);
+       }
+}
+
+/*
+ * Check for Thanksgiving
+ */
+static bool lamexp_thanksgiving(const QDate &date)
+{
+       int day = 0;
+
+       switch(QDate(date.year(), 11, 1).dayOfWeek())
+       {
+               case 1: day = 25; break; 
+               case 2: day = 24; break; 
+               case 3: day = 23; break; 
+               case 4: day = 22; break; 
+               case 5: day = 28; break; 
+               case 6: day = 27; break; 
+               case 7: day = 26; break;
+       }
+
+       return (date.month() == 11) && (date.day() == day);
+}
+
+/*
+ * Initialize app icon
+ */
+QIcon lamexp_app_icon(const QDate *date, const QTime *time)
+{
+       QDate currentDate = (date) ? QDate(*date) : QDate::currentDate();
+       QTime currentTime = (time) ? QTime(*time) : QTime::currentTime();
+       
+       if(lamexp_thanksgiving(currentDate))
+       {
+               return QIcon(":/MainIcon6.png");
+       }
+       else if(((currentDate.month() == 12) && (currentDate.day() == 31) && (currentTime.hour() >= 20)) || ((currentDate.month() == 1) && (currentDate.day() == 1)  && (currentTime.hour() <= 19)))
+       {
+               return QIcon(":/MainIcon5.png");
+       }
+       else if(((currentDate.month() == 10) && (currentDate.day() == 31) && (currentTime.hour() >= 12)) || ((currentDate.month() == 11) && (currentDate.day() == 1)  && (currentTime.hour() <= 11)))
+       {
+               return QIcon(":/MainIcon4.png");
+       }
+       else if((currentDate.month() == 12) && (currentDate.day() >= 24) && (currentDate.day() <= 26))
+       {
+               return QIcon(":/MainIcon3.png");
+       }
+       else if(lamexp_computus(currentDate))
+       {
+               return QIcon(":/MainIcon2.png");
+       }
+       else
+       {
+               return QIcon(":/MainIcon1.png");
+       }
+}
+
+/*
+ * Broadcast event to all windows
+ */
+static bool lamexp_broadcast(int eventType, bool onlyToVisible)
+{
+       if(QApplication *app = dynamic_cast<QApplication*>(QApplication::instance()))
+       {
+               qDebug("Broadcasting %d", eventType);
+               
+               bool allOk = true;
+               QEvent poEvent(static_cast<QEvent::Type>(eventType));
+               QWidgetList list = app->topLevelWidgets();
+
+               while(!list.isEmpty())
+               {
+                       QWidget *widget = list.takeFirst();
+                       if(!onlyToVisible || widget->isVisible())
+                       {
+                               if(!app->sendEvent(widget, &poEvent))
+                               {
+                                       allOk = false;
+                               }
+                       }
+               }
+
+               qDebug("Broadcast %d done (%s)", eventType, (allOk ? "OK" : "Stopped"));
+               return allOk;
+       }
+       else
+       {
+               qWarning("Broadcast failed, could not get QApplication instance!");
+               return false;
+       }
+}
+
+/*
+ * Qt event filter
+ */
+static bool lamexp_event_filter(void *message, long *result)
+{
+       if((!(LAMEXP_DEBUG)) && lamexp_check_for_debugger())
+       {
+               FatalAppExit(0, L"Not a debug build. Please unload debugger and try again!");
+               TerminateProcess(GetCurrentProcess(), -1);
+       }
+       
+       switch(reinterpret_cast<MSG*>(message)->message)
+       {
+       case WM_QUERYENDSESSION:
+               qWarning("WM_QUERYENDSESSION message received!");
+               *result = lamexp_broadcast(lamexp_event_queryendsession, false) ? TRUE : FALSE;
+               return true;
+       case WM_ENDSESSION:
+               qWarning("WM_ENDSESSION message received!");
+               if(reinterpret_cast<MSG*>(message)->wParam == TRUE)
+               {
+                       lamexp_broadcast(lamexp_event_endsession, false);
+                       if(QApplication *app = reinterpret_cast<QApplication*>(QApplication::instance()))
+                       {
+                               app->closeAllWindows();
+                               app->quit();
+                       }
+                       lamexp_finalization();
+                       exit(1);
+               }
+               *result = 0;
+               return true;
+       default:
+               /*ignore this message and let Qt handle it*/
+               return false;
+       }
+}
+
+/*
  * Check for process elevation
  */
 static bool lamexp_check_elevation(void)
@@ -756,7 +1005,6 @@ static bool lamexp_check_elevation(void)
 bool lamexp_init_qt(int argc, char* argv[])
 {
        static bool qt_initialized = false;
-       bool isWine = false;
        typedef BOOL (WINAPI *SetDllDirectoryProc)(WCHAR *lpPathName);
 
        //Don't initialized again, if done already
@@ -831,24 +1079,21 @@ bool lamexp_init_qt(int argc, char* argv[])
        }
 
        //Check for Wine
-       QLibrary ntdll("ntdll.dll");
-       if(ntdll.load())
+       if(lamexp_detect_wine())
        {
-               if(ntdll.resolve("wine_nt_to_unix_file_name") != NULL) isWine = true;
-               if(ntdll.resolve("wine_get_version") != NULL) isWine = true;
-               if(isWine) qWarning("It appears we are running under Wine, unexpected things might happen!\n");
-               ntdll.unload();
+               qWarning("It appears we are running under Wine, unexpected things might happen!\n");
        }
 
+
        //Create Qt application instance and setup version info
-       QDate date = QDate::currentDate();
        QApplication *application = new QApplication(argc, argv);
        application->setApplicationName("LameXP - Audio Encoder Front-End");
        application->setApplicationVersion(QString().sprintf("%d.%02d.%04d", lamexp_version_major(), lamexp_version_minor(), lamexp_version_build())); 
        application->setOrganizationName("LoRd_MuldeR");
        application->setOrganizationDomain("mulder.at.gg");
-       application->setWindowIcon((date.month() == 12 && date.day() >= 24 && date.day() <= 26) ? QIcon(":/MainIcon2.png") : QIcon(":/MainIcon.png"));
-       
+       application->setWindowIcon(lamexp_app_icon());
+       application->setEventFilter(lamexp_event_filter);
+
        //Set text Codec for locale
        QTextCodec::setCodecForLocale(QTextCodec::codecForName("UTF-8"));
 
@@ -872,16 +1117,19 @@ bool lamexp_init_qt(int argc, char* argv[])
        g_lamexp_translation.names.insert(LAMEXP_DEFAULT_LANGID, "English");
 
        //Check for process elevation
-       if(!lamexp_check_elevation())
+       if((!lamexp_check_elevation()) && (!lamexp_detect_wine()))
        {
-               if(QMessageBox::warning(NULL, "LameXP", "<nobr>LameXP was started with elevated rights. This is a potential security risk!</nobr>", "Quit Program (Recommended)", "Ignore") == 0)
+               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);
+               messageBox.addButton("Quit Program (Recommended)", QMessageBox::NoRole);
+               messageBox.addButton("Ignore", QMessageBox::NoRole);
+               if(messageBox.exec() == 0)
                {
                        return false;
                }
        }
 
        //Update console icon, if a console is attached
-       if(g_lamexp_console_attached && !isWine)
+       if(g_lamexp_console_attached && (!lamexp_detect_wine()))
        {
                typedef DWORD (__stdcall *SetConsoleIconFun)(HICON);
                QLibrary kernel32("kernel32.dll");
@@ -903,19 +1151,23 @@ bool lamexp_init_qt(int argc, char* argv[])
  */
 int lamexp_init_ipc(void)
 {
-       if(g_lamexp_ipc_ptr.sharedmem && g_lamexp_ipc_ptr.semaphore_read && g_lamexp_ipc_ptr.semaphore_write)
+       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)
        {
                return 0;
        }
 
        g_lamexp_ipc_ptr.semaphore_read = new QSystemSemaphore(QString(g_lamexp_ipc_uuid.semaphore_read), 0);
        g_lamexp_ipc_ptr.semaphore_write = new QSystemSemaphore(QString(g_lamexp_ipc_uuid.semaphore_write), 0);
+       g_lamexp_ipc_ptr.semaphore_read_mutex = new QSystemSemaphore(QString(g_lamexp_ipc_uuid.semaphore_read_mutex), 0);
+       g_lamexp_ipc_ptr.semaphore_write_mutex = new QSystemSemaphore(QString(g_lamexp_ipc_uuid.semaphore_write_mutex), 0);
 
        if(g_lamexp_ipc_ptr.semaphore_read->error() != QSystemSemaphore::NoError)
        {
                QString errorMessage = g_lamexp_ipc_ptr.semaphore_read->errorString();
                LAMEXP_DELETE(g_lamexp_ipc_ptr.semaphore_read);
                LAMEXP_DELETE(g_lamexp_ipc_ptr.semaphore_write);
+               LAMEXP_DELETE(g_lamexp_ipc_ptr.semaphore_read_mutex);
+               LAMEXP_DELETE(g_lamexp_ipc_ptr.semaphore_write_mutex);
                qFatal("Failed to create system smaphore: %s", errorMessage.toUtf8().constData());
                return -1;
        }
@@ -924,6 +1176,28 @@ int lamexp_init_ipc(void)
                QString errorMessage = g_lamexp_ipc_ptr.semaphore_write->errorString();
                LAMEXP_DELETE(g_lamexp_ipc_ptr.semaphore_read);
                LAMEXP_DELETE(g_lamexp_ipc_ptr.semaphore_write);
+               LAMEXP_DELETE(g_lamexp_ipc_ptr.semaphore_read_mutex);
+               LAMEXP_DELETE(g_lamexp_ipc_ptr.semaphore_write_mutex);
+               qFatal("Failed to create system smaphore: %s", errorMessage.toUtf8().constData());
+               return -1;
+       }
+       if(g_lamexp_ipc_ptr.semaphore_read_mutex->error() != QSystemSemaphore::NoError)
+       {
+               QString errorMessage = g_lamexp_ipc_ptr.semaphore_read_mutex->errorString();
+               LAMEXP_DELETE(g_lamexp_ipc_ptr.semaphore_read);
+               LAMEXP_DELETE(g_lamexp_ipc_ptr.semaphore_write);
+               LAMEXP_DELETE(g_lamexp_ipc_ptr.semaphore_read_mutex);
+               LAMEXP_DELETE(g_lamexp_ipc_ptr.semaphore_write_mutex);
+               qFatal("Failed to create system smaphore: %s", errorMessage.toUtf8().constData());
+               return -1;
+       }
+       if(g_lamexp_ipc_ptr.semaphore_write_mutex->error() != QSystemSemaphore::NoError)
+       {
+               QString errorMessage = g_lamexp_ipc_ptr.semaphore_write_mutex->errorString();
+               LAMEXP_DELETE(g_lamexp_ipc_ptr.semaphore_read);
+               LAMEXP_DELETE(g_lamexp_ipc_ptr.semaphore_write);
+               LAMEXP_DELETE(g_lamexp_ipc_ptr.semaphore_read_mutex);
+               LAMEXP_DELETE(g_lamexp_ipc_ptr.semaphore_write_mutex);
                qFatal("Failed to create system smaphore: %s", errorMessage.toUtf8().constData());
                return -1;
        }
@@ -942,6 +1216,7 @@ int lamexp_init_ipc(void)
                        else
                        {
                                QString errorMessage = g_lamexp_ipc_ptr.sharedmem->errorString();
+                               LAMEXP_DELETE(g_lamexp_ipc_ptr.sharedmem);
                                qFatal("Failed to attach to shared memory: %s", errorMessage.toUtf8().constData());
                                return -1;
                        }
@@ -949,13 +1224,16 @@ int lamexp_init_ipc(void)
                else
                {
                        QString errorMessage = g_lamexp_ipc_ptr.sharedmem->errorString();
+                       LAMEXP_DELETE(g_lamexp_ipc_ptr.sharedmem);
                        qFatal("Failed to create shared memory: %s", errorMessage.toUtf8().constData());
                        return -1;
                }
        }
 
        memset(g_lamexp_ipc_ptr.sharedmem->data(), 0, sizeof(lamexp_ipc_t));
-       g_lamexp_ipc_ptr.semaphore_write->release();
+       g_lamexp_ipc_ptr.semaphore_write->release(g_lamexp_ipc_slots);
+       g_lamexp_ipc_ptr.semaphore_read_mutex->release();
+       g_lamexp_ipc_ptr.semaphore_write_mutex->release();
 
        return 0;
 }
@@ -965,26 +1243,31 @@ int lamexp_init_ipc(void)
  */
 void lamexp_ipc_send(unsigned int command, const char* message)
 {
-       if(!g_lamexp_ipc_ptr.sharedmem || !g_lamexp_ipc_ptr.semaphore_read || !g_lamexp_ipc_ptr.semaphore_write)
+       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)
        {
                throw "Shared memory for IPC not initialized yet.";
        }
 
-       lamexp_ipc_t *lamexp_ipc = new lamexp_ipc_t;
-       memset(lamexp_ipc, 0, sizeof(lamexp_ipc_t));
-       lamexp_ipc->command = command;
+       lamexp_ipc_data_t ipc_data;
+       memset(&ipc_data, 0, sizeof(lamexp_ipc_data_t));
+       ipc_data.command = command;
+       
        if(message)
        {
-               strncpy_s(lamexp_ipc->parameter, 4096, message, _TRUNCATE);
+               strncpy_s(ipc_data.parameter, 4096, message, _TRUNCATE);
        }
 
        if(g_lamexp_ipc_ptr.semaphore_write->acquire())
        {
-               memcpy(g_lamexp_ipc_ptr.sharedmem->data(), lamexp_ipc, sizeof(lamexp_ipc_t));
-               g_lamexp_ipc_ptr.semaphore_read->release();
+               if(g_lamexp_ipc_ptr.semaphore_write_mutex->acquire())
+               {
+                       lamexp_ipc_t *ptr = reinterpret_cast<lamexp_ipc_t*>(g_lamexp_ipc_ptr.sharedmem->data());
+                       memcpy(&ptr->data[ptr->pos_write], &ipc_data, sizeof(lamexp_ipc_data_t));
+                       ptr->pos_write = (ptr->pos_write + 1) % g_lamexp_ipc_slots;
+                       g_lamexp_ipc_ptr.semaphore_read->release();
+                       g_lamexp_ipc_ptr.semaphore_write_mutex->release();
+               }
        }
-
-       LAMEXP_DELETE(lamexp_ipc);
 }
 
 /*
@@ -995,31 +1278,35 @@ void lamexp_ipc_read(unsigned int *command, char* message, size_t buffSize)
        *command = 0;
        message[0] = '\0';
        
-       if(!g_lamexp_ipc_ptr.sharedmem || !g_lamexp_ipc_ptr.semaphore_read || !g_lamexp_ipc_ptr.semaphore_write)
+       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)
        {
                throw "Shared memory for IPC not initialized yet.";
        }
 
-       lamexp_ipc_t *lamexp_ipc = new lamexp_ipc_t;
-       memset(lamexp_ipc, 0, sizeof(lamexp_ipc_t));
+       lamexp_ipc_data_t ipc_data;
+       memset(&ipc_data, 0, sizeof(lamexp_ipc_data_t));
 
        if(g_lamexp_ipc_ptr.semaphore_read->acquire())
        {
-               memcpy(lamexp_ipc, g_lamexp_ipc_ptr.sharedmem->data(), sizeof(lamexp_ipc_t));
-               g_lamexp_ipc_ptr.semaphore_write->release();
-
-               if(!(lamexp_ipc->reserved_1 || lamexp_ipc->reserved_2))
+               if(g_lamexp_ipc_ptr.semaphore_read_mutex->acquire())
                {
-                       *command = lamexp_ipc->command;
-                       strncpy_s(message, buffSize, lamexp_ipc->parameter, _TRUNCATE);
-               }
-               else
-               {
-                       qWarning("Malformed IPC message, will be ignored");
+                       lamexp_ipc_t *ptr = reinterpret_cast<lamexp_ipc_t*>(g_lamexp_ipc_ptr.sharedmem->data());
+                       memcpy(&ipc_data, &ptr->data[ptr->pos_read], sizeof(lamexp_ipc_data_t));
+                       ptr->pos_read = (ptr->pos_read + 1) % g_lamexp_ipc_slots;
+                       g_lamexp_ipc_ptr.semaphore_write->release();
+                       g_lamexp_ipc_ptr.semaphore_read_mutex->release();
+
+                       if(!(ipc_data.reserved_1 || ipc_data.reserved_2))
+                       {
+                               *command = ipc_data.command;
+                               strncpy_s(message, buffSize, ipc_data.parameter, _TRUNCATE);
+                       }
+                       else
+                       {
+                               qWarning("Malformed IPC message, will be ignored");
+                       }
                }
        }
-
-       LAMEXP_DELETE(lamexp_ipc);
 }
 
 /*
@@ -1374,15 +1661,17 @@ QString lamexp_known_folder(lamexp_known_folder_t folder_id)
        static const GUID GUID_PROGRAM_FILES = {0x905e63b6,0xc1bf,0x494e,{0xb2,0x9c,0x65,0xb7,0x32,0xd3,0xd2,0x1a}};
        static const GUID GUID_SYSTEM_FOLDER = {0x1AC14E77,0x02E7,0x4E5D,{0xB7,0x44,0x2E,0xB1,0xAE,0x51,0x98,0xB7}};
 
-       static QLibrary *Kernel32Lib = NULL;
        static SHGetKnownFolderPathFun SHGetKnownFolderPathPtr = NULL;
        static SHGetFolderPathFun SHGetFolderPathPtr = NULL;
 
        if((!SHGetKnownFolderPathPtr) && (!SHGetFolderPathPtr))
        {
-               if(!Kernel32Lib) Kernel32Lib = new QLibrary("shell32.dll");
-               SHGetKnownFolderPathPtr = (SHGetKnownFolderPathFun) Kernel32Lib->resolve("SHGetKnownFolderPath");
-               SHGetFolderPathPtr = (SHGetFolderPathFun) Kernel32Lib->resolve("SHGetFolderPathW");
+               QLibrary kernel32Lib("shell32.dll");
+               if(kernel32Lib.load())
+               {
+                       SHGetKnownFolderPathPtr = (SHGetKnownFolderPathFun) kernel32Lib.resolve("SHGetKnownFolderPath");
+                       SHGetFolderPathPtr = (SHGetFolderPathFun) kernel32Lib.resolve("SHGetFolderPathW");
+               }
        }
 
        int folderCSIDL = -1;
@@ -1488,17 +1777,26 @@ bool lamexp_themes_enabled(void)
 {
        typedef int (WINAPI *IsAppThemedFun)(void);
        
-       bool isAppThemed = false;
-       QLibrary uxTheme(QString("%1/UxTheme.dll").arg(lamexp_known_folder(lamexp_folder_systemfolder)));
-       IsAppThemedFun IsAppThemedPtr = (IsAppThemedFun) uxTheme.resolve("IsAppThemed");
+       static bool isAppThemed = false;
+       static bool isAppThemed_initialized = false;
 
-       if(IsAppThemedPtr)
+       if(!isAppThemed_initialized)
        {
-               isAppThemed = IsAppThemedPtr();
-               if(!isAppThemed)
+               IsAppThemedFun IsAppThemedPtr = NULL;
+               QLibrary uxTheme(QString("%1/UxTheme.dll").arg(lamexp_known_folder(lamexp_folder_systemfolder)));
+               if(uxTheme.load())
                {
-                       qWarning("Theme support is disabled for this process!");
+                       IsAppThemedPtr = (IsAppThemedFun) uxTheme.resolve("IsAppThemed");
                }
+               if(IsAppThemedPtr)
+               {
+                       isAppThemed = IsAppThemedPtr();
+                       if(!isAppThemed)
+                       {
+                               qWarning("Theme support is disabled for this process!");
+                       }
+               }
+               isAppThemed_initialized = true;
        }
 
        return isAppThemed;
@@ -1694,6 +1992,8 @@ QStringList lamexp_available_codepages(bool noAliases)
  */
 void lamexp_finalization(void)
 {
+       qDebug("lamexp_finalization()");
+       
        //Free all tools
        if(!g_lamexp_tool_registry.isEmpty())
        {
@@ -1738,6 +2038,30 @@ void lamexp_finalization(void)
        LAMEXP_DELETE(g_lamexp_ipc_ptr.sharedmem);
        LAMEXP_DELETE(g_lamexp_ipc_ptr.semaphore_read);
        LAMEXP_DELETE(g_lamexp_ipc_ptr.semaphore_write);
+       LAMEXP_DELETE(g_lamexp_ipc_ptr.semaphore_read_mutex);
+       LAMEXP_DELETE(g_lamexp_ipc_ptr.semaphore_write_mutex);
+
+       //Free STDOUT and STDERR buffers
+       if(g_lamexp_console_attached)
+       {
+               if(std::filebuf *tmp = dynamic_cast<std::filebuf*>(std::cout.rdbuf()))
+               {
+                       std::cout.rdbuf(NULL);
+                       LAMEXP_DELETE(tmp);
+               }
+               if(std::filebuf *tmp = dynamic_cast<std::filebuf*>(std::cerr.rdbuf()))
+               {
+                       std::cerr.rdbuf(NULL);
+                       LAMEXP_DELETE(tmp);
+               }
+       }
+
+       //Close log file
+       if(g_lamexp_log_file)
+       {
+               fclose(g_lamexp_log_file);
+               g_lamexp_log_file = NULL;
+       }
 }
 
 /*