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