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 */
42 #include "bpy_operator.h"
49 #include "BLI_winstuff.h"
52 #include "DNA_anim_types.h"
53 #include "DNA_space_types.h"
54 #include "DNA_text_types.h"
56 #include "MEM_guardedalloc.h"
59 #include "BLI_storage.h"
60 #include "BLI_fileops.h"
61 #include "BLI_string.h"
63 #include "BKE_context.h"
64 #include "BKE_fcurve.h"
66 #include "BKE_context.h"
67 #include "BKE_global.h"
70 #include "BPY_extern.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"
81 /* for internal use, when starting and ending python scripts */
83 /* incase a python script triggers another python call, stop bpy_context_clear from invalidating */
84 static int py_call_level= 0;
92 static int bpy_timer_count = 0;
93 static double bpy_timer; /* time since python starts */
94 static double bpy_timer_run; /* time for each python script run */
95 static double bpy_timer_run_tot; /* accumulate python runs */
98 void bpy_context_set(bContext *C, PyGILState_STATE *gilstate)
103 *gilstate = PyGILState_Ensure();
105 if(py_call_level==1) {
107 if(C) { // XXX - should always be true.
109 bpy_import_main_set(CTX_data_main(C));
112 fprintf(stderr, "ERROR: Python context called with a NULL Context. this should not happen!\n");
115 BPY_update_modules(); /* can give really bad results if this isnt here */
118 if(bpy_timer_count==0) {
119 /* record time from the beginning */
120 bpy_timer= PIL_check_seconds_timer();
121 bpy_timer_run = bpy_timer_run_tot = 0.0;
123 bpy_timer_run= PIL_check_seconds_timer();
131 void bpy_context_clear(bContext *C, PyGILState_STATE *gilstate)
136 PyGILState_Release(*gilstate);
138 if(py_call_level < 0) {
139 fprintf(stderr, "ERROR: Python context internal state bug. this should not happen!\n");
141 else if(py_call_level==0) {
142 // XXX - Calling classes currently wont store the context :\, cant set NULL because of this. but this is very flakey still.
143 //BPy_SetContext(NULL);
144 //bpy_import_main_set(NULL);
147 bpy_timer_run_tot += PIL_check_seconds_timer() - bpy_timer_run;
154 static void bpy_import_test(char *modname)
156 PyObject *mod= PyImport_ImportModuleLevel(modname, NULL, NULL, NULL, 0);
166 void BPY_free_compiled_text( struct Text *text )
168 if( text->compiled ) {
169 Py_DECREF( ( PyObject * ) text->compiled );
170 text->compiled = NULL;
174 /*****************************************************************************
175 * Description: Creates the bpy module and adds it to sys.modules for importing
176 *****************************************************************************/
177 static BPy_StructRNA *bpy_context_module= NULL; /* for fast access */
178 static void bpy_init_modules( void )
182 /* Needs to be first since this dir is needed for future modules */
183 char *modpath= BLI_gethome_folder("scripts/modules", BLI_GETHOME_ALL);
185 PyObject *sys_path= PySys_GetObject("path"); /* borrow */
186 PyObject *py_modpath= PyUnicode_FromString(modpath);
187 PyList_Insert(sys_path, 0, py_modpath); /* add first */
188 Py_DECREF(py_modpath);
191 /* 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, "ui", BPY_ui_module() ); // XXX very experimental, consider this a test, especially PyCObject is not meant to be permanent
220 bpy_context_module= ( BPy_StructRNA * ) PyObject_NEW( BPy_StructRNA, &pyrna_struct_Type );
221 RNA_pointer_create(NULL, &RNA_Context, NULL, &bpy_context_module->ptr);
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 BLI_setenv("PYTHONHOME", py_path_bundle);
285 BLI_setenv("PYTHONPATH", py_path_bundle);
289 static wchar_t py_path_bundle_wchar[FILE_MAXDIR];
291 mbstowcs(py_path_bundle_wchar, py_path_bundle, FILE_MAXDIR);
292 Py_SetPythonHome(py_path_bundle_wchar);
298 void BPY_set_context(bContext *C)
303 /* call BPY_set_context first */
304 void BPY_start_python( int argc, char **argv )
306 PyThreadState *py_tstate = NULL;
308 BPY_start_python_path(); /* allow to use our own included python */
312 // PySys_SetArgv( argc, argv); // broken in py3, not a huge deal
313 /* sigh, why do python guys not have a char** version anymore? :( */
316 PyObject *py_argv= PyList_New(argc);
318 for (i=0; i<argc; i++)
319 PyList_SET_ITEM(py_argv, i, PyUnicode_FromString(argv[i]));
321 PySys_SetObject("argv", py_argv);
325 /* Initialize thread support (also acquires lock) */
326 PyEval_InitThreads();
329 /* bpy.* and lets us import it */
332 { /* our own import and reload functions */
334 //PyObject *m = PyImport_AddModule("__builtin__");
335 //PyObject *d = PyModule_GetDict(m);
336 PyObject *d = PyEval_GetBuiltins( );
337 PyDict_SetItemString(d, "reload", item=PyCFunction_New(bpy_reload_meth, NULL)); Py_DECREF(item);
338 PyDict_SetItemString(d, "__import__", item=PyCFunction_New(bpy_import_meth, NULL)); Py_DECREF(item);
343 py_tstate = PyGILState_GetThisThreadState();
344 PyEval_ReleaseThread(py_tstate);
347 void BPY_end_python( void )
349 // fprintf(stderr, "Ending Python!\n");
351 PyGILState_Ensure(); /* finalizing, no need to grab the state */
353 // free other python data.
356 /* clear all python data from structs */
361 // measure time since py started
362 bpy_timer = PIL_check_seconds_timer() - bpy_timer;
364 printf("*bpy stats* - ");
365 printf("tot exec: %d, ", bpy_timer_count);
366 printf("tot run: %.4fsec, ", bpy_timer_run_tot);
367 if(bpy_timer_count>0)
368 printf("average run: %.6fsec, ", (bpy_timer_run_tot/bpy_timer_count));
371 printf("tot usage %.4f%%", (bpy_timer_run_tot/bpy_timer)*100.0);
375 // fprintf(stderr, "Ending Python Done!\n");
381 /* Can run a file or text block */
382 int BPY_run_python_script( bContext *C, const char *fn, struct Text *text, struct ReportList *reports)
384 PyObject *py_dict, *py_result= NULL;
385 PyGILState_STATE gilstate;
387 if (fn==NULL && text==NULL) {
391 bpy_context_set(C, &gilstate);
393 py_dict = CreateGlobalDictionary(C, text?text->id.name+2:fn);
397 if( !text->compiled ) { /* if it wasn't already compiled, do it now */
398 char *buf = txt_to_buf( text );
401 Py_CompileString( buf, text->id.name+2, Py_file_input );
405 if( PyErr_Occurred( ) ) {
406 BPY_free_compiled_text( text );
410 py_result = PyEval_EvalCode( text->compiled, py_dict, py_dict );
413 FILE *fp= fopen(fn, "r");
416 /* Previously we used PyRun_File to run directly the code on a FILE
417 * object, but as written in the Python/C API Ref Manual, chapter 2,
418 * 'FILE structs for different C libraries can be different and
420 * So now we load the script file data to a buffer */
425 pystring= malloc(strlen(fn) + 32);
427 sprintf(pystring, "exec(open(r'%s').read())", fn);
428 py_result = PyRun_String( pystring, Py_file_input, py_dict, py_dict );
431 py_result = PyRun_File(fp, fn, Py_file_input, py_dict, py_dict);
436 PyErr_Format(PyExc_SystemError, "Python file \"%s\" could not be opened: %s", fn, strerror(errno));
442 BPy_errors_to_report(reports);
444 Py_DECREF( py_result );
449 bpy_context_clear(C, &gilstate);
451 return py_result ? 1:0;
455 /* TODO - move into bpy_space.c ? */
456 /* GUI interface routines */
458 /* Copied from Draw.c */
459 static void exit_pydraw( SpaceScript * sc, short err )
461 Script *script = NULL;
463 if( !sc || !sc->script )
469 BPy_errors_to_report(NULL); // TODO, reports
470 script->flags = 0; /* mark script struct for deletion */
471 SCRIPT_SET_NULL(script);
472 script->scriptname[0] = '\0';
473 script->scriptarg[0] = '\0';
474 // XXX 2.5 error_pyscript();
475 // XXX 2.5 scrarea_queue_redraw( sc->area );
479 BPy_Set_DrawButtonsList(sc->but_refs);
480 BPy_Free_DrawButtonsList(); /*clear all temp button references*/
485 Py_XDECREF( ( PyObject * ) script->py_draw );
486 Py_XDECREF( ( PyObject * ) script->py_event );
487 Py_XDECREF( ( PyObject * ) script->py_button );
489 script->py_draw = script->py_event = script->py_button = NULL;
492 static int bpy_run_script_init(bContext *C, SpaceScript * sc)
494 if (sc->script==NULL)
497 if (sc->script->py_draw==NULL && sc->script->scriptname[0] != '\0')
498 BPY_run_python_script(C, sc->script->scriptname, NULL, NULL);
500 if (sc->script->py_draw==NULL)
506 int BPY_run_script_space_draw(const struct bContext *C, SpaceScript * sc)
508 if (bpy_run_script_init( (bContext *)C, sc)) {
509 PyGILState_STATE gilstate = PyGILState_Ensure();
510 PyObject *result = PyObject_CallObject( sc->script->py_draw, NULL );
515 PyGILState_Release(gilstate);
520 // XXX - not used yet, listeners dont get a context
521 int BPY_run_script_space_listener(bContext *C, SpaceScript * sc)
523 if (bpy_run_script_init(C, sc)) {
524 PyGILState_STATE gilstate = PyGILState_Ensure();
526 PyObject *result = PyObject_CallObject( sc->script->py_draw, NULL );
531 PyGILState_Release(gilstate);
536 void BPY_DECREF(void *pyob_ptr)
538 Py_DECREF((PyObject *)pyob_ptr);
542 /* called from the the scripts window, assume context is ok */
543 int BPY_run_python_script_space(const char *modulename, const char *func)
545 PyObject *py_dict, *py_result= NULL;
547 PyGILState_STATE gilstate;
549 /* for calling the module function */
552 gilstate = PyGILState_Ensure();
554 py_dict = CreateGlobalDictionary(C);
556 PyObject *module = PyImport_ImportModule(scpt->script.filename);
558 PyErr_SetFormat(PyExc_SystemError, "could not import '%s'", scpt->script.filename);
561 py_func = PyObject_GetAttrString(modulename, func);
563 PyErr_SetFormat(PyExc_SystemError, "module has no function '%s.%s'\n", scpt->script.filename, func);
567 if (!PyCallable_Check(py_func)) {
568 PyErr_SetFormat(PyExc_SystemError, "module item is not callable '%s.%s'\n", scpt->script.filename, func);
571 py_result= PyObject_CallObject(py_func, NULL); // XXX will need args eventually
577 BPy_errors_to_report(NULL); // TODO - reports
579 Py_DECREF( py_result );
585 PyGILState_Release(gilstate);
590 // #define TIME_REGISTRATION
592 #ifdef TIME_REGISTRATION
593 #include "PIL_time.h"
596 /* ****************************************** */
597 /* Drivers - PyExpression Evaluation */
599 /* for pydrivers (drivers using one-line Python expressions to express relationships between targets) */
600 PyObject *bpy_pydriver_Dict = NULL;
602 /* For faster execution we keep a special dictionary for pydrivers, with
603 * the needed modules and aliases.
605 static int bpy_pydriver_create_dict(void)
609 /* validate namespace for driver evaluation */
610 if (bpy_pydriver_Dict) return -1;
616 bpy_pydriver_Dict = d;
618 /* import some modules: builtins, bpy, math, (Blender.noise )*/
619 PyDict_SetItemString(d, "__builtins__", PyEval_GetBuiltins());
621 mod = PyImport_ImportModule("math");
623 PyDict_Merge(d, PyModule_GetDict(mod), 0); /* 0 - dont overwrite existing values */
625 /* Only keep for backwards compat! - just import all math into root, they are standard */
626 PyDict_SetItemString(d, "math", mod);
627 PyDict_SetItemString(d, "m", mod);
631 /* add bpy to global namespace */
632 mod= PyImport_ImportModuleLevel("bpy", NULL, NULL, NULL, 0);
634 PyDict_SetItemString(bpy_pydriver_Dict, "bpy", mod);
639 #if 0 // non existant yet
640 mod = PyImport_ImportModule("Blender.Noise");
642 PyDict_SetItemString(d, "noise", mod);
643 PyDict_SetItemString(d, "n", mod);
649 /* If there's a Blender text called pydrivers.py, import it.
650 * Users can add their own functions to this module.
652 if (G.f & G_DOSCRIPTLINKS) {
653 mod = importText("pydrivers"); /* can also use PyImport_Import() */
655 PyDict_SetItemString(d, "pydrivers", mod);
656 PyDict_SetItemString(d, "p", mod);
662 #endif // non existant yet
667 /* Update function, it gets rid of pydrivers global dictionary, forcing
668 * BPY_pydriver_eval to recreate it. This function is used to force
669 * reloading the Blender text module "pydrivers.py", if available, so
670 * updates in it reach pydriver evaluation.
672 void BPY_pydriver_update(void)
674 PyGILState_STATE gilstate = PyGILState_Ensure();
676 if (bpy_pydriver_Dict) { /* free the global dict used by pydrivers */
677 PyDict_Clear(bpy_pydriver_Dict);
678 Py_DECREF(bpy_pydriver_Dict);
679 bpy_pydriver_Dict = NULL;
682 PyGILState_Release(gilstate);
687 /* error return function for BPY_eval_pydriver */
688 static float pydriver_error(ChannelDriver *driver)
690 if (bpy_pydriver_Dict) { /* free the global dict used by pydrivers */
691 PyDict_Clear(bpy_pydriver_Dict);
692 Py_DECREF(bpy_pydriver_Dict);
693 bpy_pydriver_Dict = NULL;
696 driver->flag |= DRIVER_FLAG_INVALID; /* py expression failed */
697 fprintf(stderr, "\nError in Driver: The following Python expression failed:\n\t'%s'\n\n", driver->expression);
699 BPy_errors_to_report(NULL); // TODO - reports
704 /* This evals py driver expressions, 'expr' is a Python expression that
705 * should evaluate to a float number, which is returned.
707 float BPY_pydriver_eval (ChannelDriver *driver)
709 PyObject *driver_vars=NULL;
711 PyGILState_STATE gilstate;
714 float result = 0.0f; /* default return */
718 /* sanity checks - should driver be executed? */
719 if ((driver == NULL) /*|| (G.f & G_DOSCRIPTLINKS)==0*/)
722 /* get the py expression to be evaluated */
723 expr = driver->expression;
724 if ((expr == NULL) || (expr[0]=='\0'))
727 gilstate = PyGILState_Ensure();
729 /* init global dictionary for py-driver evaluation settings */
730 if (!bpy_pydriver_Dict) {
731 if (bpy_pydriver_create_dict() != 0) {
732 fprintf(stderr, "Pydriver error: couldn't create Python dictionary");
733 PyGILState_Release(gilstate);
738 /* add target values to a dict that will be used as '__locals__' dict */
739 driver_vars = PyDict_New(); // XXX do we need to decref this?
740 for (dtar= driver->targets.first; dtar; dtar= dtar->next) {
741 PyObject *driver_arg = NULL;
744 /* try to get variable value */
745 tval= driver_get_target_value(driver, dtar);
746 driver_arg= PyFloat_FromDouble((double)tval);
748 /* try to add to dictionary */
749 if (PyDict_SetItemString(driver_vars, dtar->name, driver_arg)) {
750 /* this target failed - bad name */
752 /* first one - print some extra info for easier identification */
753 fprintf(stderr, "\nBPY_pydriver_eval() - Error while evaluating PyDriver:\n");
757 fprintf(stderr, "\tBPY_pydriver_eval() - couldn't add variable '%s' to namespace \n", dtar->name);
758 BPy_errors_to_report(NULL); // TODO - reports
762 /* execute expression to get a value */
763 retval = PyRun_String(expr, Py_eval_input, bpy_pydriver_Dict, driver_vars);
765 /* decref the driver vars first... */
766 Py_DECREF(driver_vars);
768 /* process the result */
769 if (retval == NULL) {
770 result = pydriver_error(driver);
771 PyGILState_Release(gilstate);
775 result = (float)PyFloat_AsDouble(retval);
778 if ((result == -1) && PyErr_Occurred()) {
779 result = pydriver_error(driver);
780 PyGILState_Release(gilstate);
784 /* all fine, make sure the "invalid expression" flag is cleared */
785 driver->flag &= ~DRIVER_FLAG_INVALID;
787 PyGILState_Release(gilstate);
792 int BPY_button_eval(bContext *C, char *expr, double *value)
794 PyGILState_STATE gilstate;
795 PyObject *dict, *mod, *retval;
798 if (!value || !expr || expr[0]=='\0') return -1;
800 bpy_context_set(C, &gilstate);
802 dict= CreateGlobalDictionary(C, NULL);
804 /* import some modules: builtins,math*/
805 PyDict_SetItemString(dict, "__builtins__", PyEval_GetBuiltins());
807 mod = PyImport_ImportModule("math");
809 PyDict_Merge(dict, PyModule_GetDict(mod), 0); /* 0 - dont overwrite existing values */
811 /* Only keep for backwards compat! - just import all math into root, they are standard */
812 PyDict_SetItemString(dict, "math", mod);
813 PyDict_SetItemString(dict, "m", mod);
817 retval = PyRun_String(expr, Py_eval_input, dict, dict);
819 if (retval == NULL) {
825 if(PyTuple_Check(retval)) {
826 /* Users my have typed in 10km, 2m
827 * add up all values */
831 for(i=0; i<PyTuple_GET_SIZE(retval); i++) {
832 val+= PyFloat_AsDouble(PyTuple_GET_ITEM(retval, i));
836 val = PyFloat_AsDouble(retval);
840 if(val==-1 && PyErr_Occurred()) {
849 BPy_errors_to_report(CTX_wm_reports(C));
853 bpy_context_clear(C, &gilstate);
858 void BPY_load_user_modules(bContext *C)
860 PyGILState_STATE gilstate;
863 bpy_context_set(C, &gilstate);
865 for(text=CTX_data_main(C)->text.first; text; text= text->id.next) {
866 if(text->flags & TXT_ISSCRIPT && BLI_testextensie(text->id.name+2, ".py")) {
867 PyObject *module= bpy_text_import(text);
878 bpy_context_clear(C, &gilstate);
881 int BPY_context_get(bContext *C, const char *member, bContextDataResult *result)
883 PyObject *pyctx= (PyObject *)CTX_py_dict_get(C);
884 PyObject *item= PyDict_GetItemString(pyctx, member);
885 PointerRNA *ptr= NULL;
891 else if(item==Py_None) {
894 else if(BPy_StructRNA_Check(item)) {
895 ptr= &(((BPy_StructRNA *)item)->ptr);
897 //result->ptr= ((BPy_StructRNA *)item)->ptr;
898 CTX_data_pointer_set(result, ptr->id.data, ptr->type, ptr->data);
901 else if (PySequence_Check(item)) {
902 PyObject *seq_fast= PySequence_Fast(item, "bpy_context_get sequence conversion");
903 if (seq_fast==NULL) {
908 int len= PySequence_Fast_GET_SIZE(seq_fast);
910 for(i = 0; i < len; i++) {
911 PyObject *list_item= PySequence_Fast_GET_ITEM(seq_fast, i);
913 if(BPy_StructRNA_Check(list_item)) {
915 CollectionPointerLink *link= MEM_callocN(sizeof(CollectionPointerLink), "bpy_context_get");
916 link->ptr= ((BPy_StructRNA *)item)->ptr;
917 BLI_addtail(&result->list, link);
919 ptr= &(((BPy_StructRNA *)list_item)->ptr);
920 CTX_data_list_add(result, ptr->id.data, ptr->type, ptr->data);
923 printf("List item not a valid type\n");
934 if (item) printf("Context '%s' not a valid type\n", member);
935 else printf("Context '%s' not found\n", member);
937 else if (G.f & G_DEBUG) {
938 printf("Context '%s' found\n", member);