1 /**
2  * A sensible main() function.
3  *
4  * License:
5  *   This Source Code Form is subject to the terms of
6  *   the Mozilla Public License, v. 2.0. If a copy of
7  *   the MPL was not distributed with this file, You
8  *   can obtain one at http://mozilla.org/MPL/2.0/.
9  *
10  * Authors:
11  *   Vladimir Panteleev <vladimir@thecybershadow.net>
12  */
13 
14 module ae.utils.main;
15 
16 /**
17  * Mix in a main function, which should be adequate
18  * for most end-user programs.
19  *
20  * In debug mode (-debug), this is a pass-through.
21  * Otherwise, this will catch uncaught exceptions,
22  * and display only the message (sans stack trace)
23  * to the user - on standard error, or, for Windows
24  * GUI programs, in a message box.
25  */
26 mixin template main(alias realMain)
27 {
28 	int run(string[] args)
29 	{
30 		static if (is(typeof(realMain())))
31 			static if (is(typeof(realMain()) == void))
32 				{ realMain(); return 0; }
33 			else
34 				return realMain();
35 		else
36 			static if (is(typeof(realMain(args)) == void))
37 				{ realMain(args); return 0; }
38 			else
39 				return realMain(args);
40 	}
41 
42 	int main(string[] args)
43 	{
44 		debug
45 			return run(args);
46 		else
47 		{
48 			try
49 				return run(args);
50 			catch (Throwable e)
51 			{
52 				version (Windows)
53 				{
54 					import core.sys.windows.windows;
55 					auto h = GetStdHandle(STD_ERROR_HANDLE);
56 					if (!h || h == INVALID_HANDLE_VALUE)
57 					{
58 						import ae.sys.windows : messageBox;
59 						messageBox(e.msg, "Fatal error", MB_ICONERROR);
60 						return 1;
61 					}
62 				}
63 
64 				import std.stdio;
65 				stderr.writefln("Fatal error: %s", e.msg);
66 				return 1;
67 			}
68 		}
69 	}
70 }