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