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