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