2 * ***** BEGIN GPL LICENSE BLOCK *****
4 * This program is free software; you can redistribute it and/or
5 * modify it under the terms of the GNU General Public License
6 * as published by the Free Software Foundation; either version 2
7 * of the License, or (at your option) any later version.
9 * This program is distributed in the hope that it will be useful,
10 * but WITHOUT ANY WARRANTY; without even the implied warranty of
11 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12 * GNU General Public License for more details.
14 * You should have received a copy of the GNU General Public License
15 * along with this program; if not, write to the Free Software Foundation,
16 * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
18 * Contributor(s): Willian P. Germano, Campbell Barton
20 * ***** END GPL LICENSE BLOCK *****
23 /** \file blender/python/generic/bpy_internal_import.c
26 * This file defines replacements for pythons '__import__' and 'imp.reload'
27 * functions which can import from blender textblocks.
30 * This should eventually be replaced by import hooks (pep 302).
37 #include "MEM_guardedalloc.h"
39 #include "DNA_text_types.h"
41 #include "BLI_listbase.h"
42 #include "BLI_path_util.h"
43 #include "BLI_string.h"
44 #include "BLI_utildefines.h"
47 #include "BKE_text.h" /* txt_to_buf */
50 #include "bpy_internal_import.h" /* own include */
52 static Main *bpy_import_main = NULL;
53 static ListBase bpy_import_main_list;
55 static PyMethodDef bpy_import_meth;
56 static PyMethodDef bpy_reload_meth;
57 static PyObject *imp_reload_orig = NULL;
59 /* 'builtins' is most likely PyEval_GetBuiltins() */
62 * \note to the discerning developer, yes - this is nasty
63 * monkey-patching our own import into Python's builtin 'imp' module.
65 * However Python's alternative is to use import hooks,
66 * which are implemented in a way that we can't use our own importer as a
67 * fall-back (instead we must try and fail - raise an exception every time).
68 * Since importing from blenders text-blocks is not the common case
69 * I prefer to use Pythons import by default and fall-back to
70 * Blenders - which we can only do by intercepting import calls I'm afraid.
73 void bpy_import_init(PyObject *builtins)
78 PyDict_SetItemString(builtins, "__import__", item = PyCFunction_New(&bpy_import_meth, NULL)); Py_DECREF(item);
81 * XXX, use import hooks */
82 mod = PyImport_ImportModuleLevel("imp", NULL, NULL, NULL, 0);
84 PyObject *mod_dict = PyModule_GetDict(mod);
86 /* blender owns the function */
87 imp_reload_orig = PyDict_GetItemString(mod_dict, "reload");
88 Py_INCREF(imp_reload_orig);
90 PyDict_SetItemString(mod_dict, "reload", item = PyCFunction_New(&bpy_reload_meth, NULL)); Py_DECREF(item);
94 BLI_assert(!"unable to load 'imp' module.");
99 static void free_compiled_text(Text *text)
101 if (text->compiled) {
102 Py_DECREF((PyObject *)text->compiled);
104 text->compiled = NULL;
107 struct Main *bpy_import_main_get(void)
109 return bpy_import_main;
112 void bpy_import_main_set(struct Main *maggie)
114 bpy_import_main = maggie;
117 void bpy_import_main_extra_add(struct Main *maggie)
119 BLI_addhead(&bpy_import_main_list, maggie);
122 void bpy_import_main_extra_remove(struct Main *maggie)
124 BLI_remlink_safe(&bpy_import_main_list, maggie);
127 /* returns a dummy filename for a textblock so we can tell what file a text block comes from */
128 void bpy_text_filename_get(char *fn, size_t fn_len, Text *text)
130 BLI_snprintf(fn, fn_len, "%s%c%s", ID_BLEND_PATH(bpy_import_main, &text->id), SEP, text->id.name + 2);
133 bool bpy_text_compile(Text *text)
135 char fn_dummy[FILE_MAX];
138 bpy_text_filename_get(fn_dummy, sizeof(fn_dummy), text);
140 /* if previously compiled, free the object */
141 free_compiled_text(text);
143 buf = txt_to_buf(text);
144 text->compiled = Py_CompileString(buf, fn_dummy, Py_file_input);
147 if (PyErr_Occurred()) {
150 PySys_SetObject("last_traceback", NULL);
151 free_compiled_text(text);
159 PyObject *bpy_text_import(Text *text)
161 char modulename[MAX_ID_NAME + 2];
164 if (!text->compiled) {
165 if (bpy_text_compile(text) == false) {
170 len = strlen(text->id.name + 2);
171 BLI_strncpy(modulename, text->id.name + 2, len);
172 modulename[len - 3] = '\0'; /* remove .py */
173 return PyImport_ExecCodeModule(modulename, text->compiled);
176 PyObject *bpy_text_import_name(const char *name, int *found)
179 char txtname[MAX_ID_NAME - 2];
180 int namelen = strlen(name);
181 //XXX Main *maggie = bpy_import_main ? bpy_import_main:G.main;
182 Main *maggie = bpy_import_main;
187 printf("ERROR: bpy_import_main_set() was not called before running python. this is a bug.\n");
191 /* we know this cant be importable, the name is too long for blender! */
192 if (namelen >= (MAX_ID_NAME - 2) - 3)
195 memcpy(txtname, name, namelen);
196 memcpy(&txtname[namelen], ".py", 4);
198 text = BLI_findstring(&maggie->text, txtname, offsetof(ID, name) + 2);
202 return bpy_text_import(text);
205 /* If we still haven't found the module try additional modules form bpy_import_main_list */
206 maggie = bpy_import_main_list.first;
207 while (maggie && !text) {
208 text = BLI_findstring(&maggie->text, txtname, offsetof(ID, name) + 2);
209 maggie = maggie->next;
217 return bpy_text_import(text);
222 * find in-memory module and recompile
225 PyObject *bpy_text_reimport(PyObject *module, int *found)
229 const char *filepath;
230 //XXX Main *maggie = bpy_import_main ? bpy_import_main:G.main;
231 Main *maggie = bpy_import_main;
234 printf("ERROR: bpy_import_main_set() was not called before running python. this is a bug.\n");
240 /* get name, filename from the module itself */
241 if ((name = PyModule_GetName(module)) == NULL)
244 if ((filepath = (char *)PyModule_GetFilename(module)) == NULL)
247 /* look up the text object */
248 text = BLI_findstring(&maggie->text, BLI_path_basename(filepath), offsetof(ID, name) + 2);
250 /* uh-oh.... didn't find it */
256 if (bpy_text_compile(text) == false) {
260 /* make into a module */
261 return PyImport_ExecCodeModule((char *)name, text->compiled);
265 static PyObject *blender_import(PyObject *UNUSED(self), PyObject *args, PyObject *kw)
267 PyObject *exception, *err, *tb;
270 PyObject *globals = NULL, *locals = NULL, *fromlist = NULL;
271 int level = 0; /* relative imports */
274 //PyObject_Print(args, stderr, 0);
275 static const char *kwlist[] = {"name", "globals", "locals", "fromlist", "level", NULL};
277 if (!PyArg_ParseTupleAndKeywords(args, kw, "s|OOOi:bpy_import_meth", (char **)kwlist,
278 &name, &globals, &locals, &fromlist, &level))
283 /* import existing builtin modules or modules that have been imported already */
284 newmodule = PyImport_ImportModuleLevel(name, globals, locals, fromlist, level);
289 PyErr_Fetch(&exception, &err, &tb); /* get the python error in case we cant import as blender text either */
291 /* importing from existing modules failed, see if we have this module as blender text */
292 newmodule = bpy_text_import_name(name, &found);
294 if (newmodule) { /* found module as blender text, ignore above exception */
296 Py_XDECREF(exception);
299 /* printf("imported from text buffer...\n"); */
301 else if (found == 1) { /* blender text module failed to execute but was found, use its error message */
302 Py_XDECREF(exception);
308 /* no blender text was found that could import the module
309 * reuse the original error from PyImport_ImportModuleEx */
310 PyErr_Restore(exception, err, tb);
317 * our reload() module, to handle reloading in-memory scripts
320 static PyObject *blender_reload(PyObject *UNUSED(self), PyObject *module)
322 PyObject *exception, *err, *tb;
323 PyObject *newmodule = NULL;
326 /* try reimporting from file */
328 /* in Py3.3 this just calls imp.reload() which we overwrite, causing recursive calls */
329 //newmodule = PyImport_ReloadModule(module);
331 newmodule = PyObject_CallFunctionObjArgs(imp_reload_orig, module, NULL);
336 /* no file, try importing from memory */
337 PyErr_Fetch(&exception, &err, &tb); /*restore for probable later use */
339 newmodule = bpy_text_reimport(module, &found);
340 if (newmodule) { /* found module as blender text, ignore above exception */
342 Py_XDECREF(exception);
345 /* printf("imported from text buffer...\n"); */
347 else if (found == 1) { /* blender text module failed to execute but was found, use its error message */
348 Py_XDECREF(exception);
354 /* no blender text was found that could import the module
355 * reuse the original error from PyImport_ImportModuleEx */
356 PyErr_Restore(exception, err, tb);
362 static PyMethodDef bpy_import_meth = {"bpy_import_meth", (PyCFunction)blender_import, METH_VARARGS | METH_KEYWORDS, "blenders import"};
363 static PyMethodDef bpy_reload_meth = {"bpy_reload_meth", (PyCFunction)blender_reload, METH_O, "blenders reload"};