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., 59 Temple Place - Suite 330, Boston, MA 02111-1307, 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 *****
32 /* grr, python redefines */
33 #ifdef _POSIX_C_SOURCE
34 #undef _POSIX_C_SOURCE
38 #include "compile.h" /* for the PyCodeObject */
39 #include "eval.h" /* for PyEval_EvalCode */
43 #include "bpy_props.h"
44 #include "bpy_operator.h"
50 #include "BLI_winstuff.h"
53 #include "DNA_space_types.h"
54 #include "DNA_text_types.h"
56 #include "MEM_guardedalloc.h"
58 #include "BLI_path_util.h"
59 #include "BLI_storage.h"
60 #include "BLI_fileops.h"
61 #include "BLI_string.h"
63 #include "BKE_context.h"
65 #include "BKE_context.h"
68 #include "BPY_extern.h"
70 #include "BPy_Freestyle.h"
72 #include "../generic/bpy_internal_import.h" // our own imports
73 /* external util modules */
75 #include "../generic/Mathutils.h"
76 #include "../generic/Geometry.h"
77 #include "../generic/BGL.h"
78 #include "../generic/IDProp.h"
80 /* for internal use, when starting and ending python scripts */
82 /* incase a python script triggers another python call, stop bpy_context_clear from invalidating */
83 static int py_call_level= 0;
91 static int bpy_timer_count = 0;
92 static double bpy_timer; /* time since python starts */
93 static double bpy_timer_run; /* time for each python script run */
94 static double bpy_timer_run_tot; /* accumulate python runs */
97 void bpy_context_set(bContext *C, PyGILState_STATE *gilstate)
102 *gilstate = PyGILState_Ensure();
104 if(py_call_level==1) {
106 if(C) { // XXX - should always be true.
108 bpy_import_main_set(CTX_data_main(C));
111 fprintf(stderr, "ERROR: Python context called with a NULL Context. this should not happen!\n");
114 BPY_update_modules(); /* can give really bad results if this isnt here */
117 if(bpy_timer_count==0) {
118 /* record time from the beginning */
119 bpy_timer= PIL_check_seconds_timer();
120 bpy_timer_run = bpy_timer_run_tot = 0.0;
122 bpy_timer_run= PIL_check_seconds_timer();
130 void bpy_context_clear(bContext *C, PyGILState_STATE *gilstate)
135 PyGILState_Release(*gilstate);
137 if(py_call_level < 0) {
138 fprintf(stderr, "ERROR: Python context internal state bug. this should not happen!\n");
140 else if(py_call_level==0) {
141 // XXX - Calling classes currently wont store the context :\, cant set NULL because of this. but this is very flakey still.
142 //BPy_SetContext(NULL);
143 //bpy_import_main_set(NULL);
146 bpy_timer_run_tot += PIL_check_seconds_timer() - bpy_timer_run;
153 static void bpy_import_test(char *modname)
155 PyObject *mod= PyImport_ImportModuleLevel(modname, NULL, NULL, NULL, 0);
165 void BPY_free_compiled_text( struct Text *text )
167 if( text->compiled ) {
168 Py_DECREF( ( PyObject * ) text->compiled );
169 text->compiled = NULL;
173 /*****************************************************************************
174 * Description: Creates the bpy module and adds it to sys.modules for importing
175 *****************************************************************************/
176 static BPy_StructRNA *bpy_context_module= NULL; /* for fast access */
177 static void bpy_init_modules( void )
181 /* Needs to be first since this dir is needed for future modules */
182 char *modpath= BLI_gethome_folder("scripts/modules", BLI_GETHOME_ALL);
184 PyObject *sys_path= PySys_GetObject("path"); /* borrow */
185 PyObject *py_modpath= PyUnicode_FromString(modpath);
186 PyList_Insert(sys_path, 0, py_modpath); /* add first */
187 Py_DECREF(py_modpath);
190 /* stand alone utility modules not related to blender directly */
198 mod = PyModule_New("_bpy");
200 /* add the module so we can import it */
201 PyDict_SetItemString(PySys_GetObject("modules"), "_bpy", mod);
204 /* run first, initializes rna types */
207 PyModule_AddObject( mod, "types", BPY_rna_types() ); /* needs to be first so bpy_types can run */
208 bpy_import_test("bpy_types");
209 PyModule_AddObject( mod, "data", BPY_rna_module() ); /* imports bpy_types by running this */
210 bpy_import_test("bpy_types");
211 /* PyModule_AddObject( mod, "doc", BPY_rna_doc() ); */
212 PyModule_AddObject( mod, "props", BPY_rna_props() );
213 PyModule_AddObject( mod, "ops", BPY_operator_module() ); /* ops is now a python module that does the conversion from SOME_OT_foo -> some.foo */
214 PyModule_AddObject( mod, "app", BPY_app_struct() );
218 bpy_context_module= ( BPy_StructRNA * ) PyObject_NEW( BPy_StructRNA, &pyrna_struct_Type );
220 RNA_pointer_create(NULL, &RNA_Context, NULL, &bpy_context_module->ptr);
221 bpy_context_module->freeptr= 0;
223 PyModule_AddObject(mod, "context", (PyObject *)bpy_context_module);
226 /* add our own modules dir, this is a python package */
227 bpy_import_test("bpy");
230 void BPY_update_modules( void )
232 #if 0 // slow, this runs all the time poll, draw etc 100's of time a sec.
233 PyObject *mod= PyImport_ImportModuleLevel("bpy", NULL, NULL, NULL, 0);
234 PyModule_AddObject( mod, "data", BPY_rna_module() );
235 PyModule_AddObject( mod, "types", BPY_rna_types() ); // atm this does not need updating
238 /* refreshes the main struct */
239 BPY_update_rna_module();
240 bpy_context_module->ptr.data= (void *)BPy_GetContext();
243 /*****************************************************************************
244 * Description: This function creates a new Python dictionary object.
245 *****************************************************************************/
246 static PyObject *CreateGlobalDictionary( bContext *C, const char *filename )
250 PyObject *dict = PyDict_New( );
251 PyDict_SetItemString( dict, "__builtins__", PyEval_GetBuiltins( ) );
253 item = PyUnicode_FromString( "__main__" );
254 PyDict_SetItemString( dict, "__name__", item );
257 /* __file__ only for nice UI'ness */
259 PyObject *item = PyUnicode_FromString( filename );
260 PyDict_SetItemString( dict, "__file__", item );
264 /* add bpy to global namespace */
265 mod= PyImport_ImportModuleLevel("bpy", NULL, NULL, NULL, 0);
266 PyDict_SetItemString( dict, "bpy", mod );
272 /* must be called before Py_Initialize */
273 void BPY_start_python_path(void)
275 char *py_path_bundle= BLI_gethome_folder("python", BLI_GETHOME_ALL);
277 if(py_path_bundle==NULL)
280 /* set the environment path */
281 printf("found bundled python: %s\n", py_path_bundle);
284 /* OSX allow file/directory names to contain : character (represented as / in the Finder)
285 but current Python lib (release 3.1.1) doesn't handle these correctly */
286 if(strchr(py_path_bundle, ':'))
287 printf("Warning : Blender application is located in a path containing : or / chars\
288 \nThis may make python import function fail\n");
292 /* cmake/MSVC debug build crashes without this, why only
293 in this case is unknown.. */
295 char *envpath = getenv("PYTHONPATH");
297 if(envpath && envpath[0]) {
298 char *newenvpath = BLI_sprintfN("%s;%s", py_path_bundle, envpath);
299 BLI_setenv("PYTHONPATH", newenvpath);
300 MEM_freeN(newenvpath);
303 BLI_setenv("PYTHONPATH", py_path_bundle);
308 static wchar_t py_path_bundle_wchar[FILE_MAXDIR];
310 mbstowcs(py_path_bundle_wchar, py_path_bundle, FILE_MAXDIR);
311 Py_SetPythonHome(py_path_bundle_wchar);
317 void BPY_set_context(bContext *C)
322 /* call BPY_set_context first */
323 void BPY_start_python( int argc, char **argv )
325 PyThreadState *py_tstate = NULL;
327 BPY_start_python_path(); /* allow to use our own included python */
331 // PySys_SetArgv( argc, argv); // broken in py3, not a huge deal
332 /* sigh, why do python guys not have a char** version anymore? :( */
336 PyObject *py_argv= PyList_New(argc);
337 for (i=0; i<argc; i++)
338 PyList_SET_ITEM(py_argv, i, PyUnicode_FromString(argv[i]));
340 #else // should fix bug #20021 - utf path name problems
341 PyObject *py_argv= PyList_New(0);
342 for (i=0; i<argc; i++) {
343 PyObject *item= PyUnicode_Decode(argv[i], strlen(argv[i]), Py_FileSystemDefaultEncoding, NULL);
344 if(item==NULL) { // should never happen
349 PyList_Append(py_argv, item);
354 PySys_SetObject("argv", py_argv);
358 /* Initialize thread support (also acquires lock) */
359 PyEval_InitThreads();
362 /* bpy.* and lets us import it */
365 { /* our own import and reload functions */
367 //PyObject *m = PyImport_AddModule("__builtin__");
368 //PyObject *d = PyModule_GetDict(m);
369 PyObject *d = PyEval_GetBuiltins( );
370 PyDict_SetItemString(d, "reload", item=PyCFunction_New(bpy_reload_meth, NULL)); Py_DECREF(item);
371 PyDict_SetItemString(d, "__import__", item=PyCFunction_New(bpy_import_meth, NULL)); Py_DECREF(item);
376 py_tstate = PyGILState_GetThisThreadState();
377 PyEval_ReleaseThread(py_tstate);
380 void BPY_end_python( void )
382 // fprintf(stderr, "Ending Python!\n");
384 PyGILState_Ensure(); /* finalizing, no need to grab the state */
386 // free other python data.
389 /* clear all python data from structs */
394 // measure time since py started
395 bpy_timer = PIL_check_seconds_timer() - bpy_timer;
397 printf("*bpy stats* - ");
398 printf("tot exec: %d, ", bpy_timer_count);
399 printf("tot run: %.4fsec, ", bpy_timer_run_tot);
400 if(bpy_timer_count>0)
401 printf("average run: %.6fsec, ", (bpy_timer_run_tot/bpy_timer_count));
404 printf("tot usage %.4f%%", (bpy_timer_run_tot/bpy_timer)*100.0);
408 // fprintf(stderr, "Ending Python Done!\n");
414 /* Can run a file or text block */
415 int BPY_run_python_script( bContext *C, const char *fn, struct Text *text, struct ReportList *reports)
417 PyObject *py_dict, *py_result= NULL;
418 PyGILState_STATE gilstate;
420 if (fn==NULL && text==NULL) {
424 bpy_context_set(C, &gilstate);
426 py_dict = CreateGlobalDictionary(C, text?text->id.name+2:fn);
430 if( !text->compiled ) { /* if it wasn't already compiled, do it now */
431 char *buf = txt_to_buf( text );
434 Py_CompileString( buf, text->id.name+2, Py_file_input );
438 if( PyErr_Occurred( ) ) {
439 BPY_free_compiled_text( text );
443 py_result = PyEval_EvalCode( text->compiled, py_dict, py_dict );
446 FILE *fp= fopen(fn, "r");
449 /* Previously we used PyRun_File to run directly the code on a FILE
450 * object, but as written in the Python/C API Ref Manual, chapter 2,
451 * 'FILE structs for different C libraries can be different and
453 * So now we load the script file data to a buffer */
458 pystring= MEM_mallocN(strlen(fn) + 32, "pystring");
460 sprintf(pystring, "exec(open(r'%s').read())", fn);
461 py_result = PyRun_String( pystring, Py_file_input, py_dict, py_dict );
464 py_result = PyRun_File(fp, fn, Py_file_input, py_dict, py_dict);
469 PyErr_Format(PyExc_SystemError, "Python file \"%s\" could not be opened: %s", fn, strerror(errno));
475 BPy_errors_to_report(reports);
477 Py_DECREF( py_result );
482 bpy_context_clear(C, &gilstate);
484 return py_result ? 1:0;
488 /* TODO - move into bpy_space.c ? */
489 /* GUI interface routines */
491 /* Copied from Draw.c */
492 static void exit_pydraw( SpaceScript * sc, short err )
494 Script *script = NULL;
496 if( !sc || !sc->script )
502 BPy_errors_to_report(NULL); // TODO, reports
503 script->flags = 0; /* mark script struct for deletion */
504 SCRIPT_SET_NULL(script);
505 script->scriptname[0] = '\0';
506 script->scriptarg[0] = '\0';
507 // XXX 2.5 error_pyscript();
508 // XXX 2.5 scrarea_queue_redraw( sc->area );
512 BPy_Set_DrawButtonsList(sc->but_refs);
513 BPy_Free_DrawButtonsList(); /*clear all temp button references*/
518 Py_XDECREF( ( PyObject * ) script->py_draw );
519 Py_XDECREF( ( PyObject * ) script->py_event );
520 Py_XDECREF( ( PyObject * ) script->py_button );
522 script->py_draw = script->py_event = script->py_button = NULL;
525 static int bpy_run_script_init(bContext *C, SpaceScript * sc)
527 if (sc->script==NULL)
530 if (sc->script->py_draw==NULL && sc->script->scriptname[0] != '\0')
531 BPY_run_python_script(C, sc->script->scriptname, NULL, NULL);
533 if (sc->script->py_draw==NULL)
539 int BPY_run_script_space_draw(const struct bContext *C, SpaceScript * sc)
541 if (bpy_run_script_init( (bContext *)C, sc)) {
542 PyGILState_STATE gilstate = PyGILState_Ensure();
543 PyObject *result = PyObject_CallObject( sc->script->py_draw, NULL );
548 PyGILState_Release(gilstate);
553 // XXX - not used yet, listeners dont get a context
554 int BPY_run_script_space_listener(bContext *C, SpaceScript * sc)
556 if (bpy_run_script_init(C, sc)) {
557 PyGILState_STATE gilstate = PyGILState_Ensure();
559 PyObject *result = PyObject_CallObject( sc->script->py_draw, NULL );
564 PyGILState_Release(gilstate);
569 void BPY_DECREF(void *pyob_ptr)
571 PyGILState_STATE gilstate = PyGILState_Ensure();
572 Py_DECREF((PyObject *)pyob_ptr);
573 PyGILState_Release(gilstate);
577 /* called from the the scripts window, assume context is ok */
578 int BPY_run_python_script_space(const char *modulename, const char *func)
580 PyObject *py_dict, *py_result= NULL;
582 PyGILState_STATE gilstate;
584 /* for calling the module function */
587 gilstate = PyGILState_Ensure();
589 py_dict = CreateGlobalDictionary(C);
591 PyObject *module = PyImport_ImportModule(scpt->script.filename);
593 PyErr_SetFormat(PyExc_SystemError, "could not import '%s'", scpt->script.filename);
596 py_func = PyObject_GetAttrString(modulename, func);
598 PyErr_SetFormat(PyExc_SystemError, "module has no function '%s.%s'\n", scpt->script.filename, func);
602 if (!PyCallable_Check(py_func)) {
603 PyErr_SetFormat(PyExc_SystemError, "module item is not callable '%s.%s'\n", scpt->script.filename, func);
606 py_result= PyObject_CallObject(py_func, NULL); // XXX will need args eventually
612 BPy_errors_to_report(NULL); // TODO - reports
614 Py_DECREF( py_result );
620 PyGILState_Release(gilstate);
625 // #define TIME_REGISTRATION
627 #ifdef TIME_REGISTRATION
628 #include "PIL_time.h"
632 int BPY_button_eval(bContext *C, char *expr, double *value)
634 PyGILState_STATE gilstate;
635 PyObject *dict, *mod, *retval;
638 if (!value || !expr || expr[0]=='\0') return -1;
640 bpy_context_set(C, &gilstate);
642 dict= CreateGlobalDictionary(C, NULL);
644 /* import some modules: builtins,math*/
645 PyDict_SetItemString(dict, "__builtins__", PyEval_GetBuiltins());
647 mod = PyImport_ImportModule("math");
649 PyDict_Merge(dict, PyModule_GetDict(mod), 0); /* 0 - dont overwrite existing values */
651 /* Only keep for backwards compat! - just import all math into root, they are standard */
652 PyDict_SetItemString(dict, "math", mod);
653 PyDict_SetItemString(dict, "m", mod);
657 retval = PyRun_String(expr, Py_eval_input, dict, dict);
659 if (retval == NULL) {
665 if(PyTuple_Check(retval)) {
666 /* Users my have typed in 10km, 2m
667 * add up all values */
671 for(i=0; i<PyTuple_GET_SIZE(retval); i++) {
672 val+= PyFloat_AsDouble(PyTuple_GET_ITEM(retval, i));
676 val = PyFloat_AsDouble(retval);
680 if(val==-1 && PyErr_Occurred()) {
689 BPy_errors_to_report(CTX_wm_reports(C));
693 bpy_context_clear(C, &gilstate);
698 void BPY_load_user_modules(bContext *C)
700 PyGILState_STATE gilstate;
701 Main *bmain= CTX_data_main(C);
704 /* can happen on file load */
708 bpy_context_set(C, &gilstate);
710 for(text=CTX_data_main(C)->text.first; text; text= text->id.next) {
711 if(text->flags & TXT_ISSCRIPT && BLI_testextensie(text->id.name+2, ".py")) {
712 PyObject *module= bpy_text_import(text);
723 bpy_context_clear(C, &gilstate);
726 int BPY_context_get(bContext *C, const char *member, bContextDataResult *result)
728 PyObject *pyctx= (PyObject *)CTX_py_dict_get(C);
729 PyObject *item= PyDict_GetItemString(pyctx, member);
730 PointerRNA *ptr= NULL;
736 else if(item==Py_None) {
739 else if(BPy_StructRNA_Check(item)) {
740 ptr= &(((BPy_StructRNA *)item)->ptr);
742 //result->ptr= ((BPy_StructRNA *)item)->ptr;
743 CTX_data_pointer_set(result, ptr->id.data, ptr->type, ptr->data);
746 else if (PySequence_Check(item)) {
747 PyObject *seq_fast= PySequence_Fast(item, "bpy_context_get sequence conversion");
748 if (seq_fast==NULL) {
753 int len= PySequence_Fast_GET_SIZE(seq_fast);
755 for(i = 0; i < len; i++) {
756 PyObject *list_item= PySequence_Fast_GET_ITEM(seq_fast, i);
758 if(BPy_StructRNA_Check(list_item)) {
760 CollectionPointerLink *link= MEM_callocN(sizeof(CollectionPointerLink), "bpy_context_get");
761 link->ptr= ((BPy_StructRNA *)item)->ptr;
762 BLI_addtail(&result->list, link);
764 ptr= &(((BPy_StructRNA *)list_item)->ptr);
765 CTX_data_list_add(result, ptr->id.data, ptr->type, ptr->data);
768 printf("List item not a valid type\n");
779 if (item) printf("Context '%s' not a valid type\n", member);
780 else printf("Context '%s' not found\n", member);
783 printf("Context '%s' found\n", member);