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