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