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