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