svn merge https://svn.blender.org/svnroot/bf-blender/trunk/blender -r22205:22290
[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 = PyGILState_Ensure();
97
98         bpy_import_main_set(CTX_data_main(C));
99         
100         BPY_update_modules(); // XXX - the RNA pointers can change so update before running, would like a nicer solutuon for this.
101
102         args = PyTuple_New(1);
103         PyTuple_SET_ITEM(args, 0, PyObject_GetAttrString(py_class, "__rna__")); // need to use an rna instance as the first arg
104         py_class_instance = PyObject_Call(py_class, args, NULL);
105         Py_DECREF(args);
106         
107         if (py_class_instance) { /* Initializing the class worked, now run its invoke function */
108                 
109                 
110                 /* Assign instance attributes from operator properties */
111                 {
112                         const char *arg_name;
113
114                         RNA_STRUCT_BEGIN(op->ptr, prop) {
115                                 arg_name= RNA_property_identifier(prop);
116
117                                 if (strcmp(arg_name, "rna_type")==0) continue;
118
119                                 item = pyrna_prop_to_py(op->ptr, prop);
120                                 PyObject_SetAttrString(py_class_instance, arg_name, item);
121                                 Py_DECREF(item);
122                         }
123                         RNA_STRUCT_END;
124                 }
125
126                 /* set operator pointer RNA as instance "__operator__" attribute */
127                 RNA_pointer_create(NULL, &RNA_Operator, op, &ptr_operator);
128                 py_operator= pyrna_struct_CreatePyObject(&ptr_operator);
129                 PyObject_SetAttrString(py_class_instance, "__operator__", py_operator);
130                 Py_DECREF(py_operator);
131
132                 RNA_pointer_create(NULL, &RNA_Context, C, &ptr_context);
133                 
134                 if (mode==PYOP_INVOKE) {
135                         item= PyObject_GetAttrString(py_class, "invoke");
136                         args = PyTuple_New(3);
137                         
138                         RNA_pointer_create(NULL, &RNA_Event, event, &ptr_event);
139
140                         // PyTuple_SET_ITEM "steals" object reference, it is
141                         // an object passed shouldn't be DECREF'ed
142                         PyTuple_SET_ITEM(args, 1, pyrna_struct_CreatePyObject(&ptr_context));
143                         PyTuple_SET_ITEM(args, 2, pyrna_struct_CreatePyObject(&ptr_event));
144                 }
145                 else if (mode==PYOP_EXEC) {
146                         item= PyObject_GetAttrString(py_class, "execute");
147                         args = PyTuple_New(2);
148                         
149                         PyTuple_SET_ITEM(args, 1, pyrna_struct_CreatePyObject(&ptr_context));
150                 }
151                 else if (mode==PYOP_POLL) {
152                         item= PyObject_GetAttrString(py_class, "poll");
153                         args = PyTuple_New(2);
154                         //XXX  Todo - wrap context in a useful way, None for now.
155                         PyTuple_SET_ITEM(args, 1, Py_None);
156                 }
157                 PyTuple_SET_ITEM(args, 0, py_class_instance);
158         
159                 ret = PyObject_Call(item, args, NULL);
160                 
161                 Py_DECREF(args);
162                 Py_DECREF(item);
163         }
164         
165         if (ret == NULL) { /* covers py_class_instance failing too */
166                 BPy_errors_to_report(op->reports);
167         }
168         else {
169                 if (mode==PYOP_POLL) {
170                         if (PyBool_Check(ret) == 0) {
171                                 PyErr_SetString(PyExc_ValueError, "Python poll function return value ");
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                         BPy_errors_to_report(op->reports);
181
182                         ret_flag = OPERATOR_CANCELLED;
183                 }
184                 /* there is no need to copy the py keyword dict modified by
185                  * pyot->py_invoke(), back to the operator props since they are just
186                  * thrown away anyway
187                  *
188                  * If we ever want to do this and use the props again,
189                  * it can be done with - pyrna_pydict_to_props(op->ptr, kw, "")
190                  */
191                 
192                 Py_DECREF(ret);
193         }
194
195 #if 0 /* only for testing */
196
197         /* print operator return value */
198         if (mode != PYOP_POLL) {
199                 char flag_str[100];
200                 char class_name[100];
201                 BPY_flag_def *flag_def = pyop_ret_flags;
202
203                 strcpy(flag_str, "");
204                 
205                 while(flag_def->name) {
206                         if (ret_flag & flag_def->flag) {
207                                 if(flag_str[1])
208                                         sprintf(flag_str, "%s | %s", flag_str, flag_def->name);
209                                 else
210                                         strcpy(flag_str, flag_def->name);
211                         }
212                         flag_def++;
213                 }
214
215                 /* get class name */
216                 item= PyObject_GetAttrString(py_class, PYOP_ATTR_IDNAME);
217                 strcpy(class_name, _PyUnicode_AsString(item));
218                 Py_DECREF(item);
219
220                 fprintf(stderr, "%s's %s returned %s\n", class_name, mode == PYOP_EXEC ? "execute" : "invoke", flag_str);
221         }
222 #endif
223
224         PyGILState_Release(gilstate);
225         bpy_import_main_set(NULL);
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, event);    
233 }
234
235 static int PYTHON_OT_exec(bContext *C, wmOperator *op)
236 {
237         return PYTHON_OT_generic(PYOP_EXEC, C, op, NULL);
238 }
239
240 static int PYTHON_OT_poll(bContext *C)
241 {
242         // XXX TODO - no way to get the operator type (and therefor class) from the poll function.
243         //return PYTHON_OT_generic(PYOP_POLL, C, NULL, NULL);
244         return 1;
245 }
246
247 void PYTHON_OT_wrapper(wmOperatorType *ot, void *userdata)
248 {
249         PyObject *py_class = (PyObject *)userdata;
250         PyObject *props, *item;
251
252         /* identifiers */
253         item= PyObject_GetAttrString(py_class, PYOP_ATTR_IDNAME_BL);
254         ot->idname= _PyUnicode_AsString(item);
255         Py_DECREF(item);
256
257         item= PyObject_GetAttrString(py_class, PYOP_ATTR_UINAME);
258         if (item) {
259                 ot->name= _PyUnicode_AsString(item);
260                 Py_DECREF(item);
261         }
262         else {
263                 ot->name= ot->idname;
264                 PyErr_Clear();
265         }
266
267         item= PyObject_GetAttrString(py_class, PYOP_ATTR_DESCRIPTION);
268         ot->description= (item && PyUnicode_Check(item)) ? _PyUnicode_AsString(item):"undocumented python operator";
269         Py_XDECREF(item);
270         
271         /* api callbacks, detailed checks dont on adding */ 
272         if (PyObject_HasAttrString(py_class, "invoke"))
273                 ot->invoke= PYTHON_OT_invoke;
274         if (PyObject_HasAttrString(py_class, "execute"))
275                 ot->exec= PYTHON_OT_exec;
276         if (PyObject_HasAttrString(py_class, "poll"))
277                 ot->poll= PYTHON_OT_poll;
278         
279         ot->pyop_data= userdata;
280         
281         /* flags */
282         item= PyObject_GetAttrString(py_class, PYOP_ATTR_REGISTER);
283         if (item) {
284                 ot->flag= PyObject_IsTrue(item)!=0 ? OPTYPE_REGISTER:0;
285                 Py_DECREF(item);
286         }
287         else {
288                 ot->flag= OPTYPE_REGISTER; /* unspesified, leave on for now to help debug */
289                 PyErr_Clear();
290         }
291         
292         props= PyObject_GetAttrString(py_class, PYOP_ATTR_PROP);
293         
294         if (props) {
295                 PyObject *dummy_args = PyTuple_New(0);
296                 int i;
297
298                 for(i=0; i<PyList_Size(props); i++) {
299                         PyObject *py_func_ptr, *py_kw, *py_srna_cobject, *py_ret;
300                         item = PyList_GET_ITEM(props, i);
301                         
302                         if (PyArg_ParseTuple(item, "O!O!", &PyCObject_Type, &py_func_ptr, &PyDict_Type, &py_kw)) {
303                                 
304                                 PyObject *(*pyfunc)(PyObject *, PyObject *, PyObject *);
305                                 pyfunc = PyCObject_AsVoidPtr(py_func_ptr);
306                                 py_srna_cobject = PyCObject_FromVoidPtr(ot->srna, NULL);
307                                 
308                                 py_ret = pyfunc(py_srna_cobject, dummy_args, py_kw);
309                                 if (py_ret) {
310                                         Py_DECREF(py_ret);
311                                 } else {
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