a0cbc4637a44c83fef1ccbc0f95019d217b5a85b
[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_compat.h"
41 #include "bpy_util.h"
42
43 #include "../generic/bpy_internal_import.h" // our own imports
44
45 #define PYOP_ATTR_PROP                  "__props__"
46 #define PYOP_ATTR_UINAME                "__label__"
47 #define PYOP_ATTR_IDNAME                "__idname__"    /* the name given by python */
48 #define PYOP_ATTR_IDNAME_BL             "__idname_bl__" /* our own name converted into blender syntax, users wont see this */
49 #define PYOP_ATTR_DESCRIPTION   "__doc__"       /* use pythons docstring */
50 #define PYOP_ATTR_REGISTER              "__register__"  /* True/False. if this python operator should be registered */
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         
83 extern void BPY_update_modules( void ); //XXX temp solution
84
85 static int PYTHON_OT_generic(int mode, bContext *C, wmOperator *op, wmEvent *event)
86 {
87         PyObject *py_class = op->type->pyop_data;
88         PyObject *args;
89         PyObject *ret= NULL, *py_class_instance, *item= NULL;
90         int ret_flag= (mode==PYOP_POLL ? 0:OPERATOR_CANCELLED);
91         PointerRNA ptr_context;
92         PointerRNA ptr_operator;
93         PointerRNA ptr_event;
94         PyObject *py_operator;
95
96         PyGILState_STATE gilstate;
97
98         bpy_context_set(C, &gilstate);
99
100         args = PyTuple_New(1);
101         PyTuple_SET_ITEM(args, 0, PyObject_GetAttrString(py_class, "__rna__")); // need to use an rna instance as the first arg
102         py_class_instance = PyObject_Call(py_class, args, NULL);
103         Py_DECREF(args);
104         
105         if (py_class_instance) { /* Initializing the class worked, now run its invoke function */
106                 
107                 
108                 /* Assign instance attributes from operator properties */
109                 {
110                         const char *arg_name;
111
112                         RNA_STRUCT_BEGIN(op->ptr, prop) {
113                                 arg_name= RNA_property_identifier(prop);
114
115                                 if (strcmp(arg_name, "rna_type")==0) continue;
116
117                                 item = pyrna_prop_to_py(op->ptr, prop);
118                                 PyObject_SetAttrString(py_class_instance, arg_name, item);
119                                 Py_DECREF(item);
120                         }
121                         RNA_STRUCT_END;
122                 }
123
124                 /* set operator pointer RNA as instance "__operator__" attribute */
125                 RNA_pointer_create(NULL, &RNA_Operator, op, &ptr_operator);
126                 py_operator= pyrna_struct_CreatePyObject(&ptr_operator);
127                 PyObject_SetAttrString(py_class_instance, "__operator__", py_operator);
128                 Py_DECREF(py_operator);
129
130                 RNA_pointer_create(NULL, &RNA_Context, C, &ptr_context);
131                 
132                 if (mode==PYOP_INVOKE) {
133                         item= PyObject_GetAttrString(py_class, "invoke");
134                         args = PyTuple_New(3);
135                         
136                         RNA_pointer_create(NULL, &RNA_Event, event, &ptr_event);
137
138                         // PyTuple_SET_ITEM "steals" object reference, it is
139                         // an object passed shouldn't be DECREF'ed
140                         PyTuple_SET_ITEM(args, 1, pyrna_struct_CreatePyObject(&ptr_context));
141                         PyTuple_SET_ITEM(args, 2, pyrna_struct_CreatePyObject(&ptr_event));
142                 }
143                 else if (mode==PYOP_EXEC) {
144                         item= PyObject_GetAttrString(py_class, "execute");
145                         args = PyTuple_New(2);
146                         
147                         PyTuple_SET_ITEM(args, 1, pyrna_struct_CreatePyObject(&ptr_context));
148                 }
149                 else if (mode==PYOP_POLL) {
150                         item= PyObject_GetAttrString(py_class, "poll");
151                         args = PyTuple_New(2);
152                         //XXX  Todo - wrap context in a useful way, None for now.
153                         PyTuple_SET_ITEM(args, 1, Py_None);
154                 }
155                 PyTuple_SET_ITEM(args, 0, py_class_instance);
156         
157                 ret = PyObject_Call(item, args, NULL);
158                 
159                 Py_DECREF(args);
160                 Py_DECREF(item);
161         }
162         
163         if (ret == NULL) { /* covers py_class_instance failing too */
164                 BPy_errors_to_report(op->reports);
165         }
166         else {
167                 if (mode==PYOP_POLL) {
168                         if (PyBool_Check(ret) == 0) {
169                                 PyErr_SetString(PyExc_ValueError, "Python poll function return value ");
170                                 BPy_errors_to_report(op->reports);
171                         }
172                         else {
173                                 ret_flag= ret==Py_True ? 1:0;
174                         }
175                         
176                 } else if (BPY_flag_from_seq(pyop_ret_flags, ret, &ret_flag) == -1) {
177                          /* the returned value could not be converted into a flag */
178                         BPy_errors_to_report(op->reports);
179
180                         ret_flag = OPERATOR_CANCELLED;
181                 }
182                 /* there is no need to copy the py keyword dict modified by
183                  * pyot->py_invoke(), back to the operator props since they are just
184                  * thrown away anyway
185                  *
186                  * If we ever want to do this and use the props again,
187                  * it can be done with - pyrna_pydict_to_props(op->ptr, kw, "")
188                  */
189                 
190                 Py_DECREF(ret);
191         }
192
193 #if 0 /* only for testing */
194
195         /* print operator return value */
196         if (mode != PYOP_POLL) {
197                 char flag_str[100];
198                 char class_name[100];
199                 BPY_flag_def *flag_def = pyop_ret_flags;
200
201                 strcpy(flag_str, "");
202                 
203                 while(flag_def->name) {
204                         if (ret_flag & flag_def->flag) {
205                                 if(flag_str[1])
206                                         sprintf(flag_str, "%s | %s", flag_str, flag_def->name);
207                                 else
208                                         strcpy(flag_str, flag_def->name);
209                         }
210                         flag_def++;
211                 }
212
213                 /* get class name */
214                 item= PyObject_GetAttrString(py_class, PYOP_ATTR_IDNAME);
215                 strcpy(class_name, _PyUnicode_AsString(item));
216                 Py_DECREF(item);
217
218                 fprintf(stderr, "%s's %s returned %s\n", class_name, mode == PYOP_EXEC ? "execute" : "invoke", flag_str);
219         }
220 #endif
221
222         bpy_context_clear(C, &gilstate);
223
224         return ret_flag;
225 }
226
227 static int PYTHON_OT_invoke(bContext *C, wmOperator *op, wmEvent *event)
228 {
229         return PYTHON_OT_generic(PYOP_INVOKE, C, op, event);    
230 }
231
232 static int PYTHON_OT_exec(bContext *C, wmOperator *op)
233 {
234         return PYTHON_OT_generic(PYOP_EXEC, C, op, NULL);
235 }
236
237 static int PYTHON_OT_poll(bContext *C)
238 {
239         // XXX TODO - no way to get the operator type (and therefor class) from the poll function.
240         //return PYTHON_OT_generic(PYOP_POLL, C, NULL, NULL);
241         return 1;
242 }
243
244 void PYTHON_OT_wrapper(wmOperatorType *ot, void *userdata)
245 {
246         PyObject *py_class = (PyObject *)userdata;
247         PyObject *props, *item;
248
249         /* identifiers */
250         item= PyObject_GetAttrString(py_class, PYOP_ATTR_IDNAME_BL);
251         ot->idname= _PyUnicode_AsString(item);
252         Py_DECREF(item);
253
254         item= PyObject_GetAttrString(py_class, PYOP_ATTR_UINAME);
255         if (item) {
256                 ot->name= _PyUnicode_AsString(item);
257                 Py_DECREF(item);
258         }
259         else {
260                 ot->name= ot->idname;
261                 PyErr_Clear();
262         }
263
264         item= PyObject_GetAttrString(py_class, PYOP_ATTR_DESCRIPTION);
265         ot->description= (item && PyUnicode_Check(item)) ? _PyUnicode_AsString(item):"undocumented python operator";
266         Py_XDECREF(item);
267         
268         /* api callbacks, detailed checks dont on adding */ 
269         if (PyObject_HasAttrString(py_class, "invoke"))
270                 ot->invoke= PYTHON_OT_invoke;
271         if (PyObject_HasAttrString(py_class, "execute"))
272                 ot->exec= PYTHON_OT_exec;
273         if (PyObject_HasAttrString(py_class, "poll"))
274                 ot->poll= PYTHON_OT_poll;
275         
276         ot->pyop_data= userdata;
277         
278         /* flags */
279         item= PyObject_GetAttrString(py_class, PYOP_ATTR_REGISTER);
280         if (item) {
281                 ot->flag= PyObject_IsTrue(item)!=0 ? OPTYPE_REGISTER:0;
282                 Py_DECREF(item);
283         }
284         else {
285                 ot->flag= OPTYPE_REGISTER; /* unspesified, leave on for now to help debug */
286                 PyErr_Clear();
287         }
288         
289         props= PyObject_GetAttrString(py_class, PYOP_ATTR_PROP);
290         
291         if (props) {
292                 PyObject *dummy_args = PyTuple_New(0);
293                 int i;
294
295                 for(i=0; i<PyList_Size(props); i++) {
296                         PyObject *py_func_ptr, *py_kw, *py_srna_cobject, *py_ret;
297                         item = PyList_GET_ITEM(props, i);
298                         
299                         if (PyArg_ParseTuple(item, "O!O!:PYTHON_OT_wrapper", &PyCObject_Type, &py_func_ptr, &PyDict_Type, &py_kw)) {
300                                 
301                                 PyObject *(*pyfunc)(PyObject *, PyObject *, PyObject *);
302                                 pyfunc = PyCObject_AsVoidPtr(py_func_ptr);
303                                 py_srna_cobject = PyCObject_FromVoidPtr(ot->srna, NULL);
304                                 
305                                 py_ret = pyfunc(py_srna_cobject, dummy_args, py_kw);
306                                 if (py_ret) {
307                                         Py_DECREF(py_ret);
308                                 } else {
309                                         fprintf(stderr, "BPy Operator \"%s\" registration error: %s item %d could not run\n", ot->idname, PYOP_ATTR_PROP, i);
310                                         PyLineSpit();
311                                         PyErr_Print();
312                                         PyErr_Clear();
313                                 }
314                                 Py_DECREF(py_srna_cobject);
315                                 
316                         } else {
317                                 /* cant return NULL from here */ // XXX a bit ugly
318                                 PyErr_Print();
319                                 PyErr_Clear();
320                         }
321                         
322                         // expect a tuple with a CObject and a dict
323                 }
324                 Py_DECREF(dummy_args);
325                 Py_DECREF(props);
326         } else {
327                 PyErr_Clear();
328         }
329 }
330
331
332 /* pyOperators - Operators defined IN Python */
333 PyObject *PYOP_wrap_add(PyObject *self, PyObject *py_class)
334 {       
335         PyObject *base_class, *item;
336         wmOperatorType *ot;
337         
338         
339         char *idname= NULL;
340         char idname_bl[OP_MAX_TYPENAME]; /* converted to blender syntax */
341         int i;
342
343         static struct BPY_class_attr_check pyop_class_attr_values[]= {
344                 {PYOP_ATTR_IDNAME,              's', -1, OP_MAX_TYPENAME-3,     0}, /* -3 because a.b -> A_OT_b */
345                 {PYOP_ATTR_UINAME,              's', -1,-1,     BPY_CLASS_ATTR_OPTIONAL},
346                 {PYOP_ATTR_PROP,                'l', -1,-1,     BPY_CLASS_ATTR_OPTIONAL},
347                 {PYOP_ATTR_DESCRIPTION, 's', -1,-1,     BPY_CLASS_ATTR_NONE_OK},
348                 {"execute",                             'f', 2, -1, BPY_CLASS_ATTR_OPTIONAL},
349                 {"invoke",                              'f', 3, -1, BPY_CLASS_ATTR_OPTIONAL},
350                 {"poll",                                'f', 2, -1, BPY_CLASS_ATTR_OPTIONAL},
351                 {NULL, 0, 0, 0}
352         };
353
354         // in python would be...
355         //PyObject *optype = PyObject_GetAttrString(PyObject_GetAttrString(PyDict_GetItemString(PyEval_GetGlobals(), "bpy"), "types"), "Operator");
356         base_class = PyObject_GetAttrStringArgs(PyDict_GetItemString(PyEval_GetGlobals(), "bpy"), 2, "types", "Operator");
357
358         if(BPY_class_validate("Operator", py_class, base_class, pyop_class_attr_values, NULL) < 0) {
359                 return NULL; /* BPY_class_validate sets the error */
360         }
361         Py_DECREF(base_class);
362
363         /* class name is used for operator ID - this can be changed later if we want */
364         item= PyObject_GetAttrString(py_class, PYOP_ATTR_IDNAME);
365         idname =  _PyUnicode_AsString(item);
366
367
368         /* annoying conversion! */
369         WM_operator_bl_idname(idname_bl, idname);
370         Py_DECREF(item);
371
372         item= PyUnicode_FromString(idname_bl);
373         PyObject_SetAttrString(py_class, PYOP_ATTR_IDNAME_BL, item);
374         idname =  _PyUnicode_AsString(item);
375         Py_DECREF(item);
376         /* end annoying conversion! */
377
378         
379         /* remove if it already exists */
380         if ((ot=WM_operatortype_exists(idname))) {
381                 if(ot->pyop_data) {
382                         Py_XDECREF((PyObject*)ot->pyop_data);
383                 }
384                 WM_operatortype_remove(idname);
385         }
386         
387         /* If we have properties set, check its a list of dicts */
388         item= PyObject_GetAttrString(py_class, PYOP_ATTR_PROP);
389         if (item) {
390                 for(i=0; i<PyList_Size(item); i++) {
391                         PyObject *py_args = PyList_GET_ITEM(item, i);
392                         PyObject *py_func_ptr, *py_kw; /* place holders */
393                         
394                         if (!PyArg_ParseTuple(py_args, "O!O!", &PyCObject_Type, &py_func_ptr, &PyDict_Type, &py_kw)) {
395                                 PyErr_Format(PyExc_ValueError, "Cant register operator class - %s.properties must contain values from FloatProperty", idname);
396                                 return NULL;                            
397                         }
398                 }
399                 Py_DECREF(item);
400         }
401         else {
402                 PyErr_Clear();
403         }
404         
405         Py_INCREF(py_class);
406         WM_operatortype_append_ptr(PYTHON_OT_wrapper, py_class);
407
408         Py_RETURN_NONE;
409 }
410
411 PyObject *PYOP_wrap_remove(PyObject *self, PyObject *value)
412 {
413         PyObject *py_class;
414         char *idname= NULL;
415         wmOperatorType *ot;
416         
417
418         if (PyUnicode_Check(value))
419                 idname = _PyUnicode_AsString(value);
420         else if (PyCFunction_Check(value)) {
421                 PyObject *cfunc_self = PyCFunction_GetSelf(value);
422                 if (cfunc_self)
423                         idname = _PyUnicode_AsString(cfunc_self);
424         }
425         
426         if (idname==NULL) {
427                 PyErr_SetString( PyExc_ValueError, "Expected the operator name as a string or the operator function");
428                 return NULL;
429         }
430
431         if (!(ot= WM_operatortype_exists(idname))) {
432                 PyErr_Format( PyExc_AttributeError, "Operator \"%s\" does not exists, cant remove", idname);
433                 return NULL;
434         }
435         
436         if (!(py_class= (PyObject *)ot->pyop_data)) {
437                 PyErr_Format( PyExc_AttributeError, "Operator \"%s\" was not created by python", idname);
438                 return NULL;
439         }
440         
441         Py_XDECREF(py_class);
442
443         WM_operatortype_remove(idname);
444
445         Py_RETURN_NONE;
446 }
447
448
449