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