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