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