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