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