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