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