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.xx/python/include/python3.2d/pyconfig.h' to
212 * parse from the 'sysconfig' module which is used by 'site',
213 * so for now disable site. 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 /* should fix bug #20021 - utf path name problems, by replacing
225 * PyUnicode_FromString, with this one */
226 PyList_SET_ITEM(py_argv, i, PyC_UnicodeFromByte(argv[i]));
229 PySys_SetObject("argv", py_argv);
233 /* Initialize thread support (also acquires lock) */
234 PyEval_InitThreads();
239 /* must run before python initializes */
240 PyImport_ExtendInittab(bpy_internal_modules);
243 bpy_intern_string_init();
245 /* bpy.* and lets us import it */
248 bpy_import_init(PyEval_GetBuiltins());
252 BPY_atexit_register(); /* this can init any time */
254 #ifndef WITH_PYTHON_MODULE
255 py_tstate= PyGILState_GetThisThreadState();
256 PyEval_ReleaseThread(py_tstate);
260 void BPY_python_end(void)
262 // fprintf(stderr, "Ending Python!\n");
264 PyGILState_Ensure(); /* finalizing, no need to grab the state */
266 // free other python data.
269 /* clear all python data from structs */
271 bpy_intern_string_exit();
273 BPY_atexit_unregister(); /* without this we get recursive calls to WM_exit */
278 // measure time since py started
279 bpy_timer= PIL_check_seconds_timer() - bpy_timer;
281 printf("*bpy stats* - ");
282 printf("tot exec: %d, ", bpy_timer_count);
283 printf("tot run: %.4fsec, ", bpy_timer_run_tot);
284 if (bpy_timer_count>0)
285 printf("average run: %.6fsec, ", (bpy_timer_run_tot/bpy_timer_count));
288 printf("tot usage %.4f%%", (bpy_timer_run_tot/bpy_timer)*100.0);
292 // fprintf(stderr, "Ending Python Done!\n");
298 static void python_script_error_jump_text(struct Text *text)
302 python_script_error_jump(text->id.name+2, &lineno, &offset);
304 /* select the line with the error */
305 txt_move_to(text, lineno - 1, INT_MAX, FALSE);
306 txt_move_to(text, lineno - 1, offset, TRUE);
310 /* super annoying, undo _PyModule_Clear(), bug [#23871] */
311 #define PYMODULE_CLEAR_WORKAROUND
313 #ifdef PYMODULE_CLEAR_WORKAROUND
314 /* bad!, we should never do this, but currently only safe way I could find to keep namespace.
315 * from being cleared. - campbell */
319 /* ommit other values, we only want the dict. */
323 static int python_script_exec(bContext *C, const char *fn, struct Text *text, struct ReportList *reports, const short do_jump)
325 PyObject *main_mod= NULL;
326 PyObject *py_dict= NULL, *py_result= NULL;
327 PyGILState_STATE gilstate;
329 BLI_assert(fn || text);
331 if (fn==NULL && text==NULL) {
335 bpy_context_set(C, &gilstate);
337 PyC_MainModule_Backup(&main_mod);
340 char fn_dummy[FILE_MAXDIR];
341 bpy_text_filename_get(fn_dummy, sizeof(fn_dummy), text);
343 if (text->compiled == NULL) { /* if it wasn't already compiled, do it now */
344 char *buf= txt_to_buf(text);
346 text->compiled= Py_CompileString(buf, fn_dummy, Py_file_input);
350 if (PyErr_Occurred()) {
352 python_script_error_jump_text(text);
354 BPY_text_free_code(text);
358 if (text->compiled) {
359 py_dict= PyC_DefaultNameSpace(fn_dummy);
360 py_result= PyEval_EvalCode(text->compiled, py_dict, py_dict);
365 FILE *fp= fopen(fn, "r");
368 py_dict= PyC_DefaultNameSpace(fn);
371 /* Previously we used PyRun_File to run directly the code on a FILE
372 * object, but as written in the Python/C API Ref Manual, chapter 2,
373 * 'FILE structs for different C libraries can be different and
375 * So now we load the script file data to a buffer */
381 pystring= MEM_mallocN(strlen(fn) + 32, "pystring");
383 sprintf(pystring, "exec(open(r'%s').read())", fn);
384 py_result= PyRun_String(pystring, Py_file_input, py_dict, py_dict);
388 py_result= PyRun_File(fp, fn, Py_file_input, py_dict, py_dict);
393 PyErr_Format(PyExc_IOError,
394 "Python file \"%s\" could not be opened: %s",
395 fn, strerror(errno));
403 python_script_error_jump_text(text);
406 BPy_errors_to_report(reports);
409 Py_DECREF(py_result);
413 #ifdef PYMODULE_CLEAR_WORKAROUND
414 PyModuleObject *mmod= (PyModuleObject *)PyDict_GetItemString(PyThreadState_GET()->interp->modules, "__main__");
415 PyObject *dict_back= mmod->md_dict;
416 /* freeing the module will clear the namespace,
417 * gives problems running classes defined in this namespace being used later. */
419 Py_DECREF(dict_back);
422 #undef PYMODULE_CLEAR_WORKAROUND
425 PyC_MainModule_Restore(main_mod);
427 bpy_context_clear(C, &gilstate);
429 return (py_result != NULL);
432 /* Can run a file or text block */
433 int BPY_filepath_exec(bContext *C, const char *filepath, struct ReportList *reports)
435 return python_script_exec(C, filepath, NULL, reports, FALSE);
439 int BPY_text_exec(bContext *C, struct Text *text, struct ReportList *reports, const short do_jump)
441 return python_script_exec(C, NULL, text, reports, do_jump);
444 void BPY_DECREF(void *pyob_ptr)
446 PyGILState_STATE gilstate= PyGILState_Ensure();
447 Py_DECREF((PyObject *)pyob_ptr);
448 PyGILState_Release(gilstate);
451 /* return -1 on error, else 0 */
452 int BPY_button_exec(bContext *C, const char *expr, double *value, const short verbose)
454 PyGILState_STATE gilstate;
455 PyObject *py_dict, *mod, *retval;
457 PyObject *main_mod= NULL;
459 if (!value || !expr) return -1;
466 bpy_context_set(C, &gilstate);
468 PyC_MainModule_Backup(&main_mod);
470 py_dict= PyC_DefaultNameSpace("<blender button>");
472 mod= PyImport_ImportModule("math");
474 PyDict_Merge(py_dict, PyModule_GetDict(mod), 0); /* 0 - dont overwrite existing values */
477 else { /* highly unlikely but possibly */
482 retval= PyRun_String(expr, Py_eval_input, py_dict, py_dict);
484 if (retval == NULL) {
490 if (PyTuple_Check(retval)) {
491 /* Users my have typed in 10km, 2m
492 * add up all values */
496 for (i=0; i<PyTuple_GET_SIZE(retval); i++) {
497 val+= PyFloat_AsDouble(PyTuple_GET_ITEM(retval, i));
501 val= PyFloat_AsDouble(retval);
505 if (val==-1 && PyErr_Occurred()) {
508 else if (!finite(val)) {
518 BPy_errors_to_report(CTX_wm_reports(C));
525 PyC_MainModule_Backup(&main_mod);
527 bpy_context_clear(C, &gilstate);
532 int BPY_string_exec(bContext *C, const char *expr)
534 PyGILState_STATE gilstate;
535 PyObject *main_mod= NULL;
536 PyObject *py_dict, *retval;
538 Main *bmain_back; /* XXX, quick fix for release (Copy Settings crash), needs further investigation */
540 if (!expr) return -1;
546 bpy_context_set(C, &gilstate);
548 PyC_MainModule_Backup(&main_mod);
550 py_dict= PyC_DefaultNameSpace("<blender string>");
552 bmain_back= bpy_import_main_get();
553 bpy_import_main_set(CTX_data_main(C));
555 retval= PyRun_String(expr, Py_eval_input, py_dict, py_dict);
557 bpy_import_main_set(bmain_back);
559 if (retval == NULL) {
562 BPy_errors_to_report(CTX_wm_reports(C));
568 PyC_MainModule_Restore(main_mod);
570 bpy_context_clear(C, &gilstate);
576 void BPY_modules_load_user(bContext *C)
578 PyGILState_STATE gilstate;
579 Main *bmain= CTX_data_main(C);
582 /* can happen on file load */
586 /* update pointers since this can run from a nested script
589 bpy_context_update(C);
592 bpy_context_set(C, &gilstate);
594 for (text=CTX_data_main(C)->text.first; text; text= text->id.next) {
595 if (text->flags & TXT_ISSCRIPT && BLI_testextensie(text->id.name+2, ".py")) {
596 if (!(G.f & G_SCRIPT_AUTOEXEC)) {
597 printf("scripts disabled for \"%s\", skipping '%s'\n", bmain->name, text->id.name+2);
600 PyObject *module= bpy_text_import(text);
612 bpy_context_clear(C, &gilstate);
615 int BPY_context_member_get(bContext *C, const char *member, bContextDataResult *result)
617 PyObject *pyctx= (PyObject *)CTX_py_dict_get(C);
618 PyObject *item= PyDict_GetItemString(pyctx, member);
619 PointerRNA *ptr= NULL;
625 else if (item==Py_None) {
628 else if (BPy_StructRNA_Check(item)) {
629 ptr= &(((BPy_StructRNA *)item)->ptr);
631 //result->ptr= ((BPy_StructRNA *)item)->ptr;
632 CTX_data_pointer_set(result, ptr->id.data, ptr->type, ptr->data);
635 else if (PySequence_Check(item)) {
636 PyObject *seq_fast= PySequence_Fast(item, "bpy_context_get sequence conversion");
637 if (seq_fast==NULL) {
642 int len= PySequence_Fast_GET_SIZE(seq_fast);
644 for (i= 0; i < len; i++) {
645 PyObject *list_item= PySequence_Fast_GET_ITEM(seq_fast, i);
647 if (BPy_StructRNA_Check(list_item)) {
649 CollectionPointerLink *link= MEM_callocN(sizeof(CollectionPointerLink), "bpy_context_get");
650 link->ptr= ((BPy_StructRNA *)item)->ptr;
651 BLI_addtail(&result->list, link);
653 ptr= &(((BPy_StructRNA *)list_item)->ptr);
654 CTX_data_list_add(result, ptr->id.data, ptr->type, ptr->data);
657 printf("List item not a valid type\n");
668 if (item) printf("PyContext '%s' not a valid type\n", member);
669 else printf("PyContext '%s' not found\n", member);
673 printf("PyContext '%s' found\n", member);
681 #ifdef WITH_PYTHON_MODULE
682 #include "BLI_fileops.h"
683 /* TODO, reloading the module isnt functional at the moment. */
685 static void bpy_module_free(void *mod);
686 extern int main_python_enter(int argc, const char **argv);
687 extern void main_python_exit(void);
688 static struct PyModuleDef bpy_proxy_def= {
689 PyModuleDef_HEAD_INIT,
693 NULL, /* m_methods */
695 NULL, /* m_traverse */
697 bpy_module_free, /* m_free */
702 /* Type-specific fields go here. */
706 /* call once __file__ is set */
707 void bpy_module_delay_init(PyObject *bpy_proxy)
711 PyObject *filename_obj= PyModule_GetFilenameObject(bpy_proxy); /* updating the module dict below will loose the reference to __file__ */
712 const char *filename_rel= _PyUnicode_AsString(filename_obj); /* can be relative */
713 char filename_abs[1024];
715 BLI_strncpy(filename_abs, filename_rel, sizeof(filename_abs));
716 BLI_path_cwd(filename_abs);
718 argv[0]= filename_abs;
721 // printf("module found %s\n", argv[0]);
723 main_python_enter(argc, argv);
725 /* initialized in BPy_init_modules() */
726 PyDict_Update(PyModule_GetDict(bpy_proxy), PyModule_GetDict(bpy_package_py));
729 static void dealloc_obj_dealloc(PyObject *self);
731 static PyTypeObject dealloc_obj_Type= {{{0}}};
733 /* use our own dealloc so we can free a property if we use one */
734 static void dealloc_obj_dealloc(PyObject *self)
736 bpy_module_delay_init(((dealloc_obj *)self)->mod);
738 /* Note, for subclassed PyObjects we cant just call PyObject_DEL() directly or it will crash */
739 dealloc_obj_Type.tp_free(self);
745 PyObject *bpy_proxy= PyModule_Create(&bpy_proxy_def);
748 * 1) this init function is expected to have a private member defined - 'md_def'
749 * but this is only set for C defined modules (not py packages)
750 * so we cant return 'bpy_package_py' as is.
752 * 2) there is a 'bpy' C module for python to load which is basically all of blender,
753 * and there is scripts/bpy/__init__.py,
754 * we may end up having to rename this module so there is no naming conflict here eg:
755 * 'from blender import bpy'
757 * 3) we dont know the filename at this point, workaround by assigning a dummy value
758 * which calls back when its freed so the real loading can take place.
761 /* assign an object which is freed after __file__ is assigned */
764 /* assign dummy type */
765 dealloc_obj_Type.tp_name= "dealloc_obj";
766 dealloc_obj_Type.tp_basicsize= sizeof(dealloc_obj);
767 dealloc_obj_Type.tp_dealloc= dealloc_obj_dealloc;
768 dealloc_obj_Type.tp_flags= Py_TPFLAGS_DEFAULT;
770 if (PyType_Ready(&dealloc_obj_Type) < 0)
773 dob= (dealloc_obj *) dealloc_obj_Type.tp_alloc(&dealloc_obj_Type, 0);
774 dob->mod= bpy_proxy; /* borrow */
775 PyModule_AddObject(bpy_proxy, "__file__", (PyObject *)dob); /* borrow */
780 static void bpy_module_free(void *UNUSED(mod))