- access console languages as modules rather then having the py operator call an...
[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(RNA_struct_idproperties_check(&self->ptr)==0) {
1209                 PyErr_SetString( PyExc_TypeError, "this type doesn't support IDProperties");
1210                 return NULL;
1211         }
1212
1213         if(name==NULL) {
1214                 PyErr_SetString( PyExc_TypeError, "only strings are allowed as keys of ID properties");
1215                 return NULL;
1216         }
1217
1218         group= RNA_struct_idproperties(&self->ptr, 0);
1219
1220         if(group==NULL) {
1221                 PyErr_Format( PyExc_TypeError, "key \"%s\" not found", name);
1222                 return NULL;
1223         }
1224
1225         idprop= IDP_GetPropertyFromGroup(group, name);
1226
1227         if(idprop==NULL) {
1228                 PyErr_Format( PyExc_TypeError, "key \"%s\" not found", name);
1229                 return NULL;
1230         }
1231
1232         return BPy_IDGroup_WrapData(self->ptr.id.data, idprop);
1233 }
1234
1235 static int pyrna_struct_ass_subscript( BPy_StructRNA *self, PyObject *key, PyObject *value )
1236 {
1237         IDProperty *group= RNA_struct_idproperties(&self->ptr, 1);
1238
1239         if(group==NULL) {
1240                 PyErr_SetString(PyExc_TypeError, "id properties not supported for this type");
1241                 return -1;
1242         }
1243
1244         return BPy_Wrap_SetMapItem(group, key, value);
1245 }
1246
1247 static PyMappingMethods pyrna_struct_as_mapping = {
1248         ( lenfunc ) NULL,       /* mp_length */
1249         ( binaryfunc ) pyrna_struct_subscript,  /* mp_subscript */
1250         ( objobjargproc ) pyrna_struct_ass_subscript,   /* mp_ass_subscript */
1251 };
1252
1253 static PyObject *pyrna_struct_keys(BPy_PropertyRNA *self)
1254 {
1255         IDProperty *group;
1256
1257         if(RNA_struct_idproperties_check(&self->ptr)==0) {
1258                 PyErr_SetString( PyExc_TypeError, "this type doesnt support IDProperties");
1259                 return NULL;
1260         }
1261
1262         group= RNA_struct_idproperties(&self->ptr, 0);
1263
1264         if(group==NULL)
1265                 return PyList_New(0);
1266
1267         return BPy_Wrap_GetKeys(group);
1268 }
1269
1270 static PyObject *pyrna_struct_items(BPy_PropertyRNA *self)
1271 {
1272         IDProperty *group;
1273
1274         if(RNA_struct_idproperties_check(&self->ptr)==0) {
1275                 PyErr_SetString( PyExc_TypeError, "this type doesnt support IDProperties");
1276                 return NULL;
1277         }
1278
1279         group= RNA_struct_idproperties(&self->ptr, 0);
1280
1281         if(group==NULL)
1282                 return PyList_New(0);
1283
1284         return BPy_Wrap_GetItems(self->ptr.id.data, group);
1285 }
1286
1287
1288 static PyObject *pyrna_struct_values(BPy_PropertyRNA *self)
1289 {
1290         IDProperty *group;
1291
1292         if(RNA_struct_idproperties_check(&self->ptr)==0) {
1293                 PyErr_SetString( PyExc_TypeError, "this type doesnt support IDProperties");
1294                 return NULL;
1295         }
1296
1297         group= RNA_struct_idproperties(&self->ptr, 0);
1298
1299         if(group==NULL)
1300                 return PyList_New(0);
1301
1302         return BPy_Wrap_GetValues(self->ptr.id.data, group);
1303 }
1304
1305 static PyObject *pyrna_struct_keyframe_insert(BPy_StructRNA *self, PyObject *args)
1306 {
1307         char *path, *path_full;
1308         int index= -1; /* default to all */
1309         float cfra = CTX_data_scene(BPy_GetContext())->r.cfra;
1310         PropertyRNA *prop;
1311         PyObject *result;
1312
1313         if (!PyArg_ParseTuple(args, "s|if:keyframe_insert", &path, &index, &cfra))
1314                 return NULL;
1315
1316         if (self->ptr.data==NULL) {
1317                 PyErr_Format( PyExc_TypeError, "keyframe_insert, this struct has no data, cant be animated", path);
1318                 return NULL;
1319         }
1320
1321         prop = RNA_struct_find_property(&self->ptr, path);
1322
1323         if (prop==NULL) {
1324                 PyErr_Format( PyExc_TypeError, "keyframe_insert, property \"%s\" not found", path);
1325                 return NULL;
1326         }
1327
1328         if (!RNA_property_animateable(&self->ptr, prop)) {
1329                 PyErr_Format( PyExc_TypeError, "keyframe_insert, property \"%s\" not animatable", path);
1330                 return NULL;
1331         }
1332
1333         path_full= RNA_path_from_ID_to_property(&self->ptr, prop);
1334
1335         if (path_full==NULL) {
1336                 PyErr_Format( PyExc_TypeError, "keyframe_insert, could not make path to \"%s\"", path);
1337                 return NULL;
1338         }
1339
1340         result= PyBool_FromLong( insert_keyframe((ID *)self->ptr.id.data, NULL, NULL, path_full, index, cfra, 0));
1341         MEM_freeN(path_full);
1342
1343         return result;
1344 }
1345
1346
1347 static PyObject *pyrna_struct_driver_add(BPy_StructRNA *self, PyObject *args)
1348 {
1349         char *path, *path_full;
1350         int index= -1; /* default to all */
1351         PropertyRNA *prop;
1352         PyObject *result;
1353
1354         if (!PyArg_ParseTuple(args, "s|i:driver_add", &path, &index))
1355                 return NULL;
1356
1357         if (self->ptr.data==NULL) {
1358                 PyErr_Format( PyExc_TypeError, "driver_add, this struct has no data, cant be animated", path);
1359                 return NULL;
1360         }
1361
1362         prop = RNA_struct_find_property(&self->ptr, path);
1363
1364         if (prop==NULL) {
1365                 PyErr_Format( PyExc_TypeError, "driver_add, property \"%s\" not found", path);
1366                 return NULL;
1367         }
1368
1369         if (!RNA_property_animateable(&self->ptr, prop)) {
1370                 PyErr_Format( PyExc_TypeError, "driver_add, property \"%s\" not animatable", path);
1371                 return NULL;
1372         }
1373
1374         path_full= RNA_path_from_ID_to_property(&self->ptr, prop);
1375
1376         if (path_full==NULL) {
1377                 PyErr_Format( PyExc_TypeError, "driver_add, could not make path to \"%s\"", path);
1378                 return NULL;
1379         }
1380
1381         result= PyBool_FromLong( ANIM_add_driver((ID *)self->ptr.id.data, path_full, index, 0, DRIVER_TYPE_PYTHON));
1382         MEM_freeN(path_full);
1383
1384         return result;
1385 }
1386
1387
1388 static PyObject *pyrna_struct_is_property_set(BPy_StructRNA *self, PyObject *args)
1389 {
1390         char *name;
1391
1392         if (!PyArg_ParseTuple(args, "s:is_property_set", &name))
1393                 return NULL;
1394
1395         return PyBool_FromLong(RNA_property_is_set(&self->ptr, name));
1396 }
1397
1398 static PyObject *pyrna_struct_is_property_hidden(BPy_StructRNA *self, PyObject *args)
1399 {
1400         PropertyRNA *prop;
1401         char *name;
1402         int hidden;
1403
1404         if (!PyArg_ParseTuple(args, "s:is_property_hidden", &name))
1405                 return NULL;
1406         
1407         prop= RNA_struct_find_property(&self->ptr, name);
1408         hidden= (prop)? (RNA_property_flag(prop) & PROP_HIDDEN): 1;
1409
1410         return PyBool_FromLong(hidden);
1411 }
1412
1413 static PyObject *pyrna_struct_dir(BPy_StructRNA *self)
1414 {
1415         PyObject *ret, *dict;
1416         PyObject *pystring;
1417         
1418         /* for looping over attrs and funcs */
1419         PropertyRNA *iterprop;
1420         
1421         /* Include this incase this instance is a subtype of a python class
1422          * In these instances we may want to return a function or variable provided by the subtype
1423          * */
1424
1425         if (BPy_StructRNA_CheckExact(self)) {
1426                 ret = PyList_New(0);
1427         } else {
1428                 pystring = PyUnicode_FromString("__dict__");
1429                 dict = PyObject_GenericGetAttr((PyObject *)self, pystring);
1430                 Py_DECREF(pystring);
1431
1432                 if (dict==NULL) {
1433                         PyErr_Clear();
1434                         ret = PyList_New(0);
1435                 }
1436                 else {
1437                         ret = PyDict_Keys(dict);
1438                         Py_DECREF(dict);
1439                 }
1440         }
1441         
1442         /* Collect RNA items*/
1443         {
1444                 /*
1445                  * Collect RNA attributes
1446                  */
1447                 char name[256], *nameptr;
1448
1449                 iterprop= RNA_struct_iterator_property(self->ptr.type);
1450
1451                 RNA_PROP_BEGIN(&self->ptr, itemptr, iterprop) {
1452                         nameptr= RNA_struct_name_get_alloc(&itemptr, name, sizeof(name));
1453
1454                         if(nameptr) {
1455                                 pystring = PyUnicode_FromString(nameptr);
1456                                 PyList_Append(ret, pystring);
1457                                 Py_DECREF(pystring);
1458
1459                                 if(name != nameptr)
1460                                         MEM_freeN(nameptr);
1461                         }
1462                 }
1463                 RNA_PROP_END;
1464         }
1465         
1466         
1467         {
1468                 /*
1469                  * Collect RNA function items
1470                  */
1471                 PointerRNA tptr;
1472                 const char *idname;
1473
1474                 RNA_pointer_create(NULL, &RNA_Struct, self->ptr.type, &tptr);
1475                 iterprop= RNA_struct_find_property(&tptr, "functions");
1476
1477                 RNA_PROP_BEGIN(&tptr, itemptr, iterprop) {
1478                         idname= RNA_function_identifier(itemptr.data);
1479
1480                         pystring = PyUnicode_FromString(idname);
1481                         PyList_Append(ret, pystring);
1482                         Py_DECREF(pystring);
1483                 }
1484                 RNA_PROP_END;
1485         }
1486
1487         if(self->ptr.type == &RNA_Context) {
1488                 ListBase lb = CTX_data_dir_get(self->ptr.data);
1489                 LinkData *link;
1490
1491                 for(link=lb.first; link; link=link->next) {
1492                         pystring = PyUnicode_FromString(link->data);
1493                         PyList_Append(ret, pystring);
1494                         Py_DECREF(pystring);
1495                 }
1496
1497                 BLI_freelistN(&lb);
1498         }
1499         
1500         /* Hard coded names */
1501         if(self->ptr.id.data) {
1502                 pystring = PyUnicode_FromString("id_data");
1503                 PyList_Append(ret, pystring);
1504                 Py_DECREF(pystring);
1505         }
1506
1507         return ret;
1508 }
1509
1510
1511 //---------------getattr--------------------------------------------
1512 static PyObject *pyrna_struct_getattro( BPy_StructRNA *self, PyObject *pyname )
1513 {
1514         char *name = _PyUnicode_AsString(pyname);
1515         PyObject *ret;
1516         PropertyRNA *prop;
1517         FunctionRNA *func;
1518         
1519         if(name[0]=='_') { // rna can't start with a "_", so for __dict__ and similar we can skip using rna lookups
1520                 /* annoying exception, maybe we need to have different types for this... */
1521                 if((strcmp(name, "__getitem__")==0 || strcmp(name, "__setitem__")==0) && !RNA_struct_idproperties_check(&self->ptr)) {
1522                         PyErr_SetString(PyExc_AttributeError, "StructRNA - no __getitem__ support for this type");
1523                         ret = NULL;
1524                 }
1525                 else {
1526                         ret = PyObject_GenericGetAttr((PyObject *)self, pyname);
1527                 }
1528         }
1529         else if ((prop = RNA_struct_find_property(&self->ptr, name))) {
1530                 ret = pyrna_prop_to_py(&self->ptr, prop);
1531         }
1532         else if ((func = RNA_struct_find_function(&self->ptr, name))) {
1533                 ret = pyrna_func_to_py((BPy_DummyPointerRNA *)self, func);
1534         }
1535         else if (self->ptr.type == &RNA_Context) {
1536                 PointerRNA newptr;
1537                 ListBase newlb;
1538                 int done;
1539
1540                 done= CTX_data_get(self->ptr.data, name, &newptr, &newlb);
1541
1542                 if(done==1) { /* found */
1543                         if (newptr.data) {
1544                                 ret = pyrna_struct_CreatePyObject(&newptr);
1545                         }
1546                         else if (newlb.first) {
1547                                 CollectionPointerLink *link;
1548                                 PyObject *linkptr;
1549
1550                                 ret = PyList_New(0);
1551
1552                                 for(link=newlb.first; link; link=link->next) {
1553                                         linkptr= pyrna_struct_CreatePyObject(&link->ptr);
1554                                         PyList_Append(ret, linkptr);
1555                                         Py_DECREF(linkptr);
1556                                 }
1557                         }
1558                         else {
1559                                 ret = Py_None;
1560                                 Py_INCREF(ret);
1561                         }
1562                 }
1563                 else if (done==-1) { /* found but not set */
1564                         ret = Py_None;
1565                         Py_INCREF(ret);
1566                 }
1567         else { /* not found in the context */
1568                 /* lookup the subclass. raise an error if its not found */
1569                 ret = PyObject_GenericGetAttr((PyObject *)self, pyname);
1570         }
1571
1572                 BLI_freelistN(&newlb);
1573         }
1574         else if (strcmp(name, "id_data")==0) { /* XXX - hard coded */
1575                 if(self->ptr.id.data) {
1576                         PointerRNA id_ptr;
1577                         RNA_id_pointer_create((ID *)self->ptr.id.data, &id_ptr);
1578                         ret = pyrna_struct_CreatePyObject(&id_ptr);
1579                 }
1580                 else {
1581                         ret = Py_None;
1582                         Py_INCREF(ret);
1583                 }
1584         }
1585         else {
1586 #if 0
1587                 PyErr_Format( PyExc_AttributeError, "StructRNA - Attribute \"%.200s\" not found", name);
1588                 ret = NULL;
1589 #endif
1590                 /* Include this incase this instance is a subtype of a python class
1591                  * In these instances we may want to return a function or variable provided by the subtype
1592                  *
1593                  * Also needed to return methods when its not a subtype
1594                  * */
1595
1596                 /* The error raised here will be displayed */
1597                 ret = PyObject_GenericGetAttr((PyObject *)self, pyname);
1598         }
1599         
1600         return ret;
1601 }
1602
1603 //--------------- setattr-------------------------------------------
1604 static int pyrna_struct_setattro( BPy_StructRNA *self, PyObject *pyname, PyObject *value )
1605 {
1606         char *name = _PyUnicode_AsString(pyname);
1607         PropertyRNA *prop = RNA_struct_find_property(&self->ptr, name);
1608         
1609         if (prop==NULL) {
1610                 // XXX - This currently allows anything to be assigned to an rna prop, need to see how this should be used
1611                 // but for now it makes porting scripts confusing since it fails silently.
1612 #if 0
1613                 if (!BPy_StructRNA_CheckExact(self) && PyObject_GenericSetAttr((PyObject *)self, pyname, value) >= 0) {
1614                         return 0;
1615                 } else
1616 #endif
1617                 {
1618                         PyErr_Format( PyExc_AttributeError, "StructRNA - Attribute \"%.200s\" not found", name);
1619                         return -1;
1620                 }
1621         }               
1622         
1623         if (!RNA_property_editable(&self->ptr, prop)) {
1624                 PyErr_Format( PyExc_AttributeError, "StructRNA - Attribute \"%.200s\" from \"%.200s\" is read-only", RNA_property_identifier(prop), RNA_struct_identifier(self->ptr.type) );
1625                 return -1;
1626         }
1627                 
1628         /* pyrna_py_to_prop sets its own exceptions */
1629         return pyrna_py_to_prop(&self->ptr, prop, NULL, value, "StructRNA - item.attr = val:");
1630 }
1631
1632 static PyObject *pyrna_prop_getattro( BPy_PropertyRNA *self, PyObject *pyname )
1633 {
1634         char *name = _PyUnicode_AsString(pyname);
1635
1636         if(name[0] != '_') {
1637                 if (RNA_property_type(self->prop) == PROP_COLLECTION) {
1638                         PyObject *ret;
1639                         PropertyRNA *prop;
1640                         FunctionRNA *func;
1641
1642                         PointerRNA r_ptr;
1643                         if(RNA_property_collection_type_get(&self->ptr, self->prop, &r_ptr)) {
1644                                 if ((prop = RNA_struct_find_property(&r_ptr, name))) {
1645                                         ret = pyrna_prop_to_py(&r_ptr, prop);
1646
1647                                         return ret;
1648                                 }
1649                                 else if ((func = RNA_struct_find_function(&r_ptr, name))) {
1650                                         PyObject *self_collection= pyrna_struct_CreatePyObject(&r_ptr);
1651                                         ret = pyrna_func_to_py((BPy_DummyPointerRNA *)self_collection, func);
1652                                         Py_DECREF(self_collection);
1653
1654                                         return ret;
1655                                 }
1656                         }
1657                 }
1658         }
1659
1660         /* The error raised here will be displayed */
1661         return PyObject_GenericGetAttr((PyObject *)self, pyname);
1662 }
1663
1664 //--------------- setattr-------------------------------------------
1665 static int pyrna_prop_setattro( BPy_PropertyRNA *self, PyObject *pyname, PyObject *value )
1666 {
1667         char *name = _PyUnicode_AsString(pyname);
1668         PropertyRNA *prop;
1669
1670         if (RNA_property_type(self->prop) == PROP_COLLECTION) {
1671                 PointerRNA r_ptr;
1672                 if(RNA_property_collection_type_get(&self->ptr, self->prop, &r_ptr)) {
1673                         if ((prop = RNA_struct_find_property(&r_ptr, name))) {
1674                                 /* pyrna_py_to_prop sets its own exceptions */
1675                                 return pyrna_py_to_prop(&r_ptr, prop, NULL, value, "BPy_PropertyRNA - Attribute (setattr):");
1676                         }
1677                 }
1678         }
1679
1680         PyErr_Format( PyExc_AttributeError, "BPy_PropertyRNA - Attribute \"%.200s\" not found", name);
1681         return -1;
1682 }
1683
1684 /* odd case, we need to be able return a python method from a tp_getset */
1685 static PyObject *pyrna_prop_add(BPy_PropertyRNA *self)
1686 {
1687         PointerRNA r_ptr;
1688
1689         RNA_property_collection_add(&self->ptr, self->prop, &r_ptr);
1690         if(!r_ptr.data) {
1691                 PyErr_SetString( PyExc_TypeError, "add() not supported for this collection");
1692                 return NULL;
1693         }
1694         else {
1695                 return pyrna_struct_CreatePyObject(&r_ptr);
1696         }
1697 }
1698
1699 static PyObject *pyrna_prop_remove(BPy_PropertyRNA *self, PyObject *value)
1700 {
1701         PyObject *ret;
1702         int key= PyLong_AsSsize_t(value);
1703
1704         if (key==-1 && PyErr_Occurred()) {
1705                 PyErr_SetString( PyExc_TypeError, "remove() expected one int argument");
1706                 return NULL;
1707         }
1708
1709         if(!RNA_property_collection_remove(&self->ptr, self->prop, key)) {
1710                 PyErr_SetString( PyExc_TypeError, "remove() not supported for this collection");
1711                 return NULL;
1712         }
1713
1714         ret = Py_None;
1715         Py_INCREF(ret);
1716
1717         return ret;
1718 }
1719
1720 /*****************************************************************************/
1721 /* Python attributes get/set structure:                                      */
1722 /*****************************************************************************/
1723 #if 0
1724 static PyGetSetDef pyrna_prop_getseters[] = {
1725         {"active", (getter)pyrna_prop_get_active, (setter)pyrna_prop_set_active, "", NULL},
1726         {NULL,NULL,NULL,NULL,NULL}  /* Sentinel */
1727 };
1728 #endif
1729
1730 static PyObject *pyrna_prop_keys(BPy_PropertyRNA *self)
1731 {
1732         PyObject *ret;
1733         if (RNA_property_type(self->prop) != PROP_COLLECTION) {
1734                 PyErr_SetString( PyExc_TypeError, "keys() is only valid for collection types" );
1735                 ret = NULL;
1736         } else {
1737                 PyObject *item;
1738                 char name[256], *nameptr;
1739
1740                 ret = PyList_New(0);
1741                 
1742                 RNA_PROP_BEGIN(&self->ptr, itemptr, self->prop) {
1743                         nameptr= RNA_struct_name_get_alloc(&itemptr, name, sizeof(name));
1744
1745                         if(nameptr) {
1746                                 /* add to python list */
1747                                 item = PyUnicode_FromString( nameptr );
1748                                 PyList_Append(ret, item);
1749                                 Py_DECREF(item);
1750                                 /* done */
1751                                 
1752                                 if(name != nameptr)
1753                                         MEM_freeN(nameptr);
1754                         }
1755                 }
1756                 RNA_PROP_END;
1757         }
1758         
1759         return ret;
1760 }
1761
1762 static PyObject *pyrna_prop_items(BPy_PropertyRNA *self)
1763 {
1764         PyObject *ret;
1765         if (RNA_property_type(self->prop) != PROP_COLLECTION) {
1766                 PyErr_SetString( PyExc_TypeError, "items() is only valid for collection types" );
1767                 ret = NULL;
1768         } else {
1769                 PyObject *item;
1770                 char name[256], *nameptr;
1771                 int i= 0;
1772
1773                 ret = PyList_New(0);
1774                 
1775                 RNA_PROP_BEGIN(&self->ptr, itemptr, self->prop) {
1776                         if(itemptr.data) {
1777                                 /* add to python list */
1778                                 item= PyTuple_New(2);
1779                                 nameptr= RNA_struct_name_get_alloc(&itemptr, name, sizeof(name));
1780                                 if(nameptr) {
1781                                         PyTuple_SET_ITEM(item, 0, PyUnicode_FromString( nameptr ));
1782                                         if(name != nameptr)
1783                                                 MEM_freeN(nameptr);
1784                                 }
1785                                 else {
1786                                         PyTuple_SET_ITEM(item, 0, PyLong_FromSsize_t(i)); /* a bit strange but better then returning an empty list */
1787                                 }
1788                                 PyTuple_SET_ITEM(item, 1, pyrna_struct_CreatePyObject(&itemptr));
1789                                 
1790                                 PyList_Append(ret, item);
1791                                 Py_DECREF(item);
1792                                 
1793                                 i++;
1794                         }
1795                 }
1796                 RNA_PROP_END;
1797         }
1798         
1799         return ret;
1800 }
1801
1802
1803 static PyObject *pyrna_prop_values(BPy_PropertyRNA *self)
1804 {
1805         PyObject *ret;
1806         
1807         if (RNA_property_type(self->prop) != PROP_COLLECTION) {
1808                 PyErr_SetString( PyExc_TypeError, "values() is only valid for collection types" );
1809                 ret = NULL;
1810         } else {
1811                 PyObject *item;
1812                 ret = PyList_New(0);
1813                 
1814                 RNA_PROP_BEGIN(&self->ptr, itemptr, self->prop) {
1815                         item = pyrna_struct_CreatePyObject(&itemptr);
1816                         PyList_Append(ret, item);
1817                         Py_DECREF(item);
1818                 }
1819                 RNA_PROP_END;
1820         }
1821         
1822         return ret;
1823 }
1824
1825 static PyObject *pyrna_prop_get(BPy_PropertyRNA *self, PyObject *args)
1826 {
1827         PointerRNA newptr;
1828         
1829         char *key;
1830         PyObject* def = Py_None;
1831
1832         if (!PyArg_ParseTuple(args, "s|O:get", &key, &def))
1833                 return NULL;
1834         
1835         if(RNA_property_collection_lookup_string(&self->ptr, self->prop, key, &newptr))
1836                 return pyrna_struct_CreatePyObject(&newptr);
1837         
1838         Py_INCREF(def);
1839         return def;
1840 }
1841
1842 static void foreach_attr_type(  BPy_PropertyRNA *self, char *attr,
1843                                                                         /* values to assign */
1844                                                                         RawPropertyType *raw_type, int *attr_tot, int *attr_signed )
1845 {
1846         PropertyRNA *prop;
1847         *raw_type= -1;
1848         *attr_tot= 0;
1849         *attr_signed= FALSE;
1850
1851         RNA_PROP_BEGIN(&self->ptr, itemptr, self->prop) {
1852                 prop = RNA_struct_find_property(&itemptr, attr);
1853                 *raw_type= RNA_property_raw_type(prop);
1854                 *attr_tot = RNA_property_array_length(&itemptr, prop);
1855                 *attr_signed= (RNA_property_subtype(prop)==PROP_UNSIGNED) ? FALSE:TRUE;
1856                 break;
1857         }
1858         RNA_PROP_END;
1859 }
1860
1861 /* pyrna_prop_foreach_get/set both use this */
1862 static int foreach_parse_args(
1863                 BPy_PropertyRNA *self, PyObject *args,
1864
1865                 /*values to assign */
1866                 char **attr, PyObject **seq, int *tot, int *size, RawPropertyType *raw_type, int *attr_tot, int *attr_signed)
1867 {
1868 #if 0
1869         int array_tot;
1870         int target_tot;
1871 #endif
1872
1873         *size= *raw_type= *attr_tot= *attr_signed= FALSE;
1874
1875         if(!PyArg_ParseTuple(args, "sO", attr, seq) || (!PySequence_Check(*seq) && PyObject_CheckBuffer(*seq))) {
1876                 PyErr_SetString( PyExc_TypeError, "foreach_get(attr, sequence) expects a string and a sequence" );
1877                 return -1;
1878         }
1879
1880         *tot= PySequence_Length(*seq); // TODO - buffer may not be a sequence! array.array() is tho.
1881
1882         if(*tot>0) {
1883                 foreach_attr_type(self, *attr, raw_type, attr_tot, attr_signed);
1884                 *size= RNA_raw_type_sizeof(*raw_type);
1885
1886 #if 0   // works fine but not strictly needed, we could allow RNA_property_collection_raw_* to do the checks
1887                 if((*attr_tot) < 1)
1888                         *attr_tot= 1;
1889
1890                 if (RNA_property_type(self->prop) == PROP_COLLECTION)
1891                         array_tot = RNA_property_collection_length(&self->ptr, self->prop);
1892                 else
1893                         array_tot = RNA_property_array_length(&self->ptr, self->prop);
1894
1895
1896                 target_tot= array_tot * (*attr_tot);
1897
1898                 /* rna_access.c - rna_raw_access(...) uses this same method */
1899                 if(target_tot != (*tot)) {
1900                         PyErr_Format( PyExc_TypeError, "foreach_get(attr, sequence) sequence length mismatch given %d, needed %d", *tot, target_tot);
1901                         return -1;
1902                 }
1903 #endif
1904         }
1905
1906         return 0;
1907 }
1908
1909 static int foreach_compat_buffer(RawPropertyType raw_type, int attr_signed, const char *format)
1910 {
1911         char f = format ? *format:'B'; /* B is assumed when not set */
1912
1913         switch(raw_type) {
1914         case PROP_RAW_CHAR:
1915                 if (attr_signed)        return (f=='b') ? 1:0;
1916                 else                            return (f=='B') ? 1:0;
1917         case PROP_RAW_SHORT:
1918                 if (attr_signed)        return (f=='h') ? 1:0;
1919                 else                            return (f=='H') ? 1:0;
1920         case PROP_RAW_INT:
1921                 if (attr_signed)        return (f=='i') ? 1:0;
1922                 else                            return (f=='I') ? 1:0;
1923         case PROP_RAW_FLOAT:
1924                 return (f=='f') ? 1:0;
1925         case PROP_RAW_DOUBLE:
1926                 return (f=='d') ? 1:0;
1927         }
1928
1929         return 0;
1930 }
1931
1932 static PyObject *foreach_getset(BPy_PropertyRNA *self, PyObject *args, int set)
1933 {
1934         PyObject *item = NULL;
1935         int i=0, ok=0, buffer_is_compat;
1936         void *array= NULL;
1937
1938         /* get/set both take the same args currently */
1939         char *attr;
1940         PyObject *seq;
1941         int tot, size, attr_tot, attr_signed;
1942         RawPropertyType raw_type;
1943
1944         if(foreach_parse_args(self, args,    &attr, &seq, &tot, &size, &raw_type, &attr_tot, &attr_signed) < 0)
1945                 return NULL;
1946
1947         if(tot==0)
1948                 Py_RETURN_NONE;
1949
1950
1951
1952         if(set) { /* get the array from python */
1953                 buffer_is_compat = FALSE;
1954                 if(PyObject_CheckBuffer(seq)) {
1955                         Py_buffer buf;
1956                         PyObject_GetBuffer(seq, &buf, PyBUF_SIMPLE | PyBUF_FORMAT);
1957
1958                         /* check if the buffer matches */
1959
1960                         buffer_is_compat = foreach_compat_buffer(raw_type, attr_signed, buf.format);
1961
1962                         if(buffer_is_compat) {
1963                                 ok = RNA_property_collection_raw_set(NULL, &self->ptr, self->prop, attr, buf.buf, raw_type, tot);
1964                         }
1965
1966                         PyBuffer_Release(&buf);
1967                 }
1968
1969                 /* could not use the buffer, fallback to sequence */
1970                 if(!buffer_is_compat) {
1971                         array= PyMem_Malloc(size * tot);
1972
1973                         for( ; i<tot; i++) {
1974                                 item= PySequence_GetItem(seq, i);
1975                                 switch(raw_type) {
1976                                 case PROP_RAW_CHAR:
1977                                         ((char *)array)[i]= (char)PyLong_AsSsize_t(item);
1978                                         break;
1979                                 case PROP_RAW_SHORT:
1980                                         ((short *)array)[i]= (short)PyLong_AsSsize_t(item);
1981                                         break;
1982                                 case PROP_RAW_INT:
1983                                         ((int *)array)[i]= (int)PyLong_AsSsize_t(item);
1984                                         break;
1985                                 case PROP_RAW_FLOAT:
1986                                         ((float *)array)[i]= (float)PyFloat_AsDouble(item);
1987                                         break;
1988                                 case PROP_RAW_DOUBLE:
1989                                         ((double *)array)[i]= (double)PyFloat_AsDouble(item);
1990                                         break;
1991                                 }
1992
1993                                 Py_DECREF(item);
1994                         }
1995
1996                         ok = RNA_property_collection_raw_set(NULL, &self->ptr, self->prop, attr, array, raw_type, tot);
1997                 }
1998         }
1999         else {
2000                 buffer_is_compat = FALSE;
2001                 if(PyObject_CheckBuffer(seq)) {
2002                         Py_buffer buf;
2003                         PyObject_GetBuffer(seq, &buf, PyBUF_SIMPLE | PyBUF_FORMAT);
2004
2005                         /* check if the buffer matches, TODO - signed/unsigned types */
2006
2007                         buffer_is_compat = foreach_compat_buffer(raw_type, attr_signed, buf.format);
2008
2009                         if(buffer_is_compat) {
2010                                 ok = RNA_property_collection_raw_get(NULL, &self->ptr, self->prop, attr, buf.buf, raw_type, tot);
2011                         }
2012
2013                         PyBuffer_Release(&buf);
2014                 }
2015
2016                 /* could not use the buffer, fallback to sequence */
2017                 if(!buffer_is_compat) {
2018                         array= PyMem_Malloc(size * tot);
2019
2020                         ok = RNA_property_collection_raw_get(NULL, &self->ptr, self->prop, attr, array, raw_type, tot);
2021
2022                         if(!ok) i= tot; /* skip the loop */
2023
2024                         for( ; i<tot; i++) {
2025
2026                                 switch(raw_type) {
2027                                 case PROP_RAW_CHAR:
2028                                         item= PyLong_FromSsize_t(  (Py_ssize_t) ((char *)array)[i]  );
2029                                         break;
2030                                 case PROP_RAW_SHORT:
2031                                         item= PyLong_FromSsize_t(  (Py_ssize_t) ((short *)array)[i]  );
2032                                         break;
2033                                 case PROP_RAW_INT:
2034                                         item= PyLong_FromSsize_t(  (Py_ssize_t) ((int *)array)[i]  );
2035                                         break;
2036                                 case PROP_RAW_FLOAT:
2037                                         item= PyFloat_FromDouble(  (double) ((float *)array)[i]  );
2038                                         break;
2039                                 case PROP_RAW_DOUBLE:
2040                                         item= PyFloat_FromDouble(  (double) ((double *)array)[i]  );
2041                                         break;
2042                                 }
2043
2044                                 PySequence_SetItem(seq, i, item);
2045                                 Py_DECREF(item);
2046                         }
2047                 }
2048         }
2049
2050         if(PyErr_Occurred()) {
2051                 /* Maybe we could make our own error */
2052                 PyErr_Print();
2053                 PyErr_SetString(PyExc_SystemError, "could not access the py sequence");
2054                 return NULL;
2055         }
2056         if (!ok) {
2057                 PyErr_SetString(PyExc_SystemError, "internal error setting the array");
2058                 return NULL;
2059         }
2060
2061         if(array)
2062                 PyMem_Free(array);
2063
2064         Py_RETURN_NONE;
2065 }
2066
2067 static PyObject *pyrna_prop_foreach_get(BPy_PropertyRNA *self, PyObject *args)
2068 {
2069         return foreach_getset(self, args, 0);
2070 }
2071
2072 static  PyObject *pyrna_prop_foreach_set(BPy_PropertyRNA *self, PyObject *args)
2073 {
2074         return foreach_getset(self, args, 1);
2075 }
2076
2077 /* A bit of a kludge, make a list out of a collection or array,
2078  * then return the lists iter function, not especially fast but convenient for now */
2079 PyObject *pyrna_prop_iter(BPy_PropertyRNA *self)
2080 {
2081         /* Try get values from a collection */
2082         PyObject *ret;
2083         PyObject *iter;
2084         
2085         if(RNA_property_array_check(&self->ptr, self->prop)) {
2086                 int len = pyrna_prop_array_length(self);
2087                 int i;
2088                 PyErr_Clear();
2089                 ret = PyList_New(len);
2090                 
2091                 for (i=0; i < len; i++) {
2092                         PyList_SET_ITEM(ret, i, pyrna_prop_to_py_index(self, i));
2093                 }
2094         }
2095         else if ((ret = pyrna_prop_values(self))) {
2096                 /* do nothing */
2097         }
2098         else {
2099                 PyErr_SetString( PyExc_TypeError, "this BPy_PropertyRNA object is not iterable" );
2100                 return NULL;
2101         }
2102         
2103         
2104         /* we know this is a list so no need to PyIter_Check */
2105         iter = PyObject_GetIter(ret);
2106         Py_DECREF(ret);
2107         return iter;
2108 }
2109
2110 static struct PyMethodDef pyrna_struct_methods[] = {
2111
2112         /* only for PointerRNA's with ID'props */
2113         {"keys", (PyCFunction)pyrna_struct_keys, METH_NOARGS, NULL},
2114         {"values", (PyCFunction)pyrna_struct_values, METH_NOARGS, NULL},
2115         {"items", (PyCFunction)pyrna_struct_items, METH_NOARGS, NULL},
2116
2117         /* maybe this become and ID function */
2118         {"keyframe_insert", (PyCFunction)pyrna_struct_keyframe_insert, METH_VARARGS, NULL},
2119         {"driver_add", (PyCFunction)pyrna_struct_driver_add, METH_VARARGS, NULL},
2120         {"is_property_set", (PyCFunction)pyrna_struct_is_property_set, METH_VARARGS, NULL},
2121         {"is_property_hidden", (PyCFunction)pyrna_struct_is_property_hidden, METH_VARARGS, NULL},
2122         {"__dir__", (PyCFunction)pyrna_struct_dir, METH_NOARGS, NULL},
2123         {NULL, NULL, 0, NULL}
2124 };
2125
2126 static struct PyMethodDef pyrna_prop_methods[] = {
2127         {"keys", (PyCFunction)pyrna_prop_keys, METH_NOARGS, NULL},
2128         {"items", (PyCFunction)pyrna_prop_items, METH_NOARGS,NULL},
2129         {"values", (PyCFunction)pyrna_prop_values, METH_NOARGS, NULL},
2130         
2131         {"get", (PyCFunction)pyrna_prop_get, METH_VARARGS, NULL},
2132
2133         /* moved into a getset */
2134         {"add", (PyCFunction)pyrna_prop_add, METH_NOARGS, NULL},
2135         {"remove", (PyCFunction)pyrna_prop_remove, METH_O, NULL},
2136
2137         /* array accessor function */
2138         {"foreach_get", (PyCFunction)pyrna_prop_foreach_get, METH_VARARGS, NULL},
2139         {"foreach_set", (PyCFunction)pyrna_prop_foreach_set, METH_VARARGS, NULL},
2140         {NULL, NULL, 0, NULL}
2141 };
2142
2143 /* only needed for subtyping, so a new class gets a valid BPy_StructRNA
2144  * todo - also accept useful args */
2145 static PyObject * pyrna_struct_new(PyTypeObject *type, PyObject *args, PyObject *kwds) {
2146
2147         BPy_StructRNA *base = NULL;
2148         
2149         if (!PyArg_ParseTuple(args, "O!:Base BPy_StructRNA", &pyrna_struct_Type, &base))
2150                 return NULL;
2151         
2152         if (type == &pyrna_struct_Type) {
2153                 return pyrna_struct_CreatePyObject(&base->ptr);
2154         } else {
2155                 BPy_StructRNA *ret = (BPy_StructRNA *) type->tp_alloc(type, 0);
2156                 ret->ptr = base->ptr;
2157                 return (PyObject *)ret;
2158         }
2159 }
2160
2161 /* only needed for subtyping, so a new class gets a valid BPy_StructRNA
2162  * todo - also accept useful args */
2163 static PyObject * pyrna_prop_new(PyTypeObject *type, PyObject *args, PyObject *kwds) {
2164
2165         BPy_PropertyRNA *base = NULL;
2166         
2167         if (!PyArg_ParseTuple(args, "O!:Base BPy_PropertyRNA", &pyrna_prop_Type, &base))
2168                 return NULL;
2169         
2170         if (type == &pyrna_prop_Type) {
2171                 return pyrna_prop_CreatePyObject(&base->ptr, base->prop);
2172         } else {
2173                 BPy_PropertyRNA *ret = (BPy_PropertyRNA *) type->tp_alloc(type, 0);
2174                 ret->ptr = base->ptr;
2175                 ret->prop = base->prop;
2176                 return (PyObject *)ret;
2177         }
2178 }
2179
2180 PyObject *pyrna_param_to_py(PointerRNA *ptr, PropertyRNA *prop, void *data)
2181 {
2182         PyObject *ret;
2183         int type = RNA_property_type(prop);
2184
2185         int a;
2186
2187         if(RNA_property_array_check(ptr, prop)) {
2188                 int len = RNA_property_array_length(ptr, prop);
2189
2190                 /* resolve the array from a new pytype */
2191                 ret = PyTuple_New(len);
2192
2193                 /* kazanbas: TODO make multidim sequences here */
2194
2195                 switch (type) {
2196                 case PROP_BOOLEAN:
2197                         for(a=0; a<len; a++)
2198                                 PyTuple_SET_ITEM(ret, a, PyBool_FromLong( ((int*)data)[a] ));
2199                         break;
2200                 case PROP_INT:
2201                         for(a=0; a<len; a++)
2202                                 PyTuple_SET_ITEM(ret, a, PyLong_FromSsize_t( (Py_ssize_t)((int*)data)[a] ));
2203                         break;
2204                 case PROP_FLOAT:
2205                         for(a=0; a<len; a++)
2206                                 PyTuple_SET_ITEM(ret, a, PyFloat_FromDouble( ((float*)data)[a] ));
2207                         break;
2208                 default:
2209                         PyErr_Format(PyExc_TypeError, "RNA Error: unknown array type \"%d\" (pyrna_param_to_py)", type);
2210                         ret = NULL;
2211                         break;
2212                 }
2213         }
2214         else {
2215                 /* see if we can coorce into a python type - PropertyType */
2216                 switch (type) {
2217                 case PROP_BOOLEAN:
2218                         ret = PyBool_FromLong( *(int*)data );
2219                         break;
2220                 case PROP_INT:
2221                         ret = PyLong_FromSsize_t( (Py_ssize_t)*(int*)data );
2222                         break;
2223                 case PROP_FLOAT:
2224                         ret = PyFloat_FromDouble( *(float*)data );
2225                         break;
2226                 case PROP_STRING:
2227                 {
2228                         ret = PyUnicode_FromString( *(char**)data );
2229                         break;
2230                 }
2231                 case PROP_ENUM:
2232                 {
2233                         const char *identifier;
2234                         int val = *(int*)data;
2235                         
2236                         if (RNA_property_enum_identifier(BPy_GetContext(), ptr, prop, val, &identifier)) {
2237                                 ret = PyUnicode_FromString( identifier );
2238                         } else {
2239                                 /* prefer not fail silently incase of api errors, maybe disable it later */
2240                                 char error_str[128];
2241                                 sprintf(error_str, "RNA Warning: Current value \"%d\" matches no enum", val);
2242                                 PyErr_Warn(PyExc_RuntimeWarning, error_str);
2243                                 
2244                                 ret = PyUnicode_FromString( "" );
2245                                 /*PyErr_Format(PyExc_AttributeError, "RNA Error: Current value \"%d\" matches no enum", val);
2246                                 ret = NULL;*/
2247                         }
2248
2249                         break;
2250                 }
2251                 case PROP_POINTER:
2252                 {
2253                         PointerRNA newptr;
2254                         StructRNA *type= RNA_property_pointer_type(ptr, prop);
2255                         int flag = RNA_property_flag(prop);
2256
2257                         if(flag & PROP_RNAPTR) {
2258                                 /* in this case we get the full ptr */
2259                                 newptr= *(PointerRNA*)data;
2260                         }
2261                         else {
2262                                 if(RNA_struct_is_ID(type)) {
2263                                         RNA_id_pointer_create(*(void**)data, &newptr);
2264                                 } else {
2265                                         /* note: this is taken from the function's ID pointer
2266                                          * and will break if a function returns a pointer from
2267                                          * another ID block, watch this! - it should at least be
2268                                          * easy to debug since they are all ID's */
2269                                         RNA_pointer_create(ptr->id.data, type, *(void**)data, &newptr);
2270                                 }
2271                         }
2272
2273                         if (newptr.data) {
2274                                 ret = pyrna_struct_CreatePyObject(&newptr);
2275                         } else {
2276                                 ret = Py_None;
2277                                 Py_INCREF(ret);
2278                         }
2279                         break;
2280                 }
2281                 case PROP_COLLECTION:
2282                 {
2283                         ListBase *lb= (ListBase*)data;
2284                         CollectionPointerLink *link;
2285                         PyObject *linkptr;
2286
2287                         ret = PyList_New(0);
2288
2289                         for(link=lb->first; link; link=link->next) {
2290                                 linkptr= pyrna_struct_CreatePyObject(&link->ptr);
2291                                 PyList_Append(ret, linkptr);
2292                                 Py_DECREF(linkptr);
2293                         }
2294
2295                         break;
2296                 }
2297                 default:
2298                         PyErr_Format(PyExc_TypeError, "RNA Error: unknown type \"%d\" (pyrna_param_to_py)", type);
2299                         ret = NULL;
2300                         break;
2301                 }
2302         }
2303
2304         return ret;
2305 }
2306
2307 static PyObject * pyrna_func_call(PyObject *self, PyObject *args, PyObject *kw)
2308 {
2309         /* Note, both BPy_StructRNA and BPy_PropertyRNA can be used here */
2310         PointerRNA *self_ptr= &(((BPy_DummyPointerRNA *)PyTuple_GET_ITEM(self, 0))->ptr);
2311         FunctionRNA *self_func=  PyCObject_AsVoidPtr(PyTuple_GET_ITEM(self, 1));
2312
2313         PointerRNA funcptr;
2314         ParameterList parms;
2315         ParameterIterator iter;
2316         PropertyRNA *pret, *parm;
2317         PyObject *ret, *item;
2318         int i, args_len, parms_len, flag, err= 0, kw_tot= 0, kw_arg;
2319         const char *parm_id;
2320         void *retdata= NULL;
2321
2322         /* Should never happen but it does in rare cases */
2323         if(self_ptr==NULL) {
2324                 PyErr_SetString(PyExc_RuntimeError, "rna functions internal rna pointer is NULL, this is a bug. aborting");
2325                 return NULL;
2326         }
2327         
2328         if(self_func==NULL) {
2329                 PyErr_Format(PyExc_RuntimeError, "%.200s.<unknown>(): rna function internal function is NULL, this is a bug. aborting", RNA_struct_identifier(self_ptr->type));
2330                 return NULL;
2331         }
2332         
2333         /* include the ID pointer for pyrna_param_to_py() so we can include the
2334          * ID pointer on return values, this only works when returned values have
2335          * the same ID as the functions. */
2336         RNA_pointer_create(self_ptr->id.data, &RNA_Function, self_func, &funcptr);
2337
2338         pret= RNA_function_return(self_func);
2339         args_len= PyTuple_GET_SIZE(args);
2340
2341         RNA_parameter_list_create(&parms, self_ptr, self_func);
2342         RNA_parameter_list_begin(&parms, &iter);
2343         parms_len = RNA_parameter_list_size(&parms);
2344
2345         if(args_len + (kw ? PyDict_Size(kw):0) > parms_len) {
2346                 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);
2347                 err= -1;
2348         }
2349
2350         /* parse function parameters */
2351         for (i= 0; iter.valid && err==0; RNA_parameter_list_next(&iter)) {
2352                 parm= iter.parm;
2353
2354                 if (parm==pret) {
2355                         retdata= iter.data;
2356                         continue;
2357                 }
2358
2359                 parm_id= RNA_property_identifier(parm);
2360                 flag= RNA_property_flag(parm);
2361                 item= NULL;
2362
2363                 if ((i < args_len) && (flag & PROP_REQUIRED)) {
2364                         item= PyTuple_GET_ITEM(args, i);
2365                         i++;
2366
2367                         kw_arg= FALSE;
2368                 }
2369                 else if (kw != NULL) {
2370                         item= PyDict_GetItemString(kw, parm_id);  /* borrow ref */
2371                         if(item)
2372                                 kw_tot++; /* make sure invalid keywords are not given */
2373
2374                         kw_arg= TRUE;
2375                 }
2376
2377                 if (item==NULL) {
2378                         if(flag & PROP_REQUIRED) {
2379                                 PyErr_Format(PyExc_TypeError, "%.200s.%.200s(): required parameter \"%.200s\" not specified", RNA_struct_identifier(self_ptr->type), RNA_function_identifier(self_func), parm_id);
2380                                 err= -1;
2381                                 break;
2382                         }
2383                         else /* PyDict_GetItemString wont raise an error */
2384                                 continue;
2385                 }
2386
2387                 err= pyrna_py_to_prop(&funcptr, parm, iter.data, item, "");
2388
2389                 if(err!=0) {
2390                         /* the error generated isnt that useful, so generate it again with a useful prefix
2391                          * could also write a function to prepend to error messages */
2392                         char error_prefix[512];
2393                         PyErr_Clear(); /* re-raise */
2394
2395                         if(kw_arg==TRUE)
2396                                 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);
2397                         else
2398                                 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);
2399
2400                         pyrna_py_to_prop(&funcptr, parm, iter.data, item, error_prefix);
2401
2402                         break;
2403                 }
2404         }
2405
2406
2407         /* Check if we gave args that dont exist in the function
2408          * printing the error is slow but it should only happen when developing.
2409          * the if below is quick, checking if it passed less keyword args then we gave.
2410          * (Dont overwrite the error if we have one, otherwise can skip important messages and confuse with args)
2411          */
2412         if(err == 0 && kw && (PyDict_Size(kw) > kw_tot)) {
2413                 PyObject *key, *value;
2414                 Py_ssize_t pos = 0;
2415
2416                 DynStr *bad_args= BLI_dynstr_new();
2417                 DynStr *good_args= BLI_dynstr_new();
2418
2419                 char *arg_name, *bad_args_str, *good_args_str;
2420                 int found= FALSE, first= TRUE;
2421
2422                 while (PyDict_Next(kw, &pos, &key, &value)) {
2423
2424                         arg_name= _PyUnicode_AsString(key);
2425                         found= FALSE;
2426
2427                         if(arg_name==NULL) { /* unlikely the argname is not a string but ignore if it is*/
2428                                 PyErr_Clear();
2429                         }
2430                         else {
2431                                 /* Search for arg_name */
2432                                 RNA_parameter_list_begin(&parms, &iter);
2433                                 for(; iter.valid; RNA_parameter_list_next(&iter)) {
2434                                         parm= iter.parm;
2435                                         if (strcmp(arg_name, RNA_property_identifier(parm))==0) {
2436                                                 found= TRUE;
2437                                                 break;
2438                                         }
2439                                 }
2440
2441                                 RNA_parameter_list_end(&iter);
2442
2443                                 if(found==FALSE) {
2444                                         BLI_dynstr_appendf(bad_args, first ? "%s" : ", %s", arg_name);
2445                                         first= FALSE;
2446                                 }
2447                         }
2448                 }
2449
2450                 /* list good args */
2451                 first= TRUE;
2452
2453                 RNA_parameter_list_begin(&parms, &iter);
2454                 for(; iter.valid; RNA_parameter_list_next(&iter)) {
2455                         parm= iter.parm;
2456                         BLI_dynstr_appendf(good_args, first ? "%s" : ", %s", RNA_property_identifier(parm));
2457                         first= FALSE;
2458                 }
2459                 RNA_parameter_list_end(&iter);
2460
2461
2462                 bad_args_str= BLI_dynstr_get_cstring(bad_args);
2463                 good_args_str= BLI_dynstr_get_cstring(good_args);
2464
2465                 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);
2466
2467                 BLI_dynstr_free(bad_args);
2468                 BLI_dynstr_free(good_args);
2469                 MEM_freeN(bad_args_str);
2470                 MEM_freeN(good_args_str);
2471
2472                 err= -1;
2473         }
2474
2475         ret= NULL;
2476         if (err==0) {
2477                 /* call function */
2478                 ReportList reports;
2479                 bContext *C= BPy_GetContext();
2480
2481                 BKE_reports_init(&reports, RPT_STORE);
2482                 RNA_function_call(C, &reports, self_ptr, self_func, &parms);
2483
2484                 err= (BPy_reports_to_error(&reports))? -1: 0;
2485                 BKE_reports_clear(&reports);
2486
2487                 /* return value */
2488                 if(err==0) {
2489                         if(pret) {
2490                                 ret= pyrna_param_to_py(&funcptr, pret, retdata);
2491
2492                                 /* possible there is an error in conversion */
2493                                 if(ret==NULL)
2494                                         err= -1;
2495                         }
2496                 }
2497         }
2498
2499         /* cleanup */
2500         RNA_parameter_list_end(&iter);
2501         RNA_parameter_list_free(&parms);
2502
2503         if (ret)
2504                 return ret;
2505
2506         if (err==-1)
2507                 return NULL;
2508
2509         Py_RETURN_NONE;
2510 }
2511
2512 /*-----------------------BPy_StructRNA method def------------------------------*/
2513 PyTypeObject pyrna_struct_Type = {
2514         PyVarObject_HEAD_INIT(NULL, 0)
2515         "StructRNA",                    /* tp_name */
2516         sizeof( BPy_StructRNA ),        /* tp_basicsize */
2517         0,                      /* tp_itemsize */
2518         /* methods */
2519         ( destructor ) pyrna_struct_dealloc,/* tp_dealloc */
2520         NULL,                       /* printfunc tp_print; */
2521         NULL,                                           /* getattrfunc tp_getattr; */
2522         NULL,                                           /* setattrfunc tp_setattr; */
2523         NULL,                                           /* tp_compare */ /* DEPRECATED in python 3.0! */
2524         ( reprfunc ) pyrna_struct_repr, /* tp_repr */
2525
2526         /* Method suites for standard classes */
2527
2528         NULL,                       /* PyNumberMethods *tp_as_number; */
2529         &pyrna_struct_as_sequence,      /* PySequenceMethods *tp_as_sequence; */
2530         &pyrna_struct_as_mapping,       /* PyMappingMethods *tp_as_mapping; */
2531
2532         /* More standard operations (here for binary compatibility) */
2533
2534         ( hashfunc )pyrna_struct_hash,  /* hashfunc tp_hash; */
2535         NULL,                                           /* ternaryfunc tp_call; */
2536         NULL,                       /* reprfunc tp_str; */
2537         ( getattrofunc ) pyrna_struct_getattro, /* getattrofunc tp_getattro; */
2538         ( setattrofunc ) pyrna_struct_setattro, /* setattrofunc tp_setattro; */
2539
2540         /* Functions to access object as input/output buffer */
2541         NULL,                       /* PyBufferProcs *tp_as_buffer; */
2542
2543   /*** Flags to define presence of optional/expanded features ***/
2544         Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE,         /* long tp_flags; */
2545
2546         NULL,                                           /*  char *tp_doc;  Documentation string */
2547   /*** Assigned meaning in release 2.0 ***/
2548         /* call function for all accessible objects */
2549         NULL,                       /* traverseproc tp_traverse; */
2550
2551         /* delete references to contained objects */
2552         NULL,                       /* inquiry tp_clear; */
2553
2554   /***  Assigned meaning in release 2.1 ***/
2555   /*** rich comparisons ***/
2556         (richcmpfunc)pyrna_struct_richcmp,      /* richcmpfunc tp_richcompare; */
2557
2558   /***  weak reference enabler ***/
2559         0,                          /* long tp_weaklistoffset; */
2560
2561   /*** Added in release 2.2 ***/
2562         /*   Iterators */
2563         NULL,                       /* getiterfunc tp_iter; */
2564         NULL,                       /* iternextfunc tp_iternext; */
2565
2566   /*** Attribute descriptor and subclassing stuff ***/
2567         pyrna_struct_methods,                   /* struct PyMethodDef *tp_methods; */
2568         NULL,                       /* struct PyMemberDef *tp_members; */
2569         NULL,                                           /* struct PyGetSetDef *tp_getset; */
2570         NULL,                       /* struct _typeobject *tp_base; */
2571         NULL,                       /* PyObject *tp_dict; */
2572         NULL,                       /* descrgetfunc tp_descr_get; */
2573         NULL,                       /* descrsetfunc tp_descr_set; */
2574         0,                          /* long tp_dictoffset; */
2575         NULL,                       /* initproc tp_init; */
2576         NULL,                       /* allocfunc tp_alloc; */
2577         pyrna_struct_new,                       /* newfunc tp_new; */
2578         /*  Low-level free-memory routine */
2579         NULL,                       /* freefunc tp_free;  */
2580         /* For PyObject_IS_GC */
2581         NULL,                       /* inquiry tp_is_gc;  */
2582         NULL,                       /* PyObject *tp_bases; */
2583         /* method resolution order */
2584         NULL,                       /* PyObject *tp_mro;  */
2585         NULL,                       /* PyObject *tp_cache; */
2586         NULL,                       /* PyObject *tp_subclasses; */
2587         NULL,                       /* PyObject *tp_weaklist; */
2588         NULL
2589 };
2590
2591 /*-----------------------BPy_PropertyRNA method def------------------------------*/
2592 PyTypeObject pyrna_prop_Type = {
2593         PyVarObject_HEAD_INIT(NULL, 0)
2594         "PropertyRNA",          /* tp_name */
2595         sizeof( BPy_PropertyRNA ),                      /* tp_basicsize */
2596         0,                      /* tp_itemsize */
2597         /* methods */
2598         NULL,                                           /* tp_dealloc */
2599         NULL,                       /* printfunc tp_print; */
2600         NULL,                                           /* getattrfunc tp_getattr; */
2601         NULL,                       /* setattrfunc tp_setattr; */
2602         NULL,                                           /* tp_compare */ /* DEPRECATED in python 3.0! */
2603         ( reprfunc ) pyrna_prop_repr,   /* tp_repr */
2604
2605         /* Method suites for standard classes */
2606
2607         NULL,                       /* PyNumberMethods *tp_as_number; */
2608         &pyrna_prop_as_sequence,        /* PySequenceMethods *tp_as_sequence; */
2609         &pyrna_prop_as_mapping,         /* PyMappingMethods *tp_as_mapping; */
2610
2611         /* More standard operations (here for binary compatibility) */
2612
2613         NULL,                                           /* hashfunc tp_hash; */
2614         NULL,                       /* ternaryfunc tp_call; */
2615         NULL,                       /* reprfunc tp_str; */
2616
2617         /* will only use these if this is a subtype of a py class */
2618         ( getattrofunc ) pyrna_prop_getattro,   /* getattrofunc tp_getattro; */
2619         ( setattrofunc ) pyrna_prop_setattro,   /* setattrofunc tp_setattro; */
2620
2621         /* Functions to access object as input/output buffer */
2622         NULL,                       /* PyBufferProcs *tp_as_buffer; */
2623
2624   /*** Flags to define presence of optional/expanded features ***/
2625         Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE,         /* long tp_flags; */
2626
2627         NULL,                                           /*  char *tp_doc;  Documentation string */
2628   /*** Assigned meaning in release 2.0 ***/
2629         /* call function for all accessible objects */
2630         NULL,                       /* traverseproc tp_traverse; */
2631
2632         /* delete references to contained objects */
2633         NULL,                       /* inquiry tp_clear; */
2634
2635   /***  Assigned meaning in release 2.1 ***/
2636   /*** rich comparisons ***/
2637         (richcmpfunc)pyrna_prop_richcmp,        /* richcmpfunc tp_richcompare; */
2638
2639   /***  weak reference enabler ***/
2640         0,                          /* long tp_weaklistoffset; */
2641
2642   /*** Added in release 2.2 ***/
2643         /*   Iterators */
2644         (getiterfunc)pyrna_prop_iter,   /* getiterfunc tp_iter; */
2645         NULL,                       /* iternextfunc tp_iternext; */
2646
2647   /*** Attribute descriptor and subclassing stuff ***/
2648         pyrna_prop_methods,                     /* struct PyMethodDef *tp_methods; */
2649         NULL,                       /* struct PyMemberDef *tp_members; */
2650         NULL /*pyrna_prop_getseters*/,          /* struct PyGetSetDef *tp_getset; */
2651         NULL,                       /* struct _typeobject *tp_base; */
2652         NULL,                       /* PyObject *tp_dict; */
2653         NULL,                       /* descrgetfunc tp_descr_get; */
2654         NULL,                       /* descrsetfunc tp_descr_set; */
2655         0,                          /* long tp_dictoffset; */
2656         NULL,                       /* initproc tp_init; */
2657         NULL,                       /* allocfunc tp_alloc; */
2658         pyrna_prop_new,                         /* newfunc tp_new; */
2659         /*  Low-level free-memory routine */
2660         NULL,                       /* freefunc tp_free;  */
2661         /* For PyObject_IS_GC */
2662         NULL,                       /* inquiry tp_is_gc;  */
2663         NULL,                       /* PyObject *tp_bases; */
2664         /* method resolution order */
2665         NULL,                       /* PyObject *tp_mro;  */
2666         NULL,                       /* PyObject *tp_cache; */
2667         NULL,                       /* PyObject *tp_subclasses; */
2668         NULL,                       /* PyObject *tp_weaklist; */
2669         NULL
2670 };
2671
2672 static struct PyMethodDef pyrna_struct_subtype_methods[] = {
2673         {"BoolProperty", (PyCFunction)BPy_BoolProperty, METH_VARARGS|METH_KEYWORDS, ""},
2674         {"IntProperty", (PyCFunction)BPy_IntProperty, METH_VARARGS|METH_KEYWORDS, ""},
2675         {"FloatProperty", (PyCFunction)BPy_FloatProperty, METH_VARARGS|METH_KEYWORDS, ""},
2676         {"StringProperty", (PyCFunction)BPy_StringProperty, METH_VARARGS|METH_KEYWORDS, ""},
2677         {"EnumProperty", (PyCFunction)BPy_EnumProperty, METH_VARARGS|METH_KEYWORDS, ""},
2678         {"PointerProperty", (PyCFunction)BPy_PointerProperty, METH_VARARGS|METH_KEYWORDS, ""},
2679         {"CollectionProperty", (PyCFunction)BPy_CollectionProperty, METH_VARARGS|METH_KEYWORDS, ""},
2680
2681 //      {"__get_rna", (PyCFunction)BPy_GetStructRNA, METH_NOARGS, ""},
2682         {NULL, NULL, 0, NULL}
2683 };
2684
2685 static void pyrna_subtype_set_rna(PyObject *newclass, StructRNA *srna)
2686 {
2687         PointerRNA ptr;
2688         PyObject *item;
2689         
2690         Py_INCREF(newclass);
2691
2692         if (RNA_struct_py_type_get(srna))
2693                 PyObSpit("RNA WAS SET - ", RNA_struct_py_type_get(srna));
2694         
2695         Py_XDECREF(((PyObject *)RNA_struct_py_type_get(srna)));
2696         
2697         RNA_struct_py_type_set(srna, (void *)newclass); /* Store for later use */
2698
2699         /* Not 100% needed but useful,
2700          * having an instance within a type looks wrong however this instance IS an rna type */
2701
2702         /* python deals with the curcular ref */
2703         RNA_pointer_create(NULL, &RNA_Struct, srna, &ptr);
2704         item = pyrna_struct_CreatePyObject(&ptr);
2705
2706         //item = PyCObject_FromVoidPtr(srna, NULL);
2707         PyDict_SetItemString(((PyTypeObject *)newclass)->tp_dict, "bl_rna", item);
2708         Py_DECREF(item);
2709         /* done with rna instance */
2710
2711         /* attach functions into the class
2712          * so you can do... bpy.types.Scene.SomeFunction()
2713          */
2714         {
2715                 PyMethodDef *ml;
2716
2717                 for(ml= pyrna_struct_subtype_methods; ml->ml_name; ml++){
2718                         PyObject_SetAttrString(newclass, ml->ml_name, PyCFunction_New(ml, newclass));
2719                 }
2720         }
2721 }
2722
2723 /*
2724 static StructRNA *srna_from_self(PyObject *self);
2725 PyObject *BPy_GetStructRNA(PyObject *self)
2726 {
2727         StructRNA *srna= pyrna_struct_as_srna(self);
2728         PointerRNA ptr;
2729         PyObject *ret;
2730
2731         RNA_pointer_create(NULL, &RNA_Struct, srna, &ptr);
2732         ret= pyrna_struct_CreatePyObject(&ptr);
2733
2734         if(ret) {
2735                 return ret;
2736         }
2737         else {
2738                 Py_RETURN_NONE;
2739         }
2740 }
2741 */
2742
2743 static PyObject* pyrna_srna_Subtype(StructRNA *srna);
2744
2745 /* return a borrowed reference */
2746 static PyObject* pyrna_srna_PyBase(StructRNA *srna) //, PyObject *bpy_types_dict)
2747 {
2748         /* Assume RNA_struct_py_type_get(srna) was already checked */
2749         StructRNA *base;
2750
2751         PyObject *py_base= NULL;
2752
2753         /* get the base type */
2754         base= RNA_struct_base(srna);
2755
2756         if(base && base != srna) {
2757                 /*/printf("debug subtype %s %p\n", RNA_struct_identifier(srna), srna); */
2758                 py_base= pyrna_srna_Subtype(base); //, bpy_types_dict);
2759                 Py_DECREF(py_base); /* srna owns, this is only to pass as an arg */
2760         }
2761
2762         if(py_base==NULL) {
2763                 py_base= (PyObject *)&pyrna_struct_Type;
2764         }
2765
2766         return py_base;
2767 }
2768
2769 /* check if we have a native python subclass, use it when it exists
2770  * return a borrowed reference */
2771 static PyObject* pyrna_srna_ExternalType(StructRNA *srna)
2772 {
2773         PyObject *bpy_types_dict= NULL;
2774         const char *idname= RNA_struct_identifier(srna);
2775         PyObject *newclass;
2776
2777         if(bpy_types_dict==NULL) {
2778                 PyObject *bpy_types= PyImport_ImportModuleLevel("bpy_types", NULL, NULL, NULL, 0);
2779
2780                 if(bpy_types==NULL) {
2781                         PyErr_Print();
2782                         PyErr_Clear();
2783                         fprintf(stderr, "pyrna_srna_ExternalType: failed to find 'bpy_types' module\n");
2784                         return NULL;
2785                 }
2786
2787                 bpy_types_dict = PyModule_GetDict(bpy_types); // borrow
2788                 Py_DECREF(bpy_types); // fairly safe to assume the dict is kept
2789         }
2790
2791         newclass= PyDict_GetItemString(bpy_types_dict, idname);
2792
2793         /* sanity check, could skip this unless in debug mode */
2794         if(newclass) {
2795                 PyObject *base_compare= pyrna_srna_PyBase(srna);
2796                 PyObject *bases= PyObject_GetAttrString(newclass, "__bases__");
2797
2798                 if(PyTuple_GET_SIZE(bases)) {
2799                         PyObject *base= PyTuple_GET_ITEM(bases, 0);
2800
2801                         if(base_compare != base) {
2802                                 PyLineSpit();
2803                                 fprintf(stderr, "pyrna_srna_ExternalType: incorrect subclassing of SRNA '%s'\n", idname);
2804                                 PyObSpit("Expected! ", base_compare);
2805                                 newclass= NULL;
2806                         }
2807                         else {
2808                                 if(G.f & G_DEBUG)
2809                                         fprintf(stderr, "SRNA Subclassed: '%s'\n", idname);
2810                         }
2811                 }
2812
2813                 Py_DECREF(bases);
2814         }
2815
2816         return newclass;
2817 }
2818
2819 static PyObject* pyrna_srna_Subtype(StructRNA *srna)
2820 {
2821         PyObject *newclass = NULL;
2822
2823         if (srna == NULL) {
2824                 newclass= NULL; /* Nothing to do */
2825         } else if ((newclass= RNA_struct_py_type_get(srna))) {
2826                 Py_INCREF(newclass);
2827         } else if ((newclass= pyrna_srna_ExternalType(srna))) {
2828                 pyrna_subtype_set_rna(newclass, srna);
2829                 Py_INCREF(newclass);
2830         } else {
2831                 /* subclass equivelents
2832                 - class myClass(myBase):
2833                         some='value' # or ...
2834                 - myClass = type(name='myClass', bases=(myBase,), dict={'__module__':'bpy.types'})
2835                 */
2836
2837                 /* Assume RNA_struct_py_type_get(srna) was alredy checked */
2838                 PyObject *py_base= pyrna_srna_PyBase(srna);
2839
2840                 const char *idname= RNA_struct_identifier(srna);
2841                 const char *descr= RNA_struct_ui_description(srna);
2842
2843                 if(!descr) descr= "(no docs)";
2844                 
2845                 /* always use O not N when calling, N causes refcount errors */
2846                 newclass = PyObject_CallFunction(       (PyObject*)&PyType_Type, "s(O){ssss}", idname, py_base, "__module__","bpy.types", "__doc__",descr);
2847                 /* newclass will now have 2 ref's, ???, probably 1 is internal since decrefing here segfaults */
2848
2849                 /* PyObSpit("new class ref", newclass); */
2850
2851                 if (newclass) {
2852
2853                         /* srna owns one, and the other is owned by the caller */
2854                         pyrna_subtype_set_rna(newclass, srna);
2855
2856                         Py_DECREF(newclass); /* let srna own */
2857                 }
2858                 else {
2859                         /* this should not happen */
2860                         PyErr_Print();
2861                         PyErr_Clear();
2862                 }
2863         }
2864         
2865         return newclass;
2866 }
2867
2868 /* use for subtyping so we know which srna is used for a PointerRNA */
2869 static StructRNA *srna_from_ptr(PointerRNA *ptr)
2870 {
2871         if(ptr->type == &RNA_Struct) {
2872                 return ptr->data;
2873         }
2874         else {
2875                 return ptr->type;
2876         }
2877 }
2878
2879 /* always returns a new ref, be sure to decref when done */
2880 static PyObject* pyrna_struct_Subtype(PointerRNA *ptr)
2881 {
2882         return pyrna_srna_Subtype(srna_from_ptr(ptr));
2883 }
2884
2885 /*-----------------------CreatePyObject---------------------------------*/
2886 PyObject *pyrna_struct_CreatePyObject( PointerRNA *ptr )
2887 {
2888         BPy_StructRNA *pyrna= NULL;
2889         
2890         if (ptr->data==NULL && ptr->type==NULL) { /* Operator RNA has NULL data */
2891                 Py_RETURN_NONE;
2892         }
2893         else {
2894                 PyTypeObject *tp = (PyTypeObject *)pyrna_struct_Subtype(ptr);
2895                 
2896                 if (tp) {
2897                         pyrna = (BPy_StructRNA *) tp->tp_alloc(tp, 0);
2898                         Py_DECREF(tp); /* srna owns, cant hold a ref */
2899                 }
2900                 else {
2901                         fprintf(stderr, "Could not make type\n");
2902                         pyrna = ( BPy_StructRNA * ) PyObject_NEW( BPy_StructRNA, &pyrna_struct_Type );
2903                 }
2904         }
2905
2906         if( !pyrna ) {
2907                 PyErr_SetString( PyExc_MemoryError, "couldn't create BPy_StructRNA object" );
2908                 return NULL;
2909         }
2910         
2911         pyrna->ptr= *ptr;
2912         pyrna->freeptr= FALSE;
2913         
2914         // PyObSpit("NewStructRNA: ", (PyObject *)pyrna);
2915         
2916         return ( PyObject * ) pyrna;
2917 }
2918
2919 PyObject *pyrna_prop_CreatePyObject( PointerRNA *ptr, PropertyRNA *prop )
2920 {
2921         BPy_PropertyRNA *pyrna;
2922
2923         pyrna = ( BPy_PropertyRNA * ) PyObject_NEW( BPy_PropertyRNA, &pyrna_prop_Type );
2924
2925         if( !pyrna ) {
2926                 PyErr_SetString( PyExc_MemoryError, "couldn't create BPy_rna object" );
2927                 return NULL;
2928         }
2929         
2930         pyrna->ptr = *ptr;
2931         pyrna->prop = prop;
2932
2933         pyrna->arraydim= 0;
2934         pyrna->arrayoffset= 0;
2935                 
2936         return ( PyObject * ) pyrna;
2937 }
2938
2939 void BPY_rna_init(void)
2940 {
2941 #ifdef USE_MATHUTILS // register mathutils callbacks, ok to run more then once.
2942         mathutils_rna_array_cb_index= Mathutils_RegisterCallback(&mathutils_rna_array_cb);
2943         mathutils_rna_matrix_cb_index= Mathutils_RegisterCallback(&mathutils_rna_matrix_cb);
2944 #endif
2945
2946         if( PyType_Ready( &pyrna_struct_Type ) < 0 )
2947                 return;
2948
2949         if( PyType_Ready( &pyrna_prop_Type ) < 0 )
2950                 return;
2951 }
2952
2953 /* bpy.data from python */
2954 static PointerRNA *rna_module_ptr= NULL;
2955 PyObject *BPY_rna_module(void)
2956 {
2957         BPy_StructRNA *pyrna;
2958         PointerRNA ptr;
2959
2960         /* for now, return the base RNA type rather then a real module */
2961         RNA_main_pointer_create(G.main, &ptr);
2962         pyrna= (BPy_StructRNA *)pyrna_struct_CreatePyObject(&ptr);
2963         
2964         rna_module_ptr= &pyrna->ptr;
2965         return (PyObject *)pyrna;
2966 }
2967
2968 void BPY_update_rna_module(void)
2969 {
2970         RNA_main_pointer_create(G.main, rna_module_ptr);
2971 }
2972
2973 #if 0
2974 /* This is a way we can access docstrings for RNA types
2975  * without having the datatypes in blender */
2976 PyObject *BPY_rna_doc( void )
2977 {
2978         PointerRNA ptr;
2979         
2980         /* for now, return the base RNA type rather then a real module */
2981         RNA_blender_rna_pointer_create(&ptr);
2982         
2983         return pyrna_struct_CreatePyObject(&ptr);
2984 }
2985 #endif
2986
2987
2988 /* pyrna_basetype_* - BPy_BaseTypeRNA is just a BPy_PropertyRNA struct with a differnt type
2989  * the self->ptr and self->prop are always set to the "structs" collection */
2990 //---------------getattr--------------------------------------------
2991 static PyObject *pyrna_basetype_getattro( BPy_BaseTypeRNA *self, PyObject *pyname )
2992 {
2993         PointerRNA newptr;
2994         PyObject *ret;
2995         
2996         if (RNA_property_collection_lookup_string(&self->ptr, self->prop, _PyUnicode_AsString(pyname), &newptr)) {
2997                 ret= pyrna_struct_Subtype(&newptr);
2998                 if (ret==NULL) {
2999                         PyErr_Format(PyExc_SystemError, "bpy.types.%.200s subtype could not be generated, this is a bug!", _PyUnicode_AsString(pyname));
3000                 }
3001         }
3002         else {
3003 #if 0
3004                 PyErr_Format(PyExc_AttributeError, "bpy.types.%.200s RNA_Struct does not exist", _PyUnicode_AsString(pyname));
3005                 return NULL;
3006 #endif
3007                 /* The error raised here will be displayed */
3008                 ret= PyObject_GenericGetAttr((PyObject *)self, pyname);
3009         }
3010
3011         return ret;
3012 }
3013
3014 static PyObject *pyrna_basetype_dir(BPy_BaseTypeRNA *self);
3015 static struct PyMethodDef pyrna_basetype_methods[] = {
3016         {"__dir__", (PyCFunction)pyrna_basetype_dir, METH_NOARGS, ""},
3017         {"register", (PyCFunction)pyrna_basetype_register, METH_O, ""},
3018         {"unregister", (PyCFunction)pyrna_basetype_unregister, METH_O, ""},
3019         {NULL, NULL, 0, NULL}
3020 };
3021
3022 static PyObject *pyrna_basetype_dir(BPy_BaseTypeRNA *self)
3023 {
3024         PyObject *list, *name;
3025         PyMethodDef *meth;
3026         
3027         list= pyrna_prop_keys(self); /* like calling structs.keys(), avoids looping here */
3028
3029         for(meth=pyrna_basetype_methods; meth->ml_name; meth++) {
3030                 name = PyUnicode_FromString(meth->ml_name);
3031                 PyList_Append(list, name);
3032                 Py_DECREF(name);
3033         }
3034         
3035         return list;
3036 }
3037
3038 PyTypeObject pyrna_basetype_Type = BLANK_PYTHON_TYPE;
3039
3040 PyObject *BPY_rna_types(void)
3041 {
3042         BPy_BaseTypeRNA *self;
3043
3044         if ((pyrna_basetype_Type.tp_flags & Py_TPFLAGS_READY)==0)  {
3045                 pyrna_basetype_Type.tp_name = "RNA_Types";
3046                 pyrna_basetype_Type.tp_basicsize = sizeof( BPy_BaseTypeRNA );
3047                 pyrna_basetype_Type.tp_getattro = ( getattrofunc )pyrna_basetype_getattro;
3048                 pyrna_basetype_Type.tp_flags = Py_TPFLAGS_DEFAULT;
3049                 pyrna_basetype_Type.tp_methods = pyrna_basetype_methods;
3050                 
3051                 if( PyType_Ready( &pyrna_basetype_Type ) < 0 )
3052                         return NULL;
3053         }
3054         
3055         self= (BPy_BaseTypeRNA *)PyObject_NEW( BPy_BaseTypeRNA, &pyrna_basetype_Type );
3056         
3057         /* avoid doing this lookup for every getattr */
3058         RNA_blender_rna_pointer_create(&self->ptr);
3059         self->prop = RNA_struct_find_property(&self->ptr, "structs");
3060         
3061         return (PyObject *)self;
3062 }
3063
3064 static struct PyMethodDef props_methods[] = {
3065         {"BoolProperty", (PyCFunction)BPy_BoolProperty, METH_VARARGS|METH_KEYWORDS, ""},
3066         {"IntProperty", (PyCFunction)BPy_IntProperty, METH_VARARGS|METH_KEYWORDS, ""},
3067         {"FloatProperty", (PyCFunction)BPy_FloatProperty, METH_VARARGS|METH_KEYWORDS, ""},
3068         {"StringProperty", (PyCFunction)BPy_StringProperty, METH_VARARGS|METH_KEYWORDS, ""},
3069         {"EnumProperty", (PyCFunction)BPy_EnumProperty, METH_VARARGS|METH_KEYWORDS, ""},
3070         {"PointerProperty", (PyCFunction)BPy_PointerProperty, METH_VARARGS|METH_KEYWORDS, ""},
3071         {"CollectionProperty", (PyCFunction)BPy_CollectionProperty, METH_VARARGS|METH_KEYWORDS, ""},
3072         {NULL, NULL, 0, NULL}
3073 };
3074
3075 static struct PyModuleDef props_module = {
3076         PyModuleDef_HEAD_INIT,
3077         "bpy.props",
3078         "",
3079         -1,/* multiple "initialization" just copies the module dict. */
3080         props_methods,
3081         NULL, NULL, NULL, NULL
3082 };
3083
3084 PyObject *BPY_rna_props( void )
3085 {
3086         PyObject *submodule;
3087         submodule= PyModule_Create(&props_module);
3088         PyDict_SetItemString(PySys_GetObject("modules"), props_module.m_name, submodule);
3089         
3090         /* INCREF since its its assumed that all these functions return the
3091          * module with a new ref like PyDict_New, since they are passed to
3092           * PyModule_AddObject which steals a ref */
3093         Py_INCREF(submodule);
3094         
3095         return submodule;
3096 }
3097
3098 static StructRNA *pyrna_struct_as_srna(PyObject *self)
3099 {
3100         BPy_StructRNA *py_srna = NULL;
3101         StructRNA *srna;
3102         
3103         /* ack, PyObject_GetAttrString wont look up this types tp_dict first :/ */
3104         if(PyType_Check(self)) {
3105                 py_srna = (BPy_StructRNA *)PyDict_GetItemString(((PyTypeObject *)self)->tp_dict, "bl_rna");
3106                 Py_XINCREF(py_srna);
3107         }
3108         
3109         if(py_srna==NULL)
3110                 py_srna = (BPy_StructRNA*)PyObject_GetAttrString(self, "bl_rna");
3111
3112         if(py_srna==NULL) {
3113                 PyErr_SetString(PyExc_SystemError, "internal error, self had no bl_rna attribute, should never happen.");
3114                 return NULL;
3115         }
3116
3117         if(!BPy_StructRNA_Check(py_srna)) {
3118                 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);
3119                 Py_DECREF(py_srna);
3120                 return NULL;
3121         }
3122
3123         if(py_srna->ptr.type != &RNA_Struct) {
3124                 PyErr_SetString(PyExc_SystemError, "internal error, bl_rna was not a RNA_Struct type of rna struct.");
3125                 Py_DECREF(py_srna);
3126                 return NULL;
3127         }
3128
3129         srna= py_srna->ptr.data;
3130         Py_DECREF(py_srna);
3131
3132         return srna;
3133 }
3134
3135
3136 /* Orphan functions, not sure where they should go */
3137 /* get the srna for methods attached to types */
3138 /* */
3139 static StructRNA *srna_from_self(PyObject *self)
3140 {
3141         /* a bit sloppy but would cause a very confusing bug if
3142          * an error happened to be set here */
3143         PyErr_Clear();
3144         
3145         if(self==NULL) {
3146                 return NULL;
3147         }
3148         else if (PyCObject_Check(self)) {
3149                 return PyCObject_AsVoidPtr(self);
3150         }
3151         else if (PyType_Check(self)==0) {
3152                 return NULL;
3153         }
3154         /* These cases above not errors, they just mean the type was not compatible
3155          * After this any errors will be raised in the script */
3156
3157         return pyrna_struct_as_srna(self);
3158 }
3159
3160 /* operators use this so it can store the args given but defer running
3161  * it until the operator runs where these values are used to setup the 
3162  * default args for that operator instance */
3163 static PyObject *bpy_prop_deferred_return(void *func, PyObject *kw)
3164 {
3165         PyObject *ret = PyTuple_New(2);
3166         PyTuple_SET_ITEM(ret, 0, PyCObject_FromVoidPtr(func, NULL));
3167         PyTuple_SET_ITEM(ret, 1, kw);
3168         Py_INCREF(kw);
3169         return ret;     
3170 }
3171
3172 /* Function that sets RNA, NOTE - self is NULL when called from python, but being abused from C so we can pass the srna allong
3173  * This isnt incorrect since its a python object - but be careful */
3174
3175 PyObject *BPy_BoolProperty(PyObject *self, PyObject *args, PyObject *kw)
3176 {
3177         static char *kwlist[] = {"attr", "name", "description", "default", NULL};
3178         char *id=NULL, *name="", *description="";
3179         int def=0;
3180         PropertyRNA *prop;
3181         StructRNA *srna;
3182         
3183         if (PyTuple_Size(args) > 0) {
3184                 PyErr_SetString(PyExc_ValueError, "all args must be keywors"); // TODO - py3 can enforce this.
3185                 return NULL;
3186         }
3187         
3188         srna= srna_from_self(self);
3189         if(srna==NULL && PyErr_Occurred()) {
3190                 return NULL; /* self's type was compatible but error getting the srna */
3191         }
3192         else if(srna) {
3193
3194                 if (!PyArg_ParseTupleAndKeywords(args, kw, "s|ssi:BoolProperty", kwlist, &id, &name, &description, &def))
3195                         return NULL;
3196
3197                 prop= RNA_def_boolean(srna, id, def, name, description);
3198                 RNA_def_property_duplica