OSDN Git Service

Happy new year 2016!
[lamexp/LameXP.git] / src / Main.cpp
index c7c4fd8..c604a35 100644 (file)
@@ -1,11 +1,12 @@
 ///////////////////////////////////////////////////////////////////////////////
 // LameXP - Audio Encoder Front-End
-// Copyright (C) 2004-2011 LoRd_MuldeR <MuldeR2@GMX.de>
+// Copyright (C) 2004-2016 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
 // the Free Software Foundation; either version 2 of the License, or
-// (at your option) any later version.
+// (at your option) any later version, but always including the *additional*
+// restrictions defined in the "License.txt" file.
 //
 // This program is distributed in the hope that it will be useful,
 // but WITHOUT ANY WARRANTY; without even the implied warranty of
 #include "Model_FileList.h"
 #include "Model_AudioFile.h"
 #include "Encoder_Abstract.h"
-#include "WinSevenTaskbar.h"
+#include "ShellIntegration.h"
+
+//MUitls
+#include <MUtils/Global.h>
+#include <MUtils/OSSupport.h>
+#include <MUtils/Version.h>
+#include <MUtils/CPUFeatures.h>
+#include <MUtils/Terminal.h>
+#include <MUtils/Startup.h>
+#include <MUtils/IPCChannel.h>
 
 //Qt includes
+#include <QMutex>
 #include <QApplication>
 #include <QMessageBox>
 #include <QDate>
-#include <QMutex>
 #include <QDir>
-#include <QInputDialog>
+
+//VLD
+#ifdef _MSC_VER
+#include <vld.h>
+#endif
 
 ///////////////////////////////////////////////////////////////////////////////
-// Main function
+// Helper functions
 ///////////////////////////////////////////////////////////////////////////////
 
-static int lamexp_main(int argc, char* argv[])
+static void lamexp_print_logo(void)
 {
-       int iResult = -1;
-       int iShutdown = shutdownFlag_None;
-       bool bAccepted = true;
-       
-       //Init console
-       lamexp_init_console(argc, argv);
-
        //Print version info
        qDebug("LameXP - Audio Encoder Front-End v%d.%02d %s (Build #%03d)", lamexp_version_major(), lamexp_version_minor(), lamexp_version_release(), lamexp_version_build());
-       qDebug("Copyright (c) 2004-%04d LoRd_MuldeR <mulder2@gmx.de>. Some rights reserved.", qMax(lamexp_version_date().year(),QDate::currentDate().year()));
-       qDebug("Built on %s at %s with %s for Win-%s.\n", lamexp_version_date().toString(Qt::ISODate).toLatin1().constData(), lamexp_version_time(), lamexp_version_compiler(), lamexp_version_arch());
+       qDebug("Copyright (c) 2004-%04d LoRd_MuldeR <mulder2@gmx.de>. Some rights reserved.", qMax(MUtils::Version::app_build_date().year(), MUtils::OS::current_date().year()));
+       qDebug("Built on %s at %s with %s for Win-%s.\n", MUTILS_UTF8(MUtils::Version::app_build_date().toString(Qt::ISODate)), MUTILS_UTF8(MUtils::Version::app_build_time().toString(Qt::ISODate)), MUtils::Version::compiler_version(), MUtils::Version::compiler_arch());
        
        //print license info
        qDebug("This program is free software: you can redistribute it and/or modify");
        qDebug("it under the terms of the GNU General Public License <http://www.gnu.org/>.");
        qDebug("Note that this program is distributed with ABSOLUTELY NO WARRANTY.\n");
 
+       //Print library version
+       qDebug("This application is powerd by MUtils library v%u.%02u (%s, %s).\n", MUtils::Version::lib_version_major(), MUtils::Version::lib_version_minor(), MUTILS_UTF8(MUtils::Version::lib_build_date().toString(Qt::ISODate)), MUTILS_UTF8(MUtils::Version::lib_build_time().toString(Qt::ISODate)));
+       
        //Print warning, if this is a "debug" build
-       if(LAMEXP_DEBUG)
+       if(MUTILS_DEBUG)
        {
                qWarning("---------------------------------------------------------");
                qWarning("DEBUG BUILD: DO NOT RELEASE THIS BINARY TO THE PUBLIC !!!");
-               qWarning("---------------------------------------------------------\n"); 
-       }
-       
-       //Detect CPU capabilities
-       lamexp_cpu_t cpuFeatures = lamexp_detect_cpu_features(argc, argv);
-       qDebug("   CPU vendor id  :  %s (Intel: %s)", cpuFeatures.vendor, LAMEXP_BOOL(cpuFeatures.intel));
-       qDebug("CPU brand string  :  %s", cpuFeatures.brand);
-       qDebug("   CPU signature  :  Family: %d, Model: %d, Stepping: %d", cpuFeatures.family, cpuFeatures.model, cpuFeatures.stepping);
-       qDebug("CPU capabilities  :  MMX: %s, SSE: %s, SSE2: %s, SSE3: %s, SSSE3: %s, x64: %s", LAMEXP_BOOL(cpuFeatures.mmx), LAMEXP_BOOL(cpuFeatures.sse), LAMEXP_BOOL(cpuFeatures.sse2), LAMEXP_BOOL(cpuFeatures.sse3), LAMEXP_BOOL(cpuFeatures.ssse3), LAMEXP_BOOL(cpuFeatures.x64));
-       qDebug(" Number of CPU's  :  %d\n", cpuFeatures.count);
-       
-       //Initialize Qt
-       if(!lamexp_init_qt(argc, argv))
-       {
-               return -1;
+               qWarning("---------------------------------------------------------\n");
        }
+}
 
-       //Check for expiration
-       if(lamexp_version_demo())
-       {
-               qWarning(QString("Note: This demo (pre-release) version of LameXP will expire at %1.\n").arg(lamexp_version_expires().toString(Qt::ISODate)).toLatin1().constData());
-       }
+static int lamexp_initialize_ipc(MUtils::IPCChannel *const ipcChannel)
+{
+       int iResult = 0;
 
-       //Check for multiple instances of LameXP
-       if((iResult = lamexp_init_ipc()) != 0)
+       if((iResult = ipcChannel->initialize()) != MUtils::IPCChannel::RET_SUCCESS_MASTER)
        {
-               qDebug("LameXP is already running, connecting to running instance...");
-               if(iResult == 1)
+               if(iResult == MUtils::IPCChannel::RET_SUCCESS_SLAVE)
                {
-                       MessageProducerThread *messageProducerThread = new MessageProducerThread();
+                       qDebug("LameXP is already running, connecting to running instance...");
+                       QScopedPointer<MessageProducerThread> messageProducerThread(new MessageProducerThread(ipcChannel));
                        messageProducerThread->start();
                        if(!messageProducerThread->wait(30000))
                        {
+                               qWarning("MessageProducer thread has encountered timeout -> going to kill!");
                                messageProducerThread->terminate();
-                               QMessageBox messageBox(QMessageBox::Critical, "LameXP", "LameXP is already running, but the running instance doesn't respond!", QMessageBox::NoButton, NULL, Qt::Dialog | Qt::MSWindowsFixedSizeDialogHint | Qt::WindowStaysOnTopHint);
-                               messageBox.exec();
                                messageProducerThread->wait();
-                               LAMEXP_DELETE(messageProducerThread);
+                               MUtils::OS::system_message_err(L"LameXP", L"LameXP is already running, but the running instance doesn't respond!");
                                return -1;
                        }
-                       LAMEXP_DELETE(messageProducerThread);
+                       return 0;
                }
-               return 0;
-       }
-
-       //Kill application?
-       for(int i = 0; i < argc; i++)
-       {
-               if(!_stricmp("--kill", argv[i]) || !_stricmp("--force-kill", argv[i]))
+               else
                {
-                       return 0;
+                       qFatal("The IPC initialization has failed!");
+                       return -1;
                }
        }
-       
-       //Self-test
-       if(LAMEXP_DEBUG)
-       {
-               InitializationThread::selfTest();
-       }
 
-       //Taskbar init
-       WinSevenTaskbar::init();
+       return 1;
+}
+
+static void lamexp_show_splash(const MUtils::CPUFetaures::cpu_info_t &cpuFeatures, SettingsModel *const settingsModel)
+{
+       QScopedPointer<InitializationThread> poInitializationThread(new InitializationThread(cpuFeatures));
+       SplashScreen::showSplash(poInitializationThread.data());
+       settingsModel->slowStartup(poInitializationThread->getSlowIndicator());
+}
+
+static int lamexp_main_loop(const MUtils::CPUFetaures::cpu_info_t &cpuFeatures, MUtils::IPCChannel *const ipcChannel, int &iShutdown)
+{
+       int iResult = -1;
+       bool bAccepted = true;
 
        //Create models
-       FileListModel *fileListModel = new FileListModel();
-       AudioFileModel *metaInfo = new AudioFileModel();
-       SettingsModel *settingsModel = new SettingsModel();
-       
+       QScopedPointer<FileListModel>           fileListModel(new FileListModel()          );
+       QScopedPointer<AudioFileModel_MetaInfo> metaInfo     (new AudioFileModel_MetaInfo());
+       QScopedPointer<SettingsModel>           settingsModel(new SettingsModel()          );
+
        //Show splash screen
-       InitializationThread *poInitializationThread = new InitializationThread(&cpuFeatures);
-       SplashScreen::showSplash(poInitializationThread);
-       settingsModel->slowStartup(poInitializationThread->getSlowIndicator());
-       LAMEXP_DELETE(poInitializationThread);
+       lamexp_show_splash(cpuFeatures, settingsModel.data());
 
        //Validate settings
        settingsModel->validate();
 
        //Create main window
-       MainWindow *poMainWindow = new MainWindow(fileListModel, metaInfo, settingsModel);
-       
+       QScopedPointer<MainWindow> poMainWindow(new MainWindow(ipcChannel, fileListModel.data(), metaInfo.data(), settingsModel.data()));
+
        //Main application loop
-       while(bAccepted && (iShutdown <= shutdownFlag_None))
+       while(bAccepted && (iShutdown <= SHUTDOWN_FLAG_NONE))
        {
                //Show main window
                poMainWindow->show();
-               iResult = QApplication::instance()->exec();
+               iResult = qApp->exec();
                bAccepted = poMainWindow->isAccepted();
 
+               //Sync settings
+               settingsModel->syncNow();
+
                //Show processing dialog
-               if(bAccepted && fileListModel->rowCount() > 0)
+               if(bAccepted && (fileListModel->rowCount() > 0))
                {
-                       ProcessingDialog *processingDialog = new ProcessingDialog(fileListModel, metaInfo, settingsModel);
+                       ProcessingDialog *processingDialog = new ProcessingDialog(fileListModel.data(), metaInfo.data(), settingsModel.data());
                        processingDialog->exec();
                        iShutdown = processingDialog->getShutdownFlag();
-                       LAMEXP_DELETE(processingDialog);
+                       MUTILS_DELETE(processingDialog);
                }
        }
-       
-       //Free models
-       LAMEXP_DELETE(poMainWindow);
-       LAMEXP_DELETE(fileListModel);
-       LAMEXP_DELETE(metaInfo);
-       LAMEXP_DELETE(settingsModel);
 
-       //Taskbar un-init
-       WinSevenTaskbar::uninit();
+       return iResult;
+}
 
-       //Final clean-up
-       qDebug("Shutting down, please wait...\n");
+///////////////////////////////////////////////////////////////////////////////
+// Main function
+///////////////////////////////////////////////////////////////////////////////
 
-       //Shotdown computer
-       if(iShutdown > shutdownFlag_None)
+static int lamexp_main(int &argc, char **argv)
+{
+       int iResult = -1;
+       int iShutdown = SHUTDOWN_FLAG_NONE;
+
+       //Print logo
+       lamexp_print_logo();
+
+       //Get CLI arguments
+       const MUtils::OS::ArgumentMap &arguments = MUtils::OS::arguments();
+
+       //Enumerate CLI arguments
+       if(!arguments.isEmpty())
        {
-               if(!lamexp_shutdown_computer(QApplication::applicationFilePath(), 12, true, (iShutdown == shutdownFlag_Hibernate)))
+               qDebug("Command-Line Arguments:");
+               foreach(const QString &key, arguments.uniqueKeys())
                {
-                       QMessageBox messageBox(QMessageBox::Critical, "LameXP", "Sorry, LameXP was unable to shutdown your computer!", QMessageBox::NoButton, NULL, Qt::Dialog | Qt::MSWindowsFixedSizeDialogHint | Qt::WindowStaysOnTopHint);
+                       foreach(const QString &val, arguments.values(key))
+                       {
+                               if(!val.isEmpty())
+                               {
+                                       qDebug("--%s = \"%s\"", MUTILS_UTF8(key), MUTILS_UTF8(val));
+                                       continue;
+                               }
+                               qDebug("--%s", MUTILS_UTF8(key));
+                       }
                }
+               qDebug(" ");
        }
 
-       //Terminate
-       return iResult;
-}
+       //Uninstall?
+       if(arguments.contains("uninstall"))
+       {
+               qWarning("Un-install: Removing LameXP shell integration...");
+               ShellIntegration::remove(false);
+               return EXIT_SUCCESS;
+       }
 
-///////////////////////////////////////////////////////////////////////////////
-// Applicaton entry point
-///////////////////////////////////////////////////////////////////////////////
+       //Detect CPU capabilities
+       const MUtils::CPUFetaures::cpu_info_t cpuFeatures = MUtils::CPUFetaures::detect();
+       qDebug("   CPU vendor id  :  %s (Intel=%s)", cpuFeatures.vendor, MUTILS_BOOL2STR(cpuFeatures.intel));
+       qDebug("CPU brand string  :  %s", cpuFeatures.brand);
+       qDebug("   CPU signature  :  Family=%d Model=%d Stepping=%d", cpuFeatures.family, cpuFeatures.model, cpuFeatures.stepping);
+       qDebug("CPU capabilities  :  MMX=%s SSE=%s SSE2=%s SSE3=%s SSSE3=%s SSE4=%s SSE4.2=%s x64=%s", MUTILS_BOOL2STR(cpuFeatures.features & MUtils::CPUFetaures::FLAG_MMX), MUTILS_BOOL2STR(cpuFeatures.features & MUtils::CPUFetaures::FLAG_SSE), MUTILS_BOOL2STR(cpuFeatures.features & MUtils::CPUFetaures::FLAG_SSE2), MUTILS_BOOL2STR(cpuFeatures.features & MUtils::CPUFetaures::FLAG_SSE3), MUTILS_BOOL2STR(cpuFeatures.features & MUtils::CPUFetaures::FLAG_SSSE3), MUTILS_BOOL2STR(cpuFeatures.features & MUtils::CPUFetaures::FLAG_SSE4), MUTILS_BOOL2STR(cpuFeatures.features & MUtils::CPUFetaures::FLAG_SSE42), MUTILS_BOOL2STR(cpuFeatures.x64));
+       qDebug(" Number of CPU's  :  %d\n", cpuFeatures.count);
 
-static int _main(int argc, char* argv[])
-{
-       if(LAMEXP_DEBUG)
+       //Initialize Qt
+       QScopedPointer<QApplication> application(MUtils::Startup::create_qt(argc, argv, QLatin1String("LameXP - Audio Encoder Front-End")));
+       if(application.isNull())
        {
-               int iResult = -1;
-               qInstallMsgHandler(lamexp_message_handler);
-               LAMEXP_MEMORY_CHECK(iResult = lamexp_main(argc, argv));
-               lamexp_finalization();
-               return iResult;
+               return EXIT_FAILURE;
        }
-       else
+
+       //Initialize application
+       application->setWindowIcon(lamexp_app_icon());
+       application->setApplicationVersion(QString().sprintf("%d.%02d.%04d", lamexp_version_major(), lamexp_version_minor(), lamexp_version_build())); 
+
+       //Check for expiration
+       if(lamexp_version_demo())
        {
-               int iResult = -1;
-               try
+               const QDate currentDate = MUtils::OS::current_date();
+               if(currentDate.addDays(1) < MUtils::Version::app_build_date())
                {
-                       qInstallMsgHandler(lamexp_message_handler);
-                       iResult = lamexp_main(argc, argv);
-                       lamexp_finalization();
+                       qFatal("System's date (%s) is before LameXP build date (%s). Huh?", currentDate.toString(Qt::ISODate).toLatin1().constData(), MUtils::Version::app_build_date().toString(Qt::ISODate).toLatin1().constData());
                }
-               catch(char *error)
-               {
-                       fflush(stdout);
-                       fflush(stderr);
-                       fprintf(stderr, "\nGURU MEDITATION !!!\n\nException error message: %s\n", error);
-                       FatalAppExit(0, L"Unhandeled C++ exception error, application will exit!");
-                       TerminateProcess(GetCurrentProcess(), -1);
-               }
-               catch(int error)
-               {
-                       fflush(stdout);
-                       fflush(stderr);
-                       fprintf(stderr, "\nGURU MEDITATION !!!\n\nException error code: 0x%X\n", error);
-                       FatalAppExit(0, L"Unhandeled C++ exception error, application will exit!");
-                       TerminateProcess(GetCurrentProcess(), -1);
-               }
-               catch(...)
-               {
-                       fflush(stdout);
-                       fflush(stderr);
-                       fprintf(stderr, "\nGURU MEDITATION !!!\n");
-                       FatalAppExit(0, L"Unhandeled C++ exception error, application will exit!");
-                       TerminateProcess(GetCurrentProcess(), -1);
-               }
-               return iResult;
+               qWarning(QString("Note: This demo (pre-release) version of LameXP will expire at %1.\n").arg(lamexp_version_expires().toString(Qt::ISODate)).toLatin1().constData());
        }
-}
 
-int main(int argc, char* argv[])
-{
-       if(LAMEXP_DEBUG)
+       //Initialize IPC
+       QScopedPointer<MUtils::IPCChannel> ipcChannel(new MUtils::IPCChannel("lamexp-v4", lamexp_version_build(), "instance"));
+       if((iResult = lamexp_initialize_ipc(ipcChannel.data())) < 1)
        {
-               return _main(argc, argv);
+               return (iResult == 0) ? EXIT_SUCCESS : EXIT_FAILURE;
        }
-       else
+
+       //Kill application?
+       if(arguments.contains("kill") || arguments.contains("force-kill"))
        {
-               __try
-               {
-                       SetUnhandledExceptionFilter(lamexp_exception_handler);
-                       _set_invalid_parameter_handler(lamexp_invalid_param_handler);
-                       return _main(argc, argv);
-               }
-               __except(1)
+               return EXIT_SUCCESS;
+       }
+       
+       //Self-test
+       if(MUTILS_DEBUG)
+       {
+               InitializationThread::selfTest();
+       }
+
+       //Main application loop
+       iResult = lamexp_main_loop(cpuFeatures, ipcChannel.data(), iShutdown);
+
+       //Final clean-up
+       qDebug("Shutting down, please wait...\n");
+
+       //Shotdown computer
+       if(iShutdown > SHUTDOWN_FLAG_NONE)
+       {
+               if(!MUtils::OS::shutdown_computer(QApplication::applicationFilePath(), 12, true, (iShutdown == SHUTDOWN_FLAG_HIBERNATE)))
                {
-                       fflush(stdout);
-                       fflush(stderr);
-                       fprintf(stderr, "\nGURU MEDITATION !!!\n\nUnhandeled structured exception error! [code: 0x%X]\n", GetExceptionCode());
-                       FatalAppExit(0, L"Unhandeled structured exception error, application will exit!");
-                       TerminateProcess(GetCurrentProcess(), -1);
+                       QMessageBox messageBox(QMessageBox::Critical, "LameXP", "Sorry, LameXP was unable to shutdown your computer!", QMessageBox::NoButton, NULL, Qt::Dialog | Qt::MSWindowsFixedSizeDialogHint | Qt::WindowStaysOnTopHint);
                }
        }
+
+       //Terminate
+       return iResult;
 }
 
 ///////////////////////////////////////////////////////////////////////////////
-// CRT initialization
+// Applicaton entry point
 ///////////////////////////////////////////////////////////////////////////////
 
-extern "C"
+int main(int argc, char* argv[])
 {
-       int WinMainCRTStartup(void);
-
-       int lamexp_crt_startup(void)
-       {
-               return WinMainCRTStartup();
-       }
+       return MUtils::Startup::startup(argc, argv, lamexp_main, "LameXP", lamexp_version_demo());
 }