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