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