2.5
[blender.git] / source / blender / python / intern / bpy_operator.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 #include "bpy_operator.h"
27 #include "bpy_opwrapper.h"
28 #include "bpy_rna.h" /* for setting arg props only - pyrna_py_to_prop() */
29 #include "bpy_compat.h"
30
31 //#include "blendef.h"
32 #include "BLI_dynstr.h"
33
34 #include "WM_api.h"
35 #include "WM_types.h"
36
37 #include "MEM_guardedalloc.h"
38 #include "BKE_idprop.h"
39
40 extern ListBase global_ops; /* evil, temp use */
41
42
43
44 /* This function is only used by operators right now
45  * Its used for taking keyword args and filling in property values */
46 int PYOP_props_from_dict(PointerRNA *ptr, PyObject *kw)
47 {
48         int error_val = 0;
49         int totkw;
50         const char *arg_name= NULL;
51         PyObject *item;
52
53         PropertyRNA *prop, *iterprop;
54         CollectionPropertyIterator iter;
55
56         iterprop= RNA_struct_iterator_property(ptr);
57         RNA_property_collection_begin(ptr, iterprop, &iter);
58
59         totkw = kw ? PyDict_Size(kw):0;
60
61         for(; iter.valid; RNA_property_collection_next(&iter)) {
62                 prop= iter.ptr.data;
63
64                 arg_name= RNA_property_identifier(&iter.ptr, prop);
65
66                 if (strcmp(arg_name, "rna_type")==0) continue;
67
68                 if (kw==NULL) {
69                         PyErr_Format( PyExc_AttributeError, "no args, expected \"%s\"", arg_name ? arg_name : "<UNKNOWN>");
70                         error_val= -1;
71                         break;
72                 }
73
74                 item= PyDict_GetItemString(kw, arg_name);
75
76                 if (item == NULL) {
77                         PyErr_Format( PyExc_AttributeError, "argument \"%s\" missing", arg_name ? arg_name : "<UNKNOWN>");
78                         error_val = -1; /* pyrna_py_to_prop sets the error */
79                         break;
80                 }
81
82                 if (pyrna_py_to_prop(ptr, prop, item)) {
83                         error_val= -1;
84                         break;
85                 }
86
87                 totkw--;
88         }
89
90         RNA_property_collection_end(&iter);
91
92         if (error_val==0 && totkw > 0) { /* some keywords were given that were not used :/ */
93                 PyObject *key, *value;
94                 Py_ssize_t pos = 0;
95
96                 while (PyDict_Next(kw, &pos, &key, &value)) {
97                         arg_name= _PyUnicode_AsString(key);
98                         if (RNA_struct_find_property(ptr, arg_name) == NULL) break;
99                         arg_name= NULL;
100                 }
101
102                 PyErr_Format( PyExc_AttributeError, "argument \"%s\" unrecognized", arg_name ? arg_name : "<UNKNOWN>");
103                 error_val = -1;
104         }
105
106         return error_val;
107 }
108
109
110
111
112 static int pyop_func_compare( BPy_OperatorFunc * a, BPy_OperatorFunc * b )
113 {
114         return (strcmp(a->name, b->name)==0) ? 0 : -1;
115 }
116
117 /*----------------------repr--------------------------------------------*/
118 static PyObject *pyop_base_repr( BPy_OperatorBase * self )
119 {
120         return PyUnicode_FromFormat( "[BPy_OperatorBase]");
121 }
122
123 static PyObject *pyop_func_repr( BPy_OperatorFunc * self )
124 {
125         return PyUnicode_FromFormat( "[BPy_OperatorFunc \"%s\"]", self->name);
126 }
127
128
129 //---------------getattr--------------------------------------------
130 static PyObject *pyop_base_getattro( BPy_OperatorBase * self, PyObject *pyname )
131 {
132         char *name = _PyUnicode_AsString(pyname);
133         PyObject *ret;
134         wmOperatorType *ot;
135
136         if ((ot = WM_operatortype_find(name))) {
137                 ret= pyop_func_CreatePyObject(self->C, name);
138         }
139         else if ((ret = PyObject_GenericGetAttr((PyObject *)self, pyname))) {
140                 /* do nothing, this accounts for methoddef's add and remove */
141         }
142         else {
143                 PyErr_Format( PyExc_AttributeError, "Operator \"%s\" not found", name);
144                 ret= NULL;
145         }
146         
147         return ret;
148 }
149
150 /* getseter's */
151 PyObject *pyop_func_get_rna(BPy_OperatorFunc *self)
152 {
153         BPy_StructRNA *pyrna;
154         PointerRNA ptr;
155         wmOperatorType *ot;
156
157         ot= WM_operatortype_find(self->name);
158         if (ot == NULL) {
159                 PyErr_SetString( PyExc_SystemError, "Operator could not be found");
160                 return NULL;
161         }
162
163         pyrna= (BPy_StructRNA *)pyrna_struct_CreatePyObject(&ptr); /* were not really using &ptr, overwite next */
164
165         /* XXX POINTER - if this 'ot' is python generated, it could be free'd */
166         RNA_pointer_create(NULL, NULL, ot->srna, &pyrna->properties, &pyrna->ptr);
167         return (PyObject *)pyrna;
168 }
169
170 static PyGetSetDef pyop_func_getseters[] = {
171         {"rna", (getter)pyop_func_get_rna, (setter)NULL, "vertex's coordinate", NULL},
172         {NULL,NULL,NULL,NULL,NULL}  /* Sentinel */
173 };
174
175 static PyObject * pyop_func_call(BPy_OperatorFunc * self, PyObject *args, PyObject *kw)
176 {
177         IDProperty *properties = NULL;
178         wmOperatorType *ot;
179
180         int error_val = 0;
181         PointerRNA ptr;
182         
183         if (PyTuple_Size(args)) {
184                 PyErr_SetString( PyExc_AttributeError, "All operator args must be keywords");
185                 return NULL;
186         }
187
188         ot= WM_operatortype_find(self->name);
189         if (ot == NULL) {
190                 PyErr_SetString( PyExc_SystemError, "Operator could not be found");
191                 return NULL;
192         }
193         
194         RNA_pointer_create(NULL, NULL, ot->srna, &properties, &ptr);
195         
196         error_val= PYOP_props_from_dict(&ptr, kw);
197         
198         if (error_val==0) {
199                 WM_operator_name_call(self->C, self->name, WM_OP_EXEC_DEFAULT, properties);
200         }
201
202         if (properties) {
203                 IDP_FreeProperty(properties);
204                 MEM_freeN(properties);
205         }
206 #if 0
207         /* if there is some way to know an operator takes args we should use this */
208         {
209                 /* no props */
210                 if (kw != NULL) {
211                         PyErr_Format(PyExc_AttributeError, "Operator \"%s\" does not take any args", self->name);
212                         return NULL;
213                 }
214
215                 WM_operator_name_call(self->C, self->name, WM_OP_EXEC_DEFAULT, NULL);
216         }
217 #endif
218
219         if (error_val==-1) {
220                 return NULL;
221         }
222
223         Py_RETURN_NONE;
224 }
225
226 PyObject *pyop_base_dir(PyObject *self);
227
228 static struct PyMethodDef pyop_base_methods[] = {
229         {"add", (PyCFunction)PYOP_wrap_add, METH_VARARGS, ""},
230         {"remove", (PyCFunction)PYOP_wrap_remove, METH_VARARGS, ""},
231         {"__dir__", (PyCFunction)pyop_base_dir, METH_NOARGS, ""},
232         {NULL, NULL, 0, NULL}
233 };
234
235 PyObject *pyop_base_dir(PyObject *self)
236 {
237         PyObject *ret = PyList_New(0);
238         PyObject *item;
239         wmOperatorType *ot;
240         PyMethodDef *meth;
241         
242         for(ot= WM_operatortype_first(); ot; ot= ot->next) {
243                 item = PyUnicode_FromString( ot->idname );
244                 PyList_Append(ret, item);
245                 Py_DECREF(item);
246         }
247
248         for(meth=pyop_base_methods; meth->ml_name; meth++) {
249                 item = PyUnicode_FromString( meth->ml_name );
250                 PyList_Append(ret, item);
251                 Py_DECREF(item);
252         }
253
254         return ret;
255 }
256
257 /*-----------------------BPy_OperatorBase method def------------------------------*/
258 PyTypeObject pyop_base_Type = {
259 #if (PY_VERSION_HEX >= 0x02060000)
260         PyVarObject_HEAD_INIT(&PyType_Type, 0)
261 #else
262         /* python 2.5 and below */
263         PyObject_HEAD_INIT( NULL )  /* required py macro */
264         0,                          /* ob_size */
265 #endif
266
267         "Operator",             /* tp_name */
268         sizeof( BPy_OperatorBase ),                     /* tp_basicsize */
269         0,                      /* tp_itemsize */
270         /* methods */
271         NULL,                                           /* tp_dealloc */
272         NULL,                       /* printfunc tp_print; */
273         NULL,                                           /* getattrfunc tp_getattr; */
274         NULL,                       /* setattrfunc tp_setattr; */
275         NULL,                                           /* tp_compare */
276         ( reprfunc ) pyop_base_repr,    /* tp_repr */
277
278         /* Method suites for standard classes */
279
280         NULL,                       /* PyNumberMethods *tp_as_number; */
281         NULL,                                           /* PySequenceMethods *tp_as_sequence; */
282         NULL,                                           /* PyMappingMethods *tp_as_mapping; */
283
284         /* More standard operations (here for binary compatibility) */
285
286         NULL,                                           /* hashfunc tp_hash; */
287         NULL,                       /* ternaryfunc tp_call; */
288         NULL,                       /* reprfunc tp_str; */
289         ( getattrofunc )pyop_base_getattro, /*PyObject_GenericGetAttr - MINGW Complains, assign later */        /* getattrofunc tp_getattro; */
290         NULL, /*PyObject_GenericSetAttr - MINGW Complains, assign later */      /* setattrofunc tp_setattro; */
291
292         /* Functions to access object as input/output buffer */
293         NULL,                       /* PyBufferProcs *tp_as_buffer; */
294
295   /*** Flags to define presence of optional/expanded features ***/
296         Py_TPFLAGS_DEFAULT,         /* long tp_flags; */
297
298         NULL,                                           /*  char *tp_doc;  Documentation string */
299   /*** Assigned meaning in release 2.0 ***/
300         /* call function for all accessible objects */
301         NULL,                       /* traverseproc tp_traverse; */
302
303         /* delete references to contained objects */
304         NULL,                       /* inquiry tp_clear; */
305
306   /***  Assigned meaning in release 2.1 ***/
307   /*** rich comparisons ***/
308         NULL,                       /* richcmpfunc tp_richcompare; */
309
310   /***  weak reference enabler ***/
311         0,                          /* long tp_weaklistoffset; */
312
313   /*** Added in release 2.2 ***/
314         /*   Iterators */
315         NULL,                                           /* getiterfunc tp_iter; */
316         NULL,                       /* iternextfunc tp_iternext; */
317
318   /*** Attribute descriptor and subclassing stuff ***/
319         pyop_base_methods,                                              /* struct PyMethodDef *tp_methods; */
320         NULL,                       /* struct PyMemberDef *tp_members; */
321         NULL,           /* struct PyGetSetDef *tp_getset; */
322         NULL,                       /* struct _typeobject *tp_base; */
323         NULL,                       /* PyObject *tp_dict; */
324         NULL,                       /* descrgetfunc tp_descr_get; */
325         NULL,                       /* descrsetfunc tp_descr_set; */
326         0,                          /* long tp_dictoffset; */
327         NULL,                       /* initproc tp_init; */
328         NULL,                       /* allocfunc tp_alloc; */
329         NULL,                                           /* newfunc tp_new; */
330         /*  Low-level free-memory routine */
331         NULL,                       /* freefunc tp_free;  */
332         /* For PyObject_IS_GC */
333         NULL,                       /* inquiry tp_is_gc;  */
334         NULL,                       /* PyObject *tp_bases; */
335         /* method resolution order */
336         NULL,                       /* PyObject *tp_mro;  */
337         NULL,                       /* PyObject *tp_cache; */
338         NULL,                       /* PyObject *tp_subclasses; */
339         NULL,                       /* PyObject *tp_weaklist; */
340         NULL
341 };
342
343 /*-----------------------BPy_OperatorBase method def------------------------------*/
344 PyTypeObject pyop_func_Type = {
345 #if (PY_VERSION_HEX >= 0x02060000)
346         PyVarObject_HEAD_INIT(&PyType_Type, 0)
347 #else
348         /* python 2.5 and below */
349         PyObject_HEAD_INIT( NULL )  /* required py macro */
350         0,                          /* ob_size */
351 #endif
352
353         "OperatorFunc",         /* tp_name */
354         sizeof( BPy_OperatorFunc ),                     /* tp_basicsize */
355         0,                      /* tp_itemsize */
356         /* methods */
357         NULL,                                           /* tp_dealloc */
358         NULL,                       /* printfunc tp_print; */
359         NULL,                                           /* getattrfunc tp_getattr; */
360         NULL,                       /* setattrfunc tp_setattr; */
361         ( cmpfunc ) pyop_func_compare,  /* tp_compare */
362         ( reprfunc ) pyop_func_repr,    /* tp_repr */
363
364         /* Method suites for standard classes */
365
366         NULL,                       /* PyNumberMethods *tp_as_number; */
367         NULL,                                           /* PySequenceMethods *tp_as_sequence; */
368         NULL,                                           /* PyMappingMethods *tp_as_mapping; */
369
370         /* More standard operations (here for binary compatibility) */
371
372         NULL,                                           /* hashfunc tp_hash; */
373         (ternaryfunc)pyop_func_call,                       /* ternaryfunc tp_call; */
374         NULL,                       /* reprfunc tp_str; */
375         NULL,                                           /* getattrofunc tp_getattro; */
376         NULL, /*PyObject_GenericSetAttr - MINGW Complains, assign later */      /* setattrofunc tp_setattro; */
377
378         /* Functions to access object as input/output buffer */
379         NULL,                       /* PyBufferProcs *tp_as_buffer; */
380
381   /*** Flags to define presence of optional/expanded features ***/
382         Py_TPFLAGS_DEFAULT,         /* long tp_flags; */
383
384         NULL,                                           /*  char *tp_doc;  Documentation string */
385   /*** Assigned meaning in release 2.0 ***/
386         /* call function for all accessible objects */
387         NULL,                       /* traverseproc tp_traverse; */
388
389         /* delete references to contained objects */
390         NULL,                       /* inquiry tp_clear; */
391
392   /***  Assigned meaning in release 2.1 ***/
393   /*** rich comparisons ***/
394         NULL,                       /* richcmpfunc tp_richcompare; */
395
396   /***  weak reference enabler ***/
397         0,                          /* long tp_weaklistoffset; */
398
399   /*** Added in release 2.2 ***/
400         /*   Iterators */
401         NULL,                                           /* getiterfunc tp_iter; */
402         NULL,                       /* iternextfunc tp_iternext; */
403
404   /*** Attribute descriptor and subclassing stuff ***/
405         NULL,                                           /* struct PyMethodDef *tp_methods; */
406         NULL,                       /* struct PyMemberDef *tp_members; */
407         pyop_func_getseters,            /* struct PyGetSetDef *tp_getset; */
408         NULL,                       /* struct _typeobject *tp_base; */
409         NULL,                       /* PyObject *tp_dict; */
410         NULL,                       /* descrgetfunc tp_descr_get; */
411         NULL,                       /* descrsetfunc tp_descr_set; */
412         0,                          /* long tp_dictoffset; */
413         NULL,                       /* initproc tp_init; */
414         NULL,                       /* allocfunc tp_alloc; */
415         NULL,                                           /* newfunc tp_new; */
416         /*  Low-level free-memory routine */
417         NULL,                       /* freefunc tp_free;  */
418         /* For PyObject_IS_GC */
419         NULL,                       /* inquiry tp_is_gc;  */
420         NULL,                       /* PyObject *tp_bases; */
421         /* method resolution order */
422         NULL,                       /* PyObject *tp_mro;  */
423         NULL,                       /* PyObject *tp_cache; */
424         NULL,                       /* PyObject *tp_subclasses; */
425         NULL,                       /* PyObject *tp_weaklist; */
426         NULL
427 };
428
429 PyObject *pyop_base_CreatePyObject( bContext *C )
430 {
431         BPy_OperatorBase *pyop;
432
433         pyop = ( BPy_OperatorBase * ) PyObject_NEW( BPy_OperatorBase, &pyop_base_Type );
434
435         if( !pyop ) {
436                 PyErr_SetString( PyExc_MemoryError, "couldn't create BPy_OperatorBase object" );
437                 return NULL;
438         }
439
440         pyop->C = C; /* TODO - copy this? */
441
442         return ( PyObject * ) pyop;
443 }
444
445 PyObject *pyop_func_CreatePyObject( bContext *C, char *name )
446 {
447         BPy_OperatorFunc *pyop;
448
449         pyop = ( BPy_OperatorFunc * ) PyObject_NEW( BPy_OperatorFunc, &pyop_func_Type );
450
451         if( !pyop ) {
452                 PyErr_SetString( PyExc_MemoryError, "couldn't create BPy_OperatorFunc object" );
453                 return NULL;
454         }
455
456         strcpy(pyop->name, name);
457         pyop->C= C; /* TODO - how should contexts be dealt with? */
458
459         return ( PyObject * ) pyop;
460 }
461
462 PyObject *BPY_operator_module( bContext *C )
463 {
464         if( PyType_Ready( &pyop_base_Type ) < 0 )
465                 return NULL;
466
467         if( PyType_Ready( &pyop_func_Type ) < 0 )
468                 return NULL;
469
470         //submodule = Py_InitModule3( "operator", M_rna_methods, "rna module" );
471         return pyop_base_CreatePyObject(C);
472 }
473
474
475