OSDN Git Service

Updated copyright year.
[mutilities/MUtilities.git] / src / Startup.cpp
1 ///////////////////////////////////////////////////////////////////////////////
2 // MuldeR's Utilities for Qt
3 // Copyright (C) 2004-2023 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 #if QT_VERSION >= QT_VERSION_CHECK(5,0,0)
41 #include <QAbstractNativeEventFilter>
42 #else
43 #define QAbstractNativeEventFilter QObject
44 #define Q_DECL_OVERRIDE
45 #endif
46
47 //CRT
48 #include <string.h>
49
50 //MSVC
51 #if defined(_MSC_VER)
52 #define FORCE_INLINE __forceinline
53 #else
54 #define FORCE_INLINE inline
55 #endif
56
57 ///////////////////////////////////////////////////////////////////////////////
58 // Qt Static Initialization
59 ///////////////////////////////////////////////////////////////////////////////
60
61 #ifdef QT_NODLL
62
63 #if QT_VERSION < QT_VERSION_CHECK(5,0,0)
64 Q_IMPORT_PLUGIN(qico)
65 Q_IMPORT_PLUGIN(qsvg)
66 #else
67 Q_IMPORT_PLUGIN(QWindowsIntegrationPlugin)
68 Q_IMPORT_PLUGIN(QICOPlugin)
69 #endif
70
71 static void doInitializeResources(void)
72 {
73         Q_INIT_RESOURCE(MUtilsData);
74 }
75
76 static void doCleanupResources(void)
77 {
78         Q_CLEANUP_RESOURCE(MUtilsData);
79 }
80
81 namespace MUtils
82 {
83         namespace Startup
84         {
85                 namespace Internal
86                 {
87                         class ResourceInitializer
88                         {
89                         public:
90                                 ResourceInitializer(void)
91                                 {
92                                         doInitializeResources();
93                                 }
94
95                                 ~ResourceInitializer(void)
96                                 {
97                                         doCleanupResources();
98                                 }
99                         };
100
101                         static ResourceInitializer resourceInitializer;
102                 }
103         }
104 }
105
106 #endif //QT_NODLL
107
108 ///////////////////////////////////////////////////////////////////////////////
109 // MESSAGE HANDLER
110 ///////////////////////////////////////////////////////////////////////////////
111
112 #if QT_VERSION < QT_VERSION_CHECK(5,0,0)
113 static void qt_message_handler(QtMsgType type, const char *const msg)
114 {
115         if (msg && msg[0])
116         {
117                 MUtils::Terminal::write(type, msg);
118                 if ((type == QtCriticalMsg) || (type == QtFatalMsg))
119                 {
120                         MUtils::OS::fatal_exit(MUTILS_WCHR(QString::fromUtf8(msg)));
121                 }
122         }
123 }
124 #else
125 #define qInstallMsgHandler(X) qInstallMessageHandler((X))
126 static void qt_message_handler(QtMsgType type, const QMessageLogContext&, const QString &msg)
127 {
128         if (!msg.isEmpty())
129         {
130                 MUtils::Terminal::write(type, msg.toUtf8().constData());
131                 if ((type == QtCriticalMsg) || (type == QtFatalMsg))
132                 {
133                         MUtils::OS::fatal_exit(MUTILS_WCHR(msg));
134                 }
135         }
136 }
137 #endif
138
139 ///////////////////////////////////////////////////////////////////////////////
140 // EVENT FILTER
141 ///////////////////////////////////////////////////////////////////////////////
142
143 namespace MUtils
144 {
145         namespace Startup
146         {
147                 namespace Internal
148                 {
149                         class NativeEventFilter : public QAbstractNativeEventFilter
150                         {
151                         public:
152                                 bool nativeEventFilter(const QByteArray&, void *message, long *result) Q_DECL_OVERRIDE
153                                 {
154                                         return filterEvent(message, result);
155                                 };
156
157                                 static FORCE_INLINE bool filterEvent(void *message, long *result)
158                                 {
159                                         return MUtils::OS::handle_os_message(message, result);
160                                 }
161
162                                 static NativeEventFilter *instance(void)
163                                 {
164                                         while (m_instance.isNull())
165                                         {
166                                                 m_instance.reset(new NativeEventFilter());
167                                         }
168                                         return m_instance.data();
169                                 }
170
171                         private:
172                                 NativeEventFilter(void) {}
173                                 static QScopedPointer<MUtils::Startup::Internal::NativeEventFilter> m_instance;
174                         };
175                 }
176         }
177 }
178
179 ///////////////////////////////////////////////////////////////////////////////
180 // STARTUP FUNCTION
181 ///////////////////////////////////////////////////////////////////////////////
182
183 static FORCE_INLINE int startup_main(int &argc, char **argv, MUtils::Startup::main_function_t *const entry_point, const char* const appName, const bool &debugConsole)
184 {
185         qInstallMsgHandler(qt_message_handler);
186         MUtils::Terminal::setup(argc, argv, appName, MUTILS_DEBUG || debugConsole);
187         return entry_point(argc, argv);
188 }
189
190 static FORCE_INLINE int startup_helper(int &argc, char **argv, MUtils::Startup::main_function_t *const entry_point, const char* const appName, const bool &debugConsole)
191 {
192         int iResult = -1;
193         try
194         {
195                 iResult = startup_main(argc, argv, entry_point, appName, debugConsole);
196         }
197         catch(const std::exception &error)
198         {
199                 MUTILS_PRINT_ERROR("\nGURU MEDITATION !!!\n\nException error:\n%s\n", error.what());
200                 MUtils::OS::fatal_exit(L"Unhandeled C++ exception error, application will exit!");
201         }
202         catch(...)
203         {
204                 MUTILS_PRINT_ERROR("\nGURU MEDITATION !!!\n\nUnknown exception error!\n");
205                 MUtils::OS::fatal_exit(L"Unhandeled C++ exception error, application will exit!");
206         }
207         return iResult;
208 }
209
210 int MUtils::Startup::startup(int &argc, char **argv, main_function_t *const entry_point, const char* const appName, const bool &debugConsole)
211 {
212         int iResult = -1;
213 #if (MUTILS_DEBUG)
214 #ifdef _MSC_VER
215         _CrtSetDbgFlag(_CRTDBG_CHECK_ALWAYS_DF || _CrtSetDbgFlag(_CRTDBG_REPORT_FLAG));
216 #endif //_MSCVER
217         iResult = startup_main(argc, argv, entry_point, appName, debugConsole);
218 #else //MUTILS_DEBUG
219 #ifdef _MSC_VER
220         __try
221         {
222                 MUtils::ErrorHandler::initialize();
223                 MUtils::OS::check_debugger();
224                 iResult = startup_helper(argc, argv, entry_point, appName, debugConsole);
225         }
226         __except(1)
227         {
228                 MUTILS_PRINT_ERROR("\nGURU MEDITATION !!!\n\nUnhandeled structured exception error!\n");
229                 MUtils::OS::fatal_exit(L"Unhandeled structured exception error, application will exit!");
230         }
231 #else //_MSCVER
232         MUtils::ErrorHandler::initialize();
233         MUtils::OS::check_debugger();
234         iResult = startup_helper(argc, argv, entry_point, appName, debugConsole);
235 #endif //_MSCVER
236 #endif //MUTILS_DEBUG
237         return iResult;
238 }
239
240 ///////////////////////////////////////////////////////////////////////////////
241 // QT INITIALIZATION
242 ///////////////////////////////////////////////////////////////////////////////
243
244 static QMutex g_init_lock;
245 static const char *const g_imageformats[] = {"bmp", "png", "jpg", "gif", "ico", "xpm", "svg", NULL};
246
247 #define CHECK_OSVER(MINREQ_OS) \
248         ((osVersion.type == MUtils::OS::Version::OS_WINDOWS) && (osVersion >= MUtils::OS::Version::MINREQ_OS))
249
250 #define CHECK_SPACK(MIN_OS, MAX_OS, REQUIRED_SP) \
251         ((osVersion < MUtils::OS::Version::MIN_OS) || (osVersion >= MUtils::OS::Version::MAX_OS) || (osVersion.versionSPack >= (REQUIRED_SP)))
252
253 static FORCE_INLINE QString getExecutableName(int &argc, char **argv)
254 {
255         if(argc >= 1)
256         {
257                 const char *argv0 = argv[0];
258                 for (int i = 0; i < 2; i++)
259                 {
260                         static const char SEP[2] = { '/', '\\' };
261                         if (const char *const ptr = strrchr(argv0, SEP[i]))
262                         {
263                                 argv0 = ptr + 1;
264                         }
265                 }
266                 if(strlen(argv0) > 1)
267                 {
268                         return QString::fromLatin1(argv0);
269                 }
270         }
271         return QLatin1String("Program.exe");
272 }
273
274 static FORCE_INLINE void qt_registry_cleanup(void)
275 {
276         static const wchar_t *const QT_JUNK_KEY = L"Software\\Trolltech\\OrganizationDefaults";
277         MUtils::Registry::reg_key_delete(MUtils::Registry::root_user, MUTILS_QSTR(QT_JUNK_KEY), true, true);
278 }
279
280 QApplication *MUtils::Startup::create_qt(int &argc, char **argv, const QString &appName, const QString &appAuthor, const QString &appDomain, const bool xpSupport)
281 {
282         QMutexLocker lock(&g_init_lock);
283         const OS::ArgumentMap &arguments = MUtils::OS::arguments();
284
285         //Don't initialized again, if done already
286         QScopedPointer<QApplication> application(dynamic_cast<QApplication*>(QApplication::instance()));
287         if(!application.isNull())
288         {
289                 qWarning("Qt is already initialized!");
290                 return application.take();
291         }
292
293         //Extract executable name from argv[] array
294         const QString executableName = getExecutableName(argc, argv);
295
296         //Check Qt version
297 #ifdef QT_BUILD_KEY
298         qDebug("Using Qt v%s [%s], %s, %s", qVersion(), QLibraryInfo::buildDate().toString(Qt::ISODate).toLatin1().constData(), (qSharedBuild() ? "DLL" : "Static"), QLibraryInfo::buildKey().toLatin1().constData());
299         qDebug("Compiled with Qt v%s, %s\n", QT_VERSION_STR, QT_BUILD_KEY);
300         if(_stricmp(qVersion(), QT_VERSION_STR))
301         {
302                 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());
303                 return false;
304         }
305         if(QLibraryInfo::buildKey().compare(QString::fromLatin1(QT_BUILD_KEY), Qt::CaseInsensitive))
306         {
307                 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());
308                 return false;
309         }
310 #else
311         qDebug("Using Qt v%s [%s], %s", qVersion(), QLibraryInfo::buildDate().toString(Qt::ISODate).toLatin1().constData(), (qSharedBuild() ? "DLL" : "Static"));
312         qDebug("Compiled with Qt v%s\n", QT_VERSION_STR);
313 #endif
314
315         //Detect the operating system version
316         const MUtils::OS::Version::os_version_t &osVersion = MUtils::OS::os_version();
317         if (const char *const friendlyName = MUtils::OS::os_friendly_name(osVersion))
318         {
319                 qDebug("Running on %s (NT v%u.%u.%u-sp%u).\n", friendlyName, osVersion.versionMajor, osVersion.versionMinor, osVersion.versionBuild, osVersion.versionSPack);
320         }
321         else
322         {
323                 qWarning("Running on an unknown WindowsNT-based system (v%u.%u.%u-sp%u).\n", osVersion.versionMajor, osVersion.versionMinor, osVersion.versionBuild, osVersion.versionSPack);
324         }
325
326         //Check whether we are running on a supported Windows version
327         if (xpSupport)
328         {
329                 if (!CHECK_OSVER(WINDOWS_WINXP))
330                 {
331                         qFatal("%s", MUTILS_L1STR(QApplication::tr("Executable '%1' requires Windows XP or later.").arg(executableName)));
332                 }
333         }
334         else
335         {
336                 if (!CHECK_OSVER(WINDOWS_VISTA))
337                 {
338                         qFatal("%s", MUTILS_L1STR(QApplication::tr("Executable '%1' requires Windows Vista or later.").arg(executableName)));
339                 }
340         }
341
342         //Check for required service packs
343         if (!CHECK_SPACK(WINDOWS_WINXP, WINDOWS_XPX64, 3))
344         {
345                 qFatal("%s", MUTILS_L1STR(QApplication::tr("Executable '%1' requires Service Pack 3 for Windows XP.").arg(executableName)));
346         }
347         if (!CHECK_SPACK(WINDOWS_XPX64, WINDOWS_VISTA, 2))
348         {
349                 qFatal("%s", MUTILS_L1STR(QApplication::tr("Executable '%1' requires Service Pack 2 for Windows XP x64-Edition.").arg(executableName)));
350         }
351         if (!CHECK_SPACK(WINDOWS_VISTA, WINDOWS_WIN70, 2))
352         {
353                 qFatal("%s", MUTILS_L1STR(QApplication::tr("Executable '%1' requires Service Pack 2 for Windows Vista.").arg(executableName)));
354         }
355
356         //Check for Windows 8.0
357         if ((osVersion >= MUtils::OS::Version::WINDOWS_WIN80) && (osVersion < MUtils::OS::Version::WINDOWS_WIN81))
358         {
359                 qFatal("%s", MUTILS_L1STR(QApplication::tr("Executable '%1' requires Windows 8.1 or later.").arg(executableName)));
360         }
361
362         //Check for Wine
363         if(MUtils::OS::running_on_wine())
364         {
365                 qWarning("It appears we are running under Wine, unexpected things might happen!\n");
366         }
367
368         //Set text Codec for locale
369         QTextCodec::setCodecForLocale(QTextCodec::codecForName("UTF-8"));
370
371         //Create Qt application instance
372         application.reset(new QApplication(argc, argv));
373
374         //Register the Qt clean-up function
375         atexit(qt_registry_cleanup);
376
377         //Load plugins from application directory
378         QCoreApplication::setLibraryPaths(QStringList() << QApplication::applicationDirPath());
379         qDebug("Library Path:\n%s\n", MUTILS_UTF8(QApplication::libraryPaths().first()));
380
381         //Set application properties
382         application->setApplicationName(appName);
383         application->setOrganizationDomain(appDomain);
384         application->setOrganizationName(appAuthor);
385 #if QT_VERSION < QT_VERSION_CHECK(5,0,0)
386         application->setEventFilter(&Internal::NativeEventFilter::filterEvent);
387 #else
388         application->installNativeEventFilter(Internal::NativeEventFilter::instance());
389 #endif
390
391         //Check for supported image formats
392         QList<QByteArray> supportedFormats = QImageReader::supportedImageFormats();
393         for(int i = 0; g_imageformats[i]; i++)
394         {
395                 if(!supportedFormats.contains(g_imageformats[i]))
396                 {
397                         qFatal("Qt initialization error: QImageIOHandler for '%s' missing!", g_imageformats[i]);
398                         return NULL;
399                 }
400         }
401         
402         //Setup console icon
403         MUtils::Terminal::set_icon(QIcon(":/mutils/icons/bug.png"));
404
405         //Enable larger/smaller font size
406         double fontScaleFactor = 1.0;
407         if(arguments.contains("huge-font" )) fontScaleFactor = 1.500;
408         if(arguments.contains("big-font"  )) fontScaleFactor = 1.250;
409         if(arguments.contains("small-font")) fontScaleFactor = 0.875;
410         if(arguments.contains("tiny-font" )) fontScaleFactor = 0.750;
411         if(!qFuzzyCompare(fontScaleFactor, 1.0))
412         {
413                 qWarning("Application font scale factor set to: %.3f\n", fontScaleFactor);
414                 QFont appFont = application->font();
415                 appFont.setPointSizeF(appFont.pointSizeF() * fontScaleFactor);
416                 application->setFont(appFont);
417         }
418
419         //Check for process elevation
420         if(MUtils::OS::is_elevated() && (!MUtils::OS::running_on_wine()))
421         {
422                 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);
423                 messageBox.addButton("Quit Program (Recommended)", QMessageBox::NoRole);
424                 messageBox.addButton("Ignore", QMessageBox::NoRole);
425                 if(messageBox.exec() == 0)
426                 {
427                         return NULL;
428                 }
429         }
430
431         //QApplication created successfully
432         return application.take();
433 }
434
435 ///////////////////////////////////////////////////////////////////////////////
436