19d8b79884f7da62f5d7bdbe8c45419d4383a612
[blender.git] / source / blender / python / intern / bpy_interface.c
1
2 #include <stdio.h>
3 #include <stdlib.h>
4
5 #include <Python.h>
6 #include "compile.h"            /* for the PyCodeObject */
7 #include "eval.h"               /* for PyEval_EvalCode */
8
9 #include "BKE_context.h"
10
11 #include "bpy_compat.h"
12
13 #include "bpy_rna.h"
14 #include "bpy_operator.h"
15 #include "bpy_ui.h"
16
17 #include "DNA_space_types.h"
18
19 #include "BKE_text.h"
20 #include "DNA_text_types.h"
21 #include "MEM_guardedalloc.h"
22
23 void BPY_free_compiled_text( struct Text *text )
24 {
25         if( text->compiled ) {
26                 Py_DECREF( ( PyObject * ) text->compiled );
27                 text->compiled = NULL;
28         }
29 }
30
31 /*****************************************************************************
32 * Description: This function creates a new Python dictionary object.
33 *****************************************************************************/
34
35 static PyObject *CreateGlobalDictionary( bContext *C )
36 {
37         PyObject *dict = PyDict_New(  );
38         PyObject *item = PyUnicode_FromString( "__main__" );
39         PyDict_SetItemString( dict, "__builtins__", PyEval_GetBuiltins(  ) );
40         PyDict_SetItemString( dict, "__name__", item );
41         Py_DECREF(item);
42         
43         /* Add Modules */
44         item = BPY_rna_module();
45         PyDict_SetItemString( dict, "bpy", item );
46         Py_DECREF(item);
47         
48         item = BPY_rna_doc();
49         PyDict_SetItemString( dict, "bpydoc", item );
50         Py_DECREF(item);
51
52         item = BPY_operator_module(C);
53         PyDict_SetItemString( dict, "bpyoperator", item );
54         Py_DECREF(item);
55
56         
57         // XXX very experemental, consiter this a test, especiall PyCObject is not meant to be perminant
58         item = BPY_ui_module();
59         PyDict_SetItemString( dict, "bpyui", item );
60         Py_DECREF(item);
61         
62         // XXX - evil, need to access context
63         item = PyCObject_FromVoidPtr( C, NULL );
64         PyDict_SetItemString( dict, "__bpy_context__", item );
65         Py_DECREF(item);
66         
67         return dict;
68 }
69
70 void BPY_start_python( void )
71 {
72         PyThreadState *py_tstate = NULL;
73
74         Py_Initialize(  );
75         
76         //PySys_SetArgv( argc_copy, argv_copy );
77         
78         /* Initialize thread support (also acquires lock) */
79         PyEval_InitThreads();
80         
81         // todo - sys paths - our own imports
82         
83         BPY_rna_init_types();
84         
85         py_tstate = PyGILState_GetThisThreadState();
86         PyEval_ReleaseThread(py_tstate);
87         
88 }
89
90 void BPY_end_python( void )
91 {
92         PyGILState_Ensure(); /* finalizing, no need to grab the state */
93         
94         // free other python data.
95         //BPY_rna_free_types();
96         
97         Py_Finalize(  );
98         
99         BPY_rna_free_types(); /* this MUST run after Py_Finalize since it frees Dynamic allocated PyTypes so we cant free them first */
100         return;
101 }
102
103 /* Can run a file or text block */
104 int BPY_run_python_script( bContext *C, const char *fn, struct Text *text )
105 {
106         PyObject *py_dict, *py_result;
107         PyGILState_STATE gilstate;
108         
109         if (fn==NULL && text==NULL) {
110                 return 0;
111         }
112         
113         //BPY_start_python();
114         
115         gilstate = PyGILState_Ensure();
116
117         py_dict = CreateGlobalDictionary(C);
118
119         if (text) {
120                 
121                 if( !text->compiled ) { /* if it wasn't already compiled, do it now */
122                         char *buf = txt_to_buf( text );
123
124                         text->compiled =
125                                 Py_CompileString( buf, text->id.name+2, Py_file_input );
126
127                         MEM_freeN( buf );
128
129                         if( PyErr_Occurred(  ) ) {
130                                 BPY_free_compiled_text( text );
131                                 return 0;
132                         }
133                 }
134                 py_result =  PyEval_EvalCode( text->compiled, py_dict, py_dict );
135                 
136         } else {
137                 char pystring[512];
138                 /* TODO - look into a better way to run a file */
139                 sprintf(pystring, "exec(open(r'%s').read())", fn);      
140                 py_result = PyRun_String( pystring, Py_file_input, py_dict, py_dict );                  
141         }
142         
143         if (!py_result) {
144                 PyErr_Print();
145         } else {
146                 Py_DECREF( py_result );
147         }
148         PyGILState_Release(gilstate);
149         
150         //BPY_end_python();
151         return py_result ? 1:0;
152 }
153
154
155 /* TODO - move into bpy_space.c ? */
156 /* GUI interface routines */
157
158 /* Copied from Draw.c */
159 static void exit_pydraw( SpaceScript * sc, short err )
160 {
161         Script *script = NULL;
162
163         if( !sc || !sc->script )
164                 return;
165
166         script = sc->script;
167
168         if( err ) {
169                 PyErr_Print(  );
170                 script->flags = 0;      /* mark script struct for deletion */
171                 SCRIPT_SET_NULL(script);
172                 script->scriptname[0] = '\0';
173                 script->scriptarg[0] = '\0';
174 // XXX 2.5              error_pyscript();
175 // XXX 2.5              scrarea_queue_redraw( sc->area );
176         }
177
178 #if 0 // XXX 2.5
179         BPy_Set_DrawButtonsList(sc->but_refs);
180         BPy_Free_DrawButtonsList(); /*clear all temp button references*/
181 #endif
182
183         sc->but_refs = NULL;
184         
185         Py_XDECREF( ( PyObject * ) script->py_draw );
186         Py_XDECREF( ( PyObject * ) script->py_event );
187         Py_XDECREF( ( PyObject * ) script->py_button );
188
189         script->py_draw = script->py_event = script->py_button = NULL;
190 }
191
192 static int bpy_run_script_init(bContext *C, SpaceScript * sc)
193 {
194         if (sc->script==NULL) 
195                 return 0;
196         
197         if (sc->script->py_draw==NULL && sc->script->scriptname[0] != '\0')
198                 BPY_run_python_script(C, sc->script->scriptname, NULL);
199                 
200         if (sc->script->py_draw==NULL)
201                 return 0;
202         
203         return 1;
204 }
205
206 int BPY_run_script_space_draw(bContext *C, SpaceScript * sc)
207 {
208         if (bpy_run_script_init(C, sc)) {
209                 PyGILState_STATE gilstate = PyGILState_Ensure();
210                 PyObject *result = PyObject_CallObject( sc->script->py_draw, NULL );
211                 
212                 if (result==NULL)
213                         exit_pydraw(sc, 1);
214                         
215                 PyGILState_Release(gilstate);
216         }
217         return 1;
218 }
219
220 // XXX - not used yet, listeners dont get a context
221 int BPY_run_script_space_listener(bContext *C, SpaceScript * sc)
222 {
223         if (bpy_run_script_init(C, sc)) {
224                 PyGILState_STATE gilstate = PyGILState_Ensure();
225                 
226                 PyObject *result = PyObject_CallObject( sc->script->py_draw, NULL );
227                 
228                 if (result==NULL)
229                         exit_pydraw(sc, 1);
230                         
231                 PyGILState_Release(gilstate);
232         }
233         return 1;
234 }
235
236 #if 0
237 /* called from the the scripts window, assume context is ok */
238 int BPY_run_python_script_space(const char *modulename, const char *func)
239 {
240         PyObject *py_dict, *py_result= NULL;
241         char pystring[512];
242         PyGILState_STATE gilstate;
243         
244         /* for calling the module function */
245         PyObject *py_func, 
246         
247         gilstate = PyGILState_Ensure();
248         
249         py_dict = CreateGlobalDictionary(C);
250         
251         PyObject *module = PyImport_ImportModule(scpt->script.filename);
252         if (module==NULL) {
253                 PyErr_SetFormat(PyExc_SystemError, "could not import '%s'", scpt->script.filename);
254         }
255         else {
256                 py_func = PyObject_GetAttrString(modulename, func);
257                 if (py_func==NULL) {
258                         PyErr_SetFormat(PyExc_SystemError, "module has no function '%s.%s'\n", scpt->script.filename, func);
259                 }
260                 else {
261                         if (!PyCallable_Check(py_func)) {
262                                 PyErr_SetFormat(PyExc_SystemError, "module item is not callable '%s.%s'\n", scpt->script.filename, func);
263                         }
264                         else {
265                                 py_result= PyObject_CallObject(py_func, NULL); // XXX will need args eventually
266                         }
267                 }
268         }
269         
270         if (!py_result)
271                 PyErr_Print();
272         else
273                 Py_DECREF( py_result );
274         
275         Py_XDECREF(module);
276         
277         
278         PyGILState_Release(gilstate);
279         return 1;
280 }
281 #endif