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