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