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