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 *****
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 */
48 #include "BLI_winstuff.h"
51 #include "DNA_space_types.h"
52 #include "DNA_text_types.h"
54 #include "MEM_guardedalloc.h"
56 #include "BLI_storage.h"
57 #include "BLI_fileops.h"
58 #include "BLI_string.h"
59 #include "BLI_path_util.h"
61 #include "BKE_context.h"
63 #include "BKE_context.h"
65 #include "BKE_global.h" /* only for script checking */
67 #include "BPY_extern.h"
69 #include "../generic/bpy_internal_import.h" // our own imports
71 /* for internal use, when starting and ending python scripts */
73 /* incase a python script triggers another python call, stop bpy_context_clear from invalidating */
74 static int py_call_level= 0;
75 BPy_StructRNA *bpy_context_module= NULL; /* for fast access */
82 static int bpy_timer_count = 0;
83 static double bpy_timer; /* time since python starts */
84 static double bpy_timer_run; /* time for each python script run */
85 static double bpy_timer_run_tot; /* accumulate python runs */
88 void bpy_context_set(bContext *C, PyGILState_STATE *gilstate)
93 *gilstate = PyGILState_Ensure();
95 if(py_call_level==1) {
97 if(C) { // XXX - should always be true.
99 bpy_import_main_set(CTX_data_main(C));
102 fprintf(stderr, "ERROR: Python context called with a NULL Context. this should not happen!\n");
105 BPY_update_modules(); /* can give really bad results if this isnt here */
108 if(bpy_timer_count==0) {
109 /* record time from the beginning */
110 bpy_timer= PIL_check_seconds_timer();
111 bpy_timer_run = bpy_timer_run_tot = 0.0;
113 bpy_timer_run= PIL_check_seconds_timer();
121 void bpy_context_clear(bContext *C, PyGILState_STATE *gilstate)
126 PyGILState_Release(*gilstate);
128 if(py_call_level < 0) {
129 fprintf(stderr, "ERROR: Python context internal state bug. this should not happen!\n");
131 else if(py_call_level==0) {
132 // XXX - Calling classes currently wont store the context :\, cant set NULL because of this. but this is very flakey still.
133 //BPy_SetContext(NULL);
134 //bpy_import_main_set(NULL);
137 bpy_timer_run_tot += PIL_check_seconds_timer() - bpy_timer_run;
144 void BPY_free_compiled_text( struct Text *text )
146 if( text->compiled ) {
147 Py_DECREF( ( PyObject * ) text->compiled );
148 text->compiled = NULL;
152 void BPY_update_modules( void )
154 #if 0 // slow, this runs all the time poll, draw etc 100's of time a sec.
155 PyObject *mod= PyImport_ImportModuleLevel("bpy", NULL, NULL, NULL, 0);
156 PyModule_AddObject( mod, "data", BPY_rna_module() );
157 PyModule_AddObject( mod, "types", BPY_rna_types() ); // atm this does not need updating
160 /* refreshes the main struct */
161 BPY_update_rna_module();
162 bpy_context_module->ptr.data= (void *)BPy_GetContext();
165 /*****************************************************************************
166 * Description: This function creates a new Python dictionary object.
167 *****************************************************************************/
168 static PyObject *CreateGlobalDictionary( bContext *C, const char *filename )
172 PyObject *dict = PyDict_New( );
173 PyDict_SetItemString( dict, "__builtins__", PyEval_GetBuiltins( ) );
175 item = PyUnicode_FromString( "__main__" );
176 PyDict_SetItemString( dict, "__name__", item );
179 /* __file__ only for nice UI'ness */
181 PyObject *item = PyUnicode_FromString( filename );
182 PyDict_SetItemString( dict, "__file__", item );
186 /* add bpy to global namespace */
187 mod= PyImport_ImportModuleLevel("bpy", NULL, NULL, NULL, 0);
188 PyDict_SetItemString( dict, "bpy", mod );
194 /* must be called before Py_Initialize */
195 void BPY_start_python_path(void)
197 char *py_path_bundle= BLI_gethome_folder("python", BLI_GETHOME_ALL);
199 if(py_path_bundle==NULL)
202 /* set the environment path */
203 printf("found bundled python: %s\n", py_path_bundle);
206 /* OSX allow file/directory names to contain : character (represented as / in the Finder)
207 but current Python lib (release 3.1.1) doesn't handle these correctly */
208 if(strchr(py_path_bundle, ':'))
209 printf("Warning : Blender application is located in a path containing : or / chars\
210 \nThis may make python import function fail\n");
214 /* cmake/MSVC debug build crashes without this, why only
215 in this case is unknown.. */
217 char *envpath = getenv("PYTHONPATH");
219 if(envpath && envpath[0]) {
220 char *newenvpath = BLI_sprintfN("%s;%s", py_path_bundle, envpath);
221 BLI_setenv("PYTHONPATH", newenvpath);
222 MEM_freeN(newenvpath);
225 BLI_setenv("PYTHONPATH", py_path_bundle);
230 static wchar_t py_path_bundle_wchar[FILE_MAXDIR];
232 mbstowcs(py_path_bundle_wchar, py_path_bundle, FILE_MAXDIR);
233 Py_SetPythonHome(py_path_bundle_wchar);
239 void BPY_set_context(bContext *C)
244 /* call BPY_set_context first */
245 void BPY_start_python( int argc, char **argv )
247 PyThreadState *py_tstate = NULL;
249 BPY_start_python_path(); /* allow to use our own included python */
253 // PySys_SetArgv( argc, argv); // broken in py3, not a huge deal
254 /* sigh, why do python guys not have a char** version anymore? :( */
258 PyObject *py_argv= PyList_New(argc);
259 for (i=0; i<argc; i++)
260 PyList_SET_ITEM(py_argv, i, PyUnicode_FromString(argv[i]));
262 #else // should fix bug #20021 - utf path name problems
263 PyObject *py_argv= PyList_New(0);
264 for (i=0; i<argc; i++) {
265 PyObject *item= PyUnicode_Decode(argv[i], strlen(argv[i]), Py_FileSystemDefaultEncoding, NULL);
266 if(item==NULL) { // should never happen
271 PyList_Append(py_argv, item);
276 PySys_SetObject("argv", py_argv);
280 /* Initialize thread support (also acquires lock) */
281 PyEval_InitThreads();
284 /* bpy.* and lets us import it */
287 { /* our own import and reload functions */
289 //PyObject *m = PyImport_AddModule("__builtin__");
290 //PyObject *d = PyModule_GetDict(m);
291 PyObject *d = PyEval_GetBuiltins( );
292 PyDict_SetItemString(d, "reload", item=PyCFunction_New(bpy_reload_meth, NULL)); Py_DECREF(item);
293 PyDict_SetItemString(d, "__import__", item=PyCFunction_New(bpy_import_meth, NULL)); Py_DECREF(item);
298 py_tstate = PyGILState_GetThisThreadState();
299 PyEval_ReleaseThread(py_tstate);
302 void BPY_end_python( void )
304 // fprintf(stderr, "Ending Python!\n");
306 PyGILState_Ensure(); /* finalizing, no need to grab the state */
308 // free other python data.
311 /* clear all python data from structs */
316 // measure time since py started
317 bpy_timer = PIL_check_seconds_timer() - bpy_timer;
319 printf("*bpy stats* - ");
320 printf("tot exec: %d, ", bpy_timer_count);
321 printf("tot run: %.4fsec, ", bpy_timer_run_tot);
322 if(bpy_timer_count>0)
323 printf("average run: %.6fsec, ", (bpy_timer_run_tot/bpy_timer_count));
326 printf("tot usage %.4f%%", (bpy_timer_run_tot/bpy_timer)*100.0);
330 // fprintf(stderr, "Ending Python Done!\n");
336 /* Can run a file or text block */
337 int BPY_run_python_script( bContext *C, const char *fn, struct Text *text, struct ReportList *reports)
339 PyObject *py_dict, *py_result= NULL;
340 PyGILState_STATE gilstate;
342 if (fn==NULL && text==NULL) {
346 bpy_context_set(C, &gilstate);
348 py_dict = CreateGlobalDictionary(C, text?text->id.name+2:fn);
352 if( !text->compiled ) { /* if it wasn't already compiled, do it now */
353 char *buf = txt_to_buf( text );
356 Py_CompileString( buf, text->id.name+2, Py_file_input );
360 if( PyErr_Occurred( ) ) {
361 BPY_free_compiled_text( text );
365 py_result = PyEval_EvalCode( text->compiled, py_dict, py_dict );
368 FILE *fp= fopen(fn, "r");
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 */
380 pystring= MEM_mallocN(strlen(fn) + 32, "pystring");
382 sprintf(pystring, "exec(open(r'%s').read())", fn);
383 py_result = PyRun_String( pystring, Py_file_input, py_dict, py_dict );
386 py_result = PyRun_File(fp, fn, Py_file_input, py_dict, py_dict);
391 PyErr_Format(PyExc_SystemError, "Python file \"%s\" could not be opened: %s", fn, strerror(errno));
397 BPy_errors_to_report(reports);
399 Py_DECREF( py_result );
404 bpy_context_clear(C, &gilstate);
406 return py_result ? 1:0;
410 /* TODO - move into bpy_space.c ? */
411 /* GUI interface routines */
413 /* Copied from Draw.c */
414 static void exit_pydraw( SpaceScript * sc, short err )
416 Script *script = NULL;
418 if( !sc || !sc->script )
424 BPy_errors_to_report(NULL); // TODO, reports
425 script->flags = 0; /* mark script struct for deletion */
426 SCRIPT_SET_NULL(script);
427 script->scriptname[0] = '\0';
428 script->scriptarg[0] = '\0';
429 // XXX 2.5 error_pyscript();
430 // XXX 2.5 scrarea_queue_redraw( sc->area );
434 BPy_Set_DrawButtonsList(sc->but_refs);
435 BPy_Free_DrawButtonsList(); /*clear all temp button references*/
440 Py_XDECREF( ( PyObject * ) script->py_draw );
441 Py_XDECREF( ( PyObject * ) script->py_event );
442 Py_XDECREF( ( PyObject * ) script->py_button );
444 script->py_draw = script->py_event = script->py_button = NULL;
447 static int bpy_run_script_init(bContext *C, SpaceScript * sc)
449 if (sc->script==NULL)
452 if (sc->script->py_draw==NULL && sc->script->scriptname[0] != '\0')
453 BPY_run_python_script(C, sc->script->scriptname, NULL, NULL);
455 if (sc->script->py_draw==NULL)
461 int BPY_run_script_space_draw(const struct bContext *C, SpaceScript * sc)
463 if (bpy_run_script_init( (bContext *)C, sc)) {
464 PyGILState_STATE gilstate = PyGILState_Ensure();
465 PyObject *result = PyObject_CallObject( sc->script->py_draw, NULL );
470 PyGILState_Release(gilstate);
475 // XXX - not used yet, listeners dont get a context
476 int BPY_run_script_space_listener(bContext *C, SpaceScript * sc)
478 if (bpy_run_script_init(C, sc)) {
479 PyGILState_STATE gilstate = PyGILState_Ensure();
481 PyObject *result = PyObject_CallObject( sc->script->py_draw, NULL );
486 PyGILState_Release(gilstate);
491 void BPY_DECREF(void *pyob_ptr)
493 PyGILState_STATE gilstate = PyGILState_Ensure();
494 Py_DECREF((PyObject *)pyob_ptr);
495 PyGILState_Release(gilstate);
499 /* called from the the scripts window, assume context is ok */
500 int BPY_run_python_script_space(const char *modulename, const char *func)
502 PyObject *py_dict, *py_result= NULL;
504 PyGILState_STATE gilstate;
506 /* for calling the module function */
509 gilstate = PyGILState_Ensure();
511 py_dict = CreateGlobalDictionary(C);
513 PyObject *module = PyImport_ImportModule(scpt->script.filename);
515 PyErr_SetFormat(PyExc_SystemError, "could not import '%s'", scpt->script.filename);
518 py_func = PyObject_GetAttrString(modulename, func);
520 PyErr_SetFormat(PyExc_SystemError, "module has no function '%s.%s'\n", scpt->script.filename, func);
524 if (!PyCallable_Check(py_func)) {
525 PyErr_SetFormat(PyExc_SystemError, "module item is not callable '%s.%s'\n", scpt->script.filename, func);
528 py_result= PyObject_CallObject(py_func, NULL); // XXX will need args eventually
534 BPy_errors_to_report(NULL); // TODO - reports
536 Py_DECREF( py_result );
542 PyGILState_Release(gilstate);
547 // #define TIME_REGISTRATION
549 #ifdef TIME_REGISTRATION
550 #include "PIL_time.h"
554 int BPY_button_eval(bContext *C, char *expr, double *value)
556 PyGILState_STATE gilstate;
557 PyObject *dict, *mod, *retval;
560 if (!value || !expr || expr[0]=='\0') return -1;
562 bpy_context_set(C, &gilstate);
564 dict= CreateGlobalDictionary(C, NULL);
566 /* import some modules: builtins,math*/
567 PyDict_SetItemString(dict, "__builtins__", PyEval_GetBuiltins());
569 mod = PyImport_ImportModule("math");
571 PyDict_Merge(dict, PyModule_GetDict(mod), 0); /* 0 - dont overwrite existing values */
573 /* Only keep for backwards compat! - just import all math into root, they are standard */
574 PyDict_SetItemString(dict, "math", mod);
575 PyDict_SetItemString(dict, "m", mod);
579 retval = PyRun_String(expr, Py_eval_input, dict, dict);
581 if (retval == NULL) {
587 if(PyTuple_Check(retval)) {
588 /* Users my have typed in 10km, 2m
589 * add up all values */
593 for(i=0; i<PyTuple_GET_SIZE(retval); i++) {
594 val+= PyFloat_AsDouble(PyTuple_GET_ITEM(retval, i));
598 val = PyFloat_AsDouble(retval);
602 if(val==-1 && PyErr_Occurred()) {
611 BPy_errors_to_report(CTX_wm_reports(C));
615 bpy_context_clear(C, &gilstate);
620 void BPY_load_user_modules(bContext *C)
622 PyGILState_STATE gilstate;
623 Main *bmain= CTX_data_main(C);
626 /* can happen on file load */
630 bpy_context_set(C, &gilstate);
632 for(text=CTX_data_main(C)->text.first; text; text= text->id.next) {
633 if(text->flags & TXT_ISSCRIPT && BLI_testextensie(text->id.name+2, ".py")) {
634 if(!(G.fileflags & G_SCRIPT_AUTOEXEC)) {
635 printf("scripts disabled for \"%s\", skipping '%s'\n", bmain->name, text->id.name+2);
638 PyObject *module= bpy_text_import(text);
650 bpy_context_clear(C, &gilstate);
653 int BPY_context_get(bContext *C, const char *member, bContextDataResult *result)
655 PyObject *pyctx= (PyObject *)CTX_py_dict_get(C);
656 PyObject *item= PyDict_GetItemString(pyctx, member);
657 PointerRNA *ptr= NULL;
663 else if(item==Py_None) {
666 else if(BPy_StructRNA_Check(item)) {
667 ptr= &(((BPy_StructRNA *)item)->ptr);
669 //result->ptr= ((BPy_StructRNA *)item)->ptr;
670 CTX_data_pointer_set(result, ptr->id.data, ptr->type, ptr->data);
673 else if (PySequence_Check(item)) {
674 PyObject *seq_fast= PySequence_Fast(item, "bpy_context_get sequence conversion");
675 if (seq_fast==NULL) {
680 int len= PySequence_Fast_GET_SIZE(seq_fast);
682 for(i = 0; i < len; i++) {
683 PyObject *list_item= PySequence_Fast_GET_ITEM(seq_fast, i);
685 if(BPy_StructRNA_Check(list_item)) {
687 CollectionPointerLink *link= MEM_callocN(sizeof(CollectionPointerLink), "bpy_context_get");
688 link->ptr= ((BPy_StructRNA *)item)->ptr;
689 BLI_addtail(&result->list, link);
691 ptr= &(((BPy_StructRNA *)list_item)->ptr);
692 CTX_data_list_add(result, ptr->id.data, ptr->type, ptr->data);
695 printf("List item not a valid type\n");
706 if (item) printf("Context '%s' not a valid type\n", member);
707 else printf("Context '%s' not found\n", member);
710 printf("Context '%s' found\n", member);