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