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