2.5 merged 20773:21020
[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                "__name__"      /* use pythons class name */
48 #define PYOP_ATTR_DESCRIPTION   "__doc__"       /* use pythons docstring */
49
50 static PyObject *pyop_dict_from_event(wmEvent *event)
51 {
52         PyObject *dict= PyDict_New();
53         PyObject *item;
54         char *cstring, ascii[2];
55
56         /* type */
57         item= PyUnicode_FromString(WM_key_event_string(event->type));
58         PyDict_SetItemString(dict, "type", item);       Py_DECREF(item);
59
60         /* val */
61         switch(event->val) {
62         case KM_ANY:
63                 cstring = "ANY";
64                 break;
65         case KM_RELEASE:
66                 cstring = "RELEASE";
67                 break;
68         case KM_PRESS:
69                 cstring = "PRESS";
70                 break;
71         default:
72                 cstring = "UNKNOWN";
73                 break;
74         }
75
76         item= PyUnicode_FromString(cstring);
77         PyDict_SetItemString(dict, "val", item);        Py_DECREF(item);
78
79         /* x, y (mouse) */
80         item= PyLong_FromLong(event->x);
81         PyDict_SetItemString(dict, "x", item);          Py_DECREF(item);
82
83         item= PyLong_FromLong(event->y);
84         PyDict_SetItemString(dict, "y", item);          Py_DECREF(item);
85
86         item= PyLong_FromLong(event->prevx);
87         PyDict_SetItemString(dict, "prevx", item);      Py_DECREF(item);
88
89         item= PyLong_FromLong(event->prevy);
90         PyDict_SetItemString(dict, "prevy", item);      Py_DECREF(item);
91
92         /* ascii */
93         ascii[0]= event->ascii;
94         ascii[1]= '\0';
95         item= PyUnicode_FromString(ascii);
96         PyDict_SetItemString(dict, "ascii", item);      Py_DECREF(item);
97
98         /* modifier keys */
99         item= PyLong_FromLong(event->shift);
100         PyDict_SetItemString(dict, "shift", item);      Py_DECREF(item);
101
102         item= PyLong_FromLong(event->ctrl);
103         PyDict_SetItemString(dict, "ctrl", item);       Py_DECREF(item);
104
105         item= PyLong_FromLong(event->alt);
106         PyDict_SetItemString(dict, "alt", item);        Py_DECREF(item);
107
108         item= PyLong_FromLong(event->oskey);
109         PyDict_SetItemString(dict, "oskey", item);      Py_DECREF(item);
110
111
112
113         /* modifier */
114 #if 0
115         item= PyTuple_New(0);
116         if(event->keymodifier & KM_SHIFT) {
117                 _PyTuple_Resize(&item, size+1);
118                 PyTuple_SET_ITEM(item, size, _PyUnicode_AsString("SHIFT"));
119                 size++;
120         }
121         if(event->keymodifier & KM_CTRL) {
122                 _PyTuple_Resize(&item, size+1);
123                 PyTuple_SET_ITEM(item, size, _PyUnicode_AsString("CTRL"));
124                 size++;
125         }
126         if(event->keymodifier & KM_ALT) {
127                 _PyTuple_Resize(&item, size+1);
128                 PyTuple_SET_ITEM(item, size, _PyUnicode_AsString("ALT"));
129                 size++;
130         }
131         if(event->keymodifier & KM_OSKEY) {
132                 _PyTuple_Resize(&item, size+1);
133                 PyTuple_SET_ITEM(item, size, _PyUnicode_AsString("OSKEY"));
134                 size++;
135         }
136         PyDict_SetItemString(dict, "keymodifier", item);        Py_DECREF(item);
137 #endif
138
139         return dict;
140 }
141
142 static struct BPY_flag_def pyop_ret_flags[] = {
143         {"RUNNING_MODAL", OPERATOR_RUNNING_MODAL},
144         {"CANCELLED", OPERATOR_CANCELLED},
145         {"FINISHED", OPERATOR_FINISHED},
146         {"PASS_THROUGH", OPERATOR_PASS_THROUGH},
147         {NULL, 0}
148 };
149
150 /* This invoke function can take events and
151  *
152  * It is up to the pyot->py_invoke() python func to run pyot->py_exec()
153  * the invoke function gets the keyword props as a dict, but can parse them
154  * to py_exec like this...
155  *
156  * def op_exec(x=-1, y=-1, text=""):
157  *     ...
158  *
159  * def op_invoke(event, prop_defs):
160  *     prop_defs['x'] = event['x']
161  *     ...
162  *     op_exec(**prop_defs)
163  *
164  * when there is no invoke function, C calls exec and sets the props.
165  * python class instance is stored in op->customdata so exec() can access
166  */
167
168
169 #define PYOP_EXEC 1
170 #define PYOP_INVOKE 2
171 #define PYOP_POLL 3
172         
173 extern void BPY_update_modules( void ); //XXX temp solution
174
175 static int PYTHON_OT_generic(int mode, bContext *C, wmOperator *op, wmEvent *event)
176 {
177         PyObject *py_class = op->type->pyop_data;
178         PyObject *args;
179         PyObject *ret= NULL, *py_class_instance, *item= NULL;
180         int ret_flag= (mode==PYOP_POLL ? 0:OPERATOR_CANCELLED);
181         PointerRNA ptr_context;
182         PointerRNA ptr_operator;
183         PyObject *py_operator;
184
185         PyGILState_STATE gilstate = PyGILState_Ensure();
186
187         bpy_import_main_set(CTX_data_main(C));
188         
189         BPY_update_modules(); // XXX - the RNA pointers can change so update before running, would like a nicer solutuon for this.
190
191         args = PyTuple_New(1);
192         PyTuple_SET_ITEM(args, 0, PyObject_GetAttrString(py_class, "__rna__")); // need to use an rna instance as the first arg
193         py_class_instance = PyObject_Call(py_class, args, NULL);
194         Py_DECREF(args);
195         
196         if (py_class_instance) { /* Initializing the class worked, now run its invoke function */
197                 
198                 
199                 /* Assign instance attributes from operator properties */
200                 {
201                         PropertyRNA *prop, *iterprop;
202                         CollectionPropertyIterator iter;
203                         const char *arg_name;
204
205                         iterprop= RNA_struct_iterator_property(op->ptr->type);
206                         RNA_property_collection_begin(op->ptr, iterprop, &iter);
207
208                         for(; iter.valid; RNA_property_collection_next(&iter)) {
209                                 prop= iter.ptr.data;
210                                 arg_name= RNA_property_identifier(prop);
211
212                                 if (strcmp(arg_name, "rna_type")==0) continue;
213
214                                 item = pyrna_prop_to_py(op->ptr, prop);
215                                 PyObject_SetAttrString(py_class_instance, arg_name, item);
216                                 Py_DECREF(item);
217                         }
218
219                         RNA_property_collection_end(&iter);
220                 }
221
222                 /* set operator pointer RNA as instance "__operator__" attribute */
223                 RNA_pointer_create(NULL, &RNA_Operator, op, &ptr_operator);
224                 py_operator= pyrna_struct_CreatePyObject(&ptr_operator);
225                 PyObject_SetAttrString(py_class_instance, "__operator__", py_operator);
226                 Py_DECREF(py_operator);
227
228                 RNA_pointer_create(NULL, &RNA_Context, C, &ptr_context);
229                 
230                 if (mode==PYOP_INVOKE) {
231                         item= PyObject_GetAttrString(py_class, "invoke");
232                         args = PyTuple_New(3);
233
234                         // PyTuple_SET_ITEM "steals" object reference, it is
235                         // an object passed shouldn't be DECREF'ed
236                         PyTuple_SET_ITEM(args, 1, pyrna_struct_CreatePyObject(&ptr_context));
237                         PyTuple_SET_ITEM(args, 2, pyop_dict_from_event(event));
238                 }
239                 else if (mode==PYOP_EXEC) {
240                         item= PyObject_GetAttrString(py_class, "execute");
241                         args = PyTuple_New(2);
242                         
243                         PyTuple_SET_ITEM(args, 1, pyrna_struct_CreatePyObject(&ptr_context));
244                 }
245                 else if (mode==PYOP_POLL) {
246                         item= PyObject_GetAttrString(py_class, "poll");
247                         args = PyTuple_New(2);
248                         //XXX  Todo - wrap context in a useful way, None for now.
249                         PyTuple_SET_ITEM(args, 1, Py_None);
250                 }
251                 PyTuple_SET_ITEM(args, 0, py_class_instance);
252         
253                 ret = PyObject_Call(item, args, NULL);
254                 
255                 Py_DECREF(args);
256                 Py_DECREF(item);
257         }
258         
259         if (ret == NULL) { /* covers py_class_instance failing too */
260                 BPy_errors_to_report(op->reports);
261         }
262         else {
263                 if (mode==PYOP_POLL) {
264                         if (PyBool_Check(ret) == 0) {
265                                 PyErr_SetString(PyExc_ValueError, "Python poll function return value ");
266                                 BPy_errors_to_report(op->reports);
267                         }
268                         else {
269                                 ret_flag= ret==Py_True ? 1:0;
270                         }
271                         
272                 } else if (BPY_flag_from_seq(pyop_ret_flags, ret, &ret_flag) == -1) {
273                          /* the returned value could not be converted into a flag */
274                         BPy_errors_to_report(op->reports);
275
276                         ret_flag = OPERATOR_CANCELLED;
277                 }
278                 /* there is no need to copy the py keyword dict modified by
279                  * pyot->py_invoke(), back to the operator props since they are just
280                  * thrown away anyway
281                  *
282                  * If we ever want to do this and use the props again,
283                  * it can be done with - pyrna_pydict_to_props(op->ptr, kw, "")
284                  */
285                 
286                 Py_DECREF(ret);
287         }
288
289         /* print operator return value */
290         if (mode != PYOP_POLL) {
291                 char flag_str[100];
292                 char class_name[100];
293                 BPY_flag_def *flag_def = pyop_ret_flags;
294
295                 strcpy(flag_str, "");
296                 
297                 while(flag_def->name) {
298                         if (ret_flag & flag_def->flag) {
299                                 if(flag_str[1])
300                                         sprintf(flag_str, "%s | %s", flag_str, flag_def->name);
301                                 else
302                                         strcpy(flag_str, flag_def->name);
303                         }
304                         flag_def++;
305                 }
306
307                 /* get class name */
308                 item= PyObject_GetAttrString(py_class, PYOP_ATTR_IDNAME);
309                 Py_DECREF(item);
310                 strcpy(class_name, _PyUnicode_AsString(item));
311
312                 fprintf(stderr, "%s's %s returned %s\n", class_name, mode == PYOP_EXEC ? "execute" : "invoke", flag_str);
313         }
314
315         PyGILState_Release(gilstate);
316         bpy_import_main_set(NULL);
317
318         return ret_flag;
319 }
320
321 static int PYTHON_OT_invoke(bContext *C, wmOperator *op, wmEvent *event)
322 {
323         return PYTHON_OT_generic(PYOP_INVOKE, C, op, event);    
324 }
325
326 static int PYTHON_OT_exec(bContext *C, wmOperator *op)
327 {
328         return PYTHON_OT_generic(PYOP_EXEC, C, op, NULL);
329 }
330
331 static int PYTHON_OT_poll(bContext *C)
332 {
333         // XXX TODO - no way to get the operator type (and therefor class) from the poll function.
334         //return PYTHON_OT_generic(PYOP_POLL, C, NULL, NULL);
335         return 1;
336 }
337
338 void PYTHON_OT_wrapper(wmOperatorType *ot, void *userdata)
339 {
340         PyObject *py_class = (PyObject *)userdata;
341         PyObject *props, *item;
342
343         /* identifiers */
344         item= PyObject_GetAttrString(py_class, PYOP_ATTR_IDNAME);
345         Py_DECREF(item);
346         ot->idname= _PyUnicode_AsString(item);
347         
348
349         item= PyObject_GetAttrString(py_class, PYOP_ATTR_UINAME);
350         if (item) {
351                 Py_DECREF(item);
352                 ot->name= _PyUnicode_AsString(item);
353         }
354         else {
355                 ot->name= ot->idname;
356                 PyErr_Clear();
357         }
358
359         item= PyObject_GetAttrString(py_class, PYOP_ATTR_DESCRIPTION);
360         Py_DECREF(item);
361         ot->description= (item && PyUnicode_Check(item)) ? _PyUnicode_AsString(item):"";
362         
363         /* api callbacks, detailed checks dont on adding */ 
364         if (PyObject_HasAttrString(py_class, "invoke"))
365                 ot->invoke= PYTHON_OT_invoke;
366         if (PyObject_HasAttrString(py_class, "execute"))
367                 ot->exec= PYTHON_OT_exec;
368         if (PyObject_HasAttrString(py_class, "poll"))
369                 ot->poll= PYTHON_OT_poll;
370         
371         ot->pyop_data= userdata;
372         
373         props= PyObject_GetAttrString(py_class, PYOP_ATTR_PROP);
374         
375         if (props) {
376                 PyObject *dummy_args = PyTuple_New(0);
377                 int i;
378                 
379                 Py_DECREF(props);
380
381                 for(i=0; i<PyList_Size(props); i++) {
382                         PyObject *py_func_ptr, *py_kw, *py_srna_cobject, *py_ret;
383                         item = PyList_GET_ITEM(props, i);
384                         
385                         if (PyArg_ParseTuple(item, "O!O!", &PyCObject_Type, &py_func_ptr, &PyDict_Type, &py_kw)) {
386                                 
387                                 PyObject *(*pyfunc)(PyObject *, PyObject *, PyObject *);
388                                 pyfunc = PyCObject_AsVoidPtr(py_func_ptr);
389                                 py_srna_cobject = PyCObject_FromVoidPtr(ot->srna, NULL);
390                                 
391                                 py_ret = pyfunc(py_srna_cobject, dummy_args, py_kw);
392                                 if (py_ret) {
393                                         Py_DECREF(py_ret);
394                                 } else {
395                                         PyErr_Print();
396                                         PyErr_Clear();
397                                 }
398                                 Py_DECREF(py_srna_cobject);
399                                 
400                         } else {
401                                 /* cant return NULL from here */ // XXX a bit ugly
402                                 PyErr_Print();
403                                 PyErr_Clear();
404                         }
405                         
406                         // expect a tuple with a CObject and a dict
407                 }
408                 Py_DECREF(dummy_args);
409         } else {
410                 PyErr_Clear();
411         }
412 }
413
414
415 /* pyOperators - Operators defined IN Python */
416 PyObject *PYOP_wrap_add(PyObject *self, PyObject *py_class)
417 {       
418         PyObject *base_class, *item;
419         wmOperatorType *ot;
420         
421         
422         char *idname= NULL;
423         int i;
424
425         static struct BPY_class_attr_check pyop_class_attr_values[]= {
426                 {PYOP_ATTR_IDNAME,              's', 0, 0},
427                 {PYOP_ATTR_UINAME,              's', 0, BPY_CLASS_ATTR_OPTIONAL},
428                 {PYOP_ATTR_PROP,                'l', 0, BPY_CLASS_ATTR_OPTIONAL},
429                 {PYOP_ATTR_DESCRIPTION, 's', 0, BPY_CLASS_ATTR_NONE_OK},
430                 {"execute",     'f', 2, BPY_CLASS_ATTR_OPTIONAL},
431                 {"invoke",      'f', 3, BPY_CLASS_ATTR_OPTIONAL},
432                 {"poll",        'f', 2, BPY_CLASS_ATTR_OPTIONAL},
433                 {NULL, 0, 0, 0}
434         };
435
436         // in python would be...
437         //PyObject *optype = PyObject_GetAttrString(PyObject_GetAttrString(PyDict_GetItemString(PyEval_GetGlobals(), "bpy"), "types"), "Operator");
438         base_class = PyObject_GetAttrStringArgs(PyDict_GetItemString(PyEval_GetGlobals(), "bpy"), 2, "types", "Operator");
439         Py_DECREF(base_class);
440
441         if(BPY_class_validate("Operator", py_class, base_class, pyop_class_attr_values, NULL) < 0) {
442                 return NULL; /* BPY_class_validate sets the error */
443         }
444
445         /* class name is used for operator ID - this can be changed later if we want */
446         item= PyObject_GetAttrString(py_class, PYOP_ATTR_IDNAME);
447         Py_DECREF(item);
448         idname =  _PyUnicode_AsString(item);
449         
450         /* remove if it already exists */
451         if ((ot=WM_operatortype_find(idname))) {
452                 Py_XDECREF((PyObject*)ot->pyop_data);
453                 WM_operatortype_remove(idname);
454         }
455         
456         /* If we have properties set, check its a list of dicts */
457         item= PyObject_GetAttrString(py_class, PYOP_ATTR_PROP);
458         if (item) {
459                 Py_DECREF(item);
460                 for(i=0; i<PyList_Size(item); i++) {
461                         PyObject *py_args = PyList_GET_ITEM(item, i);
462                         PyObject *py_func_ptr, *py_kw; /* place holders */
463                         
464                         if (!PyArg_ParseTuple(py_args, "O!O!", &PyCObject_Type, &py_func_ptr, &PyDict_Type, &py_kw)) {
465                                 PyErr_Format(PyExc_ValueError, "Cant register operator class - %s.properties must contain values from FloatProperty", idname);
466                                 return NULL;                            
467                         }
468                 }
469         }
470         else {
471                 PyErr_Clear();
472         }
473         
474         Py_INCREF(py_class);
475         WM_operatortype_append_ptr(PYTHON_OT_wrapper, py_class);
476
477         Py_RETURN_NONE;
478 }
479
480 PyObject *PYOP_wrap_remove(PyObject *self, PyObject *value)
481 {
482         PyObject *py_class;
483         char *idname= NULL;
484         wmOperatorType *ot;
485         
486
487         if (PyUnicode_Check(value))
488                 idname = _PyUnicode_AsString(value);
489         else if (PyCFunction_Check(value)) {
490                 PyObject *cfunc_self = PyCFunction_GetSelf(value);
491                 if (cfunc_self)
492                         idname = _PyUnicode_AsString(cfunc_self);
493         }
494         
495         if (idname==NULL) {
496                 PyErr_SetString( PyExc_ValueError, "Expected the operator name as a string or the operator function");
497                 return NULL;
498         }
499
500         if (!(ot= WM_operatortype_find(idname))) {
501                 PyErr_Format( PyExc_AttributeError, "Operator \"%s\" does not exists, cant remove", idname);
502                 return NULL;
503         }
504         
505         if (!(py_class= (PyObject *)ot->pyop_data)) {
506                 PyErr_Format( PyExc_AttributeError, "Operator \"%s\" was not created by python", idname);
507                 return NULL;
508         }
509         
510         Py_XDECREF(py_class);
511
512         WM_operatortype_remove(idname);
513
514         Py_RETURN_NONE;
515 }
516
517
518