Merge from trunk -r 24758:25003.
[blender.git] / source / blender / python / intern / bpy_operator_wrap.c
1
2 /**
3  * $Id$
4  *
5  * ***** BEGIN GPL LICENSE BLOCK *****
6  *
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.
11  *
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.
16  *
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.
20  *
21  * Contributor(s): Campbell Barton
22  *
23  * ***** END GPL LICENSE BLOCK *****
24  */
25
26
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"
33 #include "WM_api.h"
34 #include "WM_types.h"
35 #include "UI_interface.h"
36 #include "ED_screen.h"
37
38 #include "RNA_define.h"
39
40 #include "bpy_rna.h"
41 #include "bpy_util.h"
42
43 #include "../generic/bpy_internal_import.h" // our own imports
44
45 #define PYOP_ATTR_UINAME                "bl_label"
46 #define PYOP_ATTR_IDNAME                "bl_idname"             /* the name given by python */
47 #define PYOP_ATTR_IDNAME_BL     "_bl_idname"    /* our own name converted into blender syntax, users wont see this */
48 #define PYOP_ATTR_DESCRIPTION   "__doc__"               /* use pythons docstring */
49 #define PYOP_ATTR_REGISTER              "bl_register"   /* True/False. if this python operator should be registered */
50 #define PYOP_ATTR_UNDO                  "bl_undo"               /* True/False. if this python operator should be undone */
51
52 static struct BPY_flag_def pyop_ret_flags[] = {
53         {"RUNNING_MODAL", OPERATOR_RUNNING_MODAL},
54         {"CANCELLED", OPERATOR_CANCELLED},
55         {"FINISHED", OPERATOR_FINISHED},
56         {"PASS_THROUGH", OPERATOR_PASS_THROUGH},
57         {NULL, 0}
58 };
59
60 /* This invoke function can take events and
61  *
62  * It is up to the pyot->py_invoke() python func to run pyot->py_exec()
63  * the invoke function gets the keyword props as a dict, but can parse them
64  * to py_exec like this...
65  *
66  * def op_exec(x=-1, y=-1, text=""):
67  *     ...
68  *
69  * def op_invoke(event, prop_defs):
70  *     prop_defs['x'] = event['x']
71  *     ...
72  *     op_exec(**prop_defs)
73  *
74  * when there is no invoke function, C calls exec and sets the props.
75  * python class instance is stored in op->customdata so exec() can access
76  */
77
78
79 #define PYOP_EXEC 1
80 #define PYOP_INVOKE 2
81 #define PYOP_POLL 3
82 #define PYOP_DRAW 4
83         
84 extern void BPY_update_modules( void ); //XXX temp solution
85
86 static int PYTHON_OT_generic(int mode, bContext *C, wmOperatorType *ot, wmOperator *op, wmEvent *event, uiLayout *layout)
87 {
88         PyObject *py_class = ot->pyop_data;
89         PyObject *args;
90         PyObject *ret= NULL, *py_class_instance, *item= NULL;
91         int ret_flag= (mode==PYOP_POLL ? 0:OPERATOR_CANCELLED);
92         PointerRNA ptr_context;
93         PointerRNA ptr_operator;
94
95         PyGILState_STATE gilstate;
96
97         bpy_context_set(C, &gilstate);
98
99         args = PyTuple_New(1);
100
101         /* poll has no 'op', should be ok still */
102         /* use an rna instance as the first arg */
103         RNA_pointer_create(NULL, &RNA_Operator, op, &ptr_operator);
104         PyTuple_SET_ITEM(args, 0, pyrna_struct_CreatePyObject(&ptr_operator));
105
106         py_class_instance = PyObject_Call(py_class, args, NULL);
107         Py_DECREF(args);
108         
109         if (py_class_instance==NULL) { /* Initializing the class worked, now run its invoke function */
110                 PyErr_Print();
111                 PyErr_Clear();
112         }
113         else {
114                 RNA_pointer_create(NULL, &RNA_Context, C, &ptr_context);
115
116                 if (mode==PYOP_INVOKE) {
117                         PointerRNA ptr_event;
118                         item= PyObject_GetAttrString(py_class, "invoke");
119                         args = PyTuple_New(3);
120
121                         RNA_pointer_create(NULL, &RNA_Event, event, &ptr_event);
122
123                         // PyTuple_SET_ITEM "steals" object reference, it is
124                         // an object passed shouldn't be DECREF'ed
125                         PyTuple_SET_ITEM(args, 1, pyrna_struct_CreatePyObject(&ptr_context));
126                         PyTuple_SET_ITEM(args, 2, pyrna_struct_CreatePyObject(&ptr_event));
127                 }
128                 else if (mode==PYOP_EXEC) {
129                         item= PyObject_GetAttrString(py_class, "execute");
130                         args = PyTuple_New(2);
131                         
132                         PyTuple_SET_ITEM(args, 1, pyrna_struct_CreatePyObject(&ptr_context));
133                 }
134                 else if (mode==PYOP_POLL) {
135                         item= PyObject_GetAttrString(py_class, "poll");
136                         args = PyTuple_New(2);
137                         PyTuple_SET_ITEM(args, 1, pyrna_struct_CreatePyObject(&ptr_context));
138                 }
139                 else if (mode==PYOP_DRAW) {
140                         PointerRNA ptr_layout;
141                         item= PyObject_GetAttrString(py_class, "draw");
142                         args = PyTuple_New(2);
143
144                         RNA_pointer_create(NULL, &RNA_UILayout, layout, &ptr_layout);
145
146                         // PyTuple_SET_ITEM "steals" object reference, it is
147                         // an object passed shouldn't be DECREF'ed
148                         PyTuple_SET_ITEM(args, 1, pyrna_struct_CreatePyObject(&ptr_context));
149 #if 0
150                         PyTuple_SET_ITEM(args, 2, pyrna_struct_CreatePyObject(&ptr_layout));
151 #else
152                         {
153                                 /* mimic panels */
154                                 PyObject *py_layout= pyrna_struct_CreatePyObject(&ptr_layout);
155                                 PyObject *pyname= PyUnicode_FromString("layout");
156
157                                 if(PyObject_GenericSetAttr(py_class_instance, pyname, py_layout)) {
158                                         PyErr_Print();
159                                         PyErr_Clear();
160                                 }
161                                 else {
162                                         Py_DECREF(py_layout);
163                                 }
164
165                                 Py_DECREF(pyname);
166                         }
167 #endif
168                 }
169                 PyTuple_SET_ITEM(args, 0, py_class_instance);
170
171                 ret = PyObject_Call(item, args, NULL);
172
173                 Py_DECREF(args);
174                 Py_DECREF(item);
175         }
176         
177         if (ret == NULL) { /* covers py_class_instance failing too */
178                 if(op)
179                         BPy_errors_to_report(op->reports);
180         }
181         else {
182                 if (mode==PYOP_POLL) {
183                         if (PyBool_Check(ret) == 0) {
184                                 PyErr_Format(PyExc_ValueError, "Python operator '%s.poll', did not return a bool value", ot->idname);
185                                 BPy_errors_to_report(op ? op->reports:NULL); /* prints and clears if NULL given */
186                         }
187                         else {
188                                 ret_flag= ret==Py_True ? 1:0;
189                         }
190                 } else if(mode==PYOP_DRAW) {
191                         /* pass */
192                 } else if (BPY_flag_from_seq(pyop_ret_flags, ret, &ret_flag) == -1) {
193                         /* the returned value could not be converted into a flag */
194                         PyErr_Format(PyExc_ValueError, "Python operator, error using return value from \"%s\"\n", ot->idname);
195                         BPy_errors_to_report(op ? op->reports:NULL);
196                         ret_flag = OPERATOR_CANCELLED;
197                 }
198                 /* there is no need to copy the py keyword dict modified by
199                  * pyot->py_invoke(), back to the operator props since they are just
200                  * thrown away anyway
201                  *
202                  * If we ever want to do this and use the props again,
203                  * it can be done with - pyrna_pydict_to_props(op->ptr, kw, "")
204                  */
205                 
206                 Py_DECREF(ret);
207         }
208
209 #if 0 /* only for testing */
210
211         /* print operator return value */
212         if (mode != PYOP_POLL) {
213                 char flag_str[100];
214                 char class_name[100];
215                 BPY_flag_def *flag_def = pyop_ret_flags;
216
217                 strcpy(flag_str, "");
218                 
219                 while(flag_def->name) {
220                         if (ret_flag & flag_def->flag) {
221                                 if(flag_str[1])
222                                         sprintf(flag_str, "%s | %s", flag_str, flag_def->name);
223                                 else
224                                         strcpy(flag_str, flag_def->name);
225                         }
226                         flag_def++;
227                 }
228
229                 /* get class name */
230                 item= PyObject_GetAttrString(py_class, PYOP_ATTR_IDNAME);
231                 strcpy(class_name, _PyUnicode_AsString(item));
232                 Py_DECREF(item);
233
234                 fprintf(stderr, "%s's %s returned %s\n", class_name, mode == PYOP_EXEC ? "execute" : "invoke", flag_str);
235         }
236 #endif
237
238         bpy_context_clear(C, &gilstate);
239
240         return ret_flag;
241 }
242
243 static int PYTHON_OT_invoke(bContext *C, wmOperator *op, wmEvent *event)
244 {
245         return PYTHON_OT_generic(PYOP_INVOKE, C, op->type, op, event, NULL);
246 }
247
248 static int PYTHON_OT_execute(bContext *C, wmOperator *op)
249 {
250         return PYTHON_OT_generic(PYOP_EXEC, C, op->type, op, NULL, NULL);
251 }
252
253 static int PYTHON_OT_poll(bContext *C, wmOperatorType *ot)
254 {
255         return PYTHON_OT_generic(PYOP_POLL, C, ot, NULL, NULL, NULL);
256 }
257
258 static void PYTHON_OT_draw(bContext *C, wmOperator *op, uiLayout *layout)
259 {
260         PYTHON_OT_generic(PYOP_DRAW, C, op->type, op, NULL, layout);
261 }
262
263 void PYTHON_OT_wrapper(wmOperatorType *ot, void *userdata)
264 {
265         PyObject *py_class = (PyObject *)userdata;
266         PyObject *item;
267
268         /* identifiers */
269         item= PyObject_GetAttrString(py_class, PYOP_ATTR_IDNAME_BL);
270         ot->idname= _PyUnicode_AsString(item);
271         Py_DECREF(item);
272
273         item= PyObject_GetAttrString(py_class, PYOP_ATTR_UINAME);
274         if (item) {
275                 ot->name= _PyUnicode_AsString(item);
276                 Py_DECREF(item);
277         }
278         else {
279                 ot->name= ot->idname;
280                 PyErr_Clear();
281         }
282
283         item= PyObject_GetAttrString(py_class, PYOP_ATTR_DESCRIPTION);
284         ot->description= (item && PyUnicode_Check(item)) ? _PyUnicode_AsString(item):"undocumented python operator";
285         Py_XDECREF(item);
286         
287         /* api callbacks, detailed checks dont on adding */ 
288         if (PyObject_HasAttrString(py_class, "invoke"))
289                 ot->invoke= PYTHON_OT_invoke;
290         //else
291         //      ot->invoke= WM_operator_props_popup; /* could have an option for standard invokes */
292
293         if (PyObject_HasAttrString(py_class, "execute"))
294                 ot->exec= PYTHON_OT_execute;
295         if (PyObject_HasAttrString(py_class, "poll"))
296                 ot->pyop_poll= PYTHON_OT_poll;
297         if (PyObject_HasAttrString(py_class, "draw"))
298                 ot->ui= PYTHON_OT_draw;
299         
300         ot->pyop_data= userdata;
301         
302         /* flags */
303         ot->flag= 0;
304
305         item= PyObject_GetAttrString(py_class, PYOP_ATTR_REGISTER);
306         if (item) {
307                 ot->flag |= PyObject_IsTrue(item)!=0 ? OPTYPE_REGISTER:0;
308                 Py_DECREF(item);
309         }
310         else {
311                 PyErr_Clear();
312         }
313         item= PyObject_GetAttrString(py_class, PYOP_ATTR_UNDO);
314         if (item) {
315                 ot->flag |= PyObject_IsTrue(item)!=0 ? OPTYPE_UNDO:0;
316                 Py_DECREF(item);
317         }
318         else {
319                 PyErr_Clear();
320         }
321
322         /* Can't use this because it returns a dict proxy
323          *
324          * item= PyObject_GetAttrString(py_class, "__dict__");
325          */
326         item= ((PyTypeObject*)py_class)->tp_dict;
327         if(item) {
328                 /* only call this so pyrna_deferred_register_props gives a useful error
329                  * WM_operatortype_append_ptr will call RNA_def_struct_identifier
330                  * later */
331                 RNA_def_struct_identifier(ot->srna, ot->idname);
332
333                 if(pyrna_deferred_register_props(ot->srna, item)!=0) {
334                         /* failed to register operator props */
335                         PyErr_Print();
336                         PyErr_Clear();
337
338                 }
339         }
340         else {
341                 PyErr_Clear();
342         }
343 }
344
345
346 /* pyOperators - Operators defined IN Python */
347 PyObject *PYOP_wrap_add(PyObject *self, PyObject *py_class)
348 {       
349         PyObject *base_class, *item;
350         wmOperatorType *ot;
351         
352         
353         char *idname= NULL;
354         char idname_bl[OP_MAX_TYPENAME]; /* converted to blender syntax */
355
356         static struct BPY_class_attr_check pyop_class_attr_values[]= {
357                 {PYOP_ATTR_IDNAME,              's', -1, OP_MAX_TYPENAME-3,     0}, /* -3 because a.b -> A_OT_b */
358                 {PYOP_ATTR_UINAME,              's', -1,-1,     BPY_CLASS_ATTR_OPTIONAL},
359                 {PYOP_ATTR_DESCRIPTION, 's', -1,-1,     BPY_CLASS_ATTR_NONE_OK},
360                 {"execute",                             'f', 2, -1, BPY_CLASS_ATTR_OPTIONAL},
361                 {"invoke",                              'f', 3, -1, BPY_CLASS_ATTR_OPTIONAL},
362                 {"poll",                                'f', 2, -1, BPY_CLASS_ATTR_OPTIONAL},
363                 {"draw",                                'f', 2, -1, BPY_CLASS_ATTR_OPTIONAL},
364                 {NULL, 0, 0, 0}
365         };
366
367         // in python would be...
368         //PyObject *optype = PyObject_GetAttrString(PyObject_GetAttrString(PyDict_GetItemString(PyEval_GetGlobals(), "bpy"), "types"), "Operator");
369
370         //PyObject bpy_mod= PyDict_GetItemString(PyEval_GetGlobals(), "bpy");
371         PyObject *bpy_mod= PyImport_ImportModuleLevel("bpy", NULL, NULL, NULL, 0);
372         base_class = PyObject_GetAttrStringArgs(bpy_mod, 2, "types", "Operator");
373         Py_DECREF(bpy_mod);
374
375         if(BPY_class_validate("Operator", py_class, base_class, pyop_class_attr_values, NULL) < 0) {
376                 return NULL; /* BPY_class_validate sets the error */
377         }
378         Py_DECREF(base_class);
379
380         /* class name is used for operator ID - this can be changed later if we want */
381         item= PyObject_GetAttrString(py_class, PYOP_ATTR_IDNAME);
382         idname =  _PyUnicode_AsString(item);
383
384
385         /* annoying conversion! */
386         WM_operator_bl_idname(idname_bl, idname);
387         Py_DECREF(item);
388
389         item= PyUnicode_FromString(idname_bl);
390         PyObject_SetAttrString(py_class, PYOP_ATTR_IDNAME_BL, item);
391         idname =  _PyUnicode_AsString(item);
392         Py_DECREF(item);
393         /* end annoying conversion! */
394
395         
396         /* remove if it already exists */
397         if ((ot=WM_operatortype_exists(idname))) {
398                 if(ot->pyop_data) {
399                         Py_XDECREF((PyObject*)ot->pyop_data);
400                 }
401                 WM_operatortype_remove(idname);
402         }
403         
404         Py_INCREF(py_class);
405         WM_operatortype_append_ptr(PYTHON_OT_wrapper, py_class);
406
407         Py_RETURN_NONE;
408 }
409
410 PyObject *PYOP_wrap_remove(PyObject *self, PyObject *value)
411 {
412         PyObject *py_class;
413         char *idname= NULL;
414         wmOperatorType *ot;
415         
416
417         if (PyUnicode_Check(value))
418                 idname = _PyUnicode_AsString(value);
419         else if (PyCFunction_Check(value)) {
420                 PyObject *cfunc_self = PyCFunction_GetSelf(value);
421                 if (cfunc_self)
422                         idname = _PyUnicode_AsString(cfunc_self);
423         }
424         
425         if (idname==NULL) {
426                 PyErr_SetString( PyExc_ValueError, "Expected the operator name as a string or the operator function");
427                 return NULL;
428         }
429
430         if (!(ot= WM_operatortype_exists(idname))) {
431                 PyErr_Format( PyExc_AttributeError, "Operator \"%s\" does not exists, cant remove", idname);
432                 return NULL;
433         }
434         
435         if (!(py_class= (PyObject *)ot->pyop_data)) {
436                 PyErr_Format( PyExc_AttributeError, "Operator \"%s\" was not created by python", idname);
437                 return NULL;
438         }
439         
440         Py_XDECREF(py_class);
441
442         WM_operatortype_remove(idname);
443
444         Py_RETURN_NONE;
445 }