4 * ***** BEGIN GPL LICENSE BLOCK *****
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.
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.
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., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
20 * Contributor(s): Michel Selten, Willian P. Germano, Stephen Swaney,
21 * Chris Keith, Chris Want, Ken Hughes, Campbell Barton
23 * ***** END GPL LICENSE BLOCK *****
26 /** \file blender/python/intern/bpy_interface.c
27 * \ingroup pythonintern
31 /* grr, python redefines */
32 #ifdef _POSIX_C_SOURCE
33 # undef _POSIX_C_SOURCE
38 #include "MEM_guardedalloc.h"
40 #include "RNA_types.h"
46 #include "bpy_traceback.h"
47 #include "bpy_intern_string.h"
49 #include "DNA_space_types.h"
50 #include "DNA_text_types.h"
52 #include "BLI_path_util.h"
53 #include "BLI_math_base.h"
54 #include "BLI_string.h"
55 #include "BLI_string_utf8.h"
56 #include "BLI_utildefines.h"
59 #include "BKE_context.h"
62 #include "BKE_global.h" /* only for script checking */
64 #include "BPY_extern.h"
66 #include "../generic/bpy_internal_import.h" // our own imports
67 #include "../generic/py_capi_utils.h"
69 /* inittab initialization functions */
70 #include "../generic/bgl.h"
71 #include "../generic/blf_py_api.h"
72 #include "../generic/noise_py_api.h"
73 #include "../mathutils/mathutils.h"
75 /* for internal use, when starting and ending python scripts */
77 /* incase a python script triggers another python call, stop bpy_context_clear from invalidating */
78 static int py_call_level= 0;
79 BPy_StructRNA *bpy_context_module= NULL; /* for fast access */
81 // #define TIME_PY_RUN // simple python tests. prints on exit.
85 static int bpy_timer_count= 0;
86 static double bpy_timer; /* time since python starts */
87 static double bpy_timer_run; /* time for each python script run */
88 static double bpy_timer_run_tot; /* accumulate python runs */
91 /* use for updating while a python script runs - in case of file load */
92 void bpy_context_update(bContext *C)
95 bpy_import_main_set(CTX_data_main(C));
96 BPY_modules_update(C); /* can give really bad results if this isnt here */
99 void bpy_context_set(bContext *C, PyGILState_STATE *gilstate)
104 *gilstate= PyGILState_Ensure();
106 if (py_call_level==1) {
107 bpy_context_update(C);
110 if (bpy_timer_count==0) {
111 /* record time from the beginning */
112 bpy_timer= PIL_check_seconds_timer();
113 bpy_timer_run= bpy_timer_run_tot= 0.0;
115 bpy_timer_run= PIL_check_seconds_timer();
123 /* context should be used but not now because it causes some bugs */
124 void bpy_context_clear(bContext *UNUSED(C), PyGILState_STATE *gilstate)
129 PyGILState_Release(*gilstate);
131 if (py_call_level < 0) {
132 fprintf(stderr, "ERROR: Python context internal state bug. this should not happen!\n");
134 else if (py_call_level==0) {
135 // XXX - Calling classes currently wont store the context :\, cant set NULL because of this. but this is very flakey still.
136 //BPy_SetContext(NULL);
137 //bpy_import_main_set(NULL);
140 bpy_timer_run_tot += PIL_check_seconds_timer() - bpy_timer_run;
147 void BPY_text_free_code(Text *text)
149 if (text->compiled) {
150 Py_DECREF((PyObject *)text->compiled);
151 text->compiled= NULL;
155 void BPY_modules_update(bContext *C)
157 #if 0 // slow, this runs all the time poll, draw etc 100's of time a sec.
158 PyObject *mod= PyImport_ImportModuleLevel("bpy", NULL, NULL, NULL, 0);
159 PyModule_AddObject(mod, "data", BPY_rna_module());
160 PyModule_AddObject(mod, "types", BPY_rna_types()); // atm this does not need updating
163 /* refreshes the main struct */
164 BPY_update_rna_module();
165 bpy_context_module->ptr.data= (void *)C;
168 void BPY_context_set(bContext *C)
173 /* defined in AUD_C-API.cpp */
174 extern PyObject *AUD_initPython(void);
175 /* defined in cycles/blender */
176 extern PyObject *CYCLES_initPython(void);
178 static struct _inittab bpy_internal_modules[]= {
179 {(char *)"noise", BPyInit_noise},
180 {(char *)"mathutils", PyInit_mathutils},
181 // {(char *)"mathutils.geometry", PyInit_mathutils_geometry},
182 {(char *)"bgl", BPyInit_bgl},
183 {(char *)"blf", BPyInit_blf},
184 #ifdef WITH_AUDASPACE
185 {(char *)"aud", AUD_initPython},
188 {(char *)"libcycles_blender", CYCLES_initPython},
190 {(char *)"gpu", GPU_initPython},
194 /* call BPY_context_set first */
195 void BPY_python_start(int argc, const char **argv)
197 #ifndef WITH_PYTHON_MODULE
198 PyThreadState *py_tstate= NULL;
200 /* not essential but nice to set our name */
201 static wchar_t program_path_wchar[FILE_MAXDIR+FILE_MAXFILE]; /* python holds a reference */
202 BLI_strncpy_wchar_from_utf8(program_path_wchar, BLI_program_path(), sizeof(program_path_wchar) / sizeof(wchar_t));
203 Py_SetProgramName(program_path_wchar);
205 /* must run before python initializes */
206 PyImport_ExtendInittab(bpy_internal_modules);
208 /* allow to use our own included python */
209 PyC_SetHomePath(BLI_get_folder(BLENDER_SYSTEM_PYTHON, NULL));
211 /* Python 3.2 now looks for '2.58/python/include/python3.2d/pyconfig.h' to parse
212 * from the 'sysconfig' module which is used by 'site', so for now disable site.
213 * alternatively we could copy the file. */
218 // PySys_SetArgv(argc, argv); // broken in py3, not a huge deal
219 /* sigh, why do python guys not have a char** version anymore? :( */
222 PyObject *py_argv= PyList_New(argc);
223 for (i=0; i<argc; i++)
224 PyList_SET_ITEM(py_argv, i, PyC_UnicodeFromByte(argv[i])); /* should fix bug #20021 - utf path name problems, by replacing PyUnicode_FromString */
226 PySys_SetObject("argv", py_argv);
230 /* Initialize thread support (also acquires lock) */
231 PyEval_InitThreads();
236 /* must run before python initializes */
237 PyImport_ExtendInittab(bpy_internal_modules);
240 bpy_intern_string_init();
242 /* bpy.* and lets us import it */
245 bpy_import_init(PyEval_GetBuiltins());
249 BPY_atexit_register(); /* this can init any time */
251 #ifndef WITH_PYTHON_MODULE
252 py_tstate= PyGILState_GetThisThreadState();
253 PyEval_ReleaseThread(py_tstate);
257 void BPY_python_end(void)
259 // fprintf(stderr, "Ending Python!\n");
261 PyGILState_Ensure(); /* finalizing, no need to grab the state */
263 // free other python data.
266 /* clear all python data from structs */
268 bpy_intern_string_exit();
270 BPY_atexit_unregister(); /* without this we get recursive calls to WM_exit */
275 // measure time since py started
276 bpy_timer= PIL_check_seconds_timer() - bpy_timer;
278 printf("*bpy stats* - ");
279 printf("tot exec: %d, ", bpy_timer_count);
280 printf("tot run: %.4fsec, ", bpy_timer_run_tot);
281 if (bpy_timer_count>0)
282 printf("average run: %.6fsec, ", (bpy_timer_run_tot/bpy_timer_count));
285 printf("tot usage %.4f%%", (bpy_timer_run_tot/bpy_timer)*100.0);
289 // fprintf(stderr, "Ending Python Done!\n");
295 static void python_script_error_jump_text(struct Text *text)
299 python_script_error_jump(text->id.name+2, &lineno, &offset);
301 /* select the line with the error */
302 txt_move_to(text, lineno - 1, INT_MAX, FALSE);
303 txt_move_to(text, lineno - 1, offset, TRUE);
307 /* super annoying, undo _PyModule_Clear(), bug [#23871] */
308 #define PYMODULE_CLEAR_WORKAROUND
310 #ifdef PYMODULE_CLEAR_WORKAROUND
311 /* bad!, we should never do this, but currently only safe way I could find to keep namespace.
312 * from being cleared. - campbell */
316 /* ommit other values, we only want the dict. */
320 static int python_script_exec(bContext *C, const char *fn, struct Text *text, struct ReportList *reports, const short do_jump)
322 PyObject *main_mod= NULL;
323 PyObject *py_dict= NULL, *py_result= NULL;
324 PyGILState_STATE gilstate;
326 BLI_assert(fn || text);
328 if (fn==NULL && text==NULL) {
332 bpy_context_set(C, &gilstate);
334 PyC_MainModule_Backup(&main_mod);
337 char fn_dummy[FILE_MAXDIR];
338 bpy_text_filename_get(fn_dummy, sizeof(fn_dummy), text);
340 if (text->compiled == NULL) { /* if it wasn't already compiled, do it now */
341 char *buf= txt_to_buf(text);
343 text->compiled= Py_CompileString(buf, fn_dummy, Py_file_input);
347 if (PyErr_Occurred()) {
349 python_script_error_jump_text(text);
351 BPY_text_free_code(text);
355 if (text->compiled) {
356 py_dict= PyC_DefaultNameSpace(fn_dummy);
357 py_result= PyEval_EvalCode(text->compiled, py_dict, py_dict);
362 FILE *fp= fopen(fn, "r");
365 py_dict= PyC_DefaultNameSpace(fn);
368 /* Previously we used PyRun_File to run directly the code on a FILE
369 * object, but as written in the Python/C API Ref Manual, chapter 2,
370 * 'FILE structs for different C libraries can be different and
372 * So now we load the script file data to a buffer */
378 pystring= MEM_mallocN(strlen(fn) + 32, "pystring");
380 sprintf(pystring, "exec(open(r'%s').read())", fn);
381 py_result= PyRun_String(pystring, Py_file_input, py_dict, py_dict);
385 py_result= PyRun_File(fp, fn, Py_file_input, py_dict, py_dict);
390 PyErr_Format(PyExc_IOError,
391 "Python file \"%s\" could not be opened: %s",
392 fn, strerror(errno));
400 python_script_error_jump_text(text);
403 BPy_errors_to_report(reports);
406 Py_DECREF(py_result);
410 #ifdef PYMODULE_CLEAR_WORKAROUND
411 PyModuleObject *mmod= (PyModuleObject *)PyDict_GetItemString(PyThreadState_GET()->interp->modules, "__main__");
412 PyObject *dict_back= mmod->md_dict;
413 /* freeing the module will clear the namespace,
414 * gives problems running classes defined in this namespace being used later. */
416 Py_DECREF(dict_back);
419 #undef PYMODULE_CLEAR_WORKAROUND
422 PyC_MainModule_Restore(main_mod);
424 bpy_context_clear(C, &gilstate);
426 return (py_result != NULL);
429 /* Can run a file or text block */
430 int BPY_filepath_exec(bContext *C, const char *filepath, struct ReportList *reports)
432 return python_script_exec(C, filepath, NULL, reports, FALSE);
436 int BPY_text_exec(bContext *C, struct Text *text, struct ReportList *reports, const short do_jump)
438 return python_script_exec(C, NULL, text, reports, do_jump);
441 void BPY_DECREF(void *pyob_ptr)
443 PyGILState_STATE gilstate= PyGILState_Ensure();
444 Py_DECREF((PyObject *)pyob_ptr);
445 PyGILState_Release(gilstate);
448 /* return -1 on error, else 0 */
449 int BPY_button_exec(bContext *C, const char *expr, double *value, const short verbose)
451 PyGILState_STATE gilstate;
452 PyObject *py_dict, *mod, *retval;
454 PyObject *main_mod= NULL;
456 if (!value || !expr) return -1;
463 bpy_context_set(C, &gilstate);
465 PyC_MainModule_Backup(&main_mod);
467 py_dict= PyC_DefaultNameSpace("<blender button>");
469 mod= PyImport_ImportModule("math");
471 PyDict_Merge(py_dict, PyModule_GetDict(mod), 0); /* 0 - dont overwrite existing values */
474 else { /* highly unlikely but possibly */
479 retval= PyRun_String(expr, Py_eval_input, py_dict, py_dict);
481 if (retval == NULL) {
487 if (PyTuple_Check(retval)) {
488 /* Users my have typed in 10km, 2m
489 * add up all values */
493 for (i=0; i<PyTuple_GET_SIZE(retval); i++) {
494 val+= PyFloat_AsDouble(PyTuple_GET_ITEM(retval, i));
498 val= PyFloat_AsDouble(retval);
502 if (val==-1 && PyErr_Occurred()) {
505 else if (!finite(val)) {
515 BPy_errors_to_report(CTX_wm_reports(C));
522 PyC_MainModule_Backup(&main_mod);
524 bpy_context_clear(C, &gilstate);
529 int BPY_string_exec(bContext *C, const char *expr)
531 PyGILState_STATE gilstate;
532 PyObject *main_mod= NULL;
533 PyObject *py_dict, *retval;
535 Main *bmain_back; /* XXX, quick fix for release (Copy Settings crash), needs further investigation */
537 if (!expr) return -1;
543 bpy_context_set(C, &gilstate);
545 PyC_MainModule_Backup(&main_mod);
547 py_dict= PyC_DefaultNameSpace("<blender string>");
549 bmain_back= bpy_import_main_get();
550 bpy_import_main_set(CTX_data_main(C));
552 retval= PyRun_String(expr, Py_eval_input, py_dict, py_dict);
554 bpy_import_main_set(bmain_back);
556 if (retval == NULL) {
559 BPy_errors_to_report(CTX_wm_reports(C));
565 PyC_MainModule_Restore(main_mod);
567 bpy_context_clear(C, &gilstate);
573 void BPY_modules_load_user(bContext *C)
575 PyGILState_STATE gilstate;
576 Main *bmain= CTX_data_main(C);
579 /* can happen on file load */
583 /* update pointers since this can run from a nested script
586 bpy_context_update(C);
589 bpy_context_set(C, &gilstate);
591 for (text=CTX_data_main(C)->text.first; text; text= text->id.next) {
592 if (text->flags & TXT_ISSCRIPT && BLI_testextensie(text->id.name+2, ".py")) {
593 if (!(G.f & G_SCRIPT_AUTOEXEC)) {
594 printf("scripts disabled for \"%s\", skipping '%s'\n", bmain->name, text->id.name+2);
597 PyObject *module= bpy_text_import(text);
609 bpy_context_clear(C, &gilstate);
612 int BPY_context_member_get(bContext *C, const char *member, bContextDataResult *result)
614 PyObject *pyctx= (PyObject *)CTX_py_dict_get(C);
615 PyObject *item= PyDict_GetItemString(pyctx, member);
616 PointerRNA *ptr= NULL;
622 else if (item==Py_None) {
625 else if (BPy_StructRNA_Check(item)) {
626 ptr= &(((BPy_StructRNA *)item)->ptr);
628 //result->ptr= ((BPy_StructRNA *)item)->ptr;
629 CTX_data_pointer_set(result, ptr->id.data, ptr->type, ptr->data);
632 else if (PySequence_Check(item)) {
633 PyObject *seq_fast= PySequence_Fast(item, "bpy_context_get sequence conversion");
634 if (seq_fast==NULL) {
639 int len= PySequence_Fast_GET_SIZE(seq_fast);
641 for (i= 0; i < len; i++) {
642 PyObject *list_item= PySequence_Fast_GET_ITEM(seq_fast, i);
644 if (BPy_StructRNA_Check(list_item)) {
646 CollectionPointerLink *link= MEM_callocN(sizeof(CollectionPointerLink), "bpy_context_get");
647 link->ptr= ((BPy_StructRNA *)item)->ptr;
648 BLI_addtail(&result->list, link);
650 ptr= &(((BPy_StructRNA *)list_item)->ptr);
651 CTX_data_list_add(result, ptr->id.data, ptr->type, ptr->data);
654 printf("List item not a valid type\n");
665 if (item) printf("PyContext '%s' not a valid type\n", member);
666 else printf("PyContext '%s' not found\n", member);
670 printf("PyContext '%s' found\n", member);
678 #ifdef WITH_PYTHON_MODULE
679 #include "BLI_storage.h"
680 /* TODO, reloading the module isnt functional at the moment. */
682 static void bpy_module_free(void *mod);
683 extern int main_python_enter(int argc, const char **argv);
684 extern void main_python_exit(void);
685 static struct PyModuleDef bpy_proxy_def= {
686 PyModuleDef_HEAD_INIT,
690 NULL, /* m_methods */
692 NULL, /* m_traverse */
694 bpy_module_free, /* m_free */
699 /* Type-specific fields go here. */
703 /* call once __file__ is set */
704 void bpy_module_delay_init(PyObject *bpy_proxy)
708 PyObject *filename_obj= PyModule_GetFilenameObject(bpy_proxy); /* updating the module dict below will loose the reference to __file__ */
709 const char *filename_rel= _PyUnicode_AsString(filename_obj); /* can be relative */
710 char filename_abs[1024];
712 BLI_strncpy(filename_abs, filename_rel, sizeof(filename_abs));
713 BLI_path_cwd(filename_abs);
715 argv[0]= filename_abs;
718 // printf("module found %s\n", argv[0]);
720 main_python_enter(argc, argv);
722 /* initialized in BPy_init_modules() */
723 PyDict_Update(PyModule_GetDict(bpy_proxy), PyModule_GetDict(bpy_package_py));
726 static void dealloc_obj_dealloc(PyObject *self);
728 static PyTypeObject dealloc_obj_Type= {{{0}}};
730 /* use our own dealloc so we can free a property if we use one */
731 static void dealloc_obj_dealloc(PyObject *self)
733 bpy_module_delay_init(((dealloc_obj *)self)->mod);
735 /* Note, for subclassed PyObjects we cant just call PyObject_DEL() directly or it will crash */
736 dealloc_obj_Type.tp_free(self);
742 PyObject *bpy_proxy= PyModule_Create(&bpy_proxy_def);
745 * 1) this init function is expected to have a private member defined - 'md_def'
746 * but this is only set for C defined modules (not py packages)
747 * so we cant return 'bpy_package_py' as is.
749 * 2) there is a 'bpy' C module for python to load which is basically all of blender,
750 * and there is scripts/bpy/__init__.py,
751 * we may end up having to rename this module so there is no naming conflict here eg:
752 * 'from blender import bpy'
754 * 3) we dont know the filename at this point, workaround by assigning a dummy value
755 * which calls back when its freed so the real loading can take place.
758 /* assign an object which is freed after __file__ is assigned */
761 /* assign dummy type */
762 dealloc_obj_Type.tp_name= "dealloc_obj";
763 dealloc_obj_Type.tp_basicsize= sizeof(dealloc_obj);
764 dealloc_obj_Type.tp_dealloc= dealloc_obj_dealloc;
765 dealloc_obj_Type.tp_flags= Py_TPFLAGS_DEFAULT;
767 if (PyType_Ready(&dealloc_obj_Type) < 0)
770 dob= (dealloc_obj *) dealloc_obj_Type.tp_alloc(&dealloc_obj_Type, 0);
771 dob->mod= bpy_proxy; /* borrow */
772 PyModule_AddObject(bpy_proxy, "__file__", (PyObject *)dob); /* borrow */
777 static void bpy_module_free(void *UNUSED(mod))