5 * ***** BEGIN GPL LICENSE BLOCK *****
7 * This program is free software; you can redistribute it and/or
8 * modify it under the terms of the GNU General Public License
9 * as published by the Free Software Foundation; either version 2
10 * of the License, or (at your option) any later version.
12 * This program is distributed in the hope that it will be useful,
13 * but WITHOUT ANY WARRANTY; without even the implied warranty of
14 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
15 * GNU General Public License for more details.
17 * You should have received a copy of the GNU General Public License
18 * along with this program; if not, write to the Free Software Foundation,
19 * Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
21 * Contributor(s): Campbell Barton
23 * ***** END GPL LICENSE BLOCK *****
27 #include "bpy_operator_wrap.h"
28 #include "BLI_listbase.h"
29 #include "BKE_context.h"
30 #include "BKE_report.h"
31 #include "DNA_windowmanager_types.h"
32 #include "MEM_guardedalloc.h"
35 #include "ED_screen.h"
37 #include "RNA_define.h"
40 #include "bpy_compat.h"
43 #include "../generic/bpy_internal_import.h" // our own imports
45 #define PYOP_ATTR_PROP "__props__"
46 #define PYOP_ATTR_UINAME "__label__"
47 #define PYOP_ATTR_IDNAME "__name__" /* use pythons class name */
48 #define PYOP_ATTR_DESCRIPTION "__doc__" /* use pythons docstring */
50 static PyObject *pyop_dict_from_event(wmEvent *event)
52 PyObject *dict= PyDict_New();
54 char *cstring, ascii[2];
57 item= PyUnicode_FromString(WM_key_event_string(event->type));
58 PyDict_SetItemString(dict, "type", item); Py_DECREF(item);
76 item= PyUnicode_FromString(cstring);
77 PyDict_SetItemString(dict, "val", item); Py_DECREF(item);
80 item= PyLong_FromLong(event->x);
81 PyDict_SetItemString(dict, "x", item); Py_DECREF(item);
83 item= PyLong_FromLong(event->y);
84 PyDict_SetItemString(dict, "y", item); Py_DECREF(item);
86 item= PyLong_FromLong(event->prevx);
87 PyDict_SetItemString(dict, "prevx", item); Py_DECREF(item);
89 item= PyLong_FromLong(event->prevy);
90 PyDict_SetItemString(dict, "prevy", item); Py_DECREF(item);
93 ascii[0]= event->ascii;
95 item= PyUnicode_FromString(ascii);
96 PyDict_SetItemString(dict, "ascii", item); Py_DECREF(item);
99 item= PyLong_FromLong(event->shift);
100 PyDict_SetItemString(dict, "shift", item); Py_DECREF(item);
102 item= PyLong_FromLong(event->ctrl);
103 PyDict_SetItemString(dict, "ctrl", item); Py_DECREF(item);
105 item= PyLong_FromLong(event->alt);
106 PyDict_SetItemString(dict, "alt", item); Py_DECREF(item);
108 item= PyLong_FromLong(event->oskey);
109 PyDict_SetItemString(dict, "oskey", item); Py_DECREF(item);
115 item= PyTuple_New(0);
116 if(event->keymodifier & KM_SHIFT) {
117 _PyTuple_Resize(&item, size+1);
118 PyTuple_SET_ITEM(item, size, _PyUnicode_AsString("SHIFT"));
121 if(event->keymodifier & KM_CTRL) {
122 _PyTuple_Resize(&item, size+1);
123 PyTuple_SET_ITEM(item, size, _PyUnicode_AsString("CTRL"));
126 if(event->keymodifier & KM_ALT) {
127 _PyTuple_Resize(&item, size+1);
128 PyTuple_SET_ITEM(item, size, _PyUnicode_AsString("ALT"));
131 if(event->keymodifier & KM_OSKEY) {
132 _PyTuple_Resize(&item, size+1);
133 PyTuple_SET_ITEM(item, size, _PyUnicode_AsString("OSKEY"));
136 PyDict_SetItemString(dict, "keymodifier", item); Py_DECREF(item);
142 static struct BPY_flag_def pyop_ret_flags[] = {
143 {"RUNNING_MODAL", OPERATOR_RUNNING_MODAL},
144 {"CANCELLED", OPERATOR_CANCELLED},
145 {"FINISHED", OPERATOR_FINISHED},
146 {"PASS_THROUGH", OPERATOR_PASS_THROUGH},
150 /* This invoke function can take events and
152 * It is up to the pyot->py_invoke() python func to run pyot->py_exec()
153 * the invoke function gets the keyword props as a dict, but can parse them
154 * to py_exec like this...
156 * def op_exec(x=-1, y=-1, text=""):
159 * def op_invoke(event, prop_defs):
160 * prop_defs['x'] = event['x']
162 * op_exec(**prop_defs)
164 * when there is no invoke function, C calls exec and sets the props.
165 * python class instance is stored in op->customdata so exec() can access
170 #define PYOP_INVOKE 2
173 extern void BPY_update_modules( void ); //XXX temp solution
175 static int PYTHON_OT_generic(int mode, bContext *C, wmOperator *op, wmEvent *event)
177 PyObject *py_class = op->type->pyop_data;
179 PyObject *ret= NULL, *py_class_instance, *item= NULL;
180 int ret_flag= (mode==PYOP_POLL ? 0:OPERATOR_CANCELLED);
181 PointerRNA ptr_context;
182 PointerRNA ptr_operator;
183 PyObject *py_operator;
185 PyGILState_STATE gilstate = PyGILState_Ensure();
187 bpy_import_main_set(CTX_data_main(C));
189 BPY_update_modules(); // XXX - the RNA pointers can change so update before running, would like a nicer solutuon for this.
191 args = PyTuple_New(1);
192 PyTuple_SET_ITEM(args, 0, PyObject_GetAttrString(py_class, "__rna__")); // need to use an rna instance as the first arg
193 py_class_instance = PyObject_Call(py_class, args, NULL);
196 if (py_class_instance) { /* Initializing the class worked, now run its invoke function */
199 /* Assign instance attributes from operator properties */
201 PropertyRNA *prop, *iterprop;
202 CollectionPropertyIterator iter;
203 const char *arg_name;
205 iterprop= RNA_struct_iterator_property(op->ptr->type);
206 RNA_property_collection_begin(op->ptr, iterprop, &iter);
208 for(; iter.valid; RNA_property_collection_next(&iter)) {
210 arg_name= RNA_property_identifier(prop);
212 if (strcmp(arg_name, "rna_type")==0) continue;
214 item = pyrna_prop_to_py(op->ptr, prop);
215 PyObject_SetAttrString(py_class_instance, arg_name, item);
219 RNA_property_collection_end(&iter);
222 /* set operator pointer RNA as instance "__operator__" attribute */
223 RNA_pointer_create(NULL, &RNA_Operator, op, &ptr_operator);
224 py_operator= pyrna_struct_CreatePyObject(&ptr_operator);
225 PyObject_SetAttrString(py_class_instance, "__operator__", py_operator);
226 Py_DECREF(py_operator);
228 RNA_pointer_create(NULL, &RNA_Context, C, &ptr_context);
230 if (mode==PYOP_INVOKE) {
231 item= PyObject_GetAttrString(py_class, "invoke");
232 args = PyTuple_New(3);
234 // PyTuple_SET_ITEM "steals" object reference, it is
235 // an object passed shouldn't be DECREF'ed
236 PyTuple_SET_ITEM(args, 1, pyrna_struct_CreatePyObject(&ptr_context));
237 PyTuple_SET_ITEM(args, 2, pyop_dict_from_event(event));
239 else if (mode==PYOP_EXEC) {
240 item= PyObject_GetAttrString(py_class, "execute");
241 args = PyTuple_New(2);
243 PyTuple_SET_ITEM(args, 1, pyrna_struct_CreatePyObject(&ptr_context));
245 else if (mode==PYOP_POLL) {
246 item= PyObject_GetAttrString(py_class, "poll");
247 args = PyTuple_New(2);
248 //XXX Todo - wrap context in a useful way, None for now.
249 PyTuple_SET_ITEM(args, 1, Py_None);
251 PyTuple_SET_ITEM(args, 0, py_class_instance);
253 ret = PyObject_Call(item, args, NULL);
259 if (ret == NULL) { /* covers py_class_instance failing too */
260 BPy_errors_to_report(op->reports);
263 if (mode==PYOP_POLL) {
264 if (PyBool_Check(ret) == 0) {
265 PyErr_SetString(PyExc_ValueError, "Python poll function return value ");
266 BPy_errors_to_report(op->reports);
269 ret_flag= ret==Py_True ? 1:0;
272 } else if (BPY_flag_from_seq(pyop_ret_flags, ret, &ret_flag) == -1) {
273 /* the returned value could not be converted into a flag */
274 BPy_errors_to_report(op->reports);
276 ret_flag = OPERATOR_CANCELLED;
278 /* there is no need to copy the py keyword dict modified by
279 * pyot->py_invoke(), back to the operator props since they are just
282 * If we ever want to do this and use the props again,
283 * it can be done with - pyrna_pydict_to_props(op->ptr, kw, "")
289 /* print operator return value */
290 if (mode != PYOP_POLL) {
292 char class_name[100];
293 BPY_flag_def *flag_def = pyop_ret_flags;
295 strcpy(flag_str, "");
297 while(flag_def->name) {
298 if (ret_flag & flag_def->flag) {
300 sprintf(flag_str, "%s | %s", flag_str, flag_def->name);
302 strcpy(flag_str, flag_def->name);
308 item= PyObject_GetAttrString(py_class, PYOP_ATTR_IDNAME);
310 strcpy(class_name, _PyUnicode_AsString(item));
312 fprintf(stderr, "%s's %s returned %s\n", class_name, mode == PYOP_EXEC ? "execute" : "invoke", flag_str);
315 PyGILState_Release(gilstate);
316 bpy_import_main_set(NULL);
321 static int PYTHON_OT_invoke(bContext *C, wmOperator *op, wmEvent *event)
323 return PYTHON_OT_generic(PYOP_INVOKE, C, op, event);
326 static int PYTHON_OT_exec(bContext *C, wmOperator *op)
328 return PYTHON_OT_generic(PYOP_EXEC, C, op, NULL);
331 static int PYTHON_OT_poll(bContext *C)
333 // XXX TODO - no way to get the operator type (and therefor class) from the poll function.
334 //return PYTHON_OT_generic(PYOP_POLL, C, NULL, NULL);
338 void PYTHON_OT_wrapper(wmOperatorType *ot, void *userdata)
340 PyObject *py_class = (PyObject *)userdata;
341 PyObject *props, *item;
344 item= PyObject_GetAttrString(py_class, PYOP_ATTR_IDNAME);
346 ot->idname= _PyUnicode_AsString(item);
349 item= PyObject_GetAttrString(py_class, PYOP_ATTR_UINAME);
352 ot->name= _PyUnicode_AsString(item);
355 ot->name= ot->idname;
359 item= PyObject_GetAttrString(py_class, PYOP_ATTR_DESCRIPTION);
361 ot->description= (item && PyUnicode_Check(item)) ? _PyUnicode_AsString(item):"";
363 /* api callbacks, detailed checks dont on adding */
364 if (PyObject_HasAttrString(py_class, "invoke"))
365 ot->invoke= PYTHON_OT_invoke;
366 if (PyObject_HasAttrString(py_class, "execute"))
367 ot->exec= PYTHON_OT_exec;
368 if (PyObject_HasAttrString(py_class, "poll"))
369 ot->poll= PYTHON_OT_poll;
371 ot->pyop_data= userdata;
373 props= PyObject_GetAttrString(py_class, PYOP_ATTR_PROP);
376 PyObject *dummy_args = PyTuple_New(0);
381 for(i=0; i<PyList_Size(props); i++) {
382 PyObject *py_func_ptr, *py_kw, *py_srna_cobject, *py_ret;
383 item = PyList_GET_ITEM(props, i);
385 if (PyArg_ParseTuple(item, "O!O!", &PyCObject_Type, &py_func_ptr, &PyDict_Type, &py_kw)) {
387 PyObject *(*pyfunc)(PyObject *, PyObject *, PyObject *);
388 pyfunc = PyCObject_AsVoidPtr(py_func_ptr);
389 py_srna_cobject = PyCObject_FromVoidPtr(ot->srna, NULL);
391 py_ret = pyfunc(py_srna_cobject, dummy_args, py_kw);
398 Py_DECREF(py_srna_cobject);
401 /* cant return NULL from here */ // XXX a bit ugly
406 // expect a tuple with a CObject and a dict
408 Py_DECREF(dummy_args);
415 /* pyOperators - Operators defined IN Python */
416 PyObject *PYOP_wrap_add(PyObject *self, PyObject *py_class)
418 PyObject *base_class, *item;
425 static struct BPY_class_attr_check pyop_class_attr_values[]= {
426 {PYOP_ATTR_IDNAME, 's', 0, 0},
427 {PYOP_ATTR_UINAME, 's', 0, BPY_CLASS_ATTR_OPTIONAL},
428 {PYOP_ATTR_PROP, 'l', 0, BPY_CLASS_ATTR_OPTIONAL},
429 {PYOP_ATTR_DESCRIPTION, 's', 0, BPY_CLASS_ATTR_NONE_OK},
430 {"execute", 'f', 2, BPY_CLASS_ATTR_OPTIONAL},
431 {"invoke", 'f', 3, BPY_CLASS_ATTR_OPTIONAL},
432 {"poll", 'f', 2, BPY_CLASS_ATTR_OPTIONAL},
436 // in python would be...
437 //PyObject *optype = PyObject_GetAttrString(PyObject_GetAttrString(PyDict_GetItemString(PyEval_GetGlobals(), "bpy"), "types"), "Operator");
438 base_class = PyObject_GetAttrStringArgs(PyDict_GetItemString(PyEval_GetGlobals(), "bpy"), 2, "types", "Operator");
439 Py_DECREF(base_class);
441 if(BPY_class_validate("Operator", py_class, base_class, pyop_class_attr_values, NULL) < 0) {
442 return NULL; /* BPY_class_validate sets the error */
445 /* class name is used for operator ID - this can be changed later if we want */
446 item= PyObject_GetAttrString(py_class, PYOP_ATTR_IDNAME);
448 idname = _PyUnicode_AsString(item);
450 /* remove if it already exists */
451 if ((ot=WM_operatortype_find(idname))) {
452 Py_XDECREF((PyObject*)ot->pyop_data);
453 WM_operatortype_remove(idname);
456 /* If we have properties set, check its a list of dicts */
457 item= PyObject_GetAttrString(py_class, PYOP_ATTR_PROP);
460 for(i=0; i<PyList_Size(item); i++) {
461 PyObject *py_args = PyList_GET_ITEM(item, i);
462 PyObject *py_func_ptr, *py_kw; /* place holders */
464 if (!PyArg_ParseTuple(py_args, "O!O!", &PyCObject_Type, &py_func_ptr, &PyDict_Type, &py_kw)) {
465 PyErr_Format(PyExc_ValueError, "Cant register operator class - %s.properties must contain values from FloatProperty", idname);
475 WM_operatortype_append_ptr(PYTHON_OT_wrapper, py_class);
480 PyObject *PYOP_wrap_remove(PyObject *self, PyObject *value)
487 if (PyUnicode_Check(value))
488 idname = _PyUnicode_AsString(value);
489 else if (PyCFunction_Check(value)) {
490 PyObject *cfunc_self = PyCFunction_GetSelf(value);
492 idname = _PyUnicode_AsString(cfunc_self);
496 PyErr_SetString( PyExc_ValueError, "Expected the operator name as a string or the operator function");
500 if (!(ot= WM_operatortype_find(idname))) {
501 PyErr_Format( PyExc_AttributeError, "Operator \"%s\" does not exists, cant remove", idname);
505 if (!(py_class= (PyObject *)ot->pyop_data)) {
506 PyErr_Format( PyExc_AttributeError, "Operator \"%s\" was not created by python", idname);
510 Py_XDECREF(py_class);
512 WM_operatortype_remove(idname);