4 * ***** BEGIN GPL LICENSE BLOCK *****
6 * This program is free software; you can redistribute it and/or
7 * modify it under the terms of the GNU General Public License
8 * as published by the Free Software Foundation; either version 2
9 * of the License, or (at your option) any later version.
11 * This program is distributed in the hope that it will be useful,
12 * but WITHOUT ANY WARRANTY; without even the implied warranty of
13 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
14 * GNU General Public License for more details.
16 * You should have received a copy of the GNU General Public License
17 * along with this program; if not, write to the Free Software Foundation,
18 * Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
20 * Contributor(s): Campbell Barton
22 * ***** END GPL LICENSE BLOCK *****
26 #include "bpy_compat.h"
28 //#include "blendef.h"
29 #include "BLI_dynstr.h"
30 #include "BLI_listbase.h"
31 #include "BLI_string.h"
32 #include "float.h" /* FLT_MIN/MAX */
34 #include "RNA_access.h"
35 #include "RNA_define.h" /* for defining our own rna */
37 #include "MEM_guardedalloc.h"
38 #include "BKE_context.h"
39 #include "BKE_global.h" /* evil G.* */
40 #include "BKE_report.h"
45 #include "../generic/Mathutils.h" /* so we can have mathutils callbacks */
47 /* bpyrna vector callbacks */
48 static int mathutils_rna_vector_cb_index= -1; /* index for our callbacks */
50 static int mathutils_rna_generic_check(BPy_PropertyRNA *self)
52 return self->prop?1:0;
55 static int mathutils_rna_vector_get(BPy_PropertyRNA *self, int subtype, float *vec_from)
60 RNA_property_float_get_array(&self->ptr, self->prop, vec_from);
64 static int mathutils_rna_vector_set(BPy_PropertyRNA *self, int subtype, float *vec_to)
69 RNA_property_float_set_array(&self->ptr, self->prop, vec_to);
73 static int mathutils_rna_vector_get_index(BPy_PropertyRNA *self, int subtype, float *vec_from, int index)
78 vec_from[index]= RNA_property_float_get_index(&self->ptr, self->prop, index);
82 static int mathutils_rna_vector_set_index(BPy_PropertyRNA *self, int subtype, float *vec_to, int index)
87 RNA_property_float_set_index(&self->ptr, self->prop, index, vec_to[index]);
91 Mathutils_Callback mathutils_rna_vector_cb = {
92 mathutils_rna_generic_check,
93 mathutils_rna_vector_get,
94 mathutils_rna_vector_set,
95 mathutils_rna_vector_get_index,
96 mathutils_rna_vector_set_index
99 /* bpyrna matrix callbacks */
100 static int mathutils_rna_matrix_cb_index= -1; /* index for our callbacks */
102 static int mathutils_rna_matrix_get(BPy_PropertyRNA *self, int subtype, float *mat_from)
107 RNA_property_float_get_array(&self->ptr, self->prop, mat_from);
111 static int mathutils_rna_matrix_set(BPy_PropertyRNA *self, int subtype, float *mat_to)
116 RNA_property_float_set_array(&self->ptr, self->prop, mat_to);
120 Mathutils_Callback mathutils_rna_matrix_cb = {
121 mathutils_rna_generic_check,
122 mathutils_rna_matrix_get,
123 mathutils_rna_matrix_set,
130 static int pyrna_struct_compare( BPy_StructRNA * a, BPy_StructRNA * b )
132 return (a->ptr.data==b->ptr.data) ? 0 : -1;
135 static int pyrna_prop_compare( BPy_PropertyRNA * a, BPy_PropertyRNA * b )
137 return (a->prop==b->prop && a->ptr.data==b->ptr.data ) ? 0 : -1;
140 /* For some reason python3 needs these :/ */
141 static PyObject *pyrna_struct_richcmp(BPy_StructRNA * a, BPy_StructRNA * b, int op)
143 int cmp_result= -1; /* assume false */
144 if (BPy_StructRNA_Check(a) && BPy_StructRNA_Check(b)) {
145 cmp_result= pyrna_struct_compare(a, b);
148 return Py_CmpToRich(op, cmp_result);
151 static PyObject *pyrna_prop_richcmp(BPy_PropertyRNA * a, BPy_PropertyRNA * b, int op)
153 int cmp_result= -1; /* assume false */
154 if (BPy_PropertyRNA_Check(a) && BPy_PropertyRNA_Check(b)) {
155 cmp_result= pyrna_prop_compare(a, b);
158 return Py_CmpToRich(op, cmp_result);
161 /*----------------------repr--------------------------------------------*/
162 static PyObject *pyrna_struct_repr( BPy_StructRNA * self )
167 /* print name if available */
168 name= RNA_struct_name_get_alloc(&self->ptr, NULL, 0);
170 pyob= PyUnicode_FromFormat( "[BPy_StructRNA \"%s\" -> \"%s\"]", RNA_struct_identifier(self->ptr.type), name);
175 return PyUnicode_FromFormat( "[BPy_StructRNA \"%s\"]", RNA_struct_identifier(self->ptr.type));
178 static PyObject *pyrna_prop_repr( BPy_PropertyRNA * self )
184 /* if a pointer, try to print name of pointer target too */
185 if(RNA_property_type(self->prop) == PROP_POINTER) {
186 ptr= RNA_property_pointer_get(&self->ptr, self->prop);
187 name= RNA_struct_name_get_alloc(&ptr, NULL, 0);
190 pyob= PyUnicode_FromFormat( "[BPy_PropertyRNA \"%s\" -> \"%s\" -> \"%s\" ]", RNA_struct_identifier(self->ptr.type), RNA_property_identifier(self->prop), name);
196 return PyUnicode_FromFormat( "[BPy_PropertyRNA \"%s\" -> \"%s\"]", RNA_struct_identifier(self->ptr.type), RNA_property_identifier(self->prop));
199 static long pyrna_struct_hash( BPy_StructRNA * self )
201 return (long)self->ptr.data;
204 /* use our own dealloc so we can free a property if we use one */
205 static void pyrna_struct_dealloc( BPy_StructRNA * self )
207 /* Note!! for some weired reason calling PyObject_DEL() directly crashes blender! */
208 if (self->freeptr && self->ptr.data) {
209 IDP_FreeProperty(self->ptr.data);
210 MEM_freeN(self->ptr.data);
211 self->ptr.data= NULL;
214 Py_TYPE(self)->tp_free(self);
218 static char *pyrna_enum_as_string(PointerRNA *ptr, PropertyRNA *prop)
220 const EnumPropertyItem *item;
222 RNA_property_enum_items(ptr, prop, &item, NULL);
223 return (char*)BPy_enum_as_string((EnumPropertyItem*)item);
226 PyObject * pyrna_prop_to_py(PointerRNA *ptr, PropertyRNA *prop)
229 int type = RNA_property_type(prop);
230 int len = RNA_property_array_length(prop);
233 /* resolve the array from a new pytype */
234 PyObject *ret = pyrna_prop_CreatePyObject(ptr, prop);
237 /* return a mathutils vector where possible */
238 if(RNA_property_type(prop)==PROP_FLOAT) {
239 if(RNA_property_subtype(prop)==PROP_VECTOR) {
240 if(len>=2 && len <= 4) {
241 PyObject *vec_cb= newVectorObject_cb(ret, len, mathutils_rna_vector_cb_index, 0);
242 Py_DECREF(ret); /* the vector owns now */
243 ret= vec_cb; /* return the vector instead */
246 else if(RNA_property_subtype(prop)==PROP_MATRIX) {
248 PyObject *mat_cb= newMatrixObject_cb(ret, 4,4, mathutils_rna_vector_cb_index, 0);
249 Py_DECREF(ret); /* the matrix owns now */
250 ret= mat_cb; /* return the matrix instead */
253 PyObject *mat_cb= newMatrixObject_cb(ret, 3,3, mathutils_rna_vector_cb_index, 0);
254 Py_DECREF(ret); /* the matrix owns now */
255 ret= mat_cb; /* return the matrix instead */
265 /* see if we can coorce into a python type - PropertyType */
268 ret = PyBool_FromLong( RNA_property_boolean_get(ptr, prop) );
271 ret = PyLong_FromSsize_t( (Py_ssize_t)RNA_property_int_get(ptr, prop) );
274 ret = PyFloat_FromDouble( RNA_property_float_get(ptr, prop) );
279 buf = RNA_property_string_get_alloc(ptr, prop, NULL, -1);
280 ret = PyUnicode_FromString( buf );
286 const char *identifier;
287 int val = RNA_property_enum_get(ptr, prop);
289 if (RNA_property_enum_identifier(ptr, prop, val, &identifier)) {
290 ret = PyUnicode_FromString( identifier );
292 PyErr_Format(PyExc_AttributeError, "RNA Error: Current value \"%d\" matches no enum", val);
301 newptr= RNA_property_pointer_get(ptr, prop);
303 ret = pyrna_struct_CreatePyObject(&newptr);
310 case PROP_COLLECTION:
311 ret = pyrna_prop_CreatePyObject(ptr, prop);
314 PyErr_Format(PyExc_AttributeError, "RNA Error: unknown type \"%d\" (pyrna_prop_to_py)", type);
322 /* This function is only used by operators right now
323 * Its used for taking keyword args and filling in property values */
324 int pyrna_pydict_to_props(PointerRNA *ptr, PyObject *kw, const char *error_prefix)
328 const char *arg_name= NULL;
331 PropertyRNA *prop, *iterprop;
332 CollectionPropertyIterator iter;
334 iterprop= RNA_struct_iterator_property(ptr->type);
335 RNA_property_collection_begin(ptr, iterprop, &iter);
337 totkw = kw ? PyDict_Size(kw):0;
339 for(; iter.valid; RNA_property_collection_next(&iter)) {
342 arg_name= RNA_property_identifier(prop);
344 if (strcmp(arg_name, "rna_type")==0) continue;
347 PyErr_Format( PyExc_AttributeError, "%s: no keywords, expected \"%s\"", error_prefix, arg_name ? arg_name : "<UNKNOWN>");
352 item= PyDict_GetItemString(kw, arg_name);
355 PyErr_Format( PyExc_AttributeError, "%s: keyword \"%s\" missing", error_prefix, arg_name ? arg_name : "<UNKNOWN>");
356 error_val = -1; /* pyrna_py_to_prop sets the error */
360 if (pyrna_py_to_prop(ptr, prop, NULL, item)) {
368 RNA_property_collection_end(&iter);
370 if (error_val==0 && totkw > 0) { /* some keywords were given that were not used :/ */
371 PyObject *key, *value;
374 while (PyDict_Next(kw, &pos, &key, &value)) {
375 arg_name= _PyUnicode_AsString(key);
376 if (RNA_struct_find_property(ptr, arg_name) == NULL) break;
380 PyErr_Format( PyExc_AttributeError, "%s: keyword \"%s\" unrecognized", error_prefix, arg_name ? arg_name : "<UNKNOWN>");
387 static PyObject * pyrna_func_call(PyObject * self, PyObject *args, PyObject *kw);
389 PyObject *pyrna_func_to_py(PointerRNA *ptr, FunctionRNA *func)
391 static PyMethodDef func_meth = {"<generic rna function>", (PyCFunction)pyrna_func_call, METH_VARARGS|METH_KEYWORDS, "python rna function"};
392 PyObject *self= PyTuple_New(2);
394 PyTuple_SET_ITEM(self, 0, pyrna_struct_CreatePyObject(ptr));
395 PyTuple_SET_ITEM(self, 1, PyCObject_FromVoidPtr((void *)func, NULL));
397 ret= PyCFunction_New(&func_meth, self);
404 int pyrna_py_to_prop(PointerRNA *ptr, PropertyRNA *prop, void *data, PyObject *value)
406 /* XXX hard limits should be checked here */
407 int type = RNA_property_type(prop);
408 int len = RNA_property_array_length(prop);
417 if(MatrixObject_Check(value)) {
418 MatrixObject *mat = (MatrixObject*)value;
419 if(!Matrix_ReadCallback(mat))
422 py_len = mat->rowSize * mat->colSize;
423 } else // continue...
425 if (PySequence_Check(value)) {
426 py_len= (int)PySequence_Length(value);
429 PyErr_SetString(PyExc_TypeError, "expected a python sequence type assigned to an RNA array.");
432 /* done getting the length */
435 PyErr_SetString(PyExc_AttributeError, "python sequence length did not match the RNA array.");
439 /* for arrays we have a limited number of types */
444 if(data) param_arr= (int*)data;
445 else param_arr= MEM_mallocN(sizeof(char) * len, "pyrna bool array");
448 /* collect the variables before assigning, incase one of them is incorrect */
449 for (i=0; i<len; i++) {
450 item = PySequence_GetItem(value, i);
451 param_arr[i] = PyObject_IsTrue( item );
454 if (param_arr[i] < 0) {
456 MEM_freeN(param_arr);
457 PyErr_SetString(PyExc_AttributeError, "one or more of the values in the sequence is not a boolean");
462 RNA_property_boolean_set_array(ptr, prop, param_arr);
463 MEM_freeN(param_arr);
471 if(data) param_arr= (int*)data;
472 else param_arr= MEM_mallocN(sizeof(int) * len, "pyrna int array");
475 /* collect the variables */
476 for (i=0; i<len; i++) {
477 item = PySequence_GetItem(value, i);
478 param_arr[i] = (int)PyLong_AsSsize_t(item); /* deal with any errors later */
482 if (PyErr_Occurred()) {
484 MEM_freeN(param_arr);
485 PyErr_SetString(PyExc_AttributeError, "one or more of the values in the sequence could not be used as an int");
489 RNA_property_int_set_array(ptr, prop, param_arr);
490 MEM_freeN(param_arr);
497 if(data) param_arr = (float*)data;
498 else param_arr = MEM_mallocN(sizeof(float) * len, "pyrna float array");
502 if(MatrixObject_Check(value) && RNA_property_subtype(prop) == PROP_MATRIX) {
503 MatrixObject *mat = (MatrixObject*)value;
504 memcpy(param_arr, mat->contigPtr, sizeof(float) * len);
505 } else // continue...
508 /* collect the variables */
509 for (i=0; i<len; i++) {
510 item = PySequence_GetItem(value, i);
511 param_arr[i] = (float)PyFloat_AsDouble(item); /* deal with any errors later */
516 if (PyErr_Occurred()) {
518 MEM_freeN(param_arr);
519 PyErr_SetString(PyExc_AttributeError, "one or more of the values in the sequence could not be used as a float");
523 RNA_property_float_set_array(ptr, prop, param_arr);
524 MEM_freeN(param_arr);
530 /* Normal Property (not an array) */
532 /* see if we can coorce into a python type - PropertyType */
536 int param = PyObject_IsTrue( value );
539 PyErr_SetString(PyExc_TypeError, "expected True/False or 0/1");
542 if(data) *((int*)data)= param;
543 else RNA_property_boolean_set(ptr, prop, param);
549 int param = PyLong_AsSsize_t(value);
550 if (PyErr_Occurred()) {
551 PyErr_SetString(PyExc_TypeError, "expected an int type");
554 if(data) *((int*)data)= param;
555 else RNA_property_int_set(ptr, prop, param);
561 float param = PyFloat_AsDouble(value);
562 if (PyErr_Occurred()) {
563 PyErr_SetString(PyExc_TypeError, "expected a float type");
566 if(data) *((float*)data)= param;
567 else RNA_property_float_set(ptr, prop, param);
573 char *param = _PyUnicode_AsString(value);
576 PyErr_SetString(PyExc_TypeError, "expected a string type");
579 if(data) *((char**)data)= param;
580 else RNA_property_string_set(ptr, prop, param);
586 char *param = _PyUnicode_AsString(value);
589 char *enum_str= pyrna_enum_as_string(ptr, prop);
590 PyErr_Format(PyExc_TypeError, "expected a string enum type in (%s)", enum_str);
595 if (RNA_property_enum_value(ptr, prop, param, &val)) {
596 if(data) *((int*)data)= val;
597 else RNA_property_enum_set(ptr, prop, val);
599 char *enum_str= pyrna_enum_as_string(ptr, prop);
600 PyErr_Format(PyExc_AttributeError, "enum \"%s\" not found in (%s)", param, enum_str);
610 StructRNA *ptype= RNA_property_pointer_type(ptr, prop);
612 if(!BPy_StructRNA_Check(value) && value != Py_None) {
614 RNA_pointer_create(NULL, ptype, NULL, &tmp);
615 PyErr_Format(PyExc_TypeError, "expected a %s type", RNA_struct_identifier(tmp.type));
618 BPy_StructRNA *param= (BPy_StructRNA*)value;
621 int flag = RNA_property_flag(prop);
623 if(flag & PROP_RNAPTR) {
625 memset(data, 0, sizeof(PointerRNA));
627 *((PointerRNA*)data)= param->ptr;
629 else if(value == Py_None) {
630 *((void**)data)= NULL;
632 else if(RNA_struct_is_a(param->ptr.type, ptype)) {
633 *((void**)data)= param->ptr.data;
640 /* data==NULL, assign to RNA */
641 if(value == Py_None) {
643 memset(&valueptr, 0, sizeof(valueptr));
644 RNA_property_pointer_set(ptr, prop, valueptr);
646 else if(RNA_struct_is_a(param->ptr.type, ptype)) {
647 RNA_property_pointer_set(ptr, prop, param->ptr);
651 RNA_pointer_create(NULL, ptype, NULL, &tmp);
652 PyErr_Format(PyExc_TypeError, "expected a %s type", RNA_struct_identifier(tmp.type));
659 RNA_pointer_create(NULL, ptype, NULL, &tmp);
660 PyErr_Format(PyExc_TypeError, "expected a %s type", RNA_struct_identifier(tmp.type));
666 case PROP_COLLECTION:
672 /* convert a sequence of dict's into a collection */
673 if(!PySequence_Check(value)) {
674 PyErr_SetString(PyExc_TypeError, "expected a sequence of dicts for an RNA collection");
678 seq_len = PySequence_Length(value);
679 for(i=0; i<seq_len; i++) {
680 item= PySequence_GetItem(value, i);
681 if(item==NULL || PyDict_Check(item)==0) {
682 PyErr_SetString(PyExc_TypeError, "expected a sequence of dicts for an RNA collection");
687 RNA_property_collection_add(ptr, prop, &itemptr);
688 if(pyrna_pydict_to_props(&itemptr, item, "Converting a python list to an RNA collection")==-1) {
698 PyErr_SetString(PyExc_AttributeError, "unknown property type (pyrna_py_to_prop)");
707 static PyObject * pyrna_prop_to_py_index(PointerRNA *ptr, PropertyRNA *prop, int index)
710 int type = RNA_property_type(prop);
712 /* see if we can coorce into a python type - PropertyType */
715 ret = PyBool_FromLong( RNA_property_boolean_get_index(ptr, prop, index) );
718 ret = PyLong_FromSsize_t( (Py_ssize_t)RNA_property_int_get_index(ptr, prop, index) );
721 ret = PyFloat_FromDouble( RNA_property_float_get_index(ptr, prop, index) );
724 PyErr_SetString(PyExc_AttributeError, "not an array type");
732 static int pyrna_py_to_prop_index(PointerRNA *ptr, PropertyRNA *prop, int index, PyObject *value)
735 int type = RNA_property_type(prop);
737 /* see if we can coorce into a python type - PropertyType */
741 int param = PyObject_IsTrue( value );
744 PyErr_SetString(PyExc_TypeError, "expected True/False or 0/1");
747 RNA_property_boolean_set_index(ptr, prop, index, param);
753 int param = PyLong_AsSsize_t(value);
754 if (PyErr_Occurred()) {
755 PyErr_SetString(PyExc_TypeError, "expected an int type");
758 RNA_property_int_set_index(ptr, prop, index, param);
764 float param = PyFloat_AsDouble(value);
765 if (PyErr_Occurred()) {
766 PyErr_SetString(PyExc_TypeError, "expected a float type");
769 RNA_property_float_set_index(ptr, prop, index, param);
774 PyErr_SetString(PyExc_AttributeError, "not an array type");
782 //---------------sequence-------------------------------------------
783 static Py_ssize_t pyrna_prop_len( BPy_PropertyRNA * self )
787 if (RNA_property_type(self->prop) == PROP_COLLECTION) {
788 len = RNA_property_collection_length(&self->ptr, self->prop);
790 len = RNA_property_array_length(self->prop);
792 if (len==0) { /* not an array*/
793 PyErr_SetString(PyExc_AttributeError, "len() only available for collection RNA types");
801 static PyObject *pyrna_prop_subscript( BPy_PropertyRNA * self, PyObject *key )
806 char *keyname = NULL;
808 if (PyUnicode_Check(key)) {
809 keyname = _PyUnicode_AsString(key);
810 } else if (PyLong_Check(key)) {
811 keynum = PyLong_AsSsize_t(key);
813 PyErr_SetString(PyExc_AttributeError, "invalid key, key must be a string or an int");
817 if (RNA_property_type(self->prop) == PROP_COLLECTION) {
819 if (keyname) ok = RNA_property_collection_lookup_string(&self->ptr, self->prop, keyname, &newptr);
820 else ok = RNA_property_collection_lookup_int(&self->ptr, self->prop, keynum, &newptr);
823 ret = pyrna_struct_CreatePyObject(&newptr);
825 PyErr_SetString(PyExc_AttributeError, "out of range");
829 } else if (keyname) {
830 PyErr_SetString(PyExc_AttributeError, "string keys are only supported for collections");
833 int len = RNA_property_array_length(self->prop);
835 if (len==0) { /* not an array*/
836 PyErr_Format(PyExc_AttributeError, "not an array or collection %d", keynum);
841 PyErr_SetString(PyExc_AttributeError, "index out of range");
843 } else { /* not an array*/
844 ret = pyrna_prop_to_py_index(&self->ptr, self->prop, keynum);
852 static int pyrna_prop_assign_subscript( BPy_PropertyRNA * self, PyObject *key, PyObject *value )
856 char *keyname = NULL;
858 if (!RNA_property_editable(&self->ptr, self->prop)) {
859 PyErr_Format( PyExc_AttributeError, "PropertyRNA - attribute \"%s\" from \"%s\" is read-only", RNA_property_identifier(self->prop), RNA_struct_identifier(self->ptr.type) );
863 if (PyUnicode_Check(key)) {
864 keyname = _PyUnicode_AsString(key);
865 } else if (PyLong_Check(key)) {
866 keynum = PyLong_AsSsize_t(key);
868 PyErr_SetString(PyExc_AttributeError, "PropertyRNA - invalid key, key must be a string or an int");
872 if (RNA_property_type(self->prop) == PROP_COLLECTION) {
873 PyErr_SetString(PyExc_AttributeError, "PropertyRNA - assignment is not supported for collections (yet)");
875 } else if (keyname) {
876 PyErr_SetString(PyExc_AttributeError, "PropertyRNA - string keys are only supported for collections");
879 int len = RNA_property_array_length(self->prop);
881 if (len==0) { /* not an array*/
882 PyErr_Format(PyExc_AttributeError, "PropertyRNA - not an array or collection %d", keynum);
887 PyErr_SetString(PyExc_AttributeError, "PropertyRNA - index out of range");
890 ret = pyrna_py_to_prop_index(&self->ptr, self->prop, keynum, value);
899 static PyMappingMethods pyrna_prop_as_mapping = {
900 ( lenfunc ) pyrna_prop_len, /* mp_length */
901 ( binaryfunc ) pyrna_prop_subscript, /* mp_subscript */
902 ( objobjargproc ) pyrna_prop_assign_subscript, /* mp_ass_subscript */
905 static int pyrna_prop_contains(BPy_PropertyRNA * self, PyObject *value)
907 PointerRNA newptr; /* not used, just so RNA_property_collection_lookup_string runs */
908 char *keyname = _PyUnicode_AsString(value);
911 PyErr_SetString(PyExc_TypeError, "PropertyRNA - key in prop, key must be a string type");
915 if (RNA_property_type(self->prop) != PROP_COLLECTION) {
916 PyErr_SetString(PyExc_TypeError, "PropertyRNA - key in prop, is only valid for collection types");
921 if (RNA_property_collection_lookup_string(&self->ptr, self->prop, keyname, &newptr))
927 static PySequenceMethods pyrna_prop_as_sequence = {
928 NULL, /* Cant set the len otherwise it can evaluate as false */
929 NULL, /* sq_concat */
930 NULL, /* sq_repeat */
933 NULL, /* sq_ass_item */
934 NULL, /* sq_ass_slice */
935 (objobjproc)pyrna_prop_contains, /* sq_contains */
938 static PyObject *pyrna_struct_dir(BPy_StructRNA * self)
940 PyObject *ret, *dict;
943 /* for looping over attrs and funcs */
944 CollectionPropertyIterator iter;
945 PropertyRNA *iterprop;
947 /* Include this incase this instance is a subtype of a python class
948 * In these instances we may want to return a function or variable provided by the subtype
951 if (BPy_StructRNA_CheckExact(self)) {
954 pystring = PyUnicode_FromString("__dict__");
955 dict = PyObject_GenericGetAttr((PyObject *)self, pystring);
963 ret = PyDict_Keys(dict);
968 /* Collect RNA items*/
971 * Collect RNA attributes
973 char name[256], *nameptr;
975 iterprop= RNA_struct_iterator_property(self->ptr.type);
976 RNA_property_collection_begin(&self->ptr, iterprop, &iter);
978 for(; iter.valid; RNA_property_collection_next(&iter)) {
979 nameptr= RNA_struct_name_get_alloc(&iter.ptr, name, sizeof(name));
982 pystring = PyUnicode_FromString(nameptr);
983 PyList_Append(ret, pystring);
990 RNA_property_collection_end(&iter);
997 * Collect RNA function items
1001 RNA_pointer_create(NULL, &RNA_Struct, self->ptr.type, &tptr);
1002 iterprop= RNA_struct_find_property(&tptr, "functions");
1004 RNA_property_collection_begin(&tptr, iterprop, &iter);
1006 for(; iter.valid; RNA_property_collection_next(&iter)) {
1007 pystring = PyUnicode_FromString(RNA_function_identifier(iter.ptr.data));
1008 PyList_Append(ret, pystring);
1009 Py_DECREF(pystring);
1012 RNA_property_collection_end(&iter);
1015 if(self->ptr.type == &RNA_Context) {
1016 ListBase lb = CTX_data_dir_get(self->ptr.data);
1019 for(link=lb.first; link; link=link->next) {
1020 pystring = PyUnicode_FromString(link->data);
1021 PyList_Append(ret, pystring);
1022 Py_DECREF(pystring);
1032 //---------------getattr--------------------------------------------
1033 static PyObject *pyrna_struct_getattro( BPy_StructRNA * self, PyObject *pyname )
1035 char *name = _PyUnicode_AsString(pyname);
1040 /* Include this incase this instance is a subtype of a python class
1041 * In these instances we may want to return a function or variable provided by the subtype
1043 * Also needed to return methods when its not a subtype
1045 ret = PyObject_GenericGetAttr((PyObject *)self, pyname);
1046 if (ret) return ret;
1048 /* done with subtypes */
1050 if ((prop = RNA_struct_find_property(&self->ptr, name))) {
1051 ret = pyrna_prop_to_py(&self->ptr, prop);
1053 else if ((func = RNA_struct_find_function(&self->ptr, name))) {
1054 ret = pyrna_func_to_py(&self->ptr, func);
1056 else if (self->ptr.type == &RNA_Context) {
1060 CTX_data_get(self->ptr.data, name, &newptr, &newlb);
1063 ret = pyrna_struct_CreatePyObject(&newptr);
1065 else if (newlb.first) {
1066 CollectionPointerLink *link;
1069 ret = PyList_New(0);
1071 for(link=newlb.first; link; link=link->next) {
1072 linkptr= pyrna_struct_CreatePyObject(&link->ptr);
1073 PyList_Append(ret, linkptr);
1082 BLI_freelistN(&newlb);
1085 PyErr_Format( PyExc_AttributeError, "StructRNA - Attribute \"%s\" not found", name);
1092 //--------------- setattr-------------------------------------------
1093 static int pyrna_struct_setattro( BPy_StructRNA * self, PyObject *pyname, PyObject * value )
1095 char *name = _PyUnicode_AsString(pyname);
1096 PropertyRNA *prop = RNA_struct_find_property(&self->ptr, name);
1099 if (!BPy_StructRNA_CheckExact(self) && PyObject_GenericSetAttr((PyObject *)self, pyname, value) >= 0) {
1103 PyErr_Format( PyExc_AttributeError, "StructRNA - Attribute \"%s\" not found", name);
1108 if (!RNA_property_editable(&self->ptr, prop)) {
1109 PyErr_Format( PyExc_AttributeError, "StructRNA - Attribute \"%s\" from \"%s\" is read-only", RNA_property_identifier(prop), RNA_struct_identifier(self->ptr.type) );
1113 /* pyrna_py_to_prop sets its own exceptions */
1114 return pyrna_py_to_prop(&self->ptr, prop, NULL, value);
1117 PyObject *pyrna_prop_keys(BPy_PropertyRNA *self)
1120 if (RNA_property_type(self->prop) != PROP_COLLECTION) {
1121 PyErr_SetString( PyExc_TypeError, "keys() is only valid for collection types" );
1125 CollectionPropertyIterator iter;
1126 PropertyRNA *nameprop;
1127 char name[256], *nameptr;
1129 ret = PyList_New(0);
1131 RNA_property_collection_begin(&self->ptr, self->prop, &iter);
1132 for(; iter.valid; RNA_property_collection_next(&iter)) {
1133 nameptr= RNA_struct_name_get_alloc(&iter.ptr, name, sizeof(name));
1136 nameptr= RNA_property_string_get_alloc(&iter.ptr, nameprop, name, sizeof(name));
1138 /* add to python list */
1139 item = PyUnicode_FromString( nameptr );
1140 PyList_Append(ret, item);
1148 RNA_property_collection_end(&iter);
1154 PyObject *pyrna_prop_items(BPy_PropertyRNA *self)
1157 if (RNA_property_type(self->prop) != PROP_COLLECTION) {
1158 PyErr_SetString( PyExc_TypeError, "items() is only valid for collection types" );
1162 CollectionPropertyIterator iter;
1163 char name[256], *nameptr;
1166 ret = PyList_New(0);
1168 RNA_property_collection_begin(&self->ptr, self->prop, &iter);
1169 for(; iter.valid; RNA_property_collection_next(&iter)) {
1171 /* add to python list */
1172 item= PyTuple_New(2);
1173 nameptr= RNA_struct_name_get_alloc(&iter.ptr, name, sizeof(name));
1175 PyTuple_SET_ITEM(item, 0, PyUnicode_FromString( nameptr ));
1180 PyTuple_SET_ITEM(item, 0, PyLong_FromSsize_t(i)); /* a bit strange but better then returning an empty list */
1182 PyTuple_SET_ITEM(item, 1, pyrna_struct_CreatePyObject(&iter.ptr));
1184 PyList_Append(ret, item);
1190 RNA_property_collection_end(&iter);
1197 PyObject *pyrna_prop_values(BPy_PropertyRNA *self)
1201 if (RNA_property_type(self->prop) != PROP_COLLECTION) {
1202 PyErr_SetString( PyExc_TypeError, "values() is only valid for collection types" );
1206 CollectionPropertyIterator iter;
1207 ret = PyList_New(0);
1209 RNA_property_collection_begin(&self->ptr, self->prop, &iter);
1210 for(; iter.valid; RNA_property_collection_next(&iter)) {
1211 item = pyrna_struct_CreatePyObject(&iter.ptr);
1212 PyList_Append(ret, item);
1215 RNA_property_collection_end(&iter);
1221 /* A bit of a kludge, make a list out of a collection or array,
1222 * then return the lists iter function, not especially fast but convenient for now */
1223 PyObject *pyrna_prop_iter(BPy_PropertyRNA *self)
1225 /* Try get values from a collection */
1226 PyObject *ret = pyrna_prop_values(self);
1229 /* collection did not work, try array */
1230 int len = RNA_property_array_length(self->prop);
1235 ret = PyList_New(len);
1237 for (i=0; i < len; i++) {
1238 PyList_SET_ITEM(ret, i, pyrna_prop_to_py_index(&self->ptr, self->prop, i));
1244 /* we know this is a list so no need to PyIter_Check */
1245 PyObject *iter = PyObject_GetIter(ret);
1250 PyErr_SetString( PyExc_TypeError, "this BPy_PropertyRNA object is not iterable" );
1254 static struct PyMethodDef pyrna_struct_methods[] = {
1255 {"__dir__", (PyCFunction)pyrna_struct_dir, METH_NOARGS, ""},
1256 {NULL, NULL, 0, NULL}
1259 static struct PyMethodDef pyrna_prop_methods[] = {
1260 {"keys", (PyCFunction)pyrna_prop_keys, METH_NOARGS, ""},
1261 {"items", (PyCFunction)pyrna_prop_items, METH_NOARGS, ""},
1262 {"values", (PyCFunction)pyrna_prop_values, METH_NOARGS, ""},
1263 {NULL, NULL, 0, NULL}
1266 /* only needed for subtyping, so a new class gets a valid BPy_StructRNA
1267 * todo - also accept useful args */
1268 static PyObject * pyrna_struct_new(PyTypeObject *type, PyObject *args, PyObject *kwds) {
1270 BPy_StructRNA *base = NULL;
1272 if (!PyArg_ParseTuple(args, "O!:Base BPy_StructRNA", &pyrna_struct_Type, &base))
1275 if (type == &pyrna_struct_Type) {
1276 return pyrna_struct_CreatePyObject(&base->ptr);
1278 BPy_StructRNA *ret = (BPy_StructRNA *) type->tp_alloc(type, 0);
1279 ret->ptr = base->ptr;
1280 return (PyObject *)ret;
1284 /* only needed for subtyping, so a new class gets a valid BPy_StructRNA
1285 * todo - also accept useful args */
1286 static PyObject * pyrna_prop_new(PyTypeObject *type, PyObject *args, PyObject *kwds) {
1288 BPy_PropertyRNA *base = NULL;
1290 if (!PyArg_ParseTuple(args, "O!:Base BPy_PropertyRNA", &pyrna_prop_Type, &base))
1293 if (type == &pyrna_prop_Type) {
1294 return pyrna_prop_CreatePyObject(&base->ptr, base->prop);
1296 BPy_PropertyRNA *ret = (BPy_PropertyRNA *) type->tp_alloc(type, 0);
1297 ret->ptr = base->ptr;
1298 ret->prop = base->prop;
1299 return (PyObject *)ret;
1303 PyObject *pyrna_param_to_py(PointerRNA *ptr, PropertyRNA *prop, void *data)
1306 int type = RNA_property_type(prop);
1307 int len = RNA_property_array_length(prop);
1312 /* resolve the array from a new pytype */
1313 ret = PyTuple_New(len);
1317 for(a=0; a<len; a++)
1318 PyTuple_SET_ITEM(ret, a, PyBool_FromLong( ((int*)data)[a] ));
1321 for(a=0; a<len; a++)
1322 PyTuple_SET_ITEM(ret, a, PyLong_FromSsize_t( (Py_ssize_t)((int*)data)[a] ));
1325 for(a=0; a<len; a++)
1326 PyTuple_SET_ITEM(ret, a, PyFloat_FromDouble( ((float*)data)[a] ));
1329 PyErr_Format(PyExc_AttributeError, "RNA Error: unknown array type \"%d\" (pyrna_param_to_py)", type);
1335 /* see if we can coorce into a python type - PropertyType */
1338 ret = PyBool_FromLong( *(int*)data );
1341 ret = PyLong_FromSsize_t( (Py_ssize_t)*(int*)data );
1344 ret = PyFloat_FromDouble( *(float*)data );
1348 ret = PyUnicode_FromString( *(char**)data );
1353 const char *identifier;
1354 int val = *(int*)data;
1356 if (RNA_property_enum_identifier(ptr, prop, val, &identifier)) {
1357 ret = PyUnicode_FromString( identifier );
1359 PyErr_Format(PyExc_AttributeError, "RNA Error: Current value \"%d\" matches no enum", val);
1368 StructRNA *type= RNA_property_pointer_type(ptr, prop);
1369 int flag = RNA_property_flag(prop);
1371 if(flag & PROP_RNAPTR) {
1372 /* in this case we get the full ptr */
1373 newptr= *(PointerRNA*)data;
1376 /* XXX this is missing the ID part! */
1377 RNA_pointer_create(NULL, type, *(void**)data, &newptr);
1381 ret = pyrna_struct_CreatePyObject(&newptr);
1388 case PROP_COLLECTION:
1389 /* XXX not supported yet
1390 * ret = pyrna_prop_CreatePyObject(ptr, prop); */
1394 PyErr_Format(PyExc_AttributeError, "RNA Error: unknown type \"%d\" (pyrna_param_to_py)", type);
1403 static PyObject * pyrna_func_call(PyObject * self, PyObject *args, PyObject *kw)
1405 PointerRNA *self_ptr= &(((BPy_StructRNA *)PyTuple_GET_ITEM(self, 0))->ptr);
1406 FunctionRNA *self_func= PyCObject_AsVoidPtr(PyTuple_GET_ITEM(self, 1));
1409 ParameterList *parms;
1410 ParameterIterator iter;
1411 PropertyRNA *pret, *parm;
1412 PyObject *ret, *item;
1413 int i, tlen, flag, err= 0;
1414 const char *tid, *fid, *pid;
1415 void *retdata= NULL;
1418 RNA_pointer_create(NULL, &RNA_Function, self_func, &funcptr);
1420 pret= RNA_function_return(self_func);
1421 tlen= PyTuple_GET_SIZE(args);
1423 parms= RNA_parameter_list_create(self_ptr, self_func);
1424 RNA_parameter_list_begin(parms, &iter);
1426 /* parse function parameters */
1427 for (i= 0; iter.valid; RNA_parameter_list_next(&iter)) {
1435 pid= RNA_property_identifier(parm);
1436 flag= RNA_property_flag(parm);
1439 if ((i < tlen) && (flag & PROP_REQUIRED)) {
1440 item= PyTuple_GET_ITEM(args, i);
1443 else if (kw != NULL)
1444 item= PyDict_GetItemString(kw, pid); /* borrow ref */
1447 if(flag & PROP_REQUIRED) {
1448 tid= RNA_struct_identifier(self_ptr->type);
1449 fid= RNA_function_identifier(self_func);
1451 PyErr_Format(PyExc_AttributeError, "%s.%s(): required parameter \"%s\" not specified", tid, fid, pid);
1459 err= pyrna_py_to_prop(&funcptr, parm, iter.data, item);
1469 bContext *C= BPy_GetContext();
1471 BKE_reports_init(&reports, RPT_STORE);
1472 RNA_function_call(C, &reports, self_ptr, self_func, parms);
1474 err= (BPy_reports_to_error(&reports))? -1: 0;
1475 BKE_reports_clear(&reports);
1480 ret= pyrna_param_to_py(&funcptr, pret, retdata);
1484 RNA_parameter_list_end(&iter);
1485 RNA_parameter_list_free(parms);
1496 /*-----------------------BPy_StructRNA method def------------------------------*/
1497 PyTypeObject pyrna_struct_Type = {
1498 #if (PY_VERSION_HEX >= 0x02060000)
1499 PyVarObject_HEAD_INIT(NULL, 0)
1501 /* python 2.5 and below */
1502 PyObject_HEAD_INIT( NULL ) /* required py macro */
1505 "StructRNA", /* tp_name */
1506 sizeof( BPy_StructRNA ), /* tp_basicsize */
1507 0, /* tp_itemsize */
1509 ( destructor ) pyrna_struct_dealloc,/* tp_dealloc */
1510 NULL, /* printfunc tp_print; */
1511 NULL, /* getattrfunc tp_getattr; */
1512 NULL, /* setattrfunc tp_setattr; */
1513 NULL, /* tp_compare */ /* DEPRECATED in python 3.0! */
1514 ( reprfunc ) pyrna_struct_repr, /* tp_repr */
1516 /* Method suites for standard classes */
1518 NULL, /* PyNumberMethods *tp_as_number; */
1519 NULL, /* PySequenceMethods *tp_as_sequence; */
1520 NULL, /* PyMappingMethods *tp_as_mapping; */
1522 /* More standard operations (here for binary compatibility) */
1524 ( hashfunc )pyrna_struct_hash, /* hashfunc tp_hash; */
1525 NULL, /* ternaryfunc tp_call; */
1526 NULL, /* reprfunc tp_str; */
1527 ( getattrofunc ) pyrna_struct_getattro, /* getattrofunc tp_getattro; */
1528 ( setattrofunc ) pyrna_struct_setattro, /* setattrofunc tp_setattro; */
1530 /* Functions to access object as input/output buffer */
1531 NULL, /* PyBufferProcs *tp_as_buffer; */
1533 /*** Flags to define presence of optional/expanded features ***/
1534 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE, /* long tp_flags; */
1536 NULL, /* char *tp_doc; Documentation string */
1537 /*** Assigned meaning in release 2.0 ***/
1538 /* call function for all accessible objects */
1539 NULL, /* traverseproc tp_traverse; */
1541 /* delete references to contained objects */
1542 NULL, /* inquiry tp_clear; */
1544 /*** Assigned meaning in release 2.1 ***/
1545 /*** rich comparisons ***/
1546 (richcmpfunc)pyrna_struct_richcmp, /* richcmpfunc tp_richcompare; */
1548 /*** weak reference enabler ***/
1549 0, /* long tp_weaklistoffset; */
1551 /*** Added in release 2.2 ***/
1553 NULL, /* getiterfunc tp_iter; */
1554 NULL, /* iternextfunc tp_iternext; */
1556 /*** Attribute descriptor and subclassing stuff ***/
1557 pyrna_struct_methods, /* struct PyMethodDef *tp_methods; */
1558 NULL, /* struct PyMemberDef *tp_members; */
1559 NULL, /* struct PyGetSetDef *tp_getset; */
1560 NULL, /* struct _typeobject *tp_base; */
1561 NULL, /* PyObject *tp_dict; */
1562 NULL, /* descrgetfunc tp_descr_get; */
1563 NULL, /* descrsetfunc tp_descr_set; */
1564 0, /* long tp_dictoffset; */
1565 NULL, /* initproc tp_init; */
1566 NULL, /* allocfunc tp_alloc; */
1567 pyrna_struct_new, /* newfunc tp_new; */
1568 /* Low-level free-memory routine */
1569 NULL, /* freefunc tp_free; */
1570 /* For PyObject_IS_GC */
1571 NULL, /* inquiry tp_is_gc; */
1572 NULL, /* PyObject *tp_bases; */
1573 /* method resolution order */
1574 NULL, /* PyObject *tp_mro; */
1575 NULL, /* PyObject *tp_cache; */
1576 NULL, /* PyObject *tp_subclasses; */
1577 NULL, /* PyObject *tp_weaklist; */
1581 /*-----------------------BPy_PropertyRNA method def------------------------------*/
1582 PyTypeObject pyrna_prop_Type = {
1583 #if (PY_VERSION_HEX >= 0x02060000)
1584 PyVarObject_HEAD_INIT(NULL, 0)
1586 /* python 2.5 and below */
1587 PyObject_HEAD_INIT( NULL ) /* required py macro */
1591 "PropertyRNA", /* tp_name */
1592 sizeof( BPy_PropertyRNA ), /* tp_basicsize */
1593 0, /* tp_itemsize */
1595 NULL, /* tp_dealloc */
1596 NULL, /* printfunc tp_print; */
1597 NULL, /* getattrfunc tp_getattr; */
1598 NULL, /* setattrfunc tp_setattr; */
1599 NULL, /* tp_compare */ /* DEPRECATED in python 3.0! */
1600 ( reprfunc ) pyrna_prop_repr, /* tp_repr */
1602 /* Method suites for standard classes */
1604 NULL, /* PyNumberMethods *tp_as_number; */
1605 &pyrna_prop_as_sequence, /* PySequenceMethods *tp_as_sequence; */
1606 &pyrna_prop_as_mapping, /* PyMappingMethods *tp_as_mapping; */
1608 /* More standard operations (here for binary compatibility) */
1610 NULL, /* hashfunc tp_hash; */
1611 NULL, /* ternaryfunc tp_call; */
1612 NULL, /* reprfunc tp_str; */
1613 NULL, /*PyObject_GenericGetAttr - MINGW Complains, assign later */ /* getattrofunc tp_getattro; */ /* will only use these if this is a subtype of a py class */
1614 NULL, /*PyObject_GenericSetAttr - MINGW Complains, assign later */ /* setattrofunc tp_setattro; */
1616 /* Functions to access object as input/output buffer */
1617 NULL, /* PyBufferProcs *tp_as_buffer; */
1619 /*** Flags to define presence of optional/expanded features ***/
1620 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE, /* long tp_flags; */
1622 NULL, /* char *tp_doc; Documentation string */
1623 /*** Assigned meaning in release 2.0 ***/
1624 /* call function for all accessible objects */
1625 NULL, /* traverseproc tp_traverse; */
1627 /* delete references to contained objects */
1628 NULL, /* inquiry tp_clear; */
1630 /*** Assigned meaning in release 2.1 ***/
1631 /*** rich comparisons ***/
1632 (richcmpfunc)pyrna_prop_richcmp, /* richcmpfunc tp_richcompare; */
1634 /*** weak reference enabler ***/
1635 0, /* long tp_weaklistoffset; */
1637 /*** Added in release 2.2 ***/
1639 (getiterfunc)pyrna_prop_iter, /* getiterfunc tp_iter; */
1640 NULL, /* iternextfunc tp_iternext; */
1642 /*** Attribute descriptor and subclassing stuff ***/
1643 pyrna_prop_methods, /* struct PyMethodDef *tp_methods; */
1644 NULL, /* struct PyMemberDef *tp_members; */
1645 NULL, /* struct PyGetSetDef *tp_getset; */
1646 NULL, /* struct _typeobject *tp_base; */
1647 NULL, /* PyObject *tp_dict; */
1648 NULL, /* descrgetfunc tp_descr_get; */
1649 NULL, /* descrsetfunc tp_descr_set; */
1650 0, /* long tp_dictoffset; */
1651 NULL, /* initproc tp_init; */
1652 NULL, /* allocfunc tp_alloc; */
1653 pyrna_prop_new, /* newfunc tp_new; */
1654 /* Low-level free-memory routine */
1655 NULL, /* freefunc tp_free; */
1656 /* For PyObject_IS_GC */
1657 NULL, /* inquiry tp_is_gc; */
1658 NULL, /* PyObject *tp_bases; */
1659 /* method resolution order */
1660 NULL, /* PyObject *tp_mro; */
1661 NULL, /* PyObject *tp_cache; */
1662 NULL, /* PyObject *tp_subclasses; */
1663 NULL, /* PyObject *tp_weaklist; */
1667 static void pyrna_subtype_set_rna(PyObject *newclass, StructRNA *srna)
1672 Py_INCREF(newclass);
1674 if (RNA_struct_py_type_get(srna))
1675 PyObSpit("RNA WAS SET - ", RNA_struct_py_type_get(srna));
1677 Py_XDECREF(((PyObject *)RNA_struct_py_type_get(srna)));
1679 RNA_struct_py_type_set(srna, (void *)newclass); /* Store for later use */
1681 /* Not 100% needed but useful,
1682 * having an instance within a type looks wrong however this instance IS an rna type */
1683 RNA_pointer_create(NULL, &RNA_Struct, srna, &ptr);
1684 item = pyrna_struct_CreatePyObject(&ptr);
1685 PyDict_SetItemString(((PyTypeObject *)newclass)->tp_dict, "__rna__", item);
1687 /* done with rna instance */
1690 PyObject* pyrna_struct_Subtype(PointerRNA *ptr)
1692 PyObject *newclass = NULL;
1693 PropertyRNA *nameprop;
1695 if (ptr->type==NULL) {
1696 newclass= NULL; /* Nothing to do */
1697 } else if ((newclass= RNA_struct_py_type_get(ptr->data))) {
1698 Py_INCREF(newclass);
1699 } else if ((nameprop = RNA_struct_name_property(ptr->type))) {
1700 /* for now, return the base RNA type rather then a real module */
1702 /* Assume RNA_struct_py_type_get(ptr->data) was alredy checked */
1704 /* subclass equivelents
1705 - class myClass(myBase):
1706 some='value' # or ...
1707 - myClass = type(name='myClass', bases=(myBase,), dict={'some':'value'})
1709 char name[256], *nameptr;
1710 const char *descr= RNA_struct_ui_description(ptr->type);
1712 PyObject *args = PyTuple_New(3);
1713 PyObject *bases = PyTuple_New(1);
1714 PyObject *dict = PyDict_New();
1718 nameptr= RNA_property_string_get_alloc(ptr, nameprop, name, sizeof(name));
1721 //PyTuple_SET_ITEM(args, 0, PyUnicode_FromString(tp_name));
1722 PyTuple_SET_ITEM(args, 0, PyUnicode_FromString(nameptr));
1725 PyTuple_SET_ITEM(bases, 0, (PyObject *)&pyrna_struct_Type);
1726 Py_INCREF(&pyrna_struct_Type);
1728 PyTuple_SET_ITEM(args, 1, bases);
1730 // arg 3 - add an instance of the rna
1732 item= PyUnicode_FromString(descr);
1733 PyDict_SetItemString(dict, "__doc__", item);
1737 PyTuple_SET_ITEM(args, 2, dict); // fill with useful subclass things!
1739 if (PyErr_Occurred()) {
1744 newclass = PyObject_CallObject((PyObject *)&PyType_Type, args);
1748 pyrna_subtype_set_rna(newclass, ptr->data);
1750 if (name != nameptr)
1757 /*-----------------------CreatePyObject---------------------------------*/
1758 PyObject *pyrna_struct_CreatePyObject( PointerRNA *ptr )
1760 BPy_StructRNA *pyrna= NULL;
1762 if (ptr->data==NULL && ptr->type==NULL) { /* Operator RNA has NULL data */
1766 if (ptr->type == &RNA_Struct) { /* always return a python subtype from rna struct types */
1767 PyTypeObject *tp = (PyTypeObject *)pyrna_struct_Subtype(ptr);
1770 pyrna = (BPy_StructRNA *) tp->tp_alloc(tp, 0);
1773 fprintf(stderr, "Could not make type\n");
1774 pyrna = ( BPy_StructRNA * ) PyObject_NEW( BPy_StructRNA, &pyrna_struct_Type );
1778 pyrna = ( BPy_StructRNA * ) PyObject_NEW( BPy_StructRNA, &pyrna_struct_Type );
1782 PyErr_SetString( PyExc_MemoryError, "couldn't create BPy_StructRNA object" );
1788 return ( PyObject * ) pyrna;
1791 PyObject *pyrna_prop_CreatePyObject( PointerRNA *ptr, PropertyRNA *prop )
1793 BPy_PropertyRNA *pyrna;
1795 pyrna = ( BPy_PropertyRNA * ) PyObject_NEW( BPy_PropertyRNA, &pyrna_prop_Type );
1798 PyErr_SetString( PyExc_MemoryError, "couldn't create BPy_rna object" );
1805 return ( PyObject * ) pyrna;
1808 PyObject *BPY_rna_module( void )
1812 #ifdef USE_MATHUTILS // register mathutils callbacks, ok to run more then once.
1813 mathutils_rna_vector_cb_index= Mathutils_RegisterCallback(&mathutils_rna_vector_cb);
1814 mathutils_rna_matrix_cb_index= Mathutils_RegisterCallback(&mathutils_rna_matrix_cb);
1817 /* This can't be set in the pytype struct because some compilers complain */
1818 pyrna_prop_Type.tp_getattro = PyObject_GenericGetAttr;
1819 pyrna_prop_Type.tp_setattro = PyObject_GenericSetAttr;
1821 if( PyType_Ready( &pyrna_struct_Type ) < 0 )
1824 if( PyType_Ready( &pyrna_prop_Type ) < 0 )
1827 /* for now, return the base RNA type rather then a real module */
1828 RNA_main_pointer_create(G.main, &ptr);
1830 return pyrna_struct_CreatePyObject(&ptr);
1834 /* This is a way we can access docstrings for RNA types
1835 * without having the datatypes in blender */
1836 PyObject *BPY_rna_doc( void )
1840 /* for now, return the base RNA type rather then a real module */
1841 RNA_blender_rna_pointer_create(&ptr);
1843 return pyrna_struct_CreatePyObject(&ptr);
1848 /* pyrna_basetype_* - BPy_BaseTypeRNA is just a BPy_PropertyRNA struct with a differnt type
1849 * the self->ptr and self->prop are always set to the "structs" collection */
1850 //---------------getattr--------------------------------------------
1851 static PyObject *pyrna_basetype_getattro( BPy_BaseTypeRNA * self, PyObject *pyname )
1856 ret = PyObject_GenericGetAttr((PyObject *)self, pyname);
1857 if (ret) return ret;
1860 if (RNA_property_collection_lookup_string(&self->ptr, self->prop, _PyUnicode_AsString(pyname), &newptr)) {
1861 ret= pyrna_struct_Subtype(&newptr);
1863 PyErr_Format(PyExc_SystemError, "bpy.types.%s subtype could not be generated, this is a bug!", _PyUnicode_AsString(pyname));
1867 else { /* Override the error */
1868 PyErr_Format(PyExc_AttributeError, "bpy.types.%s not a valid RNA_Struct", _PyUnicode_AsString(pyname));
1873 static PyObject *pyrna_basetype_dir(BPy_BaseTypeRNA *self);
1874 static struct PyMethodDef pyrna_basetype_methods[] = {
1875 {"__dir__", (PyCFunction)pyrna_basetype_dir, METH_NOARGS, ""},
1876 {"register", (PyCFunction)pyrna_basetype_register, METH_VARARGS, ""},
1877 {"unregister", (PyCFunction)pyrna_basetype_unregister, METH_VARARGS, ""},
1878 {NULL, NULL, 0, NULL}
1881 static PyObject *pyrna_basetype_dir(BPy_BaseTypeRNA *self)
1883 PyObject *list, *name;
1886 list= pyrna_prop_keys(self); /* like calling structs.keys(), avoids looping here */
1888 for(meth=pyrna_basetype_methods; meth->ml_name; meth++) {
1889 name = PyUnicode_FromString(meth->ml_name);
1890 PyList_Append(list, name);
1897 PyTypeObject pyrna_basetype_Type = BLANK_PYTHON_TYPE;
1899 PyObject *BPY_rna_types(void)
1901 BPy_BaseTypeRNA *self;
1903 if ((pyrna_basetype_Type.tp_flags & Py_TPFLAGS_READY)==0) {
1904 pyrna_basetype_Type.tp_name = "RNA_Types";
1905 pyrna_basetype_Type.tp_basicsize = sizeof( BPy_BaseTypeRNA );
1906 pyrna_basetype_Type.tp_getattro = ( getattrofunc )pyrna_basetype_getattro;
1907 pyrna_basetype_Type.tp_flags = Py_TPFLAGS_DEFAULT;
1908 pyrna_basetype_Type.tp_methods = pyrna_basetype_methods;
1910 if( PyType_Ready( &pyrna_basetype_Type ) < 0 )
1914 self= (BPy_BaseTypeRNA *)PyObject_NEW( BPy_BaseTypeRNA, &pyrna_basetype_Type );
1916 /* avoid doing this lookup for every getattr */
1917 RNA_blender_rna_pointer_create(&self->ptr);
1918 self->prop = RNA_struct_find_property(&self->ptr, "structs");
1920 return (PyObject *)self;
1923 static struct PyMethodDef props_methods[] = {
1924 {"FloatProperty", (PyCFunction)BPy_FloatProperty, METH_VARARGS|METH_KEYWORDS, ""},
1925 {"IntProperty", (PyCFunction)BPy_IntProperty, METH_VARARGS|METH_KEYWORDS, ""},
1926 {"BoolProperty", (PyCFunction)BPy_BoolProperty, METH_VARARGS|METH_KEYWORDS, ""},
1927 {"StringProperty", (PyCFunction)BPy_StringProperty, METH_VARARGS|METH_KEYWORDS, ""},
1928 {NULL, NULL, 0, NULL}
1931 #if PY_VERSION_HEX >= 0x03000000
1932 static struct PyModuleDef props_module = {
1933 PyModuleDef_HEAD_INIT,
1936 -1,/* multiple "initialization" just copies the module dict. */
1938 NULL, NULL, NULL, NULL
1942 PyObject *BPY_rna_props( void )
1944 PyObject *submodule, *mod;
1945 #if PY_VERSION_HEX >= 0x03000000
1946 submodule= PyModule_Create(&props_module);
1948 submodule= Py_InitModule3( "bpy.props", props_methods, "" );
1951 mod = PyModule_New("props");
1952 PyModule_AddObject( submodule, "props", mod );
1954 /* INCREF since its its assumed that all these functions return the
1955 * module with a new ref like PyDict_New, since they are passed to
1956 * PyModule_AddObject which steals a ref */
1957 Py_INCREF(submodule);
1962 /* Orphan functions, not sure where they should go */
1964 /* Function that sets RNA, NOTE - self is NULL when called from python, but being abused from C so we can pass the srna allong
1965 * This isnt incorrect since its a python object - but be careful */
1966 PyObject *BPy_FloatProperty(PyObject *self, PyObject *args, PyObject *kw)
1968 static char *kwlist[] = {"attr", "name", "description", "min", "max", "soft_min", "soft_max", "default", NULL};
1969 char *id, *name="", *description="";
1970 float min=FLT_MIN, max=FLT_MAX, soft_min=FLT_MIN, soft_max=FLT_MAX, def=0.0f;
1972 if (!PyArg_ParseTupleAndKeywords(args, kw, "s|ssfffff:FloatProperty", kwlist, &id, &name, &description, &min, &max, &soft_min, &soft_max, &def))
1975 if (PyTuple_Size(args) > 0) {
1976 PyErr_SetString(PyExc_ValueError, "all args must be keywors"); // TODO - py3 can enforce this.
1980 if (self && PyCObject_Check(self)) {
1981 StructRNA *srna = PyCObject_AsVoidPtr(self);
1982 RNA_def_float(srna, id, def, min, max, name, description, soft_min, soft_max);
1985 PyObject *ret = PyTuple_New(2);
1986 PyTuple_SET_ITEM(ret, 0, PyCObject_FromVoidPtr((void *)BPy_FloatProperty, NULL));
1987 PyTuple_SET_ITEM(ret, 1, kw);
1993 PyObject *BPy_IntProperty(PyObject *self, PyObject *args, PyObject *kw)
1995 static char *kwlist[] = {"attr", "name", "description", "min", "max", "soft_min", "soft_max", "default", NULL};
1996 char *id, *name="", *description="";
1997 int min=INT_MIN, max=INT_MAX, soft_min=INT_MIN, soft_max=INT_MAX, def=0;
1999 if (!PyArg_ParseTupleAndKeywords(args, kw, "s|ssiiiii:IntProperty", kwlist, &id, &name, &description, &min, &max, &soft_min, &soft_max, &def))
2002 if (PyTuple_Size(args) > 0) {
2003 PyErr_SetString(PyExc_ValueError, "all args must be keywors"); // TODO - py3 can enforce this.
2007 if (self && PyCObject_Check(self)) {
2008 StructRNA *srna = PyCObject_AsVoidPtr(self);
2009 RNA_def_int(srna, id, def, min, max, name, description, soft_min, soft_max);
2012 PyObject *ret = PyTuple_New(2);
2013 PyTuple_SET_ITEM(ret, 0, PyCObject_FromVoidPtr((void *)BPy_IntProperty, NULL));
2014 PyTuple_SET_ITEM(ret, 1, kw);
2020 PyObject *BPy_BoolProperty(PyObject *self, PyObject *args, PyObject *kw)
2022 static char *kwlist[] = {"attr", "name", "description", "default", NULL};
2023 char *id, *name="", *description="";
2026 if (!PyArg_ParseTupleAndKeywords(args, kw, "s|ssi:IntProperty", kwlist, &id, &name, &description, &def))
2029 if (PyTuple_Size(args) > 0) {
2030 PyErr_SetString(PyExc_ValueError, "all args must be keywors"); // TODO - py3 can enforce this.
2034 if (self && PyCObject_Check(self)) {
2035 StructRNA *srna = PyCObject_AsVoidPtr(self);
2036 RNA_def_boolean(srna, id, def, name, description);
2039 PyObject *ret = PyTuple_New(2);
2040 PyTuple_SET_ITEM(ret, 0, PyCObject_FromVoidPtr((void *)BPy_IntProperty, NULL));
2041 PyTuple_SET_ITEM(ret, 1, kw);
2047 PyObject *BPy_StringProperty(PyObject *self, PyObject *args, PyObject *kw)
2049 static char *kwlist[] = {"attr", "name", "description", "maxlen", "default", NULL};
2050 char *id, *name="", *description="", *def="";
2053 if (!PyArg_ParseTupleAndKeywords(args, kw, "s|ssis:StringProperty", kwlist, &id, &name, &description, &maxlen, &def))
2056 if (PyTuple_Size(args) > 0) {
2057 PyErr_SetString(PyExc_ValueError, "all args must be keywors"); // TODO - py3 can enforce this.
2061 if (self && PyCObject_Check(self)) {
2062 StructRNA *srna = PyCObject_AsVoidPtr(self);
2063 RNA_def_string(srna, id, def, maxlen, name, description);
2066 PyObject *ret = PyTuple_New(2);
2067 PyTuple_SET_ITEM(ret, 0, PyCObject_FromVoidPtr((void *)BPy_StringProperty, NULL));
2068 PyTuple_SET_ITEM(ret, 1, kw);
2074 /*-------------------- Type Registration ------------------------*/
2076 static int rna_function_arg_count(FunctionRNA *func)
2078 const ListBase *lb= RNA_function_defined_parameters(func);
2083 for(link=lb->first; link; link=link->next) {
2084 parm= (PropertyRNA*)link;
2085 if(!(RNA_property_flag(parm) & PROP_RETURN))
2092 static int bpy_class_validate(PointerRNA *dummyptr, void *py_data, int *have_function)
2098 StructRNA *srna= dummyptr->type;
2099 const char *class_type= RNA_struct_identifier(srna);
2100 PyObject *py_class= (PyObject*)py_data;
2101 PyObject *base_class= RNA_struct_py_type_get(srna);
2102 PyObject *item, *fitem;
2103 PyObject *py_arg_count;
2104 int i, flag, arg_count, func_arg_count;
2105 char identifier[128];
2108 if (!PyObject_IsSubclass(py_class, base_class)) {
2109 PyObject *name= PyObject_GetAttrString(base_class, "__name__");
2110 PyErr_Format( PyExc_AttributeError, "expected %s subclass of class \"%s\"", class_type, name ? _PyUnicode_AsString(name):"<UNKNOWN>");
2116 /* verify callback functions */
2117 lb= RNA_struct_defined_functions(srna);
2119 for(link=lb->first; link; link=link->next) {
2120 func= (FunctionRNA*)link;
2121 flag= RNA_function_flag(func);
2123 if(!(flag & FUNC_REGISTER))
2126 item = PyObject_GetAttrString(py_class, RNA_function_identifier(func));
2128 have_function[i]= (item != NULL);
2132 if ((flag & FUNC_REGISTER_OPTIONAL)==0) {
2133 PyErr_Format( PyExc_AttributeError, "expected %s class to have an \"%s\" attribute", class_type, RNA_function_identifier(func));
2140 Py_DECREF(item); /* no need to keep a ref, the class owns it */
2142 if (PyMethod_Check(item))
2143 fitem= PyMethod_Function(item); /* py 2.x */
2145 fitem= item; /* py 3.x */
2147 if (PyFunction_Check(fitem)==0) {
2148 PyErr_Format( PyExc_AttributeError, "expected %s class \"%s\" attribute to be a function", class_type, RNA_function_identifier(func));
2152 func_arg_count= rna_function_arg_count(func);
2154 if (func_arg_count >= 0) { /* -1 if we dont care*/
2155 py_arg_count = PyObject_GetAttrString(PyFunction_GET_CODE(fitem), "co_argcount");
2156 arg_count = PyLong_AsSsize_t(py_arg_count);
2157 Py_DECREF(py_arg_count);
2159 if (arg_count != func_arg_count) {
2160 PyErr_Format( PyExc_AttributeError, "expected %s class \"%s\" function to have %d args", class_type, RNA_function_identifier(func), func_arg_count);
2167 /* verify properties */
2168 lb= RNA_struct_defined_properties(srna);
2169 for(link=lb->first; link; link=link->next) {
2170 prop= (PropertyRNA*)link;
2171 flag= RNA_property_flag(prop);
2173 if(!(flag & PROP_REGISTER))
2176 BLI_snprintf(identifier, sizeof(identifier), "__%s__", RNA_property_identifier(prop));
2177 item = PyObject_GetAttrString(py_class, identifier);
2180 if(strcmp(identifier, "__idname__") == 0) {
2181 item= PyObject_GetAttrString(py_class, "__name__");
2184 Py_DECREF(item); /* no need to keep a ref, the class owns it */
2186 if(pyrna_py_to_prop(dummyptr, prop, NULL, item) != 0)
2191 if (item==NULL && (flag & PROP_REGISTER_OPTIONAL)==0) {
2192 PyErr_Format( PyExc_AttributeError, "expected %s class to have an \"%s\" attribute", class_type, identifier);
2199 Py_DECREF(item); /* no need to keep a ref, the class owns it */
2201 if(pyrna_py_to_prop(dummyptr, prop, NULL, item) != 0)
2209 extern void BPY_update_modules( void ); //XXX temp solution
2211 static int bpy_class_call(PointerRNA *ptr, FunctionRNA *func, ParameterList *parms)
2214 PyObject *ret= NULL, *py_class, *py_class_instance, *item, *parmitem;
2215 PropertyRNA *pret= NULL, *parm;
2216 ParameterIterator iter;
2218 void *retdata= NULL;
2219 int err= 0, i, flag;
2221 PyGILState_STATE gilstate = PyGILState_Ensure();
2223 BPY_update_modules(); // XXX - the RNA pointers can change so update before running, would like a nicer solution for this.
2225 py_class= RNA_struct_py_type_get(ptr->type);
2227 item = pyrna_struct_CreatePyObject(ptr);
2229 py_class_instance = NULL;
2231 else if(item == Py_None) { /* probably wont ever happen but possible */
2233 py_class_instance = NULL;
2236 args = PyTuple_New(1);
2237 PyTuple_SET_ITEM(args, 0, item);
2238 py_class_instance = PyObject_Call(py_class, args, NULL);
2242 if (py_class_instance) { /* Initializing the class worked, now run its invoke function */
2243 item= PyObject_GetAttrString(py_class, RNA_function_identifier(func));
2244 flag= RNA_function_flag(func);
2247 pret= RNA_function_return(func);
2248 RNA_pointer_create(NULL, &RNA_Function, func, &funcptr);
2250 args = PyTuple_New(rna_function_arg_count(func));
2251 PyTuple_SET_ITEM(args, 0, py_class_instance);
2253 RNA_parameter_list_begin(parms, &iter);
2255 /* parse function parameters */
2256 for (i= 1; iter.valid; RNA_parameter_list_next(&iter)) {
2264 parmitem= pyrna_param_to_py(&funcptr, parm, iter.data);
2265 PyTuple_SET_ITEM(args, i, parmitem);
2269 ret = PyObject_Call(item, args, NULL);
2275 Py_DECREF(py_class_instance);
2276 PyErr_Format(PyExc_AttributeError, "could not find function %s in %s to execute callback.", RNA_function_identifier(func), RNA_struct_identifier(ptr->type));
2281 PyErr_Format(PyExc_AttributeError, "could not create instance of %s to call callback function %s.", RNA_struct_identifier(ptr->type), RNA_function_identifier(func));
2285 if (ret == NULL) { /* covers py_class_instance failing too */
2286 PyErr_Print(); /* XXX use reporting api? */
2291 err= pyrna_py_to_prop(&funcptr, pret, retdata, ret);
2295 PyGILState_Release(gilstate);
2300 static void bpy_class_free(void *pyob_ptr)
2303 if(((PyObject *)pyob_ptr)->ob_refcnt > 1)
2304 PyObSpit("zombie class - ref should be 1", (PyObject *)pyob_ptr);
2306 Py_DECREF((PyObject *)pyob_ptr);
2309 PyObject *pyrna_basetype_register(PyObject *self, PyObject *args)
2312 PyObject *py_class, *item;
2314 StructRegisterFunc reg;
2315 BPy_StructRNA *py_srna;
2318 if(!PyArg_ParseTuple(args, "O:register", &py_class))
2321 if(!PyType_Check(py_class)) {
2322 PyErr_SetString(PyExc_AttributeError, "expected a Type subclassed from a registerable rna type (no a Type object).");
2326 /* check we got an __rna__ attribute */
2327 item= PyObject_GetAttrString(py_class, "__rna__");
2329 if(!item || !BPy_StructRNA_Check(item)) {
2331 PyErr_SetString(PyExc_AttributeError, "expected a Type subclassed from a registerable rna type (no __rna__ property).");
2335 /* check the __rna__ attribute has the right type */
2337 py_srna= (BPy_StructRNA*)item;
2339 if(py_srna->ptr.type != &RNA_Struct) {
2340 PyErr_SetString(PyExc_AttributeError, "expected a Type subclassed from a registerable rna type (not a Struct).");
2344 /* check that we have a register callback for this type */
2345 reg= RNA_struct_register(py_srna->ptr.data);
2348 PyErr_SetString(PyExc_AttributeError, "expected a Type subclassed from a registerable rna type (no register supported).");
2352 /* get the context, so register callback can do necessary refreshes */
2353 C= BPy_GetContext();
2355 /* call the register callback */
2356 BKE_reports_init(&reports, RPT_STORE);
2357 srna= reg(C, &reports, py_class, bpy_class_validate, bpy_class_call, bpy_class_free);
2360 BPy_reports_to_error(&reports);
2361 BKE_reports_clear(&reports);
2365 BKE_reports_clear(&reports);
2367 pyrna_subtype_set_rna(py_class, srna); /* takes a ref to py_class */
2372 PyObject *pyrna_basetype_unregister(PyObject *self, PyObject *args)
2375 PyObject *py_class, *item;
2376 BPy_StructRNA *py_srna;
2377 StructUnregisterFunc unreg;
2379 if(!PyArg_ParseTuple(args, "O:unregister", &py_class))
2382 if(!PyType_Check(py_class)) {
2383 PyErr_SetString(PyExc_AttributeError, "expected a Type subclassed from a registerable rna type (no a Type object).");
2387 /* check we got an __rna__ attribute */
2388 item= PyDict_GetItemString(((PyTypeObject*)py_class)->tp_dict, "__rna__"); /* borrow ref */
2390 if(!item || !BPy_StructRNA_Check(item)) {
2391 PyErr_SetString(PyExc_AttributeError, "expected a Type subclassed from a registerable rna type (no __rna__ property).");
2395 /* check the __rna__ attribute has the right type */
2396 py_srna= (BPy_StructRNA*)item;
2398 if(py_srna->ptr.type != &RNA_Struct) {
2399 PyErr_SetString(PyExc_AttributeError, "expected a Type subclassed from a registerable rna type (not a Struct).");
2403 /* check that we have a unregister callback for this type */
2404 unreg= RNA_struct_unregister(py_srna->ptr.data);
2407 PyErr_SetString(PyExc_AttributeError, "expected a Type subclassed from a registerable rna type (no unregister supported).");
2411 /* get the context, so register callback can do necessary refreshes */
2412 C= BPy_GetContext();
2415 /* call unregister */
2416 unreg(C, py_srna->ptr.data);
2418 /* remove reference to old type */
2419 Py_DECREF(py_class);