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