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