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