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