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