2.5
[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 "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                "__name__"      /* use pythons class name */
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 = PyGILState_Ensure();
96
97         bpy_import_main_set(CTX_data_main(C));
98         
99         BPY_update_modules(); // XXX - the RNA pointers can change so update before running, would like a nicer solutuon for this.
100
101         args = PyTuple_New(1);
102         PyTuple_SET_ITEM(args, 0, PyObject_GetAttrString(py_class, "__rna__")); // need to use an rna instance as the first arg
103         py_class_instance = PyObject_Call(py_class, args, NULL);
104         Py_DECREF(args);
105         
106         if (py_class_instance) { /* Initializing the class worked, now run its invoke function */
107                 
108                 
109                 /* Assign instance attributes from operator properties */
110                 {
111                         const char *arg_name;
112
113                         RNA_STRUCT_BEGIN(op->ptr, prop) {
114                                 arg_name= RNA_property_identifier(prop);
115
116                                 if (strcmp(arg_name, "rna_type")==0) continue;
117
118                                 item = pyrna_prop_to_py(op->ptr, prop);
119                                 PyObject_SetAttrString(py_class_instance, arg_name, item);
120                                 Py_DECREF(item);
121                         }
122                         RNA_STRUCT_END;
123                 }
124
125                 /* set operator pointer RNA as instance "__operator__" attribute */
126                 RNA_pointer_create(NULL, &RNA_Operator, op, &ptr_operator);
127                 py_operator= pyrna_struct_CreatePyObject(&ptr_operator);
128                 PyObject_SetAttrString(py_class_instance, "__operator__", py_operator);
129                 Py_DECREF(py_operator);
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                         //XXX  Todo - wrap context in a useful way, None for now.
154                         PyTuple_SET_ITEM(args, 1, Py_None);
155                 }
156                 PyTuple_SET_ITEM(args, 0, py_class_instance);
157         
158                 ret = PyObject_Call(item, args, NULL);
159                 
160                 Py_DECREF(args);
161                 Py_DECREF(item);
162         }
163         
164         if (ret == NULL) { /* covers py_class_instance failing too */
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                                 BPy_errors_to_report(op->reports);
172                         }
173                         else {
174                                 ret_flag= ret==Py_True ? 1:0;
175                         }
176                         
177                 } else if (BPY_flag_from_seq(pyop_ret_flags, ret, &ret_flag) == -1) {
178                          /* the returned value could not be converted into a flag */
179                         BPy_errors_to_report(op->reports);
180
181                         ret_flag = OPERATOR_CANCELLED;
182                 }
183                 /* there is no need to copy the py keyword dict modified by
184                  * pyot->py_invoke(), back to the operator props since they are just
185                  * thrown away anyway
186                  *
187                  * If we ever want to do this and use the props again,
188                  * it can be done with - pyrna_pydict_to_props(op->ptr, kw, "")
189                  */
190                 
191                 Py_DECREF(ret);
192         }
193
194 #if 0 /* only for testing */
195
196         /* print operator return value */
197         if (mode != PYOP_POLL) {
198                 char flag_str[100];
199                 char class_name[100];
200                 BPY_flag_def *flag_def = pyop_ret_flags;
201
202                 strcpy(flag_str, "");
203                 
204                 while(flag_def->name) {
205                         if (ret_flag & flag_def->flag) {
206                                 if(flag_str[1])
207                                         sprintf(flag_str, "%s | %s", flag_str, flag_def->name);
208                                 else
209                                         strcpy(flag_str, flag_def->name);
210                         }
211                         flag_def++;
212                 }
213
214                 /* get class name */
215                 item= PyObject_GetAttrString(py_class, PYOP_ATTR_IDNAME);
216                 strcpy(class_name, _PyUnicode_AsString(item));
217                 Py_DECREF(item);
218
219                 fprintf(stderr, "%s's %s returned %s\n", class_name, mode == PYOP_EXEC ? "execute" : "invoke", flag_str);
220         }
221 #endif
222
223         PyGILState_Release(gilstate);
224         bpy_import_main_set(NULL);
225
226         return ret_flag;
227 }
228
229 static int PYTHON_OT_invoke(bContext *C, wmOperator *op, wmEvent *event)
230 {
231         return PYTHON_OT_generic(PYOP_INVOKE, C, op, event);    
232 }
233
234 static int PYTHON_OT_exec(bContext *C, wmOperator *op)
235 {
236         return PYTHON_OT_generic(PYOP_EXEC, C, op, NULL);
237 }
238
239 static int PYTHON_OT_poll(bContext *C)
240 {
241         // XXX TODO - no way to get the operator type (and therefor class) from the poll function.
242         //return PYTHON_OT_generic(PYOP_POLL, C, NULL, NULL);
243         return 1;
244 }
245
246 void PYTHON_OT_wrapper(wmOperatorType *ot, void *userdata)
247 {
248         PyObject *py_class = (PyObject *)userdata;
249         PyObject *props, *item;
250
251         /* identifiers */
252         item= PyObject_GetAttrString(py_class, PYOP_ATTR_IDNAME);
253         ot->idname= _PyUnicode_AsString(item);
254         Py_DECREF(item);
255         
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):"";
269         Py_DECREF(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         int i;
342
343         static struct BPY_class_attr_check pyop_class_attr_values[]= {
344                 {PYOP_ATTR_IDNAME,              's', 0, 0},
345                 {PYOP_ATTR_UINAME,              's', 0, BPY_CLASS_ATTR_OPTIONAL},
346                 {PYOP_ATTR_PROP,                'l', 0, BPY_CLASS_ATTR_OPTIONAL},
347                 {PYOP_ATTR_DESCRIPTION, 's', 0, BPY_CLASS_ATTR_NONE_OK},
348                 {"execute",     'f', 2, BPY_CLASS_ATTR_OPTIONAL},
349                 {"invoke",      'f', 3, BPY_CLASS_ATTR_OPTIONAL},
350                 {"poll",        'f', 2, 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         Py_DECREF(item);
367         
368         /* remove if it already exists */
369         if ((ot=WM_operatortype_exists(idname))) {
370                 if(ot->pyop_data) {
371                         Py_XDECREF((PyObject*)ot->pyop_data);
372                 }
373                 WM_operatortype_remove(idname);
374         }
375         
376         /* If we have properties set, check its a list of dicts */
377         item= PyObject_GetAttrString(py_class, PYOP_ATTR_PROP);
378         if (item) {
379                 for(i=0; i<PyList_Size(item); i++) {
380                         PyObject *py_args = PyList_GET_ITEM(item, i);
381                         PyObject *py_func_ptr, *py_kw; /* place holders */
382                         
383                         if (!PyArg_ParseTuple(py_args, "O!O!", &PyCObject_Type, &py_func_ptr, &PyDict_Type, &py_kw)) {
384                                 PyErr_Format(PyExc_ValueError, "Cant register operator class - %s.properties must contain values from FloatProperty", idname);
385                                 return NULL;                            
386                         }
387                 }
388                 Py_DECREF(item);
389         }
390         else {
391                 PyErr_Clear();
392         }
393         
394         Py_INCREF(py_class);
395         WM_operatortype_append_ptr(PYTHON_OT_wrapper, py_class);
396
397         Py_RETURN_NONE;
398 }
399
400 PyObject *PYOP_wrap_remove(PyObject *self, PyObject *value)
401 {
402         PyObject *py_class;
403         char *idname= NULL;
404         wmOperatorType *ot;
405         
406
407         if (PyUnicode_Check(value))
408                 idname = _PyUnicode_AsString(value);
409         else if (PyCFunction_Check(value)) {
410                 PyObject *cfunc_self = PyCFunction_GetSelf(value);
411                 if (cfunc_self)
412                         idname = _PyUnicode_AsString(cfunc_self);
413         }
414         
415         if (idname==NULL) {
416                 PyErr_SetString( PyExc_ValueError, "Expected the operator name as a string or the operator function");
417                 return NULL;
418         }
419
420         if (!(ot= WM_operatortype_exists(idname))) {
421                 PyErr_Format( PyExc_AttributeError, "Operator \"%s\" does not exists, cant remove", idname);
422                 return NULL;
423         }
424         
425         if (!(py_class= (PyObject *)ot->pyop_data)) {
426                 PyErr_Format( PyExc_AttributeError, "Operator \"%s\" was not created by python", idname);
427                 return NULL;
428         }
429         
430         Py_XDECREF(py_class);
431
432         WM_operatortype_remove(idname);
433
434         Py_RETURN_NONE;
435 }
436
437
438