PyRNA: enum no longer returns first item when the value isn't found
[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 (%s)",
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                         {
1405                                 /* Static, no need to free. */
1406                                 const EnumPropertyItem *enum_item;
1407                                 bool free_dummy;
1408                                 RNA_property_enum_items_ex(NULL, ptr, prop, true, &enum_item, NULL, &free_dummy);
1409                                 BLI_assert(!free_dummy);
1410
1411                                 /* Do not print warning in case of DummyRNA_NULL_items, this one will never match any value... */
1412                                 if (enum_item != DummyRNA_NULL_items) {
1413                                         const char *ptr_name = RNA_struct_name_get_alloc(ptr, NULL, 0, NULL);
1414
1415                                         /* prefer not fail silently in case of api errors, maybe disable it later */
1416                                         CLOG_WARN(BPY_LOG_RNA,
1417                                                   "current value '%d' "
1418                                                   "matches no enum in '%s', '%s', '%s'",
1419                                                   val, RNA_struct_identifier(ptr->type),
1420                                                   ptr_name, RNA_property_identifier(prop));
1421
1422 #if 0                           /* gives python decoding errors while generating docs :( */
1423                                         char error_str[256];
1424                                         BLI_snprintf(error_str, sizeof(error_str),
1425                                                      "RNA Warning: 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                                         PyErr_Warn(PyExc_RuntimeWarning, error_str);
1431 #endif
1432
1433                                         if (ptr_name)
1434                                                 MEM_freeN((void *)ptr_name);
1435                                 }
1436
1437                                 ret = PyUnicode_FromString("");
1438                         }
1439 #if 0
1440                         PyErr_Format(PyExc_AttributeError,
1441                                      "RNA Error: Current value \"%d\" matches no enum", val);
1442                         ret = NULL;
1443 #endif
1444                 }
1445         }
1446
1447         return ret;
1448 }
1449
1450 PyObject *pyrna_prop_to_py(PointerRNA *ptr, PropertyRNA *prop)
1451 {
1452         PyObject *ret;
1453         const int type = RNA_property_type(prop);
1454
1455         if (RNA_property_array_check(prop)) {
1456                 return pyrna_py_from_array(ptr, prop);
1457         }
1458
1459         /* see if we can coerce into a python type - PropertyType */
1460         switch (type) {
1461                 case PROP_BOOLEAN:
1462                         ret = PyBool_FromLong(RNA_property_boolean_get(ptr, prop));
1463                         break;
1464                 case PROP_INT:
1465                         ret = PyLong_FromLong(RNA_property_int_get(ptr, prop));
1466                         break;
1467                 case PROP_FLOAT:
1468                         ret = PyFloat_FromDouble(RNA_property_float_get(ptr, prop));
1469                         break;
1470                 case PROP_STRING:
1471                 {
1472                         const int subtype = RNA_property_subtype(prop);
1473                         const char *buf;
1474                         int buf_len;
1475                         char buf_fixed[32];
1476
1477                         buf = RNA_property_string_get_alloc(ptr, prop, buf_fixed, sizeof(buf_fixed), &buf_len);
1478 #ifdef USE_STRING_COERCE
1479                         /* only file paths get special treatment, they may contain non utf-8 chars */
1480                         if (subtype == PROP_BYTESTRING) {
1481                                 ret = PyBytes_FromStringAndSize(buf, buf_len);
1482                         }
1483                         else if (ELEM(subtype, PROP_FILEPATH, PROP_DIRPATH, PROP_FILENAME)) {
1484                                 ret = PyC_UnicodeFromByteAndSize(buf, buf_len);
1485                         }
1486                         else {
1487                                 ret = PyUnicode_FromStringAndSize(buf, buf_len);
1488                         }
1489 #else  /* USE_STRING_COERCE */
1490                         if (subtype == PROP_BYTESTRING) {
1491                                 ret = PyBytes_FromStringAndSize(buf, buf_len);
1492                         }
1493                         else {
1494                                 ret = PyUnicode_FromStringAndSize(buf, buf_len);
1495                         }
1496 #endif  /* USE_STRING_COERCE */
1497                         if (buf_fixed != buf) {
1498                                 MEM_freeN((void *)buf);
1499                         }
1500                         break;
1501                 }
1502                 case PROP_ENUM:
1503                 {
1504                         ret = pyrna_enum_to_py(ptr, prop, RNA_property_enum_get(ptr, prop));
1505                         break;
1506                 }
1507                 case PROP_POINTER:
1508                 {
1509                         PointerRNA newptr;
1510                         newptr = RNA_property_pointer_get(ptr, prop);
1511                         if (newptr.data) {
1512                                 ret = pyrna_struct_CreatePyObject(&newptr);
1513                         }
1514                         else {
1515                                 ret = Py_None;
1516                                 Py_INCREF(ret);
1517                         }
1518                         break;
1519                 }
1520                 case PROP_COLLECTION:
1521                         ret = pyrna_prop_CreatePyObject(ptr, prop);
1522                         break;
1523                 default:
1524                         PyErr_Format(PyExc_TypeError,
1525                                      "bpy_struct internal error: unknown type '%d' (pyrna_prop_to_py)", type);
1526                         ret = NULL;
1527                         break;
1528         }
1529
1530         return ret;
1531 }
1532
1533 /**
1534  * This function is used by operators and converting dicts into collections.
1535  * Its takes keyword args and fills them with property values
1536  */
1537 int pyrna_pydict_to_props(
1538         PointerRNA *ptr, PyObject *kw, const bool all_args,
1539         const char *error_prefix)
1540 {
1541         int error_val = 0;
1542         int totkw;
1543         const char *arg_name = NULL;
1544         PyObject *item;
1545
1546         totkw = kw ? PyDict_Size(kw) : 0;
1547
1548         RNA_STRUCT_BEGIN (ptr, prop)
1549         {
1550                 arg_name = RNA_property_identifier(prop);
1551
1552                 if (STREQ(arg_name, "rna_type")) {
1553                         continue;
1554                 }
1555
1556                 if (kw == NULL) {
1557                         PyErr_Format(PyExc_TypeError,
1558                                      "%.200s: no keywords, expected \"%.200s\"",
1559                                      error_prefix, arg_name ? arg_name : "<UNKNOWN>");
1560                         error_val = -1;
1561                         break;
1562                 }
1563
1564                 item = PyDict_GetItemString(kw, arg_name); /* wont set an error */
1565
1566                 if (item == NULL) {
1567                         if (all_args) {
1568                                 PyErr_Format(PyExc_TypeError,
1569                                              "%.200s: keyword \"%.200s\" missing",
1570                                              error_prefix, arg_name ? arg_name : "<UNKNOWN>");
1571                                 error_val = -1; /* pyrna_py_to_prop sets the error */
1572                                 break;
1573                         }
1574                 }
1575                 else {
1576                         if (pyrna_py_to_prop(ptr, prop, NULL, item, error_prefix)) {
1577                                 error_val = -1;
1578                                 break;
1579                         }
1580                         totkw--;
1581                 }
1582         }
1583         RNA_STRUCT_END;
1584
1585         if (error_val == 0 && totkw > 0) { /* some keywords were given that were not used :/ */
1586                 PyObject *key, *value;
1587                 Py_ssize_t pos = 0;
1588
1589                 while (PyDict_Next(kw, &pos, &key, &value)) {
1590                         arg_name = _PyUnicode_AsString(key);
1591                         if (RNA_struct_find_property(ptr, arg_name) == NULL) break;
1592                         arg_name = NULL;
1593                 }
1594
1595                 PyErr_Format(PyExc_TypeError,
1596                              "%.200s: keyword \"%.200s\" unrecognized",
1597                              error_prefix, arg_name ? arg_name : "<UNKNOWN>");
1598                 error_val = -1;
1599         }
1600
1601         return error_val;
1602 }
1603
1604
1605 static PyObject *pyrna_func_to_py(const PointerRNA *ptr, FunctionRNA *func)
1606 {
1607         BPy_FunctionRNA *pyfunc = (BPy_FunctionRNA *) PyObject_NEW(BPy_FunctionRNA, &pyrna_func_Type);
1608         pyfunc->ptr = *ptr;
1609         pyfunc->func = func;
1610         return (PyObject *)pyfunc;
1611 }
1612
1613
1614 static int pyrna_py_to_prop(
1615         PointerRNA *ptr, PropertyRNA *prop, void *data, PyObject *value,
1616         const char *error_prefix)
1617 {
1618         /* XXX hard limits should be checked here */
1619         const int type = RNA_property_type(prop);
1620
1621
1622         if (RNA_property_array_check(prop)) {
1623                 /* done getting the length */
1624                 if (pyrna_py_to_array(ptr, prop, data, value, error_prefix) == -1) {
1625                         return -1;
1626                 }
1627         }
1628         else {
1629                 /* Normal Property (not an array) */
1630
1631                 /* see if we can coerce into a python type - PropertyType */
1632                 switch (type) {
1633                         case PROP_BOOLEAN:
1634                         {
1635                                 int param;
1636                                 /* prefer not to have an exception here
1637                                  * however so many poll functions return None or a valid Object.
1638                                  * its a hassle to convert these into a bool before returning, */
1639                                 if (RNA_parameter_flag(prop) & PARM_OUTPUT) {
1640                                         param = PyObject_IsTrue(value);
1641                                 }
1642                                 else {
1643                                         param = PyC_Long_AsI32(value);
1644
1645                                         if (UNLIKELY(param & ~1)) {  /* only accept 0/1 */
1646                                                 param = -1;              /* error out below */
1647                                         }
1648                                 }
1649
1650                                 if (param == -1) {
1651                                         PyErr_Format(PyExc_TypeError,
1652                                                      "%.200s %.200s.%.200s expected True/False or 0/1, not %.200s",
1653                                                      error_prefix, RNA_struct_identifier(ptr->type),
1654                                                      RNA_property_identifier(prop), Py_TYPE(value)->tp_name);
1655                                         return -1;
1656                                 }
1657                                 else {
1658                                         if (data) *((bool *)data) = param;
1659                                         else RNA_property_boolean_set(ptr, prop, param);
1660                                 }
1661                                 break;
1662                         }
1663                         case PROP_INT:
1664                         {
1665                                 int overflow;
1666                                 long param = PyLong_AsLongAndOverflow(value, &overflow);
1667                                 if (overflow || (param > INT_MAX) || (param < INT_MIN)) {
1668                                         PyErr_Format(PyExc_ValueError,
1669                                                      "%.200s %.200s.%.200s value not in 'int' range "
1670                                                      "(" STRINGIFY(INT_MIN) ", " STRINGIFY(INT_MAX) ")",
1671                                                      error_prefix, RNA_struct_identifier(ptr->type),
1672                                                      RNA_property_identifier(prop));
1673                                         return -1;
1674                                 }
1675                                 else if (param == -1 && PyErr_Occurred()) {
1676                                         PyErr_Format(PyExc_TypeError,
1677                                                      "%.200s %.200s.%.200s expected an int type, not %.200s",
1678                                                      error_prefix, RNA_struct_identifier(ptr->type),
1679                                                      RNA_property_identifier(prop), Py_TYPE(value)->tp_name);
1680                                         return -1;
1681                                 }
1682                                 else {
1683                                         int param_i = (int)param;
1684                                         if (data) {
1685                                                 RNA_property_int_clamp(ptr, prop, &param_i);
1686                                                 *((int *)data) = param_i;
1687                                         }
1688                                         else {
1689                                                 RNA_property_int_set(ptr, prop, param_i);
1690                                         }
1691                                 }
1692                                 break;
1693                         }
1694                         case PROP_FLOAT:
1695                         {
1696                                 float param = PyFloat_AsDouble(value);
1697                                 if (PyErr_Occurred()) {
1698                                         PyErr_Format(PyExc_TypeError,
1699                                                      "%.200s %.200s.%.200s expected a float type, not %.200s",
1700                                                      error_prefix, RNA_struct_identifier(ptr->type),
1701                                                      RNA_property_identifier(prop), Py_TYPE(value)->tp_name);
1702                                         return -1;
1703                                 }
1704                                 else {
1705                                         if (data) {
1706                                                 RNA_property_float_clamp(ptr, prop, (float *)&param);
1707                                                 *((float *)data) = param;
1708                                         }
1709                                         else {
1710                                                 RNA_property_float_set(ptr, prop, param);
1711                                         }
1712                                 }
1713                                 break;
1714                         }
1715                         case PROP_STRING:
1716                         {
1717                                 const int subtype = RNA_property_subtype(prop);
1718                                 const char *param;
1719
1720                                 if (value == Py_None) {
1721                                         if ((RNA_property_flag(prop) & PROP_NEVER_NULL) == 0) {
1722                                                 if (data) {
1723                                                         *((char **)data) = (char *)NULL;
1724                                                 }
1725                                                 else {
1726                                                         RNA_property_string_set(ptr, prop, NULL);
1727                                                 }
1728                                         }
1729                                         else {
1730                                                 PyC_Err_Format_Prefix(
1731                                                         PyExc_TypeError,
1732                                                         "%.200s %.200s.%.200s doesn't support None from string types",
1733                                                         error_prefix, RNA_struct_identifier(ptr->type),
1734                                                         RNA_property_identifier(prop));
1735                                                 return -1;
1736                                         }
1737                                 }
1738                                 else if (subtype == PROP_BYTESTRING) {
1739
1740                                         /* Byte String */
1741
1742                                         param = PyBytes_AsString(value);
1743
1744                                         if (param == NULL) {
1745                                                 if (PyBytes_Check(value)) {
1746                                                         /* there was an error assigning a string type,
1747                                                          * rather than setting a new error, prefix the existing one
1748                                                          */
1749                                                         PyC_Err_Format_Prefix(PyExc_TypeError,
1750                                                                               "%.200s %.200s.%.200s error assigning bytes",
1751                                                                               error_prefix, RNA_struct_identifier(ptr->type),
1752                                                                               RNA_property_identifier(prop));
1753                                                 }
1754                                                 else {
1755                                                         PyErr_Format(PyExc_TypeError,
1756                                                                      "%.200s %.200s.%.200s expected a bytes type, not %.200s",
1757                                                                      error_prefix, RNA_struct_identifier(ptr->type),
1758                                                                      RNA_property_identifier(prop), Py_TYPE(value)->tp_name);
1759                                                 }
1760
1761                                                 return -1;
1762                                         }
1763                                         else {
1764                                                 if (data) *((char **)data) = (char *)param;
1765                                                 else RNA_property_string_set_bytes(ptr, prop, param, PyBytes_Size(value));
1766                                         }
1767                                 }
1768                                 else {
1769                                         /* Unicode String */
1770 #ifdef USE_STRING_COERCE
1771                                         PyObject *value_coerce = NULL;
1772                                         if (ELEM(subtype, PROP_FILEPATH, PROP_DIRPATH, PROP_FILENAME)) {
1773                                                 /* TODO, get size */
1774                                                 param = PyC_UnicodeAsByte(value, &value_coerce);
1775                                         }
1776                                         else {
1777                                                 param = _PyUnicode_AsString(value);
1778                                         }
1779 #else  /* USE_STRING_COERCE */
1780                                         param = _PyUnicode_AsString(value);
1781 #endif  /* USE_STRING_COERCE */
1782
1783                                         if (param == NULL) {
1784                                                 if (PyUnicode_Check(value)) {
1785                                                         /* there was an error assigning a string type,
1786                                                          * rather than setting a new error, prefix the existing one
1787                                                          */
1788                                                         PyC_Err_Format_Prefix(PyExc_TypeError,
1789                                                                               "%.200s %.200s.%.200s error assigning string",
1790                                                                               error_prefix, RNA_struct_identifier(ptr->type),
1791                                                                               RNA_property_identifier(prop));
1792                                                 }
1793                                                 else {
1794                                                         PyErr_Format(PyExc_TypeError,
1795                                                                      "%.200s %.200s.%.200s expected a string type, not %.200s",
1796                                                                      error_prefix, RNA_struct_identifier(ptr->type),
1797                                                                      RNA_property_identifier(prop), Py_TYPE(value)->tp_name);
1798                                                 }
1799
1800                                                 return -1;
1801                                         }
1802                                         else {
1803                                                 /* same as bytes */
1804                                                 /* XXX, this is suspect but needed for function calls, need to see if theres a better way */
1805                                                 if (data) *((char **)data) = (char *)param;
1806                                                 else RNA_property_string_set(ptr, prop, param);
1807                                         }
1808 #ifdef USE_STRING_COERCE
1809                                         Py_XDECREF(value_coerce);
1810 #endif  /* USE_STRING_COERCE */
1811                                 }
1812                                 break;
1813                         }
1814                         case PROP_ENUM:
1815                         {
1816                                 int val = 0;
1817
1818                                 /* type checkins is done by each function */
1819                                 if (RNA_property_flag(prop) & PROP_ENUM_FLAG) {
1820                                         /* set of enum items, concatenate all values with OR */
1821                                         if (pyrna_prop_to_enum_bitfield(ptr, prop, value, &val, error_prefix) == -1) {
1822                                                 return -1;
1823                                         }
1824                                 }
1825                                 else {
1826                                         /* simple enum string */
1827                                         if (pyrna_string_to_enum(value, ptr, prop, &val, error_prefix) == -1) {
1828                                                 return -1;
1829                                         }
1830                                 }
1831
1832                                 if (data) *((int *)data) = val;
1833                                 else RNA_property_enum_set(ptr, prop, val);
1834
1835                                 break;
1836                         }
1837                         case PROP_POINTER:
1838                         {
1839                                 PyObject *value_new = NULL;
1840
1841                                 StructRNA *ptr_type = RNA_property_pointer_type(ptr, prop);
1842                                 int flag = RNA_property_flag(prop);
1843                                 int flag_parameter = RNA_parameter_flag(prop);
1844
1845                                 /* this is really nasty!, so we can fake the operator having direct properties eg:
1846                                  * layout.prop(self, "filepath")
1847                                  * ... which in fact should be
1848                                  * layout.prop(self.properties, "filepath")
1849                                  *
1850                                  * we need to do this trick.
1851                                  * if the prop is not an operator type and the pyobject is an operator,
1852                                  * use its properties in place of its self.
1853                                  *
1854                                  * this is so bad that its almost a good reason to do away with fake 'self.properties -> self'
1855                                  * class mixing if this causes problems in the future it should be removed.
1856                                  */
1857                                 if ((ptr_type == &RNA_AnyType) &&
1858                                     (BPy_StructRNA_Check(value)))
1859                                 {
1860                                         const StructRNA *base_type =
1861                                                 RNA_struct_base_child_of(((const BPy_StructRNA *)value)->ptr.type, NULL);
1862                                         if (ELEM(base_type, &RNA_Operator, &RNA_Gizmo)) {
1863                                                 value = PyObject_GetAttr(value, bpy_intern_str_properties);
1864                                                 value_new = value;
1865                                         }
1866                                 }
1867
1868                                 /* if property is an OperatorProperties/GizmoProperties pointer and value is a map,
1869                                  * forward back to pyrna_pydict_to_props */
1870                                 if (PyDict_Check(value)) {
1871                                         const StructRNA *base_type = RNA_struct_base_child_of(ptr_type, NULL);
1872                                         if (base_type == &RNA_OperatorProperties) {
1873                                                 PointerRNA opptr = RNA_property_pointer_get(ptr, prop);
1874                                                 return pyrna_pydict_to_props(&opptr, value, false, error_prefix);
1875                                         }
1876                                         else if (base_type == &RNA_GizmoProperties) {
1877                                                 PointerRNA opptr = RNA_property_pointer_get(ptr, prop);
1878                                                 return pyrna_pydict_to_props(&opptr, value, false, error_prefix);
1879                                         }
1880                                 }
1881
1882                                 /* another exception, allow to pass a collection as an RNA property */
1883                                 if (Py_TYPE(value) == &pyrna_prop_collection_Type) { /* ok to ignore idprop collections */
1884                                         PointerRNA c_ptr;
1885                                         BPy_PropertyRNA *value_prop = (BPy_PropertyRNA *)value;
1886                                         if (RNA_property_collection_type_get(&value_prop->ptr, value_prop->prop, &c_ptr)) {
1887                                                 value = pyrna_struct_CreatePyObject(&c_ptr);
1888                                                 value_new = value;
1889                                         }
1890                                         else {
1891                                                 PyErr_Format(PyExc_TypeError,
1892                                                              "%.200s %.200s.%.200s collection has no type, "
1893                                                              "cant be used as a %.200s type",
1894                                                              error_prefix, RNA_struct_identifier(ptr->type),
1895                                                              RNA_property_identifier(prop), RNA_struct_identifier(ptr_type));
1896                                                 return -1;
1897                                         }
1898                                 }
1899
1900                                 if (!BPy_StructRNA_Check(value) && value != Py_None) {
1901                                         PyErr_Format(PyExc_TypeError,
1902                                                      "%.200s %.200s.%.200s expected a %.200s type, not %.200s",
1903                                                      error_prefix, RNA_struct_identifier(ptr->type),
1904                                                      RNA_property_identifier(prop), RNA_struct_identifier(ptr_type),
1905                                                      Py_TYPE(value)->tp_name);
1906                                         Py_XDECREF(value_new); return -1;
1907                                 }
1908                                 else if ((flag & PROP_NEVER_NULL) && value == Py_None) {
1909                                         PyErr_Format(PyExc_TypeError,
1910                                                      "%.200s %.200s.%.200s does not support a 'None' assignment %.200s type",
1911                                                      error_prefix, RNA_struct_identifier(ptr->type),
1912                                                      RNA_property_identifier(prop), RNA_struct_identifier(ptr_type));
1913                                         Py_XDECREF(value_new); return -1;
1914                                 }
1915                                 else if ((value != Py_None) &&
1916                                          ((flag & PROP_ID_SELF_CHECK) && ptr->id.data == ((BPy_StructRNA *)value)->ptr.id.data))
1917                                 {
1918                                         PyErr_Format(PyExc_TypeError,
1919                                                      "%.200s %.200s.%.200s ID type does not support assignment to its self",
1920                                                      error_prefix, RNA_struct_identifier(ptr->type),
1921                                                      RNA_property_identifier(prop));
1922                                         Py_XDECREF(value_new); return -1;
1923                                 }
1924                                 else {
1925                                         BPy_StructRNA *param = (BPy_StructRNA *)value;
1926                                         bool raise_error = false;
1927                                         if (data) {
1928
1929                                                 if (flag_parameter & PARM_RNAPTR) {
1930                                                         if (flag & PROP_THICK_WRAP) {
1931                                                                 if (value == Py_None)
1932                                                                         memset(data, 0, sizeof(PointerRNA));
1933                                                                 else if (RNA_struct_is_a(param->ptr.type, ptr_type))
1934                                                                         *((PointerRNA *)data) = param->ptr;
1935                                                                 else
1936                                                                         raise_error = true;
1937                                                         }
1938                                                         else {
1939                                                                 /* for function calls, we sometimes want to pass the 'ptr' directly,
1940                                                                  * watch out that it remains valid!, possibly we could support this later if needed */
1941                                                                 BLI_assert(value_new == NULL);
1942                                                                 if (value == Py_None)
1943                                                                         *((void **)data) = NULL;
1944                                                                 else if (RNA_struct_is_a(param->ptr.type, ptr_type))
1945                                                                         *((PointerRNA **)data) = &param->ptr;
1946                                                                 else
1947                                                                         raise_error = true;
1948                                                         }
1949                                                 }
1950                                                 else if (value == Py_None) {
1951                                                         *((void **)data) = NULL;
1952                                                 }
1953                                                 else if (RNA_struct_is_a(param->ptr.type, ptr_type)) {
1954                                                         *((void **)data) = param->ptr.data;
1955                                                 }
1956                                                 else {
1957                                                         raise_error = true;
1958                                                 }
1959                                         }
1960                                         else {
1961                                                 /* data == NULL, assign to RNA */
1962                                                 if (value == Py_None || RNA_struct_is_a(param->ptr.type, ptr_type))
1963                                                         RNA_property_pointer_set(ptr, prop, value == Py_None ? PointerRNA_NULL : param->ptr);
1964                                                 else
1965                                                         raise_error = true;
1966                                         }
1967
1968                                         if (raise_error) {
1969                                                 if (pyrna_struct_validity_check(param) == -1) {
1970                                                         /* error set */
1971                                                 }
1972                                                 else {
1973                                                         PointerRNA tmp;
1974                                                         RNA_pointer_create(NULL, ptr_type, NULL, &tmp);
1975                                                         PyErr_Format(PyExc_TypeError,
1976                                                                      "%.200s %.200s.%.200s expected a %.200s type, not %.200s",
1977                                                                      error_prefix, RNA_struct_identifier(ptr->type),
1978                                                                      RNA_property_identifier(prop), RNA_struct_identifier(tmp.type),
1979                                                                      RNA_struct_identifier(param->ptr.type));
1980                                                 }
1981                                                 Py_XDECREF(value_new); return -1;
1982                                         }
1983                                 }
1984
1985                                 Py_XDECREF(value_new);
1986
1987                                 break;
1988                         }
1989                         case PROP_COLLECTION:
1990                         {
1991                                 Py_ssize_t seq_len, i;
1992                                 PyObject *item;
1993                                 PointerRNA itemptr;
1994                                 ListBase *lb;
1995                                 CollectionPointerLink *link;
1996
1997                                 lb = (data) ? (ListBase *)data : NULL;
1998
1999                                 /* convert a sequence of dict's into a collection */
2000                                 if (!PySequence_Check(value)) {
2001                                         PyErr_Format(PyExc_TypeError,
2002                                                      "%.200s %.200s.%.200s expected a sequence for an RNA collection, not %.200s",
2003                                                      error_prefix, RNA_struct_identifier(ptr->type),
2004                                                      RNA_property_identifier(prop), Py_TYPE(value)->tp_name);
2005                                         return -1;
2006                                 }
2007
2008                                 seq_len = PySequence_Size(value);
2009                                 for (i = 0; i < seq_len; i++) {
2010                                         item = PySequence_GetItem(value, i);
2011
2012                                         if (item == NULL) {
2013                                                 PyErr_Format(PyExc_TypeError,
2014                                                              "%.200s %.200s.%.200s failed to get sequence index '%d' for an RNA collection",
2015                                                              error_prefix, RNA_struct_identifier(ptr->type),
2016                                                              RNA_property_identifier(prop), i);
2017                                                 Py_XDECREF(item);
2018                                                 return -1;
2019                                         }
2020
2021                                         if (PyDict_Check(item) == 0) {
2022                                                 PyErr_Format(PyExc_TypeError,
2023                                                              "%.200s %.200s.%.200s expected a each sequence "
2024                                                              "member to be a dict for an RNA collection, not %.200s",
2025                                                              error_prefix, RNA_struct_identifier(ptr->type),
2026                                                              RNA_property_identifier(prop), Py_TYPE(item)->tp_name);
2027                                                 Py_XDECREF(item);
2028                                                 return -1;
2029                                         }
2030
2031                                         if (lb) {
2032                                                 link = MEM_callocN(sizeof(CollectionPointerLink), "PyCollectionPointerLink");
2033                                                 link->ptr = itemptr;
2034                                                 BLI_addtail(lb, link);
2035                                         }
2036                                         else
2037                                                 RNA_property_collection_add(ptr, prop, &itemptr);
2038
2039                                         if (pyrna_pydict_to_props(
2040                                                 &itemptr, item, true,
2041                                                 "Converting a python list to an RNA collection") == -1)
2042                                         {
2043                                                 PyObject *msg = PyC_ExceptionBuffer();
2044                                                 const char *msg_char = _PyUnicode_AsString(msg);
2045
2046                                                 PyErr_Format(PyExc_TypeError,
2047                                                              "%.200s %.200s.%.200s error converting a member of a collection "
2048                                                              "from a dicts into an RNA collection, failed with: %s",
2049                                                              error_prefix, RNA_struct_identifier(ptr->type),
2050                                                              RNA_property_identifier(prop), msg_char);
2051
2052                                                 Py_DECREF(item);
2053                                                 Py_DECREF(msg);
2054                                                 return -1;
2055                                         }
2056                                         Py_DECREF(item);
2057                                 }
2058
2059                                 break;
2060                         }
2061                         default:
2062                                 PyErr_Format(PyExc_AttributeError,
2063                                              "%.200s %.200s.%.200s unknown property type (pyrna_py_to_prop)",
2064                                              error_prefix, RNA_struct_identifier(ptr->type),
2065                                              RNA_property_identifier(prop));
2066                                 return -1;
2067                 }
2068         }
2069
2070         /* Run rna property functions */
2071         if (RNA_property_update_check(prop)) {
2072                 RNA_property_update(BPy_GetContext(), ptr, prop);
2073         }
2074
2075         return 0;
2076 }
2077
2078 static PyObject *pyrna_prop_array_to_py_index(BPy_PropertyArrayRNA *self, int index)
2079 {
2080         PYRNA_PROP_CHECK_OBJ((BPy_PropertyRNA *)self);
2081         return pyrna_py_from_array_index(self, &self->ptr, self->prop, index);
2082 }
2083
2084 static int pyrna_py_to_prop_array_index(BPy_PropertyArrayRNA *self, int index, PyObject *value)
2085 {
2086         int ret = 0;
2087         PointerRNA *ptr = &self->ptr;
2088         PropertyRNA *prop = self->prop;
2089
2090         const int totdim = RNA_property_array_dimension(ptr, prop, NULL);
2091
2092         if (totdim > 1) {
2093                 /* char error_str[512]; */
2094                 if (pyrna_py_to_array_index(&self->ptr, self->prop, self->arraydim, self->arrayoffset, index, value, "") == -1) {
2095                         /* error is set */
2096                         ret = -1;
2097                 }
2098         }
2099         else {
2100                 /* see if we can coerce into a python type - PropertyType */
2101                 switch (RNA_property_type(prop)) {
2102                         case PROP_BOOLEAN:
2103                         {
2104                                 int param = PyC_Long_AsBool(value);
2105
2106                                 if (param == -1) {
2107                                         /* error is set */
2108                                         ret = -1;
2109                                 }
2110                                 else {
2111                                         RNA_property_boolean_set_index(ptr, prop, index, param);
2112                                 }
2113                                 break;
2114                         }
2115                         case PROP_INT:
2116                         {
2117                                 int param = PyC_Long_AsI32(value);
2118                                 if (param == -1 && PyErr_Occurred()) {
2119                                         PyErr_SetString(PyExc_TypeError, "expected an int type");
2120                                         ret = -1;
2121                                 }
2122                                 else {
2123                                         RNA_property_int_clamp(ptr, prop, &param);
2124                                         RNA_property_int_set_index(ptr, prop, index, param);
2125                                 }
2126                                 break;
2127                         }
2128                         case PROP_FLOAT:
2129                         {
2130                                 float param = PyFloat_AsDouble(value);
2131                                 if (PyErr_Occurred()) {
2132                                         PyErr_SetString(PyExc_TypeError, "expected a float type");
2133                                         ret = -1;
2134                                 }
2135                                 else {
2136                                         RNA_property_float_clamp(ptr, prop, &param);
2137                                         RNA_property_float_set_index(ptr, prop, index, param);
2138                                 }
2139                                 break;
2140                         }
2141                         default:
2142                                 PyErr_SetString(PyExc_AttributeError, "not an array type");
2143                                 ret = -1;
2144                                 break;
2145                 }
2146         }
2147
2148         /* Run rna property functions */
2149         if (RNA_property_update_check(prop)) {
2150                 RNA_property_update(BPy_GetContext(), ptr, prop);
2151         }
2152
2153         return ret;
2154 }
2155
2156 /* ---------------sequence------------------------------------------- */
2157 static Py_ssize_t pyrna_prop_array_length(BPy_PropertyArrayRNA *self)
2158 {
2159         PYRNA_PROP_CHECK_INT((BPy_PropertyRNA *)self);
2160
2161         if (RNA_property_array_dimension(&self->ptr, self->prop, NULL) > 1)
2162                 return RNA_property_multi_array_length(&self->ptr, self->prop, self->arraydim);
2163         else
2164                 return RNA_property_array_length(&self->ptr, self->prop);
2165 }
2166
2167 static Py_ssize_t pyrna_prop_collection_length(BPy_PropertyRNA *self)
2168 {
2169         PYRNA_PROP_CHECK_INT(self);
2170
2171         return RNA_property_collection_length(&self->ptr, self->prop);
2172 }
2173
2174 /* bool functions are for speed, so we can avoid getting the length
2175  * of 1000's of items in a linked list for eg. */
2176 static int pyrna_prop_array_bool(BPy_PropertyRNA *self)
2177 {
2178         PYRNA_PROP_CHECK_INT(self);
2179
2180         return RNA_property_array_length(&self->ptr, self->prop) ? 1 : 0;
2181 }
2182
2183 static int pyrna_prop_collection_bool(BPy_PropertyRNA *self)
2184 {
2185         /* no callback defined, just iterate and find the nth item */
2186         CollectionPropertyIterator iter;
2187         int test;
2188
2189         PYRNA_PROP_CHECK_INT(self);
2190
2191         RNA_property_collection_begin(&self->ptr, self->prop, &iter);
2192         test = iter.valid;
2193         RNA_property_collection_end(&iter);
2194         return test;
2195 }
2196
2197
2198 /* notice getting the length of the collection is avoided unless negative
2199  * index is used or to detect internal error with a valid index.
2200  * This is done for faster lookups. */
2201 #define PYRNA_PROP_COLLECTION_ABS_INDEX(ret_err)                              \
2202         if (keynum < 0) {                                                         \
2203             keynum_abs += RNA_property_collection_length(&self->ptr, self->prop); \
2204             if (keynum_abs < 0) {                                                 \
2205                 PyErr_Format(PyExc_IndexError,                                    \
2206                              "bpy_prop_collection[%d]: out of range.", keynum);   \
2207                 return ret_err;                                                   \
2208             }                                                                     \
2209         } (void)0
2210
2211
2212 /* internal use only */
2213 static PyObject *pyrna_prop_collection_subscript_int(BPy_PropertyRNA *self, Py_ssize_t keynum)
2214 {
2215         PointerRNA newptr;
2216         Py_ssize_t keynum_abs = keynum;
2217
2218         PYRNA_PROP_CHECK_OBJ(self);
2219
2220         PYRNA_PROP_COLLECTION_ABS_INDEX(NULL);
2221
2222         if (RNA_property_collection_lookup_int(&self->ptr, self->prop, keynum_abs, &newptr)) {
2223                 return pyrna_struct_CreatePyObject(&newptr);
2224         }
2225         else {
2226                 const int len = RNA_property_collection_length(&self->ptr, self->prop);
2227                 if (keynum_abs >= len) {
2228                         PyErr_Format(PyExc_IndexError,
2229                                      "bpy_prop_collection[index]: "
2230                                      "index %d out of range, size %d", keynum, len);
2231                 }
2232                 else {
2233                         PyErr_Format(PyExc_RuntimeError,
2234                                      "bpy_prop_collection[index]: internal error, "
2235                                      "valid index %d given in %d sized collection but value not found",
2236                                      keynum_abs, len);
2237                 }
2238
2239                 return NULL;
2240         }
2241 }
2242
2243 /* values type must have been already checked */
2244 static int pyrna_prop_collection_ass_subscript_int(BPy_PropertyRNA *self, Py_ssize_t keynum, PyObject *value)
2245 {
2246         Py_ssize_t keynum_abs = keynum;
2247         const PointerRNA *ptr = (value == Py_None) ? (&PointerRNA_NULL) : &((BPy_StructRNA *)value)->ptr;
2248
2249         PYRNA_PROP_CHECK_INT(self);
2250
2251         PYRNA_PROP_COLLECTION_ABS_INDEX(-1);
2252
2253         if (RNA_property_collection_assign_int(&self->ptr, self->prop, keynum_abs, ptr) == 0) {
2254                 const int len = RNA_property_collection_length(&self->ptr, self->prop);
2255                 if (keynum_abs >= len) {
2256                         PyErr_Format(PyExc_IndexError,
2257                                      "bpy_prop_collection[index] = value: "
2258                                      "index %d out of range, size %d", keynum, len);
2259                 }
2260                 else {
2261
2262                         PyErr_Format(PyExc_IndexError,
2263                                      "bpy_prop_collection[index] = value: "
2264                                      "failed assignment (unknown reason)", keynum);
2265                 }
2266                 return -1;
2267         }
2268
2269         return 0;
2270 }
2271
2272 static PyObject *pyrna_prop_array_subscript_int(BPy_PropertyArrayRNA *self, int keynum)
2273 {
2274         int len;
2275
2276         PYRNA_PROP_CHECK_OBJ((BPy_PropertyRNA *)self);
2277
2278         len = pyrna_prop_array_length(self);
2279
2280         if (keynum < 0) keynum += len;
2281
2282         if (keynum >= 0 && keynum < len)
2283                 return pyrna_prop_array_to_py_index(self, keynum);
2284
2285         PyErr_Format(PyExc_IndexError,
2286                      "bpy_prop_array[index]: index %d out of range", keynum);
2287         return NULL;
2288 }
2289
2290 static PyObject *pyrna_prop_collection_subscript_str(BPy_PropertyRNA *self, const char *keyname)
2291 {
2292         PointerRNA newptr;
2293
2294         PYRNA_PROP_CHECK_OBJ(self);
2295
2296         if (RNA_property_collection_lookup_string(&self->ptr, self->prop, keyname, &newptr))
2297                 return pyrna_struct_CreatePyObject(&newptr);
2298
2299         PyErr_Format(PyExc_KeyError, "bpy_prop_collection[key]: key \"%.200s\" not found", keyname);
2300         return NULL;
2301 }
2302 /* static PyObject *pyrna_prop_array_subscript_str(BPy_PropertyRNA *self, char *keyname) */
2303
2304 /**
2305  * Special case: `bpy.data.objects["some_id_name", "//some_lib_name.blend"]`
2306  * also for:     `bpy.data.objects.get(("some_id_name", "//some_lib_name.blend"), fallback)`
2307  *
2308  * \note
2309  * error codes since this is not to be called directly from python,
2310  * this matches pythons `__contains__` values capi.
2311  * - -1: exception set
2312  * -  0: not found
2313  * -  1: found
2314  */
2315 static int pyrna_prop_collection_subscript_str_lib_pair_ptr(
2316         BPy_PropertyRNA *self, PyObject *key,
2317         const char *err_prefix, const short err_not_found,
2318         PointerRNA *r_ptr)
2319 {
2320         const char *keyname;
2321
2322         /* first validate the args, all we know is that they are a tuple */
2323         if (PyTuple_GET_SIZE(key) != 2) {
2324                 PyErr_Format(PyExc_KeyError,
2325                              "%s: tuple key must be a pair, not size %d",
2326                              err_prefix, PyTuple_GET_SIZE(key));
2327                 return -1;
2328         }
2329         else if (self->ptr.type != &RNA_BlendData) {
2330                 PyErr_Format(PyExc_KeyError,
2331                              "%s: is only valid for bpy.data collections, not %.200s",
2332                              err_prefix, RNA_struct_identifier(self->ptr.type));
2333                 return -1;
2334         }
2335         else if ((keyname = _PyUnicode_AsString(PyTuple_GET_ITEM(key, 0))) == NULL) {
2336                 PyErr_Format(PyExc_KeyError,
2337                              "%s: id must be a string, not %.200s",
2338                              err_prefix, Py_TYPE(PyTuple_GET_ITEM(key, 0))->tp_name);
2339                 return -1;
2340         }
2341         else {
2342                 PyObject *keylib = PyTuple_GET_ITEM(key, 1);
2343                 Library *lib;
2344                 bool found = false;
2345
2346                 if (keylib == Py_None) {
2347                         lib = NULL;
2348                 }
2349                 else if (PyUnicode_Check(keylib)) {
2350                         Main *bmain = self->ptr.data;
2351                         const char *keylib_str = _PyUnicode_AsString(keylib);
2352                         lib = BLI_findstring(&bmain->library, keylib_str, offsetof(Library, name));
2353                         if (lib == NULL) {
2354                                 if (err_not_found) {
2355                                         PyErr_Format(PyExc_KeyError,
2356                                                      "%s: lib name '%.240s' "
2357                                                      "does not reference a valid library",
2358                                                      err_prefix, keylib_str);
2359                                         return -1;
2360                                 }
2361                                 else {
2362                                         return 0;
2363                                 }
2364
2365                         }
2366                 }
2367                 else {
2368                         PyErr_Format(PyExc_KeyError,
2369                                      "%s: lib must be a string or None, not %.200s",
2370                                      err_prefix, Py_TYPE(keylib)->tp_name);
2371                         return -1;
2372                 }
2373
2374                 /* lib is either a valid pointer or NULL,
2375                  * either way can do direct comparison with id.lib */
2376
2377                 RNA_PROP_BEGIN (&self->ptr, itemptr, self->prop)
2378                 {
2379                         ID *id = itemptr.data; /* always an ID */
2380                         if (id->lib == lib && (STREQLEN(keyname, id->name + 2, sizeof(id->name) - 2))) {
2381                                 found = true;
2382                                 if (r_ptr) {
2383                                         *r_ptr = itemptr;
2384                                 }
2385                                 break;
2386                         }
2387                 }
2388                 RNA_PROP_END;
2389
2390                 /* we may want to fail silently as with collection.get() */
2391                 if ((found == false) && err_not_found) {
2392                         /* only runs for getitem access so use fixed string */
2393                         PyErr_SetString(PyExc_KeyError,
2394                                         "bpy_prop_collection[key, lib]: not found");
2395                         return -1;
2396                 }
2397                 else {
2398                         return found; /* 1 / 0, no exception */
2399                 }
2400         }
2401 }
2402
2403 static PyObject *pyrna_prop_collection_subscript_str_lib_pair(
2404         BPy_PropertyRNA *self, PyObject *key,
2405         const char *err_prefix, const bool err_not_found)
2406 {
2407         PointerRNA ptr;
2408         const int contains = pyrna_prop_collection_subscript_str_lib_pair_ptr(self, key, err_prefix, err_not_found, &ptr);
2409
2410         if (contains == 1) {
2411                 return pyrna_struct_CreatePyObject(&ptr);
2412         }
2413         else {
2414                 return NULL;
2415         }
2416 }
2417
2418
2419 static PyObject *pyrna_prop_collection_subscript_slice(BPy_PropertyRNA *self, Py_ssize_t start, Py_ssize_t stop)
2420 {
2421         CollectionPropertyIterator rna_macro_iter;
2422         int count;
2423
2424         PyObject *list;
2425         PyObject *item;
2426
2427         PYRNA_PROP_CHECK_OBJ(self);
2428
2429         list = PyList_New(0);
2430
2431         /* skip to start */
2432         RNA_property_collection_begin(&self->ptr, self->prop, &rna_macro_iter);
2433         RNA_property_collection_skip(&rna_macro_iter, start);
2434
2435         /* add items until stop */
2436         for (count = start; rna_macro_iter.valid;
2437              RNA_property_collection_next(&rna_macro_iter))
2438         {
2439                 item = pyrna_struct_CreatePyObject(&rna_macro_iter.ptr);
2440                 PyList_APPEND(list, item);
2441
2442                 count++;
2443                 if (count == stop) {
2444                         break;
2445                 }
2446         }
2447
2448         RNA_property_collection_end(&rna_macro_iter);
2449
2450         return list;
2451 }
2452
2453 /* TODO - dimensions
2454  * note: could also use pyrna_prop_array_to_py_index(self, count) in a loop but its a lot slower
2455  * since at the moment it reads (and even allocates) the entire array for each index.
2456  */
2457 static PyObject *pyrna_prop_array_subscript_slice(
2458         BPy_PropertyArrayRNA *self, PointerRNA *ptr, PropertyRNA *prop,
2459         Py_ssize_t start, Py_ssize_t stop, Py_ssize_t length)
2460 {
2461         int count, totdim;
2462         PyObject *tuple;
2463
2464         /* isn't needed, internal use only */
2465         // PYRNA_PROP_CHECK_OBJ((BPy_PropertyRNA *)self);
2466
2467         tuple = PyTuple_New(stop - start);
2468
2469         totdim = RNA_property_array_dimension(ptr, prop, NULL);
2470
2471         if (totdim > 1) {
2472                 for (count = start; count < stop; count++)
2473                         PyTuple_SET_ITEM(tuple, count - start, pyrna_prop_array_to_py_index(self, count));
2474         }
2475         else {
2476                 switch (RNA_property_type(prop)) {
2477                         case PROP_FLOAT:
2478                         {
2479                                 float values_stack[PYRNA_STACK_ARRAY];
2480                                 float *values;
2481                                 if (length > PYRNA_STACK_ARRAY) { values = PyMem_MALLOC(sizeof(float) * length); }
2482                                 else                            { values = values_stack; }
2483                                 RNA_property_float_get_array(ptr, prop, values);
2484
2485                                 for (count = start; count < stop; count++)
2486                                         PyTuple_SET_ITEM(tuple, count - start, PyFloat_FromDouble(values[count]));
2487
2488                                 if (values != values_stack) {
2489                                         PyMem_FREE(values);
2490                                 }
2491                                 break;
2492                         }
2493                         case PROP_BOOLEAN:
2494                         {
2495                                 bool values_stack[PYRNA_STACK_ARRAY];
2496                                 bool *values;
2497                                 if (length > PYRNA_STACK_ARRAY) { values = PyMem_MALLOC(sizeof(bool) * length); }
2498                                 else                            { values = values_stack; }
2499
2500                                 RNA_property_boolean_get_array(ptr, prop, values);
2501                                 for (count = start; count < stop; count++)
2502                                         PyTuple_SET_ITEM(tuple, count - start, PyBool_FromLong(values[count]));
2503
2504                                 if (values != values_stack) {
2505                                         PyMem_FREE(values);
2506                                 }
2507                                 break;
2508                         }
2509                         case PROP_INT:
2510                         {
2511                                 int values_stack[PYRNA_STACK_ARRAY];
2512                                 int *values;
2513                                 if (length > PYRNA_STACK_ARRAY) { values = PyMem_MALLOC(sizeof(int) * length); }
2514                                 else                            { values = values_stack; }
2515
2516                                 RNA_property_int_get_array(ptr, prop, values);
2517                                 for (count = start; count < stop; count++)
2518                                         PyTuple_SET_ITEM(tuple, count - start, PyLong_FromLong(values[count]));
2519
2520                                 if (values != values_stack) {
2521                                         PyMem_FREE(values);
2522                                 }
2523                                 break;
2524                         }
2525                         default:
2526                                 BLI_assert(!"Invalid array type");
2527
2528                                 PyErr_SetString(PyExc_TypeError, "not an array type");
2529                                 Py_DECREF(tuple);
2530                                 tuple = NULL;
2531                                 break;
2532                 }
2533         }
2534         return tuple;
2535 }
2536
2537 static PyObject *pyrna_prop_collection_subscript(BPy_PropertyRNA *self, PyObject *key)
2538 {
2539         PYRNA_PROP_CHECK_OBJ(self);
2540
2541         if (PyUnicode_Check(key)) {
2542                 return pyrna_prop_collection_subscript_str(self, _PyUnicode_AsString(key));
2543         }
2544         else if (PyIndex_Check(key)) {
2545                 Py_ssize_t i = PyNumber_AsSsize_t(key, PyExc_IndexError);
2546                 if (i == -1 && PyErr_Occurred())
2547                         return NULL;
2548
2549                 return pyrna_prop_collection_subscript_int(self, i);
2550         }
2551         else if (PySlice_Check(key)) {
2552                 PySliceObject *key_slice = (PySliceObject *)key;
2553                 Py_ssize_t step = 1;
2554
2555                 if (key_slice->step != Py_None && !_PyEval_SliceIndex(key, &step)) {
2556                         return NULL;
2557                 }
2558                 else if (step != 1) {
2559                         PyErr_SetString(PyExc_TypeError, "bpy_prop_collection[slice]: slice steps not supported");
2560                         return NULL;
2561                 }
2562                 else if (key_slice->start == Py_None && key_slice->stop == Py_None) {
2563                         return pyrna_prop_collection_subscript_slice(self, 0, PY_SSIZE_T_MAX);
2564                 }
2565                 else {
2566                         Py_ssize_t start = 0, stop = PY_SSIZE_T_MAX;
2567
2568                         /* avoid PySlice_GetIndicesEx because it needs to know the length ahead of time. */
2569                         if (key_slice->start != Py_None && !_PyEval_SliceIndex(key_slice->start, &start)) return NULL;
2570                         if (key_slice->stop  != Py_None && !_PyEval_SliceIndex(key_slice->stop,  &stop))  return NULL;
2571
2572                         if (start < 0 || stop < 0) {
2573                                 /* only get the length for negative values */
2574                                 Py_ssize_t len = (Py_ssize_t)RNA_property_collection_length(&self->ptr, self->prop);
2575                                 if (start < 0) start += len;
2576                                 if (stop  < 0) stop  += len;
2577                         }
2578
2579                         if (stop - start <= 0) {
2580                                 return PyList_New(0);
2581                         }
2582                         else {
2583                                 return pyrna_prop_collection_subscript_slice(self, start, stop);
2584                         }
2585                 }
2586         }
2587         else if (PyTuple_Check(key)) {
2588                 /* special case, for ID datablocks we */
2589                 return pyrna_prop_collection_subscript_str_lib_pair(self, key,
2590                                                                     "bpy_prop_collection[id, lib]", true);
2591         }
2592         else {
2593                 PyErr_Format(PyExc_TypeError,
2594                              "bpy_prop_collection[key]: invalid key, "
2595                              "must be a string or an int, not %.200s",
2596                              Py_TYPE(key)->tp_name);
2597                 return NULL;
2598         }
2599 }
2600
2601 /* generic check to see if a PyObject is compatible with a collection
2602  * -1 on failure, 0 on success, sets the error */
2603 static int pyrna_prop_collection_type_check(BPy_PropertyRNA *self, PyObject *value)
2604 {
2605         StructRNA *prop_srna;
2606
2607         if (value == Py_None) {
2608                 if (RNA_property_flag(self->prop) & PROP_NEVER_NULL) {
2609                         PyErr_Format(PyExc_TypeError,
2610                                      "bpy_prop_collection[key] = value: invalid, "
2611                                      "this collection doesn't support None assignment");
2612                         return -1;
2613                 }
2614                 else {
2615                         return 0; /* None is OK */
2616                 }
2617         }
2618         else if (BPy_StructRNA_Check(value) == 0) {
2619                 PyErr_Format(PyExc_TypeError,
2620                              "bpy_prop_collection[key] = value: invalid, "
2621                              "expected a StructRNA type or None, not a %.200s",
2622                              Py_TYPE(value)->tp_name);
2623                 return -1;
2624         }
2625         else if ((prop_srna = RNA_property_pointer_type(&self->ptr, self->prop))) {
2626                 StructRNA *value_srna = ((BPy_StructRNA *)value)->ptr.type;
2627                 if (RNA_struct_is_a(value_srna, prop_srna) == 0) {
2628                         PyErr_Format(PyExc_TypeError,
2629                                      "bpy_prop_collection[key] = value: invalid, "
2630                                      "expected a '%.200s' type or None, not a '%.200s'",
2631                                      RNA_struct_identifier(prop_srna),
2632                                      RNA_struct_identifier(value_srna)
2633                                      );
2634                         return -1;
2635                 }
2636                 else {
2637                         return 0; /* OK, this is the correct type!*/
2638                 }
2639         }
2640
2641         PyErr_Format(PyExc_TypeError,
2642                      "bpy_prop_collection[key] = value: internal error, "
2643                      "failed to get the collection type");
2644         return -1;
2645 }
2646
2647 /* note: currently this is a copy of 'pyrna_prop_collection_subscript' with
2648  * large blocks commented, we may support slice/key indices later */
2649 static int pyrna_prop_collection_ass_subscript(BPy_PropertyRNA *self, PyObject *key, PyObject *value)
2650 {
2651         PYRNA_PROP_CHECK_INT(self);
2652
2653         /* validate the assigned value */
2654         if (value == NULL) {
2655                 PyErr_SetString(PyExc_TypeError,
2656                                 "del bpy_prop_collection[key]: not supported");
2657                 return -1;
2658         }
2659         else if (pyrna_prop_collection_type_check(self, value) == -1) {
2660                 return -1; /* exception is set */
2661         }
2662
2663 #if 0
2664         if (PyUnicode_Check(key)) {
2665                 return pyrna_prop_collection_subscript_str(self, _PyUnicode_AsString(key));
2666         }
2667         else
2668 #endif
2669         if (PyIndex_Check(key)) {
2670                 Py_ssize_t i = PyNumber_AsSsize_t(key, PyExc_IndexError);
2671                 if (i == -1 && PyErr_Occurred())
2672                         return -1;
2673
2674                 return pyrna_prop_collection_ass_subscript_int(self, i, value);
2675         }
2676 #if 0 /* TODO, fake slice assignment */
2677         else if (PySlice_Check(key)) {
2678                 PySliceObject *key_slice = (PySliceObject *)key;
2679                 Py_ssize_t step = 1;
2680
2681                 if (key_slice->step != Py_None && !_PyEval_SliceIndex(key, &step)) {
2682                         return NULL;
2683                 }
2684                 else if (step != 1) {
2685                         PyErr_SetString(PyExc_TypeError, "bpy_prop_collection[slice]: slice steps not supported");
2686                         return NULL;
2687                 }
2688                 else if (key_slice->start == Py_None && key_slice->stop == Py_None) {
2689                         return pyrna_prop_collection_subscript_slice(self, 0, PY_SSIZE_T_MAX);
2690                 }
2691                 else {
2692                         Py_ssize_t start = 0, stop = PY_SSIZE_T_MAX;
2693
2694                         /* avoid PySlice_GetIndicesEx because it needs to know the length ahead of time. */
2695                         if (key_slice->start != Py_None && !_PyEval_SliceIndex(key_slice->start, &start)) return NULL;
2696                         if (key_slice->stop != Py_None && !_PyEval_SliceIndex(key_slice->stop, &stop))    return NULL;
2697
2698                         if (start < 0 || stop < 0) {
2699                                 /* only get the length for negative values */
2700                                 Py_ssize_t len = (Py_ssize_t)RNA_property_collection_length(&self->ptr, self->prop);
2701                                 if (start < 0) start += len;
2702                                 if (stop  < 0) stop  += len;
2703                         }
2704
2705                         if (stop - start <= 0) {
2706                                 return PyList_New(0);
2707                         }
2708                         else {
2709                                 return pyrna_prop_collection_subscript_slice(self, start, stop);
2710                         }
2711                 }
2712         }
2713 #endif
2714         else {
2715                 PyErr_Format(PyExc_TypeError,
2716                              "bpy_prop_collection[key]: invalid key, "
2717                              "must be a string or an int, not %.200s",
2718                              Py_TYPE(key)->tp_name);
2719                 return -1;
2720         }
2721 }
2722
2723 static PyObject *pyrna_prop_array_subscript(BPy_PropertyArrayRNA *self, PyObject *key)
2724 {
2725         PYRNA_PROP_CHECK_OBJ((BPy_PropertyRNA *)self);
2726
2727 #if 0
2728         if (PyUnicode_Check(key)) {
2729                 return pyrna_prop_array_subscript_str(self, _PyUnicode_AsString(key));
2730         }
2731         else
2732 #endif
2733         if (PyIndex_Check(key)) {
2734                 Py_ssize_t i = PyNumber_AsSsize_t(key, PyExc_IndexError);
2735                 if (i == -1 && PyErr_Occurred())
2736                         return NULL;
2737                 return pyrna_prop_array_subscript_int(self, i);
2738         }
2739         else if (PySlice_Check(key)) {
2740                 Py_ssize_t step = 1;
2741                 PySliceObject *key_slice = (PySliceObject *)key;
2742
2743                 if (key_slice->step != Py_None && !_PyEval_SliceIndex(key, &step)) {
2744                         return NULL;
2745                 }
2746                 else if (step != 1) {
2747                         PyErr_SetString(PyExc_TypeError, "bpy_prop_array[slice]: slice steps not supported");
2748                         return NULL;
2749                 }
2750                 else if (key_slice->start == Py_None && key_slice->stop == Py_None) {
2751                         /* note, no significant advantage with optimizing [:] slice as with collections
2752                          * but include here for consistency with collection slice func */
2753                         Py_ssize_t len = (Py_ssize_t)pyrna_prop_array_length(self);
2754                         return pyrna_prop_array_subscript_slice(self, &self->ptr, self->prop, 0, len, len);
2755                 }
2756                 else {
2757                         int len = pyrna_prop_array_length(self);
2758                         Py_ssize_t start, stop, slicelength;
2759
2760                         if (PySlice_GetIndicesEx(key, len, &start, &stop, &step, &slicelength) < 0)
2761                                 return NULL;
2762
2763                         if (slicelength <= 0) {
2764                                 return PyTuple_New(0);
2765                         }
2766                         else {
2767                                 return pyrna_prop_array_subscript_slice(self, &self->ptr, self->prop, start, stop, len);
2768                         }
2769                 }
2770         }
2771         else {
2772                 PyErr_SetString(PyExc_AttributeError, "bpy_prop_array[key]: invalid key, key must be an int");
2773                 return NULL;
2774         }
2775 }
2776
2777 /**
2778  * Helpers for #prop_subscript_ass_array_slice
2779  */
2780
2781 static PyObject *prop_subscript_ass_array_slice__as_seq_fast(PyObject *value, int length)
2782 {
2783         PyObject *value_fast;
2784         if (!(value_fast = PySequence_Fast(
2785                   value,
2786                   "bpy_prop_array[slice] = value: "
2787                   "element in assignment is not a sequence type")))
2788         {
2789                 return NULL;
2790         }
2791         else if (PySequence_Fast_GET_SIZE(value_fast) != length) {
2792                 Py_DECREF(value_fast);
2793                 PyErr_SetString(
2794                         PyExc_ValueError,
2795                         "bpy_prop_array[slice] = value: "
2796                         "re-sizing bpy_struct element in arrays isn't supported");
2797
2798                 return NULL;
2799         }
2800         else {
2801                 return value_fast;
2802         }
2803 }
2804
2805 static int prop_subscript_ass_array_slice__float_recursive(
2806         PyObject **value_items, float *value,
2807         int totdim, const int dimsize[],
2808         const float range[2])
2809 {
2810         const int length = dimsize[0];
2811         if (totdim > 1) {
2812                 int index = 0;
2813                 int i;
2814                 for (i = 0; i != length; i++) {
2815                         PyObject *subvalue = prop_subscript_ass_array_slice__as_seq_fast(value_items[i], dimsize[1]);
2816                         if (UNLIKELY(subvalue == NULL)) {
2817                                 return 0;
2818                         }
2819
2820                         index += prop_subscript_ass_array_slice__float_recursive(
2821                                 PySequence_Fast_ITEMS(subvalue), &value[index],
2822                                 totdim - 1, &dimsize[1], range);
2823
2824                         Py_DECREF(subvalue);
2825                 }
2826                 return index;
2827         }
2828         else {
2829                 BLI_assert(totdim == 1);
2830                 const float min = range[0], max = range[1];
2831                 int i;
2832                 for (i = 0; i != length; i++) {
2833                         float v = PyFloat_AsDouble(value_items[i]);
2834                         CLAMP(v, min, max);
2835                         value[i] = v;
2836                 }
2837                 return i;
2838         }
2839 }
2840
2841 static int prop_subscript_ass_array_slice__int_recursive(
2842         PyObject **value_items, int *value,
2843         int totdim, const int dimsize[],
2844         const int range[2])
2845 {
2846         const int length = dimsize[0];
2847         if (totdim > 1) {
2848                 int index = 0;
2849                 int i;
2850                 for (i = 0; i != length; i++) {
2851                         PyObject *subvalue = prop_subscript_ass_array_slice__as_seq_fast(value_items[i], dimsize[1]);
2852                         if (UNLIKELY(subvalue == NULL)) {
2853                                 return 0;
2854                         }
2855
2856                         index += prop_subscript_ass_array_slice__int_recursive(
2857                                 PySequence_Fast_ITEMS(subvalue), &value[index],
2858                                 totdim - 1, &dimsize[1], range);
2859
2860                         Py_DECREF(subvalue);
2861                 }
2862                 return index;
2863         }
2864         else {
2865                 BLI_assert(totdim == 1);
2866                 const int min = range[0], max = range[1];
2867                 int i;
2868                 for (i = 0; i != length; i++) {
2869                         int v = PyLong_AsLong(value_items[i]);
2870                         CLAMP(v, min, max);
2871                         value[i] = v;
2872                 }
2873                 return i;
2874         }
2875 }
2876
2877 static int prop_subscript_ass_array_slice__bool_recursive(
2878         PyObject **value_items, bool *value,
2879         int totdim, const int dimsize[])
2880 {
2881         const int length = dimsize[0];
2882         if (totdim > 1) {
2883                 int index = 0;
2884                 int i;
2885                 for (i = 0; i != length; i++) {
2886                         PyObject *subvalue = prop_subscript_ass_array_slice__as_seq_fast(value_items[i], dimsize[1]);
2887                         if (UNLIKELY(subvalue == NULL)) {
2888                                 return 0;
2889                         }
2890
2891                         index += prop_subscript_ass_array_slice__bool_recursive(
2892                                 PySequence_Fast_ITEMS(subvalue), &value[index],
2893                                 totdim - 1, &dimsize[1]);
2894
2895                         Py_DECREF(subvalue);
2896                 }
2897                 return index;
2898         }
2899         else {
2900                 BLI_assert(totdim == 1);
2901                 int i;
2902                 for (i = 0; i != length; i++) {
2903                         int v = PyLong_AsLong(value_items[i]);
2904                         value[i] = v;
2905                 }
2906                 return i;
2907         }
2908 }
2909
2910 /* could call (pyrna_py_to_prop_array_index(self, i, value) in a loop but it is slow */
2911 static int prop_subscript_ass_array_slice(
2912         PointerRNA *ptr, PropertyRNA *prop, int arraydim, int arrayoffset,
2913         int start, int stop, int length, PyObject *value_orig)
2914 {
2915         const int length_flat = RNA_property_array_length(ptr, prop);
2916         PyObject *value;
2917         PyObject **value_items;
2918         void *values_alloc = NULL;
2919         int ret = 0;
2920
2921         if (value_orig == NULL) {
2922                 PyErr_SetString(PyExc_TypeError,
2923                                 "bpy_prop_array[slice] = value: deleting with list types is not supported by bpy_struct");
2924                 return -1;
2925         }
2926
2927         if (!(value = PySequence_Fast(value_orig, "bpy_prop_array[slice] = value: assignment is not a sequence type"))) {
2928                 return -1;
2929         }
2930
2931         if (PySequence_Fast_GET_SIZE(value) != stop - start) {
2932                 Py_DECREF(value);
2933                 PyErr_SetString(PyExc_TypeError,
2934                                 "bpy_prop_array[slice] = value: re-sizing bpy_struct arrays isn't supported");
2935                 return -1;
2936         }
2937
2938         int dimsize[3];
2939         int totdim = RNA_property_array_dimension(ptr, prop, dimsize);
2940         if (totdim > 1) {
2941                 BLI_assert(dimsize[arraydim] == length);
2942         }
2943
2944         int span = 1;
2945         if (totdim > 1) {
2946                 for (int i = arraydim + 1; i < totdim; i++) {
2947                         span *= dimsize[i];
2948                 }
2949         }
2950
2951         value_items = PySequence_Fast_ITEMS(value);
2952         switch (RNA_property_type(prop)) {
2953                 case PROP_FLOAT:
2954                 {
2955                         float values_stack[PYRNA_STACK_ARRAY];
2956                         float *values = (length_flat > PYRNA_STACK_ARRAY) ?
2957                                         (values_alloc = PyMem_MALLOC(sizeof(*values) * length_flat)) : values_stack;
2958