OSDN Git Service

Some clean-up and simplification for JobObject class.
[mutilities/MUtilities.git] / src / Startup.cpp
1 ///////////////////////////////////////////////////////////////////////////////
2 // MuldeR's Utilities for Qt
3 // Copyright (C) 2004-2016 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.
14 //
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
18 //
19 // http://www.gnu.org/licenses/lgpl-2.1.txt
20 //////////////////////////////////////////////////////////////////////////////////
21
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/Registry.h>
28 #include <MUtils/Exception.h>
29
30 //Qt
31 #include <QApplication>
32 #include <QMutex>
33 #include <QStringList>
34 #include <QLibraryInfo>
35 #include <QTextCodec>
36 #include <QImageReader>
37 #include <QFont>
38 #include <QMessageBox>
39 #include <QtPlugin>
40
41 //CRT
42 #include <string.h>
43
44 ///////////////////////////////////////////////////////////////////////////////
45 // Qt Static Initialization
46 ///////////////////////////////////////////////////////////////////////////////
47
48 #ifdef QT_NODLL
49
50 #if QT_VERSION < QT_VERSION_CHECK(5,0,0)
51 Q_IMPORT_PLUGIN(qico)
52 Q_IMPORT_PLUGIN(qsvg)
53 #else
54 Q_IMPORT_PLUGIN(QWindowsIntegrationPlugin)
55 Q_IMPORT_PLUGIN(QICOPlugin)
56 #endif
57
58 static void doInitializeResources(void)
59 {
60         Q_INIT_RESOURCE(MUtilsData);
61 }
62
63 static void doCleanupResources(void)
64 {
65         Q_CLEANUP_RESOURCE(MUtilsData);
66 }
67
68 namespace MUtils
69 {
70         namespace Startup
71         {
72                 namespace Internal
73                 {
74                         class ResourceInitializer
75                         {
76                         public:
77                                 ResourceInitializer(void)
78                                 {
79                                         doInitializeResources();
80                                 }
81
82                                 ~ResourceInitializer(void)
83                                 {
84                                         doCleanupResources();
85                                 }
86                         };
87
88                         static ResourceInitializer resourceInitializer;
89                 }
90         }
91 }
92
93 #endif //QT_NODLL
94
95 ///////////////////////////////////////////////////////////////////////////////
96 // MESSAGE HANDLER
97 ///////////////////////////////////////////////////////////////////////////////
98
99 static void qt_message_handler(QtMsgType type, const char *const msg)
100 {
101         if((!msg) || (!(msg[0])))
102         {
103                 return;
104         }
105
106         MUtils::Terminal::write(type, msg);
107
108         if((type == QtCriticalMsg) || (type == QtFatalMsg))
109         {
110                 MUtils::OS::fatal_exit(MUTILS_WCHR(QString::fromUtf8(msg)));
111         }
112 }
113
114 static bool qt_event_filter(void *message, long *result)
115 {
116         return MUtils::OS::handle_os_message(message, result);
117 }
118
119 ///////////////////////////////////////////////////////////////////////////////
120 // STARTUP FUNCTION
121 ///////////////////////////////////////////////////////////////////////////////
122
123 static int startup_main(int &argc, char **argv, MUtils::Startup::main_function_t *const entry_point, const char* const appName, const bool &debugConsole)
124 {
125         qInstallMsgHandler(qt_message_handler);
126         MUtils::Terminal::setup(argc, argv, appName, MUTILS_DEBUG || debugConsole);
127         return entry_point(argc, argv);
128 }
129
130 static int startup_helper(int &argc, char **argv, MUtils::Startup::main_function_t *const entry_point, const char* const appName, const bool &debugConsole)
131 {
132         int iResult = -1;
133         try
134         {
135                 iResult = startup_main(argc, argv, entry_point, appName, debugConsole);
136         }
137         catch(const std::exception &error)
138         {
139                 MUTILS_PRINT_ERROR("\nGURU MEDITATION !!!\n\nException error:\n%s\n", error.what());
140                 MUtils::OS::fatal_exit(L"Unhandeled C++ exception error, application will exit!");
141         }
142         catch(...)
143         {
144                 MUTILS_PRINT_ERROR("\nGURU MEDITATION !!!\n\nUnknown exception error!\n");
145                 MUtils::OS::fatal_exit(L"Unhandeled C++ exception error, application will exit!");
146         }
147         return iResult;
148 }
149
150 int MUtils::Startup::startup(int &argc, char **argv, main_function_t *const entry_point, const char* const appName, const bool &debugConsole)
151 {
152         int iResult = -1;
153 #if (MUTILS_DEBUG)
154 #ifdef _MSC_VER
155         _CrtSetDbgFlag(_CRTDBG_CHECK_ALWAYS_DF || _CrtSetDbgFlag(_CRTDBG_REPORT_FLAG));
156 #endif //_MSCVER
157         iResult = startup_main(argc, argv, entry_point, appName, debugConsole);
158 #else //MUTILS_DEBUG
159 #ifdef _MSC_VER
160         __try
161         {
162                 MUtils::ErrorHandler::initialize();
163                 MUtils::OS::check_debugger();
164                 iResult = startup_helper(argc, argv, entry_point, appName, debugConsole);
165         }
166         __except(1)
167         {
168                 MUTILS_PRINT_ERROR("\nGURU MEDITATION !!!\n\nUnhandeled structured exception error!\n");
169                 MUtils::OS::fatal_exit(L"Unhandeled structured exception error, application will exit!");
170         }
171 #else //_MSCVER
172         MUtils::ErrorHandler::initialize();
173         MUtils::OS::check_debugger();
174         iResult = startup_helper(argc, argv, entry_point, appName, debugConsole);
175 #endif //_MSCVER
176 #endif //MUTILS_DEBUG
177         return iResult;
178 }
179
180 ///////////////////////////////////////////////////////////////////////////////
181 // QT INITIALIZATION
182 ///////////////////////////////////////////////////////////////////////////////
183
184 static QMutex g_init_lock;
185 static const char *const g_imageformats[] = {"bmp", "png", "jpg", "gif", "ico", "xpm", "svg", NULL};
186
187 static QString getExecutableName(int &argc, char **argv)
188 {
189         if(argc >= 1)
190         {
191                 const char *argv0 = argv[0];
192                 for (int i = 0; i < 2; i++)
193                 {
194                         static const char SEP[2] = { '/', '\\' };
195                         if (const char *const ptr = strrchr(argv0, SEP[i]))
196                         {
197                                 argv0 = ptr + 1;
198                         }
199                 }
200                 if(strlen(argv0) > 1)
201                 {
202                         return QString::fromLatin1(argv0);
203                 }
204         }
205         return QLatin1String("Program.exe");
206 }
207
208 static void qt_registry_cleanup(void)
209 {
210         static const wchar_t *const QT_JUNK_KEY = L"Software\\Trolltech\\OrganizationDefaults";
211         MUtils::Registry::reg_key_delete(MUtils::Registry::root_user, MUTILS_QSTR(QT_JUNK_KEY), true, true);
212 }
213
214 QApplication *MUtils::Startup::create_qt(int &argc, char **argv, const QString &appName)
215 {
216         QMutexLocker lock(&g_init_lock);
217         const OS::ArgumentMap &arguments = MUtils::OS::arguments();
218
219         //Don't initialized again, if done already
220         if(QApplication::instance() != NULL)
221         {
222                 qWarning("Qt is already initialized!");
223                 return NULL;
224         }
225
226         //Extract executable name from argv[] array
227         const QString executableName = getExecutableName(argc, argv);
228
229         //Check Qt version
230 #ifdef QT_BUILD_KEY
231         qDebug("Using Qt v%s [%s], %s, %s", qVersion(), QLibraryInfo::buildDate().toString(Qt::ISODate).toLatin1().constData(), (qSharedBuild() ? "DLL" : "Static"), QLibraryInfo::buildKey().toLatin1().constData());
232         qDebug("Compiled with Qt v%s [%s], %s\n", QT_VERSION_STR, QT_PACKAGEDATE_STR, QT_BUILD_KEY);
233         if(_stricmp(qVersion(), QT_VERSION_STR))
234         {
235                 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());
236                 return false;
237         }
238         if(QLibraryInfo::buildKey().compare(QString::fromLatin1(QT_BUILD_KEY), Qt::CaseInsensitive))
239         {
240                 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());
241                 return false;
242         }
243 #else
244         qDebug("Using Qt v%s [%s], %s", qVersion(), QLibraryInfo::buildDate().toString(Qt::ISODate).toLatin1().constData(), (qSharedBuild() ? "DLL" : "Static"));
245         qDebug("Compiled with Qt v%s [%s]\n", QT_VERSION_STR, QT_PACKAGEDATE_STR);
246 #endif
247
248         //Check the Windows version
249         const MUtils::OS::Version::os_version_t &osVersion = MUtils::OS::os_version();
250         if((osVersion.type != MUtils::OS::Version::OS_WINDOWS) || (osVersion < MUtils::OS::Version::WINDOWS_WINXP))
251         {
252                 qFatal("%s", QApplication::tr("Executable '%1' requires Windows XP or later.").arg(executableName).toLatin1().constData());
253         }
254
255         //Check whether we are running on a supported Windows version
256         if(const char *const friendlyName = MUtils::OS::os_friendly_name(osVersion))
257         {
258                 qDebug("Running on %s (NT v%u.%u.%u).\n", friendlyName, osVersion.versionMajor, osVersion.versionMinor, osVersion.versionBuild);
259         }
260         else
261         {
262                 const QString message = QString().sprintf("Running on an unknown WindowsNT-based system (v%u.%u.%u).", osVersion.versionMajor, osVersion.versionMinor, osVersion.versionBuild);
263                 qWarning("%s\n", MUTILS_UTF8(message));
264                 MUtils::OS::system_message_wrn(MUTILS_WCHR(executableName), MUTILS_WCHR(message));
265         }
266
267         //Check for compat mode
268         if(osVersion.overrideFlag && (osVersion <= MUtils::OS::Version::WINDOWS_WN100))
269         {
270                 qWarning("Windows compatibility mode detected!");
271                 if(!arguments.contains("ignore-compat-mode"))
272                 {
273                         qFatal("%s", QApplication::tr("Executable '%1' doesn't support Windows compatibility mode.").arg(executableName).toLatin1().constData());
274                         return NULL;
275                 }
276         }
277
278         //Check for Wine
279         if(MUtils::OS::running_on_wine())
280         {
281                 qWarning("It appears we are running under Wine, unexpected things might happen!\n");
282         }
283
284         //Set text Codec for locale
285         QTextCodec::setCodecForLocale(QTextCodec::codecForName("UTF-8"));
286
287         //Create Qt application instance
288         QApplication *application = new QApplication(argc, argv);
289
290         //Register the Qt clean-up function
291         atexit(qt_registry_cleanup);
292
293         //Load plugins from application directory
294         QCoreApplication::setLibraryPaths(QStringList() << QApplication::applicationDirPath());
295         qDebug("Library Path:\n%s\n", MUTILS_UTF8(QApplication::libraryPaths().first()));
296
297         //Set application properties
298         application->setApplicationName(appName);
299         application->setOrganizationName("LoRd_MuldeR");
300         application->setOrganizationDomain("mulder.at.gg");
301         application->setEventFilter(qt_event_filter);
302
303         //Check for supported image formats
304         QList<QByteArray> supportedFormats = QImageReader::supportedImageFormats();
305         for(int i = 0; g_imageformats[i]; i++)
306         {
307                 if(!supportedFormats.contains(g_imageformats[i]))
308                 {
309                         qFatal("Qt initialization error: QImageIOHandler for '%s' missing!", g_imageformats[i]);
310                         MUTILS_DELETE(application);
311                         return NULL;
312                 }
313         }
314         
315         //Setup console icon
316         MUtils::Terminal::set_icon(QIcon(":/mutils/icons/bug.png"));
317
318         //Enable larger/smaller font size
319         double fontScaleFactor = 1.0;
320         if(arguments.contains("huge-font" )) fontScaleFactor = 1.500;
321         if(arguments.contains("big-font"  )) fontScaleFactor = 1.250;
322         if(arguments.contains("small-font")) fontScaleFactor = 0.875;
323         if(arguments.contains("tiny-font" )) fontScaleFactor = 0.750;
324         if(!qFuzzyCompare(fontScaleFactor, 1.0))
325         {
326                 qWarning("Application font scale factor set to: %.3f\n", fontScaleFactor);
327                 QFont appFont = application->font();
328                 appFont.setPointSizeF(appFont.pointSizeF() * fontScaleFactor);
329                 application->setFont(appFont);
330         }
331
332         //Check for process elevation
333         if(MUtils::OS::is_elevated() && (!MUtils::OS::running_on_wine()))
334         {
335                 QMessageBox messageBox(QMessageBox::Warning, executableName, "<nobr>This program was started with 'elevated' rights, altough it 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);
336                 messageBox.addButton("Quit Program (Recommended)", QMessageBox::NoRole);
337                 messageBox.addButton("Ignore", QMessageBox::NoRole);
338                 if(messageBox.exec() == 0)
339                 {
340                         MUTILS_DELETE(application);
341                         return NULL;
342                 }
343         }
344
345         //Qt created successfully
346         return application;
347 }
348
349 ///////////////////////////////////////////////////////////////////////////////
350