make linking python optional
[mussa.git] / qui / mussagl.cpp
1 #include <boost/filesystem/operations.hpp>
2 #ifdef USE_PYTHON
3 #include <boost/python.hpp>
4 #endif
5
6 using namespace boost::filesystem;
7
8 #include <stdlib.h>
9 #include <iostream>
10 #include <QApplication>
11
12 #include "qui/MussaWindow.hpp"
13 #include "alg/parse_options.hpp"
14 #include "mussa_exceptions.hpp"
15
16 int main(int argc, char **argv)
17 {
18   MussaOptions opts;
19
20   // if we're under unix and don't have a display, see if we can still run
21 #ifdef Q_WS_X11
22   opts.useGUI = getenv("DISPLAY") != 0;
23 #endif
24
25   QApplication app(argc, argv, opts.useGUI);
26   Q_INIT_RESOURCE(icons);
27
28   initialize_mussa(opts, argc, argv);
29
30   if (opts.analysis == 0) {
31     return 1;
32   }
33
34   try {
35 #ifdef USE_PYTHON
36     if (opts.runAsPythonInterpeter) {
37       Py_Initialize();
38       boost::python::object main_module((boost::python::handle<>(boost::python::borrowed(PyImport_AddModule("__main__")))));
39       boost::python::object main_namespace = main_module.attr("__dict__");
40
41       boost::python::handle<> ignored((PyRun_String(
42                         //"from IPython.Shell import IPShellEmbed\n"
43                         //"shell = IPShellEmbed(['mussa'], '')\n",
44                         //"import mussa\n"
45                         "def square(x):\n"
46                         "  r = x * x\n"
47                         "  print 'the square is %d' % (r)\n"
48                         "  return r\n",
49                         Py_file_input, 
50                         main_namespace.ptr(),
51                         main_namespace.ptr())
52                       ));
53       boost::python::object square = main_module.attr("square");
54       int result = boost::python::extract<int>(square(3));
55       std::cout << "C++ has " << result << std::endl;
56       PyRun_InteractiveLoop(stdin, "mussa");
57     } else 
58 #endif /* USE_PYTHON */
59     if (opts.useGUI) { 
60       MussaWindow win(opts.analysis);
61       win.show();
62       app.exec();
63     }
64     return 0;
65   } catch (mussa_error e) {
66     qFatal(e.what());
67   } catch (boost::filesystem::filesystem_error e) {
68     qFatal(e.what());
69   }
70 #ifdef USE_PYTHON
71   catch (boost::python::error_already_set e) {
72     PyErr_Print();
73   }
74 #endif /* USE_PYTHON */
75   catch (std::runtime_error e) {
76     qFatal(e.what());
77   } catch (...) {
78     qFatal("unrecognized exception");
79   }
80   return 1; 
81 }