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