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 *****
25 /** \file blender/python/intern/bpy_rna.c
26 * \ingroup pythonintern
33 #include <float.h> /* FLT_MIN/MAX */
35 #include "RNA_types.h"
38 #include "bpy_rna_anim.h"
39 #include "bpy_props.h"
41 #include "bpy_rna_callback.h"
42 #include "bpy_intern_string.h"
44 #ifdef USE_PYRNA_INVALIDATE_WEAKREF
45 #include "MEM_guardedalloc.h"
48 #include "BLI_dynstr.h"
49 #include "BLI_string.h"
50 #include "BLI_listbase.h"
51 #include "BLI_math_rotation.h"
52 #include "BLI_utildefines.h"
54 #ifdef USE_PYRNA_INVALIDATE_WEAKREF
55 #include "BLI_ghash.h"
58 #include "RNA_enum_types.h"
59 #include "RNA_define.h" /* RNA_def_property_free_identifier */
60 #include "RNA_access.h"
62 #include "MEM_guardedalloc.h"
64 #include "BKE_idcode.h"
65 #include "BKE_context.h"
66 #include "BKE_global.h" /* evil G.* */
67 #include "BKE_report.h"
68 #include "BKE_idprop.h"
70 #include "BKE_animsys.h"
71 #include "BKE_fcurve.h"
73 #include "../generic/IDProp.h" /* for IDprop lookups */
74 #include "../generic/py_capi_utils.h"
76 #define USE_PEDANTIC_WRITE
78 #define USE_STRING_COERCE
80 static PyObject* pyrna_struct_Subtype(PointerRNA *ptr);
81 static PyObject *pyrna_prop_collection_values(BPy_PropertyRNA *self);
83 int pyrna_struct_validity_check(BPy_StructRNA *pysrna)
87 PyErr_Format(PyExc_ReferenceError,
88 "StructRNA of type %.200s has been removed",
89 Py_TYPE(pysrna)->tp_name);
93 int pyrna_prop_validity_check(BPy_PropertyRNA *self)
97 PyErr_Format(PyExc_ReferenceError,
98 "PropertyRNA of type %.200s.%.200s has been removed",
99 Py_TYPE(self)->tp_name, RNA_property_identifier(self->prop));
103 #if defined(USE_PYRNA_INVALIDATE_GC) || defined(USE_PYRNA_INVALIDATE_WEAKREF)
104 static void pyrna_invalidate(BPy_DummyPointerRNA *self)
106 self->ptr.type= NULL; /* this is checked for validity */
107 self->ptr.id.data= NULL; /* should not be needed but prevent bad pointer access, just incase */
111 #ifdef USE_PYRNA_INVALIDATE_GC
112 #define FROM_GC(g) ((PyObject *)(((PyGC_Head *)g)+1))
114 /* only for sizeof() */
115 struct gc_generation {
121 static void id_release_gc(struct ID *id)
124 // unsigned int i= 0;
126 /* hack below to get the 2 other lists from _PyGC_generation0 that are normally not exposed */
127 PyGC_Head *gen= (PyGC_Head *)(((char *)_PyGC_generation0) + (sizeof(gc_generation) * j));
128 PyGC_Head *g= gen->gc.gc_next;
129 while ((g= g->gc.gc_next) != gen) {
130 PyObject *ob= FROM_GC(g);
131 if(PyType_IsSubtype(Py_TYPE(ob), &pyrna_struct_Type) || PyType_IsSubtype(Py_TYPE(ob), &pyrna_prop_Type)) {
132 BPy_DummyPointerRNA *ob_ptr= (BPy_DummyPointerRNA *)ob;
133 if(ob_ptr->ptr.id.data == id) {
134 pyrna_invalidate(ob_ptr);
135 // printf("freeing: %p %s, %.200s\n", (void *)ob, id->name, Py_TYPE(ob)->tp_name);
141 // printf("id_release_gc freed '%s': %d\n", id->name, i);
145 #ifdef USE_PYRNA_INVALIDATE_WEAKREF
146 //#define DEBUG_RNA_WEAKREF
148 struct GHash *id_weakref_pool= NULL;
149 static PyObject *id_free_weakref_cb(PyObject *weakinfo_pair, PyObject *weakref);
150 static PyMethodDef id_free_weakref_cb_def= {"id_free_weakref_cb", (PyCFunction)id_free_weakref_cb, METH_O, NULL};
152 /* adds a reference to the list, remember to decref */
153 static GHash *id_weakref_pool_get(ID *id)
155 GHash *weakinfo_hash= NULL;
157 if(id_weakref_pool) {
158 weakinfo_hash= BLI_ghash_lookup(id_weakref_pool, (void *)id);
161 /* first time, allocate pool */
162 id_weakref_pool= BLI_ghash_new(BLI_ghashutil_ptrhash, BLI_ghashutil_ptrcmp, "rna_global_pool");
166 if(weakinfo_hash==NULL) {
167 /* we're using a ghash as a set, could use libHX's HXMAP_SINGULAR but would be an extra dep. */
168 weakinfo_hash= BLI_ghash_new(BLI_ghashutil_ptrhash, BLI_ghashutil_ptrcmp, "rna_id");
169 BLI_ghash_insert(id_weakref_pool, (void *)id, weakinfo_hash);
172 return weakinfo_hash;
175 /* called from pyrna_struct_CreatePyObject() and pyrna_prop_CreatePyObject() */
176 void id_weakref_pool_add(ID *id, BPy_DummyPointerRNA *pyrna)
179 PyObject *weakref_capsule;
180 PyObject *weakref_cb_py;
182 /* create a new function instance and insert the list as 'self' so we can remove ourself from it */
183 GHash *weakinfo_hash= id_weakref_pool_get(id); /* new or existing */
185 weakref_capsule= PyCapsule_New(weakinfo_hash, NULL, NULL);
186 weakref_cb_py= PyCFunction_New(&id_free_weakref_cb_def, weakref_capsule);
187 Py_DECREF(weakref_capsule);
189 /* add weakref to weakinfo_hash list */
190 weakref= PyWeakref_NewRef((PyObject *)pyrna, weakref_cb_py);
192 Py_DECREF(weakref_cb_py); /* function owned by the weakref now */
194 /* important to add at the end, since first removal looks at the end */
195 BLI_ghash_insert(weakinfo_hash, (void *)weakref, id); /* using a hash table as a set, all 'id's are the same */
196 /* weakinfo_hash owns the weakref */
200 /* workaround to get the last id without a lookup */
201 static ID *_id_tmp_ptr;
202 static void value_id_set(void *id)
204 _id_tmp_ptr= (ID *)id;
207 static void id_release_weakref_list(struct ID *id, GHash *weakinfo_hash);
208 static PyObject *id_free_weakref_cb(PyObject *weakinfo_capsule, PyObject *weakref)
210 /* important to search backwards */
211 GHash *weakinfo_hash= PyCapsule_GetPointer(weakinfo_capsule, NULL);
214 if(BLI_ghash_size(weakinfo_hash) > 1) {
215 BLI_ghash_remove(weakinfo_hash, weakref, NULL, NULL);
217 else { /* get the last id and free it */
218 BLI_ghash_remove(weakinfo_hash, weakref, NULL, value_id_set);
219 id_release_weakref_list(_id_tmp_ptr, weakinfo_hash);
227 static void id_release_weakref_list(struct ID *id, GHash *weakinfo_hash)
229 GHashIterator weakinfo_hash_iter;
231 BLI_ghashIterator_init(&weakinfo_hash_iter, weakinfo_hash);
233 #ifdef DEBUG_RNA_WEAKREF
234 fprintf(stdout, "id_release_weakref: '%s', %d items\n", id->name, BLI_ghash_size(weakinfo_hash));
237 while (!BLI_ghashIterator_isDone(&weakinfo_hash_iter)) {
238 PyObject *weakref= (PyObject *)BLI_ghashIterator_getKey(&weakinfo_hash_iter);
239 PyObject *item= PyWeakref_GET_OBJECT(weakref);
240 if(item != Py_None) {
242 #ifdef DEBUG_RNA_WEAKREF
243 PyC_ObSpit("id_release_weakref item ", item);
246 pyrna_invalidate((BPy_DummyPointerRNA *)item);
251 BLI_ghashIterator_step(&weakinfo_hash_iter);
254 BLI_ghash_remove(id_weakref_pool, (void *)id, NULL, NULL);
255 BLI_ghash_free(weakinfo_hash, NULL, NULL);
257 if(BLI_ghash_size(id_weakref_pool) == 0) {
258 BLI_ghash_free(id_weakref_pool, NULL, NULL);
259 id_weakref_pool= NULL;
260 #ifdef DEBUG_RNA_WEAKREF
261 printf("id_release_weakref freeing pool\n");
266 static void id_release_weakref(struct ID *id)
268 GHash *weakinfo_hash= BLI_ghash_lookup(id_weakref_pool, (void *)id);
270 id_release_weakref_list(id, weakinfo_hash);
274 #endif /* USE_PYRNA_INVALIDATE_WEAKREF */
276 void BPY_id_release(struct ID *id)
278 #ifdef USE_PYRNA_INVALIDATE_GC
282 #ifdef USE_PYRNA_INVALIDATE_WEAKREF
283 if(id_weakref_pool) {
284 PyGILState_STATE gilstate= PyGILState_Ensure();
286 id_release_weakref(id);
288 PyGILState_Release(gilstate);
290 #endif /* USE_PYRNA_INVALIDATE_WEAKREF */
295 #ifdef USE_PEDANTIC_WRITE
296 static short rna_disallow_writes= FALSE;
298 static int rna_id_write_error(PointerRNA *ptr, PyObject *key)
300 ID *id= ptr->id.data;
302 const short idcode= GS(id->name);
303 if(!ELEM(idcode, ID_WM, ID_SCR)) { /* may need more added here */
304 const char *idtype= BKE_idcode_to_name(idcode);
306 if(key && PyUnicode_Check(key)) pyname= _PyUnicode_AsString(key);
307 else pyname= "<UNKNOWN>";
309 /* make a nice string error */
310 BLI_assert(idtype != NULL);
311 PyErr_Format(PyExc_AttributeError,
312 "Writing to ID classes in this context is not allowed: "
313 "%.200s, %.200s datablock, error setting %.200s.%.200s",
314 id->name+2, idtype, RNA_struct_identifier(ptr->type), pyname);
321 #endif // USE_PEDANTIC_WRITE
324 #ifdef USE_PEDANTIC_WRITE
325 int pyrna_write_check(void)
327 return !rna_disallow_writes;
330 void pyrna_write_set(int val)
332 rna_disallow_writes= !val;
334 #else // USE_PEDANTIC_WRITE
335 int pyrna_write_check(void)
339 void pyrna_write_set(int UNUSED(val))
343 #endif // USE_PEDANTIC_WRITE
345 static Py_ssize_t pyrna_prop_collection_length(BPy_PropertyRNA *self);
346 static Py_ssize_t pyrna_prop_array_length(BPy_PropertyArrayRNA *self);
347 static int pyrna_py_to_prop(PointerRNA *ptr, PropertyRNA *prop, void *data, PyObject *value, const char *error_prefix);
348 static int deferred_register_prop(StructRNA *srna, PyObject *key, PyObject *item);
351 #include "../mathutils/mathutils.h" /* so we can have mathutils callbacks */
353 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);
354 static short pyrna_rotation_euler_order_get(PointerRNA *ptr, PropertyRNA **prop_eul_order, short order_fallback);
356 /* bpyrna vector/euler/quat callbacks */
357 static int mathutils_rna_array_cb_index= -1; /* index for our callbacks */
359 /* subtype not used much yet */
360 #define MATHUTILS_CB_SUBTYPE_EUL 0
361 #define MATHUTILS_CB_SUBTYPE_VEC 1
362 #define MATHUTILS_CB_SUBTYPE_QUAT 2
363 #define MATHUTILS_CB_SUBTYPE_COLOR 3
365 static int mathutils_rna_generic_check(BaseMathObject *bmo)
367 BPy_PropertyRNA *self= (BPy_PropertyRNA *)bmo->cb_user;
369 PYRNA_PROP_CHECK_INT(self)
371 return self->prop ? 0 : -1;
374 static int mathutils_rna_vector_get(BaseMathObject *bmo, int subtype)
376 BPy_PropertyRNA *self= (BPy_PropertyRNA *)bmo->cb_user;
378 PYRNA_PROP_CHECK_INT(self)
383 RNA_property_float_get_array(&self->ptr, self->prop, bmo->data);
385 /* Euler order exception */
386 if(subtype==MATHUTILS_CB_SUBTYPE_EUL) {
387 EulerObject *eul= (EulerObject *)bmo;
388 PropertyRNA *prop_eul_order= NULL;
389 eul->order= pyrna_rotation_euler_order_get(&self->ptr, &prop_eul_order, eul->order);
395 static int mathutils_rna_vector_set(BaseMathObject *bmo, int subtype)
397 BPy_PropertyRNA *self= (BPy_PropertyRNA *)bmo->cb_user;
400 PYRNA_PROP_CHECK_INT(self)
405 #ifdef USE_PEDANTIC_WRITE
406 if(rna_disallow_writes && rna_id_write_error(&self->ptr, NULL)) {
409 #endif // USE_PEDANTIC_WRITE
411 if (!RNA_property_editable_flag(&self->ptr, self->prop)) {
412 PyErr_Format(PyExc_AttributeError,
413 "bpy_prop \"%.200s.%.200s\" is read-only",
414 RNA_struct_identifier(self->ptr.type), RNA_property_identifier(self->prop));
418 RNA_property_float_range(&self->ptr, self->prop, &min, &max);
420 if(min != FLT_MIN || max != FLT_MAX) {
421 int i, len= RNA_property_array_length(&self->ptr, self->prop);
422 for(i=0; i<len; i++) {
423 CLAMP(bmo->data[i], min, max);
427 RNA_property_float_set_array(&self->ptr, self->prop, bmo->data);
428 if(RNA_property_update_check(self->prop)) {
429 RNA_property_update(BPy_GetContext(), &self->ptr, self->prop);
432 /* Euler order exception */
433 if(subtype==MATHUTILS_CB_SUBTYPE_EUL) {
434 EulerObject *eul= (EulerObject *)bmo;
435 PropertyRNA *prop_eul_order= NULL;
436 short order= pyrna_rotation_euler_order_get(&self->ptr, &prop_eul_order, eul->order);
437 if(order != eul->order) {
438 RNA_property_enum_set(&self->ptr, prop_eul_order, eul->order);
439 if(RNA_property_update_check(prop_eul_order)) {
440 RNA_property_update(BPy_GetContext(), &self->ptr, prop_eul_order);
447 static int mathutils_rna_vector_get_index(BaseMathObject *bmo, int UNUSED(subtype), int index)
449 BPy_PropertyRNA *self= (BPy_PropertyRNA *)bmo->cb_user;
451 PYRNA_PROP_CHECK_INT(self)
456 bmo->data[index]= RNA_property_float_get_index(&self->ptr, self->prop, index);
460 static int mathutils_rna_vector_set_index(BaseMathObject *bmo, int UNUSED(subtype), int index)
462 BPy_PropertyRNA *self= (BPy_PropertyRNA *)bmo->cb_user;
464 PYRNA_PROP_CHECK_INT(self)
469 #ifdef USE_PEDANTIC_WRITE
470 if(rna_disallow_writes && rna_id_write_error(&self->ptr, NULL)) {
473 #endif // USE_PEDANTIC_WRITE
475 if (!RNA_property_editable_flag(&self->ptr, self->prop)) {
476 PyErr_Format(PyExc_AttributeError,
477 "bpy_prop \"%.200s.%.200s\" is read-only",
478 RNA_struct_identifier(self->ptr.type), RNA_property_identifier(self->prop));
482 RNA_property_float_clamp(&self->ptr, self->prop, &bmo->data[index]);
483 RNA_property_float_set_index(&self->ptr, self->prop, index, bmo->data[index]);
485 if(RNA_property_update_check(self->prop)) {
486 RNA_property_update(BPy_GetContext(), &self->ptr, self->prop);
492 static Mathutils_Callback mathutils_rna_array_cb= {
493 (BaseMathCheckFunc) mathutils_rna_generic_check,
494 (BaseMathGetFunc) mathutils_rna_vector_get,
495 (BaseMathSetFunc) mathutils_rna_vector_set,
496 (BaseMathGetIndexFunc) mathutils_rna_vector_get_index,
497 (BaseMathSetIndexFunc) mathutils_rna_vector_set_index
501 /* bpyrna matrix callbacks */
502 static int mathutils_rna_matrix_cb_index= -1; /* index for our callbacks */
504 static int mathutils_rna_matrix_get(BaseMathObject *bmo, int UNUSED(subtype))
506 BPy_PropertyRNA *self= (BPy_PropertyRNA *)bmo->cb_user;
508 PYRNA_PROP_CHECK_INT(self)
513 RNA_property_float_get_array(&self->ptr, self->prop, bmo->data);
517 static int mathutils_rna_matrix_set(BaseMathObject *bmo, int UNUSED(subtype))
519 BPy_PropertyRNA *self= (BPy_PropertyRNA *)bmo->cb_user;
521 PYRNA_PROP_CHECK_INT(self)
526 #ifdef USE_PEDANTIC_WRITE
527 if(rna_disallow_writes && rna_id_write_error(&self->ptr, NULL)) {
530 #endif // USE_PEDANTIC_WRITE
532 if (!RNA_property_editable_flag(&self->ptr, self->prop)) {
533 PyErr_Format(PyExc_AttributeError,
534 "bpy_prop \"%.200s.%.200s\" is read-only",
535 RNA_struct_identifier(self->ptr.type), RNA_property_identifier(self->prop));
539 /* can ignore clamping here */
540 RNA_property_float_set_array(&self->ptr, self->prop, bmo->data);
542 if(RNA_property_update_check(self->prop)) {
543 RNA_property_update(BPy_GetContext(), &self->ptr, self->prop);
548 static Mathutils_Callback mathutils_rna_matrix_cb= {
549 mathutils_rna_generic_check,
550 mathutils_rna_matrix_get,
551 mathutils_rna_matrix_set,
556 static short pyrna_rotation_euler_order_get(PointerRNA *ptr, PropertyRNA **prop_eul_order, short order_fallback)
558 /* attempt to get order */
559 if(*prop_eul_order==NULL)
560 *prop_eul_order= RNA_struct_find_property(ptr, "rotation_mode");
562 if(*prop_eul_order) {
563 short order= RNA_property_enum_get(ptr, *prop_eul_order);
564 if (order >= EULER_ORDER_XYZ && order <= EULER_ORDER_ZYX) /* could be quat or axisangle */
568 return order_fallback;
571 #endif // USE_MATHUTILS
573 /* note that PROP_NONE is included as a vector subtype. this is because its handy to
574 * have x/y access to fcurve keyframes and other fixed size float arrays of length 2-4. */
575 #define PROP_ALL_VECTOR_SUBTYPES PROP_COORDS: case PROP_TRANSLATION: case PROP_DIRECTION: case PROP_VELOCITY: case PROP_ACCELERATION: case PROP_XYZ: case PROP_XYZ_LENGTH
577 PyObject *pyrna_math_object_from_array(PointerRNA *ptr, PropertyRNA *prop)
585 int flag= RNA_property_flag(prop);
587 /* disallow dynamic sized arrays to be wrapped since the size could change
588 * to a size mathutils does not support */
589 if ((RNA_property_type(prop) != PROP_FLOAT) || (flag & PROP_DYNAMIC))
592 len= RNA_property_array_length(ptr, prop);
593 subtype= RNA_property_subtype(prop);
594 totdim= RNA_property_array_dimension(ptr, prop, NULL);
595 is_thick= (flag & PROP_THICK_WRAP);
597 if (totdim == 1 || (totdim == 2 && subtype == PROP_MATRIX)) {
599 ret= pyrna_prop_CreatePyObject(ptr, prop); /* owned by the mathutils PyObject */
601 switch(RNA_property_subtype(prop)) {
602 case PROP_ALL_VECTOR_SUBTYPES:
603 if(len>=2 && len <= 4) {
605 ret= newVectorObject(NULL, len, Py_NEW, NULL);
606 RNA_property_float_get_array(ptr, prop, ((VectorObject *)ret)->vec);
609 PyObject *vec_cb= newVectorObject_cb(ret, len, mathutils_rna_array_cb_index, MATHUTILS_CB_SUBTYPE_VEC);
610 Py_DECREF(ret); /* the vector owns now */
611 ret= vec_cb; /* return the vector instead */
618 ret= newMatrixObject(NULL, 4, 4, Py_NEW, NULL);
619 RNA_property_float_get_array(ptr, prop, ((MatrixObject *)ret)->contigPtr);
622 PyObject *mat_cb= newMatrixObject_cb(ret, 4,4, mathutils_rna_matrix_cb_index, FALSE);
623 Py_DECREF(ret); /* the matrix owns now */
624 ret= mat_cb; /* return the matrix instead */
629 ret= newMatrixObject(NULL, 3, 3, Py_NEW, NULL);
630 RNA_property_float_get_array(ptr, prop, ((MatrixObject *)ret)->contigPtr);
633 PyObject *mat_cb= newMatrixObject_cb(ret, 3,3, mathutils_rna_matrix_cb_index, FALSE);
634 Py_DECREF(ret); /* the matrix owns now */
635 ret= mat_cb; /* return the matrix instead */
640 case PROP_QUATERNION:
641 if(len==3) { /* euler */
643 /* attempt to get order, only needed for thick types since wrapped with update via callbacks */
644 PropertyRNA *prop_eul_order= NULL;
645 short order= pyrna_rotation_euler_order_get(ptr, &prop_eul_order, EULER_ORDER_XYZ);
647 ret= newEulerObject(NULL, order, Py_NEW, NULL); // TODO, get order from RNA
648 RNA_property_float_get_array(ptr, prop, ((EulerObject *)ret)->eul);
651 /* order will be updated from callback on use */
652 PyObject *eul_cb= newEulerObject_cb(ret, EULER_ORDER_XYZ, mathutils_rna_array_cb_index, MATHUTILS_CB_SUBTYPE_EUL); // TODO, get order from RNA
653 Py_DECREF(ret); /* the euler owns now */
654 ret= eul_cb; /* return the euler instead */
659 ret= newQuaternionObject(NULL, Py_NEW, NULL);
660 RNA_property_float_get_array(ptr, prop, ((QuaternionObject *)ret)->quat);
663 PyObject *quat_cb= newQuaternionObject_cb(ret, mathutils_rna_array_cb_index, MATHUTILS_CB_SUBTYPE_QUAT);
664 Py_DECREF(ret); /* the quat owns now */
665 ret= quat_cb; /* return the quat instead */
670 case PROP_COLOR_GAMMA:
671 if(len==3) { /* color */
673 ret= newColorObject(NULL, Py_NEW, NULL); // TODO, get order from RNA
674 RNA_property_float_get_array(ptr, prop, ((ColorObject *)ret)->col);
677 PyObject *col_cb= newColorObject_cb(ret, mathutils_rna_array_cb_index, MATHUTILS_CB_SUBTYPE_COLOR);
678 Py_DECREF(ret); /* the color owns now */
679 ret= col_cb; /* return the color instead */
689 /* this is an array we cant reference (since its not thin wrappable)
690 * and cannot be coerced into a mathutils type, so return as a list */
691 ret= pyrna_prop_array_subscript_slice(NULL, ptr, prop, 0, len, len);
694 ret= pyrna_prop_CreatePyObject(ptr, prop); /* owned by the mathutils PyObject */
697 #else // USE_MATHUTILS
700 #endif // USE_MATHUTILS
705 /* same as RNA_enum_value_from_id but raises an exception */
706 int pyrna_enum_value_from_id(EnumPropertyItem *item, const char *identifier, int *value, const char *error_prefix)
708 if(RNA_enum_value_from_id(item, identifier, value) == 0) {
709 const char *enum_str= BPy_enum_as_string(item);
710 PyErr_Format(PyExc_TypeError,
711 "%s: '%.200s' not found in (%s)",
712 error_prefix, identifier, enum_str);
713 MEM_freeN((void *)enum_str);
720 static int pyrna_struct_compare(BPy_StructRNA *a, BPy_StructRNA *b)
722 return (a->ptr.data==b->ptr.data) ? 0 : -1;
725 static int pyrna_prop_compare(BPy_PropertyRNA *a, BPy_PropertyRNA *b)
727 return (a->prop==b->prop && a->ptr.data==b->ptr.data) ? 0 : -1;
730 static PyObject *pyrna_struct_richcmp(PyObject *a, PyObject *b, int op)
733 int ok= -1; /* zero is true */
735 if (BPy_StructRNA_Check(a) && BPy_StructRNA_Check(b))
736 ok= pyrna_struct_compare((BPy_StructRNA *)a, (BPy_StructRNA *)b);
740 ok= !ok; /* pass through */
742 res= ok ? Py_False : Py_True;
749 res= Py_NotImplemented;
756 return Py_INCREF(res), res;
759 static PyObject *pyrna_prop_richcmp(PyObject *a, PyObject *b, int op)
762 int ok= -1; /* zero is true */
764 if (BPy_PropertyRNA_Check(a) && BPy_PropertyRNA_Check(b))
765 ok= pyrna_prop_compare((BPy_PropertyRNA *)a, (BPy_PropertyRNA *)b);
769 ok= !ok; /* pass through */
771 res= ok ? Py_False : Py_True;
778 res= Py_NotImplemented;
785 return Py_INCREF(res), res;
788 /*----------------------repr--------------------------------------------*/
789 static PyObject *pyrna_struct_str(BPy_StructRNA *self)
794 if(!PYRNA_STRUCT_IS_VALID(self)) {
795 return PyUnicode_FromFormat("<bpy_struct, %.200s dead>",
796 Py_TYPE(self)->tp_name);
799 /* print name if available */
800 name= RNA_struct_name_get_alloc(&self->ptr, NULL, FALSE);
802 ret= PyUnicode_FromFormat("<bpy_struct, %.200s(\"%.200s\")>",
803 RNA_struct_identifier(self->ptr.type),
805 MEM_freeN((void *)name);
809 return PyUnicode_FromFormat("<bpy_struct, %.200s at %p>",
810 RNA_struct_identifier(self->ptr.type),
814 static PyObject *pyrna_struct_repr(BPy_StructRNA *self)
816 ID *id= self->ptr.id.data;
820 if(id == NULL || !PYRNA_STRUCT_IS_VALID(self))
821 return pyrna_struct_str(self); /* fallback */
823 tmp_str= PyUnicode_FromString(id->name+2);
825 if(RNA_struct_is_ID(self->ptr.type)) {
826 ret= PyUnicode_FromFormat("bpy.data.%s[%R]",
827 BKE_idcode_to_name_plural(GS(id->name)),
832 path= RNA_path_from_ID_to_struct(&self->ptr);
834 ret= PyUnicode_FromFormat("bpy.data.%s[%R].%s",
835 BKE_idcode_to_name_plural(GS(id->name)),
838 MEM_freeN((void *)path);
840 else { /* cant find, print something sane */
841 ret= PyUnicode_FromFormat("bpy.data.%s[%R]...%s",
842 BKE_idcode_to_name_plural(GS(id->name)),
844 RNA_struct_identifier(self->ptr.type));
853 static PyObject *pyrna_prop_str(BPy_PropertyRNA *self)
858 const char *type_id= NULL;
859 char type_fmt[64]= "";
862 PYRNA_PROP_CHECK_OBJ(self)
864 type= RNA_property_type(self->prop);
866 if(RNA_enum_id_from_value(property_type_items, type, &type_id)==0) {
867 PyErr_SetString(PyExc_RuntimeError, "could not use property type, internal error"); /* should never happen */
871 /* this should never fail */
875 while ((*c++= tolower(*type_id++))) {} ;
877 if(type==PROP_COLLECTION) {
878 len= pyrna_prop_collection_length(self);
880 else if (RNA_property_array_check(self->prop)) {
881 len= pyrna_prop_array_length((BPy_PropertyArrayRNA *)self);
885 sprintf(--c, "[%d]", len);
888 /* if a pointer, try to print name of pointer target too */
889 if(RNA_property_type(self->prop) == PROP_POINTER) {
890 ptr= RNA_property_pointer_get(&self->ptr, self->prop);
891 name= RNA_struct_name_get_alloc(&ptr, NULL, FALSE);
894 ret= PyUnicode_FromFormat("<bpy_%.200s, %.200s.%.200s(\"%.200s\")>",
896 RNA_struct_identifier(self->ptr.type),
897 RNA_property_identifier(self->prop),
899 MEM_freeN((void *)name);
903 if(RNA_property_type(self->prop) == PROP_COLLECTION) {
905 if(RNA_property_collection_type_get(&self->ptr, self->prop, &r_ptr)) {
906 return PyUnicode_FromFormat("<bpy_%.200s, %.200s>",
908 RNA_struct_identifier(r_ptr.type));
912 return PyUnicode_FromFormat("<bpy_%.200s, %.200s.%.200s>",
914 RNA_struct_identifier(self->ptr.type),
915 RNA_property_identifier(self->prop));
918 static PyObject *pyrna_prop_repr(BPy_PropertyRNA *self)
920 ID *id= self->ptr.id.data;
925 PYRNA_PROP_CHECK_OBJ(self)
928 return pyrna_prop_str(self); /* fallback */
930 tmp_str= PyUnicode_FromString(id->name+2);
932 path= RNA_path_from_ID_to_property(&self->ptr, self->prop);
934 ret= PyUnicode_FromFormat("bpy.data.%s[%R].%s",
935 BKE_idcode_to_name_plural(GS(id->name)),
938 MEM_freeN((void *)path);
940 else { /* cant find, print something sane */
941 ret= PyUnicode_FromFormat("bpy.data.%s[%R]...%s",
942 BKE_idcode_to_name_plural(GS(id->name)),
944 RNA_property_identifier(self->prop));
953 static PyObject *pyrna_func_repr(BPy_FunctionRNA *self)
955 return PyUnicode_FromFormat("<%.200s %.200s.%.200s()>",
956 Py_TYPE(self)->tp_name,
957 RNA_struct_identifier(self->ptr.type),
958 RNA_function_identifier(self->func));
962 static long pyrna_struct_hash(BPy_StructRNA *self)
964 return _Py_HashPointer(self->ptr.data);
967 /* from python's meth_hash v3.1.2 */
968 static long pyrna_prop_hash(BPy_PropertyRNA *self)
971 if (self->ptr.data == NULL)
974 x= _Py_HashPointer(self->ptr.data);
978 y= _Py_HashPointer((void*)(self->prop));
987 #ifdef USE_PYRNA_STRUCT_REFERENCE
988 static int pyrna_struct_traverse(BPy_StructRNA *self, visitproc visit, void *arg)
990 Py_VISIT(self->reference);
994 static int pyrna_struct_clear(BPy_StructRNA *self)
996 Py_CLEAR(self->reference);
999 #endif /* !USE_PYRNA_STRUCT_REFERENCE */
1001 /* use our own dealloc so we can free a property if we use one */
1002 static void pyrna_struct_dealloc(BPy_StructRNA *self)
1004 #ifdef PYRNA_FREE_SUPPORT
1005 if (self->freeptr && self->ptr.data) {
1006 IDP_FreeProperty(self->ptr.data);
1007 MEM_freeN(self->ptr.data);
1008 self->ptr.data= NULL;
1010 #endif /* PYRNA_FREE_SUPPORT */
1013 if (self->in_weakreflist != NULL) {
1014 PyObject_ClearWeakRefs((PyObject *)self);
1018 #ifdef USE_PYRNA_STRUCT_REFERENCE
1019 if(self->reference) {
1020 PyObject_GC_UnTrack(self);
1021 pyrna_struct_clear(self);
1023 #endif /* !USE_PYRNA_STRUCT_REFERENCE */
1025 /* Note, for subclassed PyObjects we cant just call PyObject_DEL() directly or it will crash */
1026 Py_TYPE(self)->tp_free(self);
1029 #ifdef USE_PYRNA_STRUCT_REFERENCE
1030 static void pyrna_struct_reference_set(BPy_StructRNA *self, PyObject *reference)
1032 if(self->reference) {
1033 // PyObject_GC_UnTrack(self); /* INITIALIZED TRACKED? */
1034 pyrna_struct_clear(self);
1036 /* reference is now NULL */
1039 self->reference= reference;
1040 Py_INCREF(reference);
1041 // PyObject_GC_Track(self); /* INITIALIZED TRACKED? */
1044 #endif /* !USE_PYRNA_STRUCT_REFERENCE */
1046 /* use our own dealloc so we can free a property if we use one */
1047 static void pyrna_prop_dealloc(BPy_PropertyRNA *self)
1050 if (self->in_weakreflist != NULL) {
1051 PyObject_ClearWeakRefs((PyObject *)self);
1054 /* Note, for subclassed PyObjects we cant just call PyObject_DEL() directly or it will crash */
1055 Py_TYPE(self)->tp_free(self);
1058 static void pyrna_prop_array_dealloc(BPy_PropertyRNA *self)
1061 if (self->in_weakreflist != NULL) {
1062 PyObject_ClearWeakRefs((PyObject *)self);
1065 /* Note, for subclassed PyObjects we cant just call PyObject_DEL() directly or it will crash */
1066 Py_TYPE(self)->tp_free(self);
1069 static const char *pyrna_enum_as_string(PointerRNA *ptr, PropertyRNA *prop)
1071 EnumPropertyItem *item;
1075 RNA_property_enum_items(BPy_GetContext(), ptr, prop, &item, NULL, &free);
1077 result= BPy_enum_as_string(item);
1090 static int pyrna_string_to_enum(PyObject *item, PointerRNA *ptr, PropertyRNA *prop, int *val, const char *error_prefix)
1092 const char *param= _PyUnicode_AsString(item);
1095 const char *enum_str= pyrna_enum_as_string(ptr, prop);
1096 PyErr_Format(PyExc_TypeError,
1097 "%.200s expected a string enum type in (%.200s)",
1098 error_prefix, enum_str);
1099 MEM_freeN((void *)enum_str);
1103 /* hack so that dynamic enums used for operator properties will be able to be built (i.e. context will be supplied to itemf)
1104 * and thus running defining operator buttons for such operators in UI will work */
1105 RNA_def_property_clear_flag(prop, PROP_ENUM_NO_CONTEXT);
1107 if (!RNA_property_enum_value(BPy_GetContext(), ptr, prop, param, val)) {
1108 const char *enum_str= pyrna_enum_as_string(ptr, prop);
1109 PyErr_Format(PyExc_TypeError,
1110 "%.200s enum \"%.200s\" not found in (%.200s)",
1111 error_prefix, param, enum_str);
1112 MEM_freeN((void *)enum_str);
1120 /* 'value' _must_ be a set type, error check before calling */
1121 int pyrna_set_to_enum_bitfield(EnumPropertyItem *items, PyObject *value, int *r_value, const char *error_prefix)
1123 /* set of enum items, concatenate all values with OR */
1133 while (_PySet_NextEntry(value, &pos, &key, &hash)) {
1134 const char *param= _PyUnicode_AsString(key);
1137 PyErr_Format(PyExc_TypeError,
1138 "%.200s expected a string, not %.200s",
1139 error_prefix, Py_TYPE(key)->tp_name);
1143 if(pyrna_enum_value_from_id(items, param, &ret, error_prefix) < 0) {
1154 static int pyrna_prop_to_enum_bitfield(PointerRNA *ptr, PropertyRNA *prop, PyObject *value, int *r_value, const char *error_prefix)
1156 EnumPropertyItem *item;
1162 if (!PyAnySet_Check(value)) {
1163 PyErr_Format(PyExc_TypeError,
1164 "%.200s, %.200s.%.200s expected a set, not a %.200s",
1165 error_prefix, RNA_struct_identifier(ptr->type),
1166 RNA_property_identifier(prop), Py_TYPE(value)->tp_name);
1170 RNA_property_enum_items(BPy_GetContext(), ptr, prop, &item, NULL, &free);
1173 ret= pyrna_set_to_enum_bitfield(item, value, r_value, error_prefix);
1176 if(PySet_GET_SIZE(value)) {
1177 PyErr_Format(PyExc_TypeError,
1178 "%.200s: empty enum \"%.200s\" could not have any values assigned",
1179 error_prefix, RNA_property_identifier(prop));
1193 PyObject *pyrna_enum_bitfield_to_py(EnumPropertyItem *items, int value)
1195 PyObject *ret= PySet_New(NULL);
1196 const char *identifier[RNA_ENUM_BITFLAG_SIZE + 1];
1198 if(RNA_enum_bitflag_identifiers(items, value, identifier)) {
1201 for(index=0; identifier[index]; index++) {
1202 item= PyUnicode_FromString(identifier[index]);
1203 PySet_Add(ret, item);
1211 static PyObject *pyrna_enum_to_py(PointerRNA *ptr, PropertyRNA *prop, int val)
1213 PyObject *item, *ret= NULL;
1215 if(RNA_property_flag(prop) & PROP_ENUM_FLAG) {
1216 const char *identifier[RNA_ENUM_BITFLAG_SIZE + 1];
1218 ret= PySet_New(NULL);
1220 if (RNA_property_enum_bitflag_identifiers(BPy_GetContext(), ptr, prop, val, identifier)) {
1223 for(index=0; identifier[index]; index++) {
1224 item= PyUnicode_FromString(identifier[index]);
1225 PySet_Add(ret, item);
1232 const char *identifier;
1233 if (RNA_property_enum_identifier(BPy_GetContext(), ptr, prop, val, &identifier)) {
1234 ret= PyUnicode_FromString(identifier);
1237 EnumPropertyItem *enum_item;
1240 /* don't throw error here, can't trust blender 100% to give the
1241 * right values, python code should not generate error for that */
1242 RNA_property_enum_items(BPy_GetContext(), ptr, prop, &enum_item, NULL, &free);
1243 if(enum_item && enum_item->identifier) {
1244 ret= PyUnicode_FromString(enum_item->identifier);
1247 const char *ptr_name= RNA_struct_name_get_alloc(ptr, NULL, FALSE);
1249 /* prefer not fail silently incase of api errors, maybe disable it later */
1250 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));
1252 #if 0 // gives python decoding errors while generating docs :(
1253 char error_str[256];
1254 BLI_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));
1255 PyErr_Warn(PyExc_RuntimeWarning, error_str);
1259 MEM_freeN((void *)ptr_name);
1261 ret= PyUnicode_FromString("");
1265 MEM_freeN(enum_item);
1267 PyErr_Format(PyExc_AttributeError,
1268 "RNA Error: Current value \"%d\" matches no enum", val);
1277 PyObject *pyrna_prop_to_py(PointerRNA *ptr, PropertyRNA *prop)
1280 int type= RNA_property_type(prop);
1282 if (RNA_property_array_check(prop)) {
1283 return pyrna_py_from_array(ptr, prop);
1286 /* see if we can coorce into a python type - PropertyType */
1289 ret= PyBool_FromLong(RNA_property_boolean_get(ptr, prop));
1292 ret= PyLong_FromSsize_t((Py_ssize_t)RNA_property_int_get(ptr, prop));
1295 ret= PyFloat_FromDouble(RNA_property_float_get(ptr, prop));
1299 int subtype= RNA_property_subtype(prop);
1303 buf= RNA_property_string_get_alloc(ptr, prop, buf_fixed, sizeof(buf_fixed));
1304 #ifdef USE_STRING_COERCE
1305 /* only file paths get special treatment, they may contain non utf-8 chars */
1306 if(ELEM3(subtype, PROP_FILEPATH, PROP_DIRPATH, PROP_FILENAME)) {
1307 ret= PyC_UnicodeFromByte(buf);
1310 ret= PyUnicode_FromString(buf);
1312 #else // USE_STRING_COERCE
1313 ret= PyUnicode_FromString(buf);
1314 #endif // USE_STRING_COERCE
1315 if(buf_fixed != buf) {
1316 MEM_freeN((void *)buf);
1322 ret= pyrna_enum_to_py(ptr, prop, RNA_property_enum_get(ptr, prop));
1328 newptr= RNA_property_pointer_get(ptr, prop);
1330 ret= pyrna_struct_CreatePyObject(&newptr);
1338 case PROP_COLLECTION:
1339 ret= pyrna_prop_CreatePyObject(ptr, prop);
1342 PyErr_Format(PyExc_TypeError,
1343 "bpy_struct internal error: unknown type '%d' (pyrna_prop_to_py)", type);
1351 /* This function is used by operators and converting dicts into collections.
1352 * Its takes keyword args and fills them with property values */
1353 int pyrna_pydict_to_props(PointerRNA *ptr, PyObject *kw, int all_args, const char *error_prefix)
1357 const char *arg_name= NULL;
1360 totkw= kw ? PyDict_Size(kw):0;
1362 RNA_STRUCT_BEGIN(ptr, prop) {
1363 arg_name= RNA_property_identifier(prop);
1365 if (strcmp(arg_name, "rna_type")==0) continue;
1368 PyErr_Format(PyExc_TypeError,
1369 "%.200s: no keywords, expected \"%.200s\"",
1370 error_prefix, arg_name ? arg_name : "<UNKNOWN>");
1375 item= PyDict_GetItemString(kw, arg_name); /* wont set an error */
1379 PyErr_Format(PyExc_TypeError,
1380 "%.200s: keyword \"%.200s\" missing",
1381 error_prefix, arg_name ? arg_name : "<UNKNOWN>");
1382 error_val= -1; /* pyrna_py_to_prop sets the error */
1387 if (pyrna_py_to_prop(ptr, prop, NULL, item, error_prefix)) {
1396 if (error_val==0 && totkw > 0) { /* some keywords were given that were not used :/ */
1397 PyObject *key, *value;
1400 while (PyDict_Next(kw, &pos, &key, &value)) {
1401 arg_name= _PyUnicode_AsString(key);
1402 if (RNA_struct_find_property(ptr, arg_name) == NULL) break;
1406 PyErr_Format(PyExc_TypeError,
1407 "%.200s: keyword \"%.200s\" unrecognized",
1408 error_prefix, arg_name ? arg_name : "<UNKNOWN>");
1416 static PyObject *pyrna_func_to_py(PointerRNA *ptr, FunctionRNA *func)
1418 BPy_FunctionRNA* pyfunc= (BPy_FunctionRNA *) PyObject_NEW(BPy_FunctionRNA, &pyrna_func_Type);
1421 return (PyObject *)pyfunc;
1425 static int pyrna_py_to_prop(PointerRNA *ptr, PropertyRNA *prop, void *data, PyObject *value, const char *error_prefix)
1427 /* XXX hard limits should be checked here */
1428 int type= RNA_property_type(prop);
1431 if (RNA_property_array_check(prop)) {
1432 /* done getting the length */
1433 if(pyrna_py_to_array(ptr, prop, data, value, error_prefix) == -1) {
1438 /* Normal Property (not an array) */
1440 /* see if we can coorce into a python type - PropertyType */
1445 /* prefer not to have an exception here
1446 * however so many poll functions return None or a valid Object.
1447 * its a hassle to convert these into a bool before returning, */
1448 if(RNA_property_flag(prop) & PROP_OUTPUT)
1449 param= PyObject_IsTrue(value);
1451 param= PyLong_AsLong(value);
1454 PyErr_Format(PyExc_TypeError,
1455 "%.200s %.200s.%.200s expected True/False or 0/1, not %.200s",
1456 error_prefix, RNA_struct_identifier(ptr->type),
1457 RNA_property_identifier(prop), Py_TYPE(value)->tp_name);
1461 if(data) *((int*)data)= param;
1462 else RNA_property_boolean_set(ptr, prop, param);
1469 long param= PyLong_AsLongAndOverflow(value, &overflow);
1470 if(overflow || (param > INT_MAX) || (param < INT_MIN)) {
1471 PyErr_Format(PyExc_ValueError,
1472 "%.200s %.200s.%.200s value not in 'int' range "
1473 "(" STRINGIFY(INT_MIN) ", " STRINGIFY(INT_MAX) ")",
1474 error_prefix, RNA_struct_identifier(ptr->type),
1475 RNA_property_identifier(prop));
1478 else if (param==-1 && PyErr_Occurred()) {
1479 PyErr_Format(PyExc_TypeError,
1480 "%.200s %.200s.%.200s expected an int type, not %.200s",
1481 error_prefix, RNA_struct_identifier(ptr->type),
1482 RNA_property_identifier(prop), Py_TYPE(value)->tp_name);
1486 int param_i= (int)param;
1487 RNA_property_int_clamp(ptr, prop, ¶m_i);
1488 if(data) *((int*)data)= param_i;
1489 else RNA_property_int_set(ptr, prop, param_i);
1495 float param= PyFloat_AsDouble(value);
1496 if (PyErr_Occurred()) {
1497 PyErr_Format(PyExc_TypeError,
1498 "%.200s %.200s.%.200s expected a float type, not %.200s",
1499 error_prefix, RNA_struct_identifier(ptr->type),
1500 RNA_property_identifier(prop), Py_TYPE(value)->tp_name);
1504 RNA_property_float_clamp(ptr, prop, (float *)¶m);
1505 if(data) *((float*)data)= param;
1506 else RNA_property_float_set(ptr, prop, param);
1513 #ifdef USE_STRING_COERCE
1514 PyObject *value_coerce= NULL;
1515 int subtype= RNA_property_subtype(prop);
1516 if(ELEM3(subtype, PROP_FILEPATH, PROP_DIRPATH, PROP_FILENAME)) {
1517 /* TODO, get size */
1518 param= PyC_UnicodeAsByte(value, &value_coerce);
1521 param= _PyUnicode_AsString(value);
1523 #else // USE_STRING_COERCE
1524 param= _PyUnicode_AsString(value);
1525 #endif // USE_STRING_COERCE
1528 PyErr_Format(PyExc_TypeError,
1529 "%.200s %.200s.%.200s expected a string type, not %.200s",
1530 error_prefix, RNA_struct_identifier(ptr->type),
1531 RNA_property_identifier(prop), Py_TYPE(value)->tp_name);
1535 if(data) *((char**)data)= (char *)param; /*XXX, this is suspect but needed for function calls, need to see if theres a better way */
1536 else RNA_property_string_set(ptr, prop, param);
1538 #ifdef USE_STRING_COERCE
1539 Py_XDECREF(value_coerce);
1540 #endif // USE_STRING_COERCE
1547 /* type checkins is done by each function */
1548 if(RNA_property_flag(prop) & PROP_ENUM_FLAG) {
1549 /* set of enum items, concatenate all values with OR */
1550 if(pyrna_prop_to_enum_bitfield(ptr, prop, value, &val, error_prefix) < 0) {
1555 /* simple enum string */
1556 if (!pyrna_string_to_enum(value, ptr, prop, &val, error_prefix) < 0) {
1561 if(data) *((int*)data)= val;
1562 else RNA_property_enum_set(ptr, prop, val);
1568 PyObject *value_new= NULL;
1570 StructRNA *ptr_type= RNA_property_pointer_type(ptr, prop);
1571 int flag= RNA_property_flag(prop);
1573 /* this is really nasty!, so we can fake the operator having direct properties eg:
1574 * layout.prop(self, "filepath")
1575 * ... which infact should be
1576 * layout.prop(self.properties, "filepath")
1578 * we need to do this trick.
1579 * if the prop is not an operator type and the pyobject is an operator, use its properties in place of its self.
1581 * this is so bad that its almost a good reason to do away with fake 'self.properties -> self' class mixing
1582 * if this causes problems in the future it should be removed.
1584 if( (ptr_type == &RNA_AnyType) &&
1585 (BPy_StructRNA_Check(value)) &&
1586 (RNA_struct_is_a(((BPy_StructRNA *)value)->ptr.type, &RNA_Operator))
1588 value= PyObject_GetAttrString(value, "properties");
1593 /* if property is an OperatorProperties pointer and value is a map, forward back to pyrna_pydict_to_props */
1594 if (RNA_struct_is_a(ptr_type, &RNA_OperatorProperties) && PyDict_Check(value)) {
1595 PointerRNA opptr= RNA_property_pointer_get(ptr, prop);
1596 return pyrna_pydict_to_props(&opptr, value, 0, error_prefix);
1599 /* another exception, allow to pass a collection as an RNA property */
1600 if(Py_TYPE(value)==&pyrna_prop_collection_Type) { /* ok to ignore idprop collections */
1602 BPy_PropertyRNA *value_prop= (BPy_PropertyRNA *)value;
1603 if(RNA_property_collection_type_get(&value_prop->ptr, value_prop->prop, &c_ptr)) {
1604 value= pyrna_struct_CreatePyObject(&c_ptr);
1608 PyErr_Format(PyExc_TypeError,
1609 "%.200s %.200s.%.200s collection has no type, "
1610 "cant be used as a %.200s type",
1611 error_prefix, RNA_struct_identifier(ptr->type),
1612 RNA_property_identifier(prop), RNA_struct_identifier(ptr_type));
1617 if(!BPy_StructRNA_Check(value) && value != Py_None) {
1618 PyErr_Format(PyExc_TypeError,
1619 "%.200s %.200s.%.200s expected a %.200s type, not %.200s",
1620 error_prefix, RNA_struct_identifier(ptr->type),
1621 RNA_property_identifier(prop), RNA_struct_identifier(ptr_type),
1622 Py_TYPE(value)->tp_name);
1623 Py_XDECREF(value_new); return -1;
1625 else if((flag & PROP_NEVER_NULL) && value == Py_None) {
1626 PyErr_Format(PyExc_TypeError,
1627 "%.200s %.200s.%.200s does not support a 'None' assignment %.200s type",
1628 error_prefix, RNA_struct_identifier(ptr->type),
1629 RNA_property_identifier(prop), RNA_struct_identifier(ptr_type));
1630 Py_XDECREF(value_new); return -1;
1632 else if(value != Py_None && ((flag & PROP_ID_SELF_CHECK) && ptr->id.data == ((BPy_StructRNA*)value)->ptr.id.data)) {
1633 PyErr_Format(PyExc_TypeError,
1634 "%.200s %.200s.%.200s ID type does not support assignment to its self",
1635 error_prefix, RNA_struct_identifier(ptr->type),
1636 RNA_property_identifier(prop));
1637 Py_XDECREF(value_new); return -1;
1640 BPy_StructRNA *param= (BPy_StructRNA*)value;
1641 int raise_error= FALSE;
1644 if(flag & PROP_RNAPTR) {
1645 if(value == Py_None)
1646 memset(data, 0, sizeof(PointerRNA));
1648 *((PointerRNA*)data)= param->ptr;
1650 else if(value == Py_None) {
1651 *((void**)data)= NULL;
1653 else if(RNA_struct_is_a(param->ptr.type, ptr_type)) {
1654 *((void**)data)= param->ptr.data;
1661 /* data==NULL, assign to RNA */
1662 if(value == Py_None) {
1663 PointerRNA valueptr= {{NULL}};
1664 RNA_property_pointer_set(ptr, prop, valueptr);
1666 else if(RNA_struct_is_a(param->ptr.type, ptr_type)) {
1667 RNA_property_pointer_set(ptr, prop, param->ptr);
1671 RNA_pointer_create(NULL, ptr_type, NULL, &tmp);
1672 PyErr_Format(PyExc_TypeError,
1673 "%.200s %.200s.%.200s expected a %.200s type. not %.200s",
1674 error_prefix, RNA_struct_identifier(ptr->type),
1675 RNA_property_identifier(prop), RNA_struct_identifier(tmp.type),
1676 RNA_struct_identifier(param->ptr.type));
1677 Py_XDECREF(value_new); return -1;
1683 RNA_pointer_create(NULL, ptr_type, NULL, &tmp);
1684 PyErr_Format(PyExc_TypeError,
1685 "%.200s %.200s.%.200s expected a %.200s type, not %.200s",
1686 error_prefix, RNA_struct_identifier(ptr->type),
1687 RNA_property_identifier(prop), RNA_struct_identifier(tmp.type),
1688 RNA_struct_identifier(param->ptr.type));
1689 Py_XDECREF(value_new); return -1;
1693 Py_XDECREF(value_new);
1697 case PROP_COLLECTION:
1703 CollectionPointerLink *link;
1705 lb= (data)? (ListBase*)data: NULL;
1707 /* convert a sequence of dict's into a collection */
1708 if(!PySequence_Check(value)) {
1709 PyErr_Format(PyExc_TypeError,
1710 "%.200s %.200s.%.200s expected a sequence for an RNA collection, not %.200s",
1711 error_prefix, RNA_struct_identifier(ptr->type),
1712 RNA_property_identifier(prop), Py_TYPE(value)->tp_name);
1716 seq_len= PySequence_Size(value);
1717 for(i=0; i<seq_len; i++) {
1718 item= PySequence_GetItem(value, i);
1721 PyErr_Format(PyExc_TypeError,
1722 "%.200s %.200s.%.200s failed to get sequence index '%d' for an RNA collection",
1723 error_prefix, RNA_struct_identifier(ptr->type),
1724 RNA_property_identifier(prop), i);
1729 if(PyDict_Check(item)==0) {
1730 PyErr_Format(PyExc_TypeError,
1731 "%.200s %.200s.%.200s expected a each sequence "
1732 "member to be a dict for an RNA collection, not %.200s",
1733 error_prefix, RNA_struct_identifier(ptr->type),
1734 RNA_property_identifier(prop), Py_TYPE(item)->tp_name);
1740 link= MEM_callocN(sizeof(CollectionPointerLink), "PyCollectionPointerLink");
1742 BLI_addtail(lb, link);
1745 RNA_property_collection_add(ptr, prop, &itemptr);
1747 if(pyrna_pydict_to_props(&itemptr, item, 1, "Converting a python list to an RNA collection")==-1) {
1748 PyObject *msg= PyC_ExceptionBuffer();
1749 const char *msg_char= _PyUnicode_AsString(msg);
1751 PyErr_Format(PyExc_TypeError,
1752 "%.200s %.200s.%.200s error converting a member of a collection "
1753 "from a dicts into an RNA collection, failed with: %s",
1754 error_prefix, RNA_struct_identifier(ptr->type),
1755 RNA_property_identifier(prop), msg_char);
1767 PyErr_Format(PyExc_AttributeError,
1768 "%.200s %.200s.%.200s unknown property type (pyrna_py_to_prop)",
1769 error_prefix, RNA_struct_identifier(ptr->type),
1770 RNA_property_identifier(prop));
1776 /* Run rna property functions */
1777 if(RNA_property_update_check(prop)) {
1778 RNA_property_update(BPy_GetContext(), ptr, prop);
1784 static PyObject *pyrna_prop_array_to_py_index(BPy_PropertyArrayRNA *self, int index)
1786 PYRNA_PROP_CHECK_OBJ((BPy_PropertyRNA *)self)
1787 return pyrna_py_from_array_index(self, &self->ptr, self->prop, index);
1790 static int pyrna_py_to_prop_array_index(BPy_PropertyArrayRNA *self, int index, PyObject *value)
1793 PointerRNA *ptr= &self->ptr;
1794 PropertyRNA *prop= self->prop;
1796 const int totdim= RNA_property_array_dimension(ptr, prop, NULL);
1799 /* char error_str[512]; */
1800 if (pyrna_py_to_array_index(&self->ptr, self->prop, self->arraydim, self->arrayoffset, index, value, "") == -1) {
1806 /* see if we can coerce into a python type - PropertyType */
1807 switch (RNA_property_type(prop)) {
1810 int param= PyLong_AsLong(value);
1812 if(param < 0 || param > 1) {
1813 PyErr_SetString(PyExc_TypeError, "expected True/False or 0/1");
1817 RNA_property_boolean_set_index(ptr, prop, index, param);
1823 int param= PyLong_AsLong(value);
1824 if (param==-1 && PyErr_Occurred()) {
1825 PyErr_SetString(PyExc_TypeError, "expected an int type");
1829 RNA_property_int_clamp(ptr, prop, ¶m);
1830 RNA_property_int_set_index(ptr, prop, index, param);
1836 float param= PyFloat_AsDouble(value);
1837 if (PyErr_Occurred()) {
1838 PyErr_SetString(PyExc_TypeError, "expected a float type");
1842 RNA_property_float_clamp(ptr, prop, ¶m);
1843 RNA_property_float_set_index(ptr, prop, index, param);
1848 PyErr_SetString(PyExc_AttributeError, "not an array type");
1854 /* Run rna property functions */
1855 if(RNA_property_update_check(prop)) {
1856 RNA_property_update(BPy_GetContext(), ptr, prop);
1862 //---------------sequence-------------------------------------------
1863 static Py_ssize_t pyrna_prop_array_length(BPy_PropertyArrayRNA *self)
1865 PYRNA_PROP_CHECK_INT((BPy_PropertyRNA *)self)
1867 if (RNA_property_array_dimension(&self->ptr, self->prop, NULL) > 1)
1868 return RNA_property_multi_array_length(&self->ptr, self->prop, self->arraydim);
1870 return RNA_property_array_length(&self->ptr, self->prop);
1873 static Py_ssize_t pyrna_prop_collection_length(BPy_PropertyRNA *self)
1875 PYRNA_PROP_CHECK_INT(self)
1877 return RNA_property_collection_length(&self->ptr, self->prop);
1880 /* bool functions are for speed, so we can avoid getting the length
1881 * of 1000's of items in a linked list for eg. */
1882 static int pyrna_prop_array_bool(BPy_PropertyRNA *self)
1884 PYRNA_PROP_CHECK_INT(self)
1886 return RNA_property_array_length(&self->ptr, self->prop) ? 1 : 0;
1889 static int pyrna_prop_collection_bool(BPy_PropertyRNA *self)
1891 /* no callback defined, just iterate and find the nth item */
1892 CollectionPropertyIterator iter;
1895 PYRNA_PROP_CHECK_INT(self)
1897 RNA_property_collection_begin(&self->ptr, self->prop, &iter);
1899 RNA_property_collection_end(&iter);
1903 /* internal use only */
1904 static PyObject *pyrna_prop_collection_subscript_int(BPy_PropertyRNA *self, Py_ssize_t keynum)
1907 Py_ssize_t keynum_abs= keynum;
1909 PYRNA_PROP_CHECK_OBJ(self)
1911 /* notice getting the length of the collection is avoided unless negative index is used
1912 * or to detect internal error with a valid index.
1913 * This is done for faster lookups. */
1915 keynum_abs += RNA_property_collection_length(&self->ptr, self->prop);
1917 if(keynum_abs < 0) {
1918 PyErr_Format(PyExc_IndexError, "bpy_prop_collection[%d]: out of range.", keynum);
1923 if(RNA_property_collection_lookup_int(&self->ptr, self->prop, keynum_abs, &newptr)) {
1924 return pyrna_struct_CreatePyObject(&newptr);
1927 const int len= RNA_property_collection_length(&self->ptr, self->prop);
1928 if(keynum_abs >= len) {
1929 PyErr_Format(PyExc_IndexError,
1930 "bpy_prop_collection[index]: "
1931 "index %d out of range, size %d", keynum, len);
1934 PyErr_Format(PyExc_RuntimeError,
1935 "bpy_prop_collection[index]: internal error, "
1936 "valid index %d given in %d sized collection but value not found",
1944 static PyObject *pyrna_prop_array_subscript_int(BPy_PropertyArrayRNA *self, int keynum)
1948 PYRNA_PROP_CHECK_OBJ((BPy_PropertyRNA *)self)
1950 len= pyrna_prop_array_length(self);
1952 if(keynum < 0) keynum += len;
1954 if(keynum >= 0 && keynum < len)
1955 return pyrna_prop_array_to_py_index(self, keynum);
1957 PyErr_Format(PyExc_IndexError, "bpy_prop_array[index]: index %d out of range", keynum);
1961 static PyObject *pyrna_prop_collection_subscript_str(BPy_PropertyRNA *self, const char *keyname)
1965 PYRNA_PROP_CHECK_OBJ(self)
1967 if(RNA_property_collection_lookup_string(&self->ptr, self->prop, keyname, &newptr))
1968 return pyrna_struct_CreatePyObject(&newptr);
1970 PyErr_Format(PyExc_KeyError, "bpy_prop_collection[key]: key \"%.200s\" not found", keyname);
1973 /* static PyObject *pyrna_prop_array_subscript_str(BPy_PropertyRNA *self, char *keyname) */
1975 static PyObject *pyrna_prop_collection_subscript_slice(BPy_PropertyRNA *self, Py_ssize_t start, Py_ssize_t stop)
1977 CollectionPropertyIterator rna_macro_iter;
1983 PYRNA_PROP_CHECK_OBJ(self)
1985 list= PyList_New(0);
1987 /* first loop up-until the start */
1988 for(RNA_property_collection_begin(&self->ptr, self->prop, &rna_macro_iter); rna_macro_iter.valid; RNA_property_collection_next(&rna_macro_iter)) {
1989 /* PointerRNA itemptr= rna_macro_iter.ptr; */
1990 if(count == start) {
1996 /* add items until stop */
1997 for(; rna_macro_iter.valid; RNA_property_collection_next(&rna_macro_iter)) {
1998 item= pyrna_struct_CreatePyObject(&rna_macro_iter.ptr);
1999 PyList_Append(list, item);
2008 RNA_property_collection_end(&rna_macro_iter);
2013 /* TODO - dimensions
2014 * note: could also use pyrna_prop_array_to_py_index(self, count) in a loop but its a lot slower
2015 * since at the moment it reads (and even allocates) the entire array for each index.
2017 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)
2022 PYRNA_PROP_CHECK_OBJ((BPy_PropertyRNA *)self)
2024 tuple= PyTuple_New(stop - start);
2026 /* PYRNA_PROP_CHECK_OBJ(self) isn't needed, internal use only */
2028 totdim= RNA_property_array_dimension(ptr, prop, NULL);
2031 for (count= start; count < stop; count++)
2032 PyTuple_SET_ITEM(tuple, count - start, pyrna_prop_array_to_py_index(self, count));
2035 switch (RNA_property_type(prop)) {
2038 float values_stack[PYRNA_STACK_ARRAY];
2040 if(length > PYRNA_STACK_ARRAY) { values= PyMem_MALLOC(sizeof(float) * length); }
2041 else { values= values_stack; }
2042 RNA_property_float_get_array(ptr, prop, values);
2044 for(count=start; count<stop; count++)
2045 PyTuple_SET_ITEM(tuple, count-start, PyFloat_FromDouble(values[count]));
2047 if(values != values_stack) {
2054 int values_stack[PYRNA_STACK_ARRAY];
2056 if(length > PYRNA_STACK_ARRAY) { values= PyMem_MALLOC(sizeof(int) * length); }
2057 else { values= values_stack; }
2059 RNA_property_boolean_get_array(ptr, prop, values);
2060 for(count=start; count<stop; count++)
2061 PyTuple_SET_ITEM(tuple, count-start, PyBool_FromLong(values[count]));
2063 if(values != values_stack) {
2070 int values_stack[PYRNA_STACK_ARRAY];
2072 if(length > PYRNA_STACK_ARRAY) { values= PyMem_MALLOC(sizeof(int) * length); }
2073 else { values= values_stack; }
2075 RNA_property_int_get_array(ptr, prop, values);
2076 for(count=start; count<stop; count++)
2077 PyTuple_SET_ITEM(tuple, count-start, PyLong_FromSsize_t(values[count]));
2079 if(values != values_stack) {
2085 BLI_assert(!"Invalid array type");
2087 PyErr_SetString(PyExc_TypeError, "not an array type");
2095 static PyObject *pyrna_prop_collection_subscript(BPy_PropertyRNA *self, PyObject *key)
2097 PYRNA_PROP_CHECK_OBJ(self)
2099 if (PyUnicode_Check(key)) {
2100 return pyrna_prop_collection_subscript_str(self, _PyUnicode_AsString(key));
2102 else if (PyIndex_Check(key)) {
2103 Py_ssize_t i= PyNumber_AsSsize_t(key, PyExc_IndexError);
2104 if (i == -1 && PyErr_Occurred())
2107 return pyrna_prop_collection_subscript_int(self, i);
2109 else if (PySlice_Check(key)) {
2110 PySliceObject *key_slice= (PySliceObject *)key;
2113 if(key_slice->step != Py_None && !_PyEval_SliceIndex(key, &step)) {
2116 else if (step != 1) {
2117 PyErr_SetString(PyExc_TypeError, "bpy_prop_collection[slice]: slice steps not supported");
2120 else if(key_slice->start == Py_None && key_slice->stop == Py_None) {
2121 return pyrna_prop_collection_subscript_slice(self, 0, PY_SSIZE_T_MAX);
2124 Py_ssize_t start= 0, stop= PY_SSIZE_T_MAX;
2126 /* avoid PySlice_GetIndicesEx because it needs to know the length ahead of time. */
2127 if(key_slice->start != Py_None && !_PyEval_SliceIndex(key_slice->start, &start)) return NULL;
2128 if(key_slice->stop != Py_None && !_PyEval_SliceIndex(key_slice->stop, &stop)) return NULL;
2130 if(start < 0 || stop < 0) {
2131 /* only get the length for negative values */
2132 Py_ssize_t len= (Py_ssize_t)RNA_property_collection_length(&self->ptr, self->prop);
2133 if(start < 0) start += len;
2134 if(stop < 0) start += len;
2137 if (stop - start <= 0) {
2138 return PyList_New(0);
2141 return pyrna_prop_collection_subscript_slice(self, start, stop);
2146 PyErr_Format(PyExc_TypeError,
2147 "bpy_prop_collection[key]: invalid key, "
2148 "must be a string or an int, not %.200s",
2149 Py_TYPE(key)->tp_name);
2154 static PyObject *pyrna_prop_array_subscript(BPy_PropertyArrayRNA *self, PyObject *key)
2156 PYRNA_PROP_CHECK_OBJ((BPy_PropertyRNA *)self)
2158 /*if (PyUnicode_Check(key)) {
2159 return pyrna_prop_array_subscript_str(self, _PyUnicode_AsString(key));
2162 if (PyIndex_Check(key)) {
2163 Py_ssize_t i= PyNumber_AsSsize_t(key, PyExc_IndexError);
2164 if (i == -1 && PyErr_Occurred())
2166 return pyrna_prop_array_subscript_int(self, PyLong_AsLong(key));
2168 else if (PySlice_Check(key)) {
2170 PySliceObject *key_slice= (PySliceObject *)key;
2172 if(key_slice->step != Py_None && !_PyEval_SliceIndex(key, &step)) {
2175 else if (step != 1) {
2176 PyErr_SetString(PyExc_TypeError, "bpy_prop_array[slice]: slice steps not supported");
2179 else if(key_slice->start == Py_None && key_slice->stop == Py_None) {
2180 /* note, no significant advantage with optimizing [:] slice as with collections but include here for consistency with collection slice func */
2181 Py_ssize_t len= (Py_ssize_t)pyrna_prop_array_length(self);
2182 return pyrna_prop_array_subscript_slice(self, &self->ptr, self->prop, 0, len, len);
2185 int len= pyrna_prop_array_length(self);
2186 Py_ssize_t start, stop, slicelength;
2188 if (PySlice_GetIndicesEx((void *)key, len, &start, &stop, &step, &slicelength) < 0)
2191 if (slicelength <= 0) {
2192 return PyTuple_New(0);
2195 return pyrna_prop_array_subscript_slice(self, &self->ptr, self->prop, start, stop, len);
2200 PyErr_SetString(PyExc_AttributeError, "bpy_prop_array[key]: invalid key, key must be an int");
2205 /* could call (pyrna_py_to_prop_array_index(self, i, value) in a loop but it is slow */
2206 static int prop_subscript_ass_array_slice(PointerRNA *ptr, PropertyRNA *prop, int start, int stop, int length, PyObject *value_orig)
2210 void *values_alloc= NULL;
2213 if(value_orig == NULL) {
2214 PyErr_SetString(PyExc_TypeError, "bpy_prop_array[slice]= value: deleting with list types is not supported by bpy_struct");
2218 if(!(value=PySequence_Fast(value_orig, "bpy_prop_array[slice]= value: assignment is not a sequence type"))) {
2222 if(PySequence_Fast_GET_SIZE(value) != stop-start) {
2224 PyErr_SetString(PyExc_TypeError, "bpy_prop_array[slice]= value: resizing bpy_struct arrays isn't supported");
2228 switch (RNA_property_type(prop)) {
2231 float values_stack[PYRNA_STACK_ARRAY];
2232 float *values, fval;
2235 RNA_property_float_range(ptr, prop, &min, &max);
2237 if(length > PYRNA_STACK_ARRAY) { values= values_alloc= PyMem_MALLOC(sizeof(float) * length); }
2238 else { values= values_stack; }
2239 if(start != 0 || stop != length) /* partial assignment? - need to get the array */
2240 RNA_property_float_get_array(ptr, prop, values);
2242 for(count=start; count<stop; count++) {
2243 fval= PyFloat_AsDouble(PySequence_Fast_GET_ITEM(value, count-start));
2244 CLAMP(fval, min, max);
2245 values[count]= fval;
2248 if(PyErr_Occurred()) ret= -1;
2249 else RNA_property_float_set_array(ptr, prop, values);
2254 int values_stack[PYRNA_STACK_ARRAY];
2256 if(length > PYRNA_STACK_ARRAY) { values= values_alloc= PyMem_MALLOC(sizeof(int) * length); }
2257 else { values= values_stack; }
2259 if(start != 0 || stop != length) /* partial assignment? - need to get the array */
2260 RNA_property_boolean_get_array(ptr, prop, values);
2262 for(count=start; count<stop; count++)
2263 values[count]= PyLong_AsLong(PySequence_Fast_GET_ITEM(value, count-start));
2265 if(PyErr_Occurred()) ret= -1;
2266 else RNA_property_boolean_set_array(ptr, prop, values);
2271 int values_stack[PYRNA_STACK_ARRAY];
2275 RNA_property_int_range(ptr, prop, &min, &max);
2277 if(length > PYRNA_STACK_ARRAY) { values= values_alloc= PyMem_MALLOC(sizeof(int) * length); }
2278 else { values= values_stack; }
2280 if(start != 0 || stop != length) /* partial assignment? - need to get the array */
2281 RNA_property_int_get_array(ptr, prop, values);
2283 for(count=start; count<stop; count++) {
2284 ival= PyLong_AsLong(PySequence_Fast_GET_ITEM(value, count-start));
2285 CLAMP(ival, min, max);
2286 values[count]= ival;
2289 if(PyErr_Occurred()) ret= -1;
2290 else RNA_property_int_set_array(ptr, prop, values);
2294 PyErr_SetString(PyExc_TypeError, "not an array type");
2301 PyMem_FREE(values_alloc);
2308 static int prop_subscript_ass_array_int(BPy_PropertyArrayRNA *self, Py_ssize_t keynum, PyObject *value)
2312 PYRNA_PROP_CHECK_INT((BPy_PropertyRNA *)self)
2314 len= pyrna_prop_array_length(self);
2316 if(keynum < 0) keynum += len;
2318 if(keynum >= 0 && keynum < len)
2319 return pyrna_py_to_prop_array_index(self, keynum, value);
2321 PyErr_SetString(PyExc_IndexError, "bpy_prop_array[index] = value: index out of range");
2325 static int pyrna_prop_array_ass_subscript(BPy_PropertyArrayRNA *self, PyObject *key, PyObject *value)
2327 /* char *keyname= NULL; */ /* not supported yet */
2330 PYRNA_PROP_CHECK_INT((BPy_PropertyRNA *)self);
2332 if (!RNA_property_editable_flag(&self->ptr, self->prop)) {
2333 PyErr_Format(PyExc_AttributeError,
2334 "bpy_prop_collection: attribute \"%.200s\" from \"%.200s\" is read-only",
2335 RNA_property_identifier(self->prop), RNA_struct_identifier(self->ptr.type));
2339 else if (PyIndex_Check(key)) {
2340 Py_ssize_t i= PyNumber_AsSsize_t(key, PyExc_IndexError);
2341 if (i == -1 && PyErr_Occurred()) {
2345 ret= prop_subscript_ass_array_int(self, i, value);
2348 else if (PySlice_Check(key)) {
2349 int len= RNA_property_array_length(&self->ptr, self->prop);
2350 Py_ssize_t start, stop, step, slicelength;
2352 if (PySlice_GetIndicesEx((void *)key, len, &start, &stop, &step, &slicelength) < 0) {
2355 else if (slicelength <= 0) {
2356 ret= 0; /* do nothing */
2358 else if (step == 1) {
2359 ret= prop_subscript_ass_array_slice(&self->ptr, self->prop, start, stop, len, value);
2362 PyErr_SetString(PyExc_TypeError, "slice steps not supported with rna");
2367 PyErr_SetString(PyExc_AttributeError, "invalid key, key must be an int");
2372 if(RNA_property_update_check(self->prop)) {
2373 RNA_property_update(BPy_GetContext(), &self->ptr, self->prop);
2380 /* for slice only */
2381 static PyMappingMethods pyrna_prop_array_as_mapping= {
2382 (lenfunc) pyrna_prop_array_length, /* mp_length */
2383 (binaryfunc) pyrna_prop_array_subscript, /* mp_subscript */
2384 (objobjargproc) pyrna_prop_array_ass_subscript, /* mp_ass_subscript */
2387 static PyMappingMethods pyrna_prop_collection_as_mapping= {
2388 (lenfunc) pyrna_prop_collection_length, /* mp_length */
2389 (binaryfunc) pyrna_prop_collection_subscript, /* mp_subscript */
2390 (objobjargproc) NULL, /* mp_ass_subscript */
2393 /* only for fast bool's, large structs, assign nb_bool on init */
2394 static PyNumberMethods pyrna_prop_array_as_number= {
2396 NULL, /* nb_subtract */
2397 NULL, /* nb_multiply */
2398 NULL, /* nb_remainder */
2399 NULL, /* nb_divmod */
2400 NULL, /* nb_power */
2401 NULL, /* nb_negative */
2402 NULL, /* nb_positive */
2403 NULL, /* nb_absolute */
2404 (inquiry) pyrna_prop_array_bool, /* nb_bool */
2406 static PyNumberMethods pyrna_prop_collection_as_number= {
2408 NULL, /* nb_subtract */
2409 NULL, /* nb_multiply */
2410 NULL, /* nb_remainder */
2411 NULL, /* nb_divmod */
2412 NULL, /* nb_power */
2413 NULL, /* nb_negative */
2414 NULL, /* nb_positive */
2415 NULL, /* nb_absolute */
2416 (inquiry) pyrna_prop_collection_bool, /* nb_bool */
2419 static int pyrna_prop_array_contains(BPy_PropertyRNA *self, PyObject *value)
2421 return pyrna_array_contains_py(&self->ptr, self->prop, value);
2424 static int pyrna_prop_collection_contains(BPy_PropertyRNA *self, PyObject *value)
2426 PointerRNA newptr; /* not used, just so RNA_property_collection_lookup_string runs */
2428 /* key in dict style check */
2429 const char *keyname= _PyUnicode_AsString(value);
2432 PyErr_SetString(PyExc_TypeError, "bpy_prop_collection.__contains__: expected a string");
2436 if (RNA_property_collection_lookup_string(&self->ptr, self->prop, keyname, &newptr))
2442 static int pyrna_struct_contains(BPy_StructRNA *self, PyObject *value)
2445 const char *name= _PyUnicode_AsString(value);
2447 PYRNA_STRUCT_CHECK_INT(self)
2450 PyErr_SetString(PyExc_TypeError, "bpy_struct.__contains__: expected a string");
2454 if(RNA_struct_idprops_check(self->ptr.type)==0) {
2455 PyErr_SetString(PyExc_TypeError, "bpy_struct: this type doesn't support IDProperties");
2459 group= RNA_struct_idprops(&self->ptr, 0);
2464 return IDP_GetPropertyFromGroup(group, name) ? 1:0;
2467 static PySequenceMethods pyrna_prop_array_as_sequence= {
2468 (lenfunc)pyrna_prop_array_length, /* Cant set the len otherwise it can evaluate as false */
2469 NULL, /* sq_concat */
2470 NULL, /* sq_repeat */
2471 (ssizeargfunc)pyrna_prop_array_subscript_int, /* sq_item */ /* Only set this so PySequence_Check() returns True */
2472 NULL, /* sq_slice */
2473 (ssizeobjargproc)prop_subscript_ass_array_int, /* sq_ass_item */
2474 NULL, /* *was* sq_ass_slice */
2475 (objobjproc)pyrna_prop_array_contains, /* sq_contains */
2476 (binaryfunc) NULL, /* sq_inplace_concat */
2477 (ssizeargfunc) NULL, /* sq_inplace_repeat */
2480 static PySequenceMethods pyrna_prop_collection_as_sequence= {
2481 (lenfunc)pyrna_prop_collection_length, /* Cant set the len otherwise it can evaluate as false */
2482 NULL, /* sq_concat */
2483 NULL, /* sq_repeat */
2484 (ssizeargfunc)pyrna_prop_collection_subscript_int, /* sq_item */ /* Only set this so PySequence_Check() returns True */
2485 NULL, /* *was* sq_slice */
2486 NULL, /* sq_ass_item */
2487 NULL, /* *was* sq_ass_slice */
2488 (objobjproc)pyrna_prop_collection_contains, /* sq_contains */
2489 (binaryfunc) NULL, /* sq_inplace_concat */
2490 (ssizeargfunc) NULL, /* sq_inplace_repeat */
2493 static PySequenceMethods pyrna_struct_as_sequence= {
2494 NULL, /* Cant set the len otherwise it can evaluate as false */
2495 NULL, /* sq_concat */
2496 NULL, /* sq_repeat */
2497 NULL, /* sq_item */ /* Only set this so PySequence_Check() returns True */
2498 NULL, /* *was* sq_slice */
2499 NULL, /* sq_ass_item */
2500 NULL, /* *was* sq_ass_slice */
2501 (objobjproc)pyrna_struct_contains, /* sq_contains */
2502 (binaryfunc) NULL, /* sq_inplace_concat */
2503 (ssizeargfunc) NULL, /* sq_inplace_repeat */
2506 static PyObject *pyrna_struct_subscript(BPy_StructRNA *self, PyObject *key)
2508 /* mostly copied from BPy_IDGroup_Map_GetItem */
2509 IDProperty *group, *idprop;
2510 const char *name= _PyUnicode_AsString(key);
2512 PYRNA_STRUCT_CHECK_OBJ(self)
2514 if(RNA_struct_idprops_check(self->ptr.type)==0) {
2515 PyErr_SetString(PyExc_TypeError, "this type doesn't support IDProperties");
2520 PyErr_SetString(PyExc_TypeError, "bpy_struct[key]: only strings are allowed as keys of ID properties");
2524 group= RNA_struct_idprops(&self->ptr, 0);
2527 PyErr_Format(PyExc_KeyError, "bpy_struct[key]: key \"%s\" not found", name);
2531 idprop= IDP_GetPropertyFromGroup(group, name);
2534 PyErr_Format(PyExc_KeyError, "bpy_struct[key]: key \"%s\" not found", name);
2538 return BPy_IDGroup_WrapData(self->ptr.id.data, idprop);
2541 static int pyrna_struct_ass_subscript(BPy_StructRNA *self, PyObject *key, PyObject *value)
2545 PYRNA_STRUCT_CHECK_INT(self)
2547 group= RNA_struct_idprops(&self->ptr, 1);
2549 #ifdef USE_PEDANTIC_WRITE
2550 if(rna_disallow_writes && rna_id_write_error(&self->ptr, key)) {
2553 #endif // USE_STRING_COERCE
2556 PyErr_SetString(PyExc_TypeError, "bpy_struct[key]= val: id properties not supported for this type");
2560 return BPy_Wrap_SetMapItem(group, key, value);
2563 static PyMappingMethods pyrna_struct_as_mapping= {
2564 (lenfunc) NULL, /* mp_length */
2565 (binaryfunc) pyrna_struct_subscript, /* mp_subscript */
2566 (objobjargproc) pyrna_struct_ass_subscript, /* mp_ass_subscript */
2569 PyDoc_STRVAR(pyrna_struct_keys_doc,
2570 ".. method:: keys()\n"
2572 " Returns the keys of this objects custom properties (matches pythons\n"
2573 " dictionary function of the same name).\n"
2575 " :return: custom property keys.\n"
2576 " :rtype: list of strings\n"
2578 " .. note:: Only :class:`ID`, :class:`Bone` and :class:`PoseBone` classes\n"
2579 " support custom properties.\n"
2581 static PyObject *pyrna_struct_keys(BPy_PropertyRNA *self)
2585 if(RNA_struct_idprops_check(self->ptr.type)==0) {
2586 PyErr_SetString(PyExc_TypeError, "bpy_struct.keys(): this type doesn't support IDProperties");
2590 group= RNA_struct_idprops(&self->ptr, 0);
2593 return PyList_New(0);
2595 return BPy_Wrap_GetKeys(group);
2598 PyDoc_STRVAR(pyrna_struct_items_doc,
2599 ".. method:: items()\n"
2601 " Returns the items of this objects custom properties (matches pythons\n"
2602 " dictionary function of the same name).\n"
2604 " :return: custom property key, value pairs.\n"
2605 " :rtype: list of key, value tuples\n"
2607 " .. note:: Only :class:`ID`, :class:`Bone` and :class:`PoseBone`\n"
2608 " classes support custom properties.\n"
2610 static PyObject *pyrna_struct_items(BPy_PropertyRNA *self)
2614 if(RNA_struct_idprops_check(self->ptr.type)==0) {
2615 PyErr_SetString(PyExc_TypeError, "bpy_struct.items(): this type doesn't support IDProperties");
2619 group= RNA_struct_idprops(&self->ptr, 0);
2622 return PyList_New(0);
2624 return BPy_Wrap_GetItems(self->ptr.id.data, group);
2627 PyDoc_STRVAR(pyrna_struct_values_doc,
2628 ".. method:: values()\n"
2630 " Returns the values of this objects custom properties (matches pythons\n"
2631 " dictionary function of the same name).\n"
2633 " :return: custom property values.\n"
2636 " .. note:: Only :class:`ID`, :class:`Bone` and :class:`PoseBone`\n"
2637 " classes support custom properties.\n"
2639 static PyObject *pyrna_struct_values(BPy_PropertyRNA *self)
2643 if(RNA_struct_idprops_check(self->ptr.type)==0) {
2644 PyErr_SetString(PyExc_TypeError, "bpy_struct.values(): this type doesn't support IDProperties");
2648 group= RNA_struct_idprops(&self->ptr, 0);
2651 return PyList_New(0);
2653 return BPy_Wrap_GetValues(self->ptr.id.data, group);
2657 PyDoc_STRVAR(pyrna_struct_is_property_set_doc,
2658 ".. method:: is_property_set(property)\n"
2660 " Check if a property is set, use for testing operator properties.\n"
2662 " :return: True when the property has been set.\n"
2663 " :rtype: boolean\n"
2665 static PyObject *pyrna_struct_is_property_set(BPy_StructRNA *self, PyObject *args)
2671 PYRNA_STRUCT_CHECK_OBJ(self)
2673 if (!PyArg_ParseTuple(args, "s:is_property_set", &name))
2676 if((prop= RNA_struct_find_property(&self->ptr, name)) == NULL) {
2677 PyErr_Format(PyExc_TypeError,
2678 "%.200s.is_property_set(\"%.200s\") not found",
2679 RNA_struct_identifier(self->ptr.type), name);
2683 /* double property lookup, could speed up */
2684 /* return PyBool_FromLong(RNA_property_is_set(&self->ptr, name)); */
2685 if(RNA_property_flag(prop) & PROP_IDPROPERTY) {
2686 IDProperty *group= RNA_struct_idprops(&self->ptr, 0);
2688 ret= IDP_GetPropertyFromGroup(group, name) ? 1:0;
2698 return PyBool_FromLong(ret);
2701 PyDoc_STRVAR(pyrna_struct_is_property_hidden_doc,
2702 ".. method:: is_property_hidden(property)\n"
2704 " Check if a property is hidden.\n"
2706 " :return: True when the property is hidden.\n"
2707 " :rtype: boolean\n"
2709 static PyObject *pyrna_struct_is_property_hidden(BPy_StructRNA *self, PyObject *args)
2714 PYRNA_STRUCT_CHECK_OBJ(self)
2716 if (!PyArg_ParseTuple(args, "s:is_property_hidden", &name))
2719 if((prop= RNA_struct_find_property(&self->ptr, name)) == NULL) {
2720 PyErr_Format(PyExc_TypeError,
2721 "%.200s.is_property_hidden(\"%.200s\") not found",
2722 RNA_struct_identifier(self->ptr.type), name);
2726 return PyBool_FromLong(RNA_property_flag(prop) & PROP_HIDDEN);
2729 PyDoc_STRVAR(pyrna_struct_path_resolve_doc,
2730 ".. method:: path_resolve(path, coerce=True)\n"
2732 " Returns the property from the path, raise an exception when not found.\n"
2734 " :arg path: path which this property resolves.\n"
2735 " :type path: string\n"
2736 " :arg coerce: optional argument, when True, the property will be converted\n"
2737 " into its python representation.\n"
2738 " :type coerce: boolean\n"
2740 static PyObject *pyrna_struct_path_resolve(BPy_StructRNA *self, PyObject *args)
2743 PyObject *coerce= Py_True;
2745 PropertyRNA *r_prop;
2748 PYRNA_STRUCT_CHECK_OBJ(self)
2750 if (!PyArg_ParseTuple(args, "s|O!:path_resolve", &path, &PyBool_Type, &coerce))
2753 if (RNA_path_resolve_full(&self->ptr, path, &r_ptr, &r_prop, &index)) {
2756 if(index >= RNA_property_array_length(&r_ptr, r_prop) || index < 0) {
2757 PyErr_Format(PyExc_TypeError,
2758 "%.200s.path_resolve(\"%.200s\") index out of range",
2759 RNA_struct_identifier(self->ptr.type), path);
2763 return pyrna_array_index(&r_ptr, r_prop, index);
2767 if(coerce == Py_False) {
2768 return pyrna_prop_CreatePyObject(&r_ptr, r_prop);
2771 return pyrna_prop_to_py(&r_ptr, r_prop);
2776 return pyrna_struct_CreatePyObject(&r_ptr);
2780 PyErr_Format(PyExc_TypeError,
2781 "%.200s.path_resolve(\"%.200s\") could not be resolved",
2782 RNA_struct_identifier(self->ptr.type), path);
2787 PyDoc_STRVAR(pyrna_struct_path_from_id_doc,
2788 ".. method:: path_from_id(property=\"\")\n"
2790 " Returns the data path from the ID to this object (string).\n"
2792 " :arg property: Optional property name which can be used if the path is\n"
2793 " to a property of this object.\n"
2794 " :type property: string\n"
2795 " :return: The path from :class:`bpy_struct.id_data`\n"
2796 " to this struct and property (when given).\n"
2799 static PyObject *pyrna_struct_path_from_id(BPy_StructRNA *self, PyObject *args)
2801 const char *name= NULL;
2806 PYRNA_STRUCT_CHECK_OBJ(self)
2808 if (!PyArg_ParseTuple(args, "|s:path_from_id", &name))
2812 prop= RNA_struct_find_property(&self->ptr, name);
2814 PyErr_Format(PyExc_TypeError,
2815 "%.200s.path_from_id(\"%.200s\") not found",
2816 RNA_struct_identifier(self->ptr.type), name);
2820 path= RNA_path_from_ID_to_property(&self->ptr, prop);
2823 path= RNA_path_from_ID_to_struct(&self->ptr);
2828 PyErr_Format(PyExc_TypeError,
2829 "%.200s.path_from_id(\"%s\") found but does not support path creation",
2830 RNA_struct_identifier(self->ptr.type), name);
2833 PyErr_Format(PyExc_TypeError,
2834 "%.200s.path_from_id() does not support path creation for this type",
2835 RNA_struct_identifier(self->ptr.type));
2840 ret= PyUnicode_FromString(path);
2841 MEM_freeN((void *)path);
2846 PyDoc_STRVAR(pyrna_prop_path_from_id_doc,
2847 ".. method:: path_from_id()\n"
2849 " Returns the data path from the ID to this property (string).\n"
2851 " :return: The path from :class:`bpy_struct.id_data` to this property.\n"
2854 static PyObject *pyrna_prop_path_from_id(BPy_PropertyRNA *self)
2857 PropertyRNA *prop= self->prop;
2860 path= RNA_path_from_ID_to_property(&self->ptr, self->prop);
2863 PyErr_Format(PyExc_TypeError,
2864 "%.200s.%.200s.path_from_id() does not support path creation for this type",
2865 RNA_struct_identifier(self->ptr.type), RNA_property_identifier(prop));
2869 ret= PyUnicode_FromString(path);
2870 MEM_freeN((void *)path);
2875 PyDoc_STRVAR(pyrna_struct_type_recast_doc,
2876 ".. method:: type_recast()\n"
2878 " Return a new instance, this is needed because types\n"
2879 " such as textures can be changed at runtime.\n"
2881 " :return: a new instance of this object with the type initialized again.\n"
2882 " :rtype: subclass of :class:`bpy_struct`\n"
2884 static PyObject *pyrna_struct_type_recast(BPy_StructRNA *self)
2888 PYRNA_STRUCT_CHECK_OBJ(self)
2890 RNA_pointer_recast(&self->ptr, &r_ptr);
2891 return pyrna_struct_CreatePyObject(&r_ptr);
2894 static void pyrna_dir_members_py(PyObject *list, PyObject *self)
2897 PyObject **dict_ptr;
2900 dict_ptr= _PyObject_GetDictPtr((PyObject *)self);
2902 if(dict_ptr && (dict=*dict_ptr)) {
2903 list_tmp= PyDict_Keys(dict);
2904 PyList_SetSlice(list, INT_MAX, INT_MAX, list_tmp);
2905 Py_DECREF(list_tmp);
2908 dict= ((PyTypeObject *)Py_TYPE(self))->tp_dict;
2910 list_tmp= PyDict_Keys(dict);
2911 PyList_SetSlice(list, INT_MAX, INT_MAX, list_tmp);
2912 Py_DECREF(list_tmp);
2916 static void pyrna_dir_members_rna(PyObject *list, PointerRNA *ptr)
2921 /* for looping over attrs and funcs */
2923 PropertyRNA *iterprop;
2926 RNA_pointer_create(NULL, &RNA_Struct, ptr->type, &tptr);
2927 iterprop= RNA_struct_find_property(&tptr, "functions");
2929 RNA_PROP_BEGIN(&tptr, itemptr, iterprop) {
2930 idname= RNA_function_identifier(itemptr.data);
2932 pystring= PyUnicode_FromString(idname);
2933 PyList_Append(list, pystring);
2934 Py_DECREF(pystring);
2941 * Collect RNA attributes
2943 char name[256], *nameptr;
2945 iterprop= RNA_struct_iterator_property(ptr->type);
2947 RNA_PROP_BEGIN(ptr, itemptr, iterprop) {
2948 nameptr= RNA_struct_name_get_alloc(&itemptr, name, sizeof(name));
2951 pystring= PyUnicode_FromString(nameptr);
2952 PyList_Append(list, pystring);
2953 Py_DECREF(pystring);
2964 static PyObject *pyrna_struct_dir(BPy_StructRNA *self)
2969 PYRNA_STRUCT_CHECK_OBJ(self)
2971 /* Include this incase this instance is a subtype of a python class
2972 * In these instances we may want to return a function or variable provided by the subtype
2976 if (!BPy_StructRNA_CheckExact(self))
2977 pyrna_dir_members_py(ret, (PyObject *)self);
2979 pyrna_dir_members_rna(ret, &self->ptr);
2981 if(self->ptr.type == &RNA_Context) {
2982 ListBase lb= CTX_data_dir_get(self->ptr.data);
2985 for(link=lb.first; link; link=link->next) {
2986 pystring= PyUnicode_FromString(link->data);
2987 PyList_Append(ret, pystring);
2988 Py_DECREF(pystring);
2995 /* set(), this is needed to remove-doubles because the deferred
2996 * register-props will be in both the python __dict__ and accessed as RNA */
2998 PyObject *set= PySet_New(ret);
3001 ret= PySequence_List(set);
3008 //---------------getattr--------------------------------------------
3009 static PyObject *pyrna_struct_getattro(BPy_StructRNA *self, PyObject *pyname)
3011 const char *name= _PyUnicode_AsString(pyname);
3016 PYRNA_STRUCT_CHECK_OBJ(self)
3019 PyErr_SetString(PyExc_AttributeError, "bpy_struct: __getattr__ must be a string");
3022 else if(name[0]=='_') { // rna can't start with a "_", so for __dict__ and similar we can skip using rna lookups
3023 /* annoying exception, maybe we need to have different types for this... */
3024 if((strcmp(name, "__getitem__")==0 || strcmp(name, "__setitem__")==0) && !RNA_struct_idprops_check(self->ptr.type)) {
3025 PyErr_SetString(PyExc_AttributeError, "bpy_struct: no __getitem__ support for this type");
3029 ret= PyObject_GenericGetAttr((PyObject *)self, pyname);
3032 else if ((prop= RNA_struct_find_property(&self->ptr, name))) {
3033 ret= pyrna_prop_to_py(&self->ptr, prop);
3035 /* RNA function only if callback is declared (no optional functions) */
3036 else if ((func= RNA_struct_find_function(&self->ptr, name)) && RNA_function_defined(func)) {
3037 ret= pyrna_func_to_py(&self->ptr, func);
3039 else if (self->ptr.type == &RNA_Context) {
3040 bContext *C= self->ptr.data;
3042 PyErr_Format(PyExc_AttributeError,
3043 "bpy_struct: Context is 'NULL', can't get \"%.200s\" from context",
3052 int done= CTX_data_get(C, name, &newptr, &newlb, &newtype);
3054 if(done==1) { /* found */
3056 case CTX_DATA_TYPE_POINTER:
3057 if(newptr.data == NULL) {
3062 ret= pyrna_struct_CreatePyObject(&newptr);
3065 case CTX_DATA_TYPE_COLLECTION:
3067 CollectionPointerLink *link;
3072 for(link=newlb.first; link; link=link->next) {
3073 linkptr= pyrna_struct_CreatePyObject(&link->ptr);
3074 PyList_Append(ret, linkptr);
3080 /* should never happen */
3081 BLI_assert(!"Invalid context type");
3083 PyErr_Format(PyExc_AttributeError,
3084 "bpy_struct: Context type invalid %d, can't get \"%.200s\" from context",
3089 else if (done==-1) { /* found but not set */
3093 else { /* not found in the context */
3094 /* lookup the subclass. raise an error if its not found */
3095 ret= PyObject_GenericGetAttr((PyObject *)self, pyname);
3098 BLI_freelistN(&newlb);
3103 PyErr_Format(PyExc_AttributeError,
3104 "bpy_struct: attribute \"%.200s\" not found",
3108 /* Include this incase this instance is a subtype of a python class
3109 * In these instances we may want to return a function or variable provided by the subtype
3111 * Also needed to return methods when its not a subtype
3114 /* The error raised here will be displayed */
3115 ret= PyObject_GenericGetAttr((PyObject *)self, pyname);
3122 static int pyrna_struct_pydict_contains(PyObject *self, PyObject *pyname)
3124 PyObject *dict= *(_PyObject_GetDictPtr((PyObject *)self));
3125 if (dict==NULL) /* unlikely */
3128 return PyDict_Contains(dict, pyname);
3132 //--------------- setattr-------------------------------------------
3133 static int pyrna_is_deferred_prop(PyObject *value)
3135 return PyTuple_CheckExact(value) && PyTuple_GET_SIZE(value)==2 && PyCallable_Check(PyTuple_GET_ITEM(value, 0)) && PyDict_CheckExact(PyTuple_GET_ITEM(value, 1));
3139 static PyObject *pyrna_struct_meta_idprop_getattro(PyObject *cls, PyObject *attr)
3141 PyObject *ret= PyType_Type.tp_getattro(cls, attr);
3144 * >>> bpy.types.Scene.foo= BoolProperty()
3145 * >>> bpy.types.Scene.foo
3146 * <bpy_struct, BooleanProperty("foo")>
3147 * ...rather than returning the deferred class register tuple as checked by pyrna_is_deferred_prop()
3149 * Disable for now, this is faking internal behavior in a way thats too tricky to maintain well. */
3151 if(ret == NULL) { // || pyrna_is_deferred_prop(ret)
3152 StructRNA *srna= srna_from_self(cls, "StructRNA.__getattr__");
3154 PropertyRNA *prop= RNA_struct_type_find_property(srna, _PyUnicode_AsString(attr));
3157 PyErr_Clear(); /* clear error from tp_getattro */
3158 RNA_pointer_create(NULL, &RNA_Property, prop, &tptr);
3159 ret= pyrna_struct_CreatePyObject(&tptr);