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