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