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