2.50: svn merge https://svn.blender.org/svnroot/bf-blender/trunk/blender -r19323...
[blender.git] / source / blender / python / intern / bpy_rna.c
1 /**
2  * $Id$
3  *
4  * ***** BEGIN GPL LICENSE BLOCK *****
5  *
6  * This program is free software; you can redistribute it and/or
7  * modify it under the terms of the GNU General Public License
8  * as published by the Free Software Foundation; either version 2
9  * of the License, or (at your option) any later version.
10  *
11  * This program is distributed in the hope that it will be useful,
12  * but WITHOUT ANY WARRANTY; without even the implied warranty of
13  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
14  * GNU General Public License for more details.
15  *
16  * You should have received a copy of the GNU General Public License
17  * along with this program; if not, write to the Free Software Foundation,
18  * Inc., 59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.
19  *
20  * Contributor(s): Campbell Barton
21  *
22  * ***** END GPL LICENSE BLOCK *****
23  */
24
25 #include "bpy_rna.h"
26 #include "bpy_compat.h"
27 #include "bpy_util.h"
28 //#include "blendef.h"
29 #include "BLI_dynstr.h"
30 #include "BLI_listbase.h"
31 #include "BLI_string.h"
32 #include "float.h" /* FLT_MIN/MAX */
33
34 #include "RNA_access.h"
35 #include "RNA_define.h" /* for defining our own rna */
36
37 #include "MEM_guardedalloc.h"
38 #include "BKE_context.h"
39 #include "BKE_global.h" /* evil G.* */
40 #include "BKE_report.h"
41
42 static int pyrna_struct_compare( BPy_StructRNA * a, BPy_StructRNA * b )
43 {
44         return (a->ptr.data==b->ptr.data) ? 0 : -1;
45 }
46
47 static int pyrna_prop_compare( BPy_PropertyRNA * a, BPy_PropertyRNA * b )
48 {
49         return (a->prop==b->prop && a->ptr.data==b->ptr.data ) ? 0 : -1;
50 }
51
52 /* For some reason python3 needs these :/ */
53 static PyObject *pyrna_struct_richcmp(BPy_StructRNA * a, BPy_StructRNA * b, int op)
54 {
55         int cmp_result= -1; /* assume false */
56         if (BPy_StructRNA_Check(a) && BPy_StructRNA_Check(b)) {
57                 cmp_result= pyrna_struct_compare(a, b);
58         }
59
60         return Py_CmpToRich(op, cmp_result);
61 }
62
63 static PyObject *pyrna_prop_richcmp(BPy_PropertyRNA * a, BPy_PropertyRNA * b, int op)
64 {
65         int cmp_result= -1; /* assume false */
66         if (BPy_PropertyRNA_Check(a) && BPy_PropertyRNA_Check(b)) {
67                 cmp_result= pyrna_prop_compare(a, b);
68         }
69
70         return Py_CmpToRich(op, cmp_result);
71 }
72
73 /*----------------------repr--------------------------------------------*/
74 static PyObject *pyrna_struct_repr( BPy_StructRNA * self )
75 {
76         PropertyRNA *prop;
77         char str[512];
78
79         /* print name if available */
80         prop= RNA_struct_name_property(self->ptr.type);
81         if(prop) {
82                 RNA_property_string_get(&self->ptr, prop, str);
83                 return PyUnicode_FromFormat( "[BPy_StructRNA \"%s\" -> \"%s\"]", RNA_struct_identifier(self->ptr.type), str);
84         }
85
86         return PyUnicode_FromFormat( "[BPy_StructRNA \"%s\"]", RNA_struct_identifier(self->ptr.type));
87 }
88
89 static PyObject *pyrna_prop_repr( BPy_PropertyRNA * self )
90 {
91         PropertyRNA *prop;
92         PointerRNA ptr;
93         char str[512];
94
95         /* if a pointer, try to print name of pointer target too */
96         if(RNA_property_type(self->prop) == PROP_POINTER) {
97                 ptr= RNA_property_pointer_get(&self->ptr, self->prop);
98
99                 if(ptr.data) {
100                         prop= RNA_struct_name_property(ptr.type);
101                         if(prop) {
102                                 RNA_property_string_get(&ptr, prop, str);
103                                 return PyUnicode_FromFormat( "[BPy_PropertyRNA \"%s\" -> \"%s\" -> \"%s\" ]", RNA_struct_identifier(self->ptr.type), RNA_property_identifier(self->prop), str);
104                         }
105                 }
106         }
107
108         return PyUnicode_FromFormat( "[BPy_PropertyRNA \"%s\" -> \"%s\"]", RNA_struct_identifier(self->ptr.type), RNA_property_identifier(self->prop));
109 }
110
111 static long pyrna_struct_hash( BPy_StructRNA * self )
112 {
113         return (long)self->ptr.data;
114 }
115
116 /* use our own dealloc so we can free a property if we use one */
117 static void pyrna_struct_dealloc( BPy_StructRNA * self )
118 {
119         /* Note!! for some weired reason calling PyObject_DEL() directly crashes blender! */
120         if (self->freeptr && self->ptr.data) {
121                 IDP_FreeProperty(self->ptr.data);
122                 MEM_freeN(self->ptr.data);
123                 self->ptr.data= NULL;
124         }
125
126         Py_TYPE(self)->tp_free(self);
127         return;
128 }
129
130 static char *pyrna_enum_as_string(PointerRNA *ptr, PropertyRNA *prop)
131 {
132         const EnumPropertyItem *item;
133         int totitem;
134         
135         RNA_property_enum_items(ptr, prop, &item, &totitem);
136         return (char*)BPy_enum_as_string((EnumPropertyItem*)item);
137 }
138
139 PyObject * pyrna_prop_to_py(PointerRNA *ptr, PropertyRNA *prop)
140 {
141         PyObject *ret;
142         int type = RNA_property_type(prop);
143         int len = RNA_property_array_length(prop);
144
145         if (len > 0) {
146                 /* resolve the array from a new pytype */
147                 return pyrna_prop_CreatePyObject(ptr, prop);
148         }
149         
150         /* see if we can coorce into a python type - PropertyType */
151         switch (type) {
152         case PROP_BOOLEAN:
153                 ret = PyBool_FromLong( RNA_property_boolean_get(ptr, prop) );
154                 break;
155         case PROP_INT:
156                 ret = PyLong_FromSsize_t( (Py_ssize_t)RNA_property_int_get(ptr, prop) );
157                 break;
158         case PROP_FLOAT:
159                 ret = PyFloat_FromDouble( RNA_property_float_get(ptr, prop) );
160                 break;
161         case PROP_STRING:
162         {
163                 char *buf;
164                 buf = RNA_property_string_get_alloc(ptr, prop, NULL, -1);
165                 ret = PyUnicode_FromString( buf );
166                 MEM_freeN(buf);
167                 break;
168         }
169         case PROP_ENUM:
170         {
171                 const char *identifier;
172                 int val = RNA_property_enum_get(ptr, prop);
173                 
174                 if (RNA_property_enum_identifier(ptr, prop, val, &identifier)) {
175                         ret = PyUnicode_FromString( identifier );
176                 } else {
177                         PyErr_Format(PyExc_AttributeError, "RNA Error: Current value \"%d\" matches no enum", val);
178                         ret = NULL;
179                 }
180
181                 break;
182         }
183         case PROP_POINTER:
184         {
185                 PointerRNA newptr;
186                 newptr= RNA_property_pointer_get(ptr, prop);
187                 if (newptr.data) {
188                         ret = pyrna_struct_CreatePyObject(&newptr);
189                 } else {
190                         ret = Py_None;
191                         Py_INCREF(ret);
192                 }
193                 break;
194         }
195         case PROP_COLLECTION:
196                 ret = pyrna_prop_CreatePyObject(ptr, prop);
197                 break;
198         default:
199                 PyErr_Format(PyExc_AttributeError, "RNA Error: unknown type \"%d\" (pyrna_prop_to_py)", type);
200                 ret = NULL;
201                 break;
202         }
203         
204         return ret;
205 }
206
207 static PyObject * pyrna_func_call(PyObject * self, PyObject *args, PyObject *kw);
208
209 PyObject *pyrna_func_to_py(PointerRNA *ptr, FunctionRNA *func)
210 {
211         static PyMethodDef func_meth = {"<generic rna function>", (PyCFunction)pyrna_func_call, METH_VARARGS|METH_KEYWORDS, "python rna function"};
212         PyObject *self= PyTuple_New(2);
213         PyObject *ret;
214         PyTuple_SET_ITEM(self, 0, pyrna_struct_CreatePyObject(ptr));
215         PyTuple_SET_ITEM(self, 1, PyCObject_FromVoidPtr((void *)func, NULL));
216         
217         ret= PyCFunction_New(&func_meth, self);
218         Py_DECREF(self);
219         
220         return ret;
221 }
222
223
224 int pyrna_py_to_prop(PointerRNA *ptr, PropertyRNA *prop, void *data, PyObject *value)
225 {
226         /* XXX hard limits should be checked here */
227         int type = RNA_property_type(prop);
228         int len = RNA_property_array_length(prop);
229         
230         if (len > 0) {
231                 PyObject *item;
232                 int i;
233                 
234                 if (!PySequence_Check(value)) {
235                         PyErr_SetString(PyExc_TypeError, "expected a python sequence type assigned to an RNA array.");
236                         return -1;
237                 }
238                 
239                 if ((int)PySequence_Length(value) != len) {
240                         PyErr_SetString(PyExc_AttributeError, "python sequence length did not match the RNA array.");
241                         return -1;
242                 }
243                 
244                 /* for arrays we have a limited number of types */
245                 switch (type) {
246                 case PROP_BOOLEAN:
247                 {
248                         int *param_arr;
249                         if(data)        param_arr= (int*)data;
250                         else            param_arr= MEM_mallocN(sizeof(char) * len, "pyrna bool array");
251
252                         
253                         /* collect the variables before assigning, incase one of them is incorrect */
254                         for (i=0; i<len; i++) {
255                                 item = PySequence_GetItem(value, i);
256                                 param_arr[i] = PyObject_IsTrue( item );
257                                 Py_DECREF(item);
258                                 
259                                 if (param_arr[i] < 0) {
260                                         if(data==NULL)
261                                                 MEM_freeN(param_arr);
262                                         PyErr_SetString(PyExc_AttributeError, "one or more of the values in the sequence is not a boolean");
263                                         return -1;
264                                 }
265                         }
266                         if(data==NULL) {
267                                 RNA_property_boolean_set_array(ptr, prop, param_arr);
268                                 MEM_freeN(param_arr);
269                         }
270
271                         break;
272                 }
273                 case PROP_INT:
274                 {
275                         int *param_arr;
276                         if(data)        param_arr= (int*)data;
277                         else            param_arr= MEM_mallocN(sizeof(int) * len, "pyrna int array");
278
279                         
280                         /* collect the variables */
281                         for (i=0; i<len; i++) {
282                                 item = PySequence_GetItem(value, i);
283                                 param_arr[i] = (int)PyLong_AsSsize_t(item); /* deal with any errors later */
284                                 Py_DECREF(item);
285                         }
286                         
287                         if (PyErr_Occurred()) {
288                                 if(data==NULL)
289                                         MEM_freeN(param_arr);
290                                 PyErr_SetString(PyExc_AttributeError, "one or more of the values in the sequence could not be used as an int");
291                                 return -1;
292                         }
293                         if(data==NULL) {
294                                 RNA_property_int_set_array(ptr, prop, param_arr);
295                                 MEM_freeN(param_arr);
296                         }
297                         break;
298                 }
299                 case PROP_FLOAT:
300                 {
301                         float *param_arr;
302                         if(data)        param_arr = (float*)data;
303                         else            param_arr = MEM_mallocN(sizeof(float) * len, "pyrna float array");
304
305
306                         
307                         /* collect the variables */
308                         for (i=0; i<len; i++) {
309                                 item = PySequence_GetItem(value, i);
310                                 param_arr[i] = (float)PyFloat_AsDouble(item); /* deal with any errors later */
311                                 Py_DECREF(item);
312                         }
313                         
314                         if (PyErr_Occurred()) {
315                                 if(data==NULL)
316                                         MEM_freeN(param_arr);
317                                 PyErr_SetString(PyExc_AttributeError, "one or more of the values in the sequence could not be used as a float");
318                                 return -1;
319                         }
320                         if(data==NULL) {
321                                 RNA_property_float_set_array(ptr, prop, param_arr);                             
322                                 MEM_freeN(param_arr);
323                         }
324                         break;
325                 }
326                 }
327         } else {
328                 /* Normal Property (not an array) */
329                 
330                 /* see if we can coorce into a python type - PropertyType */
331                 switch (type) {
332                 case PROP_BOOLEAN:
333                 {
334                         int param = PyObject_IsTrue( value );
335                         
336                         if( param < 0 ) {
337                                 PyErr_SetString(PyExc_TypeError, "expected True/False or 0/1");
338                                 return -1;
339                         } else {
340                                 if(data)        *((int*)data)= param;
341                                 else            RNA_property_boolean_set(ptr, prop, param);
342                         }
343                         break;
344                 }
345                 case PROP_INT:
346                 {
347                         int param = PyLong_AsSsize_t(value);
348                         if (PyErr_Occurred()) {
349                                 PyErr_SetString(PyExc_TypeError, "expected an int type");
350                                 return -1;
351                         } else {
352                                 if(data)        *((int*)data)= param;
353                                 else            RNA_property_int_set(ptr, prop, param);
354                         }
355                         break;
356                 }
357                 case PROP_FLOAT:
358                 {
359                         float param = PyFloat_AsDouble(value);
360                         if (PyErr_Occurred()) {
361                                 PyErr_SetString(PyExc_TypeError, "expected a float type");
362                                 return -1;
363                         } else {
364                                 if(data)        *((float*)data)= param;
365                                 else            RNA_property_float_set(ptr, prop, param);
366                         }
367                         break;
368                 }
369                 case PROP_STRING:
370                 {
371                         char *param = _PyUnicode_AsString(value);
372                         
373                         if (param==NULL) {
374                                 PyErr_SetString(PyExc_TypeError, "expected a string type");
375                                 return -1;
376                         } else {
377                                 if(data)        *((char**)data)= param;
378                                 else            RNA_property_string_set(ptr, prop, param);
379                         }
380                         break;
381                 }
382                 case PROP_ENUM:
383                 {
384                         char *param = _PyUnicode_AsString(value);
385                         
386                         if (param==NULL) {
387                                 char *enum_str= pyrna_enum_as_string(ptr, prop);
388                                 PyErr_Format(PyExc_TypeError, "expected a string enum type in (%s)", enum_str);
389                                 MEM_freeN(enum_str);
390                                 return -1;
391                         } else {
392                                 int val;
393                                 if (RNA_property_enum_value(ptr, prop, param, &val)) {
394                                         if(data)        *((int*)data)= val;
395                                         else            RNA_property_enum_set(ptr, prop, val);
396                                 } else {
397                                         char *enum_str= pyrna_enum_as_string(ptr, prop);
398                                         PyErr_Format(PyExc_AttributeError, "enum \"%s\" not found in (%s)", param, enum_str);
399                                         MEM_freeN(enum_str);
400                                         return -1;
401                                 }
402                         }
403                         
404                         break;
405                 }
406                 case PROP_POINTER:
407                 {
408                         StructRNA *ptype= RNA_property_pointer_type(prop);
409
410                         if(!BPy_StructRNA_Check(value)) {
411                                 PointerRNA tmp;
412                                 RNA_pointer_create(NULL, ptype, NULL, &tmp);
413                                 PyErr_Format(PyExc_TypeError, "expected a %s type", RNA_struct_identifier(tmp.type));
414                                 return -1;
415                         } else {
416                                 BPy_StructRNA *param= (BPy_StructRNA*)value;
417                                 int raise_error= 0;
418                                 if(data) {
419                                         if(ptype == &RNA_AnyType) {
420                                                 *((PointerRNA*)data)= param->ptr;
421                                         }
422                                         else if(RNA_struct_is_a(param->ptr.type, ptype)) {
423                                                 *((void**)data)= param->ptr.data;
424                                         } else {
425                                                 raise_error= 1;
426                                         }
427                                 }
428                                 else {
429                                         /* data==NULL, assign to RNA */
430                                         if(RNA_struct_is_a(param->ptr.type, ptype)) {
431                                                 RNA_property_pointer_set(ptr, prop, param->ptr);
432                                         } else {
433                                                 PointerRNA tmp;
434                                                 RNA_pointer_create(NULL, ptype, NULL, &tmp);
435                                                 PyErr_Format(PyExc_TypeError, "expected a %s type", RNA_struct_identifier(tmp.type));
436                                                 return -1;
437                                         }
438                                 }
439                                 
440                                 if(raise_error) {
441                                         PointerRNA tmp;
442                                         RNA_pointer_create(NULL, ptype, NULL, &tmp);
443                                         PyErr_Format(PyExc_TypeError, "expected a %s type", RNA_struct_identifier(tmp.type));
444                                         return -1;
445                                 }
446                         }
447                         break;
448                 }
449                 case PROP_COLLECTION:
450                         PyErr_SetString(PyExc_AttributeError, "cant convert collections yet");
451                         return -1;
452                         break;
453                 default:
454                         PyErr_SetString(PyExc_AttributeError, "unknown property type (pyrna_py_to_prop)");
455                         return -1;
456                         break;
457                 }
458         }
459         
460         return 0;
461 }
462
463 static PyObject * pyrna_prop_to_py_index(PointerRNA *ptr, PropertyRNA *prop, int index)
464 {
465         PyObject *ret;
466         int type = RNA_property_type(prop);
467         
468         /* see if we can coorce into a python type - PropertyType */
469         switch (type) {
470         case PROP_BOOLEAN:
471                 ret = PyBool_FromLong( RNA_property_boolean_get_index(ptr, prop, index) );
472                 break;
473         case PROP_INT:
474                 ret = PyLong_FromSsize_t( (Py_ssize_t)RNA_property_int_get_index(ptr, prop, index) );
475                 break;
476         case PROP_FLOAT:
477                 ret = PyFloat_FromDouble( RNA_property_float_get_index(ptr, prop, index) );
478                 break;
479         default:
480                 PyErr_SetString(PyExc_AttributeError, "not an array type");
481                 ret = NULL;
482                 break;
483         }
484         
485         return ret;
486 }
487
488 static int pyrna_py_to_prop_index(PointerRNA *ptr, PropertyRNA *prop, int index, PyObject *value)
489 {
490         int ret = 0;
491         int type = RNA_property_type(prop);
492         
493         /* see if we can coorce into a python type - PropertyType */
494         switch (type) {
495         case PROP_BOOLEAN:
496         {
497                 int param = PyObject_IsTrue( value );
498                 
499                 if( param < 0 ) {
500                         PyErr_SetString(PyExc_TypeError, "expected True/False or 0/1");
501                         ret = -1;
502                 } else {
503                         RNA_property_boolean_set_index(ptr, prop, index, param);
504                 }
505                 break;
506         }
507         case PROP_INT:
508         {
509                 int param = PyLong_AsSsize_t(value);
510                 if (PyErr_Occurred()) {
511                         PyErr_SetString(PyExc_TypeError, "expected an int type");
512                         ret = -1;
513                 } else {
514                         RNA_property_int_set_index(ptr, prop, index, param);
515                 }
516                 break;
517         }
518         case PROP_FLOAT:
519         {
520                 float param = PyFloat_AsDouble(value);
521                 if (PyErr_Occurred()) {
522                         PyErr_SetString(PyExc_TypeError, "expected a float type");
523                         ret = -1;
524                 } else {
525                         RNA_property_float_set_index(ptr, prop, index, param);
526                 }
527                 break;
528         }
529         default:
530                 PyErr_SetString(PyExc_AttributeError, "not an array type");
531                 ret = -1;
532                 break;
533         }
534         
535         return ret;
536 }
537
538 //---------------sequence-------------------------------------------
539 static Py_ssize_t pyrna_prop_len( BPy_PropertyRNA * self )
540 {
541         Py_ssize_t len;
542         
543         if (RNA_property_type(self->prop) == PROP_COLLECTION) {
544                 len = RNA_property_collection_length(&self->ptr, self->prop);
545         } else {
546                 len = RNA_property_array_length(self->prop);
547                 
548                 if (len==0) { /* not an array*/
549                         PyErr_SetString(PyExc_AttributeError, "len() only available for collection RNA types");
550                         return -1;
551                 }
552         }
553         
554         return len;
555 }
556
557 static PyObject *pyrna_prop_subscript( BPy_PropertyRNA * self, PyObject *key )
558 {
559         PyObject *ret;
560         PointerRNA newptr;
561         int keynum = 0;
562         char *keyname = NULL;
563         
564         if (PyUnicode_Check(key)) {
565                 keyname = _PyUnicode_AsString(key);
566         } else if (PyLong_Check(key)) {
567                 keynum = PyLong_AsSsize_t(key);
568         } else {
569                 PyErr_SetString(PyExc_AttributeError, "invalid key, key must be a string or an int");
570                 return NULL;
571         }
572         
573         if (RNA_property_type(self->prop) == PROP_COLLECTION) {
574                 int ok;
575                 if (keyname)    ok = RNA_property_collection_lookup_string(&self->ptr, self->prop, keyname, &newptr);
576                 else                    ok = RNA_property_collection_lookup_int(&self->ptr, self->prop, keynum, &newptr);
577                 
578                 if (ok) {
579                         ret = pyrna_struct_CreatePyObject(&newptr);
580                 } else {
581                         PyErr_SetString(PyExc_AttributeError, "out of range");
582                         ret = NULL;
583                 }
584                 
585         } else if (keyname) {
586                 PyErr_SetString(PyExc_AttributeError, "string keys are only supported for collections");
587                 ret = NULL;
588         } else {
589                 int len = RNA_property_array_length(self->prop);
590                 
591                 if (len==0) { /* not an array*/
592                         PyErr_Format(PyExc_AttributeError, "not an array or collection %d", keynum);
593                         ret = NULL;
594                 }
595                 
596                 if (keynum >= len){
597                         PyErr_SetString(PyExc_AttributeError, "index out of range");
598                         ret = NULL;
599                 } else { /* not an array*/
600                         ret = pyrna_prop_to_py_index(&self->ptr, self->prop, keynum);
601                 }
602         }
603         
604         return ret;
605 }
606
607
608 static int pyrna_prop_assign_subscript( BPy_PropertyRNA * self, PyObject *key, PyObject *value )
609 {
610         int ret = 0;
611         int keynum = 0;
612         char *keyname = NULL;
613         
614         if (!RNA_property_editable(&self->ptr, self->prop)) {
615                 PyErr_Format( PyExc_AttributeError, "PropertyRNA - attribute \"%s\" from \"%s\" is read-only", RNA_property_identifier(self->prop), RNA_struct_identifier(self->ptr.type) );
616                 return -1;
617         }
618         
619         if (PyUnicode_Check(key)) {
620                 keyname = _PyUnicode_AsString(key);
621         } else if (PyLong_Check(key)) {
622                 keynum = PyLong_AsSsize_t(key);
623         } else {
624                 PyErr_SetString(PyExc_AttributeError, "PropertyRNA - invalid key, key must be a string or an int");
625                 return -1;
626         }
627         
628         if (RNA_property_type(self->prop) == PROP_COLLECTION) {
629                 PyErr_SetString(PyExc_AttributeError, "PropertyRNA - assignment is not supported for collections (yet)");
630                 ret = -1;
631         } else if (keyname) {
632                 PyErr_SetString(PyExc_AttributeError, "PropertyRNA - string keys are only supported for collections");
633                 ret = -1;
634         } else {
635                 int len = RNA_property_array_length(self->prop);
636                 
637                 if (len==0) { /* not an array*/
638                         PyErr_Format(PyExc_AttributeError, "PropertyRNA - not an array or collection %d", keynum);
639                         ret = -1;
640                 }
641                 
642                 if (keynum >= len){
643                         PyErr_SetString(PyExc_AttributeError, "PropertyRNA - index out of range");
644                         ret = -1;
645                 } else {
646                         ret = pyrna_py_to_prop_index(&self->ptr, self->prop, keynum, value);
647                 }
648         }
649         
650         return ret;
651 }
652
653
654
655 static PyMappingMethods pyrna_prop_as_mapping = {
656         ( lenfunc ) pyrna_prop_len,     /* mp_length */
657         ( binaryfunc ) pyrna_prop_subscript,    /* mp_subscript */
658         ( objobjargproc ) pyrna_prop_assign_subscript,  /* mp_ass_subscript */
659 };
660
661 static PyObject *pyrna_struct_dir(BPy_StructRNA * self)
662 {
663         PyObject *ret, *dict;
664         PyObject *pystring;
665         
666         /* for looping over attrs and funcs */
667         CollectionPropertyIterator iter;
668         PropertyRNA *iterprop;
669         
670         /* Include this incase this instance is a subtype of a python class
671          * In these instances we may want to return a function or variable provided by the subtype
672          * */
673
674         if (BPy_StructRNA_CheckExact(self)) {
675                 ret = PyList_New(0);
676         } else {
677                 pystring = PyUnicode_FromString("__dict__");
678                 dict = PyObject_GenericGetAttr((PyObject *)self, pystring);
679                 Py_DECREF(pystring);
680
681                 if (dict==NULL) {
682                         PyErr_Clear();
683                         ret = PyList_New(0);
684                 }
685                 else {
686                         ret = PyDict_Keys(dict);
687                         Py_DECREF(dict);
688                 }
689         }
690         
691         /* Collect RNA items*/
692         {
693                 /*
694                  * Collect RNA attributes
695                  */
696                 PropertyRNA *nameprop;
697                 char name[256], *nameptr;
698
699                 iterprop= RNA_struct_iterator_property(self->ptr.type);
700                 RNA_property_collection_begin(&self->ptr, iterprop, &iter);
701
702                 for(; iter.valid; RNA_property_collection_next(&iter)) {
703                         if(iter.ptr.data && (nameprop = RNA_struct_name_property(iter.ptr.type))) {
704                                 nameptr= RNA_property_string_get_alloc(&iter.ptr, nameprop, name, sizeof(name));
705                                 
706                                 pystring = PyUnicode_FromString(nameptr);
707                                 PyList_Append(ret, pystring);
708                                 Py_DECREF(pystring);
709                                 
710                                 if ((char *)&name != nameptr)
711                                         MEM_freeN(nameptr);
712                         }
713                 }
714                 RNA_property_collection_end(&iter);
715         
716         }
717         
718         
719         {
720                 /*
721                  * Collect RNA function items
722                  */
723                 PointerRNA tptr;
724
725                 RNA_pointer_create(NULL, &RNA_Struct, self->ptr.type, &tptr);
726                 iterprop= RNA_struct_find_property(&tptr, "functions");
727
728                 RNA_property_collection_begin(&tptr, iterprop, &iter);
729
730                 for(; iter.valid; RNA_property_collection_next(&iter)) {
731                         pystring = PyUnicode_FromString(RNA_function_identifier(iter.ptr.data));
732                         PyList_Append(ret, pystring);
733                         Py_DECREF(pystring);
734                 }
735
736                 RNA_property_collection_end(&iter);
737         }
738         
739         return ret;
740 }
741
742
743 //---------------getattr--------------------------------------------
744 static PyObject *pyrna_struct_getattro( BPy_StructRNA * self, PyObject *pyname )
745 {
746         char *name = _PyUnicode_AsString(pyname);
747         PyObject *ret;
748         PropertyRNA *prop;
749         FunctionRNA *func;
750         
751         /* Include this incase this instance is a subtype of a python class
752          * In these instances we may want to return a function or variable provided by the subtype
753          * 
754          * Also needed to return methods when its not a subtype
755          * */
756         ret = PyObject_GenericGetAttr((PyObject *)self, pyname);
757         if (ret)        return ret;
758         else            PyErr_Clear();
759         /* done with subtypes */
760         
761         if ((prop = RNA_struct_find_property(&self->ptr, name))) {
762                 ret = pyrna_prop_to_py(&self->ptr, prop);
763         }
764         else if ((func = RNA_struct_find_function(&self->ptr, name))) {
765                 ret = pyrna_func_to_py(&self->ptr, func);
766         }
767         else if (self->ptr.type == &RNA_Context) {
768                 PointerRNA newptr;
769                 ListBase newlb;
770
771                 CTX_data_get(self->ptr.data, name, &newptr, &newlb);
772
773         if (newptr.data) {
774             ret = pyrna_struct_CreatePyObject(&newptr);
775                 }
776                 else if (newlb.first) {
777                         CollectionPointerLink *link;
778                         PyObject *linkptr;
779
780                         ret = PyList_New(0);
781
782                         for(link=newlb.first; link; link=link->next) {
783                                 linkptr= pyrna_struct_CreatePyObject(&link->ptr);
784                                 PyList_Append(ret, linkptr);
785                                 Py_DECREF(linkptr);
786                         }
787                 }
788         else {
789             ret = Py_None;
790             Py_INCREF(ret);
791         }
792
793                 BLI_freelistN(&newlb);
794         }
795         else {
796                 PyErr_Format( PyExc_AttributeError, "StructRNA - Attribute \"%s\" not found", name);
797                 ret = NULL;
798         }
799         
800         return ret;
801 }
802
803 //--------------- setattr-------------------------------------------
804 static int pyrna_struct_setattro( BPy_StructRNA * self, PyObject *pyname, PyObject * value )
805 {
806         char *name = _PyUnicode_AsString(pyname);
807         PropertyRNA *prop = RNA_struct_find_property(&self->ptr, name);
808         
809         if (prop==NULL) {
810                 if (!BPy_StructRNA_CheckExact(self) && PyObject_GenericSetAttr((PyObject *)self, pyname, value) >= 0) {
811                         return 0;
812                 }
813                 else {
814                         PyErr_Format( PyExc_AttributeError, "StructRNA - Attribute \"%s\" not found", name);
815                         return -1;
816                 }
817         }               
818         
819         if (!RNA_property_editable(&self->ptr, prop)) {
820                 PyErr_Format( PyExc_AttributeError, "StructRNA - Attribute \"%s\" from \"%s\" is read-only", RNA_property_identifier(prop), RNA_struct_identifier(self->ptr.type) );
821                 return -1;
822         }
823                 
824         /* pyrna_py_to_prop sets its own exceptions */
825         return pyrna_py_to_prop(&self->ptr, prop, NULL, value);
826 }
827
828 PyObject *pyrna_prop_keys(BPy_PropertyRNA *self)
829 {
830         PyObject *ret;
831         if (RNA_property_type(self->prop) != PROP_COLLECTION) {
832                 PyErr_SetString( PyExc_TypeError, "keys() is only valid for collection types" );
833                 ret = NULL;
834         } else {
835                 PyObject *item;
836                 CollectionPropertyIterator iter;
837                 PropertyRNA *nameprop;
838                 char name[256], *nameptr;
839
840                 ret = PyList_New(0);
841                 
842                 RNA_property_collection_begin(&self->ptr, self->prop, &iter);
843                 for(; iter.valid; RNA_property_collection_next(&iter)) {
844                         if(iter.ptr.data && (nameprop = RNA_struct_name_property(iter.ptr.type))) {
845                                 nameptr= RNA_property_string_get_alloc(&iter.ptr, nameprop, name, sizeof(name));                                
846                                 
847                                 /* add to python list */
848                                 item = PyUnicode_FromString( nameptr );
849                                 PyList_Append(ret, item);
850                                 Py_DECREF(item);
851                                 /* done */
852                                 
853                                 if ((char *)&name != nameptr)
854                                         MEM_freeN(nameptr);
855                         }
856                 }
857                 RNA_property_collection_end(&iter);
858         }
859         
860         return ret;
861 }
862
863 PyObject *pyrna_prop_items(BPy_PropertyRNA *self)
864 {
865         PyObject *ret;
866         if (RNA_property_type(self->prop) != PROP_COLLECTION) {
867                 PyErr_SetString( PyExc_TypeError, "items() is only valid for collection types" );
868                 ret = NULL;
869         } else {
870                 PyObject *item;
871                 CollectionPropertyIterator iter;
872                 PropertyRNA *nameprop;
873                 char name[256], *nameptr;
874
875                 ret = PyList_New(0);
876                 
877                 RNA_property_collection_begin(&self->ptr, self->prop, &iter);
878                 for(; iter.valid; RNA_property_collection_next(&iter)) {
879                         if(iter.ptr.data && (nameprop = RNA_struct_name_property(iter.ptr.type))) {
880                                 nameptr= RNA_property_string_get_alloc(&iter.ptr, nameprop, name, sizeof(name));
881                                 
882                                 /* add to python list */
883                                 item = Py_BuildValue("(NN)", PyUnicode_FromString( nameptr ), pyrna_struct_CreatePyObject(&iter.ptr));
884                                 PyList_Append(ret, item);
885                                 Py_DECREF(item);
886                                 /* done */
887                                 
888                                 if ((char *)&name != nameptr)
889                                         MEM_freeN(nameptr);
890                         }
891                 }
892                 RNA_property_collection_end(&iter);
893         }
894         
895         return ret;
896 }
897
898
899 PyObject *pyrna_prop_values(BPy_PropertyRNA *self)
900 {
901         PyObject *ret;
902         if (RNA_property_type(self->prop) != PROP_COLLECTION) {
903                 PyErr_SetString( PyExc_TypeError, "values() is only valid for collection types" );
904                 ret = NULL;
905         } else {
906                 PyObject *item;
907                 CollectionPropertyIterator iter;
908                 PropertyRNA *nameprop;
909                 
910                 ret = PyList_New(0);
911                 
912                 RNA_property_collection_begin(&self->ptr, self->prop, &iter);
913                 for(; iter.valid; RNA_property_collection_next(&iter)) {
914                         if(iter.ptr.data && (nameprop = RNA_struct_name_property(iter.ptr.type))) {
915                                 item = pyrna_struct_CreatePyObject(&iter.ptr);
916                                 PyList_Append(ret, item);
917                                 Py_DECREF(item);
918                         }
919                 }
920                 RNA_property_collection_end(&iter);
921         }
922         
923         return ret;
924 }
925
926 /* A bit of a kludge, make a list out of a collection or array,
927  * then return the lists iter function, not especially fast but convenient for now */
928 PyObject *pyrna_prop_iter(BPy_PropertyRNA *self)
929 {
930         /* Try get values from a collection */
931         PyObject *ret = pyrna_prop_values(self);
932         
933         if (ret==NULL) {
934                 /* collection did not work, try array */
935                 int len = RNA_property_array_length(self->prop);
936                 
937                 if (len) {
938                         int i;
939                         PyErr_Clear();
940                         ret = PyList_New(len);
941                         
942                         for (i=0; i < len; i++) {
943                                 PyList_SET_ITEM(ret, i, pyrna_prop_to_py_index(&self->ptr, self->prop, i));
944                         }
945                 }
946         }
947         
948         if (ret) {
949                 /* we know this is a list so no need to PyIter_Check */
950                 PyObject *iter = PyObject_GetIter(ret); 
951                 Py_DECREF(ret);
952                 return iter;
953         }
954         
955         PyErr_SetString( PyExc_TypeError, "this BPy_PropertyRNA object is not iterable" );
956         return NULL;
957 }
958
959 static struct PyMethodDef pyrna_struct_methods[] = {
960         {"__dir__", (PyCFunction)pyrna_struct_dir, METH_NOARGS, ""},
961         {NULL, NULL, 0, NULL}
962 };
963
964 static struct PyMethodDef pyrna_prop_methods[] = {
965         {"keys", (PyCFunction)pyrna_prop_keys, METH_NOARGS, ""},
966         {"items", (PyCFunction)pyrna_prop_items, METH_NOARGS, ""},
967         {"values", (PyCFunction)pyrna_prop_values, METH_NOARGS, ""},
968         {NULL, NULL, 0, NULL}
969 };
970
971 /* only needed for subtyping, so a new class gets a valid BPy_StructRNA
972  * todo - also accept useful args */
973 static PyObject * pyrna_struct_new(PyTypeObject *type, PyObject *args, PyObject *kwds) {
974
975         BPy_StructRNA *base = NULL;
976         
977         if (!PyArg_ParseTuple(args, "O!:Base BPy_StructRNA", &pyrna_struct_Type, &base))
978                 return NULL;
979         
980         if (type == &pyrna_struct_Type) {
981                 return pyrna_struct_CreatePyObject(&base->ptr);
982         } else {
983                 BPy_StructRNA *ret = (BPy_StructRNA *) type->tp_alloc(type, 0);
984                 ret->ptr = base->ptr;
985                 return (PyObject *)ret;
986         }
987 }
988
989 /* only needed for subtyping, so a new class gets a valid BPy_StructRNA
990  * todo - also accept useful args */
991 static PyObject * pyrna_prop_new(PyTypeObject *type, PyObject *args, PyObject *kwds) {
992
993         BPy_PropertyRNA *base = NULL;
994         
995         if (!PyArg_ParseTuple(args, "O!:Base BPy_PropertyRNA", &pyrna_prop_Type, &base))
996                 return NULL;
997         
998         if (type == &pyrna_prop_Type) {
999                 return pyrna_prop_CreatePyObject(&base->ptr, base->prop);
1000         } else {
1001                 BPy_PropertyRNA *ret = (BPy_PropertyRNA *) type->tp_alloc(type, 0);
1002                 ret->ptr = base->ptr;
1003                 ret->prop = base->prop;
1004                 return (PyObject *)ret;
1005         }
1006 }
1007
1008 PyObject *pyrna_param_to_py(PointerRNA *ptr, PropertyRNA *prop, void *data)
1009 {
1010         PyObject *ret;
1011         int type = RNA_property_type(prop);
1012         int len = RNA_property_array_length(prop);
1013
1014         int a;
1015
1016         if(len > 0) {
1017                 /* resolve the array from a new pytype */
1018                 ret = PyTuple_New(len);
1019
1020                 switch (type) {
1021                 case PROP_BOOLEAN:
1022                         for(a=0; a<len; a++)
1023                                 PyTuple_SET_ITEM(ret, a, PyBool_FromLong( ((int*)data)[a] ));
1024                         break;
1025                 case PROP_INT:
1026                         for(a=0; a<len; a++)
1027                                 PyTuple_SET_ITEM(ret, a, PyLong_FromSsize_t( (Py_ssize_t)((int*)data)[a] ));
1028                         break;
1029                 case PROP_FLOAT:
1030                         for(a=0; a<len; a++)
1031                                 PyTuple_SET_ITEM(ret, a, PyFloat_FromDouble( ((float*)data)[a] ));
1032                         break;
1033                 default:
1034                         PyErr_Format(PyExc_AttributeError, "RNA Error: unknown array type \"%d\" (pyrna_param_to_py)", type);
1035                         ret = NULL;
1036                         break;
1037                 }
1038         }
1039         else {
1040                 /* see if we can coorce into a python type - PropertyType */
1041                 switch (type) {
1042                 case PROP_BOOLEAN:
1043                         ret = PyBool_FromLong( *(int*)data );
1044                         break;
1045                 case PROP_INT:
1046                         ret = PyLong_FromSsize_t( (Py_ssize_t)*(int*)data );
1047                         break;
1048                 case PROP_FLOAT:
1049                         ret = PyFloat_FromDouble( *(float*)data );
1050                         break;
1051                 case PROP_STRING:
1052                 {
1053                         ret = PyUnicode_FromString( *(char**)data );
1054                         break;
1055                 }
1056                 case PROP_ENUM:
1057                 {
1058                         const char *identifier;
1059                         int val = *(int*)data;
1060                         
1061                         if (RNA_property_enum_identifier(ptr, prop, val, &identifier)) {
1062                                 ret = PyUnicode_FromString( identifier );
1063                         } else {
1064                                 PyErr_Format(PyExc_AttributeError, "RNA Error: Current value \"%d\" matches no enum", val);
1065                                 ret = NULL;
1066                         }
1067
1068                         break;
1069                 }
1070                 case PROP_POINTER:
1071                 {
1072                         PointerRNA newptr;
1073                         StructRNA *type= RNA_property_pointer_type(prop);
1074
1075                         if(type == &RNA_AnyType) {
1076                                 /* in this case we get the full ptr */
1077                                 newptr= *(PointerRNA*)data;
1078                         }
1079                         else {
1080                                 /* XXX this is missing the ID part! */
1081                                 RNA_pointer_create(NULL, type, *(void**)data, &newptr);
1082                         }
1083
1084                         if (newptr.data) {
1085                                 ret = pyrna_struct_CreatePyObject(&newptr);
1086                         } else {
1087                                 ret = Py_None;
1088                                 Py_INCREF(ret);
1089                         }
1090                         break;
1091                 }
1092                 case PROP_COLLECTION:
1093                         /* XXX not supported yet
1094                          * ret = pyrna_prop_CreatePyObject(ptr, prop); */
1095                         break;
1096                 default:
1097                         PyErr_Format(PyExc_AttributeError, "RNA Error: unknown type \"%d\" (pyrna_param_to_py)", type);
1098                         ret = NULL;
1099                         break;
1100                 }
1101         }
1102
1103         return ret;
1104 }
1105
1106 static PyObject * pyrna_func_call(PyObject * self, PyObject *args, PyObject *kw)
1107 {
1108         PointerRNA *self_ptr= &(((BPy_StructRNA *)PyTuple_GET_ITEM(self, 0))->ptr);
1109         FunctionRNA *self_func=  PyCObject_AsVoidPtr(PyTuple_GET_ITEM(self, 1));
1110
1111         PointerRNA funcptr;
1112         ParameterList *parms;
1113         ParameterIterator iter;
1114         PropertyRNA *pret, *parm;
1115         PyObject *ret, *item;
1116         int i, tlen, flag, err= 0;
1117         const char *tid, *fid, *pid;
1118         void *retdata= NULL;
1119
1120         /* setup */
1121         RNA_pointer_create(NULL, &RNA_Function, self_func, &funcptr);
1122
1123         pret= RNA_function_return(self_func);
1124         tlen= PyTuple_GET_SIZE(args);
1125
1126         parms= RNA_parameter_list_create(self_ptr, self_func);
1127         RNA_parameter_list_begin(parms, &iter);
1128
1129         /* parse function parameters */
1130         for (i= 0; iter.valid; RNA_parameter_list_next(&iter)) {
1131                 parm= iter.parm;
1132
1133                 if (parm==pret) {
1134                         retdata= iter.data;
1135                         continue;
1136                 }
1137
1138                 pid= RNA_property_identifier(parm);
1139                 flag= RNA_property_flag(parm);
1140                 item= NULL;
1141
1142                 if ((i < tlen) && (flag & PROP_REQUIRED)) {
1143                         item= PyTuple_GET_ITEM(args, i);
1144                         i++;
1145                 }
1146                 else if (kw != NULL)
1147                         item= PyDict_GetItemString(kw, pid);
1148
1149                 if (item==NULL) {
1150                         if(flag & PROP_REQUIRED) {
1151                                 tid= RNA_struct_identifier(self_ptr->type);
1152                                 fid= RNA_function_identifier(self_func);
1153
1154                                 PyErr_Format(PyExc_AttributeError, "%s.%s(): required parameter \"%s\" not specified", tid, fid, pid);
1155                                 err= -1;
1156                                 break;
1157                         }
1158                         else
1159                                 continue;
1160                 }
1161
1162                 err= pyrna_py_to_prop(&funcptr, parm, iter.data, item);
1163
1164                 if(err!=0)
1165                         break;
1166         }
1167
1168         ret= NULL;
1169         if (err==0) {
1170                 /* call function */
1171                 RNA_function_call(self_ptr, self_func, parms);
1172
1173                 /* return value */
1174                 if(pret)
1175                         ret= pyrna_param_to_py(&funcptr, pret, retdata);
1176         }
1177
1178         /* cleanup */
1179         RNA_parameter_list_end(&iter);
1180         RNA_parameter_list_free(parms);
1181
1182         if (ret)
1183                 return ret;
1184
1185         if (err==-1)
1186                 return NULL;
1187
1188         Py_RETURN_NONE;
1189 }
1190
1191 /*-----------------------BPy_StructRNA method def------------------------------*/
1192 PyTypeObject pyrna_struct_Type = {
1193 #if (PY_VERSION_HEX >= 0x02060000)
1194         PyVarObject_HEAD_INIT(NULL, 0)
1195 #else
1196         /* python 2.5 and below */
1197         PyObject_HEAD_INIT( NULL )  /* required py macro */
1198         0,                          /* ob_size */
1199 #endif
1200         "StructRNA",                    /* tp_name */
1201         sizeof( BPy_StructRNA ),        /* tp_basicsize */
1202         0,                      /* tp_itemsize */
1203         /* methods */
1204         ( destructor ) pyrna_struct_dealloc,/* tp_dealloc */
1205         NULL,                       /* printfunc tp_print; */
1206         NULL,                                           /* getattrfunc tp_getattr; */
1207         NULL,                                           /* setattrfunc tp_setattr; */
1208         NULL,                                           /* tp_compare */ /* DEPRECATED in python 3.0! */
1209         ( reprfunc ) pyrna_struct_repr, /* tp_repr */
1210
1211         /* Method suites for standard classes */
1212
1213         NULL,                       /* PyNumberMethods *tp_as_number; */
1214         NULL,                                           /* PySequenceMethods *tp_as_sequence; */
1215         NULL,                                           /* PyMappingMethods *tp_as_mapping; */
1216
1217         /* More standard operations (here for binary compatibility) */
1218
1219         ( hashfunc )pyrna_struct_hash,  /* hashfunc tp_hash; */
1220         NULL,                                           /* ternaryfunc tp_call; */
1221         NULL,                       /* reprfunc tp_str; */
1222         ( getattrofunc ) pyrna_struct_getattro, /* getattrofunc tp_getattro; */
1223         ( setattrofunc ) pyrna_struct_setattro, /* setattrofunc tp_setattro; */
1224
1225         /* Functions to access object as input/output buffer */
1226         NULL,                       /* PyBufferProcs *tp_as_buffer; */
1227
1228   /*** Flags to define presence of optional/expanded features ***/
1229         Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE,         /* long tp_flags; */
1230
1231         NULL,                                           /*  char *tp_doc;  Documentation string */
1232   /*** Assigned meaning in release 2.0 ***/
1233         /* call function for all accessible objects */
1234         NULL,                       /* traverseproc tp_traverse; */
1235
1236         /* delete references to contained objects */
1237         NULL,                       /* inquiry tp_clear; */
1238
1239   /***  Assigned meaning in release 2.1 ***/
1240   /*** rich comparisons ***/
1241         (richcmpfunc)pyrna_struct_richcmp,      /* richcmpfunc tp_richcompare; */
1242
1243   /***  weak reference enabler ***/
1244         0,                          /* long tp_weaklistoffset; */
1245
1246   /*** Added in release 2.2 ***/
1247         /*   Iterators */
1248         NULL,                       /* getiterfunc tp_iter; */
1249         NULL,                       /* iternextfunc tp_iternext; */
1250
1251   /*** Attribute descriptor and subclassing stuff ***/
1252         pyrna_struct_methods,                   /* struct PyMethodDef *tp_methods; */
1253         NULL,                       /* struct PyMemberDef *tp_members; */
1254         NULL,                                           /* struct PyGetSetDef *tp_getset; */
1255         NULL,                       /* struct _typeobject *tp_base; */
1256         NULL,                       /* PyObject *tp_dict; */
1257         NULL,                       /* descrgetfunc tp_descr_get; */
1258         NULL,                       /* descrsetfunc tp_descr_set; */
1259         0,                          /* long tp_dictoffset; */
1260         NULL,                       /* initproc tp_init; */
1261         NULL,                       /* allocfunc tp_alloc; */
1262         pyrna_struct_new,                       /* newfunc tp_new; */
1263         /*  Low-level free-memory routine */
1264         NULL,                       /* freefunc tp_free;  */
1265         /* For PyObject_IS_GC */
1266         NULL,                       /* inquiry tp_is_gc;  */
1267         NULL,                       /* PyObject *tp_bases; */
1268         /* method resolution order */
1269         NULL,                       /* PyObject *tp_mro;  */
1270         NULL,                       /* PyObject *tp_cache; */
1271         NULL,                       /* PyObject *tp_subclasses; */
1272         NULL,                       /* PyObject *tp_weaklist; */
1273         NULL
1274 };
1275
1276 /*-----------------------BPy_PropertyRNA method def------------------------------*/
1277 PyTypeObject pyrna_prop_Type = {
1278 #if (PY_VERSION_HEX >= 0x02060000)
1279         PyVarObject_HEAD_INIT(NULL, 0)
1280 #else
1281         /* python 2.5 and below */
1282         PyObject_HEAD_INIT( NULL )  /* required py macro */
1283         0,                          /* ob_size */
1284 #endif
1285         
1286         "PropertyRNA",          /* tp_name */
1287         sizeof( BPy_PropertyRNA ),                      /* tp_basicsize */
1288         0,                      /* tp_itemsize */
1289         /* methods */
1290         NULL,                                           /* tp_dealloc */
1291         NULL,                       /* printfunc tp_print; */
1292         NULL,                                           /* getattrfunc tp_getattr; */
1293         NULL,                       /* setattrfunc tp_setattr; */
1294         NULL,                                           /* tp_compare */ /* DEPRECATED in python 3.0! */
1295         ( reprfunc ) pyrna_prop_repr,   /* tp_repr */
1296
1297         /* Method suites for standard classes */
1298
1299         NULL,                       /* PyNumberMethods *tp_as_number; */
1300         NULL,                                           /* PySequenceMethods *tp_as_sequence; */
1301         &pyrna_prop_as_mapping,         /* PyMappingMethods *tp_as_mapping; */
1302
1303         /* More standard operations (here for binary compatibility) */
1304
1305         NULL,                                           /* hashfunc tp_hash; */
1306         NULL,                       /* ternaryfunc tp_call; */
1307         NULL,                       /* reprfunc tp_str; */
1308         NULL, /*PyObject_GenericGetAttr - MINGW Complains, assign later */      /* getattrofunc tp_getattro; */ /* will only use these if this is a subtype of a py class */
1309         NULL, /*PyObject_GenericSetAttr - MINGW Complains, assign later */      /* setattrofunc tp_setattro; */
1310
1311         /* Functions to access object as input/output buffer */
1312         NULL,                       /* PyBufferProcs *tp_as_buffer; */
1313
1314   /*** Flags to define presence of optional/expanded features ***/
1315         Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE,         /* long tp_flags; */
1316
1317         NULL,                                           /*  char *tp_doc;  Documentation string */
1318   /*** Assigned meaning in release 2.0 ***/
1319         /* call function for all accessible objects */
1320         NULL,                       /* traverseproc tp_traverse; */
1321
1322         /* delete references to contained objects */
1323         NULL,                       /* inquiry tp_clear; */
1324
1325   /***  Assigned meaning in release 2.1 ***/
1326   /*** rich comparisons ***/
1327         (richcmpfunc)pyrna_prop_richcmp,        /* richcmpfunc tp_richcompare; */
1328
1329   /***  weak reference enabler ***/
1330         0,                          /* long tp_weaklistoffset; */
1331
1332   /*** Added in release 2.2 ***/
1333         /*   Iterators */
1334         (getiterfunc)pyrna_prop_iter,   /* getiterfunc tp_iter; */
1335         NULL,                       /* iternextfunc tp_iternext; */
1336
1337   /*** Attribute descriptor and subclassing stuff ***/
1338         pyrna_prop_methods,                     /* struct PyMethodDef *tp_methods; */
1339         NULL,                       /* struct PyMemberDef *tp_members; */
1340         NULL,                                           /* struct PyGetSetDef *tp_getset; */
1341         NULL,                       /* struct _typeobject *tp_base; */
1342         NULL,                       /* PyObject *tp_dict; */
1343         NULL,                       /* descrgetfunc tp_descr_get; */
1344         NULL,                       /* descrsetfunc tp_descr_set; */
1345         0,                          /* long tp_dictoffset; */
1346         NULL,                       /* initproc tp_init; */
1347         NULL,                       /* allocfunc tp_alloc; */
1348         pyrna_prop_new,                         /* newfunc tp_new; */
1349         /*  Low-level free-memory routine */
1350         NULL,                       /* freefunc tp_free;  */
1351         /* For PyObject_IS_GC */
1352         NULL,                       /* inquiry tp_is_gc;  */
1353         NULL,                       /* PyObject *tp_bases; */
1354         /* method resolution order */
1355         NULL,                       /* PyObject *tp_mro;  */
1356         NULL,                       /* PyObject *tp_cache; */
1357         NULL,                       /* PyObject *tp_subclasses; */
1358         NULL,                       /* PyObject *tp_weaklist; */
1359         NULL
1360 };
1361
1362 static void pyrna_subtype_set_rna(PyObject *newclass, StructRNA *srna)
1363 {
1364         PointerRNA ptr;
1365         PyObject *item;
1366
1367         RNA_struct_py_type_set(srna, (void *)newclass); /* Store for later use */
1368
1369         /* Not 100% needed but useful,
1370          * having an instance within a type looks wrong however this instance IS an rna type */
1371         RNA_pointer_create(NULL, &RNA_Struct, srna, &ptr);
1372         item = pyrna_struct_CreatePyObject(&ptr);
1373         PyDict_SetItemString(((PyTypeObject *)newclass)->tp_dict, "__rna__", item);
1374         Py_DECREF(item);
1375         /* done with rna instance */
1376 }
1377
1378 PyObject* pyrna_struct_Subtype(PointerRNA *ptr)
1379 {
1380         PyObject *newclass = NULL;
1381         PropertyRNA *nameprop;
1382
1383         if (ptr->type==NULL) {
1384                 newclass= NULL; /* Nothing to do */
1385         } else if ((newclass= RNA_struct_py_type_get(ptr->data))) {
1386                 Py_INCREF(newclass);
1387         } else if ((nameprop = RNA_struct_name_property(ptr->type))) {
1388                 /* for now, return the base RNA type rather then a real module */
1389                 
1390                 /* Assume RNA_struct_py_type_get(ptr->data) was alredy checked */
1391                 
1392                 /* subclass equivelents
1393                 - class myClass(myBase):
1394                         some='value' # or ...
1395                 - myClass = type(name='myClass', bases=(myBase,), dict={'some':'value'})
1396                 */
1397                 char name[256], *nameptr;
1398                 const char *descr= RNA_struct_ui_description(ptr->type);
1399
1400                 PyObject *args = PyTuple_New(3);
1401                 PyObject *bases = PyTuple_New(1);
1402                 PyObject *dict = PyDict_New();
1403                 PyObject *item;
1404                 
1405                 
1406                 nameptr= RNA_property_string_get_alloc(ptr, nameprop, name, sizeof(name));
1407                 
1408                 // arg 1
1409                 //PyTuple_SET_ITEM(args, 0, PyUnicode_FromString(tp_name));
1410                 PyTuple_SET_ITEM(args, 0, PyUnicode_FromString(nameptr));
1411                 
1412                 // arg 2
1413                 PyTuple_SET_ITEM(bases, 0, (PyObject *)&pyrna_struct_Type);
1414                 Py_INCREF(&pyrna_struct_Type);
1415
1416                 PyTuple_SET_ITEM(args, 1, bases);
1417                 
1418                 // arg 3 - add an instance of the rna 
1419                 if(descr) {
1420                         item= PyUnicode_FromString(descr);
1421                         PyDict_SetItemString(dict, "__doc__", item);
1422                         Py_DECREF(item);
1423                 }
1424                 
1425                 PyTuple_SET_ITEM(args, 2, dict); // fill with useful subclass things!
1426                 
1427                 if (PyErr_Occurred()) {
1428                         PyErr_Print();
1429                         PyErr_Clear();
1430                 }
1431                 
1432                 newclass = PyObject_CallObject((PyObject *)&PyType_Type, args);
1433                 Py_DECREF(args);
1434
1435                 if (newclass)
1436                         pyrna_subtype_set_rna(newclass, ptr->data);
1437                 
1438                 if (name != nameptr)
1439                         MEM_freeN(nameptr);
1440         }
1441         
1442         return newclass;
1443 }
1444
1445 /*-----------------------CreatePyObject---------------------------------*/
1446 PyObject *pyrna_struct_CreatePyObject( PointerRNA *ptr )
1447 {
1448         BPy_StructRNA *pyrna= NULL;
1449         
1450         if (ptr->data==NULL && ptr->type==NULL) { /* Operator RNA has NULL data */
1451                 Py_RETURN_NONE;
1452         }
1453         
1454         if (ptr->type == &RNA_Struct) { /* always return a python subtype from rna struct types */
1455                 PyTypeObject *tp = (PyTypeObject *)pyrna_struct_Subtype(ptr);
1456                 
1457                 if (tp) {
1458                         pyrna = (BPy_StructRNA *) tp->tp_alloc(tp, 0);
1459                 }
1460                 else {
1461                         fprintf(stderr, "Could not make type\n");
1462                         pyrna = ( BPy_StructRNA * ) PyObject_NEW( BPy_StructRNA, &pyrna_struct_Type );
1463                 }
1464         }
1465         else {
1466                 pyrna = ( BPy_StructRNA * ) PyObject_NEW( BPy_StructRNA, &pyrna_struct_Type );
1467         }
1468         
1469         if( !pyrna ) {
1470                 PyErr_SetString( PyExc_MemoryError, "couldn't create BPy_StructRNA object" );
1471                 return NULL;
1472         }
1473         
1474         pyrna->ptr= *ptr;
1475         pyrna->freeptr= 0;
1476         return ( PyObject * ) pyrna;
1477 }
1478
1479 PyObject *pyrna_prop_CreatePyObject( PointerRNA *ptr, PropertyRNA *prop )
1480 {
1481         BPy_PropertyRNA *pyrna;
1482
1483         pyrna = ( BPy_PropertyRNA * ) PyObject_NEW( BPy_PropertyRNA, &pyrna_prop_Type );
1484
1485         if( !pyrna ) {
1486                 PyErr_SetString( PyExc_MemoryError, "couldn't create BPy_rna object" );
1487                 return NULL;
1488         }
1489         
1490         pyrna->ptr = *ptr;
1491         pyrna->prop = prop;
1492                 
1493         return ( PyObject * ) pyrna;
1494 }
1495
1496 PyObject *BPY_rna_module( void )
1497 {
1498         PointerRNA ptr;
1499         
1500         /* This can't be set in the pytype struct because some compilers complain */
1501         pyrna_prop_Type.tp_getattro = PyObject_GenericGetAttr; 
1502         pyrna_prop_Type.tp_setattro = PyObject_GenericSetAttr; 
1503         
1504         if( PyType_Ready( &pyrna_struct_Type ) < 0 )
1505                 return NULL;
1506         
1507         if( PyType_Ready( &pyrna_prop_Type ) < 0 )
1508                 return NULL;
1509
1510         /* for now, return the base RNA type rather then a real module */
1511         RNA_main_pointer_create(G.main, &ptr);
1512         
1513         return pyrna_struct_CreatePyObject(&ptr);
1514 }
1515
1516 #if 0
1517 /* This is a way we can access docstrings for RNA types
1518  * without having the datatypes in blender */
1519 PyObject *BPY_rna_doc( void )
1520 {
1521         PointerRNA ptr;
1522         
1523         /* for now, return the base RNA type rather then a real module */
1524         RNA_blender_rna_pointer_create(&ptr);
1525         
1526         return pyrna_struct_CreatePyObject(&ptr);
1527 }
1528 #endif
1529
1530
1531 /* pyrna_basetype_* - BPy_BaseTypeRNA is just a BPy_PropertyRNA struct with a differnt type
1532  * the self->ptr and self->prop are always set to the "structs" collection */
1533 //---------------getattr--------------------------------------------
1534 static PyObject *pyrna_basetype_getattro( BPy_BaseTypeRNA * self, PyObject *pyname )
1535 {
1536         PointerRNA newptr;
1537         PyObject *ret;
1538         
1539         ret = PyObject_GenericGetAttr((PyObject *)self, pyname);
1540         if (ret)        return ret;
1541         else            PyErr_Clear();
1542         
1543         if (RNA_property_collection_lookup_string(&self->ptr, self->prop, _PyUnicode_AsString(pyname), &newptr)) {
1544                 ret= pyrna_struct_Subtype(&newptr);
1545                 if (ret==NULL) {
1546                         PyErr_Format(PyExc_SystemError, "bpy.types.%s subtype could not be generated, this is a bug!", _PyUnicode_AsString(pyname));
1547                 }
1548                 return ret;
1549         }
1550         else { /* Override the error */
1551                 PyErr_Format(PyExc_AttributeError, "bpy.types.%s not a valid RNA_Struct", _PyUnicode_AsString(pyname));
1552                 return NULL;
1553         }
1554 }
1555
1556 static PyObject *pyrna_basetype_dir(BPy_BaseTypeRNA *self);
1557 static struct PyMethodDef pyrna_basetype_methods[] = {
1558         {"__dir__", (PyCFunction)pyrna_basetype_dir, METH_NOARGS, ""},
1559         {"register", (PyCFunction)pyrna_basetype_register, METH_VARARGS, ""},
1560         {"unregister", (PyCFunction)pyrna_basetype_unregister, METH_VARARGS, ""},
1561         {NULL, NULL, 0, NULL}
1562 };
1563
1564 static PyObject *pyrna_basetype_dir(BPy_BaseTypeRNA *self)
1565 {
1566         PyObject *list, *name;
1567         PyMethodDef *meth;
1568         
1569         list= pyrna_prop_keys(self); /* like calling structs.keys(), avoids looping here */
1570
1571         for(meth=pyrna_basetype_methods; meth->ml_name; meth++) {
1572                 name = PyUnicode_FromString(meth->ml_name);
1573                 PyList_Append(list, name);
1574                 Py_DECREF(name);
1575         }
1576         
1577         return list;
1578 }
1579
1580 PyTypeObject pyrna_basetype_Type = BLANK_PYTHON_TYPE;
1581
1582 PyObject *BPY_rna_types(void)
1583 {
1584         BPy_BaseTypeRNA *self;
1585
1586         if ((pyrna_basetype_Type.tp_flags & Py_TPFLAGS_READY)==0)  {
1587                 pyrna_basetype_Type.tp_name = "RNA_Types";
1588                 pyrna_basetype_Type.tp_basicsize = sizeof( BPy_BaseTypeRNA );
1589                 pyrna_basetype_Type.tp_getattro = ( getattrofunc )pyrna_basetype_getattro;
1590                 pyrna_basetype_Type.tp_flags = Py_TPFLAGS_DEFAULT;
1591                 pyrna_basetype_Type.tp_methods = pyrna_basetype_methods;
1592                 
1593                 if( PyType_Ready( &pyrna_basetype_Type ) < 0 )
1594                         return NULL;
1595         }
1596         
1597         self= (BPy_BaseTypeRNA *)PyObject_NEW( BPy_BaseTypeRNA, &pyrna_basetype_Type );
1598         
1599         /* avoid doing this lookup for every getattr */
1600         RNA_blender_rna_pointer_create(&self->ptr);
1601         self->prop = RNA_struct_find_property(&self->ptr, "structs");
1602         
1603         return (PyObject *)self;
1604 }
1605
1606
1607
1608 /* Orphan functions, not sure where they should go */
1609
1610 /* Function that sets RNA, NOTE - self is NULL when called from python, but being abused from C so we can pass the srna allong
1611  * This isnt incorrect since its a python object - but be careful */
1612 PyObject *BPy_FloatProperty(PyObject *self, PyObject *args, PyObject *kw)
1613 {
1614         static char *kwlist[] = {"attr", "name", "description", "min", "max", "soft_min", "soft_max", "default", NULL};
1615         char *id, *name="", *description="";
1616         float min=FLT_MIN, max=FLT_MAX, soft_min=FLT_MIN, soft_max=FLT_MAX, def=0.0f;
1617         
1618         if (!PyArg_ParseTupleAndKeywords(args, kw, "s|ssfffff:FloatProperty", kwlist, &id, &name, &description, &min, &max, &soft_min, &soft_max, &def))
1619                 return NULL;
1620         
1621         if (PyTuple_Size(args) > 0) {
1622                 PyErr_SetString(PyExc_ValueError, "all args must be keywors"); // TODO - py3 can enforce this.
1623                 return NULL;
1624         }
1625         
1626         if (self) {
1627                 StructRNA *srna = PyCObject_AsVoidPtr(self);
1628                 RNA_def_float(srna, id, def, min, max, name, description, soft_min, soft_max);
1629                 Py_RETURN_NONE;
1630         } else {
1631                 PyObject *ret = PyTuple_New(2);
1632                 PyTuple_SET_ITEM(ret, 0, PyCObject_FromVoidPtr((void *)BPy_FloatProperty, NULL));
1633                 PyTuple_SET_ITEM(ret, 1, kw);
1634                 Py_INCREF(kw);
1635                 return ret;
1636         }
1637 }
1638
1639 PyObject *BPy_IntProperty(PyObject *self, PyObject *args, PyObject *kw)
1640 {
1641         static char *kwlist[] = {"attr", "name", "description", "min", "max", "soft_min", "soft_max", "default", NULL};
1642         char *id, *name="", *description="";
1643         int min=INT_MIN, max=INT_MAX, soft_min=INT_MIN, soft_max=INT_MAX, def=0;
1644         
1645         if (!PyArg_ParseTupleAndKeywords(args, kw, "s|ssiiiii:IntProperty", kwlist, &id, &name, &description, &min, &max, &soft_min, &soft_max, &def))
1646                 return NULL;
1647         
1648         if (PyTuple_Size(args) > 0) {
1649                 PyErr_SetString(PyExc_ValueError, "all args must be keywors"); // TODO - py3 can enforce this.
1650                 return NULL;
1651         }
1652         
1653         if (self) {
1654                 StructRNA *srna = PyCObject_AsVoidPtr(self);
1655                 RNA_def_int(srna, id, def, min, max, name, description, soft_min, soft_max);
1656                 Py_RETURN_NONE;
1657         } else {
1658                 PyObject *ret = PyTuple_New(2);
1659                 PyTuple_SET_ITEM(ret, 0, PyCObject_FromVoidPtr((void *)BPy_IntProperty, NULL));
1660                 PyTuple_SET_ITEM(ret, 1, kw);
1661                 Py_INCREF(kw);
1662                 return ret;
1663         }
1664 }
1665
1666 PyObject *BPy_BoolProperty(PyObject *self, PyObject *args, PyObject *kw)
1667 {
1668         static char *kwlist[] = {"attr", "name", "description", "default", NULL};
1669         char *id, *name="", *description="";
1670         int def=0;
1671         
1672         if (!PyArg_ParseTupleAndKeywords(args, kw, "s|ssi:IntProperty", kwlist, &id, &name, &description, &def))
1673                 return NULL;
1674         
1675         if (PyTuple_Size(args) > 0) {
1676                 PyErr_SetString(PyExc_ValueError, "all args must be keywors"); // TODO - py3 can enforce this.
1677                 return NULL;
1678         }
1679         
1680         if (self) {
1681                 StructRNA *srna = PyCObject_AsVoidPtr(self);
1682                 RNA_def_boolean(srna, id, def, name, description);
1683                 Py_RETURN_NONE;
1684         } else {
1685                 PyObject *ret = PyTuple_New(2);
1686                 PyTuple_SET_ITEM(ret, 0, PyCObject_FromVoidPtr((void *)BPy_IntProperty, NULL));
1687                 PyTuple_SET_ITEM(ret, 1, kw);
1688                 Py_INCREF(kw);
1689                 return ret;
1690         }
1691 }
1692
1693 /*-------------------- Type Registration ------------------------*/
1694
1695 static int rna_function_arg_count(FunctionRNA *func)
1696 {
1697         const ListBase *lb= RNA_function_defined_parameters(func);
1698         PropertyRNA *parm;
1699         Link *link;
1700         int count= 1;
1701
1702         for(link=lb->first; link; link=link->next) {
1703                 parm= (PropertyRNA*)link;
1704                 if(!(RNA_property_flag(parm) & PROP_RETURN))
1705                         count++;
1706         }
1707         
1708         return count;
1709 }
1710
1711 static int bpy_class_validate(PointerRNA *dummyptr, void *py_data, int *have_function)
1712 {
1713         const ListBase *lb;
1714         Link *link;
1715         FunctionRNA *func;
1716         PropertyRNA *prop;
1717         StructRNA *srna= dummyptr->type;
1718         const char *class_type= RNA_struct_identifier(srna);
1719         PyObject *py_class= (PyObject*)py_data;
1720         PyObject *base_class= RNA_struct_py_type_get(srna);
1721         PyObject *item, *fitem;
1722         PyObject *py_arg_count;
1723         int i, flag, arg_count, func_arg_count;
1724         char identifier[128];
1725
1726         if (base_class) {
1727                 if (!PyObject_IsSubclass(py_class, base_class)) {
1728                         PyObject *name= PyObject_GetAttrString(base_class, "__name__");
1729                         PyErr_Format( PyExc_AttributeError, "expected %s subclass of class \"%s\"", class_type, name ? _PyUnicode_AsString(name):"<UNKNOWN>");
1730                         Py_XDECREF(name);
1731                         return -1;
1732                 }
1733         }
1734
1735         /* verify callback functions */
1736         lb= RNA_struct_defined_functions(srna);
1737         i= 0;
1738         for(link=lb->first; link; link=link->next) {
1739                 func= (FunctionRNA*)link;
1740                 flag= RNA_function_flag(func);
1741
1742                 if(!(flag & FUNC_REGISTER))
1743                         continue;
1744
1745                 item = PyObject_GetAttrString(py_class, RNA_function_identifier(func));
1746
1747                 have_function[i]= (item != NULL);
1748                 i++;
1749
1750                 if (item==NULL) {
1751                         if ((flag & FUNC_REGISTER_OPTIONAL)==0) {
1752                                 PyErr_Format( PyExc_AttributeError, "expected %s class to have an \"%s\" attribute", class_type, RNA_function_identifier(func));
1753                                 return -1;
1754                         }
1755
1756                         PyErr_Clear();
1757                 }
1758                 else {
1759                         Py_DECREF(item); /* no need to keep a ref, the class owns it */
1760
1761                         if (PyMethod_Check(item))
1762                                 fitem= PyMethod_Function(item); /* py 2.x */
1763                         else
1764                                 fitem= item; /* py 3.x */
1765
1766                         if (PyFunction_Check(fitem)==0) {
1767                                 PyErr_Format( PyExc_AttributeError, "expected %s class \"%s\" attribute to be a function", class_type, RNA_function_identifier(func));
1768                                 return -1;
1769                         }
1770
1771                         func_arg_count= rna_function_arg_count(func);
1772
1773                         if (func_arg_count >= 0) { /* -1 if we dont care*/
1774                                 py_arg_count = PyObject_GetAttrString(PyFunction_GET_CODE(fitem), "co_argcount");
1775                                 arg_count = PyLong_AsSsize_t(py_arg_count);
1776                                 Py_DECREF(py_arg_count);
1777
1778                                 if (arg_count != func_arg_count) {
1779                                         PyErr_Format( PyExc_AttributeError, "expected %s class \"%s\" function to have %d args", class_type, RNA_function_identifier(func), func_arg_count);
1780                                         return -1;
1781                                 }
1782                         }
1783                 }
1784         }
1785
1786         /* verify properties */
1787         lb= RNA_struct_defined_properties(srna);
1788         for(link=lb->first; link; link=link->next) {
1789                 prop= (PropertyRNA*)link;
1790                 flag= RNA_property_flag(prop);
1791
1792                 if(!(flag & PROP_REGISTER))
1793                         continue;
1794
1795                 BLI_snprintf(identifier, sizeof(identifier), "__%s__", RNA_property_identifier(prop));
1796                 item = PyObject_GetAttrString(py_class, identifier);
1797
1798                 if (item==NULL) {
1799                         if(strcmp(identifier, "__idname__") == 0) {
1800                                 item= PyObject_GetAttrString(py_class, "__name__");
1801
1802                                 if(item) {
1803                                         Py_DECREF(item); /* no need to keep a ref, the class owns it */
1804
1805                                         if(pyrna_py_to_prop(dummyptr, prop, NULL, item) != 0)
1806                                                 return -1;
1807                                 }
1808                         }
1809
1810                         if (item==NULL && (flag & PROP_REGISTER_OPTIONAL)==0) {
1811                                 PyErr_Format( PyExc_AttributeError, "expected %s class to have an \"%s\" attribute", class_type, identifier);
1812                                 return -1;
1813                         }
1814
1815                         PyErr_Clear();
1816                 }
1817                 else {
1818                         Py_DECREF(item); /* no need to keep a ref, the class owns it */
1819
1820                         if(pyrna_py_to_prop(dummyptr, prop, NULL, item) != 0)
1821                                 return -1;
1822                 }
1823         }
1824
1825         return 0;
1826 }
1827
1828 extern void BPY_update_modules( void ); //XXX temp solution
1829
1830 static int bpy_class_call(PointerRNA *ptr, FunctionRNA *func, ParameterList *parms)
1831 {
1832         PyObject *args;
1833         PyObject *ret= NULL, *py_class, *py_class_instance, *item, *parmitem;
1834         PropertyRNA *pret= NULL, *parm;
1835         ParameterIterator iter;
1836         PointerRNA funcptr;
1837         void *retdata= NULL;
1838         int err= 0, i, flag;
1839
1840         PyGILState_STATE gilstate = PyGILState_Ensure();
1841
1842         BPY_update_modules(); // XXX - the RNA pointers can change so update before running, would like a nicer solution for this.
1843
1844         py_class= RNA_struct_py_type_get(ptr->type);
1845         
1846         args = PyTuple_New(1);
1847         PyTuple_SET_ITEM(args, 0, pyrna_struct_CreatePyObject(ptr));
1848         py_class_instance = PyObject_Call(py_class, args, NULL);
1849         Py_DECREF(args);
1850
1851         if (py_class_instance) { /* Initializing the class worked, now run its invoke function */
1852                 item= PyObject_GetAttrString(py_class, RNA_function_identifier(func));
1853                 flag= RNA_function_flag(func);
1854
1855                 if(item) {
1856                         pret= RNA_function_return(func);
1857                         RNA_pointer_create(NULL, &RNA_Function, func, &funcptr);
1858
1859                         args = PyTuple_New(rna_function_arg_count(func));
1860                         PyTuple_SET_ITEM(args, 0, py_class_instance);
1861
1862                         RNA_parameter_list_begin(parms, &iter);
1863
1864                         /* parse function parameters */
1865                         for (i= 1; iter.valid; RNA_parameter_list_next(&iter)) {
1866                                 parm= iter.parm;
1867
1868                                 if (parm==pret) {
1869                                         retdata= iter.data;
1870                                         continue;
1871                                 }
1872
1873                                 parmitem= pyrna_param_to_py(&funcptr, parm, iter.data);
1874                                 PyTuple_SET_ITEM(args, i, parmitem);
1875                                 i++;
1876                         }
1877
1878                         ret = PyObject_Call(item, args, NULL);
1879
1880                         /* args is decref'd from item */
1881                         Py_DECREF(item);
1882                 }
1883                 else {
1884                         Py_DECREF(py_class_instance);
1885                         PyErr_Format(PyExc_AttributeError, "could not find function %s in %s to execute callback.", RNA_function_identifier(func), RNA_struct_identifier(ptr->type));
1886                         err= -1;
1887                 }
1888         }
1889         else {
1890                 PyErr_Format(PyExc_AttributeError, "could not create instance of %s to call callback function %s.", RNA_struct_identifier(ptr->type), RNA_function_identifier(func));
1891                 err= -1;
1892         }
1893
1894         if (ret == NULL) { /* covers py_class_instance failing too */
1895                 PyErr_Print(); /* XXX use reporting api? */
1896                 err= -1;
1897         }
1898         else {
1899                 if(retdata)
1900                         err= pyrna_py_to_prop(&funcptr, pret, retdata, ret);
1901                 Py_DECREF(ret);
1902         }
1903
1904         PyGILState_Release(gilstate);
1905         
1906         return err;
1907 }
1908
1909 static void bpy_class_free(void *pyob_ptr)
1910 {
1911         Py_DECREF((PyObject *)pyob_ptr);
1912 }
1913
1914 PyObject *pyrna_basetype_register(PyObject *self, PyObject *args)
1915 {
1916         bContext *C= NULL;
1917         PyObject *py_class, *item;
1918         ReportList reports;
1919         StructRegisterFunc reg;
1920         BPy_StructRNA *py_srna;
1921         StructRNA *srna;
1922
1923         if(!PyArg_ParseTuple(args, "O:register", &py_class))
1924                 return NULL;
1925         
1926         if(!PyType_Check(py_class)) {
1927                 PyErr_SetString(PyExc_AttributeError, "expected a Type subclassed from a registerable rna type (no a Type object).");
1928                 return NULL;
1929         }
1930
1931         /* check we got an __rna__ attribute */
1932         item= PyObject_GetAttrString(py_class, "__rna__");
1933
1934         if(!item || !BPy_StructRNA_Check(item)) {
1935                 if(item) {
1936                         Py_DECREF(item);
1937                 }
1938                 PyErr_SetString(PyExc_AttributeError, "expected a Type subclassed from a registerable rna type (no __rna__ property).");
1939                 return NULL;
1940         }
1941
1942         /* check the __rna__ attribute has the right type */
1943         Py_DECREF(item);
1944         py_srna= (BPy_StructRNA*)item;
1945
1946         if(py_srna->ptr.type != &RNA_Struct) {
1947                 PyErr_SetString(PyExc_AttributeError, "expected a Type subclassed from a registerable rna type (not a Struct).");
1948                 return NULL;
1949         }
1950         
1951         /* check that we have a register callback for this type */
1952         reg= RNA_struct_register(py_srna->ptr.data);
1953
1954         if(!reg) {
1955                 PyErr_SetString(PyExc_AttributeError, "expected a Type subclassed from a registerable rna type (no register supported).");
1956                 return NULL;
1957         }
1958         
1959         /* get the context, so register callback can do necessary refreshes */
1960         item= PyDict_GetItemString(PyEval_GetGlobals(), "__bpy_context__");
1961
1962         if(item) {
1963                 C= (bContext*)PyCObject_AsVoidPtr(item);
1964                 Py_DECREF(item);
1965         }
1966
1967         /* call the register callback */
1968         BKE_reports_init(&reports, RPT_PRINT);
1969         srna= reg(C, &reports, py_class, bpy_class_validate, bpy_class_call, bpy_class_free);
1970
1971         if(!srna) {
1972                 BPy_reports_to_error(&reports);
1973                 BKE_reports_clear(&reports);
1974                 return NULL;
1975         }
1976
1977         BKE_reports_clear(&reports);
1978
1979         pyrna_subtype_set_rna(py_class, srna);
1980         Py_INCREF(py_class);
1981
1982         Py_RETURN_NONE;
1983 }
1984
1985 PyObject *pyrna_basetype_unregister(PyObject *self, PyObject *args)
1986 {
1987         bContext *C= NULL;
1988         PyObject *py_class, *item;
1989         BPy_StructRNA *py_srna;
1990         StructUnregisterFunc unreg;
1991
1992         if(!PyArg_ParseTuple(args, "O:register", &py_class))
1993                 return NULL;
1994
1995         if(!PyType_Check(py_class)) {
1996                 PyErr_SetString(PyExc_AttributeError, "expected a Type subclassed from a registerable rna type (no a Type object).");
1997                 return NULL;
1998         }
1999
2000         /* check we got an __rna__ attribute */
2001         item= PyDict_GetItemString(((PyTypeObject*)py_class)->tp_dict, "__rna__");
2002
2003         if(!item || !BPy_StructRNA_Check(item)) {
2004                 if(item) {
2005                         Py_DECREF(item);
2006                 }
2007                 PyErr_SetString(PyExc_AttributeError, "expected a Type subclassed from a registerable rna type (no __rna__ property).");
2008                 return NULL;
2009         }
2010
2011         /* check the __rna__ attribute has the right type */
2012         Py_DECREF(item);
2013         py_srna= (BPy_StructRNA*)item;
2014
2015         if(py_srna->ptr.type != &RNA_Struct) {
2016                 PyErr_SetString(PyExc_AttributeError, "expected a Type subclassed from a registerable rna type (not a Struct).");
2017                 return NULL;
2018         }
2019         
2020         /* check that we have a unregister callback for this type */
2021         unreg= RNA_struct_unregister(py_srna->ptr.data);
2022
2023         if(!unreg) {
2024                 PyErr_SetString(PyExc_AttributeError, "expected a Type subclassed from a registerable rna type (no unregister supported).");
2025                 return NULL;
2026         }
2027         
2028         /* get the context, so register callback can do necessary refreshes */
2029         item= PyDict_GetItemString(PyEval_GetGlobals(), "__bpy_context__");
2030
2031         if(item) {
2032                 C= (bContext*)PyCObject_AsVoidPtr(item);
2033                 Py_DECREF(item);
2034         }
2035
2036         /* call unregister */
2037         unreg(C, py_srna->ptr.data);
2038
2039         /* remove reference to old type */
2040         Py_DECREF(py_class);
2041
2042         Py_RETURN_NONE;
2043 }
2044