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