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