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