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