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_utildefines.h"
58 #include "BKE_context.h"
60 #include "BKE_font.h" /* only for utf8towchar */
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)
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);
176 static struct _inittab bpy_internal_modules[]= {
177 {(char *)"noise", BPyInit_noise},
178 {(char *)"mathutils", PyInit_mathutils},
179 // {(char *)"mathutils.geometry", PyInit_mathutils_geometry},
180 {(char *)"bgl", BPyInit_bgl},
181 {(char *)"blf", BPyInit_blf},
182 #ifdef WITH_AUDASPACE
183 {(char *)"aud", AUD_initPython},
185 {(char *)"gpu", GPU_initPython},
189 /* call BPY_context_set first */
190 void BPY_python_start(int argc, const char **argv)
192 #ifndef WITH_PYTHON_MODULE
193 PyThreadState *py_tstate= NULL;
195 /* not essential but nice to set our name */
196 static wchar_t bprogname_wchar[FILE_MAXDIR+FILE_MAXFILE]; /* python holds a reference */
197 utf8towchar(bprogname_wchar, bprogname);
198 Py_SetProgramName(bprogname_wchar);
200 /* must run before python initializes */
201 PyImport_ExtendInittab(bpy_internal_modules);
203 /* allow to use our own included python */
204 PyC_SetHomePath(BLI_get_folder(BLENDER_SYSTEM_PYTHON, NULL));
206 /* Python 3.2 now looks for '2.58/python/include/python3.2d/pyconfig.h' to parse
207 * from the 'sysconfig' module which is used by 'site', so for now disable site.
208 * alternatively we could copy the file. */
213 // PySys_SetArgv(argc, argv); // broken in py3, not a huge deal
214 /* sigh, why do python guys not have a char** version anymore? :( */
217 PyObject *py_argv= PyList_New(argc);
218 for (i=0; i<argc; i++)
219 PyList_SET_ITEM(py_argv, i, PyC_UnicodeFromByte(argv[i])); /* should fix bug #20021 - utf path name problems, by replacing PyUnicode_FromString */
221 PySys_SetObject("argv", py_argv);
225 /* Initialize thread support (also acquires lock) */
226 PyEval_InitThreads();
231 /* must run before python initializes */
232 PyImport_ExtendInittab(bpy_internal_modules);
235 bpy_intern_string_init();
237 /* bpy.* and lets us import it */
240 bpy_import_init(PyEval_GetBuiltins());
244 BPY_atexit_init(); /* this can init any time */
246 #ifndef WITH_PYTHON_MODULE
247 py_tstate= PyGILState_GetThisThreadState();
248 PyEval_ReleaseThread(py_tstate);
252 void BPY_python_end(void)
254 // fprintf(stderr, "Ending Python!\n");
256 PyGILState_Ensure(); /* finalizing, no need to grab the state */
258 // free other python data.
261 /* clear all python data from structs */
263 bpy_intern_string_exit();
268 // measure time since py started
269 bpy_timer= PIL_check_seconds_timer() - bpy_timer;
271 printf("*bpy stats* - ");
272 printf("tot exec: %d, ", bpy_timer_count);
273 printf("tot run: %.4fsec, ", bpy_timer_run_tot);
274 if(bpy_timer_count>0)
275 printf("average run: %.6fsec, ", (bpy_timer_run_tot/bpy_timer_count));
278 printf("tot usage %.4f%%", (bpy_timer_run_tot/bpy_timer)*100.0);
282 // fprintf(stderr, "Ending Python Done!\n");
288 static void python_script_error_jump_text(struct Text *text)
292 python_script_error_jump(text->id.name+2, &lineno, &offset);
294 /* select the line with the error */
295 txt_move_to(text, lineno - 1, INT_MAX, FALSE);
296 txt_move_to(text, lineno - 1, offset, TRUE);
300 /* super annoying, undo _PyModule_Clear(), bug [#23871] */
301 #define PYMODULE_CLEAR_WORKAROUND
303 #ifdef PYMODULE_CLEAR_WORKAROUND
304 /* bad!, we should never do this, but currently only safe way I could find to keep namespace.
305 * from being cleared. - campbell */
309 /* ommit other values, we only want the dict. */
313 static int python_script_exec(bContext *C, const char *fn, struct Text *text, struct ReportList *reports, const short do_jump)
315 PyObject *main_mod= NULL;
316 PyObject *py_dict= NULL, *py_result= NULL;
317 PyGILState_STATE gilstate;
319 BLI_assert(fn || text);
321 if (fn==NULL && text==NULL) {
325 bpy_context_set(C, &gilstate);
327 PyC_MainModule_Backup(&main_mod);
330 char fn_dummy[FILE_MAXDIR];
331 bpy_text_filename_get(fn_dummy, sizeof(fn_dummy), text);
333 if(text->compiled == NULL) { /* if it wasn't already compiled, do it now */
334 char *buf= txt_to_buf(text);
336 text->compiled= Py_CompileString(buf, fn_dummy, Py_file_input);
340 if(PyErr_Occurred()) {
342 python_script_error_jump_text(text);
344 BPY_text_free_code(text);
349 py_dict= PyC_DefaultNameSpace(fn_dummy);
350 py_result= PyEval_EvalCode(text->compiled, py_dict, py_dict);
355 FILE *fp= fopen(fn, "r");
358 py_dict= PyC_DefaultNameSpace(fn);
361 /* Previously we used PyRun_File to run directly the code on a FILE
362 * object, but as written in the Python/C API Ref Manual, chapter 2,
363 * 'FILE structs for different C libraries can be different and
365 * So now we load the script file data to a buffer */
371 pystring= MEM_mallocN(strlen(fn) + 32, "pystring");
373 sprintf(pystring, "exec(open(r'%s').read())", fn);
374 py_result= PyRun_String(pystring, Py_file_input, py_dict, py_dict);
378 py_result= PyRun_File(fp, fn, Py_file_input, py_dict, py_dict);
383 PyErr_Format(PyExc_IOError,
384 "Python file \"%s\" could not be opened: %s",
385 fn, strerror(errno));
393 python_script_error_jump_text(text);
396 BPy_errors_to_report(reports);
399 Py_DECREF(py_result);
403 #ifdef PYMODULE_CLEAR_WORKAROUND
404 PyModuleObject *mmod= (PyModuleObject *)PyDict_GetItemString(PyThreadState_GET()->interp->modules, "__main__");
405 PyObject *dict_back= mmod->md_dict;
406 /* freeing the module will clear the namespace,
407 * gives problems running classes defined in this namespace being used later. */
409 Py_DECREF(dict_back);
412 #undef PYMODULE_CLEAR_WORKAROUND
415 PyC_MainModule_Restore(main_mod);
417 bpy_context_clear(C, &gilstate);
419 return (py_result != NULL);
422 /* Can run a file or text block */
423 int BPY_filepath_exec(bContext *C, const char *filepath, struct ReportList *reports)
425 return python_script_exec(C, filepath, NULL, reports, FALSE);
429 int BPY_text_exec(bContext *C, struct Text *text, struct ReportList *reports, const short do_jump)
431 return python_script_exec(C, NULL, text, reports, do_jump);
434 void BPY_DECREF(void *pyob_ptr)
436 PyGILState_STATE gilstate= PyGILState_Ensure();
437 Py_DECREF((PyObject *)pyob_ptr);
438 PyGILState_Release(gilstate);
441 /* return -1 on error, else 0 */
442 int BPY_button_exec(bContext *C, const char *expr, double *value, const short verbose)
444 PyGILState_STATE gilstate;
445 PyObject *py_dict, *mod, *retval;
447 PyObject *main_mod= NULL;
449 if (!value || !expr) return -1;
456 bpy_context_set(C, &gilstate);
458 PyC_MainModule_Backup(&main_mod);
460 py_dict= PyC_DefaultNameSpace("<blender button>");
462 mod= PyImport_ImportModule("math");
464 PyDict_Merge(py_dict, PyModule_GetDict(mod), 0); /* 0 - dont overwrite existing values */
467 else { /* highly unlikely but possibly */
472 retval= PyRun_String(expr, Py_eval_input, py_dict, py_dict);
474 if (retval == NULL) {
480 if(PyTuple_Check(retval)) {
481 /* Users my have typed in 10km, 2m
482 * add up all values */
486 for(i=0; i<PyTuple_GET_SIZE(retval); i++) {
487 val+= PyFloat_AsDouble(PyTuple_GET_ITEM(retval, i));
491 val= PyFloat_AsDouble(retval);
495 if(val==-1 && PyErr_Occurred()) {
498 else if (!finite(val)) {
508 BPy_errors_to_report(CTX_wm_reports(C));
515 PyC_MainModule_Backup(&main_mod);
517 bpy_context_clear(C, &gilstate);
522 int BPY_string_exec(bContext *C, const char *expr)
524 PyGILState_STATE gilstate;
525 PyObject *main_mod= NULL;
526 PyObject *py_dict, *retval;
528 Main *bmain_back; /* XXX, quick fix for release (Copy Settings crash), needs further investigation */
530 if (!expr) return -1;
536 bpy_context_set(C, &gilstate);
538 PyC_MainModule_Backup(&main_mod);
540 py_dict= PyC_DefaultNameSpace("<blender string>");
542 bmain_back= bpy_import_main_get();
543 bpy_import_main_set(CTX_data_main(C));
545 retval= PyRun_String(expr, Py_eval_input, py_dict, py_dict);
547 bpy_import_main_set(bmain_back);
549 if (retval == NULL) {
552 BPy_errors_to_report(CTX_wm_reports(C));
558 PyC_MainModule_Restore(main_mod);
560 bpy_context_clear(C, &gilstate);
566 void BPY_modules_load_user(bContext *C)
568 PyGILState_STATE gilstate;
569 Main *bmain= CTX_data_main(C);
572 /* can happen on file load */
576 /* update pointers since this can run from a nested script
579 bpy_context_update(C);
582 bpy_context_set(C, &gilstate);
584 for(text=CTX_data_main(C)->text.first; text; text= text->id.next) {
585 if(text->flags & TXT_ISSCRIPT && BLI_testextensie(text->id.name+2, ".py")) {
586 if(!(G.f & G_SCRIPT_AUTOEXEC)) {
587 printf("scripts disabled for \"%s\", skipping '%s'\n", bmain->name, text->id.name+2);
590 PyObject *module= bpy_text_import(text);
602 bpy_context_clear(C, &gilstate);
605 int BPY_context_member_get(bContext *C, const char *member, bContextDataResult *result)
607 PyObject *pyctx= (PyObject *)CTX_py_dict_get(C);
608 PyObject *item= PyDict_GetItemString(pyctx, member);
609 PointerRNA *ptr= NULL;
615 else if(item==Py_None) {
618 else if(BPy_StructRNA_Check(item)) {
619 ptr= &(((BPy_StructRNA *)item)->ptr);
621 //result->ptr= ((BPy_StructRNA *)item)->ptr;
622 CTX_data_pointer_set(result, ptr->id.data, ptr->type, ptr->data);
625 else if (PySequence_Check(item)) {
626 PyObject *seq_fast= PySequence_Fast(item, "bpy_context_get sequence conversion");
627 if (seq_fast==NULL) {
632 int len= PySequence_Fast_GET_SIZE(seq_fast);
634 for(i= 0; i < len; i++) {
635 PyObject *list_item= PySequence_Fast_GET_ITEM(seq_fast, i);
637 if(BPy_StructRNA_Check(list_item)) {
639 CollectionPointerLink *link= MEM_callocN(sizeof(CollectionPointerLink), "bpy_context_get");
640 link->ptr= ((BPy_StructRNA *)item)->ptr;
641 BLI_addtail(&result->list, link);
643 ptr= &(((BPy_StructRNA *)list_item)->ptr);
644 CTX_data_list_add(result, ptr->id.data, ptr->type, ptr->data);
647 printf("List item not a valid type\n");
658 if (item) printf("PyContext '%s' not a valid type\n", member);
659 else printf("PyContext '%s' not found\n", member);
663 printf("PyContext '%s' found\n", member);
671 #ifdef WITH_PYTHON_MODULE
672 #include "BLI_storage.h"
673 /* TODO, reloading the module isnt functional at the moment. */
675 static void bpy_module_free(void *mod);
676 extern int main_python_enter(int argc, const char **argv);
677 extern void main_python_exit(void);
678 static struct PyModuleDef bpy_proxy_def= {
679 PyModuleDef_HEAD_INIT,
683 NULL, /* m_methods */
685 NULL, /* m_traverse */
687 bpy_module_free, /* m_free */
692 /* Type-specific fields go here. */
696 /* call once __file__ is set */
697 void bpy_module_delay_init(PyObject *bpy_proxy)
701 PyObject *filename_obj= PyModule_GetFilenameObject(bpy_proxy); /* updating the module dict below will loose the reference to __file__ */
702 const char *filename_rel= _PyUnicode_AsString(filename_obj); /* can be relative */
703 char filename_abs[1024];
705 BLI_strncpy(filename_abs, filename_rel, sizeof(filename_abs));
706 BLI_path_cwd(filename_abs);
708 argv[0]= filename_abs;
711 // printf("module found %s\n", argv[0]);
713 main_python_enter(argc, argv);
715 /* initialized in BPy_init_modules() */
716 PyDict_Update(PyModule_GetDict(bpy_proxy), PyModule_GetDict(bpy_package_py));
719 static void dealloc_obj_dealloc(PyObject *self);
721 static PyTypeObject dealloc_obj_Type= {{{0}}};
723 /* use our own dealloc so we can free a property if we use one */
724 static void dealloc_obj_dealloc(PyObject *self)
726 bpy_module_delay_init(((dealloc_obj *)self)->mod);
728 /* Note, for subclassed PyObjects we cant just call PyObject_DEL() directly or it will crash */
729 dealloc_obj_Type.tp_free(self);
735 PyObject *bpy_proxy= PyModule_Create(&bpy_proxy_def);
738 * 1) this init function is expected to have a private member defined - 'md_def'
739 * but this is only set for C defined modules (not py packages)
740 * so we cant return 'bpy_package_py' as is.
742 * 2) there is a 'bpy' C module for python to load which is basically all of blender,
743 * and there is scripts/bpy/__init__.py,
744 * we may end up having to rename this module so there is no naming conflict here eg:
745 * 'from blender import bpy'
747 * 3) we dont know the filename at this point, workaround by assigning a dummy value
748 * which calls back when its freed so the real loading can take place.
751 /* assign an object which is freed after __file__ is assigned */
754 /* assign dummy type */
755 dealloc_obj_Type.tp_name= "dealloc_obj";
756 dealloc_obj_Type.tp_basicsize= sizeof(dealloc_obj);
757 dealloc_obj_Type.tp_dealloc= dealloc_obj_dealloc;
758 dealloc_obj_Type.tp_flags= Py_TPFLAGS_DEFAULT;
760 if(PyType_Ready(&dealloc_obj_Type) < 0)
763 dob= (dealloc_obj *) dealloc_obj_Type.tp_alloc(&dealloc_obj_Type, 0);
764 dob->mod= bpy_proxy; /* borrow */
765 PyModule_AddObject(bpy_proxy, "__file__", (PyObject *)dob); /* borrow */
770 static void bpy_module_free(void *UNUSED(mod))