Draw function for operators (just like panels), used for the redo popup, file selecto...
[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 "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 (*ui)(struct bContext *, struct PointerRNA *, struct uiLayout *);
264 //
265 //static int PYTHON_OT_ui(bContext *C, PointerRNA *, uiLayout *layout)
266 //{
267 //      PointerRNA ptr_context, ptr_layout;
268 //      RNA_pointer_create(NULL, &RNA_Context, C, &ptr_context);
269 //      RNA_pointer_create(NULL, &RNA_UILayout, layout, &ptr_layout);
270 //
271 //}
272
273 void PYTHON_OT_wrapper(wmOperatorType *ot, void *userdata)
274 {
275         PyObject *py_class = (PyObject *)userdata;
276         PyObject *item;
277
278         /* identifiers */
279         item= PyObject_GetAttrString(py_class, PYOP_ATTR_IDNAME_BL);
280         ot->idname= _PyUnicode_AsString(item);
281         Py_DECREF(item);
282
283         item= PyObject_GetAttrString(py_class, PYOP_ATTR_UINAME);
284         if (item) {
285                 ot->name= _PyUnicode_AsString(item);
286                 Py_DECREF(item);
287         }
288         else {
289                 ot->name= ot->idname;
290                 PyErr_Clear();
291         }
292
293         item= PyObject_GetAttrString(py_class, PYOP_ATTR_DESCRIPTION);
294         ot->description= (item && PyUnicode_Check(item)) ? _PyUnicode_AsString(item):"undocumented python operator";
295         Py_XDECREF(item);
296         
297         /* api callbacks, detailed checks dont on adding */ 
298         if (PyObject_HasAttrString(py_class, "invoke"))
299                 ot->invoke= PYTHON_OT_invoke;
300         //else
301         //      ot->invoke= WM_operator_props_popup; /* could have an option for standard invokes */
302
303         if (PyObject_HasAttrString(py_class, "execute"))
304                 ot->exec= PYTHON_OT_execute;
305         if (PyObject_HasAttrString(py_class, "poll"))
306                 ot->pyop_poll= PYTHON_OT_poll;
307         if (PyObject_HasAttrString(py_class, "draw"))
308                 ot->ui= PYTHON_OT_draw;
309         
310         ot->pyop_data= userdata;
311         
312         /* flags */
313         ot->flag= 0;
314
315         item= PyObject_GetAttrString(py_class, PYOP_ATTR_REGISTER);
316         if (item) {
317                 ot->flag |= PyObject_IsTrue(item)!=0 ? OPTYPE_REGISTER:0;
318                 Py_DECREF(item);
319         }
320         else {
321                 PyErr_Clear();
322         }
323         item= PyObject_GetAttrString(py_class, PYOP_ATTR_UNDO);
324         if (item) {
325                 ot->flag |= PyObject_IsTrue(item)!=0 ? OPTYPE_UNDO:0;
326                 Py_DECREF(item);
327         }
328         else {
329                 PyErr_Clear();
330         }
331
332         /* Can't use this because it returns a dict proxy
333          *
334          * item= PyObject_GetAttrString(py_class, "__dict__");
335          */
336         item= ((PyTypeObject*)py_class)->tp_dict;
337         if(item) {
338                 /* only call this so pyrna_deferred_register_props gives a useful error
339                  * WM_operatortype_append_ptr will call RNA_def_struct_identifier
340                  * later */
341                 RNA_def_struct_identifier(ot->srna, ot->idname);
342
343                 if(pyrna_deferred_register_props(ot->srna, item)!=0) {
344                         /* failed to register operator props */
345                         PyErr_Print();
346                         PyErr_Clear();
347
348                 }
349         }
350         else {
351                 PyErr_Clear();
352         }
353 }
354
355
356 /* pyOperators - Operators defined IN Python */
357 PyObject *PYOP_wrap_add(PyObject *self, PyObject *py_class)
358 {       
359         PyObject *base_class, *item;
360         wmOperatorType *ot;
361         
362         
363         char *idname= NULL;
364         char idname_bl[OP_MAX_TYPENAME]; /* converted to blender syntax */
365
366         static struct BPY_class_attr_check pyop_class_attr_values[]= {
367                 {PYOP_ATTR_IDNAME,              's', -1, OP_MAX_TYPENAME-3,     0}, /* -3 because a.b -> A_OT_b */
368                 {PYOP_ATTR_UINAME,              's', -1,-1,     BPY_CLASS_ATTR_OPTIONAL},
369                 {PYOP_ATTR_DESCRIPTION, 's', -1,-1,     BPY_CLASS_ATTR_NONE_OK},
370                 {"execute",                             'f', 2, -1, BPY_CLASS_ATTR_OPTIONAL},
371                 {"invoke",                              'f', 3, -1, BPY_CLASS_ATTR_OPTIONAL},
372                 {"poll",                                'f', 2, -1, BPY_CLASS_ATTR_OPTIONAL},
373                 {"draw",                                'f', 2, -1, BPY_CLASS_ATTR_OPTIONAL},
374                 {NULL, 0, 0, 0}
375         };
376
377         // in python would be...
378         //PyObject *optype = PyObject_GetAttrString(PyObject_GetAttrString(PyDict_GetItemString(PyEval_GetGlobals(), "bpy"), "types"), "Operator");
379
380         //PyObject bpy_mod= PyDict_GetItemString(PyEval_GetGlobals(), "bpy");
381         PyObject *bpy_mod= PyImport_ImportModuleLevel("bpy", NULL, NULL, NULL, 0);
382         base_class = PyObject_GetAttrStringArgs(bpy_mod, 2, "types", "Operator");
383         Py_DECREF(bpy_mod);
384
385         if(BPY_class_validate("Operator", py_class, base_class, pyop_class_attr_values, NULL) < 0) {
386                 return NULL; /* BPY_class_validate sets the error */
387         }
388         Py_DECREF(base_class);
389
390         /* class name is used for operator ID - this can be changed later if we want */
391         item= PyObject_GetAttrString(py_class, PYOP_ATTR_IDNAME);
392         idname =  _PyUnicode_AsString(item);
393
394
395         /* annoying conversion! */
396         WM_operator_bl_idname(idname_bl, idname);
397         Py_DECREF(item);
398
399         item= PyUnicode_FromString(idname_bl);
400         PyObject_SetAttrString(py_class, PYOP_ATTR_IDNAME_BL, item);
401         idname =  _PyUnicode_AsString(item);
402         Py_DECREF(item);
403         /* end annoying conversion! */
404
405         
406         /* remove if it already exists */
407         if ((ot=WM_operatortype_exists(idname))) {
408                 if(ot->pyop_data) {
409                         Py_XDECREF((PyObject*)ot->pyop_data);
410                 }
411                 WM_operatortype_remove(idname);
412         }
413         
414         Py_INCREF(py_class);
415         WM_operatortype_append_ptr(PYTHON_OT_wrapper, py_class);
416
417         Py_RETURN_NONE;
418 }
419
420 PyObject *PYOP_wrap_remove(PyObject *self, PyObject *value)
421 {
422         PyObject *py_class;
423         char *idname= NULL;
424         wmOperatorType *ot;
425         
426
427         if (PyUnicode_Check(value))
428                 idname = _PyUnicode_AsString(value);
429         else if (PyCFunction_Check(value)) {
430                 PyObject *cfunc_self = PyCFunction_GetSelf(value);
431                 if (cfunc_self)
432                         idname = _PyUnicode_AsString(cfunc_self);
433         }
434         
435         if (idname==NULL) {
436                 PyErr_SetString( PyExc_ValueError, "Expected the operator name as a string or the operator function");
437                 return NULL;
438         }
439
440         if (!(ot= WM_operatortype_exists(idname))) {
441                 PyErr_Format( PyExc_AttributeError, "Operator \"%s\" does not exists, cant remove", idname);
442                 return NULL;
443         }
444         
445         if (!(py_class= (PyObject *)ot->pyop_data)) {
446                 PyErr_Format( PyExc_AttributeError, "Operator \"%s\" was not created by python", idname);
447                 return NULL;
448         }
449         
450         Py_XDECREF(py_class);
451
452         WM_operatortype_remove(idname);
453
454         Py_RETURN_NONE;
455 }
456
457
458