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