Refactored the terminal initialization code. Also, we will now properly shut down...
[MUtilities.git] / src / Startup.cpp
blobaaa82cdf65390d669cc968ec23b604b719ff5fb7
1 ///////////////////////////////////////////////////////////////////////////////
2 // MuldeR's Utilities for Qt
3 // Copyright (C) 2004-2014 LoRd_MuldeR <MuldeR2@GMX.de>
4 //
5 // This library is free software; you can redistribute it and/or
6 // modify it under the terms of the GNU Lesser General Public
7 // License as published by the Free Software Foundation; either
8 // version 2.1 of the License, or (at your option) any later version.
9 //
10 // This library 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 GNU
13 // Lesser General Public License for more details.
15 // You should have received a copy of the GNU Lesser General Public
16 // License along with this library; if not, write to the Free Software
17 // Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
19 // http://www.gnu.org/licenses/lgpl-2.1.txt
20 //////////////////////////////////////////////////////////////////////////////////
22 //MUtils
23 #include <MUtils/Startup.h>
24 #include <MUtils/OSSupport.h>
25 #include <MUtils/Terminal.h>
26 #include <MUtils/ErrorHandler.h>
27 #include <MUtils/Exception.h>
29 //Qt
30 #include <QApplication>
31 #include <QMutex>
32 #include <QStringList>
33 #include <QLibraryInfo>
34 #include <QTextCodec>
35 #include <QImageReader>
36 #include <QFont>
37 #include <QMessageBox>
39 ///////////////////////////////////////////////////////////////////////////////
40 // MESSAGE HANDLER
41 ///////////////////////////////////////////////////////////////////////////////
43 static void qt_message_handler(QtMsgType type, const char *msg)
45 if((!msg) || (!(msg[0])))
47 return;
50 MUtils::Terminal::write(type, msg);
52 if((type == QtCriticalMsg) || (type == QtFatalMsg))
54 MUtils::OS::fatal_exit(MUTILS_WCHR(QString::fromUtf8(msg)));
58 static bool qt_event_filter(void *message, long *result)
60 return MUtils::OS::handle_os_message(message, result);
63 ///////////////////////////////////////////////////////////////////////////////
64 // STARTUP FUNCTION
65 ///////////////////////////////////////////////////////////////////////////////
67 static int startup_main(int &argc, char **argv, MUtils::Startup::main_function_t *const entry_point, const char* const appName, const bool &debugConsole)
69 qInstallMsgHandler(qt_message_handler);
70 MUtils::Terminal::setup(argc, argv, appName, MUTILS_DEBUG || debugConsole);
71 return entry_point(argc, argv);
74 static int startup_helper(int &argc, char **argv, MUtils::Startup::main_function_t *const entry_point, const char* const appName, const bool &debugConsole)
76 int iResult = -1;
77 try
79 iResult = startup_main(argc, argv, entry_point, appName, debugConsole);
81 catch(const std::exception &error)
83 MUTILS_PRINT_ERROR("\nGURU MEDITATION !!!\n\nException error:\n%s\n", error.what());
84 MUtils::OS::fatal_exit(L"Unhandeled C++ exception error, application will exit!");
86 catch(...)
88 MUTILS_PRINT_ERROR("\nGURU MEDITATION !!!\n\nUnknown exception error!\n");
89 MUtils::OS::fatal_exit(L"Unhandeled C++ exception error, application will exit!");
91 return iResult;
94 int MUtils::Startup::startup(int &argc, char **argv, main_function_t *const entry_point, const char* const appName, const bool &debugConsole)
96 int iResult = -1;
97 #if (MUTILS_DEBUG)
98 #ifdef _MSC_VER
99 _CrtSetDbgFlag(_CRTDBG_CHECK_ALWAYS_DF || _CrtSetDbgFlag(_CRTDBG_REPORT_FLAG));
100 #endif //_MSCVER
101 iResult = startup_main(argc, argv, entry_point, appName, debugConsole);
102 #else //MUTILS_DEBUG
103 #ifdef _MSC_VER
104 __try
106 MUtils::ErrorHandler::initialize();
107 MUtils::OS::check_debugger();
108 iResult = startup_helper(argc, argv, entry_point, appName, debugConsole);
110 __except(1)
112 MUTILS_PRINT_ERROR("\nGURU MEDITATION !!!\n\nUnhandeled structured exception error!\n");
113 MUtils::OS::fatal_exit(L"Unhandeled structured exception error, application will exit!");
115 #else //_MSCVER
116 MUtils::ErrorHandler::initialize();
117 MUtils::OS::check_debugger();
118 iResult = startup_helper(argc, argv, entry_point, appName, debugConsole);
119 #endif //_MSCVER
120 #endif //MUTILS_DEBUG
121 return iResult;
124 ///////////////////////////////////////////////////////////////////////////////
125 // QT INITIALIZATION
126 ///////////////////////////////////////////////////////////////////////////////
128 static QMutex g_init_lock;
129 static const char *const g_imageformats[] = {"bmp", "png", "jpg", "gif", "ico", "xpm", "svg", NULL};
131 QApplication *MUtils::Startup::create_qt(int &argc, char **argv, const QString &appName)
133 QMutexLocker lock(&g_init_lock);
134 const QStringList &arguments = MUtils::OS::arguments();
136 //Don't initialized again, if done already
137 if(QApplication::instance() != NULL)
139 qWarning("Qt is already initialized!");
140 return NULL;
143 //Extract executable name from argv[] array
144 QString executableName = QLatin1String("LameXP.exe");
145 if(arguments.count() > 0)
147 static const char *delimiters = "\\/:?";
148 executableName = arguments[0].trimmed();
149 for(int i = 0; delimiters[i]; i++)
151 int temp = executableName.lastIndexOf(QChar(delimiters[i]));
152 if(temp >= 0) executableName = executableName.mid(temp + 1);
154 executableName = executableName.trimmed();
155 if(executableName.isEmpty())
157 executableName = QLatin1String("LameXP.exe");
161 //Check Qt version
162 #ifdef QT_BUILD_KEY
163 qDebug("Using Qt v%s [%s], %s, %s", qVersion(), QLibraryInfo::buildDate().toString(Qt::ISODate).toLatin1().constData(), (qSharedBuild() ? "DLL" : "Static"), QLibraryInfo::buildKey().toLatin1().constData());
164 qDebug("Compiled with Qt v%s [%s], %s\n", QT_VERSION_STR, QT_PACKAGEDATE_STR, QT_BUILD_KEY);
165 if(_stricmp(qVersion(), QT_VERSION_STR))
167 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());
168 return false;
170 if(QLibraryInfo::buildKey().compare(QString::fromLatin1(QT_BUILD_KEY), Qt::CaseInsensitive))
172 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());
173 return false;
175 #else
176 qDebug("Using Qt v%s [%s], %s", qVersion(), QLibraryInfo::buildDate().toString(Qt::ISODate).toLatin1().constData(), (qSharedBuild() ? "DLL" : "Static"));
177 qDebug("Compiled with Qt v%s [%s]\n", QT_VERSION_STR, QT_PACKAGEDATE_STR);
178 #endif
180 //Check the Windows version
182 const MUtils::OS::Version::os_version_t &osVersion = MUtils::OS::os_version();
183 if((osVersion.type != MUtils::OS::Version::OS_WINDOWS) || (osVersion < MUtils::OS::Version::WINDOWS_WINXP))
185 qFatal("%s", QApplication::tr("Executable '%1' requires Windows XP or later.").arg(executableName).toLatin1().constData());
188 //Check whether we are running on a supported Windows version
189 if(const char *const friendlyName = MUtils::OS::os_friendly_name(osVersion))
191 qDebug("Running on %s (NT v%u.%u).\n", friendlyName, osVersion.versionMajor, osVersion.versionMinor);
193 else
195 const QString message = QString().sprintf("Running on an unknown WindowsNT-based system (v%u.%u).", osVersion.versionMajor, osVersion.versionMinor);
196 qWarning("%s\n", MUTILS_UTF8(message));
197 MUtils::OS::system_message_wrn(MUTILS_WCHR(message), L"LameXP");
200 //Check for compat mode
201 if(osVersion.overrideFlag && (osVersion <= MUtils::OS::Version::WINDOWS_WN100))
203 qWarning("Windows compatibility mode detected!");
204 if(!arguments.contains("--ignore-compat-mode", Qt::CaseInsensitive))
206 qFatal("%s", QApplication::tr("Executable '%1' doesn't support Windows compatibility mode.").arg(executableName).toLatin1().constData());
207 return NULL;
211 //Check for Wine
212 if(MUtils::OS::running_on_wine())
214 qWarning("It appears we are running under Wine, unexpected things might happen!\n");
217 //Set text Codec for locale
218 QTextCodec::setCodecForLocale(QTextCodec::codecForName("UTF-8"));
220 //Create Qt application instance
221 QApplication *application = new QApplication(argc, argv);
223 //Load plugins from application directory
224 QCoreApplication::setLibraryPaths(QStringList() << QApplication::applicationDirPath());
225 qDebug("Library Path:\n%s\n", MUTILS_UTF8(QApplication::libraryPaths().first()));
227 //Set application properties
228 application->setApplicationName(appName);
229 application->setOrganizationName("LoRd_MuldeR");
230 application->setOrganizationDomain("mulder.at.gg");
231 application->setEventFilter(qt_event_filter);
233 //Check for supported image formats
234 QList<QByteArray> supportedFormats = QImageReader::supportedImageFormats();
235 for(int i = 0; g_imageformats[i]; i++)
237 if(!supportedFormats.contains(g_imageformats[i]))
239 qFatal("Qt initialization error: QImageIOHandler for '%s' missing!", g_imageformats[i]);
240 MUTILS_DELETE(application);
241 return NULL;
245 //Setup console icon
246 MUtils::Terminal::set_icon(QIcon(":/mutils/icons/bug.png"));
248 //Enable larger/smaller font size
249 double fontScaleFactor = 1.0;
250 if(arguments.contains("--huge-font", Qt::CaseInsensitive)) fontScaleFactor = 1.500;
251 if(arguments.contains("--big-font", Qt::CaseInsensitive)) fontScaleFactor = 1.250;
252 if(arguments.contains("--small-font", Qt::CaseInsensitive)) fontScaleFactor = 0.875;
253 if(arguments.contains("--tiny-font", Qt::CaseInsensitive)) fontScaleFactor = 0.750;
254 if(!qFuzzyCompare(fontScaleFactor, 1.0))
256 qWarning("Application font scale factor set to: %.3f\n", fontScaleFactor);
257 QFont appFont = application->font();
258 appFont.setPointSizeF(appFont.pointSizeF() * fontScaleFactor);
259 application->setFont(appFont);
262 //Check for process elevation
263 if(MUtils::OS::is_elevated() && (!MUtils::OS::running_on_wine()))
265 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);
266 messageBox.addButton("Quit Program (Recommended)", QMessageBox::NoRole);
267 messageBox.addButton("Ignore", QMessageBox::NoRole);
268 if(messageBox.exec() == 0)
270 MUTILS_DELETE(application);
271 return NULL;
275 //Qt created successfully
276 return application;
279 ///////////////////////////////////////////////////////////////////////////////