commit before doing some hefty shapekey change, will break compilation
[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                         {"EnumProperty", (PyCFunction)BPy_EnumProperty, METH_VARARGS|METH_KEYWORDS, ""},
245                         {"PointerProperty", (PyCFunction)BPy_PointerProperty, METH_VARARGS|METH_KEYWORDS, ""},
246                         {"CollectionProperty", (PyCFunction)BPy_CollectionProperty, METH_VARARGS|METH_KEYWORDS, ""},
247                         {NULL, NULL, 0, NULL}
248                 };
249                 
250                 for(ml = bpy_prop_meths; ml->ml_name; ml++) {
251                         PyDict_SetItemString( dict, ml->ml_name, PyCFunction_New(ml, NULL));
252                 }
253         }
254         
255         /* add bpy to global namespace */
256         mod= PyImport_ImportModuleLevel("bpy", NULL, NULL, NULL, 0);
257         PyDict_SetItemString( dict, "bpy", mod );
258         Py_DECREF(mod);
259         
260         return dict;
261 }
262
263 /* must be called before Py_Initialize */
264 void BPY_start_python_path(void)
265 {
266         char *py_path_bundle= BLI_gethome_folder("python", BLI_GETHOME_ALL);
267
268         if(py_path_bundle==NULL)
269                 return;
270
271         /* set the environment path */
272         printf("found bundled python: %s\n", py_path_bundle);
273
274 #if 0
275         BLI_setenv("PYTHONHOME", py_path_bundle);
276         BLI_setenv("PYTHONPATH", py_path_bundle);
277 #endif
278
279         {
280                 static wchar_t py_path_bundle_wchar[FILE_MAXDIR];
281
282                 mbstowcs(py_path_bundle_wchar, py_path_bundle, FILE_MAXDIR);
283                 Py_SetPythonHome(py_path_bundle_wchar);
284         }
285 }
286
287
288 void BPY_start_python( int argc, char **argv )
289 {
290         PyThreadState *py_tstate = NULL;
291         
292         BPY_start_python_path(); /* allow to use our own included python */
293
294         Py_Initialize(  );
295         
296         /*convert argv to wchar_t*/
297         // PySys_SetArgv( argc, argv); // broken in py3, not a huge deal
298         
299         /*temporarily set argv*/
300         /* sigh, why do python guys not have a char** version anymore? :( */
301         {
302                 int i;
303                 PyObject *py_argv= PyList_New(argc);
304
305                 for (i=0; i<argc; i++)
306                         PyList_SET_ITEM(py_argv, i, PyUnicode_FromString(argv[i]));
307
308                 PySys_SetObject("argv", py_argv);
309                 Py_DECREF(py_argv);
310         }
311         
312         /* Initialize thread support (also acquires lock) */
313         PyEval_InitThreads();
314         
315         
316         /* bpy.* and lets us import it */
317         bpy_init_modules(); 
318
319         { /* our own import and reload functions */
320                 PyObject *item;
321                 //PyObject *m = PyImport_AddModule("__builtin__");
322                 //PyObject *d = PyModule_GetDict(m);
323                 PyObject *d = PyEval_GetBuiltins(  );
324                 PyDict_SetItemString(d, "reload",               item=PyCFunction_New(bpy_reload_meth, NULL));   Py_DECREF(item);
325                 PyDict_SetItemString(d, "__import__",   item=PyCFunction_New(bpy_import_meth, NULL));   Py_DECREF(item);
326                 
327                 /* a bit nasty but this prevents help() and input() from locking blender
328                  * Ideally we could have some way for the console to replace sys.stdin but
329                  * python would lock blender while waiting for a return value, not easy :| */
330                 PySys_SetObject("stdin", Py_None);
331         }
332         
333         pyrna_alloc_types();
334
335         py_tstate = PyGILState_GetThisThreadState();
336         PyEval_ReleaseThread(py_tstate);
337 }
338
339 void BPY_end_python( void )
340 {
341         // fprintf(stderr, "Ending Python!\n");
342
343         PyGILState_Ensure(); /* finalizing, no need to grab the state */
344         
345         // free other python data.
346         pyrna_free_types();
347
348         /* clear all python data from structs */
349         
350         Py_Finalize(  );
351         
352 #ifdef TIME_PY_RUN
353         // measure time since py started
354         bpy_timer = PIL_check_seconds_timer() - bpy_timer;
355
356         printf("*bpy stats* - ");
357         printf("tot exec: %d,  ", bpy_timer_count);
358         printf("tot run: %.4fsec,  ", bpy_timer_run_tot);
359         if(bpy_timer_count>0)
360                 printf("average run: %.6fsec,  ", (bpy_timer_run_tot/bpy_timer_count));
361
362         if(bpy_timer>0.0)
363                 printf("tot usage %.4f%%", (bpy_timer_run_tot/bpy_timer)*100.0);
364
365         printf("\n");
366
367         // fprintf(stderr, "Ending Python Done!\n");
368
369 #endif
370
371 }
372
373 /* Can run a file or text block */
374 int BPY_run_python_script( bContext *C, const char *fn, struct Text *text, struct ReportList *reports)
375 {
376         PyObject *py_dict, *py_result= NULL;
377         PyGILState_STATE gilstate;
378         
379         if (fn==NULL && text==NULL) {
380                 return 0;
381         }
382         
383         bpy_context_set(C, &gilstate);
384         
385         py_dict = CreateGlobalDictionary(C);
386
387         if (text) {
388                 
389                 if( !text->compiled ) { /* if it wasn't already compiled, do it now */
390                         char *buf = txt_to_buf( text );
391
392                         text->compiled =
393                                 Py_CompileString( buf, text->id.name+2, Py_file_input );
394
395                         MEM_freeN( buf );
396
397                         if( PyErr_Occurred(  ) ) {
398                                 BPY_free_compiled_text( text );
399                         }
400                 }
401                 if(text->compiled)
402                         py_result =  PyEval_EvalCode( text->compiled, py_dict, py_dict );
403                 
404         } else {
405 #if 0
406                 char *pystring;
407                 pystring= malloc(strlen(fn) + 32);
408                 pystring[0]= '\0';
409                 sprintf(pystring, "exec(open(r'%s').read())", fn);
410                 py_result = PyRun_String( pystring, Py_file_input, py_dict, py_dict );
411                 free(pystring);
412 #else
413                 FILE *fp= fopen(fn, "r");               
414                 if(fp) {
415                         py_result = PyRun_File(fp, fn, Py_file_input, py_dict, py_dict);
416                         fclose(fp);
417                 }
418                 else {
419                         PyErr_Format(PyExc_SystemError, "Python file \"%s\" could not be opened: %s", fn, strerror(errno));
420                         py_result= NULL;
421                 }
422 #endif
423         }
424         
425         if (!py_result) {
426                 BPy_errors_to_report(reports);
427         } else {
428                 Py_DECREF( py_result );
429         }
430         
431         Py_DECREF(py_dict);
432         
433         bpy_context_clear(C, &gilstate);
434
435         return py_result ? 1:0;
436 }
437
438
439 /* TODO - move into bpy_space.c ? */
440 /* GUI interface routines */
441
442 /* Copied from Draw.c */
443 static void exit_pydraw( SpaceScript * sc, short err )
444 {
445         Script *script = NULL;
446
447         if( !sc || !sc->script )
448                 return;
449
450         script = sc->script;
451
452         if( err ) {
453                 BPy_errors_to_report(NULL); // TODO, reports
454                 script->flags = 0;      /* mark script struct for deletion */
455                 SCRIPT_SET_NULL(script);
456                 script->scriptname[0] = '\0';
457                 script->scriptarg[0] = '\0';
458 // XXX 2.5              error_pyscript();
459 // XXX 2.5              scrarea_queue_redraw( sc->area );
460         }
461
462 #if 0 // XXX 2.5
463         BPy_Set_DrawButtonsList(sc->but_refs);
464         BPy_Free_DrawButtonsList(); /*clear all temp button references*/
465 #endif
466
467         sc->but_refs = NULL;
468         
469         Py_XDECREF( ( PyObject * ) script->py_draw );
470         Py_XDECREF( ( PyObject * ) script->py_event );
471         Py_XDECREF( ( PyObject * ) script->py_button );
472
473         script->py_draw = script->py_event = script->py_button = NULL;
474 }
475
476 static int bpy_run_script_init(bContext *C, SpaceScript * sc)
477 {
478         if (sc->script==NULL) 
479                 return 0;
480         
481         if (sc->script->py_draw==NULL && sc->script->scriptname[0] != '\0')
482                 BPY_run_python_script(C, sc->script->scriptname, NULL, NULL);
483                 
484         if (sc->script->py_draw==NULL)
485                 return 0;
486         
487         return 1;
488 }
489
490 int BPY_run_script_space_draw(const struct bContext *C, SpaceScript * sc)
491 {
492         if (bpy_run_script_init( (bContext *)C, sc)) {
493                 PyGILState_STATE gilstate = PyGILState_Ensure();
494                 PyObject *result = PyObject_CallObject( sc->script->py_draw, NULL );
495                 
496                 if (result==NULL)
497                         exit_pydraw(sc, 1);
498                         
499                 PyGILState_Release(gilstate);
500         }
501         return 1;
502 }
503
504 // XXX - not used yet, listeners dont get a context
505 int BPY_run_script_space_listener(bContext *C, SpaceScript * sc)
506 {
507         if (bpy_run_script_init(C, sc)) {
508                 PyGILState_STATE gilstate = PyGILState_Ensure();
509                 
510                 PyObject *result = PyObject_CallObject( sc->script->py_draw, NULL );
511                 
512                 if (result==NULL)
513                         exit_pydraw(sc, 1);
514                         
515                 PyGILState_Release(gilstate);
516         }
517         return 1;
518 }
519
520 void BPY_DECREF(void *pyob_ptr)
521 {
522         Py_DECREF((PyObject *)pyob_ptr);
523 }
524
525 #if 0
526 /* called from the the scripts window, assume context is ok */
527 int BPY_run_python_script_space(const char *modulename, const char *func)
528 {
529         PyObject *py_dict, *py_result= NULL;
530         char pystring[512];
531         PyGILState_STATE gilstate;
532         
533         /* for calling the module function */
534         PyObject *py_func, 
535         
536         gilstate = PyGILState_Ensure();
537         
538         py_dict = CreateGlobalDictionary(C);
539         
540         PyObject *module = PyImport_ImportModule(scpt->script.filename);
541         if (module==NULL) {
542                 PyErr_SetFormat(PyExc_SystemError, "could not import '%s'", scpt->script.filename);
543         }
544         else {
545                 py_func = PyObject_GetAttrString(modulename, func);
546                 if (py_func==NULL) {
547                         PyErr_SetFormat(PyExc_SystemError, "module has no function '%s.%s'\n", scpt->script.filename, func);
548                 }
549                 else {
550                         Py_DECREF(py_func);
551                         if (!PyCallable_Check(py_func)) {
552                                 PyErr_SetFormat(PyExc_SystemError, "module item is not callable '%s.%s'\n", scpt->script.filename, func);
553                         }
554                         else {
555                                 py_result= PyObject_CallObject(py_func, NULL); // XXX will need args eventually
556                         }
557                 }
558         }
559         
560         if (!py_result) {
561                 BPy_errors_to_report(NULL); // TODO - reports
562         } else
563                 Py_DECREF( py_result );
564         
565         Py_XDECREF(module);
566         
567         Py_DECREF(py_dict);
568         
569         PyGILState_Release(gilstate);
570         return 1;
571 }
572 #endif
573
574 // #define TIME_REGISTRATION
575
576 #ifdef TIME_REGISTRATION
577 #include "PIL_time.h"
578 #endif
579
580 /* for use by BPY_run_ui_scripts only */
581 static int bpy_import_module(char *modname, int reload)
582 {
583         PyObject *mod= PyImport_ImportModuleLevel(modname, NULL, NULL, NULL, 0);
584         if (mod) {
585                 if (reload) {
586                         PyObject *mod_orig= mod;
587                         mod= PyImport_ReloadModule(mod);
588                         Py_DECREF(mod_orig);
589                 }
590         }
591
592         if(mod) {
593                 Py_DECREF(mod); /* could be NULL from reloading */
594                 return 0;
595         } else {
596                 return -1;
597         }
598 }
599
600 /* XXX this is temporary, need a proper script registration system for 2.5 */
601 void BPY_run_ui_scripts(bContext *C, int reload)
602 {
603 #ifdef TIME_REGISTRATION
604         double time = PIL_check_seconds_timer();
605 #endif
606         DIR *dir; 
607         struct dirent *de;
608         char *file_extension;
609         char *dirname;
610         char path[FILE_MAX];
611         char *dirs[] = {"scripts/ui", "scripts/io", NULL};
612         int path_flags[] = {BLI_GETHOME_LOCAL|BLI_GETHOME_SYSTEM, BLI_GETHOME_USER}; /* SYSTEM / NON-SYSTEM */
613         int a, err, flag_iter;
614         
615         PyGILState_STATE gilstate;
616         PyObject *sys_path;
617
618         bpy_context_set(C, &gilstate);
619
620         sys_path= PySys_GetObject("path"); /* borrow */
621         PyList_Insert(sys_path, 0, Py_None); /* place holder, resizes the list */
622
623         /* Scan system scripts first, then local/user */
624         for(flag_iter=0; flag_iter < sizeof(path_flags)/sizeof(int); flag_iter++) {
625                 
626                 for(a=0; dirs[a]; a++) {
627                         dirname= BLI_gethome_folder(dirs[a], path_flags[flag_iter]);
628
629                         if(!dirname)
630                                 continue;
631
632                         dir = opendir(dirname);
633
634                         if(!dir)
635                                 continue;
636                         
637                         /* set the first dir in the sys.path for fast importing of modules */
638                         PyList_SetItem(sys_path, 0, PyUnicode_FromString(dirname)); /* steals the ref */
639                                 
640                         while((de = readdir(dir)) != NULL) {
641                                 /* We could stat the file but easier just to let python
642                                  * import it and complain if theres a problem */
643                                 err = 0;
644
645                                 if (de->d_name[0] == '.') {
646                                         /* do nothing, probably .svn */
647                                 }
648                                 else if ((file_extension = strstr(de->d_name, ".py"))) {
649                                         /* normal py files? */
650                                         if(file_extension && file_extension[3] == '\0') {
651                                                 de->d_name[(file_extension - de->d_name)] = '\0';
652                                                 err= bpy_import_module(de->d_name, reload);
653                                         }
654                                 }
655 #ifndef __linux__
656                                 else if( BLI_join_dirfile(path, dirname, de->d_name), S_ISDIR(BLI_exist(path))) {
657 #else
658                                 else if(de->d_type==DT_DIR) {
659                                         BLI_join_dirfile(path, dirname, de->d_name);
660 #endif
661                                         /* support packages */
662                                         BLI_join_dirfile(path, path, "__init__.py");
663
664                                         if(BLI_exists(path)) {
665                                                 err= bpy_import_module(de->d_name, reload);
666                                         }
667                                 }
668
669                                 if(err==-1) {
670                                         BPy_errors_to_report(NULL);
671                                         fprintf(stderr, "unable to import %s/%s\n", dirname, de->d_name);
672                                 }
673                         }
674
675                         closedir(dir);
676                 }
677         }
678         
679         PyList_SetSlice(sys_path, 0, 1, NULL); /* remove the first item */
680
681         bpy_context_clear(C, &gilstate);
682         
683 #ifdef TIME_REGISTRATION
684         printf("script time %f\n", (PIL_check_seconds_timer()-time));
685 #endif
686
687         /* reset the timer so as not to take loading into the stats */
688         bpy_timer_count = 0;
689 }
690
691 /* ****************************************** */
692 /* Drivers - PyExpression Evaluation */
693
694 /* for pydrivers (drivers using one-line Python expressions to express relationships between targets) */
695 PyObject *bpy_pydriver_Dict = NULL;
696
697 /* For faster execution we keep a special dictionary for pydrivers, with
698  * the needed modules and aliases. 
699  */
700 static int bpy_pydriver_create_dict(void)
701 {
702         PyObject *d, *mod;
703         
704         /* validate namespace for driver evaluation */
705         if (bpy_pydriver_Dict) return -1;
706
707         d = PyDict_New();
708         if (d == NULL) 
709                 return -1;
710         else
711                 bpy_pydriver_Dict = d;
712
713         /* import some modules: builtins, bpy, math, (Blender.noise )*/
714         PyDict_SetItemString(d, "__builtins__", PyEval_GetBuiltins());
715
716         mod = PyImport_ImportModule("math");
717         if (mod) {
718                 PyDict_Merge(d, PyModule_GetDict(mod), 0); /* 0 - dont overwrite existing values */
719                 
720                 /* Only keep for backwards compat! - just import all math into root, they are standard */
721                 PyDict_SetItemString(d, "math", mod);
722                 PyDict_SetItemString(d, "m", mod);
723                 Py_DECREF(mod);
724         } 
725         
726         /* add bpy to global namespace */
727         mod= PyImport_ImportModuleLevel("bpy", NULL, NULL, NULL, 0);
728         if (mod) {
729                 PyDict_SetItemString(bpy_pydriver_Dict, "bpy", mod);
730                 Py_DECREF(mod);
731         }
732         
733         
734 #if 0 // non existant yet
735         mod = PyImport_ImportModule("Blender.Noise");
736         if (mod) {
737                 PyDict_SetItemString(d, "noise", mod);
738                 PyDict_SetItemString(d, "n", mod);
739                 Py_DECREF(mod);
740         } else {
741                 PyErr_Clear();
742         }
743         
744         /* If there's a Blender text called pydrivers.py, import it.
745          * Users can add their own functions to this module. 
746          */
747         if (G.f & G_DOSCRIPTLINKS) {
748                 mod = importText("pydrivers"); /* can also use PyImport_Import() */
749                 if (mod) {
750                         PyDict_SetItemString(d, "pydrivers", mod);
751                         PyDict_SetItemString(d, "p", mod);
752                         Py_DECREF(mod);
753                 } else {
754                         PyErr_Clear();
755                 }
756         }
757 #endif // non existant yet
758         
759         return 0;
760 }
761
762 /* Update function, it gets rid of pydrivers global dictionary, forcing
763  * BPY_pydriver_eval to recreate it. This function is used to force
764  * reloading the Blender text module "pydrivers.py", if available, so
765  * updates in it reach pydriver evaluation. 
766  */
767 void BPY_pydriver_update(void)
768 {
769         PyGILState_STATE gilstate = PyGILState_Ensure();
770
771         if (bpy_pydriver_Dict) { /* free the global dict used by pydrivers */
772                 PyDict_Clear(bpy_pydriver_Dict);
773                 Py_DECREF(bpy_pydriver_Dict);
774                 bpy_pydriver_Dict = NULL;
775         }
776
777         PyGILState_Release(gilstate);
778
779         return;
780 }
781
782 /* error return function for BPY_eval_pydriver */
783 static float pydriver_error(ChannelDriver *driver) 
784 {
785         if (bpy_pydriver_Dict) { /* free the global dict used by pydrivers */
786                 PyDict_Clear(bpy_pydriver_Dict);
787                 Py_DECREF(bpy_pydriver_Dict);
788                 bpy_pydriver_Dict = NULL;
789         }
790
791         driver->flag |= DRIVER_FLAG_INVALID; /* py expression failed */
792         fprintf(stderr, "\nError in Driver: The following Python expression failed:\n\t'%s'\n\n", driver->expression);
793         
794         BPy_errors_to_report(NULL); // TODO - reports
795
796         return 0.0f;
797 }
798
799 /* This evals py driver expressions, 'expr' is a Python expression that
800  * should evaluate to a float number, which is returned. 
801  */
802 float BPY_pydriver_eval (ChannelDriver *driver)
803 {
804         PyObject *driver_vars=NULL;
805         PyObject *retval;
806         PyGILState_STATE gilstate;
807         
808         DriverTarget *dtar;
809         float result = 0.0f; /* default return */
810         char *expr = NULL;
811         short targets_ok= 1;
812         
813         /* sanity checks - should driver be executed? */
814         if ((driver == NULL) /*|| (G.f & G_DOSCRIPTLINKS)==0*/) 
815                 return result;
816         
817         /* get the py expression to be evaluated */
818         expr = driver->expression; 
819         if ((expr == NULL) || (expr[0]=='\0')) 
820                 return result;
821
822         gilstate = PyGILState_Ensure();
823         
824         /* init global dictionary for py-driver evaluation settings */
825         if (!bpy_pydriver_Dict) {
826                 if (bpy_pydriver_create_dict() != 0) {
827                         fprintf(stderr, "Pydriver error: couldn't create Python dictionary");
828                         PyGILState_Release(gilstate);
829                         return result;
830                 }
831         }
832         
833         /* add target values to a dict that will be used as '__locals__' dict */
834         driver_vars = PyDict_New(); // XXX do we need to decref this?
835         for (dtar= driver->targets.first; dtar; dtar= dtar->next) {
836                 PyObject *driver_arg = NULL;
837                 float tval = 0.0f;
838                 
839                 /* try to get variable value */
840                 tval= driver_get_target_value(driver, dtar);
841                 driver_arg= PyFloat_FromDouble((double)tval);
842                 
843                 /* try to add to dictionary */
844                 if (PyDict_SetItemString(driver_vars, dtar->name, driver_arg)) {
845                         /* this target failed - bad name */
846                         if (targets_ok) {
847                                 /* first one - print some extra info for easier identification */
848                                 fprintf(stderr, "\nBPY_pydriver_eval() - Error while evaluating PyDriver:\n");
849                                 targets_ok= 0;
850                         }
851                         
852                         fprintf(stderr, "\tBPY_pydriver_eval() - couldn't add variable '%s' to namespace \n", dtar->name);
853                         BPy_errors_to_report(NULL); // TODO - reports
854                 }
855         }
856         
857         /* execute expression to get a value */
858         retval = PyRun_String(expr, Py_eval_input, bpy_pydriver_Dict, driver_vars);
859         
860         /* decref the driver vars first...  */
861         Py_DECREF(driver_vars);
862         
863         /* process the result */
864         if (retval == NULL) {
865                 result = pydriver_error(driver);
866                 PyGILState_Release(gilstate);
867                 return result;
868         }
869
870         result = (float)PyFloat_AsDouble(retval);
871         Py_DECREF(retval);
872         
873         if ((result == -1) && PyErr_Occurred()) {
874                 result = pydriver_error(driver);
875                 PyGILState_Release(gilstate);
876                 return result;
877         }
878         
879         /* all fine, make sure the "invalid expression" flag is cleared */
880         driver->flag &= ~DRIVER_FLAG_INVALID;
881
882         PyGILState_Release(gilstate);
883
884         return result;
885 }
886
887 int BPY_button_eval(bContext *C, char *expr, double *value)
888 {
889         PyGILState_STATE gilstate;
890         PyObject *dict, *mod, *retval;
891         int error_ret = 0;
892         
893         if (!value || !expr || expr[0]=='\0') return -1;
894         
895         bpy_context_set(C, &gilstate);
896         
897         dict= CreateGlobalDictionary(C);
898         
899         /* import some modules: builtins,math*/
900         PyDict_SetItemString(dict, "__builtins__", PyEval_GetBuiltins());
901
902         mod = PyImport_ImportModule("math");
903         if (mod) {
904                 PyDict_Merge(dict, PyModule_GetDict(mod), 0); /* 0 - dont overwrite existing values */
905                 
906                 /* Only keep for backwards compat! - just import all math into root, they are standard */
907                 PyDict_SetItemString(dict, "math", mod);
908                 PyDict_SetItemString(dict, "m", mod);
909                 Py_DECREF(mod);
910         } 
911         
912         retval = PyRun_String(expr, Py_eval_input, dict, dict);
913         
914         if (retval == NULL) {
915                 error_ret= -1;
916         }
917         else {
918                 double val;
919
920                 if(PyTuple_Check(retval)) {
921                         /* Users my have typed in 10km, 2m
922                          * add up all values */
923                         int i;
924                         val= 0.0;
925
926                         for(i=0; i<PyTuple_GET_SIZE(retval); i++) {
927                                 val+= PyFloat_AsDouble(PyTuple_GET_ITEM(retval, i));
928                         }
929                 }
930                 else {
931                         val = PyFloat_AsDouble(retval);
932                 }
933                 Py_DECREF(retval);
934                 
935                 if(val==-1 && PyErr_Occurred()) {
936                         error_ret= -1;
937                 }
938                 else {
939                         *value= val;
940                 }
941         }
942         
943         if(error_ret) {
944                 BPy_errors_to_report(CTX_wm_reports(C));
945         }
946         
947         Py_DECREF(dict);
948         bpy_context_clear(C, &gilstate);
949         
950         return error_ret;
951 }
952