]> Shamusworld >> Repos - architektonas/blob - src/base/rs_python.cpp
aadbd9ce8cc0366f59f489a2d77e6a4285daa718
[architektonas] / src / base / rs_python.cpp
1 // rs_python.cpp
2 //
3 // Part of the Architektonas Project
4 // Originally part of QCad Community Edition by Andrew Mustun
5 // Extensively rewritten and refactored by James L. Hammons
6 // (C) 2010 Underground Software
7 //
8 // JLH = James L. Hammons <jlhamm@acm.org>
9 //
10 // Who  When        What
11 // ---  ----------  -----------------------------------------------------------
12 // JLH  06/02/2010  Added this text. :-)
13 //
14
15 #include "rs_python.h"
16
17 #ifdef RS_OPT_PYTHON
18
19 //
20 // This is exported from the Boost::Python library declarations
21 // that are declared inside rs_python_wrappers.cpp.
22 //
23 extern "C" void initqcad();
24
25 /**
26  * The unique instance of the Python scripting engine
27  */
28 RS_Python* RS_Python::uniqueInstance = NULL;
29
30 /**
31  * Constructor
32  */
33 RS_Python::RS_Python()
34 {
35     graphic = NULL;
36     Py_Initialize();
37     initqcad();
38 }
39
40 /**
41  *  Gets the one and only RS_Python instance
42  *  (creates a new one on first call only)
43  *
44  *  @return Pointer to the single instance of this
45  * singleton class
46  */
47 RS_Python* RS_Python::instance() {
48     if(uniqueInstance==NULL) {
49         uniqueInstance = new RS_Python;
50     }
51     return uniqueInstance;
52 }
53
54
55 /**
56  * Launches the given script.
57  */
58 int RS_Python::launch(const QString& script) {
59     PyObject *modname, *mod, *mdict, *func, *rslt;
60     //Py_SetProgramName(argv[0]);
61
62     modname = PyString_FromString(script);
63     mod = PyImport_Import(modname);
64     if (mod) {
65         //printf( "mod\n");
66         mdict = PyModule_GetDict(mod);
67
68         // Borrowed reference to start function
69         func = PyDict_GetItemString(mdict, "start");
70         if (func) {
71             //printf( "func\n");
72             if (PyCallable_Check(func)) {
73                 //printf("calling..\n");
74                 rslt = PyObject_CallFunction(func, "(s)", "noparam");
75                 //printf("calling ok\n");
76                 if (rslt) {
77                     // The result value is currently not used
78                     Py_XDECREF(rslt);
79                 } else
80                 {
81                     // Give user some feed back what went wrong
82                     printf("*** PYTHON RUNTIME ERROR ***\n");
83                     PyErr_Print();
84                 }
85             }
86         } else {
87             printf("no such function: start\n");
88         }
89         Py_XDECREF(mod);
90     } else {
91         printf("*** ERROR LOADING SCRIPT '%s' ***\n", script.latin1());
92         PyErr_Print();
93     }
94     Py_XDECREF(modname);
95     //Py_Finalize();
96     return 0;
97 }
98
99 #endif