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