UI:
[blender.git] / source / blender / python / intern / bpy_interface.c
1
2 #include <stdio.h>
3 #include <stdlib.h>
4 #include <string.h>
5 #include <sys/stat.h>
6
7 #ifndef WIN32
8 #include <dirent.h>
9 #else
10 #include "BLI_winstuff.h"
11 #endif
12
13 #include <Python.h>
14 #include "compile.h"            /* for the PyCodeObject */
15 #include "eval.h"               /* for PyEval_EvalCode */
16
17 #include "bpy_compat.h"
18
19 #include "bpy_rna.h"
20 #include "bpy_operator.h"
21 #include "bpy_ui.h"
22
23 #include "DNA_anim_types.h"
24 #include "DNA_space_types.h"
25 #include "DNA_text_types.h"
26
27 #include "MEM_guardedalloc.h"
28
29 #include "BLI_util.h"
30 #include "BLI_string.h"
31
32 #include "BKE_context.h"
33 #include "BKE_fcurve.h"
34 #include "BKE_text.h"
35
36 #include "BPY_extern.h"
37
38 void BPY_free_compiled_text( struct Text *text )
39 {
40         if( text->compiled ) {
41                 Py_DECREF( ( PyObject * ) text->compiled );
42                 text->compiled = NULL;
43         }
44 }
45
46 /*****************************************************************************
47 * Description: Creates the bpy module and adds it to sys.modules for importing
48 *****************************************************************************/
49 static void bpy_init_modules( void )
50 {
51         PyObject *mod;
52         
53         mod = PyModule_New("bpy");
54         
55         PyModule_AddObject( mod, "data", BPY_rna_module() );
56         /* PyModule_AddObject( mod, "doc", BPY_rna_doc() ); */
57         PyModule_AddObject( mod, "types", BPY_rna_types() );
58         PyModule_AddObject( mod, "ops", BPY_operator_module() );
59         PyModule_AddObject( mod, "ui", BPY_ui_module() ); // XXX very experemental, consider this a test, especially PyCObject is not meant to be perminant
60         
61         /* add the module so we can import it */
62         PyDict_SetItemString(PySys_GetObject("modules"), "bpy", mod);
63         Py_DECREF(mod);
64 }
65
66 #if (PY_VERSION_HEX < 0x02050000)
67 PyObject *PyImport_ImportModuleLevel(char *name, void *a, void *b, void *c, int d)
68 {
69         return PyImport_ImportModule(name);
70 }
71 #endif
72
73 void BPY_update_modules( void )
74 {
75         PyObject *mod= PyImport_ImportModuleLevel("bpy", NULL, NULL, NULL, 0);
76         PyModule_AddObject( mod, "data", BPY_rna_module() );
77         PyModule_AddObject( mod, "types", BPY_rna_types() );
78 }
79
80 /*****************************************************************************
81 * Description: This function creates a new Python dictionary object.
82 *****************************************************************************/
83 static PyObject *CreateGlobalDictionary( bContext *C )
84 {
85         PyObject *mod;
86         PyObject *dict = PyDict_New(  );
87         PyObject *item = PyUnicode_FromString( "__main__" );
88         PyDict_SetItemString( dict, "__builtins__", PyEval_GetBuiltins(  ) );
89         PyDict_SetItemString( dict, "__name__", item );
90         Py_DECREF(item);
91         
92         // XXX - evil, need to access context
93         BPy_SetContext(C);
94         
95         // XXX - put somewhere more logical
96         {
97                 PyMethodDef *ml;
98                 static PyMethodDef bpy_prop_meths[] = {
99                         {"FloatProperty", (PyCFunction)BPy_FloatProperty, METH_VARARGS|METH_KEYWORDS, ""},
100                         {"IntProperty", (PyCFunction)BPy_IntProperty, METH_VARARGS|METH_KEYWORDS, ""},
101                         {"BoolProperty", (PyCFunction)BPy_BoolProperty, METH_VARARGS|METH_KEYWORDS, ""},
102                         {NULL, NULL, 0, NULL}
103                 };
104                 
105                 for(ml = bpy_prop_meths; ml->ml_name; ml++) {
106                         PyDict_SetItemString( dict, ml->ml_name, PyCFunction_New(ml, NULL));
107                 }
108         }
109         
110         /* add bpy to global namespace */
111         mod= PyImport_ImportModuleLevel("bpy", NULL, NULL, NULL, 0);
112         PyDict_SetItemString( dict, "bpy", mod );
113         Py_DECREF(mod);
114         
115         return dict;
116 }
117
118 void BPY_start_python( int argc, char **argv )
119 {
120         PyThreadState *py_tstate = NULL;
121         
122         Py_Initialize(  );
123         
124         //PySys_SetArgv( argc_copy, argv_copy );
125         
126         /* Initialize thread support (also acquires lock) */
127         PyEval_InitThreads();
128         
129         
130         /* bpy.* and lets us import it */
131         bpy_init_modules(); 
132
133         
134         py_tstate = PyGILState_GetThisThreadState();
135         PyEval_ReleaseThread(py_tstate);
136         
137 }
138
139 void BPY_end_python( void )
140 {
141         PyGILState_Ensure(); /* finalizing, no need to grab the state */
142         
143         // free other python data.
144         //BPY_rna_free_types();
145         
146         Py_Finalize(  );
147         
148         return;
149 }
150
151 /* Can run a file or text block */
152 int BPY_run_python_script( bContext *C, const char *fn, struct Text *text )
153 {
154         PyObject *py_dict, *py_result;
155         PyGILState_STATE gilstate;
156         
157         if (fn==NULL && text==NULL) {
158                 return 0;
159         }
160         
161         //BPY_start_python();
162         
163         gilstate = PyGILState_Ensure();
164
165         BPY_update_modules(); /* can give really bad results if this isnt here */
166         
167         py_dict = CreateGlobalDictionary(C);
168
169         if (text) {
170                 
171                 if( !text->compiled ) { /* if it wasn't already compiled, do it now */
172                         char *buf = txt_to_buf( text );
173
174                         text->compiled =
175                                 Py_CompileString( buf, text->id.name+2, Py_file_input );
176
177                         MEM_freeN( buf );
178
179                         if( PyErr_Occurred(  ) ) {
180                                 PyErr_Print(); PyErr_Clear();
181                                 BPY_free_compiled_text( text );
182                                 PyGILState_Release(gilstate);
183                                 return 0;
184                         }
185                 }
186                 py_result =  PyEval_EvalCode( text->compiled, py_dict, py_dict );
187                 
188         } else {
189                 char pystring[512];
190                 /* TODO - look into a better way to run a file */
191                 sprintf(pystring, "exec(open(r'%s').read())", fn);      
192                 py_result = PyRun_String( pystring, Py_file_input, py_dict, py_dict );                  
193         }
194         
195         if (!py_result) {
196                 PyErr_Print(); PyErr_Clear();
197         } else {
198                 Py_DECREF( py_result );
199         }
200         
201         Py_DECREF(py_dict);
202         PyGILState_Release(gilstate);
203         
204         //BPY_end_python();
205         return py_result ? 1:0;
206 }
207
208
209 /* TODO - move into bpy_space.c ? */
210 /* GUI interface routines */
211
212 /* Copied from Draw.c */
213 static void exit_pydraw( SpaceScript * sc, short err )
214 {
215         Script *script = NULL;
216
217         if( !sc || !sc->script )
218                 return;
219
220         script = sc->script;
221
222         if( err ) {
223                 PyErr_Print(); PyErr_Clear();
224                 script->flags = 0;      /* mark script struct for deletion */
225                 SCRIPT_SET_NULL(script);
226                 script->scriptname[0] = '\0';
227                 script->scriptarg[0] = '\0';
228 // XXX 2.5              error_pyscript();
229 // XXX 2.5              scrarea_queue_redraw( sc->area );
230         }
231
232 #if 0 // XXX 2.5
233         BPy_Set_DrawButtonsList(sc->but_refs);
234         BPy_Free_DrawButtonsList(); /*clear all temp button references*/
235 #endif
236
237         sc->but_refs = NULL;
238         
239         Py_XDECREF( ( PyObject * ) script->py_draw );
240         Py_XDECREF( ( PyObject * ) script->py_event );
241         Py_XDECREF( ( PyObject * ) script->py_button );
242
243         script->py_draw = script->py_event = script->py_button = NULL;
244 }
245
246 static int bpy_run_script_init(bContext *C, SpaceScript * sc)
247 {
248         if (sc->script==NULL) 
249                 return 0;
250         
251         if (sc->script->py_draw==NULL && sc->script->scriptname[0] != '\0')
252                 BPY_run_python_script(C, sc->script->scriptname, NULL);
253                 
254         if (sc->script->py_draw==NULL)
255                 return 0;
256         
257         return 1;
258 }
259
260 int BPY_run_script_space_draw(struct bContext *C, SpaceScript * sc)
261 {
262         if (bpy_run_script_init(C, sc)) {
263                 PyGILState_STATE gilstate = PyGILState_Ensure();
264                 PyObject *result = PyObject_CallObject( sc->script->py_draw, NULL );
265                 
266                 if (result==NULL)
267                         exit_pydraw(sc, 1);
268                         
269                 PyGILState_Release(gilstate);
270         }
271         return 1;
272 }
273
274 // XXX - not used yet, listeners dont get a context
275 int BPY_run_script_space_listener(bContext *C, SpaceScript * sc)
276 {
277         if (bpy_run_script_init(C, sc)) {
278                 PyGILState_STATE gilstate = PyGILState_Ensure();
279                 
280                 PyObject *result = PyObject_CallObject( sc->script->py_draw, NULL );
281                 
282                 if (result==NULL)
283                         exit_pydraw(sc, 1);
284                         
285                 PyGILState_Release(gilstate);
286         }
287         return 1;
288 }
289
290 void BPY_DECREF(void *pyob_ptr)
291 {
292         Py_DECREF((PyObject *)pyob_ptr);
293 }
294
295 #if 0
296 /* called from the the scripts window, assume context is ok */
297 int BPY_run_python_script_space(const char *modulename, const char *func)
298 {
299         PyObject *py_dict, *py_result= NULL;
300         char pystring[512];
301         PyGILState_STATE gilstate;
302         
303         /* for calling the module function */
304         PyObject *py_func, 
305         
306         gilstate = PyGILState_Ensure();
307         
308         py_dict = CreateGlobalDictionary(C);
309         
310         PyObject *module = PyImport_ImportModule(scpt->script.filename);
311         if (module==NULL) {
312                 PyErr_SetFormat(PyExc_SystemError, "could not import '%s'", scpt->script.filename);
313         }
314         else {
315                 py_func = PyObject_GetAttrString(modulename, func);
316                 if (py_func==NULL) {
317                         PyErr_SetFormat(PyExc_SystemError, "module has no function '%s.%s'\n", scpt->script.filename, func);
318                 }
319                 else {
320                         Py_DECREF(py_func);
321                         if (!PyCallable_Check(py_func)) {
322                                 PyErr_SetFormat(PyExc_SystemError, "module item is not callable '%s.%s'\n", scpt->script.filename, func);
323                         }
324                         else {
325                                 py_result= PyObject_CallObject(py_func, NULL); // XXX will need args eventually
326                         }
327                 }
328         }
329         
330         if (!py_result) {
331                 PyErr_Print(); PyErr_Clear();
332         } else
333                 Py_DECREF( py_result );
334         
335         Py_XDECREF(module);
336         
337         Py_DECREF(py_dict);
338         
339         PyGILState_Release(gilstate);
340         return 1;
341 }
342 #endif
343
344 // #define TIME_REGISTRATION
345
346 #ifdef TIME_REGISTRATION
347 #include "PIL_time.h"
348 #endif
349
350 /* XXX this is temporary, need a proper script registration system for 2.5 */
351 void BPY_run_ui_scripts(bContext *C, int reload)
352 {
353 #ifdef TIME_REGISTRATION
354         double time = PIL_check_seconds_timer();
355 #endif
356         DIR *dir; 
357         struct dirent *de;
358         char *file_extension;
359         char path[FILE_MAX];
360         char *dirname= BLI_gethome_folder("ui");
361         int filelen; /* filename length */
362         
363         PyGILState_STATE gilstate;
364         PyObject *mod;
365         PyObject *sys_path_orig;
366         PyObject *sys_path_new;
367         
368         if(!dirname)
369                 return;
370         
371         dir = opendir(dirname);
372
373         if(!dir)
374                 return;
375         
376         gilstate = PyGILState_Ensure();
377         
378         /* backup sys.path */
379         sys_path_orig= PySys_GetObject("path");
380         Py_INCREF(sys_path_orig); /* dont free it */
381         
382         sys_path_new= PyList_New(1);
383         PyList_SET_ITEM(sys_path_new, 0, PyUnicode_FromString(dirname));
384         PySys_SetObject("path", sys_path_new);
385         Py_DECREF(sys_path_new);
386         
387         // XXX - evil, need to access context
388         BPy_SetContext(C);
389         
390         while((de = readdir(dir)) != NULL) {
391                 /* We could stat the file but easier just to let python
392                  * import it and complain if theres a problem */
393                 
394                 file_extension = strstr(de->d_name, ".py");
395                 
396                 if(file_extension && *(file_extension + 3) == '\0') {
397                         filelen = strlen(de->d_name);
398                         BLI_strncpy(path, de->d_name, filelen-2); /* cut off the .py on copy */
399                         
400                         mod= PyImport_ImportModuleLevel(path, NULL, NULL, NULL, 0);
401                         if (mod) {
402                                 if (reload) {
403                                         PyObject *mod_orig= mod;
404                                         mod= PyImport_ReloadModule(mod);
405                                         Py_DECREF(mod_orig);
406                                 }
407                         }
408                         
409                         if(mod) {
410                                 Py_DECREF(mod); /* could be NULL from reloading */
411                         } else {
412                                 PyErr_Print(); PyErr_Clear();
413                                 fprintf(stderr, "unable to import \"%s\"  %s/%s\n", path, dirname, de->d_name);
414                         }
415                 }
416         }
417
418         closedir(dir);
419         
420         PySys_SetObject("path", sys_path_orig);
421         Py_DECREF(sys_path_orig);
422         
423         PyGILState_Release(gilstate);
424 #ifdef TIME_REGISTRATION
425         printf("script time %f\n", (PIL_check_seconds_timer()-time));
426 #endif
427 }
428
429 /* ****************************************** */
430 /* Drivers - PyExpression Evaluation */
431
432 /* for pydrivers (drivers using one-line Python expressions to express relationships between targets) */
433 PyObject *bpy_pydriver_Dict = NULL;
434
435 /* For faster execution we keep a special dictionary for pydrivers, with
436  * the needed modules and aliases. 
437  */
438 static int bpy_pydriver_create_dict(void)
439 {
440         PyObject *d, *mod;
441         
442         /* validate namespace for driver evaluation */
443         if (bpy_pydriver_Dict) return -1;
444
445         d = PyDict_New();
446         if (d == NULL) 
447                 return -1;
448         else
449                 bpy_pydriver_Dict = d;
450
451         /* import some modules: builtins, bpy, math, (Blender.noise )*/
452         PyDict_SetItemString(d, "__builtins__", PyEval_GetBuiltins());
453
454         mod = PyImport_ImportModule("math");
455         if (mod) {
456                 PyDict_Merge(d, PyModule_GetDict(mod), 0); /* 0 - dont overwrite existing values */
457                 
458                 /* Only keep for backwards compat! - just import all math into root, they are standard */
459                 PyDict_SetItemString(d, "math", mod);
460                 PyDict_SetItemString(d, "m", mod);
461                 Py_DECREF(mod);
462         } 
463         
464         /* add bpy to global namespace */
465         mod= PyImport_ImportModuleLevel("bpy", NULL, NULL, NULL, 0);
466         if (mod) {
467                 PyDict_SetItemString(bpy_pydriver_Dict, "bpy", mod);
468                 Py_DECREF(mod);
469         }
470         
471         
472 #if 0 // non existant yet
473         mod = PyImport_ImportModule("Blender.Noise");
474         if (mod) {
475                 PyDict_SetItemString(d, "noise", mod);
476                 PyDict_SetItemString(d, "n", mod);
477                 Py_DECREF(mod);
478         } else {
479                 PyErr_Clear();
480         }
481         
482         /* If there's a Blender text called pydrivers.py, import it.
483          * Users can add their own functions to this module. 
484          */
485         if (G.f & G_DOSCRIPTLINKS) {
486                 mod = importText("pydrivers"); /* can also use PyImport_Import() */
487                 if (mod) {
488                         PyDict_SetItemString(d, "pydrivers", mod);
489                         PyDict_SetItemString(d, "p", mod);
490                         Py_DECREF(mod);
491                 } else {
492                         PyErr_Clear();
493                 }
494         }
495 #endif // non existant yet
496         
497         return 0;
498 }
499
500 /* Update function, it gets rid of pydrivers global dictionary, forcing
501  * BPY_pydriver_eval to recreate it. This function is used to force
502  * reloading the Blender text module "pydrivers.py", if available, so
503  * updates in it reach pydriver evaluation. 
504  */
505 void BPY_pydriver_update(void)
506 {
507         PyGILState_STATE gilstate = PyGILState_Ensure();
508
509         if (bpy_pydriver_Dict) { /* free the global dict used by pydrivers */
510                 PyDict_Clear(bpy_pydriver_Dict);
511                 Py_DECREF(bpy_pydriver_Dict);
512                 bpy_pydriver_Dict = NULL;
513         }
514
515         PyGILState_Release(gilstate);
516
517         return;
518 }
519
520 /* error return function for BPY_eval_pydriver */
521 static float pydriver_error(ChannelDriver *driver) 
522 {
523         if (bpy_pydriver_Dict) { /* free the global dict used by pydrivers */
524                 PyDict_Clear(bpy_pydriver_Dict);
525                 Py_DECREF(bpy_pydriver_Dict);
526                 bpy_pydriver_Dict = NULL;
527         }
528
529         driver->flag |= DRIVER_FLAG_INVALID; /* py expression failed */
530         fprintf(stderr, "\nError in Driver: The following Python expression failed:\n\t'%s'\n\n", driver->expression);
531         
532         PyErr_Print(); PyErr_Clear();
533
534         return 0.0f;
535 }
536
537 /* This evals py driver expressions, 'expr' is a Python expression that
538  * should evaluate to a float number, which is returned. 
539  */
540 float BPY_pydriver_eval (ChannelDriver *driver)
541 {
542         PyObject *driver_vars=NULL;
543         PyObject *retval;
544         PyGILState_STATE gilstate;
545         
546         DriverTarget *dtar;
547         float result = 0.0f; /* default return */
548         char *expr = NULL;
549         short targets_ok= 1;
550         
551         /* sanity checks - should driver be executed? */
552         if ((driver == NULL) /*|| (G.f & G_DOSCRIPTLINKS)==0*/) 
553                 return result;
554         
555         /* get the py expression to be evaluated */
556         expr = driver->expression; 
557         if ((expr == NULL) || (expr[0]=='\0')) 
558                 return result;
559
560         gilstate = PyGILState_Ensure();
561         
562         /* init global dictionary for py-driver evaluation settings */
563         if (!bpy_pydriver_Dict) {
564                 if (bpy_pydriver_create_dict() != 0) {
565                         fprintf(stderr, "Pydriver error: couldn't create Python dictionary");
566                         PyGILState_Release(gilstate);
567                         return result;
568                 }
569         }
570         
571         /* add target values to a dict that will be used as '__locals__' dict */
572         driver_vars = PyDict_New(); // XXX do we need to decref this?
573         for (dtar= driver->targets.first; dtar; dtar= dtar->next) {
574                 PyObject *driver_arg = NULL;
575                 float tval = 0.0f;
576                 
577                 /* try to get variable value */
578                 tval= driver_get_target_value(driver, dtar);
579                 driver_arg= PyFloat_FromDouble((double)tval);
580                 
581                 /* try to add to dictionary */
582                 if (PyDict_SetItemString(driver_vars, dtar->name, driver_arg)) {
583                         /* this target failed - bad name */
584                         if (targets_ok) {
585                                 /* first one - print some extra info for easier identification */
586                                 fprintf(stderr, "\nBPY_pydriver_eval() - Error while evaluating PyDriver:\n");
587                                 targets_ok= 0;
588                         }
589                         
590                         fprintf(stderr, "\tBPY_pydriver_eval() - couldn't add variable '%s' to namespace \n", dtar->name);
591                         PyErr_Print(); PyErr_Clear();
592                 }
593         }
594         
595         /* execute expression to get a value */
596         retval = PyRun_String(expr, Py_eval_input, bpy_pydriver_Dict, driver_vars);
597         
598         /* decref the driver vars first...  */
599         Py_DECREF(driver_vars);
600         
601         /* process the result */
602         if (retval == NULL) {
603                 result = pydriver_error(driver);
604                 PyGILState_Release(gilstate);
605                 return result;
606         }
607
608         result = (float)PyFloat_AsDouble(retval);
609         Py_DECREF(retval);
610         
611         if ((result == -1) && PyErr_Occurred()) {
612                 result = pydriver_error(driver);
613                 PyGILState_Release(gilstate);
614                 return result;
615         }
616         
617         /* all fine, make sure the "invalid expression" flag is cleared */
618         driver->flag &= ~DRIVER_FLAG_INVALID;
619
620         PyGILState_Release(gilstate);
621
622         return result;
623 }