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