remove python2.x support
[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_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         PyObject *mod= PyImport_ImportModuleLevel("bpy", NULL, NULL, NULL, 0);
158         PyModule_AddObject( mod, "data", BPY_rna_module() );
159         PyModule_AddObject( mod, "types", BPY_rna_types() );
160 }
161
162 /*****************************************************************************
163 * Description: This function creates a new Python dictionary object.
164 *****************************************************************************/
165 static PyObject *CreateGlobalDictionary( bContext *C )
166 {
167         PyObject *mod;
168         PyObject *dict = PyDict_New(  );
169         PyObject *item = PyUnicode_FromString( "__main__" );
170         PyDict_SetItemString( dict, "__builtins__", PyEval_GetBuiltins(  ) );
171         PyDict_SetItemString( dict, "__name__", item );
172         Py_DECREF(item);
173         
174         // XXX - put somewhere more logical
175         {
176                 PyMethodDef *ml;
177                 static PyMethodDef bpy_prop_meths[] = {
178                         {"FloatProperty", (PyCFunction)BPy_FloatProperty, METH_VARARGS|METH_KEYWORDS, ""},
179                         {"IntProperty", (PyCFunction)BPy_IntProperty, METH_VARARGS|METH_KEYWORDS, ""},
180                         {"BoolProperty", (PyCFunction)BPy_BoolProperty, METH_VARARGS|METH_KEYWORDS, ""},
181                         {"StringProperty", (PyCFunction)BPy_StringProperty, METH_VARARGS|METH_KEYWORDS, ""},
182                         {NULL, NULL, 0, NULL}
183                 };
184                 
185                 for(ml = bpy_prop_meths; ml->ml_name; ml++) {
186                         PyDict_SetItemString( dict, ml->ml_name, PyCFunction_New(ml, NULL));
187                 }
188         }
189         
190         /* add bpy to global namespace */
191         mod= PyImport_ImportModuleLevel("bpy", NULL, NULL, NULL, 0);
192         PyDict_SetItemString( dict, "bpy", mod );
193         Py_DECREF(mod);
194         
195         return dict;
196 }
197
198 /* Use this so we can include our own python bundle */
199 #if 0
200 wchar_t* Py_GetPath(void)
201 {
202         int i;
203         static wchar_t py_path[FILE_MAXDIR] = L"";
204         char *dirname= BLI_gethome_folder("python");
205         if(dirname) {
206                 i= mbstowcs(py_path, dirname, FILE_MAXDIR);
207                 printf("py path %s, %d\n", dirname, i);
208         }
209         return py_path;
210 }
211 #endif
212
213
214 /* must be called before Py_Initialize */
215 void BPY_start_python_path(void)
216 {
217         char *py_path_bundle= BLI_gethome_folder("python");
218
219         if(py_path_bundle==NULL)
220                 return;
221
222         /* set the environment path */
223         printf("found bundled python: %s\n", py_path_bundle);
224
225         BLI_setenv("PYTHONHOME", py_path_bundle);
226         BLI_setenv("PYTHONPATH", py_path_bundle);
227 }
228
229
230 void BPY_start_python( int argc, char **argv )
231 {
232         PyThreadState *py_tstate = NULL;
233         
234         BPY_start_python_path(); /* allow to use our own included python */
235
236         Py_Initialize(  );
237         
238         // PySys_SetArgv( argc, argv); // broken in py3, not a huge deal
239         /* sigh, why do python guys not have a char** version anymore? :( */
240         {
241                 int i;
242                 PyObject *py_argv= PyList_New(argc);
243
244                 for (i=0; i<argc; i++)
245                         PyList_SET_ITEM(py_argv, i, PyUnicode_FromString(argv[i]));
246
247                 PySys_SetObject("argv", py_argv);
248                 Py_DECREF(py_argv);
249         }
250         
251         /* Initialize thread support (also acquires lock) */
252         PyEval_InitThreads();
253         
254         
255         /* bpy.* and lets us import it */
256         bpy_init_modules(); 
257
258         { /* our own import and reload functions */
259                 PyObject *item;
260                 //PyObject *m = PyImport_AddModule("__builtin__");
261                 //PyObject *d = PyModule_GetDict(m);
262                 PyObject *d = PyEval_GetBuiltins(  );
263                 PyDict_SetItemString(d, "reload",               item=PyCFunction_New(bpy_reload_meth, NULL));   Py_DECREF(item);
264                 PyDict_SetItemString(d, "__import__",   item=PyCFunction_New(bpy_import_meth, NULL));   Py_DECREF(item);
265         }
266         
267         py_tstate = PyGILState_GetThisThreadState();
268         PyEval_ReleaseThread(py_tstate);
269 }
270
271 void BPY_end_python( void )
272 {
273         PyGILState_Ensure(); /* finalizing, no need to grab the state */
274         
275         // free other python data.
276         //BPY_rna_free_types();
277         
278         Py_Finalize(  );
279         
280 #ifdef TIME_PY_RUN
281         // measure time since py started
282         bpy_timer = PIL_check_seconds_timer() - bpy_timer;
283
284         printf("*bpy stats* - ");
285         printf("tot exec: %d,  ", bpy_timer_count);
286         printf("tot run: %.4fsec,  ", bpy_timer_run_tot);
287         if(bpy_timer_count>0)
288                 printf("average run: %.6fsec,  ", (bpy_timer_run_tot/bpy_timer_count));
289
290         if(bpy_timer>0.0)
291                 printf("tot usage %.4f%%", (bpy_timer_run_tot/bpy_timer)*100.0);
292
293         printf("\n");
294
295 #endif
296
297 }
298
299 /* Can run a file or text block */
300 int BPY_run_python_script( bContext *C, const char *fn, struct Text *text, struct ReportList *reports)
301 {
302         PyObject *py_dict, *py_result= NULL;
303         PyGILState_STATE gilstate;
304         
305         if (fn==NULL && text==NULL) {
306                 return 0;
307         }
308         
309         bpy_context_set(C, &gilstate);
310         
311         py_dict = CreateGlobalDictionary(C);
312
313         if (text) {
314                 
315                 if( !text->compiled ) { /* if it wasn't already compiled, do it now */
316                         char *buf = txt_to_buf( text );
317
318                         text->compiled =
319                                 Py_CompileString( buf, text->id.name+2, Py_file_input );
320
321                         MEM_freeN( buf );
322
323                         if( PyErr_Occurred(  ) ) {
324                                 BPY_free_compiled_text( text );
325                         }
326                 }
327                 if(text->compiled)
328                         py_result =  PyEval_EvalCode( text->compiled, py_dict, py_dict );
329                 
330         } else {
331 #if 0
332                 char *pystring;
333                 pystring= malloc(strlen(fn) + 32);
334                 pystring[0]= '\0';
335                 sprintf(pystring, "exec(open(r'%s').read())", fn);
336                 py_result = PyRun_String( pystring, Py_file_input, py_dict, py_dict );
337                 free(pystring);
338 #else
339                 FILE *fp= fopen(fn, "r");               
340                 if(fp) {
341                         py_result = PyRun_File(fp, fn, Py_file_input, py_dict, py_dict);
342                         fclose(fp);
343                 }
344                 else {
345                         PyErr_Format(PyExc_SystemError, "Python file \"%s\" could not be opened: %s", fn, strerror(errno));
346                         py_result= NULL;
347                 }
348 #endif
349         }
350         
351         if (!py_result) {
352                 BPy_errors_to_report(reports);
353         } else {
354                 Py_DECREF( py_result );
355         }
356         
357         Py_DECREF(py_dict);
358         
359         bpy_context_clear(C, &gilstate);
360
361         return py_result ? 1:0;
362 }
363
364
365 /* TODO - move into bpy_space.c ? */
366 /* GUI interface routines */
367
368 /* Copied from Draw.c */
369 static void exit_pydraw( SpaceScript * sc, short err )
370 {
371         Script *script = NULL;
372
373         if( !sc || !sc->script )
374                 return;
375
376         script = sc->script;
377
378         if( err ) {
379                 BPy_errors_to_report(NULL); // TODO, reports
380                 script->flags = 0;      /* mark script struct for deletion */
381                 SCRIPT_SET_NULL(script);
382                 script->scriptname[0] = '\0';
383                 script->scriptarg[0] = '\0';
384 // XXX 2.5              error_pyscript();
385 // XXX 2.5              scrarea_queue_redraw( sc->area );
386         }
387
388 #if 0 // XXX 2.5
389         BPy_Set_DrawButtonsList(sc->but_refs);
390         BPy_Free_DrawButtonsList(); /*clear all temp button references*/
391 #endif
392
393         sc->but_refs = NULL;
394         
395         Py_XDECREF( ( PyObject * ) script->py_draw );
396         Py_XDECREF( ( PyObject * ) script->py_event );
397         Py_XDECREF( ( PyObject * ) script->py_button );
398
399         script->py_draw = script->py_event = script->py_button = NULL;
400 }
401
402 static int bpy_run_script_init(bContext *C, SpaceScript * sc)
403 {
404         if (sc->script==NULL) 
405                 return 0;
406         
407         if (sc->script->py_draw==NULL && sc->script->scriptname[0] != '\0')
408                 BPY_run_python_script(C, sc->script->scriptname, NULL, NULL);
409                 
410         if (sc->script->py_draw==NULL)
411                 return 0;
412         
413         return 1;
414 }
415
416 int BPY_run_script_space_draw(const struct bContext *C, SpaceScript * sc)
417 {
418         if (bpy_run_script_init( (bContext *)C, sc)) {
419                 PyGILState_STATE gilstate = PyGILState_Ensure();
420                 PyObject *result = PyObject_CallObject( sc->script->py_draw, NULL );
421                 
422                 if (result==NULL)
423                         exit_pydraw(sc, 1);
424                         
425                 PyGILState_Release(gilstate);
426         }
427         return 1;
428 }
429
430 // XXX - not used yet, listeners dont get a context
431 int BPY_run_script_space_listener(bContext *C, SpaceScript * sc)
432 {
433         if (bpy_run_script_init(C, sc)) {
434                 PyGILState_STATE gilstate = PyGILState_Ensure();
435                 
436                 PyObject *result = PyObject_CallObject( sc->script->py_draw, NULL );
437                 
438                 if (result==NULL)
439                         exit_pydraw(sc, 1);
440                         
441                 PyGILState_Release(gilstate);
442         }
443         return 1;
444 }
445
446 void BPY_DECREF(void *pyob_ptr)
447 {
448         Py_DECREF((PyObject *)pyob_ptr);
449 }
450
451 #if 0
452 /* called from the the scripts window, assume context is ok */
453 int BPY_run_python_script_space(const char *modulename, const char *func)
454 {
455         PyObject *py_dict, *py_result= NULL;
456         char pystring[512];
457         PyGILState_STATE gilstate;
458         
459         /* for calling the module function */
460         PyObject *py_func, 
461         
462         gilstate = PyGILState_Ensure();
463         
464         py_dict = CreateGlobalDictionary(C);
465         
466         PyObject *module = PyImport_ImportModule(scpt->script.filename);
467         if (module==NULL) {
468                 PyErr_SetFormat(PyExc_SystemError, "could not import '%s'", scpt->script.filename);
469         }
470         else {
471                 py_func = PyObject_GetAttrString(modulename, func);
472                 if (py_func==NULL) {
473                         PyErr_SetFormat(PyExc_SystemError, "module has no function '%s.%s'\n", scpt->script.filename, func);
474                 }
475                 else {
476                         Py_DECREF(py_func);
477                         if (!PyCallable_Check(py_func)) {
478                                 PyErr_SetFormat(PyExc_SystemError, "module item is not callable '%s.%s'\n", scpt->script.filename, func);
479                         }
480                         else {
481                                 py_result= PyObject_CallObject(py_func, NULL); // XXX will need args eventually
482                         }
483                 }
484         }
485         
486         if (!py_result) {
487                 BPy_errors_to_report(NULL); // TODO - reports
488         } else
489                 Py_DECREF( py_result );
490         
491         Py_XDECREF(module);
492         
493         Py_DECREF(py_dict);
494         
495         PyGILState_Release(gilstate);
496         return 1;
497 }
498 #endif
499
500 // #define TIME_REGISTRATION
501
502 #ifdef TIME_REGISTRATION
503 #include "PIL_time.h"
504 #endif
505
506 /* for use by BPY_run_ui_scripts only */
507 static int bpy_import_module(char *modname, int reload)
508 {
509         PyObject *mod= PyImport_ImportModuleLevel(modname, NULL, NULL, NULL, 0);
510         if (mod) {
511                 if (reload) {
512                         PyObject *mod_orig= mod;
513                         mod= PyImport_ReloadModule(mod);
514                         Py_DECREF(mod_orig);
515                 }
516         }
517
518         if(mod) {
519                 Py_DECREF(mod); /* could be NULL from reloading */
520                 return 0;
521         } else {
522                 return -1;
523         }
524 }
525
526 /* XXX this is temporary, need a proper script registration system for 2.5 */
527 void BPY_run_ui_scripts(bContext *C, int reload)
528 {
529 #ifdef TIME_REGISTRATION
530         double time = PIL_check_seconds_timer();
531 #endif
532         DIR *dir; 
533         struct dirent *de;
534         char *file_extension;
535         char *dirname;
536         char path[FILE_MAX];
537         char *dirs[] = {"ui", "io", NULL};
538         int a, err;
539         
540         PyGILState_STATE gilstate;
541         PyObject *sys_path;
542
543         bpy_context_set(C, &gilstate);
544
545         sys_path= PySys_GetObject("path"); /* borrow */
546         PyList_Insert(sys_path, 0, Py_None); /* place holder, resizes the list */
547
548         for(a=0; dirs[a]; a++) {
549                 dirname= BLI_gethome_folder(dirs[a]);
550
551                 if(!dirname)
552                         continue;
553
554                 dir = opendir(dirname);
555
556                 if(!dir)
557                         continue;
558                 
559                 /* set the first dir in the sys.path for fast importing of modules */
560                 PyList_SetItem(sys_path, 0, PyUnicode_FromString(dirname)); /* steals the ref */
561                         
562                 while((de = readdir(dir)) != NULL) {
563                         /* We could stat the file but easier just to let python
564                          * import it and complain if theres a problem */
565                         err = 0;
566
567                         if (de->d_name[0] == '.') {
568                                 /* do nothing, probably .svn */
569                         }
570                         else if ((file_extension = strstr(de->d_name, ".py"))) {
571                                 /* normal py files? */
572                                 if(file_extension && file_extension[3] == '\0') {
573                                         de->d_name[(file_extension - de->d_name)] = '\0';
574                                         err= bpy_import_module(de->d_name, reload);
575                                 }
576                         }
577 #ifndef __linux__
578                         else if( BLI_join_dirfile(path, dirname, de->d_name), S_ISDIR(BLI_exists(path))) {
579 #else
580                         else if(de->d_type==DT_DIR) {
581                                 BLI_join_dirfile(path, dirname, de->d_name);
582 #endif
583                                 /* support packages */
584                                 BLI_join_dirfile(path, path, "__init__.py");
585
586                                 if(BLI_exists(path)) {
587                                         err= bpy_import_module(de->d_name, reload);
588                                 }
589                         }
590
591                         if(err==-1) {
592                                 BPy_errors_to_report(NULL);
593                                 fprintf(stderr, "unable to import %s/%s\n", dirname, de->d_name);
594                         }
595                 }
596
597                 closedir(dir);
598         }
599         
600         PyList_SetSlice(sys_path, 0, 1, NULL); /* remove the first item */
601
602         bpy_context_clear(C, &gilstate);
603         
604 #ifdef TIME_REGISTRATION
605         printf("script time %f\n", (PIL_check_seconds_timer()-time));
606 #endif
607
608         /* reset the timer so as not to take loading into the stats */
609         bpy_timer_count = 0;
610 }
611
612 /* ****************************************** */
613 /* Drivers - PyExpression Evaluation */
614
615 /* for pydrivers (drivers using one-line Python expressions to express relationships between targets) */
616 PyObject *bpy_pydriver_Dict = NULL;
617
618 /* For faster execution we keep a special dictionary for pydrivers, with
619  * the needed modules and aliases. 
620  */
621 static int bpy_pydriver_create_dict(void)
622 {
623         PyObject *d, *mod;
624         
625         /* validate namespace for driver evaluation */
626         if (bpy_pydriver_Dict) return -1;
627
628         d = PyDict_New();
629         if (d == NULL) 
630                 return -1;
631         else
632                 bpy_pydriver_Dict = d;
633
634         /* import some modules: builtins, bpy, math, (Blender.noise )*/
635         PyDict_SetItemString(d, "__builtins__", PyEval_GetBuiltins());
636
637         mod = PyImport_ImportModule("math");
638         if (mod) {
639                 PyDict_Merge(d, PyModule_GetDict(mod), 0); /* 0 - dont overwrite existing values */
640                 
641                 /* Only keep for backwards compat! - just import all math into root, they are standard */
642                 PyDict_SetItemString(d, "math", mod);
643                 PyDict_SetItemString(d, "m", mod);
644                 Py_DECREF(mod);
645         } 
646         
647         /* add bpy to global namespace */
648         mod= PyImport_ImportModuleLevel("bpy", NULL, NULL, NULL, 0);
649         if (mod) {
650                 PyDict_SetItemString(bpy_pydriver_Dict, "bpy", mod);
651                 Py_DECREF(mod);
652         }
653         
654         
655 #if 0 // non existant yet
656         mod = PyImport_ImportModule("Blender.Noise");
657         if (mod) {
658                 PyDict_SetItemString(d, "noise", mod);
659                 PyDict_SetItemString(d, "n", mod);
660                 Py_DECREF(mod);
661         } else {
662                 PyErr_Clear();
663         }
664         
665         /* If there's a Blender text called pydrivers.py, import it.
666          * Users can add their own functions to this module. 
667          */
668         if (G.f & G_DOSCRIPTLINKS) {
669                 mod = importText("pydrivers"); /* can also use PyImport_Import() */
670                 if (mod) {
671                         PyDict_SetItemString(d, "pydrivers", mod);
672                         PyDict_SetItemString(d, "p", mod);
673                         Py_DECREF(mod);
674                 } else {
675                         PyErr_Clear();
676                 }
677         }
678 #endif // non existant yet
679         
680         return 0;
681 }
682
683 /* Update function, it gets rid of pydrivers global dictionary, forcing
684  * BPY_pydriver_eval to recreate it. This function is used to force
685  * reloading the Blender text module "pydrivers.py", if available, so
686  * updates in it reach pydriver evaluation. 
687  */
688 void BPY_pydriver_update(void)
689 {
690         PyGILState_STATE gilstate = PyGILState_Ensure();
691
692         if (bpy_pydriver_Dict) { /* free the global dict used by pydrivers */
693                 PyDict_Clear(bpy_pydriver_Dict);
694                 Py_DECREF(bpy_pydriver_Dict);
695                 bpy_pydriver_Dict = NULL;
696         }
697
698         PyGILState_Release(gilstate);
699
700         return;
701 }
702
703 /* error return function for BPY_eval_pydriver */
704 static float pydriver_error(ChannelDriver *driver) 
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         driver->flag |= DRIVER_FLAG_INVALID; /* py expression failed */
713         fprintf(stderr, "\nError in Driver: The following Python expression failed:\n\t'%s'\n\n", driver->expression);
714         
715         BPy_errors_to_report(NULL); // TODO - reports
716
717         return 0.0f;
718 }
719
720 /* This evals py driver expressions, 'expr' is a Python expression that
721  * should evaluate to a float number, which is returned. 
722  */
723 float BPY_pydriver_eval (ChannelDriver *driver)
724 {
725         PyObject *driver_vars=NULL;
726         PyObject *retval;
727         PyGILState_STATE gilstate;
728         
729         DriverTarget *dtar;
730         float result = 0.0f; /* default return */
731         char *expr = NULL;
732         short targets_ok= 1;
733         
734         /* sanity checks - should driver be executed? */
735         if ((driver == NULL) /*|| (G.f & G_DOSCRIPTLINKS)==0*/) 
736                 return result;
737         
738         /* get the py expression to be evaluated */
739         expr = driver->expression; 
740         if ((expr == NULL) || (expr[0]=='\0')) 
741                 return result;
742
743         gilstate = PyGILState_Ensure();
744         
745         /* init global dictionary for py-driver evaluation settings */
746         if (!bpy_pydriver_Dict) {
747                 if (bpy_pydriver_create_dict() != 0) {
748                         fprintf(stderr, "Pydriver error: couldn't create Python dictionary");
749                         PyGILState_Release(gilstate);
750                         return result;
751                 }
752         }
753         
754         /* add target values to a dict that will be used as '__locals__' dict */
755         driver_vars = PyDict_New(); // XXX do we need to decref this?
756         for (dtar= driver->targets.first; dtar; dtar= dtar->next) {
757                 PyObject *driver_arg = NULL;
758                 float tval = 0.0f;
759                 
760                 /* try to get variable value */
761                 tval= driver_get_target_value(driver, dtar);
762                 driver_arg= PyFloat_FromDouble((double)tval);
763                 
764                 /* try to add to dictionary */
765                 if (PyDict_SetItemString(driver_vars, dtar->name, driver_arg)) {
766                         /* this target failed - bad name */
767                         if (targets_ok) {
768                                 /* first one - print some extra info for easier identification */
769                                 fprintf(stderr, "\nBPY_pydriver_eval() - Error while evaluating PyDriver:\n");
770                                 targets_ok= 0;
771                         }
772                         
773                         fprintf(stderr, "\tBPY_pydriver_eval() - couldn't add variable '%s' to namespace \n", dtar->name);
774                         BPy_errors_to_report(NULL); // TODO - reports
775                 }
776         }
777         
778         /* execute expression to get a value */
779         retval = PyRun_String(expr, Py_eval_input, bpy_pydriver_Dict, driver_vars);
780         
781         /* decref the driver vars first...  */
782         Py_DECREF(driver_vars);
783         
784         /* process the result */
785         if (retval == NULL) {
786                 result = pydriver_error(driver);
787                 PyGILState_Release(gilstate);
788                 return result;
789         }
790
791         result = (float)PyFloat_AsDouble(retval);
792         Py_DECREF(retval);
793         
794         if ((result == -1) && PyErr_Occurred()) {
795                 result = pydriver_error(driver);
796                 PyGILState_Release(gilstate);
797                 return result;
798         }
799         
800         /* all fine, make sure the "invalid expression" flag is cleared */
801         driver->flag &= ~DRIVER_FLAG_INVALID;
802
803         PyGILState_Release(gilstate);
804
805         return result;
806 }