fix for own missing var in recent commit.
[blender.git] / source / blender / python / intern / bpy_interface.c
1
2 #include <stdio.h>
3 #include <stdlib.h>
4 #include <string.h>
5 #include <sys/stat.h>
6
7 #ifndef WIN32
8 #include <dirent.h>
9 #else
10 #include "BLI_winstuff.h"
11 #endif
12
13 #include <Python.h>
14 #include "compile.h"            /* for the PyCodeObject */
15 #include "eval.h"               /* for PyEval_EvalCode */
16
17 #include "bpy_compat.h"
18
19 #include "bpy_rna.h"
20 #include "bpy_operator.h"
21 #include "bpy_ui.h"
22 #include "bpy_util.h"
23
24 #include "DNA_anim_types.h"
25 #include "DNA_space_types.h"
26 #include "DNA_text_types.h"
27
28 #include "MEM_guardedalloc.h"
29
30 #include "BLI_util.h"
31 #include "BLI_string.h"
32
33 #include "BKE_context.h"
34 #include "BKE_fcurve.h"
35 #include "BKE_text.h"
36
37 #include "BPY_extern.h"
38
39 #include "../generic/bpy_internal_import.h" // our own imports
40 /* external util modules */
41
42 #include "../generic/Mathutils.h"
43 #include "../generic/Geometry.h"
44 #include "../generic/BGL.h"
45
46
47 void BPY_free_compiled_text( struct Text *text )
48 {
49         if( text->compiled ) {
50                 Py_DECREF( ( PyObject * ) text->compiled );
51                 text->compiled = NULL;
52         }
53 }
54
55 /*****************************************************************************
56 * Description: Creates the bpy module and adds it to sys.modules for importing
57 *****************************************************************************/
58 static void bpy_init_modules( void )
59 {
60         PyObject *mod;
61         
62         mod = PyModule_New("bpy");
63         
64         PyModule_AddObject( mod, "data", BPY_rna_module() );
65         /* PyModule_AddObject( mod, "doc", BPY_rna_doc() ); */
66         PyModule_AddObject( mod, "types", BPY_rna_types() );
67         PyModule_AddObject( mod, "props", BPY_rna_props() );
68         PyModule_AddObject( mod, "ops", BPY_operator_module() );
69         PyModule_AddObject( mod, "ui", BPY_ui_module() ); // XXX very experimental, consider this a test, especially PyCObject is not meant to be permanent
70         
71         /* add the module so we can import it */
72         PyDict_SetItemString(PySys_GetObject("modules"), "bpy", mod);
73         Py_DECREF(mod);
74
75
76         /* stand alone utility modules not related to blender directly */
77         Geometry_Init("Geometry");
78         Mathutils_Init("Mathutils");
79         BGL_Init("BGL");
80 }
81
82 #if (PY_VERSION_HEX < 0x02050000)
83 PyObject *PyImport_ImportModuleLevel(char *name, void *a, void *b, void *c, int d)
84 {
85         return PyImport_ImportModule(name);
86 }
87 #endif
88
89 void BPY_update_modules( void )
90 {
91         PyObject *mod= PyImport_ImportModuleLevel("bpy", NULL, NULL, NULL, 0);
92         PyModule_AddObject( mod, "data", BPY_rna_module() );
93         PyModule_AddObject( mod, "types", BPY_rna_types() );
94 }
95
96 /*****************************************************************************
97 * Description: This function creates a new Python dictionary object.
98 *****************************************************************************/
99 static PyObject *CreateGlobalDictionary( bContext *C )
100 {
101         PyObject *mod;
102         PyObject *dict = PyDict_New(  );
103         PyObject *item = PyUnicode_FromString( "__main__" );
104         PyDict_SetItemString( dict, "__builtins__", PyEval_GetBuiltins(  ) );
105         PyDict_SetItemString( dict, "__name__", item );
106         Py_DECREF(item);
107         
108         // XXX - evil, need to access context
109         BPy_SetContext(C);
110         
111         // XXX - put somewhere more logical
112         {
113                 PyMethodDef *ml;
114                 static PyMethodDef bpy_prop_meths[] = {
115                         {"FloatProperty", (PyCFunction)BPy_FloatProperty, METH_VARARGS|METH_KEYWORDS, ""},
116                         {"IntProperty", (PyCFunction)BPy_IntProperty, METH_VARARGS|METH_KEYWORDS, ""},
117                         {"BoolProperty", (PyCFunction)BPy_BoolProperty, METH_VARARGS|METH_KEYWORDS, ""},
118                         {"StringProperty", (PyCFunction)BPy_StringProperty, METH_VARARGS|METH_KEYWORDS, ""},
119                         {NULL, NULL, 0, NULL}
120                 };
121                 
122                 for(ml = bpy_prop_meths; ml->ml_name; ml++) {
123                         PyDict_SetItemString( dict, ml->ml_name, PyCFunction_New(ml, NULL));
124                 }
125         }
126         
127         /* add bpy to global namespace */
128         mod= PyImport_ImportModuleLevel("bpy", NULL, NULL, NULL, 0);
129         PyDict_SetItemString( dict, "bpy", mod );
130         Py_DECREF(mod);
131         
132         return dict;
133 }
134
135 /* Use this so we can include our own python bundle */
136 #if 0
137 wchar_t* Py_GetPath(void)
138 {
139         int i;
140         static wchar_t py_path[FILE_MAXDIR] = L"";
141         char *dirname= BLI_gethome_folder("python");
142         if(dirname) {
143                 i= mbstowcs(py_path, dirname, FILE_MAXDIR);
144                 printf("py path %s, %d\n", dirname, i);
145         }
146         return py_path;
147 }
148 #endif
149
150
151 /* must be called before Py_Initialize */
152 void BPY_start_python_path(void)
153 {
154         char py_path[FILE_MAXDIR + 11] = "";
155         char *py_path_bundle= BLI_gethome_folder("python");
156
157         if(py_path_bundle==NULL)
158                 return;
159
160         /* set the environment path */
161         printf("found bundled python: %s\n", py_path_bundle);
162
163 #if (defined(WIN32) || defined(WIN64))
164 #if defined(FREE_WINDOWS)
165         sprintf(py_path, "PYTHONPATH=%s", py_path_bundle)
166         putenv(py_path);
167 #else
168         _putenv_s("PYTHONPATH", py_path_bundle);
169 #endif
170 #else
171 #ifdef __sgi
172         sprintf(py_path, "PYTHONPATH=%s", py_path_bundle)
173         putenv(py_path);
174 #else
175         setenv("PYTHONPATH", py_path_bundle, 1);
176 #endif
177 #endif
178
179 }
180
181
182 void BPY_start_python( int argc, char **argv )
183 {
184         PyThreadState *py_tstate = NULL;
185         
186         BPY_start_python_path(); /* allow to use our own included python */
187
188         Py_Initialize(  );
189         
190         //PySys_SetArgv( argc_copy, argv_copy );
191         
192         /* Initialize thread support (also acquires lock) */
193         PyEval_InitThreads();
194         
195         
196         /* bpy.* and lets us import it */
197         bpy_init_modules(); 
198
199         { /* our own import and reload functions */
200                 PyObject *item;
201                 //PyObject *m = PyImport_AddModule("__builtin__");
202                 //PyObject *d = PyModule_GetDict(m);
203                 PyObject *d = PyEval_GetBuiltins(  );
204                 PyDict_SetItemString(d, "reload",               item=PyCFunction_New(bpy_reload_meth, NULL));   Py_DECREF(item);
205                 PyDict_SetItemString(d, "__import__",   item=PyCFunction_New(bpy_import_meth, NULL));   Py_DECREF(item);
206         }
207         
208         py_tstate = PyGILState_GetThisThreadState();
209         PyEval_ReleaseThread(py_tstate);
210 }
211
212 void BPY_end_python( void )
213 {
214         PyGILState_Ensure(); /* finalizing, no need to grab the state */
215         
216         // free other python data.
217         //BPY_rna_free_types();
218         
219         Py_Finalize(  );
220         
221         return;
222 }
223
224 /* Can run a file or text block */
225 int BPY_run_python_script( bContext *C, const char *fn, struct Text *text, struct ReportList *reports)
226 {
227         PyObject *py_dict, *py_result;
228         PyGILState_STATE gilstate;
229         
230         if (fn==NULL && text==NULL) {
231                 return 0;
232         }
233         
234         //BPY_start_python();
235         
236         gilstate = PyGILState_Ensure();
237
238         BPY_update_modules(); /* can give really bad results if this isnt here */
239         bpy_import_main_set(CTX_data_main(C));
240         
241         py_dict = CreateGlobalDictionary(C);
242
243         if (text) {
244                 
245                 if( !text->compiled ) { /* if it wasn't already compiled, do it now */
246                         char *buf = txt_to_buf( text );
247
248                         text->compiled =
249                                 Py_CompileString( buf, text->id.name+2, Py_file_input );
250
251                         MEM_freeN( buf );
252
253                         if( PyErr_Occurred(  ) ) {
254                                 BPy_errors_to_report(reports);
255                                 BPY_free_compiled_text( text );
256                                 PyGILState_Release(gilstate);
257                                 return 0;
258                         }
259                 }
260                 py_result =  PyEval_EvalCode( text->compiled, py_dict, py_dict );
261                 
262         } else {
263                 char pystring[512];
264                 /* TODO - look into a better way to run a file */
265                 sprintf(pystring, "exec(open(r'%s').read())", fn);      
266                 py_result = PyRun_String( pystring, Py_file_input, py_dict, py_dict );                  
267         }
268         
269         if (!py_result) {
270                 BPy_errors_to_report(reports);
271         } else {
272                 Py_DECREF( py_result );
273         }
274         
275         Py_DECREF(py_dict);
276         PyGILState_Release(gilstate);
277         bpy_import_main_set(NULL);
278         
279         //BPY_end_python();
280         return py_result ? 1:0;
281 }
282
283
284 /* TODO - move into bpy_space.c ? */
285 /* GUI interface routines */
286
287 /* Copied from Draw.c */
288 static void exit_pydraw( SpaceScript * sc, short err )
289 {
290         Script *script = NULL;
291
292         if( !sc || !sc->script )
293                 return;
294
295         script = sc->script;
296
297         if( err ) {
298                 BPy_errors_to_report(NULL); // TODO, reports
299                 script->flags = 0;      /* mark script struct for deletion */
300                 SCRIPT_SET_NULL(script);
301                 script->scriptname[0] = '\0';
302                 script->scriptarg[0] = '\0';
303 // XXX 2.5              error_pyscript();
304 // XXX 2.5              scrarea_queue_redraw( sc->area );
305         }
306
307 #if 0 // XXX 2.5
308         BPy_Set_DrawButtonsList(sc->but_refs);
309         BPy_Free_DrawButtonsList(); /*clear all temp button references*/
310 #endif
311
312         sc->but_refs = NULL;
313         
314         Py_XDECREF( ( PyObject * ) script->py_draw );
315         Py_XDECREF( ( PyObject * ) script->py_event );
316         Py_XDECREF( ( PyObject * ) script->py_button );
317
318         script->py_draw = script->py_event = script->py_button = NULL;
319 }
320
321 static int bpy_run_script_init(bContext *C, SpaceScript * sc)
322 {
323         if (sc->script==NULL) 
324                 return 0;
325         
326         if (sc->script->py_draw==NULL && sc->script->scriptname[0] != '\0')
327                 BPY_run_python_script(C, sc->script->scriptname, NULL, NULL);
328                 
329         if (sc->script->py_draw==NULL)
330                 return 0;
331         
332         return 1;
333 }
334
335 int BPY_run_script_space_draw(struct bContext *C, SpaceScript * sc)
336 {
337         if (bpy_run_script_init(C, sc)) {
338                 PyGILState_STATE gilstate = PyGILState_Ensure();
339                 PyObject *result = PyObject_CallObject( sc->script->py_draw, NULL );
340                 
341                 if (result==NULL)
342                         exit_pydraw(sc, 1);
343                         
344                 PyGILState_Release(gilstate);
345         }
346         return 1;
347 }
348
349 // XXX - not used yet, listeners dont get a context
350 int BPY_run_script_space_listener(bContext *C, SpaceScript * sc)
351 {
352         if (bpy_run_script_init(C, sc)) {
353                 PyGILState_STATE gilstate = PyGILState_Ensure();
354                 
355                 PyObject *result = PyObject_CallObject( sc->script->py_draw, NULL );
356                 
357                 if (result==NULL)
358                         exit_pydraw(sc, 1);
359                         
360                 PyGILState_Release(gilstate);
361         }
362         return 1;
363 }
364
365 void BPY_DECREF(void *pyob_ptr)
366 {
367         Py_DECREF((PyObject *)pyob_ptr);
368 }
369
370 #if 0
371 /* called from the the scripts window, assume context is ok */
372 int BPY_run_python_script_space(const char *modulename, const char *func)
373 {
374         PyObject *py_dict, *py_result= NULL;
375         char pystring[512];
376         PyGILState_STATE gilstate;
377         
378         /* for calling the module function */
379         PyObject *py_func, 
380         
381         gilstate = PyGILState_Ensure();
382         
383         py_dict = CreateGlobalDictionary(C);
384         
385         PyObject *module = PyImport_ImportModule(scpt->script.filename);
386         if (module==NULL) {
387                 PyErr_SetFormat(PyExc_SystemError, "could not import '%s'", scpt->script.filename);
388         }
389         else {
390                 py_func = PyObject_GetAttrString(modulename, func);
391                 if (py_func==NULL) {
392                         PyErr_SetFormat(PyExc_SystemError, "module has no function '%s.%s'\n", scpt->script.filename, func);
393                 }
394                 else {
395                         Py_DECREF(py_func);
396                         if (!PyCallable_Check(py_func)) {
397                                 PyErr_SetFormat(PyExc_SystemError, "module item is not callable '%s.%s'\n", scpt->script.filename, func);
398                         }
399                         else {
400                                 py_result= PyObject_CallObject(py_func, NULL); // XXX will need args eventually
401                         }
402                 }
403         }
404         
405         if (!py_result) {
406                 BPy_errors_to_report(NULL); // TODO - reports
407         } else
408                 Py_DECREF( py_result );
409         
410         Py_XDECREF(module);
411         
412         Py_DECREF(py_dict);
413         
414         PyGILState_Release(gilstate);
415         return 1;
416 }
417 #endif
418
419 // #define TIME_REGISTRATION
420
421 #ifdef TIME_REGISTRATION
422 #include "PIL_time.h"
423 #endif
424
425 /* XXX this is temporary, need a proper script registration system for 2.5 */
426 void BPY_run_ui_scripts(bContext *C, int reload)
427 {
428 #ifdef TIME_REGISTRATION
429         double time = PIL_check_seconds_timer();
430 #endif
431         DIR *dir; 
432         struct dirent *de;
433         char *file_extension;
434         char *dirname;
435         char path[FILE_MAX];
436         char *dirs[] = {"io", "ui", NULL};
437         int a, filelen; /* filename length */
438         
439         PyGILState_STATE gilstate;
440         PyObject *mod;
441         PyObject *sys_path_orig;
442         PyObject *sys_path_new;
443
444         gilstate = PyGILState_Ensure();
445         
446         // XXX - evil, need to access context
447         BPy_SetContext(C);
448         bpy_import_main_set(CTX_data_main(C));
449
450         for(a=0; dirs[a]; a++) {
451                 dirname= BLI_gethome_folder(dirs[a]);
452
453                 if(!dirname)
454                         continue;
455
456                 dir = opendir(dirname);
457
458                 if(!dir)
459                         continue;
460
461                 /* backup sys.path */
462                 sys_path_orig= PySys_GetObject("path");
463                 Py_INCREF(sys_path_orig); /* dont free it */
464                 
465                 sys_path_new= PyList_New(1);
466                 PyList_SET_ITEM(sys_path_new, 0, PyUnicode_FromString(dirname));
467                 PySys_SetObject("path", sys_path_new);
468                 Py_DECREF(sys_path_new);
469                         
470                 while((de = readdir(dir)) != NULL) {
471                         /* We could stat the file but easier just to let python
472                          * import it and complain if theres a problem */
473                         
474                         file_extension = strstr(de->d_name, ".py");
475                         
476                         if(file_extension && *(file_extension + 3) == '\0') {
477                                 filelen = strlen(de->d_name);
478                                 BLI_strncpy(path, de->d_name, filelen-2); /* cut off the .py on copy */
479                                 
480                                 mod= PyImport_ImportModuleLevel(path, NULL, NULL, NULL, 0);
481                                 if (mod) {
482                                         if (reload) {
483                                                 PyObject *mod_orig= mod;
484                                                 mod= PyImport_ReloadModule(mod);
485                                                 Py_DECREF(mod_orig);
486                                         }
487                                 }
488                                 
489                                 if(mod) {
490                                         Py_DECREF(mod); /* could be NULL from reloading */
491                                 } else {
492                                         BPy_errors_to_report(NULL); // TODO - reports
493                                         fprintf(stderr, "unable to import \"%s\"  %s/%s\n", path, dirname, de->d_name);
494                                 }
495
496                         }
497                 }
498
499                 closedir(dir);
500
501                 PySys_SetObject("path", sys_path_orig);
502                 Py_DECREF(sys_path_orig);
503         }
504         
505         bpy_import_main_set(NULL);
506         
507         PyGILState_Release(gilstate);
508 #ifdef TIME_REGISTRATION
509         printf("script time %f\n", (PIL_check_seconds_timer()-time));
510 #endif
511 }
512
513 /* ****************************************** */
514 /* Drivers - PyExpression Evaluation */
515
516 /* for pydrivers (drivers using one-line Python expressions to express relationships between targets) */
517 PyObject *bpy_pydriver_Dict = NULL;
518
519 /* For faster execution we keep a special dictionary for pydrivers, with
520  * the needed modules and aliases. 
521  */
522 static int bpy_pydriver_create_dict(void)
523 {
524         PyObject *d, *mod;
525         
526         /* validate namespace for driver evaluation */
527         if (bpy_pydriver_Dict) return -1;
528
529         d = PyDict_New();
530         if (d == NULL) 
531                 return -1;
532         else
533                 bpy_pydriver_Dict = d;
534
535         /* import some modules: builtins, bpy, math, (Blender.noise )*/
536         PyDict_SetItemString(d, "__builtins__", PyEval_GetBuiltins());
537
538         mod = PyImport_ImportModule("math");
539         if (mod) {
540                 PyDict_Merge(d, PyModule_GetDict(mod), 0); /* 0 - dont overwrite existing values */
541                 
542                 /* Only keep for backwards compat! - just import all math into root, they are standard */
543                 PyDict_SetItemString(d, "math", mod);
544                 PyDict_SetItemString(d, "m", mod);
545                 Py_DECREF(mod);
546         } 
547         
548         /* add bpy to global namespace */
549         mod= PyImport_ImportModuleLevel("bpy", NULL, NULL, NULL, 0);
550         if (mod) {
551                 PyDict_SetItemString(bpy_pydriver_Dict, "bpy", mod);
552                 Py_DECREF(mod);
553         }
554         
555         
556 #if 0 // non existant yet
557         mod = PyImport_ImportModule("Blender.Noise");
558         if (mod) {
559                 PyDict_SetItemString(d, "noise", mod);
560                 PyDict_SetItemString(d, "n", mod);
561                 Py_DECREF(mod);
562         } else {
563                 PyErr_Clear();
564         }
565         
566         /* If there's a Blender text called pydrivers.py, import it.
567          * Users can add their own functions to this module. 
568          */
569         if (G.f & G_DOSCRIPTLINKS) {
570                 mod = importText("pydrivers"); /* can also use PyImport_Import() */
571                 if (mod) {
572                         PyDict_SetItemString(d, "pydrivers", mod);
573                         PyDict_SetItemString(d, "p", mod);
574                         Py_DECREF(mod);
575                 } else {
576                         PyErr_Clear();
577                 }
578         }
579 #endif // non existant yet
580         
581         return 0;
582 }
583
584 /* Update function, it gets rid of pydrivers global dictionary, forcing
585  * BPY_pydriver_eval to recreate it. This function is used to force
586  * reloading the Blender text module "pydrivers.py", if available, so
587  * updates in it reach pydriver evaluation. 
588  */
589 void BPY_pydriver_update(void)
590 {
591         PyGILState_STATE gilstate = PyGILState_Ensure();
592
593         if (bpy_pydriver_Dict) { /* free the global dict used by pydrivers */
594                 PyDict_Clear(bpy_pydriver_Dict);
595                 Py_DECREF(bpy_pydriver_Dict);
596                 bpy_pydriver_Dict = NULL;
597         }
598
599         PyGILState_Release(gilstate);
600
601         return;
602 }
603
604 /* error return function for BPY_eval_pydriver */
605 static float pydriver_error(ChannelDriver *driver) 
606 {
607         if (bpy_pydriver_Dict) { /* free the global dict used by pydrivers */
608                 PyDict_Clear(bpy_pydriver_Dict);
609                 Py_DECREF(bpy_pydriver_Dict);
610                 bpy_pydriver_Dict = NULL;
611         }
612
613         driver->flag |= DRIVER_FLAG_INVALID; /* py expression failed */
614         fprintf(stderr, "\nError in Driver: The following Python expression failed:\n\t'%s'\n\n", driver->expression);
615         
616         BPy_errors_to_report(NULL); // TODO - reports
617
618         return 0.0f;
619 }
620
621 /* This evals py driver expressions, 'expr' is a Python expression that
622  * should evaluate to a float number, which is returned. 
623  */
624 float BPY_pydriver_eval (ChannelDriver *driver)
625 {
626         PyObject *driver_vars=NULL;
627         PyObject *retval;
628         PyGILState_STATE gilstate;
629         
630         DriverTarget *dtar;
631         float result = 0.0f; /* default return */
632         char *expr = NULL;
633         short targets_ok= 1;
634         
635         /* sanity checks - should driver be executed? */
636         if ((driver == NULL) /*|| (G.f & G_DOSCRIPTLINKS)==0*/) 
637                 return result;
638         
639         /* get the py expression to be evaluated */
640         expr = driver->expression; 
641         if ((expr == NULL) || (expr[0]=='\0')) 
642                 return result;
643
644         gilstate = PyGILState_Ensure();
645         
646         /* init global dictionary for py-driver evaluation settings */
647         if (!bpy_pydriver_Dict) {
648                 if (bpy_pydriver_create_dict() != 0) {
649                         fprintf(stderr, "Pydriver error: couldn't create Python dictionary");
650                         PyGILState_Release(gilstate);
651                         return result;
652                 }
653         }
654         
655         /* add target values to a dict that will be used as '__locals__' dict */
656         driver_vars = PyDict_New(); // XXX do we need to decref this?
657         for (dtar= driver->targets.first; dtar; dtar= dtar->next) {
658                 PyObject *driver_arg = NULL;
659                 float tval = 0.0f;
660                 
661                 /* try to get variable value */
662                 tval= driver_get_target_value(driver, dtar);
663                 driver_arg= PyFloat_FromDouble((double)tval);
664                 
665                 /* try to add to dictionary */
666                 if (PyDict_SetItemString(driver_vars, dtar->name, driver_arg)) {
667                         /* this target failed - bad name */
668                         if (targets_ok) {
669                                 /* first one - print some extra info for easier identification */
670                                 fprintf(stderr, "\nBPY_pydriver_eval() - Error while evaluating PyDriver:\n");
671                                 targets_ok= 0;
672                         }
673                         
674                         fprintf(stderr, "\tBPY_pydriver_eval() - couldn't add variable '%s' to namespace \n", dtar->name);
675                         BPy_errors_to_report(NULL); // TODO - reports
676                 }
677         }
678         
679         /* execute expression to get a value */
680         retval = PyRun_String(expr, Py_eval_input, bpy_pydriver_Dict, driver_vars);
681         
682         /* decref the driver vars first...  */
683         Py_DECREF(driver_vars);
684         
685         /* process the result */
686         if (retval == NULL) {
687                 result = pydriver_error(driver);
688                 PyGILState_Release(gilstate);
689                 return result;
690         }
691
692         result = (float)PyFloat_AsDouble(retval);
693         Py_DECREF(retval);
694         
695         if ((result == -1) && PyErr_Occurred()) {
696                 result = pydriver_error(driver);
697                 PyGILState_Release(gilstate);
698                 return result;
699         }
700         
701         /* all fine, make sure the "invalid expression" flag is cleared */
702         driver->flag &= ~DRIVER_FLAG_INVALID;
703
704         PyGILState_Release(gilstate);
705
706         return result;
707 }