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