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"
43 #ifdef USE_PYRNA_INVALIDATE_WEAKREF
44 #include "MEM_guardedalloc.h"
47 #include "BLI_dynstr.h"
48 #include "BLI_string.h"
49 #include "BLI_listbase.h"
50 #include "BLI_math_rotation.h"
51 #include "BLI_utildefines.h"
53 #ifdef USE_PYRNA_INVALIDATE_WEAKREF
54 #include "BLI_ghash.h"
57 #include "RNA_enum_types.h"
58 #include "RNA_define.h" /* RNA_def_property_free_identifier */
59 #include "RNA_access.h"
61 #include "MEM_guardedalloc.h"
63 #include "BKE_idcode.h"
64 #include "BKE_context.h"
65 #include "BKE_global.h" /* evil G.* */
66 #include "BKE_report.h"
67 #include "BKE_idprop.h"
69 #include "BKE_animsys.h"
70 #include "BKE_fcurve.h"
72 #include "../generic/IDProp.h" /* for IDprop lookups */
73 #include "../generic/py_capi_utils.h"
75 #define USE_PEDANTIC_WRITE
77 #define USE_STRING_COERCE
79 static PyObject* pyrna_struct_Subtype(PointerRNA *ptr);
80 static PyObject *pyrna_prop_collection_values(BPy_PropertyRNA *self);
82 int pyrna_struct_validity_check(BPy_StructRNA *pysrna)
86 PyErr_Format(PyExc_ReferenceError, "StructRNA of type %.200s has been removed", Py_TYPE(pysrna)->tp_name);
90 int pyrna_prop_validity_check(BPy_PropertyRNA *self)
94 PyErr_Format(PyExc_ReferenceError,
95 "PropertyRNA of type %.200s.%.200s has been removed",
96 Py_TYPE(self)->tp_name, RNA_property_identifier(self->prop));
100 #if defined(USE_PYRNA_INVALIDATE_GC) || defined(USE_PYRNA_INVALIDATE_WEAKREF)
101 static void pyrna_invalidate(BPy_DummyPointerRNA *self)
103 self->ptr.type= NULL; /* this is checked for validity */
104 self->ptr.id.data= NULL; /* should not be needed but prevent bad pointer access, just incase */
108 #ifdef USE_PYRNA_INVALIDATE_GC
109 #define FROM_GC(g) ((PyObject *)(((PyGC_Head *)g)+1))
111 /* only for sizeof() */
112 struct gc_generation {
118 static void id_release_gc(struct ID *id)
121 // unsigned int i= 0;
123 /* hack below to get the 2 other lists from _PyGC_generation0 that are normally not exposed */
124 PyGC_Head *gen= (PyGC_Head *)(((char *)_PyGC_generation0) + (sizeof(gc_generation) * j));
125 PyGC_Head *g= gen->gc.gc_next;
126 while ((g= g->gc.gc_next) != gen) {
127 PyObject *ob= FROM_GC(g);
128 if(PyType_IsSubtype(Py_TYPE(ob), &pyrna_struct_Type) || PyType_IsSubtype(Py_TYPE(ob), &pyrna_prop_Type)) {
129 BPy_DummyPointerRNA *ob_ptr= (BPy_DummyPointerRNA *)ob;
130 if(ob_ptr->ptr.id.data == id) {
131 pyrna_invalidate(ob_ptr);
132 // printf("freeing: %p %s, %.200s\n", (void *)ob, id->name, Py_TYPE(ob)->tp_name);
138 // printf("id_release_gc freed '%s': %d\n", id->name, i);
142 #ifdef USE_PYRNA_INVALIDATE_WEAKREF
143 //#define DEBUG_RNA_WEAKREF
145 struct GHash *id_weakref_pool= NULL;
146 static PyObject *id_free_weakref_cb(PyObject *weakinfo_pair, PyObject *weakref);
147 static PyMethodDef id_free_weakref_cb_def= {"id_free_weakref_cb", (PyCFunction)id_free_weakref_cb, METH_O, NULL};
149 /* adds a reference to the list, remember to decref */
150 static GHash *id_weakref_pool_get(ID *id)
152 GHash *weakinfo_hash= NULL;
154 if(id_weakref_pool) {
155 weakinfo_hash= BLI_ghash_lookup(id_weakref_pool, (void *)id);
158 /* first time, allocate pool */
159 id_weakref_pool= BLI_ghash_new(BLI_ghashutil_ptrhash, BLI_ghashutil_ptrcmp, "rna_global_pool");
163 if(weakinfo_hash==NULL) {
164 /* we're using a ghash as a set, could use libHX's HXMAP_SINGULAR but would be an extra dep. */
165 weakinfo_hash= BLI_ghash_new(BLI_ghashutil_ptrhash, BLI_ghashutil_ptrcmp, "rna_id");
166 BLI_ghash_insert(id_weakref_pool, (void *)id, weakinfo_hash);
169 return weakinfo_hash;
172 /* called from pyrna_struct_CreatePyObject() and pyrna_prop_CreatePyObject() */
173 void id_weakref_pool_add(ID *id, BPy_DummyPointerRNA *pyrna)
176 PyObject *weakref_capsule;
177 PyObject *weakref_cb_py;
179 /* create a new function instance and insert the list as 'self' so we can remove ourself from it */
180 GHash *weakinfo_hash= id_weakref_pool_get(id); /* new or existing */
182 weakref_capsule= PyCapsule_New(weakinfo_hash, NULL, NULL);
183 weakref_cb_py= PyCFunction_New(&id_free_weakref_cb_def, weakref_capsule);
184 Py_DECREF(weakref_capsule);
186 /* add weakref to weakinfo_hash list */
187 weakref= PyWeakref_NewRef((PyObject *)pyrna, weakref_cb_py);
189 Py_DECREF(weakref_cb_py); /* function owned by the weakref now */
191 /* important to add at the end, since first removal looks at the end */
192 BLI_ghash_insert(weakinfo_hash, (void *)weakref, id); /* using a hash table as a set, all 'id's are the same */
193 /* weakinfo_hash owns the weakref */
197 /* workaround to get the last id without a lookup */
198 static ID *_id_tmp_ptr;
199 static void value_id_set(void *id)
201 _id_tmp_ptr= (ID *)id;
204 static void id_release_weakref_list(struct ID *id, GHash *weakinfo_hash);
205 static PyObject *id_free_weakref_cb(PyObject *weakinfo_capsule, PyObject *weakref)
207 /* important to search backwards */
208 GHash *weakinfo_hash= PyCapsule_GetPointer(weakinfo_capsule, NULL);
211 if(BLI_ghash_size(weakinfo_hash) > 1) {
212 BLI_ghash_remove(weakinfo_hash, weakref, NULL, NULL);
214 else { /* get the last id and free it */
215 BLI_ghash_remove(weakinfo_hash, weakref, NULL, value_id_set);
216 id_release_weakref_list(_id_tmp_ptr, weakinfo_hash);
224 static void id_release_weakref_list(struct ID *id, GHash *weakinfo_hash)
226 GHashIterator weakinfo_hash_iter;
228 BLI_ghashIterator_init(&weakinfo_hash_iter, weakinfo_hash);
230 #ifdef DEBUG_RNA_WEAKREF
231 fprintf(stdout, "id_release_weakref: '%s', %d items\n", id->name, BLI_ghash_size(weakinfo_hash));
234 while (!BLI_ghashIterator_isDone(&weakinfo_hash_iter)) {
235 PyObject *weakref= (PyObject *)BLI_ghashIterator_getKey(&weakinfo_hash_iter);
236 PyObject *item= PyWeakref_GET_OBJECT(weakref);
237 if(item != Py_None) {
239 #ifdef DEBUG_RNA_WEAKREF
240 PyC_ObSpit("id_release_weakref item ", item);
243 pyrna_invalidate((BPy_DummyPointerRNA *)item);
248 BLI_ghashIterator_step(&weakinfo_hash_iter);
251 BLI_ghash_remove(id_weakref_pool, (void *)id, NULL, NULL);
252 BLI_ghash_free(weakinfo_hash, NULL, NULL);
254 if(BLI_ghash_size(id_weakref_pool) == 0) {
255 BLI_ghash_free(id_weakref_pool, NULL, NULL);
256 id_weakref_pool= NULL;
257 #ifdef DEBUG_RNA_WEAKREF
258 printf("id_release_weakref freeing pool\n");
263 static void id_release_weakref(struct ID *id)
265 GHash *weakinfo_hash= BLI_ghash_lookup(id_weakref_pool, (void *)id);
267 id_release_weakref_list(id, weakinfo_hash);
271 #endif /* USE_PYRNA_INVALIDATE_WEAKREF */
273 void BPY_id_release(struct ID *id)
275 #ifdef USE_PYRNA_INVALIDATE_GC
279 #ifdef USE_PYRNA_INVALIDATE_WEAKREF
280 if(id_weakref_pool) {
281 PyGILState_STATE gilstate= PyGILState_Ensure();
283 id_release_weakref(id);
285 PyGILState_Release(gilstate);
287 #endif /* USE_PYRNA_INVALIDATE_WEAKREF */
292 #ifdef USE_PEDANTIC_WRITE
293 static short rna_disallow_writes= FALSE;
295 static int rna_id_write_error(PointerRNA *ptr, PyObject *key)
297 ID *id= ptr->id.data;
299 const short idcode= GS(id->name);
300 if(!ELEM(idcode, ID_WM, ID_SCR)) { /* may need more added here */
301 const char *idtype= BKE_idcode_to_name(idcode);
303 if(key && PyUnicode_Check(key)) pyname= _PyUnicode_AsString(key);
304 else pyname= "<UNKNOWN>";
306 /* make a nice string error */
307 BLI_assert(idtype != NULL);
308 PyErr_Format(PyExc_AttributeError,
309 "Writing to ID classes in this context is not allowed: "
310 "%.200s, %.200s datablock, error setting %.200s.%.200s",
311 id->name+2, idtype, RNA_struct_identifier(ptr->type), pyname);
318 #endif // USE_PEDANTIC_WRITE
321 #ifdef USE_PEDANTIC_WRITE
322 int pyrna_write_check(void)
324 return !rna_disallow_writes;
326 #else // USE_PEDANTIC_WRITE
327 int pyrna_write_check(void)
331 #endif // USE_PEDANTIC_WRITE
333 static Py_ssize_t pyrna_prop_collection_length(BPy_PropertyRNA *self);
334 static Py_ssize_t pyrna_prop_array_length(BPy_PropertyArrayRNA *self);
335 static int pyrna_py_to_prop(PointerRNA *ptr, PropertyRNA *prop, void *data, PyObject *value, const char *error_prefix);
336 static int deferred_register_prop(StructRNA *srna, PyObject *key, PyObject *item);
339 #include "../generic/mathutils.h" /* so we can have mathutils callbacks */
341 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);
342 static short pyrna_rotation_euler_order_get(PointerRNA *ptr, PropertyRNA **prop_eul_order, short order_fallback);
344 /* bpyrna vector/euler/quat callbacks */
345 static int mathutils_rna_array_cb_index= -1; /* index for our callbacks */
347 /* subtype not used much yet */
348 #define MATHUTILS_CB_SUBTYPE_EUL 0
349 #define MATHUTILS_CB_SUBTYPE_VEC 1
350 #define MATHUTILS_CB_SUBTYPE_QUAT 2
351 #define MATHUTILS_CB_SUBTYPE_COLOR 3
353 static int mathutils_rna_generic_check(BaseMathObject *bmo)
355 BPy_PropertyRNA *self= (BPy_PropertyRNA *)bmo->cb_user;
357 PYRNA_PROP_CHECK_INT(self)
359 return self->prop ? 0 : -1;
362 static int mathutils_rna_vector_get(BaseMathObject *bmo, int subtype)
364 BPy_PropertyRNA *self= (BPy_PropertyRNA *)bmo->cb_user;
366 PYRNA_PROP_CHECK_INT(self)
371 RNA_property_float_get_array(&self->ptr, self->prop, bmo->data);
373 /* Euler order exception */
374 if(subtype==MATHUTILS_CB_SUBTYPE_EUL) {
375 EulerObject *eul= (EulerObject *)bmo;
376 PropertyRNA *prop_eul_order= NULL;
377 eul->order= pyrna_rotation_euler_order_get(&self->ptr, &prop_eul_order, eul->order);
383 static int mathutils_rna_vector_set(BaseMathObject *bmo, int subtype)
385 BPy_PropertyRNA *self= (BPy_PropertyRNA *)bmo->cb_user;
388 PYRNA_PROP_CHECK_INT(self)
393 #ifdef USE_PEDANTIC_WRITE
394 if(rna_disallow_writes && rna_id_write_error(&self->ptr, NULL)) {
397 #endif // USE_PEDANTIC_WRITE
399 if (!RNA_property_editable_flag(&self->ptr, self->prop)) {
400 PyErr_Format(PyExc_AttributeError,
401 "bpy_prop \"%.200s.%.200s\" is read-only",
402 RNA_struct_identifier(self->ptr.type), RNA_property_identifier(self->prop));
406 RNA_property_float_range(&self->ptr, self->prop, &min, &max);
408 if(min != FLT_MIN || max != FLT_MAX) {
409 int i, len= RNA_property_array_length(&self->ptr, self->prop);
410 for(i=0; i<len; i++) {
411 CLAMP(bmo->data[i], min, max);
415 RNA_property_float_set_array(&self->ptr, self->prop, bmo->data);
416 if(RNA_property_update_check(self->prop)) {
417 RNA_property_update(BPy_GetContext(), &self->ptr, self->prop);
420 /* Euler order exception */
421 if(subtype==MATHUTILS_CB_SUBTYPE_EUL) {
422 EulerObject *eul= (EulerObject *)bmo;
423 PropertyRNA *prop_eul_order= NULL;
424 short order= pyrna_rotation_euler_order_get(&self->ptr, &prop_eul_order, eul->order);
425 if(order != eul->order) {
426 RNA_property_enum_set(&self->ptr, prop_eul_order, eul->order);
427 if(RNA_property_update_check(prop_eul_order)) {
428 RNA_property_update(BPy_GetContext(), &self->ptr, prop_eul_order);
435 static int mathutils_rna_vector_get_index(BaseMathObject *bmo, int UNUSED(subtype), int index)
437 BPy_PropertyRNA *self= (BPy_PropertyRNA *)bmo->cb_user;
439 PYRNA_PROP_CHECK_INT(self)
444 bmo->data[index]= RNA_property_float_get_index(&self->ptr, self->prop, index);
448 static int mathutils_rna_vector_set_index(BaseMathObject *bmo, int UNUSED(subtype), int index)
450 BPy_PropertyRNA *self= (BPy_PropertyRNA *)bmo->cb_user;
452 PYRNA_PROP_CHECK_INT(self)
457 #ifdef USE_PEDANTIC_WRITE
458 if(rna_disallow_writes && rna_id_write_error(&self->ptr, NULL)) {
461 #endif // USE_PEDANTIC_WRITE
463 if (!RNA_property_editable_flag(&self->ptr, self->prop)) {
464 PyErr_Format(PyExc_AttributeError,
465 "bpy_prop \"%.200s.%.200s\" is read-only",
466 RNA_struct_identifier(self->ptr.type), RNA_property_identifier(self->prop));
470 RNA_property_float_clamp(&self->ptr, self->prop, &bmo->data[index]);
471 RNA_property_float_set_index(&self->ptr, self->prop, index, bmo->data[index]);
473 if(RNA_property_update_check(self->prop)) {
474 RNA_property_update(BPy_GetContext(), &self->ptr, self->prop);
480 static Mathutils_Callback mathutils_rna_array_cb= {
481 (BaseMathCheckFunc) mathutils_rna_generic_check,
482 (BaseMathGetFunc) mathutils_rna_vector_get,
483 (BaseMathSetFunc) mathutils_rna_vector_set,
484 (BaseMathGetIndexFunc) mathutils_rna_vector_get_index,
485 (BaseMathSetIndexFunc) mathutils_rna_vector_set_index
489 /* bpyrna matrix callbacks */
490 static int mathutils_rna_matrix_cb_index= -1; /* index for our callbacks */
492 static int mathutils_rna_matrix_get(BaseMathObject *bmo, int UNUSED(subtype))
494 BPy_PropertyRNA *self= (BPy_PropertyRNA *)bmo->cb_user;
496 PYRNA_PROP_CHECK_INT(self)
501 RNA_property_float_get_array(&self->ptr, self->prop, bmo->data);
505 static int mathutils_rna_matrix_set(BaseMathObject *bmo, int UNUSED(subtype))
507 BPy_PropertyRNA *self= (BPy_PropertyRNA *)bmo->cb_user;
509 PYRNA_PROP_CHECK_INT(self)
514 #ifdef USE_PEDANTIC_WRITE
515 if(rna_disallow_writes && rna_id_write_error(&self->ptr, NULL)) {
518 #endif // USE_PEDANTIC_WRITE
520 if (!RNA_property_editable_flag(&self->ptr, self->prop)) {
521 PyErr_Format(PyExc_AttributeError,
522 "bpy_prop \"%.200s.%.200s\" is read-only",
523 RNA_struct_identifier(self->ptr.type), RNA_property_identifier(self->prop));
527 /* can ignore clamping here */
528 RNA_property_float_set_array(&self->ptr, self->prop, bmo->data);
530 if(RNA_property_update_check(self->prop)) {
531 RNA_property_update(BPy_GetContext(), &self->ptr, self->prop);
536 static Mathutils_Callback mathutils_rna_matrix_cb= {
537 mathutils_rna_generic_check,
538 mathutils_rna_matrix_get,
539 mathutils_rna_matrix_set,
544 static short pyrna_rotation_euler_order_get(PointerRNA *ptr, PropertyRNA **prop_eul_order, short order_fallback)
546 /* attempt to get order */
547 if(*prop_eul_order==NULL)
548 *prop_eul_order= RNA_struct_find_property(ptr, "rotation_mode");
550 if(*prop_eul_order) {
551 short order= RNA_property_enum_get(ptr, *prop_eul_order);
552 if (order >= EULER_ORDER_XYZ && order <= EULER_ORDER_ZYX) /* could be quat or axisangle */
556 return order_fallback;
559 #endif // USE_MATHUTILS
561 /* note that PROP_NONE is included as a vector subtype. this is because its handy to
562 * have x/y access to fcurve keyframes and other fixed size float arrays of length 2-4. */
563 #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
565 PyObject *pyrna_math_object_from_array(PointerRNA *ptr, PropertyRNA *prop)
573 int flag= RNA_property_flag(prop);
575 /* disallow dynamic sized arrays to be wrapped since the size could change
576 * to a size mathutils does not support */
577 if ((RNA_property_type(prop) != PROP_FLOAT) || (flag & PROP_DYNAMIC))
580 len= RNA_property_array_length(ptr, prop);
581 subtype= RNA_property_subtype(prop);
582 totdim= RNA_property_array_dimension(ptr, prop, NULL);
583 is_thick= (flag & PROP_THICK_WRAP);
585 if (totdim == 1 || (totdim == 2 && subtype == PROP_MATRIX)) {
587 ret= pyrna_prop_CreatePyObject(ptr, prop); /* owned by the mathutils PyObject */
589 switch(RNA_property_subtype(prop)) {
590 case PROP_ALL_VECTOR_SUBTYPES:
591 if(len>=2 && len <= 4) {
593 ret= newVectorObject(NULL, len, Py_NEW, NULL);
594 RNA_property_float_get_array(ptr, prop, ((VectorObject *)ret)->vec);
597 PyObject *vec_cb= newVectorObject_cb(ret, len, mathutils_rna_array_cb_index, MATHUTILS_CB_SUBTYPE_VEC);
598 Py_DECREF(ret); /* the vector owns now */
599 ret= vec_cb; /* return the vector instead */
606 ret= newMatrixObject(NULL, 4, 4, Py_NEW, NULL);
607 RNA_property_float_get_array(ptr, prop, ((MatrixObject *)ret)->contigPtr);
610 PyObject *mat_cb= newMatrixObject_cb(ret, 4,4, mathutils_rna_matrix_cb_index, FALSE);
611 Py_DECREF(ret); /* the matrix owns now */
612 ret= mat_cb; /* return the matrix instead */
617 ret= newMatrixObject(NULL, 3, 3, Py_NEW, NULL);
618 RNA_property_float_get_array(ptr, prop, ((MatrixObject *)ret)->contigPtr);
621 PyObject *mat_cb= newMatrixObject_cb(ret, 3,3, mathutils_rna_matrix_cb_index, FALSE);
622 Py_DECREF(ret); /* the matrix owns now */
623 ret= mat_cb; /* return the matrix instead */
628 case PROP_QUATERNION:
629 if(len==3) { /* euler */
631 /* attempt to get order, only needed for thick types since wrapped with update via callbacks */
632 PropertyRNA *prop_eul_order= NULL;
633 short order= pyrna_rotation_euler_order_get(ptr, &prop_eul_order, EULER_ORDER_XYZ);
635 ret= newEulerObject(NULL, order, Py_NEW, NULL); // TODO, get order from RNA
636 RNA_property_float_get_array(ptr, prop, ((EulerObject *)ret)->eul);
639 /* order will be updated from callback on use */
640 PyObject *eul_cb= newEulerObject_cb(ret, EULER_ORDER_XYZ, mathutils_rna_array_cb_index, MATHUTILS_CB_SUBTYPE_EUL); // TODO, get order from RNA
641 Py_DECREF(ret); /* the euler owns now */
642 ret= eul_cb; /* return the euler instead */
647 ret= newQuaternionObject(NULL, Py_NEW, NULL);
648 RNA_property_float_get_array(ptr, prop, ((QuaternionObject *)ret)->quat);
651 PyObject *quat_cb= newQuaternionObject_cb(ret, mathutils_rna_array_cb_index, MATHUTILS_CB_SUBTYPE_QUAT);
652 Py_DECREF(ret); /* the quat owns now */
653 ret= quat_cb; /* return the quat instead */
658 case PROP_COLOR_GAMMA:
659 if(len==3) { /* color */
661 ret= newColorObject(NULL, Py_NEW, NULL); // TODO, get order from RNA
662 RNA_property_float_get_array(ptr, prop, ((ColorObject *)ret)->col);
665 PyObject *col_cb= newColorObject_cb(ret, mathutils_rna_array_cb_index, MATHUTILS_CB_SUBTYPE_COLOR);
666 Py_DECREF(ret); /* the color owns now */
667 ret= col_cb; /* return the color instead */
677 /* this is an array we cant reference (since its not thin wrappable)
678 * and cannot be coerced into a mathutils type, so return as a list */
679 ret= pyrna_prop_array_subscript_slice(NULL, ptr, prop, 0, len, len);
682 ret= pyrna_prop_CreatePyObject(ptr, prop); /* owned by the mathutils PyObject */
685 #else // USE_MATHUTILS
688 #endif // USE_MATHUTILS
693 /* same as RNA_enum_value_from_id but raises an exception */
694 int pyrna_enum_value_from_id(EnumPropertyItem *item, const char *identifier, int *value, const char *error_prefix)
696 if(RNA_enum_value_from_id(item, identifier, value) == 0) {
697 const char *enum_str= BPy_enum_as_string(item);
698 PyErr_Format(PyExc_TypeError,
699 "%s: '%.200s' not found in (%s)",
700 error_prefix, identifier, enum_str);
701 MEM_freeN((void *)enum_str);
708 static int pyrna_struct_compare(BPy_StructRNA *a, BPy_StructRNA *b)
710 return (a->ptr.data==b->ptr.data) ? 0 : -1;
713 static int pyrna_prop_compare(BPy_PropertyRNA *a, BPy_PropertyRNA *b)
715 return (a->prop==b->prop && a->ptr.data==b->ptr.data) ? 0 : -1;
718 static PyObject *pyrna_struct_richcmp(PyObject *a, PyObject *b, int op)
721 int ok= -1; /* zero is true */
723 if (BPy_StructRNA_Check(a) && BPy_StructRNA_Check(b))
724 ok= pyrna_struct_compare((BPy_StructRNA *)a, (BPy_StructRNA *)b);
728 ok= !ok; /* pass through */
730 res= ok ? Py_False : Py_True;
737 res= Py_NotImplemented;
744 return Py_INCREF(res), res;
747 static PyObject *pyrna_prop_richcmp(PyObject *a, PyObject *b, int op)
750 int ok= -1; /* zero is true */
752 if (BPy_PropertyRNA_Check(a) && BPy_PropertyRNA_Check(b))
753 ok= pyrna_prop_compare((BPy_PropertyRNA *)a, (BPy_PropertyRNA *)b);
757 ok= !ok; /* pass through */
759 res= ok ? Py_False : Py_True;
766 res= Py_NotImplemented;
773 return Py_INCREF(res), res;
776 /*----------------------repr--------------------------------------------*/
777 static PyObject *pyrna_struct_str(BPy_StructRNA *self)
782 if(!PYRNA_STRUCT_IS_VALID(self)) {
783 return PyUnicode_FromFormat("<bpy_struct, %.200s dead>", Py_TYPE(self)->tp_name);
786 /* print name if available */
787 name= RNA_struct_name_get_alloc(&self->ptr, NULL, FALSE);
789 ret= PyUnicode_FromFormat("<bpy_struct, %.200s(\"%.200s\")>", RNA_struct_identifier(self->ptr.type), name);
790 MEM_freeN((void *)name);
794 return PyUnicode_FromFormat("<bpy_struct, %.200s at %p>", RNA_struct_identifier(self->ptr.type), self->ptr.data);
797 static PyObject *pyrna_struct_repr(BPy_StructRNA *self)
799 ID *id= self->ptr.id.data;
800 if(id == NULL || !PYRNA_STRUCT_IS_VALID(self))
801 return pyrna_struct_str(self); /* fallback */
803 if(RNA_struct_is_ID(self->ptr.type)) {
804 return PyUnicode_FromFormat("bpy.data.%s[\"%s\"]", BKE_idcode_to_name_plural(GS(id->name)), id->name+2);
809 path= RNA_path_from_ID_to_struct(&self->ptr);
811 ret= PyUnicode_FromFormat("bpy.data.%s[\"%s\"].%s", BKE_idcode_to_name_plural(GS(id->name)), id->name+2, path);
812 MEM_freeN((void *)path);
814 else { /* cant find, print something sane */
815 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));
822 static PyObject *pyrna_prop_str(BPy_PropertyRNA *self)
827 const char *type_id= NULL;
828 char type_fmt[64]= "";
831 PYRNA_PROP_CHECK_OBJ(self)
833 type= RNA_property_type(self->prop);
835 if(RNA_enum_id_from_value(property_type_items, type, &type_id)==0) {
836 PyErr_SetString(PyExc_RuntimeError, "could not use property type, internal error"); /* should never happen */
840 /* this should never fail */
844 while ((*c++= tolower(*type_id++))) {} ;
846 if(type==PROP_COLLECTION) {
847 len= pyrna_prop_collection_length(self);
849 else if (RNA_property_array_check(&self->ptr, self->prop)) {
850 len= pyrna_prop_array_length((BPy_PropertyArrayRNA *)self);
854 sprintf(--c, "[%d]", len);
857 /* if a pointer, try to print name of pointer target too */
858 if(RNA_property_type(self->prop) == PROP_POINTER) {
859 ptr= RNA_property_pointer_get(&self->ptr, self->prop);
860 name= RNA_struct_name_get_alloc(&ptr, NULL, FALSE);
863 ret= PyUnicode_FromFormat("<bpy_%.200s, %.200s.%.200s(\"%.200s\")>", type_fmt, RNA_struct_identifier(self->ptr.type), RNA_property_identifier(self->prop), name);
864 MEM_freeN((void *)name);
868 if(RNA_property_type(self->prop) == PROP_COLLECTION) {
870 if(RNA_property_collection_type_get(&self->ptr, self->prop, &r_ptr)) {
871 return PyUnicode_FromFormat("<bpy_%.200s, %.200s>", type_fmt, RNA_struct_identifier(r_ptr.type));
875 return PyUnicode_FromFormat("<bpy_%.200s, %.200s.%.200s>", type_fmt, RNA_struct_identifier(self->ptr.type), RNA_property_identifier(self->prop));
878 static PyObject *pyrna_prop_repr(BPy_PropertyRNA *self)
884 PYRNA_PROP_CHECK_OBJ(self)
886 if((id= self->ptr.id.data) == NULL)
887 return pyrna_prop_str(self); /* fallback */
889 path= RNA_path_from_ID_to_property(&self->ptr, self->prop);
891 ret= PyUnicode_FromFormat("bpy.data.%s[\"%s\"].%s", BKE_idcode_to_name_plural(GS(id->name)), id->name+2, path);
892 MEM_freeN((void *)path);
894 else { /* cant find, print something sane */
895 ret= PyUnicode_FromFormat("bpy.data.%s[\"%s\"]...%s", BKE_idcode_to_name_plural(GS(id->name)), id->name+2, RNA_property_identifier(self->prop));
901 static long pyrna_struct_hash(BPy_StructRNA *self)
903 return _Py_HashPointer(self->ptr.data);
906 /* from python's meth_hash v3.1.2 */
907 static long pyrna_prop_hash(BPy_PropertyRNA *self)
910 if (self->ptr.data == NULL)
913 x= _Py_HashPointer(self->ptr.data);
917 y= _Py_HashPointer((void*)(self->prop));
926 #ifdef USE_PYRNA_STRUCT_REFERENCE
927 static int pyrna_struct_traverse(BPy_StructRNA *self, visitproc visit, void *arg)
929 Py_VISIT(self->reference);
933 static int pyrna_struct_clear(BPy_StructRNA *self)
935 Py_CLEAR(self->reference);
938 #endif /* !USE_PYRNA_STRUCT_REFERENCE */
940 /* use our own dealloc so we can free a property if we use one */
941 static void pyrna_struct_dealloc(BPy_StructRNA *self)
943 if (self->freeptr && self->ptr.data) {
944 IDP_FreeProperty(self->ptr.data);
945 MEM_freeN(self->ptr.data);
946 self->ptr.data= NULL;
950 if (self->in_weakreflist != NULL) {
951 PyObject_ClearWeakRefs((PyObject *)self);
955 #ifdef USE_PYRNA_STRUCT_REFERENCE
956 if(self->reference) {
957 PyObject_GC_UnTrack(self);
958 pyrna_struct_clear(self);
960 #endif /* !USE_PYRNA_STRUCT_REFERENCE */
962 /* Note, for subclassed PyObjects we cant just call PyObject_DEL() directly or it will crash */
963 Py_TYPE(self)->tp_free(self);
966 #ifdef USE_PYRNA_STRUCT_REFERENCE
967 static void pyrna_struct_reference_set(BPy_StructRNA *self, PyObject *reference)
969 if(self->reference) {
970 // PyObject_GC_UnTrack(self); /* INITIALIZED TRACKED? */
971 pyrna_struct_clear(self);
973 /* reference is now NULL */
976 self->reference= reference;
977 Py_INCREF(reference);
978 // PyObject_GC_Track(self); /* INITIALIZED TRACKED? */
981 #endif /* !USE_PYRNA_STRUCT_REFERENCE */
983 /* use our own dealloc so we can free a property if we use one */
984 static void pyrna_prop_dealloc(BPy_PropertyRNA *self)
987 if (self->in_weakreflist != NULL) {
988 PyObject_ClearWeakRefs((PyObject *)self);
991 /* Note, for subclassed PyObjects we cant just call PyObject_DEL() directly or it will crash */
992 Py_TYPE(self)->tp_free(self);
995 static void pyrna_prop_array_dealloc(BPy_PropertyRNA *self)
998 if (self->in_weakreflist != NULL) {
999 PyObject_ClearWeakRefs((PyObject *)self);
1002 /* Note, for subclassed PyObjects we cant just call PyObject_DEL() directly or it will crash */
1003 Py_TYPE(self)->tp_free(self);
1006 static const char *pyrna_enum_as_string(PointerRNA *ptr, PropertyRNA *prop)
1008 EnumPropertyItem *item;
1012 RNA_property_enum_items(BPy_GetContext(), ptr, prop, &item, NULL, &free);
1014 result= BPy_enum_as_string(item);
1027 static int pyrna_string_to_enum(PyObject *item, PointerRNA *ptr, PropertyRNA *prop, int *val, const char *error_prefix)
1029 const char *param= _PyUnicode_AsString(item);
1032 const char *enum_str= pyrna_enum_as_string(ptr, prop);
1033 PyErr_Format(PyExc_TypeError,
1034 "%.200s expected a string enum type in (%.200s)",
1035 error_prefix, enum_str);
1036 MEM_freeN((void *)enum_str);
1040 /* hack so that dynamic enums used for operator properties will be able to be built (i.e. context will be supplied to itemf)
1041 * and thus running defining operator buttons for such operators in UI will work */
1042 RNA_def_property_clear_flag(prop, PROP_ENUM_NO_CONTEXT);
1044 if (!RNA_property_enum_value(BPy_GetContext(), ptr, prop, param, val)) {
1045 const char *enum_str= pyrna_enum_as_string(ptr, prop);
1046 PyErr_Format(PyExc_TypeError,
1047 "%.200s enum \"%.200s\" not found in (%.200s)",
1048 error_prefix, param, enum_str);
1049 MEM_freeN((void *)enum_str);
1057 int pyrna_set_to_enum_bitfield(EnumPropertyItem *items, PyObject *value, int *r_value, const char *error_prefix)
1059 /* set of enum items, concatenate all values with OR */
1069 while (_PySet_NextEntry(value, &pos, &key, &hash)) {
1070 const char *param= _PyUnicode_AsString(key);
1073 PyErr_Format(PyExc_TypeError,
1074 "%.200s expected a string, not %.200s",
1075 error_prefix, Py_TYPE(key)->tp_name);
1078 if(pyrna_enum_value_from_id(items, param, &ret, error_prefix) < 0)
1088 static int pyrna_prop_to_enum_bitfield(PointerRNA *ptr, PropertyRNA *prop, PyObject *value, int *r_value, const char *error_prefix)
1090 EnumPropertyItem *item;
1096 RNA_property_enum_items(BPy_GetContext(), ptr, prop, &item, NULL, &free);
1099 ret= pyrna_set_to_enum_bitfield(item, value, r_value, error_prefix);
1102 if(PySet_GET_SIZE(value)) {
1103 PyErr_Format(PyExc_TypeError,
1104 "%.200s: empty enum \"%.200s\" could not have any values assigned",
1105 error_prefix, RNA_property_identifier(prop));
1119 PyObject *pyrna_enum_bitfield_to_py(EnumPropertyItem *items, int value)
1121 PyObject *ret= PySet_New(NULL);
1122 const char *identifier[RNA_ENUM_BITFLAG_SIZE + 1];
1124 if(RNA_enum_bitflag_identifiers(items, value, identifier)) {
1127 for(index=0; identifier[index]; index++) {
1128 item= PyUnicode_FromString(identifier[index]);
1129 PySet_Add(ret, item);
1137 static PyObject *pyrna_enum_to_py(PointerRNA *ptr, PropertyRNA *prop, int val)
1139 PyObject *item, *ret= NULL;
1141 if(RNA_property_flag(prop) & PROP_ENUM_FLAG) {
1142 const char *identifier[RNA_ENUM_BITFLAG_SIZE + 1];
1144 ret= PySet_New(NULL);
1146 if (RNA_property_enum_bitflag_identifiers(BPy_GetContext(), ptr, prop, val, identifier)) {
1149 for(index=0; identifier[index]; index++) {
1150 item= PyUnicode_FromString(identifier[index]);
1151 PySet_Add(ret, item);
1158 const char *identifier;
1159 if (RNA_property_enum_identifier(BPy_GetContext(), ptr, prop, val, &identifier)) {
1160 ret= PyUnicode_FromString(identifier);
1163 EnumPropertyItem *enum_item;
1166 /* don't throw error here, can't trust blender 100% to give the
1167 * right values, python code should not generate error for that */
1168 RNA_property_enum_items(BPy_GetContext(), ptr, prop, &enum_item, NULL, &free);
1169 if(enum_item && enum_item->identifier) {
1170 ret= PyUnicode_FromString(enum_item->identifier);
1173 const char *ptr_name= RNA_struct_name_get_alloc(ptr, NULL, FALSE);
1175 /* prefer not fail silently incase of api errors, maybe disable it later */
1176 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));
1178 #if 0 // gives python decoding errors while generating docs :(
1179 char error_str[256];
1180 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));
1181 PyErr_Warn(PyExc_RuntimeWarning, error_str);
1185 MEM_freeN((void *)ptr_name);
1187 ret= PyUnicode_FromString("");
1191 MEM_freeN(enum_item);
1193 PyErr_Format(PyExc_AttributeError,
1194 "RNA Error: Current value \"%d\" matches no enum", val);
1203 PyObject * pyrna_prop_to_py(PointerRNA *ptr, PropertyRNA *prop)
1206 int type= RNA_property_type(prop);
1208 if (RNA_property_array_check(ptr, prop)) {
1209 return pyrna_py_from_array(ptr, prop);
1212 /* see if we can coorce into a python type - PropertyType */
1215 ret= PyBool_FromLong(RNA_property_boolean_get(ptr, prop));
1218 ret= PyLong_FromSsize_t((Py_ssize_t)RNA_property_int_get(ptr, prop));
1221 ret= PyFloat_FromDouble(RNA_property_float_get(ptr, prop));
1225 int subtype= RNA_property_subtype(prop);
1227 buf= RNA_property_string_get_alloc(ptr, prop, NULL, -1);
1228 #ifdef USE_STRING_COERCE
1229 /* only file paths get special treatment, they may contain non utf-8 chars */
1230 if(ELEM3(subtype, PROP_FILEPATH, PROP_DIRPATH, PROP_FILENAME)) {
1231 ret= PyC_UnicodeFromByte(buf);
1234 ret= PyUnicode_FromString(buf);
1236 #else // USE_STRING_COERCE
1237 ret= PyUnicode_FromString(buf);
1238 #endif // USE_STRING_COERCE
1239 MEM_freeN((void *)buf);
1244 ret= pyrna_enum_to_py(ptr, prop, RNA_property_enum_get(ptr, prop));
1250 newptr= RNA_property_pointer_get(ptr, prop);
1252 ret= pyrna_struct_CreatePyObject(&newptr);
1260 case PROP_COLLECTION:
1261 ret= pyrna_prop_CreatePyObject(ptr, prop);
1264 PyErr_Format(PyExc_TypeError,
1265 "bpy_struct internal error: unknown type '%d' (pyrna_prop_to_py)", type);
1273 /* This function is used by operators and converting dicts into collections.
1274 * Its takes keyword args and fills them with property values */
1275 int pyrna_pydict_to_props(PointerRNA *ptr, PyObject *kw, int all_args, const char *error_prefix)
1279 const char *arg_name= NULL;
1282 totkw= kw ? PyDict_Size(kw):0;
1284 RNA_STRUCT_BEGIN(ptr, prop) {
1285 arg_name= RNA_property_identifier(prop);
1287 if (strcmp(arg_name, "rna_type")==0) continue;
1290 PyErr_Format(PyExc_TypeError,
1291 "%.200s: no keywords, expected \"%.200s\"",
1292 error_prefix, arg_name ? arg_name : "<UNKNOWN>");
1297 item= PyDict_GetItemString(kw, arg_name); /* wont set an error */
1301 PyErr_Format(PyExc_TypeError,
1302 "%.200s: keyword \"%.200s\" missing",
1303 error_prefix, arg_name ? arg_name : "<UNKNOWN>");
1304 error_val= -1; /* pyrna_py_to_prop sets the error */
1309 if (pyrna_py_to_prop(ptr, prop, NULL, item, error_prefix)) {
1318 if (error_val==0 && totkw > 0) { /* some keywords were given that were not used :/ */
1319 PyObject *key, *value;
1322 while (PyDict_Next(kw, &pos, &key, &value)) {
1323 arg_name= _PyUnicode_AsString(key);
1324 if (RNA_struct_find_property(ptr, arg_name) == NULL) break;
1328 PyErr_Format(PyExc_TypeError,
1329 "%.200s: keyword \"%.200s\" unrecognized",
1330 error_prefix, arg_name ? arg_name : "<UNKNOWN>");
1337 static PyObject * pyrna_func_call(PyObject *self, PyObject *args, PyObject *kw);
1339 static PyObject *pyrna_func_to_py(BPy_DummyPointerRNA *pyrna, FunctionRNA *func)
1341 static PyMethodDef func_meth= {"<generic rna function>", (PyCFunction)pyrna_func_call, METH_VARARGS|METH_KEYWORDS, "python rna function"};
1346 PyErr_Format(PyExc_RuntimeError,
1347 "%.200s: type attempted to get NULL function",
1348 RNA_struct_identifier(pyrna->ptr.type));
1352 self= PyTuple_New(2);
1354 PyTuple_SET_ITEM(self, 0, (PyObject *)pyrna);
1357 PyTuple_SET_ITEM(self, 1, PyCapsule_New((void *)func, NULL, NULL));
1359 ret= PyCFunction_New(&func_meth, self);
1367 static int pyrna_py_to_prop(PointerRNA *ptr, PropertyRNA *prop, void *data, PyObject *value, const char *error_prefix)
1369 /* XXX hard limits should be checked here */
1370 int type= RNA_property_type(prop);
1373 if (RNA_property_array_check(ptr, prop)) {
1376 /* done getting the length */
1377 ok= pyrna_py_to_array(ptr, prop, data, value, error_prefix);
1384 /* Normal Property (not an array) */
1386 /* see if we can coorce into a python type - PropertyType */
1391 /* prefer not to have an exception here
1392 * however so many poll functions return None or a valid Object.
1393 * its a hassle to convert these into a bool before returning, */
1394 if(RNA_property_flag(prop) & PROP_OUTPUT)
1395 param= PyObject_IsTrue(value);
1397 param= PyLong_AsLong(value);
1400 PyErr_Format(PyExc_TypeError,
1401 "%.200s %.200s.%.200s expected True/False or 0/1, not %.200s",
1402 error_prefix, RNA_struct_identifier(ptr->type),
1403 RNA_property_identifier(prop), Py_TYPE(value)->tp_name);
1407 if(data) *((int*)data)= param;
1408 else RNA_property_boolean_set(ptr, prop, param);
1415 long param= PyLong_AsLongAndOverflow(value, &overflow);
1416 if(overflow || (param > INT_MAX) || (param < INT_MIN)) {
1417 PyErr_Format(PyExc_ValueError,
1418 "%.200s %.200s.%.200s value not in 'int' range "
1419 "(" STRINGIFY(INT_MIN) ", " STRINGIFY(INT_MAX) ")",
1420 error_prefix, RNA_struct_identifier(ptr->type),
1421 RNA_property_identifier(prop));
1424 else if (param==-1 && PyErr_Occurred()) {
1425 PyErr_Format(PyExc_TypeError,
1426 "%.200s %.200s.%.200s expected an int type, not %.200s",
1427 error_prefix, RNA_struct_identifier(ptr->type),
1428 RNA_property_identifier(prop), Py_TYPE(value)->tp_name);
1432 int param_i= (int)param;
1433 RNA_property_int_clamp(ptr, prop, ¶m_i);
1434 if(data) *((int*)data)= param_i;
1435 else RNA_property_int_set(ptr, prop, param_i);
1441 float param= PyFloat_AsDouble(value);
1442 if (PyErr_Occurred()) {
1443 PyErr_Format(PyExc_TypeError,
1444 "%.200s %.200s.%.200s expected a float type, not %.200s",
1445 error_prefix, RNA_struct_identifier(ptr->type),
1446 RNA_property_identifier(prop), Py_TYPE(value)->tp_name);
1450 RNA_property_float_clamp(ptr, prop, (float *)¶m);
1451 if(data) *((float*)data)= param;
1452 else RNA_property_float_set(ptr, prop, param);
1459 #ifdef USE_STRING_COERCE
1460 PyObject *value_coerce= NULL;
1461 int subtype= RNA_property_subtype(prop);
1462 if(ELEM3(subtype, PROP_FILEPATH, PROP_DIRPATH, PROP_FILENAME)) {
1463 /* TODO, get size */
1464 param= PyC_UnicodeAsByte(value, &value_coerce);
1467 param= _PyUnicode_AsString(value);
1469 #else // USE_STRING_COERCE
1470 param= _PyUnicode_AsStringSize(value);
1471 #endif // USE_STRING_COERCE
1474 PyErr_Format(PyExc_TypeError,
1475 "%.200s %.200s.%.200s expected a string type, not %.200s",
1476 error_prefix, RNA_struct_identifier(ptr->type),
1477 RNA_property_identifier(prop), Py_TYPE(value)->tp_name);
1481 if(data) *((char**)data)= (char *)param; /*XXX, this is suspect but needed for function calls, need to see if theres a better way */
1482 else RNA_property_string_set(ptr, prop, param);
1484 #ifdef USE_STRING_COERCE
1485 Py_XDECREF(value_coerce);
1486 #endif // USE_STRING_COERCE
1493 if (PyUnicode_Check(value)) {
1494 if (!pyrna_string_to_enum(value, ptr, prop, &val, error_prefix))
1497 else if (PyAnySet_Check(value)) {
1498 if(RNA_property_flag(prop) & PROP_ENUM_FLAG) {
1499 /* set of enum items, concatenate all values with OR */
1500 if(pyrna_prop_to_enum_bitfield(ptr, prop, value, &val, error_prefix) < 0)
1504 PyErr_Format(PyExc_TypeError,
1505 "%.200s, %.200s.%.200s is not a bitflag enum type",
1506 error_prefix, RNA_struct_identifier(ptr->type),
1507 RNA_property_identifier(prop));
1512 const char *enum_str= pyrna_enum_as_string(ptr, prop);
1513 PyErr_Format(PyExc_TypeError,
1514 "%.200s %.200s.%.200s expected a string enum or a set of strings in (%.2000s), not %.200s",
1515 error_prefix, RNA_struct_identifier(ptr->type),
1516 RNA_property_identifier(prop), enum_str,
1517 Py_TYPE(value)->tp_name);
1518 MEM_freeN((void *)enum_str);
1522 if(data) *((int*)data)= val;
1523 else RNA_property_enum_set(ptr, prop, val);
1529 PyObject *value_new= NULL;
1531 StructRNA *ptr_type= RNA_property_pointer_type(ptr, prop);
1532 int flag= RNA_property_flag(prop);
1534 /* this is really nasty!, so we can fake the operator having direct properties eg:
1535 * layout.prop(self, "filepath")
1536 * ... which infact should be
1537 * layout.prop(self.properties, "filepath")
1539 * we need to do this trick.
1540 * if the prop is not an operator type and the pyobject is an operator, use its properties in place of its self.
1542 * this is so bad that its almost a good reason to do away with fake 'self.properties -> self' class mixing
1543 * if this causes problems in the future it should be removed.
1545 if( (ptr_type == &RNA_AnyType) &&
1546 (BPy_StructRNA_Check(value)) &&
1547 (RNA_struct_is_a(((BPy_StructRNA *)value)->ptr.type, &RNA_Operator))
1549 value= PyObject_GetAttrString(value, "properties");
1554 /* if property is an OperatorProperties pointer and value is a map, forward back to pyrna_pydict_to_props */
1555 if (RNA_struct_is_a(ptr_type, &RNA_OperatorProperties) && PyDict_Check(value)) {
1556 PointerRNA opptr= RNA_property_pointer_get(ptr, prop);
1557 return pyrna_pydict_to_props(&opptr, value, 0, error_prefix);
1560 /* another exception, allow to pass a collection as an RNA property */
1561 if(Py_TYPE(value)==&pyrna_prop_collection_Type) { /* ok to ignore idprop collections */
1563 BPy_PropertyRNA *value_prop= (BPy_PropertyRNA *)value;
1564 if(RNA_property_collection_type_get(&value_prop->ptr, value_prop->prop, &c_ptr)) {
1565 value= pyrna_struct_CreatePyObject(&c_ptr);
1569 PyErr_Format(PyExc_TypeError,
1570 "%.200s %.200s.%.200s collection has no type, "
1571 "cant be used as a %.200s type",
1572 error_prefix, RNA_struct_identifier(ptr->type),
1573 RNA_property_identifier(prop), RNA_struct_identifier(ptr_type));
1578 if(!BPy_StructRNA_Check(value) && value != Py_None) {
1579 PyErr_Format(PyExc_TypeError,
1580 "%.200s %.200s.%.200s expected a %.200s type, not %.200s",
1581 error_prefix, RNA_struct_identifier(ptr->type),
1582 RNA_property_identifier(prop), RNA_struct_identifier(ptr_type),
1583 Py_TYPE(value)->tp_name);
1584 Py_XDECREF(value_new); return -1;
1586 else if((flag & PROP_NEVER_NULL) && value == Py_None) {
1587 PyErr_Format(PyExc_TypeError,
1588 "%.200s %.200s.%.200s does not support a 'None' assignment %.200s type",
1589 error_prefix, RNA_struct_identifier(ptr->type),
1590 RNA_property_identifier(prop), RNA_struct_identifier(ptr_type));
1591 Py_XDECREF(value_new); return -1;
1593 else if(value != Py_None && ((flag & PROP_ID_SELF_CHECK) && ptr->id.data == ((BPy_StructRNA*)value)->ptr.id.data)) {
1594 PyErr_Format(PyExc_TypeError,
1595 "%.200s %.200s.%.200s ID type does not support assignment to its self",
1596 error_prefix, RNA_struct_identifier(ptr->type),
1597 RNA_property_identifier(prop));
1598 Py_XDECREF(value_new); return -1;
1601 BPy_StructRNA *param= (BPy_StructRNA*)value;
1602 int raise_error= FALSE;
1605 if(flag & PROP_RNAPTR) {
1606 if(value == Py_None)
1607 memset(data, 0, sizeof(PointerRNA));
1609 *((PointerRNA*)data)= param->ptr;
1611 else if(value == Py_None) {
1612 *((void**)data)= NULL;
1614 else if(RNA_struct_is_a(param->ptr.type, ptr_type)) {
1615 *((void**)data)= param->ptr.data;
1622 /* data==NULL, assign to RNA */
1623 if(value == Py_None) {
1624 PointerRNA valueptr= {{NULL}};
1625 RNA_property_pointer_set(ptr, prop, valueptr);
1627 else if(RNA_struct_is_a(param->ptr.type, ptr_type)) {
1628 RNA_property_pointer_set(ptr, prop, param->ptr);
1632 RNA_pointer_create(NULL, ptr_type, NULL, &tmp);
1633 PyErr_Format(PyExc_TypeError,
1634 "%.200s %.200s.%.200s expected a %.200s type. not %.200s",
1635 error_prefix, RNA_struct_identifier(ptr->type),
1636 RNA_property_identifier(prop), RNA_struct_identifier(tmp.type),
1637 RNA_struct_identifier(param->ptr.type));
1638 Py_XDECREF(value_new); return -1;
1644 RNA_pointer_create(NULL, ptr_type, NULL, &tmp);
1645 PyErr_Format(PyExc_TypeError,
1646 "%.200s %.200s.%.200s expected a %.200s type, not %.200s",
1647 error_prefix, RNA_struct_identifier(ptr->type),
1648 RNA_property_identifier(prop), RNA_struct_identifier(tmp.type),
1649 RNA_struct_identifier(param->ptr.type));
1650 Py_XDECREF(value_new); return -1;
1654 Py_XDECREF(value_new);
1658 case PROP_COLLECTION:
1664 CollectionPointerLink *link;
1666 lb= (data)? (ListBase*)data: NULL;
1668 /* convert a sequence of dict's into a collection */
1669 if(!PySequence_Check(value)) {
1670 PyErr_Format(PyExc_TypeError,
1671 "%.200s %.200s.%.200s expected a sequence for an RNA collection, not %.200s",
1672 error_prefix, RNA_struct_identifier(ptr->type),
1673 RNA_property_identifier(prop), Py_TYPE(value)->tp_name);
1677 seq_len= PySequence_Size(value);
1678 for(i=0; i<seq_len; i++) {
1679 item= PySequence_GetItem(value, i);
1682 PyErr_Format(PyExc_TypeError,
1683 "%.200s %.200s.%.200s failed to get sequence index '%d' for an RNA collection",
1684 error_prefix, RNA_struct_identifier(ptr->type),
1685 RNA_property_identifier(prop), i);
1690 if(PyDict_Check(item)==0) {
1691 PyErr_Format(PyExc_TypeError,
1692 "%.200s %.200s.%.200s expected a each sequence "
1693 "member to be a dict for an RNA collection, not %.200s",
1694 error_prefix, RNA_struct_identifier(ptr->type),
1695 RNA_property_identifier(prop), Py_TYPE(item)->tp_name);
1701 link= MEM_callocN(sizeof(CollectionPointerLink), "PyCollectionPointerLink");
1703 BLI_addtail(lb, link);
1706 RNA_property_collection_add(ptr, prop, &itemptr);
1708 if(pyrna_pydict_to_props(&itemptr, item, 1, "Converting a python list to an RNA collection")==-1) {
1709 PyObject *msg= PyC_ExceptionBuffer();
1710 const char *msg_char= _PyUnicode_AsString(msg);
1712 PyErr_Format(PyExc_TypeError,
1713 "%.200s %.200s.%.200s error converting a member of a collection "
1714 "from a dicts into an RNA collection, failed with: %s",
1715 error_prefix, RNA_struct_identifier(ptr->type),
1716 RNA_property_identifier(prop), msg_char);
1728 PyErr_Format(PyExc_AttributeError,
1729 "%.200s %.200s.%.200s unknown property type (pyrna_py_to_prop)",
1730 error_prefix, RNA_struct_identifier(ptr->type),
1731 RNA_property_identifier(prop));
1737 /* Run rna property functions */
1738 if(RNA_property_update_check(prop)) {
1739 RNA_property_update(BPy_GetContext(), ptr, prop);
1745 static PyObject *pyrna_prop_array_to_py_index(BPy_PropertyArrayRNA *self, int index)
1747 PYRNA_PROP_CHECK_OBJ((BPy_PropertyRNA *)self)
1748 return pyrna_py_from_array_index(self, &self->ptr, self->prop, index);
1751 static int pyrna_py_to_prop_array_index(BPy_PropertyArrayRNA *self, int index, PyObject *value)
1754 PointerRNA *ptr= &self->ptr;
1755 PropertyRNA *prop= self->prop;
1757 const int totdim= RNA_property_array_dimension(ptr, prop, NULL);
1760 /* char error_str[512]; */
1761 if (!pyrna_py_to_array_index(&self->ptr, self->prop, self->arraydim, self->arrayoffset, index, value, "")) {
1762 /* PyErr_SetString(PyExc_AttributeError, error_str); */
1767 /* see if we can coerce into a python type - PropertyType */
1768 switch (RNA_property_type(prop)) {
1771 int param= PyLong_AsLong(value);
1773 if(param < 0 || param > 1) {
1774 PyErr_SetString(PyExc_TypeError, "expected True/False or 0/1");
1778 RNA_property_boolean_set_index(ptr, prop, index, param);
1784 int param= PyLong_AsLong(value);
1785 if (param==-1 && PyErr_Occurred()) {
1786 PyErr_SetString(PyExc_TypeError, "expected an int type");
1790 RNA_property_int_clamp(ptr, prop, ¶m);
1791 RNA_property_int_set_index(ptr, prop, index, param);
1797 float param= PyFloat_AsDouble(value);
1798 if (PyErr_Occurred()) {
1799 PyErr_SetString(PyExc_TypeError, "expected a float type");
1803 RNA_property_float_clamp(ptr, prop, ¶m);
1804 RNA_property_float_set_index(ptr, prop, index, param);
1809 PyErr_SetString(PyExc_AttributeError, "not an array type");
1815 /* Run rna property functions */
1816 if(RNA_property_update_check(prop)) {
1817 RNA_property_update(BPy_GetContext(), ptr, prop);
1823 //---------------sequence-------------------------------------------
1824 static Py_ssize_t pyrna_prop_array_length(BPy_PropertyArrayRNA *self)
1826 PYRNA_PROP_CHECK_INT((BPy_PropertyRNA *)self)
1828 if (RNA_property_array_dimension(&self->ptr, self->prop, NULL) > 1)
1829 return RNA_property_multi_array_length(&self->ptr, self->prop, self->arraydim);
1831 return RNA_property_array_length(&self->ptr, self->prop);
1834 static Py_ssize_t pyrna_prop_collection_length(BPy_PropertyRNA *self)
1836 PYRNA_PROP_CHECK_INT(self)
1838 return RNA_property_collection_length(&self->ptr, self->prop);
1841 /* bool functions are for speed, so we can avoid getting the length
1842 * of 1000's of items in a linked list for eg. */
1843 static int pyrna_prop_array_bool(BPy_PropertyRNA *self)
1845 PYRNA_PROP_CHECK_INT(self)
1847 return RNA_property_array_length(&self->ptr, self->prop) ? 1 : 0;
1850 static int pyrna_prop_collection_bool(BPy_PropertyRNA *self)
1852 /* no callback defined, just iterate and find the nth item */
1853 CollectionPropertyIterator iter;
1856 PYRNA_PROP_CHECK_INT(self)
1858 RNA_property_collection_begin(&self->ptr, self->prop, &iter);
1860 RNA_property_collection_end(&iter);
1864 /* internal use only */
1865 static PyObject *pyrna_prop_collection_subscript_int(BPy_PropertyRNA *self, Py_ssize_t keynum)
1868 Py_ssize_t keynum_abs= keynum;
1870 PYRNA_PROP_CHECK_OBJ(self)
1872 /* notice getting the length of the collection is avoided unless negative index is used
1873 * or to detect internal error with a valid index.
1874 * This is done for faster lookups. */
1876 keynum_abs += RNA_property_collection_length(&self->ptr, self->prop);
1878 if(keynum_abs < 0) {
1879 PyErr_Format(PyExc_IndexError, "bpy_prop_collection[%d]: out of range.", keynum);
1884 if(RNA_property_collection_lookup_int(&self->ptr, self->prop, keynum_abs, &newptr)) {
1885 return pyrna_struct_CreatePyObject(&newptr);
1888 const int len= RNA_property_collection_length(&self->ptr, self->prop);
1889 if(keynum_abs >= len) {
1890 PyErr_Format(PyExc_IndexError,
1891 "bpy_prop_collection[index]: "
1892 "index %d out of range, size %d", keynum, len);
1895 PyErr_Format(PyExc_RuntimeError,
1896 "bpy_prop_collection[index]: internal error, "
1897 "valid index %d given in %d sized collection but value not found",
1905 static PyObject *pyrna_prop_array_subscript_int(BPy_PropertyArrayRNA *self, int keynum)
1909 PYRNA_PROP_CHECK_OBJ((BPy_PropertyRNA *)self)
1911 len= pyrna_prop_array_length(self);
1913 if(keynum < 0) keynum += len;
1915 if(keynum >= 0 && keynum < len)
1916 return pyrna_prop_array_to_py_index(self, keynum);
1918 PyErr_Format(PyExc_IndexError, "bpy_prop_array[index]: index %d out of range", keynum);
1922 static PyObject *pyrna_prop_collection_subscript_str(BPy_PropertyRNA *self, const char *keyname)
1926 PYRNA_PROP_CHECK_OBJ(self)
1928 if(RNA_property_collection_lookup_string(&self->ptr, self->prop, keyname, &newptr))
1929 return pyrna_struct_CreatePyObject(&newptr);
1931 PyErr_Format(PyExc_KeyError, "bpy_prop_collection[key]: key \"%.200s\" not found", keyname);
1934 /* static PyObject *pyrna_prop_array_subscript_str(BPy_PropertyRNA *self, char *keyname) */
1936 static PyObject *pyrna_prop_collection_subscript_slice(BPy_PropertyRNA *self, Py_ssize_t start, Py_ssize_t stop)
1938 CollectionPropertyIterator rna_macro_iter;
1944 PYRNA_PROP_CHECK_OBJ(self)
1946 list= PyList_New(0);
1948 /* first loop up-until the start */
1949 for(RNA_property_collection_begin(&self->ptr, self->prop, &rna_macro_iter); rna_macro_iter.valid; RNA_property_collection_next(&rna_macro_iter)) {
1950 /* PointerRNA itemptr= rna_macro_iter.ptr; */
1951 if(count == start) {
1957 /* add items until stop */
1958 for(; rna_macro_iter.valid; RNA_property_collection_next(&rna_macro_iter)) {
1959 item= pyrna_struct_CreatePyObject(&rna_macro_iter.ptr);
1960 PyList_Append(list, item);
1969 RNA_property_collection_end(&rna_macro_iter);
1974 /* TODO - dimensions
1975 * note: could also use pyrna_prop_array_to_py_index(self, count) in a loop but its a lot slower
1976 * since at the moment it reads (and even allocates) the entire array for each index.
1978 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)
1983 PYRNA_PROP_CHECK_OBJ((BPy_PropertyRNA *)self)
1985 tuple= PyTuple_New(stop - start);
1987 /* PYRNA_PROP_CHECK_OBJ(self) isn't needed, internal use only */
1989 totdim= RNA_property_array_dimension(ptr, prop, NULL);
1992 for (count= start; count < stop; count++)
1993 PyTuple_SET_ITEM(tuple, count - start, pyrna_prop_array_to_py_index(self, count));
1996 switch (RNA_property_type(prop)) {
1999 float values_stack[PYRNA_STACK_ARRAY];
2001 if(length > PYRNA_STACK_ARRAY) { values= PyMem_MALLOC(sizeof(float) * length); }
2002 else { values= values_stack; }
2003 RNA_property_float_get_array(ptr, prop, values);
2005 for(count=start; count<stop; count++)
2006 PyTuple_SET_ITEM(tuple, count-start, PyFloat_FromDouble(values[count]));
2008 if(values != values_stack) {
2015 int values_stack[PYRNA_STACK_ARRAY];
2017 if(length > PYRNA_STACK_ARRAY) { values= PyMem_MALLOC(sizeof(int) * length); }
2018 else { values= values_stack; }
2020 RNA_property_boolean_get_array(ptr, prop, values);
2021 for(count=start; count<stop; count++)
2022 PyTuple_SET_ITEM(tuple, count-start, PyBool_FromLong(values[count]));
2024 if(values != values_stack) {
2031 int values_stack[PYRNA_STACK_ARRAY];
2033 if(length > PYRNA_STACK_ARRAY) { values= PyMem_MALLOC(sizeof(int) * length); }
2034 else { values= values_stack; }
2036 RNA_property_int_get_array(ptr, prop, values);
2037 for(count=start; count<stop; count++)
2038 PyTuple_SET_ITEM(tuple, count-start, PyLong_FromSsize_t(values[count]));
2040 if(values != values_stack) {
2046 BLI_assert(!"Invalid array type");
2048 PyErr_SetString(PyExc_TypeError, "not an array type");
2056 static PyObject *pyrna_prop_collection_subscript(BPy_PropertyRNA *self, PyObject *key)
2058 PYRNA_PROP_CHECK_OBJ(self)
2060 if (PyUnicode_Check(key)) {
2061 return pyrna_prop_collection_subscript_str(self, _PyUnicode_AsString(key));
2063 else if (PyIndex_Check(key)) {
2064 Py_ssize_t i= PyNumber_AsSsize_t(key, PyExc_IndexError);
2065 if (i == -1 && PyErr_Occurred())
2068 return pyrna_prop_collection_subscript_int(self, i);
2070 else if (PySlice_Check(key)) {
2071 PySliceObject *key_slice= (PySliceObject *)key;
2074 if(key_slice->step != Py_None && !_PyEval_SliceIndex(key, &step)) {
2077 else if (step != 1) {
2078 PyErr_SetString(PyExc_TypeError, "bpy_prop_collection[slice]: slice steps not supported");
2081 else if(key_slice->start == Py_None && key_slice->stop == Py_None) {
2082 return pyrna_prop_collection_subscript_slice(self, 0, PY_SSIZE_T_MAX);
2085 Py_ssize_t start= 0, stop= PY_SSIZE_T_MAX;
2087 /* avoid PySlice_GetIndicesEx because it needs to know the length ahead of time. */
2088 if(key_slice->start != Py_None && !_PyEval_SliceIndex(key_slice->start, &start)) return NULL;
2089 if(key_slice->stop != Py_None && !_PyEval_SliceIndex(key_slice->stop, &stop)) return NULL;
2091 if(start < 0 || stop < 0) {
2092 /* only get the length for negative values */
2093 Py_ssize_t len= (Py_ssize_t)RNA_property_collection_length(&self->ptr, self->prop);
2094 if(start < 0) start += len;
2095 if(stop < 0) start += len;
2098 if (stop - start <= 0) {
2099 return PyList_New(0);
2102 return pyrna_prop_collection_subscript_slice(self, start, stop);
2107 PyErr_Format(PyExc_TypeError,
2108 "bpy_prop_collection[key]: invalid key, "
2109 "must be a string or an int, not %.200s",
2110 Py_TYPE(key)->tp_name);
2115 static PyObject *pyrna_prop_array_subscript(BPy_PropertyArrayRNA *self, PyObject *key)
2117 PYRNA_PROP_CHECK_OBJ((BPy_PropertyRNA *)self)
2119 /*if (PyUnicode_Check(key)) {
2120 return pyrna_prop_array_subscript_str(self, _PyUnicode_AsString(key));
2123 if (PyIndex_Check(key)) {
2124 Py_ssize_t i= PyNumber_AsSsize_t(key, PyExc_IndexError);
2125 if (i == -1 && PyErr_Occurred())
2127 return pyrna_prop_array_subscript_int(self, PyLong_AsLong(key));
2129 else if (PySlice_Check(key)) {
2131 PySliceObject *key_slice= (PySliceObject *)key;
2133 if(key_slice->step != Py_None && !_PyEval_SliceIndex(key, &step)) {
2136 else if (step != 1) {
2137 PyErr_SetString(PyExc_TypeError, "bpy_prop_array[slice]: slice steps not supported");
2140 else if(key_slice->start == Py_None && key_slice->stop == Py_None) {
2141 /* note, no significant advantage with optimizing [:] slice as with collections but include here for consistency with collection slice func */
2142 Py_ssize_t len= (Py_ssize_t)pyrna_prop_array_length(self);
2143 return pyrna_prop_array_subscript_slice(self, &self->ptr, self->prop, 0, len, len);
2146 int len= pyrna_prop_array_length(self);
2147 Py_ssize_t start, stop, slicelength;
2149 if (PySlice_GetIndicesEx((void *)key, len, &start, &stop, &step, &slicelength) < 0)
2152 if (slicelength <= 0) {
2153 return PyTuple_New(0);
2156 return pyrna_prop_array_subscript_slice(self, &self->ptr, self->prop, start, stop, len);
2161 PyErr_SetString(PyExc_AttributeError, "bpy_prop_array[key]: invalid key, key must be an int");
2166 /* could call (pyrna_py_to_prop_array_index(self, i, value) in a loop but it is slow */
2167 static int prop_subscript_ass_array_slice(PointerRNA *ptr, PropertyRNA *prop, int start, int stop, int length, PyObject *value_orig)
2171 void *values_alloc= NULL;
2174 if(value_orig == NULL) {
2175 PyErr_SetString(PyExc_TypeError, "bpy_prop_array[slice]= value: deleting with list types is not supported by bpy_struct");
2179 if(!(value=PySequence_Fast(value_orig, "bpy_prop_array[slice]= value: assignment is not a sequence type"))) {
2183 if(PySequence_Fast_GET_SIZE(value) != stop-start) {
2185 PyErr_SetString(PyExc_TypeError, "bpy_prop_array[slice]= value: resizing bpy_struct arrays isn't supported");
2189 switch (RNA_property_type(prop)) {
2192 float values_stack[PYRNA_STACK_ARRAY];
2193 float *values, fval;
2196 RNA_property_float_range(ptr, prop, &min, &max);
2198 if(length > PYRNA_STACK_ARRAY) { values= values_alloc= PyMem_MALLOC(sizeof(float) * length); }
2199 else { values= values_stack; }
2200 if(start != 0 || stop != length) /* partial assignment? - need to get the array */
2201 RNA_property_float_get_array(ptr, prop, values);
2203 for(count=start; count<stop; count++) {
2204 fval= PyFloat_AsDouble(PySequence_Fast_GET_ITEM(value, count-start));
2205 CLAMP(fval, min, max);
2206 values[count]= fval;
2209 if(PyErr_Occurred()) ret= -1;
2210 else RNA_property_float_set_array(ptr, prop, values);
2215 int values_stack[PYRNA_STACK_ARRAY];
2217 if(length > PYRNA_STACK_ARRAY) { values= values_alloc= PyMem_MALLOC(sizeof(int) * length); }
2218 else { values= values_stack; }
2220 if(start != 0 || stop != length) /* partial assignment? - need to get the array */
2221 RNA_property_boolean_get_array(ptr, prop, values);
2223 for(count=start; count<stop; count++)
2224 values[count]= PyLong_AsLong(PySequence_Fast_GET_ITEM(value, count-start));
2226 if(PyErr_Occurred()) ret= -1;
2227 else RNA_property_boolean_set_array(ptr, prop, values);
2232 int values_stack[PYRNA_STACK_ARRAY];
2236 RNA_property_int_range(ptr, prop, &min, &max);
2238 if(length > PYRNA_STACK_ARRAY) { values= values_alloc= PyMem_MALLOC(sizeof(int) * length); }
2239 else { values= values_stack; }
2241 if(start != 0 || stop != length) /* partial assignment? - need to get the array */
2242 RNA_property_int_get_array(ptr, prop, values);
2244 for(count=start; count<stop; count++) {
2245 ival= PyLong_AsLong(PySequence_Fast_GET_ITEM(value, count-start));
2246 CLAMP(ival, min, max);
2247 values[count]= ival;
2250 if(PyErr_Occurred()) ret= -1;
2251 else RNA_property_int_set_array(ptr, prop, values);
2255 PyErr_SetString(PyExc_TypeError, "not an array type");
2262 PyMem_FREE(values_alloc);
2269 static int prop_subscript_ass_array_int(BPy_PropertyArrayRNA *self, Py_ssize_t keynum, PyObject *value)
2273 PYRNA_PROP_CHECK_INT((BPy_PropertyRNA *)self)
2275 len= pyrna_prop_array_length(self);
2277 if(keynum < 0) keynum += len;
2279 if(keynum >= 0 && keynum < len)
2280 return pyrna_py_to_prop_array_index(self, keynum, value);
2282 PyErr_SetString(PyExc_IndexError, "bpy_prop_array[index] = value: index out of range");
2286 static int pyrna_prop_array_ass_subscript(BPy_PropertyArrayRNA *self, PyObject *key, PyObject *value)
2288 /* char *keyname= NULL; */ /* not supported yet */
2291 PYRNA_PROP_CHECK_INT((BPy_PropertyRNA *)self);
2293 if (!RNA_property_editable_flag(&self->ptr, self->prop)) {
2294 PyErr_Format(PyExc_AttributeError,
2295 "bpy_prop_collection: attribute \"%.200s\" from \"%.200s\" is read-only",
2296 RNA_property_identifier(self->prop), RNA_struct_identifier(self->ptr.type));
2300 else if (PyIndex_Check(key)) {
2301 Py_ssize_t i= PyNumber_AsSsize_t(key, PyExc_IndexError);
2302 if (i == -1 && PyErr_Occurred()) {
2306 ret= prop_subscript_ass_array_int(self, i, value);
2309 else if (PySlice_Check(key)) {
2310 int len= RNA_property_array_length(&self->ptr, self->prop);
2311 Py_ssize_t start, stop, step, slicelength;
2313 if (PySlice_GetIndicesEx((void *)key, len, &start, &stop, &step, &slicelength) < 0) {
2316 else if (slicelength <= 0) {
2317 ret= 0; /* do nothing */
2319 else if (step == 1) {
2320 ret= prop_subscript_ass_array_slice(&self->ptr, self->prop, start, stop, len, value);
2323 PyErr_SetString(PyExc_TypeError, "slice steps not supported with rna");
2328 PyErr_SetString(PyExc_AttributeError, "invalid key, key must be an int");
2333 if(RNA_property_update_check(self->prop)) {
2334 RNA_property_update(BPy_GetContext(), &self->ptr, self->prop);
2341 /* for slice only */
2342 static PyMappingMethods pyrna_prop_array_as_mapping= {
2343 (lenfunc) pyrna_prop_array_length, /* mp_length */
2344 (binaryfunc) pyrna_prop_array_subscript, /* mp_subscript */
2345 (objobjargproc) pyrna_prop_array_ass_subscript, /* mp_ass_subscript */
2348 static PyMappingMethods pyrna_prop_collection_as_mapping= {
2349 (lenfunc) pyrna_prop_collection_length, /* mp_length */
2350 (binaryfunc) pyrna_prop_collection_subscript, /* mp_subscript */
2351 (objobjargproc) NULL, /* mp_ass_subscript */
2354 /* only for fast bool's, large structs, assign nb_bool on init */
2355 static PyNumberMethods pyrna_prop_array_as_number= {
2357 NULL, /* nb_subtract */
2358 NULL, /* nb_multiply */
2359 NULL, /* nb_remainder */
2360 NULL, /* nb_divmod */
2361 NULL, /* nb_power */
2362 NULL, /* nb_negative */
2363 NULL, /* nb_positive */
2364 NULL, /* nb_absolute */
2365 (inquiry) pyrna_prop_array_bool, /* nb_bool */
2367 static PyNumberMethods pyrna_prop_collection_as_number= {
2369 NULL, /* nb_subtract */
2370 NULL, /* nb_multiply */
2371 NULL, /* nb_remainder */
2372 NULL, /* nb_divmod */
2373 NULL, /* nb_power */
2374 NULL, /* nb_negative */
2375 NULL, /* nb_positive */
2376 NULL, /* nb_absolute */
2377 (inquiry) pyrna_prop_collection_bool, /* nb_bool */
2380 static int pyrna_prop_array_contains(BPy_PropertyRNA *self, PyObject *value)
2382 return pyrna_array_contains_py(&self->ptr, self->prop, value);
2385 static int pyrna_prop_collection_contains(BPy_PropertyRNA *self, PyObject *value)
2387 PointerRNA newptr; /* not used, just so RNA_property_collection_lookup_string runs */
2389 /* key in dict style check */
2390 const char *keyname= _PyUnicode_AsString(value);
2393 PyErr_SetString(PyExc_TypeError, "bpy_prop_collection.__contains__: expected a string");
2397 if (RNA_property_collection_lookup_string(&self->ptr, self->prop, keyname, &newptr))
2403 static int pyrna_struct_contains(BPy_StructRNA *self, PyObject *value)
2406 const char *name= _PyUnicode_AsString(value);
2408 PYRNA_STRUCT_CHECK_INT(self)
2411 PyErr_SetString(PyExc_TypeError, "bpy_struct.__contains__: expected a string");
2415 if(RNA_struct_idprops_check(self->ptr.type)==0) {
2416 PyErr_SetString(PyExc_TypeError, "bpy_struct: this type doesn't support IDProperties");
2420 group= RNA_struct_idprops(&self->ptr, 0);
2425 return IDP_GetPropertyFromGroup(group, name) ? 1:0;
2428 static PySequenceMethods pyrna_prop_array_as_sequence= {
2429 (lenfunc)pyrna_prop_array_length, /* Cant set the len otherwise it can evaluate as false */
2430 NULL, /* sq_concat */
2431 NULL, /* sq_repeat */
2432 (ssizeargfunc)pyrna_prop_array_subscript_int, /* sq_item */ /* Only set this so PySequence_Check() returns True */
2433 NULL, /* sq_slice */
2434 (ssizeobjargproc)prop_subscript_ass_array_int, /* sq_ass_item */
2435 NULL, /* *was* sq_ass_slice */
2436 (objobjproc)pyrna_prop_array_contains, /* sq_contains */
2437 (binaryfunc) NULL, /* sq_inplace_concat */
2438 (ssizeargfunc) NULL, /* sq_inplace_repeat */
2441 static PySequenceMethods pyrna_prop_collection_as_sequence= {
2442 (lenfunc)pyrna_prop_collection_length, /* Cant set the len otherwise it can evaluate as false */
2443 NULL, /* sq_concat */
2444 NULL, /* sq_repeat */
2445 (ssizeargfunc)pyrna_prop_collection_subscript_int, /* sq_item */ /* Only set this so PySequence_Check() returns True */
2446 NULL, /* *was* sq_slice */
2447 NULL, /* sq_ass_item */
2448 NULL, /* *was* sq_ass_slice */
2449 (objobjproc)pyrna_prop_collection_contains, /* sq_contains */
2450 (binaryfunc) NULL, /* sq_inplace_concat */
2451 (ssizeargfunc) NULL, /* sq_inplace_repeat */
2454 static PySequenceMethods pyrna_struct_as_sequence= {
2455 NULL, /* Cant set the len otherwise it can evaluate as false */
2456 NULL, /* sq_concat */
2457 NULL, /* sq_repeat */
2458 NULL, /* sq_item */ /* Only set this so PySequence_Check() returns True */
2459 NULL, /* *was* sq_slice */
2460 NULL, /* sq_ass_item */
2461 NULL, /* *was* sq_ass_slice */
2462 (objobjproc)pyrna_struct_contains, /* sq_contains */
2463 (binaryfunc) NULL, /* sq_inplace_concat */
2464 (ssizeargfunc) NULL, /* sq_inplace_repeat */
2467 static PyObject *pyrna_struct_subscript(BPy_StructRNA *self, PyObject *key)
2469 /* mostly copied from BPy_IDGroup_Map_GetItem */
2470 IDProperty *group, *idprop;
2471 const char *name= _PyUnicode_AsString(key);
2473 PYRNA_STRUCT_CHECK_OBJ(self)
2475 if(RNA_struct_idprops_check(self->ptr.type)==0) {
2476 PyErr_SetString(PyExc_TypeError, "this type doesn't support IDProperties");
2481 PyErr_SetString(PyExc_TypeError, "bpy_struct[key]: only strings are allowed as keys of ID properties");
2485 group= RNA_struct_idprops(&self->ptr, 0);
2488 PyErr_Format(PyExc_KeyError, "bpy_struct[key]: key \"%s\" not found", name);
2492 idprop= IDP_GetPropertyFromGroup(group, name);
2495 PyErr_Format(PyExc_KeyError, "bpy_struct[key]: key \"%s\" not found", name);
2499 return BPy_IDGroup_WrapData(self->ptr.id.data, idprop);
2502 static int pyrna_struct_ass_subscript(BPy_StructRNA *self, PyObject *key, PyObject *value)
2506 PYRNA_STRUCT_CHECK_INT(self)
2508 group= RNA_struct_idprops(&self->ptr, 1);
2510 #ifdef USE_PEDANTIC_WRITE
2511 if(rna_disallow_writes && rna_id_write_error(&self->ptr, key)) {
2514 #endif // USE_STRING_COERCE
2517 PyErr_SetString(PyExc_TypeError, "bpy_struct[key]= val: id properties not supported for this type");
2521 return BPy_Wrap_SetMapItem(group, key, value);
2524 static PyMappingMethods pyrna_struct_as_mapping= {
2525 (lenfunc) NULL, /* mp_length */
2526 (binaryfunc) pyrna_struct_subscript, /* mp_subscript */
2527 (objobjargproc) pyrna_struct_ass_subscript, /* mp_ass_subscript */
2530 static char pyrna_struct_keys_doc[] =
2531 ".. method:: keys()\n"
2533 " Returns the keys of this objects custom properties (matches pythons dictionary function of the same name).\n"
2535 " :return: custom property keys.\n"
2536 " :rtype: list of strings\n"
2538 " .. note:: Only :class:`ID`, :class:`Bone` and :class:`PoseBone` classes support custom properties.\n";
2540 static PyObject *pyrna_struct_keys(BPy_PropertyRNA *self)
2544 if(RNA_struct_idprops_check(self->ptr.type)==0) {
2545 PyErr_SetString(PyExc_TypeError, "bpy_struct.keys(): this type doesn't support IDProperties");
2549 group= RNA_struct_idprops(&self->ptr, 0);
2552 return PyList_New(0);
2554 return BPy_Wrap_GetKeys(group);
2557 static char pyrna_struct_items_doc[] =
2558 ".. method:: items()\n"
2560 " Returns the items of this objects custom properties (matches pythons dictionary function of the same name).\n"
2562 " :return: custom property key, value pairs.\n"
2563 " :rtype: list of key, value tuples\n"
2565 " .. note:: Only :class:`ID`, :class:`Bone` and :class:`PoseBone` classes support custom properties.\n";
2567 static PyObject *pyrna_struct_items(BPy_PropertyRNA *self)
2571 if(RNA_struct_idprops_check(self->ptr.type)==0) {
2572 PyErr_SetString(PyExc_TypeError, "bpy_struct.items(): this type doesn't support IDProperties");
2576 group= RNA_struct_idprops(&self->ptr, 0);
2579 return PyList_New(0);
2581 return BPy_Wrap_GetItems(self->ptr.id.data, group);
2584 static char pyrna_struct_values_doc[] =
2585 ".. method:: values()\n"
2587 " Returns the values of this objects custom properties (matches pythons dictionary function of the same name).\n"
2589 " :return: custom property values.\n"
2592 " .. note:: Only :class:`ID`, :class:`Bone` and :class:`PoseBone` classes support custom properties.\n";
2594 static PyObject *pyrna_struct_values(BPy_PropertyRNA *self)
2598 if(RNA_struct_idprops_check(self->ptr.type)==0) {
2599 PyErr_SetString(PyExc_TypeError, "bpy_struct.values(): this type doesn't support IDProperties");
2603 group= RNA_struct_idprops(&self->ptr, 0);
2606 return PyList_New(0);
2608 return BPy_Wrap_GetValues(self->ptr.id.data, group);
2612 static char pyrna_struct_is_property_set_doc[] =
2613 ".. method:: is_property_set(property)\n"
2615 " Check if a property is set, use for testing operator properties.\n"
2617 " :return: True when the property has been set.\n"
2618 " :rtype: boolean\n"
2620 static PyObject *pyrna_struct_is_property_set(BPy_StructRNA *self, PyObject *args)
2626 PYRNA_STRUCT_CHECK_OBJ(self)
2628 if (!PyArg_ParseTuple(args, "s:is_property_set", &name))
2631 if((prop= RNA_struct_find_property(&self->ptr, name)) == NULL) {
2632 PyErr_Format(PyExc_TypeError,
2633 "%.200s.is_property_set(\"%.200s\") not found",
2634 RNA_struct_identifier(self->ptr.type), name);
2638 /* double property lookup, could speed up */
2639 /* return PyBool_FromLong(RNA_property_is_set(&self->ptr, name)); */
2640 if(RNA_property_flag(prop) & PROP_IDPROPERTY) {
2641 IDProperty *group= RNA_struct_idprops(&self->ptr, 0);
2643 ret= IDP_GetPropertyFromGroup(group, name) ? 1:0;
2653 return PyBool_FromLong(ret);
2656 static char pyrna_struct_is_property_hidden_doc[] =
2657 ".. method:: is_property_hidden(property)\n"
2659 " Check if a property is hidden.\n"
2661 " :return: True when the property is hidden.\n"
2662 " :rtype: boolean\n"
2664 static PyObject *pyrna_struct_is_property_hidden(BPy_StructRNA *self, PyObject *args)
2669 PYRNA_STRUCT_CHECK_OBJ(self)
2671 if (!PyArg_ParseTuple(args, "s:is_property_hidden", &name))
2674 if((prop= RNA_struct_find_property(&self->ptr, name)) == NULL) {
2675 PyErr_Format(PyExc_TypeError,
2676 "%.200s.is_property_hidden(\"%.200s\") not found",
2677 RNA_struct_identifier(self->ptr.type), name);
2681 return PyBool_FromLong(RNA_property_flag(prop) & PROP_HIDDEN);
2684 static char pyrna_struct_path_resolve_doc[] =
2685 ".. method:: path_resolve(path, coerce=True)\n"
2687 " Returns the property from the path, raise an exception when not found.\n"
2689 " :arg path: path which this property resolves.\n"
2690 " :type path: string\n"
2691 " :arg coerce: optional argument, when True, the property will be converted into its python representation.\n"
2692 " :type coerce: boolean\n"
2694 static PyObject *pyrna_struct_path_resolve(BPy_StructRNA *self, PyObject *args)
2697 PyObject *coerce= Py_True;
2699 PropertyRNA *r_prop;
2702 PYRNA_STRUCT_CHECK_OBJ(self)
2704 if (!PyArg_ParseTuple(args, "s|O!:path_resolve", &path, &PyBool_Type, &coerce))
2707 if (RNA_path_resolve_full(&self->ptr, path, &r_ptr, &r_prop, &index)) {
2710 if(index >= RNA_property_array_length(&r_ptr, r_prop) || index < 0) {
2711 PyErr_Format(PyExc_TypeError,
2712 "%.200s.path_resolve(\"%.200s\") index out of range",
2713 RNA_struct_identifier(self->ptr.type), path);
2717 return pyrna_array_index(&r_ptr, r_prop, index);
2721 if(coerce == Py_False) {
2722 return pyrna_prop_CreatePyObject(&r_ptr, r_prop);
2725 return pyrna_prop_to_py(&r_ptr, r_prop);
2730 return pyrna_struct_CreatePyObject(&r_ptr);
2734 PyErr_Format(PyExc_TypeError,
2735 "%.200s.path_resolve(\"%.200s\") could not be resolved",
2736 RNA_struct_identifier(self->ptr.type), path);
2741 static char pyrna_struct_path_from_id_doc[] =
2742 ".. method:: path_from_id(property=\"\")\n"
2744 " Returns the data path from the ID to this object (string).\n"
2746 " :arg property: Optional property name which can be used if the path is to a property of this object.\n"
2747 " :type property: string\n"
2748 " :return: The path from :class:`bpy_struct.id_data` to this struct and property (when given).\n"
2751 static PyObject *pyrna_struct_path_from_id(BPy_StructRNA *self, PyObject *args)
2753 const char *name= NULL;
2758 PYRNA_STRUCT_CHECK_OBJ(self)
2760 if (!PyArg_ParseTuple(args, "|s:path_from_id", &name))
2764 prop= RNA_struct_find_property(&self->ptr, name);
2766 PyErr_Format(PyExc_TypeError,
2767 "%.200s.path_from_id(\"%.200s\") not found",
2768 RNA_struct_identifier(self->ptr.type), name);
2772 path= RNA_path_from_ID_to_property(&self->ptr, prop);
2775 path= RNA_path_from_ID_to_struct(&self->ptr);
2780 PyErr_Format(PyExc_TypeError,
2781 "%.200s.path_from_id(\"%s\") found but does not support path creation",
2782 RNA_struct_identifier(self->ptr.type), name);
2785 PyErr_Format(PyExc_TypeError,
2786 "%.200s.path_from_id() does not support path creation for this type",
2787 RNA_struct_identifier(self->ptr.type));
2792 ret= PyUnicode_FromString(path);
2793 MEM_freeN((void *)path);
2798 static char pyrna_prop_path_from_id_doc[] =
2799 ".. method:: path_from_id()\n"
2801 " Returns the data path from the ID to this property (string).\n"
2803 " :return: The path from :class:`bpy_struct.id_data` to this property.\n"
2806 static PyObject *pyrna_prop_path_from_id(BPy_PropertyRNA *self)
2809 PropertyRNA *prop= self->prop;
2812 path= RNA_path_from_ID_to_property(&self->ptr, self->prop);
2815 PyErr_Format(PyExc_TypeError,
2816 "%.200s.%.200s.path_from_id() does not support path creation for this type",
2817 RNA_struct_identifier(self->ptr.type), RNA_property_identifier(prop));
2821 ret= PyUnicode_FromString(path);
2822 MEM_freeN((void *)path);
2827 static char pyrna_struct_type_recast_doc[] =
2828 ".. method:: type_recast()\n"
2830 " Return a new instance, this is needed because types such as textures can be changed at runtime.\n"
2832 " :return: a new instance of this object with the type initialized again.\n"
2833 " :rtype: subclass of :class:`bpy_struct`\n"
2835 static PyObject *pyrna_struct_type_recast(BPy_StructRNA *self)
2839 PYRNA_STRUCT_CHECK_OBJ(self)
2841 RNA_pointer_recast(&self->ptr, &r_ptr);
2842 return pyrna_struct_CreatePyObject(&r_ptr);
2845 static void pyrna_dir_members_py(PyObject *list, PyObject *self)
2848 PyObject **dict_ptr;
2851 dict_ptr= _PyObject_GetDictPtr((PyObject *)self);
2853 if(dict_ptr && (dict=*dict_ptr)) {
2854 list_tmp= PyDict_Keys(dict);
2855 PyList_SetSlice(list, INT_MAX, INT_MAX, list_tmp);
2856 Py_DECREF(list_tmp);
2859 dict= ((PyTypeObject *)Py_TYPE(self))->tp_dict;
2861 list_tmp= PyDict_Keys(dict);
2862 PyList_SetSlice(list, INT_MAX, INT_MAX, list_tmp);
2863 Py_DECREF(list_tmp);
2867 static void pyrna_dir_members_rna(PyObject *list, PointerRNA *ptr)
2872 /* for looping over attrs and funcs */
2874 PropertyRNA *iterprop;
2877 RNA_pointer_create(NULL, &RNA_Struct, ptr->type, &tptr);
2878 iterprop= RNA_struct_find_property(&tptr, "functions");
2880 RNA_PROP_BEGIN(&tptr, itemptr, iterprop) {
2881 idname= RNA_function_identifier(itemptr.data);
2883 pystring= PyUnicode_FromString(idname);
2884 PyList_Append(list, pystring);
2885 Py_DECREF(pystring);
2892 * Collect RNA attributes
2894 char name[256], *nameptr;
2896 iterprop= RNA_struct_iterator_property(ptr->type);
2898 RNA_PROP_BEGIN(ptr, itemptr, iterprop) {
2899 nameptr= RNA_struct_name_get_alloc(&itemptr, name, sizeof(name));
2902 pystring= PyUnicode_FromString(nameptr);
2903 PyList_Append(list, pystring);
2904 Py_DECREF(pystring);
2915 static PyObject *pyrna_struct_dir(BPy_StructRNA *self)
2920 PYRNA_STRUCT_CHECK_OBJ(self)
2922 /* Include this incase this instance is a subtype of a python class
2923 * In these instances we may want to return a function or variable provided by the subtype
2927 if (!BPy_StructRNA_CheckExact(self))
2928 pyrna_dir_members_py(ret, (PyObject *)self);
2930 pyrna_dir_members_rna(ret, &self->ptr);
2932 if(self->ptr.type == &RNA_Context) {
2933 ListBase lb= CTX_data_dir_get(self->ptr.data);
2936 for(link=lb.first; link; link=link->next) {
2937 pystring= PyUnicode_FromString(link->data);
2938 PyList_Append(ret, pystring);
2939 Py_DECREF(pystring);
2946 /* set(), this is needed to remove-doubles because the deferred
2947 * register-props will be in both the python __dict__ and accessed as RNA */
2949 PyObject *set= PySet_New(ret);
2952 ret= PySequence_List(set);
2959 //---------------getattr--------------------------------------------
2960 static PyObject *pyrna_struct_getattro(BPy_StructRNA *self, PyObject *pyname)
2962 const char *name= _PyUnicode_AsString(pyname);
2967 PYRNA_STRUCT_CHECK_OBJ(self)
2970 PyErr_SetString(PyExc_AttributeError, "bpy_struct: __getattr__ must be a string");
2973 else if(name[0]=='_') { // rna can't start with a "_", so for __dict__ and similar we can skip using rna lookups
2974 /* annoying exception, maybe we need to have different types for this... */
2975 if((strcmp(name, "__getitem__")==0 || strcmp(name, "__setitem__")==0) && !RNA_struct_idprops_check(self->ptr.type)) {
2976 PyErr_SetString(PyExc_AttributeError, "bpy_struct: no __getitem__ support for this type");
2980 ret= PyObject_GenericGetAttr((PyObject *)self, pyname);
2983 else if ((prop= RNA_struct_find_property(&self->ptr, name))) {
2984 ret= pyrna_prop_to_py(&self->ptr, prop);
2986 /* RNA function only if callback is declared (no optional functions) */
2987 else if ((func= RNA_struct_find_function(&self->ptr, name)) && RNA_function_defined(func)) {
2988 ret= pyrna_func_to_py((BPy_DummyPointerRNA *)self, func);
2990 else if (self->ptr.type == &RNA_Context) {
2991 bContext *C= self->ptr.data;
2993 PyErr_Format(PyExc_AttributeError, "bpy_struct: Context is 'NULL', can't get \"%.200s\" from context", name);
3001 int done= CTX_data_get(C, name, &newptr, &newlb, &newtype);
3003 if(done==1) { /* found */
3005 case CTX_DATA_TYPE_POINTER:
3006 if(newptr.data == NULL) {
3011 ret= pyrna_struct_CreatePyObject(&newptr);
3014 case CTX_DATA_TYPE_COLLECTION:
3016 CollectionPointerLink *link;
3021 for(link=newlb.first; link; link=link->next) {
3022 linkptr= pyrna_struct_CreatePyObject(&link->ptr);
3023 PyList_Append(ret, linkptr);
3029 /* should never happen */
3030 BLI_assert(!"Invalid context type");
3032 PyErr_Format(PyExc_AttributeError,
3033 "bpy_struct: Context type invalid %d, can't get \"%.200s\" from context",
3038 else if (done==-1) { /* found but not set */
3042 else { /* not found in the context */
3043 /* lookup the subclass. raise an error if its not found */
3044 ret= PyObject_GenericGetAttr((PyObject *)self, pyname);
3047 BLI_freelistN(&newlb);
3052 PyErr_Format(PyExc_AttributeError, "bpy_struct: attribute \"%.200s\" not found", name);
3055 /* Include this incase this instance is a subtype of a python class
3056 * In these instances we may want to return a function or variable provided by the subtype
3058 * Also needed to return methods when its not a subtype
3061 /* The error raised here will be displayed */
3062 ret= PyObject_GenericGetAttr((PyObject *)self, pyname);
3069 static int pyrna_struct_pydict_contains(PyObject *self, PyObject *pyname)
3071 PyObject *dict= *(_PyObject_GetDictPtr((PyObject *)self));
3072 if (dict==NULL) /* unlikely */
3075 return PyDict_Contains(dict, pyname);
3079 //--------------- setattr-------------------------------------------
3080 static int pyrna_is_deferred_prop(PyObject *value)