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