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