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