ob.getChilren() often requested for 2.4x api, notice this is only 1 line of python.
[blender-staging.git] / source / blender / python / intern / bpy_interface.c
1 /**
2  * $Id:
3  *
4  * ***** BEGIN GPL LICENSE BLOCK *****
5  *
6  * This program is free software; you can redistribute it and/or
7  * modify it under the terms of the GNU General Public License
8  * as published by the Free Software Foundation; either version 2
9  * of the License, or (at your option) any later version.
10  *
11  * This program is distributed in the hope that it will be useful,
12  * but WITHOUT ANY WARRANTY; without even the implied warranty of
13  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
14  * GNU General Public License for more details.
15  *
16  * You should have received a copy of the GNU General Public License
17  * along with this program; if not, write to the Free Software Foundation,
18  * Inc., 59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.
19  *
20  * Contributor(s): Michel Selten, Willian P. Germano, Stephen Swaney,
21  * Chris Keith, Chris Want, Ken Hughes, Campbell Barton
22  *
23  * ***** END GPL LICENSE BLOCK *****
24  */
25  
26 #include <stdio.h>
27 #include <stdlib.h>
28 #include <string.h>
29 #include <sys/stat.h>
30
31
32 /* grr, python redefines */
33 #ifdef _POSIX_C_SOURCE
34 #undef _POSIX_C_SOURCE
35 #endif
36
37 #include <Python.h>
38 #include "compile.h"            /* for the PyCodeObject */
39 #include "eval.h"               /* for PyEval_EvalCode */
40
41 #include "bpy_rna.h"
42 #include "bpy_operator.h"
43 #include "bpy_ui.h"
44 #include "bpy_util.h"
45
46 #ifndef WIN32
47 #include <dirent.h>
48 #else
49 #include "BLI_winstuff.h"
50 #endif
51
52 #include "DNA_anim_types.h"
53 #include "DNA_space_types.h"
54 #include "DNA_text_types.h"
55
56 #include "MEM_guardedalloc.h"
57
58 #include "BLI_util.h"
59 #include "BLI_storage.h"
60 #include "BLI_fileops.h"
61 #include "BLI_string.h"
62
63 #include "BKE_context.h"
64 #include "BKE_fcurve.h"
65 #include "BKE_text.h"
66
67 #include "BPY_extern.h"
68
69 #include "../generic/bpy_internal_import.h" // our own imports
70 /* external util modules */
71
72 #include "../generic/Mathutils.h"
73 #include "../generic/Geometry.h"
74 #include "../generic/BGL.h"
75
76
77 /* for internal use, when starting and ending python scripts */
78
79 /* incase a python script triggers another python call, stop bpy_context_clear from invalidating */
80 static int py_call_level= 0;
81
82
83 // only for tests
84 #define TIME_PY_RUN
85
86 #ifdef TIME_PY_RUN
87 #include "PIL_time.h"
88 static int              bpy_timer_count = 0;
89 static double   bpy_timer; /* time since python starts */
90 static double   bpy_timer_run; /* time for each python script run */
91 static double   bpy_timer_run_tot; /* accumulate python runs */
92 #endif
93
94 void bpy_context_set(bContext *C, PyGILState_STATE *gilstate)
95 {
96         py_call_level++;
97
98         if(gilstate)
99                 *gilstate = PyGILState_Ensure();
100
101         if(py_call_level==1) {
102
103                 BPY_update_modules(); /* can give really bad results if this isnt here */
104
105                 if(C) { // XXX - should always be true.
106                         BPy_SetContext(C);
107                         bpy_import_main_set(CTX_data_main(C));
108                 }
109                 else {
110                         fprintf(stderr, "ERROR: Python context called with a NULL Context. this should not happen!\n");
111                 }
112
113 #ifdef TIME_PY_RUN
114                 if(bpy_timer_count==0) {
115                         /* record time from the beginning */
116                         bpy_timer= PIL_check_seconds_timer();
117                         bpy_timer_run = bpy_timer_run_tot = 0.0;
118                 }
119                 bpy_timer_run= PIL_check_seconds_timer();
120
121
122                 bpy_timer_count++;
123 #endif
124         }
125 }
126
127 void bpy_context_clear(bContext *C, PyGILState_STATE *gilstate)
128 {
129         py_call_level--;
130
131         if(gilstate)
132                 PyGILState_Release(*gilstate);
133
134         if(py_call_level < 0) {
135                 fprintf(stderr, "ERROR: Python context internal state bug. this should not happen!\n");
136         }
137         else if(py_call_level==0) {
138                 // XXX - Calling classes currently wont store the context :\, cant set NULL because of this. but this is very flakey still.
139                 //BPy_SetContext(NULL);
140                 //bpy_import_main_set(NULL);
141
142 #ifdef TIME_PY_RUN
143                 bpy_timer_run_tot += PIL_check_seconds_timer() - bpy_timer_run;
144                 bpy_timer_count++;
145 #endif
146
147         }
148 }
149
150 static void bpy_import_test(char *modname)
151 {
152         PyObject *mod= PyImport_ImportModuleLevel(modname, NULL, NULL, NULL, 0);
153         if(mod) {
154                 Py_DECREF(mod);
155         }
156         else {
157                 PyErr_Print();
158                 PyErr_Clear();
159         }       
160 }
161
162 void BPY_free_compiled_text( struct Text *text )
163 {
164         if( text->compiled ) {
165                 Py_DECREF( ( PyObject * ) text->compiled );
166                 text->compiled = NULL;
167         }
168 }
169
170 /*****************************************************************************
171 * Description: Creates the bpy module and adds it to sys.modules for importing
172 *****************************************************************************/
173 static void bpy_init_modules( void )
174 {
175         PyObject *mod;
176         
177         mod = PyModule_New("bpy");
178         
179         PyModule_AddObject( mod, "data", BPY_rna_module() );
180         /* PyModule_AddObject( mod, "doc", BPY_rna_doc() ); */
181         PyModule_AddObject( mod, "types", BPY_rna_types() );
182         PyModule_AddObject( mod, "props", BPY_rna_props() );
183         PyModule_AddObject( mod, "__ops__", BPY_operator_module() ); /* ops is now a python module that does the conversion from SOME_OT_foo -> some.foo */
184         PyModule_AddObject( mod, "ui", BPY_ui_module() ); // XXX very experimental, consider this a test, especially PyCObject is not meant to be permanent
185         
186         /* add the module so we can import it */
187         PyDict_SetItemString(PySys_GetObject("modules"), "bpy", mod);
188         Py_DECREF(mod);
189
190         /* add our own modules dir */
191         {
192                 char *modpath= BLI_gethome_folder("scripts/modules", BLI_GETHOME_ALL);
193                 
194                 if(modpath) {
195                         PyObject *sys_path= PySys_GetObject("path"); /* borrow */
196                         PyObject *py_modpath= PyUnicode_FromString(modpath);
197                         PyList_Insert(sys_path, 0, py_modpath); /* add first */
198                         Py_DECREF(py_modpath);
199                 }
200                 
201                 bpy_import_test("bpy_ops"); /* adds its self to bpy.ops */
202                 bpy_import_test("bpy_sys"); /* adds its self to bpy.sys */
203                 bpy_import_test("bpy_ext"); /* extensions to our existing types */
204         }
205         
206         /* stand alone utility modules not related to blender directly */
207         Geometry_Init();
208         Mathutils_Init();
209         BGL_Init();
210 }
211
212 void BPY_update_modules( void )
213 {
214 #if 0 // slow, this runs all the time poll, draw etc 100's of time a sec.
215         PyObject *mod= PyImport_ImportModuleLevel("bpy", NULL, NULL, NULL, 0);
216         PyModule_AddObject( mod, "data", BPY_rna_module() );
217         PyModule_AddObject( mod, "types", BPY_rna_types() ); // atm this does not need updating
218 #endif
219
220         /* refreshes the main struct */
221         BPY_update_rna_module();
222
223 }
224
225 /*****************************************************************************
226 * Description: This function creates a new Python dictionary object.
227 *****************************************************************************/
228 static PyObject *CreateGlobalDictionary( bContext *C )
229 {
230         PyObject *mod;
231         PyObject *dict = PyDict_New(  );
232         PyObject *item = PyUnicode_FromString( "__main__" );
233         PyDict_SetItemString( dict, "__builtins__", PyEval_GetBuiltins(  ) );
234         PyDict_SetItemString( dict, "__name__", item );
235         Py_DECREF(item);
236         
237         // XXX - put somewhere more logical
238         {
239                 PyMethodDef *ml;
240                 static PyMethodDef bpy_prop_meths[] = {
241                         {"FloatProperty", (PyCFunction)BPy_FloatProperty, METH_VARARGS|METH_KEYWORDS, ""},
242                         {"IntProperty", (PyCFunction)BPy_IntProperty, METH_VARARGS|METH_KEYWORDS, ""},
243                         {"BoolProperty", (PyCFunction)BPy_BoolProperty, METH_VARARGS|METH_KEYWORDS, ""},
244                         {"StringProperty", (PyCFunction)BPy_StringProperty, METH_VARARGS|METH_KEYWORDS, ""},
245                         {"EnumProperty", (PyCFunction)BPy_EnumProperty, METH_VARARGS|METH_KEYWORDS, ""},
246                         {"PointerProperty", (PyCFunction)BPy_PointerProperty, METH_VARARGS|METH_KEYWORDS, ""},
247                         {"CollectionProperty", (PyCFunction)BPy_CollectionProperty, METH_VARARGS|METH_KEYWORDS, ""},
248                         {NULL, NULL, 0, NULL}
249                 };
250                 
251                 for(ml = bpy_prop_meths; ml->ml_name; ml++) {
252                         PyDict_SetItemString( dict, ml->ml_name, PyCFunction_New(ml, NULL));
253                 }
254         }
255         
256         /* add bpy to global namespace */
257         mod= PyImport_ImportModuleLevel("bpy", NULL, NULL, NULL, 0);
258         PyDict_SetItemString( dict, "bpy", mod );
259         Py_DECREF(mod);
260         
261         return dict;
262 }
263
264 /* must be called before Py_Initialize */
265 void BPY_start_python_path(void)
266 {
267         char *py_path_bundle= BLI_gethome_folder("python", BLI_GETHOME_ALL);
268
269         if(py_path_bundle==NULL)
270                 return;
271
272         /* set the environment path */
273         printf("found bundled python: %s\n", py_path_bundle);
274
275 #if 0
276         BLI_setenv("PYTHONHOME", py_path_bundle);
277         BLI_setenv("PYTHONPATH", py_path_bundle);
278 #endif
279
280         {
281                 static wchar_t py_path_bundle_wchar[FILE_MAXDIR];
282
283                 mbstowcs(py_path_bundle_wchar, py_path_bundle, FILE_MAXDIR);
284                 Py_SetPythonHome(py_path_bundle_wchar);
285         }
286 }
287
288
289 void BPY_start_python( int argc, char **argv )
290 {
291         PyThreadState *py_tstate = NULL;
292         
293         BPY_start_python_path(); /* allow to use our own included python */
294
295         Py_Initialize(  );
296         
297         // PySys_SetArgv( argc, argv); // broken in py3, not a huge deal
298         /* sigh, why do python guys not have a char** version anymore? :( */
299         {
300                 int i;
301                 PyObject *py_argv= PyList_New(argc);
302
303                 for (i=0; i<argc; i++)
304                         PyList_SET_ITEM(py_argv, i, PyUnicode_FromString(argv[i]));
305
306                 PySys_SetObject("argv", py_argv);
307                 Py_DECREF(py_argv);
308         }
309         
310         /* Initialize thread support (also acquires lock) */
311         PyEval_InitThreads();
312         
313         
314         /* bpy.* and lets us import it */
315         bpy_init_modules(); 
316
317         { /* our own import and reload functions */
318                 PyObject *item;
319                 //PyObject *m = PyImport_AddModule("__builtin__");
320                 //PyObject *d = PyModule_GetDict(m);
321                 PyObject *d = PyEval_GetBuiltins(  );
322                 PyDict_SetItemString(d, "reload",               item=PyCFunction_New(bpy_reload_meth, NULL));   Py_DECREF(item);
323                 PyDict_SetItemString(d, "__import__",   item=PyCFunction_New(bpy_import_meth, NULL));   Py_DECREF(item);
324                 
325                 /* a bit nasty but this prevents help() and input() from locking blender
326                  * Ideally we could have some way for the console to replace sys.stdin but
327                  * python would lock blender while waiting for a return value, not easy :| */
328                 PySys_SetObject("stdin", Py_None);
329         }
330         
331         pyrna_alloc_types();
332
333         py_tstate = PyGILState_GetThisThreadState();
334         PyEval_ReleaseThread(py_tstate);
335 }
336
337 void BPY_end_python( void )
338 {
339         // fprintf(stderr, "Ending Python!\n");
340
341         PyGILState_Ensure(); /* finalizing, no need to grab the state */
342         
343         // free other python data.
344         pyrna_free_types();
345
346         /* clear all python data from structs */
347         
348         Py_Finalize(  );
349         
350 #ifdef TIME_PY_RUN
351         // measure time since py started
352         bpy_timer = PIL_check_seconds_timer() - bpy_timer;
353
354         printf("*bpy stats* - ");
355         printf("tot exec: %d,  ", bpy_timer_count);
356         printf("tot run: %.4fsec,  ", bpy_timer_run_tot);
357         if(bpy_timer_count>0)
358                 printf("average run: %.6fsec,  ", (bpy_timer_run_tot/bpy_timer_count));
359
360         if(bpy_timer>0.0)
361                 printf("tot usage %.4f%%", (bpy_timer_run_tot/bpy_timer)*100.0);
362
363         printf("\n");
364
365         // fprintf(stderr, "Ending Python Done!\n");
366
367 #endif
368
369 }
370
371 /* Can run a file or text block */
372 int BPY_run_python_script( bContext *C, const char *fn, struct Text *text, struct ReportList *reports)
373 {
374         PyObject *py_dict, *py_result= NULL;
375         PyGILState_STATE gilstate;
376         
377         if (fn==NULL && text==NULL) {
378                 return 0;
379         }
380         
381         bpy_context_set(C, &gilstate);
382         
383         py_dict = CreateGlobalDictionary(C);
384
385         if (text) {
386                 
387                 if( !text->compiled ) { /* if it wasn't already compiled, do it now */
388                         char *buf = txt_to_buf( text );
389
390                         text->compiled =
391                                 Py_CompileString( buf, text->id.name+2, Py_file_input );
392
393                         MEM_freeN( buf );
394
395                         if( PyErr_Occurred(  ) ) {
396                                 BPY_free_compiled_text( text );
397                         }
398                 }
399                 if(text->compiled)
400                         py_result =  PyEval_EvalCode( text->compiled, py_dict, py_dict );
401                 
402         } else {
403 #if 0
404                 char *pystring;
405                 pystring= malloc(strlen(fn) + 32);
406                 pystring[0]= '\0';
407                 sprintf(pystring, "exec(open(r'%s').read())", fn);
408                 py_result = PyRun_String( pystring, Py_file_input, py_dict, py_dict );
409                 free(pystring);
410 #else
411                 FILE *fp= fopen(fn, "r");               
412                 if(fp) {
413                         py_result = PyRun_File(fp, fn, Py_file_input, py_dict, py_dict);
414                         fclose(fp);
415                 }
416                 else {
417                         PyErr_Format(PyExc_SystemError, "Python file \"%s\" could not be opened: %s", fn, strerror(errno));
418                         py_result= NULL;
419                 }
420 #endif
421         }
422         
423         if (!py_result) {
424                 BPy_errors_to_report(reports);
425         } else {
426                 Py_DECREF( py_result );
427         }
428         
429         Py_DECREF(py_dict);
430         
431         bpy_context_clear(C, &gilstate);
432
433         return py_result ? 1:0;
434 }
435
436
437 /* TODO - move into bpy_space.c ? */
438 /* GUI interface routines */
439
440 /* Copied from Draw.c */
441 static void exit_pydraw( SpaceScript * sc, short err )
442 {
443         Script *script = NULL;
444
445         if( !sc || !sc->script )
446                 return;
447
448         script = sc->script;
449
450         if( err ) {
451                 BPy_errors_to_report(NULL); // TODO, reports
452                 script->flags = 0;      /* mark script struct for deletion */
453                 SCRIPT_SET_NULL(script);
454                 script->scriptname[0] = '\0';
455                 script->scriptarg[0] = '\0';
456 // XXX 2.5              error_pyscript();
457 // XXX 2.5              scrarea_queue_redraw( sc->area );
458         }
459
460 #if 0 // XXX 2.5
461         BPy_Set_DrawButtonsList(sc->but_refs);
462         BPy_Free_DrawButtonsList(); /*clear all temp button references*/
463 #endif
464
465         sc->but_refs = NULL;
466         
467         Py_XDECREF( ( PyObject * ) script->py_draw );
468         Py_XDECREF( ( PyObject * ) script->py_event );
469         Py_XDECREF( ( PyObject * ) script->py_button );
470
471         script->py_draw = script->py_event = script->py_button = NULL;
472 }
473
474 static int bpy_run_script_init(bContext *C, SpaceScript * sc)
475 {
476         if (sc->script==NULL) 
477                 return 0;
478         
479         if (sc->script->py_draw==NULL && sc->script->scriptname[0] != '\0')
480                 BPY_run_python_script(C, sc->script->scriptname, NULL, NULL);
481                 
482         if (sc->script->py_draw==NULL)
483                 return 0;
484         
485         return 1;
486 }
487
488 int BPY_run_script_space_draw(const struct bContext *C, SpaceScript * sc)
489 {
490         if (bpy_run_script_init( (bContext *)C, sc)) {
491                 PyGILState_STATE gilstate = PyGILState_Ensure();
492                 PyObject *result = PyObject_CallObject( sc->script->py_draw, NULL );
493                 
494                 if (result==NULL)
495                         exit_pydraw(sc, 1);
496                         
497                 PyGILState_Release(gilstate);
498         }
499         return 1;
500 }
501
502 // XXX - not used yet, listeners dont get a context
503 int BPY_run_script_space_listener(bContext *C, SpaceScript * sc)
504 {
505         if (bpy_run_script_init(C, sc)) {
506                 PyGILState_STATE gilstate = PyGILState_Ensure();
507                 
508                 PyObject *result = PyObject_CallObject( sc->script->py_draw, NULL );
509                 
510                 if (result==NULL)
511                         exit_pydraw(sc, 1);
512                         
513                 PyGILState_Release(gilstate);
514         }
515         return 1;
516 }
517
518 void BPY_DECREF(void *pyob_ptr)
519 {
520         Py_DECREF((PyObject *)pyob_ptr);
521 }
522
523 #if 0
524 /* called from the the scripts window, assume context is ok */
525 int BPY_run_python_script_space(const char *modulename, const char *func)
526 {
527         PyObject *py_dict, *py_result= NULL;
528         char pystring[512];
529         PyGILState_STATE gilstate;
530         
531         /* for calling the module function */
532         PyObject *py_func, 
533         
534         gilstate = PyGILState_Ensure();
535         
536         py_dict = CreateGlobalDictionary(C);
537         
538         PyObject *module = PyImport_ImportModule(scpt->script.filename);
539         if (module==NULL) {
540                 PyErr_SetFormat(PyExc_SystemError, "could not import '%s'", scpt->script.filename);
541         }
542         else {
543                 py_func = PyObject_GetAttrString(modulename, func);
544                 if (py_func==NULL) {
545                         PyErr_SetFormat(PyExc_SystemError, "module has no function '%s.%s'\n", scpt->script.filename, func);
546                 }
547                 else {
548                         Py_DECREF(py_func);
549                         if (!PyCallable_Check(py_func)) {
550                                 PyErr_SetFormat(PyExc_SystemError, "module item is not callable '%s.%s'\n", scpt->script.filename, func);
551                         }
552                         else {
553                                 py_result= PyObject_CallObject(py_func, NULL); // XXX will need args eventually
554                         }
555                 }
556         }
557         
558         if (!py_result) {
559                 BPy_errors_to_report(NULL); // TODO - reports
560         } else
561                 Py_DECREF( py_result );
562         
563         Py_XDECREF(module);
564         
565         Py_DECREF(py_dict);
566         
567         PyGILState_Release(gilstate);
568         return 1;
569 }
570 #endif
571
572 // #define TIME_REGISTRATION
573
574 #ifdef TIME_REGISTRATION
575 #include "PIL_time.h"
576 #endif
577
578 /* for use by BPY_run_ui_scripts only */
579 static int bpy_import_module(char *modname, int reload)
580 {
581         PyObject *mod= PyImport_ImportModuleLevel(modname, NULL, NULL, NULL, 0);
582         if (mod) {
583                 if (reload) {
584                         PyObject *mod_orig= mod;
585                         mod= PyImport_ReloadModule(mod);
586                         Py_DECREF(mod_orig);
587                 }
588         }
589
590         if(mod) {
591                 Py_DECREF(mod); /* could be NULL from reloading */
592                 return 0;
593         } else {
594                 return -1;
595         }
596 }
597
598 /* XXX this is temporary, need a proper script registration system for 2.5 */
599 void BPY_run_ui_scripts(bContext *C, int reload)
600 {
601 #ifdef TIME_REGISTRATION
602         double time = PIL_check_seconds_timer();
603 #endif
604         DIR *dir; 
605         struct dirent *de;
606         char *file_extension;
607         char *dirname;
608         char path[FILE_MAX];
609         char *dirs[] = {"scripts/ui", "scripts/io", NULL};
610         int path_flags[] = {BLI_GETHOME_LOCAL|BLI_GETHOME_SYSTEM, BLI_GETHOME_USER}; /* SYSTEM / NON-SYSTEM */
611         int a, err, flag_iter;
612         
613         PyGILState_STATE gilstate;
614         PyObject *sys_path;
615
616         bpy_context_set(C, &gilstate);
617
618         sys_path= PySys_GetObject("path"); /* borrow */
619         PyList_Insert(sys_path, 0, Py_None); /* place holder, resizes the list */
620
621         /* Scan system scripts first, then local/user */
622         for(flag_iter=0; flag_iter < sizeof(path_flags)/sizeof(int); flag_iter++) {
623                 
624                 for(a=0; dirs[a]; a++) {
625                         dirname= BLI_gethome_folder(dirs[a], path_flags[flag_iter]);
626
627                         if(!dirname)
628                                 continue;
629
630                         dir = opendir(dirname);
631
632                         if(!dir)
633                                 continue;
634                         
635                         /* set the first dir in the sys.path for fast importing of modules */
636                         PyList_SetItem(sys_path, 0, PyUnicode_FromString(dirname)); /* steals the ref */
637                                 
638                         while((de = readdir(dir)) != NULL) {
639                                 /* We could stat the file but easier just to let python
640                                  * import it and complain if theres a problem */
641                                 err = 0;
642
643                                 if (de->d_name[0] == '.') {
644                                         /* do nothing, probably .svn */
645                                 }
646                                 else if ((file_extension = strstr(de->d_name, ".py"))) {
647                                         /* normal py files? */
648                                         if(file_extension && file_extension[3] == '\0') {
649                                                 de->d_name[(file_extension - de->d_name)] = '\0';
650                                                 err= bpy_import_module(de->d_name, reload);
651                                         }
652                                 }
653 #ifndef __linux__
654                                 else if( BLI_join_dirfile(path, dirname, de->d_name), S_ISDIR(BLI_exist(path))) {
655 #else
656                                 else if(de->d_type==DT_DIR) {
657                                         BLI_join_dirfile(path, dirname, de->d_name);
658 #endif
659                                         /* support packages */
660                                         BLI_join_dirfile(path, path, "__init__.py");
661
662                                         if(BLI_exists(path)) {
663                                                 err= bpy_import_module(de->d_name, reload);
664                                         }
665                                 }
666
667                                 if(err==-1) {
668                                         BPy_errors_to_report(NULL);
669                                         fprintf(stderr, "unable to import %s/%s\n", dirname, de->d_name);
670                                 }
671                         }
672
673                         closedir(dir);
674                 }
675         }
676         
677         PyList_SetSlice(sys_path, 0, 1, NULL); /* remove the first item */
678
679         bpy_context_clear(C, &gilstate);
680         
681 #ifdef TIME_REGISTRATION
682         printf("script time %f\n", (PIL_check_seconds_timer()-time));
683 #endif
684
685         /* reset the timer so as not to take loading into the stats */
686         bpy_timer_count = 0;
687 }
688
689 /* ****************************************** */
690 /* Drivers - PyExpression Evaluation */
691
692 /* for pydrivers (drivers using one-line Python expressions to express relationships between targets) */
693 PyObject *bpy_pydriver_Dict = NULL;
694
695 /* For faster execution we keep a special dictionary for pydrivers, with
696  * the needed modules and aliases. 
697  */
698 static int bpy_pydriver_create_dict(void)
699 {
700         PyObject *d, *mod;
701         
702         /* validate namespace for driver evaluation */
703         if (bpy_pydriver_Dict) return -1;
704
705         d = PyDict_New();
706         if (d == NULL) 
707                 return -1;
708         else
709                 bpy_pydriver_Dict = d;
710
711         /* import some modules: builtins, bpy, math, (Blender.noise )*/
712         PyDict_SetItemString(d, "__builtins__", PyEval_GetBuiltins());
713
714         mod = PyImport_ImportModule("math");
715         if (mod) {
716                 PyDict_Merge(d, PyModule_GetDict(mod), 0); /* 0 - dont overwrite existing values */
717                 
718                 /* Only keep for backwards compat! - just import all math into root, they are standard */
719                 PyDict_SetItemString(d, "math", mod);
720                 PyDict_SetItemString(d, "m", mod);
721                 Py_DECREF(mod);
722         } 
723         
724         /* add bpy to global namespace */
725         mod= PyImport_ImportModuleLevel("bpy", NULL, NULL, NULL, 0);
726         if (mod) {
727                 PyDict_SetItemString(bpy_pydriver_Dict, "bpy", mod);
728                 Py_DECREF(mod);
729         }
730         
731         
732 #if 0 // non existant yet
733         mod = PyImport_ImportModule("Blender.Noise");
734         if (mod) {
735                 PyDict_SetItemString(d, "noise", mod);
736                 PyDict_SetItemString(d, "n", mod);
737                 Py_DECREF(mod);
738         } else {
739                 PyErr_Clear();
740         }
741         
742         /* If there's a Blender text called pydrivers.py, import it.
743          * Users can add their own functions to this module. 
744          */
745         if (G.f & G_DOSCRIPTLINKS) {
746                 mod = importText("pydrivers"); /* can also use PyImport_Import() */
747                 if (mod) {
748                         PyDict_SetItemString(d, "pydrivers", mod);
749                         PyDict_SetItemString(d, "p", mod);
750                         Py_DECREF(mod);
751                 } else {
752                         PyErr_Clear();
753                 }
754         }
755 #endif // non existant yet
756         
757         return 0;
758 }
759
760 /* Update function, it gets rid of pydrivers global dictionary, forcing
761  * BPY_pydriver_eval to recreate it. This function is used to force
762  * reloading the Blender text module "pydrivers.py", if available, so
763  * updates in it reach pydriver evaluation. 
764  */
765 void BPY_pydriver_update(void)
766 {
767         PyGILState_STATE gilstate = PyGILState_Ensure();
768
769         if (bpy_pydriver_Dict) { /* free the global dict used by pydrivers */
770                 PyDict_Clear(bpy_pydriver_Dict);
771                 Py_DECREF(bpy_pydriver_Dict);
772                 bpy_pydriver_Dict = NULL;
773         }
774
775         PyGILState_Release(gilstate);
776
777         return;
778 }
779
780 /* error return function for BPY_eval_pydriver */
781 static float pydriver_error(ChannelDriver *driver) 
782 {
783         if (bpy_pydriver_Dict) { /* free the global dict used by pydrivers */
784                 PyDict_Clear(bpy_pydriver_Dict);
785                 Py_DECREF(bpy_pydriver_Dict);
786                 bpy_pydriver_Dict = NULL;
787         }
788
789         driver->flag |= DRIVER_FLAG_INVALID; /* py expression failed */
790         fprintf(stderr, "\nError in Driver: The following Python expression failed:\n\t'%s'\n\n", driver->expression);
791         
792         BPy_errors_to_report(NULL); // TODO - reports
793
794         return 0.0f;
795 }
796
797 /* This evals py driver expressions, 'expr' is a Python expression that
798  * should evaluate to a float number, which is returned. 
799  */
800 float BPY_pydriver_eval (ChannelDriver *driver)
801 {
802         PyObject *driver_vars=NULL;
803         PyObject *retval;
804         PyGILState_STATE gilstate;
805         
806         DriverTarget *dtar;
807         float result = 0.0f; /* default return */
808         char *expr = NULL;
809         short targets_ok= 1;
810         
811         /* sanity checks - should driver be executed? */
812         if ((driver == NULL) /*|| (G.f & G_DOSCRIPTLINKS)==0*/) 
813                 return result;
814         
815         /* get the py expression to be evaluated */
816         expr = driver->expression; 
817         if ((expr == NULL) || (expr[0]=='\0')) 
818                 return result;
819
820         gilstate = PyGILState_Ensure();
821         
822         /* init global dictionary for py-driver evaluation settings */
823         if (!bpy_pydriver_Dict) {
824                 if (bpy_pydriver_create_dict() != 0) {
825                         fprintf(stderr, "Pydriver error: couldn't create Python dictionary");
826                         PyGILState_Release(gilstate);
827                         return result;
828                 }
829         }
830         
831         /* add target values to a dict that will be used as '__locals__' dict */
832         driver_vars = PyDict_New(); // XXX do we need to decref this?
833         for (dtar= driver->targets.first; dtar; dtar= dtar->next) {
834                 PyObject *driver_arg = NULL;
835                 float tval = 0.0f;
836                 
837                 /* try to get variable value */
838                 tval= driver_get_target_value(driver, dtar);
839                 driver_arg= PyFloat_FromDouble((double)tval);
840                 
841                 /* try to add to dictionary */
842                 if (PyDict_SetItemString(driver_vars, dtar->name, driver_arg)) {
843                         /* this target failed - bad name */
844                         if (targets_ok) {
845                                 /* first one - print some extra info for easier identification */
846                                 fprintf(stderr, "\nBPY_pydriver_eval() - Error while evaluating PyDriver:\n");
847                                 targets_ok= 0;
848                         }
849                         
850                         fprintf(stderr, "\tBPY_pydriver_eval() - couldn't add variable '%s' to namespace \n", dtar->name);
851                         BPy_errors_to_report(NULL); // TODO - reports
852                 }
853         }
854         
855         /* execute expression to get a value */
856         retval = PyRun_String(expr, Py_eval_input, bpy_pydriver_Dict, driver_vars);
857         
858         /* decref the driver vars first...  */
859         Py_DECREF(driver_vars);
860         
861         /* process the result */
862         if (retval == NULL) {
863                 result = pydriver_error(driver);
864                 PyGILState_Release(gilstate);
865                 return result;
866         }
867
868         result = (float)PyFloat_AsDouble(retval);
869         Py_DECREF(retval);
870         
871         if ((result == -1) && PyErr_Occurred()) {
872                 result = pydriver_error(driver);
873                 PyGILState_Release(gilstate);
874                 return result;
875         }
876         
877         /* all fine, make sure the "invalid expression" flag is cleared */
878         driver->flag &= ~DRIVER_FLAG_INVALID;
879
880         PyGILState_Release(gilstate);
881
882         return result;
883 }
884
885 int BPY_button_eval(bContext *C, char *expr, double *value)
886 {
887         PyGILState_STATE gilstate;
888         PyObject *dict, *mod, *retval;
889         int error_ret = 0;
890         
891         if (!value || !expr || expr[0]=='\0') return -1;
892         
893         bpy_context_set(C, &gilstate);
894         
895         dict= CreateGlobalDictionary(C);
896         
897         /* import some modules: builtins,math*/
898         PyDict_SetItemString(dict, "__builtins__", PyEval_GetBuiltins());
899
900         mod = PyImport_ImportModule("math");
901         if (mod) {
902                 PyDict_Merge(dict, PyModule_GetDict(mod), 0); /* 0 - dont overwrite existing values */
903                 
904                 /* Only keep for backwards compat! - just import all math into root, they are standard */
905                 PyDict_SetItemString(dict, "math", mod);
906                 PyDict_SetItemString(dict, "m", mod);
907                 Py_DECREF(mod);
908         } 
909         
910         retval = PyRun_String(expr, Py_eval_input, dict, dict);
911         
912         if (retval == NULL) {
913                 error_ret= -1;
914         }
915         else {
916                 double val;
917
918                 if(PyTuple_Check(retval)) {
919                         /* Users my have typed in 10km, 2m
920                          * add up all values */
921                         int i;
922                         val= 0.0;
923
924                         for(i=0; i<PyTuple_GET_SIZE(retval); i++) {
925                                 val+= PyFloat_AsDouble(PyTuple_GET_ITEM(retval, i));
926                         }
927                 }
928                 else {
929                         val = PyFloat_AsDouble(retval);
930                 }
931                 Py_DECREF(retval);
932                 
933                 if(val==-1 && PyErr_Occurred()) {
934                         error_ret= -1;
935                 }
936                 else {
937                         *value= val;
938                 }
939         }
940         
941         if(error_ret) {
942                 BPy_errors_to_report(CTX_wm_reports(C));
943         }
944         
945         Py_DECREF(dict);
946         bpy_context_clear(C, &gilstate);
947         
948         return error_ret;
949 }
950