python access to RNA arrays.
[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 static void foreach_attr_type(  BPy_PropertyRNA *self, char *attr,
1229                                                                         /* values to assign */
1230                                                                         RawPropertyType *raw_type, int *attr_tot, int *attr_signed )
1231 {
1232         PropertyRNA *prop;
1233         *raw_type= -1;
1234         *attr_tot= 0;
1235         *attr_signed= 0;
1236
1237         RNA_PROP_BEGIN(&self->ptr, itemptr, self->prop) {
1238                 prop = RNA_struct_find_property(&itemptr, attr);
1239                 *raw_type= RNA_property_raw_type(prop);
1240                 *attr_tot = RNA_property_array_length(prop);
1241                 *attr_signed= (RNA_property_subtype(prop)==PROP_UNSIGNED) ? 0:1;
1242                 break;
1243         }
1244         RNA_PROP_END;
1245 }
1246
1247 /* pyrna_prop_foreach_get/set both use this */
1248 static int foreach_parse_args(
1249                 BPy_PropertyRNA *self, PyObject *args,
1250
1251                 /*values to assign */
1252                 char **attr, PyObject **seq, int *tot, int *size, RawPropertyType *raw_type, int *attr_tot, int *attr_signed)
1253 {
1254         int array_tot;
1255         int target_tot;
1256
1257         *size= *raw_type= *attr_tot= *attr_signed= 0;
1258
1259         if(!PyArg_ParseTuple(args, "sO", attr, seq) || (!PySequence_Check(*seq) && PyObject_CheckBuffer(*seq))) {
1260                 PyErr_SetString( PyExc_TypeError, "foreach_get(attr, sequence) expects a string and a sequence" );
1261                 return -1;
1262         }
1263
1264         *tot= PySequence_Length(*seq); // TODO - buffer may not be a sequence! array.array() is tho.
1265
1266         if(*tot>0) {
1267                 foreach_attr_type(self, *attr, raw_type, attr_tot, attr_signed);
1268                 *size= RNA_raw_type_sizeof(*raw_type);
1269
1270 #if 0   // works fine but not strictly needed, we could allow RNA_property_collection_raw_* to do the checks
1271                 if((*attr_tot) < 1)
1272                         *attr_tot= 1;
1273
1274                 if (RNA_property_type(self->prop) == PROP_COLLECTION)
1275                         array_tot = RNA_property_collection_length(&self->ptr, self->prop);
1276                 else
1277                         array_tot = RNA_property_array_length(self->prop);
1278
1279
1280                 target_tot= array_tot * (*attr_tot);
1281
1282                 /* rna_access.c - rna_raw_access(...) uses this same method */
1283                 if(target_tot != (*tot)) {
1284                         PyErr_Format( PyExc_TypeError, "foreach_get(attr, sequence) sequence length mismatch given %d, needed %d", *tot, target_tot);
1285                         return -1;
1286                 }
1287 #endif
1288         }
1289
1290         return 0;
1291 }
1292
1293 static int foreach_compat_buffer(RawPropertyType raw_type, int attr_signed, const char *format)
1294 {
1295         char f = format ? *format:'B'; /* B is assumed when not set */
1296
1297         switch(raw_type) {
1298         case PROP_RAW_CHAR:
1299                 if (attr_signed)        return (f=='b') ? 1:0;
1300                 else                            return (f=='B') ? 1:0;
1301         case PROP_RAW_SHORT:
1302                 if (attr_signed)        return (f=='h') ? 1:0;
1303                 else                            return (f=='H') ? 1:0;
1304         case PROP_RAW_INT:
1305                 if (attr_signed)        return (f=='i') ? 1:0;
1306                 else                            return (f=='I') ? 1:0;
1307         case PROP_RAW_FLOAT:
1308                 return (f=='f') ? 1:0;
1309         case PROP_RAW_DOUBLE:
1310                 return (f=='d') ? 1:0;
1311         }
1312
1313         return 0;
1314 }
1315
1316 static PyObject *foreach_getset(BPy_PropertyRNA *self, PyObject *args, int set)
1317 {
1318         PyObject *item;
1319         int i=0, ok, buffer_is_compat;
1320         void *array= NULL;
1321
1322         /* get/set both take the same args currently */
1323         char *attr;
1324         PyObject *seq;
1325         int tot, size, attr_tot, attr_signed;
1326         RawPropertyType raw_type;
1327
1328         if(foreach_parse_args(self, args,    &attr, &seq, &tot, &size, &raw_type, &attr_tot, &attr_signed) < 0)
1329                 return NULL;
1330
1331         if(tot==0)
1332                 Py_RETURN_NONE;
1333
1334
1335
1336         if(set) { /* get the array from python */
1337                 buffer_is_compat = 0;
1338                 if(PyObject_CheckBuffer(seq)) {
1339                         Py_buffer buf;
1340                         PyObject_GetBuffer(seq, &buf, PyBUF_SIMPLE | PyBUF_FORMAT);
1341
1342                         /* check if the buffer matches, TODO - signed/unsigned types */
1343
1344                         buffer_is_compat = foreach_compat_buffer(raw_type, attr_signed, buf.format);
1345
1346                         if(buffer_is_compat) {
1347                                 ok = RNA_property_collection_raw_set(NULL, &self->ptr, self->prop, attr, buf.buf, raw_type, tot);
1348                         }
1349
1350                         PyBuffer_Release(&buf);
1351                 }
1352
1353                 /* could not use the buffer, fallback to sequence */
1354                 if(!buffer_is_compat) {
1355                         array= PyMem_Malloc(size * tot);
1356
1357                         for( ; i<tot; i++) {
1358                                 item= PySequence_GetItem(seq, i);
1359                                 switch(raw_type) {
1360                                 case PROP_RAW_CHAR:
1361                                         ((char *)array)[i]= (char)PyLong_AsSsize_t(item);
1362                                         break;
1363                                 case PROP_RAW_SHORT:
1364                                         ((short *)array)[i]= (short)PyLong_AsSsize_t(item);
1365                                         break;
1366                                 case PROP_RAW_INT:
1367                                         ((int *)array)[i]= (int)PyLong_AsSsize_t(item);
1368                                         break;
1369                                 case PROP_RAW_FLOAT:
1370                                         ((float *)array)[i]= (float)PyFloat_AsDouble(item);
1371                                         break;
1372                                 case PROP_RAW_DOUBLE:
1373                                         ((double *)array)[i]= (double)PyFloat_AsDouble(item);
1374                                         break;
1375                                 }
1376
1377                                 Py_DECREF(item);
1378                         }
1379
1380                         ok = RNA_property_collection_raw_set(NULL, &self->ptr, self->prop, attr, array, raw_type, tot);
1381                 }
1382         }
1383         else {
1384                 buffer_is_compat = 0;
1385                 if(PyObject_CheckBuffer(seq)) {
1386                         Py_buffer buf;
1387                         PyObject_GetBuffer(seq, &buf, PyBUF_SIMPLE | PyBUF_FORMAT);
1388
1389                         /* check if the buffer matches, TODO - signed/unsigned types */
1390
1391                         buffer_is_compat = foreach_compat_buffer(raw_type, attr_signed, buf.format);
1392
1393                         if(buffer_is_compat) {
1394                                 ok = RNA_property_collection_raw_get(NULL, &self->ptr, self->prop, attr, buf.buf, raw_type, tot);
1395                         }
1396
1397                         PyBuffer_Release(&buf);
1398                 }
1399
1400                 /* could not use the buffer, fallback to sequence */
1401                 if(!buffer_is_compat) {
1402                         array= PyMem_Malloc(size * tot);
1403
1404                         ok = RNA_property_collection_raw_get(NULL, &self->ptr, self->prop, attr, array, raw_type, tot);
1405
1406                         if(!ok) i= tot; /* skip the loop */
1407
1408                         for( ; i<tot; i++) {
1409
1410                                 switch(raw_type) {
1411                                 case PROP_RAW_CHAR:
1412                                         item= PyLong_FromSsize_t(  (Py_ssize_t) ((char *)array)[i]  );
1413                                         break;
1414                                 case PROP_RAW_SHORT:
1415                                         item= PyLong_FromSsize_t(  (Py_ssize_t) ((short *)array)[i]  );
1416                                         break;
1417                                 case PROP_RAW_INT:
1418                                         item= PyLong_FromSsize_t(  (Py_ssize_t) ((int *)array)[i]  );
1419                                         break;
1420                                 case PROP_RAW_FLOAT:
1421                                         item= PyFloat_FromDouble(  (double) ((float *)array)[i]  );
1422                                         break;
1423                                 case PROP_RAW_DOUBLE:
1424                                         item= PyFloat_FromDouble(  (double) ((double *)array)[i]  );
1425                                         break;
1426                                 }
1427
1428                                 PySequence_SetItem(seq, i, item);
1429                                 Py_DECREF(item);
1430                         }
1431                 }
1432         }
1433
1434         if(PyErr_Occurred()) {
1435                 /* Maybe we could make our own error */
1436                 PyErr_Print();
1437                 PyErr_SetString(PyExc_SystemError, "could not access the py sequence");
1438                 return NULL;
1439         }
1440         if (!ok) {
1441                 PyErr_SetString(PyExc_SystemError, "internal error setting the array");
1442                 return NULL;
1443         }
1444
1445         if(array)
1446                 PyMem_Free(array);
1447
1448         Py_RETURN_NONE;
1449 }
1450
1451 static PyObject *pyrna_prop_foreach_get(BPy_PropertyRNA *self, PyObject *args)
1452 {
1453         return foreach_getset(self, args, 0);
1454 }
1455
1456 static  PyObject *pyrna_prop_foreach_set(BPy_PropertyRNA *self, PyObject *args)
1457 {
1458         return foreach_getset(self, args, 1);
1459 }
1460
1461
1462 /* A bit of a kludge, make a list out of a collection or array,
1463  * then return the lists iter function, not especially fast but convenient for now */
1464 PyObject *pyrna_prop_iter(BPy_PropertyRNA *self)
1465 {
1466         /* Try get values from a collection */
1467         PyObject *ret = pyrna_prop_values(self);
1468         
1469         if (ret==NULL) {
1470                 /* collection did not work, try array */
1471                 int len = RNA_property_array_length(self->prop);
1472                 
1473                 if (len) {
1474                         int i;
1475                         PyErr_Clear();
1476                         ret = PyList_New(len);
1477                         
1478                         for (i=0; i < len; i++) {
1479                                 PyList_SET_ITEM(ret, i, pyrna_prop_to_py_index(&self->ptr, self->prop, i));
1480                         }
1481                 }
1482         }
1483         
1484         if (ret) {
1485                 /* we know this is a list so no need to PyIter_Check */
1486                 PyObject *iter = PyObject_GetIter(ret); 
1487                 Py_DECREF(ret);
1488                 return iter;
1489         }
1490         
1491         PyErr_SetString( PyExc_TypeError, "this BPy_PropertyRNA object is not iterable" );
1492         return NULL;
1493 }
1494
1495 static struct PyMethodDef pyrna_struct_methods[] = {
1496         {"__dir__", (PyCFunction)pyrna_struct_dir, METH_NOARGS, NULL},
1497         {NULL, NULL, 0, NULL}
1498 };
1499
1500 static struct PyMethodDef pyrna_prop_methods[] = {
1501         {"keys", (PyCFunction)pyrna_prop_keys, METH_NOARGS, NULL},
1502         {"items", (PyCFunction)pyrna_prop_items, METH_NOARGS,NULL},
1503         {"values", (PyCFunction)pyrna_prop_values, METH_NOARGS, NULL},
1504
1505         /* array accessor function */
1506         {"foreach_get", (PyCFunction)pyrna_prop_foreach_get, METH_VARARGS, NULL},
1507         {"foreach_set", (PyCFunction)pyrna_prop_foreach_set, METH_VARARGS, NULL},
1508         {NULL, NULL, 0, NULL}
1509 };
1510
1511 /* only needed for subtyping, so a new class gets a valid BPy_StructRNA
1512  * todo - also accept useful args */
1513 static PyObject * pyrna_struct_new(PyTypeObject *type, PyObject *args, PyObject *kwds) {
1514
1515         BPy_StructRNA *base = NULL;
1516         
1517         if (!PyArg_ParseTuple(args, "O!:Base BPy_StructRNA", &pyrna_struct_Type, &base))
1518                 return NULL;
1519         
1520         if (type == &pyrna_struct_Type) {
1521                 return pyrna_struct_CreatePyObject(&base->ptr);
1522         } else {
1523                 BPy_StructRNA *ret = (BPy_StructRNA *) type->tp_alloc(type, 0);
1524                 ret->ptr = base->ptr;
1525                 return (PyObject *)ret;
1526         }
1527 }
1528
1529 /* only needed for subtyping, so a new class gets a valid BPy_StructRNA
1530  * todo - also accept useful args */
1531 static PyObject * pyrna_prop_new(PyTypeObject *type, PyObject *args, PyObject *kwds) {
1532
1533         BPy_PropertyRNA *base = NULL;
1534         
1535         if (!PyArg_ParseTuple(args, "O!:Base BPy_PropertyRNA", &pyrna_prop_Type, &base))
1536                 return NULL;
1537         
1538         if (type == &pyrna_prop_Type) {
1539                 return pyrna_prop_CreatePyObject(&base->ptr, base->prop);
1540         } else {
1541                 BPy_PropertyRNA *ret = (BPy_PropertyRNA *) type->tp_alloc(type, 0);
1542                 ret->ptr = base->ptr;
1543                 ret->prop = base->prop;
1544                 return (PyObject *)ret;
1545         }
1546 }
1547
1548 PyObject *pyrna_param_to_py(PointerRNA *ptr, PropertyRNA *prop, void *data)
1549 {
1550         PyObject *ret;
1551         int type = RNA_property_type(prop);
1552         int len = RNA_property_array_length(prop);
1553
1554         int a;
1555
1556         if(len > 0) {
1557                 /* resolve the array from a new pytype */
1558                 ret = PyTuple_New(len);
1559
1560                 switch (type) {
1561                 case PROP_BOOLEAN:
1562                         for(a=0; a<len; a++)
1563                                 PyTuple_SET_ITEM(ret, a, PyBool_FromLong( ((int*)data)[a] ));
1564                         break;
1565                 case PROP_INT:
1566                         for(a=0; a<len; a++)
1567                                 PyTuple_SET_ITEM(ret, a, PyLong_FromSsize_t( (Py_ssize_t)((int*)data)[a] ));
1568                         break;
1569                 case PROP_FLOAT:
1570                         for(a=0; a<len; a++)
1571                                 PyTuple_SET_ITEM(ret, a, PyFloat_FromDouble( ((float*)data)[a] ));
1572                         break;
1573                 default:
1574                         PyErr_Format(PyExc_AttributeError, "RNA Error: unknown array type \"%d\" (pyrna_param_to_py)", type);
1575                         ret = NULL;
1576                         break;
1577                 }
1578         }
1579         else {
1580                 /* see if we can coorce into a python type - PropertyType */
1581                 switch (type) {
1582                 case PROP_BOOLEAN:
1583                         ret = PyBool_FromLong( *(int*)data );
1584                         break;
1585                 case PROP_INT:
1586                         ret = PyLong_FromSsize_t( (Py_ssize_t)*(int*)data );
1587                         break;
1588                 case PROP_FLOAT:
1589                         ret = PyFloat_FromDouble( *(float*)data );
1590                         break;
1591                 case PROP_STRING:
1592                 {
1593                         ret = PyUnicode_FromString( *(char**)data );
1594                         break;
1595                 }
1596                 case PROP_ENUM:
1597                 {
1598                         const char *identifier;
1599                         int val = *(int*)data;
1600                         
1601                         if (RNA_property_enum_identifier(ptr, prop, val, &identifier)) {
1602                                 ret = PyUnicode_FromString( identifier );
1603                         } else {
1604                                 PyErr_Format(PyExc_AttributeError, "RNA Error: Current value \"%d\" matches no enum", val);
1605                                 ret = NULL;
1606                         }
1607
1608                         break;
1609                 }
1610                 case PROP_POINTER:
1611                 {
1612                         PointerRNA newptr;
1613                         StructRNA *type= RNA_property_pointer_type(ptr, prop);
1614                         int flag = RNA_property_flag(prop);
1615
1616                         if(flag & PROP_RNAPTR) {
1617                                 /* in this case we get the full ptr */
1618                                 newptr= *(PointerRNA*)data;
1619                         }
1620                         else {
1621                                 /* XXX this is missing the ID part! */
1622                                 RNA_pointer_create(NULL, type, *(void**)data, &newptr);
1623                         }
1624
1625                         if (newptr.data) {
1626                                 ret = pyrna_struct_CreatePyObject(&newptr);
1627                         } else {
1628                                 ret = Py_None;
1629                                 Py_INCREF(ret);
1630                         }
1631                         break;
1632                 }
1633                 case PROP_COLLECTION:
1634                 {
1635                         ListBase *lb= (ListBase*)data;
1636                         CollectionPointerLink *link;
1637                         PyObject *linkptr;
1638
1639                         ret = PyList_New(0);
1640
1641                         for(link=lb->first; link; link=link->next) {
1642                                 linkptr= pyrna_struct_CreatePyObject(&link->ptr);
1643                                 PyList_Append(ret, linkptr);
1644                                 Py_DECREF(linkptr);
1645                         }
1646
1647                         break;
1648                 }
1649                 default:
1650                         PyErr_Format(PyExc_AttributeError, "RNA Error: unknown type \"%d\" (pyrna_param_to_py)", type);
1651                         ret = NULL;
1652                         break;
1653                 }
1654         }
1655
1656         return ret;
1657 }
1658
1659 static PyObject * pyrna_func_call(PyObject * self, PyObject *args, PyObject *kw)
1660 {
1661         PointerRNA *self_ptr= &(((BPy_StructRNA *)PyTuple_GET_ITEM(self, 0))->ptr);
1662         FunctionRNA *self_func=  PyCObject_AsVoidPtr(PyTuple_GET_ITEM(self, 1));
1663
1664         PointerRNA funcptr;
1665         ParameterList *parms;
1666         ParameterIterator iter;
1667         PropertyRNA *pret, *parm;
1668         PyObject *ret, *item;
1669         int i, tlen, flag, err= 0;
1670         const char *tid, *fid, *pid;
1671         void *retdata= NULL;
1672
1673         /* setup */
1674         RNA_pointer_create(NULL, &RNA_Function, self_func, &funcptr);
1675
1676         pret= RNA_function_return(self_func);
1677         tlen= PyTuple_GET_SIZE(args);
1678
1679         parms= RNA_parameter_list_create(self_ptr, self_func);
1680         RNA_parameter_list_begin(parms, &iter);
1681
1682         /* parse function parameters */
1683         for (i= 0; iter.valid; RNA_parameter_list_next(&iter)) {
1684                 parm= iter.parm;
1685
1686                 if (parm==pret) {
1687                         retdata= iter.data;
1688                         continue;
1689                 }
1690
1691                 pid= RNA_property_identifier(parm);
1692                 flag= RNA_property_flag(parm);
1693                 item= NULL;
1694
1695                 if ((i < tlen) && (flag & PROP_REQUIRED)) {
1696                         item= PyTuple_GET_ITEM(args, i);
1697                         i++;
1698                 }
1699                 else if (kw != NULL)
1700                         item= PyDict_GetItemString(kw, pid);  /* borrow ref */
1701
1702                 if (item==NULL) {
1703                         if(flag & PROP_REQUIRED) {
1704                                 tid= RNA_struct_identifier(self_ptr->type);
1705                                 fid= RNA_function_identifier(self_func);
1706
1707                                 PyErr_Format(PyExc_AttributeError, "%s.%s(): required parameter \"%s\" not specified", tid, fid, pid);
1708                                 err= -1;
1709                                 break;
1710                         }
1711                         else
1712                                 continue;
1713                 }
1714
1715                 err= pyrna_py_to_prop(&funcptr, parm, iter.data, item);
1716
1717                 if(err!=0)
1718                         break;
1719         }
1720
1721         ret= NULL;
1722         if (err==0) {
1723                 /* call function */
1724                 ReportList reports;
1725                 bContext *C= BPy_GetContext();
1726
1727                 BKE_reports_init(&reports, RPT_STORE);
1728                 RNA_function_call(C, &reports, self_ptr, self_func, parms);
1729
1730                 err= (BPy_reports_to_error(&reports))? -1: 0;
1731                 BKE_reports_clear(&reports);
1732
1733                 /* return value */
1734                 if(err==0)
1735                         if(pret)
1736                                 ret= pyrna_param_to_py(&funcptr, pret, retdata);
1737         }
1738
1739         /* cleanup */
1740         RNA_parameter_list_end(&iter);
1741         RNA_parameter_list_free(parms);
1742
1743         if (ret)
1744                 return ret;
1745
1746         if (err==-1)
1747                 return NULL;
1748
1749         Py_RETURN_NONE;
1750 }
1751
1752 /*-----------------------BPy_StructRNA method def------------------------------*/
1753 PyTypeObject pyrna_struct_Type = {
1754 #if (PY_VERSION_HEX >= 0x02060000)
1755         PyVarObject_HEAD_INIT(NULL, 0)
1756 #else
1757         /* python 2.5 and below */
1758         PyObject_HEAD_INIT( NULL )  /* required py macro */
1759         0,                          /* ob_size */
1760 #endif
1761         "StructRNA",                    /* tp_name */
1762         sizeof( BPy_StructRNA ),        /* tp_basicsize */
1763         0,                      /* tp_itemsize */
1764         /* methods */
1765         ( destructor ) pyrna_struct_dealloc,/* tp_dealloc */
1766         NULL,                       /* printfunc tp_print; */
1767         NULL,                                           /* getattrfunc tp_getattr; */
1768         NULL,                                           /* setattrfunc tp_setattr; */
1769         NULL,                                           /* tp_compare */ /* DEPRECATED in python 3.0! */
1770         ( reprfunc ) pyrna_struct_repr, /* tp_repr */
1771
1772         /* Method suites for standard classes */
1773
1774         NULL,                       /* PyNumberMethods *tp_as_number; */
1775         NULL,                                           /* PySequenceMethods *tp_as_sequence; */
1776         NULL,                                           /* PyMappingMethods *tp_as_mapping; */
1777
1778         /* More standard operations (here for binary compatibility) */
1779
1780         ( hashfunc )pyrna_struct_hash,  /* hashfunc tp_hash; */
1781         NULL,                                           /* ternaryfunc tp_call; */
1782         NULL,                       /* reprfunc tp_str; */
1783         ( getattrofunc ) pyrna_struct_getattro, /* getattrofunc tp_getattro; */
1784         ( setattrofunc ) pyrna_struct_setattro, /* setattrofunc tp_setattro; */
1785
1786         /* Functions to access object as input/output buffer */
1787         NULL,                       /* PyBufferProcs *tp_as_buffer; */
1788
1789   /*** Flags to define presence of optional/expanded features ***/
1790         Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE,         /* long tp_flags; */
1791
1792         NULL,                                           /*  char *tp_doc;  Documentation string */
1793   /*** Assigned meaning in release 2.0 ***/
1794         /* call function for all accessible objects */
1795         NULL,                       /* traverseproc tp_traverse; */
1796
1797         /* delete references to contained objects */
1798         NULL,                       /* inquiry tp_clear; */
1799
1800   /***  Assigned meaning in release 2.1 ***/
1801   /*** rich comparisons ***/
1802         (richcmpfunc)pyrna_struct_richcmp,      /* richcmpfunc tp_richcompare; */
1803
1804   /***  weak reference enabler ***/
1805         0,                          /* long tp_weaklistoffset; */
1806
1807   /*** Added in release 2.2 ***/
1808         /*   Iterators */
1809         NULL,                       /* getiterfunc tp_iter; */
1810         NULL,                       /* iternextfunc tp_iternext; */
1811
1812   /*** Attribute descriptor and subclassing stuff ***/
1813         pyrna_struct_methods,                   /* struct PyMethodDef *tp_methods; */
1814         NULL,                       /* struct PyMemberDef *tp_members; */
1815         NULL,                                           /* struct PyGetSetDef *tp_getset; */
1816         NULL,                       /* struct _typeobject *tp_base; */
1817         NULL,                       /* PyObject *tp_dict; */
1818         NULL,                       /* descrgetfunc tp_descr_get; */
1819         NULL,                       /* descrsetfunc tp_descr_set; */
1820         0,                          /* long tp_dictoffset; */
1821         NULL,                       /* initproc tp_init; */
1822         NULL,                       /* allocfunc tp_alloc; */
1823         pyrna_struct_new,                       /* newfunc tp_new; */
1824         /*  Low-level free-memory routine */
1825         NULL,                       /* freefunc tp_free;  */
1826         /* For PyObject_IS_GC */
1827         NULL,                       /* inquiry tp_is_gc;  */
1828         NULL,                       /* PyObject *tp_bases; */
1829         /* method resolution order */
1830         NULL,                       /* PyObject *tp_mro;  */
1831         NULL,                       /* PyObject *tp_cache; */
1832         NULL,                       /* PyObject *tp_subclasses; */
1833         NULL,                       /* PyObject *tp_weaklist; */
1834         NULL
1835 };
1836
1837 /*-----------------------BPy_PropertyRNA method def------------------------------*/
1838 PyTypeObject pyrna_prop_Type = {
1839 #if (PY_VERSION_HEX >= 0x02060000)
1840         PyVarObject_HEAD_INIT(NULL, 0)
1841 #else
1842         /* python 2.5 and below */
1843         PyObject_HEAD_INIT( NULL )  /* required py macro */
1844         0,                          /* ob_size */
1845 #endif
1846         
1847         "PropertyRNA",          /* tp_name */
1848         sizeof( BPy_PropertyRNA ),                      /* tp_basicsize */
1849         0,                      /* tp_itemsize */
1850         /* methods */
1851         NULL,                                           /* tp_dealloc */
1852         NULL,                       /* printfunc tp_print; */
1853         NULL,                                           /* getattrfunc tp_getattr; */
1854         NULL,                       /* setattrfunc tp_setattr; */
1855         NULL,                                           /* tp_compare */ /* DEPRECATED in python 3.0! */
1856         ( reprfunc ) pyrna_prop_repr,   /* tp_repr */
1857
1858         /* Method suites for standard classes */
1859
1860         NULL,                       /* PyNumberMethods *tp_as_number; */
1861         &pyrna_prop_as_sequence,        /* PySequenceMethods *tp_as_sequence; */
1862         &pyrna_prop_as_mapping,         /* PyMappingMethods *tp_as_mapping; */
1863
1864         /* More standard operations (here for binary compatibility) */
1865
1866         NULL,                                           /* hashfunc tp_hash; */
1867         NULL,                       /* ternaryfunc tp_call; */
1868         NULL,                       /* reprfunc tp_str; */
1869         NULL, /*PyObject_GenericGetAttr - MINGW Complains, assign later */      /* getattrofunc tp_getattro; */ /* will only use these if this is a subtype of a py class */
1870         NULL, /*PyObject_GenericSetAttr - MINGW Complains, assign later */      /* setattrofunc tp_setattro; */
1871
1872         /* Functions to access object as input/output buffer */
1873         NULL,                       /* PyBufferProcs *tp_as_buffer; */
1874
1875   /*** Flags to define presence of optional/expanded features ***/
1876         Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE,         /* long tp_flags; */
1877
1878         NULL,                                           /*  char *tp_doc;  Documentation string */
1879   /*** Assigned meaning in release 2.0 ***/
1880         /* call function for all accessible objects */
1881         NULL,                       /* traverseproc tp_traverse; */
1882
1883         /* delete references to contained objects */
1884         NULL,                       /* inquiry tp_clear; */
1885
1886   /***  Assigned meaning in release 2.1 ***/
1887   /*** rich comparisons ***/
1888         (richcmpfunc)pyrna_prop_richcmp,        /* richcmpfunc tp_richcompare; */
1889
1890   /***  weak reference enabler ***/
1891         0,                          /* long tp_weaklistoffset; */
1892
1893   /*** Added in release 2.2 ***/
1894         /*   Iterators */
1895         (getiterfunc)pyrna_prop_iter,   /* getiterfunc tp_iter; */
1896         NULL,                       /* iternextfunc tp_iternext; */
1897
1898   /*** Attribute descriptor and subclassing stuff ***/
1899         pyrna_prop_methods,                     /* struct PyMethodDef *tp_methods; */
1900         NULL,                       /* struct PyMemberDef *tp_members; */
1901         NULL,                                           /* struct PyGetSetDef *tp_getset; */
1902         NULL,                       /* struct _typeobject *tp_base; */
1903         NULL,                       /* PyObject *tp_dict; */
1904         NULL,                       /* descrgetfunc tp_descr_get; */
1905         NULL,                       /* descrsetfunc tp_descr_set; */
1906         0,                          /* long tp_dictoffset; */
1907         NULL,                       /* initproc tp_init; */
1908         NULL,                       /* allocfunc tp_alloc; */
1909         pyrna_prop_new,                         /* newfunc tp_new; */
1910         /*  Low-level free-memory routine */
1911         NULL,                       /* freefunc tp_free;  */
1912         /* For PyObject_IS_GC */
1913         NULL,                       /* inquiry tp_is_gc;  */
1914         NULL,                       /* PyObject *tp_bases; */
1915         /* method resolution order */
1916         NULL,                       /* PyObject *tp_mro;  */
1917         NULL,                       /* PyObject *tp_cache; */
1918         NULL,                       /* PyObject *tp_subclasses; */
1919         NULL,                       /* PyObject *tp_weaklist; */
1920         NULL
1921 };
1922
1923 static void pyrna_subtype_set_rna(PyObject *newclass, StructRNA *srna)
1924 {
1925         PointerRNA ptr;
1926         PyObject *item;
1927         
1928         Py_INCREF(newclass);
1929         
1930         if (RNA_struct_py_type_get(srna))
1931                 PyObSpit("RNA WAS SET - ", RNA_struct_py_type_get(srna));
1932         
1933         Py_XDECREF(((PyObject *)RNA_struct_py_type_get(srna)));
1934         
1935         RNA_struct_py_type_set(srna, (void *)newclass); /* Store for later use */
1936
1937         /* Not 100% needed but useful,
1938          * having an instance within a type looks wrong however this instance IS an rna type */
1939         RNA_pointer_create(NULL, &RNA_Struct, srna, &ptr);
1940         item = pyrna_struct_CreatePyObject(&ptr);
1941         PyDict_SetItemString(((PyTypeObject *)newclass)->tp_dict, "__rna__", item);
1942         Py_DECREF(item);
1943         /* done with rna instance */
1944 }
1945
1946 PyObject* pyrna_struct_Subtype(PointerRNA *ptr)
1947 {
1948         PyObject *newclass = NULL;
1949         PropertyRNA *nameprop;
1950
1951         if (ptr->type==NULL) {
1952                 newclass= NULL; /* Nothing to do */
1953         } else if ((newclass= RNA_struct_py_type_get(ptr->data))) {
1954                 Py_INCREF(newclass);
1955         } else if ((nameprop = RNA_struct_name_property(ptr->type))) {
1956                 /* for now, return the base RNA type rather then a real module */
1957                 
1958                 /* Assume RNA_struct_py_type_get(ptr->data) was alredy checked */
1959                 
1960                 /* subclass equivelents
1961                 - class myClass(myBase):
1962                         some='value' # or ...
1963                 - myClass = type(name='myClass', bases=(myBase,), dict={'some':'value'})
1964                 */
1965                 char name[256], *nameptr;
1966                 const char *descr= RNA_struct_ui_description(ptr->type);
1967
1968                 PyObject *args = PyTuple_New(3);
1969                 PyObject *bases = PyTuple_New(1);
1970                 PyObject *dict = PyDict_New();
1971                 PyObject *item;
1972                 
1973                 
1974                 nameptr= RNA_property_string_get_alloc(ptr, nameprop, name, sizeof(name));
1975                 
1976                 // arg 1
1977                 //PyTuple_SET_ITEM(args, 0, PyUnicode_FromString(tp_name));
1978                 PyTuple_SET_ITEM(args, 0, PyUnicode_FromString(nameptr));
1979                 
1980                 // arg 2
1981                 PyTuple_SET_ITEM(bases, 0, (PyObject *)&pyrna_struct_Type);
1982                 Py_INCREF(&pyrna_struct_Type);
1983
1984                 PyTuple_SET_ITEM(args, 1, bases);
1985                 
1986                 // arg 3 - add an instance of the rna 
1987                 if(descr) {
1988                         item= PyUnicode_FromString(descr);
1989                         PyDict_SetItemString(dict, "__doc__", item);
1990                         Py_DECREF(item);
1991                 }
1992                 
1993                 PyTuple_SET_ITEM(args, 2, dict); // fill with useful subclass things!
1994                 
1995                 if (PyErr_Occurred()) {
1996                         PyErr_Print();
1997                         PyErr_Clear();
1998                 }
1999                 
2000                 newclass = PyObject_CallObject((PyObject *)&PyType_Type, args);
2001                 Py_DECREF(args);
2002
2003                 if (newclass)
2004                         pyrna_subtype_set_rna(newclass, ptr->data);
2005                 
2006                 if (name != nameptr)
2007                         MEM_freeN(nameptr);
2008         }
2009         
2010         return newclass;
2011 }
2012
2013 /*-----------------------CreatePyObject---------------------------------*/
2014 PyObject *pyrna_struct_CreatePyObject( PointerRNA *ptr )
2015 {
2016         BPy_StructRNA *pyrna= NULL;
2017         
2018         if (ptr->data==NULL && ptr->type==NULL) { /* Operator RNA has NULL data */
2019                 Py_RETURN_NONE;
2020         }
2021         
2022         if (ptr->type == &RNA_Struct) { /* always return a python subtype from rna struct types */
2023                 PyTypeObject *tp = (PyTypeObject *)pyrna_struct_Subtype(ptr);
2024                 
2025                 if (tp) {
2026                         pyrna = (BPy_StructRNA *) tp->tp_alloc(tp, 0);
2027                 }
2028                 else {
2029                         fprintf(stderr, "Could not make type\n");
2030                         pyrna = ( BPy_StructRNA * ) PyObject_NEW( BPy_StructRNA, &pyrna_struct_Type );
2031                 }
2032         }
2033         else {
2034                 pyrna = ( BPy_StructRNA * ) PyObject_NEW( BPy_StructRNA, &pyrna_struct_Type );
2035         }
2036         
2037         if( !pyrna ) {
2038                 PyErr_SetString( PyExc_MemoryError, "couldn't create BPy_StructRNA object" );
2039                 return NULL;
2040         }
2041         
2042         pyrna->ptr= *ptr;
2043         pyrna->freeptr= 0;
2044         return ( PyObject * ) pyrna;
2045 }
2046
2047 PyObject *pyrna_prop_CreatePyObject( PointerRNA *ptr, PropertyRNA *prop )
2048 {
2049         BPy_PropertyRNA *pyrna;
2050
2051         pyrna = ( BPy_PropertyRNA * ) PyObject_NEW( BPy_PropertyRNA, &pyrna_prop_Type );
2052
2053         if( !pyrna ) {
2054                 PyErr_SetString( PyExc_MemoryError, "couldn't create BPy_rna object" );
2055                 return NULL;
2056         }
2057         
2058         pyrna->ptr = *ptr;
2059         pyrna->prop = prop;
2060                 
2061         return ( PyObject * ) pyrna;
2062 }
2063
2064 PyObject *BPY_rna_module( void )
2065 {
2066         PointerRNA ptr;
2067         
2068 #ifdef USE_MATHUTILS // register mathutils callbacks, ok to run more then once.
2069         mathutils_rna_array_cb_index= Mathutils_RegisterCallback(&mathutils_rna_array_cb);
2070         mathutils_rna_matrix_cb_index= Mathutils_RegisterCallback(&mathutils_rna_matrix_cb);
2071 #endif
2072         
2073         /* This can't be set in the pytype struct because some compilers complain */
2074         pyrna_prop_Type.tp_getattro = PyObject_GenericGetAttr; 
2075         pyrna_prop_Type.tp_setattro = PyObject_GenericSetAttr; 
2076         
2077         if( PyType_Ready( &pyrna_struct_Type ) < 0 )
2078                 return NULL;
2079         
2080         if( PyType_Ready( &pyrna_prop_Type ) < 0 )
2081                 return NULL;
2082
2083         /* for now, return the base RNA type rather then a real module */
2084         RNA_main_pointer_create(G.main, &ptr);
2085         
2086         return pyrna_struct_CreatePyObject(&ptr);
2087 }
2088
2089 #if 0
2090 /* This is a way we can access docstrings for RNA types
2091  * without having the datatypes in blender */
2092 PyObject *BPY_rna_doc( void )
2093 {
2094         PointerRNA ptr;
2095         
2096         /* for now, return the base RNA type rather then a real module */
2097         RNA_blender_rna_pointer_create(&ptr);
2098         
2099         return pyrna_struct_CreatePyObject(&ptr);
2100 }
2101 #endif
2102
2103
2104 /* pyrna_basetype_* - BPy_BaseTypeRNA is just a BPy_PropertyRNA struct with a differnt type
2105  * the self->ptr and self->prop are always set to the "structs" collection */
2106 //---------------getattr--------------------------------------------
2107 static PyObject *pyrna_basetype_getattro( BPy_BaseTypeRNA * self, PyObject *pyname )
2108 {
2109         PointerRNA newptr;
2110         PyObject *ret;
2111         
2112         ret = PyObject_GenericGetAttr((PyObject *)self, pyname);
2113         if (ret)        return ret;
2114         else            PyErr_Clear();
2115         
2116         if (RNA_property_collection_lookup_string(&self->ptr, self->prop, _PyUnicode_AsString(pyname), &newptr)) {
2117                 ret= pyrna_struct_Subtype(&newptr);
2118                 if (ret==NULL) {
2119                         PyErr_Format(PyExc_SystemError, "bpy.types.%s subtype could not be generated, this is a bug!", _PyUnicode_AsString(pyname));
2120                 }
2121                 return ret;
2122         }
2123         else { /* Override the error */
2124                 PyErr_Format(PyExc_AttributeError, "bpy.types.%s not a valid RNA_Struct", _PyUnicode_AsString(pyname));
2125                 return NULL;
2126         }
2127 }
2128
2129 static PyObject *pyrna_basetype_dir(BPy_BaseTypeRNA *self);
2130 static struct PyMethodDef pyrna_basetype_methods[] = {
2131         {"__dir__", (PyCFunction)pyrna_basetype_dir, METH_NOARGS, ""},
2132         {"register", (PyCFunction)pyrna_basetype_register, METH_VARARGS, ""},
2133         {"unregister", (PyCFunction)pyrna_basetype_unregister, METH_VARARGS, ""},
2134         {NULL, NULL, 0, NULL}
2135 };
2136
2137 static PyObject *pyrna_basetype_dir(BPy_BaseTypeRNA *self)
2138 {
2139         PyObject *list, *name;
2140         PyMethodDef *meth;
2141         
2142         list= pyrna_prop_keys(self); /* like calling structs.keys(), avoids looping here */
2143
2144         for(meth=pyrna_basetype_methods; meth->ml_name; meth++) {
2145                 name = PyUnicode_FromString(meth->ml_name);
2146                 PyList_Append(list, name);
2147                 Py_DECREF(name);
2148         }
2149         
2150         return list;
2151 }
2152
2153 PyTypeObject pyrna_basetype_Type = BLANK_PYTHON_TYPE;
2154
2155 PyObject *BPY_rna_types(void)
2156 {
2157         BPy_BaseTypeRNA *self;
2158
2159         if ((pyrna_basetype_Type.tp_flags & Py_TPFLAGS_READY)==0)  {
2160                 pyrna_basetype_Type.tp_name = "RNA_Types";
2161                 pyrna_basetype_Type.tp_basicsize = sizeof( BPy_BaseTypeRNA );
2162                 pyrna_basetype_Type.tp_getattro = ( getattrofunc )pyrna_basetype_getattro;
2163                 pyrna_basetype_Type.tp_flags = Py_TPFLAGS_DEFAULT;
2164                 pyrna_basetype_Type.tp_methods = pyrna_basetype_methods;
2165                 
2166                 if( PyType_Ready( &pyrna_basetype_Type ) < 0 )
2167                         return NULL;
2168         }
2169         
2170         self= (BPy_BaseTypeRNA *)PyObject_NEW( BPy_BaseTypeRNA, &pyrna_basetype_Type );
2171         
2172         /* avoid doing this lookup for every getattr */
2173         RNA_blender_rna_pointer_create(&self->ptr);
2174         self->prop = RNA_struct_find_property(&self->ptr, "structs");
2175         
2176         return (PyObject *)self;
2177 }
2178
2179 static struct PyMethodDef props_methods[] = {
2180         {"FloatProperty", (PyCFunction)BPy_FloatProperty, METH_VARARGS|METH_KEYWORDS, ""},
2181         {"IntProperty", (PyCFunction)BPy_IntProperty, METH_VARARGS|METH_KEYWORDS, ""},
2182         {"BoolProperty", (PyCFunction)BPy_BoolProperty, METH_VARARGS|METH_KEYWORDS, ""},
2183         {"StringProperty", (PyCFunction)BPy_StringProperty, METH_VARARGS|METH_KEYWORDS, ""},
2184         {NULL, NULL, 0, NULL}
2185 };
2186
2187 #if PY_VERSION_HEX >= 0x03000000
2188 static struct PyModuleDef props_module = {
2189         PyModuleDef_HEAD_INIT,
2190         "bpyprops",
2191         "",
2192         -1,/* multiple "initialization" just copies the module dict. */
2193         props_methods,
2194         NULL, NULL, NULL, NULL
2195 };
2196 #endif
2197
2198 PyObject *BPY_rna_props( void )
2199 {
2200         PyObject *submodule, *mod;
2201 #if PY_VERSION_HEX >= 0x03000000
2202         submodule= PyModule_Create(&props_module);
2203 #else /* Py2.x */
2204         submodule= Py_InitModule3( "bpy.props", props_methods, "" );
2205 #endif
2206         
2207         mod = PyModule_New("props");
2208         PyModule_AddObject( submodule, "props", mod );
2209         
2210         /* INCREF since its its assumed that all these functions return the
2211          * module with a new ref like PyDict_New, since they are passed to
2212           * PyModule_AddObject which steals a ref */
2213         Py_INCREF(submodule);
2214         
2215         return submodule;
2216 }
2217
2218 /* Orphan functions, not sure where they should go */
2219
2220 /* Function that sets RNA, NOTE - self is NULL when called from python, but being abused from C so we can pass the srna allong
2221  * This isnt incorrect since its a python object - but be careful */
2222 PyObject *BPy_FloatProperty(PyObject *self, PyObject *args, PyObject *kw)
2223 {
2224         static char *kwlist[] = {"attr", "name", "description", "min", "max", "soft_min", "soft_max", "default", NULL};
2225         char *id, *name="", *description="";
2226         float min=FLT_MIN, max=FLT_MAX, soft_min=FLT_MIN, soft_max=FLT_MAX, def=0.0f;
2227         
2228         if (!PyArg_ParseTupleAndKeywords(args, kw, "s|ssfffff:FloatProperty", kwlist, &id, &name, &description, &min, &max, &soft_min, &soft_max, &def))
2229                 return NULL;
2230         
2231         if (PyTuple_Size(args) > 0) {
2232                 PyErr_SetString(PyExc_ValueError, "all args must be keywors"); // TODO - py3 can enforce this.
2233                 return NULL;
2234         }
2235         
2236         if (self && PyCObject_Check(self)) {
2237                 StructRNA *srna = PyCObject_AsVoidPtr(self);
2238                 RNA_def_float(srna, id, def, min, max, name, description, soft_min, soft_max);
2239                 Py_RETURN_NONE;
2240         } else {
2241                 PyObject *ret = PyTuple_New(2);
2242                 PyTuple_SET_ITEM(ret, 0, PyCObject_FromVoidPtr((void *)BPy_FloatProperty, NULL));
2243                 PyTuple_SET_ITEM(ret, 1, kw);
2244                 Py_INCREF(kw);
2245                 return ret;
2246         }
2247 }
2248
2249 PyObject *BPy_IntProperty(PyObject *self, PyObject *args, PyObject *kw)
2250 {
2251         static char *kwlist[] = {"attr", "name", "description", "min", "max", "soft_min", "soft_max", "default", NULL};
2252         char *id, *name="", *description="";
2253         int min=INT_MIN, max=INT_MAX, soft_min=INT_MIN, soft_max=INT_MAX, def=0;
2254         
2255         if (!PyArg_ParseTupleAndKeywords(args, kw, "s|ssiiiii:IntProperty", kwlist, &id, &name, &description, &min, &max, &soft_min, &soft_max, &def))
2256                 return NULL;
2257         
2258         if (PyTuple_Size(args) > 0) {
2259                 PyErr_SetString(PyExc_ValueError, "all args must be keywors"); // TODO - py3 can enforce this.
2260                 return NULL;
2261         }
2262         
2263         if (self && PyCObject_Check(self)) {
2264                 StructRNA *srna = PyCObject_AsVoidPtr(self);
2265                 RNA_def_int(srna, id, def, min, max, name, description, soft_min, soft_max);
2266                 Py_RETURN_NONE;
2267         } else {
2268                 PyObject *ret = PyTuple_New(2);
2269                 PyTuple_SET_ITEM(ret, 0, PyCObject_FromVoidPtr((void *)BPy_IntProperty, NULL));
2270                 PyTuple_SET_ITEM(ret, 1, kw);
2271                 Py_INCREF(kw);
2272                 return ret;
2273         }
2274 }
2275
2276 PyObject *BPy_BoolProperty(PyObject *self, PyObject *args, PyObject *kw)
2277 {
2278         static char *kwlist[] = {"attr", "name", "description", "default", NULL};
2279         char *id, *name="", *description="";
2280         int def=0;
2281         
2282         if (!PyArg_ParseTupleAndKeywords(args, kw, "s|ssi:BoolProperty", kwlist, &id, &name, &description, &def))
2283                 return NULL;
2284         
2285         if (PyTuple_Size(args) > 0) {
2286                 PyErr_SetString(PyExc_ValueError, "all args must be keywors"); // TODO - py3 can enforce this.
2287                 return NULL;
2288         }
2289         
2290         if (self && PyCObject_Check(self)) {
2291                 StructRNA *srna = PyCObject_AsVoidPtr(self);
2292                 RNA_def_boolean(srna, id, def, name, description);
2293                 Py_RETURN_NONE;
2294         } else {
2295                 PyObject *ret = PyTuple_New(2);
2296                 PyTuple_SET_ITEM(ret, 0, PyCObject_FromVoidPtr((void *)BPy_BoolProperty, NULL));
2297                 PyTuple_SET_ITEM(ret, 1, kw);
2298                 Py_INCREF(kw);
2299                 return ret;
2300         }
2301 }
2302
2303 PyObject *BPy_StringProperty(PyObject *self, PyObject *args, PyObject *kw)
2304 {
2305         static char *kwlist[] = {"attr", "name", "description", "maxlen", "default", NULL};
2306         char *id, *name="", *description="", *def="";
2307         int maxlen=0;
2308         
2309         if (!PyArg_ParseTupleAndKeywords(args, kw, "s|ssis:StringProperty", kwlist, &id, &name, &description, &maxlen, &def))
2310                 return NULL;
2311         
2312         if (PyTuple_Size(args) > 0) {
2313                 PyErr_SetString(PyExc_ValueError, "all args must be keywors"); // TODO - py3 can enforce this.
2314                 return NULL;
2315         }
2316         
2317         if (self && PyCObject_Check(self)) {
2318                 StructRNA *srna = PyCObject_AsVoidPtr(self);
2319                 RNA_def_string(srna, id, def, maxlen, name, description);
2320                 Py_RETURN_NONE;
2321         } else {
2322                 PyObject *ret = PyTuple_New(2);
2323                 PyTuple_SET_ITEM(ret, 0, PyCObject_FromVoidPtr((void *)BPy_StringProperty, NULL));
2324                 PyTuple_SET_ITEM(ret, 1, kw);
2325                 Py_INCREF(kw);
2326                 return ret;
2327         }
2328 }
2329
2330 /*-------------------- Type Registration ------------------------*/
2331
2332 static int rna_function_arg_count(FunctionRNA *func)
2333 {
2334         const ListBase *lb= RNA_function_defined_parameters(func);
2335         PropertyRNA *parm;
2336         Link *link;
2337         int count= 1;
2338
2339         for(link=lb->first; link; link=link->next) {
2340                 parm= (PropertyRNA*)link;
2341                 if(!(RNA_property_flag(parm) & PROP_RETURN))
2342                         count++;
2343         }
2344         
2345         return count;
2346 }
2347
2348 static int bpy_class_validate(PointerRNA *dummyptr, void *py_data, int *have_function)
2349 {
2350         const ListBase *lb;
2351         Link *link;
2352         FunctionRNA *func;
2353         PropertyRNA *prop;
2354         StructRNA *srna= dummyptr->type;
2355         const char *class_type= RNA_struct_identifier(srna);
2356         PyObject *py_class= (PyObject*)py_data;
2357         PyObject *base_class= RNA_struct_py_type_get(srna);
2358         PyObject *item, *fitem;
2359         PyObject *py_arg_count;
2360         int i, flag, arg_count, func_arg_count;
2361         char identifier[128];
2362
2363         if (base_class) {
2364                 if (!PyObject_IsSubclass(py_class, base_class)) {
2365                         PyObject *name= PyObject_GetAttrString(base_class, "__name__");
2366                         PyErr_Format( PyExc_AttributeError, "expected %s subclass of class \"%s\"", class_type, name ? _PyUnicode_AsString(name):"<UNKNOWN>");
2367                         Py_XDECREF(name);
2368                         return -1;
2369                 }
2370         }
2371
2372         /* verify callback functions */
2373         lb= RNA_struct_defined_functions(srna);
2374         i= 0;
2375         for(link=lb->first; link; link=link->next) {
2376                 func= (FunctionRNA*)link;
2377                 flag= RNA_function_flag(func);
2378
2379                 if(!(flag & FUNC_REGISTER))
2380                         continue;
2381
2382                 item = PyObject_GetAttrString(py_class, RNA_function_identifier(func));
2383
2384                 have_function[i]= (item != NULL);
2385                 i++;
2386
2387                 if (item==NULL) {
2388                         if ((flag & FUNC_REGISTER_OPTIONAL)==0) {
2389                                 PyErr_Format( PyExc_AttributeError, "expected %s class to have an \"%s\" attribute", class_type, RNA_function_identifier(func));
2390                                 return -1;
2391                         }
2392
2393                         PyErr_Clear();
2394                 }
2395                 else {
2396                         Py_DECREF(item); /* no need to keep a ref, the class owns it */
2397
2398                         if (PyMethod_Check(item))
2399                                 fitem= PyMethod_Function(item); /* py 2.x */
2400                         else
2401                                 fitem= item; /* py 3.x */
2402
2403                         if (PyFunction_Check(fitem)==0) {
2404                                 PyErr_Format( PyExc_AttributeError, "expected %s class \"%s\" attribute to be a function", class_type, RNA_function_identifier(func));
2405                                 return -1;
2406                         }
2407
2408                         func_arg_count= rna_function_arg_count(func);
2409
2410                         if (func_arg_count >= 0) { /* -1 if we dont care*/
2411                                 py_arg_count = PyObject_GetAttrString(PyFunction_GET_CODE(fitem), "co_argcount");
2412                                 arg_count = PyLong_AsSsize_t(py_arg_count);
2413                                 Py_DECREF(py_arg_count);
2414
2415                                 if (arg_count != func_arg_count) {
2416                                         PyErr_Format( PyExc_AttributeError, "expected %s class \"%s\" function to have %d args", class_type, RNA_function_identifier(func), func_arg_count);
2417                                         return -1;
2418                                 }
2419                         }
2420                 }
2421         }
2422
2423         /* verify properties */
2424         lb= RNA_struct_defined_properties(srna);
2425         for(link=lb->first; link; link=link->next) {
2426                 prop= (PropertyRNA*)link;
2427                 flag= RNA_property_flag(prop);
2428
2429                 if(!(flag & PROP_REGISTER))
2430                         continue;
2431
2432                 BLI_snprintf(identifier, sizeof(identifier), "__%s__", RNA_property_identifier(prop));
2433                 item = PyObject_GetAttrString(py_class, identifier);
2434
2435                 if (item==NULL) {
2436                         if(strcmp(identifier, "__idname__") == 0) {
2437                                 item= PyObject_GetAttrString(py_class, "__name__");
2438
2439                                 if(item) {
2440                                         Py_DECREF(item); /* no need to keep a ref, the class owns it */
2441
2442                                         if(pyrna_py_to_prop(dummyptr, prop, NULL, item) != 0)
2443                                                 return -1;
2444                                 }
2445                         }
2446
2447                         if (item==NULL && (flag & PROP_REGISTER_OPTIONAL)==0) {
2448                                 PyErr_Format( PyExc_AttributeError, "expected %s class to have an \"%s\" attribute", class_type, identifier);
2449                                 return -1;
2450                         }
2451
2452                         PyErr_Clear();
2453                 }
2454                 else {
2455                         Py_DECREF(item); /* no need to keep a ref, the class owns it */
2456
2457                         if(pyrna_py_to_prop(dummyptr, prop, NULL, item) != 0)
2458                                 return -1;
2459                 }
2460         }
2461
2462         return 0;
2463 }
2464
2465 extern void BPY_update_modules( void ); //XXX temp solution
2466
2467 static int bpy_class_call(PointerRNA *ptr, FunctionRNA *func, ParameterList *parms)
2468 {
2469         PyObject *args;
2470         PyObject *ret= NULL, *py_class, *py_class_instance, *item, *parmitem;
2471         PropertyRNA *pret= NULL, *parm;
2472         ParameterIterator iter;
2473         PointerRNA funcptr;
2474         void *retdata= NULL;
2475         int err= 0, i, flag;
2476
2477         PyGILState_STATE gilstate = PyGILState_Ensure();
2478
2479         BPY_update_modules(); // XXX - the RNA pointers can change so update before running, would like a nicer solution for this.
2480
2481         py_class= RNA_struct_py_type_get(ptr->type);
2482         
2483         item = pyrna_struct_CreatePyObject(ptr);
2484         if(item == NULL) {
2485                 py_class_instance = NULL;
2486         }
2487         else if(item == Py_None) { /* probably wont ever happen but possible */
2488                 Py_DECREF(item);
2489                 py_class_instance = NULL;
2490         }
2491         else {
2492                 args = PyTuple_New(1);
2493                 PyTuple_SET_ITEM(args, 0, item);
2494                 py_class_instance = PyObject_Call(py_class, args, NULL);
2495                 Py_DECREF(args);
2496         }
2497
2498         if (py_class_instance) { /* Initializing the class worked, now run its invoke function */
2499                 item= PyObject_GetAttrString(py_class, RNA_function_identifier(func));
2500                 flag= RNA_function_flag(func);
2501
2502                 if(item) {
2503                         pret= RNA_function_return(func);
2504                         RNA_pointer_create(NULL, &RNA_Function, func, &funcptr);
2505
2506                         args = PyTuple_New(rna_function_arg_count(func));
2507                         PyTuple_SET_ITEM(args, 0, py_class_instance);
2508
2509                         RNA_parameter_list_begin(parms, &iter);
2510
2511                         /* parse function parameters */
2512                         for (i= 1; iter.valid; RNA_parameter_list_next(&iter)) {
2513                                 parm= iter.parm;
2514
2515                                 if (parm==pret) {
2516                                         retdata= iter.data;
2517                                         continue;
2518                                 }
2519
2520                                 parmitem= pyrna_param_to_py(&funcptr, parm, iter.data);
2521                                 PyTuple_SET_ITEM(args, i, parmitem);
2522                                 i++;
2523                         }
2524
2525                         ret = PyObject_Call(item, args, NULL);
2526
2527                         Py_DECREF(item);
2528                         Py_DECREF(args);
2529                 }
2530                 else {
2531                         Py_DECREF(py_class_instance);
2532                         PyErr_Format(PyExc_AttributeError, "could not find function %s in %s to execute callback.", RNA_function_identifier(func), RNA_struct_identifier(ptr->type));
2533                         err= -1;
2534                 }
2535         }
2536         else {
2537                 PyErr_Format(PyExc_AttributeError, "could not create instance of %s to call callback function %s.", RNA_struct_identifier(ptr->type), RNA_function_identifier(func));
2538                 err= -1;
2539         }
2540
2541         if (ret == NULL) { /* covers py_class_instance failing too */
2542                 PyErr_Print(); /* XXX use reporting api? */
2543                 err= -1;
2544         }
2545         else {
2546                 if(retdata)
2547                         err= pyrna_py_to_prop(&funcptr, pret, retdata, ret);
2548                 Py_DECREF(ret);
2549         }
2550
2551         PyGILState_Release(gilstate);
2552         
2553         return err;
2554 }
2555
2556 static void bpy_class_free(void *pyob_ptr)
2557 {
2558         if(G.f&G_DEBUG) {
2559                 if(((PyObject *)pyob_ptr)->ob_refcnt > 1)
2560                         PyObSpit("zombie class - ref should be 1", (PyObject *)pyob_ptr);
2561         }
2562         Py_DECREF((PyObject *)pyob_ptr);
2563 }
2564
2565 PyObject *pyrna_basetype_register(PyObject *self, PyObject *args)
2566 {
2567         bContext *C= NULL;
2568         PyObject *py_class, *item;
2569         ReportList reports;
2570         StructRegisterFunc reg;
2571         BPy_StructRNA *py_srna;
2572         StructRNA *srna;
2573
2574         if(!PyArg_ParseTuple(args, "O:register", &py_class))
2575                 return NULL;
2576         
2577         if(!PyType_Check(py_class)) {
2578                 PyErr_SetString(PyExc_AttributeError, "expected a Type subclassed from a registerable rna type (no a Type object).");
2579                 return NULL;
2580         }
2581
2582         /* check we got an __rna__ attribute */
2583         item= PyObject_GetAttrString(py_class, "__rna__");
2584
2585         if(!item || !BPy_StructRNA_Check(item)) {
2586                 Py_XDECREF(item);
2587                 PyErr_SetString(PyExc_AttributeError, "expected a Type subclassed from a registerable rna type (no __rna__ property).");
2588                 return NULL;
2589         }
2590
2591         /* check the __rna__ attribute has the right type */
2592         Py_DECREF(item);
2593         py_srna= (BPy_StructRNA*)item;
2594
2595         if(py_srna->ptr.type != &RNA_Struct) {
2596                 PyErr_SetString(PyExc_AttributeError, "expected a Type subclassed from a registerable rna type (not a Struct).");
2597                 return NULL;
2598         }
2599         
2600         /* check that we have a register callback for this type */
2601         reg= RNA_struct_register(py_srna->ptr.data);
2602
2603         if(!reg) {
2604                 PyErr_SetString(PyExc_AttributeError, "expected a Type subclassed from a registerable rna type (no register supported).");
2605                 return NULL;
2606         }
2607         
2608         /* get the context, so register callback can do necessary refreshes */
2609         C= BPy_GetContext();
2610
2611         /* call the register callback */
2612         BKE_reports_init(&reports, RPT_STORE);
2613         srna= reg(C, &reports, py_class, bpy_class_validate, bpy_class_call, bpy_class_free);
2614
2615         if(!srna) {
2616                 BPy_reports_to_error(&reports);
2617                 BKE_reports_clear(&reports);
2618                 return NULL;
2619         }
2620
2621         BKE_reports_clear(&reports);
2622
2623         pyrna_subtype_set_rna(py_class, srna); /* takes a ref to py_class */
2624
2625         Py_RETURN_NONE;
2626 }
2627
2628 PyObject *pyrna_basetype_unregister(PyObject *self, PyObject *args)
2629 {
2630         bContext *C= NULL;
2631         PyObject *py_class, *item;
2632         BPy_StructRNA *py_srna;
2633         StructUnregisterFunc unreg;
2634
2635         if(!PyArg_ParseTuple(args, "O:unregister", &py_class))
2636                 return NULL;
2637
2638         if(!PyType_Check(py_class)) {
2639                 PyErr_SetString(PyExc_AttributeError, "expected a Type subclassed from a registerable rna type (no a Type object).");
2640                 return NULL;
2641         }
2642
2643         /* check we got an __rna__ attribute */
2644         item= PyDict_GetItemString(((PyTypeObject*)py_class)->tp_dict, "__rna__");  /* borrow ref */
2645
2646         if(!item || !BPy_StructRNA_Check(item)) {
2647                 PyErr_SetString(PyExc_AttributeError, "expected a Type subclassed from a registerable rna type (no __rna__ property).");
2648                 return NULL;
2649         }
2650
2651         /* check the __rna__ attribute has the right type */
2652         py_srna= (BPy_StructRNA*)item;
2653
2654         if(py_srna->ptr.type != &RNA_Struct) {
2655                 PyErr_SetString(PyExc_AttributeError, "expected a Type subclassed from a registerable rna type (not a Struct).");
2656                 return NULL;
2657         }
2658         
2659         /* check that we have a unregister callback for this type */
2660         unreg= RNA_struct_unregister(py_srna->ptr.data);
2661
2662         if(!unreg) {
2663                 PyErr_SetString(PyExc_AttributeError, "expected a Type subclassed from a registerable rna type (no unregister supported).");
2664                 return NULL;
2665         }
2666         
2667         /* get the context, so register callback can do necessary refreshes */
2668         C= BPy_GetContext();
2669         
2670
2671         /* call unregister */
2672         unreg(C, py_srna->ptr.data);
2673
2674         /* remove reference to old type */
2675         Py_DECREF(py_class);
2676
2677         Py_RETURN_NONE;
2678 }
2679