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