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