10 #include "BLI_winstuff.h"
14 #include "compile.h" /* for the PyCodeObject */
15 #include "eval.h" /* for PyEval_EvalCode */
17 #include "bpy_compat.h"
20 #include "bpy_operator.h"
24 #include "DNA_anim_types.h"
25 #include "DNA_space_types.h"
26 #include "DNA_text_types.h"
28 #include "MEM_guardedalloc.h"
31 #include "BLI_string.h"
33 #include "BKE_context.h"
34 #include "BKE_fcurve.h"
37 #include "BPY_extern.h"
39 #include "../generic/bpy_internal_import.h" // our own imports
42 void BPY_free_compiled_text( struct Text *text )
44 if( text->compiled ) {
45 Py_DECREF( ( PyObject * ) text->compiled );
46 text->compiled = NULL;
50 /*****************************************************************************
51 * Description: Creates the bpy module and adds it to sys.modules for importing
52 *****************************************************************************/
53 static void bpy_init_modules( void )
57 mod = PyModule_New("bpy");
59 PyModule_AddObject( mod, "data", BPY_rna_module() );
60 /* PyModule_AddObject( mod, "doc", BPY_rna_doc() ); */
61 PyModule_AddObject( mod, "types", BPY_rna_types() );
62 PyModule_AddObject( mod, "props", BPY_rna_props() );
63 PyModule_AddObject( mod, "ops", BPY_operator_module() );
64 PyModule_AddObject( mod, "ui", BPY_ui_module() ); // XXX very experemental, consider this a test, especially PyCObject is not meant to be perminant
66 /* add the module so we can import it */
67 PyDict_SetItemString(PySys_GetObject("modules"), "bpy", mod);
71 #if (PY_VERSION_HEX < 0x02050000)
72 PyObject *PyImport_ImportModuleLevel(char *name, void *a, void *b, void *c, int d)
74 return PyImport_ImportModule(name);
78 void BPY_update_modules( void )
80 PyObject *mod= PyImport_ImportModuleLevel("bpy", NULL, NULL, NULL, 0);
81 PyModule_AddObject( mod, "data", BPY_rna_module() );
82 PyModule_AddObject( mod, "types", BPY_rna_types() );
85 /*****************************************************************************
86 * Description: This function creates a new Python dictionary object.
87 *****************************************************************************/
88 static PyObject *CreateGlobalDictionary( bContext *C )
91 PyObject *dict = PyDict_New( );
92 PyObject *item = PyUnicode_FromString( "__main__" );
93 PyDict_SetItemString( dict, "__builtins__", PyEval_GetBuiltins( ) );
94 PyDict_SetItemString( dict, "__name__", item );
97 // XXX - evil, need to access context
100 // XXX - put somewhere more logical
103 static PyMethodDef bpy_prop_meths[] = {
104 {"FloatProperty", (PyCFunction)BPy_FloatProperty, METH_VARARGS|METH_KEYWORDS, ""},
105 {"IntProperty", (PyCFunction)BPy_IntProperty, METH_VARARGS|METH_KEYWORDS, ""},
106 {"BoolProperty", (PyCFunction)BPy_BoolProperty, METH_VARARGS|METH_KEYWORDS, ""},
107 {"StringProperty", (PyCFunction)BPy_StringProperty, METH_VARARGS|METH_KEYWORDS, ""},
108 {NULL, NULL, 0, NULL}
111 for(ml = bpy_prop_meths; ml->ml_name; ml++) {
112 PyDict_SetItemString( dict, ml->ml_name, PyCFunction_New(ml, NULL));
116 /* add bpy to global namespace */
117 mod= PyImport_ImportModuleLevel("bpy", NULL, NULL, NULL, 0);
118 PyDict_SetItemString( dict, "bpy", mod );
124 void BPY_start_python( int argc, char **argv )
126 PyThreadState *py_tstate = NULL;
130 //PySys_SetArgv( argc_copy, argv_copy );
132 /* Initialize thread support (also acquires lock) */
133 PyEval_InitThreads();
136 /* bpy.* and lets us import it */
139 { /* our own import and reload functions */
141 //PyObject *m = PyImport_AddModule("__builtin__");
142 //PyObject *d = PyModule_GetDict(m);
143 PyObject *d = PyEval_GetBuiltins( );
144 PyDict_SetItemString(d, "reload", item=PyCFunction_New(bpy_reload_meth, NULL)); Py_DECREF(item);
145 PyDict_SetItemString(d, "__import__", item=PyCFunction_New(bpy_import_meth, NULL)); Py_DECREF(item);
148 py_tstate = PyGILState_GetThisThreadState();
149 PyEval_ReleaseThread(py_tstate);
152 void BPY_end_python( void )
154 PyGILState_Ensure(); /* finalizing, no need to grab the state */
156 // free other python data.
157 //BPY_rna_free_types();
164 /* Can run a file or text block */
165 int BPY_run_python_script( bContext *C, const char *fn, struct Text *text, struct ReportList *reports)
167 PyObject *py_dict, *py_result;
168 PyGILState_STATE gilstate;
170 if (fn==NULL && text==NULL) {
174 //BPY_start_python();
176 gilstate = PyGILState_Ensure();
178 BPY_update_modules(); /* can give really bad results if this isnt here */
179 bpy_import_main_set(CTX_data_main(C));
181 py_dict = CreateGlobalDictionary(C);
185 if( !text->compiled ) { /* if it wasn't already compiled, do it now */
186 char *buf = txt_to_buf( text );
189 Py_CompileString( buf, text->id.name+2, Py_file_input );
193 if( PyErr_Occurred( ) ) {
194 BPy_errors_to_report(reports);
195 BPY_free_compiled_text( text );
196 PyGILState_Release(gilstate);
200 py_result = PyEval_EvalCode( text->compiled, py_dict, py_dict );
204 /* TODO - look into a better way to run a file */
205 sprintf(pystring, "exec(open(r'%s').read())", fn);
206 py_result = PyRun_String( pystring, Py_file_input, py_dict, py_dict );
210 BPy_errors_to_report(reports);
212 Py_DECREF( py_result );
216 PyGILState_Release(gilstate);
217 bpy_import_main_set(NULL);
220 return py_result ? 1:0;
224 /* TODO - move into bpy_space.c ? */
225 /* GUI interface routines */
227 /* Copied from Draw.c */
228 static void exit_pydraw( SpaceScript * sc, short err )
230 Script *script = NULL;
232 if( !sc || !sc->script )
238 BPy_errors_to_report(NULL); // TODO, reports
239 script->flags = 0; /* mark script struct for deletion */
240 SCRIPT_SET_NULL(script);
241 script->scriptname[0] = '\0';
242 script->scriptarg[0] = '\0';
243 // XXX 2.5 error_pyscript();
244 // XXX 2.5 scrarea_queue_redraw( sc->area );
248 BPy_Set_DrawButtonsList(sc->but_refs);
249 BPy_Free_DrawButtonsList(); /*clear all temp button references*/
254 Py_XDECREF( ( PyObject * ) script->py_draw );
255 Py_XDECREF( ( PyObject * ) script->py_event );
256 Py_XDECREF( ( PyObject * ) script->py_button );
258 script->py_draw = script->py_event = script->py_button = NULL;
261 static int bpy_run_script_init(bContext *C, SpaceScript * sc)
263 if (sc->script==NULL)
266 if (sc->script->py_draw==NULL && sc->script->scriptname[0] != '\0')
267 BPY_run_python_script(C, sc->script->scriptname, NULL, NULL);
269 if (sc->script->py_draw==NULL)
275 int BPY_run_script_space_draw(struct bContext *C, SpaceScript * sc)
277 if (bpy_run_script_init(C, sc)) {
278 PyGILState_STATE gilstate = PyGILState_Ensure();
279 PyObject *result = PyObject_CallObject( sc->script->py_draw, NULL );
284 PyGILState_Release(gilstate);
289 // XXX - not used yet, listeners dont get a context
290 int BPY_run_script_space_listener(bContext *C, SpaceScript * sc)
292 if (bpy_run_script_init(C, sc)) {
293 PyGILState_STATE gilstate = PyGILState_Ensure();
295 PyObject *result = PyObject_CallObject( sc->script->py_draw, NULL );
300 PyGILState_Release(gilstate);
305 void BPY_DECREF(void *pyob_ptr)
307 Py_DECREF((PyObject *)pyob_ptr);
311 /* called from the the scripts window, assume context is ok */
312 int BPY_run_python_script_space(const char *modulename, const char *func)
314 PyObject *py_dict, *py_result= NULL;
316 PyGILState_STATE gilstate;
318 /* for calling the module function */
321 gilstate = PyGILState_Ensure();
323 py_dict = CreateGlobalDictionary(C);
325 PyObject *module = PyImport_ImportModule(scpt->script.filename);
327 PyErr_SetFormat(PyExc_SystemError, "could not import '%s'", scpt->script.filename);
330 py_func = PyObject_GetAttrString(modulename, func);
332 PyErr_SetFormat(PyExc_SystemError, "module has no function '%s.%s'\n", scpt->script.filename, func);
336 if (!PyCallable_Check(py_func)) {
337 PyErr_SetFormat(PyExc_SystemError, "module item is not callable '%s.%s'\n", scpt->script.filename, func);
340 py_result= PyObject_CallObject(py_func, NULL); // XXX will need args eventually
346 BPy_errors_to_report(NULL); // TODO - reports
348 Py_DECREF( py_result );
354 PyGILState_Release(gilstate);
359 // #define TIME_REGISTRATION
361 #ifdef TIME_REGISTRATION
362 #include "PIL_time.h"
365 /* XXX this is temporary, need a proper script registration system for 2.5 */
366 void BPY_run_ui_scripts(bContext *C, int reload)
368 #ifdef TIME_REGISTRATION
369 double time = PIL_check_seconds_timer();
373 char *file_extension;
376 char *dirs[] = {"io", "ui", NULL};
377 int a, filelen; /* filename length */
379 PyGILState_STATE gilstate;
381 PyObject *sys_path_orig;
382 PyObject *sys_path_new;
384 gilstate = PyGILState_Ensure();
386 // XXX - evil, need to access context
388 bpy_import_main_set(CTX_data_main(C));
390 for(a=0; dirs[a]; a++) {
391 dirname= BLI_gethome_folder(dirs[a]);
396 dir = opendir(dirname);
401 /* backup sys.path */
402 sys_path_orig= PySys_GetObject("path");
403 Py_INCREF(sys_path_orig); /* dont free it */
405 sys_path_new= PyList_New(1);
406 PyList_SET_ITEM(sys_path_new, 0, PyUnicode_FromString(dirname));
407 PySys_SetObject("path", sys_path_new);
408 Py_DECREF(sys_path_new);
410 while((de = readdir(dir)) != NULL) {
411 /* We could stat the file but easier just to let python
412 * import it and complain if theres a problem */
414 file_extension = strstr(de->d_name, ".py");
416 if(file_extension && *(file_extension + 3) == '\0') {
417 filelen = strlen(de->d_name);
418 BLI_strncpy(path, de->d_name, filelen-2); /* cut off the .py on copy */
420 mod= PyImport_ImportModuleLevel(path, NULL, NULL, NULL, 0);
423 PyObject *mod_orig= mod;
424 mod= PyImport_ReloadModule(mod);
430 Py_DECREF(mod); /* could be NULL from reloading */
432 BPy_errors_to_report(NULL); // TODO - reports
433 fprintf(stderr, "unable to import \"%s\" %s/%s\n", path, dirname, de->d_name);
441 PySys_SetObject("path", sys_path_orig);
442 Py_DECREF(sys_path_orig);
445 bpy_import_main_set(NULL);
447 PyGILState_Release(gilstate);
448 #ifdef TIME_REGISTRATION
449 printf("script time %f\n", (PIL_check_seconds_timer()-time));
453 /* ****************************************** */
454 /* Drivers - PyExpression Evaluation */
456 /* for pydrivers (drivers using one-line Python expressions to express relationships between targets) */
457 PyObject *bpy_pydriver_Dict = NULL;
459 /* For faster execution we keep a special dictionary for pydrivers, with
460 * the needed modules and aliases.
462 static int bpy_pydriver_create_dict(void)
466 /* validate namespace for driver evaluation */
467 if (bpy_pydriver_Dict) return -1;
473 bpy_pydriver_Dict = d;
475 /* import some modules: builtins, bpy, math, (Blender.noise )*/
476 PyDict_SetItemString(d, "__builtins__", PyEval_GetBuiltins());
478 mod = PyImport_ImportModule("math");
480 PyDict_Merge(d, PyModule_GetDict(mod), 0); /* 0 - dont overwrite existing values */
482 /* Only keep for backwards compat! - just import all math into root, they are standard */
483 PyDict_SetItemString(d, "math", mod);
484 PyDict_SetItemString(d, "m", mod);
488 /* add bpy to global namespace */
489 mod= PyImport_ImportModuleLevel("bpy", NULL, NULL, NULL, 0);
491 PyDict_SetItemString(bpy_pydriver_Dict, "bpy", mod);
496 #if 0 // non existant yet
497 mod = PyImport_ImportModule("Blender.Noise");
499 PyDict_SetItemString(d, "noise", mod);
500 PyDict_SetItemString(d, "n", mod);
506 /* If there's a Blender text called pydrivers.py, import it.
507 * Users can add their own functions to this module.
509 if (G.f & G_DOSCRIPTLINKS) {
510 mod = importText("pydrivers"); /* can also use PyImport_Import() */
512 PyDict_SetItemString(d, "pydrivers", mod);
513 PyDict_SetItemString(d, "p", mod);
519 #endif // non existant yet
524 /* Update function, it gets rid of pydrivers global dictionary, forcing
525 * BPY_pydriver_eval to recreate it. This function is used to force
526 * reloading the Blender text module "pydrivers.py", if available, so
527 * updates in it reach pydriver evaluation.
529 void BPY_pydriver_update(void)
531 PyGILState_STATE gilstate = PyGILState_Ensure();
533 if (bpy_pydriver_Dict) { /* free the global dict used by pydrivers */
534 PyDict_Clear(bpy_pydriver_Dict);
535 Py_DECREF(bpy_pydriver_Dict);
536 bpy_pydriver_Dict = NULL;
539 PyGILState_Release(gilstate);
544 /* error return function for BPY_eval_pydriver */
545 static float pydriver_error(ChannelDriver *driver)
547 if (bpy_pydriver_Dict) { /* free the global dict used by pydrivers */
548 PyDict_Clear(bpy_pydriver_Dict);
549 Py_DECREF(bpy_pydriver_Dict);
550 bpy_pydriver_Dict = NULL;
553 driver->flag |= DRIVER_FLAG_INVALID; /* py expression failed */
554 fprintf(stderr, "\nError in Driver: The following Python expression failed:\n\t'%s'\n\n", driver->expression);
556 BPy_errors_to_report(NULL); // TODO - reports
561 /* This evals py driver expressions, 'expr' is a Python expression that
562 * should evaluate to a float number, which is returned.
564 float BPY_pydriver_eval (ChannelDriver *driver)
566 PyObject *driver_vars=NULL;
568 PyGILState_STATE gilstate;
571 float result = 0.0f; /* default return */
575 /* sanity checks - should driver be executed? */
576 if ((driver == NULL) /*|| (G.f & G_DOSCRIPTLINKS)==0*/)
579 /* get the py expression to be evaluated */
580 expr = driver->expression;
581 if ((expr == NULL) || (expr[0]=='\0'))
584 gilstate = PyGILState_Ensure();
586 /* init global dictionary for py-driver evaluation settings */
587 if (!bpy_pydriver_Dict) {
588 if (bpy_pydriver_create_dict() != 0) {
589 fprintf(stderr, "Pydriver error: couldn't create Python dictionary");
590 PyGILState_Release(gilstate);
595 /* add target values to a dict that will be used as '__locals__' dict */
596 driver_vars = PyDict_New(); // XXX do we need to decref this?
597 for (dtar= driver->targets.first; dtar; dtar= dtar->next) {
598 PyObject *driver_arg = NULL;
601 /* try to get variable value */
602 tval= driver_get_target_value(driver, dtar);
603 driver_arg= PyFloat_FromDouble((double)tval);
605 /* try to add to dictionary */
606 if (PyDict_SetItemString(driver_vars, dtar->name, driver_arg)) {
607 /* this target failed - bad name */
609 /* first one - print some extra info for easier identification */
610 fprintf(stderr, "\nBPY_pydriver_eval() - Error while evaluating PyDriver:\n");
614 fprintf(stderr, "\tBPY_pydriver_eval() - couldn't add variable '%s' to namespace \n", dtar->name);
615 BPy_errors_to_report(NULL); // TODO - reports
619 /* execute expression to get a value */
620 retval = PyRun_String(expr, Py_eval_input, bpy_pydriver_Dict, driver_vars);
622 /* decref the driver vars first... */
623 Py_DECREF(driver_vars);
625 /* process the result */
626 if (retval == NULL) {
627 result = pydriver_error(driver);
628 PyGILState_Release(gilstate);
632 result = (float)PyFloat_AsDouble(retval);
635 if ((result == -1) && PyErr_Occurred()) {
636 result = pydriver_error(driver);
637 PyGILState_Release(gilstate);
641 /* all fine, make sure the "invalid expression" flag is cleared */
642 driver->flag &= ~DRIVER_FLAG_INVALID;
644 PyGILState_Release(gilstate);