ok anoter compile fix
[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 /* For some reason python3 needs these :/ */
119 static PyObject *pyop_func_richcmp(BPy_OperatorFunc * a, BPy_OperatorFunc * b, int op)
120 {
121         int cmp_result= -1; /* assume false */
122         if (BPy_OperatorFunc_Check(a) && BPy_OperatorFunc_Check(b)) {
123                 cmp_result= pyop_func_compare(a, b);
124         }
125
126         return Py_CmpToRich(op, cmp_result);
127 }
128
129
130 /*----------------------repr--------------------------------------------*/
131 static PyObject *pyop_base_repr( BPy_OperatorBase * self )
132 {
133         return PyUnicode_FromFormat( "[BPy_OperatorBase]");
134 }
135
136 static PyObject *pyop_func_repr( BPy_OperatorFunc * self )
137 {
138         return PyUnicode_FromFormat( "[BPy_OperatorFunc \"%s\"]", self->name);
139 }
140
141 static struct PyMethodDef pyop_base_methods[] = {
142         {"add", (PyCFunction)PYOP_wrap_add, METH_VARARGS, ""},
143         {"remove", (PyCFunction)PYOP_wrap_remove, METH_VARARGS, ""},
144         {NULL, NULL, 0, NULL}
145 };
146
147 //---------------getattr--------------------------------------------
148 static PyObject *pyop_base_getattro( BPy_OperatorBase * self, PyObject *pyname )
149 {
150         char *name = _PyUnicode_AsString(pyname);
151         PyObject *ret;
152         wmOperatorType *ot;
153         PyMethodDef *meth;
154         
155         if ((ot = WM_operatortype_find(name))) {
156                 ret= pyop_func_CreatePyObject(self->C, name);
157         }
158         else if (strcmp(name, "__dict__")==0) {
159                 ret = PyDict_New();
160
161                 for(ot= WM_operatortype_first(); ot; ot= ot->next) {
162                         PyDict_SetItemString(ret, ot->idname, Py_None);
163                 }
164
165                 for(meth=pyop_base_methods; meth->ml_name; meth++) {
166                         PyDict_SetItemString(ret, meth->ml_name, Py_None);
167                 }
168         }
169         else if ((ret = PyObject_GenericGetAttr((PyObject *)self, pyname))) {
170                 /* do nothing, this accounts for methoddef's add and remove */
171         }
172         else {
173                 PyErr_Format( PyExc_AttributeError, "Operator \"%s\" not found", name);
174                 ret= NULL;
175         }
176
177         return ret;
178 }
179
180 /* getseter's */
181 PyObject *pyop_func_get_rna(BPy_OperatorFunc *self)
182 {
183         BPy_StructRNA *pyrna;
184         PointerRNA ptr;
185         wmOperatorType *ot;
186
187         ot= WM_operatortype_find(self->name);
188         if (ot == NULL) {
189                 PyErr_SetString( PyExc_SystemError, "Operator could not be found");
190                 return NULL;
191         }
192
193         pyrna= (BPy_StructRNA *)pyrna_struct_CreatePyObject(&ptr); /* were not really using &ptr, overwite next */
194
195         /* XXX POINTER - if this 'ot' is python generated, it could be free'd */
196         RNA_pointer_create(NULL, ot->srna, NULL, &pyrna->ptr);
197         pyrna->freeptr= 1;
198
199         return (PyObject *)pyrna;
200 }
201
202 static PyGetSetDef pyop_func_getseters[] = {
203         {"rna", (getter)pyop_func_get_rna, (setter)NULL, "Operator RNA properties", NULL},
204         {NULL,NULL,NULL,NULL,NULL}  /* Sentinel */
205 };
206
207 static PyObject * pyop_func_call(BPy_OperatorFunc * self, PyObject *args, PyObject *kw)
208 {
209         wmOperatorType *ot;
210
211         int error_val = 0;
212         PointerRNA ptr;
213         char *report_str= NULL;
214
215         if (PyTuple_Size(args)) {
216                 PyErr_SetString( PyExc_AttributeError, "All operator args must be keywords");
217                 return NULL;
218         }
219
220         ot= WM_operatortype_find(self->name);
221         if (ot == NULL) {
222                 PyErr_SetString( PyExc_SystemError, "Operator could not be found");
223                 return NULL;
224         }
225         
226         if(ot->poll && (ot->poll(self->C) == 0)) {
227                 PyErr_SetString( PyExc_SystemError, "Operator poll() function failed, context is incorrect");
228                 return NULL;
229         }
230         
231         WM_operator_properties_create(&ptr, self->name);
232         
233         error_val= PYOP_props_from_dict(&ptr, kw);
234         
235         if (error_val==0) {
236                 ReportList reports;
237
238                 BKE_reports_init(&reports, RPT_STORE);
239
240                 WM_operator_call_py(self->C, ot, &ptr, &reports);
241
242                 report_str= BKE_reports_string(&reports, RPT_ERROR);
243
244                 if (report_str) {
245                         PyErr_SetString(PyExc_SystemError, report_str);
246                         MEM_freeN(report_str);
247                         error_val = -1;
248                 }
249
250                 if (reports.list.first)
251                         BKE_reports_clear(&reports);
252         }
253
254         WM_operator_properties_free(&ptr);
255
256 #if 0
257         /* if there is some way to know an operator takes args we should use this */
258         {
259                 /* no props */
260                 if (kw != NULL) {
261                         PyErr_Format(PyExc_AttributeError, "Operator \"%s\" does not take any args", self->name);
262                         return NULL;
263                 }
264
265                 WM_operator_name_call(self->C, self->name, WM_OP_EXEC_DEFAULT, NULL);
266         }
267 #endif
268
269         if (error_val==-1) {
270                 return NULL;
271         }
272
273         Py_RETURN_NONE;
274 }
275
276 /*-----------------------BPy_OperatorBase method def------------------------------*/
277 PyTypeObject pyop_base_Type = {
278 #if (PY_VERSION_HEX >= 0x02060000)
279         PyVarObject_HEAD_INIT(NULL, 0)
280 #else
281         /* python 2.5 and below */
282         PyObject_HEAD_INIT( NULL )  /* required py macro */
283         0,                          /* ob_size */
284 #endif
285
286         "Operator",             /* tp_name */
287         sizeof( BPy_OperatorBase ),                     /* tp_basicsize */
288         0,                      /* tp_itemsize */
289         /* methods */
290         NULL,                                           /* tp_dealloc */
291         NULL,                       /* printfunc tp_print; */
292         NULL,                                           /* getattrfunc tp_getattr; */
293         NULL,                       /* setattrfunc tp_setattr; */
294         NULL,                                           /* tp_compare */
295         ( reprfunc ) pyop_base_repr,    /* tp_repr */
296
297         /* Method suites for standard classes */
298
299         NULL,                       /* PyNumberMethods *tp_as_number; */
300         NULL,                                           /* PySequenceMethods *tp_as_sequence; */
301         NULL,                                           /* PyMappingMethods *tp_as_mapping; */
302
303         /* More standard operations (here for binary compatibility) */
304
305         NULL,                                           /* hashfunc tp_hash; */
306         NULL,                       /* ternaryfunc tp_call; */
307         NULL,                       /* reprfunc tp_str; */
308         ( getattrofunc )pyop_base_getattro, /*PyObject_GenericGetAttr - MINGW Complains, assign later */        /* getattrofunc tp_getattro; */
309         NULL, /*PyObject_GenericSetAttr - MINGW Complains, assign later */      /* setattrofunc tp_setattro; */
310
311         /* Functions to access object as input/output buffer */
312         NULL,                       /* PyBufferProcs *tp_as_buffer; */
313
314   /*** Flags to define presence of optional/expanded features ***/
315         Py_TPFLAGS_DEFAULT,         /* long tp_flags; */
316
317         NULL,                                           /*  char *tp_doc;  Documentation string */
318   /*** Assigned meaning in release 2.0 ***/
319         /* call function for all accessible objects */
320         NULL,                       /* traverseproc tp_traverse; */
321
322         /* delete references to contained objects */
323         NULL,                       /* inquiry tp_clear; */
324
325   /***  Assigned meaning in release 2.1 ***/
326   /*** rich comparisons ***/
327         NULL,                       /* richcmpfunc tp_richcompare; */
328
329   /***  weak reference enabler ***/
330         0,                          /* long tp_weaklistoffset; */
331
332   /*** Added in release 2.2 ***/
333         /*   Iterators */
334         NULL,                                           /* getiterfunc tp_iter; */
335         NULL,                       /* iternextfunc tp_iternext; */
336
337   /*** Attribute descriptor and subclassing stuff ***/
338         pyop_base_methods,                                              /* struct PyMethodDef *tp_methods; */
339         NULL,                       /* struct PyMemberDef *tp_members; */
340         NULL,           /* struct PyGetSetDef *tp_getset; */
341         NULL,                       /* struct _typeobject *tp_base; */
342         NULL,                       /* PyObject *tp_dict; */
343         NULL,                       /* descrgetfunc tp_descr_get; */
344         NULL,                       /* descrsetfunc tp_descr_set; */
345         0,                          /* long tp_dictoffset; */
346         NULL,                       /* initproc tp_init; */
347         NULL,                       /* allocfunc tp_alloc; */
348         NULL,                                           /* newfunc tp_new; */
349         /*  Low-level free-memory routine */
350         NULL,                       /* freefunc tp_free;  */
351         /* For PyObject_IS_GC */
352         NULL,                       /* inquiry tp_is_gc;  */
353         NULL,                       /* PyObject *tp_bases; */
354         /* method resolution order */
355         NULL,                       /* PyObject *tp_mro;  */
356         NULL,                       /* PyObject *tp_cache; */
357         NULL,                       /* PyObject *tp_subclasses; */
358         NULL,                       /* PyObject *tp_weaklist; */
359         NULL
360 };
361
362 /*-----------------------BPy_OperatorBase method def------------------------------*/
363 PyTypeObject pyop_func_Type = {
364 #if (PY_VERSION_HEX >= 0x02060000)
365         PyVarObject_HEAD_INIT(NULL, 0)
366 #else
367         /* python 2.5 and below */
368         PyObject_HEAD_INIT( NULL )  /* required py macro */
369         0,                          /* ob_size */
370 #endif
371
372         "OperatorFunc",         /* tp_name */
373         sizeof( BPy_OperatorFunc ),                     /* tp_basicsize */
374         0,                      /* tp_itemsize */
375         /* methods */
376         NULL,                                           /* tp_dealloc */
377         NULL,                       /* printfunc tp_print; */
378         NULL,                                           /* getattrfunc tp_getattr; */
379         NULL,                       /* setattrfunc tp_setattr; */
380         NULL,                                           /* tp_compare */ /* DEPRECATED in python 3.0! */
381         ( reprfunc ) pyop_func_repr,    /* tp_repr */
382
383         /* Method suites for standard classes */
384
385         NULL,                       /* PyNumberMethods *tp_as_number; */
386         NULL,                                           /* PySequenceMethods *tp_as_sequence; */
387         NULL,                                           /* PyMappingMethods *tp_as_mapping; */
388
389         /* More standard operations (here for binary compatibility) */
390
391         NULL,                                           /* hashfunc tp_hash; */
392         (ternaryfunc)pyop_func_call,                       /* ternaryfunc tp_call; */
393         NULL,                       /* reprfunc tp_str; */
394         NULL,                                           /* getattrofunc tp_getattro; */
395         NULL, /*PyObject_GenericSetAttr - MINGW Complains, assign later */      /* setattrofunc tp_setattro; */
396
397         /* Functions to access object as input/output buffer */
398         NULL,                       /* PyBufferProcs *tp_as_buffer; */
399
400   /*** Flags to define presence of optional/expanded features ***/
401         Py_TPFLAGS_DEFAULT,         /* long tp_flags; */
402
403         NULL,                                           /*  char *tp_doc;  Documentation string */
404   /*** Assigned meaning in release 2.0 ***/
405         /* call function for all accessible objects */
406         NULL,                       /* traverseproc tp_traverse; */
407
408         /* delete references to contained objects */
409         NULL,                       /* inquiry tp_clear; */
410
411   /***  Assigned meaning in release 2.1 ***/
412   /*** rich comparisons ***/
413         (richcmpfunc)pyop_func_richcmp, /* richcmpfunc tp_richcompare; */
414
415   /***  weak reference enabler ***/
416         0,                          /* long tp_weaklistoffset; */
417
418   /*** Added in release 2.2 ***/
419         /*   Iterators */
420         NULL,                                           /* getiterfunc tp_iter; */
421         NULL,                       /* iternextfunc tp_iternext; */
422
423   /*** Attribute descriptor and subclassing stuff ***/
424         NULL,                                           /* struct PyMethodDef *tp_methods; */
425         NULL,                       /* struct PyMemberDef *tp_members; */
426         pyop_func_getseters,            /* struct PyGetSetDef *tp_getset; */
427         NULL,                       /* struct _typeobject *tp_base; */
428         NULL,                       /* PyObject *tp_dict; */
429         NULL,                       /* descrgetfunc tp_descr_get; */
430         NULL,                       /* descrsetfunc tp_descr_set; */
431         0,                          /* long tp_dictoffset; */
432         NULL,                       /* initproc tp_init; */
433         NULL,                       /* allocfunc tp_alloc; */
434         NULL,                                           /* newfunc tp_new; */
435         /*  Low-level free-memory routine */
436         NULL,                       /* freefunc tp_free;  */
437         /* For PyObject_IS_GC */
438         NULL,                       /* inquiry tp_is_gc;  */
439         NULL,                       /* PyObject *tp_bases; */
440         /* method resolution order */
441         NULL,                       /* PyObject *tp_mro;  */
442         NULL,                       /* PyObject *tp_cache; */
443         NULL,                       /* PyObject *tp_subclasses; */
444         NULL,                       /* PyObject *tp_weaklist; */
445         NULL
446 };
447
448 PyObject *pyop_base_CreatePyObject( bContext *C )
449 {
450         BPy_OperatorBase *pyop;
451
452         pyop = ( BPy_OperatorBase * ) PyObject_NEW( BPy_OperatorBase, &pyop_base_Type );
453
454         if( !pyop ) {
455                 PyErr_SetString( PyExc_MemoryError, "couldn't create BPy_OperatorBase object" );
456                 return NULL;
457         }
458
459         pyop->C = C; /* TODO - copy this? */
460
461         return ( PyObject * ) pyop;
462 }
463
464 PyObject *pyop_func_CreatePyObject( bContext *C, char *name )
465 {
466         BPy_OperatorFunc *pyop;
467
468         pyop = ( BPy_OperatorFunc * ) PyObject_NEW( BPy_OperatorFunc, &pyop_func_Type );
469
470         if( !pyop ) {
471                 PyErr_SetString( PyExc_MemoryError, "couldn't create BPy_OperatorFunc object" );
472                 return NULL;
473         }
474
475         strcpy(pyop->name, name);
476         pyop->C= C; /* TODO - how should contexts be dealt with? */
477
478         return ( PyObject * ) pyop;
479 }
480
481 PyObject *BPY_operator_module( bContext *C )
482 {
483         if( PyType_Ready( &pyop_base_Type ) < 0 )
484                 return NULL;
485
486         if( PyType_Ready( &pyop_func_Type ) < 0 )
487                 return NULL;
488
489         //submodule = Py_InitModule3( "operator", M_rna_methods, "rna module" );
490         return pyop_base_CreatePyObject(C);
491 }
492
493
494