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