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