Context
[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         if(self->ptr.type == &RNA_Context) {
880                 ListBase lb = CTX_data_dir_get(self->ptr.data);
881                 LinkData *link;
882
883                 for(link=lb.first; link; link=link->next) {
884                         pystring = PyUnicode_FromString(link->data);
885                         PyList_Append(ret, pystring);
886                         Py_DECREF(pystring);
887                 }
888
889                 BLI_freelistN(&lb);
890         }
891         
892         return ret;
893 }
894
895
896 //---------------getattr--------------------------------------------
897 static PyObject *pyrna_struct_getattro( BPy_StructRNA * self, PyObject *pyname )
898 {
899         char *name = _PyUnicode_AsString(pyname);
900         PyObject *ret;
901         PropertyRNA *prop;
902         FunctionRNA *func;
903         
904         /* Include this incase this instance is a subtype of a python class
905          * In these instances we may want to return a function or variable provided by the subtype
906          * 
907          * Also needed to return methods when its not a subtype
908          * */
909         ret = PyObject_GenericGetAttr((PyObject *)self, pyname);
910         if (ret)        return ret;
911         else            PyErr_Clear();
912         /* done with subtypes */
913         
914         if ((prop = RNA_struct_find_property(&self->ptr, name))) {
915                 ret = pyrna_prop_to_py(&self->ptr, prop);
916         }
917         else if ((func = RNA_struct_find_function(&self->ptr, name))) {
918                 ret = pyrna_func_to_py(&self->ptr, func);
919         }
920         else if (self->ptr.type == &RNA_Context) {
921                 PointerRNA newptr;
922                 ListBase newlb;
923
924                 CTX_data_get(self->ptr.data, name, &newptr, &newlb);
925
926         if (newptr.data) {
927             ret = pyrna_struct_CreatePyObject(&newptr);
928                 }
929                 else if (newlb.first) {
930                         CollectionPointerLink *link;
931                         PyObject *linkptr;
932
933                         ret = PyList_New(0);
934
935                         for(link=newlb.first; link; link=link->next) {
936                                 linkptr= pyrna_struct_CreatePyObject(&link->ptr);
937                                 PyList_Append(ret, linkptr);
938                                 Py_DECREF(linkptr);
939                         }
940                 }
941         else {
942             ret = Py_None;
943             Py_INCREF(ret);
944         }
945
946                 BLI_freelistN(&newlb);
947         }
948         else {
949                 PyErr_Format( PyExc_AttributeError, "StructRNA - Attribute \"%s\" not found", name);
950                 ret = NULL;
951         }
952         
953         return ret;
954 }
955
956 //--------------- setattr-------------------------------------------
957 static int pyrna_struct_setattro( BPy_StructRNA * self, PyObject *pyname, PyObject * value )
958 {
959         char *name = _PyUnicode_AsString(pyname);
960         PropertyRNA *prop = RNA_struct_find_property(&self->ptr, name);
961         
962         if (prop==NULL) {
963                 if (!BPy_StructRNA_CheckExact(self) && PyObject_GenericSetAttr((PyObject *)self, pyname, value) >= 0) {
964                         return 0;
965                 }
966                 else {
967                         PyErr_Format( PyExc_AttributeError, "StructRNA - Attribute \"%s\" not found", name);
968                         return -1;
969                 }
970         }               
971         
972         if (!RNA_property_editable(&self->ptr, prop)) {
973                 PyErr_Format( PyExc_AttributeError, "StructRNA - Attribute \"%s\" from \"%s\" is read-only", RNA_property_identifier(prop), RNA_struct_identifier(self->ptr.type) );
974                 return -1;
975         }
976                 
977         /* pyrna_py_to_prop sets its own exceptions */
978         return pyrna_py_to_prop(&self->ptr, prop, NULL, value);
979 }
980
981 PyObject *pyrna_prop_keys(BPy_PropertyRNA *self)
982 {
983         PyObject *ret;
984         if (RNA_property_type(self->prop) != PROP_COLLECTION) {
985                 PyErr_SetString( PyExc_TypeError, "keys() is only valid for collection types" );
986                 ret = NULL;
987         } else {
988                 PyObject *item;
989                 CollectionPropertyIterator iter;
990                 PropertyRNA *nameprop;
991                 char name[256], *nameptr;
992
993                 ret = PyList_New(0);
994                 
995                 RNA_property_collection_begin(&self->ptr, self->prop, &iter);
996                 for(; iter.valid; RNA_property_collection_next(&iter)) {
997                         if(iter.ptr.data && (nameprop = RNA_struct_name_property(iter.ptr.type))) {
998                                 nameptr= RNA_property_string_get_alloc(&iter.ptr, nameprop, name, sizeof(name));                                
999                                 
1000                                 /* add to python list */
1001                                 item = PyUnicode_FromString( nameptr );
1002                                 PyList_Append(ret, item);
1003                                 Py_DECREF(item);
1004                                 /* done */
1005                                 
1006                                 if ((char *)&name != nameptr)
1007                                         MEM_freeN(nameptr);
1008                         }
1009                 }
1010                 RNA_property_collection_end(&iter);
1011         }
1012         
1013         return ret;
1014 }
1015
1016 PyObject *pyrna_prop_items(BPy_PropertyRNA *self)
1017 {
1018         PyObject *ret;
1019         if (RNA_property_type(self->prop) != PROP_COLLECTION) {
1020                 PyErr_SetString( PyExc_TypeError, "items() is only valid for collection types" );
1021                 ret = NULL;
1022         } else {
1023                 PyObject *item;
1024                 CollectionPropertyIterator iter;
1025                 PropertyRNA *nameprop;
1026                 char name[256], *nameptr;
1027                 int i= 0;
1028
1029                 ret = PyList_New(0);
1030                 
1031                 RNA_property_collection_begin(&self->ptr, self->prop, &iter);
1032                 for(; iter.valid; RNA_property_collection_next(&iter)) {
1033                         if(iter.ptr.data) {
1034                                 /* add to python list */
1035                                 item= PyTuple_New(2);
1036                                 if(nameprop = RNA_struct_name_property(iter.ptr.type)) {
1037                                         nameptr= RNA_property_string_get_alloc(&iter.ptr, nameprop, name, sizeof(name));
1038                                         PyTuple_SET_ITEM(item, 0, PyUnicode_FromString( nameptr ));
1039                                         if ((char *)&name != nameptr)
1040                                                 MEM_freeN(nameptr);
1041                                 }
1042                                 else {
1043                                         PyTuple_SET_ITEM(item, 0, PyLong_FromSsize_t(i)); /* a bit strange but better then returning an empty list */
1044                                 }
1045                                 PyTuple_SET_ITEM(item, 1, pyrna_struct_CreatePyObject(&iter.ptr));
1046                                 
1047                                 PyList_Append(ret, item);
1048                                 Py_DECREF(item);
1049                                 
1050                                 i++;
1051                         }
1052                 }
1053                 RNA_property_collection_end(&iter);
1054         }
1055         
1056         return ret;
1057 }
1058
1059
1060 PyObject *pyrna_prop_values(BPy_PropertyRNA *self)
1061 {
1062         PyObject *ret;
1063         
1064         if (RNA_property_type(self->prop) != PROP_COLLECTION) {
1065                 PyErr_SetString( PyExc_TypeError, "values() is only valid for collection types" );
1066                 ret = NULL;
1067         } else {
1068                 PyObject *item;
1069                 CollectionPropertyIterator iter;
1070                 PropertyRNA *iterprop;
1071                 ret = PyList_New(0);
1072                 
1073                 //iterprop= RNA_struct_iterator_property(self->ptr.type);
1074                 RNA_property_collection_begin(&self->ptr, self->prop, &iter);
1075                 for(; iter.valid; RNA_property_collection_next(&iter)) {
1076                         item = pyrna_struct_CreatePyObject(&iter.ptr);
1077                         PyList_Append(ret, item);
1078                         Py_DECREF(item);
1079                 }
1080                 RNA_property_collection_end(&iter);
1081         }
1082         
1083         return ret;
1084 }
1085
1086 /* A bit of a kludge, make a list out of a collection or array,
1087  * then return the lists iter function, not especially fast but convenient for now */
1088 PyObject *pyrna_prop_iter(BPy_PropertyRNA *self)
1089 {
1090         /* Try get values from a collection */
1091         PyObject *ret = pyrna_prop_values(self);
1092         
1093         if (ret==NULL) {
1094                 /* collection did not work, try array */
1095                 int len = RNA_property_array_length(self->prop);
1096                 
1097                 if (len) {
1098                         int i;
1099                         PyErr_Clear();
1100                         ret = PyList_New(len);
1101                         
1102                         for (i=0; i < len; i++) {
1103                                 PyList_SET_ITEM(ret, i, pyrna_prop_to_py_index(&self->ptr, self->prop, i));
1104                         }
1105                 }
1106         }
1107         
1108         if (ret) {
1109                 /* we know this is a list so no need to PyIter_Check */
1110                 PyObject *iter = PyObject_GetIter(ret); 
1111                 Py_DECREF(ret);
1112                 return iter;
1113         }
1114         
1115         PyErr_SetString( PyExc_TypeError, "this BPy_PropertyRNA object is not iterable" );
1116         return NULL;
1117 }
1118
1119 static struct PyMethodDef pyrna_struct_methods[] = {
1120         {"__dir__", (PyCFunction)pyrna_struct_dir, METH_NOARGS, ""},
1121         {NULL, NULL, 0, NULL}
1122 };
1123
1124 static struct PyMethodDef pyrna_prop_methods[] = {
1125         {"keys", (PyCFunction)pyrna_prop_keys, METH_NOARGS, ""},
1126         {"items", (PyCFunction)pyrna_prop_items, METH_NOARGS, ""},
1127         {"values", (PyCFunction)pyrna_prop_values, METH_NOARGS, ""},
1128         {NULL, NULL, 0, NULL}
1129 };
1130
1131 /* only needed for subtyping, so a new class gets a valid BPy_StructRNA
1132  * todo - also accept useful args */
1133 static PyObject * pyrna_struct_new(PyTypeObject *type, PyObject *args, PyObject *kwds) {
1134
1135         BPy_StructRNA *base = NULL;
1136         
1137         if (!PyArg_ParseTuple(args, "O!:Base BPy_StructRNA", &pyrna_struct_Type, &base))
1138                 return NULL;
1139         
1140         if (type == &pyrna_struct_Type) {
1141                 return pyrna_struct_CreatePyObject(&base->ptr);
1142         } else {
1143                 BPy_StructRNA *ret = (BPy_StructRNA *) type->tp_alloc(type, 0);
1144                 ret->ptr = base->ptr;
1145                 return (PyObject *)ret;
1146         }
1147 }
1148
1149 /* only needed for subtyping, so a new class gets a valid BPy_StructRNA
1150  * todo - also accept useful args */
1151 static PyObject * pyrna_prop_new(PyTypeObject *type, PyObject *args, PyObject *kwds) {
1152
1153         BPy_PropertyRNA *base = NULL;
1154         
1155         if (!PyArg_ParseTuple(args, "O!:Base BPy_PropertyRNA", &pyrna_prop_Type, &base))
1156                 return NULL;
1157         
1158         if (type == &pyrna_prop_Type) {
1159                 return pyrna_prop_CreatePyObject(&base->ptr, base->prop);
1160         } else {
1161                 BPy_PropertyRNA *ret = (BPy_PropertyRNA *) type->tp_alloc(type, 0);
1162                 ret->ptr = base->ptr;
1163                 ret->prop = base->prop;
1164                 return (PyObject *)ret;
1165         }
1166 }
1167
1168 PyObject *pyrna_param_to_py(PointerRNA *ptr, PropertyRNA *prop, void *data)
1169 {
1170         PyObject *ret;
1171         int type = RNA_property_type(prop);
1172         int len = RNA_property_array_length(prop);
1173
1174         int a;
1175
1176         if(len > 0) {
1177                 /* resolve the array from a new pytype */
1178                 ret = PyTuple_New(len);
1179
1180                 switch (type) {
1181                 case PROP_BOOLEAN:
1182                         for(a=0; a<len; a++)
1183                                 PyTuple_SET_ITEM(ret, a, PyBool_FromLong( ((int*)data)[a] ));
1184                         break;
1185                 case PROP_INT:
1186                         for(a=0; a<len; a++)
1187                                 PyTuple_SET_ITEM(ret, a, PyLong_FromSsize_t( (Py_ssize_t)((int*)data)[a] ));
1188                         break;
1189                 case PROP_FLOAT:
1190                         for(a=0; a<len; a++)
1191                                 PyTuple_SET_ITEM(ret, a, PyFloat_FromDouble( ((float*)data)[a] ));
1192                         break;
1193                 default:
1194                         PyErr_Format(PyExc_AttributeError, "RNA Error: unknown array type \"%d\" (pyrna_param_to_py)", type);
1195                         ret = NULL;
1196                         break;
1197                 }
1198         }
1199         else {
1200                 /* see if we can coorce into a python type - PropertyType */
1201                 switch (type) {
1202                 case PROP_BOOLEAN:
1203                         ret = PyBool_FromLong( *(int*)data );
1204                         break;
1205                 case PROP_INT:
1206                         ret = PyLong_FromSsize_t( (Py_ssize_t)*(int*)data );
1207                         break;
1208                 case PROP_FLOAT:
1209                         ret = PyFloat_FromDouble( *(float*)data );
1210                         break;
1211                 case PROP_STRING:
1212                 {
1213                         ret = PyUnicode_FromString( *(char**)data );
1214                         break;
1215                 }
1216                 case PROP_ENUM:
1217                 {
1218                         const char *identifier;
1219                         int val = *(int*)data;
1220                         
1221                         if (RNA_property_enum_identifier(ptr, prop, val, &identifier)) {
1222                                 ret = PyUnicode_FromString( identifier );
1223                         } else {
1224                                 PyErr_Format(PyExc_AttributeError, "RNA Error: Current value \"%d\" matches no enum", val);
1225                                 ret = NULL;
1226                         }
1227
1228                         break;
1229                 }
1230                 case PROP_POINTER:
1231                 {
1232                         PointerRNA newptr;
1233                         StructRNA *type= RNA_property_pointer_type(ptr, prop);
1234                         int flag = RNA_property_flag(prop);
1235
1236                         if(flag & PROP_RNAPTR) {
1237                                 /* in this case we get the full ptr */
1238                                 newptr= *(PointerRNA*)data;
1239                         }
1240                         else {
1241                                 /* XXX this is missing the ID part! */
1242                                 RNA_pointer_create(NULL, type, *(void**)data, &newptr);
1243                         }
1244
1245                         if (newptr.data) {
1246                                 ret = pyrna_struct_CreatePyObject(&newptr);
1247                         } else {
1248                                 ret = Py_None;
1249                                 Py_INCREF(ret);
1250                         }
1251                         break;
1252                 }
1253                 case PROP_COLLECTION:
1254                         /* XXX not supported yet
1255                          * ret = pyrna_prop_CreatePyObject(ptr, prop); */
1256                         ret = NULL;
1257                         break;
1258                 default:
1259                         PyErr_Format(PyExc_AttributeError, "RNA Error: unknown type \"%d\" (pyrna_param_to_py)", type);
1260                         ret = NULL;
1261                         break;
1262                 }
1263         }
1264
1265         return ret;
1266 }
1267
1268 static PyObject * pyrna_func_call(PyObject * self, PyObject *args, PyObject *kw)
1269 {
1270         PointerRNA *self_ptr= &(((BPy_StructRNA *)PyTuple_GET_ITEM(self, 0))->ptr);
1271         FunctionRNA *self_func=  PyCObject_AsVoidPtr(PyTuple_GET_ITEM(self, 1));
1272
1273         PointerRNA funcptr;
1274         ParameterList *parms;
1275         ParameterIterator iter;
1276         PropertyRNA *pret, *parm;
1277         PyObject *ret, *item;
1278         int i, tlen, flag, err= 0;
1279         const char *tid, *fid, *pid;
1280         void *retdata= NULL;
1281
1282         /* setup */
1283         RNA_pointer_create(NULL, &RNA_Function, self_func, &funcptr);
1284
1285         pret= RNA_function_return(self_func);
1286         tlen= PyTuple_GET_SIZE(args);
1287
1288         parms= RNA_parameter_list_create(self_ptr, self_func);
1289         RNA_parameter_list_begin(parms, &iter);
1290
1291         /* parse function parameters */
1292         for (i= 0; iter.valid; RNA_parameter_list_next(&iter)) {
1293                 parm= iter.parm;
1294
1295                 if (parm==pret) {
1296                         retdata= iter.data;
1297                         continue;
1298                 }
1299
1300                 pid= RNA_property_identifier(parm);
1301                 flag= RNA_property_flag(parm);
1302                 item= NULL;
1303
1304                 if ((i < tlen) && (flag & PROP_REQUIRED)) {
1305                         item= PyTuple_GET_ITEM(args, i);
1306                         i++;
1307                 }
1308                 else if (kw != NULL)
1309                         item= PyDict_GetItemString(kw, pid);  /* borrow ref */
1310
1311                 if (item==NULL) {
1312                         if(flag & PROP_REQUIRED) {
1313                                 tid= RNA_struct_identifier(self_ptr->type);
1314                                 fid= RNA_function_identifier(self_func);
1315
1316                                 PyErr_Format(PyExc_AttributeError, "%s.%s(): required parameter \"%s\" not specified", tid, fid, pid);
1317                                 err= -1;
1318                                 break;
1319                         }
1320                         else
1321                                 continue;
1322                 }
1323
1324                 err= pyrna_py_to_prop(&funcptr, parm, iter.data, item);
1325
1326                 if(err!=0)
1327                         break;
1328         }
1329
1330         ret= NULL;
1331         if (err==0) {
1332                 /* call function */
1333                 ReportList reports;
1334                 bContext *C= BPy_GetContext();
1335
1336                 BKE_reports_init(&reports, RPT_STORE);
1337                 RNA_function_call(C, &reports, self_ptr, self_func, parms);
1338
1339                 err= (BPy_reports_to_error(&reports))? -1: 0;
1340                 BKE_reports_clear(&reports);
1341
1342                 /* return value */
1343                 if(err==0)
1344                         if(pret)
1345                                 ret= pyrna_param_to_py(&funcptr, pret, retdata);
1346         }
1347
1348         /* cleanup */
1349         RNA_parameter_list_end(&iter);
1350         RNA_parameter_list_free(parms);
1351
1352         if (ret)
1353                 return ret;
1354
1355         if (err==-1)
1356                 return NULL;
1357
1358         Py_RETURN_NONE;
1359 }
1360
1361 /*-----------------------BPy_StructRNA method def------------------------------*/
1362 PyTypeObject pyrna_struct_Type = {
1363 #if (PY_VERSION_HEX >= 0x02060000)
1364         PyVarObject_HEAD_INIT(NULL, 0)
1365 #else
1366         /* python 2.5 and below */
1367         PyObject_HEAD_INIT( NULL )  /* required py macro */
1368         0,                          /* ob_size */
1369 #endif
1370         "StructRNA",                    /* tp_name */
1371         sizeof( BPy_StructRNA ),        /* tp_basicsize */
1372         0,                      /* tp_itemsize */
1373         /* methods */
1374         ( destructor ) pyrna_struct_dealloc,/* tp_dealloc */
1375         NULL,                       /* printfunc tp_print; */
1376         NULL,                                           /* getattrfunc tp_getattr; */
1377         NULL,                                           /* setattrfunc tp_setattr; */
1378         NULL,                                           /* tp_compare */ /* DEPRECATED in python 3.0! */
1379         ( reprfunc ) pyrna_struct_repr, /* tp_repr */
1380
1381         /* Method suites for standard classes */
1382
1383         NULL,                       /* PyNumberMethods *tp_as_number; */
1384         NULL,                                           /* PySequenceMethods *tp_as_sequence; */
1385         NULL,                                           /* PyMappingMethods *tp_as_mapping; */
1386
1387         /* More standard operations (here for binary compatibility) */
1388
1389         ( hashfunc )pyrna_struct_hash,  /* hashfunc tp_hash; */
1390         NULL,                                           /* ternaryfunc tp_call; */
1391         NULL,                       /* reprfunc tp_str; */
1392         ( getattrofunc ) pyrna_struct_getattro, /* getattrofunc tp_getattro; */
1393         ( setattrofunc ) pyrna_struct_setattro, /* setattrofunc tp_setattro; */
1394
1395         /* Functions to access object as input/output buffer */
1396         NULL,                       /* PyBufferProcs *tp_as_buffer; */
1397
1398   /*** Flags to define presence of optional/expanded features ***/
1399         Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE,         /* long tp_flags; */
1400
1401         NULL,                                           /*  char *tp_doc;  Documentation string */
1402   /*** Assigned meaning in release 2.0 ***/
1403         /* call function for all accessible objects */
1404         NULL,                       /* traverseproc tp_traverse; */
1405
1406         /* delete references to contained objects */
1407         NULL,                       /* inquiry tp_clear; */
1408
1409   /***  Assigned meaning in release 2.1 ***/
1410   /*** rich comparisons ***/
1411         (richcmpfunc)pyrna_struct_richcmp,      /* richcmpfunc tp_richcompare; */
1412
1413   /***  weak reference enabler ***/
1414         0,                          /* long tp_weaklistoffset; */
1415
1416   /*** Added in release 2.2 ***/
1417         /*   Iterators */
1418         NULL,                       /* getiterfunc tp_iter; */
1419         NULL,                       /* iternextfunc tp_iternext; */
1420
1421   /*** Attribute descriptor and subclassing stuff ***/
1422         pyrna_struct_methods,                   /* struct PyMethodDef *tp_methods; */
1423         NULL,                       /* struct PyMemberDef *tp_members; */
1424         NULL,                                           /* struct PyGetSetDef *tp_getset; */
1425         NULL,                       /* struct _typeobject *tp_base; */
1426         NULL,                       /* PyObject *tp_dict; */
1427         NULL,                       /* descrgetfunc tp_descr_get; */
1428         NULL,                       /* descrsetfunc tp_descr_set; */
1429         0,                          /* long tp_dictoffset; */
1430         NULL,                       /* initproc tp_init; */
1431         NULL,                       /* allocfunc tp_alloc; */
1432         pyrna_struct_new,                       /* newfunc tp_new; */
1433         /*  Low-level free-memory routine */
1434         NULL,                       /* freefunc tp_free;  */
1435         /* For PyObject_IS_GC */
1436         NULL,                       /* inquiry tp_is_gc;  */
1437         NULL,                       /* PyObject *tp_bases; */
1438         /* method resolution order */
1439         NULL,                       /* PyObject *tp_mro;  */
1440         NULL,                       /* PyObject *tp_cache; */
1441         NULL,                       /* PyObject *tp_subclasses; */
1442         NULL,                       /* PyObject *tp_weaklist; */
1443         NULL
1444 };
1445
1446 /*-----------------------BPy_PropertyRNA method def------------------------------*/
1447 PyTypeObject pyrna_prop_Type = {
1448 #if (PY_VERSION_HEX >= 0x02060000)
1449         PyVarObject_HEAD_INIT(NULL, 0)
1450 #else
1451         /* python 2.5 and below */
1452         PyObject_HEAD_INIT( NULL )  /* required py macro */
1453         0,                          /* ob_size */
1454 #endif
1455         
1456         "PropertyRNA",          /* tp_name */
1457         sizeof( BPy_PropertyRNA ),                      /* tp_basicsize */
1458         0,                      /* tp_itemsize */
1459         /* methods */
1460         NULL,                                           /* tp_dealloc */
1461         NULL,                       /* printfunc tp_print; */
1462         NULL,                                           /* getattrfunc tp_getattr; */
1463         NULL,                       /* setattrfunc tp_setattr; */
1464         NULL,                                           /* tp_compare */ /* DEPRECATED in python 3.0! */
1465         ( reprfunc ) pyrna_prop_repr,   /* tp_repr */
1466
1467         /* Method suites for standard classes */
1468
1469         NULL,                       /* PyNumberMethods *tp_as_number; */
1470         &pyrna_prop_as_sequence,        /* PySequenceMethods *tp_as_sequence; */
1471         &pyrna_prop_as_mapping,         /* PyMappingMethods *tp_as_mapping; */
1472
1473         /* More standard operations (here for binary compatibility) */
1474
1475         NULL,                                           /* hashfunc tp_hash; */
1476         NULL,                       /* ternaryfunc tp_call; */
1477         NULL,                       /* reprfunc tp_str; */
1478         NULL, /*PyObject_GenericGetAttr - MINGW Complains, assign later */      /* getattrofunc tp_getattro; */ /* will only use these if this is a subtype of a py class */
1479         NULL, /*PyObject_GenericSetAttr - MINGW Complains, assign later */      /* setattrofunc tp_setattro; */
1480
1481         /* Functions to access object as input/output buffer */
1482         NULL,                       /* PyBufferProcs *tp_as_buffer; */
1483
1484   /*** Flags to define presence of optional/expanded features ***/
1485         Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE,         /* long tp_flags; */
1486
1487         NULL,                                           /*  char *tp_doc;  Documentation string */
1488   /*** Assigned meaning in release 2.0 ***/
1489         /* call function for all accessible objects */
1490         NULL,                       /* traverseproc tp_traverse; */
1491
1492         /* delete references to contained objects */
1493         NULL,                       /* inquiry tp_clear; */
1494
1495   /***  Assigned meaning in release 2.1 ***/
1496   /*** rich comparisons ***/
1497         (richcmpfunc)pyrna_prop_richcmp,        /* richcmpfunc tp_richcompare; */
1498
1499   /***  weak reference enabler ***/
1500         0,                          /* long tp_weaklistoffset; */
1501
1502   /*** Added in release 2.2 ***/
1503         /*   Iterators */
1504         (getiterfunc)pyrna_prop_iter,   /* getiterfunc tp_iter; */
1505         NULL,                       /* iternextfunc tp_iternext; */
1506
1507   /*** Attribute descriptor and subclassing stuff ***/
1508         pyrna_prop_methods,                     /* struct PyMethodDef *tp_methods; */
1509         NULL,                       /* struct PyMemberDef *tp_members; */
1510         NULL,                                           /* struct PyGetSetDef *tp_getset; */
1511         NULL,                       /* struct _typeobject *tp_base; */
1512         NULL,                       /* PyObject *tp_dict; */
1513         NULL,                       /* descrgetfunc tp_descr_get; */
1514         NULL,                       /* descrsetfunc tp_descr_set; */
1515         0,                          /* long tp_dictoffset; */
1516         NULL,                       /* initproc tp_init; */
1517         NULL,                       /* allocfunc tp_alloc; */
1518         pyrna_prop_new,                         /* newfunc tp_new; */
1519         /*  Low-level free-memory routine */
1520         NULL,                       /* freefunc tp_free;  */
1521         /* For PyObject_IS_GC */
1522         NULL,                       /* inquiry tp_is_gc;  */
1523         NULL,                       /* PyObject *tp_bases; */
1524         /* method resolution order */
1525         NULL,                       /* PyObject *tp_mro;  */
1526         NULL,                       /* PyObject *tp_cache; */
1527         NULL,                       /* PyObject *tp_subclasses; */
1528         NULL,                       /* PyObject *tp_weaklist; */
1529         NULL
1530 };
1531
1532 static void pyrna_subtype_set_rna(PyObject *newclass, StructRNA *srna)
1533 {
1534         PointerRNA ptr;
1535         PyObject *item;
1536         
1537         Py_INCREF(newclass);
1538         
1539         if (RNA_struct_py_type_get(srna))
1540                 PyObSpit("RNA WAS SET - ", RNA_struct_py_type_get(srna));
1541         
1542         Py_XDECREF(((PyObject *)RNA_struct_py_type_get(srna)));
1543         
1544         RNA_struct_py_type_set(srna, (void *)newclass); /* Store for later use */
1545
1546         /* Not 100% needed but useful,
1547          * having an instance within a type looks wrong however this instance IS an rna type */
1548         RNA_pointer_create(NULL, &RNA_Struct, srna, &ptr);
1549         item = pyrna_struct_CreatePyObject(&ptr);
1550         PyDict_SetItemString(((PyTypeObject *)newclass)->tp_dict, "__rna__", item);
1551         Py_DECREF(item);
1552         /* done with rna instance */
1553 }
1554
1555 PyObject* pyrna_struct_Subtype(PointerRNA *ptr)
1556 {
1557         PyObject *newclass = NULL;
1558         PropertyRNA *nameprop;
1559
1560         if (ptr->type==NULL) {
1561                 newclass= NULL; /* Nothing to do */
1562         } else if ((newclass= RNA_struct_py_type_get(ptr->data))) {
1563                 Py_INCREF(newclass);
1564         } else if ((nameprop = RNA_struct_name_property(ptr->type))) {
1565                 /* for now, return the base RNA type rather then a real module */
1566                 
1567                 /* Assume RNA_struct_py_type_get(ptr->data) was alredy checked */
1568                 
1569                 /* subclass equivelents
1570                 - class myClass(myBase):
1571                         some='value' # or ...
1572                 - myClass = type(name='myClass', bases=(myBase,), dict={'some':'value'})
1573                 */
1574                 char name[256], *nameptr;
1575                 const char *descr= RNA_struct_ui_description(ptr->type);
1576
1577                 PyObject *args = PyTuple_New(3);
1578                 PyObject *bases = PyTuple_New(1);
1579                 PyObject *dict = PyDict_New();
1580                 PyObject *item;
1581                 
1582                 
1583                 nameptr= RNA_property_string_get_alloc(ptr, nameprop, name, sizeof(name));
1584                 
1585                 // arg 1
1586                 //PyTuple_SET_ITEM(args, 0, PyUnicode_FromString(tp_name));
1587                 PyTuple_SET_ITEM(args, 0, PyUnicode_FromString(nameptr));
1588                 
1589                 // arg 2
1590                 PyTuple_SET_ITEM(bases, 0, (PyObject *)&pyrna_struct_Type);
1591                 Py_INCREF(&pyrna_struct_Type);
1592
1593                 PyTuple_SET_ITEM(args, 1, bases);
1594                 
1595                 // arg 3 - add an instance of the rna 
1596                 if(descr) {
1597                         item= PyUnicode_FromString(descr);
1598                         PyDict_SetItemString(dict, "__doc__", item);
1599                         Py_DECREF(item);
1600                 }
1601                 
1602                 PyTuple_SET_ITEM(args, 2, dict); // fill with useful subclass things!
1603                 
1604                 if (PyErr_Occurred()) {
1605                         PyErr_Print();
1606                         PyErr_Clear();
1607                 }
1608                 
1609                 newclass = PyObject_CallObject((PyObject *)&PyType_Type, args);
1610                 Py_DECREF(args);
1611
1612                 if (newclass)
1613                         pyrna_subtype_set_rna(newclass, ptr->data);
1614                 
1615                 if (name != nameptr)
1616                         MEM_freeN(nameptr);
1617         }
1618         
1619         return newclass;
1620 }
1621
1622 /*-----------------------CreatePyObject---------------------------------*/
1623 PyObject *pyrna_struct_CreatePyObject( PointerRNA *ptr )
1624 {
1625         BPy_StructRNA *pyrna= NULL;
1626         
1627         if (ptr->data==NULL && ptr->type==NULL) { /* Operator RNA has NULL data */
1628                 Py_RETURN_NONE;
1629         }
1630         
1631         if (ptr->type == &RNA_Struct) { /* always return a python subtype from rna struct types */
1632                 PyTypeObject *tp = (PyTypeObject *)pyrna_struct_Subtype(ptr);
1633                 
1634                 if (tp) {
1635                         pyrna = (BPy_StructRNA *) tp->tp_alloc(tp, 0);
1636                 }
1637                 else {
1638                         fprintf(stderr, "Could not make type\n");
1639                         pyrna = ( BPy_StructRNA * ) PyObject_NEW( BPy_StructRNA, &pyrna_struct_Type );
1640                 }
1641         }
1642         else {
1643                 pyrna = ( BPy_StructRNA * ) PyObject_NEW( BPy_StructRNA, &pyrna_struct_Type );
1644         }
1645         
1646         if( !pyrna ) {
1647                 PyErr_SetString( PyExc_MemoryError, "couldn't create BPy_StructRNA object" );
1648                 return NULL;
1649         }
1650         
1651         pyrna->ptr= *ptr;
1652         pyrna->freeptr= 0;
1653         return ( PyObject * ) pyrna;
1654 }
1655
1656 PyObject *pyrna_prop_CreatePyObject( PointerRNA *ptr, PropertyRNA *prop )
1657 {
1658         BPy_PropertyRNA *pyrna;
1659
1660         pyrna = ( BPy_PropertyRNA * ) PyObject_NEW( BPy_PropertyRNA, &pyrna_prop_Type );
1661
1662         if( !pyrna ) {
1663                 PyErr_SetString( PyExc_MemoryError, "couldn't create BPy_rna object" );
1664                 return NULL;
1665         }
1666         
1667         pyrna->ptr = *ptr;
1668         pyrna->prop = prop;
1669                 
1670         return ( PyObject * ) pyrna;
1671 }
1672
1673 PyObject *BPY_rna_module( void )
1674 {
1675         PointerRNA ptr;
1676         
1677         /* This can't be set in the pytype struct because some compilers complain */
1678         pyrna_prop_Type.tp_getattro = PyObject_GenericGetAttr; 
1679         pyrna_prop_Type.tp_setattro = PyObject_GenericSetAttr; 
1680         
1681         if( PyType_Ready( &pyrna_struct_Type ) < 0 )
1682                 return NULL;
1683         
1684         if( PyType_Ready( &pyrna_prop_Type ) < 0 )
1685                 return NULL;
1686
1687         /* for now, return the base RNA type rather then a real module */
1688         RNA_main_pointer_create(G.main, &ptr);
1689         
1690         return pyrna_struct_CreatePyObject(&ptr);
1691 }
1692
1693 #if 0
1694 /* This is a way we can access docstrings for RNA types
1695  * without having the datatypes in blender */
1696 PyObject *BPY_rna_doc( void )
1697 {
1698         PointerRNA ptr;
1699         
1700         /* for now, return the base RNA type rather then a real module */
1701         RNA_blender_rna_pointer_create(&ptr);
1702         
1703         return pyrna_struct_CreatePyObject(&ptr);
1704 }
1705 #endif
1706
1707
1708 /* pyrna_basetype_* - BPy_BaseTypeRNA is just a BPy_PropertyRNA struct with a differnt type
1709  * the self->ptr and self->prop are always set to the "structs" collection */
1710 //---------------getattr--------------------------------------------
1711 static PyObject *pyrna_basetype_getattro( BPy_BaseTypeRNA * self, PyObject *pyname )
1712 {
1713         PointerRNA newptr;
1714         PyObject *ret;
1715         
1716         ret = PyObject_GenericGetAttr((PyObject *)self, pyname);
1717         if (ret)        return ret;
1718         else            PyErr_Clear();
1719         
1720         if (RNA_property_collection_lookup_string(&self->ptr, self->prop, _PyUnicode_AsString(pyname), &newptr)) {
1721                 ret= pyrna_struct_Subtype(&newptr);
1722                 if (ret==NULL) {
1723                         PyErr_Format(PyExc_SystemError, "bpy.types.%s subtype could not be generated, this is a bug!", _PyUnicode_AsString(pyname));
1724                 }
1725                 return ret;
1726         }
1727         else { /* Override the error */
1728                 PyErr_Format(PyExc_AttributeError, "bpy.types.%s not a valid RNA_Struct", _PyUnicode_AsString(pyname));
1729                 return NULL;
1730         }
1731 }
1732
1733 static PyObject *pyrna_basetype_dir(BPy_BaseTypeRNA *self);
1734 static struct PyMethodDef pyrna_basetype_methods[] = {
1735         {"__dir__", (PyCFunction)pyrna_basetype_dir, METH_NOARGS, ""},
1736         {"register", (PyCFunction)pyrna_basetype_register, METH_VARARGS, ""},
1737         {"unregister", (PyCFunction)pyrna_basetype_unregister, METH_VARARGS, ""},
1738         {NULL, NULL, 0, NULL}
1739 };
1740
1741 static PyObject *pyrna_basetype_dir(BPy_BaseTypeRNA *self)
1742 {
1743         PyObject *list, *name;
1744         PyMethodDef *meth;
1745         
1746         list= pyrna_prop_keys(self); /* like calling structs.keys(), avoids looping here */
1747
1748         for(meth=pyrna_basetype_methods; meth->ml_name; meth++) {
1749                 name = PyUnicode_FromString(meth->ml_name);
1750                 PyList_Append(list, name);
1751                 Py_DECREF(name);
1752         }
1753         
1754         return list;
1755 }
1756
1757 PyTypeObject pyrna_basetype_Type = BLANK_PYTHON_TYPE;
1758
1759 PyObject *BPY_rna_types(void)
1760 {
1761         BPy_BaseTypeRNA *self;
1762
1763         if ((pyrna_basetype_Type.tp_flags & Py_TPFLAGS_READY)==0)  {
1764                 pyrna_basetype_Type.tp_name = "RNA_Types";
1765                 pyrna_basetype_Type.tp_basicsize = sizeof( BPy_BaseTypeRNA );
1766                 pyrna_basetype_Type.tp_getattro = ( getattrofunc )pyrna_basetype_getattro;
1767                 pyrna_basetype_Type.tp_flags = Py_TPFLAGS_DEFAULT;
1768                 pyrna_basetype_Type.tp_methods = pyrna_basetype_methods;
1769                 
1770                 if( PyType_Ready( &pyrna_basetype_Type ) < 0 )
1771                         return NULL;
1772         }
1773         
1774         self= (BPy_BaseTypeRNA *)PyObject_NEW( BPy_BaseTypeRNA, &pyrna_basetype_Type );
1775         
1776         /* avoid doing this lookup for every getattr */
1777         RNA_blender_rna_pointer_create(&self->ptr);
1778         self->prop = RNA_struct_find_property(&self->ptr, "structs");
1779         
1780         return (PyObject *)self;
1781 }
1782
1783 static struct PyMethodDef props_methods[] = {
1784         {"FloatProperty", (PyCFunction)BPy_FloatProperty, METH_VARARGS|METH_KEYWORDS, ""},
1785         {"IntProperty", (PyCFunction)BPy_IntProperty, METH_VARARGS|METH_KEYWORDS, ""},
1786         {"BoolProperty", (PyCFunction)BPy_BoolProperty, METH_VARARGS|METH_KEYWORDS, ""},
1787         {"StringProperty", (PyCFunction)BPy_StringProperty, METH_VARARGS|METH_KEYWORDS, ""},
1788         {NULL, NULL, 0, NULL}
1789 };
1790
1791 #if PY_VERSION_HEX >= 0x03000000
1792 static struct PyModuleDef props_module = {
1793         PyModuleDef_HEAD_INIT,
1794         "bpyprops",
1795         "",
1796         -1,/* multiple "initialization" just copies the module dict. */
1797         props_methods,
1798         NULL, NULL, NULL, NULL
1799 };
1800 #endif
1801
1802 PyObject *BPY_rna_props( void )
1803 {
1804         PyObject *submodule, *mod;
1805 #if PY_VERSION_HEX >= 0x03000000
1806         submodule= PyModule_Create(&props_module);
1807 #else /* Py2.x */
1808         submodule= Py_InitModule3( "bpy.props", props_methods, "" );
1809 #endif
1810         
1811         mod = PyModule_New("props");
1812         PyModule_AddObject( submodule, "props", mod );
1813         
1814         /* INCREF since its its assumed that all these functions return the
1815          * module with a new ref like PyDict_New, since they are passed to
1816           * PyModule_AddObject which steals a ref */
1817         Py_INCREF(submodule);
1818         
1819         return submodule;
1820 }
1821
1822 /* Orphan functions, not sure where they should go */
1823
1824 /* Function that sets RNA, NOTE - self is NULL when called from python, but being abused from C so we can pass the srna allong
1825  * This isnt incorrect since its a python object - but be careful */
1826 PyObject *BPy_FloatProperty(PyObject *self, PyObject *args, PyObject *kw)
1827 {
1828         static char *kwlist[] = {"attr", "name", "description", "min", "max", "soft_min", "soft_max", "default", NULL};
1829         char *id, *name="", *description="";
1830         float min=FLT_MIN, max=FLT_MAX, soft_min=FLT_MIN, soft_max=FLT_MAX, def=0.0f;
1831         
1832         if (!PyArg_ParseTupleAndKeywords(args, kw, "s|ssfffff:FloatProperty", kwlist, &id, &name, &description, &min, &max, &soft_min, &soft_max, &def))
1833                 return NULL;
1834         
1835         if (PyTuple_Size(args) > 0) {
1836                 PyErr_SetString(PyExc_ValueError, "all args must be keywors"); // TODO - py3 can enforce this.
1837                 return NULL;
1838         }
1839         
1840         if (self && PyCObject_Check(self)) {
1841                 StructRNA *srna = PyCObject_AsVoidPtr(self);
1842                 RNA_def_float(srna, id, def, min, max, name, description, soft_min, soft_max);
1843                 Py_RETURN_NONE;
1844         } else {
1845                 PyObject *ret = PyTuple_New(2);
1846                 PyTuple_SET_ITEM(ret, 0, PyCObject_FromVoidPtr((void *)BPy_FloatProperty, NULL));
1847                 PyTuple_SET_ITEM(ret, 1, kw);
1848                 Py_INCREF(kw);
1849                 return ret;
1850         }
1851 }
1852
1853 PyObject *BPy_IntProperty(PyObject *self, PyObject *args, PyObject *kw)
1854 {
1855         static char *kwlist[] = {"attr", "name", "description", "min", "max", "soft_min", "soft_max", "default", NULL};
1856         char *id, *name="", *description="";
1857         int min=INT_MIN, max=INT_MAX, soft_min=INT_MIN, soft_max=INT_MAX, def=0;
1858         
1859         if (!PyArg_ParseTupleAndKeywords(args, kw, "s|ssiiiii:IntProperty", kwlist, &id, &name, &description, &min, &max, &soft_min, &soft_max, &def))
1860                 return NULL;
1861         
1862         if (PyTuple_Size(args) > 0) {
1863                 PyErr_SetString(PyExc_ValueError, "all args must be keywors"); // TODO - py3 can enforce this.
1864                 return NULL;
1865         }
1866         
1867         if (self && PyCObject_Check(self)) {
1868                 StructRNA *srna = PyCObject_AsVoidPtr(self);
1869                 RNA_def_int(srna, id, def, min, max, name, description, soft_min, soft_max);
1870                 Py_RETURN_NONE;
1871         } else {
1872                 PyObject *ret = PyTuple_New(2);
1873                 PyTuple_SET_ITEM(ret, 0, PyCObject_FromVoidPtr((void *)BPy_IntProperty, NULL));
1874                 PyTuple_SET_ITEM(ret, 1, kw);
1875                 Py_INCREF(kw);
1876                 return ret;
1877         }
1878 }
1879
1880 PyObject *BPy_BoolProperty(PyObject *self, PyObject *args, PyObject *kw)
1881 {
1882         static char *kwlist[] = {"attr", "name", "description", "default", NULL};
1883         char *id, *name="", *description="";
1884         int def=0;
1885         
1886         if (!PyArg_ParseTupleAndKeywords(args, kw, "s|ssi:IntProperty", kwlist, &id, &name, &description, &def))
1887                 return NULL;
1888         
1889         if (PyTuple_Size(args) > 0) {
1890                 PyErr_SetString(PyExc_ValueError, "all args must be keywors"); // TODO - py3 can enforce this.
1891                 return NULL;
1892         }
1893         
1894         if (self && PyCObject_Check(self)) {
1895                 StructRNA *srna = PyCObject_AsVoidPtr(self);
1896                 RNA_def_boolean(srna, id, def, name, description);
1897                 Py_RETURN_NONE;
1898         } else {
1899                 PyObject *ret = PyTuple_New(2);
1900                 PyTuple_SET_ITEM(ret, 0, PyCObject_FromVoidPtr((void *)BPy_IntProperty, NULL));
1901                 PyTuple_SET_ITEM(ret, 1, kw);
1902                 Py_INCREF(kw);
1903                 return ret;
1904         }
1905 }
1906
1907 PyObject *BPy_StringProperty(PyObject *self, PyObject *args, PyObject *kw)
1908 {
1909         static char *kwlist[] = {"attr", "name", "description", "maxlen", "default", NULL};
1910         char *id, *name="", *description="", *def="";
1911         int maxlen=0;
1912         
1913         if (!PyArg_ParseTupleAndKeywords(args, kw, "s|ssis:StringProperty", kwlist, &id, &name, &description, &maxlen, &def))
1914                 return NULL;
1915         
1916         if (PyTuple_Size(args) > 0) {
1917                 PyErr_SetString(PyExc_ValueError, "all args must be keywors"); // TODO - py3 can enforce this.
1918                 return NULL;
1919         }
1920         
1921         if (self && PyCObject_Check(self)) {
1922                 StructRNA *srna = PyCObject_AsVoidPtr(self);
1923                 RNA_def_string(srna, id, def, maxlen, name, description);
1924                 Py_RETURN_NONE;
1925         } else {
1926                 PyObject *ret = PyTuple_New(2);
1927                 PyTuple_SET_ITEM(ret, 0, PyCObject_FromVoidPtr((void *)BPy_StringProperty, NULL));
1928                 PyTuple_SET_ITEM(ret, 1, kw);
1929                 Py_INCREF(kw);
1930                 return ret;
1931         }
1932 }
1933
1934 /*-------------------- Type Registration ------------------------*/
1935
1936 static int rna_function_arg_count(FunctionRNA *func)
1937 {
1938         const ListBase *lb= RNA_function_defined_parameters(func);
1939         PropertyRNA *parm;
1940         Link *link;
1941         int count= 1;
1942
1943         for(link=lb->first; link; link=link->next) {
1944                 parm= (PropertyRNA*)link;
1945                 if(!(RNA_property_flag(parm) & PROP_RETURN))
1946                         count++;
1947         }
1948         
1949         return count;
1950 }
1951
1952 static int bpy_class_validate(PointerRNA *dummyptr, void *py_data, int *have_function)
1953 {
1954         const ListBase *lb;
1955         Link *link;
1956         FunctionRNA *func;
1957         PropertyRNA *prop;
1958         StructRNA *srna= dummyptr->type;
1959         const char *class_type= RNA_struct_identifier(srna);
1960         PyObject *py_class= (PyObject*)py_data;
1961         PyObject *base_class= RNA_struct_py_type_get(srna);
1962         PyObject *item, *fitem;
1963         PyObject *py_arg_count;
1964         int i, flag, arg_count, func_arg_count;
1965         char identifier[128];
1966
1967         if (base_class) {
1968                 if (!PyObject_IsSubclass(py_class, base_class)) {
1969                         PyObject *name= PyObject_GetAttrString(base_class, "__name__");
1970                         PyErr_Format( PyExc_AttributeError, "expected %s subclass of class \"%s\"", class_type, name ? _PyUnicode_AsString(name):"<UNKNOWN>");
1971                         Py_XDECREF(name);
1972                         return -1;
1973                 }
1974         }
1975
1976         /* verify callback functions */
1977         lb= RNA_struct_defined_functions(srna);
1978         i= 0;
1979         for(link=lb->first; link; link=link->next) {
1980                 func= (FunctionRNA*)link;
1981                 flag= RNA_function_flag(func);
1982
1983                 if(!(flag & FUNC_REGISTER))
1984                         continue;
1985
1986                 item = PyObject_GetAttrString(py_class, RNA_function_identifier(func));
1987
1988                 have_function[i]= (item != NULL);
1989                 i++;
1990
1991                 if (item==NULL) {
1992                         if ((flag & FUNC_REGISTER_OPTIONAL)==0) {
1993                                 PyErr_Format( PyExc_AttributeError, "expected %s class to have an \"%s\" attribute", class_type, RNA_function_identifier(func));
1994                                 return -1;
1995                         }
1996
1997                         PyErr_Clear();
1998                 }
1999                 else {
2000                         Py_DECREF(item); /* no need to keep a ref, the class owns it */
2001
2002                         if (PyMethod_Check(item))
2003                                 fitem= PyMethod_Function(item); /* py 2.x */
2004                         else
2005                                 fitem= item; /* py 3.x */
2006
2007                         if (PyFunction_Check(fitem)==0) {
2008                                 PyErr_Format( PyExc_AttributeError, "expected %s class \"%s\" attribute to be a function", class_type, RNA_function_identifier(func));
2009                                 return -1;
2010                         }
2011
2012                         func_arg_count= rna_function_arg_count(func);
2013
2014                         if (func_arg_count >= 0) { /* -1 if we dont care*/
2015                                 py_arg_count = PyObject_GetAttrString(PyFunction_GET_CODE(fitem), "co_argcount");
2016                                 arg_count = PyLong_AsSsize_t(py_arg_count);
2017                                 Py_DECREF(py_arg_count);
2018
2019                                 if (arg_count != func_arg_count) {
2020                                         PyErr_Format( PyExc_AttributeError, "expected %s class \"%s\" function to have %d args", class_type, RNA_function_identifier(func), func_arg_count);
2021                                         return -1;
2022                                 }
2023                         }
2024                 }
2025         }
2026
2027         /* verify properties */
2028         lb= RNA_struct_defined_properties(srna);
2029         for(link=lb->first; link; link=link->next) {
2030                 prop= (PropertyRNA*)link;
2031                 flag= RNA_property_flag(prop);
2032
2033                 if(!(flag & PROP_REGISTER))
2034                         continue;
2035
2036                 BLI_snprintf(identifier, sizeof(identifier), "__%s__", RNA_property_identifier(prop));
2037                 item = PyObject_GetAttrString(py_class, identifier);
2038
2039                 if (item==NULL) {
2040                         if(strcmp(identifier, "__idname__") == 0) {
2041                                 item= PyObject_GetAttrString(py_class, "__name__");
2042
2043                                 if(item) {
2044                                         Py_DECREF(item); /* no need to keep a ref, the class owns it */
2045
2046                                         if(pyrna_py_to_prop(dummyptr, prop, NULL, item) != 0)
2047                                                 return -1;
2048                                 }
2049                         }
2050
2051                         if (item==NULL && (flag & PROP_REGISTER_OPTIONAL)==0) {
2052                                 PyErr_Format( PyExc_AttributeError, "expected %s class to have an \"%s\" attribute", class_type, identifier);
2053                                 return -1;
2054                         }
2055
2056                         PyErr_Clear();
2057                 }
2058                 else {
2059                         Py_DECREF(item); /* no need to keep a ref, the class owns it */
2060
2061                         if(pyrna_py_to_prop(dummyptr, prop, NULL, item) != 0)
2062                                 return -1;
2063                 }
2064         }
2065
2066         return 0;
2067 }
2068
2069 extern void BPY_update_modules( void ); //XXX temp solution
2070
2071 static int bpy_class_call(PointerRNA *ptr, FunctionRNA *func, ParameterList *parms)
2072 {
2073         PyObject *args;
2074         PyObject *ret= NULL, *py_class, *py_class_instance, *item, *parmitem;
2075         PropertyRNA *pret= NULL, *parm;
2076         ParameterIterator iter;
2077         PointerRNA funcptr;
2078         void *retdata= NULL;
2079         int err= 0, i, flag;
2080
2081         PyGILState_STATE gilstate = PyGILState_Ensure();
2082
2083         BPY_update_modules(); // XXX - the RNA pointers can change so update before running, would like a nicer solution for this.
2084
2085         py_class= RNA_struct_py_type_get(ptr->type);
2086         
2087         item = pyrna_struct_CreatePyObject(ptr);
2088         if(item == NULL) {
2089                 py_class_instance = NULL;
2090         }
2091         else if(item == Py_None) { /* probably wont ever happen but possible */
2092                 Py_DECREF(item);
2093                 py_class_instance = NULL;
2094         }
2095         else {
2096                 args = PyTuple_New(1);
2097                 PyTuple_SET_ITEM(args, 0, item);
2098                 py_class_instance = PyObject_Call(py_class, args, NULL);
2099                 Py_DECREF(args);
2100         }
2101
2102         if (py_class_instance) { /* Initializing the class worked, now run its invoke function */
2103                 item= PyObject_GetAttrString(py_class, RNA_function_identifier(func));
2104                 flag= RNA_function_flag(func);
2105
2106                 if(item) {
2107                         pret= RNA_function_return(func);
2108                         RNA_pointer_create(NULL, &RNA_Function, func, &funcptr);
2109
2110                         args = PyTuple_New(rna_function_arg_count(func));
2111                         PyTuple_SET_ITEM(args, 0, py_class_instance);
2112
2113                         RNA_parameter_list_begin(parms, &iter);
2114
2115                         /* parse function parameters */
2116                         for (i= 1; iter.valid; RNA_parameter_list_next(&iter)) {
2117                                 parm= iter.parm;
2118
2119                                 if (parm==pret) {
2120                                         retdata= iter.data;
2121                                         continue;
2122                                 }
2123
2124                                 parmitem= pyrna_param_to_py(&funcptr, parm, iter.data);
2125                                 PyTuple_SET_ITEM(args, i, parmitem);
2126                                 i++;
2127                         }
2128
2129                         ret = PyObject_Call(item, args, NULL);
2130
2131                         Py_DECREF(item);
2132                         Py_DECREF(args);
2133                 }
2134                 else {
2135                         Py_DECREF(py_class_instance);
2136                         PyErr_Format(PyExc_AttributeError, "could not find function %s in %s to execute callback.", RNA_function_identifier(func), RNA_struct_identifier(ptr->type));
2137                         err= -1;
2138                 }
2139         }
2140         else {
2141                 PyErr_Format(PyExc_AttributeError, "could not create instance of %s to call callback function %s.", RNA_struct_identifier(ptr->type), RNA_function_identifier(func));
2142                 err= -1;
2143         }
2144
2145         if (ret == NULL) { /* covers py_class_instance failing too */
2146                 PyErr_Print(); /* XXX use reporting api? */
2147                 err= -1;
2148         }
2149         else {
2150                 if(retdata)
2151                         err= pyrna_py_to_prop(&funcptr, pret, retdata, ret);
2152                 Py_DECREF(ret);
2153         }
2154
2155         PyGILState_Release(gilstate);
2156         
2157         return err;
2158 }
2159
2160 static void bpy_class_free(void *pyob_ptr)
2161 {
2162         if(G.f&G_DEBUG) {
2163                 if(((PyObject *)pyob_ptr)->ob_refcnt > 1)
2164                         PyObSpit("zombie class - ref should be 1", (PyObject *)pyob_ptr);
2165         }
2166         Py_DECREF((PyObject *)pyob_ptr);
2167 }
2168
2169 PyObject *pyrna_basetype_register(PyObject *self, PyObject *args)
2170 {
2171         bContext *C= NULL;
2172         PyObject *py_class, *item;
2173         ReportList reports;
2174         StructRegisterFunc reg;
2175         BPy_StructRNA *py_srna;
2176         StructRNA *srna;
2177
2178         if(!PyArg_ParseTuple(args, "O:register", &py_class))
2179                 return NULL;
2180         
2181         if(!PyType_Check(py_class)) {
2182                 PyErr_SetString(PyExc_AttributeError, "expected a Type subclassed from a registerable rna type (no a Type object).");
2183                 return NULL;
2184         }
2185
2186         /* check we got an __rna__ attribute */
2187         item= PyObject_GetAttrString(py_class, "__rna__");
2188
2189         if(!item || !BPy_StructRNA_Check(item)) {
2190                 Py_XDECREF(item);
2191                 PyErr_SetString(PyExc_AttributeError, "expected a Type subclassed from a registerable rna type (no __rna__ property).");
2192                 return NULL;
2193         }
2194
2195         /* check the __rna__ attribute has the right type */
2196         Py_DECREF(item);
2197         py_srna= (BPy_StructRNA*)item;
2198
2199         if(py_srna->ptr.type != &RNA_Struct) {
2200                 PyErr_SetString(PyExc_AttributeError, "expected a Type subclassed from a registerable rna type (not a Struct).");
2201                 return NULL;
2202         }
2203         
2204         /* check that we have a register callback for this type */
2205         reg= RNA_struct_register(py_srna->ptr.data);
2206
2207         if(!reg) {
2208                 PyErr_SetString(PyExc_AttributeError, "expected a Type subclassed from a registerable rna type (no register supported).");
2209                 return NULL;
2210         }
2211         
2212         /* get the context, so register callback can do necessary refreshes */
2213         C= BPy_GetContext();
2214
2215         /* call the register callback */
2216         BKE_reports_init(&reports, RPT_STORE);
2217         srna= reg(C, &reports, py_class, bpy_class_validate, bpy_class_call, bpy_class_free);
2218
2219         if(!srna) {
2220                 BPy_reports_to_error(&reports);
2221                 BKE_reports_clear(&reports);
2222                 return NULL;
2223         }
2224
2225         BKE_reports_clear(&reports);
2226
2227         pyrna_subtype_set_rna(py_class, srna); /* takes a ref to py_class */
2228
2229         Py_RETURN_NONE;
2230 }
2231
2232 PyObject *pyrna_basetype_unregister(PyObject *self, PyObject *args)
2233 {
2234         bContext *C= NULL;
2235         PyObject *py_class, *item;
2236         BPy_StructRNA *py_srna;
2237         StructUnregisterFunc unreg;
2238
2239         if(!PyArg_ParseTuple(args, "O:unregister", &py_class))
2240                 return NULL;
2241
2242         if(!PyType_Check(py_class)) {
2243                 PyErr_SetString(PyExc_AttributeError, "expected a Type subclassed from a registerable rna type (no a Type object).");
2244                 return NULL;
2245         }
2246
2247         /* check we got an __rna__ attribute */
2248         item= PyDict_GetItemString(((PyTypeObject*)py_class)->tp_dict, "__rna__");  /* borrow ref */
2249
2250         if(!item || !BPy_StructRNA_Check(item)) {
2251                 PyErr_SetString(PyExc_AttributeError, "expected a Type subclassed from a registerable rna type (no __rna__ property).");
2252                 return NULL;
2253         }
2254
2255         /* check the __rna__ attribute has the right type */
2256         py_srna= (BPy_StructRNA*)item;
2257
2258         if(py_srna->ptr.type != &RNA_Struct) {
2259                 PyErr_SetString(PyExc_AttributeError, "expected a Type subclassed from a registerable rna type (not a Struct).");
2260                 return NULL;
2261         }
2262         
2263         /* check that we have a unregister callback for this type */
2264         unreg= RNA_struct_unregister(py_srna->ptr.data);
2265
2266         if(!unreg) {
2267                 PyErr_SetString(PyExc_AttributeError, "expected a Type subclassed from a registerable rna type (no unregister supported).");
2268                 return NULL;
2269         }
2270         
2271         /* get the context, so register callback can do necessary refreshes */
2272         C= BPy_GetContext();
2273         
2274
2275         /* call unregister */
2276         unreg(C, py_srna->ptr.data);
2277
2278         /* remove reference to old type */
2279         Py_DECREF(py_class);
2280
2281         Py_RETURN_NONE;
2282 }
2283