set the PYTHONPATH to BLI_gethome_folder("python") if it exists.
[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_bundle= BLI_gethome_folder("python");
155
156         if(py_path_bundle==NULL)
157                 return;
158
159         /* set the environment path */
160         printf("found bundled python: %s\n", py_path_bundle);
161
162 #if (defined(WIN32) || defined(WIN64))
163 #if defined(FREE_WINDOWS)
164         sprintf(py_path, "PYTHONPATH=%s", py_path_bundle)
165         putenv(py_path);
166 #else
167         _putenv_s("PYTHONPATH", py_path_bundle);
168 #endif
169 #else
170 #ifdef __sgi
171         sprintf(py_path, "PYTHONPATH=%s", py_path_bundle)
172         putenv(py_path);
173 #else
174         setenv("PYTHONPATH", py_path_bundle, 1); /* initializing the video driver can cause crashes on some systems - Campbell */
175 #endif
176 #endif
177
178 }
179
180
181 void BPY_start_python( int argc, char **argv )
182 {
183         PyThreadState *py_tstate = NULL;
184         
185         BPY_start_python_path(); /* allow to use our own included python */
186
187         Py_Initialize(  );
188         
189         //PySys_SetArgv( argc_copy, argv_copy );
190         
191         /* Initialize thread support (also acquires lock) */
192         PyEval_InitThreads();
193         
194         
195         /* bpy.* and lets us import it */
196         bpy_init_modules(); 
197
198         { /* our own import and reload functions */
199                 PyObject *item;
200                 //PyObject *m = PyImport_AddModule("__builtin__");
201                 //PyObject *d = PyModule_GetDict(m);
202                 PyObject *d = PyEval_GetBuiltins(  );
203                 PyDict_SetItemString(d, "reload",               item=PyCFunction_New(bpy_reload_meth, NULL));   Py_DECREF(item);
204                 PyDict_SetItemString(d, "__import__",   item=PyCFunction_New(bpy_import_meth, NULL));   Py_DECREF(item);
205         }
206         
207         py_tstate = PyGILState_GetThisThreadState();
208         PyEval_ReleaseThread(py_tstate);
209 }
210
211 void BPY_end_python( void )
212 {
213         PyGILState_Ensure(); /* finalizing, no need to grab the state */
214         
215         // free other python data.
216         //BPY_rna_free_types();
217         
218         Py_Finalize(  );
219         
220         return;
221 }
222
223 /* Can run a file or text block */
224 int BPY_run_python_script( bContext *C, const char *fn, struct Text *text, struct ReportList *reports)
225 {
226         PyObject *py_dict, *py_result;
227         PyGILState_STATE gilstate;
228         
229         if (fn==NULL && text==NULL) {
230                 return 0;
231         }
232         
233         //BPY_start_python();
234         
235         gilstate = PyGILState_Ensure();
236
237         BPY_update_modules(); /* can give really bad results if this isnt here */
238         bpy_import_main_set(CTX_data_main(C));
239         
240         py_dict = CreateGlobalDictionary(C);
241
242         if (text) {
243                 
244                 if( !text->compiled ) { /* if it wasn't already compiled, do it now */
245                         char *buf = txt_to_buf( text );
246
247                         text->compiled =
248                                 Py_CompileString( buf, text->id.name+2, Py_file_input );
249
250                         MEM_freeN( buf );
251
252                         if( PyErr_Occurred(  ) ) {
253                                 BPy_errors_to_report(reports);
254                                 BPY_free_compiled_text( text );
255                                 PyGILState_Release(gilstate);
256                                 return 0;
257                         }
258                 }
259                 py_result =  PyEval_EvalCode( text->compiled, py_dict, py_dict );
260                 
261         } else {
262                 char pystring[512];
263                 /* TODO - look into a better way to run a file */
264                 sprintf(pystring, "exec(open(r'%s').read())", fn);      
265                 py_result = PyRun_String( pystring, Py_file_input, py_dict, py_dict );                  
266         }
267         
268         if (!py_result) {
269                 BPy_errors_to_report(reports);
270         } else {
271                 Py_DECREF( py_result );
272         }
273         
274         Py_DECREF(py_dict);
275         PyGILState_Release(gilstate);
276         bpy_import_main_set(NULL);
277         
278         //BPY_end_python();
279         return py_result ? 1:0;
280 }
281
282
283 /* TODO - move into bpy_space.c ? */
284 /* GUI interface routines */
285
286 /* Copied from Draw.c */
287 static void exit_pydraw( SpaceScript * sc, short err )
288 {
289         Script *script = NULL;
290
291         if( !sc || !sc->script )
292                 return;
293
294         script = sc->script;
295
296         if( err ) {
297                 BPy_errors_to_report(NULL); // TODO, reports
298                 script->flags = 0;      /* mark script struct for deletion */
299                 SCRIPT_SET_NULL(script);
300                 script->scriptname[0] = '\0';
301                 script->scriptarg[0] = '\0';
302 // XXX 2.5              error_pyscript();
303 // XXX 2.5              scrarea_queue_redraw( sc->area );
304         }
305
306 #if 0 // XXX 2.5
307         BPy_Set_DrawButtonsList(sc->but_refs);
308         BPy_Free_DrawButtonsList(); /*clear all temp button references*/
309 #endif
310
311         sc->but_refs = NULL;
312         
313         Py_XDECREF( ( PyObject * ) script->py_draw );
314         Py_XDECREF( ( PyObject * ) script->py_event );
315         Py_XDECREF( ( PyObject * ) script->py_button );
316
317         script->py_draw = script->py_event = script->py_button = NULL;
318 }
319
320 static int bpy_run_script_init(bContext *C, SpaceScript * sc)
321 {
322         if (sc->script==NULL) 
323                 return 0;
324         
325         if (sc->script->py_draw==NULL && sc->script->scriptname[0] != '\0')
326                 BPY_run_python_script(C, sc->script->scriptname, NULL, NULL);
327                 
328         if (sc->script->py_draw==NULL)
329                 return 0;
330         
331         return 1;
332 }
333
334 int BPY_run_script_space_draw(struct bContext *C, SpaceScript * sc)
335 {
336         if (bpy_run_script_init(C, sc)) {
337                 PyGILState_STATE gilstate = PyGILState_Ensure();
338                 PyObject *result = PyObject_CallObject( sc->script->py_draw, NULL );
339                 
340                 if (result==NULL)
341                         exit_pydraw(sc, 1);
342                         
343                 PyGILState_Release(gilstate);
344         }
345         return 1;
346 }
347
348 // XXX - not used yet, listeners dont get a context
349 int BPY_run_script_space_listener(bContext *C, SpaceScript * sc)
350 {
351         if (bpy_run_script_init(C, sc)) {
352                 PyGILState_STATE gilstate = PyGILState_Ensure();
353                 
354                 PyObject *result = PyObject_CallObject( sc->script->py_draw, NULL );
355                 
356                 if (result==NULL)
357                         exit_pydraw(sc, 1);
358                         
359                 PyGILState_Release(gilstate);
360         }
361         return 1;
362 }
363
364 void BPY_DECREF(void *pyob_ptr)
365 {
366         Py_DECREF((PyObject *)pyob_ptr);
367 }
368
369 #if 0
370 /* called from the the scripts window, assume context is ok */
371 int BPY_run_python_script_space(const char *modulename, const char *func)
372 {
373         PyObject *py_dict, *py_result= NULL;
374         char pystring[512];
375         PyGILState_STATE gilstate;
376         
377         /* for calling the module function */
378         PyObject *py_func, 
379         
380         gilstate = PyGILState_Ensure();
381         
382         py_dict = CreateGlobalDictionary(C);
383         
384         PyObject *module = PyImport_ImportModule(scpt->script.filename);
385         if (module==NULL) {
386                 PyErr_SetFormat(PyExc_SystemError, "could not import '%s'", scpt->script.filename);
387         }
388         else {
389                 py_func = PyObject_GetAttrString(modulename, func);
390                 if (py_func==NULL) {
391                         PyErr_SetFormat(PyExc_SystemError, "module has no function '%s.%s'\n", scpt->script.filename, func);
392                 }
393                 else {
394                         Py_DECREF(py_func);
395                         if (!PyCallable_Check(py_func)) {
396                                 PyErr_SetFormat(PyExc_SystemError, "module item is not callable '%s.%s'\n", scpt->script.filename, func);
397                         }
398                         else {
399                                 py_result= PyObject_CallObject(py_func, NULL); // XXX will need args eventually
400                         }
401                 }
402         }
403         
404         if (!py_result) {
405                 BPy_errors_to_report(NULL); // TODO - reports
406         } else
407                 Py_DECREF( py_result );
408         
409         Py_XDECREF(module);
410         
411         Py_DECREF(py_dict);
412         
413         PyGILState_Release(gilstate);
414         return 1;
415 }
416 #endif
417
418 // #define TIME_REGISTRATION
419
420 #ifdef TIME_REGISTRATION
421 #include "PIL_time.h"
422 #endif
423
424 /* XXX this is temporary, need a proper script registration system for 2.5 */
425 void BPY_run_ui_scripts(bContext *C, int reload)
426 {
427 #ifdef TIME_REGISTRATION
428         double time = PIL_check_seconds_timer();
429 #endif
430         DIR *dir; 
431         struct dirent *de;
432         char *file_extension;
433         char *dirname;
434         char path[FILE_MAX];
435         char *dirs[] = {"io", "ui", NULL};
436         int a, filelen; /* filename length */
437         
438         PyGILState_STATE gilstate;
439         PyObject *mod;
440         PyObject *sys_path_orig;
441         PyObject *sys_path_new;
442
443         gilstate = PyGILState_Ensure();
444         
445         // XXX - evil, need to access context
446         BPy_SetContext(C);
447         bpy_import_main_set(CTX_data_main(C));
448
449         for(a=0; dirs[a]; a++) {
450                 dirname= BLI_gethome_folder(dirs[a]);
451
452                 if(!dirname)
453                         continue;
454
455                 dir = opendir(dirname);
456
457                 if(!dir)
458                         continue;
459
460                 /* backup sys.path */
461                 sys_path_orig= PySys_GetObject("path");
462                 Py_INCREF(sys_path_orig); /* dont free it */
463                 
464                 sys_path_new= PyList_New(1);
465                 PyList_SET_ITEM(sys_path_new, 0, PyUnicode_FromString(dirname));
466                 PySys_SetObject("path", sys_path_new);
467                 Py_DECREF(sys_path_new);
468                         
469                 while((de = readdir(dir)) != NULL) {
470                         /* We could stat the file but easier just to let python
471                          * import it and complain if theres a problem */
472                         
473                         file_extension = strstr(de->d_name, ".py");
474                         
475                         if(file_extension && *(file_extension + 3) == '\0') {
476                                 filelen = strlen(de->d_name);
477                                 BLI_strncpy(path, de->d_name, filelen-2); /* cut off the .py on copy */
478                                 
479                                 mod= PyImport_ImportModuleLevel(path, NULL, NULL, NULL, 0);
480                                 if (mod) {
481                                         if (reload) {
482                                                 PyObject *mod_orig= mod;
483                                                 mod= PyImport_ReloadModule(mod);
484                                                 Py_DECREF(mod_orig);
485                                         }
486                                 }
487                                 
488                                 if(mod) {
489                                         Py_DECREF(mod); /* could be NULL from reloading */
490                                 } else {
491                                         BPy_errors_to_report(NULL); // TODO - reports
492                                         fprintf(stderr, "unable to import \"%s\"  %s/%s\n", path, dirname, de->d_name);
493                                 }
494
495                         }
496                 }
497
498                 closedir(dir);
499
500                 PySys_SetObject("path", sys_path_orig);
501                 Py_DECREF(sys_path_orig);
502         }
503         
504         bpy_import_main_set(NULL);
505         
506         PyGILState_Release(gilstate);
507 #ifdef TIME_REGISTRATION
508         printf("script time %f\n", (PIL_check_seconds_timer()-time));
509 #endif
510 }
511
512 /* ****************************************** */
513 /* Drivers - PyExpression Evaluation */
514
515 /* for pydrivers (drivers using one-line Python expressions to express relationships between targets) */
516 PyObject *bpy_pydriver_Dict = NULL;
517
518 /* For faster execution we keep a special dictionary for pydrivers, with
519  * the needed modules and aliases. 
520  */
521 static int bpy_pydriver_create_dict(void)
522 {
523         PyObject *d, *mod;
524         
525         /* validate namespace for driver evaluation */
526         if (bpy_pydriver_Dict) return -1;
527
528         d = PyDict_New();
529         if (d == NULL) 
530                 return -1;
531         else
532                 bpy_pydriver_Dict = d;
533
534         /* import some modules: builtins, bpy, math, (Blender.noise )*/
535         PyDict_SetItemString(d, "__builtins__", PyEval_GetBuiltins());
536
537         mod = PyImport_ImportModule("math");
538         if (mod) {
539                 PyDict_Merge(d, PyModule_GetDict(mod), 0); /* 0 - dont overwrite existing values */
540                 
541                 /* Only keep for backwards compat! - just import all math into root, they are standard */
542                 PyDict_SetItemString(d, "math", mod);
543                 PyDict_SetItemString(d, "m", mod);
544                 Py_DECREF(mod);
545         } 
546         
547         /* add bpy to global namespace */
548         mod= PyImport_ImportModuleLevel("bpy", NULL, NULL, NULL, 0);
549         if (mod) {
550                 PyDict_SetItemString(bpy_pydriver_Dict, "bpy", mod);
551                 Py_DECREF(mod);
552         }
553         
554         
555 #if 0 // non existant yet
556         mod = PyImport_ImportModule("Blender.Noise");
557         if (mod) {
558                 PyDict_SetItemString(d, "noise", mod);
559                 PyDict_SetItemString(d, "n", mod);
560                 Py_DECREF(mod);
561         } else {
562                 PyErr_Clear();
563         }
564         
565         /* If there's a Blender text called pydrivers.py, import it.
566          * Users can add their own functions to this module. 
567          */
568         if (G.f & G_DOSCRIPTLINKS) {
569                 mod = importText("pydrivers"); /* can also use PyImport_Import() */
570                 if (mod) {
571                         PyDict_SetItemString(d, "pydrivers", mod);
572                         PyDict_SetItemString(d, "p", mod);
573                         Py_DECREF(mod);
574                 } else {
575                         PyErr_Clear();
576                 }
577         }
578 #endif // non existant yet
579         
580         return 0;
581 }
582
583 /* Update function, it gets rid of pydrivers global dictionary, forcing
584  * BPY_pydriver_eval to recreate it. This function is used to force
585  * reloading the Blender text module "pydrivers.py", if available, so
586  * updates in it reach pydriver evaluation. 
587  */
588 void BPY_pydriver_update(void)
589 {
590         PyGILState_STATE gilstate = PyGILState_Ensure();
591
592         if (bpy_pydriver_Dict) { /* free the global dict used by pydrivers */
593                 PyDict_Clear(bpy_pydriver_Dict);
594                 Py_DECREF(bpy_pydriver_Dict);
595                 bpy_pydriver_Dict = NULL;
596         }
597
598         PyGILState_Release(gilstate);
599
600         return;
601 }
602
603 /* error return function for BPY_eval_pydriver */
604 static float pydriver_error(ChannelDriver *driver) 
605 {
606         if (bpy_pydriver_Dict) { /* free the global dict used by pydrivers */
607                 PyDict_Clear(bpy_pydriver_Dict);
608                 Py_DECREF(bpy_pydriver_Dict);
609                 bpy_pydriver_Dict = NULL;
610         }
611
612         driver->flag |= DRIVER_FLAG_INVALID; /* py expression failed */
613         fprintf(stderr, "\nError in Driver: The following Python expression failed:\n\t'%s'\n\n", driver->expression);
614         
615         BPy_errors_to_report(NULL); // TODO - reports
616
617         return 0.0f;
618 }
619
620 /* This evals py driver expressions, 'expr' is a Python expression that
621  * should evaluate to a float number, which is returned. 
622  */
623 float BPY_pydriver_eval (ChannelDriver *driver)
624 {
625         PyObject *driver_vars=NULL;
626         PyObject *retval;
627         PyGILState_STATE gilstate;
628         
629         DriverTarget *dtar;
630         float result = 0.0f; /* default return */
631         char *expr = NULL;
632         short targets_ok= 1;
633         
634         /* sanity checks - should driver be executed? */
635         if ((driver == NULL) /*|| (G.f & G_DOSCRIPTLINKS)==0*/) 
636                 return result;
637         
638         /* get the py expression to be evaluated */
639         expr = driver->expression; 
640         if ((expr == NULL) || (expr[0]=='\0')) 
641                 return result;
642
643         gilstate = PyGILState_Ensure();
644         
645         /* init global dictionary for py-driver evaluation settings */
646         if (!bpy_pydriver_Dict) {
647                 if (bpy_pydriver_create_dict() != 0) {
648                         fprintf(stderr, "Pydriver error: couldn't create Python dictionary");
649                         PyGILState_Release(gilstate);
650                         return result;
651                 }
652         }
653         
654         /* add target values to a dict that will be used as '__locals__' dict */
655         driver_vars = PyDict_New(); // XXX do we need to decref this?
656         for (dtar= driver->targets.first; dtar; dtar= dtar->next) {
657                 PyObject *driver_arg = NULL;
658                 float tval = 0.0f;
659                 
660                 /* try to get variable value */
661                 tval= driver_get_target_value(driver, dtar);
662                 driver_arg= PyFloat_FromDouble((double)tval);
663                 
664                 /* try to add to dictionary */
665                 if (PyDict_SetItemString(driver_vars, dtar->name, driver_arg)) {
666                         /* this target failed - bad name */
667                         if (targets_ok) {
668                                 /* first one - print some extra info for easier identification */
669                                 fprintf(stderr, "\nBPY_pydriver_eval() - Error while evaluating PyDriver:\n");
670                                 targets_ok= 0;
671                         }
672                         
673                         fprintf(stderr, "\tBPY_pydriver_eval() - couldn't add variable '%s' to namespace \n", dtar->name);
674                         BPy_errors_to_report(NULL); // TODO - reports
675                 }
676         }
677         
678         /* execute expression to get a value */
679         retval = PyRun_String(expr, Py_eval_input, bpy_pydriver_Dict, driver_vars);
680         
681         /* decref the driver vars first...  */
682         Py_DECREF(driver_vars);
683         
684         /* process the result */
685         if (retval == NULL) {
686                 result = pydriver_error(driver);
687                 PyGILState_Release(gilstate);
688                 return result;
689         }
690
691         result = (float)PyFloat_AsDouble(retval);
692         Py_DECREF(retval);
693         
694         if ((result == -1) && PyErr_Occurred()) {
695                 result = pydriver_error(driver);
696                 PyGILState_Release(gilstate);
697                 return result;
698         }
699         
700         /* all fine, make sure the "invalid expression" flag is cleared */
701         driver->flag &= ~DRIVER_FLAG_INVALID;
702
703         PyGILState_Release(gilstate);
704
705         return result;
706 }