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