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