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