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., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
20 * Contributor(s): Campbell Barton
22 * ***** END GPL LICENSE BLOCK *****
27 #include <float.h> /* FLT_MIN/MAX */
30 #include "bpy_props.h"
32 #include "bpy_rna_callback.h"
34 #include "BLI_dynstr.h"
35 #include "BLI_string.h"
36 #include "BLI_listbase.h"
37 #include "BLI_utildefines.h"
39 #include "RNA_enum_types.h"
40 #include "RNA_define.h" /* RNA_def_property_free_identifier */
42 #include "MEM_guardedalloc.h"
44 #include "BKE_idcode.h"
45 #include "BKE_context.h"
46 #include "BKE_global.h" /* evil G.* */
47 #include "BKE_report.h"
49 #include "BKE_animsys.h"
50 #include "BKE_fcurve.h"
52 /* only for keyframing */
53 #include "DNA_scene_types.h"
54 #include "DNA_anim_types.h"
55 #include "ED_keyframing.h"
57 #include "../generic/IDProp.h" /* for IDprop lookups */
58 #include "../generic/py_capi_utils.h"
60 #define USE_PEDANTIC_WRITE
62 #define USE_STRING_COERCE
64 static PyObject *pyrna_prop_collection_values(BPy_PropertyRNA *self);
66 #ifdef USE_PEDANTIC_WRITE
67 static short rna_disallow_writes= FALSE;
69 static int rna_id_write_error(PointerRNA *ptr, PyObject *key)
73 const short idcode= GS(id->name);
74 if(!ELEM(idcode, ID_WM, ID_SCR)) { /* may need more added here */
75 const char *idtype= BKE_idcode_to_name(idcode);
77 if(key && PyUnicode_Check(key)) pyname= _PyUnicode_AsString(key);
78 else pyname= "<UNKNOWN>";
80 /* make a nice string error */
81 BLI_assert(idtype != NULL);
82 PyErr_Format(PyExc_AttributeError, "Writing to ID classes in this context is not allowed: %.200s, %.200s datablock, error setting %.200s.%.200s", id->name+2, idtype, RNA_struct_identifier(ptr->type), pyname);
89 #endif // USE_PEDANTIC_WRITE
92 #ifdef USE_PEDANTIC_WRITE
93 int pyrna_write_check(void)
95 return !rna_disallow_writes;
97 #else // USE_PEDANTIC_WRITE
98 int pyrna_write_check(void)
102 #endif // USE_PEDANTIC_WRITE
104 static Py_ssize_t pyrna_prop_collection_length(BPy_PropertyRNA *self);
105 static Py_ssize_t pyrna_prop_array_length(BPy_PropertyArrayRNA *self);
106 static int pyrna_py_to_prop(PointerRNA *ptr, PropertyRNA *prop, void *data, PyObject *value, const char *error_prefix);
107 static int deferred_register_prop(StructRNA *srna, PyObject *key, PyObject *item);
110 #include "../generic/mathutils.h" /* so we can have mathutils callbacks */
112 static PyObject *pyrna_prop_array_subscript_slice(BPy_PropertyArrayRNA *self, PointerRNA *ptr, PropertyRNA *prop, Py_ssize_t start, Py_ssize_t stop, Py_ssize_t length);
113 static short pyrna_rotation_euler_order_get(PointerRNA *ptr, PropertyRNA **prop_eul_order, short order_fallback);
115 /* bpyrna vector/euler/quat callbacks */
116 static int mathutils_rna_array_cb_index= -1; /* index for our callbacks */
118 /* subtype not used much yet */
119 #define MATHUTILS_CB_SUBTYPE_EUL 0
120 #define MATHUTILS_CB_SUBTYPE_VEC 1
121 #define MATHUTILS_CB_SUBTYPE_QUAT 2
122 #define MATHUTILS_CB_SUBTYPE_COLOR 3
124 static int mathutils_rna_generic_check(BaseMathObject *bmo)
126 BPy_PropertyRNA *self= (BPy_PropertyRNA *)bmo->cb_user;
127 return self->prop ? 1:0;
130 static int mathutils_rna_vector_get(BaseMathObject *bmo, int subtype)
132 BPy_PropertyRNA *self= (BPy_PropertyRNA *)bmo->cb_user;
136 RNA_property_float_get_array(&self->ptr, self->prop, bmo->data);
138 /* Euler order exception */
139 if(subtype==MATHUTILS_CB_SUBTYPE_EUL) {
140 EulerObject *eul= (EulerObject *)bmo;
141 PropertyRNA *prop_eul_order= NULL;
142 eul->order= pyrna_rotation_euler_order_get(&self->ptr, &prop_eul_order, eul->order);
148 static int mathutils_rna_vector_set(BaseMathObject *bmo, int subtype)
150 BPy_PropertyRNA *self= (BPy_PropertyRNA *)bmo->cb_user;
155 #ifdef USE_PEDANTIC_WRITE
156 if(rna_disallow_writes && rna_id_write_error(&self->ptr, NULL)) {
159 #endif // USE_PEDANTIC_WRITE
161 if (!RNA_property_editable_flag(&self->ptr, self->prop)) {
162 PyErr_Format(PyExc_AttributeError, "bpy_prop \"%.200s.%.200s\" is read-only", RNA_struct_identifier(self->ptr.type), RNA_property_identifier(self->prop));
166 RNA_property_float_range(&self->ptr, self->prop, &min, &max);
168 if(min != FLT_MIN || max != FLT_MAX) {
169 int i, len= RNA_property_array_length(&self->ptr, self->prop);
170 for(i=0; i<len; i++) {
171 CLAMP(bmo->data[i], min, max);
175 RNA_property_float_set_array(&self->ptr, self->prop, bmo->data);
176 if(RNA_property_update_check(self->prop)) {
177 RNA_property_update(BPy_GetContext(), &self->ptr, self->prop);
180 /* Euler order exception */
181 if(subtype==MATHUTILS_CB_SUBTYPE_EUL) {
182 EulerObject *eul= (EulerObject *)bmo;
183 PropertyRNA *prop_eul_order= NULL;
184 short order= pyrna_rotation_euler_order_get(&self->ptr, &prop_eul_order, eul->order);
185 if(order != eul->order) {
186 RNA_property_enum_set(&self->ptr, prop_eul_order, eul->order);
187 if(RNA_property_update_check(prop_eul_order)) {
188 RNA_property_update(BPy_GetContext(), &self->ptr, prop_eul_order);
195 static int mathutils_rna_vector_get_index(BaseMathObject *bmo, int UNUSED(subtype), int index)
197 BPy_PropertyRNA *self= (BPy_PropertyRNA *)bmo->cb_user;
202 bmo->data[index]= RNA_property_float_get_index(&self->ptr, self->prop, index);
206 static int mathutils_rna_vector_set_index(BaseMathObject *bmo, int UNUSED(subtype), int index)
208 BPy_PropertyRNA *self= (BPy_PropertyRNA *)bmo->cb_user;
213 #ifdef USE_PEDANTIC_WRITE
214 if(rna_disallow_writes && rna_id_write_error(&self->ptr, NULL)) {
217 #endif // USE_PEDANTIC_WRITE
219 if (!RNA_property_editable_flag(&self->ptr, self->prop)) {
220 PyErr_Format(PyExc_AttributeError, "bpy_prop \"%.200s.%.200s\" is read-only", RNA_struct_identifier(self->ptr.type), RNA_property_identifier(self->prop));
224 RNA_property_float_clamp(&self->ptr, self->prop, &bmo->data[index]);
225 RNA_property_float_set_index(&self->ptr, self->prop, index, bmo->data[index]);
227 if(RNA_property_update_check(self->prop)) {
228 RNA_property_update(BPy_GetContext(), &self->ptr, self->prop);
234 static Mathutils_Callback mathutils_rna_array_cb = {
235 (BaseMathCheckFunc) mathutils_rna_generic_check,
236 (BaseMathGetFunc) mathutils_rna_vector_get,
237 (BaseMathSetFunc) mathutils_rna_vector_set,
238 (BaseMathGetIndexFunc) mathutils_rna_vector_get_index,
239 (BaseMathSetIndexFunc) mathutils_rna_vector_set_index
243 /* bpyrna matrix callbacks */
244 static int mathutils_rna_matrix_cb_index= -1; /* index for our callbacks */
246 static int mathutils_rna_matrix_get(BaseMathObject *bmo, int UNUSED(subtype))
248 BPy_PropertyRNA *self= (BPy_PropertyRNA *)bmo->cb_user;
253 RNA_property_float_get_array(&self->ptr, self->prop, bmo->data);
257 static int mathutils_rna_matrix_set(BaseMathObject *bmo, int UNUSED(subtype))
259 BPy_PropertyRNA *self= (BPy_PropertyRNA *)bmo->cb_user;
264 #ifdef USE_PEDANTIC_WRITE
265 if(rna_disallow_writes && rna_id_write_error(&self->ptr, NULL)) {
268 #endif // USE_PEDANTIC_WRITE
270 if (!RNA_property_editable_flag(&self->ptr, self->prop)) {
271 PyErr_Format(PyExc_AttributeError, "bpy_prop \"%.200s.%.200s\" is read-only", RNA_struct_identifier(self->ptr.type), RNA_property_identifier(self->prop));
275 /* can ignore clamping here */
276 RNA_property_float_set_array(&self->ptr, self->prop, bmo->data);
278 if(RNA_property_update_check(self->prop)) {
279 RNA_property_update(BPy_GetContext(), &self->ptr, self->prop);
284 static Mathutils_Callback mathutils_rna_matrix_cb = {
285 mathutils_rna_generic_check,
286 mathutils_rna_matrix_get,
287 mathutils_rna_matrix_set,
292 static short pyrna_rotation_euler_order_get(PointerRNA *ptr, PropertyRNA **prop_eul_order, short order_fallback)
294 /* attempt to get order */
295 if(*prop_eul_order==NULL)
296 *prop_eul_order= RNA_struct_find_property(ptr, "rotation_mode");
298 if(*prop_eul_order) {
299 short order= RNA_property_enum_get(ptr, *prop_eul_order);
300 if (order >= ROT_MODE_XYZ && order <= ROT_MODE_ZYX) /* could be quat or axisangle */
304 return order_fallback;
307 #endif // USE_MATHUTILS
309 #define PROP_ALL_VECTOR_SUBTYPES PROP_TRANSLATION: case PROP_DIRECTION: case PROP_VELOCITY: case PROP_ACCELERATION: case PROP_XYZ: case PROP_XYZ_LENGTH
311 PyObject *pyrna_math_object_from_array(PointerRNA *ptr, PropertyRNA *prop)
319 int flag= RNA_property_flag(prop);
321 /* disallow dynamic sized arrays to be wrapped since the size could change
322 * to a size mathutils does not support */
323 if ((RNA_property_type(prop) != PROP_FLOAT) || (flag & PROP_DYNAMIC))
326 len= RNA_property_array_length(ptr, prop);
327 subtype= RNA_property_subtype(prop);
328 totdim= RNA_property_array_dimension(ptr, prop, NULL);
329 is_thick = (flag & PROP_THICK_WRAP);
331 if (totdim == 1 || (totdim == 2 && subtype == PROP_MATRIX)) {
333 ret = pyrna_prop_CreatePyObject(ptr, prop); /* owned by the Mathutils PyObject */
335 switch(RNA_property_subtype(prop)) {
336 case PROP_ALL_VECTOR_SUBTYPES:
337 if(len>=2 && len <= 4) {
339 ret= newVectorObject(NULL, len, Py_NEW, NULL);
340 RNA_property_float_get_array(ptr, prop, ((VectorObject *)ret)->vec);
343 PyObject *vec_cb= newVectorObject_cb(ret, len, mathutils_rna_array_cb_index, MATHUTILS_CB_SUBTYPE_VEC);
344 Py_DECREF(ret); /* the vector owns now */
345 ret= vec_cb; /* return the vector instead */
352 ret= newMatrixObject(NULL, 4, 4, Py_NEW, NULL);
353 RNA_property_float_get_array(ptr, prop, ((MatrixObject *)ret)->contigPtr);
356 PyObject *mat_cb= newMatrixObject_cb(ret, 4,4, mathutils_rna_matrix_cb_index, FALSE);
357 Py_DECREF(ret); /* the matrix owns now */
358 ret= mat_cb; /* return the matrix instead */
363 ret= newMatrixObject(NULL, 3, 3, Py_NEW, NULL);
364 RNA_property_float_get_array(ptr, prop, ((MatrixObject *)ret)->contigPtr);
367 PyObject *mat_cb= newMatrixObject_cb(ret, 3,3, mathutils_rna_matrix_cb_index, FALSE);
368 Py_DECREF(ret); /* the matrix owns now */
369 ret= mat_cb; /* return the matrix instead */
374 case PROP_QUATERNION:
375 if(len==3) { /* euler */
377 /* attempt to get order, only needed for thick types since wrapped with update via callbacks */
378 PropertyRNA *prop_eul_order= NULL;
379 short order= pyrna_rotation_euler_order_get(ptr, &prop_eul_order, ROT_MODE_XYZ);
381 ret= newEulerObject(NULL, order, Py_NEW, NULL); // TODO, get order from RNA
382 RNA_property_float_get_array(ptr, prop, ((EulerObject *)ret)->eul);
385 /* order will be updated from callback on use */
386 PyObject *eul_cb= newEulerObject_cb(ret, ROT_MODE_XYZ, mathutils_rna_array_cb_index, MATHUTILS_CB_SUBTYPE_EUL); // TODO, get order from RNA
387 Py_DECREF(ret); /* the euler owns now */
388 ret= eul_cb; /* return the euler instead */
393 ret= newQuaternionObject(NULL, Py_NEW, NULL);
394 RNA_property_float_get_array(ptr, prop, ((QuaternionObject *)ret)->quat);
397 PyObject *quat_cb= newQuaternionObject_cb(ret, mathutils_rna_array_cb_index, MATHUTILS_CB_SUBTYPE_QUAT);
398 Py_DECREF(ret); /* the quat owns now */
399 ret= quat_cb; /* return the quat instead */
404 if(len==3) { /* color */
406 ret= newColorObject(NULL, Py_NEW, NULL); // TODO, get order from RNA
407 RNA_property_float_get_array(ptr, prop, ((ColorObject *)ret)->col);
410 PyObject *col_cb= newColorObject_cb(ret, mathutils_rna_array_cb_index, MATHUTILS_CB_SUBTYPE_COLOR);
411 Py_DECREF(ret); /* the color owns now */
412 ret= col_cb; /* return the color instead */
422 /* this is an array we cant reference (since its not thin wrappable)
423 * and cannot be coerced into a mathutils type, so return as a list */
424 ret = pyrna_prop_array_subscript_slice(NULL, ptr, prop, 0, len, len);
426 ret = pyrna_prop_CreatePyObject(ptr, prop); /* owned by the Mathutils PyObject */
429 #else // USE_MATHUTILS
432 #endif // USE_MATHUTILS
437 /* same as RNA_enum_value_from_id but raises an exception */
438 int pyrna_enum_value_from_id(EnumPropertyItem *item, const char *identifier, int *value, const char *error_prefix)
440 if(RNA_enum_value_from_id(item, identifier, value) == 0) {
441 const char *enum_str= BPy_enum_as_string(item);
442 PyErr_Format(PyExc_TypeError, "%s: '%.200s' not found in (%s)", error_prefix, identifier, enum_str);
443 MEM_freeN((void *)enum_str);
450 static int pyrna_struct_compare( BPy_StructRNA * a, BPy_StructRNA * b )
452 return (a->ptr.data==b->ptr.data) ? 0 : -1;
455 static int pyrna_prop_compare( BPy_PropertyRNA * a, BPy_PropertyRNA * b )
457 return (a->prop==b->prop && a->ptr.data==b->ptr.data ) ? 0 : -1;
460 static PyObject *pyrna_struct_richcmp(PyObject *a, PyObject *b, int op)
463 int ok= -1; /* zero is true */
465 if (BPy_StructRNA_Check(a) && BPy_StructRNA_Check(b))
466 ok= pyrna_struct_compare((BPy_StructRNA *)a, (BPy_StructRNA *)b);
470 ok = !ok; /* pass through */
472 res = ok ? Py_False : Py_True;
479 res = Py_NotImplemented;
486 return Py_INCREF(res), res;
489 static PyObject *pyrna_prop_richcmp(PyObject *a, PyObject *b, int op)
492 int ok= -1; /* zero is true */
494 if (BPy_PropertyRNA_Check(a) && BPy_PropertyRNA_Check(b))
495 ok= pyrna_prop_compare((BPy_PropertyRNA *)a, (BPy_PropertyRNA *)b);
499 ok = !ok; /* pass through */
501 res = ok ? Py_False : Py_True;
508 res = Py_NotImplemented;
515 return Py_INCREF(res), res;
518 /*----------------------repr--------------------------------------------*/
519 static PyObject *pyrna_struct_str( BPy_StructRNA *self )
524 /* print name if available */
525 name= RNA_struct_name_get_alloc(&self->ptr, NULL, FALSE);
527 ret= PyUnicode_FromFormat( "<bpy_struct, %.200s(\"%.200s\")>", RNA_struct_identifier(self->ptr.type), name);
528 MEM_freeN((void *)name);
532 return PyUnicode_FromFormat( "<bpy_struct, %.200s at %p>", RNA_struct_identifier(self->ptr.type), self->ptr.data);
535 static PyObject *pyrna_struct_repr(BPy_StructRNA *self)
537 ID *id= self->ptr.id.data;
539 return pyrna_struct_str(self); /* fallback */
541 if(RNA_struct_is_ID(self->ptr.type)) {
542 return PyUnicode_FromFormat( "bpy.data.%s[\"%s\"]", BKE_idcode_to_name_plural(GS(id->name)), id->name+2);
547 path= RNA_path_from_ID_to_struct(&self->ptr);
549 ret= PyUnicode_FromFormat( "bpy.data.%s[\"%s\"].%s", BKE_idcode_to_name_plural(GS(id->name)), id->name+2, path);
550 MEM_freeN((void *)path);
552 else { /* cant find, print something sane */
553 ret= PyUnicode_FromFormat( "bpy.data.%s[\"%s\"]...%s", BKE_idcode_to_name_plural(GS(id->name)), id->name+2, RNA_struct_identifier(self->ptr.type));
560 static PyObject *pyrna_prop_str( BPy_PropertyRNA *self )
565 const char *type_id= NULL;
566 char type_fmt[64]= "";
567 int type= RNA_property_type(self->prop);
569 if(RNA_enum_id_from_value(property_type_items, type, &type_id)==0) {
570 PyErr_SetString(PyExc_RuntimeError, "could not use property type, internal error"); /* should never happen */
574 /* this should never fail */
578 while ( (*c++= tolower(*type_id++)) ) {} ;
580 if(type==PROP_COLLECTION) {
581 len= pyrna_prop_collection_length(self);
582 } else if (RNA_property_array_check(&self->ptr, self->prop)) {
583 len= pyrna_prop_array_length((BPy_PropertyArrayRNA *)self);
587 sprintf(--c, "[%d]", len);
590 /* if a pointer, try to print name of pointer target too */
591 if(RNA_property_type(self->prop) == PROP_POINTER) {
592 ptr= RNA_property_pointer_get(&self->ptr, self->prop);
593 name= RNA_struct_name_get_alloc(&ptr, NULL, FALSE);
596 ret= PyUnicode_FromFormat( "<bpy_%.200s, %.200s.%.200s(\"%.200s\")>", type_fmt, RNA_struct_identifier(self->ptr.type), RNA_property_identifier(self->prop), name);
597 MEM_freeN((void *)name);
601 if(RNA_property_type(self->prop) == PROP_COLLECTION) {
603 if(RNA_property_collection_type_get(&self->ptr, self->prop, &r_ptr)) {
604 return PyUnicode_FromFormat( "<bpy_%.200s, %.200s>", type_fmt, RNA_struct_identifier(r_ptr.type));
608 return PyUnicode_FromFormat( "<bpy_%.200s, %.200s.%.200s>", type_fmt, RNA_struct_identifier(self->ptr.type), RNA_property_identifier(self->prop));
611 static PyObject *pyrna_prop_repr(BPy_PropertyRNA *self)
613 ID *id= self->ptr.id.data;
618 return pyrna_prop_str(self); /* fallback */
620 path= RNA_path_from_ID_to_property(&self->ptr, self->prop);
622 ret= PyUnicode_FromFormat( "bpy.data.%s[\"%s\"].%s", BKE_idcode_to_name_plural(GS(id->name)), id->name+2, path);
623 MEM_freeN((void *)path);
625 else { /* cant find, print something sane */
626 ret= PyUnicode_FromFormat( "bpy.data.%s[\"%s\"]...%s", BKE_idcode_to_name_plural(GS(id->name)), id->name+2, RNA_property_identifier(self->prop));
632 static long pyrna_struct_hash( BPy_StructRNA *self )
634 return _Py_HashPointer(self->ptr.data);
637 /* from python's meth_hash v3.1.2 */
638 static long pyrna_prop_hash(BPy_PropertyRNA *self)
641 if (self->ptr.data == NULL)
644 x = _Py_HashPointer(self->ptr.data);
648 y = _Py_HashPointer((void*)(self->prop));
657 /* use our own dealloc so we can free a property if we use one */
658 static void pyrna_struct_dealloc( BPy_StructRNA *self )
660 if (self->freeptr && self->ptr.data) {
661 IDP_FreeProperty(self->ptr.data);
662 MEM_freeN(self->ptr.data);
663 self->ptr.data= NULL;
666 /* Note, for subclassed PyObjects we cant just call PyObject_DEL() directly or it will crash */
667 Py_TYPE(self)->tp_free(self);
671 static const char *pyrna_enum_as_string(PointerRNA *ptr, PropertyRNA *prop)
673 EnumPropertyItem *item;
677 RNA_property_enum_items(BPy_GetContext(), ptr, prop, &item, NULL, &free);
679 result= BPy_enum_as_string(item);
692 static int pyrna_string_to_enum(PyObject *item, PointerRNA *ptr, PropertyRNA *prop, int *val, const char *error_prefix)
694 const char *param= _PyUnicode_AsString(item);
697 const char *enum_str= pyrna_enum_as_string(ptr, prop);
698 PyErr_Format(PyExc_TypeError, "%.200s expected a string enum type in (%.200s)", error_prefix, enum_str);
699 MEM_freeN((void *)enum_str);
702 /* hack so that dynamic enums used for operator properties will be able to be built (i.e. context will be supplied to itemf)
703 * and thus running defining operator buttons for such operators in UI will work */
704 RNA_def_property_clear_flag(prop, PROP_ENUM_NO_CONTEXT);
706 if (!RNA_property_enum_value(BPy_GetContext(), ptr, prop, param, val)) {
707 const char *enum_str= pyrna_enum_as_string(ptr, prop);
708 PyErr_Format(PyExc_TypeError, "%.200s enum \"%.200s\" not found in (%.200s)", error_prefix, param, enum_str);
709 MEM_freeN((void *)enum_str);
717 int pyrna_set_to_enum_bitfield(EnumPropertyItem *items, PyObject *value, int *r_value, const char *error_prefix)
719 /* set of enum items, concatenate all values with OR */
729 while (_PySet_NextEntry(value, &pos, &key, &hash)) {
730 const char *param= _PyUnicode_AsString(key);
733 PyErr_Format(PyExc_TypeError, "%.200s expected a string, not %.200s", error_prefix, Py_TYPE(key)->tp_name);
736 if(pyrna_enum_value_from_id(items, param, &ret, error_prefix) < 0)
746 static int pyrna_prop_to_enum_bitfield(PointerRNA *ptr, PropertyRNA *prop, PyObject *value, int *r_value, const char *error_prefix)
748 EnumPropertyItem *item;
754 RNA_property_enum_items(BPy_GetContext(), ptr, prop, &item, NULL, &free);
757 ret= pyrna_set_to_enum_bitfield(item, value, r_value, error_prefix);
760 if(PySet_GET_SIZE(value)) {
761 PyErr_Format(PyExc_TypeError, "%.200s: empty enum \"%.200s\" could not have any values assigned", error_prefix, RNA_property_identifier(prop));
775 PyObject *pyrna_enum_bitfield_to_py(EnumPropertyItem *items, int value)
777 PyObject *ret= PySet_New(NULL);
778 const char *identifier[RNA_ENUM_BITFLAG_SIZE + 1];
780 if(RNA_enum_bitflag_identifiers(items, value, identifier)) {
783 for(index=0; identifier[index]; index++) {
784 item= PyUnicode_FromString(identifier[index]);
785 PySet_Add(ret, item);
793 static PyObject *pyrna_enum_to_py(PointerRNA *ptr, PropertyRNA *prop, int val)
795 PyObject *item, *ret= NULL;
797 if(RNA_property_flag(prop) & PROP_ENUM_FLAG) {
798 const char *identifier[RNA_ENUM_BITFLAG_SIZE + 1];
800 ret= PySet_New(NULL);
802 if (RNA_property_enum_bitflag_identifiers(BPy_GetContext(), ptr, prop, val, identifier)) {
805 for(index=0; identifier[index]; index++) {
806 item= PyUnicode_FromString(identifier[index]);
807 PySet_Add(ret, item);
814 const char *identifier;
815 if (RNA_property_enum_identifier(BPy_GetContext(), ptr, prop, val, &identifier)) {
816 ret = PyUnicode_FromString(identifier);
818 EnumPropertyItem *enum_item;
821 /* don't throw error here, can't trust blender 100% to give the
822 * right values, python code should not generate error for that */
823 RNA_property_enum_items(BPy_GetContext(), ptr, prop, &enum_item, NULL, &free);
824 if(enum_item && enum_item->identifier) {
825 ret= PyUnicode_FromString(enum_item->identifier);
828 const char *ptr_name= RNA_struct_name_get_alloc(ptr, NULL, FALSE);
830 /* prefer not fail silently incase of api errors, maybe disable it later */
831 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));
833 #if 0 // gives python decoding errors while generating docs :(
835 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));
836 PyErr_Warn(PyExc_RuntimeWarning, error_str);
840 MEM_freeN((void *)ptr_name);
842 ret = PyUnicode_FromString("");
846 MEM_freeN(enum_item);
848 /*PyErr_Format(PyExc_AttributeError, "RNA Error: Current value \"%d\" matches no enum", val);
856 PyObject * pyrna_prop_to_py(PointerRNA *ptr, PropertyRNA *prop)
859 int type = RNA_property_type(prop);
861 if (RNA_property_array_check(ptr, prop)) {
862 return pyrna_py_from_array(ptr, prop);
865 /* see if we can coorce into a python type - PropertyType */
868 ret = PyBool_FromLong( RNA_property_boolean_get(ptr, prop) );
871 ret = PyLong_FromSsize_t( (Py_ssize_t)RNA_property_int_get(ptr, prop) );
874 ret = PyFloat_FromDouble( RNA_property_float_get(ptr, prop) );
878 int subtype= RNA_property_subtype(prop);
880 buf = RNA_property_string_get_alloc(ptr, prop, NULL, -1);
881 #ifdef USE_STRING_COERCE
882 /* only file paths get special treatment, they may contain non utf-8 chars */
883 if(ELEM3(subtype, PROP_FILEPATH, PROP_DIRPATH, PROP_FILENAME)) {
884 ret= PyC_UnicodeFromByte(buf);
887 ret= PyUnicode_FromString(buf);
889 #else // USE_STRING_COERCE
890 ret= PyUnicode_FromString(buf);
891 #endif // USE_STRING_COERCE
892 MEM_freeN((void *)buf);
897 ret= pyrna_enum_to_py(ptr, prop, RNA_property_enum_get(ptr, prop));
903 newptr= RNA_property_pointer_get(ptr, prop);
905 ret = pyrna_struct_CreatePyObject(&newptr);
912 case PROP_COLLECTION:
913 ret = pyrna_prop_CreatePyObject(ptr, prop);
916 PyErr_Format(PyExc_TypeError, "bpy_struct internal error: unknown type '%d' (pyrna_prop_to_py)", type);
924 /* This function is used by operators and converting dicts into collections.
925 * Its takes keyword args and fills them with property values */
926 int pyrna_pydict_to_props(PointerRNA *ptr, PyObject *kw, int all_args, const char *error_prefix)
930 const char *arg_name= NULL;
933 totkw = kw ? PyDict_Size(kw):0;
935 RNA_STRUCT_BEGIN(ptr, prop) {
936 arg_name= RNA_property_identifier(prop);
938 if (strcmp(arg_name, "rna_type")==0) continue;
941 PyErr_Format(PyExc_TypeError, "%.200s: no keywords, expected \"%.200s\"", error_prefix, arg_name ? arg_name : "<UNKNOWN>");
946 item= PyDict_GetItemString(kw, arg_name); /* wont set an error */
950 PyErr_Format(PyExc_TypeError, "%.200s: keyword \"%.200s\" missing", error_prefix, arg_name ? arg_name : "<UNKNOWN>");
951 error_val = -1; /* pyrna_py_to_prop sets the error */
955 if (pyrna_py_to_prop(ptr, prop, NULL, item, error_prefix)) {
964 if (error_val==0 && totkw > 0) { /* some keywords were given that were not used :/ */
965 PyObject *key, *value;
968 while (PyDict_Next(kw, &pos, &key, &value)) {
969 arg_name= _PyUnicode_AsString(key);
970 if (RNA_struct_find_property(ptr, arg_name) == NULL) break;
974 PyErr_Format(PyExc_TypeError, "%.200s: keyword \"%.200s\" unrecognized", error_prefix, arg_name ? arg_name : "<UNKNOWN>");
981 static PyObject * pyrna_func_call(PyObject *self, PyObject *args, PyObject *kw);
983 static PyObject *pyrna_func_to_py(BPy_DummyPointerRNA *pyrna, FunctionRNA *func)
985 static PyMethodDef func_meth = {"<generic rna function>", (PyCFunction)pyrna_func_call, METH_VARARGS|METH_KEYWORDS, "python rna function"};
990 PyErr_Format(PyExc_RuntimeError, "%.200s: type attempted to get NULL function", RNA_struct_identifier(pyrna->ptr.type));
994 self= PyTuple_New(2);
996 PyTuple_SET_ITEM(self, 0, (PyObject *)pyrna);
999 PyTuple_SET_ITEM(self, 1, PyCapsule_New((void *)func, NULL, NULL));
1001 ret= PyCFunction_New(&func_meth, self);
1009 static int pyrna_py_to_prop(PointerRNA *ptr, PropertyRNA *prop, void *data, PyObject *value, const char *error_prefix)
1011 /* XXX hard limits should be checked here */
1012 int type = RNA_property_type(prop);
1015 if (RNA_property_array_check(ptr, prop)) {
1017 /* char error_str[512]; */
1020 #ifdef USE_MATHUTILS
1021 if(MatrixObject_Check(value)) {
1022 MatrixObject *mat = (MatrixObject*)value;
1023 if(!BaseMath_ReadCallback(mat))
1025 } else /* continue... */
1026 #endif // USE_MATHUTILS
1027 if (!PySequence_Check(value)) {
1028 PyErr_Format(PyExc_TypeError, "%.200s RNA array assignment to %.200s.%.200s expected a sequence, not %.200s", error_prefix, RNA_struct_identifier(ptr->type), RNA_property_identifier(prop), Py_TYPE(value)->tp_name);
1031 /* done getting the length */
1032 ok= pyrna_py_to_array(ptr, prop, data, value, error_prefix);
1035 /* PyErr_Format(PyExc_AttributeError, "%.200s %s", error_prefix, error_str); */
1040 /* Normal Property (not an array) */
1042 /* see if we can coorce into a python type - PropertyType */
1047 /* prefer not to have an exception here
1048 * however so many poll functions return None or a valid Object.
1049 * its a hassle to convert these into a bool before returning, */
1050 if(RNA_property_flag(prop) & PROP_OUTPUT)
1051 param = PyObject_IsTrue( value );
1053 param = PyLong_AsLong( value );
1056 PyErr_Format(PyExc_TypeError, "%.200s %.200s.%.200s expected True/False or 0/1, not %.200s", error_prefix, RNA_struct_identifier(ptr->type), RNA_property_identifier(prop), Py_TYPE(value)->tp_name);
1059 if(data) *((int*)data)= param;
1060 else RNA_property_boolean_set(ptr, prop, param);
1067 long param= PyLong_AsLongAndOverflow(value, &overflow);
1068 if(overflow || (param > INT_MAX) || (param < INT_MIN)) {
1069 PyErr_Format(PyExc_ValueError, "%.200s %.200s.%.200s value not in 'int' range (" STRINGIFY(INT_MIN) ", " STRINGIFY(INT_MAX) ")", error_prefix, RNA_struct_identifier(ptr->type), RNA_property_identifier(prop));
1072 else if (param==-1 && PyErr_Occurred()) {
1073 PyErr_Format(PyExc_TypeError, "%.200s %.200s.%.200s expected an int type, not %.200s", error_prefix, RNA_struct_identifier(ptr->type), RNA_property_identifier(prop), Py_TYPE(value)->tp_name);
1076 int param_i= (int)param;
1077 RNA_property_int_clamp(ptr, prop, ¶m_i);
1078 if(data) *((int*)data)= param_i;
1079 else RNA_property_int_set(ptr, prop, param_i);
1085 float param = PyFloat_AsDouble(value);
1086 if (PyErr_Occurred()) {
1087 PyErr_Format(PyExc_TypeError, "%.200s %.200s.%.200s expected a float type, not %.200s", error_prefix, RNA_struct_identifier(ptr->type), RNA_property_identifier(prop), Py_TYPE(value)->tp_name);
1090 RNA_property_float_clamp(ptr, prop, (float *)¶m);
1091 if(data) *((float*)data)= param;
1092 else RNA_property_float_set(ptr, prop, param);
1099 #ifdef USE_STRING_COERCE
1100 PyObject *value_coerce= NULL;
1101 int subtype= RNA_property_subtype(prop);
1102 if(ELEM3(subtype, PROP_FILEPATH, PROP_DIRPATH, PROP_FILENAME)) {
1103 /* TODO, get size */
1104 param= PyC_UnicodeAsByte(value, &value_coerce);
1107 param= _PyUnicode_AsString(value);
1109 #else // USE_STRING_COERCE
1110 param= _PyUnicode_AsStringSize(value);
1111 #endif // USE_STRING_COERCE
1114 PyErr_Format(PyExc_TypeError, "%.200s %.200s.%.200s expected a string type, not %.200s", error_prefix, RNA_struct_identifier(ptr->type), RNA_property_identifier(prop), Py_TYPE(value)->tp_name);
1118 if(data) *((char**)data)= (char *)param; /*XXX, this is suspect but needed for function calls, need to see if theres a better way */
1119 else RNA_property_string_set(ptr, prop, param);
1121 #ifdef USE_STRING_COERCE
1122 Py_XDECREF(value_coerce);
1123 #endif // USE_STRING_COERCE
1130 if (PyUnicode_Check(value)) {
1131 if (!pyrna_string_to_enum(value, ptr, prop, &val, error_prefix))
1134 else if (PyAnySet_Check(value)) {
1135 if(RNA_property_flag(prop) & PROP_ENUM_FLAG) {
1136 /* set of enum items, concatenate all values with OR */
1137 if(pyrna_prop_to_enum_bitfield(ptr, prop, value, &val, error_prefix) < 0)
1141 PyErr_Format(PyExc_TypeError, "%.200s, %.200s.%.200s is not a bitflag enum type", error_prefix, RNA_struct_identifier(ptr->type), RNA_property_identifier(prop));
1146 const char *enum_str= pyrna_enum_as_string(ptr, prop);
1147 PyErr_Format(PyExc_TypeError, "%.200s %.200s.%.200s expected a string enum or a set of strings in (%.2000s), not %.200s", error_prefix, RNA_struct_identifier(ptr->type), RNA_property_identifier(prop), enum_str, Py_TYPE(value)->tp_name);
1148 MEM_freeN((void *)enum_str);
1152 if(data) *((int*)data)= val;
1153 else RNA_property_enum_set(ptr, prop, val);
1159 PyObject *value_new= NULL;
1161 StructRNA *ptr_type= RNA_property_pointer_type(ptr, prop);
1162 int flag = RNA_property_flag(prop);
1164 /* this is really nasty!, so we can fake the operator having direct properties eg:
1165 * layout.prop(self, "filepath")
1166 * ... which infact should be
1167 * layout.prop(self.properties, "filepath")
1169 * we need to do this trick.
1170 * if the prop is not an operator type and the pyobject is an operator, use its properties in place of its self.
1172 * this is so bad that its almost a good reason to do away with fake 'self.properties -> self' class mixing
1173 * if this causes problems in the future it should be removed.
1175 if( (ptr_type == &RNA_AnyType) &&
1176 (BPy_StructRNA_Check(value)) &&
1177 (RNA_struct_is_a(((BPy_StructRNA *)value)->ptr.type, &RNA_Operator))
1179 value= PyObject_GetAttrString(value, "properties");
1184 /* if property is an OperatorProperties pointer and value is a map, forward back to pyrna_pydict_to_props */
1185 if (RNA_struct_is_a(ptr_type, &RNA_OperatorProperties) && PyDict_Check(value)) {
1186 PointerRNA opptr = RNA_property_pointer_get(ptr, prop);
1187 return pyrna_pydict_to_props(&opptr, value, 0, error_prefix);
1190 /* another exception, allow to pass a collection as an RNA property */
1191 if(Py_TYPE(value)==&pyrna_prop_collection_Type) { /* ok to ignore idprop collections */
1193 BPy_PropertyRNA *value_prop= (BPy_PropertyRNA *)value;
1194 if(RNA_property_collection_type_get(&value_prop->ptr, value_prop->prop, &c_ptr)) {
1195 value= pyrna_struct_CreatePyObject(&c_ptr);
1199 PyErr_Format(PyExc_TypeError, "%.200s %.200s.%.200s collection has no type, cant be used as a %.200s type", error_prefix, RNA_struct_identifier(ptr->type), RNA_property_identifier(prop), RNA_struct_identifier(ptr_type));
1204 if(!BPy_StructRNA_Check(value) && value != Py_None) {
1205 PyErr_Format(PyExc_TypeError, "%.200s %.200s.%.200s expected a %.200s type, not %.200s", error_prefix, RNA_struct_identifier(ptr->type), RNA_property_identifier(prop), RNA_struct_identifier(ptr_type), Py_TYPE(value)->tp_name);
1206 Py_XDECREF(value_new); return -1;
1207 } else if((flag & PROP_NEVER_NULL) && value == Py_None) {
1208 PyErr_Format(PyExc_TypeError, "%.200s %.200s.%.200s does not support a 'None' assignment %.200s type", error_prefix, RNA_struct_identifier(ptr->type), RNA_property_identifier(prop), RNA_struct_identifier(ptr_type));
1209 Py_XDECREF(value_new); return -1;
1210 } else if(value != Py_None && ((flag & PROP_ID_SELF_CHECK) && ptr->id.data == ((BPy_StructRNA*)value)->ptr.id.data)) {
1211 PyErr_Format(PyExc_TypeError, "%.200s %.200s.%.200s ID type does not support assignment to its self", error_prefix, RNA_struct_identifier(ptr->type), RNA_property_identifier(prop));
1212 Py_XDECREF(value_new); return -1;
1214 BPy_StructRNA *param= (BPy_StructRNA*)value;
1215 int raise_error= FALSE;
1218 if(flag & PROP_RNAPTR) {
1219 if(value == Py_None)
1220 memset(data, 0, sizeof(PointerRNA));
1222 *((PointerRNA*)data)= param->ptr;
1224 else if(value == Py_None) {
1225 *((void**)data)= NULL;
1227 else if(RNA_struct_is_a(param->ptr.type, ptr_type)) {
1228 *((void**)data)= param->ptr.data;
1235 /* data==NULL, assign to RNA */
1236 if(value == Py_None) {
1237 PointerRNA valueptr= {{NULL}};
1238 RNA_property_pointer_set(ptr, prop, valueptr);
1240 else if(RNA_struct_is_a(param->ptr.type, ptr_type)) {
1241 RNA_property_pointer_set(ptr, prop, param->ptr);
1245 RNA_pointer_create(NULL, ptr_type, NULL, &tmp);
1246 PyErr_Format(PyExc_TypeError, "%.200s %.200s.%.200s expected a %.200s type. not %.200s", error_prefix, RNA_struct_identifier(ptr->type), RNA_property_identifier(prop), RNA_struct_identifier(tmp.type), RNA_struct_identifier(param->ptr.type));
1247 Py_XDECREF(value_new); return -1;
1253 RNA_pointer_create(NULL, ptr_type, NULL, &tmp);
1254 PyErr_Format(PyExc_TypeError, "%.200s %.200s.%.200s expected a %.200s type, not %.200s", error_prefix, RNA_struct_identifier(ptr->type), RNA_property_identifier(prop), RNA_struct_identifier(tmp.type), RNA_struct_identifier(param->ptr.type));
1255 Py_XDECREF(value_new); return -1;
1259 Py_XDECREF(value_new);
1263 case PROP_COLLECTION:
1269 CollectionPointerLink *link;
1271 lb= (data)? (ListBase*)data: NULL;
1273 /* convert a sequence of dict's into a collection */
1274 if(!PySequence_Check(value)) {
1275 PyErr_Format(PyExc_TypeError, "%.200s %.200s.%.200s expected a sequence for an RNA collection, not %.200s", error_prefix, RNA_struct_identifier(ptr->type), RNA_property_identifier(prop), Py_TYPE(value)->tp_name);
1279 seq_len = PySequence_Size(value);
1280 for(i=0; i<seq_len; i++) {
1281 item= PySequence_GetItem(value, i);
1284 PyErr_Format(PyExc_TypeError, "%.200s %.200s.%.200s failed to get sequence index '%d' for an RNA collection", error_prefix, RNA_struct_identifier(ptr->type), RNA_property_identifier(prop), i);
1289 if(PyDict_Check(item)==0) {
1290 PyErr_Format(PyExc_TypeError, "%.200s %.200s.%.200s expected a each sequence member to be a dict for an RNA collection, not %.200s", error_prefix, RNA_struct_identifier(ptr->type), RNA_property_identifier(prop), Py_TYPE(item)->tp_name);
1296 link= MEM_callocN(sizeof(CollectionPointerLink), "PyCollectionPointerLink");
1298 BLI_addtail(lb, link);
1301 RNA_property_collection_add(ptr, prop, &itemptr);
1303 if(pyrna_pydict_to_props(&itemptr, item, 1, "Converting a python list to an RNA collection")==-1) {
1304 PyObject *msg= PyC_ExceptionBuffer();
1305 const char *msg_char= _PyUnicode_AsString(msg);
1307 PyErr_Format(PyExc_TypeError, "%.200s %.200s.%.200s error converting a member of a collection from a dicts into an RNA collection, failed with: %s", error_prefix, RNA_struct_identifier(ptr->type), RNA_property_identifier(prop), msg_char);
1319 PyErr_Format(PyExc_AttributeError, "%.200s %.200s.%.200s unknown property type (pyrna_py_to_prop)", error_prefix, RNA_struct_identifier(ptr->type), RNA_property_identifier(prop));
1325 /* Run rna property functions */
1326 if(RNA_property_update_check(prop)) {
1327 RNA_property_update(BPy_GetContext(), ptr, prop);
1333 static PyObject * pyrna_prop_array_to_py_index(BPy_PropertyArrayRNA *self, int index)
1335 return pyrna_py_from_array_index(self, &self->ptr, self->prop, index);
1338 static int pyrna_py_to_prop_array_index(BPy_PropertyArrayRNA *self, int index, PyObject *value)
1341 PointerRNA *ptr= &self->ptr;
1342 PropertyRNA *prop= self->prop;
1344 const int totdim= RNA_property_array_dimension(ptr, prop, NULL);
1347 /* char error_str[512]; */
1348 if (!pyrna_py_to_array_index(&self->ptr, self->prop, self->arraydim, self->arrayoffset, index, value, "")) {
1349 /* PyErr_SetString(PyExc_AttributeError, error_str); */
1354 /* see if we can coorce into a python type - PropertyType */
1355 switch (RNA_property_type(prop)) {
1358 int param = PyLong_AsLong( value );
1360 if( param < 0 || param > 1) {
1361 PyErr_SetString(PyExc_TypeError, "expected True/False or 0/1");
1364 RNA_property_boolean_set_index(ptr, prop, index, param);
1370 int param = PyLong_AsLong(value);
1371 if (param==-1 && PyErr_Occurred()) {
1372 PyErr_SetString(PyExc_TypeError, "expected an int type");
1375 RNA_property_int_clamp(ptr, prop, ¶m);
1376 RNA_property_int_set_index(ptr, prop, index, param);
1382 float param = PyFloat_AsDouble(value);
1383 if (PyErr_Occurred()) {
1384 PyErr_SetString(PyExc_TypeError, "expected a float type");
1387 RNA_property_float_clamp(ptr, prop, ¶m);
1388 RNA_property_float_set_index(ptr, prop, index, param);
1393 PyErr_SetString(PyExc_AttributeError, "not an array type");
1399 /* Run rna property functions */
1400 if(RNA_property_update_check(prop)) {
1401 RNA_property_update(BPy_GetContext(), ptr, prop);
1407 //---------------sequence-------------------------------------------
1408 static Py_ssize_t pyrna_prop_array_length(BPy_PropertyArrayRNA *self)
1410 if (RNA_property_array_dimension(&self->ptr, self->prop, NULL) > 1)
1411 return RNA_property_multi_array_length(&self->ptr, self->prop, self->arraydim);
1413 return RNA_property_array_length(&self->ptr, self->prop);
1416 static Py_ssize_t pyrna_prop_collection_length( BPy_PropertyRNA *self )
1418 return RNA_property_collection_length(&self->ptr, self->prop);
1421 /* bool funcs are for speed, so we can avoid getting the length
1422 * of 1000's of items in a linked list for eg. */
1423 static int pyrna_prop_array_bool(BPy_PropertyRNA *self)
1425 return RNA_property_array_length(&self->ptr, self->prop) ? 1 : 0;
1428 static int pyrna_prop_collection_bool( BPy_PropertyRNA *self )
1430 /* no callback defined, just iterate and find the nth item */
1431 CollectionPropertyIterator iter;
1434 RNA_property_collection_begin(&self->ptr, self->prop, &iter);
1436 RNA_property_collection_end(&iter);
1440 /* internal use only */
1441 static PyObject *pyrna_prop_collection_subscript_int(BPy_PropertyRNA *self, Py_ssize_t keynum)
1444 Py_ssize_t keynum_abs= keynum;
1446 /* notice getting the length of the collection is avoided unless negative index is used
1447 * or to detect internal error with a valid index.
1448 * This is done for faster lookups. */
1450 keynum_abs += RNA_property_collection_length(&self->ptr, self->prop);
1452 if(keynum_abs < 0) {
1453 PyErr_Format(PyExc_IndexError, "bpy_prop_collection[%d]: out of range.", keynum);
1458 if(RNA_property_collection_lookup_int(&self->ptr, self->prop, keynum_abs, &newptr)) {
1459 return pyrna_struct_CreatePyObject(&newptr);
1462 const int len= RNA_property_collection_length(&self->ptr, self->prop);
1463 if(keynum_abs >= len) {
1464 PyErr_Format(PyExc_IndexError, "bpy_prop_collection[index]: index %d out of range, size %d", keynum, len);
1467 PyErr_Format(PyExc_RuntimeError, "bpy_prop_collection[index]: internal error, valid index %d given in %d sized collection but value not found", keynum_abs, len);
1474 static PyObject *pyrna_prop_array_subscript_int(BPy_PropertyArrayRNA *self, int keynum)
1476 int len= pyrna_prop_array_length(self);
1478 if(keynum < 0) keynum += len;
1480 if(keynum >= 0 && keynum < len)
1481 return pyrna_prop_array_to_py_index(self, keynum);
1483 PyErr_Format(PyExc_IndexError, "bpy_prop_array[index]: index %d out of range", keynum);
1487 static PyObject *pyrna_prop_collection_subscript_str(BPy_PropertyRNA *self, const char *keyname)
1490 if(RNA_property_collection_lookup_string(&self->ptr, self->prop, keyname, &newptr))
1491 return pyrna_struct_CreatePyObject(&newptr);
1493 PyErr_Format(PyExc_KeyError, "bpy_prop_collection[key]: key \"%.200s\" not found", keyname);
1496 /* static PyObject *pyrna_prop_array_subscript_str(BPy_PropertyRNA *self, char *keyname) */
1498 static PyObject *pyrna_prop_collection_subscript_slice(BPy_PropertyRNA *self, Py_ssize_t start, Py_ssize_t stop)
1502 PyObject *list= PyList_New(0);
1505 /* first loop up-until the start */
1506 CollectionPropertyIterator rna_macro_iter;
1507 for(RNA_property_collection_begin(&self->ptr, self->prop, &rna_macro_iter); rna_macro_iter.valid; RNA_property_collection_next(&rna_macro_iter)) {
1508 /* PointerRNA itemptr= rna_macro_iter.ptr; */
1509 if(count == start) {
1515 /* add items until stop */
1516 for(; rna_macro_iter.valid; RNA_property_collection_next(&rna_macro_iter)) {
1517 item= pyrna_struct_CreatePyObject(&rna_macro_iter.ptr);
1518 PyList_Append(list, item);
1527 RNA_property_collection_end(&rna_macro_iter);
1532 /* TODO - dimensions
1533 * note: could also use pyrna_prop_array_to_py_index(self, count) in a loop but its a lot slower
1534 * since at the moment it reads (and even allocates) the entire array for each index.
1536 static PyObject *pyrna_prop_array_subscript_slice(BPy_PropertyArrayRNA *self, PointerRNA *ptr, PropertyRNA *prop, Py_ssize_t start, Py_ssize_t stop, Py_ssize_t length)
1540 PyObject *tuple= PyTuple_New(stop - start);
1542 totdim = RNA_property_array_dimension(ptr, prop, NULL);
1545 for (count = start; count < stop; count++)
1546 PyTuple_SET_ITEM(tuple, count - start, pyrna_prop_array_to_py_index(self, count));
1549 switch (RNA_property_type(prop)) {
1552 float values_stack[PYRNA_STACK_ARRAY];
1554 if(length > PYRNA_STACK_ARRAY) { values= PyMem_MALLOC(sizeof(float) * length); }
1555 else { values= values_stack; }
1556 RNA_property_float_get_array(ptr, prop, values);
1558 for(count=start; count<stop; count++)
1559 PyTuple_SET_ITEM(tuple, count-start, PyFloat_FromDouble(values[count]));
1561 if(values != values_stack) {
1568 int values_stack[PYRNA_STACK_ARRAY];
1570 if(length > PYRNA_STACK_ARRAY) { values= PyMem_MALLOC(sizeof(int) * length); }
1571 else { values= values_stack; }
1573 RNA_property_boolean_get_array(ptr, prop, values);
1574 for(count=start; count<stop; count++)
1575 PyTuple_SET_ITEM(tuple, count-start, PyBool_FromLong(values[count]));
1577 if(values != values_stack) {
1584 int values_stack[PYRNA_STACK_ARRAY];
1586 if(length > PYRNA_STACK_ARRAY) { values= PyMem_MALLOC(sizeof(int) * length); }
1587 else { values= values_stack; }
1589 RNA_property_int_get_array(ptr, prop, values);
1590 for(count=start; count<stop; count++)
1591 PyTuple_SET_ITEM(tuple, count-start, PyLong_FromSsize_t(values[count]));
1593 if(values != values_stack) {
1599 BLI_assert(!"Invalid array type");
1601 PyErr_SetString(PyExc_TypeError, "not an array type");
1609 static PyObject *pyrna_prop_collection_subscript(BPy_PropertyRNA *self, PyObject *key)
1611 if (PyUnicode_Check(key)) {
1612 return pyrna_prop_collection_subscript_str(self, _PyUnicode_AsString(key));
1614 else if (PyIndex_Check(key)) {
1615 Py_ssize_t i = PyNumber_AsSsize_t(key, PyExc_IndexError);
1616 if (i == -1 && PyErr_Occurred())
1619 return pyrna_prop_collection_subscript_int(self, i);
1621 else if (PySlice_Check(key)) {
1622 PySliceObject *key_slice= (PySliceObject *)key;
1625 if(key_slice->step != Py_None && !_PyEval_SliceIndex(key, &step)) {
1628 else if (step != 1) {
1629 PyErr_SetString(PyExc_TypeError, "bpy_prop_collection[slice]: slice steps not supported");
1632 else if(key_slice->start == Py_None && key_slice->stop == Py_None) {
1633 return pyrna_prop_collection_subscript_slice(self, 0, PY_SSIZE_T_MAX);
1636 Py_ssize_t start= 0, stop= PY_SSIZE_T_MAX;
1638 /* avoid PySlice_GetIndicesEx because it needs to know the length ahead of time. */
1639 if(key_slice->start != Py_None && !_PyEval_SliceIndex(key_slice->start, &start)) return NULL;
1640 if(key_slice->stop != Py_None && !_PyEval_SliceIndex(key_slice->stop, &stop)) return NULL;
1642 if(start < 0 || stop < 0) {
1643 /* only get the length for negative values */
1644 Py_ssize_t len= (Py_ssize_t)RNA_property_collection_length(&self->ptr, self->prop);
1645 if(start < 0) start += len;
1646 if(stop < 0) start += len;
1649 if (stop - start <= 0) {
1650 return PyList_New(0);
1653 return pyrna_prop_collection_subscript_slice(self, start, stop);
1658 PyErr_Format(PyExc_TypeError, "bpy_prop_collection[key]: invalid key, must be a string or an int, not %.200s", Py_TYPE(key)->tp_name);
1663 static PyObject *pyrna_prop_array_subscript(BPy_PropertyArrayRNA *self, PyObject *key)
1665 /*if (PyUnicode_Check(key)) {
1666 return pyrna_prop_array_subscript_str(self, _PyUnicode_AsString(key));
1668 if (PyIndex_Check(key)) {
1669 Py_ssize_t i = PyNumber_AsSsize_t(key, PyExc_IndexError);
1670 if (i == -1 && PyErr_Occurred())
1672 return pyrna_prop_array_subscript_int(self, PyLong_AsLong(key));
1674 else if (PySlice_Check(key)) {
1676 PySliceObject *key_slice= (PySliceObject *)key;
1678 if(key_slice->step != Py_None && !_PyEval_SliceIndex(key, &step)) {
1681 else if (step != 1) {
1682 PyErr_SetString(PyExc_TypeError, "bpy_prop_array[slice]: slice steps not supported");
1685 else if(key_slice->start == Py_None && key_slice->stop == Py_None) {
1686 /* note, no significant advantage with optimizing [:] slice as with collections but include here for consistency with collection slice func */
1687 Py_ssize_t len= (Py_ssize_t)pyrna_prop_array_length(self);
1688 return pyrna_prop_array_subscript_slice(self, &self->ptr, self->prop, 0, len, len);
1691 int len= pyrna_prop_array_length(self);
1692 Py_ssize_t start, stop, slicelength;
1694 if (PySlice_GetIndicesEx((void *)key, len, &start, &stop, &step, &slicelength) < 0)
1697 if (slicelength <= 0) {
1698 return PyTuple_New(0);
1701 return pyrna_prop_array_subscript_slice(self, &self->ptr, self->prop, start, stop, len);
1706 PyErr_SetString(PyExc_AttributeError, "bpy_prop_array[key]: invalid key, key must be an int");
1711 /* could call (pyrna_py_to_prop_array_index(self, i, value) in a loop but it is slow */
1712 static int prop_subscript_ass_array_slice(PointerRNA *ptr, PropertyRNA *prop, int start, int stop, int length, PyObject *value_orig)
1716 void *values_alloc= NULL;
1719 if(value_orig == NULL) {
1720 PyErr_SetString(PyExc_TypeError, "bpy_prop_array[slice] = value: deleting with list types is not supported by bpy_struct");
1724 if(!(value=PySequence_Fast(value_orig, "bpy_prop_array[slice] = value: assignment is not a sequence type"))) {
1728 if(PySequence_Fast_GET_SIZE(value) != stop-start) {
1730 PyErr_SetString(PyExc_TypeError, "bpy_prop_array[slice] = value: resizing bpy_struct arrays isn't supported");
1734 switch (RNA_property_type(prop)) {
1737 float values_stack[PYRNA_STACK_ARRAY];
1738 float *values, fval;
1741 RNA_property_float_range(ptr, prop, &min, &max);
1743 if(length > PYRNA_STACK_ARRAY) { values= values_alloc= PyMem_MALLOC(sizeof(float) * length); }
1744 else { values= values_stack; }
1745 if(start != 0 || stop != length) /* partial assignment? - need to get the array */
1746 RNA_property_float_get_array(ptr, prop, values);
1748 for(count=start; count<stop; count++) {
1749 fval = PyFloat_AsDouble(PySequence_Fast_GET_ITEM(value, count-start));
1750 CLAMP(fval, min, max);
1751 values[count] = fval;
1754 if(PyErr_Occurred()) ret= -1;
1755 else RNA_property_float_set_array(ptr, prop, values);
1760 int values_stack[PYRNA_STACK_ARRAY];
1762 if(length > PYRNA_STACK_ARRAY) { values= values_alloc= PyMem_MALLOC(sizeof(int) * length); }
1763 else { values= values_stack; }
1765 if(start != 0 || stop != length) /* partial assignment? - need to get the array */
1766 RNA_property_boolean_get_array(ptr, prop, values);
1768 for(count=start; count<stop; count++)
1769 values[count] = PyLong_AsLong(PySequence_Fast_GET_ITEM(value, count-start));
1771 if(PyErr_Occurred()) ret= -1;
1772 else RNA_property_boolean_set_array(ptr, prop, values);
1777 int values_stack[PYRNA_STACK_ARRAY];
1781 RNA_property_int_range(ptr, prop, &min, &max);
1783 if(length > PYRNA_STACK_ARRAY) { values= values_alloc= PyMem_MALLOC(sizeof(int) * length); }
1784 else { values= values_stack; }
1786 if(start != 0 || stop != length) /* partial assignment? - need to get the array */
1787 RNA_property_int_get_array(ptr, prop, values);
1789 for(count=start; count<stop; count++) {
1790 ival = PyLong_AsLong(PySequence_Fast_GET_ITEM(value, count-start));
1791 CLAMP(ival, min, max);
1792 values[count] = ival;
1795 if(PyErr_Occurred()) ret= -1;
1796 else RNA_property_int_set_array(ptr, prop, values);
1800 PyErr_SetString(PyExc_TypeError, "not an array type");
1807 PyMem_FREE(values_alloc);
1814 static int prop_subscript_ass_array_int(BPy_PropertyArrayRNA *self, Py_ssize_t keynum, PyObject *value)
1816 int len= pyrna_prop_array_length(self);
1818 if(keynum < 0) keynum += len;
1820 if(keynum >= 0 && keynum < len)
1821 return pyrna_py_to_prop_array_index(self, keynum, value);
1823 PyErr_SetString(PyExc_IndexError, "bpy_prop_array[index] = value: index out of range");
1827 static int pyrna_prop_array_ass_subscript( BPy_PropertyArrayRNA *self, PyObject *key, PyObject *value )
1829 /* char *keyname = NULL; */ /* not supported yet */
1832 if (!RNA_property_editable_flag(&self->ptr, self->prop)) {
1833 PyErr_Format(PyExc_AttributeError, "bpy_prop_collection: attribute \"%.200s\" from \"%.200s\" is read-only", RNA_property_identifier(self->prop), RNA_struct_identifier(self->ptr.type) );
1837 else if (PyIndex_Check(key)) {
1838 Py_ssize_t i = PyNumber_AsSsize_t(key, PyExc_IndexError);
1839 if (i == -1 && PyErr_Occurred()) {
1843 ret= prop_subscript_ass_array_int(self, i, value);
1846 else if (PySlice_Check(key)) {
1847 int len= RNA_property_array_length(&self->ptr, self->prop);
1848 Py_ssize_t start, stop, step, slicelength;
1850 if (PySlice_GetIndicesEx((void *)key, len, &start, &stop, &step, &slicelength) < 0) {
1853 else if (slicelength <= 0) {
1854 ret= 0; /* do nothing */
1856 else if (step == 1) {
1857 ret= prop_subscript_ass_array_slice(&self->ptr, self->prop, start, stop, len, value);
1860 PyErr_SetString(PyExc_TypeError, "slice steps not supported with rna");
1865 PyErr_SetString(PyExc_AttributeError, "invalid key, key must be an int");
1870 if(RNA_property_update_check(self->prop)) {
1871 RNA_property_update(BPy_GetContext(), &self->ptr, self->prop);
1878 /* for slice only */
1879 static PyMappingMethods pyrna_prop_array_as_mapping = {
1880 ( lenfunc ) pyrna_prop_array_length, /* mp_length */
1881 ( binaryfunc ) pyrna_prop_array_subscript, /* mp_subscript */
1882 ( objobjargproc ) pyrna_prop_array_ass_subscript, /* mp_ass_subscript */
1885 static PyMappingMethods pyrna_prop_collection_as_mapping = {
1886 ( lenfunc ) pyrna_prop_collection_length, /* mp_length */
1887 ( binaryfunc ) pyrna_prop_collection_subscript, /* mp_subscript */
1888 ( objobjargproc ) NULL, /* mp_ass_subscript */
1891 /* only for fast bool's, large structs, assign nb_bool on init */
1892 static PyNumberMethods pyrna_prop_array_as_number = {
1894 NULL, /* nb_subtract */
1895 NULL, /* nb_multiply */
1896 NULL, /* nb_remainder */
1897 NULL, /* nb_divmod */
1898 NULL, /* nb_power */
1899 NULL, /* nb_negative */
1900 NULL, /* nb_positive */
1901 NULL, /* nb_absolute */
1902 (inquiry) pyrna_prop_array_bool, /* nb_bool */
1904 static PyNumberMethods pyrna_prop_collection_as_number = {
1906 NULL, /* nb_subtract */
1907 NULL, /* nb_multiply */
1908 NULL, /* nb_remainder */
1909 NULL, /* nb_divmod */
1910 NULL, /* nb_power */
1911 NULL, /* nb_negative */
1912 NULL, /* nb_positive */
1913 NULL, /* nb_absolute */
1914 (inquiry) pyrna_prop_collection_bool, /* nb_bool */
1917 static int pyrna_prop_array_contains(BPy_PropertyRNA *self, PyObject *value)
1919 return pyrna_array_contains_py(&self->ptr, self->prop, value);
1922 static int pyrna_prop_collection_contains(BPy_PropertyRNA *self, PyObject *value)
1924 PointerRNA newptr; /* not used, just so RNA_property_collection_lookup_string runs */
1926 /* key in dict style check */
1927 const char *keyname = _PyUnicode_AsString(value);
1930 PyErr_SetString(PyExc_TypeError, "bpy_prop_collection.__contains__: expected a string");
1934 if (RNA_property_collection_lookup_string(&self->ptr, self->prop, keyname, &newptr))
1940 static int pyrna_struct_contains(BPy_StructRNA *self, PyObject *value)
1943 const char *name = _PyUnicode_AsString(value);
1946 PyErr_SetString(PyExc_TypeError, "bpy_struct.__contains__: expected a string");
1950 if(RNA_struct_idprops_check(self->ptr.type)==0) {
1951 PyErr_SetString(PyExc_TypeError, "bpy_struct: this type doesnt support IDProperties");
1955 group= RNA_struct_idprops(&self->ptr, 0);
1960 return IDP_GetPropertyFromGroup(group, name) ? 1:0;
1963 static PySequenceMethods pyrna_prop_array_as_sequence = {
1964 (lenfunc)pyrna_prop_array_length, /* Cant set the len otherwise it can evaluate as false */
1965 NULL, /* sq_concat */
1966 NULL, /* sq_repeat */
1967 (ssizeargfunc)pyrna_prop_array_subscript_int, /* sq_item */ /* Only set this so PySequence_Check() returns True */
1968 NULL, /* sq_slice */
1969 (ssizeobjargproc)prop_subscript_ass_array_int, /* sq_ass_item */
1970 NULL, /* *was* sq_ass_slice */
1971 (objobjproc)pyrna_prop_array_contains, /* sq_contains */
1972 (binaryfunc) NULL, /* sq_inplace_concat */
1973 (ssizeargfunc) NULL, /* sq_inplace_repeat */
1976 static PySequenceMethods pyrna_prop_collection_as_sequence = {
1977 (lenfunc)pyrna_prop_collection_length, /* Cant set the len otherwise it can evaluate as false */
1978 NULL, /* sq_concat */
1979 NULL, /* sq_repeat */
1980 (ssizeargfunc)pyrna_prop_collection_subscript_int, /* sq_item */ /* Only set this so PySequence_Check() returns True */
1981 NULL, /* *was* sq_slice */
1982 NULL, /* sq_ass_item */
1983 NULL, /* *was* sq_ass_slice */
1984 (objobjproc)pyrna_prop_collection_contains, /* sq_contains */
1985 (binaryfunc) NULL, /* sq_inplace_concat */
1986 (ssizeargfunc) NULL, /* sq_inplace_repeat */
1989 static PySequenceMethods pyrna_struct_as_sequence = {
1990 NULL, /* Cant set the len otherwise it can evaluate as false */
1991 NULL, /* sq_concat */
1992 NULL, /* sq_repeat */
1993 NULL, /* sq_item */ /* Only set this so PySequence_Check() returns True */
1994 NULL, /* *was* sq_slice */
1995 NULL, /* sq_ass_item */
1996 NULL, /* *was* sq_ass_slice */
1997 (objobjproc)pyrna_struct_contains, /* sq_contains */
1998 (binaryfunc) NULL, /* sq_inplace_concat */
1999 (ssizeargfunc) NULL, /* sq_inplace_repeat */
2002 static PyObject *pyrna_struct_subscript( BPy_StructRNA *self, PyObject *key )
2004 /* mostly copied from BPy_IDGroup_Map_GetItem */
2005 IDProperty *group, *idprop;
2006 const char *name= _PyUnicode_AsString(key);
2008 if(RNA_struct_idprops_check(self->ptr.type)==0) {
2009 PyErr_SetString(PyExc_TypeError, "this type doesn't support IDProperties");
2014 PyErr_SetString(PyExc_TypeError, "bpy_struct[key]: only strings are allowed as keys of ID properties");
2018 group= RNA_struct_idprops(&self->ptr, 0);
2021 PyErr_Format(PyExc_KeyError, "bpy_struct[key]: key \"%s\" not found", name);
2025 idprop= IDP_GetPropertyFromGroup(group, name);
2028 PyErr_Format(PyExc_KeyError, "bpy_struct[key]: key \"%s\" not found", name);
2032 return BPy_IDGroup_WrapData(self->ptr.id.data, idprop);
2035 static int pyrna_struct_ass_subscript( BPy_StructRNA *self, PyObject *key, PyObject *value )
2037 IDProperty *group= RNA_struct_idprops(&self->ptr, 1);
2039 #ifdef USE_PEDANTIC_WRITE
2040 if(rna_disallow_writes && rna_id_write_error(&self->ptr, key)) {
2043 #endif // USE_STRING_COERCE
2046 PyErr_SetString(PyExc_TypeError, "bpy_struct[key] = val: id properties not supported for this type");
2050 return BPy_Wrap_SetMapItem(group, key, value);
2053 static PyMappingMethods pyrna_struct_as_mapping = {
2054 ( lenfunc ) NULL, /* mp_length */
2055 ( binaryfunc ) pyrna_struct_subscript, /* mp_subscript */
2056 ( objobjargproc ) pyrna_struct_ass_subscript, /* mp_ass_subscript */
2059 static char pyrna_struct_keys_doc[] =
2060 ".. method:: keys()\n"
2062 " Returns the keys of this objects custom properties (matches pythons dictionary function of the same name).\n"
2064 " :return: custom property keys.\n"
2065 " :rtype: list of strings\n"
2067 " .. note:: Only :class:`ID`, :class:`Bone` and :class:`PoseBone` classes support custom properties.\n";
2069 static PyObject *pyrna_struct_keys(BPy_PropertyRNA *self)
2073 if(RNA_struct_idprops_check(self->ptr.type)==0) {
2074 PyErr_SetString(PyExc_TypeError, "bpy_struct.keys(): this type doesn't support IDProperties");
2078 group= RNA_struct_idprops(&self->ptr, 0);
2081 return PyList_New(0);
2083 return BPy_Wrap_GetKeys(group);
2086 static char pyrna_struct_items_doc[] =
2087 ".. method:: items()\n"
2089 " Returns the items of this objects custom properties (matches pythons dictionary function of the same name).\n"
2091 " :return: custom property key, value pairs.\n"
2092 " :rtype: list of key, value tuples\n"
2094 " .. note:: Only :class:`ID`, :class:`Bone` and :class:`PoseBone` classes support custom properties.\n";
2096 static PyObject *pyrna_struct_items(BPy_PropertyRNA *self)
2100 if(RNA_struct_idprops_check(self->ptr.type)==0) {
2101 PyErr_SetString(PyExc_TypeError, "bpy_struct.items(): this type doesn't support IDProperties");
2105 group= RNA_struct_idprops(&self->ptr, 0);
2108 return PyList_New(0);
2110 return BPy_Wrap_GetItems(self->ptr.id.data, group);
2113 static char pyrna_struct_values_doc[] =
2114 ".. method:: values()\n"
2116 " Returns the values of this objects custom properties (matches pythons dictionary function of the same name).\n"
2118 " :return: custom property values.\n"
2121 " .. note:: Only :class:`ID`, :class:`Bone` and :class:`PoseBone` classes support custom properties.\n";
2123 static PyObject *pyrna_struct_values(BPy_PropertyRNA *self)
2127 if(RNA_struct_idprops_check(self->ptr.type)==0) {
2128 PyErr_SetString(PyExc_TypeError, "bpy_struct.values(): this type doesn't support IDProperties");
2132 group= RNA_struct_idprops(&self->ptr, 0);
2135 return PyList_New(0);
2137 return BPy_Wrap_GetValues(self->ptr.id.data, group);
2140 /* for keyframes and drivers */
2141 static int pyrna_struct_anim_args_parse(PointerRNA *ptr, const char *error_prefix, const char *path,
2142 const char **path_full, int *index)
2144 const int is_idbase= RNA_struct_is_ID(ptr->type);
2148 if (ptr->data==NULL) {
2149 PyErr_Format(PyExc_TypeError, "%.200s this struct has no data, can't be animated", error_prefix);
2153 /* full paths can only be given from ID base */
2156 if(RNA_path_resolve_full(ptr, path, &r_ptr, &prop, &r_index)==0) {
2159 else if(r_index != -1) {
2160 PyErr_Format(PyExc_ValueError, "%.200s path includes index, must be a separate argument", error_prefix, path);
2163 else if(ptr->id.data != r_ptr.id.data) {
2164 PyErr_Format(PyExc_ValueError, "%.200s path spans ID blocks", error_prefix, path);
2169 prop = RNA_struct_find_property(ptr, path);
2174 PyErr_Format(PyExc_TypeError, "%.200s property \"%s\" not found", error_prefix, path);
2178 if (!RNA_property_animateable(&r_ptr, prop)) {
2179 PyErr_Format(PyExc_TypeError, "%.200s property \"%s\" not animatable", error_prefix, path);
2183 if(RNA_property_array_check(&r_ptr, prop) == 0) {
2184 if((*index) == -1) {
2188 PyErr_Format(PyExc_TypeError, "%.200s index %d was given while property \"%s\" is not an array", error_prefix, *index, path);
2193 int array_len= RNA_property_array_length(&r_ptr, prop);
2194 if((*index) < -1 || (*index) >= array_len) {
2195 PyErr_Format(PyExc_TypeError, "%.200s index out of range \"%s\", given %d, array length is %d", error_prefix, path, *index, array_len);
2201 *path_full= BLI_strdup(path);
2204 *path_full= RNA_path_from_ID_to_property(&r_ptr, prop);
2206 if (*path_full==NULL) {
2207 PyErr_Format(PyExc_TypeError, "%.200s could not make path to \"%s\"", error_prefix, path);
2215 /* internal use for insert and delete */
2216 static int pyrna_struct_keyframe_parse(PointerRNA *ptr, PyObject *args, PyObject *kw, const char *parse_str, const char *error_prefix,
2217 const char **path_full, int *index, float *cfra, const char **group_name) /* return values */
2219 static const char *kwlist[] = {"data_path", "index", "frame", "group", NULL};
2222 /* note, parse_str MUST start with 's|ifs' */
2223 if (!PyArg_ParseTupleAndKeywords(args, kw, parse_str, (char **)kwlist, &path, index, cfra, group_name))
2226 if(pyrna_struct_anim_args_parse(ptr, error_prefix, path, path_full, index) < 0)
2230 *cfra= CTX_data_scene(BPy_GetContext())->r.cfra;
2232 return 0; /* success */
2235 static char pyrna_struct_keyframe_insert_doc[] =
2236 ".. method:: keyframe_insert(data_path, index=-1, frame=bpy.context.scene.frame_current, group=\"\")\n"
2238 " Insert a keyframe on the property given, adding fcurves and animation data when necessary.\n"
2240 " :arg data_path: path to the property to key, analogous to the fcurve's data path.\n"
2241 " :type data_path: string\n"
2242 " :arg index: array index of the property to key. Defaults to -1 which will key all indices or a single channel if the property is not an array.\n"
2243 " :type index: int\n"
2244 " :arg frame: The frame on which the keyframe is inserted, defaulting to the current frame.\n"
2245 " :type frame: float\n"
2246 " :arg group: The name of the group the F-Curve should be added to if it doesn't exist yet.\n"
2247 " :type group: str\n"
2248 " :return: Success of keyframe insertion.\n"
2251 static PyObject *pyrna_struct_keyframe_insert(BPy_StructRNA *self, PyObject *args, PyObject *kw)
2253 /* args, pyrna_struct_keyframe_parse handles these */
2254 const char *path_full= NULL;
2256 float cfra= FLT_MAX;
2257 const char *group_name= NULL;
2259 if(pyrna_struct_keyframe_parse(&self->ptr, args, kw, "s|ifs:bpy_struct.keyframe_insert()", "bpy_struct.keyframe_insert()", &path_full, &index, &cfra, &group_name) == -1) {
2266 BKE_reports_init(&reports, RPT_STORE);
2268 result= insert_keyframe(&reports, (ID *)self->ptr.id.data, NULL, group_name, path_full, index, cfra, 0);
2269 MEM_freeN((void *)path_full);
2271 if(BPy_reports_to_error(&reports, TRUE))
2274 return PyBool_FromLong(result);
2278 static char pyrna_struct_keyframe_delete_doc[] =
2279 ".. method:: keyframe_delete(data_path, index=-1, frame=bpy.context.scene.frame_current, group=\"\")\n"
2281 " Remove a keyframe from this properties fcurve.\n"
2283 " :arg data_path: path to the property to remove a key, analogous to the fcurve's data path.\n"
2284 " :type data_path: string\n"
2285 " :arg index: array index of the property to remove a key. Defaults to -1 removing all indices or a single channel if the property is not an array.\n"
2286 " :type index: int\n"
2287 " :arg frame: The frame on which the keyframe is deleted, defaulting to the current frame.\n"
2288 " :type frame: float\n"
2289 " :arg group: The name of the group the F-Curve should be added to if it doesn't exist yet.\n"
2290 " :type group: str\n"
2291 " :return: Success of keyframe deleation.\n"
2294 static PyObject *pyrna_struct_keyframe_delete(BPy_StructRNA *self, PyObject *args, PyObject *kw)
2296 /* args, pyrna_struct_keyframe_parse handles these */
2297 const char *path_full= NULL;
2299 float cfra= FLT_MAX;
2300 const char *group_name= NULL;
2302 if(pyrna_struct_keyframe_parse(&self->ptr, args, kw, "s|ifs:bpy_struct.keyframe_delete()", "bpy_struct.keyframe_insert()", &path_full, &index, &cfra, &group_name) == -1) {
2309 BKE_reports_init(&reports, RPT_STORE);
2311 result= delete_keyframe(&reports, (ID *)self->ptr.id.data, NULL, group_name, path_full, index, cfra, 0);
2312 MEM_freeN((void *)path_full);
2314 if(BPy_reports_to_error(&reports, TRUE))
2317 return PyBool_FromLong(result);
2322 static char pyrna_struct_driver_add_doc[] =
2323 ".. method:: driver_add(path, index=-1)\n"
2325 " Adds driver(s) to the given property\n"
2327 " :arg path: path to the property to drive, analogous to the fcurve's data path.\n"
2328 " :type path: string\n"
2329 " :arg index: array index of the property drive. Defaults to -1 for all indices or a single channel if the property is not an array.\n"
2330 " :type index: int\n"
2331 " :return: The driver(s) added.\n"
2332 " :rtype: :class:`FCurve` or list if index is -1 with an array property.";
2334 static PyObject *pyrna_struct_driver_add(BPy_StructRNA *self, PyObject *args)
2336 const char *path, *path_full;
2339 if (!PyArg_ParseTuple(args, "s|i:driver_add", &path, &index))
2342 if(pyrna_struct_anim_args_parse(&self->ptr, "bpy_struct.driver_add():", path, &path_full, &index) < 0) {
2346 PyObject *ret= NULL;
2350 BKE_reports_init(&reports, RPT_STORE);
2352 result= ANIM_add_driver(&reports, (ID *)self->ptr.id.data, path_full, index, 0, DRIVER_TYPE_PYTHON);
2354 if(BPy_reports_to_error(&reports, TRUE))
2358 ID *id= self->ptr.id.data;
2359 AnimData *adt= BKE_animdata_from_id(id);
2365 if(index == -1) { /* all, use a list */
2368 while((fcu= list_find_fcurve(&adt->drivers, path_full, i++))) {
2369 RNA_pointer_create(id, &RNA_FCurve, fcu, &tptr);
2370 item= pyrna_struct_CreatePyObject(&tptr);
2371 PyList_Append(ret, item);
2376 fcu= list_find_fcurve(&adt->drivers, path_full, index);
2377 RNA_pointer_create(id, &RNA_FCurve, fcu, &tptr);
2378 ret= pyrna_struct_CreatePyObject(&tptr);
2382 /* XXX, should be handled by reports, */
2383 PyErr_SetString(PyExc_TypeError, "bpy_struct.driver_add(): failed because of an internal error");
2387 MEM_freeN((void *)path_full);
2394 static char pyrna_struct_driver_remove_doc[] =
2395 ".. method:: driver_remove(path, index=-1)\n"
2397 " Remove driver(s) from the given property\n"
2399 " :arg path: path to the property to drive, analogous to the fcurve's data path.\n"
2400 " :type path: string\n"
2401 " :arg index: array index of the property drive. Defaults to -1 for all indices or a single channel if the property is not an array.\n"
2402 " :type index: int\n"
2403 " :return: Success of driver removal.\n"
2406 static PyObject *pyrna_struct_driver_remove(BPy_StructRNA *self, PyObject *args)
2408 const char *path, *path_full;
2411 if (!PyArg_ParseTuple(args, "s|i:driver_remove", &path, &index))
2414 if(pyrna_struct_anim_args_parse(&self->ptr, "bpy_struct.driver_remove():", path, &path_full, &index) < 0) {
2421 BKE_reports_init(&reports, RPT_STORE);
2423 result= ANIM_remove_driver(&reports, (ID *)self->ptr.id.data, path_full, index, 0);
2425 MEM_freeN((void *)path_full);
2427 if(BPy_reports_to_error(&reports, TRUE))
2430 return PyBool_FromLong(result);
2435 static char pyrna_struct_is_property_set_doc[] =
2436 ".. method:: is_property_set(property)\n"
2438 " Check if a property is set, use for testing operator properties.\n"
2440 " :return: True when the property has been set.\n"
2443 static PyObject *pyrna_struct_is_property_set(BPy_StructRNA *self, PyObject *args)
2449 if (!PyArg_ParseTuple(args, "s:is_property_set", &name))
2452 if((prop= RNA_struct_find_property(&self->ptr, name)) == NULL) {
2453 PyErr_Format(PyExc_TypeError, "%.200s.is_property_set(\"%.200s\") not found", RNA_struct_identifier(self->ptr.type), name);
2457 /* double property lookup, could speed up */
2458 /* return PyBool_FromLong(RNA_property_is_set(&self->ptr, name)); */
2459 if(RNA_property_flag(prop) & PROP_IDPROPERTY) {
2460 IDProperty *group= RNA_struct_idprops(&self->ptr, 0);
2462 ret= IDP_GetPropertyFromGroup(group, name) ? 1:0;
2472 return PyBool_FromLong(ret);
2475 static char pyrna_struct_is_property_hidden_doc[] =
2476 ".. method:: is_property_hidden(property)\n"
2478 " Check if a property is hidden.\n"
2480 " :return: True when the property is hidden.\n"
2483 static PyObject *pyrna_struct_is_property_hidden(BPy_StructRNA *self, PyObject *args)
2488 if (!PyArg_ParseTuple(args, "s:is_property_hidden", &name))
2491 if((prop= RNA_struct_find_property(&self->ptr, name)) == NULL) {
2492 PyErr_Format(PyExc_TypeError, "%.200s.is_property_hidden(\"%.200s\") not found", RNA_struct_identifier(self->ptr.type), name);
2496 return PyBool_FromLong(RNA_property_flag(prop) & PROP_HIDDEN);
2499 static char pyrna_struct_path_resolve_doc[] =
2500 ".. method:: path_resolve(path, coerce=True)\n"
2502 " Returns the property from the path, raise an exception when not found.\n"
2504 " :arg path: path which this property resolves.\n"
2505 " :type path: string\n"
2506 " :arg coerce: optional argument, when True, the property will be converted into its python representation.\n"
2507 " :type coerce: boolean\n";
2509 static PyObject *pyrna_struct_path_resolve(BPy_StructRNA *self, PyObject *args)
2512 PyObject *coerce= Py_True;
2514 PropertyRNA *r_prop;
2517 if (!PyArg_ParseTuple(args, "s|O!:path_resolve", &path, &PyBool_Type, &coerce))
2520 if (RNA_path_resolve_full(&self->ptr, path, &r_ptr, &r_prop, &index)) {
2523 if(index >= RNA_property_array_length(&r_ptr, r_prop) || index < 0) {
2524 PyErr_Format(PyExc_TypeError, "%.200s.path_resolve(\"%.200s\") index out of range", RNA_struct_identifier(self->ptr.type), path);
2528 return pyrna_array_index(&r_ptr, r_prop, index);
2532 if(coerce == Py_False) {
2533 return pyrna_prop_CreatePyObject(&r_ptr, r_prop);
2536 return pyrna_prop_to_py(&r_ptr, r_prop);
2541 return pyrna_struct_CreatePyObject(&r_ptr);
2545 PyErr_Format(PyExc_TypeError, "%.200s.path_resolve(\"%.200s\") could not be resolved", RNA_struct_identifier(self->ptr.type), path);
2550 static char pyrna_struct_path_from_id_doc[] =
2551 ".. method:: path_from_id(property=\"\")\n"
2553 " Returns the data path from the ID to this object (string).\n"
2555 " :arg property: Optional property name which can be used if the path is to a property of this object.\n"
2556 " :type property: string\n"
2557 " :return: The path from :class:`bpy_struct.id_data` to this struct and property (when given).\n"
2560 static PyObject *pyrna_struct_path_from_id(BPy_StructRNA *self, PyObject *args)
2562 const char *name= NULL;
2567 if (!PyArg_ParseTuple(args, "|s:path_from_id", &name))
2571 prop= RNA_struct_find_property(&self->ptr, name);
2573 PyErr_Format(PyExc_TypeError, "%.200s.path_from_id(\"%.200s\") not found", RNA_struct_identifier(self->ptr.type), name);
2577 path= RNA_path_from_ID_to_property(&self->ptr, prop);
2580 path= RNA_path_from_ID_to_struct(&self->ptr);
2584 if(name) PyErr_Format(PyExc_TypeError, "%.200s.path_from_id(\"%s\") found but does not support path creation", RNA_struct_identifier(self->ptr.type), name);
2585 else PyErr_Format(PyExc_TypeError, "%.200s.path_from_id() does not support path creation for this type", RNA_struct_identifier(self->ptr.type));
2589 ret= PyUnicode_FromString(path);
2590 MEM_freeN((void *)path);
2595 static char pyrna_prop_path_from_id_doc[] =
2596 ".. method:: path_from_id()\n"
2598 " Returns the data path from the ID to this property (string).\n"
2600 " :return: The path from :class:`bpy_struct.id_data` to this property.\n"
2603 static PyObject *pyrna_prop_path_from_id(BPy_PropertyRNA *self)
2606 PropertyRNA *prop = self->prop;
2609 path= RNA_path_from_ID_to_property(&self->ptr, self->prop);
2612 PyErr_Format(PyExc_TypeError, "%.200s.%.200s.path_from_id() does not support path creation for this type", RNA_struct_identifier(self->ptr.type), RNA_property_identifier(prop));
2616 ret= PyUnicode_FromString(path);
2617 MEM_freeN((void *)path);
2622 static char pyrna_struct_type_recast_doc[] =
2623 ".. method:: type_recast()\n"
2625 " Return a new instance, this is needed because types such as textures can be changed at runtime.\n"
2627 " :return: a new instance of this object with the type initialized again.\n"
2628 " :rtype: subclass of :class:`bpy_struct`";
2630 static PyObject *pyrna_struct_type_recast(BPy_StructRNA *self)
2633 RNA_pointer_recast(&self->ptr, &r_ptr);
2634 return pyrna_struct_CreatePyObject(&r_ptr);
2637 static void pyrna_dir_members_py(PyObject *list, PyObject *self)
2640 PyObject **dict_ptr;
2643 dict_ptr= _PyObject_GetDictPtr((PyObject *)self);
2645 if(dict_ptr && (dict=*dict_ptr)) {
2646 list_tmp = PyDict_Keys(dict);
2647 PyList_SetSlice(list, INT_MAX, INT_MAX, list_tmp);
2648 Py_DECREF(list_tmp);
2651 dict= ((PyTypeObject *)Py_TYPE(self))->tp_dict;
2653 list_tmp = PyDict_Keys(dict);
2654 PyList_SetSlice(list, INT_MAX, INT_MAX, list_tmp);
2655 Py_DECREF(list_tmp);
2659 static void pyrna_dir_members_rna(PyObject *list, PointerRNA *ptr)
2664 /* for looping over attrs and funcs */
2666 PropertyRNA *iterprop;
2669 RNA_pointer_create(NULL, &RNA_Struct, ptr->type, &tptr);
2670 iterprop= RNA_struct_find_property(&tptr, "functions");
2672 RNA_PROP_BEGIN(&tptr, itemptr, iterprop) {
2673 idname= RNA_function_identifier(itemptr.data);
2675 pystring = PyUnicode_FromString(idname);
2676 PyList_Append(list, pystring);
2677 Py_DECREF(pystring);
2684 * Collect RNA attributes
2686 char name[256], *nameptr;
2688 iterprop= RNA_struct_iterator_property(ptr->type);
2690 RNA_PROP_BEGIN(ptr, itemptr, iterprop) {
2691 nameptr= RNA_struct_name_get_alloc(&itemptr, name, sizeof(name));
2694 pystring = PyUnicode_FromString(nameptr);
2695 PyList_Append(list, pystring);
2696 Py_DECREF(pystring);
2707 static PyObject *pyrna_struct_dir(BPy_StructRNA *self)
2712 /* Include this incase this instance is a subtype of a python class
2713 * In these instances we may want to return a function or variable provided by the subtype
2715 ret = PyList_New(0);
2717 if (!BPy_StructRNA_CheckExact(self))
2718 pyrna_dir_members_py(ret, (PyObject *)self);
2720 pyrna_dir_members_rna(ret, &self->ptr);
2722 if(self->ptr.type == &RNA_Context) {
2723 ListBase lb = CTX_data_dir_get(self->ptr.data);
2726 for(link=lb.first; link; link=link->next) {
2727 pystring = PyUnicode_FromString(link->data);
2728 PyList_Append(ret, pystring);
2729 Py_DECREF(pystring);
2736 /* set(), this is needed to remove-doubles because the deferred
2737 * register-props will be in both the python __dict__ and accessed as RNA */
2739 PyObject *set= PySet_New(ret);
2742 ret= PySequence_List(set);
2749 //---------------getattr--------------------------------------------
2750 static PyObject *pyrna_struct_getattro( BPy_StructRNA *self, PyObject *pyname )
2752 const char *name = _PyUnicode_AsString(pyname);
2758 PyErr_SetString(PyExc_AttributeError, "bpy_struct: __getattr__ must be a string");
2761 else if(name[0]=='_') { // rna can't start with a "_", so for __dict__ and similar we can skip using rna lookups
2762 /* annoying exception, maybe we need to have different types for this... */
2763 if((strcmp(name, "__getitem__")==0 || strcmp(name, "__setitem__")==0) && !RNA_struct_idprops_check(self->ptr.type)) {
2764 PyErr_SetString(PyExc_AttributeError, "bpy_struct: no __getitem__ support for this type");
2768 ret = PyObject_GenericGetAttr((PyObject *)self, pyname);
2771 else if ((prop = RNA_struct_find_property(&self->ptr, name))) {
2772 ret = pyrna_prop_to_py(&self->ptr, prop);
2774 /* RNA function only if callback is declared (no optional functions) */
2775 else if ((func = RNA_struct_find_function(&self->ptr, name)) && RNA_function_defined(func)) {
2776 ret = pyrna_func_to_py((BPy_DummyPointerRNA *)self, func);
2778 else if (self->ptr.type == &RNA_Context) {
2779 bContext *C = self->ptr.data;
2781 PyErr_Format(PyExc_AttributeError, "bpy_struct: Context is 'NULL', can't get \"%.200s\" from context", name);
2789 int done= CTX_data_get(C, name, &newptr, &newlb, &newtype);
2791 if(done==1) { /* found */
2793 case CTX_DATA_TYPE_POINTER:
2794 if(newptr.data == NULL) {
2799 ret= pyrna_struct_CreatePyObject(&newptr);
2802 case CTX_DATA_TYPE_COLLECTION:
2804 CollectionPointerLink *link;
2807 ret = PyList_New(0);
2809 for(link=newlb.first; link; link=link->next) {
2810 linkptr= pyrna_struct_CreatePyObject(&link->ptr);
2811 PyList_Append(ret, linkptr);
2817 /* should never happen */
2818 BLI_assert(!"Invalid context type");
2820 PyErr_Format(PyExc_AttributeError, "bpy_struct: Context type invalid %d, can't get \"%.200s\" from context", newtype, name);
2824 else if (done==-1) { /* found but not set */
2828 else { /* not found in the context */
2829 /* lookup the subclass. raise an error if its not found */
2830 ret = PyObject_GenericGetAttr((PyObject *)self, pyname);
2833 BLI_freelistN(&newlb);
2838 PyErr_Format(PyExc_AttributeError, "bpy_struct: attribute \"%.200s\" not found", name);
2841 /* Include this incase this instance is a subtype of a python class
2842 * In these instances we may want to return a function or variable provided by the subtype
2844 * Also needed to return methods when its not a subtype
2847 /* The error raised here will be displayed */
2848 ret = PyObject_GenericGetAttr((PyObject *)self, pyname);
2855 static int pyrna_struct_pydict_contains(PyObject *self, PyObject *pyname)
2857 PyObject *dict= *(_PyObject_GetDictPtr((PyObject *)self));
2858 if (dict==NULL) /* unlikely */
2861 return PyDict_Contains(dict, pyname);
2865 //--------------- setattr-------------------------------------------
2866 static int pyrna_is_deferred_prop(PyObject *value)
2868 return PyTuple_CheckExact(value) && PyTuple_GET_SIZE(value)==2 && PyCallable_Check(PyTuple_GET_ITEM(value, 0)) && PyDict_CheckExact(PyTuple_GET_ITEM(value, 1));
2872 static PyObject *pyrna_struct_meta_idprop_getattro(PyObject *cls, PyObject *attr)
2874 PyObject *ret= PyType_Type.tp_getattro(cls, attr);
2877 * >>> bpy.types.Scene.foo = BoolProperty()
2878 * >>> bpy.types.Scene.foo
2879 * <bpy_struct, BooleanProperty("foo")>
2880 * ...rather then returning the defered class register tuple as checked by pyrna_is_deferred_prop()
2882 * Disable for now, this is faking internal behavior in a way thats too tricky to maintain well. */
2884 if(ret == NULL) { // || pyrna_is_deferred_prop(ret)
2885 StructRNA *srna= srna_from_self(cls, "StructRNA.__getattr__");
2887 PropertyRNA *prop= RNA_struct_type_find_property(srna, _PyUnicode_AsString(attr));
2890 PyErr_Clear(); /* clear error from tp_getattro */
2891 RNA_pointer_create(NULL, &RNA_Property, prop, &tptr);
2892 ret= pyrna_struct_CreatePyObject(&tptr);
2902 static int pyrna_struct_meta_idprop_setattro(PyObject *cls, PyObject *attr, PyObject *value)
2904 StructRNA *srna= srna_from_self(cls, "StructRNA.__setattr__");
2907 if(value && pyrna_is_deferred_prop(value)) {
2908 PyErr_Format(PyExc_AttributeError, "pyrna_struct_meta_idprop_setattro() unable to get srna from class '%.200s'", ((PyTypeObject *)cls)->tp_name);
2912 /* srna_from_self may set an error */
2914 return PyType_Type.tp_setattro(cls, attr, value);
2918 /* check if the value is a property */
2919 if(pyrna_is_deferred_prop(value)) {
2920 int ret= deferred_register_prop(srna, attr, value);
2926 /* pass through and assign to the classes __dict__ as well
2927 * when the value isn't assigned it still creates the RNA property
2928 * but gets confusing from script writers POV if the assigned value cant be read back. */
2931 /* remove existing property if its set or we also end up with confusement */
2932 const char *attr_str= _PyUnicode_AsString(attr);
2933 RNA_def_property_free_identifier(srna, attr_str); /* ignore on failier */
2936 else { /* __delattr__ */
2937 /* first find if this is a registered property */
2938 const char *attr_str= _PyUnicode_AsString(attr);
2939 int ret= RNA_def_property_free_identifier(srna, attr_str);
2941 PyErr_Format(PyExc_TypeError, "struct_meta_idprop.detattr(): '%s' not a dynamic property", attr_str);
2946 /* fallback to standard py, delattr/setattr */
2947 return PyType_Type.tp_setattro(cls, attr, value);
2950 static int pyrna_struct_setattro( BPy_StructRNA *self, PyObject *pyname, PyObject *value )
2952 const char *name = _PyUnicode_AsString(pyname);
2953 PropertyRNA *prop= NULL;
2955 #ifdef USE_PEDANTIC_WRITE
2956 if(rna_disallow_writes && rna_id_write_error(&self->ptr, pyname)) {
2959 #endif // USE_STRING_COERCE
2962 PyErr_SetString(PyExc_AttributeError, "bpy_struct: __setattr__ must be a string");
2965 else if (name[0] != '_' && (prop= RNA_struct_find_property(&self->ptr, name))) {
2966 if (!RNA_property_editable_flag(&self->ptr, prop)) {
2967 PyErr_Format(PyExc_AttributeError, "bpy_struct: attribute \"%.200s\" from \"%.200s\" is read-only", RNA_property_identifier(prop), RNA_struct_identifier(self->ptr.type) );
2971 else if (self->ptr.type == &RNA_Context) {
2972 /* code just raises correct error, context prop's cant be set, unless its apart of the py class */
2973 bContext *C = self->ptr.data;
2975 PyErr_Format(PyExc_AttributeError, "bpy_struct: Context is 'NULL', can't set \"%.200s\" from context", name);
2983 int done= CTX_data_get(C, name, &newptr, &newlb, &newtype);
2986 PyErr_Format(PyExc_AttributeError, "bpy_struct: Context property \"%.200s\" is read-only", name);
2987 BLI_freelistN(&newlb);
2991 BLI_freelistN(&newlb);
2995 /* pyrna_py_to_prop sets its own exceptions */
2998 PyErr_SetString(PyExc_AttributeError, "bpy_struct: del not supported");
3001 return pyrna_py_to_prop(&self->ptr, prop, NULL, value, "bpy_struct: item.attr = val:");
3004 return PyObject_GenericSetAttr((PyObject *)self, pyname, value);
3008 static PyObject *pyrna_prop_dir(BPy_PropertyRNA *self)
3013 /* Include this incase this instance is a subtype of a python class
3014 * In these instances we may want to return a function or variable provided by the subtype
3016 ret = PyList_New(0);
3018 if (!BPy_PropertyRNA_CheckExact(self))
3019 pyrna_dir_members_py(ret, (PyObject *)self);
3021 if(RNA_property_collection_type_get(&self->ptr, self->prop, &r_ptr))
3022 pyrna_dir_members_rna(ret, &r_ptr);
3028 static PyObject *pyrna_prop_array_getattro( BPy_PropertyRNA *self, PyObject *pyname )
3030 return PyObject_GenericGetAttr((PyObject *)self, pyname);
3033 static PyObject *pyrna_prop_collection_getattro( BPy_PropertyRNA *self, PyObject *pyname )
3035 const char *name = _PyUnicode_AsString(pyname);
3038 PyErr_SetString(PyExc_AttributeError, "bpy_prop_collection: __getattr__ must be a string");
3041 else if(name[0] != '_') {
3047 if(RNA_property_collection_type_get(&self->ptr, self->prop, &r_ptr)) {
3048 if ((prop = RNA_struct_find_property(&r_ptr, name))) {
3049 ret = pyrna_prop_to_py(&r_ptr, prop);
3053 else if ((func = RNA_struct_find_function(&r_ptr, name))) {
3054 PyObject *self_collection= pyrna_struct_CreatePyObject(&r_ptr);
3055 ret = pyrna_func_to_py((BPy_DummyPointerRNA *)self_collection, func);
3056 Py_DECREF(self_collection);
3063 /* The error raised here will be displayed */
3064 return PyObject_GenericGetAttr((PyObject *)self, pyname);
3067 //--------------- setattr-------------------------------------------
3068 static int pyrna_prop_collection_setattro( BPy_PropertyRNA *self, PyObject *pyname, PyObject *value )
3070 const char *name = _PyUnicode_AsString(pyname);
3074 #ifdef USE_PEDANTIC_WRITE
3075 if(rna_disallow_writes && rna_id_write_error(&self->ptr, pyname)) {
3078 #endif // USE_STRING_COERCE
3081 PyErr_SetString(PyExc_AttributeError, "bpy_prop: __setattr__ must be a string");
3084 else if(value == NULL) {
3085 PyErr_SetString(PyExc_AttributeError, "bpy_prop: del not supported");
3088 else if(RNA_property_collection_type_get(&self->ptr, self->prop, &r_ptr)) {
3089 if ((prop = RNA_struct_find_property(&r_ptr, name))) {
3090 /* pyrna_py_to_prop sets its own exceptions */
3091 return pyrna_py_to_prop(&r_ptr, prop, NULL, value, "BPy_PropertyRNA - Attribute (setattr):");
3095 PyErr_Format(PyExc_AttributeError, "bpy_prop_collection: attribute \"%.200s\" not found", name);
3099 /* odd case, we need to be able return a python method from a tp_getset */
3100 static PyObject *pyrna_prop_collection_idprop_add(BPy_PropertyRNA *self)
3104 RNA_property_collection_add(&self->ptr, self->prop, &r_ptr);
3106 PyErr_SetString(PyExc_TypeError, "bpy_prop_collection.add(): not supported for this collection");
3110 return pyrna_struct_CreatePyObject(&r_ptr);
3114 static PyObject *pyrna_prop_collection_idprop_remove(BPy_PropertyRNA *self, PyObject *value)
3116 int key= PyLong_AsLong(value);
3118 if (key==-1 && PyErr_Occurred()) {
3119 PyErr_SetString(PyExc_TypeError, "bpy_prop_collection.remove(): expected one int argument");
3123 if(!RNA_property_collection_remove(&self->ptr, self->prop, key)) {
3124 PyErr_SetString(PyExc_TypeError, "bpy_prop_collection.remove() not supported for this collection");
3131 static PyObject *pyrna_prop_collection_idprop_move(BPy_PropertyRNA *self, PyObject *args)
3135 if (!PyArg_ParseTuple(args, "ii", &key, &pos)) {
3136 PyErr_SetString(PyExc_TypeError, "bpy_prop_collection.move(): expected two ints as arguments");
3140 if(!RNA_property_collection_move(&self->ptr, self->prop, key, pos)) {
3141 PyErr_SetString(PyExc_TypeError, "bpy_prop_collection.move() not supported for this collection");
3148 static PyObject *pyrna_struct_get_id_data(BPy_DummyPointerRNA *self)
3150 /* used for struct and pointer since both have a ptr */
3151 if(self->ptr.id.data) {
3153 RNA_id_pointer_create((ID *)self->ptr.id.data, &id_ptr);
3154 return pyrna_struct_CreatePyObject(&id_ptr);
3160 /*****************************************************************************/
3161 /* Python attributes get/set structure: */
3162 /*****************************************************************************/
3164 static PyGetSetDef pyrna_prop_getseters[] = {
3165 {(char *)"id_data", (getter)pyrna_struct_get_id_data, (setter)NULL, (char *)"The :class:`ID` object this datablock is from or None, (not available for all data types)", NULL},