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