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): Campbell Barton
20 * ***** END GPL LICENSE BLOCK *****
23 /** \file blender/python/intern/bpy_operator.c
24 * \ingroup pythonintern
26 * This file defines '_bpy.ops', an internal python module which gives python
27 * the ability to inspect and call both C and Python defined operators.
30 * This module is exposed to the user via 'release/scripts/modules/bpy/ops.py'
31 * which fakes exposing operators as modules/functions using its own classes.
36 #include "RNA_types.h"
38 #include "BLI_utildefines.h"
39 #include "BLI_string.h"
41 #include "BPY_extern.h"
42 #include "bpy_operator.h"
43 #include "bpy_operator_wrap.h"
44 #include "bpy_rna.h" /* for setting arg props only - pyrna_py_to_prop() */
46 #include "../generic/bpy_internal_import.h"
48 #include "RNA_access.h"
49 #include "RNA_enum_types.h"
54 #include "MEM_guardedalloc.h"
56 #include "BLI_ghash.h"
58 #include "BKE_report.h"
59 #include "BKE_context.h"
61 /* so operators called can spawn threads which aquire the GIL */
62 #define BPY_RELEASE_GIL
65 static PyObject *pyop_poll(PyObject *UNUSED(self), PyObject *args)
69 PyObject *context_dict = NULL; /* optional args */
70 PyObject *context_dict_back;
71 const char *context_str = NULL;
74 int context = WM_OP_EXEC_DEFAULT;
76 /* XXX Todo, work out a better solution for passing on context,
77 * could make a tuple from self and pack the name and Context into it... */
78 bContext *C = (bContext *)BPy_GetContext();
81 PyErr_SetString(PyExc_RuntimeError, "Context is None, cant poll any operators");
85 if (!PyArg_ParseTuple(args, "s|Os:_bpy.ops.poll", &opname, &context_dict, &context_str))
88 ot = WM_operatortype_find(opname, true);
91 PyErr_Format(PyExc_AttributeError,
92 "Polling operator \"bpy.ops.%s\" error, "
93 "could not be found", opname);
98 if (RNA_enum_value_from_id(operator_context_items, context_str, &context) == 0) {
99 char *enum_str = BPy_enum_as_string(operator_context_items);
100 PyErr_Format(PyExc_TypeError,
101 "Calling operator \"bpy.ops.%s.poll\" error, "
102 "expected a string enum in (%.200s)",
109 if (context_dict == NULL || context_dict == Py_None) {
112 else if (!PyDict_Check(context_dict)) {
113 PyErr_Format(PyExc_TypeError,
114 "Calling operator \"bpy.ops.%s.poll\" error, "
115 "custom context expected a dict or None, got a %.200s",
116 opname, Py_TYPE(context_dict)->tp_name);
120 context_dict_back = CTX_py_dict_get(C);
121 CTX_py_dict_set(C, (void *)context_dict);
122 Py_XINCREF(context_dict); /* so we done loose it */
124 /* main purpose of thsi function */
125 ret = WM_operator_poll_context((bContext *)C, ot, context) ? Py_True : Py_False;
127 /* restore with original context dict, probably NULL but need this for nested operator calls */
128 Py_XDECREF(context_dict);
129 CTX_py_dict_set(C, (void *)context_dict_back);
135 static PyObject *pyop_call(PyObject *UNUSED(self), PyObject *args)
140 int operator_ret = OPERATOR_CANCELLED;
143 const char *context_str = NULL;
144 PyObject *kw = NULL; /* optional args */
145 PyObject *context_dict = NULL; /* optional args */
146 PyObject *context_dict_back;
148 /* note that context is an int, python does the conversion in this case */
149 int context = WM_OP_EXEC_DEFAULT;
152 /* XXX Todo, work out a better solution for passing on context,
153 * could make a tuple from self and pack the name and Context into it... */
154 bContext *C = (bContext *)BPy_GetContext();
157 PyErr_SetString(PyExc_RuntimeError, "Context is None, cant poll any operators");
161 if (!PyArg_ParseTuple(args, "sO|O!si:_bpy.ops.call",
162 &opname, &context_dict, &PyDict_Type, &kw, &context_str, &is_undo))
167 ot = WM_operatortype_find(opname, true);
170 PyErr_Format(PyExc_AttributeError,
171 "Calling operator \"bpy.ops.%s\" error, "
172 "could not be found", opname);
176 if (!pyrna_write_check()) {
177 PyErr_Format(PyExc_RuntimeError,
178 "Calling operator \"bpy.ops.%s\" error, "
179 "can't modify blend data in this state (drawing/rendering)",
185 if (RNA_enum_value_from_id(operator_context_items, context_str, &context) == 0) {
186 char *enum_str = BPy_enum_as_string(operator_context_items);
187 PyErr_Format(PyExc_TypeError,
188 "Calling operator \"bpy.ops.%s\" error, "
189 "expected a string enum in (%.200s)",
196 if (context_dict == NULL || context_dict == Py_None) {
199 else if (!PyDict_Check(context_dict)) {
200 PyErr_Format(PyExc_TypeError,
201 "Calling operator \"bpy.ops.%s\" error, "
202 "custom context expected a dict or None, got a %.200s",
203 opname, Py_TYPE(context_dict)->tp_name);
207 context_dict_back = CTX_py_dict_get(C);
209 CTX_py_dict_set(C, (void *)context_dict);
210 Py_XINCREF(context_dict); /* so we done loose it */
212 if (WM_operator_poll_context((bContext *)C, ot, context) == false) {
213 const char *msg = CTX_wm_operator_poll_msg_get(C);
214 PyErr_Format(PyExc_RuntimeError,
215 "Operator bpy.ops.%.200s.poll() %.200s",
216 opname, msg ? msg : "failed, context is incorrect");
217 CTX_wm_operator_poll_msg_set(C, NULL); /* better set to NULL else it could be used again */
221 WM_operator_properties_create_ptr(&ptr, ot);
222 WM_operator_properties_sanitize(&ptr, 0);
224 if (kw && PyDict_Size(kw))
225 error_val = pyrna_pydict_to_props(&ptr, kw, 0, "Converting py args to operator properties: ");
228 if (error_val == 0) {
231 reports = MEM_mallocN(sizeof(ReportList), "wmOperatorReportList");
232 BKE_reports_init(reports, RPT_STORE | RPT_OP_HOLD); /* own so these don't move into global reports */
234 #ifdef BPY_RELEASE_GIL
235 /* release GIL, since a thread could be started from an operator
236 * that updates a driver */
237 /* note: I have not seen any examples of code that does this
238 * so it may not be officially supported but seems to work ok. */
240 PyThreadState *ts = PyEval_SaveThread();
243 operator_ret = WM_operator_call_py(C, ot, context, &ptr, reports, is_undo);
245 #ifdef BPY_RELEASE_GIL
247 PyEval_RestoreThread(ts);
251 error_val = BPy_reports_to_error(reports, PyExc_RuntimeError, false);
253 /* operator output is nice to have in the terminal/console too */
254 if (reports->list.first) {
255 char *report_str = BKE_reports_string(reports, 0); /* all reports */
258 PySys_WriteStdout("%s\n", report_str);
259 MEM_freeN(report_str);
263 BKE_reports_clear(reports);
264 if ((reports->flag & RPT_FREE) == 0) {
269 WM_operator_properties_free(&ptr);
272 /* if there is some way to know an operator takes args we should use this */
276 PyErr_Format(PyExc_AttributeError,
277 "Operator \"%s\" does not take any args",
282 WM_operator_name_call(C, opname, WM_OP_EXEC_DEFAULT, NULL);
287 /* restore with original context dict, probably NULL but need this for nested operator calls */
288 Py_XDECREF(context_dict);
289 CTX_py_dict_set(C, (void *)context_dict_back);
291 if (error_val == -1) {
295 /* when calling bpy.ops.wm.read_factory_settings() bpy.data's main pointer is freed by clear_globals(),
296 * further access will crash blender. setting context is not needed in this case, only calling because this
297 * function corrects bpy.data (internal Main pointer) */
298 BPY_modules_update(C);
300 /* needed for when WM_OT_read_factory_settings us called from within a script */
301 bpy_import_main_set(CTX_data_main(C));
303 /* return operator_ret as a bpy enum */
304 return pyrna_enum_bitfield_to_py(operator_return_items, operator_ret);
308 static PyObject *pyop_as_string(PyObject *UNUSED(self), PyObject *args)
314 PyObject *kw = NULL; /* optional args */
322 bContext *C = (bContext *)BPy_GetContext();
325 PyErr_SetString(PyExc_RuntimeError, "Context is None, cant get the string representation of this object.");
329 if (!PyArg_ParseTuple(args, "s|O!ii:_bpy.ops.as_string", &opname, &PyDict_Type, &kw, &all_args, ¯o_args))
332 ot = WM_operatortype_find(opname, true);
335 PyErr_Format(PyExc_AttributeError,
336 "_bpy.ops.as_string: operator \"%.200s\" "
337 "could not be found", opname);
341 /* WM_operator_properties_create(&ptr, opname); */
342 /* Save another lookup */
343 RNA_pointer_create(NULL, ot->srna, NULL, &ptr);
345 if (kw && PyDict_Size(kw))
346 error_val = pyrna_pydict_to_props(&ptr, kw, 0, "Converting py args to operator properties: ");
349 buf = WM_operator_pystring_ex(C, NULL, all_args, macro_args, ot, &ptr);
351 WM_operator_properties_free(&ptr);
353 if (error_val == -1) {
358 pybuf = PyUnicode_FromString(buf);
362 pybuf = PyUnicode_FromString("");
368 static PyObject *pyop_dir(PyObject *UNUSED(self))
370 GHashIterator *iter = WM_operatortype_iter();
371 PyObject *list = PyList_New(0), *name;
373 for ( ; !BLI_ghashIterator_done(iter); BLI_ghashIterator_step(iter)) {
374 wmOperatorType *ot = BLI_ghashIterator_getValue(iter);
376 name = PyUnicode_FromString(ot->idname);
377 PyList_Append(list, name);
380 BLI_ghashIterator_free(iter);
385 static PyObject *pyop_getrna(PyObject *UNUSED(self), PyObject *value)
389 const char *opname = _PyUnicode_AsString(value);
390 BPy_StructRNA *pyrna = NULL;
392 if (opname == NULL) {
393 PyErr_SetString(PyExc_TypeError, "_bpy.ops.get_rna() expects a string argument");
396 ot = WM_operatortype_find(opname, true);
398 PyErr_Format(PyExc_KeyError, "_bpy.ops.get_rna(\"%s\") not found", opname);
403 //RNA_pointer_create(NULL, &RNA_Struct, ot->srna, &ptr);
405 /* XXX - should call WM_operator_properties_free */
406 WM_operator_properties_create_ptr(&ptr, ot);
407 WM_operator_properties_sanitize(&ptr, 0);
410 pyrna = (BPy_StructRNA *)pyrna_struct_CreatePyObject(&ptr);
411 #ifdef PYRNA_FREE_SUPPORT
412 pyrna->freeptr = true;
414 return (PyObject *)pyrna;
417 static PyObject *pyop_getinstance(PyObject *UNUSED(self), PyObject *value)
422 const char *opname = _PyUnicode_AsString(value);
423 BPy_StructRNA *pyrna = NULL;
425 if (opname == NULL) {
426 PyErr_SetString(PyExc_TypeError, "_bpy.ops.get_instance() expects a string argument");
429 ot = WM_operatortype_find(opname, true);
431 PyErr_Format(PyExc_KeyError, "_bpy.ops.get_instance(\"%s\") not found", opname);
435 #ifdef PYRNA_FREE_SUPPORT
436 op = MEM_callocN(sizeof(wmOperator), __func__);
438 op = PyMem_MALLOC(sizeof(wmOperator));
439 memset(op, 0, sizeof(wmOperator));
441 BLI_strncpy(op->idname, op->idname, sizeof(op->idname)); /* in case its needed */
444 RNA_pointer_create(NULL, &RNA_Operator, op, &ptr);
446 pyrna = (BPy_StructRNA *)pyrna_struct_CreatePyObject(&ptr);
447 #ifdef PYRNA_FREE_SUPPORT
448 pyrna->freeptr = true;
450 op->ptr = &pyrna->ptr;
452 return (PyObject *)pyrna;
455 static struct PyMethodDef bpy_ops_methods[] = {
456 {"poll", (PyCFunction) pyop_poll, METH_VARARGS, NULL},
457 {"call", (PyCFunction) pyop_call, METH_VARARGS, NULL},
458 {"as_string", (PyCFunction) pyop_as_string, METH_VARARGS, NULL},
459 {"dir", (PyCFunction) pyop_dir, METH_NOARGS, NULL},
460 {"get_rna", (PyCFunction) pyop_getrna, METH_O, NULL}, /* only for introspection, leaks memory */
461 {"get_instance", (PyCFunction) pyop_getinstance, METH_O, NULL}, /* only for introspection, leaks memory */
462 {"macro_define", (PyCFunction) PYOP_wrap_macro_define, METH_VARARGS, NULL},
463 {NULL, NULL, 0, NULL}
466 static struct PyModuleDef bpy_ops_module = {
467 PyModuleDef_HEAD_INIT,
470 -1, /* multiple "initialization" just copies the module dict. */
472 NULL, NULL, NULL, NULL
475 PyObject *BPY_operator_module(void)
479 submodule = PyModule_Create(&bpy_ops_module);