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