OSDN Git Service

Moved Natural String Sort functions into MUtils library.
[mutilities/MUtilities.git] / src / Startup.cpp
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.
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/Exception.h>
28
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>
38
39 ///////////////////////////////////////////////////////////////////////////////
40 // MESSAGE HANDLER
41 ///////////////////////////////////////////////////////////////////////////////
42
43 static void qt_message_handler(QtMsgType type, const char *msg)
44 {
45         if((!msg) || (!(msg[0])))
46         {
47                 return;
48         }
49
50         MUtils::Terminal::write(type, msg);
51
52         if((type == QtCriticalMsg) || (type == QtFatalMsg))
53         {
54                 MUtils::OS::fatal_exit(MUTILS_WCHR(QString::fromUtf8(msg)));
55         }
56 }
57
58 static bool qt_event_filter(void *message, long *result)
59 {
60         return MUtils::OS::handle_os_message(message, result);
61 }
62
63 ///////////////////////////////////////////////////////////////////////////////
64 // STARTUP FUNCTION
65 ///////////////////////////////////////////////////////////////////////////////
66
67 static int startup_main(int &argc, char **argv, MUtils::Startup::main_function_t *const entry_point)
68 {
69         qInstallMsgHandler(qt_message_handler);
70         MUtils::Terminal::setup(argc, argv, MUTILS_DEBUG);
71         return entry_point(argc, argv);
72 }
73
74 static int startup_helper(int &argc, char **argv, MUtils::Startup::main_function_t *const entry_point)
75 {
76         int iResult = -1;
77         try
78         {
79                 iResult = startup_main(argc, argv, entry_point);
80         }
81         catch(const std::exception &error)
82         {
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!");
85         }
86         catch(...)
87         {
88                 MUTILS_PRINT_ERROR("\nGURU MEDITATION !!!\n\nUnknown exception error!\n");
89                 MUtils::OS::fatal_exit(L"Unhandeled C++ exception error, application will exit!");
90         }
91         return iResult;
92 }
93
94 int MUtils::Startup::startup(int &argc, char **argv, main_function_t *const entry_point)
95 {
96         int iResult = -1;
97 #if 1||(MUTILS_DEBUG)
98         iResult = startup_main(argc, argv, entry_point);
99 #else //MUTILS_DEBUG
100 #ifdef _MSC_VER
101         __try
102         {
103                 MUtils::ErrorHandler::initialize();
104                 iResult = startup_helper(argc, argv, entry_point);
105         }
106         __except(1)
107         {
108                 MUTILS_PRINT_ERROR("\nGURU MEDITATION !!!\n\nUnhandeled structured exception error!\n");
109                 MUtils::OS::fatal_exit(L"Unhandeled structured exception error, application will exit!");
110         }
111 #else //_MSCVER
112         MUtils::ErrorHandler::initialize();
113         iResult = startup_helper(argc, argv, entry_point);
114 #endif //_MSCVER
115 #endif //MUTILS_DEBUG
116         return iResult;
117 }
118
119 ///////////////////////////////////////////////////////////////////////////////
120 // QT INITIALIZATION
121 ///////////////////////////////////////////////////////////////////////////////
122
123 static QMutex g_qt_lock;
124 static QScopedPointer<QApplication> g_application;
125
126 static const char *const g_imageformats[] = {"bmp", "png", "jpg", "gif", "ico", "xpm", "svg", NULL};
127
128 bool MUtils::Startup::init_qt(int &argc, char **argv, const QString &appName)
129 {
130         QMutexLocker lock(&g_qt_lock);
131         const QStringList &arguments = MUtils::OS::arguments();
132
133         //Don't initialized again, if done already
134         if(!g_application.isNull())
135         {
136                 return true;
137         }
138
139         //Extract executable name from argv[] array
140         QString executableName = QLatin1String("LameXP.exe");
141         if(arguments.count() > 0)
142         {
143                 static const char *delimiters = "\\/:?";
144                 executableName = arguments[0].trimmed();
145                 for(int i = 0; delimiters[i]; i++)
146                 {
147                         int temp = executableName.lastIndexOf(QChar(delimiters[i]));
148                         if(temp >= 0) executableName = executableName.mid(temp + 1);
149                 }
150                 executableName = executableName.trimmed();
151                 if(executableName.isEmpty())
152                 {
153                         executableName = QLatin1String("LameXP.exe");
154                 }
155         }
156
157         //Check Qt version
158 #ifdef QT_BUILD_KEY
159         qDebug("Using Qt v%s [%s], %s, %s", qVersion(), QLibraryInfo::buildDate().toString(Qt::ISODate).toLatin1().constData(), (qSharedBuild() ? "DLL" : "Static"), QLibraryInfo::buildKey().toLatin1().constData());
160         qDebug("Compiled with Qt v%s [%s], %s\n", QT_VERSION_STR, QT_PACKAGEDATE_STR, QT_BUILD_KEY);
161         if(_stricmp(qVersion(), QT_VERSION_STR))
162         {
163                 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());
164                 return false;
165         }
166         if(QLibraryInfo::buildKey().compare(QString::fromLatin1(QT_BUILD_KEY), Qt::CaseInsensitive))
167         {
168                 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());
169                 return false;
170         }
171 #else
172         qDebug("Using Qt v%s [%s], %s", qVersion(), QLibraryInfo::buildDate().toString(Qt::ISODate).toLatin1().constData(), (qSharedBuild() ? "DLL" : "Static"));
173         qDebug("Compiled with Qt v%s [%s]\n", QT_VERSION_STR, QT_PACKAGEDATE_STR);
174 #endif
175
176         //Check the Windows version
177         
178         const MUtils::OS::Version::os_version_t &osVersion = MUtils::OS::os_version();
179         if((osVersion.type != MUtils::OS::Version::OS_WINDOWS) || (osVersion < MUtils::OS::Version::WINDOWS_WINXP))
180         {
181                 qFatal("%s", QApplication::tr("Executable '%1' requires Windows XP or later.").arg(executableName).toLatin1().constData());
182         }
183
184         //Check whether we are running on a supported Windows version
185         if(const char *const friendlyName = MUtils::OS::os_friendly_name(osVersion))
186         {
187                 qDebug("Running on %s (NT v%u.%u).\n", friendlyName, osVersion.versionMajor, osVersion.versionMinor);
188         }
189         else
190         {
191                 const QString message = QString().sprintf("Running on an unknown WindowsNT-based system (v%u.%u).", osVersion.versionMajor, osVersion.versionMinor);
192                 qWarning("%s\n", MUTILS_UTF8(message));
193                 MUtils::OS::system_message_wrn(MUTILS_WCHR(message), L"LameXP");
194         }
195
196         //Check for compat mode
197         if(osVersion.overrideFlag && (osVersion <= MUtils::OS::Version::WINDOWS_WN100))
198         {
199                 qWarning("Windows compatibility mode detected!");
200                 if(!arguments.contains("--ignore-compat-mode", Qt::CaseInsensitive))
201                 {
202                         qFatal("%s", QApplication::tr("Executable '%1' doesn't support Windows compatibility mode.").arg(executableName).toLatin1().constData());
203                         return false;
204                 }
205         }
206
207         //Check for Wine
208         if(MUtils::OS::running_on_wine())
209         {
210                 qWarning("It appears we are running under Wine, unexpected things might happen!\n");
211         }
212
213         //Set text Codec for locale
214         QTextCodec::setCodecForLocale(QTextCodec::codecForName("UTF-8"));
215
216         //Create Qt application instance
217         g_application.reset(new QApplication(argc, argv));
218
219         //Load plugins from application directory
220         QCoreApplication::setLibraryPaths(QStringList() << QApplication::applicationDirPath());
221         qDebug("Library Path:\n%s\n", MUTILS_UTF8(QApplication::libraryPaths().first()));
222
223         //Set application properties
224         g_application->setApplicationName(appName);
225         g_application->setOrganizationName("LoRd_MuldeR");
226         g_application->setOrganizationDomain("mulder.at.gg");
227         g_application->setEventFilter(qt_event_filter);
228
229         //Check for supported image formats
230         QList<QByteArray> supportedFormats = QImageReader::supportedImageFormats();
231         for(int i = 0; g_imageformats[i]; i++)
232         {
233                 if(!supportedFormats.contains(g_imageformats[i]))
234                 {
235                         qFatal("Qt initialization error: QImageIOHandler for '%s' missing!", g_imageformats[i]);
236                         return false;
237                 }
238         }
239         
240         //Enable larger/smaller font size
241         double fontScaleFactor = 1.0;
242         if(arguments.contains("--huge-font",  Qt::CaseInsensitive)) fontScaleFactor = 1.500;
243         if(arguments.contains("--big-font",   Qt::CaseInsensitive)) fontScaleFactor = 1.250;
244         if(arguments.contains("--small-font", Qt::CaseInsensitive)) fontScaleFactor = 0.875;
245         if(arguments.contains("--tiny-font",  Qt::CaseInsensitive)) fontScaleFactor = 0.750;
246         if(!qFuzzyCompare(fontScaleFactor, 1.0))
247         {
248                 qWarning("Application font scale factor set to: %.3f\n", fontScaleFactor);
249                 QFont appFont = g_application->font();
250                 appFont.setPointSizeF(appFont.pointSizeF() * fontScaleFactor);
251                 g_application->setFont(appFont);
252         }
253
254         //Check for process elevation
255         if(MUtils::OS::is_elevated() && (!MUtils::OS::running_on_wine()))
256         {
257                 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);
258                 messageBox.addButton("Quit Program (Recommended)", QMessageBox::NoRole);
259                 messageBox.addButton("Ignore", QMessageBox::NoRole);
260                 if(messageBox.exec() == 0)
261                 {
262                         return NULL;
263                 }
264         }
265
266         //Successful
267         return g_application.data();
268 }
269
270 ///////////////////////////////////////////////////////////////////////////////