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