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 *****
27 //#include "blendef.h"
28 #include "BLI_dynstr.h"
29 #include "BLI_listbase.h"
30 #include "BLI_string.h"
31 #include "float.h" /* FLT_MIN/MAX */
33 #include "RNA_access.h"
34 #include "RNA_define.h" /* for defining our own rna */
36 #include "MEM_guardedalloc.h"
37 #include "BKE_utildefines.h"
38 #include "BKE_context.h"
39 #include "BKE_global.h" /* evil G.* */
40 #include "BKE_report.h"
42 #include "BKE_animsys.h"
43 #include "BKE_fcurve.h"
45 /* only for keyframing */
46 #include "DNA_scene_types.h"
47 #include "DNA_anim_types.h"
48 #include "ED_keyframing.h"
53 #include "../generic/Mathutils.h" /* so we can have mathutils callbacks */
54 #include "../generic/IDProp.h" /* for IDprop lookups */
56 /* bpyrna vector/euler/quat callbacks */
57 static int mathutils_rna_array_cb_index= -1; /* index for our callbacks */
59 static int mathutils_rna_generic_check(BPy_PropertyRNA *self)
61 return self->prop?1:0;
64 static int mathutils_rna_vector_get(BPy_PropertyRNA *self, int subtype, float *vec_from)
69 RNA_property_float_get_array(&self->ptr, self->prop, vec_from);
73 static int mathutils_rna_vector_set(BPy_PropertyRNA *self, int subtype, float *vec_to)
78 RNA_property_float_set_array(&self->ptr, self->prop, vec_to);
79 RNA_property_update(BPy_GetContext(), &self->ptr, self->prop);
83 static int mathutils_rna_vector_get_index(BPy_PropertyRNA *self, int subtype, float *vec_from, int index)
88 vec_from[index]= RNA_property_float_get_index(&self->ptr, self->prop, index);
92 static int mathutils_rna_vector_set_index(BPy_PropertyRNA *self, int subtype, float *vec_to, int index)
97 RNA_property_float_set_index(&self->ptr, self->prop, index, vec_to[index]);
98 RNA_property_update(BPy_GetContext(), &self->ptr, self->prop);
102 Mathutils_Callback mathutils_rna_array_cb = {
103 (BaseMathCheckFunc) mathutils_rna_generic_check,
104 (BaseMathGetFunc) mathutils_rna_vector_get,
105 (BaseMathSetFunc) mathutils_rna_vector_set,
106 (BaseMathGetIndexFunc) mathutils_rna_vector_get_index,
107 (BaseMathSetIndexFunc) mathutils_rna_vector_set_index
111 /* bpyrna matrix callbacks */
112 static int mathutils_rna_matrix_cb_index= -1; /* index for our callbacks */
114 static int mathutils_rna_matrix_get(BPy_PropertyRNA *self, int subtype, float *mat_from)
119 RNA_property_float_get_array(&self->ptr, self->prop, mat_from);
123 static int mathutils_rna_matrix_set(BPy_PropertyRNA *self, int subtype, float *mat_to)
128 RNA_property_float_set_array(&self->ptr, self->prop, mat_to);
129 RNA_property_update(BPy_GetContext(), &self->ptr, self->prop);
133 Mathutils_Callback mathutils_rna_matrix_cb = {
134 (BaseMathCheckFunc) mathutils_rna_generic_check,
135 (BaseMathGetFunc) mathutils_rna_matrix_get,
136 (BaseMathSetFunc) mathutils_rna_matrix_set,
137 (BaseMathGetIndexFunc) NULL,
138 (BaseMathSetIndexFunc) NULL
141 PyObject *pyrna_math_object_from_array(PointerRNA *ptr, PropertyRNA *prop)
149 /* disallow dynamic sized arrays to be wrapped since the size could change
150 * to a size mathutils does not support */
151 if ((RNA_property_type(prop) != PROP_FLOAT) || (RNA_property_flag(prop) & PROP_DYNAMIC))
154 len= RNA_property_array_length(ptr, prop);
155 subtype= RNA_property_subtype(prop);
156 totdim= RNA_property_array_dimension(ptr, prop, NULL);
158 if (totdim == 1 || (totdim == 2 && subtype == PROP_MATRIX)) {
159 ret = pyrna_prop_CreatePyObject(ptr, prop); /* owned by the Mathutils PyObject */
161 switch(RNA_property_subtype(prop)) {
162 case PROP_TRANSLATION:
165 case PROP_ACCELERATION:
167 if(len>=2 && len <= 4) {
168 PyObject *vec_cb= newVectorObject_cb(ret, len, mathutils_rna_array_cb_index, FALSE);
169 Py_DECREF(ret); /* the vector owns now */
170 ret= vec_cb; /* return the vector instead */
175 PyObject *mat_cb= newMatrixObject_cb(ret, 4,4, mathutils_rna_matrix_cb_index, FALSE);
176 Py_DECREF(ret); /* the matrix owns now */
177 ret= mat_cb; /* return the matrix instead */
180 PyObject *mat_cb= newMatrixObject_cb(ret, 3,3, mathutils_rna_matrix_cb_index, FALSE);
181 Py_DECREF(ret); /* the matrix owns now */
182 ret= mat_cb; /* return the matrix instead */
186 case PROP_QUATERNION:
187 if(len==3) { /* euler */
188 PyObject *eul_cb= newEulerObject_cb(ret, mathutils_rna_array_cb_index, FALSE);
189 Py_DECREF(ret); /* the matrix owns now */
190 ret= eul_cb; /* return the matrix instead */
193 PyObject *quat_cb= newQuaternionObject_cb(ret, mathutils_rna_array_cb_index, FALSE);
194 Py_DECREF(ret); /* the matrix owns now */
195 ret= quat_cb; /* return the matrix instead */
209 static StructRNA *pyrna_struct_as_srna(PyObject *self);
211 static int pyrna_struct_compare( BPy_StructRNA * a, BPy_StructRNA * b )
213 return (a->ptr.data==b->ptr.data) ? 0 : -1;
216 static int pyrna_prop_compare( BPy_PropertyRNA * a, BPy_PropertyRNA * b )
218 return (a->prop==b->prop && a->ptr.data==b->ptr.data ) ? 0 : -1;
221 static PyObject *pyrna_struct_richcmp(PyObject *a, PyObject *b, int op)
224 int ok= -1; /* zero is true */
226 if (BPy_StructRNA_Check(a) && BPy_StructRNA_Check(b))
227 ok= pyrna_struct_compare((BPy_StructRNA *)a, (BPy_StructRNA *)b);
231 ok = !ok; /* pass through */
233 res = ok ? Py_False : Py_True;
240 res = Py_NotImplemented;
251 static PyObject *pyrna_prop_richcmp(PyObject *a, PyObject *b, int op)
254 int ok= -1; /* zero is true */
256 if (BPy_PropertyRNA_Check(a) && BPy_PropertyRNA_Check(b))
257 ok= pyrna_prop_compare((BPy_PropertyRNA *)a, (BPy_PropertyRNA *)b);
261 ok = !ok; /* pass through */
263 res = ok ? Py_False : Py_True;
270 res = Py_NotImplemented;
281 /*----------------------repr--------------------------------------------*/
282 static PyObject *pyrna_struct_repr( BPy_StructRNA *self )
287 /* print name if available */
288 name= RNA_struct_name_get_alloc(&self->ptr, NULL, FALSE);
290 pyob= PyUnicode_FromFormat( "[BPy_StructRNA \"%.200s\" -> \"%.200s\"]", RNA_struct_identifier(self->ptr.type), name);
295 return PyUnicode_FromFormat( "[BPy_StructRNA \"%.200s\"]", RNA_struct_identifier(self->ptr.type));
298 static PyObject *pyrna_prop_repr( BPy_PropertyRNA *self )
304 /* if a pointer, try to print name of pointer target too */
305 if(RNA_property_type(self->prop) == PROP_POINTER) {
306 ptr= RNA_property_pointer_get(&self->ptr, self->prop);
307 name= RNA_struct_name_get_alloc(&ptr, NULL, FALSE);
310 pyob= PyUnicode_FromFormat( "[BPy_PropertyRNA \"%.200s\" -> \"%.200s\" -> \"%.200s\" ]", RNA_struct_identifier(self->ptr.type), RNA_property_identifier(self->prop), name);
316 return PyUnicode_FromFormat( "[BPy_PropertyRNA \"%.200s\" -> \"%.200s\"]", RNA_struct_identifier(self->ptr.type), RNA_property_identifier(self->prop));
319 static long pyrna_struct_hash( BPy_StructRNA *self )
321 return (long)self->ptr.data;
324 /* use our own dealloc so we can free a property if we use one */
325 static void pyrna_struct_dealloc( BPy_StructRNA *self )
327 if (self->freeptr && self->ptr.data) {
328 IDP_FreeProperty(self->ptr.data);
329 if (self->ptr.type != &RNA_Context)
331 MEM_freeN(self->ptr.data);
332 self->ptr.data= NULL;
336 /* Note, for subclassed PyObjects we cant just call PyObject_DEL() directly or it will crash */
337 Py_TYPE(self)->tp_free(self);
341 static char *pyrna_enum_as_string(PointerRNA *ptr, PropertyRNA *prop)
343 EnumPropertyItem *item;
347 RNA_property_enum_items(BPy_GetContext(), ptr, prop, &item, NULL, &free);
349 result= (char*)BPy_enum_as_string(item);
361 static int pyrna_string_to_enum(PyObject *item, PointerRNA *ptr, PropertyRNA *prop, int *val, const char *error_prefix)
363 char *param= _PyUnicode_AsString(item);
366 char *enum_str= pyrna_enum_as_string(ptr, prop);
367 PyErr_Format(PyExc_TypeError, "%.200s expected a string enum type in (%.200s)", error_prefix, enum_str);
371 if (!RNA_property_enum_value(BPy_GetContext(), ptr, prop, param, val)) {
372 char *enum_str= pyrna_enum_as_string(ptr, prop);
373 PyErr_Format(PyExc_TypeError, "%.200s enum \"%.200s\" not found in (%.200s)", error_prefix, param, enum_str);
382 PyObject * pyrna_prop_to_py(PointerRNA *ptr, PropertyRNA *prop)
385 int type = RNA_property_type(prop);
387 if (RNA_property_array_check(ptr, prop)) {
388 return pyrna_py_from_array(ptr, prop);
391 /* see if we can coorce into a python type - PropertyType */
394 ret = PyBool_FromLong( RNA_property_boolean_get(ptr, prop) );
397 ret = PyLong_FromSsize_t( (Py_ssize_t)RNA_property_int_get(ptr, prop) );
400 ret = PyFloat_FromDouble( RNA_property_float_get(ptr, prop) );
405 buf = RNA_property_string_get_alloc(ptr, prop, NULL, -1);
406 ret = PyUnicode_FromString( buf );
412 const char *identifier;
413 int val = RNA_property_enum_get(ptr, prop);
415 if (RNA_property_enum_identifier(BPy_GetContext(), ptr, prop, val, &identifier)) {
416 ret = PyUnicode_FromString( identifier );
418 EnumPropertyItem *item;
421 /* don't throw error here, can't trust blender 100% to give the
422 * right values, python code should not generate error for that */
423 RNA_property_enum_items(BPy_GetContext(), ptr, prop, &item, NULL, &free);
424 if(item && item->identifier) {
425 ret = PyUnicode_FromString( item->identifier );
428 char *ptr_name= RNA_struct_name_get_alloc(ptr, NULL, FALSE);
430 /* prefer not fail silently incase of api errors, maybe disable it later */
431 printf("RNA Warning: Current value \"%d\" matches no enum in '%s', '%s', '%s'\n", val, RNA_struct_identifier(ptr->type), ptr_name, RNA_property_identifier(prop));
433 #if 0 // gives python decoding errors while generating docs :(
435 snprintf(error_str, sizeof(error_str), "RNA Warning: Current value \"%d\" matches no enum in '%s', '%s', '%s'", val, RNA_struct_identifier(ptr->type), ptr_name, RNA_property_identifier(prop));
436 PyErr_Warn(PyExc_RuntimeWarning, error_str);
442 ret = PyUnicode_FromString( "" );
448 /*PyErr_Format(PyExc_AttributeError, "RNA Error: Current value \"%d\" matches no enum", val);
457 newptr= RNA_property_pointer_get(ptr, prop);
459 ret = pyrna_struct_CreatePyObject(&newptr);
466 case PROP_COLLECTION:
467 ret = pyrna_prop_CreatePyObject(ptr, prop);
470 PyErr_Format(PyExc_TypeError, "RNA Error: unknown type \"%d\" (pyrna_prop_to_py)", type);
478 /* This function is used by operators and converting dicts into collections.
479 * Its takes keyword args and fills them with property values */
480 int pyrna_pydict_to_props(PointerRNA *ptr, PyObject *kw, int all_args, const char *error_prefix)
484 const char *arg_name= NULL;
487 totkw = kw ? PyDict_Size(kw):0;
489 RNA_STRUCT_BEGIN(ptr, prop) {
490 arg_name= RNA_property_identifier(prop);
492 if (strcmp(arg_name, "rna_type")==0) continue;
495 PyErr_Format( PyExc_TypeError, "%.200s: no keywords, expected \"%.200s\"", error_prefix, arg_name ? arg_name : "<UNKNOWN>");
500 item= PyDict_GetItemString(kw, arg_name); /* wont set an error */
504 PyErr_Format( PyExc_TypeError, "%.200s: keyword \"%.200s\" missing", error_prefix, arg_name ? arg_name : "<UNKNOWN>");
505 error_val = -1; /* pyrna_py_to_prop sets the error */
509 if (pyrna_py_to_prop(ptr, prop, NULL, item, error_prefix)) {
518 if (error_val==0 && totkw > 0) { /* some keywords were given that were not used :/ */
519 PyObject *key, *value;
522 while (PyDict_Next(kw, &pos, &key, &value)) {
523 arg_name= _PyUnicode_AsString(key);
524 if (RNA_struct_find_property(ptr, arg_name) == NULL) break;
528 PyErr_Format( PyExc_TypeError, "%.200s: keyword \"%.200s\" unrecognized", error_prefix, arg_name ? arg_name : "<UNKNOWN>");
535 static PyObject * pyrna_func_call(PyObject *self, PyObject *args, PyObject *kw);
537 PyObject *pyrna_func_to_py(BPy_DummyPointerRNA *pyrna, FunctionRNA *func)
539 static PyMethodDef func_meth = {"<generic rna function>", (PyCFunction)pyrna_func_call, METH_VARARGS|METH_KEYWORDS, "python rna function"};
544 PyErr_Format( PyExc_RuntimeError, "%.200s: type attempted to get NULL function", RNA_struct_identifier(pyrna->ptr.type));
548 self= PyTuple_New(2);
550 PyTuple_SET_ITEM(self, 0, (PyObject *)pyrna);
553 PyTuple_SET_ITEM(self, 1, PyCObject_FromVoidPtr((void *)func, NULL));
555 ret= PyCFunction_New(&func_meth, self);
562 int pyrna_py_to_prop(PointerRNA *ptr, PropertyRNA *prop, void *data, PyObject *value, const char *error_prefix)
564 /* XXX hard limits should be checked here */
565 int type = RNA_property_type(prop);
568 if (RNA_property_array_check(ptr, prop)) {
570 /* char error_str[512]; */
574 if(MatrixObject_Check(value)) {
575 MatrixObject *mat = (MatrixObject*)value;
576 if(!BaseMath_ReadCallback(mat))
578 } else /* continue... */
580 if (!PySequence_Check(value)) {
581 PyErr_Format(PyExc_TypeError, "%.200s RNA array assignment expected a sequence instead of %.200s instance.", error_prefix, Py_TYPE(value)->tp_name);
584 /* done getting the length */
585 ok= pyrna_py_to_array(ptr, prop, data, value, error_prefix);
588 /* PyErr_Format(PyExc_AttributeError, "%.200s %s", error_prefix, error_str); */
593 /* Normal Property (not an array) */
595 /* see if we can coorce into a python type - PropertyType */
600 /* prefer not to have an exception here
601 * however so many poll functions return None or a valid Object.
602 * its a hassle to convert these into a bool before returning, */
603 if(RNA_property_flag(prop) & PROP_RETURN)
604 param = PyObject_IsTrue( value );
606 param = PyLong_AsSsize_t( value );
608 if( param < 0 || param > 1) {
609 PyErr_Format(PyExc_TypeError, "%.200s expected True/False or 0/1", error_prefix);
612 if(data) *((int*)data)= param;
613 else RNA_property_boolean_set(ptr, prop, param);
619 int param = PyLong_AsSsize_t(value);
620 if (param==-1 && PyErr_Occurred()) {
621 PyErr_Format(PyExc_TypeError, "%.200s expected an int type", error_prefix);
624 if(data) *((int*)data)= param;
625 else RNA_property_int_set(ptr, prop, param);
631 float param = PyFloat_AsDouble(value);
632 if (PyErr_Occurred()) {
633 PyErr_Format(PyExc_TypeError, "%.200s expected a float type", error_prefix);
636 if(data) *((float*)data)= param;
637 else RNA_property_float_set(ptr, prop, param);
643 char *param = _PyUnicode_AsString(value);
646 PyErr_Format(PyExc_TypeError, "%.200s expected a string type", error_prefix);
649 if(data) *((char**)data)= param;
650 else RNA_property_string_set(ptr, prop, param);
658 if (PyUnicode_Check(value)) {
659 if (!pyrna_string_to_enum(value, ptr, prop, &val, error_prefix))
662 else if (PyTuple_Check(value)) {
663 /* tuple of enum items, concatenate all values with OR */
665 for (i= 0; i < PyTuple_Size(value); i++) {
668 /* PyTuple_GET_ITEM returns a borrowed reference */
669 if (!pyrna_string_to_enum(PyTuple_GET_ITEM(value, i), ptr, prop, &tmpval, error_prefix))
676 char *enum_str= pyrna_enum_as_string(ptr, prop);
677 PyErr_Format(PyExc_TypeError, "%.200s expected a string enum or a tuple of strings in (%.200s)", error_prefix, enum_str);
682 if(data) *((int*)data)= val;
683 else RNA_property_enum_set(ptr, prop, val);
689 StructRNA *ptype= RNA_property_pointer_type(ptr, prop);
690 int flag = RNA_property_flag(prop);
692 if(!BPy_StructRNA_Check(value) && value != Py_None) {
693 PyErr_Format(PyExc_TypeError, "%.200s expected a %.200s type", error_prefix, RNA_struct_identifier(ptype));
695 } else if((flag & PROP_NEVER_NULL) && value == Py_None) {
696 PyErr_Format(PyExc_TypeError, "%.200s does not suppory a 'None' assignment %.200s type", error_prefix, RNA_struct_identifier(ptype));
699 BPy_StructRNA *param= (BPy_StructRNA*)value;
700 int raise_error= FALSE;
703 if(flag & PROP_RNAPTR) {
705 memset(data, 0, sizeof(PointerRNA));
707 *((PointerRNA*)data)= param->ptr;
709 else if(value == Py_None) {
710 *((void**)data)= NULL;
712 else if(RNA_struct_is_a(param->ptr.type, ptype)) {
713 *((void**)data)= param->ptr.data;
720 /* data==NULL, assign to RNA */
721 if(value == Py_None) {
723 memset(&valueptr, 0, sizeof(valueptr));
724 RNA_property_pointer_set(ptr, prop, valueptr);
726 else if(RNA_struct_is_a(param->ptr.type, ptype)) {
727 RNA_property_pointer_set(ptr, prop, param->ptr);
731 RNA_pointer_create(NULL, ptype, NULL, &tmp);
732 PyErr_Format(PyExc_TypeError, "%.200s expected a %.200s type", error_prefix, RNA_struct_identifier(tmp.type));
739 RNA_pointer_create(NULL, ptype, NULL, &tmp);
740 PyErr_Format(PyExc_TypeError, "%.200s expected a %.200s type", error_prefix, RNA_struct_identifier(tmp.type));
746 case PROP_COLLECTION:
752 CollectionPointerLink *link;
754 lb= (data)? (ListBase*)data: NULL;
756 /* convert a sequence of dict's into a collection */
757 if(!PySequence_Check(value)) {
758 PyErr_Format(PyExc_TypeError, "%.200s expected a sequence of dicts for an RNA collection", error_prefix);
762 seq_len = PySequence_Length(value);
763 for(i=0; i<seq_len; i++) {
764 item= PySequence_GetItem(value, i);
765 if(item==NULL || PyDict_Check(item)==0) {
766 PyErr_Format(PyExc_TypeError, "%.200s expected a sequence of dicts for an RNA collection", error_prefix);
772 link= MEM_callocN(sizeof(CollectionPointerLink), "PyCollectionPointerLink");
774 BLI_addtail(lb, link);
777 RNA_property_collection_add(ptr, prop, &itemptr);
779 if(pyrna_pydict_to_props(&itemptr, item, 1, "Converting a python list to an RNA collection")==-1) {
789 PyErr_Format(PyExc_AttributeError, "%.200s unknown property type (pyrna_py_to_prop)", error_prefix);
795 /* Run rna property functions */
796 RNA_property_update(BPy_GetContext(), ptr, prop);
801 static PyObject * pyrna_prop_to_py_index(BPy_PropertyRNA *self, int index)
803 return pyrna_py_from_array_index(self, index);
806 static int pyrna_py_to_prop_index(BPy_PropertyRNA *self, int index, PyObject *value)
810 PointerRNA *ptr= &self->ptr;
811 PropertyRNA *prop= self->prop;
812 int type = RNA_property_type(prop);
814 totdim= RNA_property_array_dimension(ptr, prop, NULL);
817 /* char error_str[512]; */
818 if (!pyrna_py_to_array_index(&self->ptr, self->prop, self->arraydim, self->arrayoffset, index, value, "")) {
819 /* PyErr_SetString(PyExc_AttributeError, error_str); */
824 /* see if we can coorce into a python type - PropertyType */
828 int param = PyLong_AsSsize_t( value );
830 if( param < 0 || param > 1) {
831 PyErr_SetString(PyExc_TypeError, "expected True/False or 0/1");
834 RNA_property_boolean_set_index(ptr, prop, index, param);
840 int param = PyLong_AsSsize_t(value);
841 if (param==-1 && PyErr_Occurred()) {
842 PyErr_SetString(PyExc_TypeError, "expected an int type");
845 RNA_property_int_set_index(ptr, prop, index, param);
851 float param = PyFloat_AsDouble(value);
852 if (PyErr_Occurred()) {
853 PyErr_SetString(PyExc_TypeError, "expected a float type");
856 RNA_property_float_set_index(ptr, prop, index, param);
861 PyErr_SetString(PyExc_AttributeError, "not an array type");
870 //---------------sequence-------------------------------------------
871 static int pyrna_prop_array_length(BPy_PropertyRNA *self)
873 if (RNA_property_array_dimension(&self->ptr, self->prop, NULL) > 1)
874 return RNA_property_multi_array_length(&self->ptr, self->prop, self->arraydim);
876 return RNA_property_array_length(&self->ptr, self->prop);
879 static Py_ssize_t pyrna_prop_len( BPy_PropertyRNA *self )
883 if (RNA_property_type(self->prop) == PROP_COLLECTION) {
884 len = RNA_property_collection_length(&self->ptr, self->prop);
885 } else if (RNA_property_array_check(&self->ptr, self->prop)) {
886 len = pyrna_prop_array_length(self);
888 PyErr_SetString(PyExc_AttributeError, "len() only available for collection and array RNA types");
889 len = -1; /* error value */
895 /* internal use only */
896 static PyObject *prop_subscript_collection_int(BPy_PropertyRNA *self, int keynum)
900 if(keynum < 0) keynum += RNA_property_collection_length(&self->ptr, self->prop);
902 if(RNA_property_collection_lookup_int(&self->ptr, self->prop, keynum, &newptr))
903 return pyrna_struct_CreatePyObject(&newptr);
905 PyErr_Format(PyExc_IndexError, "index %d out of range", keynum);
909 static PyObject *prop_subscript_array_int(BPy_PropertyRNA *self, int keynum)
911 int len= pyrna_prop_array_length(self);
913 if(keynum < 0) keynum += len;
915 if(keynum >= 0 && keynum < len)
916 return pyrna_prop_to_py_index(self, keynum);
918 PyErr_Format(PyExc_IndexError, "index %d out of range", keynum);
922 static PyObject *prop_subscript_collection_str(BPy_PropertyRNA *self, char *keyname)
925 if(RNA_property_collection_lookup_string(&self->ptr, self->prop, keyname, &newptr))
926 return pyrna_struct_CreatePyObject(&newptr);
928 PyErr_Format(PyExc_KeyError, "key \"%.200s\" not found", keyname);
931 /* static PyObject *prop_subscript_array_str(BPy_PropertyRNA *self, char *keyname) */
933 static PyObject *prop_subscript_collection_slice(BPy_PropertyRNA *self, int start, int stop)
936 PyObject *list = PyList_New(stop - start);
939 start = MIN2(start,stop); /* values are clamped from */
941 for(count = start; count < stop; count++) {
942 if(RNA_property_collection_lookup_int(&self->ptr, self->prop, count - start, &newptr)) {
943 PyList_SetItem(list, count - start, pyrna_struct_CreatePyObject(&newptr));
948 PyErr_SetString(PyExc_RuntimeError, "error getting an rna struct from a collection");
955 static PyObject *prop_subscript_array_slice(BPy_PropertyRNA *self, int start, int stop)
957 PyObject *list = PyList_New(stop - start);
960 start = MIN2(start,stop); /* values are clamped from PySlice_GetIndicesEx */
962 for(count = start; count < stop; count++)
963 PyList_SetItem(list, count - start, pyrna_prop_to_py_index(self, count));
968 static PyObject *prop_subscript_collection(BPy_PropertyRNA *self, PyObject *key)
970 if (PyUnicode_Check(key)) {
971 return prop_subscript_collection_str(self, _PyUnicode_AsString(key));
973 else if (PyIndex_Check(key)) {
974 Py_ssize_t i = PyNumber_AsSsize_t(key, PyExc_IndexError);
975 if (i == -1 && PyErr_Occurred())
978 return prop_subscript_collection_int(self, i);
980 else if (PySlice_Check(key)) {
981 int len= RNA_property_collection_length(&self->ptr, self->prop);
982 Py_ssize_t start, stop, step, slicelength;
984 if (PySlice_GetIndicesEx((PySliceObject*)key, len, &start, &stop, &step, &slicelength) < 0)
987 if (slicelength <= 0) {
988 return PyList_New(0);
990 else if (step == 1) {
991 return prop_subscript_collection_slice(self, start, stop);
994 PyErr_SetString(PyExc_TypeError, "slice steps not supported with rna");
999 PyErr_Format(PyExc_TypeError, "invalid rna key, key must be a string or an int instead of %.200s instance.", Py_TYPE(key)->tp_name);
1004 static PyObject *prop_subscript_array(BPy_PropertyRNA *self, PyObject *key)
1006 /*if (PyUnicode_Check(key)) {
1007 return prop_subscript_array_str(self, _PyUnicode_AsString(key));
1009 if (PyIndex_Check(key)) {
1010 Py_ssize_t i = PyNumber_AsSsize_t(key, PyExc_IndexError);
1011 if (i == -1 && PyErr_Occurred())
1013 return prop_subscript_array_int(self, PyLong_AsSsize_t(key));
1015 else if (PySlice_Check(key)) {
1016 Py_ssize_t start, stop, step, slicelength;
1017 int len = pyrna_prop_array_length(self);
1019 if (PySlice_GetIndicesEx((PySliceObject*)key, len, &start, &stop, &step, &slicelength) < 0)
1022 if (slicelength <= 0) {
1023 return PyList_New(0);
1025 else if (step == 1) {
1026 return prop_subscript_array_slice(self, start, stop);
1029 PyErr_SetString(PyExc_TypeError, "slice steps not supported with rna");
1034 PyErr_SetString(PyExc_AttributeError, "invalid key, key must be an int");
1039 static PyObject *pyrna_prop_subscript( BPy_PropertyRNA *self, PyObject *key )
1041 if (RNA_property_type(self->prop) == PROP_COLLECTION) {
1042 return prop_subscript_collection(self, key);
1043 } else if (RNA_property_array_check(&self->ptr, self->prop)) {
1044 return prop_subscript_array(self, key);
1047 PyErr_SetString(PyExc_TypeError, "rna type is not an array or a collection");
1051 static int prop_subscript_ass_array_slice(BPy_PropertyRNA *self, int begin, int end, PyObject *value)
1055 /* values are clamped from */
1056 begin = MIN2(begin,end);
1058 for(count = begin; count < end; count++) {
1059 if(pyrna_py_to_prop_index(self, count - begin, value) == -1) {
1060 /* TODO - this is wrong since some values have been assigned... will need to fix that */
1061 return -1; /* pyrna_struct_CreatePyObject should set the error */
1068 static int prop_subscript_ass_array_int(BPy_PropertyRNA *self, int keynum, PyObject *value)
1070 int len= pyrna_prop_array_length(self);
1072 if(keynum < 0) keynum += len;
1074 if(keynum >= 0 && keynum < len)
1075 return pyrna_py_to_prop_index(self, keynum, value);
1077 PyErr_SetString(PyExc_IndexError, "out of range");
1081 static int pyrna_prop_ass_subscript( BPy_PropertyRNA *self, PyObject *key, PyObject *value )
1083 /* char *keyname = NULL; */ /* not supported yet */
1085 if (!RNA_property_editable(&self->ptr, self->prop)) {
1086 PyErr_Format( PyExc_AttributeError, "PropertyRNA - attribute \"%.200s\" from \"%.200s\" is read-only", RNA_property_identifier(self->prop), RNA_struct_identifier(self->ptr.type) );
1090 /* maybe one day we can support this... */
1091 if (RNA_property_type(self->prop) == PROP_COLLECTION) {
1092 PyErr_Format( PyExc_AttributeError, "PropertyRNA - attribute \"%.200s\" from \"%.200s\" is a collection, assignment not supported", RNA_property_identifier(self->prop), RNA_struct_identifier(self->ptr.type) );
1096 if (PyIndex_Check(key)) {
1097 Py_ssize_t i = PyNumber_AsSsize_t(key, PyExc_IndexError);
1098 if (i == -1 && PyErr_Occurred())
1101 return prop_subscript_ass_array_int(self, i, value);
1103 else if (PySlice_Check(key)) {
1104 int len= RNA_property_array_length(&self->ptr, self->prop);
1105 Py_ssize_t start, stop, step, slicelength;
1107 if (PySlice_GetIndicesEx((PySliceObject*)key, len, &start, &stop, &step, &slicelength) < 0)
1110 if (slicelength <= 0) {
1113 else if (step == 1) {
1114 return prop_subscript_ass_array_slice(self, start, stop, value);
1117 PyErr_SetString(PyExc_TypeError, "slice steps not supported with rna");
1122 PyErr_SetString(PyExc_AttributeError, "invalid key, key must be an int");
1128 static PyMappingMethods pyrna_prop_as_mapping = {
1129 ( lenfunc ) pyrna_prop_len, /* mp_length */
1130 ( binaryfunc ) pyrna_prop_subscript, /* mp_subscript */
1131 ( objobjargproc ) pyrna_prop_ass_subscript, /* mp_ass_subscript */
1134 static int pyrna_prop_contains(BPy_PropertyRNA *self, PyObject *value)
1136 PointerRNA newptr; /* not used, just so RNA_property_collection_lookup_string runs */
1137 char *keyname = _PyUnicode_AsString(value);
1140 PyErr_SetString(PyExc_TypeError, "PropertyRNA - key in prop, key must be a string type");
1144 if (RNA_property_type(self->prop) != PROP_COLLECTION) {
1145 PyErr_SetString(PyExc_TypeError, "PropertyRNA - key in prop, is only valid for collection types");
1150 if (RNA_property_collection_lookup_string(&self->ptr, self->prop, keyname, &newptr))
1156 static int pyrna_struct_contains(BPy_StructRNA *self, PyObject *value)
1159 char *name = _PyUnicode_AsString(value);
1162 PyErr_SetString( PyExc_TypeError, "expected a string");
1166 if(RNA_struct_idproperties_check(&self->ptr)==0) {
1167 PyErr_SetString( PyExc_TypeError, "this type doesnt support IDProperties");
1171 group= RNA_struct_idproperties(&self->ptr, 0);
1176 return IDP_GetPropertyFromGroup(group, name) ? 1:0;
1179 static PyObject *pyrna_prop_item(BPy_PropertyRNA *self, Py_ssize_t index)
1181 /* reuse subscript functions */
1182 if (RNA_property_type(self->prop) == PROP_COLLECTION) {
1183 return prop_subscript_collection_int(self, index);
1184 } else if (RNA_property_array_check(&self->ptr, self->prop)) {
1185 return prop_subscript_array_int(self, index);
1188 PyErr_SetString(PyExc_TypeError, "rna type is not an array or a collection");
1192 static PySequenceMethods pyrna_prop_as_sequence = {
1193 NULL, /* Cant set the len otherwise it can evaluate as false */
1194 NULL, /* sq_concat */
1195 NULL, /* sq_repeat */
1196 (ssizeargfunc)pyrna_prop_item, /* sq_item */ /* Only set this so PySequence_Check() returns True */
1197 NULL, /* sq_slice */
1198 NULL, /* sq_ass_item */
1199 NULL, /* sq_ass_slice */
1200 (objobjproc)pyrna_prop_contains, /* sq_contains */
1203 static PySequenceMethods pyrna_struct_as_sequence = {
1204 NULL, /* Cant set the len otherwise it can evaluate as false */
1205 NULL, /* sq_concat */
1206 NULL, /* sq_repeat */
1207 NULL, /* sq_item */ /* Only set this so PySequence_Check() returns True */
1208 NULL, /* sq_slice */
1209 NULL, /* sq_ass_item */
1210 NULL, /* sq_ass_slice */
1211 (objobjproc)pyrna_struct_contains, /* sq_contains */
1214 static PyObject *pyrna_struct_subscript( BPy_StructRNA *self, PyObject *key )
1216 /* mostly copied from BPy_IDGroup_Map_GetItem */
1217 IDProperty *group, *idprop;
1218 char *name= _PyUnicode_AsString(key);
1220 if(RNA_struct_idproperties_check(&self->ptr)==0) {
1221 PyErr_SetString( PyExc_TypeError, "this type doesn't support IDProperties");
1226 PyErr_SetString( PyExc_TypeError, "only strings are allowed as keys of ID properties");
1230 group= RNA_struct_idproperties(&self->ptr, 0);
1233 PyErr_Format( PyExc_KeyError, "key \"%s\" not found", name);
1237 idprop= IDP_GetPropertyFromGroup(group, name);
1240 PyErr_Format( PyExc_KeyError, "key \"%s\" not found", name);
1244 return BPy_IDGroup_WrapData(self->ptr.id.data, idprop);
1247 static int pyrna_struct_ass_subscript( BPy_StructRNA *self, PyObject *key, PyObject *value )
1249 IDProperty *group= RNA_struct_idproperties(&self->ptr, 1);
1252 PyErr_SetString(PyExc_TypeError, "id properties not supported for this type");
1256 return BPy_Wrap_SetMapItem(group, key, value);
1259 static PyMappingMethods pyrna_struct_as_mapping = {
1260 ( lenfunc ) NULL, /* mp_length */
1261 ( binaryfunc ) pyrna_struct_subscript, /* mp_subscript */
1262 ( objobjargproc ) pyrna_struct_ass_subscript, /* mp_ass_subscript */
1265 static PyObject *pyrna_struct_keys(BPy_PropertyRNA *self)
1269 if(RNA_struct_idproperties_check(&self->ptr)==0) {
1270 PyErr_SetString( PyExc_TypeError, "this type doesnt support IDProperties");
1274 group= RNA_struct_idproperties(&self->ptr, 0);
1277 return PyList_New(0);
1279 return BPy_Wrap_GetKeys(group);
1282 static PyObject *pyrna_struct_items(BPy_PropertyRNA *self)
1286 if(RNA_struct_idproperties_check(&self->ptr)==0) {
1287 PyErr_SetString( PyExc_TypeError, "this type doesnt support IDProperties");
1291 group= RNA_struct_idproperties(&self->ptr, 0);
1294 return PyList_New(0);
1296 return BPy_Wrap_GetItems(self->ptr.id.data, group);
1300 static PyObject *pyrna_struct_values(BPy_PropertyRNA *self)
1304 if(RNA_struct_idproperties_check(&self->ptr)==0) {
1305 PyErr_SetString( PyExc_TypeError, "this type doesnt support IDProperties");
1309 group= RNA_struct_idproperties(&self->ptr, 0);
1312 return PyList_New(0);
1314 return BPy_Wrap_GetValues(self->ptr.id.data, group);
1317 static PyObject *pyrna_struct_keyframe_insert(BPy_StructRNA *self, PyObject *args)
1319 char *path, *path_full;
1320 int index= -1; /* default to all */
1321 float cfra = CTX_data_scene(BPy_GetContext())->r.cfra;
1325 if (!PyArg_ParseTuple(args, "s|if:keyframe_insert", &path, &index, &cfra))
1328 if (self->ptr.data==NULL) {
1329 PyErr_Format( PyExc_TypeError, "keyframe_insert, this struct has no data, cant be animated", path);
1333 prop = RNA_struct_find_property(&self->ptr, path);
1336 PyErr_Format( PyExc_TypeError, "keyframe_insert, property \"%s\" not found", path);
1340 if (!RNA_property_animateable(&self->ptr, prop)) {
1341 PyErr_Format( PyExc_TypeError, "keyframe_insert, property \"%s\" not animatable", path);
1345 path_full= RNA_path_from_ID_to_property(&self->ptr, prop);
1347 if (path_full==NULL) {
1348 PyErr_Format( PyExc_TypeError, "keyframe_insert, could not make path to \"%s\"", path);
1352 result= PyBool_FromLong( insert_keyframe((ID *)self->ptr.id.data, NULL, NULL, path_full, index, cfra, 0));
1353 MEM_freeN(path_full);
1359 static PyObject *pyrna_struct_driver_add(BPy_StructRNA *self, PyObject *args)
1361 char *path, *path_full;
1362 int index= -1; /* default to all */
1366 if (!PyArg_ParseTuple(args, "s|i:driver_add", &path, &index))
1369 if (self->ptr.data==NULL) {
1370 PyErr_Format( PyExc_TypeError, "driver_add, this struct has no data, cant be animated", path);
1374 prop = RNA_struct_find_property(&self->ptr, path);
1377 PyErr_Format( PyExc_TypeError, "driver_add, property \"%s\" not found", path);
1381 if (!RNA_property_animateable(&self->ptr, prop)) {
1382 PyErr_Format( PyExc_TypeError, "driver_add, property \"%s\" not animatable", path);
1386 path_full= RNA_path_from_ID_to_property(&self->ptr, prop);
1388 if (path_full==NULL) {
1389 PyErr_Format( PyExc_TypeError, "driver_add, could not make path to \"%s\"", path);
1393 if(ANIM_add_driver((ID *)self->ptr.id.data, path_full, index, 0, DRIVER_TYPE_PYTHON)) {
1394 ID *id= self->ptr.id.data;
1395 AnimData *adt= BKE_animdata_from_id(id);
1401 if(index == -1) { /* all, use a list */
1404 while((fcu= list_find_fcurve(&adt->drivers, path_full, i++))) {
1405 RNA_pointer_create(id, &RNA_FCurve, fcu, &tptr);
1406 item= pyrna_struct_CreatePyObject(&tptr);
1407 PyList_Append(ret, item);
1412 fcu= list_find_fcurve(&adt->drivers, path_full, index);
1413 RNA_pointer_create(id, &RNA_FCurve, fcu, &tptr);
1414 ret= pyrna_struct_CreatePyObject(&tptr);
1422 MEM_freeN(path_full);
1427 static PyObject *pyrna_struct_is_property_set(BPy_StructRNA *self, PyObject *args)
1431 if (!PyArg_ParseTuple(args, "s:is_property_set", &name))
1434 return PyBool_FromLong(RNA_property_is_set(&self->ptr, name));
1437 static PyObject *pyrna_struct_is_property_hidden(BPy_StructRNA *self, PyObject *args)
1443 if (!PyArg_ParseTuple(args, "s:is_property_hidden", &name))
1446 prop= RNA_struct_find_property(&self->ptr, name);
1447 hidden= (prop)? (RNA_property_flag(prop) & PROP_HIDDEN): 1;
1449 return PyBool_FromLong(hidden);
1452 static PyObject *pyrna_struct_path_resolve(BPy_StructRNA *self, PyObject *value)
1454 char *path= _PyUnicode_AsString(value);
1456 PropertyRNA *r_prop;
1459 PyErr_SetString( PyExc_TypeError, "items() is only valid for collection types" );
1463 if (RNA_path_resolve(&self->ptr, path, &r_ptr, &r_prop))
1464 return pyrna_prop_CreatePyObject(&r_ptr, r_prop);
1469 static PyObject *pyrna_struct_path_to_id(BPy_StructRNA *self, PyObject *args)
1476 if (!PyArg_ParseTuple(args, "|s:path_to_id", &name))
1480 prop= RNA_struct_find_property(&self->ptr, name);
1482 PyErr_Format(PyExc_TypeError, "path_to_id(\"%.200s\") not found", name);
1486 path= RNA_path_from_ID_to_property(&self->ptr, prop);
1489 path= RNA_path_from_ID_to_struct(&self->ptr);
1493 if(name) PyErr_Format(PyExc_TypeError, "%.200s.path_to_id(\"%s\") found but does not support path creation", RNA_struct_identifier(self->ptr.type), name);
1494 else PyErr_Format(PyExc_TypeError, "%.200s.path_to_id() does not support path creation for this type", name);
1498 ret= PyUnicode_FromString(path);
1504 static PyObject *pyrna_prop_path_to_id(BPy_PropertyRNA *self)
1507 PropertyRNA *prop = self->prop;
1510 path= RNA_path_from_ID_to_property(&self->ptr, self->prop);
1513 PyErr_Format(PyExc_TypeError, "%.200s.%.200s.path_to_id() does not support path creation for this type", RNA_struct_identifier(self->ptr.type), RNA_property_identifier(prop));
1517 ret= PyUnicode_FromString(path);
1523 static void pyrna_dir_members_py(PyObject *list, PyObject *self)
1526 PyObject **dict_ptr;
1529 dict_ptr= _PyObject_GetDictPtr((PyObject *)self);
1531 if(dict_ptr && (dict=*dict_ptr)) {
1532 list_tmp = PyDict_Keys(dict);
1533 PyList_SetSlice(list, INT_MAX, INT_MAX, list_tmp);
1534 Py_DECREF(list_tmp);
1537 dict= ((PyTypeObject *)Py_TYPE(self))->tp_dict;
1539 list_tmp = PyDict_Keys(dict);
1540 PyList_SetSlice(list, INT_MAX, INT_MAX, list_tmp);
1541 Py_DECREF(list_tmp);
1545 static void pyrna_dir_members_rna(PyObject *list, PointerRNA *ptr)
1550 /* for looping over attrs and funcs */
1552 PropertyRNA *iterprop;
1555 RNA_pointer_create(NULL, &RNA_Struct, ptr->type, &tptr);
1556 iterprop= RNA_struct_find_property(&tptr, "functions");
1558 RNA_PROP_BEGIN(&tptr, itemptr, iterprop) {
1559 idname= RNA_function_identifier(itemptr.data);
1561 pystring = PyUnicode_FromString(idname);
1562 PyList_Append(list, pystring);
1563 Py_DECREF(pystring);
1570 * Collect RNA attributes
1572 char name[256], *nameptr;
1574 iterprop= RNA_struct_iterator_property(ptr->type);
1576 RNA_PROP_BEGIN(ptr, itemptr, iterprop) {
1577 nameptr= RNA_struct_name_get_alloc(&itemptr, name, sizeof(name));
1580 pystring = PyUnicode_FromString(nameptr);
1581 PyList_Append(list, pystring);
1582 Py_DECREF(pystring);
1593 static PyObject *pyrna_struct_dir(BPy_StructRNA *self)
1598 /* Include this incase this instance is a subtype of a python class
1599 * In these instances we may want to return a function or variable provided by the subtype
1601 ret = PyList_New(0);
1603 if (!BPy_StructRNA_CheckExact(self))
1604 pyrna_dir_members_py(ret, (PyObject *)self);
1606 pyrna_dir_members_rna(ret, &self->ptr);
1608 if(self->ptr.type == &RNA_Context) {
1609 ListBase lb = CTX_data_dir_get(self->ptr.data);
1612 for(link=lb.first; link; link=link->next) {
1613 pystring = PyUnicode_FromString(link->data);
1614 PyList_Append(ret, pystring);
1615 Py_DECREF(pystring);
1621 /* Hard coded names */
1622 if(self->ptr.id.data) {
1623 pystring = PyUnicode_FromString("id_data");
1624 PyList_Append(ret, pystring);
1625 Py_DECREF(pystring);
1631 //---------------getattr--------------------------------------------
1632 static PyObject *pyrna_struct_getattro( BPy_StructRNA *self, PyObject *pyname )
1634 char *name = _PyUnicode_AsString(pyname);
1639 if(name[0]=='_') { // rna can't start with a "_", so for __dict__ and similar we can skip using rna lookups
1640 /* annoying exception, maybe we need to have different types for this... */
1641 if((strcmp(name, "__getitem__")==0 || strcmp(name, "__setitem__")==0) && !RNA_struct_idproperties_check(&self->ptr)) {
1642 PyErr_SetString(PyExc_AttributeError, "StructRNA - no __getitem__ support for this type");
1646 ret = PyObject_GenericGetAttr((PyObject *)self, pyname);
1649 else if ((prop = RNA_struct_find_property(&self->ptr, name))) {
1650 ret = pyrna_prop_to_py(&self->ptr, prop);
1652 else if ((func = RNA_struct_find_function(&self->ptr, name))) {
1653 ret = pyrna_func_to_py((BPy_DummyPointerRNA *)self, func);
1655 else if (self->ptr.type == &RNA_Context) {
1660 done= CTX_data_get(self->ptr.data, name, &newptr, &newlb);
1662 if(done==1) { /* found */
1664 ret = pyrna_struct_CreatePyObject(&newptr);
1666 else if (newlb.first) {
1667 CollectionPointerLink *link;
1670 ret = PyList_New(0);
1672 for(link=newlb.first; link; link=link->next) {
1673 linkptr= pyrna_struct_CreatePyObject(&link->ptr);
1674 PyList_Append(ret, linkptr);
1683 else if (done==-1) { /* found but not set */
1687 else { /* not found in the context */
1688 /* lookup the subclass. raise an error if its not found */
1689 ret = PyObject_GenericGetAttr((PyObject *)self, pyname);
1692 BLI_freelistN(&newlb);
1694 else if (strcmp(name, "id_data")==0) { /* XXX - hard coded */
1695 if(self->ptr.id.data) {
1697 RNA_id_pointer_create((ID *)self->ptr.id.data, &id_ptr);
1698 ret = pyrna_struct_CreatePyObject(&id_ptr);
1707 PyErr_Format( PyExc_AttributeError, "StructRNA - Attribute \"%.200s\" not found", name);
1710 /* Include this incase this instance is a subtype of a python class
1711 * In these instances we may want to return a function or variable provided by the subtype
1713 * Also needed to return methods when its not a subtype
1716 /* The error raised here will be displayed */
1717 ret = PyObject_GenericGetAttr((PyObject *)self, pyname);
1724 static int pyrna_struct_pydict_contains(PyObject *self, PyObject *pyname)
1726 PyObject *dict= *(_PyObject_GetDictPtr((PyObject *)self));
1727 if (dict==NULL) /* unlikely */
1730 return PyDict_Contains(dict, pyname);
1734 //--------------- setattr-------------------------------------------
1735 static int pyrna_struct_setattro( BPy_StructRNA *self, PyObject *pyname, PyObject *value )
1737 char *name = _PyUnicode_AsString(pyname);
1738 PropertyRNA *prop = RNA_struct_find_property(&self->ptr, name);
1741 return PyObject_GenericSetAttr((PyObject *)self, pyname, value);
1743 // XXX - This currently allows anything to be assigned to an rna prop, need to see how this should be used
1744 // but for now it makes porting scripts confusing since it fails silently.
1745 // edit: allowing this for setting classes internal attributes.
1746 // edit: allow this for any attribute that alredy exists as a python attr
1747 if ( (name[0]=='_' /* || pyrna_struct_pydict_contains(self, pyname) */ ) &&
1748 !BPy_StructRNA_CheckExact(self) &&
1753 PyErr_Format( PyExc_AttributeError, "StructRNA - Attribute \"%.200s\" not found", name);
1759 if (!RNA_property_editable(&self->ptr, prop)) {
1760 PyErr_Format( PyExc_AttributeError, "StructRNA - Attribute \"%.200s\" from \"%.200s\" is read-only", RNA_property_identifier(prop), RNA_struct_identifier(self->ptr.type) );
1764 /* pyrna_py_to_prop sets its own exceptions */
1765 return pyrna_py_to_prop(&self->ptr, prop, NULL, value, "StructRNA - item.attr = val:");
1768 static PyObject *pyrna_prop_dir(BPy_PropertyRNA *self)
1773 /* Include this incase this instance is a subtype of a python class
1774 * In these instances we may want to return a function or variable provided by the subtype
1776 ret = PyList_New(0);
1778 if (!BPy_PropertyRNA_CheckExact(self))
1779 pyrna_dir_members_py(ret, (PyObject *)self);
1781 if(RNA_property_collection_type_get(&self->ptr, self->prop, &r_ptr))
1782 pyrna_dir_members_rna(ret, &r_ptr);
1788 static PyObject *pyrna_prop_getattro( BPy_PropertyRNA *self, PyObject *pyname )
1790 char *name = _PyUnicode_AsString(pyname);
1792 if(name[0] != '_') {
1793 if (RNA_property_type(self->prop) == PROP_COLLECTION) {
1799 if(RNA_property_collection_type_get(&self->ptr, self->prop, &r_ptr)) {
1800 if ((prop = RNA_struct_find_property(&r_ptr, name))) {
1801 ret = pyrna_prop_to_py(&r_ptr, prop);
1805 else if ((func = RNA_struct_find_function(&r_ptr, name))) {
1806 PyObject *self_collection= pyrna_struct_CreatePyObject(&r_ptr);
1807 ret = pyrna_func_to_py((BPy_DummyPointerRNA *)self_collection, func);
1808 Py_DECREF(self_collection);
1816 /* The error raised here will be displayed */
1817 return PyObject_GenericGetAttr((PyObject *)self, pyname);
1820 //--------------- setattr-------------------------------------------
1821 static int pyrna_prop_setattro( BPy_PropertyRNA *self, PyObject *pyname, PyObject *value )
1823 char *name = _PyUnicode_AsString(pyname);
1826 if (RNA_property_type(self->prop) == PROP_COLLECTION) {
1828 if(RNA_property_collection_type_get(&self->ptr, self->prop, &r_ptr)) {
1829 if ((prop = RNA_struct_find_property(&r_ptr, name))) {
1830 /* pyrna_py_to_prop sets its own exceptions */
1831 return pyrna_py_to_prop(&r_ptr, prop, NULL, value, "BPy_PropertyRNA - Attribute (setattr):");
1836 PyErr_Format( PyExc_AttributeError, "BPy_PropertyRNA - Attribute \"%.200s\" not found", name);
1840 /* odd case, we need to be able return a python method from a tp_getset */
1841 static PyObject *pyrna_prop_add(BPy_PropertyRNA *self)
1845 RNA_property_collection_add(&self->ptr, self->prop, &r_ptr);
1847 PyErr_SetString( PyExc_TypeError, "add() not supported for this collection");
1851 return pyrna_struct_CreatePyObject(&r_ptr);
1855 static PyObject *pyrna_prop_remove(BPy_PropertyRNA *self, PyObject *value)
1858 int key= PyLong_AsSsize_t(value);
1860 if (key==-1 && PyErr_Occurred()) {
1861 PyErr_SetString( PyExc_TypeError, "remove() expected one int argument");
1865 if(!RNA_property_collection_remove(&self->ptr, self->prop, key)) {
1866 PyErr_SetString( PyExc_TypeError, "remove() not supported for this collection");
1876 /*****************************************************************************/
1877 /* Python attributes get/set structure: */
1878 /*****************************************************************************/
1880 static PyGetSetDef pyrna_prop_getseters[] = {
1881 {"active", (getter)pyrna_prop_get_active, (setter)pyrna_prop_set_active, "", NULL},
1882 {NULL,NULL,NULL,NULL,NULL} /* Sentinel */
1886 static PyObject *pyrna_prop_keys(BPy_PropertyRNA *self)
1889 if (RNA_property_type(self->prop) != PROP_COLLECTION) {
1890 PyErr_SetString( PyExc_TypeError, "keys() is only valid for collection types" );
1894 char name[256], *nameptr;
1896 ret = PyList_New(0);
1898 RNA_PROP_BEGIN(&self->ptr, itemptr, self->prop) {
1899 nameptr= RNA_struct_name_get_alloc(&itemptr, name, sizeof(name));
1902 /* add to python list */
1903 item = PyUnicode_FromString( nameptr );
1904 PyList_Append(ret, item);
1918 static PyObject *pyrna_prop_items(BPy_PropertyRNA *self)
1921 if (RNA_property_type(self->prop) != PROP_COLLECTION) {
1922 PyErr_SetString( PyExc_TypeError, "items() is only valid for collection types" );
1926 char name[256], *nameptr;
1929 ret = PyList_New(0);
1931 RNA_PROP_BEGIN(&self->ptr, itemptr, self->prop) {
1933 /* add to python list */
1934 item= PyTuple_New(2);
1935 nameptr= RNA_struct_name_get_alloc(&itemptr, name, sizeof(name));
1937 PyTuple_SET_ITEM(item, 0, PyUnicode_FromString( nameptr ));
1942 PyTuple_SET_ITEM(item, 0, PyLong_FromSsize_t(i)); /* a bit strange but better then returning an empty list */
1944 PyTuple_SET_ITEM(item, 1, pyrna_struct_CreatePyObject(&itemptr));
1946 PyList_Append(ret, item);
1959 static PyObject *pyrna_prop_values(BPy_PropertyRNA *self)
1963 if (RNA_property_type(self->prop) != PROP_COLLECTION) {
1964 PyErr_SetString( PyExc_TypeError, "values() is only valid for collection types" );
1968 ret = PyList_New(0);
1970 RNA_PROP_BEGIN(&self->ptr, itemptr, self->prop) {
1971 item = pyrna_struct_CreatePyObject(&itemptr);
1972 PyList_Append(ret, item);
1981 static PyObject *pyrna_struct_get(BPy_StructRNA *self, PyObject *args)
1983 IDProperty *group, *idprop;
1986 PyObject* def = Py_None;
1988 if (!PyArg_ParseTuple(args, "s|O:get", &key, &def))
1991 /* mostly copied from BPy_IDGroup_Map_GetItem */
1992 if(RNA_struct_idproperties_check(&self->ptr)==0) {
1993 PyErr_SetString( PyExc_TypeError, "this type doesn't support IDProperties");
1997 group= RNA_struct_idproperties(&self->ptr, 0);
1999 idprop= IDP_GetPropertyFromGroup(group, key);
2002 return BPy_IDGroup_WrapData(self->ptr.id.data, idprop);
2009 static PyObject *pyrna_prop_get(BPy_PropertyRNA *self, PyObject *args)
2014 PyObject* def = Py_None;
2016 if (!PyArg_ParseTuple(args, "s|O:get", &key, &def))
2019 if(RNA_property_collection_lookup_string(&self->ptr, self->prop, key, &newptr))
2020 return pyrna_struct_CreatePyObject(&newptr);
2026 static void foreach_attr_type( BPy_PropertyRNA *self, char *attr,
2027 /* values to assign */
2028 RawPropertyType *raw_type, int *attr_tot, int *attr_signed )
2033 *attr_signed= FALSE;
2035 RNA_PROP_BEGIN(&self->ptr, itemptr, self->prop) {
2036 prop = RNA_struct_find_property(&itemptr, attr);
2037 *raw_type= RNA_property_raw_type(prop);
2038 *attr_tot = RNA_property_array_length(&itemptr, prop);
2039 *attr_signed= (RNA_property_subtype(prop)==PROP_UNSIGNED) ? FALSE:TRUE;
2045 /* pyrna_prop_foreach_get/set both use this */
2046 static int foreach_parse_args(
2047 BPy_PropertyRNA *self, PyObject *args,
2049 /*values to assign */
2050 char **attr, PyObject **seq, int *tot, int *size, RawPropertyType *raw_type, int *attr_tot, int *attr_signed)
2057 *size= *raw_type= *attr_tot= *attr_signed= FALSE;
2059 if(!PyArg_ParseTuple(args, "sO", attr, seq) || (!PySequence_Check(*seq) && PyObject_CheckBuffer(*seq))) {
2060 PyErr_SetString( PyExc_TypeError, "foreach_get(attr, sequence) expects a string and a sequence" );
2064 *tot= PySequence_Length(*seq); // TODO - buffer may not be a sequence! array.array() is tho.
2067 foreach_attr_type(self, *attr, raw_type, attr_tot, attr_signed);
2068 *size= RNA_raw_type_sizeof(*raw_type);
2070 #if 0 // works fine but not strictly needed, we could allow RNA_property_collection_raw_* to do the checks
2074 if (RNA_property_type(self->prop) == PROP_COLLECTION)
2075 array_tot = RNA_property_collection_length(&self->ptr, self->prop);
2077 array_tot = RNA_property_array_length(&self->ptr, self->prop);
2080 target_tot= array_tot * (*attr_tot);
2082 /* rna_access.c - rna_raw_access(...) uses this same method */
2083 if(target_tot != (*tot)) {
2084 PyErr_Format( PyExc_TypeError, "foreach_get(attr, sequence) sequence length mismatch given %d, needed %d", *tot, target_tot);
2093 static int foreach_compat_buffer(RawPropertyType raw_type, int attr_signed, const char *format)
2095 char f = format ? *format:'B'; /* B is assumed when not set */
2099 if (attr_signed) return (f=='b') ? 1:0;
2100 else return (f=='B') ? 1:0;
2101 case PROP_RAW_SHORT:
2102 if (attr_signed) return (f=='h') ? 1:0;
2103 else return (f=='H') ? 1:0;
2105 if (attr_signed) return (f=='i') ? 1:0;
2106 else return (f=='I') ? 1:0;
2107 case PROP_RAW_FLOAT:
2108 return (f=='f') ? 1:0;
2109 case PROP_RAW_DOUBLE:
2110 return (f=='d') ? 1:0;
2116 static PyObject *foreach_getset(BPy_PropertyRNA *self, PyObject *args, int set)
2118 PyObject *item = NULL;
2119 int i=0, ok=0, buffer_is_compat;
2122 /* get/set both take the same args currently */
2125 int tot, size, attr_tot, attr_signed;
2126 RawPropertyType raw_type;
2128 if(foreach_parse_args(self, args, &attr, &seq, &tot, &size, &raw_type, &attr_tot, &attr_signed) < 0)
2136 if(set) { /* get the array from python */
2137 buffer_is_compat = FALSE;
2138 if(PyObject_CheckBuffer(seq)) {
2140 PyObject_GetBuffer(seq, &buf, PyBUF_SIMPLE | PyBUF_FORMAT);
2142 /* check if the buffer matches */
2144 buffer_is_compat = foreach_compat_buffer(raw_type, attr_signed, buf.format);
2146 if(buffer_is_compat) {
2147 ok = RNA_property_collection_raw_set(NULL, &self->ptr, self->prop, attr, buf.buf, raw_type, tot);
2150 PyBuffer_Release(&buf);
2153 /* could not use the buffer, fallback to sequence */
2154 if(!buffer_is_compat) {
2155 array= PyMem_Malloc(size * tot);
2157 for( ; i<tot; i++) {
2158 item= PySequence_GetItem(seq, i);
2161 ((char *)array)[i]= (char)PyLong_AsSsize_t(item);
2163 case PROP_RAW_SHORT:
2164 ((short *)array)[i]= (short)PyLong_AsSsize_t(item);
2167 ((int *)array)[i]= (int)PyLong_AsSsize_t(item);
2169 case PROP_RAW_FLOAT:
2170 ((float *)array)[i]= (float)PyFloat_AsDouble(item);
2172 case PROP_RAW_DOUBLE:
2173 ((double *)array)[i]= (double)PyFloat_AsDouble(item);
2180 ok = RNA_property_collection_raw_set(NULL, &self->ptr, self->prop, attr, array, raw_type, tot);
2184 buffer_is_compat = FALSE;
2185 if(PyObject_CheckBuffer(seq)) {
2187 PyObject_GetBuffer(seq, &buf, PyBUF_SIMPLE | PyBUF_FORMAT);
2189 /* check if the buffer matches, TODO - signed/unsigned types */
2191 buffer_is_compat = foreach_compat_buffer(raw_type, attr_signed, buf.format);
2193 if(buffer_is_compat) {
2194 ok = RNA_property_collection_raw_get(NULL, &self->ptr, self->prop, attr, buf.buf, raw_type, tot);
2197 PyBuffer_Release(&buf);
2200 /* could not use the buffer, fallback to sequence */
2201 if(!buffer_is_compat) {
2202 array= PyMem_Malloc(size * tot);
2204 ok = RNA_property_collection_raw_get(NULL, &self->ptr, self->prop, attr, array, raw_type, tot);
2206 if(!ok) i= tot; /* skip the loop */
2208 for( ; i<tot; i++) {
2212 item= PyLong_FromSsize_t( (Py_ssize_t) ((char *)array)[i] );
2214 case PROP_RAW_SHORT:
2215 item= PyLong_FromSsize_t( (Py_ssize_t) ((short *)array)[i] );
2218 item= PyLong_FromSsize_t( (Py_ssize_t) ((int *)array)[i] );
2220 case PROP_RAW_FLOAT:
2221 item= PyFloat_FromDouble( (double) ((float *)array)[i] );
2223 case PROP_RAW_DOUBLE:
2224 item= PyFloat_FromDouble( (double) ((double *)array)[i] );
2228 PySequence_SetItem(seq, i, item);
2234 if(PyErr_Occurred()) {
2235 /* Maybe we could make our own error */
2237 PyErr_SetString(PyExc_SystemError, "could not access the py sequence");
2241 PyErr_SetString(PyExc_SystemError, "internal error setting the array");
2251 static PyObject *pyrna_prop_foreach_get(BPy_PropertyRNA *self, PyObject *args)
2253 return foreach_getset(self, args, 0);
2256 static PyObject *pyrna_prop_foreach_set(BPy_PropertyRNA *self, PyObject *args)
2258 return foreach_getset(self, args, 1);
2261 /* A bit of a kludge, make a list out of a collection or array,
2262 * then return the lists iter function, not especially fast but convenient for now */
2263 PyObject *pyrna_prop_iter(BPy_PropertyRNA *self)
2265 /* Try get values from a collection */
2269 if(RNA_property_array_check(&self->ptr, self->prop)) {
2270 int len = pyrna_prop_array_length(self);
2273 ret = PyList_New(len);
2275 for (i=0; i < len; i++) {
2276 PyList_SET_ITEM(ret, i, pyrna_prop_to_py_index(self, i));
2279 else if ((ret = pyrna_prop_values(self))) {
2283 PyErr_SetString( PyExc_TypeError, "this BPy_PropertyRNA object is not iterable" );
2288 /* we know this is a list so no need to PyIter_Check */
2289 iter = PyObject_GetIter(ret);
2294 static struct PyMethodDef pyrna_struct_methods[] = {
2296 /* only for PointerRNA's with ID'props */
2297 {"keys", (PyCFunction)pyrna_struct_keys, METH_NOARGS, NULL},
2298 {"values", (PyCFunction)pyrna_struct_values, METH_NOARGS, NULL},
2299 {"items", (PyCFunction)pyrna_struct_items, METH_NOARGS, NULL},
2301 {"get", (PyCFunction)pyrna_struct_get, METH_VARARGS, NULL},
2303 /* maybe this become and ID function */
2304 {"keyframe_insert", (PyCFunction)pyrna_struct_keyframe_insert, METH_VARARGS, NULL},
2305 {"driver_add", (PyCFunction)pyrna_struct_driver_add, METH_VARARGS, NULL},
2306 {"is_property_set", (PyCFunction)pyrna_struct_is_property_set, METH_VARARGS, NULL},
2307 {"is_property_hidden", (PyCFunction)pyrna_struct_is_property_hidden, METH_VARARGS, NULL},
2308 {"path_resolve", (PyCFunction)pyrna_struct_path_resolve, METH_O, NULL},
2309 {"path_to_id", (PyCFunction)pyrna_struct_path_to_id, METH_VARARGS, NULL},
2310 {"__dir__", (PyCFunction)pyrna_struct_dir, METH_NOARGS, NULL},
2311 {NULL, NULL, 0, NULL}
2314 static struct PyMethodDef pyrna_prop_methods[] = {
2315 {"keys", (PyCFunction)pyrna_prop_keys, METH_NOARGS, NULL},
2316 {"items", (PyCFunction)pyrna_prop_items, METH_NOARGS,NULL},
2317 {"values", (PyCFunction)pyrna_prop_values, METH_NOARGS, NULL},
2319 {"get", (PyCFunction)pyrna_prop_get, METH_VARARGS, NULL},
2321 /* moved into a getset */
2322 {"add", (PyCFunction)pyrna_prop_add, METH_NOARGS, NULL},
2323 {"remove", (PyCFunction)pyrna_prop_remove, METH_O, NULL},
2325 /* almost the same as the srna function */
2326 {"path_to_id", (PyCFunction)pyrna_prop_path_to_id, METH_NOARGS, NULL},
2328 /* array accessor function */
2329 {"foreach_get", (PyCFunction)pyrna_prop_foreach_get, METH_VARARGS, NULL},
2330 {"foreach_set", (PyCFunction)pyrna_prop_foreach_set, METH_VARARGS, NULL},
2331 {"__dir__", (PyCFunction)pyrna_prop_dir, METH_NOARGS, NULL},
2332 {NULL, NULL, 0, NULL}
2335 /* only needed for subtyping, so a new class gets a valid BPy_StructRNA
2336 * todo - also accept useful args */
2337 static PyObject * pyrna_struct_new(PyTypeObject *type, PyObject *args, PyObject *kwds) {
2339 BPy_StructRNA *base = NULL;
2341 if (!PyArg_ParseTuple(args, "O!:Base BPy_StructRNA", &pyrna_struct_Type, &base))
2344 if (type == &pyrna_struct_Type) {
2345 return pyrna_struct_CreatePyObject(&base->ptr);
2347 BPy_StructRNA *ret = (BPy_StructRNA *) type->tp_alloc(type, 0);
2348 ret->ptr = base->ptr;
2349 return (PyObject *)ret;
2353 /* only needed for subtyping, so a new class gets a valid BPy_StructRNA
2354 * todo - also accept useful args */
2355 static PyObject * pyrna_prop_new(PyTypeObject *type, PyObject *args, PyObject *kwds) {
2357 BPy_PropertyRNA *base = NULL;
2359 if (!PyArg_ParseTuple(args, "O!:Base BPy_PropertyRNA", &pyrna_prop_Type, &base))
2362 if (type == &pyrna_prop_Type) {
2363 return pyrna_prop_CreatePyObject(&base->ptr, base->prop);
2365 BPy_PropertyRNA *ret = (BPy_PropertyRNA *) type->tp_alloc(type, 0);
2366 ret->ptr = base->ptr;
2367 ret->prop = base->prop;
2368 return (PyObject *)ret;
2372 PyObject *pyrna_param_to_py(PointerRNA *ptr, PropertyRNA *prop, void *data)
2375 int type = RNA_property_type(prop);
2379 if(RNA_property_array_check(ptr, prop)) {
2380 int len = RNA_property_array_length(ptr, prop);
2382 /* resolve the array from a new pytype */
2383 ret = PyTuple_New(len);
2385 /* kazanbas: TODO make multidim sequences here */
2389 for(a=0; a<len; a++)
2390 PyTuple_SET_ITEM(ret, a, PyBool_FromLong( ((int*)data)[a] ));
2393 for(a=0; a<len; a++)
2394 PyTuple_SET_ITEM(ret, a, PyLong_FromSsize_t( (Py_ssize_t)((int*)data)[a] ));
2397 for(a=0; a<len; a++)
2398 PyTuple_SET_ITEM(ret, a, PyFloat_FromDouble( ((float*)data)[a] ));
2401 PyErr_Format(PyExc_TypeError, "RNA Error: unknown array type \"%d\" (pyrna_param_to_py)", type);
2407 /* see if we can coorce into a python type - PropertyType */
2410 ret = PyBool_FromLong( *(int*)data );
2413 ret = PyLong_FromSsize_t( (Py_ssize_t)*(int*)data );
2416 ret = PyFloat_FromDouble( *(float*)data );
2420 ret = PyUnicode_FromString( *(char**)data );
2425 const char *identifier;
2426 int val = *(int*)data;
2428 if (RNA_property_enum_identifier(BPy_GetContext(), ptr, prop, val, &identifier)) {
2429 ret = PyUnicode_FromString( identifier );
2431 /* prefer not fail silently incase of api errors, maybe disable it later */
2432 char error_str[128];
2433 sprintf(error_str, "RNA Warning: Current value \"%d\" matches no enum", val);
2434 PyErr_Warn(PyExc_RuntimeWarning, error_str);
2436 ret = PyUnicode_FromString( "" );
2437 /*PyErr_Format(PyExc_AttributeError, "RNA Error: Current value \"%d\" matches no enum", val);
2446 StructRNA *type= RNA_property_pointer_type(ptr, prop);
2447 int flag = RNA_property_flag(prop);
2449 if(flag & PROP_RNAPTR) {
2450 /* in this case we get the full ptr */
2451 newptr= *(PointerRNA*)data;
2454 if(RNA_struct_is_ID(type)) {
2455 RNA_id_pointer_create(*(void**)data, &newptr);
2457 /* note: this is taken from the function's ID pointer
2458 * and will break if a function returns a pointer from
2459 * another ID block, watch this! - it should at least be
2460 * easy to debug since they are all ID's */
2461 RNA_pointer_create(ptr->id.data, type, *(void**)data, &newptr);
2466 ret = pyrna_struct_CreatePyObject(&newptr);
2473 case PROP_COLLECTION:
2475 ListBase *lb= (ListBase*)data;
2476 CollectionPointerLink *link;
2479 ret = PyList_New(0);
2481 for(link=lb->first; link; link=link->next) {
2482 linkptr= pyrna_struct_CreatePyObject(&link->ptr);
2483 PyList_Append(ret, linkptr);
2490 PyErr_Format(PyExc_TypeError, "RNA Error: unknown type \"%d\" (pyrna_param_to_py)", type);
2499 static PyObject * pyrna_func_call(PyObject *self, PyObject *args, PyObject *kw)
2501 /* Note, both BPy_StructRNA and BPy_PropertyRNA can be used here */
2502 PointerRNA *self_ptr= &(((BPy_DummyPointerRNA *)PyTuple_GET_ITEM(self, 0))->ptr);
2503 FunctionRNA *self_func= PyCObject_AsVoidPtr(PyTuple_GET_ITEM(self, 1));
2506 ParameterList parms;
2507 ParameterIterator iter;
2508 PropertyRNA *pret, *parm;
2509 PyObject *ret, *item;
2510 int i, args_len, parms_len, flag, err= 0, kw_tot= 0, kw_arg;
2511 const char *parm_id;
2512 void *retdata= NULL;
2514 /* Should never happen but it does in rare cases */
2515 if(self_ptr==NULL) {
2516 PyErr_SetString(PyExc_RuntimeError, "rna functions internal rna pointer is NULL, this is a bug. aborting");
2520 if(self_func==NULL) {
2521 PyErr_Format(PyExc_RuntimeError, "%.200s.<unknown>(): rna function internal function is NULL, this is a bug. aborting", RNA_struct_identifier(self_ptr->type));
2525 /* include the ID pointer for pyrna_param_to_py() so we can include the
2526 * ID pointer on return values, this only works when returned values have
2527 * the same ID as the functions. */
2528 RNA_pointer_create(self_ptr->id.data, &RNA_Function, self_func, &funcptr);
2530 pret= RNA_function_return(self_func);
2531 args_len= PyTuple_GET_SIZE(args);
2533 RNA_parameter_list_create(&parms, self_ptr, self_func);
2534 RNA_parameter_list_begin(&parms, &iter);
2535 parms_len = RNA_parameter_list_size(&parms);
2537 if(args_len + (kw ? PyDict_Size(kw):0) > parms_len) {
2538 PyErr_Format(PyExc_TypeError, "%.200s.%.200s(): takes at most %d arguments, got %d", RNA_struct_identifier(self_ptr->type), RNA_function_identifier(self_func), parms_len, args_len);
2542 /* parse function parameters */
2543 for (i= 0; iter.valid && err==0; RNA_parameter_list_next(&iter)) {
2551 parm_id= RNA_property_identifier(parm);
2552 flag= RNA_property_flag(parm);
2555 if ((i < args_len) && (flag & PROP_REQUIRED)) {
2556 item= PyTuple_GET_ITEM(args, i);
2561 else if (kw != NULL) {
2562 item= PyDict_GetItemString(kw, parm_id); /* borrow ref */
2564 kw_tot++; /* make sure invalid keywords are not given */
2570 if(flag & PROP_REQUIRED) {
2571 PyErr_Format(PyExc_TypeError, "%.200s.%.200s(): required parameter \"%.200s\" not specified", RNA_struct_identifier(self_ptr->type), RNA_function_identifier(self_func), parm_id);
2575 else /* PyDict_GetItemString wont raise an error */
2579 err= pyrna_py_to_prop(&funcptr, parm, iter.data, item, "");
2582 /* the error generated isnt that useful, so generate it again with a useful prefix
2583 * could also write a function to prepend to error messages */
2584 char error_prefix[512];
2585 PyErr_Clear(); /* re-raise */
2588 snprintf(error_prefix, sizeof(error_prefix), "%s.%s(): error with keyword argument \"%s\" - ", RNA_struct_identifier(self_ptr->type), RNA_function_identifier(self_func), parm_id);
2590 snprintf(error_prefix, sizeof(error_prefix), "%s.%s(): error with argument %d, \"%s\" - ", RNA_struct_identifier(self_ptr->type), RNA_function_identifier(self_func), i, parm_id);
2592 pyrna_py_to_prop(&funcptr, parm, iter.data, item, error_prefix);
2599 /* Check if we gave args that dont exist in the function
2600 * printing the error is slow but it should only happen when developing.
2601 * the if below is quick, checking if it passed less keyword args then we gave.
2602 * (Dont overwrite the error if we have one, otherwise can skip important messages and confuse with args)
2604 if(err == 0 && kw && (PyDict_Size(kw) > kw_tot)) {
2605 PyObject *key, *value;
2608 DynStr *bad_args= BLI_dynstr_new();
2609 DynStr *good_args= BLI_dynstr_new();
2611 char *arg_name, *bad_args_str, *good_args_str;
2612 int found= FALSE, first= TRUE;
2614 while (PyDict_Next(kw, &pos, &key, &value)) {
2616 arg_name= _PyUnicode_AsString(key);
2619 if(arg_name==NULL) { /* unlikely the argname is not a string but ignore if it is*/
2623 /* Search for arg_name */
2624 RNA_parameter_list_begin(&parms, &iter);
2625 for(; iter.valid; RNA_parameter_list_next(&iter)) {
2627 if (strcmp(arg_name, RNA_property_identifier(parm))==0) {
2633 RNA_parameter_list_end(&iter);
2636 BLI_dynstr_appendf(bad_args, first ? "%s" : ", %s", arg_name);
2642 /* list good args */
2645 RNA_parameter_list_begin(&parms, &iter);
2646 for(; iter.valid; RNA_parameter_list_next(&iter)) {
2648 BLI_dynstr_appendf(good_args, first ? "%s" : ", %s", RNA_property_identifier(parm));
2651 RNA_parameter_list_end(&iter);
2654 bad_args_str= BLI_dynstr_get_cstring(bad_args);
2655 good_args_str= BLI_dynstr_get_cstring(good_args);
2657 PyErr_Format(PyExc_TypeError, "%.200s.%.200s(): was called with invalid keyword arguments(s) (%s), expected (%s)", RNA_struct_identifier(self_ptr->type), RNA_function_identifier(self_func), bad_args_str, good_args_str);
2659 BLI_dynstr_free(bad_args);
2660 BLI_dynstr_free(good_args);
2661 MEM_freeN(bad_args_str);
2662 MEM_freeN(good_args_str);
2671 bContext *C= BPy_GetContext();
2673 BKE_reports_init(&reports, RPT_STORE);
2674 RNA_function_call(C, &reports, self_ptr, self_func, &parms);
2676 err= (BPy_reports_to_error(&reports))? -1: 0;
2677 BKE_reports_clear(&reports);
2682 ret= pyrna_param_to_py(&funcptr, pret, retdata);
2684 /* possible there is an error in conversion */
2692 RNA_parameter_list_end(&iter);
2693 RNA_parameter_list_free(&parms);
2704 /*-----------------------BPy_StructRNA method def------------------------------*/
2705 PyTypeObject pyrna_struct_Type = {
2706 PyVarObject_HEAD_INIT(NULL, 0)
2707 "StructRNA", /* tp_name */
2708 sizeof( BPy_StructRNA ), /* tp_basicsize */
2709 0, /* tp_itemsize */
2711 ( destructor ) pyrna_struct_dealloc,/* tp_dealloc */
2712 NULL, /* printfunc tp_print; */
2713 NULL, /* getattrfunc tp_getattr; */
2714 NULL, /* setattrfunc tp_setattr; */
2715 NULL, /* tp_compare */ /* DEPRECATED in python 3.0! */
2716 ( reprfunc ) pyrna_struct_repr, /* tp_repr */
2718 /* Method suites for standard classes */
2720 NULL, /* PyNumberMethods *tp_as_number; */
2721 &pyrna_struct_as_sequence, /* PySequenceMethods *tp_as_sequence; */
2722 &pyrna_struct_as_mapping, /* PyMappingMethods *tp_as_mapping; */
2724 /* More standard operations (here for binary compatibility) */
2726 ( hashfunc )pyrna_struct_hash, /* hashfunc tp_hash; */
2727 NULL, /* ternaryfunc tp_call; */
2728 NULL, /* reprfunc tp_str; */
2729 ( getattrofunc ) pyrna_struct_getattro, /* getattrofunc tp_getattro; */
2730 ( setattrofunc ) pyrna_struct_setattro, /* setattrofunc tp_setattro; */
2732 /* Functions to access object as input/output buffer */
2733 NULL, /* PyBufferProcs *tp_as_buffer; */
2735 /*** Flags to define presence of optional/expanded features ***/
2736 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE, /* long tp_flags; */
2738 NULL, /* char *tp_doc; Documentation string */
2739 /*** Assigned meaning in release 2.0 ***/
2740 /* call function for all accessible objects */
2741 NULL, /* traverseproc tp_traverse; */
2743 /* delete references to contained objects */
2744 NULL, /* inquiry tp_clear; */
2746 /*** Assigned meaning in release 2.1 ***/
2747 /*** rich comparisons ***/
2748 (richcmpfunc)pyrna_struct_richcmp, /* richcmpfunc tp_richcompare; */
2750 /*** weak reference enabler ***/
2751 0, /* long tp_weaklistoffset; */
2753 /*** Added in release 2.2 ***/
2755 NULL, /* getiterfunc tp_iter; */
2756 NULL, /* iternextfunc tp_iternext; */
2758 /*** Attribute descriptor and subclassing stuff ***/
2759 pyrna_struct_methods, /* struct PyMethodDef *tp_methods; */
2760 NULL, /* struct PyMemberDef *tp_members; */
2761 NULL, /* struct PyGetSetDef *tp_getset; */
2762 NULL, /* struct _typeobject *tp_base; */
2763 NULL, /* PyObject *tp_dict; */
2764 NULL, /* descrgetfunc tp_descr_get; */
2765 NULL, /* descrsetfunc tp_descr_set; */
2766 0, /* long tp_dictoffset; */
2767 NULL, /* initproc tp_init; */
2768 NULL, /* allocfunc tp_alloc; */
2769 pyrna_struct_new, /* newfunc tp_new; */
2770 /* Low-level free-memory routine */
2771 NULL, /* freefunc tp_free; */
2772 /* For PyObject_IS_GC */
2773 NULL, /* inquiry tp_is_gc; */
2774 NULL, /* PyObject *tp_bases; */
2775 /* method resolution order */
2776 NULL, /* PyObject *tp_mro; */
2777 NULL, /* PyObject *tp_cache; */
2778 NULL, /* PyObject *tp_subclasses; */
2779 NULL, /* PyObject *tp_weaklist; */
2783 /*-----------------------BPy_PropertyRNA method def------------------------------*/
2784 PyTypeObject pyrna_prop_Type = {
2785 PyVarObject_HEAD_INIT(NULL, 0)
2786 "PropertyRNA", /* tp_name */
2787 sizeof( BPy_PropertyRNA ), /* tp_basicsize */
2788 0, /* tp_itemsize */
2790 NULL, /* tp_dealloc */
2791 NULL, /* printfunc tp_print; */
2792 NULL, /* getattrfunc tp_getattr; */
2793 NULL, /* setattrfunc tp_setattr; */
2794 NULL, /* tp_compare */ /* DEPRECATED in python 3.0! */
2795 ( reprfunc ) pyrna_prop_repr, /* tp_repr */
2797 /* Method suites for standard classes */
2799 NULL, /* PyNumberMethods *tp_as_number; */
2800 &pyrna_prop_as_sequence, /* PySequenceMethods *tp_as_sequence; */
2801 &pyrna_prop_as_mapping, /* PyMappingMethods *tp_as_mapping; */
2803 /* More standard operations (here for binary compatibility) */
2805 NULL, /* hashfunc tp_hash; */
2806 NULL, /* ternaryfunc tp_call; */
2807 NULL, /* reprfunc tp_str; */
2809 /* will only use these if this is a subtype of a py class */
2810 ( getattrofunc ) pyrna_prop_getattro, /* getattrofunc tp_getattro; */
2811 ( setattrofunc ) pyrna_prop_setattro, /* setattrofunc tp_setattro; */
2813 /* Functions to access object as input/output buffer */
2814 NULL, /* PyBufferProcs *tp_as_buffer; */
2816 /*** Flags to define presence of optional/expanded features ***/
2817 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE, /* long tp_flags; */
2819 NULL, /* char *tp_doc; Documentation string */
2820 /*** Assigned meaning in release 2.0 ***/
2821 /* call function for all accessible objects */
2822 NULL, /* traverseproc tp_traverse; */
2824 /* delete references to contained objects */
2825 NULL, /* inquiry tp_clear; */
2827 /*** Assigned meaning in release 2.1 ***/
2828 /*** rich comparisons ***/
2829 (richcmpfunc)pyrna_prop_richcmp, /* richcmpfunc tp_richcompare; */
2831 /*** weak reference enabler ***/
2832 0, /* long tp_weaklistoffset; */
2834 /*** Added in release 2.2 ***/
2836 (getiterfunc)pyrna_prop_iter, /* getiterfunc tp_iter; */
2837 NULL, /* iternextfunc tp_iternext; */
2839 /*** Attribute descriptor and subclassing stuff ***/
2840 pyrna_prop_methods, /* struct PyMethodDef *tp_methods; */
2841 NULL, /* struct PyMemberDef *tp_members; */
2842 NULL /*pyrna_prop_getseters*/, /* struct PyGetSetDef *tp_getset; */
2843 NULL, /* struct _typeobject *tp_base; */
2844 NULL, /* PyObject *tp_dict; */
2845 NULL, /* descrgetfunc tp_descr_get; */
2846 NULL, /* descrsetfunc tp_descr_set; */
2847 0, /* long tp_dictoffset; */
2848 NULL, /* initproc tp_init; */
2849 NULL, /* allocfunc tp_alloc; */
2850 pyrna_prop_new, /* newfunc tp_new; */
2851 /* Low-level free-memory routine */
2852 NULL, /* freefunc tp_free; */
2853 /* For PyObject_IS_GC */
2854 NULL, /* inquiry tp_is_gc; */
2855 NULL, /* PyObject *tp_bases; */
2856 /* method resolution order */
2857 NULL, /* PyObject *tp_mro; */
2858 NULL, /* PyObject *tp_cache; */
2859 NULL, /* PyObject *tp_subclasses; */
2860 NULL, /* PyObject *tp_weaklist; */
2864 static struct PyMethodDef pyrna_struct_subtype_methods[] = {
2865 {"BoolProperty", (PyCFunction)BPy_BoolProperty, METH_VARARGS|METH_KEYWORDS, ""},
2866 {"IntProperty", (PyCFunction)BPy_IntProperty, METH_VARARGS|METH_KEYWORDS, ""},
2867 {"FloatProperty", (PyCFunction)BPy_FloatProperty, METH_VARARGS|METH_KEYWORDS, ""},
2868 {"StringProperty", (PyCFunction)BPy_StringProperty, METH_VARARGS|METH_KEYWORDS, ""},
2869 {"EnumProperty", (PyCFunction)BPy_EnumProperty, METH_VARARGS|METH_KEYWORDS, ""},
2870 {"PointerProperty", (PyCFunction)BPy_PointerProperty, METH_VARARGS|METH_KEYWORDS, ""},
2871 {"CollectionProperty", (PyCFunction)BPy_CollectionProperty, METH_VARARGS|METH_KEYWORDS, ""},
2873 // {"__get_rna", (PyCFunction)BPy_GetStructRNA, METH_NOARGS, ""},
2874 {NULL, NULL, 0, NULL}
2877 static void pyrna_subtype_set_rna(PyObject *newclass, StructRNA *srna)
2882 Py_INCREF(newclass);
2884 if (RNA_struct_py_type_get(srna))
2885 PyObSpit("RNA WAS SET - ", RNA_struct_py_type_get(srna));
2887 Py_XDECREF(((PyObject *)RNA_struct_py_type_get(srna)));
2889 RNA_struct_py_type_set(srna, (void *)newclass); /* Store for later use */
2891 /* Not 100% needed but useful,
2892 * having an instance within a type looks wrong however this instance IS an rna type */
2894 /* python deals with the curcular ref */
2895 RNA_pointer_create(NULL, &RNA_Struct, srna, &ptr);
2896 item = pyrna_struct_CreatePyObject(&ptr);
2898 //item = PyCObject_FromVoidPtr(srna, NULL);
2899 PyDict_SetItemString(((PyTypeObject *)newclass)->tp_dict, "bl_rna", item);
2901 /* done with rna instance */
2903 /* attach functions into the class
2904 * so you can do... bpy.types.Scene.SomeFunction()
2909 for(ml= pyrna_struct_subtype_methods; ml->ml_name; ml++){
2910 PyObject_SetAttrString(newclass, ml->ml_name, PyCFunction_New(ml, newclass));
2916 static StructRNA *srna_from_self(PyObject *self);
2917 PyObject *BPy_GetStructRNA(PyObject *self)
2919 StructRNA *srna= pyrna_struct_as_srna(self);
2923 RNA_pointer_create(NULL, &RNA_Struct, srna, &ptr);
2924 ret= pyrna_struct_CreatePyObject(&ptr);
2935 static PyObject* pyrna_srna_Subtype(StructRNA *srna);
2937 /* return a borrowed reference */
2938 static PyObject* pyrna_srna_PyBase(StructRNA *srna) //, PyObject *bpy_types_dict)
2940 /* Assume RNA_struct_py_type_get(srna) was already checked */
2943 PyObject *py_base= NULL;
2945 /* get the base type */
2946 base= RNA_struct_base(srna);
2948 if(base && base != srna) {
2949 /*/printf("debug subtype %s %p\n", RNA_struct_identifier(srna), srna); */
2950 py_base= pyrna_srna_Subtype(base); //, bpy_types_dict);
2951 Py_DECREF(py_base); /* srna owns, this is only to pass as an arg */
2955 py_base= (PyObject *)&pyrna_struct_Type;
2961 /* check if we have a native python subclass, use it when it exists
2962 * return a borrowed reference */
2963 static PyObject* pyrna_srna_ExternalType(StructRNA *srna)
2965 PyObject *bpy_types_dict= NULL;
2966 const char *idname= RNA_struct_identifier(srna);
2969 if(bpy_types_dict==NULL) {
2970 PyObject *bpy_types= PyImport_ImportModuleLevel("bpy_types", NULL, NULL, NULL, 0);
2972 if(bpy_types==NULL) {
2975 fprintf(stderr, "pyrna_srna_ExternalType: failed to find 'bpy_types' module\n");
2979 bpy_types_dict = PyModule_GetDict(bpy_types); // borrow
2980 Py_DECREF(bpy_types); // fairly safe to assume the dict is kept
2983 newclass= PyDict_GetItemString(bpy_types_dict, idname);
2985 /* sanity check, could skip this unless in debug mode */
2987 PyObject *base_compare= pyrna_srna_PyBase(srna);
2988 PyObject *bases= PyObject_GetAttrString(newclass, "__bases__");
2990 // XXX - highly dodgy!, this stops blender from creating __dict__ in instances
2991 ((PyTypeObject *)newclass)->tp_dictoffset = 0;
2993 if(PyTuple_GET_SIZE(bases)) {
2994 PyObject *base= PyTuple_GET_ITEM(bases, 0);
2996 if(base_compare != base) {
2998 fprintf(stderr, "pyrna_srna_ExternalType: incorrect subclassing of SRNA '%s'\n", idname);
2999 PyObSpit("Expected! ", base_compare);
3004 fprintf(stderr, "SRNA Subclassed: '%s'\n", idname);
3014 static PyObject* pyrna_srna_Subtype(StructRNA *srna)
3016 PyObject *newclass = NULL;
3019 newclass= NULL; /* Nothing to do */
3020 } else if ((newclass= RNA_struct_py_type_get(srna))) {
3021 Py_INCREF(newclass);
3022 } else if ((newclass= pyrna_srna_ExternalType(srna))) {
3023 pyrna_subtype_set_rna(newclass, srna);
3024 Py_INCREF(newclass);
3026 /* subclass equivelents
3027 - class myClass(myBase):
3028 some='value' # or ...
3029 - myClass = type(name='myClass', bases=(myBase,), dict={'__module__':'bpy.types'})
3032 /* Assume RNA_struct_py_type_get(srna) was alredy checked */
3033 PyObject *py_base= pyrna_srna_PyBase(srna);
3035 const char *idname= RNA_struct_identifier(srna);
3036 const char *descr= RNA_struct_ui_description(srna);
3038 if(!descr) descr= "(no docs)";
3040 /* always use O not N when calling, N causes refcount errors */
3041 newclass = PyObject_CallFunction( (PyObject*)&PyType_Type, "s(O){ssss}", idname, py_base, "__module__","bpy.types", "__doc__",descr);
3042 /* newclass will now have 2 ref's, ???, probably 1 is internal since decrefing here segfaults */
3044 /* PyObSpit("new class ref", newclass); */
3048 // XXX - highly dodgy!, this stops blender from creating __dict__ in instances
3049 ((PyTypeObject *)newclass)->tp_dictoffset = 0;
3051 /* srna owns one, and the other is owned by the caller */
3052 pyrna_subtype_set_rna(newclass, srna);
3054 Py_DECREF(newclass); /* let srna own */
3057 /* this should not happen */
3066 /* use for subtyping so we know which srna is used for a PointerRNA */
3067 static StructRNA *srna_from_ptr(PointerRNA *ptr)
3069 if(ptr->type == &RNA_Struct) {
3077 /* always returns a new ref, be sure to decref when done */
3078 static PyObject* pyrna_struct_Subtype(PointerRNA *ptr)
3080 return pyrna_srna_Subtype(srna_from_ptr(ptr));
3083 /*-----------------------CreatePyObject---------------------------------*/
3084 PyObject *pyrna_struct_CreatePyObject( PointerRNA *ptr )
3086 BPy_StructRNA *pyrna= NULL;
3088 if (ptr->data==NULL && ptr->type==NULL) { /* Operator RNA has NULL data */
3092 PyTypeObject *tp = (PyTypeObject *)pyrna_struct_Subtype(ptr);
3095 pyrna = (BPy_StructRNA *) tp->tp_alloc(tp, 0);
3096 Py_DECREF(tp); /* srna owns, cant hold a ref */
3099 fprintf(stderr, "Could not make type\n");
3100 pyrna = ( BPy_StructRNA * ) PyObject_NEW( BPy_StructRNA, &pyrna_struct_Type );
3105 PyErr_SetString( PyExc_MemoryError, "couldn't create BPy_StructRNA object" );
3110 pyrna->freeptr= FALSE;
3112 // PyObSpit("NewStructRNA: ", (PyObject *)pyrna);
3114 return ( PyObject * ) pyrna;
3117 PyObject *pyrna_prop_CreatePyObject( PointerRNA *ptr, PropertyRNA *prop )
3119 BPy_PropertyRNA *pyrna;
3121 pyrna = ( BPy_PropertyRNA * ) PyObject_NEW( BPy_PropertyRNA, &pyrna_prop_Type );
3124 PyErr_SetString( PyExc_MemoryError, "couldn't create BPy_rna object" );
3132 pyrna->arrayoffset= 0;
3134 return ( PyObject * ) pyrna;
3137 void BPY_rna_init(void)
3139 #ifdef USE_MATHUTILS // register mathutils callbacks, ok to run more then once.
3140 mathutils_rna_array_cb_index= Mathutils_RegisterCallback(&mathutils_rna_array_cb);
3141 mathutils_rna_matrix_cb_index= Mathutils_RegisterCallback(&mathutils_rna_matrix_cb);
3144 if( PyType_Ready( &pyrna_struct_Type ) < 0 )
3147 if( PyType_Ready( &pyrna_prop_Type ) < 0 )
3151 /* bpy.data from python */
3152 static PointerRNA *rna_module_ptr= NULL;
3153 PyObject *BPY_rna_module(void)
3155 BPy_StructRNA *pyrna;
3158 /* for now, return the base RNA type rather then a real module */
3159 RNA_main_pointer_create(G.main, &ptr);
3160 pyrna= (BPy_StructRNA *)pyrna_struct_CreatePyObject(&ptr);
3162 rna_module_ptr= &pyrna->ptr;
3163 return (PyObject *)pyrna;
3166 void BPY_update_rna_module(void)
3168 RNA_main_pointer_create(G.main, rna_module_ptr);
3172 /* This is a way we can access docstrings for RNA types
3173 * without having the datatypes in blender */
3174 PyObject *BPY_rna_doc( void )
3178 /* for now, return the base RNA type rather then a real module */
3179 RNA_blender_rna_pointer_create(&ptr);
3181 return pyrna_struct_CreatePyObject(&ptr);
3186 /* pyrna_basetype_* - BPy_BaseTypeRNA is just a BPy_PropertyRNA struct with a differnt type
3187 * the self->ptr and self->prop are always set to the "structs" collection */
3188 //---------------getattr--------------------------------------------
3189 static PyObject *pyrna_basetype_getattro( BPy_BaseTypeRNA *self, PyObject *pyname )
3194 if (RNA_property_collection_lookup_string(&self->ptr, self->prop, _PyUnicode_AsString(pyname), &newptr)) {
3195 ret= pyrna_struct_Subtype(&newptr);
3197 PyErr_Format(PyExc_SystemError, "bpy.types.%.200s subtype could not be generated, this is a bug!", _PyUnicode_As