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