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