formatting edits, no functional changes.
[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         if(id == NULL || !PYRNA_STRUCT_IS_VALID(self))
818                 return pyrna_struct_str(self); /* fallback */
819
820         if(RNA_struct_is_ID(self->ptr.type)) {
821                 return PyUnicode_FromFormat("bpy.data.%s[\"%s\"]",
822                                             BKE_idcode_to_name_plural(GS(id->name)),
823                                             id->name+2);
824         }
825         else {
826                 PyObject *ret;
827                 const char *path;
828                 path= RNA_path_from_ID_to_struct(&self->ptr);
829                 if(path) {
830                         ret= PyUnicode_FromFormat("bpy.data.%s[\"%s\"].%s",
831                                                   BKE_idcode_to_name_plural(GS(id->name)),
832                                                   id->name+2,
833                                                   path);
834                         MEM_freeN((void *)path);
835                 }
836                 else { /* cant find, print something sane */
837                         ret= PyUnicode_FromFormat("bpy.data.%s[\"%s\"]...%s",
838                                                   BKE_idcode_to_name_plural(GS(id->name)),
839                                                   id->name+2,
840                                                   RNA_struct_identifier(self->ptr.type));
841                 }
842
843                 return ret;
844         }
845 }
846
847 static PyObject *pyrna_prop_str(BPy_PropertyRNA *self)
848 {
849         PyObject *ret;
850         PointerRNA ptr;
851         const char *name;
852         const char *type_id= NULL;
853         char type_fmt[64]= "";
854         int type;
855
856         PYRNA_PROP_CHECK_OBJ(self)
857
858         type= RNA_property_type(self->prop);
859
860         if(RNA_enum_id_from_value(property_type_items, type, &type_id)==0) {
861                 PyErr_SetString(PyExc_RuntimeError, "could not use property type, internal error"); /* should never happen */
862                 return NULL;
863         }
864         else {
865                 /* this should never fail */
866                 int len= -1;
867                 char *c= type_fmt;
868
869                 while ((*c++= tolower(*type_id++))) {} ;
870
871                 if(type==PROP_COLLECTION) {
872                         len= pyrna_prop_collection_length(self);
873                 }
874                 else if (RNA_property_array_check(self->prop)) {
875                         len= pyrna_prop_array_length((BPy_PropertyArrayRNA *)self);
876                 }
877
878                 if(len != -1)
879                         sprintf(--c, "[%d]", len);
880         }
881
882         /* if a pointer, try to print name of pointer target too */
883         if(RNA_property_type(self->prop) == PROP_POINTER) {
884                 ptr= RNA_property_pointer_get(&self->ptr, self->prop);
885                 name= RNA_struct_name_get_alloc(&ptr, NULL, FALSE);
886
887                 if(name) {
888                         ret= PyUnicode_FromFormat("<bpy_%.200s, %.200s.%.200s(\"%.200s\")>",
889                                                   type_fmt,
890                                                   RNA_struct_identifier(self->ptr.type),
891                                                   RNA_property_identifier(self->prop),
892                                                   name);
893                         MEM_freeN((void *)name);
894                         return ret;
895                 }
896         }
897         if(RNA_property_type(self->prop) == PROP_COLLECTION) {
898                 PointerRNA r_ptr;
899                 if(RNA_property_collection_type_get(&self->ptr, self->prop, &r_ptr)) {
900                         return PyUnicode_FromFormat("<bpy_%.200s, %.200s>",
901                                                     type_fmt,
902                                                     RNA_struct_identifier(r_ptr.type));
903                 }
904         }
905
906         return PyUnicode_FromFormat("<bpy_%.200s, %.200s.%.200s>",
907                                     type_fmt,
908                                     RNA_struct_identifier(self->ptr.type),
909                                     RNA_property_identifier(self->prop));
910 }
911
912 static PyObject *pyrna_prop_repr(BPy_PropertyRNA *self)
913 {
914         ID *id;
915         PyObject *ret;
916         const char *path;
917
918         PYRNA_PROP_CHECK_OBJ(self)
919
920         if((id= self->ptr.id.data) == NULL)
921                 return pyrna_prop_str(self); /* fallback */
922
923         path= RNA_path_from_ID_to_property(&self->ptr, self->prop);
924         if(path) {
925                 ret= PyUnicode_FromFormat("bpy.data.%s[\"%s\"].%s", BKE_idcode_to_name_plural(GS(id->name)), id->name+2, path);
926                 MEM_freeN((void *)path);
927         }
928         else { /* cant find, print something sane */
929                 ret= PyUnicode_FromFormat("bpy.data.%s[\"%s\"]...%s",
930                                           BKE_idcode_to_name_plural(GS(id->name)),
931                                           id->name+2,
932                                           RNA_property_identifier(self->prop));
933         }
934
935         return ret;
936 }
937
938
939 static PyObject *pyrna_func_repr(BPy_FunctionRNA *self)
940 {
941         return PyUnicode_FromFormat("<%.200s %.200s.%.200s()>",
942                                     Py_TYPE(self)->tp_name,
943                                     RNA_struct_identifier(self->ptr.type),
944                                     RNA_function_identifier(self->func));
945 }
946
947
948 static long pyrna_struct_hash(BPy_StructRNA *self)
949 {
950         return _Py_HashPointer(self->ptr.data);
951 }
952
953 /* from python's meth_hash v3.1.2 */
954 static long pyrna_prop_hash(BPy_PropertyRNA *self)
955 {
956         long x, y;
957         if (self->ptr.data == NULL)
958                 x= 0;
959         else {
960                 x= _Py_HashPointer(self->ptr.data);
961                 if (x == -1)
962                         return -1;
963         }
964         y= _Py_HashPointer((void*)(self->prop));
965         if (y == -1)
966                 return -1;
967         x ^= y;
968         if (x == -1)
969                 x= -2;
970         return x;
971 }
972
973 #ifdef USE_PYRNA_STRUCT_REFERENCE
974 static int pyrna_struct_traverse(BPy_StructRNA *self, visitproc visit, void *arg)
975 {
976         Py_VISIT(self->reference);
977         return 0;
978 }
979
980 static int pyrna_struct_clear(BPy_StructRNA *self)
981 {
982         Py_CLEAR(self->reference);
983         return 0;
984 }
985 #endif /* !USE_PYRNA_STRUCT_REFERENCE */
986
987 /* use our own dealloc so we can free a property if we use one */
988 static void pyrna_struct_dealloc(BPy_StructRNA *self)
989 {
990 #ifdef PYRNA_FREE_SUPPORT
991         if (self->freeptr && self->ptr.data) {
992                 IDP_FreeProperty(self->ptr.data);
993                 MEM_freeN(self->ptr.data);
994                 self->ptr.data= NULL;
995         }
996 #endif /* PYRNA_FREE_SUPPORT */
997
998 #ifdef USE_WEAKREFS
999         if (self->in_weakreflist != NULL) {
1000                 PyObject_ClearWeakRefs((PyObject *)self);
1001         }
1002 #endif
1003
1004 #ifdef USE_PYRNA_STRUCT_REFERENCE
1005         if(self->reference) {
1006                 PyObject_GC_UnTrack(self);
1007                 pyrna_struct_clear(self);
1008         }
1009 #endif /* !USE_PYRNA_STRUCT_REFERENCE */
1010
1011         /* Note, for subclassed PyObjects we cant just call PyObject_DEL() directly or it will crash */
1012         Py_TYPE(self)->tp_free(self);
1013 }
1014
1015 #ifdef USE_PYRNA_STRUCT_REFERENCE
1016 static void pyrna_struct_reference_set(BPy_StructRNA *self, PyObject *reference)
1017 {
1018         if(self->reference) {
1019 //              PyObject_GC_UnTrack(self); /* INITIALIZED TRACKED? */
1020                 pyrna_struct_clear(self);
1021         }
1022         /* reference is now NULL */
1023
1024         if(reference) {
1025                 self->reference= reference;
1026                 Py_INCREF(reference);
1027 //              PyObject_GC_Track(self);  /* INITIALIZED TRACKED? */
1028         }
1029 }
1030 #endif /* !USE_PYRNA_STRUCT_REFERENCE */
1031
1032 /* use our own dealloc so we can free a property if we use one */
1033 static void pyrna_prop_dealloc(BPy_PropertyRNA *self)
1034 {
1035 #ifdef USE_WEAKREFS
1036         if (self->in_weakreflist != NULL) {
1037                 PyObject_ClearWeakRefs((PyObject *)self);
1038         }
1039 #endif
1040         /* Note, for subclassed PyObjects we cant just call PyObject_DEL() directly or it will crash */
1041         Py_TYPE(self)->tp_free(self);
1042 }
1043
1044 static void pyrna_prop_array_dealloc(BPy_PropertyRNA *self)
1045 {
1046 #ifdef USE_WEAKREFS
1047         if (self->in_weakreflist != NULL) {
1048                 PyObject_ClearWeakRefs((PyObject *)self);
1049         }
1050 #endif
1051         /* Note, for subclassed PyObjects we cant just call PyObject_DEL() directly or it will crash */
1052         Py_TYPE(self)->tp_free(self);
1053 }
1054
1055 static const char *pyrna_enum_as_string(PointerRNA *ptr, PropertyRNA *prop)
1056 {
1057         EnumPropertyItem *item;
1058         const char *result;
1059         int free= FALSE;
1060
1061         RNA_property_enum_items(BPy_GetContext(), ptr, prop, &item, NULL, &free);
1062         if(item) {
1063                 result= BPy_enum_as_string(item);
1064         }
1065         else {
1066                 result= "";
1067         }
1068
1069         if(free)
1070                 MEM_freeN(item);
1071
1072         return result;
1073 }
1074
1075
1076 static int pyrna_string_to_enum(PyObject *item, PointerRNA *ptr, PropertyRNA *prop, int *val, const char *error_prefix)
1077 {
1078         const char *param= _PyUnicode_AsString(item);
1079
1080         if (param==NULL) {
1081                 const char *enum_str= pyrna_enum_as_string(ptr, prop);
1082                 PyErr_Format(PyExc_TypeError,
1083                              "%.200s expected a string enum type in (%.200s)",
1084                              error_prefix, enum_str);
1085                 MEM_freeN((void *)enum_str);
1086                 return 0;
1087         }
1088         else {
1089                 /* hack so that dynamic enums used for operator properties will be able to be built (i.e. context will be supplied to itemf)
1090                  * and thus running defining operator buttons for such operators in UI will work */
1091                 RNA_def_property_clear_flag(prop, PROP_ENUM_NO_CONTEXT);
1092
1093                 if (!RNA_property_enum_value(BPy_GetContext(), ptr, prop, param, val)) {
1094                         const char *enum_str= pyrna_enum_as_string(ptr, prop);
1095                         PyErr_Format(PyExc_TypeError,
1096                                      "%.200s enum \"%.200s\" not found in (%.200s)",
1097                                      error_prefix, param, enum_str);
1098                         MEM_freeN((void *)enum_str);
1099                         return 0;
1100                 }
1101         }
1102
1103         return 1;
1104 }
1105
1106 int pyrna_set_to_enum_bitfield(EnumPropertyItem *items, PyObject *value, int *r_value, const char *error_prefix)
1107 {
1108         /* set of enum items, concatenate all values with OR */
1109         int ret, flag= 0;
1110
1111         /* set looping */
1112         Py_ssize_t pos= 0;
1113         Py_ssize_t hash= 0;
1114         PyObject *key;
1115
1116         *r_value= 0;
1117
1118         while (_PySet_NextEntry(value, &pos, &key, &hash)) {
1119                 const char *param= _PyUnicode_AsString(key);
1120
1121                 if(param==NULL) {
1122                         PyErr_Format(PyExc_TypeError,
1123                                      "%.200s expected a string, not %.200s",
1124                                      error_prefix, Py_TYPE(key)->tp_name);
1125                         return -1;
1126                 }
1127                 if(pyrna_enum_value_from_id(items, param, &ret, error_prefix) < 0)
1128                         return -1;
1129
1130                 flag |= ret;
1131         }
1132
1133         *r_value= flag;
1134         return 0;
1135 }
1136
1137 static int pyrna_prop_to_enum_bitfield(PointerRNA *ptr, PropertyRNA *prop, PyObject *value, int *r_value, const char *error_prefix)
1138 {
1139         EnumPropertyItem *item;
1140         int ret;
1141         int free= FALSE;
1142
1143         *r_value= 0;
1144
1145         RNA_property_enum_items(BPy_GetContext(), ptr, prop, &item, NULL, &free);
1146
1147         if(item) {
1148                 ret= pyrna_set_to_enum_bitfield(item, value, r_value, error_prefix);
1149         }
1150         else {
1151                 if(PySet_GET_SIZE(value)) {
1152                         PyErr_Format(PyExc_TypeError,
1153                                      "%.200s: empty enum \"%.200s\" could not have any values assigned",
1154                                      error_prefix, RNA_property_identifier(prop));
1155                         ret= -1;
1156                 }
1157                 else {
1158                         ret= 0;
1159                 }
1160         }
1161
1162         if(free)
1163                 MEM_freeN(item);
1164
1165         return ret;
1166 }
1167
1168 PyObject *pyrna_enum_bitfield_to_py(EnumPropertyItem *items, int value)
1169 {
1170         PyObject *ret= PySet_New(NULL);
1171         const char *identifier[RNA_ENUM_BITFLAG_SIZE + 1];
1172
1173         if(RNA_enum_bitflag_identifiers(items, value, identifier)) {
1174                 PyObject *item;
1175                 int index;
1176                 for(index=0; identifier[index]; index++) {
1177                         item= PyUnicode_FromString(identifier[index]);
1178                         PySet_Add(ret, item);
1179                         Py_DECREF(item);
1180                 }
1181         }
1182
1183         return ret;
1184 }
1185
1186 static PyObject *pyrna_enum_to_py(PointerRNA *ptr, PropertyRNA *prop, int val)
1187 {
1188         PyObject *item, *ret= NULL;
1189
1190         if(RNA_property_flag(prop) & PROP_ENUM_FLAG) {
1191                 const char *identifier[RNA_ENUM_BITFLAG_SIZE + 1];
1192
1193                 ret= PySet_New(NULL);
1194
1195                 if (RNA_property_enum_bitflag_identifiers(BPy_GetContext(), ptr, prop, val, identifier)) {
1196                         int index;
1197
1198                         for(index=0; identifier[index]; index++) {
1199                                 item= PyUnicode_FromString(identifier[index]);
1200                                 PySet_Add(ret, item);
1201                                 Py_DECREF(item);
1202                         }
1203
1204                 }
1205         }
1206         else {
1207                 const char *identifier;
1208                 if (RNA_property_enum_identifier(BPy_GetContext(), ptr, prop, val, &identifier)) {
1209                         ret= PyUnicode_FromString(identifier);
1210                 }
1211                 else {
1212                         EnumPropertyItem *enum_item;
1213                         int free= FALSE;
1214
1215                         /* don't throw error here, can't trust blender 100% to give the
1216                          * right values, python code should not generate error for that */
1217                         RNA_property_enum_items(BPy_GetContext(), ptr, prop, &enum_item, NULL, &free);
1218                         if(enum_item && enum_item->identifier) {
1219                                 ret= PyUnicode_FromString(enum_item->identifier);
1220                         }
1221                         else {
1222                                 const char *ptr_name= RNA_struct_name_get_alloc(ptr, NULL, FALSE);
1223
1224                                 /* prefer not fail silently incase of api errors, maybe disable it later */
1225                                 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));
1226
1227 #if 0                   // gives python decoding errors while generating docs :(
1228                                 char error_str[256];
1229                                 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));
1230                                 PyErr_Warn(PyExc_RuntimeWarning, error_str);
1231 #endif
1232
1233                                 if(ptr_name)
1234                                         MEM_freeN((void *)ptr_name);
1235
1236                                 ret= PyUnicode_FromString("");
1237                         }
1238
1239                         if(free)
1240                                 MEM_freeN(enum_item);
1241                         /*
1242                         PyErr_Format(PyExc_AttributeError,
1243                                      "RNA Error: Current value \"%d\" matches no enum", val);
1244                         ret= NULL;
1245                         */
1246                 }
1247         }
1248
1249         return ret;
1250 }
1251
1252 PyObject *pyrna_prop_to_py(PointerRNA *ptr, PropertyRNA *prop)
1253 {
1254         PyObject *ret;
1255         int type= RNA_property_type(prop);
1256
1257         if (RNA_property_array_check(prop)) {
1258                 return pyrna_py_from_array(ptr, prop);
1259         }
1260
1261         /* see if we can coorce into a python type - PropertyType */
1262         switch (type) {
1263         case PROP_BOOLEAN:
1264                 ret= PyBool_FromLong(RNA_property_boolean_get(ptr, prop));
1265                 break;
1266         case PROP_INT:
1267                 ret= PyLong_FromSsize_t((Py_ssize_t)RNA_property_int_get(ptr, prop));
1268                 break;
1269         case PROP_FLOAT:
1270                 ret= PyFloat_FromDouble(RNA_property_float_get(ptr, prop));
1271                 break;
1272         case PROP_STRING:
1273         {
1274                 int subtype= RNA_property_subtype(prop);
1275                 const char *buf;
1276                 buf= RNA_property_string_get_alloc(ptr, prop, NULL, -1);
1277 #ifdef USE_STRING_COERCE
1278                 /* only file paths get special treatment, they may contain non utf-8 chars */
1279                 if(ELEM3(subtype, PROP_FILEPATH, PROP_DIRPATH, PROP_FILENAME)) {
1280                         ret= PyC_UnicodeFromByte(buf);
1281                 }
1282                 else {
1283                         ret= PyUnicode_FromString(buf);
1284                 }
1285 #else // USE_STRING_COERCE
1286                 ret= PyUnicode_FromString(buf);
1287 #endif // USE_STRING_COERCE
1288                 MEM_freeN((void *)buf);
1289                 break;
1290         }
1291         case PROP_ENUM:
1292         {
1293                 ret= pyrna_enum_to_py(ptr, prop, RNA_property_enum_get(ptr, prop));
1294                 break;
1295         }
1296         case PROP_POINTER:
1297         {
1298                 PointerRNA newptr;
1299                 newptr= RNA_property_pointer_get(ptr, prop);
1300                 if (newptr.data) {
1301                         ret= pyrna_struct_CreatePyObject(&newptr);
1302                 }
1303                 else {
1304                         ret= Py_None;
1305                         Py_INCREF(ret);
1306                 }
1307                 break;
1308         }
1309         case PROP_COLLECTION:
1310                 ret= pyrna_prop_CreatePyObject(ptr, prop);
1311                 break;
1312         default:
1313                 PyErr_Format(PyExc_TypeError,
1314                              "bpy_struct internal error: unknown type '%d' (pyrna_prop_to_py)", type);
1315                 ret= NULL;
1316                 break;
1317         }
1318
1319         return ret;
1320 }
1321
1322 /* This function is used by operators and converting dicts into collections.
1323  * Its takes keyword args and fills them with property values */
1324 int pyrna_pydict_to_props(PointerRNA *ptr, PyObject *kw, int all_args, const char *error_prefix)
1325 {
1326         int error_val= 0;
1327         int totkw;
1328         const char *arg_name= NULL;
1329         PyObject *item;
1330
1331         totkw= kw ? PyDict_Size(kw):0;
1332
1333         RNA_STRUCT_BEGIN(ptr, prop) {
1334                 arg_name= RNA_property_identifier(prop);
1335
1336                 if (strcmp(arg_name, "rna_type")==0) continue;
1337
1338                 if (kw==NULL) {
1339                         PyErr_Format(PyExc_TypeError,
1340                                      "%.200s: no keywords, expected \"%.200s\"",
1341                                      error_prefix, arg_name ? arg_name : "<UNKNOWN>");
1342                         error_val= -1;
1343                         break;
1344                 }
1345
1346                 item= PyDict_GetItemString(kw, arg_name); /* wont set an error */
1347
1348                 if (item == NULL) {
1349                         if(all_args) {
1350                                 PyErr_Format(PyExc_TypeError,
1351                                              "%.200s: keyword \"%.200s\" missing",
1352                                              error_prefix, arg_name ? arg_name : "<UNKNOWN>");
1353                                 error_val= -1; /* pyrna_py_to_prop sets the error */
1354                                 break;
1355                         }
1356                 }
1357                 else {
1358                         if (pyrna_py_to_prop(ptr, prop, NULL, item, error_prefix)) {
1359                                 error_val= -1;
1360                                 break;
1361                         }
1362                         totkw--;
1363                 }
1364         }
1365         RNA_STRUCT_END;
1366
1367         if (error_val==0 && totkw > 0) { /* some keywords were given that were not used :/ */
1368                 PyObject *key, *value;
1369                 Py_ssize_t pos= 0;
1370
1371                 while (PyDict_Next(kw, &pos, &key, &value)) {
1372                         arg_name= _PyUnicode_AsString(key);
1373                         if (RNA_struct_find_property(ptr, arg_name) == NULL) break;
1374                         arg_name= NULL;
1375                 }
1376
1377                 PyErr_Format(PyExc_TypeError,
1378                              "%.200s: keyword \"%.200s\" unrecognized",
1379                              error_prefix, arg_name ? arg_name : "<UNKNOWN>");
1380                 error_val= -1;
1381         }
1382
1383         return error_val;
1384 }
1385
1386
1387 static PyObject *pyrna_func_to_py(PointerRNA *ptr, FunctionRNA *func)
1388 {
1389         BPy_FunctionRNA* pyfunc= (BPy_FunctionRNA *) PyObject_NEW(BPy_FunctionRNA, &pyrna_func_Type);
1390         pyfunc->ptr= *ptr;
1391         pyfunc->func= func;
1392         return (PyObject *)pyfunc;
1393 }
1394
1395
1396 static int pyrna_py_to_prop(PointerRNA *ptr, PropertyRNA *prop, void *data, PyObject *value, const char *error_prefix)
1397 {
1398         /* XXX hard limits should be checked here */
1399         int type= RNA_property_type(prop);
1400
1401
1402         if (RNA_property_array_check(prop)) {
1403                 /* done getting the length */
1404                 if(pyrna_py_to_array(ptr, prop, data, value, error_prefix) == -1) {
1405                         return -1;
1406                 }
1407         }
1408         else {
1409                 /* Normal Property (not an array) */
1410
1411                 /* see if we can coorce into a python type - PropertyType */
1412                 switch (type) {
1413                 case PROP_BOOLEAN:
1414                 {
1415                         int param;
1416                         /* prefer not to have an exception here
1417                          * however so many poll functions return None or a valid Object.
1418                          * its a hassle to convert these into a bool before returning, */
1419                         if(RNA_property_flag(prop) & PROP_OUTPUT)
1420                                 param= PyObject_IsTrue(value);
1421                         else
1422                                 param= PyLong_AsLong(value);
1423
1424                         if(param < 0) {
1425                                 PyErr_Format(PyExc_TypeError,
1426                                              "%.200s %.200s.%.200s expected True/False or 0/1, not %.200s",
1427                                              error_prefix, RNA_struct_identifier(ptr->type),
1428                                              RNA_property_identifier(prop), Py_TYPE(value)->tp_name);
1429                                 return -1;
1430                         }
1431                         else {
1432                                 if(data)        *((int*)data)= param;
1433                                 else            RNA_property_boolean_set(ptr, prop, param);
1434                         }
1435                         break;
1436                 }
1437                 case PROP_INT:
1438                 {
1439                         int overflow;
1440                         long param= PyLong_AsLongAndOverflow(value, &overflow);
1441                         if(overflow || (param > INT_MAX) || (param < INT_MIN)) {
1442                                 PyErr_Format(PyExc_ValueError,
1443                                              "%.200s %.200s.%.200s value not in 'int' range "
1444                                              "(" STRINGIFY(INT_MIN) ", " STRINGIFY(INT_MAX) ")",
1445                                              error_prefix, RNA_struct_identifier(ptr->type),
1446                                              RNA_property_identifier(prop));
1447                                 return -1;
1448                         }
1449                         else if (param==-1 && PyErr_Occurred()) {
1450                                 PyErr_Format(PyExc_TypeError,
1451                                              "%.200s %.200s.%.200s expected an int type, not %.200s",
1452                                              error_prefix, RNA_struct_identifier(ptr->type),
1453                                              RNA_property_identifier(prop), Py_TYPE(value)->tp_name);
1454                                 return -1;
1455                         }
1456                         else {
1457                                 int param_i= (int)param;
1458                                 RNA_property_int_clamp(ptr, prop, &param_i);
1459                                 if(data)        *((int*)data)= param_i;
1460                                 else            RNA_property_int_set(ptr, prop, param_i);
1461                         }
1462                         break;
1463                 }
1464                 case PROP_FLOAT:
1465                 {
1466                         float param= PyFloat_AsDouble(value);
1467                         if (PyErr_Occurred()) {
1468                                 PyErr_Format(PyExc_TypeError,
1469                                              "%.200s %.200s.%.200s expected a float type, not %.200s",
1470                                              error_prefix, RNA_struct_identifier(ptr->type),
1471                                              RNA_property_identifier(prop), Py_TYPE(value)->tp_name);
1472                                 return -1;
1473                         }
1474                         else {
1475                                 RNA_property_float_clamp(ptr, prop, (float *)&param);
1476                                 if(data)        *((float*)data)= param;
1477                                 else            RNA_property_float_set(ptr, prop, param);
1478                         }
1479                         break;
1480                 }
1481                 case PROP_STRING:
1482                 {
1483                         const char *param;
1484 #ifdef USE_STRING_COERCE
1485                         PyObject *value_coerce= NULL;
1486                         int subtype= RNA_property_subtype(prop);
1487                         if(ELEM3(subtype, PROP_FILEPATH, PROP_DIRPATH, PROP_FILENAME)) {
1488                                 /* TODO, get size */
1489                                 param= PyC_UnicodeAsByte(value, &value_coerce);
1490                         }
1491                         else {
1492                                 param= _PyUnicode_AsString(value);
1493                         }
1494 #else // USE_STRING_COERCE
1495                         param= _PyUnicode_AsString(value);
1496 #endif // USE_STRING_COERCE
1497
1498                         if (param==NULL) {
1499                                 PyErr_Format(PyExc_TypeError,
1500                                              "%.200s %.200s.%.200s expected a string type, not %.200s",
1501                                              error_prefix, RNA_struct_identifier(ptr->type),
1502                                              RNA_property_identifier(prop), Py_TYPE(value)->tp_name);
1503                                 return -1;
1504                         }
1505                         else {
1506                                 if(data)        *((char**)data)= (char *)param; /*XXX, this is suspect but needed for function calls, need to see if theres a better way */
1507                                 else            RNA_property_string_set(ptr, prop, param);
1508                         }
1509 #ifdef USE_STRING_COERCE
1510                         Py_XDECREF(value_coerce);
1511 #endif // USE_STRING_COERCE
1512                         break;
1513                 }
1514                 case PROP_ENUM:
1515                 {
1516                         int val= 0;
1517
1518                         if (PyUnicode_Check(value)) {
1519                                 if (!pyrna_string_to_enum(value, ptr, prop, &val, error_prefix))
1520                                         return -1;
1521                         }
1522                         else if (PyAnySet_Check(value)) {
1523                                 if(RNA_property_flag(prop) & PROP_ENUM_FLAG) {
1524                                         /* set of enum items, concatenate all values with OR */
1525                                         if(pyrna_prop_to_enum_bitfield(ptr, prop, value, &val, error_prefix) < 0)
1526                                                 return -1;
1527                                 }
1528                                 else {
1529                                         PyErr_Format(PyExc_TypeError,
1530                                                      "%.200s, %.200s.%.200s is not a bitflag enum type",
1531                                                      error_prefix, RNA_struct_identifier(ptr->type),
1532                                                      RNA_property_identifier(prop));
1533                                         return -1;
1534                                 }
1535                         }
1536                         else {
1537                                 const char *enum_str= pyrna_enum_as_string(ptr, prop);
1538                                 PyErr_Format(PyExc_TypeError,
1539                                              "%.200s %.200s.%.200s expected a string enum or a set of strings in (%.2000s), not %.200s",
1540                                              error_prefix, RNA_struct_identifier(ptr->type),
1541                                              RNA_property_identifier(prop), enum_str,
1542                                              Py_TYPE(value)->tp_name);
1543                                 MEM_freeN((void *)enum_str);
1544                                 return -1;
1545                         }
1546
1547                         if(data)        *((int*)data)= val;
1548                         else            RNA_property_enum_set(ptr, prop, val);
1549
1550                         break;
1551                 }
1552                 case PROP_POINTER:
1553                 {
1554                         PyObject *value_new= NULL;
1555
1556                         StructRNA *ptr_type= RNA_property_pointer_type(ptr, prop);
1557                         int flag= RNA_property_flag(prop);
1558
1559                         /* this is really nasty!, so we can fake the operator having direct properties eg:
1560                          * layout.prop(self, "filepath")
1561                          * ... which infact should be
1562                          * layout.prop(self.properties, "filepath")
1563                          *
1564                          * we need to do this trick.
1565                          * if the prop is not an operator type and the pyobject is an operator, use its properties in place of its self.
1566                          *
1567                          * this is so bad that its almost a good reason to do away with fake 'self.properties -> self' class mixing
1568                          * if this causes problems in the future it should be removed.
1569                          */
1570                         if(     (ptr_type == &RNA_AnyType) &&
1571                                 (BPy_StructRNA_Check(value)) &&
1572                                 (RNA_struct_is_a(((BPy_StructRNA *)value)->ptr.type, &RNA_Operator))
1573                         ) {
1574                                 value= PyObject_GetAttrString(value, "properties");
1575                                 value_new= value;
1576                         }
1577
1578
1579                         /* if property is an OperatorProperties pointer and value is a map, forward back to pyrna_pydict_to_props */
1580                         if (RNA_struct_is_a(ptr_type, &RNA_OperatorProperties) && PyDict_Check(value)) {
1581                                 PointerRNA opptr= RNA_property_pointer_get(ptr, prop);
1582                                 return pyrna_pydict_to_props(&opptr, value, 0, error_prefix);
1583                         }
1584
1585                         /* another exception, allow to pass a collection as an RNA property */
1586                         if(Py_TYPE(value)==&pyrna_prop_collection_Type) { /* ok to ignore idprop collections */
1587                                 PointerRNA c_ptr;
1588                                 BPy_PropertyRNA *value_prop= (BPy_PropertyRNA *)value;
1589                                 if(RNA_property_collection_type_get(&value_prop->ptr, value_prop->prop, &c_ptr)) {
1590                                         value= pyrna_struct_CreatePyObject(&c_ptr);
1591                                         value_new= value;
1592                                 }
1593                                 else {
1594                                         PyErr_Format(PyExc_TypeError,
1595                                                      "%.200s %.200s.%.200s collection has no type, "
1596                                                      "cant be used as a %.200s type",
1597                                                      error_prefix, RNA_struct_identifier(ptr->type),
1598                                                      RNA_property_identifier(prop), RNA_struct_identifier(ptr_type));
1599                                         return -1;
1600                                 }
1601                         }
1602
1603                         if(!BPy_StructRNA_Check(value) && value != Py_None) {
1604                                 PyErr_Format(PyExc_TypeError,
1605                                              "%.200s %.200s.%.200s expected a %.200s type, not %.200s",
1606                                              error_prefix, RNA_struct_identifier(ptr->type),
1607                                              RNA_property_identifier(prop), RNA_struct_identifier(ptr_type),
1608                                              Py_TYPE(value)->tp_name);
1609                                 Py_XDECREF(value_new); return -1;
1610                         }
1611                         else if((flag & PROP_NEVER_NULL) && value == Py_None) {
1612                                 PyErr_Format(PyExc_TypeError,
1613                                              "%.200s %.200s.%.200s does not support a 'None' assignment %.200s type",
1614                                              error_prefix, RNA_struct_identifier(ptr->type),
1615                                              RNA_property_identifier(prop), RNA_struct_identifier(ptr_type));
1616                                 Py_XDECREF(value_new); return -1;
1617                         }
1618                         else if(value != Py_None && ((flag & PROP_ID_SELF_CHECK) && ptr->id.data == ((BPy_StructRNA*)value)->ptr.id.data)) {
1619                                 PyErr_Format(PyExc_TypeError,
1620                                              "%.200s %.200s.%.200s ID type does not support assignment to its self",
1621                                              error_prefix, RNA_struct_identifier(ptr->type),
1622                                              RNA_property_identifier(prop));
1623                                 Py_XDECREF(value_new); return -1;
1624                         }
1625                         else {
1626                                 BPy_StructRNA *param= (BPy_StructRNA*)value;
1627                                 int raise_error= FALSE;
1628                                 if(data) {
1629
1630                                         if(flag & PROP_RNAPTR) {
1631                                                 if(value == Py_None)
1632                                                         memset(data, 0, sizeof(PointerRNA));
1633                                                 else
1634                                                         *((PointerRNA*)data)= param->ptr;
1635                                         }
1636                                         else if(value == Py_None) {
1637                                                 *((void**)data)= NULL;
1638                                         }
1639                                         else if(RNA_struct_is_a(param->ptr.type, ptr_type)) {
1640                                                 *((void**)data)= param->ptr.data;
1641                                         }
1642                                         else {
1643                                                 raise_error= TRUE;
1644                                         }
1645                                 }
1646                                 else {
1647                                         /* data==NULL, assign to RNA */
1648                                         if(value == Py_None) {
1649                                                 PointerRNA valueptr= {{NULL}};
1650                                                 RNA_property_pointer_set(ptr, prop, valueptr);
1651                                         }
1652                                         else if(RNA_struct_is_a(param->ptr.type, ptr_type)) {
1653                                                 RNA_property_pointer_set(ptr, prop, param->ptr);
1654                                         }
1655                                         else {
1656                                                 PointerRNA tmp;
1657                                                 RNA_pointer_create(NULL, ptr_type, NULL, &tmp);
1658                                                 PyErr_Format(PyExc_TypeError,
1659                                                              "%.200s %.200s.%.200s expected a %.200s type. not %.200s",
1660                                                              error_prefix, RNA_struct_identifier(ptr->type),
1661                                                              RNA_property_identifier(prop), RNA_struct_identifier(tmp.type),
1662                                                              RNA_struct_identifier(param->ptr.type));
1663                                                 Py_XDECREF(value_new); return -1;
1664                                         }
1665                                 }
1666
1667                                 if(raise_error) {
1668                                         PointerRNA tmp;
1669                                         RNA_pointer_create(NULL, ptr_type, NULL, &tmp);
1670                                         PyErr_Format(PyExc_TypeError,
1671                                                      "%.200s %.200s.%.200s expected a %.200s type, not %.200s",
1672                                                      error_prefix, RNA_struct_identifier(ptr->type),
1673                                                      RNA_property_identifier(prop), RNA_struct_identifier(tmp.type),
1674                                                      RNA_struct_identifier(param->ptr.type));
1675                                         Py_XDECREF(value_new); return -1;
1676                                 }
1677                         }
1678
1679                         Py_XDECREF(value_new);
1680
1681                         break;
1682                 }
1683                 case PROP_COLLECTION:
1684                 {
1685                         int seq_len, i;
1686                         PyObject *item;
1687                         PointerRNA itemptr;
1688                         ListBase *lb;
1689                         CollectionPointerLink *link;
1690
1691                         lb= (data)? (ListBase*)data: NULL;
1692
1693                         /* convert a sequence of dict's into a collection */
1694                         if(!PySequence_Check(value)) {
1695                                 PyErr_Format(PyExc_TypeError,
1696                                              "%.200s %.200s.%.200s expected a sequence for an RNA collection, not %.200s",
1697                                              error_prefix, RNA_struct_identifier(ptr->type),
1698                                              RNA_property_identifier(prop), Py_TYPE(value)->tp_name);
1699                                 return -1;
1700                         }
1701
1702                         seq_len= PySequence_Size(value);
1703                         for(i=0; i<seq_len; i++) {
1704                                 item= PySequence_GetItem(value, i);
1705
1706                                 if(item==NULL) {
1707                                         PyErr_Format(PyExc_TypeError,
1708                                                      "%.200s %.200s.%.200s failed to get sequence index '%d' for an RNA collection",
1709                                                      error_prefix, RNA_struct_identifier(ptr->type),
1710                                                      RNA_property_identifier(prop), i);
1711                                         Py_XDECREF(item);
1712                                         return -1;
1713                                 }
1714
1715                                 if(PyDict_Check(item)==0) {
1716                                         PyErr_Format(PyExc_TypeError,
1717                                                      "%.200s %.200s.%.200s expected a each sequence "
1718                                                      "member to be a dict for an RNA collection, not %.200s",
1719                                                      error_prefix, RNA_struct_identifier(ptr->type),
1720                                                      RNA_property_identifier(prop), Py_TYPE(item)->tp_name);
1721                                         Py_XDECREF(item);
1722                                         return -1;
1723                                 }
1724
1725                                 if(lb) {
1726                                         link= MEM_callocN(sizeof(CollectionPointerLink), "PyCollectionPointerLink");
1727                                         link->ptr= itemptr;
1728                                         BLI_addtail(lb, link);
1729                                 }
1730                                 else
1731                                         RNA_property_collection_add(ptr, prop, &itemptr);
1732
1733                                 if(pyrna_pydict_to_props(&itemptr, item, 1, "Converting a python list to an RNA collection")==-1) {
1734                                         PyObject *msg= PyC_ExceptionBuffer();
1735                                         const char *msg_char= _PyUnicode_AsString(msg);
1736
1737                                         PyErr_Format(PyExc_TypeError,
1738                                                      "%.200s %.200s.%.200s error converting a member of a collection "
1739                                                      "from a dicts into an RNA collection, failed with: %s",
1740                                                      error_prefix, RNA_struct_identifier(ptr->type),
1741                                                      RNA_property_identifier(prop), msg_char);
1742
1743                                         Py_DECREF(item);
1744                                         Py_DECREF(msg);
1745                                         return -1;
1746                                 }
1747                                 Py_DECREF(item);
1748                         }
1749
1750                         break;
1751                 }
1752                 default:
1753                         PyErr_Format(PyExc_AttributeError,
1754                                      "%.200s %.200s.%.200s unknown property type (pyrna_py_to_prop)",
1755                                      error_prefix, RNA_struct_identifier(ptr->type),
1756                                      RNA_property_identifier(prop));
1757                         return -1;
1758                         break;
1759                 }
1760         }
1761
1762         /* Run rna property functions */
1763         if(RNA_property_update_check(prop)) {
1764                 RNA_property_update(BPy_GetContext(), ptr, prop);
1765         }
1766
1767         return 0;
1768 }
1769
1770 static PyObject *pyrna_prop_array_to_py_index(BPy_PropertyArrayRNA *self, int index)
1771 {
1772         PYRNA_PROP_CHECK_OBJ((BPy_PropertyRNA *)self)
1773         return pyrna_py_from_array_index(self, &self->ptr, self->prop, index);
1774 }
1775
1776 static int pyrna_py_to_prop_array_index(BPy_PropertyArrayRNA *self, int index, PyObject *value)
1777 {
1778         int ret= 0;
1779         PointerRNA *ptr= &self->ptr;
1780         PropertyRNA *prop= self->prop;
1781
1782         const int totdim= RNA_property_array_dimension(ptr, prop, NULL);
1783
1784         if (totdim > 1) {
1785                 /* char error_str[512]; */
1786                 if (pyrna_py_to_array_index(&self->ptr, self->prop, self->arraydim, self->arrayoffset, index, value, "") == -1) {
1787                         /* error is set */
1788                         ret= -1;
1789                 }
1790         }
1791         else {
1792                 /* see if we can coerce into a python type - PropertyType */
1793                 switch (RNA_property_type(prop)) {
1794                 case PROP_BOOLEAN:
1795                         {
1796                                 int param= PyLong_AsLong(value);
1797
1798                                 if(param < 0 || param > 1) {
1799                                         PyErr_SetString(PyExc_TypeError, "expected True/False or 0/1");
1800                                         ret= -1;
1801                                 }
1802                                 else {
1803                                         RNA_property_boolean_set_index(ptr, prop, index, param);
1804                                 }
1805                                 break;
1806                         }
1807                 case PROP_INT:
1808                         {
1809                                 int param= PyLong_AsLong(value);
1810                                 if (param==-1 && PyErr_Occurred()) {
1811                                         PyErr_SetString(PyExc_TypeError, "expected an int type");
1812                                         ret= -1;
1813                                 }
1814                                 else {
1815                                         RNA_property_int_clamp(ptr, prop, &param);
1816                                         RNA_property_int_set_index(ptr, prop, index, param);
1817                                 }
1818                                 break;
1819                         }
1820                 case PROP_FLOAT:
1821                         {
1822                                 float param= PyFloat_AsDouble(value);
1823                                 if (PyErr_Occurred()) {
1824                                         PyErr_SetString(PyExc_TypeError, "expected a float type");
1825                                         ret= -1;
1826                                 }
1827                                 else {
1828                                         RNA_property_float_clamp(ptr, prop, &param);
1829                                         RNA_property_float_set_index(ptr, prop, index, param);
1830                                 }
1831                                 break;
1832                         }
1833                 default:
1834                         PyErr_SetString(PyExc_AttributeError, "not an array type");
1835                         ret= -1;
1836                         break;
1837                 }
1838         }
1839
1840         /* Run rna property functions */
1841         if(RNA_property_update_check(prop)) {
1842                 RNA_property_update(BPy_GetContext(), ptr, prop);
1843         }
1844
1845         return ret;
1846 }
1847
1848 //---------------sequence-------------------------------------------
1849 static Py_ssize_t pyrna_prop_array_length(BPy_PropertyArrayRNA *self)
1850 {
1851         PYRNA_PROP_CHECK_INT((BPy_PropertyRNA *)self)
1852
1853         if (RNA_property_array_dimension(&self->ptr, self->prop, NULL) > 1)
1854                 return RNA_property_multi_array_length(&self->ptr, self->prop, self->arraydim);
1855         else
1856                 return RNA_property_array_length(&self->ptr, self->prop);
1857 }
1858
1859 static Py_ssize_t pyrna_prop_collection_length(BPy_PropertyRNA *self)
1860 {
1861         PYRNA_PROP_CHECK_INT(self)
1862
1863         return RNA_property_collection_length(&self->ptr, self->prop);
1864 }
1865
1866 /* bool functions are for speed, so we can avoid getting the length
1867  * of 1000's of items in a linked list for eg. */
1868 static int pyrna_prop_array_bool(BPy_PropertyRNA *self)
1869 {
1870         PYRNA_PROP_CHECK_INT(self)
1871
1872         return RNA_property_array_length(&self->ptr, self->prop) ? 1 : 0;
1873 }
1874
1875 static int pyrna_prop_collection_bool(BPy_PropertyRNA *self)
1876 {
1877         /* no callback defined, just iterate and find the nth item */
1878         CollectionPropertyIterator iter;
1879         int test;
1880
1881         PYRNA_PROP_CHECK_INT(self)
1882
1883         RNA_property_collection_begin(&self->ptr, self->prop, &iter);
1884         test= iter.valid;
1885         RNA_property_collection_end(&iter);
1886         return test;
1887 }
1888
1889 /* internal use only */
1890 static PyObject *pyrna_prop_collection_subscript_int(BPy_PropertyRNA *self, Py_ssize_t keynum)
1891 {
1892         PointerRNA newptr;
1893         Py_ssize_t keynum_abs= keynum;
1894
1895         PYRNA_PROP_CHECK_OBJ(self)
1896
1897         /* notice getting the length of the collection is avoided unless negative index is used
1898          * or to detect internal error with a valid index.
1899          * This is done for faster lookups. */
1900         if(keynum < 0) {
1901                 keynum_abs += RNA_property_collection_length(&self->ptr, self->prop);
1902
1903                 if(keynum_abs < 0) {
1904                         PyErr_Format(PyExc_IndexError, "bpy_prop_collection[%d]: out of range.", keynum);
1905                         return NULL;
1906                 }
1907         }
1908
1909         if(RNA_property_collection_lookup_int(&self->ptr, self->prop, keynum_abs, &newptr)) {
1910                 return pyrna_struct_CreatePyObject(&newptr);
1911         }
1912         else {
1913                 const int len= RNA_property_collection_length(&self->ptr, self->prop);
1914                 if(keynum_abs >= len) {
1915                         PyErr_Format(PyExc_IndexError,
1916                                      "bpy_prop_collection[index]: "
1917                                      "index %d out of range, size %d", keynum, len);
1918                 }
1919                 else {
1920                         PyErr_Format(PyExc_RuntimeError,
1921                                      "bpy_prop_collection[index]: internal error, "
1922                                      "valid index %d given in %d sized collection but value not found",
1923                                      keynum_abs, len);
1924                 }
1925
1926                 return NULL;
1927         }
1928 }
1929
1930 static PyObject *pyrna_prop_array_subscript_int(BPy_PropertyArrayRNA *self, int keynum)
1931 {
1932         int len;
1933
1934         PYRNA_PROP_CHECK_OBJ((BPy_PropertyRNA *)self)
1935
1936         len= pyrna_prop_array_length(self);
1937
1938         if(keynum < 0) keynum += len;
1939
1940         if(keynum >= 0 && keynum < len)
1941                 return pyrna_prop_array_to_py_index(self, keynum);
1942
1943         PyErr_Format(PyExc_IndexError, "bpy_prop_array[index]: index %d out of range", keynum);
1944         return NULL;
1945 }
1946
1947 static PyObject *pyrna_prop_collection_subscript_str(BPy_PropertyRNA *self, const char *keyname)
1948 {
1949         PointerRNA newptr;
1950
1951         PYRNA_PROP_CHECK_OBJ(self)
1952
1953         if(RNA_property_collection_lookup_string(&self->ptr, self->prop, keyname, &newptr))
1954                 return pyrna_struct_CreatePyObject(&newptr);
1955
1956         PyErr_Format(PyExc_KeyError, "bpy_prop_collection[key]: key \"%.200s\" not found", keyname);
1957         return NULL;
1958 }
1959 /* static PyObject *pyrna_prop_array_subscript_str(BPy_PropertyRNA *self, char *keyname) */
1960
1961 static PyObject *pyrna_prop_collection_subscript_slice(BPy_PropertyRNA *self, Py_ssize_t start, Py_ssize_t stop)
1962 {
1963         CollectionPropertyIterator rna_macro_iter;
1964         int count= 0;
1965
1966         PyObject *list;
1967         PyObject *item;
1968
1969         PYRNA_PROP_CHECK_OBJ(self)
1970
1971         list= PyList_New(0);
1972
1973         /* first loop up-until the start */
1974         for(RNA_property_collection_begin(&self->ptr, self->prop, &rna_macro_iter); rna_macro_iter.valid; RNA_property_collection_next(&rna_macro_iter)) {
1975                 /* PointerRNA itemptr= rna_macro_iter.ptr; */
1976                 if(count == start) {
1977                         break;
1978                 }
1979                 count++;
1980         }
1981
1982         /* add items until stop */
1983         for(; rna_macro_iter.valid; RNA_property_collection_next(&rna_macro_iter)) {
1984                 item= pyrna_struct_CreatePyObject(&rna_macro_iter.ptr);
1985                 PyList_Append(list, item);
1986                 Py_DECREF(item);
1987
1988                 count++;
1989                 if(count == stop) {
1990                         break;
1991                 }
1992         }
1993
1994         RNA_property_collection_end(&rna_macro_iter);
1995
1996         return list;
1997 }
1998
1999 /* TODO - dimensions
2000  * note: could also use pyrna_prop_array_to_py_index(self, count) in a loop but its a lot slower
2001  * since at the moment it reads (and even allocates) the entire array for each index.
2002  */
2003 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)
2004 {
2005         int count, totdim;
2006         PyObject *tuple;
2007
2008         PYRNA_PROP_CHECK_OBJ((BPy_PropertyRNA *)self)
2009
2010         tuple= PyTuple_New(stop - start);
2011
2012         /* PYRNA_PROP_CHECK_OBJ(self) isn't needed, internal use only */
2013
2014         totdim= RNA_property_array_dimension(ptr, prop, NULL);
2015
2016         if (totdim > 1) {
2017                 for (count= start; count < stop; count++)
2018                         PyTuple_SET_ITEM(tuple, count - start, pyrna_prop_array_to_py_index(self, count));
2019         }
2020         else {
2021                 switch (RNA_property_type(prop)) {
2022                 case PROP_FLOAT:
2023                         {
2024                                 float values_stack[PYRNA_STACK_ARRAY];
2025                                 float *values;
2026                                 if(length > PYRNA_STACK_ARRAY)  {       values= PyMem_MALLOC(sizeof(float) * length); }
2027                                 else                                                    {       values= values_stack; }
2028                                 RNA_property_float_get_array(ptr, prop, values);
2029
2030                                 for(count=start; count<stop; count++)
2031                                         PyTuple_SET_ITEM(tuple, count-start, PyFloat_FromDouble(values[count]));
2032
2033                                 if(values != values_stack) {
2034                                         PyMem_FREE(values);
2035                                 }
2036                                 break;
2037                         }
2038                 case PROP_BOOLEAN:
2039                         {
2040                                 int values_stack[PYRNA_STACK_ARRAY];
2041                                 int *values;
2042                                 if(length > PYRNA_STACK_ARRAY)  {       values= PyMem_MALLOC(sizeof(int) * length); }
2043                                 else                                                    {       values= values_stack; }
2044
2045                                 RNA_property_boolean_get_array(ptr, prop, values);
2046                                 for(count=start; count<stop; count++)
2047                                         PyTuple_SET_ITEM(tuple, count-start, PyBool_FromLong(values[count]));
2048
2049                                 if(values != values_stack) {
2050                                         PyMem_FREE(values);
2051                                 }
2052                                 break;
2053                         }
2054                 case PROP_INT:
2055                         {
2056                                 int values_stack[PYRNA_STACK_ARRAY];
2057                                 int *values;
2058                                 if(length > PYRNA_STACK_ARRAY)  {       values= PyMem_MALLOC(sizeof(int) * length); }
2059                                 else                                                    {       values= values_stack; }
2060
2061                                 RNA_property_int_get_array(ptr, prop, values);
2062                                 for(count=start; count<stop; count++)
2063                                         PyTuple_SET_ITEM(tuple, count-start, PyLong_FromSsize_t(values[count]));
2064
2065                                 if(values != values_stack) {
2066                                         PyMem_FREE(values);
2067                                 }
2068                                 break;
2069                         }
2070                 default:
2071                         BLI_assert(!"Invalid array type");
2072
2073                         PyErr_SetString(PyExc_TypeError, "not an array type");
2074                         Py_DECREF(tuple);
2075                         tuple= NULL;
2076                 }
2077         }
2078         return tuple;
2079 }
2080
2081 static PyObject *pyrna_prop_collection_subscript(BPy_PropertyRNA *self, PyObject *key)
2082 {
2083         PYRNA_PROP_CHECK_OBJ(self)
2084
2085         if (PyUnicode_Check(key)) {
2086                 return pyrna_prop_collection_subscript_str(self, _PyUnicode_AsString(key));
2087         }
2088         else if (PyIndex_Check(key)) {
2089                 Py_ssize_t i= PyNumber_AsSsize_t(key, PyExc_IndexError);
2090                 if (i == -1 && PyErr_Occurred())
2091                         return NULL;
2092
2093                 return pyrna_prop_collection_subscript_int(self, i);
2094         }
2095         else if (PySlice_Check(key)) {
2096                 PySliceObject *key_slice= (PySliceObject *)key;
2097                 Py_ssize_t step= 1;
2098
2099                 if(key_slice->step != Py_None && !_PyEval_SliceIndex(key, &step)) {
2100                         return NULL;
2101                 }
2102                 else if (step != 1) {
2103                         PyErr_SetString(PyExc_TypeError, "bpy_prop_collection[slice]: slice steps not supported");
2104                         return NULL;
2105                 }
2106                 else if(key_slice->start == Py_None && key_slice->stop == Py_None) {
2107                         return pyrna_prop_collection_subscript_slice(self, 0, PY_SSIZE_T_MAX);
2108                 }
2109                 else {
2110                         Py_ssize_t start= 0, stop= PY_SSIZE_T_MAX;
2111
2112                         /* avoid PySlice_GetIndicesEx because it needs to know the length ahead of time. */
2113                         if(key_slice->start != Py_None && !_PyEval_SliceIndex(key_slice->start, &start))        return NULL;
2114                         if(key_slice->stop != Py_None && !_PyEval_SliceIndex(key_slice->stop, &stop))           return NULL;
2115
2116                         if(start < 0 || stop < 0) {
2117                                 /* only get the length for negative values */
2118                                 Py_ssize_t len= (Py_ssize_t)RNA_property_collection_length(&self->ptr, self->prop);
2119                                 if(start < 0) start += len;
2120                                 if(stop < 0) start += len;
2121                         }
2122
2123                         if (stop - start <= 0) {
2124                                 return PyList_New(0);
2125                         }
2126                         else {
2127                                 return pyrna_prop_collection_subscript_slice(self, start, stop);
2128                         }
2129                 }
2130         }
2131         else {
2132                 PyErr_Format(PyExc_TypeError,
2133                              "bpy_prop_collection[key]: invalid key, "
2134                              "must be a string or an int, not %.200s",
2135                              Py_TYPE(key)->tp_name);
2136                 return NULL;
2137         }
2138 }
2139
2140 static PyObject *pyrna_prop_array_subscript(BPy_PropertyArrayRNA *self, PyObject *key)
2141 {
2142         PYRNA_PROP_CHECK_OBJ((BPy_PropertyRNA *)self)
2143
2144         /*if (PyUnicode_Check(key)) {
2145                 return pyrna_prop_array_subscript_str(self, _PyUnicode_AsString(key));
2146         }
2147         else */
2148         if (PyIndex_Check(key)) {
2149                 Py_ssize_t i= PyNumber_AsSsize_t(key, PyExc_IndexError);
2150                 if (i == -1 && PyErr_Occurred())
2151                         return NULL;
2152                 return pyrna_prop_array_subscript_int(self, PyLong_AsLong(key));
2153         }
2154         else if (PySlice_Check(key)) {
2155                 Py_ssize_t step= 1;
2156                 PySliceObject *key_slice= (PySliceObject *)key;
2157
2158                 if(key_slice->step != Py_None && !_PyEval_SliceIndex(key, &step)) {
2159                         return NULL;
2160                 }
2161                 else if (step != 1) {
2162                         PyErr_SetString(PyExc_TypeError, "bpy_prop_array[slice]: slice steps not supported");
2163                         return NULL;
2164                 }
2165                 else if(key_slice->start == Py_None && key_slice->stop == Py_None) {
2166                         /* note, no significant advantage with optimizing [:] slice as with collections but include here for consistency with collection slice func */
2167                         Py_ssize_t len= (Py_ssize_t)pyrna_prop_array_length(self);
2168                         return pyrna_prop_array_subscript_slice(self, &self->ptr, self->prop, 0, len, len);
2169                 }
2170                 else {
2171                         int len= pyrna_prop_array_length(self);
2172                         Py_ssize_t start, stop, slicelength;
2173
2174                         if (PySlice_GetIndicesEx((void *)key, len, &start, &stop, &step, &slicelength) < 0)
2175                                 return NULL;
2176
2177                         if (slicelength <= 0) {
2178                                 return PyTuple_New(0);
2179                         }
2180                         else {
2181                                 return pyrna_prop_array_subscript_slice(self, &self->ptr, self->prop, start, stop, len);
2182                         }
2183                 }
2184         }
2185         else {
2186                 PyErr_SetString(PyExc_AttributeError, "bpy_prop_array[key]: invalid key, key must be an int");
2187                 return NULL;
2188         }
2189 }
2190
2191 /* could call (pyrna_py_to_prop_array_index(self, i, value) in a loop but it is slow */
2192 static int prop_subscript_ass_array_slice(PointerRNA *ptr, PropertyRNA *prop, int start, int stop, int length, PyObject *value_orig)
2193 {
2194         PyObject *value;
2195         int count;
2196         void *values_alloc= NULL;
2197         int ret= 0;
2198
2199         if(value_orig == NULL) {
2200                 PyErr_SetString(PyExc_TypeError, "bpy_prop_array[slice]= value: deleting with list types is not supported by bpy_struct");
2201                 return -1;
2202         }
2203
2204         if(!(value=PySequence_Fast(value_orig, "bpy_prop_array[slice]= value: assignment is not a sequence type"))) {
2205                 return -1;
2206         }
2207
2208         if(PySequence_Fast_GET_SIZE(value) != stop-start) {
2209                 Py_DECREF(value);
2210                 PyErr_SetString(PyExc_TypeError, "bpy_prop_array[slice]= value: resizing bpy_struct arrays isn't supported");
2211                 return -1;
2212         }
2213
2214         switch (RNA_property_type(prop)) {
2215                 case PROP_FLOAT:
2216                 {
2217                         float values_stack[PYRNA_STACK_ARRAY];
2218                         float *values, fval;
2219
2220                         float min, max;
2221                         RNA_property_float_range(ptr, prop, &min, &max);
2222
2223                         if(length > PYRNA_STACK_ARRAY)  {       values= values_alloc= PyMem_MALLOC(sizeof(float) * length); }
2224                         else                                                    {       values= values_stack; }
2225                         if(start != 0 || stop != length) /* partial assignment? - need to get the array */
2226                                 RNA_property_float_get_array(ptr, prop, values);
2227
2228                         for(count=start; count<stop; count++) {
2229                                 fval= PyFloat_AsDouble(PySequence_Fast_GET_ITEM(value, count-start));
2230                                 CLAMP(fval, min, max);
2231                                 values[count]= fval;
2232                         }
2233
2234                         if(PyErr_Occurred())    ret= -1;
2235                         else                                    RNA_property_float_set_array(ptr, prop, values);
2236                         break;
2237                 }
2238                 case PROP_BOOLEAN:
2239                 {
2240                         int values_stack[PYRNA_STACK_ARRAY];
2241                         int *values;
2242                         if(length > PYRNA_STACK_ARRAY)  {       values= values_alloc= PyMem_MALLOC(sizeof(int) * length); }
2243                         else                                                    {       values= values_stack; }
2244
2245                         if(start != 0 || stop != length) /* partial assignment? - need to get the array */
2246                                 RNA_property_boolean_get_array(ptr, prop, values);
2247
2248                         for(count=start; count<stop; count++)
2249                                 values[count]= PyLong_AsLong(PySequence_Fast_GET_ITEM(value, count-start));
2250
2251                         if(PyErr_Occurred())    ret= -1;
2252                         else                                    RNA_property_boolean_set_array(ptr, prop, values);
2253                         break;
2254                 }
2255                 case PROP_INT:
2256                 {
2257                         int values_stack[PYRNA_STACK_ARRAY];
2258                         int *values, ival;
2259
2260                         int min, max;
2261                         RNA_property_int_range(ptr, prop, &min, &max);
2262
2263                         if(length > PYRNA_STACK_ARRAY)  {       values= values_alloc= PyMem_MALLOC(sizeof(int) * length); }
2264                         else                                                    {       values= values_stack; }
2265
2266                         if(start != 0 || stop != length) /* partial assignment? - need to get the array */
2267                                 RNA_property_int_get_array(ptr, prop, values);
2268
2269                         for(count=start; count<stop; count++) {
2270                                 ival= PyLong_AsLong(PySequence_Fast_GET_ITEM(value, count-start));
2271                                 CLAMP(ival, min, max);
2272                                 values[count]= ival;
2273                         }
2274
2275                         if(PyErr_Occurred())    ret= -1;
2276                         else                                    RNA_property_int_set_array(ptr, prop, values);
2277                         break;
2278                 }
2279                 default:
2280                         PyErr_SetString(PyExc_TypeError, "not an array type");
2281                         ret= -1;
2282         }
2283
2284         Py_DECREF(value);
2285
2286         if(values_alloc) {
2287                 PyMem_FREE(values_alloc);
2288         }
2289
2290         return ret;
2291
2292 }
2293
2294 static int prop_subscript_ass_array_int(BPy_PropertyArrayRNA *self, Py_ssize_t keynum, PyObject *value)
2295 {
2296         int len;
2297
2298         PYRNA_PROP_CHECK_INT((BPy_PropertyRNA *)self)
2299
2300         len= pyrna_prop_array_length(self);
2301
2302         if(keynum < 0) keynum += len;
2303
2304         if(keynum >= 0 && keynum < len)
2305                 return pyrna_py_to_prop_array_index(self, keynum, value);
2306
2307         PyErr_SetString(PyExc_IndexError, "bpy_prop_array[index] = value: index out of range");
2308         return -1;
2309 }
2310
2311 static int pyrna_prop_array_ass_subscript(BPy_PropertyArrayRNA *self, PyObject *key, PyObject *value)
2312 {
2313         /* char *keyname= NULL; */ /* not supported yet */
2314         int ret= -1;
2315
2316         PYRNA_PROP_CHECK_INT((BPy_PropertyRNA *)self);
2317
2318         if (!RNA_property_editable_flag(&self->ptr, self->prop)) {
2319                 PyErr_Format(PyExc_AttributeError,
2320                              "bpy_prop_collection: attribute \"%.200s\" from \"%.200s\" is read-only",
2321                              RNA_property_identifier(self->prop), RNA_struct_identifier(self->ptr.type));
2322                 ret= -1;
2323         }
2324
2325         else if (PyIndex_Check(key)) {
2326                 Py_ssize_t i= PyNumber_AsSsize_t(key, PyExc_IndexError);
2327                 if (i == -1 && PyErr_Occurred()) {
2328                         ret= -1;
2329                 }
2330                 else {
2331                         ret= prop_subscript_ass_array_int(self, i, value);
2332                 }
2333         }
2334         else if (PySlice_Check(key)) {
2335                 int len= RNA_property_array_length(&self->ptr, self->prop);
2336                 Py_ssize_t start, stop, step, slicelength;
2337
2338                 if (PySlice_GetIndicesEx((void *)key, len, &start, &stop, &step, &slicelength) < 0) {
2339                         ret= -1;
2340                 }
2341                 else if (slicelength <= 0) {
2342                         ret= 0; /* do nothing */
2343                 }
2344                 else if (step == 1) {
2345                         ret= prop_subscript_ass_array_slice(&self->ptr, self->prop, start, stop, len, value);
2346                 }
2347                 else {
2348                         PyErr_SetString(PyExc_TypeError, "slice steps not supported with rna");
2349                         ret= -1;
2350                 }
2351         }
2352         else {
2353                 PyErr_SetString(PyExc_AttributeError, "invalid key, key must be an int");
2354                 ret= -1;
2355         }
2356
2357         if(ret != -1) {
2358                 if(RNA_property_update_check(self->prop)) {
2359                         RNA_property_update(BPy_GetContext(), &self->ptr, self->prop);
2360                 }
2361         }
2362
2363         return ret;
2364 }
2365
2366 /* for slice only */
2367 static PyMappingMethods pyrna_prop_array_as_mapping= {
2368         (lenfunc) pyrna_prop_array_length,      /* mp_length */
2369         (binaryfunc) pyrna_prop_array_subscript,        /* mp_subscript */
2370         (objobjargproc) pyrna_prop_array_ass_subscript, /* mp_ass_subscript */
2371 };
2372
2373 static PyMappingMethods pyrna_prop_collection_as_mapping= {
2374         (lenfunc) pyrna_prop_collection_length, /* mp_length */
2375         (binaryfunc) pyrna_prop_collection_subscript,   /* mp_subscript */
2376         (objobjargproc) NULL,   /* mp_ass_subscript */
2377 };
2378
2379 /* only for fast bool's, large structs, assign nb_bool on init */
2380 static PyNumberMethods pyrna_prop_array_as_number= {
2381         NULL, /* nb_add */
2382         NULL, /* nb_subtract */
2383         NULL, /* nb_multiply */
2384         NULL, /* nb_remainder */
2385         NULL, /* nb_divmod */
2386         NULL, /* nb_power */
2387         NULL, /* nb_negative */
2388         NULL, /* nb_positive */
2389         NULL, /* nb_absolute */
2390         (inquiry) pyrna_prop_array_bool, /* nb_bool */
2391 };
2392 static PyNumberMethods pyrna_prop_collection_as_number= {
2393         NULL, /* nb_add */
2394         NULL, /* nb_subtract */
2395         NULL, /* nb_multiply */
2396         NULL, /* nb_remainder */
2397         NULL, /* nb_divmod */
2398         NULL, /* nb_power */
2399         NULL, /* nb_negative */
2400         NULL, /* nb_positive */
2401         NULL, /* nb_absolute */
2402         (inquiry) pyrna_prop_collection_bool, /* nb_bool */
2403 };
2404
2405 static int pyrna_prop_array_contains(BPy_PropertyRNA *self, PyObject *value)
2406 {
2407         return pyrna_array_contains_py(&self->ptr, self->prop, value);
2408 }
2409
2410 static int pyrna_prop_collection_contains(BPy_PropertyRNA *self, PyObject *value)
2411 {
2412         PointerRNA newptr; /* not used, just so RNA_property_collection_lookup_string runs */
2413
2414         /* key in dict style check */
2415         const char *keyname= _PyUnicode_AsString(value);
2416
2417         if(keyname==NULL) {
2418                 PyErr_SetString(PyExc_TypeError, "bpy_prop_collection.__contains__: expected a string");
2419                 return -1;
2420         }
2421
2422         if (RNA_property_collection_lookup_string(&self->ptr, self->prop, keyname, &newptr))
2423                 return 1;
2424
2425         return 0;
2426 }
2427
2428 static int pyrna_struct_contains(BPy_StructRNA *self, PyObject *value)
2429 {
2430         IDProperty *group;
2431         const char *name= _PyUnicode_AsString(value);
2432
2433         PYRNA_STRUCT_CHECK_INT(self)
2434
2435         if (!name) {
2436                 PyErr_SetString(PyExc_TypeError, "bpy_struct.__contains__: expected a string");
2437                 return -1;
2438         }
2439
2440         if(RNA_struct_idprops_check(self->ptr.type)==0) {
2441                 PyErr_SetString(PyExc_TypeError, "bpy_struct: this type doesn't support IDProperties");
2442                 return -1;
2443         }
2444
2445         group= RNA_struct_idprops(&self->ptr, 0);
2446
2447         if(!group)
2448                 return 0;
2449
2450         return IDP_GetPropertyFromGroup(group, name) ? 1:0;
2451 }
2452
2453 static PySequenceMethods pyrna_prop_array_as_sequence= {
2454         (lenfunc)pyrna_prop_array_length,               /* Cant set the len otherwise it can evaluate as false */
2455         NULL,           /* sq_concat */
2456         NULL,           /* sq_repeat */
2457         (ssizeargfunc)pyrna_prop_array_subscript_int, /* sq_item */ /* Only set this so PySequence_Check() returns True */
2458         NULL,           /* sq_slice */
2459         (ssizeobjargproc)prop_subscript_ass_array_int,          /* sq_ass_item */
2460         NULL,           /* *was* sq_ass_slice */
2461         (objobjproc)pyrna_prop_array_contains,  /* sq_contains */
2462         (binaryfunc) NULL, /* sq_inplace_concat */
2463         (ssizeargfunc) NULL, /* sq_inplace_repeat */
2464 };
2465
2466 static PySequenceMethods pyrna_prop_collection_as_sequence= {
2467         (lenfunc)pyrna_prop_collection_length,          /* Cant set the len otherwise it can evaluate as false */
2468         NULL,           /* sq_concat */
2469         NULL,           /* sq_repeat */
2470         (ssizeargfunc)pyrna_prop_collection_subscript_int, /* sq_item */ /* Only set this so PySequence_Check() returns True */
2471         NULL,           /* *was* sq_slice */
2472         NULL,           /* sq_ass_item */
2473         NULL,           /* *was* sq_ass_slice */
2474         (objobjproc)pyrna_prop_collection_contains,     /* sq_contains */
2475         (binaryfunc) NULL, /* sq_inplace_concat */
2476         (ssizeargfunc) NULL, /* sq_inplace_repeat */
2477 };
2478
2479 static PySequenceMethods pyrna_struct_as_sequence= {
2480         NULL,           /* Cant set the len otherwise it can evaluate as false */
2481         NULL,           /* sq_concat */
2482         NULL,           /* sq_repeat */
2483         NULL,           /* sq_item */ /* Only set this so PySequence_Check() returns True */
2484         NULL,           /* *was* sq_slice */
2485         NULL,           /* sq_ass_item */
2486         NULL,           /* *was* sq_ass_slice */
2487         (objobjproc)pyrna_struct_contains,      /* sq_contains */
2488         (binaryfunc) NULL, /* sq_inplace_concat */
2489         (ssizeargfunc) NULL, /* sq_inplace_repeat */
2490 };
2491
2492 static PyObject *pyrna_struct_subscript(BPy_StructRNA *self, PyObject *key)
2493 {
2494         /* mostly copied from BPy_IDGroup_Map_GetItem */
2495         IDProperty *group, *idprop;
2496         const char *name= _PyUnicode_AsString(key);
2497
2498         PYRNA_STRUCT_CHECK_OBJ(self)
2499
2500         if(RNA_struct_idprops_check(self->ptr.type)==0) {
2501                 PyErr_SetString(PyExc_TypeError, "this type doesn't support IDProperties");
2502                 return NULL;
2503         }
2504
2505         if(name==NULL) {
2506                 PyErr_SetString(PyExc_TypeError, "bpy_struct[key]: only strings are allowed as keys of ID properties");
2507                 return NULL;
2508         }
2509
2510         group= RNA_struct_idprops(&self->ptr, 0);
2511
2512         if(group==NULL) {
2513                 PyErr_Format(PyExc_KeyError, "bpy_struct[key]: key \"%s\" not found", name);
2514                 return NULL;
2515         }
2516
2517         idprop= IDP_GetPropertyFromGroup(group, name);
2518
2519         if(idprop==NULL) {
2520                 PyErr_Format(PyExc_KeyError, "bpy_struct[key]: key \"%s\" not found", name);
2521                 return NULL;
2522         }
2523
2524         return BPy_IDGroup_WrapData(self->ptr.id.data, idprop);
2525 }
2526
2527 static int pyrna_struct_ass_subscript(BPy_StructRNA *self, PyObject *key, PyObject *value)
2528 {
2529         IDProperty *group;
2530
2531         PYRNA_STRUCT_CHECK_INT(self)
2532
2533         group= RNA_struct_idprops(&self->ptr, 1);
2534
2535 #ifdef USE_PEDANTIC_WRITE
2536         if(rna_disallow_writes && rna_id_write_error(&self->ptr, key)) {
2537                 return -1;
2538         }
2539 #endif // USE_STRING_COERCE
2540
2541         if(group==NULL) {
2542                 PyErr_SetString(PyExc_TypeError, "bpy_struct[key]= val: id properties not supported for this type");
2543                 return -1;
2544         }
2545
2546         return BPy_Wrap_SetMapItem(group, key, value);
2547 }
2548
2549 static PyMappingMethods pyrna_struct_as_mapping= {
2550         (lenfunc) NULL, /* mp_length */
2551         (binaryfunc) pyrna_struct_subscript,    /* mp_subscript */
2552         (objobjargproc) pyrna_struct_ass_subscript,     /* mp_ass_subscript */
2553 };
2554
2555 PyDoc_STRVAR(pyrna_struct_keys_doc,
2556 ".. method:: keys()\n"
2557 "\n"
2558 "   Returns the keys of this objects custom properties (matches pythons\n"
2559 "   dictionary function of the same name).\n"
2560 "\n"
2561 "   :return: custom property keys.\n"
2562 "   :rtype: list of strings\n"
2563 "\n"
2564 "   .. note:: Only :class:`ID`, :class:`Bone` and :class:`PoseBone` classes\n"
2565 "      support custom properties.\n"
2566 );
2567 static PyObject *pyrna_struct_keys(BPy_PropertyRNA *self)
2568 {
2569         IDProperty *group;
2570
2571         if(RNA_struct_idprops_check(self->ptr.type)==0) {
2572                 PyErr_SetString(PyExc_TypeError, "bpy_struct.keys(): this type doesn't support IDProperties");
2573                 return NULL;
2574         }
2575
2576         group= RNA_struct_idprops(&self->ptr, 0);
2577
2578         if(group==NULL)
2579                 return PyList_New(0);
2580
2581         return BPy_Wrap_GetKeys(group);
2582 }
2583
2584 PyDoc_STRVAR(pyrna_struct_items_doc,
2585 ".. method:: items()\n"
2586 "\n"
2587 "   Returns the items of this objects custom properties (matches pythons\n"
2588 "   dictionary function of the same name).\n"
2589 "\n"
2590 "   :return: custom property key, value pairs.\n"
2591 "   :rtype: list of key, value tuples\n"
2592 "\n"
2593 "   .. note:: Only :class:`ID`, :class:`Bone` and :class:`PoseBone`\n"
2594 "      classes support custom properties.\n"
2595 );
2596 static PyObject *pyrna_struct_items(BPy_PropertyRNA *self)
2597 {
2598         IDProperty *group;
2599
2600         if(RNA_struct_idprops_check(self->ptr.type)==0) {
2601                 PyErr_SetString(PyExc_TypeError, "bpy_struct.items(): this type doesn't support IDProperties");
2602                 return NULL;
2603         }
2604
2605         group= RNA_struct_idprops(&self->ptr, 0);
2606
2607         if(group==NULL)
2608                 return PyList_New(0);
2609
2610         return BPy_Wrap_GetItems(self->ptr.id.data, group);
2611 }
2612
2613 PyDoc_STRVAR(pyrna_struct_values_doc,
2614 ".. method:: values()\n"
2615 "\n"
2616 "   Returns the values of this objects custom properties (matches pythons\n"
2617 "   dictionary function of the same name).\n"
2618 "\n"
2619 "   :return: custom property values.\n"
2620 "   :rtype: list\n"
2621 "\n"
2622 "   .. note:: Only :class:`ID`, :class:`Bone` and :class:`PoseBone`\n"
2623 "      classes support custom properties.\n"
2624 );
2625 static PyObject *pyrna_struct_values(BPy_PropertyRNA *self)
2626 {
2627         IDProperty *group;
2628
2629         if(RNA_struct_idprops_check(self->ptr.type)==0) {
2630                 PyErr_SetString(PyExc_TypeError, "bpy_struct.values(): this type doesn't support IDProperties");
2631                 return NULL;
2632         }
2633
2634         group= RNA_struct_idprops(&self->ptr, 0);
2635
2636         if(group==NULL)
2637                 return PyList_New(0);
2638
2639         return BPy_Wrap_GetValues(self->ptr.id.data, group);
2640 }
2641
2642
2643 PyDoc_STRVAR(pyrna_struct_is_property_set_doc,
2644 ".. method:: is_property_set(property)\n"
2645 "\n"
2646 "   Check if a property is set, use for testing operator properties.\n"
2647 "\n"
2648 "   :return: True when the property has been set.\n"
2649 "   :rtype: boolean\n"
2650 );
2651 static PyObject *pyrna_struct_is_property_set(BPy_StructRNA *self, PyObject *args)
2652 {
2653         PropertyRNA *prop;
2654         const char *name;
2655         int ret;
2656
2657         PYRNA_STRUCT_CHECK_OBJ(self)
2658
2659         if (!PyArg_ParseTuple(args, "s:is_property_set", &name))
2660                 return NULL;
2661
2662         if((prop= RNA_struct_find_property(&self->ptr, name)) == NULL) {
2663                 PyErr_Format(PyExc_TypeError,
2664                              "%.200s.is_property_set(\"%.200s\") not found",
2665                              RNA_struct_identifier(self->ptr.type), name);
2666                 return NULL;
2667         }
2668
2669         /* double property lookup, could speed up */
2670         /* return PyBool_FromLong(RNA_property_is_set(&self->ptr, name)); */
2671         if(RNA_property_flag(prop) & PROP_IDPROPERTY) {
2672                 IDProperty *group= RNA_struct_idprops(&self->ptr, 0);
2673                 if(group) {
2674                         ret= IDP_GetPropertyFromGroup(group, name) ? 1:0;
2675                 }
2676                 else {
2677                         ret= 0;
2678                 }
2679         }
2680         else {
2681                 ret= 1;
2682         }
2683
2684         return PyBool_FromLong(ret);
2685 }
2686
2687 PyDoc_STRVAR(pyrna_struct_is_property_hidden_doc,
2688 ".. method:: is_property_hidden(property)\n"
2689 "\n"
2690 "   Check if a property is hidden.\n"
2691 "\n"
2692 "   :return: True when the property is hidden.\n"
2693 "   :rtype: boolean\n"
2694 );
2695 static PyObject *pyrna_struct_is_property_hidden(BPy_StructRNA *self, PyObject *args)
2696 {
2697         PropertyRNA *prop;
2698         const char *name;
2699
2700         PYRNA_STRUCT_CHECK_OBJ(self)
2701
2702         if (!PyArg_ParseTuple(args, "s:is_property_hidden", &name))
2703                 return NULL;
2704
2705         if((prop= RNA_struct_find_property(&self->ptr, name)) == NULL) {
2706                 PyErr_Format(PyExc_TypeError,
2707                              "%.200s.is_property_hidden(\"%.200s\") not found",
2708                              RNA_struct_identifier(self->ptr.type), name);
2709                 return NULL;
2710         }
2711
2712         return PyBool_FromLong(RNA_property_flag(prop) & PROP_HIDDEN);
2713 }
2714
2715 PyDoc_STRVAR(pyrna_struct_path_resolve_doc,
2716 ".. method:: path_resolve(path, coerce=True)\n"
2717 "\n"
2718 "   Returns the property from the path, raise an exception when not found.\n"
2719 "\n"
2720 "   :arg path: path which this property resolves.\n"
2721 "   :type path: string\n"
2722 "   :arg coerce: optional argument, when True, the property will be converted\n"
2723 "      into its python representation.\n"
2724 "   :type coerce: boolean\n"
2725 );
2726 static PyObject *pyrna_struct_path_resolve(BPy_StructRNA *self, PyObject *args)
2727 {
2728         const char *path;
2729         PyObject *coerce= Py_True;
2730         PointerRNA r_ptr;
2731         PropertyRNA *r_prop;
2732         int index= -1;
2733
2734         PYRNA_STRUCT_CHECK_OBJ(self)
2735
2736         if (!PyArg_ParseTuple(args, "s|O!:path_resolve", &path, &PyBool_Type, &coerce))
2737                 return NULL;
2738
2739         if (RNA_path_resolve_full(&self->ptr, path, &r_ptr, &r_prop, &index)) {
2740                 if(r_prop) {
2741                         if(index != -1) {
2742                                 if(index >= RNA_property_array_length(&r_ptr, r_prop) || index < 0) {
2743                                         PyErr_Format(PyExc_TypeError,
2744                                                      "%.200s.path_resolve(\"%.200s\") index out of range",
2745                                                      RNA_struct_identifier(self->ptr.type), path);
2746                                         return NULL;
2747                                 }
2748                                 else {
2749                                         return pyrna_array_index(&r_ptr, r_prop, index);
2750                                 }
2751                         }
2752                         else {
2753                                 if(coerce == Py_False) {
2754                                         return pyrna_prop_CreatePyObject(&r_ptr, r_prop);
2755                                 }
2756                                 else {
2757                                         return pyrna_prop_to_py(&r_ptr, r_prop);
2758                                 }
2759                         }
2760                 }
2761                 else {
2762                         return pyrna_struct_CreatePyObject(&r_ptr);
2763                 }
2764         }
2765         else {
2766                 PyErr_Format(PyExc_TypeError,
2767                              "%.200s.path_resolve(\"%.200s\") could not be resolved",
2768                              RNA_struct_identifier(self->ptr.type), path);
2769                 return NULL;
2770         }
2771 }
2772
2773 PyDoc_STRVAR(pyrna_struct_path_from_id_doc,
2774 ".. method:: path_from_id(property=\"\")\n"
2775 "\n"
2776 "   Returns the data path from the ID to this object (string).\n"
2777 "\n"
2778 "   :arg property: Optional property name which can be used if the path is\n"
2779 "      to a property of this object.\n"
2780 "   :type property: string\n"
2781 "   :return: The path from :class:`bpy_struct.id_data`\n"
2782 "      to this struct and property (when given).\n"
2783 "   :rtype: str\n"
2784 );
2785 static PyObject *pyrna_struct_path_from_id(BPy_StructRNA *self, PyObject *args)
2786 {
2787         const char *name= NULL;
2788         const char *path;
2789         PropertyRNA *prop;
2790         PyObject *ret;
2791
2792         PYRNA_STRUCT_CHECK_OBJ(self)
2793
2794         if (!PyArg_ParseTuple(args, "|s:path_from_id", &name))
2795                 return NULL;
2796
2797         if(name) {
2798                 prop= RNA_struct_find_property(&self->ptr, name);
2799                 if(prop==NULL) {
2800                         PyErr_Format(PyExc_TypeError,
2801                                      "%.200s.path_from_id(\"%.200s\") not found",
2802                                      RNA_struct_identifier(self->ptr.type), name);
2803                         return NULL;
2804                 }
2805
2806                 path= RNA_path_from_ID_to_property(&self->ptr, prop);
2807         }
2808         else {
2809                 path= RNA_path_from_ID_to_struct(&self->ptr);
2810         }
2811
2812         if(path==NULL) {
2813                 if(name) {
2814                         PyErr_Format(PyExc_TypeError,
2815                                      "%.200s.path_from_id(\"%s\") found but does not support path creation",
2816                                      RNA_struct_identifier(self->ptr.type), name);
2817                 }
2818                 else {
2819                         PyErr_Format(PyExc_TypeError,
2820                                      "%.200s.path_from_id() does not support path creation for this type",
2821                                      RNA_struct_identifier(self->ptr.type));
2822                 }
2823                 return NULL;
2824         }
2825
2826         ret= PyUnicode_FromString(path);
2827         MEM_freeN((void *)path);
2828
2829         return ret;
2830 }
2831
2832 PyDoc_STRVAR(pyrna_prop_path_from_id_doc,
2833 ".. method:: path_from_id()\n"
2834 "\n"
2835 "   Returns the data path from the ID to this property (string).\n"
2836 "\n"
2837 "   :return: The path from :class:`bpy_struct.id_data` to this property.\n"
2838 "   :rtype: str\n"
2839 );
2840 static PyObject *pyrna_prop_path_from_id(BPy_PropertyRNA *self)
2841 {
2842         const char *path;
2843         PropertyRNA *prop= self->prop;
2844         PyObject *ret;
2845
2846         path= RNA_path_from_ID_to_property(&self->ptr, self->prop);
2847
2848         if(path==NULL) {
2849                 PyErr_Format(PyExc_TypeError,
2850                              "%.200s.%.200s.path_from_id() does not support path creation for this type",
2851                              RNA_struct_identifier(self->ptr.type), RNA_property_identifier(prop));
2852                 return NULL;
2853         }
2854
2855         ret= PyUnicode_FromString(path);
2856         MEM_freeN((void *)path);
2857
2858         return ret;
2859 }
2860
2861 PyDoc_STRVAR(pyrna_struct_type_recast_doc,
2862 ".. method:: type_recast()\n"
2863 "\n"
2864 "   Return a new instance, this is needed because types\n"
2865 "   such as textures can be changed at runtime.\n"
2866 "\n"
2867 "   :return: a new instance of this object with the type initialized again.\n"
2868 "   :rtype: subclass of :class:`bpy_struct`\n"
2869 );
2870 static PyObject *pyrna_struct_type_recast(BPy_StructRNA *self)
2871 {
2872         PointerRNA r_ptr;
2873
2874         PYRNA_STRUCT_CHECK_OBJ(self)
2875
2876         RNA_pointer_recast(&self->ptr, &r_ptr);
2877         return pyrna_struct_CreatePyObject(&r_ptr);
2878 }
2879
2880 static void pyrna_dir_members_py(PyObject *list, PyObject *self)
2881 {
2882         PyObject *dict;
2883         PyObject **dict_ptr;
2884         PyObject *list_tmp;
2885
2886         dict_ptr= _PyObject_GetDictPtr((PyObject *)self);
2887
2888         if(dict_ptr && (dict=*dict_ptr)) {
2889                 list_tmp= PyDict_Keys(dict);
2890                 PyList_SetSlice(list, INT_MAX, INT_MAX, list_tmp);
2891                 Py_DECREF(list_tmp);
2892         }
2893
2894         dict= ((PyTypeObject *)Py_TYPE(self))->tp_dict;
2895         if(dict) {
2896                 list_tmp= PyDict_Keys(dict);
2897                 PyList_SetSlice(list, INT_MAX, INT_MAX, list_tmp);
2898                 Py_DECREF(list_tmp);
2899         }
2900 }
2901
2902 static void pyrna_dir_members_rna(PyObject *list, PointerRNA *ptr)
2903 {
2904         PyObject *pystring;
2905         const char *idname;
2906
2907         /* for looping over attrs and funcs */
2908         PointerRNA tptr;
2909         PropertyRNA *iterprop;
2910
2911         {
2912                 RNA_pointer_create(NULL, &RNA_Struct, ptr->type, &tptr);
2913                 iterprop= RNA_struct_find_property(&tptr, "functions");
2914
2915                 RNA_PROP_BEGIN(&tptr, itemptr, iterprop) {
2916                         idname= RNA_function_identifier(itemptr.data);
2917
2918                         pystring= PyUnicode_FromString(idname);
2919                         PyList_Append(list, pystring);
2920                         Py_DECREF(pystring);
2921                 }
2922                 RNA_PROP_END;
2923         }
2924
2925         {
2926                 /*
2927                  * Collect RNA attributes
2928                  */
2929                 char name[256], *nameptr;
2930
2931                 iterprop= RNA_struct_iterator_property(ptr->type);
2932
2933                 RNA_PROP_BEGIN(ptr, itemptr, iterprop) {
2934                         nameptr= RNA_struct_name_get_alloc(&itemptr, name, sizeof(name));
2935
2936                         if(nameptr) {
2937                                 pystring= PyUnicode_FromString(nameptr);
2938                                 PyList_Append(list, pystring);
2939                                 Py_DECREF(pystring);
2940
2941                                 if(name != nameptr)
2942                                         MEM_freeN(nameptr);
2943                         }
2944                 }
2945                 RNA_PROP_END;
2946         }
2947 }
2948
2949
2950 static PyObject *pyrna_struct_dir(BPy_StructRNA *self)
2951 {
2952         PyObject *ret;
2953         PyObject *pystring;
2954
2955         PYRNA_STRUCT_CHECK_OBJ(self)
2956
2957         /* Include this incase this instance is a subtype of a python class
2958          * In these instances we may want to return a function or variable provided by the subtype
2959          * */
2960         ret= PyList_New(0);
2961
2962         if (!BPy_StructRNA_CheckExact(self))
2963                 pyrna_dir_members_py(ret, (PyObject *)self);
2964
2965         pyrna_dir_members_rna(ret, &self->ptr);
2966
2967         if(self->ptr.type == &RNA_Context) {
2968                 ListBase lb= CTX_data_dir_get(self->ptr.data);
2969                 LinkData *link;
2970
2971                 for(link=lb.first; link; link=link->next) {
2972                         pystring= PyUnicode_FromString(link->data);
2973                         PyList_Append(ret, pystring);
2974                         Py_DECREF(pystring);
2975                 }
2976
2977                 BLI_freelistN(&lb);
2978         }
2979
2980         {
2981                 /* set(), this is needed to remove-doubles because the deferred
2982                  * register-props will be in both the python __dict__ and accessed as RNA */
2983
2984                 PyObject *set= PySet_New(ret);
2985
2986                 Py_DECREF(ret);
2987                 ret= PySequence_List(set);
2988                 Py_DECREF(set);
2989         }
2990
2991         return ret;
2992 }
2993
2994 //---------------getattr--------------------------------------------
2995 static PyObject *pyrna_struct_getattro(BPy_StructRNA *self, PyObject *pyname)
2996 {
2997         const char *name= _PyUnicode_AsString(pyname);
2998         PyObject *ret;
2999         PropertyRNA *prop;
3000         FunctionRNA *func;
3001
3002         PYRNA_STRUCT_CHECK_OBJ(self)
3003
3004         if(name == NULL) {
3005                 PyErr_SetString(PyExc_AttributeError, "bpy_struct: __getattr__ must be a string");
3006                 ret= NULL;
3007         }
3008         else if(name[0]=='_') { // rna can't start with a "_", so for __dict__ and similar we can skip using rna lookups
3009                 /* annoying exception, maybe we need to have different types for this... */
3010                 if((strcmp(name, "__getitem__")==0 || strcmp(name, "__setitem__")==0) && !RNA_struct_idprops_check(self->ptr.type)) {
3011                         PyErr_SetString(PyExc_AttributeError, "bpy_struct: no __getitem__ support for this type");
3012                         ret= NULL;
3013                 }
3014                 else {
3015                         ret= PyObject_GenericGetAttr((PyObject *)self, pyname);
3016                 }
3017         }
3018         else if ((prop= RNA_struct_find_property(&self->ptr, name))) {
3019                 ret= pyrna_prop_to_py(&self->ptr, prop);
3020         }
3021         /* RNA function only if callback is declared (no optional functions) */
3022         else if ((func= RNA_struct_find_function(&self->ptr, name)) && RNA_function_defined(func)) {
3023                 ret= pyrna_func_to_py(&self->ptr, func);
3024         }
3025         else if (self->ptr.type == &RNA_Context) {
3026                 bContext *C= self->ptr.data;
3027                 if(C==NULL) {
3028                         PyErr_Format(PyExc_AttributeError,
3029                                      "bpy_struct: Context is 'NULL', can't get \"%.200s\" from context",
3030                                      name);
3031                         ret= NULL;
3032                 }
3033                 else {
3034                         PointerRNA newptr;
3035                         ListBase newlb;
3036                         short newtype;
3037
3038                         int done= CTX_data_get(C, name, &newptr, &newlb, &newtype);
3039
3040                         if(done==1) { /* found */
3041                                 switch(newtype) {
3042                                 case CTX_DATA_TYPE_POINTER:
3043                                         if(newptr.data == NULL) {
3044                                                 ret= Py_None;
3045                                                 Py_INCREF(ret);
3046                                         }
3047                                         else {
3048                                                 ret= pyrna_struct_CreatePyObject(&newptr);
3049                                         }
3050                                         break;
3051                                 case CTX_DATA_TYPE_COLLECTION:
3052                                         {
3053                                                 CollectionPointerLink *link;
3054                                                 PyObject *linkptr;
3055
3056                                                 ret= PyList_New(0);
3057
3058                                                 for(link=newlb.first; link; link=link->next) {
3059                                                         linkptr= pyrna_struct_CreatePyObject(&link->ptr);
3060                                                         PyList_Append(ret, linkptr);
3061                                                         Py_DECREF(linkptr);
3062                                                 }
3063                                         }
3064                                         break;
3065                                 default:
3066                                         /* should never happen */
3067                                         BLI_assert(!"Invalid context type");
3068
3069                                         PyErr_Format(PyExc_AttributeError,
3070                                                      "bpy_struct: Context type invalid %d, can't get \"%.200s\" from context",
3071                                                      newtype, name);
3072                                         ret= NULL;
3073                                 }
3074                         }
3075                         else if (done==-1) { /* found but not set */
3076                                 ret= Py_None;
3077                                 Py_INCREF(ret);
3078                         }
3079                         else { /* not found in the context */
3080                                 /* lookup the subclass. raise an error if its not found */
3081                                 ret= PyObject_GenericGetAttr((PyObject *)self, pyname);
3082                         }
3083
3084                         BLI_freelistN(&newlb);
3085                 }
3086         }
3087         else {
3088 #if 0
3089                 PyErr_Format(PyExc_AttributeError,
3090                              "bpy_struct: attribute \"%.200s\" not found",
3091                              name);
3092                 ret= NULL;
3093 #endif
3094                 /* Include this incase this instance is a subtype of a python class
3095                  * In these instances we may want to return a function or variable provided by the subtype
3096                  *
3097                  * Also needed to return methods when its not a subtype
3098                  * */
3099
3100                 /* The error raised here will be displayed */
3101                 ret= PyObject_GenericGetAttr((PyObject *)self, pyname);
3102         }
3103
3104         return ret;
3105 }
3106
3107 #if 0
3108 static int pyrna_struct_pydict_contains(PyObject *self, PyObject *pyname)
3109 {
3110         PyObject *dict= *(_PyObject_GetDictPtr((PyObject *)self));
3111         if (dict==NULL) /* unlikely */
3112                 return 0;
3113
3114         return PyDict_Contains(dict, pyname);
3115 }
3116 #endif
3117
3118 //--------------- setattr-------------------------------------------
3119 static int pyrna_is_deferred_prop(PyObject *value)
3120 {
3121         return PyTuple_CheckExact(value) && PyTuple_GET_SIZE(value)==2 && PyCallable_Check(PyTuple_GET_ITEM(value, 0)) && PyDict_CheckExact(PyTuple_GET_ITEM(value, 1));
3122 }
3123
3124 #if 0
3125 static PyObject *pyrna_struct_meta_idprop_getattro(PyObject *cls, PyObject *attr)
3126 {
3127         PyObject *ret= PyType_Type.tp_getattro(cls, attr);
3128
3129         /* Allows:
3130          * >>> bpy.types.Scene.foo= BoolProperty()
3131          * >>> bpy.types.Scene.foo
3132          * <bpy_struct, BooleanProperty("foo")>
3133          * ...rather than returning the deferred class register tuple as checked by pyrna_is_deferred_prop()
3134          *
3135          * Disable for now, this is faking internal behavior in a way thats too tricky to maintain well. */
3136 #if 0
3137         if(ret == NULL) { // || pyrna_is_deferred_prop(ret)
3138                 StructRNA *srna= srna_from_self(cls, "StructRNA.__getattr__");
3139                 if(srna) {
3140                         PropertyRNA *prop= RNA_struct_type_find_property(srna, _PyUnicode_AsString(attr));
3141                         if(prop) {
3142                                 PointerRNA tptr;
3143                                 PyErr_Clear(); /* clear error from tp_getattro */
3144                                 RNA_pointer_create(NULL, &RNA_Property, prop, &tptr);
3145                                 ret= pyrna_struct_CreatePyObject(&tptr);
3146                         }
3147                 }
3148         }
3149 #endif
3150
3151         return ret;
3152 }
3153 #endif