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