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"
45 #include "bpy_traceback.h"
47 #include "DNA_space_types.h"
48 #include "DNA_text_types.h"
50 #include "BLI_path_util.h"
51 #include "BLI_math_base.h"
52 #include "BLI_string.h"
53 #include "BLI_utildefines.h"
56 #include "BKE_context.h"
58 #include "BKE_font.h" /* only for utf8towchar */
60 #include "BKE_global.h" /* only for script checking */
62 #include "BPY_extern.h"
64 #include "../generic/bpy_internal_import.h" // our own imports
65 #include "../generic/py_capi_utils.h"
67 /* inittab initialization functions */
68 #include "../generic/noise_py_api.h"
69 #include "../generic/mathutils.h"
70 #include "../generic/bgl.h"
71 #include "../generic/blf_py_api.h"
73 /* for internal use, when starting and ending python scripts */
75 /* incase a python script triggers another python call, stop bpy_context_clear from invalidating */
76 static int py_call_level= 0;
77 BPy_StructRNA *bpy_context_module= NULL; /* for fast access */
79 // #define TIME_PY_RUN // simple python tests. prints on exit.
83 static int bpy_timer_count= 0;
84 static double bpy_timer; /* time since python starts */
85 static double bpy_timer_run; /* time for each python script run */
86 static double bpy_timer_run_tot; /* accumulate python runs */
89 void bpy_context_set(bContext *C, PyGILState_STATE *gilstate)
94 *gilstate= PyGILState_Ensure();
96 if(py_call_level==1) {
98 if(C) { // XXX - should always be true.
100 bpy_import_main_set(CTX_data_main(C));
103 fprintf(stderr, "ERROR: Python context called with a NULL Context. this should not happen!\n");
106 BPY_modules_update(C); /* can give really bad results if this isnt here */
109 if(bpy_timer_count==0) {
110 /* record time from the beginning */
111 bpy_timer= PIL_check_seconds_timer();
112 bpy_timer_run= bpy_timer_run_tot= 0.0;
114 bpy_timer_run= PIL_check_seconds_timer();
122 /* context should be used but not now because it causes some bugs */
123 void bpy_context_clear(bContext *UNUSED(C), PyGILState_STATE *gilstate)
128 PyGILState_Release(*gilstate);
130 if(py_call_level < 0) {
131 fprintf(stderr, "ERROR: Python context internal state bug. this should not happen!\n");
133 else if(py_call_level==0) {
134 // XXX - Calling classes currently wont store the context :\, cant set NULL because of this. but this is very flakey still.
135 //BPy_SetContext(NULL);
136 //bpy_import_main_set(NULL);
139 bpy_timer_run_tot += PIL_check_seconds_timer() - bpy_timer_run;
146 void BPY_text_free_code(Text *text)
149 Py_DECREF((PyObject *)text->compiled);
150 text->compiled= NULL;
154 void BPY_modules_update(bContext *C)
156 #if 0 // slow, this runs all the time poll, draw etc 100's of time a sec.
157 PyObject *mod= PyImport_ImportModuleLevel("bpy", NULL, NULL, NULL, 0);
158 PyModule_AddObject(mod, "data", BPY_rna_module());
159 PyModule_AddObject(mod, "types", BPY_rna_types()); // atm this does not need updating
162 /* refreshes the main struct */
163 BPY_update_rna_module();
164 bpy_context_module->ptr.data= (void *)C;
167 void BPY_context_set(bContext *C)
172 /* defined in AUD_C-API.cpp */
173 extern PyObject *AUD_initPython(void);
175 static struct _inittab bpy_internal_modules[]= {
176 {(char *)"noise", BPyInit_noise},
177 {(char *)"mathutils", BPyInit_mathutils},
178 // {(char *)"mathutils.geometry", BPyInit_mathutils_geometry},
179 {(char *)"bgl", BPyInit_bgl},
180 {(char *)"blf", BPyInit_blf},
181 {(char *)"aud", AUD_initPython},
185 /* call BPY_context_set first */
186 void BPY_python_start(int argc, const char **argv)
188 #ifndef WITH_PYTHON_MODULE
189 PyThreadState *py_tstate= NULL;
191 /* not essential but nice to set our name */
192 static wchar_t bprogname_wchar[FILE_MAXDIR+FILE_MAXFILE]; /* python holds a reference */
193 utf8towchar(bprogname_wchar, bprogname);
194 Py_SetProgramName(bprogname_wchar);
196 /* must run before python initializes */
197 PyImport_ExtendInittab(bpy_internal_modules);
199 /* allow to use our own included python */
200 PyC_SetHomePath(BLI_get_folder(BLENDER_PYTHON, NULL));
202 /* Python 3.2 now looks for '2.57/python/include/python3.2d/pyconfig.h' to parse
203 * from the 'sysconfig' module which is used by 'site', so for now disable site.
204 * alternatively we could copy the file. */
209 // PySys_SetArgv(argc, argv); // broken in py3, not a huge deal
210 /* sigh, why do python guys not have a char** version anymore? :( */
213 PyObject *py_argv= PyList_New(argc);
214 for (i=0; i<argc; i++)
215 PyList_SET_ITEM(py_argv, i, PyC_UnicodeFromByte(argv[i])); /* should fix bug #20021 - utf path name problems, by replacing PyUnicode_FromString */
217 PySys_SetObject("argv", py_argv);
221 /* Initialize thread support (also acquires lock) */
222 PyEval_InitThreads();
227 /* must run before python initializes */
228 PyImport_ExtendInittab(bpy_internal_modules);
231 /* bpy.* and lets us import it */
234 bpy_import_init(PyEval_GetBuiltins());
238 #ifndef WITH_PYTHON_MODULE
239 py_tstate= PyGILState_GetThisThreadState();
240 PyEval_ReleaseThread(py_tstate);
244 void BPY_python_end(void)
246 // fprintf(stderr, "Ending Python!\n");
248 PyGILState_Ensure(); /* finalizing, no need to grab the state */
250 // free other python data.
253 /* clear all python data from structs */
258 // measure time since py started
259 bpy_timer= PIL_check_seconds_timer() - bpy_timer;
261 printf("*bpy stats* - ");
262 printf("tot exec: %d, ", bpy_timer_count);
263 printf("tot run: %.4fsec, ", bpy_timer_run_tot);
264 if(bpy_timer_count>0)
265 printf("average run: %.6fsec, ", (bpy_timer_run_tot/bpy_timer_count));
268 printf("tot usage %.4f%%", (bpy_timer_run_tot/bpy_timer)*100.0);
272 // fprintf(stderr, "Ending Python Done!\n");
278 static void python_script_error_jump_text(struct Text *text)
282 python_script_error_jump(text->id.name+2, &lineno, &offset);
284 /* select the line with the error */
285 txt_move_to(text, lineno - 1, INT_MAX, FALSE);
286 txt_move_to(text, lineno - 1, offset, TRUE);
290 /* super annoying, undo _PyModule_Clear(), bug [#23871] */
291 #define PYMODULE_CLEAR_WORKAROUND
293 #ifdef PYMODULE_CLEAR_WORKAROUND
294 /* bad!, we should never do this, but currently only safe way I could find to keep namespace.
295 * from being cleared. - campbell */
299 /* ommit other values, we only want the dict. */
303 static int python_script_exec(bContext *C, const char *fn, struct Text *text, struct ReportList *reports, const short do_jump)
305 PyObject *main_mod= NULL;
306 PyObject *py_dict= NULL, *py_result= NULL;
307 PyGILState_STATE gilstate;
309 BLI_assert(fn || text);
311 if (fn==NULL && text==NULL) {
315 bpy_context_set(C, &gilstate);
317 PyC_MainModule_Backup(&main_mod);
320 char fn_dummy[FILE_MAXDIR];
321 bpy_text_filename_get(fn_dummy, sizeof(fn_dummy), text);
323 if(text->compiled == NULL) { /* if it wasn't already compiled, do it now */
324 char *buf= txt_to_buf(text);
326 text->compiled= Py_CompileString(buf, fn_dummy, Py_file_input);
330 if(PyErr_Occurred()) {
332 python_script_error_jump_text(text);
334 BPY_text_free_code(text);
339 py_dict= PyC_DefaultNameSpace(fn_dummy);
340 py_result= PyEval_EvalCode(text->compiled, py_dict, py_dict);
345 FILE *fp= fopen(fn, "r");
348 py_dict= PyC_DefaultNameSpace(fn);
351 /* Previously we used PyRun_File to run directly the code on a FILE
352 * object, but as written in the Python/C API Ref Manual, chapter 2,
353 * 'FILE structs for different C libraries can be different and
355 * So now we load the script file data to a buffer */
361 pystring= MEM_mallocN(strlen(fn) + 32, "pystring");
363 sprintf(pystring, "exec(open(r'%s').read())", fn);
364 py_result= PyRun_String(pystring, Py_file_input, py_dict, py_dict);
368 py_result= PyRun_File(fp, fn, Py_file_input, py_dict, py_dict);
373 PyErr_Format(PyExc_IOError, "Python file \"%s\" could not be opened: %s", fn, strerror(errno));
381 python_script_error_jump_text(text);
384 BPy_errors_to_report(reports);
387 Py_DECREF(py_result);
391 #ifdef PYMODULE_CLEAR_WORKAROUND
392 PyModuleObject *mmod= (PyModuleObject *)PyDict_GetItemString(PyThreadState_GET()->interp->modules, "__main__");
393 PyObject *dict_back= mmod->md_dict;
394 /* freeing the module will clear the namespace,
395 * gives problems running classes defined in this namespace being used later. */
397 Py_DECREF(dict_back);
400 #undef PYMODULE_CLEAR_WORKAROUND
403 PyC_MainModule_Restore(main_mod);
405 bpy_context_clear(C, &gilstate);
407 return (py_result != NULL);
410 /* Can run a file or text block */
411 int BPY_filepath_exec(bContext *C, const char *filepath, struct ReportList *reports)
413 return python_script_exec(C, filepath, NULL, reports, FALSE);
417 int BPY_text_exec(bContext *C, struct Text *text, struct ReportList *reports, const short do_jump)
419 return python_script_exec(C, NULL, text, reports, do_jump);
422 void BPY_DECREF(void *pyob_ptr)
424 PyGILState_STATE gilstate= PyGILState_Ensure();
425 Py_DECREF((PyObject *)pyob_ptr);
426 PyGILState_Release(gilstate);
429 /* return -1 on error, else 0 */
430 int BPY_button_exec(bContext *C, const char *expr, double *value, const short verbose)
432 PyGILState_STATE gilstate;
433 PyObject *py_dict, *mod, *retval;
435 PyObject *main_mod= NULL;
437 if (!value || !expr) return -1;
444 bpy_context_set(C, &gilstate);
446 PyC_MainModule_Backup(&main_mod);
448 py_dict= PyC_DefaultNameSpace("<blender button>");
450 mod= PyImport_ImportModule("math");
452 PyDict_Merge(py_dict, PyModule_GetDict(mod), 0); /* 0 - dont overwrite existing values */
455 else { /* highly unlikely but possibly */
460 retval= PyRun_String(expr, Py_eval_input, py_dict, py_dict);
462 if (retval == NULL) {
468 if(PyTuple_Check(retval)) {
469 /* Users my have typed in 10km, 2m
470 * add up all values */
474 for(i=0; i<PyTuple_GET_SIZE(retval); i++) {
475 val+= PyFloat_AsDouble(PyTuple_GET_ITEM(retval, i));
479 val= PyFloat_AsDouble(retval);
483 if(val==-1 && PyErr_Occurred()) {
486 else if (!finite(val)) {
496 BPy_errors_to_report(CTX_wm_reports(C));
503 PyC_MainModule_Backup(&main_mod);
505 bpy_context_clear(C, &gilstate);
510 int BPY_string_exec(bContext *C, const char *expr)
512 PyGILState_STATE gilstate;
513 PyObject *main_mod= NULL;
514 PyObject *py_dict, *retval;
516 Main *bmain_back; /* XXX, quick fix for release (Copy Settings crash), needs further investigation */
518 if (!expr) return -1;
524 bpy_context_set(C, &gilstate);
526 PyC_MainModule_Backup(&main_mod);
528 py_dict= PyC_DefaultNameSpace("<blender string>");
530 bmain_back= bpy_import_main_get();
531 bpy_import_main_set(CTX_data_main(C));
533 retval= PyRun_String(expr, Py_eval_input, py_dict, py_dict);
535 bpy_import_main_set(bmain_back);
537 if (retval == NULL) {
540 BPy_errors_to_report(CTX_wm_reports(C));
546 PyC_MainModule_Restore(main_mod);
548 bpy_context_clear(C, &gilstate);
554 void BPY_modules_load_user(bContext *C)
556 PyGILState_STATE gilstate;
557 Main *bmain= CTX_data_main(C);
560 /* can happen on file load */
564 bpy_context_set(C, &gilstate);
566 for(text=CTX_data_main(C)->text.first; text; text= text->id.next) {
567 if(text->flags & TXT_ISSCRIPT && BLI_testextensie(text->id.name+2, ".py")) {
568 if(!(G.f & G_SCRIPT_AUTOEXEC)) {
569 printf("scripts disabled for \"%s\", skipping '%s'\n", bmain->name, text->id.name+2);
572 PyObject *module= bpy_text_import(text);
584 bpy_context_clear(C, &gilstate);
587 int BPY_context_member_get(bContext *C, const char *member, bContextDataResult *result)
589 PyObject *pyctx= (PyObject *)CTX_py_dict_get(C);
590 PyObject *item= PyDict_GetItemString(pyctx, member);
591 PointerRNA *ptr= NULL;
597 else if(item==Py_None) {
600 else if(BPy_StructRNA_Check(item)) {
601 ptr= &(((BPy_StructRNA *)item)->ptr);
603 //result->ptr= ((BPy_StructRNA *)item)->ptr;
604 CTX_data_pointer_set(result, ptr->id.data, ptr->type, ptr->data);
607 else if (PySequence_Check(item)) {
608 PyObject *seq_fast= PySequence_Fast(item, "bpy_context_get sequence conversion");
609 if (seq_fast==NULL) {
614 int len= PySequence_Fast_GET_SIZE(seq_fast);
616 for(i= 0; i < len; i++) {
617 PyObject *list_item= PySequence_Fast_GET_ITEM(seq_fast, i);
619 if(BPy_StructRNA_Check(list_item)) {
621 CollectionPointerLink *link= MEM_callocN(sizeof(CollectionPointerLink), "bpy_context_get");
622 link->ptr= ((BPy_StructRNA *)item)->ptr;
623 BLI_addtail(&result->list, link);
625 ptr= &(((BPy_StructRNA *)list_item)->ptr);
626 CTX_data_list_add(result, ptr->id.data, ptr->type, ptr->data);
629 printf("List item not a valid type\n");
640 if (item) printf("PyContext '%s' not a valid type\n", member);
641 else printf("PyContext '%s' not found\n", member);
645 printf("PyContext '%s' found\n", member);
653 #ifdef WITH_PYTHON_MODULE
654 #include "BLI_storage.h"
655 /* TODO, reloading the module isnt functional at the moment. */
657 extern int main_python(int argc, const char **argv);
658 static struct PyModuleDef bpy_proxy_def= {
659 PyModuleDef_HEAD_INIT,
663 NULL, /* m_methods */
665 NULL, /* m_traverse */
672 /* Type-specific fields go here. */
676 /* call once __file__ is set */
677 void bpy_module_delay_init(PyObject *bpy_proxy)
681 PyObject *filename_obj= PyModule_GetFilenameObject(bpy_proxy); /* updating the module dict below will loose the reference to __file__ */
682 const char *filename_rel= _PyUnicode_AsString(filename_obj); /* can be relative */
683 char filename_abs[1024];
685 BLI_strncpy(filename_abs, filename_rel, sizeof(filename_abs));
686 BLI_path_cwd(filename_abs);
688 argv[0]= filename_abs;
691 // printf("module found %s\n", argv[0]);
693 main_python(argc, argv);
695 /* initialized in BPy_init_modules() */
696 PyDict_Update(PyModule_GetDict(bpy_proxy), PyModule_GetDict(bpy_package_py));
699 static void dealloc_obj_dealloc(PyObject *self);
701 static PyTypeObject dealloc_obj_Type= {{{0}}};
703 /* use our own dealloc so we can free a property if we use one */
704 static void dealloc_obj_dealloc(PyObject *self)
706 bpy_module_delay_init(((dealloc_obj *)self)->mod);
708 /* Note, for subclassed PyObjects we cant just call PyObject_DEL() directly or it will crash */
709 dealloc_obj_Type.tp_free(self);
715 PyObject *bpy_proxy= PyModule_Create(&bpy_proxy_def);
718 * 1) this init function is expected to have a private member defined - 'md_def'
719 * but this is only set for C defined modules (not py packages)
720 * so we cant return 'bpy_package_py' as is.
722 * 2) there is a 'bpy' C module for python to load which is basically all of blender,
723 * and there is scripts/bpy/__init__.py,
724 * we may end up having to rename this module so there is no naming conflict here eg:
725 * 'from blender import bpy'
727 * 3) we dont know the filename at this point, workaround by assigning a dummy value
728 * which calls back when its freed so the real loading can take place.
731 /* assign an object which is freed after __file__ is assigned */
734 /* assign dummy type */
735 dealloc_obj_Type.tp_name= "dealloc_obj";
736 dealloc_obj_Type.tp_basicsize= sizeof(dealloc_obj);
737 dealloc_obj_Type.tp_dealloc= dealloc_obj_dealloc;
738 dealloc_obj_Type.tp_flags= Py_TPFLAGS_DEFAULT;
740 if(PyType_Ready(&dealloc_obj_Type) < 0)
743 dob= (dealloc_obj *) dealloc_obj_Type.tp_alloc(&dealloc_obj_Type, 0);
744 dob->mod= bpy_proxy; /* borrow */
745 PyModule_AddObject(bpy_proxy, "__file__", (PyObject *)dob); /* borrow */