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