- dont define properties in the global script namespace
[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                 PyObject *py_argv= PyList_New(argc);
317
318                 for (i=0; i<argc; i++)
319                         PyList_SET_ITEM(py_argv, i, PyUnicode_FromString(argv[i]));
320
321                 PySys_SetObject("argv", py_argv);
322                 Py_DECREF(py_argv);
323         }
324         
325         /* Initialize thread support (also acquires lock) */
326         PyEval_InitThreads();
327         
328         
329         /* bpy.* and lets us import it */
330         bpy_init_modules(); 
331
332         { /* our own import and reload functions */
333                 PyObject *item;
334                 //PyObject *m = PyImport_AddModule("__builtin__");
335                 //PyObject *d = PyModule_GetDict(m);
336                 PyObject *d = PyEval_GetBuiltins(  );
337                 PyDict_SetItemString(d, "reload",               item=PyCFunction_New(bpy_reload_meth, NULL));   Py_DECREF(item);
338                 PyDict_SetItemString(d, "__import__",   item=PyCFunction_New(bpy_import_meth, NULL));   Py_DECREF(item);
339         }
340         
341         pyrna_alloc_types();
342
343         py_tstate = PyGILState_GetThisThreadState();
344         PyEval_ReleaseThread(py_tstate);
345 }
346
347 void BPY_end_python( void )
348 {
349         // fprintf(stderr, "Ending Python!\n");
350
351         PyGILState_Ensure(); /* finalizing, no need to grab the state */
352         
353         // free other python data.
354         pyrna_free_types();
355
356         /* clear all python data from structs */
357         
358         Py_Finalize(  );
359         
360 #ifdef TIME_PY_RUN
361         // measure time since py started
362         bpy_timer = PIL_check_seconds_timer() - bpy_timer;
363
364         printf("*bpy stats* - ");
365         printf("tot exec: %d,  ", bpy_timer_count);
366         printf("tot run: %.4fsec,  ", bpy_timer_run_tot);
367         if(bpy_timer_count>0)
368                 printf("average run: %.6fsec,  ", (bpy_timer_run_tot/bpy_timer_count));
369
370         if(bpy_timer>0.0)
371                 printf("tot usage %.4f%%", (bpy_timer_run_tot/bpy_timer)*100.0);
372
373         printf("\n");
374
375         // fprintf(stderr, "Ending Python Done!\n");
376
377 #endif
378
379 }
380
381 /* Can run a file or text block */
382 int BPY_run_python_script( bContext *C, const char *fn, struct Text *text, struct ReportList *reports)
383 {
384         PyObject *py_dict, *py_result= NULL;
385         PyGILState_STATE gilstate;
386         
387         if (fn==NULL && text==NULL) {
388                 return 0;
389         }
390         
391         bpy_context_set(C, &gilstate);
392         
393         py_dict = CreateGlobalDictionary(C, text?text->id.name+2:fn);
394
395         if (text) {
396                 
397                 if( !text->compiled ) { /* if it wasn't already compiled, do it now */
398                         char *buf = txt_to_buf( text );
399
400                         text->compiled =
401                                 Py_CompileString( buf, text->id.name+2, Py_file_input );
402
403                         MEM_freeN( buf );
404
405                         if( PyErr_Occurred(  ) ) {
406                                 BPY_free_compiled_text( text );
407                         }
408                 }
409                 if(text->compiled)
410                         py_result =  PyEval_EvalCode( text->compiled, py_dict, py_dict );
411                 
412         } else {
413                 FILE *fp= fopen(fn, "r");               
414                 if(fp) {
415 #ifdef _WIN32
416                         /* Previously we used PyRun_File to run directly the code on a FILE 
417                          * object, but as written in the Python/C API Ref Manual, chapter 2,
418                          * 'FILE structs for different C libraries can be different and 
419                          * incompatible'.
420                          * So now we load the script file data to a buffer */
421                         char *pystring;
422
423                         fclose(fp);
424
425                         pystring= malloc(strlen(fn) + 32);
426                         pystring[0]= '\0';
427                         sprintf(pystring, "exec(open(r'%s').read())", fn);
428                         py_result = PyRun_String( pystring, Py_file_input, py_dict, py_dict );
429                         free(pystring);
430 #else
431                         py_result = PyRun_File(fp, fn, Py_file_input, py_dict, py_dict);
432                         fclose(fp);
433 #endif
434                 }
435                 else {
436                         PyErr_Format(PyExc_SystemError, "Python file \"%s\" could not be opened: %s", fn, strerror(errno));
437                         py_result= NULL;
438                 }
439         }
440         
441         if (!py_result) {
442                 BPy_errors_to_report(reports);
443         } else {
444                 Py_DECREF( py_result );
445         }
446         
447         Py_DECREF(py_dict);
448         
449         bpy_context_clear(C, &gilstate);
450
451         return py_result ? 1:0;
452 }
453
454
455 /* TODO - move into bpy_space.c ? */
456 /* GUI interface routines */
457
458 /* Copied from Draw.c */
459 static void exit_pydraw( SpaceScript * sc, short err )
460 {
461         Script *script = NULL;
462
463         if( !sc || !sc->script )
464                 return;
465
466         script = sc->script;
467
468         if( err ) {
469                 BPy_errors_to_report(NULL); // TODO, reports
470                 script->flags = 0;      /* mark script struct for deletion */
471                 SCRIPT_SET_NULL(script);
472                 script->scriptname[0] = '\0';
473                 script->scriptarg[0] = '\0';
474 // XXX 2.5              error_pyscript();
475 // XXX 2.5              scrarea_queue_redraw( sc->area );
476         }
477
478 #if 0 // XXX 2.5
479         BPy_Set_DrawButtonsList(sc->but_refs);
480         BPy_Free_DrawButtonsList(); /*clear all temp button references*/
481 #endif
482
483         sc->but_refs = NULL;
484         
485         Py_XDECREF( ( PyObject * ) script->py_draw );
486         Py_XDECREF( ( PyObject * ) script->py_event );
487         Py_XDECREF( ( PyObject * ) script->py_button );
488
489         script->py_draw = script->py_event = script->py_button = NULL;
490 }
491
492 static int bpy_run_script_init(bContext *C, SpaceScript * sc)
493 {
494         if (sc->script==NULL) 
495                 return 0;
496         
497         if (sc->script->py_draw==NULL && sc->script->scriptname[0] != '\0')
498                 BPY_run_python_script(C, sc->script->scriptname, NULL, NULL);
499                 
500         if (sc->script->py_draw==NULL)
501                 return 0;
502         
503         return 1;
504 }
505
506 int BPY_run_script_space_draw(const struct bContext *C, SpaceScript * sc)
507 {
508         if (bpy_run_script_init( (bContext *)C, sc)) {
509                 PyGILState_STATE gilstate = PyGILState_Ensure();
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 // XXX - not used yet, listeners dont get a context
521 int BPY_run_script_space_listener(bContext *C, SpaceScript * sc)
522 {
523         if (bpy_run_script_init(C, sc)) {
524                 PyGILState_STATE gilstate = PyGILState_Ensure();
525                 
526                 PyObject *result = PyObject_CallObject( sc->script->py_draw, NULL );
527                 
528                 if (result==NULL)
529                         exit_pydraw(sc, 1);
530                         
531                 PyGILState_Release(gilstate);
532         }
533         return 1;
534 }
535
536 void BPY_DECREF(void *pyob_ptr)
537 {
538         Py_DECREF((PyObject *)pyob_ptr);
539 }
540
541 #if 0
542 /* called from the the scripts window, assume context is ok */
543 int BPY_run_python_script_space(const char *modulename, const char *func)
544 {
545         PyObject *py_dict, *py_result= NULL;
546         char pystring[512];
547         PyGILState_STATE gilstate;
548         
549         /* for calling the module function */
550         PyObject *py_func, 
551         
552         gilstate = PyGILState_Ensure();
553         
554         py_dict = CreateGlobalDictionary(C);
555         
556         PyObject *module = PyImport_ImportModule(scpt->script.filename);
557         if (module==NULL) {
558                 PyErr_SetFormat(PyExc_SystemError, "could not import '%s'", scpt->script.filename);
559         }
560         else {
561                 py_func = PyObject_GetAttrString(modulename, func);
562                 if (py_func==NULL) {
563                         PyErr_SetFormat(PyExc_SystemError, "module has no function '%s.%s'\n", scpt->script.filename, func);
564                 }
565                 else {
566                         Py_DECREF(py_func);
567                         if (!PyCallable_Check(py_func)) {
568                                 PyErr_SetFormat(PyExc_SystemError, "module item is not callable '%s.%s'\n", scpt->script.filename, func);
569                         }
570                         else {
571                                 py_result= PyObject_CallObject(py_func, NULL); // XXX will need args eventually
572                         }
573                 }
574         }
575         
576         if (!py_result) {
577                 BPy_errors_to_report(NULL); // TODO - reports
578         } else
579                 Py_DECREF( py_result );
580         
581         Py_XDECREF(module);
582         
583         Py_DECREF(py_dict);
584         
585         PyGILState_Release(gilstate);
586         return 1;
587 }
588 #endif
589
590 // #define TIME_REGISTRATION
591
592 #ifdef TIME_REGISTRATION
593 #include "PIL_time.h"
594 #endif
595
596 /* ****************************************** */
597 /* Drivers - PyExpression Evaluation */
598
599 /* for pydrivers (drivers using one-line Python expressions to express relationships between targets) */
600 PyObject *bpy_pydriver_Dict = NULL;
601
602 /* For faster execution we keep a special dictionary for pydrivers, with
603  * the needed modules and aliases. 
604  */
605 static int bpy_pydriver_create_dict(void)
606 {
607         PyObject *d, *mod;
608         
609         /* validate namespace for driver evaluation */
610         if (bpy_pydriver_Dict) return -1;
611
612         d = PyDict_New();
613         if (d == NULL) 
614                 return -1;
615         else
616                 bpy_pydriver_Dict = d;
617
618         /* import some modules: builtins, bpy, math, (Blender.noise )*/
619         PyDict_SetItemString(d, "__builtins__", PyEval_GetBuiltins());
620
621         mod = PyImport_ImportModule("math");
622         if (mod) {
623                 PyDict_Merge(d, PyModule_GetDict(mod), 0); /* 0 - dont overwrite existing values */
624                 
625                 /* Only keep for backwards compat! - just import all math into root, they are standard */
626                 PyDict_SetItemString(d, "math", mod);
627                 PyDict_SetItemString(d, "m", mod);
628                 Py_DECREF(mod);
629         } 
630         
631         /* add bpy to global namespace */
632         mod= PyImport_ImportModuleLevel("bpy", NULL, NULL, NULL, 0);
633         if (mod) {
634                 PyDict_SetItemString(bpy_pydriver_Dict, "bpy", mod);
635                 Py_DECREF(mod);
636         }
637         
638         
639 #if 0 // non existant yet
640         mod = PyImport_ImportModule("Blender.Noise");
641         if (mod) {
642                 PyDict_SetItemString(d, "noise", mod);
643                 PyDict_SetItemString(d, "n", mod);
644                 Py_DECREF(mod);
645         } else {
646                 PyErr_Clear();
647         }
648         
649         /* If there's a Blender text called pydrivers.py, import it.
650          * Users can add their own functions to this module. 
651          */
652         if (G.f & G_DOSCRIPTLINKS) {
653                 mod = importText("pydrivers"); /* can also use PyImport_Import() */
654                 if (mod) {
655                         PyDict_SetItemString(d, "pydrivers", mod);
656                         PyDict_SetItemString(d, "p", mod);
657                         Py_DECREF(mod);
658                 } else {
659                         PyErr_Clear();
660                 }
661         }
662 #endif // non existant yet
663         
664         return 0;
665 }
666
667 /* Update function, it gets rid of pydrivers global dictionary, forcing
668  * BPY_pydriver_eval to recreate it. This function is used to force
669  * reloading the Blender text module "pydrivers.py", if available, so
670  * updates in it reach pydriver evaluation. 
671  */
672 void BPY_pydriver_update(void)
673 {
674         PyGILState_STATE gilstate = PyGILState_Ensure();
675
676         if (bpy_pydriver_Dict) { /* free the global dict used by pydrivers */
677                 PyDict_Clear(bpy_pydriver_Dict);
678                 Py_DECREF(bpy_pydriver_Dict);
679                 bpy_pydriver_Dict = NULL;
680         }
681
682         PyGILState_Release(gilstate);
683
684         return;
685 }
686
687 /* error return function for BPY_eval_pydriver */
688 static float pydriver_error(ChannelDriver *driver) 
689 {
690         if (bpy_pydriver_Dict) { /* free the global dict used by pydrivers */
691                 PyDict_Clear(bpy_pydriver_Dict);
692                 Py_DECREF(bpy_pydriver_Dict);
693                 bpy_pydriver_Dict = NULL;
694         }
695
696         driver->flag |= DRIVER_FLAG_INVALID; /* py expression failed */
697         fprintf(stderr, "\nError in Driver: The following Python expression failed:\n\t'%s'\n\n", driver->expression);
698         
699         BPy_errors_to_report(NULL); // TODO - reports
700
701         return 0.0f;
702 }
703
704 /* This evals py driver expressions, 'expr' is a Python expression that
705  * should evaluate to a float number, which is returned. 
706  */
707 float BPY_pydriver_eval (ChannelDriver *driver)
708 {
709         PyObject *driver_vars=NULL;
710         PyObject *retval;
711         PyGILState_STATE gilstate;
712         
713         DriverTarget *dtar;
714         float result = 0.0f; /* default return */
715         char *expr = NULL;
716         short targets_ok= 1;
717         
718         /* sanity checks - should driver be executed? */
719         if ((driver == NULL) /*|| (G.f & G_DOSCRIPTLINKS)==0*/) 
720                 return result;
721         
722         /* get the py expression to be evaluated */
723         expr = driver->expression; 
724         if ((expr == NULL) || (expr[0]=='\0')) 
725                 return result;
726
727         gilstate = PyGILState_Ensure();
728         
729         /* init global dictionary for py-driver evaluation settings */
730         if (!bpy_pydriver_Dict) {
731                 if (bpy_pydriver_create_dict() != 0) {
732                         fprintf(stderr, "Pydriver error: couldn't create Python dictionary");
733                         PyGILState_Release(gilstate);
734                         return result;
735                 }
736         }
737         
738         /* add target values to a dict that will be used as '__locals__' dict */
739         driver_vars = PyDict_New(); // XXX do we need to decref this?
740         for (dtar= driver->targets.first; dtar; dtar= dtar->next) {
741                 PyObject *driver_arg = NULL;
742                 float tval = 0.0f;
743                 
744                 /* try to get variable value */
745                 tval= driver_get_target_value(driver, dtar);
746                 driver_arg= PyFloat_FromDouble((double)tval);
747                 
748                 /* try to add to dictionary */
749                 if (PyDict_SetItemString(driver_vars, dtar->name, driver_arg)) {
750                         /* this target failed - bad name */
751                         if (targets_ok) {
752                                 /* first one - print some extra info for easier identification */
753                                 fprintf(stderr, "\nBPY_pydriver_eval() - Error while evaluating PyDriver:\n");
754                                 targets_ok= 0;
755                         }
756                         
757                         fprintf(stderr, "\tBPY_pydriver_eval() - couldn't add variable '%s' to namespace \n", dtar->name);
758                         BPy_errors_to_report(NULL); // TODO - reports
759                 }
760         }
761         
762         /* execute expression to get a value */
763         retval = PyRun_String(expr, Py_eval_input, bpy_pydriver_Dict, driver_vars);
764         
765         /* decref the driver vars first...  */
766         Py_DECREF(driver_vars);
767         
768         /* process the result */
769         if (retval == NULL) {
770                 result = pydriver_error(driver);
771                 PyGILState_Release(gilstate);
772                 return result;
773         }
774
775         result = (float)PyFloat_AsDouble(retval);
776         Py_DECREF(retval);
777         
778         if ((result == -1) && PyErr_Occurred()) {
779                 result = pydriver_error(driver);
780                 PyGILState_Release(gilstate);
781                 return result;
782         }
783         
784         /* all fine, make sure the "invalid expression" flag is cleared */
785         driver->flag &= ~DRIVER_FLAG_INVALID;
786
787         PyGILState_Release(gilstate);
788
789         return result;
790 }
791
792 int BPY_button_eval(bContext *C, char *expr, double *value)
793 {
794         PyGILState_STATE gilstate;
795         PyObject *dict, *mod, *retval;
796         int error_ret = 0;
797         
798         if (!value || !expr || expr[0]=='\0') return -1;
799         
800         bpy_context_set(C, &gilstate);
801         
802         dict= CreateGlobalDictionary(C, NULL);
803         
804         /* import some modules: builtins,math*/
805         PyDict_SetItemString(dict, "__builtins__", PyEval_GetBuiltins());
806
807         mod = PyImport_ImportModule("math");
808         if (mod) {
809                 PyDict_Merge(dict, PyModule_GetDict(mod), 0); /* 0 - dont overwrite existing values */
810                 
811                 /* Only keep for backwards compat! - just import all math into root, they are standard */
812                 PyDict_SetItemString(dict, "math", mod);
813                 PyDict_SetItemString(dict, "m", mod);
814                 Py_DECREF(mod);
815         } 
816         
817         retval = PyRun_String(expr, Py_eval_input, dict, dict);
818         
819         if (retval == NULL) {
820                 error_ret= -1;
821         }
822         else {
823                 double val;
824
825                 if(PyTuple_Check(retval)) {
826                         /* Users my have typed in 10km, 2m
827                          * add up all values */
828                         int i;
829                         val= 0.0;
830
831                         for(i=0; i<PyTuple_GET_SIZE(retval); i++) {
832                                 val+= PyFloat_AsDouble(PyTuple_GET_ITEM(retval, i));
833                         }
834                 }
835                 else {
836                         val = PyFloat_AsDouble(retval);
837                 }
838                 Py_DECREF(retval);
839                 
840                 if(val==-1 && PyErr_Occurred()) {
841                         error_ret= -1;
842                 }
843                 else {
844                         *value= val;
845                 }
846         }
847         
848         if(error_ret) {
849                 BPy_errors_to_report(CTX_wm_reports(C));
850         }
851         
852         Py_DECREF(dict);
853         bpy_context_clear(C, &gilstate);
854         
855         return error_ret;
856 }
857
858 void BPY_load_user_modules(bContext *C)
859 {
860         PyGILState_STATE gilstate;
861         Text *text;
862
863         bpy_context_set(C, &gilstate);
864
865         for(text=CTX_data_main(C)->text.first; text; text= text->id.next) {
866                 if(text->flags & TXT_ISSCRIPT && BLI_testextensie(text->id.name+2, ".py")) {
867                         PyObject *module= bpy_text_import(text);
868
869                         if (module==NULL) {
870                                 PyErr_Print();
871                                 PyErr_Clear();
872                         }
873                         else {
874                                 Py_DECREF(module);
875                         }
876                 }
877         }
878         bpy_context_clear(C, &gilstate);
879 }
880
881 int BPY_context_get(bContext *C, const char *member, bContextDataResult *result)
882 {
883         PyObject *pyctx= (PyObject *)CTX_py_dict_get(C);
884         PyObject *item= PyDict_GetItemString(pyctx, member);
885         PointerRNA *ptr= NULL;
886         int done= 0;
887
888         if(item==NULL) {
889                 /* pass */
890         }
891         else if(item==Py_None) {
892                 /* pass */
893         }
894         else if(BPy_StructRNA_Check(item)) {
895                 ptr= &(((BPy_StructRNA *)item)->ptr);
896
897                 //result->ptr= ((BPy_StructRNA *)item)->ptr;
898                 CTX_data_pointer_set(result, ptr->id.data, ptr->type, ptr->data);
899                 done= 1;
900         }
901         else if (PySequence_Check(item)) {
902                 PyObject *seq_fast= PySequence_Fast(item, "bpy_context_get sequence conversion");
903                 if (seq_fast==NULL) {
904                         PyErr_Print();
905                         PyErr_Clear();
906                 }
907                 else {
908                         int len= PySequence_Fast_GET_SIZE(seq_fast);
909                         int i;
910                         for(i = 0; i < len; i++) {
911                                 PyObject *list_item= PySequence_Fast_GET_ITEM(seq_fast, i);
912
913                                 if(BPy_StructRNA_Check(list_item)) {
914                                         /*
915                                         CollectionPointerLink *link= MEM_callocN(sizeof(CollectionPointerLink), "bpy_context_get");
916                                         link->ptr= ((BPy_StructRNA *)item)->ptr;
917                                         BLI_addtail(&result->list, link);
918                                         */
919                                         ptr= &(((BPy_StructRNA *)list_item)->ptr);
920                                         CTX_data_list_add(result, ptr->id.data, ptr->type, ptr->data);
921                                 }
922                                 else {
923                                         printf("List item not a valid type\n");
924                                 }
925
926                         }
927                         Py_DECREF(seq_fast);
928
929                         done= 1;
930                 }
931         }
932
933         if(done==0) {
934                 if (item)       printf("Context '%s' not a valid type\n", member);
935                 else            printf("Context '%s' not found\n", member);
936         }
937         else if (G.f & G_DEBUG) {
938                 printf("Context '%s' found\n", member);
939         }
940
941         return done;
942 }
943