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