Cleanup
[blender.git] / source / blender / python / intern / bpy_rna.c
1 /*
2  * ***** BEGIN GPL LICENSE BLOCK *****
3  *
4  * This program is free software; you can redistribute it and/or
5  * modify it under the terms of the GNU General Public License
6  * as published by the Free Software Foundation; either version 2
7  * of the License, or (at your option) any later version.
8  *
9  * This program is distributed in the hope that it will be useful,
10  * but WITHOUT ANY WARRANTY; without even the implied warranty of
11  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
12  * GNU General Public License for more details.
13  *
14  * You should have received a copy of the GNU General Public License
15  * along with this program; if not, write to the Free Software Foundation,
16  * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
17  *
18  * Contributor(s): Campbell Barton
19  *
20  * ***** END GPL LICENSE BLOCK *****
21  */
22
23 /** \file blender/python/intern/bpy_rna.c
24  *  \ingroup pythonintern
25  *
26  * This file is the main interface between python and blenders data api (RNA),
27  * exposing RNA to python so blender data can be accessed in a python like way.
28  *
29  * The two main types are 'BPy_StructRNA' and 'BPy_PropertyRNA' - the base
30  * classes for most of the data python accesses in blender.
31  */
32
33 #include <Python.h>
34
35 #include <stddef.h>
36 #include <float.h> /* FLT_MIN/MAX */
37
38 #include "RNA_types.h"
39
40 #include "BLI_dynstr.h"
41 #include "BLI_string.h"
42 #include "BLI_listbase.h"
43 #include "BLI_math_rotation.h"
44 #include "BLI_utildefines.h"
45
46 #include "BPY_extern.h"
47
48 #include "bpy_rna.h"
49 #include "bpy_rna_anim.h"
50 #include "bpy_props.h"
51 #include "bpy_util.h"
52 #include "bpy_rna_callback.h"
53 #include "bpy_intern_string.h"
54
55 #ifdef USE_PYRNA_INVALIDATE_WEAKREF
56 #  include "BLI_ghash.h"
57 #endif
58
59 #include "RNA_enum_types.h"
60 #include "RNA_define.h" /* RNA_def_property_free_identifier */
61 #include "RNA_access.h"
62
63 #include "MEM_guardedalloc.h"
64
65 #include "BKE_main.h"
66 #include "BKE_idcode.h"
67 #include "BKE_context.h"
68 #include "BKE_global.h" /* evil G.* */
69 #include "BKE_report.h"
70 #include "BKE_idprop.h"
71
72
73 #include "../generic/idprop_py_api.h" /* for IDprop lookups */
74 #include "../generic/py_capi_utils.h"
75 #include "../generic/python_utildefines.h"
76
77 #define USE_PEDANTIC_WRITE
78 #define USE_MATHUTILS
79 #define USE_STRING_COERCE
80
81 static PyObject *pyrna_struct_Subtype(PointerRNA *ptr);
82 static PyObject *pyrna_prop_collection_values(BPy_PropertyRNA *self);
83
84 #define BPY_DOC_ID_PROP_TYPE_NOTE                                             \
85 "   .. note::\n"                                                              \
86 "\n"                                                                          \
87 "      Only :class:`bpy.types.ID`, :class:`bpy.types.Bone` and \n"            \
88 "      :class:`bpy.types.PoseBone` classes support custom properties.\n"
89
90
91 int pyrna_struct_validity_check(BPy_StructRNA *pysrna)
92 {
93         if (pysrna->ptr.type) {
94                 return 0;
95         }
96         PyErr_Format(PyExc_ReferenceError,
97                      "StructRNA of type %.200s has been removed",
98                      Py_TYPE(pysrna)->tp_name);
99         return -1;
100 }
101
102 int pyrna_prop_validity_check(BPy_PropertyRNA *self)
103 {
104         if (self->ptr.type) {
105                 return 0;
106         }
107         PyErr_Format(PyExc_ReferenceError,
108                      "PropertyRNA of type %.200s.%.200s has been removed",
109                      Py_TYPE(self)->tp_name, RNA_property_identifier(self->prop));
110         return -1;
111 }
112
113 void pyrna_invalidate(BPy_DummyPointerRNA *self)
114 {
115         RNA_POINTER_INVALIDATE(&self->ptr);
116 }
117
118 #ifdef USE_PYRNA_INVALIDATE_GC
119 #define FROM_GC(g) ((PyObject *)(((PyGC_Head *)g) + 1))
120
121 /* only for sizeof() */
122 struct gc_generation {
123         PyGC_Head head;
124         int threshold;
125         int count;
126 } gc_generation;
127
128 static void id_release_gc(struct ID *id)
129 {
130         unsigned int j;
131         // unsigned int i = 0;
132         for (j = 0; j < 3; j++) {
133                 /* hack below to get the 2 other lists from _PyGC_generation0 that are normally not exposed */
134                 PyGC_Head *gen = (PyGC_Head *)(((char *)_PyGC_generation0) + (sizeof(gc_generation) * j));
135                 PyGC_Head *g = gen->gc.gc_next;
136                 while ((g = g->gc.gc_next) != gen) {
137                         PyObject *ob = FROM_GC(g);
138                         if (PyType_IsSubtype(Py_TYPE(ob), &pyrna_struct_Type) || PyType_IsSubtype(Py_TYPE(ob), &pyrna_prop_Type)) {
139                                 BPy_DummyPointerRNA *ob_ptr = (BPy_DummyPointerRNA *)ob;
140                                 if (ob_ptr->ptr.id.data == id) {
141                                         pyrna_invalidate(ob_ptr);
142                                         // printf("freeing: %p %s, %.200s\n", (void *)ob, id->name, Py_TYPE(ob)->tp_name);
143                                         // i++;
144                                 }
145                         }
146                 }
147         }
148         // printf("id_release_gc freed '%s': %d\n", id->name, i);
149 }
150 #endif
151
152 #ifdef USE_PYRNA_INVALIDATE_WEAKREF
153 //#define DEBUG_RNA_WEAKREF
154
155 struct GHash *id_weakref_pool = NULL;
156 static PyObject *id_free_weakref_cb(PyObject *weakinfo_pair, PyObject *weakref);
157 static PyMethodDef id_free_weakref_cb_def = {"id_free_weakref_cb", (PyCFunction)id_free_weakref_cb, METH_O, NULL};
158
159 /* adds a reference to the list, remember to decref */
160 static GHash *id_weakref_pool_get(ID *id)
161 {
162         GHash *weakinfo_hash = NULL;
163
164         if (id_weakref_pool) {
165                 weakinfo_hash = BLI_ghash_lookup(id_weakref_pool, (void *)id);
166         }
167         else {
168                 /* first time, allocate pool */
169                 id_weakref_pool = BLI_ghash_ptr_new("rna_global_pool");
170                 weakinfo_hash = NULL;
171         }
172
173         if (weakinfo_hash == NULL) {
174                 /* we're using a ghash as a set, could use libHX's HXMAP_SINGULAR but would be an extra dep. */
175                 weakinfo_hash = BLI_ghash_ptr_new("rna_id");
176                 BLI_ghash_insert(id_weakref_pool, id, weakinfo_hash);
177         }
178
179         return weakinfo_hash;
180 }
181
182 /* called from pyrna_struct_CreatePyObject() and pyrna_prop_CreatePyObject() */
183 static void id_weakref_pool_add(ID *id, BPy_DummyPointerRNA *pyrna)
184 {
185         PyObject *weakref;
186         PyObject *weakref_capsule;
187         PyObject *weakref_cb_py;
188
189         /* create a new function instance and insert the list as 'self' so we can remove ourself from it */
190         GHash *weakinfo_hash = id_weakref_pool_get(id); /* new or existing */
191
192         weakref_capsule = PyCapsule_New(weakinfo_hash, NULL, NULL);
193         weakref_cb_py = PyCFunction_New(&id_free_weakref_cb_def, weakref_capsule);
194         Py_DECREF(weakref_capsule);
195
196         /* add weakref to weakinfo_hash list */
197         weakref = PyWeakref_NewRef((PyObject *)pyrna, weakref_cb_py);
198
199         Py_DECREF(weakref_cb_py); /* function owned by the weakref now */
200
201         /* important to add at the end, since first removal looks at the end */
202         BLI_ghash_insert(weakinfo_hash, weakref, id); /* using a hash table as a set, all 'id's are the same */
203         /* weakinfo_hash owns the weakref */
204
205 }
206
207 /* workaround to get the last id without a lookup */
208 static ID *_id_tmp_ptr;
209 static void value_id_set(void *id)
210 {
211         _id_tmp_ptr = (ID *)id;
212 }
213
214 static void id_release_weakref_list(struct ID *id, GHash *weakinfo_hash);
215 static PyObject *id_free_weakref_cb(PyObject *weakinfo_capsule, PyObject *weakref)
216 {
217         /* important to search backwards */
218         GHash *weakinfo_hash = PyCapsule_GetPointer(weakinfo_capsule, NULL);
219
220
221         if (BLI_ghash_size(weakinfo_hash) > 1) {
222                 BLI_ghash_remove(weakinfo_hash, weakref, NULL, NULL);
223         }
224         else { /* get the last id and free it */
225                 BLI_ghash_remove(weakinfo_hash, weakref, NULL, value_id_set);
226                 id_release_weakref_list(_id_tmp_ptr, weakinfo_hash);
227         }
228
229         Py_DECREF(weakref);
230
231         Py_RETURN_NONE;
232 }
233
234 static void id_release_weakref_list(struct ID *id, GHash *weakinfo_hash)
235 {
236         GHashIterator weakinfo_hash_iter;
237
238         BLI_ghashIterator_init(&weakinfo_hash_iter, weakinfo_hash);
239
240 #ifdef DEBUG_RNA_WEAKREF
241         fprintf(stdout, "id_release_weakref: '%s', %d items\n", id->name, BLI_ghash_size(weakinfo_hash));
242 #endif
243
244         while (!BLI_ghashIterator_done(&weakinfo_hash_iter)) {
245                 PyObject *weakref = (PyObject *)BLI_ghashIterator_getKey(&weakinfo_hash_iter);
246                 PyObject *item = PyWeakref_GET_OBJECT(weakref);
247                 if (item != Py_None) {
248
249 #ifdef DEBUG_RNA_WEAKREF
250                         PyC_ObSpit("id_release_weakref item ", item);
251 #endif
252
253                         pyrna_invalidate((BPy_DummyPointerRNA *)item);
254                 }
255
256                 Py_DECREF(weakref);
257
258                 BLI_ghashIterator_step(&weakinfo_hash_iter);
259         }
260
261         BLI_ghash_remove(id_weakref_pool, (void *)id, NULL, NULL);
262         BLI_ghash_free(weakinfo_hash, NULL, NULL);
263
264         if (BLI_ghash_size(id_weakref_pool) == 0) {
265                 BLI_ghash_free(id_weakref_pool, NULL, NULL);
266                 id_weakref_pool = NULL;
267 #ifdef DEBUG_RNA_WEAKREF
268                 printf("id_release_weakref freeing pool\n");
269 #endif
270         }
271 }
272
273 static void id_release_weakref(struct ID *id)
274 {
275         GHash *weakinfo_hash = BLI_ghash_lookup(id_weakref_pool, (void *)id);
276         if (weakinfo_hash) {
277                 id_release_weakref_list(id, weakinfo_hash);
278         }
279 }
280
281 #endif /* USE_PYRNA_INVALIDATE_WEAKREF */
282
283 void BPY_id_release(struct ID *id)
284 {
285 #ifdef USE_PYRNA_INVALIDATE_GC
286         id_release_gc(id);
287 #endif
288
289 #ifdef USE_PYRNA_INVALIDATE_WEAKREF
290         if (id_weakref_pool) {
291                 PyGILState_STATE gilstate = PyGILState_Ensure();
292
293                 id_release_weakref(id);
294
295                 PyGILState_Release(gilstate);
296         }
297 #endif /* USE_PYRNA_INVALIDATE_WEAKREF */
298
299         (void)id;
300 }
301
302 #ifdef USE_PEDANTIC_WRITE
303 static bool rna_disallow_writes = false;
304
305 static bool rna_id_write_error(PointerRNA *ptr, PyObject *key)
306 {
307         ID *id = ptr->id.data;
308         if (id) {
309                 const short idcode = GS(id->name);
310                 if (!ELEM(idcode, ID_WM, ID_SCR)) { /* may need more added here */
311                         const char *idtype = BKE_idcode_to_name(idcode);
312                         const char *pyname;
313                         if (key && PyUnicode_Check(key)) pyname = _PyUnicode_AsString(key);
314                         else                             pyname = "<UNKNOWN>";
315
316                         /* make a nice string error */
317                         BLI_assert(idtype != NULL);
318                         PyErr_Format(PyExc_AttributeError,
319                                      "Writing to ID classes in this context is not allowed: "
320                                      "%.200s, %.200s datablock, error setting %.200s.%.200s",
321                                      id->name + 2, idtype, RNA_struct_identifier(ptr->type), pyname);
322
323                         return true;
324                 }
325         }
326         return false;
327 }
328 #endif  /* USE_PEDANTIC_WRITE */
329
330
331 #ifdef USE_PEDANTIC_WRITE
332 bool pyrna_write_check(void)
333 {
334         return !rna_disallow_writes;
335 }
336
337 void pyrna_write_set(bool val)
338 {
339         rna_disallow_writes = !val;
340 }
341 #else  /* USE_PEDANTIC_WRITE */
342 bool pyrna_write_check(void)
343 {
344         return true;
345 }
346 void pyrna_write_set(bool UNUSED(val))
347 {
348         /* nothing */
349 }
350 #endif  /* USE_PEDANTIC_WRITE */
351
352 static Py_ssize_t pyrna_prop_collection_length(BPy_PropertyRNA *self);
353 static Py_ssize_t pyrna_prop_array_length(BPy_PropertyArrayRNA *self);
354 static int pyrna_py_to_prop(PointerRNA *ptr, PropertyRNA *prop, void *data, PyObject *value, const char *error_prefix);
355 static int deferred_register_prop(StructRNA *srna, PyObject *key, PyObject *item);
356
357 #ifdef USE_MATHUTILS
358 #include "../mathutils/mathutils.h" /* so we can have mathutils callbacks */
359
360 static PyObject *pyrna_prop_array_subscript_slice(BPy_PropertyArrayRNA *self, PointerRNA *ptr, PropertyRNA *prop,
361                                                   Py_ssize_t start, Py_ssize_t stop, Py_ssize_t length);
362 static short pyrna_rotation_euler_order_get(PointerRNA *ptr, PropertyRNA **prop_eul_order, const short order_fallback);
363
364 /* bpyrna vector/euler/quat callbacks */
365 static unsigned char mathutils_rna_array_cb_index = -1; /* index for our callbacks */
366
367 /* subtype not used much yet */
368 #define MATHUTILS_CB_SUBTYPE_EUL 0
369 #define MATHUTILS_CB_SUBTYPE_VEC 1
370 #define MATHUTILS_CB_SUBTYPE_QUAT 2
371 #define MATHUTILS_CB_SUBTYPE_COLOR 3
372
373 static int mathutils_rna_generic_check(BaseMathObject *bmo)
374 {
375         BPy_PropertyRNA *self = (BPy_PropertyRNA *)bmo->cb_user;
376
377         PYRNA_PROP_CHECK_INT(self);
378
379         return self->prop ? 0 : -1;
380 }
381
382 static int mathutils_rna_vector_get(BaseMathObject *bmo, int subtype)
383 {
384         BPy_PropertyRNA *self = (BPy_PropertyRNA *)bmo->cb_user;
385
386         PYRNA_PROP_CHECK_INT(self);
387
388         if (self->prop == NULL)
389                 return -1;
390
391         RNA_property_float_get_array(&self->ptr, self->prop, bmo->data);
392
393         /* Euler order exception */
394         if (subtype == MATHUTILS_CB_SUBTYPE_EUL) {
395                 EulerObject *eul = (EulerObject *)bmo;
396                 PropertyRNA *prop_eul_order = NULL;
397                 eul->order = pyrna_rotation_euler_order_get(&self->ptr, &prop_eul_order, eul->order);
398         }
399
400         return 0;
401 }
402
403 static int mathutils_rna_vector_set(BaseMathObject *bmo, int subtype)
404 {
405         BPy_PropertyRNA *self = (BPy_PropertyRNA *)bmo->cb_user;
406         float min, max;
407
408         PYRNA_PROP_CHECK_INT(self);
409
410         if (self->prop == NULL)
411                 return -1;
412
413 #ifdef USE_PEDANTIC_WRITE
414         if (rna_disallow_writes && rna_id_write_error(&self->ptr, NULL)) {
415                 return -1;
416         }
417 #endif  /* USE_PEDANTIC_WRITE */
418
419         if (!RNA_property_editable_flag(&self->ptr, self->prop)) {
420                 PyErr_Format(PyExc_AttributeError,
421                              "bpy_prop \"%.200s.%.200s\" is read-only",
422                              RNA_struct_identifier(self->ptr.type), RNA_property_identifier(self->prop));
423                 return -1;
424         }
425
426         RNA_property_float_range(&self->ptr, self->prop, &min, &max);
427
428         if (min != -FLT_MAX || max != FLT_MAX) {
429                 int i, len = RNA_property_array_length(&self->ptr, self->prop);
430                 for (i = 0; i < len; i++) {
431                         CLAMP(bmo->data[i], min, max);
432                 }
433         }
434
435         RNA_property_float_set_array(&self->ptr, self->prop, bmo->data);
436         if (RNA_property_update_check(self->prop)) {
437                 RNA_property_update(BPy_GetContext(), &self->ptr, self->prop);
438         }
439
440         /* Euler order exception */
441         if (subtype == MATHUTILS_CB_SUBTYPE_EUL) {
442                 EulerObject *eul = (EulerObject *)bmo;
443                 PropertyRNA *prop_eul_order = NULL;
444                 short order = pyrna_rotation_euler_order_get(&self->ptr, &prop_eul_order, eul->order);
445                 if (order != eul->order) {
446                         RNA_property_enum_set(&self->ptr, prop_eul_order, eul->order);
447                         if (RNA_property_update_check(prop_eul_order)) {
448                                 RNA_property_update(BPy_GetContext(), &self->ptr, prop_eul_order);
449                         }
450                 }
451         }
452         return 0;
453 }
454
455 static int mathutils_rna_vector_get_index(BaseMathObject *bmo, int UNUSED(subtype), int index)
456 {
457         BPy_PropertyRNA *self = (BPy_PropertyRNA *)bmo->cb_user;
458
459         PYRNA_PROP_CHECK_INT(self);
460
461         if (self->prop == NULL)
462                 return -1;
463
464         bmo->data[index] = RNA_property_float_get_index(&self->ptr, self->prop, index);
465         return 0;
466 }
467
468 static int mathutils_rna_vector_set_index(BaseMathObject *bmo, int UNUSED(subtype), int index)
469 {
470         BPy_PropertyRNA *self = (BPy_PropertyRNA *)bmo->cb_user;
471
472         PYRNA_PROP_CHECK_INT(self);
473
474         if (self->prop == NULL)
475                 return -1;
476
477 #ifdef USE_PEDANTIC_WRITE
478         if (rna_disallow_writes && rna_id_write_error(&self->ptr, NULL)) {
479                 return -1;
480         }
481 #endif  /* USE_PEDANTIC_WRITE */
482
483         if (!RNA_property_editable_flag(&self->ptr, self->prop)) {
484                 PyErr_Format(PyExc_AttributeError,
485                              "bpy_prop \"%.200s.%.200s\" is read-only",
486                              RNA_struct_identifier(self->ptr.type), RNA_property_identifier(self->prop));
487                 return -1;
488         }
489
490         RNA_property_float_clamp(&self->ptr, self->prop, &bmo->data[index]);
491         RNA_property_float_set_index(&self->ptr, self->prop, index, bmo->data[index]);
492
493         if (RNA_property_update_check(self->prop)) {
494                 RNA_property_update(BPy_GetContext(), &self->ptr, self->prop);
495         }
496
497         return 0;
498 }
499
500 static Mathutils_Callback mathutils_rna_array_cb = {
501         (BaseMathCheckFunc)     mathutils_rna_generic_check,
502         (BaseMathGetFunc)       mathutils_rna_vector_get,
503         (BaseMathSetFunc)       mathutils_rna_vector_set,
504         (BaseMathGetIndexFunc)  mathutils_rna_vector_get_index,
505         (BaseMathSetIndexFunc)  mathutils_rna_vector_set_index
506 };
507
508
509 /* bpyrna matrix callbacks */
510 static unsigned char mathutils_rna_matrix_cb_index = -1; /* index for our callbacks */
511
512 static int mathutils_rna_matrix_get(BaseMathObject *bmo, int UNUSED(subtype))
513 {
514         BPy_PropertyRNA *self = (BPy_PropertyRNA *)bmo->cb_user;
515
516         PYRNA_PROP_CHECK_INT(self);
517
518         if (self->prop == NULL)
519                 return -1;
520
521         RNA_property_float_get_array(&self->ptr, self->prop, bmo->data);
522         return 0;
523 }
524
525 static int mathutils_rna_matrix_set(BaseMathObject *bmo, int UNUSED(subtype))
526 {
527         BPy_PropertyRNA *self = (BPy_PropertyRNA *)bmo->cb_user;
528
529         PYRNA_PROP_CHECK_INT(self);
530
531         if (self->prop == NULL)
532                 return -1;
533
534 #ifdef USE_PEDANTIC_WRITE
535         if (rna_disallow_writes && rna_id_write_error(&self->ptr, NULL)) {
536                 return -1;
537         }
538 #endif  /* USE_PEDANTIC_WRITE */
539
540         if (!RNA_property_editable_flag(&self->ptr, self->prop)) {
541                 PyErr_Format(PyExc_AttributeError,
542                              "bpy_prop \"%.200s.%.200s\" is read-only",
543                              RNA_struct_identifier(self->ptr.type), RNA_property_identifier(self->prop));
544                 return -1;
545         }
546
547         /* can ignore clamping here */
548         RNA_property_float_set_array(&self->ptr, self->prop, bmo->data);
549
550         if (RNA_property_update_check(self->prop)) {
551                 RNA_property_update(BPy_GetContext(), &self->ptr, self->prop);
552         }
553         return 0;
554 }
555
556 static Mathutils_Callback mathutils_rna_matrix_cb = {
557         mathutils_rna_generic_check,
558         mathutils_rna_matrix_get,
559         mathutils_rna_matrix_set,
560         NULL,
561         NULL
562 };
563
564 static short pyrna_rotation_euler_order_get(PointerRNA *ptr, PropertyRNA **prop_eul_order, const short order_fallback)
565 {
566         /* attempt to get order */
567         if (*prop_eul_order == NULL)
568                 *prop_eul_order = RNA_struct_find_property(ptr, "rotation_mode");
569
570         if (*prop_eul_order) {
571                 short order = RNA_property_enum_get(ptr, *prop_eul_order);
572                 if (order >= EULER_ORDER_XYZ && order <= EULER_ORDER_ZYX) /* could be quat or axisangle */
573                         return order;
574         }
575
576         return order_fallback;
577 }
578
579 #endif  /* USE_MATHUTILS */
580
581 /* note that PROP_NONE is included as a vector subtype. this is because its handy to
582  * have x/y access to fcurve keyframes and other fixed size float arrays of length 2-4. */
583 #define PROP_ALL_VECTOR_SUBTYPES                                              \
584              PROP_COORDS:                                                         \
585         case PROP_TRANSLATION:                                                    \
586         case PROP_DIRECTION:                                                      \
587         case PROP_VELOCITY:                                                       \
588         case PROP_ACCELERATION:                                                   \
589         case PROP_XYZ:                                                            \
590         case PROP_XYZ_LENGTH                                                      \
591
592
593 PyObject *pyrna_math_object_from_array(PointerRNA *ptr, PropertyRNA *prop)
594 {
595         PyObject *ret = NULL;
596
597 #ifdef USE_MATHUTILS
598         int subtype, totdim;
599         int len;
600         const int flag = RNA_property_flag(prop);
601         const int type = RNA_property_type(prop);
602         const bool is_thick = (flag & PROP_THICK_WRAP) != 0;
603
604         /* disallow dynamic sized arrays to be wrapped since the size could change
605          * to a size mathutils does not support */
606         if (flag & PROP_DYNAMIC) {
607                 return NULL;
608         }
609
610         len = RNA_property_array_length(ptr, prop);
611         if (type == PROP_FLOAT) {
612                 /* pass */
613         }
614         else if (type == PROP_INT) {
615                 if (is_thick) {
616                         goto thick_wrap_slice;
617                 }
618                 else {
619                         return NULL;
620                 }
621         }
622         else {
623                 return NULL;
624         }
625
626         subtype = RNA_property_subtype(prop);
627         totdim = RNA_property_array_dimension(ptr, prop, NULL);
628
629         if (totdim == 1 || (totdim == 2 && subtype == PROP_MATRIX)) {
630                 if (!is_thick)
631                         ret = pyrna_prop_CreatePyObject(ptr, prop);  /* owned by the mathutils PyObject */
632
633                 switch (subtype) {
634                         case PROP_ALL_VECTOR_SUBTYPES:
635                                 if (len >= 2 && len <= 4) {
636                                         if (is_thick) {
637                                                 ret = Vector_CreatePyObject(NULL, len, NULL);
638                                                 RNA_property_float_get_array(ptr, prop, ((VectorObject *)ret)->vec);
639                                         }
640                                         else {
641                                                 PyObject *vec_cb = Vector_CreatePyObject_cb(ret, len, mathutils_rna_array_cb_index, MATHUTILS_CB_SUBTYPE_VEC);
642                                                 Py_DECREF(ret); /* the vector owns now */
643                                                 ret = vec_cb; /* return the vector instead */
644                                         }
645                                 }
646                                 break;
647                         case PROP_MATRIX:
648                                 if (len == 16) {
649                                         if (is_thick) {
650                                                 ret = Matrix_CreatePyObject(NULL, 4, 4, NULL);
651                                                 RNA_property_float_get_array(ptr, prop, ((MatrixObject *)ret)->matrix);
652                                         }
653                                         else {
654                                                 PyObject *mat_cb = Matrix_CreatePyObject_cb(ret, 4, 4, mathutils_rna_matrix_cb_index, 0);
655                                                 Py_DECREF(ret); /* the matrix owns now */
656                                                 ret = mat_cb; /* return the matrix instead */
657                                         }
658                                 }
659                                 else if (len == 9) {
660                                         if (is_thick) {
661                                                 ret = Matrix_CreatePyObject(NULL, 3, 3, NULL);
662                                                 RNA_property_float_get_array(ptr, prop, ((MatrixObject *)ret)->matrix);
663                                         }
664                                         else {
665                                                 PyObject *mat_cb = Matrix_CreatePyObject_cb(ret, 3, 3, mathutils_rna_matrix_cb_index, 0);
666                                                 Py_DECREF(ret); /* the matrix owns now */
667                                                 ret = mat_cb; /* return the matrix instead */
668                                         }
669                                 }
670                                 break;
671                         case PROP_EULER:
672                         case PROP_QUATERNION:
673                                 if (len == 3) { /* euler */
674                                         if (is_thick) {
675                                                 /* attempt to get order, only needed for thick types since wrapped with update via callbacks */
676                                                 PropertyRNA *prop_eul_order = NULL;
677                                                 short order = pyrna_rotation_euler_order_get(ptr, &prop_eul_order, EULER_ORDER_XYZ);
678
679                                                 ret = Euler_CreatePyObject(NULL, order, NULL);  /* TODO, get order from RNA */
680                                                 RNA_property_float_get_array(ptr, prop, ((EulerObject *)ret)->eul);
681                                         }
682                                         else {
683                                                 /* order will be updated from callback on use */
684                                                 PyObject *eul_cb = Euler_CreatePyObject_cb(ret, EULER_ORDER_XYZ, mathutils_rna_array_cb_index, MATHUTILS_CB_SUBTYPE_EUL); // TODO, get order from RNA
685                                                 Py_DECREF(ret); /* the euler owns now */
686                                                 ret = eul_cb; /* return the euler instead */
687                                         }
688                                 }
689                                 else if (len == 4) {
690                                         if (is_thick) {
691                                                 ret = Quaternion_CreatePyObject(NULL, NULL);
692                                                 RNA_property_float_get_array(ptr, prop, ((QuaternionObject *)ret)->quat);
693                                         }
694                                         else {
695                                                 PyObject *quat_cb = Quaternion_CreatePyObject_cb(ret, mathutils_rna_array_cb_index, MATHUTILS_CB_SUBTYPE_QUAT);
696                                                 Py_DECREF(ret); /* the quat owns now */
697                                                 ret = quat_cb; /* return the quat instead */
698                                         }
699                                 }
700                                 break;
701                         case PROP_COLOR:
702                         case PROP_COLOR_GAMMA:
703                                 if (len == 3) { /* color */
704                                         if (is_thick) {
705                                                 ret = Color_CreatePyObject(NULL, NULL);
706                                                 RNA_property_float_get_array(ptr, prop, ((ColorObject *)ret)->col);
707                                         }
708                                         else {
709                                                 PyObject *col_cb = Color_CreatePyObject_cb(ret, mathutils_rna_array_cb_index, MATHUTILS_CB_SUBTYPE_COLOR);
710                                                 Py_DECREF(ret); /* the color owns now */
711                                                 ret = col_cb; /* return the color instead */
712                                         }
713                                 }
714                                 break;
715                         default:
716                                 break;
717                 }
718         }
719
720         if (ret == NULL) {
721                 if (is_thick) {
722                         /* this is an array we cant reference (since its not thin wrappable)
723                          * and cannot be coerced into a mathutils type, so return as a list */
724 thick_wrap_slice:
725                         ret = pyrna_prop_array_subscript_slice(NULL, ptr, prop, 0, len, len);
726                 }
727                 else {
728                         ret = pyrna_prop_CreatePyObject(ptr, prop); /* owned by the mathutils PyObject */
729                 }
730         }
731 #else  /* USE_MATHUTILS */
732         (void)ptr;
733         (void)prop;
734 #endif  /* USE_MATHUTILS */
735
736         return ret;
737 }
738
739 /* same as RNA_enum_value_from_id but raises an exception */
740 int pyrna_enum_value_from_id(EnumPropertyItem *item, const char *identifier, int *value, const char *error_prefix)
741 {
742         if (RNA_enum_value_from_id(item, identifier, value) == 0) {
743                 const char *enum_str = BPy_enum_as_string(item);
744                 PyErr_Format(PyExc_ValueError,
745                              "%s: '%.200s' not found in (%s)",
746                              error_prefix, identifier, enum_str);
747                 MEM_freeN((void *)enum_str);
748                 return -1;
749         }
750
751         return 0;
752 }
753
754 /* note on __cmp__:
755  * checking the 'ptr->data' matches works in almost all cases,
756  * however there are a few RNA properties that are fake sub-structs and
757  * share the pointer with the parent, in those cases this happens 'a.b == a'
758  * see: r43352 for example.
759  *
760  * So compare the 'ptr->type' as well to avoid this problem.
761  * It's highly unlikely this would happen that 'ptr->data' and 'ptr->prop' would match,
762  * but _not_ 'ptr->type' but include this check for completeness.
763  * - campbell */
764
765 static int pyrna_struct_compare(BPy_StructRNA *a, BPy_StructRNA *b)
766 {
767         return (((a->ptr.data == b->ptr.data) &&
768                  (a->ptr.type == b->ptr.type)) ? 0 : -1);
769 }
770
771 static int pyrna_prop_compare(BPy_PropertyRNA *a, BPy_PropertyRNA *b)
772 {
773         return (((a->prop == b->prop) &&
774                  (a->ptr.data == b->ptr.data) &&
775                  (a->ptr.type == b->ptr.type)) ? 0 : -1);
776 }
777
778 static PyObject *pyrna_struct_richcmp(PyObject *a, PyObject *b, int op)
779 {
780         PyObject *res;
781         int ok = -1; /* zero is true */
782
783         if (BPy_StructRNA_Check(a) && BPy_StructRNA_Check(b))
784                 ok = pyrna_struct_compare((BPy_StructRNA *)a, (BPy_StructRNA *)b);
785
786         switch (op) {
787                 case Py_NE:
788                         ok = !ok;
789                         /* fall-through */
790                 case Py_EQ:
791                         res = ok ? Py_False : Py_True;
792                         break;
793
794                 case Py_LT:
795                 case Py_LE:
796                 case Py_GT:
797                 case Py_GE:
798                         res = Py_NotImplemented;
799                         break;
800                 default:
801                         PyErr_BadArgument();
802                         return NULL;
803         }
804
805         return Py_INCREF_RET(res);
806 }
807
808 static PyObject *pyrna_prop_richcmp(PyObject *a, PyObject *b, int op)
809 {
810         PyObject *res;
811         int ok = -1; /* zero is true */
812
813         if (BPy_PropertyRNA_Check(a) && BPy_PropertyRNA_Check(b))
814                 ok = pyrna_prop_compare((BPy_PropertyRNA *)a, (BPy_PropertyRNA *)b);
815
816         switch (op) {
817                 case Py_NE:
818                         ok = !ok;
819                         /* fall-through */
820                 case Py_EQ:
821                         res = ok ? Py_False : Py_True;
822                         break;
823
824                 case Py_LT:
825                 case Py_LE:
826                 case Py_GT:
827                 case Py_GE:
828                         res = Py_NotImplemented;
829                         break;
830                 default:
831                         PyErr_BadArgument();
832                         return NULL;
833         }
834
835         return Py_INCREF_RET(res);
836 }
837
838 /*----------------------repr--------------------------------------------*/
839 static PyObject *pyrna_struct_str(BPy_StructRNA *self)
840 {
841         PyObject *ret;
842         const char *name;
843
844         if (!PYRNA_STRUCT_IS_VALID(self)) {
845                 return PyUnicode_FromFormat("<bpy_struct, %.200s invalid>",
846                                             Py_TYPE(self)->tp_name);
847         }
848
849         /* print name if available */
850         name = RNA_struct_name_get_alloc(&self->ptr, NULL, 0, NULL);
851         if (name) {
852                 ret = PyUnicode_FromFormat("<bpy_struct, %.200s(\"%.200s\")>",
853                                            RNA_struct_identifier(self->ptr.type),
854                                            name);
855                 MEM_freeN((void *)name);
856                 return ret;
857         }
858
859         return PyUnicode_FromFormat("<bpy_struct, %.200s at %p>",
860                                     RNA_struct_identifier(self->ptr.type),
861                                     self->ptr.data);
862 }
863
864 static PyObject *pyrna_struct_repr(BPy_StructRNA *self)
865 {
866         ID *id = self->ptr.id.data;
867         PyObject *tmp_str;
868         PyObject *ret;
869
870         if (id == NULL || !PYRNA_STRUCT_IS_VALID(self))
871                 return pyrna_struct_str(self);  /* fallback */
872
873         tmp_str = PyUnicode_FromString(id->name + 2);
874
875         if (RNA_struct_is_ID(self->ptr.type)) {
876                 ret = PyUnicode_FromFormat("bpy.data.%s[%R]",
877                                            BKE_idcode_to_name_plural(GS(id->name)),
878                                            tmp_str);
879         }
880         else {
881                 const char *path;
882                 path = RNA_path_from_ID_to_struct(&self->ptr);
883                 if (path) {
884                         if (GS(id->name) == ID_NT) { /* nodetree paths are not accurate */
885                                 ret = PyUnicode_FromFormat("bpy.data...%s",
886                                                            path);
887                         }
888                         else {
889                                 ret = PyUnicode_FromFormat("bpy.data.%s[%R].%s",
890                                                            BKE_idcode_to_name_plural(GS(id->name)),
891                                                            tmp_str,
892                                                            path);
893                         }
894
895                         MEM_freeN((void *)path);
896                 }
897                 else { /* cant find, print something sane */
898                         ret = PyUnicode_FromFormat("bpy.data.%s[%R]...%s",
899                                                    BKE_idcode_to_name_plural(GS(id->name)),
900                                                    tmp_str,
901                                                    RNA_struct_identifier(self->ptr.type));
902                 }
903         }
904
905         Py_DECREF(tmp_str);
906
907         return ret;
908 }
909
910 static PyObject *pyrna_prop_str(BPy_PropertyRNA *self)
911 {
912         PyObject *ret;
913         PointerRNA ptr;
914         const char *name;
915         const char *type_id = NULL;
916         char type_fmt[64] = "";
917         int type;
918
919         PYRNA_PROP_CHECK_OBJ(self);
920
921         type = RNA_property_type(self->prop);
922
923         if (RNA_enum_id_from_value(rna_enum_property_type_items, type, &type_id) == 0) {
924                 PyErr_SetString(PyExc_RuntimeError, "could not use property type, internal error"); /* should never happen */
925                 return NULL;
926         }
927         else {
928                 /* this should never fail */
929                 int len = -1;
930                 char *c = type_fmt;
931
932                 while ((*c++ = tolower(*type_id++))) {}
933
934                 if (type == PROP_COLLECTION) {
935                         len = pyrna_prop_collection_length(self);
936                 }
937                 else if (RNA_property_array_check(self->prop)) {
938                         len = pyrna_prop_array_length((BPy_PropertyArrayRNA *)self);
939                 }
940
941                 if (len != -1)
942                         sprintf(--c, "[%d]", len);
943         }
944
945         /* if a pointer, try to print name of pointer target too */
946         if (type == PROP_POINTER) {
947                 ptr = RNA_property_pointer_get(&self->ptr, self->prop);
948                 name = RNA_struct_name_get_alloc(&ptr, NULL, 0, NULL);
949
950                 if (name) {
951                         ret = PyUnicode_FromFormat("<bpy_%.200s, %.200s.%.200s(\"%.200s\")>",
952                                                    type_fmt,
953                                                    RNA_struct_identifier(self->ptr.type),
954                                                    RNA_property_identifier(self->prop),
955                                                    name);
956                         MEM_freeN((void *)name);
957                         return ret;
958                 }
959         }
960         if (type == PROP_COLLECTION) {
961                 PointerRNA r_ptr;
962                 if (RNA_property_collection_type_get(&self->ptr, self->prop, &r_ptr)) {
963                         return PyUnicode_FromFormat("<bpy_%.200s, %.200s>",
964                                                     type_fmt,
965                                                     RNA_struct_identifier(r_ptr.type));
966                 }
967         }
968
969         return PyUnicode_FromFormat("<bpy_%.200s, %.200s.%.200s>",
970                                     type_fmt,
971                                     RNA_struct_identifier(self->ptr.type),
972                                     RNA_property_identifier(self->prop));
973 }
974
975 static PyObject *pyrna_prop_repr(BPy_PropertyRNA *self)
976 {
977         ID *id = self->ptr.id.data;
978         PyObject *tmp_str;
979         PyObject *ret;
980         const char *path;
981
982         PYRNA_PROP_CHECK_OBJ(self);
983
984         if (id == NULL)
985                 return pyrna_prop_str(self);  /* fallback */
986
987         tmp_str = PyUnicode_FromString(id->name + 2);
988
989         path = RNA_path_from_ID_to_property(&self->ptr, self->prop);
990         if (path) {
991                 const char *data_delim = (path[0] == '[') ? "" : ".";
992                 if (GS(id->name) == ID_NT) { /* nodetree paths are not accurate */
993                         ret = PyUnicode_FromFormat("bpy.data...%s",
994                                                    path);
995                 }
996                 else {
997                         ret = PyUnicode_FromFormat("bpy.data.%s[%R]%s%s",
998                                                    BKE_idcode_to_name_plural(GS(id->name)),
999                                                    tmp_str,
1000                                                    data_delim, path);
1001                 }
1002
1003                 MEM_freeN((void *)path);
1004         }
1005         else { /* cant find, print something sane */
1006                 ret = PyUnicode_FromFormat("bpy.data.%s[%R]...%s",
1007                                            BKE_idcode_to_name_plural(GS(id->name)),
1008                                            tmp_str,
1009                                            RNA_property_identifier(self->prop));
1010         }
1011
1012         Py_DECREF(tmp_str);
1013
1014         return ret;
1015 }
1016
1017
1018 static PyObject *pyrna_func_repr(BPy_FunctionRNA *self)
1019 {
1020         return PyUnicode_FromFormat("<%.200s %.200s.%.200s()>",
1021                                     Py_TYPE(self)->tp_name,
1022                                     RNA_struct_identifier(self->ptr.type),
1023                                     RNA_function_identifier(self->func));
1024 }
1025
1026
1027 static Py_hash_t pyrna_struct_hash(BPy_StructRNA *self)
1028 {
1029         return _Py_HashPointer(self->ptr.data);
1030 }
1031
1032 /* from python's meth_hash v3.1.2 */
1033 static long pyrna_prop_hash(BPy_PropertyRNA *self)
1034 {
1035         long x, y;
1036         if (self->ptr.data == NULL)
1037                 x = 0;
1038         else {
1039                 x = _Py_HashPointer(self->ptr.data);
1040                 if (x == -1)
1041                         return -1;
1042         }
1043         y = _Py_HashPointer((void *)(self->prop));
1044         if (y == -1)
1045                 return -1;
1046         x ^= y;
1047         if (x == -1)
1048                 x = -2;
1049         return x;
1050 }
1051
1052 #ifdef USE_PYRNA_STRUCT_REFERENCE
1053 static int pyrna_struct_traverse(BPy_StructRNA *self, visitproc visit, void *arg)
1054 {
1055         Py_VISIT(self->reference);
1056         return 0;
1057 }
1058
1059 static int pyrna_struct_clear(BPy_StructRNA *self)
1060 {
1061         Py_CLEAR(self->reference);
1062         return 0;
1063 }
1064 #endif /* !USE_PYRNA_STRUCT_REFERENCE */
1065
1066 /* use our own dealloc so we can free a property if we use one */
1067 static void pyrna_struct_dealloc(BPy_StructRNA *self)
1068 {
1069 #ifdef PYRNA_FREE_SUPPORT
1070         if (self->freeptr && self->ptr.data) {
1071                 IDP_FreeProperty(self->ptr.data);
1072                 MEM_freeN(self->ptr.data);
1073                 self->ptr.data = NULL;
1074         }
1075 #endif /* PYRNA_FREE_SUPPORT */
1076
1077 #ifdef USE_WEAKREFS
1078         if (self->in_weakreflist != NULL) {
1079                 PyObject_ClearWeakRefs((PyObject *)self);
1080         }
1081 #endif
1082
1083 #ifdef USE_PYRNA_STRUCT_REFERENCE
1084         if (self->reference) {
1085                 PyObject_GC_UnTrack(self);
1086                 pyrna_struct_clear(self);
1087         }
1088 #endif /* !USE_PYRNA_STRUCT_REFERENCE */
1089
1090         /* Note, for subclassed PyObjects we cant just call PyObject_DEL() directly or it will crash */
1091         Py_TYPE(self)->tp_free(self);
1092 }
1093
1094 #ifdef USE_PYRNA_STRUCT_REFERENCE
1095 static void pyrna_struct_reference_set(BPy_StructRNA *self, PyObject *reference)
1096 {
1097         if (self->reference) {
1098 //              PyObject_GC_UnTrack(self); /* INITIALIZED TRACKED ? */
1099                 pyrna_struct_clear(self);
1100         }
1101         /* reference is now NULL */
1102
1103         if (reference) {
1104                 self->reference = reference;
1105                 Py_INCREF(reference);
1106 //              PyObject_GC_Track(self);  /* INITIALIZED TRACKED ? */
1107         }
1108 }
1109 #endif /* !USE_PYRNA_STRUCT_REFERENCE */
1110
1111 /* use our own dealloc so we can free a property if we use one */
1112 static void pyrna_prop_dealloc(BPy_PropertyRNA *self)
1113 {
1114 #ifdef USE_WEAKREFS
1115         if (self->in_weakreflist != NULL) {
1116                 PyObject_ClearWeakRefs((PyObject *)self);
1117         }
1118 #endif
1119         /* Note, for subclassed PyObjects we cant just call PyObject_DEL() directly or it will crash */
1120         Py_TYPE(self)->tp_free(self);
1121 }
1122
1123 static void pyrna_prop_array_dealloc(BPy_PropertyRNA *self)
1124 {
1125 #ifdef USE_WEAKREFS
1126         if (self->in_weakreflist != NULL) {
1127                 PyObject_ClearWeakRefs((PyObject *)self);
1128         }
1129 #endif
1130         /* Note, for subclassed PyObjects we cant just call PyObject_DEL() directly or it will crash */
1131         Py_TYPE(self)->tp_free(self);
1132 }
1133
1134 static const char *pyrna_enum_as_string(PointerRNA *ptr, PropertyRNA *prop)
1135 {
1136         EnumPropertyItem *item;
1137         const char *result;
1138         bool free = false;
1139
1140         RNA_property_enum_items(BPy_GetContext(), ptr, prop, &item, NULL, &free);
1141         if (item) {
1142                 result = BPy_enum_as_string(item);
1143         }
1144         else {
1145                 result = "";
1146         }
1147
1148         if (free)
1149                 MEM_freeN(item);
1150
1151         return result;
1152 }
1153
1154
1155 static int pyrna_string_to_enum(PyObject *item, PointerRNA *ptr, PropertyRNA *prop, int *val, const char *error_prefix)
1156 {
1157         const char *param = _PyUnicode_AsString(item);
1158
1159         if (param == NULL) {
1160                 PyErr_Format(PyExc_TypeError,
1161                              "%.200s expected a string enum, not %.200s",
1162                              error_prefix, Py_TYPE(item)->tp_name);
1163                 return -1;
1164         }
1165         else {
1166                 if (!RNA_property_enum_value(BPy_GetContext(), ptr, prop, param, val)) {
1167                         const char *enum_str = pyrna_enum_as_string(ptr, prop);
1168                         PyErr_Format(PyExc_TypeError,
1169                                      "%.200s enum \"%.200s\" not found in (%.200s)",
1170                                      error_prefix, param, enum_str);
1171                         MEM_freeN((void *)enum_str);
1172                         return -1;
1173                 }
1174         }
1175
1176         return 0;
1177 }
1178
1179 /* 'value' _must_ be a set type, error check before calling */
1180 int pyrna_set_to_enum_bitfield(EnumPropertyItem *items, PyObject *value, int *r_value, const char *error_prefix)
1181 {
1182         /* set of enum items, concatenate all values with OR */
1183         int ret, flag = 0;
1184
1185         /* set looping */
1186         Py_ssize_t pos = 0;
1187         Py_ssize_t hash = 0;
1188         PyObject *key;
1189
1190         *r_value = 0;
1191
1192         while (_PySet_NextEntry(value, &pos, &key, &hash)) {
1193                 const char *param = _PyUnicode_AsString(key);
1194
1195                 if (param == NULL) {
1196                         PyErr_Format(PyExc_TypeError,
1197                                      "%.200s expected a string, not %.200s",
1198                                      error_prefix, Py_TYPE(key)->tp_name);
1199                         return -1;
1200                 }
1201
1202                 if (pyrna_enum_value_from_id(items, param, &ret, error_prefix) == -1) {
1203                         return -1;
1204                 }
1205
1206                 flag |= ret;
1207         }
1208
1209         *r_value = flag;
1210         return 0;
1211 }
1212
1213 static int pyrna_prop_to_enum_bitfield(PointerRNA *ptr, PropertyRNA *prop, PyObject *value, int *r_value, const char *error_prefix)
1214 {
1215         EnumPropertyItem *item;
1216         int ret;
1217         bool free = false;
1218
1219         *r_value = 0;
1220
1221         if (!PyAnySet_Check(value)) {
1222                 PyErr_Format(PyExc_TypeError,
1223                              "%.200s, %.200s.%.200s expected a set, not a %.200s",
1224                              error_prefix, RNA_struct_identifier(ptr->type),
1225                              RNA_property_identifier(prop), Py_TYPE(value)->tp_name);
1226                 return -1;
1227         }
1228
1229         RNA_property_enum_items(BPy_GetContext(), ptr, prop, &item, NULL, &free);
1230
1231         if (item) {
1232                 ret = pyrna_set_to_enum_bitfield(item, value, r_value, error_prefix);
1233         }
1234         else {
1235                 if (PySet_GET_SIZE(value)) {
1236                         PyErr_Format(PyExc_TypeError,
1237                                      "%.200s: empty enum \"%.200s\" could not have any values assigned",
1238                                      error_prefix, RNA_property_identifier(prop));
1239                         ret = -1;
1240                 }
1241                 else {
1242                         ret = 0;
1243                 }
1244         }
1245
1246         if (free)
1247                 MEM_freeN(item);
1248
1249         return ret;
1250 }
1251
1252 PyObject *pyrna_enum_bitfield_to_py(EnumPropertyItem *items, int value)
1253 {
1254         PyObject *ret = PySet_New(NULL);
1255         const char *identifier[RNA_ENUM_BITFLAG_SIZE + 1];
1256
1257         if (RNA_enum_bitflag_identifiers(items, value, identifier)) {
1258                 PyObject *item;
1259                 int index;
1260                 for (index = 0; identifier[index]; index++) {
1261                         item = PyUnicode_FromString(identifier[index]);
1262                         PySet_Add(ret, item);
1263                         Py_DECREF(item);
1264                 }
1265         }
1266
1267         return ret;
1268 }
1269
1270 static PyObject *pyrna_enum_to_py(PointerRNA *ptr, PropertyRNA *prop, int val)
1271 {
1272         PyObject *item, *ret = NULL;
1273
1274         if (RNA_property_flag(prop) & PROP_ENUM_FLAG) {
1275                 const char *identifier[RNA_ENUM_BITFLAG_SIZE + 1];
1276
1277                 ret = PySet_New(NULL);
1278
1279                 if (RNA_property_enum_bitflag_identifiers(BPy_GetContext(), ptr, prop, val, identifier)) {
1280                         int index;
1281
1282                         for (index = 0; identifier[index]; index++) {
1283                                 item = PyUnicode_FromString(identifier[index]);
1284                                 PySet_Add(ret, item);
1285                                 Py_DECREF(item);
1286                         }
1287
1288                 }
1289         }
1290         else {
1291                 const char *identifier;
1292                 if (RNA_property_enum_identifier(BPy_GetContext(), ptr, prop, val, &identifier)) {
1293                         ret = PyUnicode_FromString(identifier);
1294                 }
1295                 else {
1296                         EnumPropertyItem *enum_item;
1297                         bool free = false;
1298
1299                         /* don't throw error here, can't trust blender 100% to give the
1300                          * right values, python code should not generate error for that */
1301                         RNA_property_enum_items(BPy_GetContext(), ptr, prop, &enum_item, NULL, &free);
1302                         if (enum_item && enum_item->identifier) {
1303                                 ret = PyUnicode_FromString(enum_item->identifier);
1304                         }
1305                         else {
1306                                 RNA_property_enum_items(NULL, ptr, prop, &enum_item, NULL, &free);
1307
1308                                 /* Do not print warning in case of DummyRNA_NULL_items, this one will never match any value... */
1309                                 if (enum_item != DummyRNA_NULL_items) {
1310                                         const char *ptr_name = RNA_struct_name_get_alloc(ptr, NULL, 0, NULL);
1311
1312                                         /* prefer not fail silently in case of api errors, maybe disable it later */
1313                                         printf("RNA Warning: Current value \"%d\" "
1314                                                    "matches no enum in '%s', '%s', '%s'\n",
1315                                                    val, RNA_struct_identifier(ptr->type),
1316                                                    ptr_name, RNA_property_identifier(prop));
1317
1318 #if 0                           /* gives python decoding errors while generating docs :( */
1319                                         char error_str[256];
1320                                         BLI_snprintf(error_str, sizeof(error_str),
1321                                                      "RNA Warning: Current value \"%d\" "
1322                                                      "matches no enum in '%s', '%s', '%s'",
1323                                                      val, RNA_struct_identifier(ptr->type),
1324                                                      ptr_name, RNA_property_identifier(prop));
1325
1326                                         PyErr_Warn(PyExc_RuntimeWarning, error_str);
1327 #endif
1328
1329                                         if (ptr_name)
1330                                                 MEM_freeN((void *)ptr_name);
1331                                 }
1332
1333                                 ret = PyUnicode_FromString("");
1334                         }
1335
1336                         if (free)
1337                                 MEM_freeN(enum_item);
1338 #if 0
1339                         PyErr_Format(PyExc_AttributeError,
1340                                      "RNA Error: Current value \"%d\" matches no enum", val);
1341                         ret = NULL;
1342 #endif
1343                 }
1344         }
1345
1346         return ret;
1347 }
1348
1349 PyObject *pyrna_prop_to_py(PointerRNA *ptr, PropertyRNA *prop)
1350 {
1351         PyObject *ret;
1352         const int type = RNA_property_type(prop);
1353
1354         if (RNA_property_array_check(prop)) {
1355                 return pyrna_py_from_array(ptr, prop);
1356         }
1357
1358         /* see if we can coerce into a python type - PropertyType */
1359         switch (type) {
1360                 case PROP_BOOLEAN:
1361                         ret = PyBool_FromLong(RNA_property_boolean_get(ptr, prop));
1362                         break;
1363                 case PROP_INT:
1364                         ret = PyLong_FromLong(RNA_property_int_get(ptr, prop));
1365                         break;
1366                 case PROP_FLOAT:
1367                         ret = PyFloat_FromDouble(RNA_property_float_get(ptr, prop));
1368                         break;
1369                 case PROP_STRING:
1370                 {
1371                         const int subtype = RNA_property_subtype(prop);
1372                         const char *buf;
1373                         int buf_len;
1374                         char buf_fixed[32];
1375
1376                         buf = RNA_property_string_get_alloc(ptr, prop, buf_fixed, sizeof(buf_fixed), &buf_len);
1377 #ifdef USE_STRING_COERCE
1378                         /* only file paths get special treatment, they may contain non utf-8 chars */
1379                         if (subtype == PROP_BYTESTRING) {
1380                                 ret = PyBytes_FromStringAndSize(buf, buf_len);
1381                         }
1382                         else if (ELEM(subtype, PROP_FILEPATH, PROP_DIRPATH, PROP_FILENAME)) {
1383                                 ret = PyC_UnicodeFromByteAndSize(buf, buf_len);
1384                         }
1385                         else {
1386                                 ret = PyUnicode_FromStringAndSize(buf, buf_len);
1387                         }
1388 #else  /* USE_STRING_COERCE */
1389                         if (subtype == PROP_BYTESTRING) {
1390                                 ret = PyBytes_FromStringAndSize(buf, buf_len);
1391                         }
1392                         else {
1393                                 ret = PyUnicode_FromStringAndSize(buf, buf_len);
1394                         }
1395 #endif  /* USE_STRING_COERCE */
1396                         if (buf_fixed != buf) {
1397                                 MEM_freeN((void *)buf);
1398                         }
1399                         break;
1400                 }
1401                 case PROP_ENUM:
1402                 {
1403                         ret = pyrna_enum_to_py(ptr, prop, RNA_property_enum_get(ptr, prop));
1404                         break;
1405                 }
1406                 case PROP_POINTER:
1407                 {
1408                         PointerRNA newptr;
1409                         newptr = RNA_property_pointer_get(ptr, prop);
1410                         if (newptr.data) {
1411                                 ret = pyrna_struct_CreatePyObject(&newptr);
1412                         }
1413                         else {
1414                                 ret = Py_None;
1415                                 Py_INCREF(ret);
1416                         }
1417                         break;
1418                 }
1419                 case PROP_COLLECTION:
1420                         ret = pyrna_prop_CreatePyObject(ptr, prop);
1421                         break;
1422                 default:
1423                         PyErr_Format(PyExc_TypeError,
1424                                      "bpy_struct internal error: unknown type '%d' (pyrna_prop_to_py)", type);
1425                         ret = NULL;
1426                         break;
1427         }
1428
1429         return ret;
1430 }
1431
1432 /* This function is used by operators and converting dicts into collections.
1433  * Its takes keyword args and fills them with property values */
1434 int pyrna_pydict_to_props(PointerRNA *ptr, PyObject *kw, int all_args, const char *error_prefix)
1435 {
1436         int error_val = 0;
1437         int totkw;
1438         const char *arg_name = NULL;
1439         PyObject *item;
1440
1441         totkw = kw ? PyDict_Size(kw) : 0;
1442
1443         RNA_STRUCT_BEGIN (ptr, prop)
1444         {
1445                 arg_name = RNA_property_identifier(prop);
1446
1447                 if (STREQ(arg_name, "rna_type")) {
1448                         continue;
1449                 }
1450
1451                 if (kw == NULL) {
1452                         PyErr_Format(PyExc_TypeError,
1453                                      "%.200s: no keywords, expected \"%.200s\"",
1454                                      error_prefix, arg_name ? arg_name : "<UNKNOWN>");
1455                         error_val = -1;
1456                         break;
1457                 }
1458
1459                 item = PyDict_GetItemString(kw, arg_name); /* wont set an error */
1460
1461                 if (item == NULL) {
1462                         if (all_args) {
1463                                 PyErr_Format(PyExc_TypeError,
1464                                              "%.200s: keyword \"%.200s\" missing",
1465                                              error_prefix, arg_name ? arg_name : "<UNKNOWN>");
1466                                 error_val = -1; /* pyrna_py_to_prop sets the error */
1467                                 break;
1468                         }
1469                 }
1470                 else {
1471                         if (pyrna_py_to_prop(ptr, prop, NULL, item, error_prefix)) {
1472                                 error_val = -1;
1473                                 break;
1474                         }
1475                         totkw--;
1476                 }
1477         }
1478         RNA_STRUCT_END;
1479
1480         if (error_val == 0 && totkw > 0) { /* some keywords were given that were not used :/ */
1481                 PyObject *key, *value;
1482                 Py_ssize_t pos = 0;
1483
1484                 while (PyDict_Next(kw, &pos, &key, &value)) {
1485                         arg_name = _PyUnicode_AsString(key);
1486                         if (RNA_struct_find_property(ptr, arg_name) == NULL) break;
1487                         arg_name = NULL;
1488                 }
1489
1490                 PyErr_Format(PyExc_TypeError,
1491                              "%.200s: keyword \"%.200s\" unrecognized",
1492                              error_prefix, arg_name ? arg_name : "<UNKNOWN>");
1493                 error_val = -1;
1494         }
1495
1496         return error_val;
1497 }
1498
1499
1500 static PyObject *pyrna_func_to_py(const PointerRNA *ptr, FunctionRNA *func)
1501 {
1502         BPy_FunctionRNA *pyfunc = (BPy_FunctionRNA *) PyObject_NEW(BPy_FunctionRNA, &pyrna_func_Type);
1503         pyfunc->ptr = *ptr;
1504         pyfunc->func = func;
1505         return (PyObject *)pyfunc;
1506 }
1507
1508
1509 static int pyrna_py_to_prop(PointerRNA *ptr, PropertyRNA *prop, void *data, PyObject *value, const char *error_prefix)
1510 {
1511         /* XXX hard limits should be checked here */
1512         const int type = RNA_property_type(prop);
1513
1514
1515         if (RNA_property_array_check(prop)) {
1516                 /* done getting the length */
1517                 if (pyrna_py_to_array(ptr, prop, data, value, error_prefix) == -1) {
1518                         return -1;
1519                 }
1520         }
1521         else {
1522                 /* Normal Property (not an array) */
1523
1524                 /* see if we can coerce into a python type - PropertyType */
1525                 switch (type) {
1526                         case PROP_BOOLEAN:
1527                         {
1528                                 int param;
1529                                 /* prefer not to have an exception here
1530                                  * however so many poll functions return None or a valid Object.
1531                                  * its a hassle to convert these into a bool before returning, */
1532                                 if (RNA_property_flag(prop) & PROP_OUTPUT) {
1533                                         param = PyObject_IsTrue(value);
1534                                 }
1535                                 else {
1536                                         param = PyLong_AsLong(value);
1537
1538                                         if (UNLIKELY(param & ~1)) {  /* only accept 0/1 */
1539                                                 param = -1;              /* error out below */
1540                                         }
1541                                 }
1542
1543                                 if (param == -1) {
1544                                         PyErr_Format(PyExc_TypeError,
1545                                                      "%.200s %.200s.%.200s expected True/False or 0/1, not %.200s",
1546                                                      error_prefix, RNA_struct_identifier(ptr->type),
1547                                                      RNA_property_identifier(prop), Py_TYPE(value)->tp_name);
1548                                         return -1;
1549                                 }
1550                                 else {
1551                                         if (data) *((int *)data) = param;
1552                                         else RNA_property_boolean_set(ptr, prop, param);
1553                                 }
1554                                 break;
1555                         }
1556                         case PROP_INT:
1557                         {
1558                                 int overflow;
1559                                 long param = PyLong_AsLongAndOverflow(value, &overflow);
1560                                 if (overflow || (param > INT_MAX) || (param < INT_MIN)) {
1561                                         PyErr_Format(PyExc_ValueError,
1562                                                      "%.200s %.200s.%.200s value not in 'int' range "
1563                                                      "(" STRINGIFY(INT_MIN) ", " STRINGIFY(INT_MAX) ")",
1564                                                      error_prefix, RNA_struct_identifier(ptr->type),
1565                                                      RNA_property_identifier(prop));
1566                                         return -1;
1567                                 }
1568                                 else if (param == -1 && PyErr_Occurred()) {
1569                                         PyErr_Format(PyExc_TypeError,
1570                                                      "%.200s %.200s.%.200s expected an int type, not %.200s",
1571                                                      error_prefix, RNA_struct_identifier(ptr->type),
1572                                                      RNA_property_identifier(prop), Py_TYPE(value)->tp_name);
1573                                         return -1;
1574                                 }
1575                                 else {
1576                                         int param_i = (int)param;
1577                                         if (data) {
1578                                                 RNA_property_int_clamp(ptr, prop, &param_i);
1579                                                 *((int *)data) = param_i;
1580                                         }
1581                                         else {
1582                                                 RNA_property_int_set(ptr, prop, param_i);
1583                                         }
1584                                 }
1585                                 break;
1586                         }
1587                         case PROP_FLOAT:
1588                         {
1589                                 float param = PyFloat_AsDouble(value);
1590                                 if (PyErr_Occurred()) {
1591                                         PyErr_Format(PyExc_TypeError,
1592                                                      "%.200s %.200s.%.200s expected a float type, not %.200s",
1593                                                      error_prefix, RNA_struct_identifier(ptr->type),
1594                                                      RNA_property_identifier(prop), Py_TYPE(value)->tp_name);
1595                                         return -1;
1596                                 }
1597                                 else {
1598                                         if (data) {
1599                                                 RNA_property_float_clamp(ptr, prop, (float *)&param);
1600                                                 *((float *)data) = param;
1601                                         }
1602                                         else {
1603                                                 RNA_property_float_set(ptr, prop, param);
1604                                         }
1605                                 }
1606                                 break;
1607                         }
1608                         case PROP_STRING:
1609                         {
1610                                 const int subtype = RNA_property_subtype(prop);
1611                                 const char *param;
1612
1613                                 if (subtype == PROP_BYTESTRING) {
1614
1615                                         /* Byte String */
1616
1617                                         param = PyBytes_AsString(value);
1618
1619                                         if (param == NULL) {
1620                                                 if (PyBytes_Check(value)) {
1621                                                         /* there was an error assigning a string type,
1622                                                          * rather than setting a new error, prefix the existing one
1623                                                          */
1624                                                         PyC_Err_Format_Prefix(PyExc_TypeError,
1625                                                                               "%.200s %.200s.%.200s error assigning bytes",
1626                                                                               error_prefix, RNA_struct_identifier(ptr->type),
1627                                                                               RNA_property_identifier(prop));
1628                                                 }
1629                                                 else {
1630                                                         PyErr_Format(PyExc_TypeError,
1631                                                                      "%.200s %.200s.%.200s expected a bytes type, not %.200s",
1632                                                                      error_prefix, RNA_struct_identifier(ptr->type),
1633                                                                      RNA_property_identifier(prop), Py_TYPE(value)->tp_name);
1634                                                 }
1635
1636                                                 return -1;
1637                                         }
1638                                         else {
1639                                                 /* same as unicode */
1640                                                 if (data) *((char **)data) = (char *)param;  /*XXX, this is suspect but needed for function calls, need to see if theres a better way */
1641                                                 else RNA_property_string_set(ptr, prop, param);
1642                                         }
1643                                 }
1644                                 else {
1645                                         /* Unicode String */
1646 #ifdef USE_STRING_COERCE
1647                                         PyObject *value_coerce = NULL;
1648                                         if (ELEM(subtype, PROP_FILEPATH, PROP_DIRPATH, PROP_FILENAME)) {
1649                                                 /* TODO, get size */
1650                                                 param = PyC_UnicodeAsByte(value, &value_coerce);
1651                                         }
1652                                         else {
1653                                                 param = _PyUnicode_AsString(value);
1654                                         }
1655 #else  /* USE_STRING_COERCE */
1656                                         param = _PyUnicode_AsString(value);
1657 #endif  /* USE_STRING_COERCE */
1658
1659                                         if (param == NULL) {
1660                                                 if (PyUnicode_Check(value)) {
1661                                                         /* there was an error assigning a string type,
1662                                                          * rather than setting a new error, prefix the existing one
1663                                                          */
1664                                                         PyC_Err_Format_Prefix(PyExc_TypeError,
1665                                                                               "%.200s %.200s.%.200s error assigning string",
1666                                                                               error_prefix, RNA_struct_identifier(ptr->type),
1667                                                                               RNA_property_identifier(prop));
1668                                                 }
1669                                                 else {
1670                                                         PyErr_Format(PyExc_TypeError,
1671                                                                      "%.200s %.200s.%.200s expected a string type, not %.200s",
1672                                                                      error_prefix, RNA_struct_identifier(ptr->type),
1673                                                                      RNA_property_identifier(prop), Py_TYPE(value)->tp_name);
1674                                                 }
1675
1676                                                 return -1;
1677                                         }
1678                                         else {
1679                                                 /* same as bytes */
1680                                                 if (data) *((char **)data) = (char *)param;  /*XXX, this is suspect but needed for function calls, need to see if theres a better way */
1681                                                 else RNA_property_string_set(ptr, prop, param);
1682                                         }
1683 #ifdef USE_STRING_COERCE
1684                                         Py_XDECREF(value_coerce);
1685 #endif  /* USE_STRING_COERCE */
1686                                 }
1687                                 break;
1688                         }
1689                         case PROP_ENUM:
1690                         {
1691                                 int val = 0;
1692
1693                                 /* type checkins is done by each function */
1694                                 if (RNA_property_flag(prop) & PROP_ENUM_FLAG) {
1695                                         /* set of enum items, concatenate all values with OR */
1696                                         if (pyrna_prop_to_enum_bitfield(ptr, prop, value, &val, error_prefix) == -1) {
1697                                                 return -1;
1698                                         }
1699                                 }
1700                                 else {
1701                                         /* simple enum string */
1702                                         if (pyrna_string_to_enum(value, ptr, prop, &val, error_prefix) == -1) {
1703                                                 return -1;
1704                                         }
1705                                 }
1706
1707                                 if (data) *((int *)data) = val;
1708                                 else RNA_property_enum_set(ptr, prop, val);
1709
1710                                 break;
1711                         }
1712                         case PROP_POINTER:
1713                         {
1714                                 PyObject *value_new = NULL;
1715
1716                                 StructRNA *ptr_type = RNA_property_pointer_type(ptr, prop);
1717                                 int flag = RNA_property_flag(prop);
1718
1719                                 /* this is really nasty!, so we can fake the operator having direct properties eg:
1720                                  * layout.prop(self, "filepath")
1721                                  * ... which in fact should be
1722                                  * layout.prop(self.properties, "filepath")
1723                                  *
1724                                  * we need to do this trick.
1725                                  * if the prop is not an operator type and the pyobject is an operator,
1726                                  * use its properties in place of its self.
1727                                  *
1728                                  * this is so bad that its almost a good reason to do away with fake 'self.properties -> self' class mixing
1729                                  * if this causes problems in the future it should be removed.
1730                                  */
1731                                 if ((ptr_type == &RNA_AnyType) &&
1732                                     (BPy_StructRNA_Check(value)) &&
1733                                     (RNA_struct_is_a(((BPy_StructRNA *)value)->ptr.type, &RNA_Operator)))
1734                                 {
1735                                         value = PyObject_GetAttrString(value, "properties");
1736                                         value_new = value;
1737                                 }
1738
1739
1740                                 /* if property is an OperatorProperties pointer and value is a map,
1741                                  * forward back to pyrna_pydict_to_props */
1742                                 if (RNA_struct_is_a(ptr_type, &RNA_OperatorProperties) && PyDict_Check(value)) {
1743                                         PointerRNA opptr = RNA_property_pointer_get(ptr, prop);
1744                                         return pyrna_pydict_to_props(&opptr, value, 0, error_prefix);
1745                                 }
1746
1747                                 /* another exception, allow to pass a collection as an RNA property */
1748                                 if (Py_TYPE(value) == &pyrna_prop_collection_Type) { /* ok to ignore idprop collections */
1749                                         PointerRNA c_ptr;
1750                                         BPy_PropertyRNA *value_prop = (BPy_PropertyRNA *)value;
1751                                         if (RNA_property_collection_type_get(&value_prop->ptr, value_prop->prop, &c_ptr)) {
1752                                                 value = pyrna_struct_CreatePyObject(&c_ptr);
1753                                                 value_new = value;
1754                                         }
1755                                         else {
1756                                                 PyErr_Format(PyExc_TypeError,
1757                                                              "%.200s %.200s.%.200s collection has no type, "
1758                                                              "cant be used as a %.200s type",
1759                                                              error_prefix, RNA_struct_identifier(ptr->type),
1760                                                              RNA_property_identifier(prop), RNA_struct_identifier(ptr_type));
1761                                                 return -1;
1762                                         }
1763                                 }
1764
1765                                 if (!BPy_StructRNA_Check(value) && value != Py_None) {
1766                                         PyErr_Format(PyExc_TypeError,
1767                                                      "%.200s %.200s.%.200s expected a %.200s type, not %.200s",
1768                                                      error_prefix, RNA_struct_identifier(ptr->type),
1769                                                      RNA_property_identifier(prop), RNA_struct_identifier(ptr_type),
1770                                                      Py_TYPE(value)->tp_name);
1771                                         Py_XDECREF(value_new); return -1;
1772                                 }
1773                                 else if ((flag & PROP_NEVER_NULL) && value == Py_None) {
1774                                         PyErr_Format(PyExc_TypeError,
1775                                                      "%.200s %.200s.%.200s does not support a 'None' assignment %.200s type",
1776                                                      error_prefix, RNA_struct_identifier(ptr->type),
1777                                                      RNA_property_identifier(prop), RNA_struct_identifier(ptr_type));
1778                                         Py_XDECREF(value_new); return -1;
1779                                 }
1780                                 else if ((value != Py_None) &&
1781                                          ((flag & PROP_ID_SELF_CHECK) && ptr->id.data == ((BPy_StructRNA *)value)->ptr.id.data))
1782                                 {
1783                                         PyErr_Format(PyExc_TypeError,
1784                                                      "%.200s %.200s.%.200s ID type does not support assignment to its self",
1785                                                      error_prefix, RNA_struct_identifier(ptr->type),
1786                                                      RNA_property_identifier(prop));
1787                                         Py_XDECREF(value_new); return -1;
1788                                 }
1789                                 else {
1790                                         BPy_StructRNA *param = (BPy_StructRNA *)value;
1791                                         bool raise_error = false;
1792                                         if (data) {
1793
1794                                                 if (flag & PROP_RNAPTR) {
1795                                                         if (flag & PROP_THICK_WRAP) {
1796                                                                 if (value == Py_None)
1797                                                                         memset(data, 0, sizeof(PointerRNA));
1798                                                                 else if (RNA_struct_is_a(param->ptr.type, ptr_type))
1799                                                                         *((PointerRNA *)data) = param->ptr;
1800                                                                 else
1801                                                                         raise_error = true;
1802                                                         }
1803                                                         else {
1804                                                                 /* for function calls, we sometimes want to pass the 'ptr' directly,
1805                                                                  * watch out that it remains valid!, possibly we could support this later if needed */
1806                                                                 BLI_assert(value_new == NULL);
1807                                                                 if (value == Py_None)
1808                                                                         *((void **)data) = NULL;
1809                                                                 else if (RNA_struct_is_a(param->ptr.type, ptr_type))
1810                                                                         *((PointerRNA **)data) = &param->ptr;
1811                                                                 else
1812                                                                         raise_error = true;
1813                                                         }
1814                                                 }
1815                                                 else if (value == Py_None) {
1816                                                         *((void **)data) = NULL;
1817                                                 }
1818                                                 else if (RNA_struct_is_a(param->ptr.type, ptr_type)) {
1819                                                         *((void **)data) = param->ptr.data;
1820                                                 }
1821                                                 else {
1822                                                         raise_error = true;
1823                                                 }
1824                                         }
1825                                         else {
1826                                                 /* data == NULL, assign to RNA */
1827                                                 if (value == Py_None) {
1828                                                         PointerRNA valueptr = {{NULL}};
1829                                                         RNA_property_pointer_set(ptr, prop, valueptr);
1830                                                 }
1831                                                 else if (RNA_struct_is_a(param->ptr.type, ptr_type)) {
1832                                                         RNA_property_pointer_set(ptr, prop, param->ptr);
1833                                                 }
1834                                                 else {
1835                                                         raise_error = true;
1836                                                 }
1837                                         }
1838
1839                                         if (raise_error) {
1840                                                 if (pyrna_struct_validity_check(param) == -1) {
1841                                                         /* error set */
1842                                                 }
1843                                                 else {
1844                                                         PointerRNA tmp;
1845                                                         RNA_pointer_create(NULL, ptr_type, NULL, &tmp);
1846                                                         PyErr_Format(PyExc_TypeError,
1847                                                                      "%.200s %.200s.%.200s expected a %.200s type, not %.200s",
1848                                                                      error_prefix, RNA_struct_identifier(ptr->type),
1849                                                                      RNA_property_identifier(prop), RNA_struct_identifier(tmp.type),
1850                                                                      RNA_struct_identifier(param->ptr.type));
1851                                                 }
1852                                                 Py_XDECREF(value_new); return -1;
1853                                         }
1854                                 }
1855
1856                                 Py_XDECREF(value_new);
1857
1858                                 break;
1859                         }
1860                         case PROP_COLLECTION:
1861                         {
1862                                 Py_ssize_t seq_len, i;
1863                                 PyObject *item;
1864                                 PointerRNA itemptr;
1865                                 ListBase *lb;
1866                                 CollectionPointerLink *link;
1867
1868                                 lb = (data) ? (ListBase *)data : NULL;
1869
1870                                 /* convert a sequence of dict's into a collection */
1871                                 if (!PySequence_Check(value)) {
1872                                         PyErr_Format(PyExc_TypeError,
1873                                                      "%.200s %.200s.%.200s expected a sequence for an RNA collection, not %.200s",
1874                                                      error_prefix, RNA_struct_identifier(ptr->type),
1875                                                      RNA_property_identifier(prop), Py_TYPE(value)->tp_name);
1876                                         return -1;
1877                                 }
1878
1879                                 seq_len = PySequence_Size(value);
1880                                 for (i = 0; i < seq_len; i++) {
1881                                         item = PySequence_GetItem(value, i);
1882
1883                                         if (item == NULL) {
1884                                                 PyErr_Format(PyExc_TypeError,
1885                                                              "%.200s %.200s.%.200s failed to get sequence index '%d' for an RNA collection",
1886                                                              error_prefix, RNA_struct_identifier(ptr->type),
1887                                                              RNA_property_identifier(prop), i);
1888                                                 Py_XDECREF(item);
1889                                                 return -1;
1890                                         }
1891
1892                                         if (PyDict_Check(item) == 0) {
1893                                                 PyErr_Format(PyExc_TypeError,
1894                                                              "%.200s %.200s.%.200s expected a each sequence "
1895                                                              "member to be a dict for an RNA collection, not %.200s",
1896                                                              error_prefix, RNA_struct_identifier(ptr->type),
1897                                                              RNA_property_identifier(prop), Py_TYPE(item)->tp_name);
1898                                                 Py_XDECREF(item);
1899                                                 return -1;
1900                                         }
1901
1902                                         if (lb) {
1903                                                 link = MEM_callocN(sizeof(CollectionPointerLink), "PyCollectionPointerLink");
1904                                                 link->ptr = itemptr;
1905                                                 BLI_addtail(lb, link);
1906                                         }
1907                                         else
1908                                                 RNA_property_collection_add(ptr, prop, &itemptr);
1909
1910                                         if (pyrna_pydict_to_props(&itemptr, item, 1, "Converting a python list to an RNA collection") == -1) {
1911                                                 PyObject *msg = PyC_ExceptionBuffer();
1912                                                 const char *msg_char = _PyUnicode_AsString(msg);
1913
1914                                                 PyErr_Format(PyExc_TypeError,
1915                                                              "%.200s %.200s.%.200s error converting a member of a collection "
1916                                                              "from a dicts into an RNA collection, failed with: %s",
1917                                                              error_prefix, RNA_struct_identifier(ptr->type),
1918                                                              RNA_property_identifier(prop), msg_char);
1919
1920                                                 Py_DECREF(item);
1921                                                 Py_DECREF(msg);
1922                                                 return -1;
1923                                         }
1924                                         Py_DECREF(item);
1925                                 }
1926
1927                                 break;
1928                         }
1929                         default:
1930                                 PyErr_Format(PyExc_AttributeError,
1931                                              "%.200s %.200s.%.200s unknown property type (pyrna_py_to_prop)",
1932                                              error_prefix, RNA_struct_identifier(ptr->type),
1933                                              RNA_property_identifier(prop));
1934                                 return -1;
1935                 }
1936         }
1937
1938         /* Run rna property functions */
1939         if (RNA_property_update_check(prop)) {
1940                 RNA_property_update(BPy_GetContext(), ptr, prop);
1941         }
1942
1943         return 0;
1944 }
1945
1946 static PyObject *pyrna_prop_array_to_py_index(BPy_PropertyArrayRNA *self, int index)
1947 {
1948         PYRNA_PROP_CHECK_OBJ((BPy_PropertyRNA *)self);
1949         return pyrna_py_from_array_index(self, &self->ptr, self->prop, index);
1950 }
1951
1952 static int pyrna_py_to_prop_array_index(BPy_PropertyArrayRNA *self, int index, PyObject *value)
1953 {
1954         int ret = 0;
1955         PointerRNA *ptr = &self->ptr;
1956         PropertyRNA *prop = self->prop;
1957
1958         const int totdim = RNA_property_array_dimension(ptr, prop, NULL);
1959
1960         if (totdim > 1) {
1961                 /* char error_str[512]; */
1962                 if (pyrna_py_to_array_index(&self->ptr, self->prop, self->arraydim, self->arrayoffset, index, value, "") == -1) {
1963                         /* error is set */
1964                         ret = -1;
1965                 }
1966         }
1967         else {
1968                 /* see if we can coerce into a python type - PropertyType */
1969                 switch (RNA_property_type(prop)) {
1970                         case PROP_BOOLEAN:
1971                         {
1972                                 int param = PyLong_AsLong(value);
1973
1974                                 if (param < 0 || param > 1) {
1975                                         PyErr_SetString(PyExc_TypeError, "expected True/False or 0/1");
1976                                         ret = -1;
1977                                 }
1978                                 else {
1979                                         RNA_property_boolean_set_index(ptr, prop, index, param);
1980                                 }
1981                                 break;
1982                         }
1983                         case PROP_INT:
1984                         {
1985                                 int param = PyLong_AsLong(value);
1986                                 if (param == -1 && PyErr_Occurred()) {
1987                                         PyErr_SetString(PyExc_TypeError, "expected an int type");
1988                                         ret = -1;
1989                                 }
1990                                 else {
1991                                         RNA_property_int_clamp(ptr, prop, &param);
1992                                         RNA_property_int_set_index(ptr, prop, index, param);
1993                                 }
1994                                 break;
1995                         }
1996                         case PROP_FLOAT:
1997                         {
1998                                 float param = PyFloat_AsDouble(value);
1999                                 if (PyErr_Occurred()) {
2000                                         PyErr_SetString(PyExc_TypeError, "expected a float type");
2001                                         ret = -1;
2002                                 }
2003                                 else {
2004                                         RNA_property_float_clamp(ptr, prop, &param);
2005                                         RNA_property_float_set_index(ptr, prop, index, param);
2006                                 }
2007                                 break;
2008                         }
2009                         default:
2010                                 PyErr_SetString(PyExc_AttributeError, "not an array type");
2011                                 ret = -1;
2012                                 break;
2013                 }
2014         }
2015
2016         /* Run rna property functions */
2017         if (RNA_property_update_check(prop)) {
2018                 RNA_property_update(BPy_GetContext(), ptr, prop);
2019         }
2020
2021         return ret;
2022 }
2023
2024 /* ---------------sequence------------------------------------------- */
2025 static Py_ssize_t pyrna_prop_array_length(BPy_PropertyArrayRNA *self)
2026 {
2027         PYRNA_PROP_CHECK_INT((BPy_PropertyRNA *)self);
2028
2029         if (RNA_property_array_dimension(&self->ptr, self->prop, NULL) > 1)
2030                 return RNA_property_multi_array_length(&self->ptr, self->prop, self->arraydim);
2031         else
2032                 return RNA_property_array_length(&self->ptr, self->prop);
2033 }
2034
2035 static Py_ssize_t pyrna_prop_collection_length(BPy_PropertyRNA *self)
2036 {
2037         PYRNA_PROP_CHECK_INT(self);
2038
2039         return RNA_property_collection_length(&self->ptr, self->prop);
2040 }
2041
2042 /* bool functions are for speed, so we can avoid getting the length
2043  * of 1000's of items in a linked list for eg. */
2044 static int pyrna_prop_array_bool(BPy_PropertyRNA *self)
2045 {
2046         PYRNA_PROP_CHECK_INT(self);
2047
2048         return RNA_property_array_length(&self->ptr, self->prop) ? 1 : 0;
2049 }
2050
2051 static int pyrna_prop_collection_bool(BPy_PropertyRNA *self)
2052 {
2053         /* no callback defined, just iterate and find the nth item */
2054         CollectionPropertyIterator iter;
2055         int test;
2056
2057         PYRNA_PROP_CHECK_INT(self);
2058
2059         RNA_property_collection_begin(&self->ptr, self->prop, &iter);
2060         test = iter.valid;
2061         RNA_property_collection_end(&iter);
2062         return test;
2063 }
2064
2065
2066 /* notice getting the length of the collection is avoided unless negative
2067  * index is used or to detect internal error with a valid index.
2068  * This is done for faster lookups. */
2069 #define PYRNA_PROP_COLLECTION_ABS_INDEX(ret_err)                              \
2070         if (keynum < 0) {                                                         \
2071             keynum_abs += RNA_property_collection_length(&self->ptr, self->prop); \
2072             if (keynum_abs < 0) {                                                 \
2073                 PyErr_Format(PyExc_IndexError,                                    \
2074                              "bpy_prop_collection[%d]: out of range.", keynum);   \
2075                 return ret_err;                                                   \
2076             }                                                                     \
2077         } (void)0
2078
2079
2080 /* internal use only */
2081 static PyObject *pyrna_prop_collection_subscript_int(BPy_PropertyRNA *self, Py_ssize_t keynum)
2082 {
2083         PointerRNA newptr;
2084         Py_ssize_t keynum_abs = keynum;
2085
2086         PYRNA_PROP_CHECK_OBJ(self);
2087
2088         PYRNA_PROP_COLLECTION_ABS_INDEX(NULL);
2089
2090         if (RNA_property_collection_lookup_int(&self->ptr, self->prop, keynum_abs, &newptr)) {
2091                 return pyrna_struct_CreatePyObject(&newptr);
2092         }
2093         else {
2094                 const int len = RNA_property_collection_length(&self->ptr, self->prop);
2095                 if (keynum_abs >= len) {
2096                         PyErr_Format(PyExc_IndexError,
2097                                      "bpy_prop_collection[index]: "
2098                                      "index %d out of range, size %d", keynum, len);
2099                 }
2100                 else {
2101                         PyErr_Format(PyExc_RuntimeError,
2102                                      "bpy_prop_collection[index]: internal error, "
2103                                      "valid index %d given in %d sized collection but value not found",
2104                                      keynum_abs, len);
2105                 }
2106
2107                 return NULL;
2108         }
2109 }
2110
2111 /* values type must have been already checked */
2112 static int pyrna_prop_collection_ass_subscript_int(BPy_PropertyRNA *self, Py_ssize_t keynum, PyObject *value)
2113 {
2114         Py_ssize_t keynum_abs = keynum;
2115         const PointerRNA *ptr = (value == Py_None) ? (&PointerRNA_NULL) : &((BPy_StructRNA *)value)->ptr;
2116
2117         PYRNA_PROP_CHECK_INT(self);
2118
2119         PYRNA_PROP_COLLECTION_ABS_INDEX(-1);
2120
2121         if (RNA_property_collection_assign_int(&self->ptr, self->prop, keynum_abs, ptr) == 0) {
2122                 const int len = RNA_property_collection_length(&self->ptr, self->prop);
2123                 if (keynum_abs >= len) {
2124                         PyErr_Format(PyExc_IndexError,
2125                                      "bpy_prop_collection[index] = value: "
2126                                      "index %d out of range, size %d", keynum, len);
2127                 }
2128                 else {
2129
2130                         PyErr_Format(PyExc_IndexError,
2131                                      "bpy_prop_collection[index] = value: "
2132                                      "failed assignment (unknown reason)", keynum);
2133                 }
2134                 return -1;
2135         }
2136
2137         return 0;
2138 }
2139
2140 static PyObject *pyrna_prop_array_subscript_int(BPy_PropertyArrayRNA *self, int keynum)
2141 {
2142         int len;
2143
2144         PYRNA_PROP_CHECK_OBJ((BPy_PropertyRNA *)self);
2145
2146         len = pyrna_prop_array_length(self);
2147
2148         if (keynum < 0) keynum += len;
2149
2150         if (keynum >= 0 && keynum < len)
2151                 return pyrna_prop_array_to_py_index(self, keynum);
2152
2153         PyErr_Format(PyExc_IndexError,
2154                      "bpy_prop_array[index]: index %d out of range", keynum);
2155         return NULL;
2156 }
2157
2158 static PyObject *pyrna_prop_collection_subscript_str(BPy_PropertyRNA *self, const char *keyname)
2159 {
2160         PointerRNA newptr;
2161
2162         PYRNA_PROP_CHECK_OBJ(self);
2163
2164         if (RNA_property_collection_lookup_string(&self->ptr, self->prop, keyname, &newptr))
2165                 return pyrna_struct_CreatePyObject(&newptr);
2166
2167         PyErr_Format(PyExc_KeyError, "bpy_prop_collection[key]: key \"%.200s\" not found", keyname);
2168         return NULL;
2169 }
2170 /* static PyObject *pyrna_prop_array_subscript_str(BPy_PropertyRNA *self, char *keyname) */
2171
2172 /* special case: bpy.data.objects["some_id_name", "//some_lib_name.blend"]
2173  * also for:     bpy.data.objects.get(("some_id_name", "//some_lib_name.blend"), fallback)
2174  *
2175  * note:
2176  * error codes since this is not to be called directly from python,
2177  * this matches pythons __contains__ values capi.
2178  * -1: exception set
2179  *  0: not found
2180  *  1: found */
2181 static int pyrna_prop_collection_subscript_str_lib_pair_ptr(BPy_PropertyRNA *self, PyObject *key,
2182                                                             const char *err_prefix, const short err_not_found,
2183                                                             PointerRNA *r_ptr
2184                                                             )
2185 {
2186         const char *keyname;
2187
2188         /* first validate the args, all we know is that they are a tuple */
2189         if (PyTuple_GET_SIZE(key) != 2) {
2190                 PyErr_Format(PyExc_KeyError,
2191                              "%s: tuple key must be a pair, not size %d",
2192                              err_prefix, PyTuple_GET_SIZE(key));
2193                 return -1;
2194         }
2195         else if (self->ptr.type != &RNA_BlendData) {
2196                 PyErr_Format(PyExc_KeyError,
2197                              "%s: is only valid for bpy.data collections, not %.200s",
2198                              err_prefix, RNA_struct_identifier(self->ptr.type));
2199                 return -1;
2200         }
2201         else if ((keyname = _PyUnicode_AsString(PyTuple_GET_ITEM(key, 0))) == NULL) {
2202                 PyErr_Format(PyExc_KeyError,
2203                              "%s: id must be a string, not %.200s",
2204                              err_prefix, Py_TYPE(PyTuple_GET_ITEM(key, 0))->tp_name);
2205                 return -1;
2206         }
2207         else {
2208                 PyObject *keylib = PyTuple_GET_ITEM(key, 1);
2209                 Library *lib;
2210                 bool found = false;
2211
2212                 if (keylib == Py_None) {
2213                         lib = NULL;
2214                 }
2215                 else if (PyUnicode_Check(keylib)) {
2216                         Main *bmain = self->ptr.data;
2217                         const char *keylib_str = _PyUnicode_AsString(keylib);
2218                         lib = BLI_findstring(&bmain->library, keylib_str, offsetof(Library, name));
2219                         if (lib == NULL) {
2220                                 if (err_not_found) {
2221                                         PyErr_Format(PyExc_KeyError,
2222                                                      "%s: lib name '%.240s' "
2223                                                      "does not reference a valid library",
2224                                                      err_prefix, keylib_str);
2225                                         return -1;
2226                                 }
2227                                 else {
2228                                         return 0;
2229                                 }
2230
2231                         }
2232                 }
2233                 else {
2234                         PyErr_Format(PyExc_KeyError,
2235                                      "%s: lib must be a sting or None, not %.200s",
2236                                      err_prefix, Py_TYPE(keylib)->tp_name);
2237                         return -1;
2238                 }
2239
2240                 /* lib is either a valid pointer or NULL,
2241                  * either way can do direct comparison with id.lib */
2242
2243                 RNA_PROP_BEGIN (&self->ptr, itemptr, self->prop)
2244                 {
2245                         ID *id = itemptr.data; /* always an ID */
2246                         if (id->lib == lib && (STREQLEN(keyname, id->name + 2, sizeof(id->name) - 2))) {
2247                                 found = true;
2248                                 if (r_ptr) {
2249                                         *r_ptr = itemptr;
2250                                 }
2251                                 break;
2252                         }
2253                 }
2254                 RNA_PROP_END;
2255
2256                 /* we may want to fail silently as with collection.get() */
2257                 if ((found == false) && err_not_found) {
2258                         /* only runs for getitem access so use fixed string */
2259                         PyErr_SetString(PyExc_KeyError,
2260                                         "bpy_prop_collection[key, lib]: not found");
2261                         return -1;
2262                 }
2263                 else {
2264                         return found; /* 1 / 0, no exception */
2265                 }
2266         }
2267 }
2268
2269 static PyObject *pyrna_prop_collection_subscript_str_lib_pair(BPy_PropertyRNA *self, PyObject *key,
2270                                                               const char *err_prefix, const bool err_not_found)
2271 {
2272         PointerRNA ptr;
2273         const int contains = pyrna_prop_collection_subscript_str_lib_pair_ptr(self, key, err_prefix, err_not_found, &ptr);
2274
2275         if (contains == 1) {
2276                 return pyrna_struct_CreatePyObject(&ptr);
2277         }
2278         else {
2279                 return NULL;
2280         }
2281 }
2282
2283
2284 static PyObject *pyrna_prop_collection_subscript_slice(BPy_PropertyRNA *self, Py_ssize_t start, Py_ssize_t stop)
2285 {
2286         CollectionPropertyIterator rna_macro_iter;
2287         int count;
2288
2289         PyObject *list;
2290         PyObject *item;
2291
2292         PYRNA_PROP_CHECK_OBJ(self);
2293
2294         list = PyList_New(0);
2295
2296         /* skip to start */
2297         RNA_property_collection_begin(&self->ptr, self->prop, &rna_macro_iter);
2298         RNA_property_collection_skip(&rna_macro_iter, start);
2299
2300         /* add items until stop */
2301         for (count = start; rna_macro_iter.valid;
2302              RNA_property_collection_next(&rna_macro_iter))
2303         {
2304                 item = pyrna_struct_CreatePyObject(&rna_macro_iter.ptr);
2305                 PyList_APPEND(list, item);
2306
2307                 count++;
2308                 if (count == stop) {
2309                         break;
2310                 }
2311         }
2312
2313         RNA_property_collection_end(&rna_macro_iter);
2314
2315         return list;
2316 }
2317
2318 /* TODO - dimensions
2319  * note: could also use pyrna_prop_array_to_py_index(self, count) in a loop but its a lot slower
2320  * since at the moment it reads (and even allocates) the entire array for each index.
2321  */
2322 static PyObject *pyrna_prop_array_subscript_slice(BPy_PropertyArrayRNA *self, PointerRNA *ptr, PropertyRNA *prop,
2323                                                   Py_ssize_t start, Py_ssize_t stop, Py_ssize_t length)
2324 {
2325         int count, totdim;
2326         PyObject *tuple;
2327
2328         /* isn't needed, internal use only */
2329         // PYRNA_PROP_CHECK_OBJ((BPy_PropertyRNA *)self);
2330
2331         tuple = PyTuple_New(stop - start);
2332
2333         totdim = RNA_property_array_dimension(ptr, prop, NULL);
2334
2335         if (totdim > 1) {
2336                 for (count = start; count < stop; count++)
2337                         PyTuple_SET_ITEM(tuple, count - start, pyrna_prop_array_to_py_index(self, count));
2338         }
2339         else {
2340                 switch (RNA_property_type(prop)) {
2341                         case PROP_FLOAT:
2342                         {
2343                                 float values_stack[PYRNA_STACK_ARRAY];
2344                                 float *values;
2345                                 if (length > PYRNA_STACK_ARRAY) { values = PyMem_MALLOC(sizeof(float) * length); }
2346                                 else                            { values = values_stack; }
2347                                 RNA_property_float_get_array(ptr, prop, values);
2348
2349                                 for (count = start; count < stop; count++)
2350                                         PyTuple_SET_ITEM(tuple, count - start, PyFloat_FromDouble(values[count]));
2351
2352                                 if (values != values_stack) {
2353                                         PyMem_FREE(values);
2354                                 }
2355                                 break;
2356                         }
2357                         case PROP_BOOLEAN:
2358                         {
2359                                 int values_stack[PYRNA_STACK_ARRAY];
2360                                 int *values;
2361                                 if (length > PYRNA_STACK_ARRAY) { values = PyMem_MALLOC(sizeof(int) * length); }
2362                                 else                            { values = values_stack; }
2363
2364                                 RNA_property_boolean_get_array(ptr, prop, values);
2365                                 for (count = start; count < stop; count++)
2366                                         PyTuple_SET_ITEM(tuple, count - start, PyBool_FromLong(values[count]));
2367
2368                                 if (values != values_stack) {
2369                                         PyMem_FREE(values);
2370                                 }
2371                                 break;
2372                         }
2373                         case PROP_INT:
2374                         {
2375                                 int values_stack[PYRNA_STACK_ARRAY];
2376                                 int *values;
2377                                 if (length > PYRNA_STACK_ARRAY) { values = PyMem_MALLOC(sizeof(int) * length); }
2378                                 else                            { values = values_stack; }
2379
2380                                 RNA_property_int_get_array(ptr, prop, values);
2381                                 for (count = start; count < stop; count++)
2382                                         PyTuple_SET_ITEM(tuple, count - start, PyLong_FromLong(values[count]));
2383
2384                                 if (values != values_stack) {
2385                                         PyMem_FREE(values);
2386                                 }
2387                                 break;
2388                         }
2389                         default:
2390                                 BLI_assert(!"Invalid array type");
2391
2392                                 PyErr_SetString(PyExc_TypeError, "not an array type");
2393                                 Py_DECREF(tuple);
2394                                 tuple = NULL;
2395                                 break;
2396                 }
2397         }
2398         return tuple;
2399 }
2400
2401 static PyObject *pyrna_prop_collection_subscript(BPy_PropertyRNA *self, PyObject *key)
2402 {
2403         PYRNA_PROP_CHECK_OBJ(self);
2404
2405         if (PyUnicode_Check(key)) {
2406                 return pyrna_prop_collection_subscript_str(self, _PyUnicode_AsString(key));
2407         }
2408         else if (PyIndex_Check(key)) {
2409                 Py_ssize_t i = PyNumber_AsSsize_t(key, PyExc_IndexError);
2410                 if (i == -1 && PyErr_Occurred())
2411                         return NULL;
2412
2413                 return pyrna_prop_collection_subscript_int(self, i);
2414         }
2415         else if (PySlice_Check(key)) {
2416                 PySliceObject *key_slice = (PySliceObject *)key;
2417                 Py_ssize_t step = 1;
2418
2419                 if (key_slice->step != Py_None && !_PyEval_SliceIndex(key, &step)) {
2420                         return NULL;
2421                 }
2422                 else if (step != 1) {
2423                         PyErr_SetString(PyExc_TypeError, "bpy_prop_collection[slice]: slice steps not supported");
2424                         return NULL;
2425                 }
2426                 else if (key_slice->start == Py_None && key_slice->stop == Py_None) {
2427                         return pyrna_prop_collection_subscript_slice(self, 0, PY_SSIZE_T_MAX);
2428                 }
2429                 else {
2430                         Py_ssize_t start = 0, stop = PY_SSIZE_T_MAX;
2431
2432                         /* avoid PySlice_GetIndicesEx because it needs to know the length ahead of time. */
2433                         if (key_slice->start != Py_None && !_PyEval_SliceIndex(key_slice->start, &start)) return NULL;
2434                         if (key_slice->stop  != Py_None && !_PyEval_SliceIndex(key_slice->stop,  &stop))  return NULL;
2435
2436                         if (start < 0 || stop < 0) {
2437                                 /* only get the length for negative values */
2438                                 Py_ssize_t len = (Py_ssize_t)RNA_property_collection_length(&self->ptr, self->prop);
2439                                 if (start < 0) start += len;
2440                                 if (stop  < 0) stop  += len;
2441                         }
2442
2443                         if (stop - start <= 0) {
2444                                 return PyList_New(0);
2445                         }
2446                         else {
2447                                 return pyrna_prop_collection_subscript_slice(self, start, stop);
2448                         }
2449                 }
2450         }
2451         else if (PyTuple_Check(key)) {
2452                 /* special case, for ID datablocks we */
2453                 return pyrna_prop_collection_subscript_str_lib_pair(self, key,
2454                                                                     "bpy_prop_collection[id, lib]", true);
2455         }
2456         else {
2457                 PyErr_Format(PyExc_TypeError,
2458                              "bpy_prop_collection[key]: invalid key, "
2459                              "must be a string or an int, not %.200s",
2460                              Py_TYPE(key)->tp_name);
2461                 return NULL;
2462         }
2463 }
2464
2465 /* generic check to see if a PyObject is compatible with a collection
2466  * -1 on failure, 0 on success, sets the error */
2467 static int pyrna_prop_collection_type_check(BPy_PropertyRNA *self, PyObject *value)
2468 {
2469         StructRNA *prop_srna;
2470
2471         if (value == Py_None) {
2472                 if (RNA_property_flag(self->prop) & PROP_NEVER_NULL) {
2473                         PyErr_Format(PyExc_TypeError,
2474                                      "bpy_prop_collection[key] = value: invalid, "
2475                                      "this collection doesn't support None assignment");
2476                         return -1;
2477                 }
2478                 else {
2479                         return 0; /* None is OK */
2480                 }
2481         }
2482         else if (BPy_StructRNA_Check(value) == 0) {
2483                 PyErr_Format(PyExc_TypeError,
2484                              "bpy_prop_collection[key] = value: invalid, "
2485                              "expected a StructRNA type or None, not a %.200s",
2486                              Py_TYPE(value)->tp_name);
2487                 return -1;
2488         }
2489         else if ((prop_srna = RNA_property_pointer_type(&self->ptr, self->prop))) {
2490                 StructRNA *value_srna = ((BPy_StructRNA *)value)->ptr.type;
2491                 if (RNA_struct_is_a(value_srna, prop_srna) == 0) {
2492                         PyErr_Format(PyExc_TypeError,
2493                                      "bpy_prop_collection[key] = value: invalid, "
2494                                      "expected a '%.200s' type or None, not a '%.200s'",
2495                                      RNA_struct_identifier(prop_srna),
2496                                      RNA_struct_identifier(value_srna)
2497                                      );
2498                         return -1;
2499                 }
2500                 else {
2501                         return 0; /* OK, this is the correct type!*/
2502                 }
2503         }
2504
2505         PyErr_Format(PyExc_TypeError,
2506                      "bpy_prop_collection[key] = value: internal error, "
2507                      "failed to get the collection type");
2508         return -1;
2509 }
2510
2511 /* note: currently this is a copy of 'pyrna_prop_collection_subscript' with
2512  * large blocks commented, we may support slice/key indices later */
2513 static int pyrna_prop_collection_ass_subscript(BPy_PropertyRNA *self, PyObject *key, PyObject *value)
2514 {
2515         PYRNA_PROP_CHECK_INT(self);
2516
2517         /* validate the assigned value */
2518         if (value == NULL) {
2519                 PyErr_SetString(PyExc_TypeError,
2520                                 "del bpy_prop_collection[key]: not supported");
2521                 return -1;
2522         }
2523         else if (pyrna_prop_collection_type_check(self, value) == -1) {
2524                 return -1; /* exception is set */
2525         }
2526
2527 #if 0
2528         if (PyUnicode_Check(key)) {
2529                 return pyrna_prop_collection_subscript_str(self, _PyUnicode_AsString(key));
2530         }
2531         else
2532 #endif
2533         if (PyIndex_Check(key)) {
2534                 Py_ssize_t i = PyNumber_AsSsize_t(key, PyExc_IndexError);
2535                 if (i == -1 && PyErr_Occurred())
2536                         return -1;
2537
2538                 return pyrna_prop_collection_ass_subscript_int(self, i, value);
2539         }
2540 #if 0 /* TODO, fake slice assignment */
2541         else if (PySlice_Check(key)) {
2542                 PySliceObject *key_slice = (PySliceObject *)key;
2543                 Py_ssize_t step = 1;
2544
2545                 if (key_slice->step != Py_None && !_PyEval_SliceIndex(key, &step)) {
2546                         return NULL;
2547                 }
2548                 else if (step != 1) {
2549                         PyErr_SetString(PyExc_TypeError, "bpy_prop_collection[slice]: slice steps not supported");
2550                         return NULL;
2551                 }
2552                 else if (key_slice->start == Py_None && key_slice->stop == Py_None) {
2553                         return pyrna_prop_collection_subscript_slice(self, 0, PY_SSIZE_T_MAX);
2554                 }
2555                 else {
2556                         Py_ssize_t start = 0, stop = PY_SSIZE_T_MAX;
2557
2558                         /* avoid PySlice_GetIndicesEx because it needs to know the length ahead of time. */
2559                         if (key_slice->start != Py_None && !_PyEval_SliceIndex(key_slice->start, &start)) return NULL;
2560                         if (key_slice->stop != Py_None && !_PyEval_SliceIndex(key_slice->stop, &stop))    return NULL;
2561
2562                         if (start < 0 || stop < 0) {
2563                                 /* only get the length for negative values */
2564                                 Py_ssize_t len = (Py_ssize_t)RNA_property_collection_length(&self->ptr, self->prop);
2565                                 if (start < 0) start += len;
2566                                 if (stop  < 0) stop  += len;
2567                         }
2568
2569                         if (stop - start <= 0) {
2570                                 return PyList_New(0);
2571                         }
2572                         else {
2573                                 return pyrna_prop_collection_subscript_slice(self, start, stop);
2574                         }
2575                 }
2576         }
2577 #endif
2578         else {
2579                 PyErr_Format(PyExc_TypeError,
2580                              "bpy_prop_collection[key]: invalid key, "
2581                              "must be a string or an int, not %.200s",
2582                              Py_TYPE(key)->tp_name);
2583                 return -1;
2584         }
2585 }
2586
2587 static PyObject *pyrna_prop_array_subscript(BPy_PropertyArrayRNA *self, PyObject *key)
2588 {
2589         PYRNA_PROP_CHECK_OBJ((BPy_PropertyRNA *)self);
2590
2591 #if 0
2592         if (PyUnicode_Check(key)) {
2593                 return pyrna_prop_array_subscript_str(self, _PyUnicode_AsString(key));
2594         }
2595         else
2596 #endif
2597         if (PyIndex_Check(key)) {
2598                 Py_ssize_t i = PyNumber_AsSsize_t(key, PyExc_IndexError);
2599                 if (i == -1 && PyErr_Occurred())
2600                         return NULL;
2601                 return pyrna_prop_array_subscript_int(self, PyLong_AsLong(key));
2602         }
2603         else if (PySlice_Check(key)) {
2604                 Py_ssize_t step = 1;
2605                 PySliceObject *key_slice = (PySliceObject *)key;
2606
2607                 if (key_slice->step != Py_None && !_PyEval_SliceIndex(key, &step)) {
2608                         return NULL;
2609                 }
2610                 else if (step != 1) {
2611                         PyErr_SetString(PyExc_TypeError, "bpy_prop_array[slice]: slice steps not supported");
2612                         return NULL;
2613                 }
2614                 else if (key_slice->start == Py_None && key_slice->stop == Py_None) {
2615                         /* note, no significant advantage with optimizing [:] slice as with collections
2616                          * but include here for consistency with collection slice func */
2617                         Py_ssize_t len = (Py_ssize_t)pyrna_prop_array_length(self);
2618                         return pyrna_prop_array_subscript_slice(self, &self->ptr, self->prop, 0, len, len);
2619                 }
2620                 else {
2621                         int len = pyrna_prop_array_length(self);
2622                         Py_ssize_t start, stop, slicelength;
2623
2624                         if (PySlice_GetIndicesEx(key, len, &start, &stop, &step, &slicelength) < 0)
2625                                 return NULL;
2626
2627                         if (slicelength <= 0) {
2628                                 return PyTuple_New(0);
2629                         }
2630                         else {
2631                                 return pyrna_prop_array_subscript_slice(self, &self->ptr, self->prop, start, stop, len);
2632                         }
2633                 }
2634         }
2635         else {
2636                 PyErr_SetString(PyExc_AttributeError, "bpy_prop_array[key]: invalid key, key must be an int");
2637                 return NULL;
2638         }
2639 }
2640
2641 /* could call (pyrna_py_to_prop_array_index(self, i, value) in a loop but it is slow */
2642 static int prop_subscript_ass_array_slice(PointerRNA *ptr, PropertyRNA *prop,
2643                                           int start, int stop, int length, PyObject *value_orig)
2644 {
2645         PyObject *value;
2646         PyObject **value_items;
2647         int count;
2648         void *values_alloc = NULL;
2649         int ret = 0;
2650
2651         if (value_orig == NULL) {
2652                 PyErr_SetString(PyExc_TypeError,
2653                                 "bpy_prop_array[slice] = value: deleting with list types is not supported by bpy_struct");
2654                 return -1;
2655         }
2656
2657         if (!(value = PySequence_Fast(value_orig, "bpy_prop_array[slice] = value: assignment is not a sequence type"))) {
2658                 return -1;
2659         }
2660
2661         if (PySequence_Fast_GET_SIZE(value) != stop - start) {
2662                 Py_DECREF(value);
2663                 PyErr_SetString(PyExc_TypeError,
2664                                 "bpy_prop_array[slice] = value: re-sizing bpy_struct arrays isn't supported");
2665                 return -1;
2666         }
2667
2668         value_items = PySequence_Fast_ITEMS(value);
2669         switch (RNA_property_type(prop)) {
2670                 case PROP_FLOAT:
2671                 {
2672                         float values_stack[PYRNA_STACK_ARRAY];
2673                         float *values, fval;
2674
2675                         float min, max;
2676                         RNA_property_float_range(ptr, prop, &min, &max);
2677
2678                         if (length > PYRNA_STACK_ARRAY) { values = values_alloc = PyMem_MALLOC(sizeof(float) * length); }
2679                         else                            { values = values_stack; }
2680                         if (start != 0 || stop != length) /* partial assignment? - need to get the array */
2681                                 RNA_property_float_get_array(ptr, prop, values);
2682
2683                         for (count = start; count < stop; count++) {
2684                                 fval = PyFloat_AsDouble(value_items[count - start]);
2685                                 CLAMP(fval, min, max);
2686                                 values[count] = fval;
2687                         }
2688
2689                         if (PyErr_Occurred()) ret = -1;
2690                         else                  RNA_property_float_set_array(ptr, prop, values);
2691                         break;
2692                 }
2693                 case PROP_BOOLEAN:
2694                 {
2695                         int values_stack[PYRNA_STACK_ARRAY];
2696                         int *values;
2697                         if (length > PYRNA_STACK_ARRAY) { values = values_alloc = PyMem_MALLOC(sizeof(int) * length); }
2698                         else                            { values = values_stack; }
2699
2700                         if (start != 0 || stop != length) /* partial assignment? - need to get the array */
2701                                 RNA_property_boolean_get_array(ptr, prop, values);
2702
2703                         for (count = start; count < stop; count++)
2704                                 values[count] = PyLong_AsLong(value_items[count - start]);
2705
2706                         if (PyErr_Occurred()) ret = -1;
2707                         else                  RNA_property_boolean_set_array(ptr, prop, values);
2708                         break;
2709                 }
2710                 case PROP_INT:
2711                 {
2712                         int values_stack[PYRNA_STACK_ARRAY];
2713                         int *values, ival;
2714
2715                         int min, max;
2716                         RNA_property_int_range(ptr, prop, &min, &max);
2717
2718                         if (length > PYRNA_STACK_ARRAY) { values = values_alloc = PyMem_MALLOC(sizeof(int) * length); }
2719                         else                            { values = values_stack; }
2720
2721                         if (start != 0 || stop != length) /* partial assignment? - need to get the array */
2722                                 RNA_property_int_get_array(ptr, prop, values);
2723
2724                         for (count = start; count < stop; count++) {
2725                                 ival = PyLong_AsLong(value_items[count - start]);
2726                                 CLAMP(ival, min, max);
2727                                 values[count] = ival;
2728                         }
2729
2730                         if (PyErr_Occurred()) ret = -1;
2731                         else                  RNA_property_int_set_array(ptr, prop, values);
2732                         break;
2733                 }
2734                 default:
2735                         PyErr_SetString(PyExc_TypeError, "not an array type");
2736                         ret = -1;
2737                         break;
2738         }
2739
2740         Py_DECREF(value);
2741
2742         if (values_alloc) {
2743                 PyMem_FREE(values_alloc);
2744         }
2745
2746         return ret;
2747
2748 }
2749
2750 static int prop_subscript_ass_array_int(BPy_PropertyArrayRNA *self, Py_ssize_t keynum, PyObject *value)
2751 {
2752         int len;
2753
2754         PYRNA_PROP_CHECK_INT((BPy_PropertyRNA *)self);
2755
2756         len = pyrna_prop_array_length(self);
2757
2758         if (keynum < 0) keynum += len;
2759
2760         if (keynum >= 0 && keynum < len)
2761                 return pyrna_py_to_prop_array_index(self, keynum, value);
2762
2763         PyErr_SetString(PyExc_IndexError,
2764                         "bpy_prop_array[index] = value: index out of range");
2765         return -1;
2766 }
2767
2768 static int pyrna_prop_array_ass_subscript(BPy_PropertyArrayRNA *self, PyObject *key, PyObject *value)
2769 {
2770         /* char *keyname = NULL; */ /* not supported yet */
2771         int ret = -1;
2772
2773         PYRNA_PROP_CHECK_INT((BPy_PropertyRNA *)self);
2774
2775         if (!RNA_property_editable_flag(&self->ptr, self->prop)) {
2776                 PyErr_Format(PyExc_AttributeError,
2777                              "bpy_prop_collection: attribute \"%.200s\" from \"%.200s\" is read-only",
2778                              RNA_property_identifier(self->prop), RNA_struct_identifier(self->ptr.type));
2779                 ret = -1;
2780         }
2781
2782         else if (PyIndex_Check(key)) {
2783                 Py_ssize_t i = PyNumber_AsSsize_t(key, PyExc_IndexError);
2784                 if (i == -1 && PyErr_Occurred()) {
2785                         ret = -1;
2786                 }
2787                 else {
2788                         ret = prop_subscript_ass_array_int(self, i, value);
2789                 }
2790         }
2791         else if (PySlice_Check(key)) {
2792                 int len = RNA_property_array_length(&self->ptr, self->prop);
2793                 Py_ssize_t start, stop, step, slicelength;
2794
2795                 if (PySlice_GetIndicesEx(key, len, &start, &stop, &step, &slicelength) < 0) {
2796                         ret = -1;
2797                 }
2798                 else if (slicelength <= 0) {
2799                         ret = 0; /* do nothing */
2800                 }
2801                 else if (step == 1) {
2802                         ret = prop_subscript_ass_array_slice(&self->ptr, self->prop, start, stop, len, value);
2803                 }
2804                 else {
2805                         PyErr_SetString(PyExc_TypeError, "slice steps not supported with rna");
2806                         ret = -1;
2807                 }
2808         }
2809         else {
2810                 PyErr_SetString(PyExc_AttributeError, "invalid key, key must be an int");
2811                 ret = -1;
2812         }
2813
2814         if (ret != -1) {
2815                 if (RNA_property_update_check(self->prop)) {
2816                         RNA_property_update(BPy_GetContext(), &self->ptr, self->prop);
2817                 }
2818         }
2819
2820         return ret;
2821 }
2822
2823 /* for slice only */
2824 static PyMappingMethods pyrna_prop_array_as_mapping = {
2825         (lenfunc) pyrna_prop_array_length,               /* mp_length */
2826         (binaryfunc) pyrna_prop_array_subscript,         /* mp_subscript */
2827         (objobjargproc) pyrna_prop_array_ass_subscript,  /* mp_ass_subscript */
2828 };
2829
2830 static PyMappingMethods pyrna_prop_collection_as_mapping = {
2831         (lenfunc) pyrna_prop_collection_length,               /* mp_length */
2832         (binaryfunc) pyrna_prop_collection_subscript,         /* mp_subscript */
2833         (objobjargproc) pyrna_prop_collection_ass_subscript,  /* mp_ass_subscript */
2834 };
2835
2836 /* only for fast bool's, large structs, assign nb_bool on init */
2837 static PyNumberMethods pyrna_prop_array_as_number = {
2838         NULL, /* nb_add */
2839         NULL, /* nb_subtract */
2840         NULL, /* nb_multiply */
2841         NULL, /* nb_remainder */
2842         NULL, /* nb_divmod */
2843         NULL, /* nb_power */
2844         NULL, /* nb_negative */
2845         NULL, /* nb_positive */
2846         NULL, /* nb_absolute */
2847         (inquiry) pyrna_prop_array_bool, /* nb_bool */
2848 };
2849 static PyNumberMethods pyrna_prop_collection_as_number = {
2850         NULL, /* nb_add */
2851         NULL, /* nb_subtract */
2852         NULL, /* nb_multiply */
2853         NULL, /* nb_remainder */
2854         NULL, /* nb_divmod */
2855         NULL, /* nb_power */
2856         NULL, /* nb_negative */
2857         NULL, /* nb_positive */
2858         NULL, /* nb_absolute */
2859         (inquiry) pyrna_prop_collection_bool, /* nb_bool */
2860 };
2861
2862 static int pyrna_prop_array_contains(BPy_PropertyRNA *self, PyObject *value)
2863 {
2864         return pyrna_array_contains_py(&self->ptr, self->prop, value);
2865 }
2866
2867 static int pyrna_prop_collection_contains(BPy_PropertyRNA *self, PyObject *key)
2868 {
2869         PointerRNA newptr; /* not used, just so RNA_property_collection_lookup_string runs */
2870
2871         if (PyTuple_Check(key)) {
2872                 /* special case, for ID datablocks we */
2873                 return pyrna_prop_collection_subscript_str_lib_pair_ptr(self, key,
2874                                                                         "(id, lib) in bpy_prop_collection", false, NULL);
2875         }
2876         else {
2877
2878                 /* key in dict style check */
2879                 const char *keyname = _PyUnicode_AsString(key);
2880
2881                 if (keyname == NULL) {
2882                         PyErr_SetString(PyExc_TypeError,
2883                                         "bpy_prop_collection.__contains__: expected a string or a tuple of strings");
2884                         return -1;
2885                 }
2886
2887                 if (RNA_property_collection_lookup_string(&self->ptr, self->prop, keyname, &newptr))
2888                         return 1;
2889
2890                 return 0;
2891         }
2892 }
2893
2894 static int pyrna_struct_contains(BPy_StructRNA *self, PyObject *value)
2895 {
2896         IDProperty *group;
2897         const char *name = _PyUnicode_AsString(value);
2898
2899         PYRNA_STRUCT_CHECK_INT(self);
2900
2901         if (!name) {
2902                 PyErr_SetString(PyExc_TypeError, "bpy_struct.__contains__: expected a string");
2903                 return -1;
2904         }
2905
2906         if (RNA_struct_idprops_check(self->ptr.type) == 0) {
2907                 PyErr_SetString(PyExc_TypeError, "bpy_struct: this type doesn't support IDProperties");
2908                 return -1;
2909         }
2910
2911         group = RNA_struct_idprops(&self->ptr, 0);
2912
2913         if (!group)
2914                 return 0;
2915
2916         return IDP_GetPropertyFromGroup(group, name) ? 1 : 0;
2917 }
2918
2919 static PySequenceMethods pyrna_prop_array_as_sequence = {
2920         (lenfunc)pyrna_prop_array_length,
2921         NULL,       /* sq_concat */
2922         NULL,       /* sq_repeat */
2923         (ssizeargfunc)pyrna_prop_array_subscript_int, /* sq_item */ /* Only set this so PySequence_Check() returns True */
2924         NULL,       /* sq_slice */
2925         (ssizeobjargproc)prop_subscript_ass_array_int,      /* sq_ass_item */
2926         NULL,       /* *was* sq_ass_slice */
2927         (objobjproc)pyrna_prop_array_contains,  /* sq_contains */
2928         (binaryfunc) NULL, /* sq_inplace_concat */
2929         (ssizeargfunc) NULL, /* sq_inplace_repeat */
2930 };
2931
2932 static PySequenceMethods pyrna_prop_collection_as_sequence = {
2933         (lenfunc)pyrna_prop_collection_length,
2934         NULL,       /* sq_concat */
2935         NULL,       /* sq_repeat */
2936         (ssizeargfunc)pyrna_prop_collection_subscript_int, /* sq_item */ /* Only set this so PySequence_Check() returns True */
2937         NULL,       /* *was* sq_slice */
2938         (ssizeobjargproc)/* pyrna_prop_collection_ass_subscript_int */ NULL /* let mapping take this one */, /* sq_ass_item */
2939         NULL,       /* *was* sq_ass_slice */
2940         (objobjproc)pyrna_prop_collection_contains, /* sq_contains */
2941         (binaryfunc) NULL, /* sq_inplace_concat */
2942         (ssizeargfunc) NULL, /* sq_inplace_repeat */
2943 };
2944
2945 static PySequenceMethods pyrna_struct_as_sequence = {
2946         NULL,       /* Cant set the len otherwise it can evaluate as false */
2947         NULL,       /* sq_concat */
2948         NULL,       /* sq_repeat */
2949         NULL,       /* sq_item */ /* Only set this so PySequence_Check() returns True */
2950         NULL,       /* *was* sq_slice */
2951         NULL,       /* sq_ass_item */
2952         NULL,       /* *was* sq_ass_slice */
2953         (objobjproc)pyrna_struct_contains,  /* sq_contains */
2954         (binaryfunc) NULL, /* sq_inplace_concat */
2955         (ssizeargfunc) NULL, /* sq_inplace_repeat */
2956 };
2957
2958 static PyObject *pyrna_struct_subscript(BPy_StructRNA *self, PyObject *key)
2959 {
2960         /* mostly copied from BPy_IDGroup_Map_GetItem */
2961         IDProperty *group, *idprop;
2962         const char *name = _PyUnicode_AsString(key);
2963