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