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