]> vaikene.ee Git - evaf/blob - src/main/GUI/main.cpp
More work on the common library and the main GUI application.
[evaf] / src / main / GUI / main.cpp
1 /**
2 * @file main/GUI/main.cpp
3 * @brief The main eVaf GUI application class
4 * @author Enar Vaikene
5 *
6 * Copyright (c) 2011 Enar Vaikene
7 *
8 * This file is part of the eVaf C++ cross-platform application development framework.
9 *
10 * This file can be used under the terms of the GNU General Public License
11 * version 3.0 as published by the Free Software Foundation and appearing in
12 * the file LICENSE included in the packaging of this file. Please review the
13 * the following information to ensure the GNU General Public License version
14 * 3.0 requirements will be met: http://www.gnu.org/copyleft/gpl.html.
15 *
16 * Alternatively, this file may be used in accordance with the Commercial License
17 * Agreement provided with the Software.
18 */
19
20 #include "main.h"
21 #include "exithandler.h"
22 #include "fatalerr.h"
23 //#include "version_p.h"
24 #include "version.h"
25
26 #ifdef Q_OS_WIN32
27 #include "winconsole.h"
28 #endif
29
30 #include <Common/Globals>
31 #include <Common/iLogger>
32 #include <Common/iEnv>
33 #include <Common/iApp>
34
35 #include <QtGui>
36
37 #ifdef Q_OS_LINUX
38 # include <sys/types.h>
39 # include <unistd.h>
40 #endif
41
42
43 //-------------------------------------------------------------------
44
45 namespace eVaf {
46 namespace GUI {
47 namespace Internal {
48
49 /**
50 * Flag indicating that the application should be more verbose when dealing with fatal errors.
51 *
52 * If this flag is set, then shows fatal errors on the screen as dialog boxes and
53 * the user has to close them before terminating the application.
54 *
55 * If this flag is not set, then no messages are shown and the application terminates
56 * silently. Error messages are written only into the log file.
57 */
58 static bool BeVerbose = true;
59
60 #ifdef Q_OS_WIN32
61 /**
62 * Flag indicating that the application needs a console window.
63 *
64 * If this flag is set, opens an extra console window for message output.
65 */
66 static bool NeedsConsole = false;
67 #endif
68
69 /**
70 * Console severity level.
71 *
72 * This variable is used to set the console severity level. The severity level is changed
73 * with command-line arguments.
74 */
75 static eVaf::Common::iLogger::Severity ConsoleSeverityLevel = eVaf::Common::iLogger::Fatal;
76
77 /**
78 * Qt message handler replacement.
79 * @param type Type of the message
80 * @param msg The message
81 *
82 * This function outputs messages to the console and to the log file.
83 */
84 static void messageOutput(QtMsgType type, char const * const msg)
85 {
86 static bool inHandler = false;
87
88 // Avoid recursions in case outputting a message causes another message to be output
89 if (inHandler)
90 return;
91 inHandler = true;
92
93 // Qt message type conversion to eVaf logger severity levels
94 eVaf::Common::iLogger::Severity v;
95 switch (type) {
96 case QtWarningMsg:
97 v = eVaf::Common::iLogger::Warning;
98 break;
99 case QtCriticalMsg:
100 v = eVaf::Common::iLogger::Error;
101 break;
102 case QtFatalMsg:
103 v = eVaf::Common::iLogger::Fatal;
104 break;
105 default:
106 v = eVaf::Common::iLogger::Debug;
107 }
108
109 // Output to the log file and console
110 eVaf::Common::iLogger::instance()->write(v, msg);
111
112 inHandler = false;
113 }
114
115 /**
116 * Fatal error message handler
117 * @param msg The error message
118 * @param source Source of the message
119 * @param where Where the error occurred
120 *
121 * This function shows a critical error message box on the screen if needed and then terminates
122 * the application.
123 *
124 * If the critical error message is shown, then the user has an option to ignore the error. In this
125 * case the application is not terminated.
126 */
127 static void fatalMsgHandler(QString const & msg, QString const & source, QString const & where)
128 {
129 // Show the message on the screen
130 if (BeVerbose) {
131 if (FatalErr::message(QObject::tr("Fatal Error"),
132 QObject::tr("%1\n\nOccurred in '%2'")
133 .arg(msg)
134 .arg(where),
135 0) == FatalErr::Ignore)
136 return;
137 }
138 #ifdef Q_OS_LINUX
139 abort();
140 #else
141 exit(1);
142 #endif
143 }
144
145 } // namespace eVaf::GUI::Internal
146 } // namespace eVaf::GUI
147 } // namespace eVaf
148
149
150 //-------------------------------------------------------------------
151
152 using namespace eVaf;
153 using namespace eVaf::GUI;
154
155 Application::Application(int & argc, char ** argv)
156 : QApplication(argc, argv)
157 {
158 setObjectName(QString("%1-%2").arg(VER_MODULE_NAME_STR).arg(__FUNCTION__));
159
160 EVAF_INFO("%s version %s created", qPrintable(objectName()), VER_FILE_VERSION_STR);
161 }
162
163 Application::~Application()
164 {
165 EVAF_INFO("%s destroyed", qPrintable(objectName()));
166 }
167
168 bool Application::processCommandLine(int argc, char ** argv)
169 {
170 QStringList args;
171 for (int i = 1; i < argc; ++i)
172 args += argv[i];
173
174 for (int i = 0; i < args.size(); ++i) {
175 // Get the argument and optional value
176 QStringList arg = args.at(i).simplified().split(QChar('='));
177
178 if (QRegExp("(-[-]?version)|([-//]V)").exactMatch(arg.at(0))) {
179 printVersion();
180 return false;
181 }
182 else if (QRegExp("(-[-]?help)|([-//][h/?])").exactMatch(arg.at(0))) {
183 printHelp();
184 return false;
185 }
186 else if (QRegExp("-[-]?help-qt").exactMatch(arg.at(0))) {
187 printQtHelp();
188 return false;
189 }
190 else if (QRegExp("-[-]?verbose").exactMatch(arg.at(0)) && arg.size() > 1) {
191 #ifdef Q_OS_WIN32
192 Internal::NeedsConsole = true;
193 #endif
194 QString v = arg.at(1).toLower();
195 if (v == "debug")
196 Internal::ConsoleSeverityLevel = Common::iLogger::Debug;
197 else if (v == "info")
198 Internal::ConsoleSeverityLevel = Common::iLogger::Info;
199 else if (v == "warning")
200 Internal::ConsoleSeverityLevel = Common::iLogger::Warning;
201 else if (v == "error")
202 Internal::ConsoleSeverityLevel = Common::iLogger::Error;
203 else if (v == "fatal")
204 Internal::ConsoleSeverityLevel = Common::iLogger::Fatal;
205 else if (v == "none") {
206 Internal::ConsoleSeverityLevel = Common::iLogger::None;
207 Internal::BeVerbose = false;
208 #ifdef Q_OS_WIN32
209 Internal::NeedsConsole = false;
210 #endif
211 }
212 else {
213 printHelp();
214 return false;
215 }
216 }
217 else if (QRegExp("-[v]+").exactMatch(arg.at(0)) && arg.size() == 1) {
218 // The number of 'v's increases the verbosity
219 for (int j = 1; j < arg.at(0).size(); ++j) {
220 switch (Internal::ConsoleSeverityLevel) {
221 case Common::iLogger::None:
222 Internal::ConsoleSeverityLevel = Common::iLogger::Fatal;
223 break;
224 case Common::iLogger::Fatal:
225 Internal::ConsoleSeverityLevel = Common::iLogger::Error;
226 break;
227 case Common::iLogger::Error:
228 Internal::ConsoleSeverityLevel = Common::iLogger::Warning;
229 break;
230 case Common::iLogger::Warning:
231 Internal::ConsoleSeverityLevel = Common::iLogger::Info;
232 break;
233 case Common::iLogger::Info:
234 Internal::ConsoleSeverityLevel = Common::iLogger::Debug;
235 break;
236 case Common::iLogger::Debug:
237 break;
238 }
239 }
240 }
241 }
242
243 return true;
244 }
245
246 void Application::printHelp()
247 {
248 char const * const txt = QT_TR_NOOP(
249 "Usage: eVafGUI [options]\n"
250 "\n"
251 // General options
252 " -help Shows this help and quits.\n"
253 " -help-qt Shows Qt command line options and quits.\n"
254 " -version Shows version information and quits.\n"
255 " -verbose=LEVEL Specifies the verbose level. LEVEL can be one of the\n"
256 " following: NONE, FATAL, ERROR, WARNING, INFO, DEBUG.\n"
257 " -v Makes the application more verbose. Can be repeated for\n"
258 " more verbosity.\n"
259 // Handled by the iApp interface implementation
260 " -appl[ication]=NAME Specifies the name of the application.\n"
261 " -lang[uage]=xx[_CC] Specifies the language, where xx is the ISO 639\n"
262 " language code followed by an optional ISO 3166 country\n"
263 " code.\n"
264 // Handled by the iEnv interface implementation
265 " -root[dir]=DIR Specifies the application's root directory.\n"
266 " -dataroot[dir]=DIR Specifies the data root directory.\n"
267 " -etc[dir]=DIR Specifies the configuration files directory.\n"
268 " -log[dir]=DIR Specifies the log files directory.\n"
269 " -doc[dir]=DIR Specifies the documentation directory.\n"
270 " -qtplugins[dir]=DIR Specifies the Qt plugins directory.\n"
271 );
272 ::fputs(tr(txt).toLocal8Bit().constData(), stdout);
273 }
274
275 void Application::printQtHelp()
276 {
277 // Cannot translate this text as QT_TR_NOOP() is not able to process #ifdef parts.
278 char const * const txt =
279 #ifdef QT_DEBUG
280 "Qt debugging options:\n"
281 " -nograb tells Qt that it must never grab the mouse or the keyboard.\n"
282 #ifdef Q_OS_UNIX
283 " -dograb running under a debugger can cause an implicit -nograb,\n"
284 " use -dograb to override.\n"
285 " -sync switches to synchronous mode for debugging.\n\n"
286 #endif
287 #endif
288 "Qt common options:\n"
289 " -style=STYLE sets the application GUI style. Possible values are motif,\n"
290 " windows, and platinum.\n"
291 " -style STYLE is the same as listed above.\n"
292 " -stylesheet=STYLESHEET sets the application style sheet.\n"
293 " -stylesheet STYLESHEET is the same as listed above.\n"
294 " -session=SESSION restores the application from an earlier session.\n"
295 " -session SESSION is the same as listed above.\n"
296 " -widgetcount prints debug message at the end about number of widgets\n"
297 " left undestroyed and maximum number of widgets existed at\n"
298 " the same time.\n"
299 " -reverse sets the application's layout direction to Qt::RightToLeft\n\n"
300 #ifdef Q_OS_WIN32
301 "Qt options on Windows:\n"
302 " -direct3d will make the Direct3D paint engine the default widget\n"
303 " paint engine in Qt.\n\n"
304 #endif
305 #ifdef Q_WS_X11
306 "Qt options on X11:\n"
307 " -display DISPLAY sets the X display.\n"
308 " -geometry GEOMETRY sets the client geometry of the first window that is\n"
309 " shown.\n"
310 " -fn or -font FONT defines the application font.\n"
311 " -bg or -background COLOR sets the default background color and an\n"
312 " application palette.\n"
313 " -fg or -foreground COLOR sets the default foreground color.\n"
314 " -btn or -button COLOR sets the default button color.\n"
315 " -name NAME sets the application name.\n"
316 " -title TITLE sets the application title.\n"
317 " -visual TrueColor forces the application to use a TrueColor visual on an\n"
318 " 8-bit display.\n"
319 " -ncols COUNT limits the number of colors allocated in the color cube on\n"
320 " an 8-bit display, if the application is using the\n"
321 " QApplication::ManyColor color specification. If COUNT is\n"
322 " 216 then a 6x6x6 color cube is used (i.e. 6 levels of red,\n"
323 " 6 of green, and 6 of blue); for other values, a cube\n"
324 " approximately proportional to a 2x3x1 cube is used.\n"
325 " -cmap causes the application to install a private color map on an\n"
326 " 8-bit display.\n"
327 " -im sets the input method server (equivalent to setting the\n"
328 " XMODIFIERS environment variable).\n"
329 " -noxim disables the input method framework (\"no X input method\").\n"
330 " -inputstyle defines how the input is inserted into the given widget.\n"
331 " E.g., onTheSpot makes the input appear directly in the\n"
332 " widget, while overTheSpot makes the input appear in a box\n"
333 " floating over the widget and is not inserted until the\n"
334 " editing is done.\n"
335 #endif
336 ;
337 ::fputs(txt, stdout);
338 }
339
340 void Application::printVersion()
341 {
342 ::printf("%s version %s release date %s, %s version %s\n",
343 VER_PRODUCT_NAME_STR,
344 VER_PRODUCT_VERSION_STR,
345 VER_PRODUCT_DATE_STR,
346 VER_MODULE_NAME_STR,
347 VER_FILE_VERSION_STR
348 );
349 }
350
351
352 //-------------------------------------------------------------------
353
354 int main(int argc, char ** argv)
355 {
356 Common::iLogger::instance()->setSeverity(Common::iLogger::Warning);
357
358 // Install our own message handlers
359 Common::iLogger::instance()->installFatalMsgHandler(Internal::fatalMsgHandler);
360 qInstallMsgHandler(Internal::messageOutput);
361
362 // Process command-line arguments
363 if (!Application::processCommandLine(argc, argv))
364 return 1;
365
366 // Set the console severity
367 Common::iLogger::instance()->setConsoleSeverity(Internal::ConsoleSeverityLevel);
368
369 #ifdef Q_OS_WIN32
370 // Enable the extra message console on Windows
371 if (Internal::NeedsConsole)
372 Internal::enableWinConsole();
373 #endif
374
375 EVAF_INFO("%s version %s release date %s, %s version %s",
376 VER_PRODUCT_NAME_STR,
377 VER_PRODUCT_VERSION_STR,
378 VER_PRODUCT_DATE_STR,
379 VER_MODULE_NAME_STR,
380 VER_FILE_VERSION_STR);
381
382 #ifdef Q_OS_LINUX
383 EVAF_INFO("%s application pid = %d", VER_MODULE_NAME_STR, getpid());
384 #endif
385
386 Application app(argc, argv);
387
388 // Install the exit handler
389 if (!Internal::installExitHandler())
390 return 1;
391
392 // Plugin manager
393 // Plugins::PluginManager pluginManager;
394
395 // The main run loop
396 bool quit = false;
397 int rval;
398 while (!quit) {
399
400 EVAF_INFO("%s is starting up", VER_MODULE_NAME_STR);
401
402 // Initialize the common library
403 if (!Common::init())
404 return 1;
405
406 // Initialize the plugin manager and load plugins
407 //if (!pluginManager.init())
408 // return 1;
409
410 // Run the application
411 rval = app.exec();
412
413 quit = rval != Common::iApp::RC_Restart;
414
415 EVAF_INFO("%s is %s", VER_MODULE_NAME_STR, quit ? "exiting" : "restarting");
416
417 // Unload plugins and finalize the plugin manager
418 // pluginManager.done();
419 }
420
421 EVAF_INFO("%s exit with code %d", VER_MODULE_NAME_STR, rval);
422
423 return rval;
424 }