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