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