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