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