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