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