ok, apparently didn't commit this either. apparently includes a merge with trunk...
[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 "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) { /* Initializing the class worked, now run its invoke function */
109                 RNA_pointer_create(NULL, &RNA_Context, C, &ptr_context);
110
111                 if (mode==PYOP_INVOKE) {
112                         item= PyObject_GetAttrString(py_class, "invoke");
113                         args = PyTuple_New(3);
114
115                         RNA_pointer_create(NULL, &RNA_Event, event, &ptr_event);
116
117                         // PyTuple_SET_ITEM "steals" object reference, it is
118                         // an object passed shouldn't be DECREF'ed
119                         PyTuple_SET_ITEM(args, 1, pyrna_struct_CreatePyObject(&ptr_context));
120                         PyTuple_SET_ITEM(args, 2, pyrna_struct_CreatePyObject(&ptr_event));
121                 }
122                 else if (mode==PYOP_EXEC) {
123                         item= PyObject_GetAttrString(py_class, "execute");
124                         args = PyTuple_New(2);
125                         
126                         PyTuple_SET_ITEM(args, 1, pyrna_struct_CreatePyObject(&ptr_context));
127                 }
128                 else if (mode==PYOP_POLL) {
129                         item= PyObject_GetAttrString(py_class, "poll");
130                         args = PyTuple_New(2);
131                         PyTuple_SET_ITEM(args, 1, pyrna_struct_CreatePyObject(&ptr_context));
132                 }
133                 PyTuple_SET_ITEM(args, 0, py_class_instance);
134
135                 ret = PyObject_Call(item, args, NULL);
136
137                 Py_DECREF(args);
138                 Py_DECREF(item);
139         }
140         else {
141                 PyErr_Print();
142                 PyErr_Clear();
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_SetString(PyExc_ValueError, "Python poll function return value ");
153                                 if(op)
154                                         BPy_errors_to_report(op->reports);
155                         }
156                         else {
157                                 ret_flag= ret==Py_True ? 1:0;
158                         }
159                         
160                 } else if (BPY_flag_from_seq(pyop_ret_flags, ret, &ret_flag) == -1) {
161                         /* the returned value could not be converted into a flag */
162                         if(op) {
163                                 fprintf(stderr, "error using return value from \"%s\"\n", op->idname); // for some reason the error raised doesnt include file:line... this helps
164                                 BPy_errors_to_report(op->reports);
165                         }
166
167                         ret_flag = OPERATOR_CANCELLED;
168                 }
169                 /* there is no need to copy the py keyword dict modified by
170                  * pyot->py_invoke(), back to the operator props since they are just
171                  * thrown away anyway
172                  *
173                  * If we ever want to do this and use the props again,
174                  * it can be done with - pyrna_pydict_to_props(op->ptr, kw, "")
175                  */
176                 
177                 Py_DECREF(ret);
178         }
179
180 #if 0 /* only for testing */
181
182         /* print operator return value */
183         if (mode != PYOP_POLL) {
184                 char flag_str[100];
185                 char class_name[100];
186                 BPY_flag_def *flag_def = pyop_ret_flags;
187
188                 strcpy(flag_str, "");
189                 
190                 while(flag_def->name) {
191                         if (ret_flag & flag_def->flag) {
192                                 if(flag_str[1])
193                                         sprintf(flag_str, "%s | %s", flag_str, flag_def->name);
194                                 else
195                                         strcpy(flag_str, flag_def->name);
196                         }
197                         flag_def++;
198                 }
199
200                 /* get class name */
201                 item= PyObject_GetAttrString(py_class, PYOP_ATTR_IDNAME);
202                 strcpy(class_name, _PyUnicode_AsString(item));
203                 Py_DECREF(item);
204
205                 fprintf(stderr, "%s's %s returned %s\n", class_name, mode == PYOP_EXEC ? "execute" : "invoke", flag_str);
206         }
207 #endif
208
209         bpy_context_clear(C, &gilstate);
210
211         return ret_flag;
212 }
213
214 static int PYTHON_OT_invoke(bContext *C, wmOperator *op, wmEvent *event)
215 {
216         return PYTHON_OT_generic(PYOP_INVOKE, C, op->type, op, event);  
217 }
218
219 static int PYTHON_OT_execute(bContext *C, wmOperator *op)
220 {
221         return PYTHON_OT_generic(PYOP_EXEC, C, op->type, op, NULL);
222 }
223
224 static int PYTHON_OT_poll(bContext *C, wmOperatorType *ot)
225 {
226         return PYTHON_OT_generic(PYOP_POLL, C, ot, NULL, NULL);
227 }
228
229 void PYTHON_OT_wrapper(wmOperatorType *ot, void *userdata)
230 {
231         PyObject *py_class = (PyObject *)userdata;
232         PyObject *item;
233
234         /* identifiers */
235         item= PyObject_GetAttrString(py_class, PYOP_ATTR_IDNAME_BL);
236         ot->idname= _PyUnicode_AsString(item);
237         Py_DECREF(item);
238
239         item= PyObject_GetAttrString(py_class, PYOP_ATTR_UINAME);
240         if (item) {
241                 ot->name= _PyUnicode_AsString(item);
242                 Py_DECREF(item);
243         }
244         else {
245                 ot->name= ot->idname;
246                 PyErr_Clear();
247         }
248
249         item= PyObject_GetAttrString(py_class, PYOP_ATTR_DESCRIPTION);
250         ot->description= (item && PyUnicode_Check(item)) ? _PyUnicode_AsString(item):"undocumented python operator";
251         Py_XDECREF(item);
252         
253         /* api callbacks, detailed checks dont on adding */ 
254         if (PyObject_HasAttrString(py_class, "invoke"))
255                 ot->invoke= PYTHON_OT_invoke;
256         //else
257         //      ot->invoke= WM_operator_props_popup; /* could have an option for standard invokes */
258
259         if (PyObject_HasAttrString(py_class, "execute"))
260                 ot->exec= PYTHON_OT_execute;
261         if (PyObject_HasAttrString(py_class, "poll"))
262                 ot->pyop_poll= PYTHON_OT_poll;
263         
264         ot->pyop_data= userdata;
265         
266         /* flags */
267         ot->flag= 0;
268
269         item= PyObject_GetAttrString(py_class, PYOP_ATTR_REGISTER);
270         if (item) {
271                 ot->flag |= PyObject_IsTrue(item)!=0 ? OPTYPE_REGISTER:0;
272                 Py_DECREF(item);
273         }
274         else {
275                 PyErr_Clear();
276         }
277         item= PyObject_GetAttrString(py_class, PYOP_ATTR_UNDO);
278         if (item) {
279                 ot->flag |= PyObject_IsTrue(item)!=0 ? OPTYPE_UNDO:0;
280                 Py_DECREF(item);
281         }
282         else {
283                 PyErr_Clear();
284         }
285
286         /* Can't use this because it returns a dict proxy
287          *
288          * item= PyObject_GetAttrString(py_class, "__dict__");
289          */
290         item= ((PyTypeObject*)py_class)->tp_dict;
291         if(item) {
292                 /* only call this so pyrna_deferred_register_props gives a useful error
293                  * WM_operatortype_append_ptr will call RNA_def_struct_identifier
294                  * later */
295                 RNA_def_struct_identifier(ot->srna, ot->idname);
296
297                 if(pyrna_deferred_register_props(ot->srna, item)!=0) {
298                         /* failed to register operator props */
299                         PyErr_Print();
300                         PyErr_Clear();
301
302                 }
303         }
304         else {
305                 PyErr_Clear();
306         }
307 }
308
309
310 /* pyOperators - Operators defined IN Python */
311 PyObject *PYOP_wrap_add(PyObject *self, PyObject *py_class)
312 {       
313         PyObject *base_class, *item;
314         wmOperatorType *ot;
315         
316         
317         char *idname= NULL;
318         char idname_bl[OP_MAX_TYPENAME]; /* converted to blender syntax */
319
320         static struct BPY_class_attr_check pyop_class_attr_values[]= {
321                 {PYOP_ATTR_IDNAME,              's', -1, OP_MAX_TYPENAME-3,     0}, /* -3 because a.b -> A_OT_b */
322                 {PYOP_ATTR_UINAME,              's', -1,-1,     BPY_CLASS_ATTR_OPTIONAL},
323                 {PYOP_ATTR_DESCRIPTION, 's', -1,-1,     BPY_CLASS_ATTR_NONE_OK},
324                 {"execute",                             'f', 2, -1, BPY_CLASS_ATTR_OPTIONAL},
325                 {"invoke",                              'f', 3, -1, BPY_CLASS_ATTR_OPTIONAL},
326                 {"poll",                                'f', 2, -1, BPY_CLASS_ATTR_OPTIONAL},
327                 {NULL, 0, 0, 0}
328         };
329
330         // in python would be...
331         //PyObject *optype = PyObject_GetAttrString(PyObject_GetAttrString(PyDict_GetItemString(PyEval_GetGlobals(), "bpy"), "types"), "Operator");
332
333         //PyObject bpy_mod= PyDict_GetItemString(PyEval_GetGlobals(), "bpy");
334         PyObject *bpy_mod= PyImport_ImportModuleLevel("bpy", NULL, NULL, NULL, 0);
335         base_class = PyObject_GetAttrStringArgs(bpy_mod, 2, "types", "Operator");
336         Py_DECREF(bpy_mod);
337
338         if(BPY_class_validate("Operator", py_class, base_class, pyop_class_attr_values, NULL) < 0) {
339                 return NULL; /* BPY_class_validate sets the error */
340         }
341         Py_DECREF(base_class);
342
343         /* class name is used for operator ID - this can be changed later if we want */
344         item= PyObject_GetAttrString(py_class, PYOP_ATTR_IDNAME);
345         idname =  _PyUnicode_AsString(item);
346
347
348         /* annoying conversion! */
349         WM_operator_bl_idname(idname_bl, idname);
350         Py_DECREF(item);
351
352         item= PyUnicode_FromString(idname_bl);
353         PyObject_SetAttrString(py_class, PYOP_ATTR_IDNAME_BL, item);
354         idname =  _PyUnicode_AsString(item);
355         Py_DECREF(item);
356         /* end annoying conversion! */
357
358         
359         /* remove if it already exists */
360         if ((ot=WM_operatortype_exists(idname))) {
361                 if(ot->pyop_data) {
362                         Py_XDECREF((PyObject*)ot->pyop_data);
363                 }
364                 WM_operatortype_remove(idname);
365         }
366         
367         Py_INCREF(py_class);
368         WM_operatortype_append_ptr(PYTHON_OT_wrapper, py_class);
369
370         Py_RETURN_NONE;
371 }
372
373 PyObject *PYOP_wrap_remove(PyObject *self, PyObject *value)
374 {
375         PyObject *py_class;
376         char *idname= NULL;
377         wmOperatorType *ot;
378         
379
380         if (PyUnicode_Check(value))
381                 idname = _PyUnicode_AsString(value);
382         else if (PyCFunction_Check(value)) {
383                 PyObject *cfunc_self = PyCFunction_GetSelf(value);
384                 if (cfunc_self)
385                         idname = _PyUnicode_AsString(cfunc_self);
386         }
387         
388         if (idname==NULL) {
389                 PyErr_SetString( PyExc_ValueError, "Expected the operator name as a string or the operator function");
390                 return NULL;
391         }
392
393         if (!(ot= WM_operatortype_exists(idname))) {
394                 PyErr_Format( PyExc_AttributeError, "Operator \"%s\" does not exists, cant remove", idname);
395                 return NULL;
396         }
397         
398         if (!(py_class= (PyObject *)ot->pyop_data)) {
399                 PyErr_Format( PyExc_AttributeError, "Operator \"%s\" was not created by python", idname);
400                 return NULL;
401         }
402         
403         Py_XDECREF(py_class);
404
405         WM_operatortype_remove(idname);
406
407         Py_RETURN_NONE;
408 }
409
410
411