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