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