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