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