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