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