ObColor wasnt converted into an RNA string.
[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_TypeError, "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_TypeError, "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                 ReportList reports;
1314                 bContext *C= BPy_GetContext();
1315
1316                 BKE_reports_init(&reports, RPT_STORE);
1317                 RNA_function_call(C, &reports, self_ptr, self_func, parms);
1318
1319                 err= (BPy_reports_to_error(&reports))? -1: 0;
1320                 BKE_reports_clear(&reports);
1321
1322                 /* return value */
1323                 if(err==0)
1324                         if(pret)
1325                                 ret= pyrna_param_to_py(&funcptr, pret, retdata);
1326         }
1327
1328         /* cleanup */
1329         RNA_parameter_list_end(&iter);
1330         RNA_parameter_list_free(parms);
1331
1332         if (ret)
1333                 return ret;
1334
1335         if (err==-1)
1336                 return NULL;
1337
1338         Py_RETURN_NONE;
1339 }
1340
1341 /*-----------------------BPy_StructRNA method def------------------------------*/
1342 PyTypeObject pyrna_struct_Type = {
1343 #if (PY_VERSION_HEX >= 0x02060000)
1344         PyVarObject_HEAD_INIT(NULL, 0)
1345 #else
1346         /* python 2.5 and below */
1347         PyObject_HEAD_INIT( NULL )  /* required py macro */
1348         0,                          /* ob_size */
1349 #endif
1350         "StructRNA",                    /* tp_name */
1351         sizeof( BPy_StructRNA ),        /* tp_basicsize */
1352         0,                      /* tp_itemsize */
1353         /* methods */
1354         ( destructor ) pyrna_struct_dealloc,/* tp_dealloc */
1355         NULL,                       /* printfunc tp_print; */
1356         NULL,                                           /* getattrfunc tp_getattr; */
1357         NULL,                                           /* setattrfunc tp_setattr; */
1358         NULL,                                           /* tp_compare */ /* DEPRECATED in python 3.0! */
1359         ( reprfunc ) pyrna_struct_repr, /* tp_repr */
1360
1361         /* Method suites for standard classes */
1362
1363         NULL,                       /* PyNumberMethods *tp_as_number; */
1364         NULL,                                           /* PySequenceMethods *tp_as_sequence; */
1365         NULL,                                           /* PyMappingMethods *tp_as_mapping; */
1366
1367         /* More standard operations (here for binary compatibility) */
1368
1369         ( hashfunc )pyrna_struct_hash,  /* hashfunc tp_hash; */
1370         NULL,                                           /* ternaryfunc tp_call; */
1371         NULL,                       /* reprfunc tp_str; */
1372         ( getattrofunc ) pyrna_struct_getattro, /* getattrofunc tp_getattro; */
1373         ( setattrofunc ) pyrna_struct_setattro, /* setattrofunc tp_setattro; */
1374
1375         /* Functions to access object as input/output buffer */
1376         NULL,                       /* PyBufferProcs *tp_as_buffer; */
1377
1378   /*** Flags to define presence of optional/expanded features ***/
1379         Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE,         /* long tp_flags; */
1380
1381         NULL,                                           /*  char *tp_doc;  Documentation string */
1382   /*** Assigned meaning in release 2.0 ***/
1383         /* call function for all accessible objects */
1384         NULL,                       /* traverseproc tp_traverse; */
1385
1386         /* delete references to contained objects */
1387         NULL,                       /* inquiry tp_clear; */
1388
1389   /***  Assigned meaning in release 2.1 ***/
1390   /*** rich comparisons ***/
1391         (richcmpfunc)pyrna_struct_richcmp,      /* richcmpfunc tp_richcompare; */
1392
1393   /***  weak reference enabler ***/
1394         0,                          /* long tp_weaklistoffset; */
1395
1396   /*** Added in release 2.2 ***/
1397         /*   Iterators */
1398         NULL,                       /* getiterfunc tp_iter; */
1399         NULL,                       /* iternextfunc tp_iternext; */
1400
1401   /*** Attribute descriptor and subclassing stuff ***/
1402         pyrna_struct_methods,                   /* struct PyMethodDef *tp_methods; */
1403         NULL,                       /* struct PyMemberDef *tp_members; */
1404         NULL,                                           /* struct PyGetSetDef *tp_getset; */
1405         NULL,                       /* struct _typeobject *tp_base; */
1406         NULL,                       /* PyObject *tp_dict; */
1407         NULL,                       /* descrgetfunc tp_descr_get; */
1408         NULL,                       /* descrsetfunc tp_descr_set; */
1409         0,                          /* long tp_dictoffset; */
1410         NULL,                       /* initproc tp_init; */
1411         NULL,                       /* allocfunc tp_alloc; */
1412         pyrna_struct_new,                       /* newfunc tp_new; */
1413         /*  Low-level free-memory routine */
1414         NULL,                       /* freefunc tp_free;  */
1415         /* For PyObject_IS_GC */
1416         NULL,                       /* inquiry tp_is_gc;  */
1417         NULL,                       /* PyObject *tp_bases; */
1418         /* method resolution order */
1419         NULL,                       /* PyObject *tp_mro;  */
1420         NULL,                       /* PyObject *tp_cache; */
1421         NULL,                       /* PyObject *tp_subclasses; */
1422         NULL,                       /* PyObject *tp_weaklist; */
1423         NULL
1424 };
1425
1426 /*-----------------------BPy_PropertyRNA method def------------------------------*/
1427 PyTypeObject pyrna_prop_Type = {
1428 #if (PY_VERSION_HEX >= 0x02060000)
1429         PyVarObject_HEAD_INIT(NULL, 0)
1430 #else
1431         /* python 2.5 and below */
1432         PyObject_HEAD_INIT( NULL )  /* required py macro */
1433         0,                          /* ob_size */
1434 #endif
1435         
1436         "PropertyRNA",          /* tp_name */
1437         sizeof( BPy_PropertyRNA ),                      /* tp_basicsize */
1438         0,                      /* tp_itemsize */
1439         /* methods */
1440         NULL,                                           /* tp_dealloc */
1441         NULL,                       /* printfunc tp_print; */
1442         NULL,                                           /* getattrfunc tp_getattr; */
1443         NULL,                       /* setattrfunc tp_setattr; */
1444         NULL,                                           /* tp_compare */ /* DEPRECATED in python 3.0! */
1445         ( reprfunc ) pyrna_prop_repr,   /* tp_repr */
1446
1447         /* Method suites for standard classes */
1448
1449         NULL,                       /* PyNumberMethods *tp_as_number; */
1450         &pyrna_prop_as_sequence,        /* PySequenceMethods *tp_as_sequence; */
1451         &pyrna_prop_as_mapping,         /* PyMappingMethods *tp_as_mapping; */
1452
1453         /* More standard operations (here for binary compatibility) */
1454
1455         NULL,                                           /* hashfunc tp_hash; */
1456         NULL,                       /* ternaryfunc tp_call; */
1457         NULL,                       /* reprfunc tp_str; */
1458         NULL, /*PyObject_GenericGetAttr - MINGW Complains, assign later */      /* getattrofunc tp_getattro; */ /* will only use these if this is a subtype of a py class */
1459         NULL, /*PyObject_GenericSetAttr - MINGW Complains, assign later */      /* setattrofunc tp_setattro; */
1460
1461         /* Functions to access object as input/output buffer */
1462         NULL,                       /* PyBufferProcs *tp_as_buffer; */
1463
1464   /*** Flags to define presence of optional/expanded features ***/
1465         Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE,         /* long tp_flags; */
1466
1467         NULL,                                           /*  char *tp_doc;  Documentation string */
1468   /*** Assigned meaning in release 2.0 ***/
1469         /* call function for all accessible objects */
1470         NULL,                       /* traverseproc tp_traverse; */
1471
1472         /* delete references to contained objects */
1473         NULL,                       /* inquiry tp_clear; */
1474
1475   /***  Assigned meaning in release 2.1 ***/
1476   /*** rich comparisons ***/
1477         (richcmpfunc)pyrna_prop_richcmp,        /* richcmpfunc tp_richcompare; */
1478
1479   /***  weak reference enabler ***/
1480         0,                          /* long tp_weaklistoffset; */
1481
1482   /*** Added in release 2.2 ***/
1483         /*   Iterators */
1484         (getiterfunc)pyrna_prop_iter,   /* getiterfunc tp_iter; */
1485         NULL,                       /* iternextfunc tp_iternext; */
1486
1487   /*** Attribute descriptor and subclassing stuff ***/
1488         pyrna_prop_methods,                     /* struct PyMethodDef *tp_methods; */
1489         NULL,                       /* struct PyMemberDef *tp_members; */
1490         NULL,                                           /* struct PyGetSetDef *tp_getset; */
1491         NULL,                       /* struct _typeobject *tp_base; */
1492         NULL,                       /* PyObject *tp_dict; */
1493         NULL,                       /* descrgetfunc tp_descr_get; */
1494         NULL,                       /* descrsetfunc tp_descr_set; */
1495         0,                          /* long tp_dictoffset; */
1496         NULL,                       /* initproc tp_init; */
1497         NULL,                       /* allocfunc tp_alloc; */
1498         pyrna_prop_new,                         /* newfunc tp_new; */
1499         /*  Low-level free-memory routine */
1500         NULL,                       /* freefunc tp_free;  */
1501         /* For PyObject_IS_GC */
1502         NULL,                       /* inquiry tp_is_gc;  */
1503         NULL,                       /* PyObject *tp_bases; */
1504         /* method resolution order */
1505         NULL,                       /* PyObject *tp_mro;  */
1506         NULL,                       /* PyObject *tp_cache; */
1507         NULL,                       /* PyObject *tp_subclasses; */
1508         NULL,                       /* PyObject *tp_weaklist; */
1509         NULL
1510 };
1511
1512 static void pyrna_subtype_set_rna(PyObject *newclass, StructRNA *srna)
1513 {
1514         PointerRNA ptr;
1515         PyObject *item;
1516         
1517         Py_INCREF(newclass);
1518         
1519         if (RNA_struct_py_type_get(srna))
1520                 PyObSpit("RNA WAS SET - ", RNA_struct_py_type_get(srna));
1521         
1522         Py_XDECREF(((PyObject *)RNA_struct_py_type_get(srna)));
1523         
1524         RNA_struct_py_type_set(srna, (void *)newclass); /* Store for later use */
1525
1526         /* Not 100% needed but useful,
1527          * having an instance within a type looks wrong however this instance IS an rna type */
1528         RNA_pointer_create(NULL, &RNA_Struct, srna, &ptr);
1529         item = pyrna_struct_CreatePyObject(&ptr);
1530         PyDict_SetItemString(((PyTypeObject *)newclass)->tp_dict, "__rna__", item);
1531         Py_DECREF(item);
1532         /* done with rna instance */
1533 }
1534
1535 PyObject* pyrna_struct_Subtype(PointerRNA *ptr)
1536 {
1537         PyObject *newclass = NULL;
1538         PropertyRNA *nameprop;
1539
1540         if (ptr->type==NULL) {
1541                 newclass= NULL; /* Nothing to do */
1542         } else if ((newclass= RNA_struct_py_type_get(ptr->data))) {
1543                 Py_INCREF(newclass);
1544         } else if ((nameprop = RNA_struct_name_property(ptr->type))) {
1545                 /* for now, return the base RNA type rather then a real module */
1546                 
1547                 /* Assume RNA_struct_py_type_get(ptr->data) was alredy checked */
1548                 
1549                 /* subclass equivelents
1550                 - class myClass(myBase):
1551                         some='value' # or ...
1552                 - myClass = type(name='myClass', bases=(myBase,), dict={'some':'value'})
1553                 */
1554                 char name[256], *nameptr;
1555                 const char *descr= RNA_struct_ui_description(ptr->type);
1556
1557                 PyObject *args = PyTuple_New(3);
1558                 PyObject *bases = PyTuple_New(1);
1559                 PyObject *dict = PyDict_New();
1560                 PyObject *item;
1561                 
1562                 
1563                 nameptr= RNA_property_string_get_alloc(ptr, nameprop, name, sizeof(name));
1564                 
1565                 // arg 1
1566                 //PyTuple_SET_ITEM(args, 0, PyUnicode_FromString(tp_name));
1567                 PyTuple_SET_ITEM(args, 0, PyUnicode_FromString(nameptr));
1568                 
1569                 // arg 2
1570                 PyTuple_SET_ITEM(bases, 0, (PyObject *)&pyrna_struct_Type);
1571                 Py_INCREF(&pyrna_struct_Type);
1572
1573                 PyTuple_SET_ITEM(args, 1, bases);
1574                 
1575                 // arg 3 - add an instance of the rna 
1576                 if(descr) {
1577                         item= PyUnicode_FromString(descr);
1578                         PyDict_SetItemString(dict, "__doc__", item);
1579                         Py_DECREF(item);
1580                 }
1581                 
1582                 PyTuple_SET_ITEM(args, 2, dict); // fill with useful subclass things!
1583                 
1584                 if (PyErr_Occurred()) {
1585                         PyErr_Print();
1586                         PyErr_Clear();
1587                 }
1588                 
1589                 newclass = PyObject_CallObject((PyObject *)&PyType_Type, args);
1590                 Py_DECREF(args);
1591
1592                 if (newclass)
1593                         pyrna_subtype_set_rna(newclass, ptr->data);
1594                 
1595                 if (name != nameptr)
1596                         MEM_freeN(nameptr);
1597         }
1598         
1599         return newclass;
1600 }
1601
1602 /*-----------------------CreatePyObject---------------------------------*/
1603 PyObject *pyrna_struct_CreatePyObject( PointerRNA *ptr )
1604 {
1605         BPy_StructRNA *pyrna= NULL;
1606         
1607         if (ptr->data==NULL && ptr->type==NULL) { /* Operator RNA has NULL data */
1608                 Py_RETURN_NONE;
1609         }
1610         
1611         if (ptr->type == &RNA_Struct) { /* always return a python subtype from rna struct types */
1612                 PyTypeObject *tp = (PyTypeObject *)pyrna_struct_Subtype(ptr);
1613                 
1614                 if (tp) {
1615                         pyrna = (BPy_StructRNA *) tp->tp_alloc(tp, 0);
1616                 }
1617                 else {
1618                         fprintf(stderr, "Could not make type\n");
1619                         pyrna = ( BPy_StructRNA * ) PyObject_NEW( BPy_StructRNA, &pyrna_struct_Type );
1620                 }
1621         }
1622         else {
1623                 pyrna = ( BPy_StructRNA * ) PyObject_NEW( BPy_StructRNA, &pyrna_struct_Type );
1624         }
1625         
1626         if( !pyrna ) {
1627                 PyErr_SetString( PyExc_MemoryError, "couldn't create BPy_StructRNA object" );
1628                 return NULL;
1629         }
1630         
1631         pyrna->ptr= *ptr;
1632         pyrna->freeptr= 0;
1633         return ( PyObject * ) pyrna;
1634 }
1635
1636 PyObject *pyrna_prop_CreatePyObject( PointerRNA *ptr, PropertyRNA *prop )
1637 {
1638         BPy_PropertyRNA *pyrna;
1639
1640         pyrna = ( BPy_PropertyRNA * ) PyObject_NEW( BPy_PropertyRNA, &pyrna_prop_Type );
1641
1642         if( !pyrna ) {
1643                 PyErr_SetString( PyExc_MemoryError, "couldn't create BPy_rna object" );
1644                 return NULL;
1645         }
1646         
1647         pyrna->ptr = *ptr;
1648         pyrna->prop = prop;
1649                 
1650         return ( PyObject * ) pyrna;
1651 }
1652
1653 PyObject *BPY_rna_module( void )
1654 {
1655         PointerRNA ptr;
1656         
1657         /* This can't be set in the pytype struct because some compilers complain */
1658         pyrna_prop_Type.tp_getattro = PyObject_GenericGetAttr; 
1659         pyrna_prop_Type.tp_setattro = PyObject_GenericSetAttr; 
1660         
1661         if( PyType_Ready( &pyrna_struct_Type ) < 0 )
1662                 return NULL;
1663         
1664         if( PyType_Ready( &pyrna_prop_Type ) < 0 )
1665                 return NULL;
1666
1667         /* for now, return the base RNA type rather then a real module */
1668         RNA_main_pointer_create(G.main, &ptr);
1669         
1670         return pyrna_struct_CreatePyObject(&ptr);
1671 }
1672
1673 #if 0
1674 /* This is a way we can access docstrings for RNA types
1675  * without having the datatypes in blender */
1676 PyObject *BPY_rna_doc( void )
1677 {
1678         PointerRNA ptr;
1679         
1680         /* for now, return the base RNA type rather then a real module */
1681         RNA_blender_rna_pointer_create(&ptr);
1682         
1683         return pyrna_struct_CreatePyObject(&ptr);
1684 }
1685 #endif
1686
1687
1688 /* pyrna_basetype_* - BPy_BaseTypeRNA is just a BPy_PropertyRNA struct with a differnt type
1689  * the self->ptr and self->prop are always set to the "structs" collection */
1690 //---------------getattr--------------------------------------------
1691 static PyObject *pyrna_basetype_getattro( BPy_BaseTypeRNA * self, PyObject *pyname )
1692 {
1693         PointerRNA newptr;
1694         PyObject *ret;
1695         
1696         ret = PyObject_GenericGetAttr((PyObject *)self, pyname);
1697         if (ret)        return ret;
1698         else            PyErr_Clear();
1699         
1700         if (RNA_property_collection_lookup_string(&self->ptr, self->prop, _PyUnicode_AsString(pyname), &newptr)) {
1701                 ret= pyrna_struct_Subtype(&newptr);
1702                 if (ret==NULL) {
1703                         PyErr_Format(PyExc_SystemError, "bpy.types.%s subtype could not be generated, this is a bug!", _PyUnicode_AsString(pyname));
1704                 }
1705                 return ret;
1706         }
1707         else { /* Override the error */
1708                 PyErr_Format(PyExc_AttributeError, "bpy.types.%s not a valid RNA_Struct", _PyUnicode_AsString(pyname));
1709                 return NULL;
1710         }
1711 }
1712
1713 static PyObject *pyrna_basetype_dir(BPy_BaseTypeRNA *self);
1714 static struct PyMethodDef pyrna_basetype_methods[] = {
1715         {"__dir__", (PyCFunction)pyrna_basetype_dir, METH_NOARGS, ""},
1716         {"register", (PyCFunction)pyrna_basetype_register, METH_VARARGS, ""},
1717         {"unregister", (PyCFunction)pyrna_basetype_unregister, METH_VARARGS, ""},
1718         {NULL, NULL, 0, NULL}
1719 };
1720
1721 static PyObject *pyrna_basetype_dir(BPy_BaseTypeRNA *self)
1722 {
1723         PyObject *list, *name;
1724         PyMethodDef *meth;
1725         
1726         list= pyrna_prop_keys(self); /* like calling structs.keys(), avoids looping here */
1727
1728         for(meth=pyrna_basetype_methods; meth->ml_name; meth++) {
1729                 name = PyUnicode_FromString(meth->ml_name);
1730                 PyList_Append(list, name);
1731                 Py_DECREF(name);
1732         }
1733         
1734         return list;
1735 }
1736
1737 PyTypeObject pyrna_basetype_Type = BLANK_PYTHON_TYPE;
1738
1739 PyObject *BPY_rna_types(void)
1740 {
1741         BPy_BaseTypeRNA *self;
1742
1743         if ((pyrna_basetype_Type.tp_flags & Py_TPFLAGS_READY)==0)  {
1744                 pyrna_basetype_Type.tp_name = "RNA_Types";
1745                 pyrna_basetype_Type.tp_basicsize = sizeof( BPy_BaseTypeRNA );
1746                 pyrna_basetype_Type.tp_getattro = ( getattrofunc )pyrna_basetype_getattro;
1747                 pyrna_basetype_Type.tp_flags = Py_TPFLAGS_DEFAULT;
1748                 pyrna_basetype_Type.tp_methods = pyrna_basetype_methods;
1749                 
1750                 if( PyType_Ready( &pyrna_basetype_Type ) < 0 )
1751                         return NULL;
1752         }
1753         
1754         self= (BPy_BaseTypeRNA *)PyObject_NEW( BPy_BaseTypeRNA, &pyrna_basetype_Type );
1755         
1756         /* avoid doing this lookup for every getattr */
1757         RNA_blender_rna_pointer_create(&self->ptr);
1758         self->prop = RNA_struct_find_property(&self->ptr, "structs");
1759         
1760         return (PyObject *)self;
1761 }
1762
1763 static struct PyMethodDef props_methods[] = {
1764         {"FloatProperty", (PyCFunction)BPy_FloatProperty, METH_VARARGS|METH_KEYWORDS, ""},
1765         {"IntProperty", (PyCFunction)BPy_IntProperty, METH_VARARGS|METH_KEYWORDS, ""},
1766         {"BoolProperty", (PyCFunction)BPy_BoolProperty, METH_VARARGS|METH_KEYWORDS, ""},
1767         {"StringProperty", (PyCFunction)BPy_StringProperty, METH_VARARGS|METH_KEYWORDS, ""},
1768         {NULL, NULL, 0, NULL}
1769 };
1770
1771 #if PY_VERSION_HEX >= 0x03000000
1772 static struct PyModuleDef props_module = {
1773         PyModuleDef_HEAD_INIT,
1774         "bpyprops",
1775         "",
1776         -1,/* multiple "initialization" just copies the module dict. */
1777         props_methods,
1778         NULL, NULL, NULL, NULL
1779 };
1780 #endif
1781
1782 PyObject *BPY_rna_props( void )
1783 {
1784         PyObject *submodule, *mod;
1785 #if PY_VERSION_HEX >= 0x03000000
1786         submodule= PyModule_Create(&props_module);
1787 #else /* Py2.x */
1788         submodule= Py_InitModule3( "bpy.props", props_methods, "" );
1789 #endif
1790         
1791         mod = PyModule_New("props");
1792         PyModule_AddObject( submodule, "props", mod );
1793         
1794         /* INCREF since its its assumed that all these functions return the
1795          * module with a new ref like PyDict_New, since they are passed to
1796           * PyModule_AddObject which steals a ref */
1797         Py_INCREF(submodule);
1798         
1799         return submodule;
1800 }
1801
1802 /* Orphan functions, not sure where they should go */
1803
1804 /* Function that sets RNA, NOTE - self is NULL when called from python, but being abused from C so we can pass the srna allong
1805  * This isnt incorrect since its a python object - but be careful */
1806 PyObject *BPy_FloatProperty(PyObject *self, PyObject *args, PyObject *kw)
1807 {
1808         static char *kwlist[] = {"attr", "name", "description", "min", "max", "soft_min", "soft_max", "default", NULL};
1809         char *id, *name="", *description="";
1810         float min=FLT_MIN, max=FLT_MAX, soft_min=FLT_MIN, soft_max=FLT_MAX, def=0.0f;
1811         
1812         if (!PyArg_ParseTupleAndKeywords(args, kw, "s|ssfffff:FloatProperty", kwlist, &id, &name, &description, &min, &max, &soft_min, &soft_max, &def))
1813                 return NULL;
1814         
1815         if (PyTuple_Size(args) > 0) {
1816                 PyErr_SetString(PyExc_ValueError, "all args must be keywors"); // TODO - py3 can enforce this.
1817                 return NULL;
1818         }
1819         
1820         if (self && PyCObject_Check(self)) {
1821                 StructRNA *srna = PyCObject_AsVoidPtr(self);
1822                 RNA_def_float(srna, id, def, min, max, name, description, soft_min, soft_max);
1823                 Py_RETURN_NONE;
1824         } else {
1825                 PyObject *ret = PyTuple_New(2);
1826                 PyTuple_SET_ITEM(ret, 0, PyCObject_FromVoidPtr((void *)BPy_FloatProperty, NULL));
1827                 PyTuple_SET_ITEM(ret, 1, kw);
1828                 Py_INCREF(kw);
1829                 return ret;
1830         }
1831 }
1832
1833 PyObject *BPy_IntProperty(PyObject *self, PyObject *args, PyObject *kw)
1834 {
1835         static char *kwlist[] = {"attr", "name", "description", "min", "max", "soft_min", "soft_max", "default", NULL};
1836         char *id, *name="", *description="";
1837         int min=INT_MIN, max=INT_MAX, soft_min=INT_MIN, soft_max=INT_MAX, def=0;
1838         
1839         if (!PyArg_ParseTupleAndKeywords(args, kw, "s|ssiiiii:IntProperty", kwlist, &id, &name, &description, &min, &max, &soft_min, &soft_max, &def))
1840                 return NULL;
1841         
1842         if (PyTuple_Size(args) > 0) {
1843                 PyErr_SetString(PyExc_ValueError, "all args must be keywors"); // TODO - py3 can enforce this.
1844                 return NULL;
1845         }
1846         
1847         if (self && PyCObject_Check(self)) {
1848                 StructRNA *srna = PyCObject_AsVoidPtr(self);
1849                 RNA_def_int(srna, id, def, min, max, name, description, soft_min, soft_max);
1850                 Py_RETURN_NONE;
1851         } else {
1852                 PyObject *ret = PyTuple_New(2);
1853                 PyTuple_SET_ITEM(ret, 0, PyCObject_FromVoidPtr((void *)BPy_IntProperty, NULL));
1854                 PyTuple_SET_ITEM(ret, 1, kw);
1855                 Py_INCREF(kw);
1856                 return ret;
1857         }
1858 }
1859
1860 PyObject *BPy_BoolProperty(PyObject *self, PyObject *args, PyObject *kw)
1861 {
1862         static char *kwlist[] = {"attr", "name", "description", "default", NULL};
1863         char *id, *name="", *description="";
1864         int def=0;
1865         
1866         if (!PyArg_ParseTupleAndKeywords(args, kw, "s|ssi:IntProperty", kwlist, &id, &name, &description, &def))
1867                 return NULL;
1868         
1869         if (PyTuple_Size(args) > 0) {
1870                 PyErr_SetString(PyExc_ValueError, "all args must be keywors"); // TODO - py3 can enforce this.
1871                 return NULL;
1872         }
1873         
1874         if (self && PyCObject_Check(self)) {
1875                 StructRNA *srna = PyCObject_AsVoidPtr(self);
1876                 RNA_def_boolean(srna, id, def, name, description);
1877                 Py_RETURN_NONE;
1878         } else {
1879                 PyObject *ret = PyTuple_New(2);
1880                 PyTuple_SET_ITEM(ret, 0, PyCObject_FromVoidPtr((void *)BPy_IntProperty, NULL));
1881                 PyTuple_SET_ITEM(ret, 1, kw);
1882                 Py_INCREF(kw);
1883                 return ret;
1884         }
1885 }
1886
1887 PyObject *BPy_StringProperty(PyObject *self, PyObject *args, PyObject *kw)
1888 {
1889         static char *kwlist[] = {"attr", "name", "description", "maxlen", "default", NULL};
1890         char *id, *name="", *description="", *def="";
1891         int maxlen=0;
1892         
1893         if (!PyArg_ParseTupleAndKeywords(args, kw, "s|ssis:StringProperty", kwlist, &id, &name, &description, &maxlen, &def))
1894                 return NULL;
1895         
1896         if (PyTuple_Size(args) > 0) {
1897                 PyErr_SetString(PyExc_ValueError, "all args must be keywors"); // TODO - py3 can enforce this.
1898                 return NULL;
1899         }
1900         
1901         if (self && PyCObject_Check(self)) {
1902                 StructRNA *srna = PyCObject_AsVoidPtr(self);
1903                 RNA_def_string(srna, id, def, maxlen, name, description);
1904                 Py_RETURN_NONE;
1905         } else {
1906                 PyObject *ret = PyTuple_New(2);
1907                 PyTuple_SET_ITEM(ret, 0, PyCObject_FromVoidPtr((void *)BPy_StringProperty, NULL));
1908                 PyTuple_SET_ITEM(ret, 1, kw);
1909                 Py_INCREF(kw);
1910                 return ret;
1911         }
1912 }
1913
1914 /*-------------------- Type Registration ------------------------*/
1915
1916 static int rna_function_arg_count(FunctionRNA *func)
1917 {
1918         const ListBase *lb= RNA_function_defined_parameters(func);
1919         PropertyRNA *parm;
1920         Link *link;
1921         int count= 1;
1922
1923         for(link=lb->first; link; link=link->next) {
1924                 parm= (PropertyRNA*)link;
1925                 if(!(RNA_property_flag(parm) & PROP_RETURN))
1926                         count++;
1927         }
1928         
1929         return count;
1930 }
1931
1932 static int bpy_class_validate(PointerRNA *dummyptr, void *py_data, int *have_function)
1933 {
1934         const ListBase *lb;
1935         Link *link;
1936         FunctionRNA *func;
1937         PropertyRNA *prop;
1938         StructRNA *srna= dummyptr->type;
1939         const char *class_type= RNA_struct_identifier(srna);
1940         PyObject *py_class= (PyObject*)py_data;
1941         PyObject *base_class= RNA_struct_py_type_get(srna);
1942         PyObject *item, *fitem;
1943         PyObject *py_arg_count;
1944         int i, flag, arg_count, func_arg_count;
1945         char identifier[128];
1946
1947         if (base_class) {
1948                 if (!PyObject_IsSubclass(py_class, base_class)) {
1949                         PyObject *name= PyObject_GetAttrString(base_class, "__name__");
1950                         PyErr_Format( PyExc_AttributeError, "expected %s subclass of class \"%s\"", class_type, name ? _PyUnicode_AsString(name):"<UNKNOWN>");
1951                         Py_XDECREF(name);
1952                         return -1;
1953                 }
1954         }
1955
1956         /* verify callback functions */
1957         lb= RNA_struct_defined_functions(srna);
1958         i= 0;
1959         for(link=lb->first; link; link=link->next) {
1960                 func= (FunctionRNA*)link;
1961                 flag= RNA_function_flag(func);
1962
1963                 if(!(flag & FUNC_REGISTER))
1964                         continue;
1965
1966                 item = PyObject_GetAttrString(py_class, RNA_function_identifier(func));
1967
1968                 have_function[i]= (item != NULL);
1969                 i++;
1970
1971                 if (item==NULL) {
1972                         if ((flag & FUNC_REGISTER_OPTIONAL)==0) {
1973                                 PyErr_Format( PyExc_AttributeError, "expected %s class to have an \"%s\" attribute", class_type, RNA_function_identifier(func));
1974                                 return -1;
1975                         }
1976
1977                         PyErr_Clear();
1978                 }
1979                 else {
1980                         Py_DECREF(item); /* no need to keep a ref, the class owns it */
1981
1982                         if (PyMethod_Check(item))
1983                                 fitem= PyMethod_Function(item); /* py 2.x */
1984                         else
1985                                 fitem= item; /* py 3.x */
1986
1987                         if (PyFunction_Check(fitem)==0) {
1988                                 PyErr_Format( PyExc_AttributeError, "expected %s class \"%s\" attribute to be a function", class_type, RNA_function_identifier(func));
1989                                 return -1;
1990                         }
1991
1992                         func_arg_count= rna_function_arg_count(func);
1993
1994                         if (func_arg_count >= 0) { /* -1 if we dont care*/
1995                                 py_arg_count = PyObject_GetAttrString(PyFunction_GET_CODE(fitem), "co_argcount");
1996                                 arg_count = PyLong_AsSsize_t(py_arg_count);
1997                                 Py_DECREF(py_arg_count);
1998
1999                                 if (arg_count != func_arg_count) {
2000                                         PyErr_Format( PyExc_AttributeError, "expected %s class \"%s\" function to have %d args", class_type, RNA_function_identifier(func), func_arg_count);
2001                                         return -1;
2002                                 }
2003                         }
2004                 }
2005         }
2006
2007         /* verify properties */
2008         lb= RNA_struct_defined_properties(srna);
2009         for(link=lb->first; link; link=link->next) {
2010                 prop= (PropertyRNA*)link;
2011                 flag= RNA_property_flag(prop);
2012
2013                 if(!(flag & PROP_REGISTER))
2014                         continue;
2015
2016                 BLI_snprintf(identifier, sizeof(identifier), "__%s__", RNA_property_identifier(prop));
2017                 item = PyObject_GetAttrString(py_class, identifier);
2018
2019                 if (item==NULL) {
2020                         if(strcmp(identifier, "__idname__") == 0) {
2021                                 item= PyObject_GetAttrString(py_class, "__name__");
2022
2023                                 if(item) {
2024                                         Py_DECREF(item); /* no need to keep a ref, the class owns it */
2025
2026                                         if(pyrna_py_to_prop(dummyptr, prop, NULL, item) != 0)
2027                                                 return -1;
2028                                 }
2029                         }
2030
2031                         if (item==NULL && (flag & PROP_REGISTER_OPTIONAL)==0) {
2032                                 PyErr_Format( PyExc_AttributeError, "expected %s class to have an \"%s\" attribute", class_type, identifier);
2033                                 return -1;
2034                         }
2035
2036                         PyErr_Clear();
2037                 }
2038                 else {
2039                         Py_DECREF(item); /* no need to keep a ref, the class owns it */
2040
2041                         if(pyrna_py_to_prop(dummyptr, prop, NULL, item) != 0)
2042                                 return -1;
2043                 }
2044         }
2045
2046         return 0;
2047 }
2048
2049 extern void BPY_update_modules( void ); //XXX temp solution
2050
2051 static int bpy_class_call(PointerRNA *ptr, FunctionRNA *func, ParameterList *parms)
2052 {
2053         PyObject *args;
2054         PyObject *ret= NULL, *py_class, *py_class_instance, *item, *parmitem;
2055         PropertyRNA *pret= NULL, *parm;
2056         ParameterIterator iter;
2057         PointerRNA funcptr;
2058         void *retdata= NULL;
2059         int err= 0, i, flag;
2060
2061         PyGILState_STATE gilstate = PyGILState_Ensure();
2062
2063         BPY_update_modules(); // XXX - the RNA pointers can change so update before running, would like a nicer solution for this.
2064
2065         py_class= RNA_struct_py_type_get(ptr->type);
2066         
2067         item = pyrna_struct_CreatePyObject(ptr);
2068         if(item == NULL) {
2069                 py_class_instance = NULL;
2070         }
2071         else if(item == Py_None) { /* probably wont ever happen but possible */
2072                 Py_DECREF(item);
2073                 py_class_instance = NULL;
2074         }
2075         else {
2076                 args = PyTuple_New(1);
2077                 PyTuple_SET_ITEM(args, 0, item);
2078                 py_class_instance = PyObject_Call(py_class, args, NULL);
2079                 Py_DECREF(args);
2080         }
2081
2082         if (py_class_instance) { /* Initializing the class worked, now run its invoke function */
2083                 item= PyObject_GetAttrString(py_class, RNA_function_identifier(func));
2084                 flag= RNA_function_flag(func);
2085
2086                 if(item) {
2087                         pret= RNA_function_return(func);
2088                         RNA_pointer_create(NULL, &RNA_Function, func, &funcptr);
2089
2090                         args = PyTuple_New(rna_function_arg_count(func));
2091                         PyTuple_SET_ITEM(args, 0, py_class_instance);
2092
2093                         RNA_parameter_list_begin(parms, &iter);
2094
2095                         /* parse function parameters */
2096                         for (i= 1; iter.valid; RNA_parameter_list_next(&iter)) {
2097                                 parm= iter.parm;
2098
2099                                 if (parm==pret) {
2100                                         retdata= iter.data;
2101                                         continue;
2102                                 }
2103
2104                                 parmitem= pyrna_param_to_py(&funcptr, parm, iter.data);
2105                                 PyTuple_SET_ITEM(args, i, parmitem);
2106                                 i++;
2107                         }
2108
2109                         ret = PyObject_Call(item, args, NULL);
2110
2111                         Py_DECREF(item);
2112                         Py_DECREF(args);
2113                 }
2114                 else {
2115                         Py_DECREF(py_class_instance);
2116                         PyErr_Format(PyExc_AttributeError, "could not find function %s in %s to execute callback.", RNA_function_identifier(func), RNA_struct_identifier(ptr->type));
2117                         err= -1;
2118                 }
2119         }
2120         else {
2121                 PyErr_Format(PyExc_AttributeError, "could not create instance of %s to call callback function %s.", RNA_struct_identifier(ptr->type), RNA_function_identifier(func));
2122                 err= -1;
2123         }
2124
2125         if (ret == NULL) { /* covers py_class_instance failing too */
2126                 PyErr_Print(); /* XXX use reporting api? */
2127                 err= -1;
2128         }
2129         else {
2130                 if(retdata)
2131                         err= pyrna_py_to_prop(&funcptr, pret, retdata, ret);
2132                 Py_DECREF(ret);
2133         }
2134
2135         PyGILState_Release(gilstate);
2136         
2137         return err;
2138 }
2139
2140 static void bpy_class_free(void *pyob_ptr)
2141 {
2142         if(G.f&G_DEBUG) {
2143                 if(((PyObject *)pyob_ptr)->ob_refcnt > 1)
2144                         PyObSpit("zombie class - ref should be 1", (PyObject *)pyob_ptr);
2145         }
2146         Py_DECREF((PyObject *)pyob_ptr);
2147 }
2148
2149 PyObject *pyrna_basetype_register(PyObject *self, PyObject *args)
2150 {
2151         bContext *C= NULL;
2152         PyObject *py_class, *item;
2153         ReportList reports;
2154         StructRegisterFunc reg;
2155         BPy_StructRNA *py_srna;
2156         StructRNA *srna;
2157
2158         if(!PyArg_ParseTuple(args, "O:register", &py_class))
2159                 return NULL;
2160         
2161         if(!PyType_Check(py_class)) {
2162                 PyErr_SetString(PyExc_AttributeError, "expected a Type subclassed from a registerable rna type (no a Type object).");
2163                 return NULL;
2164         }
2165
2166         /* check we got an __rna__ attribute */
2167         item= PyObject_GetAttrString(py_class, "__rna__");
2168
2169         if(!item || !BPy_StructRNA_Check(item)) {
2170                 Py_XDECREF(item);
2171                 PyErr_SetString(PyExc_AttributeError, "expected a Type subclassed from a registerable rna type (no __rna__ property).");
2172                 return NULL;
2173         }
2174
2175         /* check the __rna__ attribute has the right type */
2176         Py_DECREF(item);
2177         py_srna= (BPy_StructRNA*)item;
2178
2179         if(py_srna->ptr.type != &RNA_Struct) {
2180                 PyErr_SetString(PyExc_AttributeError, "expected a Type subclassed from a registerable rna type (not a Struct).");
2181                 return NULL;
2182         }
2183         
2184         /* check that we have a register callback for this type */
2185         reg= RNA_struct_register(py_srna->ptr.data);
2186
2187         if(!reg) {
2188                 PyErr_SetString(PyExc_AttributeError, "expected a Type subclassed from a registerable rna type (no register supported).");
2189                 return NULL;
2190         }
2191         
2192         /* get the context, so register callback can do necessary refreshes */
2193         C= BPy_GetContext();
2194
2195         /* call the register callback */
2196         BKE_reports_init(&reports, RPT_STORE);
2197         srna= reg(C, &reports, py_class, bpy_class_validate, bpy_class_call, bpy_class_free);
2198
2199         if(!srna) {
2200                 BPy_reports_to_error(&reports);
2201                 BKE_reports_clear(&reports);
2202                 return NULL;
2203         }
2204
2205         BKE_reports_clear(&reports);
2206
2207         pyrna_subtype_set_rna(py_class, srna); /* takes a ref to py_class */
2208
2209         Py_RETURN_NONE;
2210 }
2211
2212 PyObject *pyrna_basetype_unregister(PyObject *self, PyObject *args)
2213 {
2214         bContext *C= NULL;
2215         PyObject *py_class, *item;
2216         BPy_StructRNA *py_srna;
2217         StructUnregisterFunc unreg;
2218
2219         if(!PyArg_ParseTuple(args, "O:unregister", &py_class))
2220                 return NULL;
2221
2222         if(!PyType_Check(py_class)) {
2223                 PyErr_SetString(PyExc_AttributeError, "expected a Type subclassed from a registerable rna type (no a Type object).");
2224                 return NULL;
2225         }
2226
2227         /* check we got an __rna__ attribute */
2228         item= PyDict_GetItemString(((PyTypeObject*)py_class)->tp_dict, "__rna__");  /* borrow ref */
2229
2230         if(!item || !BPy_StructRNA_Check(item)) {
2231                 PyErr_SetString(PyExc_AttributeError, "expected a Type subclassed from a registerable rna type (no __rna__ property).");
2232                 return NULL;
2233         }
2234
2235         /* check the __rna__ attribute has the right type */
2236         py_srna= (BPy_StructRNA*)item;
2237
2238         if(py_srna->ptr.type != &RNA_Struct) {
2239                 PyErr_SetString(PyExc_AttributeError, "expected a Type subclassed from a registerable rna type (not a Struct).");
2240                 return NULL;
2241         }
2242         
2243         /* check that we have a unregister callback for this type */
2244         unreg= RNA_struct_unregister(py_srna->ptr.data);
2245
2246         if(!unreg) {
2247                 PyErr_SetString(PyExc_AttributeError, "expected a Type subclassed from a registerable rna type (no unregister supported).");
2248                 return NULL;
2249         }
2250         
2251         /* get the context, so register callback can do necessary refreshes */
2252         C= BPy_GetContext();
2253         
2254
2255         /* call unregister */
2256         unreg(C, py_srna->ptr.data);
2257
2258         /* remove reference to old type */
2259         Py_DECREF(py_class);
2260
2261         Py_RETURN_NONE;
2262 }
2263