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