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