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