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