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