* workaround for PySys_SetArgv() in python3 needing wchar_t
[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 \"%s\" -> \"%s\"]", RNA_struct_identifier(self->ptr.type), name);
176                 MEM_freeN(name);
177                 return pyob;
178         }
179
180         return PyUnicode_FromFormat( "[BPy_StructRNA \"%s\"]", 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 \"%s\" -> \"%s\" -> \"%s\" ]", 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 \"%s\" -> \"%s\"]", 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, "%s: no keywords, expected \"%s\"", 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, "%s: keyword \"%s\" 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, "%s: keyword \"%s\" 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 %s 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 (%s)", 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 \"%s\" not found in (%s)", 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 %s 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 %s 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 %s 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_SetString(PyExc_IndexError, "out of range");
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_SetString(PyExc_IndexError, "out of range");
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_SetString(PyExc_KeyError, "key not found");
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_SetString(PyExc_AttributeError, "invalid key, key must be a string or an int");
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 \"%s\" from \"%s\" 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 \"%s\" from \"%s\" 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 NULL;
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 \"%s\" 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 \"%s\" not found", name);
1310                         return -1;
1311                 }
1312         }               
1313         
1314         if (!RNA_property_editable(&self->ptr, prop)) {
1315                 PyErr_Format( PyExc_AttributeError, "StructRNA - Attribute \"%s\" from \"%s\" 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 #if (PY_VERSION_HEX >= 0x03000000) /* foreach needs py3 */
1419 static void foreach_attr_type(  BPy_PropertyRNA *self, char *attr,
1420                                                                         /* values to assign */
1421                                                                         RawPropertyType *raw_type, int *attr_tot, int *attr_signed )
1422 {
1423         PropertyRNA *prop;
1424         *raw_type= -1;
1425         *attr_tot= 0;
1426         *attr_signed= 0;
1427
1428         RNA_PROP_BEGIN(&self->ptr, itemptr, self->prop) {
1429                 prop = RNA_struct_find_property(&itemptr, attr);
1430                 *raw_type= RNA_property_raw_type(prop);
1431                 *attr_tot = RNA_property_array_length(prop);
1432                 *attr_signed= (RNA_property_subtype(prop)==PROP_UNSIGNED) ? 0:1;
1433                 break;
1434         }
1435         RNA_PROP_END;
1436 }
1437
1438 /* pyrna_prop_foreach_get/set both use this */
1439 static int foreach_parse_args(
1440                 BPy_PropertyRNA *self, PyObject *args,
1441
1442                 /*values to assign */
1443                 char **attr, PyObject **seq, int *tot, int *size, RawPropertyType *raw_type, int *attr_tot, int *attr_signed)
1444 {
1445 #if 0
1446         int array_tot;
1447         int target_tot;
1448 #endif
1449
1450         *size= *raw_type= *attr_tot= *attr_signed= 0;
1451
1452         if(!PyArg_ParseTuple(args, "sO", attr, seq) || (!PySequence_Check(*seq) && PyObject_CheckBuffer(*seq))) {
1453                 PyErr_SetString( PyExc_TypeError, "foreach_get(attr, sequence) expects a string and a sequence" );
1454                 return -1;
1455         }
1456
1457         *tot= PySequence_Length(*seq); // TODO - buffer may not be a sequence! array.array() is tho.
1458
1459         if(*tot>0) {
1460                 foreach_attr_type(self, *attr, raw_type, attr_tot, attr_signed);
1461                 *size= RNA_raw_type_sizeof(*raw_type);
1462
1463 #if 0   // works fine but not strictly needed, we could allow RNA_property_collection_raw_* to do the checks
1464                 if((*attr_tot) < 1)
1465                         *attr_tot= 1;
1466
1467                 if (RNA_property_type(self->prop) == PROP_COLLECTION)
1468                         array_tot = RNA_property_collection_length(&self->ptr, self->prop);
1469                 else
1470                         array_tot = RNA_property_array_length(self->prop);
1471
1472
1473                 target_tot= array_tot * (*attr_tot);
1474
1475                 /* rna_access.c - rna_raw_access(...) uses this same method */
1476                 if(target_tot != (*tot)) {
1477                         PyErr_Format( PyExc_TypeError, "foreach_get(attr, sequence) sequence length mismatch given %d, needed %d", *tot, target_tot);
1478                         return -1;
1479                 }
1480 #endif
1481         }
1482
1483         return 0;
1484 }
1485
1486 static int foreach_compat_buffer(RawPropertyType raw_type, int attr_signed, const char *format)
1487 {
1488         char f = format ? *format:'B'; /* B is assumed when not set */
1489
1490         switch(raw_type) {
1491         case PROP_RAW_CHAR:
1492                 if (attr_signed)        return (f=='b') ? 1:0;
1493                 else                            return (f=='B') ? 1:0;
1494         case PROP_RAW_SHORT:
1495                 if (attr_signed)        return (f=='h') ? 1:0;
1496                 else                            return (f=='H') ? 1:0;
1497         case PROP_RAW_INT:
1498                 if (attr_signed)        return (f=='i') ? 1:0;
1499                 else                            return (f=='I') ? 1:0;
1500         case PROP_RAW_FLOAT:
1501                 return (f=='f') ? 1:0;
1502         case PROP_RAW_DOUBLE:
1503                 return (f=='d') ? 1:0;
1504         }
1505
1506         return 0;
1507 }
1508
1509 static PyObject *foreach_getset(BPy_PropertyRNA *self, PyObject *args, int set)
1510 {
1511         PyObject *item;
1512         int i=0, ok, buffer_is_compat;
1513         void *array= NULL;
1514
1515         /* get/set both take the same args currently */
1516         char *attr;
1517         PyObject *seq;
1518         int tot, size, attr_tot, attr_signed;
1519         RawPropertyType raw_type;
1520
1521         if(foreach_parse_args(self, args,    &attr, &seq, &tot, &size, &raw_type, &attr_tot, &attr_signed) < 0)
1522                 return NULL;
1523
1524         if(tot==0)
1525                 Py_RETURN_NONE;
1526
1527
1528
1529         if(set) { /* get the array from python */
1530                 buffer_is_compat = 0;
1531                 if(PyObject_CheckBuffer(seq)) {
1532                         Py_buffer buf;
1533                         PyObject_GetBuffer(seq, &buf, PyBUF_SIMPLE | PyBUF_FORMAT);
1534
1535                         /* check if the buffer matches */
1536
1537                         buffer_is_compat = foreach_compat_buffer(raw_type, attr_signed, buf.format);
1538
1539                         if(buffer_is_compat) {
1540                                 ok = RNA_property_collection_raw_set(NULL, &self->ptr, self->prop, attr, buf.buf, raw_type, tot);
1541                         }
1542
1543                         PyBuffer_Release(&buf);
1544                 }
1545
1546                 /* could not use the buffer, fallback to sequence */
1547                 if(!buffer_is_compat) {
1548                         array= PyMem_Malloc(size * tot);
1549
1550                         for( ; i<tot; i++) {
1551                                 item= PySequence_GetItem(seq, i);
1552                                 switch(raw_type) {
1553                                 case PROP_RAW_CHAR:
1554                                         ((char *)array)[i]= (char)PyLong_AsSsize_t(item);
1555                                         break;
1556                                 case PROP_RAW_SHORT:
1557                                         ((short *)array)[i]= (short)PyLong_AsSsize_t(item);
1558                                         break;
1559                                 case PROP_RAW_INT:
1560                                         ((int *)array)[i]= (int)PyLong_AsSsize_t(item);
1561                                         break;
1562                                 case PROP_RAW_FLOAT:
1563                                         ((float *)array)[i]= (float)PyFloat_AsDouble(item);
1564                                         break;
1565                                 case PROP_RAW_DOUBLE:
1566                                         ((double *)array)[i]= (double)PyFloat_AsDouble(item);
1567                                         break;
1568                                 }
1569
1570                                 Py_DECREF(item);
1571                         }
1572
1573                         ok = RNA_property_collection_raw_set(NULL, &self->ptr, self->prop, attr, array, raw_type, tot);
1574                 }
1575         }
1576         else {
1577                 buffer_is_compat = 0;
1578                 if(PyObject_CheckBuffer(seq)) {
1579                         Py_buffer buf;
1580                         PyObject_GetBuffer(seq, &buf, PyBUF_SIMPLE | PyBUF_FORMAT);
1581
1582                         /* check if the buffer matches, TODO - signed/unsigned types */
1583
1584                         buffer_is_compat = foreach_compat_buffer(raw_type, attr_signed, buf.format);
1585
1586                         if(buffer_is_compat) {
1587                                 ok = RNA_property_collection_raw_get(NULL, &self->ptr, self->prop, attr, buf.buf, raw_type, tot);
1588                         }
1589
1590                         PyBuffer_Release(&buf);
1591                 }
1592
1593                 /* could not use the buffer, fallback to sequence */
1594                 if(!buffer_is_compat) {
1595                         array= PyMem_Malloc(size * tot);
1596
1597                         ok = RNA_property_collection_raw_get(NULL, &self->ptr, self->prop, attr, array, raw_type, tot);
1598
1599                         if(!ok) i= tot; /* skip the loop */
1600
1601                         for( ; i<tot; i++) {
1602
1603                                 switch(raw_type) {
1604                                 case PROP_RAW_CHAR:
1605                                         item= PyLong_FromSsize_t(  (Py_ssize_t) ((char *)array)[i]  );
1606                                         break;
1607                                 case PROP_RAW_SHORT:
1608                                         item= PyLong_FromSsize_t(  (Py_ssize_t) ((short *)array)[i]  );
1609                                         break;
1610                                 case PROP_RAW_INT:
1611                                         item= PyLong_FromSsize_t(  (Py_ssize_t) ((int *)array)[i]  );
1612                                         break;
1613                                 case PROP_RAW_FLOAT:
1614                                         item= PyFloat_FromDouble(  (double) ((float *)array)[i]  );
1615                                         break;
1616                                 case PROP_RAW_DOUBLE:
1617                                         item= PyFloat_FromDouble(  (double) ((double *)array)[i]  );
1618                                         break;
1619                                 }
1620
1621                                 PySequence_SetItem(seq, i, item);
1622                                 Py_DECREF(item);
1623                         }
1624                 }
1625         }
1626
1627         if(PyErr_Occurred()) {
1628                 /* Maybe we could make our own error */
1629                 PyErr_Print();
1630                 PyErr_SetString(PyExc_SystemError, "could not access the py sequence");
1631                 return NULL;
1632         }
1633         if (!ok) {
1634                 PyErr_SetString(PyExc_SystemError, "internal error setting the array");
1635                 return NULL;
1636         }
1637
1638         if(array)
1639                 PyMem_Free(array);
1640
1641         Py_RETURN_NONE;
1642 }
1643
1644 static PyObject *pyrna_prop_foreach_get(BPy_PropertyRNA *self, PyObject *args)
1645 {
1646         return foreach_getset(self, args, 0);
1647 }
1648
1649 static  PyObject *pyrna_prop_foreach_set(BPy_PropertyRNA *self, PyObject *args)
1650 {
1651         return foreach_getset(self, args, 1);
1652 }
1653 #endif /* #if (PY_VERSION_HEX >= 0x03000000) */
1654
1655 /* A bit of a kludge, make a list out of a collection or array,
1656  * then return the lists iter function, not especially fast but convenient for now */
1657 PyObject *pyrna_prop_iter(BPy_PropertyRNA *self)
1658 {
1659         /* Try get values from a collection */
1660         PyObject *ret = pyrna_prop_values(self);
1661         
1662         if (ret==NULL) {
1663                 /* collection did not work, try array */
1664                 int len = RNA_property_array_length(self->prop);
1665                 
1666                 if (len) {
1667                         int i;
1668                         PyErr_Clear();
1669                         ret = PyList_New(len);
1670                         
1671                         for (i=0; i < len; i++) {
1672                                 PyList_SET_ITEM(ret, i, pyrna_prop_to_py_index(&self->ptr, self->prop, i));
1673                         }
1674                 }
1675         }
1676         
1677         if (ret) {
1678                 /* we know this is a list so no need to PyIter_Check */
1679                 PyObject *iter = PyObject_GetIter(ret); 
1680                 Py_DECREF(ret);
1681                 return iter;
1682         }
1683         
1684         PyErr_SetString( PyExc_TypeError, "this BPy_PropertyRNA object is not iterable" );
1685         return NULL;
1686 }
1687
1688 static struct PyMethodDef pyrna_struct_methods[] = {
1689
1690         /* maybe this become and ID function */
1691         {"keyframe_insert", (PyCFunction)pyrna_struct_keyframe_insert, METH_VARARGS, NULL},
1692
1693         {"__dir__", (PyCFunction)pyrna_struct_dir, METH_NOARGS, NULL},
1694         {NULL, NULL, 0, NULL}
1695 };
1696
1697 static struct PyMethodDef pyrna_prop_methods[] = {
1698         {"keys", (PyCFunction)pyrna_prop_keys, METH_NOARGS, NULL},
1699         {"items", (PyCFunction)pyrna_prop_items, METH_NOARGS,NULL},
1700         {"values", (PyCFunction)pyrna_prop_values, METH_NOARGS, NULL},
1701
1702 #if (PY_VERSION_HEX >= 0x03000000)
1703         /* array accessor function */
1704         {"foreach_get", (PyCFunction)pyrna_prop_foreach_get, METH_VARARGS, NULL},
1705         {"foreach_set", (PyCFunction)pyrna_prop_foreach_set, METH_VARARGS, NULL},
1706 #endif
1707         {NULL, NULL, 0, NULL}
1708 };
1709
1710 /* only needed for subtyping, so a new class gets a valid BPy_StructRNA
1711  * todo - also accept useful args */
1712 static PyObject * pyrna_struct_new(PyTypeObject *type, PyObject *args, PyObject *kwds) {
1713
1714         BPy_StructRNA *base = NULL;
1715         
1716         if (!PyArg_ParseTuple(args, "O!:Base BPy_StructRNA", &pyrna_struct_Type, &base))
1717                 return NULL;
1718         
1719         if (type == &pyrna_struct_Type) {
1720                 return pyrna_struct_CreatePyObject(&base->ptr);
1721         } else {
1722                 BPy_StructRNA *ret = (BPy_StructRNA *) type->tp_alloc(type, 0);
1723                 ret->ptr = base->ptr;
1724                 return (PyObject *)ret;
1725         }
1726 }
1727
1728 /* only needed for subtyping, so a new class gets a valid BPy_StructRNA
1729  * todo - also accept useful args */
1730 static PyObject * pyrna_prop_new(PyTypeObject *type, PyObject *args, PyObject *kwds) {
1731
1732         BPy_PropertyRNA *base = NULL;
1733         
1734         if (!PyArg_ParseTuple(args, "O!:Base BPy_PropertyRNA", &pyrna_prop_Type, &base))
1735                 return NULL;
1736         
1737         if (type == &pyrna_prop_Type) {
1738                 return pyrna_prop_CreatePyObject(&base->ptr, base->prop);
1739         } else {
1740                 BPy_PropertyRNA *ret = (BPy_PropertyRNA *) type->tp_alloc(type, 0);
1741                 ret->ptr = base->ptr;
1742                 ret->prop = base->prop;
1743                 return (PyObject *)ret;
1744         }
1745 }
1746
1747 PyObject *pyrna_param_to_py(PointerRNA *ptr, PropertyRNA *prop, void *data)
1748 {
1749         PyObject *ret;
1750         int type = RNA_property_type(prop);
1751         int len = RNA_property_array_length(prop);
1752
1753         int a;
1754
1755         if(len > 0) {
1756                 /* resolve the array from a new pytype */
1757                 ret = PyTuple_New(len);
1758
1759                 switch (type) {
1760                 case PROP_BOOLEAN:
1761                         for(a=0; a<len; a++)
1762                                 PyTuple_SET_ITEM(ret, a, PyBool_FromLong( ((int*)data)[a] ));
1763                         break;
1764                 case PROP_INT:
1765                         for(a=0; a<len; a++)
1766                                 PyTuple_SET_ITEM(ret, a, PyLong_FromSsize_t( (Py_ssize_t)((int*)data)[a] ));
1767                         break;
1768                 case PROP_FLOAT:
1769                         for(a=0; a<len; a++)
1770                                 PyTuple_SET_ITEM(ret, a, PyFloat_FromDouble( ((float*)data)[a] ));
1771                         break;
1772                 default:
1773                         PyErr_Format(PyExc_AttributeError, "RNA Error: unknown array type \"%d\" (pyrna_param_to_py)", type);
1774                         ret = NULL;
1775                         break;
1776                 }
1777         }
1778         else {
1779                 /* see if we can coorce into a python type - PropertyType */
1780                 switch (type) {
1781                 case PROP_BOOLEAN:
1782                         ret = PyBool_FromLong( *(int*)data );
1783                         break;
1784                 case PROP_INT:
1785                         ret = PyLong_FromSsize_t( (Py_ssize_t)*(int*)data );
1786                         break;
1787                 case PROP_FLOAT:
1788                         ret = PyFloat_FromDouble( *(float*)data );
1789                         break;
1790                 case PROP_STRING:
1791                 {
1792                         ret = PyUnicode_FromString( *(char**)data );
1793                         break;
1794                 }
1795                 case PROP_ENUM:
1796                 {
1797                         const char *identifier;
1798                         int val = *(int*)data;
1799                         
1800                         if (RNA_property_enum_identifier(ptr, prop, val, &identifier)) {
1801                                 ret = PyUnicode_FromString( identifier );
1802                         } else {
1803                                 const EnumPropertyItem *item;
1804
1805                                 /* don't throw error here, can't trust blender 100% to give the
1806                                  * right values, python code should not generate error for that */
1807                                 RNA_property_enum_items(ptr, prop, &item, NULL);
1808                                 if(item[0].identifier)
1809                                         ret = PyUnicode_FromString( item[0].identifier );
1810                                 else
1811                                         ret = PyUnicode_FromString( "" );
1812
1813                                 /*PyErr_Format(PyExc_AttributeError, "RNA Error: Current value \"%d\" matches no enum", val);
1814                                 ret = NULL;*/
1815                         }
1816
1817                         break;
1818                 }
1819                 case PROP_POINTER:
1820                 {
1821                         PointerRNA newptr;
1822                         StructRNA *type= RNA_property_pointer_type(ptr, prop);
1823                         int flag = RNA_property_flag(prop);
1824
1825                         if(flag & PROP_RNAPTR) {
1826                                 /* in this case we get the full ptr */
1827                                 newptr= *(PointerRNA*)data;
1828                         }
1829                         else {
1830                                 /* XXX this is missing the ID part! */
1831                                 RNA_pointer_create(NULL, type, *(void**)data, &newptr);
1832                         }
1833
1834                         if (newptr.data) {
1835                                 ret = pyrna_struct_CreatePyObject(&newptr);
1836                         } else {
1837                                 ret = Py_None;
1838                                 Py_INCREF(ret);
1839                         }
1840                         break;
1841                 }
1842                 case PROP_COLLECTION:
1843                 {
1844                         ListBase *lb= (ListBase*)data;
1845                         CollectionPointerLink *link;
1846                         PyObject *linkptr;
1847
1848                         ret = PyList_New(0);
1849
1850                         for(link=lb->first; link; link=link->next) {
1851                                 linkptr= pyrna_struct_CreatePyObject(&link->ptr);
1852                                 PyList_Append(ret, linkptr);
1853                                 Py_DECREF(linkptr);
1854                         }
1855
1856                         break;
1857                 }
1858                 default:
1859                         PyErr_Format(PyExc_AttributeError, "RNA Error: unknown type \"%d\" (pyrna_param_to_py)", type);
1860                         ret = NULL;
1861                         break;
1862                 }
1863         }
1864
1865         return ret;
1866 }
1867
1868 static PyObject * pyrna_func_call(PyObject * self, PyObject *args, PyObject *kw)
1869 {
1870         PointerRNA *self_ptr= &(((BPy_StructRNA *)PyTuple_GET_ITEM(self, 0))->ptr);
1871         FunctionRNA *self_func=  PyCObject_AsVoidPtr(PyTuple_GET_ITEM(self, 1));
1872
1873         PointerRNA funcptr;
1874         ParameterList *parms;
1875         ParameterIterator iter;
1876         PropertyRNA *pret, *parm;
1877         PyObject *ret, *item;
1878         int i, tlen, flag, err= 0;
1879         const char *tid, *fid, *pid;
1880         void *retdata= NULL;
1881
1882         /* setup */
1883         RNA_pointer_create(NULL, &RNA_Function, self_func, &funcptr);
1884
1885         pret= RNA_function_return(self_func);
1886         tlen= PyTuple_GET_SIZE(args);
1887
1888         parms= RNA_parameter_list_create(self_ptr, self_func);
1889         RNA_parameter_list_begin(parms, &iter);
1890
1891         /* parse function parameters */
1892         for (i= 0; iter.valid; RNA_parameter_list_next(&iter)) {
1893                 parm= iter.parm;
1894
1895                 if (parm==pret) {
1896                         retdata= iter.data;
1897                         continue;
1898                 }
1899
1900                 pid= RNA_property_identifier(parm);
1901                 flag= RNA_property_flag(parm);
1902                 item= NULL;
1903
1904                 if ((i < tlen) && (flag & PROP_REQUIRED)) {
1905                         item= PyTuple_GET_ITEM(args, i);
1906                         i++;
1907                 }
1908                 else if (kw != NULL)
1909                         item= PyDict_GetItemString(kw, pid);  /* borrow ref */
1910
1911                 if (item==NULL) {
1912                         if(flag & PROP_REQUIRED) {
1913                                 tid= RNA_struct_identifier(self_ptr->type);
1914                                 fid= RNA_function_identifier(self_func);
1915
1916                                 PyErr_Format(PyExc_AttributeError, "%s.%s(): required parameter \"%s\" not specified", tid, fid, pid);
1917                                 err= -1;
1918                                 break;
1919                         }
1920                         else
1921                                 continue;
1922                 }
1923
1924                 err= pyrna_py_to_prop(&funcptr, parm, iter.data, item);
1925
1926                 if(err!=0)
1927                         break;
1928         }
1929
1930         ret= NULL;
1931         if (err==0) {
1932                 /* call function */
1933                 ReportList reports;
1934                 bContext *C= BPy_GetContext();
1935
1936                 BKE_reports_init(&reports, RPT_STORE);
1937                 RNA_function_call(C, &reports, self_ptr, self_func, parms);
1938
1939                 err= (BPy_reports_to_error(&reports))? -1: 0;
1940                 BKE_reports_clear(&reports);
1941
1942                 /* return value */
1943                 if(err==0)
1944                         if(pret)
1945                                 ret= pyrna_param_to_py(&funcptr, pret, retdata);
1946         }
1947
1948         /* cleanup */
1949         RNA_parameter_list_end(&iter);
1950         RNA_parameter_list_free(parms);
1951
1952         if (ret)
1953                 return ret;
1954
1955         if (err==-1)
1956                 return NULL;
1957
1958         Py_RETURN_NONE;
1959 }
1960
1961 /*-----------------------BPy_StructRNA method def------------------------------*/
1962 PyTypeObject pyrna_struct_Type = {
1963 #if (PY_VERSION_HEX >= 0x02060000)
1964         PyVarObject_HEAD_INIT(NULL, 0)
1965 #else
1966         /* python 2.5 and below */
1967         PyObject_HEAD_INIT( NULL )  /* required py macro */
1968         0,                          /* ob_size */
1969 #endif
1970         "StructRNA",                    /* tp_name */
1971         sizeof( BPy_StructRNA ),        /* tp_basicsize */
1972         0,                      /* tp_itemsize */
1973         /* methods */
1974         ( destructor ) pyrna_struct_dealloc,/* tp_dealloc */
1975         NULL,                       /* printfunc tp_print; */
1976         NULL,                                           /* getattrfunc tp_getattr; */
1977         NULL,                                           /* setattrfunc tp_setattr; */
1978         NULL,                                           /* tp_compare */ /* DEPRECATED in python 3.0! */
1979         ( reprfunc ) pyrna_struct_repr, /* tp_repr */
1980
1981         /* Method suites for standard classes */
1982
1983         NULL,                       /* PyNumberMethods *tp_as_number; */
1984         NULL,                                           /* PySequenceMethods *tp_as_sequence; */
1985         NULL,                                           /* PyMappingMethods *tp_as_mapping; */
1986
1987         /* More standard operations (here for binary compatibility) */
1988
1989         ( hashfunc )pyrna_struct_hash,  /* hashfunc tp_hash; */
1990         NULL,                                           /* ternaryfunc tp_call; */
1991         NULL,                       /* reprfunc tp_str; */
1992         ( getattrofunc ) pyrna_struct_getattro, /* getattrofunc tp_getattro; */
1993         ( setattrofunc ) pyrna_struct_setattro, /* setattrofunc tp_setattro; */
1994
1995         /* Functions to access object as input/output buffer */
1996         NULL,                       /* PyBufferProcs *tp_as_buffer; */
1997
1998   /*** Flags to define presence of optional/expanded features ***/
1999         Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE,         /* long tp_flags; */
2000
2001         NULL,                                           /*  char *tp_doc;  Documentation string */
2002   /*** Assigned meaning in release 2.0 ***/
2003         /* call function for all accessible objects */
2004         NULL,                       /* traverseproc tp_traverse; */
2005
2006         /* delete references to contained objects */
2007         NULL,                       /* inquiry tp_clear; */
2008
2009   /***  Assigned meaning in release 2.1 ***/
2010   /*** rich comparisons ***/
2011         (richcmpfunc)pyrna_struct_richcmp,      /* richcmpfunc tp_richcompare; */
2012
2013   /***  weak reference enabler ***/
2014         0,                          /* long tp_weaklistoffset; */
2015
2016   /*** Added in release 2.2 ***/
2017         /*   Iterators */
2018         NULL,                       /* getiterfunc tp_iter; */
2019         NULL,                       /* iternextfunc tp_iternext; */
2020
2021   /*** Attribute descriptor and subclassing stuff ***/
2022         pyrna_struct_methods,                   /* struct PyMethodDef *tp_methods; */
2023         NULL,                       /* struct PyMemberDef *tp_members; */
2024         NULL,                                           /* struct PyGetSetDef *tp_getset; */
2025         NULL,                       /* struct _typeobject *tp_base; */
2026         NULL,                       /* PyObject *tp_dict; */
2027         NULL,                       /* descrgetfunc tp_descr_get; */
2028         NULL,                       /* descrsetfunc tp_descr_set; */
2029         0,                          /* long tp_dictoffset; */
2030         NULL,                       /* initproc tp_init; */
2031         NULL,                       /* allocfunc tp_alloc; */
2032         pyrna_struct_new,                       /* newfunc tp_new; */
2033         /*  Low-level free-memory routine */
2034         NULL,                       /* freefunc tp_free;  */
2035         /* For PyObject_IS_GC */
2036         NULL,                       /* inquiry tp_is_gc;  */
2037         NULL,                       /* PyObject *tp_bases; */
2038         /* method resolution order */
2039         NULL,                       /* PyObject *tp_mro;  */
2040         NULL,                       /* PyObject *tp_cache; */
2041         NULL,                       /* PyObject *tp_subclasses; */
2042         NULL,                       /* PyObject *tp_weaklist; */
2043         NULL
2044 };
2045
2046 /*-----------------------BPy_PropertyRNA method def------------------------------*/
2047 PyTypeObject pyrna_prop_Type = {
2048 #if (PY_VERSION_HEX >= 0x02060000)
2049         PyVarObject_HEAD_INIT(NULL, 0)
2050 #else
2051         /* python 2.5 and below */
2052         PyObject_HEAD_INIT( NULL )  /* required py macro */
2053         0,                          /* ob_size */
2054 #endif
2055         
2056         "PropertyRNA",          /* tp_name */
2057         sizeof( BPy_PropertyRNA ),                      /* tp_basicsize */
2058         0,                      /* tp_itemsize */
2059         /* methods */
2060         NULL,                                           /* tp_dealloc */
2061         NULL,                       /* printfunc tp_print; */
2062         NULL,                                           /* getattrfunc tp_getattr; */
2063         NULL,                       /* setattrfunc tp_setattr; */
2064         NULL,                                           /* tp_compare */ /* DEPRECATED in python 3.0! */
2065         ( reprfunc ) pyrna_prop_repr,   /* tp_repr */
2066
2067         /* Method suites for standard classes */
2068
2069         NULL,                       /* PyNumberMethods *tp_as_number; */
2070         &pyrna_prop_as_sequence,        /* PySequenceMethods *tp_as_sequence; */
2071         &pyrna_prop_as_mapping,         /* PyMappingMethods *tp_as_mapping; */
2072
2073         /* More standard operations (here for binary compatibility) */
2074
2075         NULL,                                           /* hashfunc tp_hash; */
2076         NULL,                       /* ternaryfunc tp_call; */
2077         NULL,                       /* reprfunc tp_str; */
2078         NULL, /*PyObject_GenericGetAttr - MINGW Complains, assign later */      /* getattrofunc tp_getattro; */ /* will only use these if this is a subtype of a py class */
2079         NULL, /*PyObject_GenericSetAttr - MINGW Complains, assign later */      /* setattrofunc tp_setattro; */
2080
2081         /* Functions to access object as input/output buffer */
2082         NULL,                       /* PyBufferProcs *tp_as_buffer; */
2083
2084   /*** Flags to define presence of optional/expanded features ***/
2085         Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE,         /* long tp_flags; */
2086
2087         NULL,                                           /*  char *tp_doc;  Documentation string */
2088   /*** Assigned meaning in release 2.0 ***/
2089         /* call function for all accessible objects */
2090         NULL,                       /* traverseproc tp_traverse; */
2091
2092         /* delete references to contained objects */
2093         NULL,                       /* inquiry tp_clear; */
2094
2095   /***  Assigned meaning in release 2.1 ***/
2096   /*** rich comparisons ***/
2097         (richcmpfunc)pyrna_prop_richcmp,        /* richcmpfunc tp_richcompare; */
2098
2099   /***  weak reference enabler ***/
2100         0,                          /* long tp_weaklistoffset; */
2101
2102   /*** Added in release 2.2 ***/
2103         /*   Iterators */
2104         (getiterfunc)pyrna_prop_iter,   /* getiterfunc tp_iter; */
2105         NULL,                       /* iternextfunc tp_iternext; */
2106
2107   /*** Attribute descriptor and subclassing stuff ***/
2108         pyrna_prop_methods,                     /* struct PyMethodDef *tp_methods; */
2109         NULL,                       /* struct PyMemberDef *tp_members; */
2110         NULL,                                           /* struct PyGetSetDef *tp_getset; */
2111         NULL,                       /* struct _typeobject *tp_base; */
2112         NULL,                       /* PyObject *tp_dict; */
2113         NULL,                       /* descrgetfunc tp_descr_get; */
2114         NULL,                       /* descrsetfunc tp_descr_set; */
2115         0,                          /* long tp_dictoffset; */
2116         NULL,                       /* initproc tp_init; */
2117         NULL,                       /* allocfunc tp_alloc; */
2118         pyrna_prop_new,                         /* newfunc tp_new; */
2119         /*  Low-level free-memory routine */
2120         NULL,                       /* freefunc tp_free;  */
2121         /* For PyObject_IS_GC */
2122         NULL,                       /* inquiry tp_is_gc;  */
2123         NULL,                       /* PyObject *tp_bases; */
2124         /* method resolution order */
2125         NULL,                       /* PyObject *tp_mro;  */
2126         NULL,                       /* PyObject *tp_cache; */
2127         NULL,                       /* PyObject *tp_subclasses; */
2128         NULL,                       /* PyObject *tp_weaklist; */
2129         NULL
2130 };
2131
2132 static void pyrna_subtype_set_rna(PyObject *newclass, StructRNA *srna)
2133 {
2134         PointerRNA ptr;
2135         PyObject *item;
2136         
2137         Py_INCREF(newclass);
2138         
2139         if (RNA_struct_py_type_get(srna))
2140                 PyObSpit("RNA WAS SET - ", RNA_struct_py_type_get(srna));
2141         
2142         Py_XDECREF(((PyObject *)RNA_struct_py_type_get(srna)));
2143         
2144         RNA_struct_py_type_set(srna, (void *)newclass); /* Store for later use */
2145
2146         /* Not 100% needed but useful,
2147          * having an instance within a type looks wrong however this instance IS an rna type */
2148         RNA_pointer_create(NULL, &RNA_Struct, srna, &ptr);
2149         item = pyrna_struct_CreatePyObject(&ptr);
2150         PyDict_SetItemString(((PyTypeObject *)newclass)->tp_dict, "__rna__", item);
2151         Py_DECREF(item);
2152         /* done with rna instance */
2153 }
2154
2155 PyObject* pyrna_struct_Subtype(PointerRNA *ptr)
2156 {
2157         PyObject *newclass = NULL;
2158         PropertyRNA *nameprop;
2159
2160         if (ptr->type==NULL) {
2161                 newclass= NULL; /* Nothing to do */
2162         } else if ((newclass= RNA_struct_py_type_get(ptr->data))) {
2163                 Py_INCREF(newclass);
2164         } else if ((nameprop = RNA_struct_name_property(ptr->type))) {
2165                 /* for now, return the base RNA type rather then a real module */
2166                 
2167                 /* Assume RNA_struct_py_type_get(ptr->data) was alredy checked */
2168                 
2169                 /* subclass equivelents
2170                 - class myClass(myBase):
2171                         some='value' # or ...
2172                 - myClass = type(name='myClass', bases=(myBase,), dict={'some':'value'})
2173                 */
2174                 char name[256], *nameptr;
2175                 const char *descr= RNA_struct_ui_description(ptr->type);
2176
2177                 PyObject *args = PyTuple_New(3);
2178                 PyObject *bases = PyTuple_New(1);
2179                 PyObject *dict = PyDict_New();
2180                 PyObject *item;
2181                 
2182                 
2183                 nameptr= RNA_property_string_get_alloc(ptr, nameprop, name, sizeof(name));
2184                 
2185                 // arg 1
2186                 //PyTuple_SET_ITEM(args, 0, PyUnicode_FromString(tp_name));
2187                 PyTuple_SET_ITEM(args, 0, PyUnicode_FromString(nameptr));
2188                 
2189                 // arg 2
2190                 PyTuple_SET_ITEM(bases, 0, (PyObject *)&pyrna_struct_Type);
2191                 Py_INCREF(&pyrna_struct_Type);
2192
2193                 PyTuple_SET_ITEM(args, 1, bases);
2194                 
2195                 // arg 3 - add an instance of the rna 
2196                 if(descr) {
2197                         item= PyUnicode_FromString(descr);
2198                         PyDict_SetItemString(dict, "__doc__", item);
2199                         Py_DECREF(item);
2200                 }
2201                 
2202                 PyTuple_SET_ITEM(args, 2, dict); // fill with useful subclass things!
2203                 
2204                 if (PyErr_Occurred()) {
2205                         PyErr_Print();
2206                         PyErr_Clear();
2207                 }
2208                 
2209                 newclass = PyObject_CallObject((PyObject *)&PyType_Type, args);
2210                 Py_DECREF(args);
2211
2212                 if (newclass)
2213                         pyrna_subtype_set_rna(newclass, ptr->data);
2214                 
2215                 if (name != nameptr)
2216                         MEM_freeN(nameptr);
2217         }
2218         
2219         return newclass;
2220 }
2221
2222 /*-----------------------CreatePyObject---------------------------------*/
2223 PyObject *pyrna_struct_CreatePyObject( PointerRNA *ptr )
2224 {
2225         BPy_StructRNA *pyrna= NULL;
2226         
2227         if (ptr->data==NULL && ptr->type==NULL) { /* Operator RNA has NULL data */
2228                 Py_RETURN_NONE;
2229         }
2230         
2231         if (ptr->type == &RNA_Struct) { /* always return a python subtype from rna struct types */
2232                 PyTypeObject *tp = (PyTypeObject *)pyrna_struct_Subtype(ptr);
2233                 
2234                 if (tp) {
2235                         pyrna = (BPy_StructRNA *) tp->tp_alloc(tp, 0);
2236                 }
2237                 else {
2238                         fprintf(stderr, "Could not make type\n");
2239                         pyrna = ( BPy_StructRNA * ) PyObject_NEW( BPy_StructRNA, &pyrna_struct_Type );
2240                 }
2241         }
2242         else {
2243                 pyrna = ( BPy_StructRNA * ) PyObject_NEW( BPy_StructRNA, &pyrna_struct_Type );
2244         }
2245         
2246         if( !pyrna ) {
2247                 PyErr_SetString( PyExc_MemoryError, "couldn't create BPy_StructRNA object" );
2248                 return NULL;
2249         }
2250         
2251         pyrna->ptr= *ptr;
2252         pyrna->freeptr= 0;
2253         return ( PyObject * ) pyrna;
2254 }
2255
2256 PyObject *pyrna_prop_CreatePyObject( PointerRNA *ptr, PropertyRNA *prop )
2257 {
2258         BPy_PropertyRNA *pyrna;
2259
2260         pyrna = ( BPy_PropertyRNA * ) PyObject_NEW( BPy_PropertyRNA, &pyrna_prop_Type );
2261
2262         if( !pyrna ) {
2263                 PyErr_SetString( PyExc_MemoryError, "couldn't create BPy_rna object" );
2264                 return NULL;
2265         }
2266         
2267         pyrna->ptr = *ptr;
2268         pyrna->prop = prop;
2269                 
2270         return ( PyObject * ) pyrna;
2271 }
2272
2273 PyObject *BPY_rna_module( void )
2274 {
2275         PointerRNA ptr;
2276         
2277 #ifdef USE_MATHUTILS // register mathutils callbacks, ok to run more then once.
2278         mathutils_rna_array_cb_index= Mathutils_RegisterCallback(&mathutils_rna_array_cb);
2279         mathutils_rna_matrix_cb_index= Mathutils_RegisterCallback(&mathutils_rna_matrix_cb);
2280 #endif
2281         
2282         /* This can't be set in the pytype struct because some compilers complain */
2283         pyrna_prop_Type.tp_getattro = PyObject_GenericGetAttr; 
2284         pyrna_prop_Type.tp_setattro = PyObject_GenericSetAttr; 
2285         
2286         if( PyType_Ready( &pyrna_struct_Type ) < 0 )
2287                 return NULL;
2288         
2289         if( PyType_Ready( &pyrna_prop_Type ) < 0 )
2290                 return NULL;
2291
2292         /* for now, return the base RNA type rather then a real module */
2293         RNA_main_pointer_create(G.main, &ptr);
2294         
2295         return pyrna_struct_CreatePyObject(&ptr);
2296 }
2297
2298 #if 0
2299 /* This is a way we can access docstrings for RNA types
2300  * without having the datatypes in blender */
2301 PyObject *BPY_rna_doc( void )
2302 {
2303         PointerRNA ptr;
2304         
2305         /* for now, return the base RNA type rather then a real module */
2306         RNA_blender_rna_pointer_create(&ptr);
2307         
2308         return pyrna_struct_CreatePyObject(&ptr);
2309 }
2310 #endif
2311
2312
2313 /* pyrna_basetype_* - BPy_BaseTypeRNA is just a BPy_PropertyRNA struct with a differnt type
2314  * the self->ptr and self->prop are always set to the "structs" collection */
2315 //---------------getattr--------------------------------------------
2316 static PyObject *pyrna_basetype_getattro( BPy_BaseTypeRNA * self, PyObject *pyname )
2317 {
2318         PointerRNA newptr;
2319         PyObject *ret;
2320         
2321         ret = PyObject_GenericGetAttr((PyObject *)self, pyname);
2322         if (ret)        return ret;
2323         else            PyErr_Clear();
2324         
2325         if (RNA_property_collection_lookup_string(&self->ptr, self->prop, _PyUnicode_AsString(pyname), &newptr)) {
2326                 ret= pyrna_struct_Subtype(&newptr);
2327                 if (ret==NULL) {
2328                         PyErr_Format(PyExc_SystemError, "bpy.types.%s subtype could not be generated, this is a bug!", _PyUnicode_AsString(pyname));
2329                 }
2330                 return ret;
2331         }
2332         else { /* Override the error */
2333                 PyErr_Format(PyExc_AttributeError, "bpy.types.%s not a valid RNA_Struct", _PyUnicode_AsString(pyname));
2334                 return NULL;
2335         }
2336 }
2337
2338 static PyObject *pyrna_basetype_dir(BPy_BaseTypeRNA *self);
2339 static struct PyMethodDef pyrna_basetype_methods[] = {
2340         {"__dir__", (PyCFunction)pyrna_basetype_dir, METH_NOARGS, ""},
2341         {"register", (PyCFunction)pyrna_basetype_register, METH_VARARGS, ""},
2342         {"unregister", (PyCFunction)pyrna_basetype_unregister, METH_VARARGS, ""},
2343         {NULL, NULL, 0, NULL}
2344 };
2345
2346 static PyObject *pyrna_basetype_dir(BPy_BaseTypeRNA *self)
2347 {
2348         PyObject *list, *name;
2349         PyMethodDef *meth;
2350         
2351         list= pyrna_prop_keys(self); /* like calling structs.keys(), avoids looping here */
2352
2353         for(meth=pyrna_basetype_methods; meth->ml_name; meth++) {
2354                 name = PyUnicode_FromString(meth->ml_name);
2355                 PyList_Append(list, name);
2356                 Py_DECREF(name);
2357         }
2358         
2359         return list;
2360 }
2361
2362 PyTypeObject pyrna_basetype_Type = BLANK_PYTHON_TYPE;
2363
2364 PyObject *BPY_rna_types(void)
2365 {
2366         BPy_BaseTypeRNA *self;
2367
2368         if ((pyrna_basetype_Type.tp_flags & Py_TPFLAGS_READY)==0)  {
2369                 pyrna_basetype_Type.tp_name = "RNA_Types";
2370                 pyrna_basetype_Type.tp_basicsize = sizeof( BPy_BaseTypeRNA );
2371                 pyrna_basetype_Type.tp_getattro = ( getattrofunc )pyrna_basetype_getattro;
2372                 pyrna_basetype_Type.tp_flags = Py_TPFLAGS_DEFAULT;
2373                 pyrna_basetype_Type.tp_methods = pyrna_basetype_methods;
2374                 
2375                 if( PyType_Ready( &pyrna_basetype_Type ) < 0 )
2376                         return NULL;
2377         }
2378         
2379         self= (BPy_BaseTypeRNA *)PyObject_NEW( BPy_BaseTypeRNA, &pyrna_basetype_Type );
2380         
2381         /* avoid doing this lookup for every getattr */
2382         RNA_blender_rna_pointer_create(&self->ptr);
2383         self->prop = RNA_struct_find_property(&self->ptr, "structs");
2384         
2385         return (PyObject *)self;
2386 }
2387
2388 static struct PyMethodDef props_methods[] = {
2389         {"FloatProperty", (PyCFunction)BPy_FloatProperty, METH_VARARGS|METH_KEYWORDS, ""},
2390         {"IntProperty", (PyCFunction)BPy_IntProperty, METH_VARARGS|METH_KEYWORDS, ""},
2391         {"BoolProperty", (PyCFunction)BPy_BoolProperty, METH_VARARGS|METH_KEYWORDS, ""},
2392         {"StringProperty", (PyCFunction)BPy_StringProperty, METH_VARARGS|METH_KEYWORDS, ""},
2393         {NULL, NULL, 0, NULL}
2394 };
2395
2396 #if PY_VERSION_HEX >= 0x03000000
2397 static struct PyModuleDef props_module = {
2398         PyModuleDef_HEAD_INIT,
2399         "bpyprops",
2400         "",
2401         -1,/* multiple "initialization" just copies the module dict. */
2402         props_methods,
2403         NULL, NULL, NULL, NULL
2404 };
2405 #endif
2406
2407 PyObject *BPY_rna_props( void )
2408 {
2409         PyObject *submodule, *mod;
2410 #if PY_VERSION_HEX >= 0x03000000
2411         submodule= PyModule_Create(&props_module);
2412 #else /* Py2.x */
2413         submodule= Py_InitModule3( "bpy.props", props_methods, "" );
2414 #endif
2415         
2416         mod = PyModule_New("props");
2417         PyModule_AddObject( submodule, "props", mod );
2418         
2419         /* INCREF since its its assumed that all these functions return the
2420          * module with a new ref like PyDict_New, since they are passed to
2421           * PyModule_AddObject which steals a ref */
2422         Py_INCREF(submodule);
2423         
2424         return submodule;
2425 }
2426
2427 /* Orphan functions, not sure where they should go */
2428
2429 /* Function that sets RNA, NOTE - self is NULL when called from python, but being abused from C so we can pass the srna allong
2430  * This isnt incorrect since its a python object - but be careful */
2431 PyObject *BPy_FloatProperty(PyObject *self, PyObject *args, PyObject *kw)
2432 {
2433         static char *kwlist[] = {"attr", "name", "description", "min", "max", "soft_min", "soft_max", "default", NULL};
2434         char *id, *name="", *description="";
2435         float min=FLT_MIN, max=FLT_MAX, soft_min=FLT_MIN, soft_max=FLT_MAX, def=0.0f;
2436         
2437         if (!PyArg_ParseTupleAndKeywords(args, kw, "s|ssfffff:FloatProperty", kwlist, &id, &name, &description, &min, &max, &soft_min, &soft_max, &def))
2438                 return NULL;
2439         
2440         if (PyTuple_Size(args) > 0) {
2441                 PyErr_SetString(PyExc_ValueError, "all args must be keywors"); // TODO - py3 can enforce this.
2442                 return NULL;
2443         }
2444         
2445         if (self && PyCObject_Check(self)) {
2446                 StructRNA *srna = PyCObject_AsVoidPtr(self);
2447                 RNA_def_float(srna, id, def, min, max, name, description, soft_min, soft_max);
2448                 Py_RETURN_NONE;
2449         } else {
2450                 PyObject *ret = PyTuple_New(2);
2451                 PyTuple_SET_ITEM(ret, 0, PyCObject_FromVoidPtr((void *)BPy_FloatProperty, NULL));
2452                 PyTuple_SET_ITEM(ret, 1, kw);
2453                 Py_INCREF(kw);
2454                 return ret;
2455         }
2456 }
2457
2458 PyObject *BPy_IntProperty(PyObject *self, PyObject *args, PyObject *kw)
2459 {
2460         static char *kwlist[] = {"attr", "name", "description", "min", "max", "soft_min", "soft_max", "default", NULL};
2461         char *id, *name="", *description="";
2462         int min=INT_MIN, max=INT_MAX, soft_min=INT_MIN, soft_max=INT_MAX, def=0;
2463         
2464         if (!PyArg_ParseTupleAndKeywords(args, kw, "s|ssiiiii:IntProperty", kwlist, &id, &name, &description, &min, &max, &soft_min, &soft_max, &def))
2465                 return NULL;
2466         
2467         if (PyTuple_Size(args) > 0) {
2468                 PyErr_SetString(PyExc_ValueError, "all args must be keywors"); // TODO - py3 can enforce this.
2469                 return NULL;
2470         }
2471         
2472         if (self && PyCObject_Check(self)) {
2473                 StructRNA *srna = PyCObject_AsVoidPtr(self);
2474                 RNA_def_int(srna, id, def, min, max, name, description, soft_min, soft_max);
2475                 Py_RETURN_NONE;
2476         } else {
2477                 PyObject *ret = PyTuple_New(2);
2478                 PyTuple_SET_ITEM(ret, 0, PyCObject_FromVoidPtr((void *)BPy_IntProperty, NULL));
2479                 PyTuple_SET_ITEM(ret, 1, kw);
2480                 Py_INCREF(kw);
2481                 return ret;
2482         }
2483 }
2484
2485 PyObject *BPy_BoolProperty(PyObject *self, PyObject *args, PyObject *kw)
2486 {
2487         static char *kwlist[] = {"attr", "name", "description", "default", NULL};
2488         char *id, *name="", *description="";
2489         int def=0;
2490         
2491         if (!PyArg_ParseTupleAndKeywords(args, kw, "s|ssi:BoolProperty", kwlist, &id, &name, &description, &def))
2492                 return NULL;
2493         
2494         if (PyTuple_Size(args) > 0) {
2495                 PyErr_SetString(PyExc_ValueError, "all args must be keywors"); // TODO - py3 can enforce this.
2496                 return NULL;
2497         }
2498         
2499         if (self && PyCObject_Check(self)) {
2500                 StructRNA *srna = PyCObject_AsVoidPtr(self);
2501                 RNA_def_boolean(srna, id, def, name, description);
2502                 Py_RETURN_NONE;
2503         } else {
2504                 PyObject *ret = PyTuple_New(2);
2505                 PyTuple_SET_ITEM(ret, 0, PyCObject_FromVoidPtr((void *)BPy_BoolProperty, NULL));
2506                 PyTuple_SET_ITEM(ret, 1, kw);
2507                 Py_INCREF(kw);
2508                 return ret;
2509         }
2510 }
2511
2512 PyObject *BPy_StringProperty(PyObject *self, PyObject *args, PyObject *kw)
2513 {
2514         static char *kwlist[] = {"attr", "name", "description", "maxlen", "default", NULL};
2515         char *id, *name="", *description="", *def="";
2516         int maxlen=0;
2517         
2518         if (!PyArg_ParseTupleAndKeywords(args, kw, "s|ssis:StringProperty", kwlist, &id, &name, &description, &maxlen, &def))
2519                 return NULL;
2520         
2521         if (PyTuple_Size(args) > 0) {
2522                 PyErr_SetString(PyExc_ValueError, "all args must be keywors"); // TODO - py3 can enforce this.
2523                 return NULL;
2524         }
2525         
2526         if (self && PyCObject_Check(self)) {
2527                 StructRNA *srna = PyCObject_AsVoidPtr(self);
2528                 RNA_def_string(srna, id, def, maxlen, name, description);
2529                 Py_RETURN_NONE;
2530         } else {
2531                 PyObject *ret = PyTuple_New(2);
2532                 PyTuple_SET_ITEM(ret, 0, PyCObject_FromVoidPtr((void *)BPy_StringProperty, NULL));
2533                 PyTuple_SET_ITEM(ret, 1, kw);
2534                 Py_INCREF(kw);
2535                 return ret;
2536         }
2537 }
2538
2539 /*-------------------- Type Registration ------------------------*/
2540
2541 static int rna_function_arg_count(FunctionRNA *func)
2542 {
2543         const ListBase *lb= RNA_function_defined_parameters(func);
2544         PropertyRNA *parm;
2545         Link *link;
2546         int count= 1;
2547
2548         for(link=lb->first; link; link=link->next) {
2549                 parm= (PropertyRNA*)link;
2550                 if(!(RNA_property_flag(parm) & PROP_RETURN))
2551                         count++;
2552         }
2553         
2554         return count;
2555 }
2556
2557 static int bpy_class_validate(PointerRNA *dummyptr, void *py_data, int *have_function)
2558 {
2559         const ListBase *lb;
2560         Link *link;
2561         FunctionRNA *func;
2562         PropertyRNA *prop;
2563         StructRNA *srna= dummyptr->type;
2564         const char *class_type= RNA_struct_identifier(srna);
2565         PyObject *py_class= (PyObject*)py_data;
2566         PyObject *base_class= RNA_struct_py_type_get(srna);
2567         PyObject *item, *fitem;
2568         PyObject *py_arg_count;
2569         int i, flag, arg_count, func_arg_count;
2570         char identifier[128];
2571
2572         if (base_class) {
2573                 if (!PyObject_IsSubclass(py_class, base_class)) {
2574                         PyObject *name= PyObject_GetAttrString(base_class, "__name__");
2575                         PyErr_Format( PyExc_AttributeError, "expected %s subclass of class \"%s\"", class_type, name ? _PyUnicode_AsString(name):"<UNKNOWN>");
2576                         Py_XDECREF(name);
2577                         return -1;
2578                 }
2579         }
2580
2581         /* verify callback functions */
2582         lb= RNA_struct_defined_functions(srna);
2583         i= 0;
2584         for(link=lb->first; link; link=link->next) {
2585                 func= (FunctionRNA*)link;
2586                 flag= RNA_function_flag(func);
2587
2588                 if(!(flag & FUNC_REGISTER))
2589                         continue;
2590
2591                 item = PyObject_GetAttrString(py_class, RNA_function_identifier(func));
2592
2593                 have_function[i]= (item != NULL);
2594                 i++;
2595
2596                 if (item==NULL) {
2597                         if ((flag & FUNC_REGISTER_OPTIONAL)==0) {
2598                                 PyErr_Format( PyExc_AttributeError, "expected %s class to have an \"%s\" attribute", class_type, RNA_function_identifier(func));
2599                                 return -1;
2600                         }
2601
2602                         PyErr_Clear();
2603                 }
2604                 else {
2605                         Py_DECREF(item); /* no need to keep a ref, the class owns it */
2606
2607                         if (PyMethod_Check(item))
2608                                 fitem= PyMethod_Function(item); /* py 2.x */
2609                         else
2610                                 fitem= item; /* py 3.x */
2611
2612                         if (PyFunction_Check(fitem)==0) {
2613                                 PyErr_Format( PyExc_AttributeError, "expected %s class \"%s\" attribute to be a function", class_type, RNA_function_identifier(func));
2614                                 return -1;
2615                         }
2616
2617                         func_arg_count= rna_function_arg_count(func);
2618
2619                         if (func_arg_count >= 0) { /* -1 if we dont care*/
2620                                 py_arg_count = PyObject_GetAttrString(PyFunction_GET_CODE(fitem), "co_argcount");
2621                                 arg_count = PyLong_AsSsize_t(py_arg_count);
2622                                 Py_DECREF(py_arg_count);
2623
2624                                 if (arg_count != func_arg_count) {
2625                                         PyErr_Format( PyExc_AttributeError, "expected %s class \"%s\" function to have %d args", class_type, RNA_function_identifier(func), func_arg_count);
2626                                         return -1;
2627                                 }
2628                         }
2629                 }
2630         }
2631
2632         /* verify properties */
2633         lb= RNA_struct_defined_properties(srna);
2634         for(link=lb->first; link; link=link->next) {
2635                 prop= (PropertyRNA*)link;
2636                 flag= RNA_property_flag(prop);
2637
2638                 if(!(flag & PROP_REGISTER))
2639                         continue;
2640
2641                 BLI_snprintf(identifier, sizeof(identifier), "__%s__", RNA_property_identifier(prop));
2642                 item = PyObject_GetAttrString(py_class, identifier);
2643
2644                 if (item==NULL) {
2645                         if(strcmp(identifier, "__idname__") == 0) {
2646                                 item= PyObject_GetAttrString(py_class, "__name__");
2647
2648                                 if(item) {
2649                                         Py_DECREF(item); /* no need to keep a ref, the class owns it */
2650
2651                                         if(pyrna_py_to_prop(dummyptr, prop, NULL, item) != 0)
2652                                                 return -1;
2653                                 }
2654                         }
2655
2656                         if (item==NULL && (flag & PROP_REGISTER_OPTIONAL)==0) {
2657                                 PyErr_Format( PyExc_AttributeError, "expected %s class to have an \"%s\" attribute", class_type, identifier);
2658                                 return -1;
2659                         }
2660
2661                         PyErr_Clear();
2662                 }
2663                 else {
2664                         Py_DECREF(item); /* no need to keep a ref, the class owns it */
2665
2666                         if(pyrna_py_to_prop(dummyptr, prop, NULL, item) != 0)
2667                                 return -1;
2668                 }
2669         }
2670
2671         return 0;
2672 }
2673
2674 extern void BPY_update_modules( void ); //XXX temp solution
2675
2676 static int bpy_class_call(PointerRNA *ptr, FunctionRNA *func, ParameterList *parms)
2677 {
2678         PyObject *args;
2679         PyObject *ret= NULL, *py_class, *py_class_instance, *item, *parmitem;
2680         PropertyRNA *pret= NULL, *parm;
2681         ParameterIterator iter;
2682         PointerRNA funcptr;
2683         void *retdata= NULL;
2684         int err= 0, i, flag;
2685
2686         PyGILState_STATE gilstate = PyGILState_Ensure();
2687
2688         BPY_update_modules(); // XXX - the RNA pointers can change so update before running, would like a nicer solution for this.
2689
2690         py_class= RNA_struct_py_type_get(ptr->type);
2691         
2692         item = pyrna_struct_CreatePyObject(ptr);
2693         if(item == NULL) {
2694                 py_class_instance = NULL;
2695         }
2696         else if(item == Py_None) { /* probably wont ever happen but possible */
2697                 Py_DECREF(item);
2698                 py_class_instance = NULL;
2699         }
2700         else {
2701                 args = PyTuple_New(1);
2702                 PyTuple_SET_ITEM(args, 0, item);
2703                 py_class_instance = PyObject_Call(py_class, args, NULL);
2704                 Py_DECREF(args);
2705         }
2706
2707         if (py_class_instance) { /* Initializing the class worked, now run its invoke function */
2708                 item= PyObject_GetAttrString(py_class, RNA_function_identifier(func));
2709                 flag= RNA_function_flag(func);
2710
2711                 if(item) {
2712                         pret= RNA_function_return(func);
2713                         RNA_pointer_create(NULL, &RNA_Function, func, &funcptr);
2714
2715                         args = PyTuple_New(rna_function_arg_count(func));
2716                         PyTuple_SET_ITEM(args, 0, py_class_instance);
2717
2718                         RNA_parameter_list_begin(parms, &iter);
2719
2720                         /* parse function parameters */
2721                         for (i= 1; iter.valid; RNA_parameter_list_next(&iter)) {
2722                                 parm= iter.parm;
2723
2724                                 if (parm==pret) {
2725                                         retdata= iter.data;
2726                                         continue;
2727                                 }
2728
2729                                 parmitem= pyrna_param_to_py(&funcptr, parm, iter.data);
2730                                 PyTuple_SET_ITEM(args, i, parmitem);
2731                                 i++;
2732                         }
2733
2734                         ret = PyObject_Call(item, args, NULL);
2735
2736                         Py_DECREF(item);
2737                         Py_DECREF(args);
2738                 }
2739                 else {
2740                         Py_DECREF(py_class_instance);
2741                         PyErr_Format(PyExc_AttributeError, "could not find function %s in %s to execute callback.", RNA_function_identifier(func), RNA_struct_identifier(ptr->type));
2742                         err= -1;
2743                 }
2744         }
2745         else {
2746                 PyErr_Format(PyExc_AttributeError, "could not create instance of %s to call callback function %s.", RNA_struct_identifier(ptr->type), RNA_function_identifier(func));
2747                 err= -1;
2748         }
2749
2750         if (ret == NULL) { /* covers py_class_instance failing too */
2751                 PyErr_Print(); /* XXX use reporting api? */
2752                 err= -1;
2753         }
2754         else {
2755                 if(retdata)
2756                         err= pyrna_py_to_prop(&funcptr, pret, retdata, ret);
2757                 Py_DECREF(ret);
2758         }
2759
2760         PyGILState_Release(gilstate);
2761         
2762         return err;
2763 }
2764
2765 static void bpy_class_free(void *pyob_ptr)
2766 {
2767         if(G.f&G_DEBUG) {
2768                 if(((PyObject *)pyob_ptr)->ob_refcnt > 1)
2769                         PyObSpit("zombie class - ref should be 1", (PyObject *)pyob_ptr);
2770         }
2771         Py_DECREF((PyObject *)pyob_ptr);
2772 }
2773
2774 PyObject *pyrna_basetype_register(PyObject *self, PyObject *args)
2775 {
2776         bContext *C= NULL;
2777         PyObject *py_class, *item;
2778         ReportList reports;
2779         StructRegisterFunc reg;
2780         BPy_StructRNA *py_srna;
2781         StructRNA *srna;
2782
2783         if(!PyArg_ParseTuple(args, "O:register", &py_class))
2784                 return NULL;
2785         
2786         if(!PyType_Check(py_class)) {
2787                 PyErr_SetString(PyExc_AttributeError, "expected a Type subclassed from a registerable rna type (no a Type object).");
2788                 return NULL;
2789         }
2790
2791         /* check we got an __rna__ attribute */
2792         item= PyObject_GetAttrString(py_class, "__rna__");
2793
2794         if(!item || !BPy_StructRNA_Check(item)) {
2795                 Py_XDECREF(item);
2796                 PyErr_SetString(PyExc_AttributeError, "expected a Type subclassed from a registerable rna type (no __rna__ property).");
2797                 return NULL;
2798         }
2799
2800         /* check the __rna__ attribute has the right type */
2801         Py_DECREF(item);
2802         py_srna= (BPy_StructRNA*)item;
2803
2804         if(py_srna->ptr.type != &RNA_Struct) {
2805                 PyErr_SetString(PyExc_AttributeError, "expected a Type subclassed from a registerable rna type (not a Struct).");
2806                 return NULL;
2807         }
2808         
2809         /* check that we have a register callback for this type */
2810         reg= RNA_struct_register(py_srna->ptr.data);
2811
2812         if(!reg) {
2813                 PyErr_SetString(PyExc_AttributeError, "expected a Type subclassed from a registerable rna type (no register supported).");
2814                 return NULL;
2815         }
2816         
2817         /* get the context, so register callback can do necessary refreshes */
2818         C= BPy_GetContext();
2819
2820         /* call the register callback */
2821         BKE_reports_init(&reports, RPT_STORE);
2822         srna= reg(C, &reports, py_class, bpy_class_validate, bpy_class_call, bpy_class_free);
2823
2824         if(!srna) {
2825                 BPy_reports_to_error(&reports);
2826                 BKE_reports_clear(&reports);
2827                 return NULL;
2828         }
2829
2830         BKE_reports_clear(&reports);
2831
2832         pyrna_subtype_set_rna(py_class, srna); /* takes a ref to py_class */
2833
2834         Py_RETURN_NONE;
2835 }
2836
2837 PyObject *pyrna_basetype_unregister(PyObject *self, PyObject *args)
2838 {
2839         bContext *C= NULL;
2840         PyObject *py_class, *item;
2841         BPy_StructRNA *py_srna;
2842         StructUnregisterFunc unreg;
2843
2844         if(!PyArg_ParseTuple(args, "O:unregister", &py_class))
2845                 return NULL;
2846
2847         if(!PyType_Check(py_class)) {
2848                 PyErr_SetString(PyExc_AttributeError, "expected a Type subclassed from a registerable rna type (no a Type object).");
2849                 return NULL;
2850         }
2851
2852         /* check we got an __rna__ attribute */
2853         item= PyDict_GetItemString(((PyTypeObject*)py_class)->tp_dict, "__rna__");  /* borrow ref */
2854
2855         if(!item || !BPy_StructRNA_Check(item)) {
2856                 PyErr_SetString(PyExc_AttributeError, "expected a Type subclassed from a registerable rna type (no __rna__ property).");
2857                 return NULL;
2858         }
2859
2860         /* check the __rna__ attribute has the right type */
2861         py_srna= (BPy_StructRNA*)item;
2862
2863         if(py_srna->ptr.type != &RNA_Struct) {
2864                 PyErr_SetString(PyExc_AttributeError, "expected a Type subclassed from a registerable rna type (not a Struct).");
2865                 return NULL;
2866         }
2867         
2868         /* check that we have a unregister callback for this type */
2869         unreg= RNA_struct_unregister(py_srna->ptr.data);
2870
2871         if(!unreg) {
2872                 PyErr_SetString(PyExc_AttributeError, "expected a Type subclassed from a registerable rna type (no unregister supported).");
2873                 return NULL;
2874         }
2875         
2876         /* get the context, so register callback can do necessary refreshes */
2877         C= BPy_GetContext();
2878         
2879
2880         /* call unregister */
2881         unreg(C, py_srna->ptr.data);
2882
2883         /* remove reference to old type */
2884         Py_DECREF(py_class);
2885
2886         Py_RETURN_NONE;
2887 }
2888