c9cd44141273a0dd1934ef64a4b9e229f8e90fd3
[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 "blendef.h"
28 #include "BLI_dynstr.h"
29
30 #include "MEM_guardedalloc.h"
31 #include "BKE_global.h" /* evil G.* */
32
33 static int pyrna_struct_compare( BPy_StructRNA * a, BPy_StructRNA * b )
34 {
35         return (a->ptr.data==b->ptr.data) ? 0 : -1;
36 }
37
38 static int pyrna_prop_compare( BPy_PropertyRNA * a, BPy_PropertyRNA * b )
39 {
40         return (a->prop==b->prop && a->ptr.data==b->ptr.data ) ? 0 : -1;
41 }
42
43
44 /* For some reason python3 needs these :/ */
45 static PyObject *pyrna_struct_richcmp(BPy_StructRNA * a, BPy_StructRNA * b, int op)
46 {
47         int cmp_result= -1; /* assume false */
48         if (BPy_StructRNA_Check(a) && BPy_StructRNA_Check(b)) {
49                 cmp_result= pyrna_struct_compare(a, b);
50         }
51
52         return Py_CmpToRich(op, cmp_result);
53 }
54
55 static PyObject *pyrna_prop_richcmp(BPy_PropertyRNA * a, BPy_PropertyRNA * b, int op)
56 {
57         int cmp_result= -1; /* assume false */
58         if (BPy_PropertyRNA_Check(a) && BPy_PropertyRNA_Check(b)) {
59                 cmp_result= pyrna_prop_compare(a, b);
60         }
61
62         return Py_CmpToRich(op, cmp_result);
63 }
64
65 /*----------------------repr--------------------------------------------*/
66 static PyObject *pyrna_struct_repr( BPy_StructRNA * self )
67 {
68         return PyUnicode_FromFormat( "[BPy_StructRNA \"%s\"]", RNA_struct_identifier(&self->ptr));
69 }
70
71 static PyObject *pyrna_prop_repr( BPy_PropertyRNA * self )
72 {
73         return PyUnicode_FromFormat( "[BPy_PropertyRNA \"%s\" -> \"%s\" ]", RNA_struct_identifier(&self->ptr), RNA_property_identifier(&self->ptr, self->prop) );
74 }
75
76 static long pyrna_struct_hash( BPy_StructRNA * self )
77 {
78         return (long)self->ptr.data;
79 }
80
81 /* use our own dealloc so we can free a property if we use one */
82 static void pyrna_struct_dealloc( BPy_StructRNA * self )
83 {
84         /* Note!! for some weired reason calling PyObject_DEL() directly crashes blender! */
85         if (self->freeptr && self->ptr.data) {
86                 IDP_FreeProperty(self->ptr.data);
87                 MEM_freeN(self->ptr.data);
88                 self->ptr.data= NULL;
89         }
90
91         ((PyObject *)self)->ob_type->tp_free(self);
92         return;
93 }
94
95 static char *pyrna_enum_as_string(PointerRNA *ptr, PropertyRNA *prop)
96 {
97         const EnumPropertyItem *item;
98         int totitem, i;
99
100         DynStr *dynstr= BLI_dynstr_new();
101         char *cstring;
102
103         RNA_property_enum_items(ptr, prop, &item, &totitem);
104
105         for (i=0; i<totitem; i++) {
106                 
107                 BLI_dynstr_appendf(dynstr, i?", '%s'":"'%s'", item[i].identifier);
108         }
109         
110         cstring = BLI_dynstr_get_cstring(dynstr);
111         BLI_dynstr_free(dynstr);
112         return cstring;
113 }
114
115 PyObject * pyrna_prop_to_py(PointerRNA *ptr, PropertyRNA *prop)
116 {
117         PyObject *ret;
118         int type = RNA_property_type(ptr, prop);
119         int len = RNA_property_array_length(ptr, prop);
120
121         if (len > 0) {
122                 /* resolve the array from a new pytype */
123                 return pyrna_prop_CreatePyObject(ptr, prop);
124         }
125         
126         /* see if we can coorce into a python type - PropertyType */
127         switch (type) {
128         case PROP_BOOLEAN:
129                 ret = PyBool_FromLong( RNA_property_boolean_get(ptr, prop) );
130                 break;
131         case PROP_INT:
132                 ret = PyLong_FromSize_t( (size_t)RNA_property_int_get(ptr, prop) );
133                 break;
134         case PROP_FLOAT:
135                 ret = PyFloat_FromDouble( RNA_property_float_get(ptr, prop) );
136                 break;
137         case PROP_STRING:
138         {
139                 char *buf;
140                 buf = RNA_property_string_get_alloc(ptr, prop, NULL, -1);
141                 ret = PyUnicode_FromString( buf );
142                 MEM_freeN(buf);
143                 break;
144         }
145         case PROP_ENUM:
146         {
147                 const char *identifier;
148                 int val = RNA_property_enum_get(ptr, prop);
149                 
150                 if (RNA_property_enum_identifier(ptr, prop, val, &identifier)) {
151                         ret = PyUnicode_FromString( identifier );
152                 } else {
153                         PyErr_Format(PyExc_AttributeError, "RNA Error: Current value \"%d\" matches no enum", val);
154                         ret = NULL;
155                 }
156
157                 break;
158         }
159         case PROP_POINTER:
160         {
161                 PointerRNA newptr;
162                 newptr= RNA_property_pointer_get(ptr, prop);
163                 if (newptr.data) {
164                         ret = pyrna_struct_CreatePyObject(&newptr);
165                 } else {
166                         ret = Py_None;
167                         Py_INCREF(ret);
168                 }
169                 break;
170         }
171         case PROP_COLLECTION:
172                 ret = pyrna_prop_CreatePyObject(ptr, prop);
173                 break;
174         default:
175                 PyErr_Format(PyExc_AttributeError, "RNA Error: unknown type \"%d\" (pyrna_prop_to_py)", type);
176                 ret = NULL;
177                 break;
178         }
179         
180         return ret;
181 }
182
183
184 int pyrna_py_to_prop(PointerRNA *ptr, PropertyRNA *prop, PyObject *value)
185 {
186         int type = RNA_property_type(ptr, prop);
187         int len = RNA_property_array_length(ptr, prop);
188         
189         if (len > 0) {
190                 PyObject *item;
191                 int i;
192                 
193                 if (!PySequence_Check(value)) {
194                         PyErr_SetString(PyExc_TypeError, "expected a python sequence type assigned to an RNA array.");
195                         return -1;
196                 }
197                 
198                 if ((int)PySequence_Length(value) != len) {
199                         PyErr_SetString(PyExc_AttributeError, "python sequence length did not match the RNA array.");
200                         return -1;
201                 }
202                 
203                 /* for arrays we have a limited number of types */
204                 switch (type) {
205                 case PROP_BOOLEAN:
206                 {
207                         int *param_arr = MEM_mallocN(sizeof(char) * len, "pyrna bool array");
208                         
209                         /* collect the variables before assigning, incase one of them is incorrect */
210                         for (i=0; i<len; i++) {
211                                 item = PySequence_GetItem(value, i);
212                                 param_arr[i] = PyObject_IsTrue( item );
213                                 Py_DECREF(item);
214                                 
215                                 if (param_arr[i] < 0) {
216                                         MEM_freeN(param_arr);
217                                         PyErr_SetString(PyExc_AttributeError, "one or more of the values in the sequence is not a boolean");
218                                         return -1;
219                                 }
220                         }
221                         
222                         RNA_property_boolean_set_array(ptr, prop, param_arr);
223                         
224                         MEM_freeN(param_arr);
225                         break;
226                 }
227                 case PROP_INT:
228                 {
229                         int *param_arr = MEM_mallocN(sizeof(int) * len, "pyrna int array");
230                         
231                         /* collect the variables before assigning, incase one of them is incorrect */
232                         for (i=0; i<len; i++) {
233                                 item = PySequence_GetItem(value, i);
234                                 param_arr[i] = (int)PyLong_AsSsize_t(item); /* deal with any errors later */
235                                 Py_DECREF(item);
236                         }
237                         
238                         if (PyErr_Occurred()) {
239                                 MEM_freeN(param_arr);
240                                 PyErr_SetString(PyExc_AttributeError, "one or more of the values in the sequence could not be used as an int");
241                                 return -1;
242                         }
243                         
244                         RNA_property_int_set_array(ptr, prop, param_arr);
245                         
246                         MEM_freeN(param_arr);
247                         break;
248                 }
249                 case PROP_FLOAT:
250                 {
251                         float *param_arr = MEM_mallocN(sizeof(float) * len, "pyrna float array");
252                         
253                         /* collect the variables before assigning, incase one of them is incorrect */
254                         for (i=0; i<len; i++) {
255                                 item = PySequence_GetItem(value, i);
256                                 param_arr[i] = (float)PyFloat_AsDouble(item); /* deal with any errors later */
257                                 Py_DECREF(item);
258                         }
259                         
260                         if (PyErr_Occurred()) {
261                                 MEM_freeN(param_arr);
262                                 PyErr_SetString(PyExc_AttributeError, "one or more of the values in the sequence could not be used as a float");
263                                 return -1;
264                         }
265                         
266                         RNA_property_float_set_array(ptr, prop, param_arr);
267                         
268                         MEM_freeN(param_arr);
269                         break;
270                 }
271                 }
272         } else {
273                 /* Normal Property (not an array) */
274                 
275                 /* see if we can coorce into a python type - PropertyType */
276                 switch (type) {
277                 case PROP_BOOLEAN:
278                 {
279                         int param = PyObject_IsTrue( value );
280                         
281                         if( param < 0 ) {
282                                 PyErr_SetString(PyExc_TypeError, "expected True/False or 0/1");
283                                 return -1;
284                         } else {
285                                 RNA_property_boolean_set(ptr, prop, param);
286                         }
287                         break;
288                 }
289                 case PROP_INT:
290                 {
291                         int param = PyLong_AsSsize_t(value);
292                         if (PyErr_Occurred()) {
293                                 PyErr_SetString(PyExc_TypeError, "expected an int type");
294                                 return -1;
295                         } else {
296                                 RNA_property_int_set(ptr, prop, param);
297                         }
298                         break;
299                 }
300                 case PROP_FLOAT:
301                 {
302                         float param = PyFloat_AsDouble(value);
303                         if (PyErr_Occurred()) {
304                                 PyErr_SetString(PyExc_TypeError, "expected a float type");
305                                 return -1;
306                         } else {
307                                 RNA_property_float_set(ptr, prop, param);
308                         }
309                         break;
310                 }
311                 case PROP_STRING:
312                 {
313                         char *param = _PyUnicode_AsString(value);
314                         
315                         if (param==NULL) {
316                                 PyErr_SetString(PyExc_TypeError, "expected a string type");
317                                 return -1;
318                         } else {
319                                 RNA_property_string_set(ptr, prop, param);
320                         }
321                         break;
322                 }
323                 case PROP_ENUM:
324                 {
325                         char *param = _PyUnicode_AsString(value);
326                         
327                         if (param==NULL) {
328                                 char *enum_str= pyrna_enum_as_string(ptr, prop);
329                                 PyErr_Format(PyExc_TypeError, "expected a string enum type in (%s)", enum_str);
330                                 MEM_freeN(enum_str);
331                                 return -1;
332                         } else {
333                                 int val;
334                                 if (RNA_property_enum_value(ptr, prop, param, &val)) {
335                                         RNA_property_enum_set(ptr, prop, val);
336                                 } else {
337                                         char *enum_str= pyrna_enum_as_string(ptr, prop);
338                                         PyErr_Format(PyExc_AttributeError, "enum \"%s\" not found in (%s)", param, enum_str);
339                                         MEM_freeN(enum_str);
340                                         return -1;
341                                 }
342                         }
343                         
344                         break;
345                 }
346                 case PROP_POINTER:
347                 {
348                         PyErr_SetString(PyExc_AttributeError, "cant assign pointers yet");
349                         return -1;
350                         break;
351                 }
352                 case PROP_COLLECTION:
353                         PyErr_SetString(PyExc_AttributeError, "cant assign to collections");
354                         return -1;
355                         break;
356                 default:
357                         PyErr_SetString(PyExc_AttributeError, "unknown property type (pyrna_py_to_prop)");
358                         return -1;
359                         break;
360                 }
361         }
362         
363         return 0;
364 }
365
366
367 static PyObject * pyrna_prop_to_py_index(PointerRNA *ptr, PropertyRNA *prop, int index)
368 {
369         PyObject *ret;
370         int type = RNA_property_type(ptr, prop);
371         
372         /* see if we can coorce into a python type - PropertyType */
373         switch (type) {
374         case PROP_BOOLEAN:
375                 ret = PyBool_FromLong( RNA_property_boolean_get_index(ptr, prop, index) );
376                 break;
377         case PROP_INT:
378                 ret = PyLong_FromSize_t( (size_t)RNA_property_int_get_index(ptr, prop, index) );
379                 break;
380         case PROP_FLOAT:
381                 ret = PyFloat_FromDouble( RNA_property_float_get_index(ptr, prop, index) );
382                 break;
383         default:
384                 PyErr_SetString(PyExc_AttributeError, "not an array type");
385                 ret = NULL;
386                 break;
387         }
388         
389         return ret;
390 }
391
392 static int pyrna_py_to_prop_index(PointerRNA *ptr, PropertyRNA *prop, int index, PyObject *value)
393 {
394         int ret = 0;
395         int type = RNA_property_type(ptr, prop);
396         
397         /* see if we can coorce into a python type - PropertyType */
398         switch (type) {
399         case PROP_BOOLEAN:
400         {
401                 int param = PyObject_IsTrue( value );
402                 
403                 if( param < 0 ) {
404                         PyErr_SetString(PyExc_TypeError, "expected True/False or 0/1");
405                         ret = -1;
406                 } else {
407                         RNA_property_boolean_set_index(ptr, prop, index, param);
408                 }
409                 break;
410         }
411         case PROP_INT:
412         {
413                 int param = PyLong_AsSsize_t(value);
414                 if (PyErr_Occurred()) {
415                         PyErr_SetString(PyExc_TypeError, "expected an int type");
416                         ret = -1;
417                 } else {
418                         RNA_property_int_set_index(ptr, prop, index, param);
419                 }
420                 break;
421         }
422         case PROP_FLOAT:
423         {
424                 float param = PyFloat_AsDouble(value);
425                 if (PyErr_Occurred()) {
426                         PyErr_SetString(PyExc_TypeError, "expected a float type");
427                         ret = -1;
428                 } else {
429                         RNA_property_float_set_index(ptr, prop, index, param);
430                 }
431                 break;
432         }
433         default:
434                 PyErr_SetString(PyExc_AttributeError, "not an array type");
435                 ret = -1;
436                 break;
437         }
438         
439         return ret;
440 }
441
442 //---------------sequence-------------------------------------------
443 static Py_ssize_t pyrna_prop_len( BPy_PropertyRNA * self )
444 {
445         Py_ssize_t len;
446         
447         if (RNA_property_type(&self->ptr, self->prop) == PROP_COLLECTION) {
448                 len = RNA_property_collection_length(&self->ptr, self->prop);
449         } else {
450                 len = RNA_property_array_length(&self->ptr, self->prop);
451                 
452                 if (len==0) { /* not an array*/
453                         PyErr_SetString(PyExc_AttributeError, "len() only available for collection RNA types");
454                         return -1;
455                 }
456         }
457         
458         return len;
459 }
460
461 static PyObject *pyrna_prop_subscript( BPy_PropertyRNA * self, PyObject *key )
462 {
463         PyObject *ret;
464         PointerRNA newptr;
465         int keynum = 0;
466         char *keyname = NULL;
467         
468         if (PyUnicode_Check(key)) {
469                 keyname = _PyUnicode_AsString(key);
470         } else if (PyLong_Check(key)) {
471                 keynum = PyLong_AsSsize_t(key);
472         } else {
473                 PyErr_SetString(PyExc_AttributeError, "invalid key, key must be a string or an int");
474                 return NULL;
475         }
476         
477         if (RNA_property_type(&self->ptr, self->prop) == PROP_COLLECTION) {
478                 int ok;
479                 if (keyname)    ok = RNA_property_collection_lookup_string(&self->ptr, self->prop, keyname, &newptr);
480                 else                    ok = RNA_property_collection_lookup_int(&self->ptr, self->prop, keynum, &newptr);
481                 
482                 if (ok) {
483                         ret = pyrna_struct_CreatePyObject(&newptr);
484                 } else {
485                         PyErr_SetString(PyExc_AttributeError, "out of range");
486                         ret = NULL;
487                 }
488                 
489         } else if (keyname) {
490                 PyErr_SetString(PyExc_AttributeError, "string keys are only supported for collections");
491                 ret = NULL;
492         } else {
493                 int len = RNA_property_array_length(&self->ptr, self->prop);
494                 
495                 if (len==0) { /* not an array*/
496                         PyErr_Format(PyExc_AttributeError, "not an array or collection %d", keynum);
497                         ret = NULL;
498                 }
499                 
500                 if (keynum >= len){
501                         PyErr_SetString(PyExc_AttributeError, "index out of range");
502                         ret = NULL;
503                 } else { /* not an array*/
504                         ret = pyrna_prop_to_py_index(&self->ptr, self->prop, keynum);
505                 }
506         }
507         
508         return ret;
509 }
510
511
512 static int pyrna_prop_assign_subscript( BPy_PropertyRNA * self, PyObject *key, PyObject *value )
513 {
514         int ret = 0;
515         int keynum = 0;
516         char *keyname = NULL;
517         
518         if (!RNA_property_editable(&self->ptr, self->prop)) {
519                 PyErr_Format( PyExc_AttributeError, "Attribute \"%s\" from \"%s\" is read-only", RNA_property_identifier(&self->ptr, self->prop), RNA_struct_identifier(&self->ptr) );
520                 return -1;
521         }
522         
523         if (PyUnicode_Check(key)) {
524                 keyname = _PyUnicode_AsString(key);
525         } else if (PyLong_Check(key)) {
526                 keynum = PyLong_AsSsize_t(key);
527         } else {
528                 PyErr_SetString(PyExc_AttributeError, "invalid key, key must be a string or an int");
529                 return -1;
530         }
531         
532         if (RNA_property_type(&self->ptr, self->prop) == PROP_COLLECTION) {
533                 PyErr_SetString(PyExc_AttributeError, "assignment is not supported for collections (yet)");
534                 ret = -1;
535         } else if (keyname) {
536                 PyErr_SetString(PyExc_AttributeError, "string keys are only supported for collections");
537                 ret = -1;
538         } else {
539                 int len = RNA_property_array_length(&self->ptr, self->prop);
540                 
541                 if (len==0) { /* not an array*/
542                         PyErr_Format(PyExc_AttributeError, "not an array or collection %d", keynum);
543                         ret = -1;
544                 }
545                 
546                 if (keynum >= len){
547                         PyErr_SetString(PyExc_AttributeError, "index out of range");
548                         ret = -1;
549                 } else {
550                         ret = pyrna_py_to_prop_index(&self->ptr, self->prop, keynum, value);
551                 }
552         }
553         
554         return ret;
555 }
556
557
558
559 static PyMappingMethods pyrna_prop_as_mapping = {
560         ( inquiry ) pyrna_prop_len,     /* mp_length */
561         ( binaryfunc ) pyrna_prop_subscript,    /* mp_subscript */
562         ( objobjargproc ) pyrna_prop_assign_subscript,  /* mp_ass_subscript */
563 };
564
565 static PyObject *pyrna_struct_dir(BPy_StructRNA * self)
566 {
567         PyObject *ret, *dict;
568         PyObject *pystring = PyUnicode_FromString("__dict__");
569         
570         /* Include this incase this instance is a subtype of a python class
571          * In these instances we may want to return a function or variable provided by the subtype
572          * */
573         dict = PyObject_GenericGetAttr((PyObject *)self, pystring);
574         Py_DECREF(pystring);
575         
576         if (dict==NULL) {
577                 PyErr_Clear();
578                 ret = PyList_New(0);
579         }
580         else {
581                 ret = PyDict_Keys(dict);
582                 Py_DECREF(dict);
583         }
584         
585         /* Collect RNA items*/
586         {
587                 PropertyRNA *iterprop, *nameprop;
588                 CollectionPropertyIterator iter;
589                 char name[256], *nameptr;
590
591                 iterprop= RNA_struct_iterator_property(&self->ptr);
592                 RNA_property_collection_begin(&self->ptr, iterprop, &iter);
593
594                 for(; iter.valid; RNA_property_collection_next(&iter)) {
595                         if(iter.ptr.data && (nameprop = RNA_struct_name_property(&iter.ptr))) {
596                                 nameptr= RNA_property_string_get_alloc(&iter.ptr, nameprop, name, sizeof(name));
597                                 
598                                 pystring = PyUnicode_FromString(nameptr);
599                                 PyList_Append(ret, pystring);
600                                 Py_DECREF(pystring);
601                                 
602                                 if ((char *)&name != nameptr)
603                                         MEM_freeN(nameptr);
604                         }
605                 }
606                 
607                 RNA_property_collection_end(&iter);
608         }
609         
610         return ret;
611 }
612
613
614 //---------------getattr--------------------------------------------
615 static PyObject *pyrna_struct_getattro( BPy_StructRNA * self, PyObject *pyname )
616 {
617         char *name = _PyUnicode_AsString(pyname);
618         PyObject *ret;
619         PropertyRNA *prop;
620         
621         /* Include this incase this instance is a subtype of a python class
622          * In these instances we may want to return a function or variable provided by the subtype
623          * */
624         ret = PyObject_GenericGetAttr((PyObject *)self, pyname);
625         if (ret)        return ret;
626         else            PyErr_Clear();
627         /* done with subtypes */
628
629         prop = RNA_struct_find_property(&self->ptr, name);
630         
631         if (prop) {
632                 ret = pyrna_prop_to_py(&self->ptr, prop);
633         }
634         else {
635                 PyErr_Format( PyExc_AttributeError, "Attribute \"%s\" not found", name);
636                 ret = NULL;
637         }
638         
639         return ret;
640 }
641
642 //--------------- setattr-------------------------------------------
643 static int pyrna_struct_setattro( BPy_StructRNA * self, PyObject *pyname, PyObject * value )
644 {
645         char *name = _PyUnicode_AsString(pyname);
646         PropertyRNA *prop = RNA_struct_find_property(&self->ptr, name);
647         
648         if (prop==NULL) {
649                 PyErr_Format( PyExc_AttributeError, "Attribute \"%s\" not found", name);
650                 return -1;
651         }               
652         
653         if (!RNA_property_editable(&self->ptr, prop)) {
654                 PyErr_Format( PyExc_AttributeError, "Attribute \"%s\" from \"%s\" is read-only", RNA_property_identifier(&self->ptr, prop), RNA_struct_identifier(&self->ptr) );
655                 return -1;
656         }
657                 
658         /* pyrna_py_to_prop sets its own exceptions */
659         return pyrna_py_to_prop(&self->ptr, prop, value);
660 }
661
662 PyObject *pyrna_prop_keys(BPy_PropertyRNA *self)
663 {
664         PyObject *ret;
665         if (RNA_property_type(&self->ptr, self->prop) != PROP_COLLECTION) {
666                 PyErr_SetString( PyExc_TypeError, "keys() is only valid for collection types" );
667                 ret = NULL;
668         } else {
669                 PyObject *item;
670                 CollectionPropertyIterator iter;
671                 PropertyRNA *nameprop;
672                 char name[256], *nameptr;
673
674                 ret = PyList_New(0);
675                 
676                 RNA_property_collection_begin(&self->ptr, self->prop, &iter);
677                 for(; iter.valid; RNA_property_collection_next(&iter)) {
678                         if(iter.ptr.data && (nameprop = RNA_struct_name_property(&iter.ptr))) {
679                                 nameptr= RNA_property_string_get_alloc(&iter.ptr, nameprop, name, sizeof(name));                                
680                                 
681                                 /* add to python list */
682                                 item = PyUnicode_FromString( nameptr );
683                                 PyList_Append(ret, item);
684                                 Py_DECREF(item);
685                                 /* done */
686                                 
687                                 if ((char *)&name != nameptr)
688                                         MEM_freeN(nameptr);
689                         }
690                 }
691                 RNA_property_collection_end(&iter);
692         }
693         
694         return ret;
695 }
696
697 PyObject *pyrna_prop_items(BPy_PropertyRNA *self)
698 {
699         PyObject *ret;
700         if (RNA_property_type(&self->ptr, self->prop) != PROP_COLLECTION) {
701                 PyErr_SetString( PyExc_TypeError, "items() is only valid for collection types" );
702                 ret = NULL;
703         } else {
704                 PyObject *item;
705                 CollectionPropertyIterator iter;
706                 PropertyRNA *nameprop;
707                 char name[256], *nameptr;
708
709                 ret = PyList_New(0);
710                 
711                 RNA_property_collection_begin(&self->ptr, self->prop, &iter);
712                 for(; iter.valid; RNA_property_collection_next(&iter)) {
713                         if(iter.ptr.data && (nameprop = RNA_struct_name_property(&iter.ptr))) {
714                                 nameptr= RNA_property_string_get_alloc(&iter.ptr, nameprop, name, sizeof(name));
715                                 
716                                 /* add to python list */
717                                 item = Py_BuildValue("(NN)", PyUnicode_FromString( nameptr ), pyrna_struct_CreatePyObject(&iter.ptr));
718                                 PyList_Append(ret, item);
719                                 Py_DECREF(item);
720                                 /* done */
721                                 
722                                 if ((char *)&name != nameptr)
723                                         MEM_freeN(nameptr);
724                         }
725                 }
726                 RNA_property_collection_end(&iter);
727         }
728         
729         return ret;
730 }
731
732
733 PyObject *pyrna_prop_values(BPy_PropertyRNA *self)
734 {
735         PyObject *ret;
736         if (RNA_property_type(&self->ptr, self->prop) != PROP_COLLECTION) {
737                 PyErr_SetString( PyExc_TypeError, "values() is only valid for collection types" );
738                 ret = NULL;
739         } else {
740                 PyObject *item;
741                 CollectionPropertyIterator iter;
742                 PropertyRNA *nameprop;
743                 
744                 ret = PyList_New(0);
745                 
746                 RNA_property_collection_begin(&self->ptr, self->prop, &iter);
747                 for(; iter.valid; RNA_property_collection_next(&iter)) {
748                         if(iter.ptr.data && (nameprop = RNA_struct_name_property(&iter.ptr))) {
749                                 item = pyrna_struct_CreatePyObject(&iter.ptr);
750                                 PyList_Append(ret, item);
751                                 Py_DECREF(item);
752                         }
753                 }
754                 RNA_property_collection_end(&iter);
755         }
756         
757         return ret;
758 }
759
760 /* A bit of a kludge, make a list out of a collection or array,
761  * then return the lists iter function, not especially fast but convenient for now */
762 PyObject *pyrna_prop_iter(BPy_PropertyRNA *self)
763 {
764         /* Try get values from a collection */
765         PyObject *ret = pyrna_prop_values(self);
766         
767         if (ret==NULL) {
768                 /* collection did not work, try array */
769                 int len = RNA_property_array_length(&self->ptr, self->prop);
770                 
771                 if (len) {
772                         int i;
773                         PyErr_Clear();
774                         ret = PyList_New(len);
775                         
776                         for (i=0; i < len; i++) {
777                                 PyList_SET_ITEM(ret, i, pyrna_prop_to_py_index(&self->ptr, self->prop, i));
778                         }
779                 }
780         }
781         
782         if (ret) {
783                 /* we know this is a list so no need to PyIter_Check */
784                 PyObject *iter = PyObject_GetIter(ret); 
785                 Py_DECREF(ret);
786                 return iter;
787         }
788         
789         PyErr_SetString( PyExc_TypeError, "this BPy_PropertyRNA object is not iterable" );
790         return NULL;
791 }
792
793 static struct PyMethodDef pyrna_struct_methods[] = {
794         {"__dir__", (PyCFunction)pyrna_struct_dir, METH_NOARGS, ""},
795         {NULL, NULL, 0, NULL}
796 };
797
798 static struct PyMethodDef pyrna_prop_methods[] = {
799         {"keys", (PyCFunction)pyrna_prop_keys, METH_NOARGS, ""},
800         {"items", (PyCFunction)pyrna_prop_items, METH_NOARGS, ""},
801         {"values", (PyCFunction)pyrna_prop_values, METH_NOARGS, ""},
802         {NULL, NULL, 0, NULL}
803 };
804
805 /* only needed for subtyping, so a new class gets a valid BPy_StructRNA
806  * todo - also accept useful args */
807 static PyObject * pyrna_struct_new(PyTypeObject *type, PyObject *args, PyObject *kwds) {
808
809         BPy_StructRNA *base = NULL;
810         
811         if (!PyArg_ParseTuple(args, "O!:Base BPy_StructRNA", &pyrna_struct_Type, &base))
812                 return NULL;
813         
814         if (type == &pyrna_struct_Type) {
815                 return pyrna_struct_CreatePyObject(&base->ptr);
816         } else {
817                 BPy_StructRNA *ret = (BPy_StructRNA *) type->tp_alloc(type, 0);
818                 ret->ptr = base->ptr;
819                 return (PyObject *)ret;
820         }
821 }
822
823 /* only needed for subtyping, so a new class gets a valid BPy_StructRNA
824  * todo - also accept useful args */
825 static PyObject * pyrna_prop_new(PyTypeObject *type, PyObject *args, PyObject *kwds) {
826
827         BPy_PropertyRNA *base = NULL;
828         
829         if (!PyArg_ParseTuple(args, "O!:Base BPy_PropertyRNA", &pyrna_prop_Type, &base))
830                 return NULL;
831         
832         if (type == &pyrna_prop_Type) {
833                 return pyrna_prop_CreatePyObject(&base->ptr, base->prop);
834         } else {
835                 BPy_PropertyRNA *ret = (BPy_PropertyRNA *) type->tp_alloc(type, 0);
836                 ret->ptr = base->ptr;
837                 ret->prop = base->prop;
838                 return (PyObject *)ret;
839         }
840 }
841
842 /*-----------------------BPy_StructRNA method def------------------------------*/
843 PyTypeObject pyrna_struct_Type = {
844 #if (PY_VERSION_HEX >= 0x02060000)
845         PyVarObject_HEAD_INIT(NULL, 0)
846 #else
847         /* python 2.5 and below */
848         PyObject_HEAD_INIT( NULL )  /* required py macro */
849         0,                          /* ob_size */
850 #endif
851         "StructRNA",                    /* tp_name */
852         sizeof( BPy_StructRNA ),        /* tp_basicsize */
853         0,                      /* tp_itemsize */
854         /* methods */
855         ( destructor ) pyrna_struct_dealloc,/* tp_dealloc */
856         NULL,                       /* printfunc tp_print; */
857         NULL,                                           /* getattrfunc tp_getattr; */
858         NULL,                                           /* setattrfunc tp_setattr; */
859         NULL,                                           /* tp_compare */ /* DEPRECATED in python 3.0! */
860         ( reprfunc ) pyrna_struct_repr, /* tp_repr */
861
862         /* Method suites for standard classes */
863
864         NULL,                       /* PyNumberMethods *tp_as_number; */
865         NULL,                                           /* PySequenceMethods *tp_as_sequence; */
866         NULL,                                           /* PyMappingMethods *tp_as_mapping; */
867
868         /* More standard operations (here for binary compatibility) */
869
870         ( hashfunc )pyrna_struct_hash,  /* hashfunc tp_hash; */
871         NULL,                                           /* ternaryfunc tp_call; */
872         NULL,                       /* reprfunc tp_str; */
873         ( getattrofunc ) pyrna_struct_getattro, /* getattrofunc tp_getattro; */
874         ( setattrofunc ) pyrna_struct_setattro, /* setattrofunc tp_setattro; */
875
876         /* Functions to access object as input/output buffer */
877         NULL,                       /* PyBufferProcs *tp_as_buffer; */
878
879   /*** Flags to define presence of optional/expanded features ***/
880         Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE,         /* long tp_flags; */
881
882         NULL,                                           /*  char *tp_doc;  Documentation string */
883   /*** Assigned meaning in release 2.0 ***/
884         /* call function for all accessible objects */
885         NULL,                       /* traverseproc tp_traverse; */
886
887         /* delete references to contained objects */
888         NULL,                       /* inquiry tp_clear; */
889
890   /***  Assigned meaning in release 2.1 ***/
891   /*** rich comparisons ***/
892         (richcmpfunc)pyrna_struct_richcmp,      /* richcmpfunc tp_richcompare; */
893
894   /***  weak reference enabler ***/
895         0,                          /* long tp_weaklistoffset; */
896
897   /*** Added in release 2.2 ***/
898         /*   Iterators */
899         NULL,                       /* getiterfunc tp_iter; */
900         NULL,                       /* iternextfunc tp_iternext; */
901
902   /*** Attribute descriptor and subclassing stuff ***/
903         pyrna_struct_methods,                   /* struct PyMethodDef *tp_methods; */
904         NULL,                       /* struct PyMemberDef *tp_members; */
905         NULL,                                           /* struct PyGetSetDef *tp_getset; */
906         NULL,                       /* struct _typeobject *tp_base; */
907         NULL,                       /* PyObject *tp_dict; */
908         NULL,                       /* descrgetfunc tp_descr_get; */
909         NULL,                       /* descrsetfunc tp_descr_set; */
910         0,                          /* long tp_dictoffset; */
911         NULL,                       /* initproc tp_init; */
912         NULL,                       /* allocfunc tp_alloc; */
913         pyrna_struct_new,                       /* newfunc tp_new; */
914         /*  Low-level free-memory routine */
915         NULL,                       /* freefunc tp_free;  */
916         /* For PyObject_IS_GC */
917         NULL,                       /* inquiry tp_is_gc;  */
918         NULL,                       /* PyObject *tp_bases; */
919         /* method resolution order */
920         NULL,                       /* PyObject *tp_mro;  */
921         NULL,                       /* PyObject *tp_cache; */
922         NULL,                       /* PyObject *tp_subclasses; */
923         NULL,                       /* PyObject *tp_weaklist; */
924         NULL
925 };
926
927 /*-----------------------BPy_PropertyRNA method def------------------------------*/
928 PyTypeObject pyrna_prop_Type = {
929 #if (PY_VERSION_HEX >= 0x02060000)
930         PyVarObject_HEAD_INIT(NULL, 0)
931 #else
932         /* python 2.5 and below */
933         PyObject_HEAD_INIT( NULL )  /* required py macro */
934         0,                          /* ob_size */
935 #endif
936         
937         "PropertyRNA",          /* tp_name */
938         sizeof( BPy_PropertyRNA ),                      /* tp_basicsize */
939         0,                      /* tp_itemsize */
940         /* methods */
941         NULL,                                           /* tp_dealloc */
942         NULL,                       /* printfunc tp_print; */
943         NULL,                                           /* getattrfunc tp_getattr; */
944         NULL,                       /* setattrfunc tp_setattr; */
945         NULL,                                           /* tp_compare */ /* DEPRECATED in python 3.0! */
946         ( reprfunc ) pyrna_prop_repr,   /* tp_repr */
947
948         /* Method suites for standard classes */
949
950         NULL,                       /* PyNumberMethods *tp_as_number; */
951         NULL,                                           /* PySequenceMethods *tp_as_sequence; */
952         &pyrna_prop_as_mapping,         /* PyMappingMethods *tp_as_mapping; */
953
954         /* More standard operations (here for binary compatibility) */
955
956         NULL,                                           /* hashfunc tp_hash; */
957         NULL,                       /* ternaryfunc tp_call; */
958         NULL,                       /* reprfunc tp_str; */
959         NULL, /*PyObject_GenericGetAttr - MINGW Complains, assign later */      /* getattrofunc tp_getattro; */ /* will only use these if this is a subtype of a py class */
960         NULL, /*PyObject_GenericSetAttr - MINGW Complains, assign later */      /* setattrofunc tp_setattro; */
961
962         /* Functions to access object as input/output buffer */
963         NULL,                       /* PyBufferProcs *tp_as_buffer; */
964
965   /*** Flags to define presence of optional/expanded features ***/
966         Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE,         /* long tp_flags; */
967
968         NULL,                                           /*  char *tp_doc;  Documentation string */
969   /*** Assigned meaning in release 2.0 ***/
970         /* call function for all accessible objects */
971         NULL,                       /* traverseproc tp_traverse; */
972
973         /* delete references to contained objects */
974         NULL,                       /* inquiry tp_clear; */
975
976   /***  Assigned meaning in release 2.1 ***/
977   /*** rich comparisons ***/
978         (richcmpfunc)pyrna_prop_richcmp,        /* richcmpfunc tp_richcompare; */
979
980   /***  weak reference enabler ***/
981         0,                          /* long tp_weaklistoffset; */
982
983   /*** Added in release 2.2 ***/
984         /*   Iterators */
985         (getiterfunc)pyrna_prop_iter,   /* getiterfunc tp_iter; */
986         NULL,                       /* iternextfunc tp_iternext; */
987
988   /*** Attribute descriptor and subclassing stuff ***/
989         pyrna_prop_methods,                     /* struct PyMethodDef *tp_methods; */
990         NULL,                       /* struct PyMemberDef *tp_members; */
991         NULL,                                           /* struct PyGetSetDef *tp_getset; */
992         NULL,                       /* struct _typeobject *tp_base; */
993         NULL,                       /* PyObject *tp_dict; */
994         NULL,                       /* descrgetfunc tp_descr_get; */
995         NULL,                       /* descrsetfunc tp_descr_set; */
996         0,                          /* long tp_dictoffset; */
997         NULL,                       /* initproc tp_init; */
998         NULL,                       /* allocfunc tp_alloc; */
999         pyrna_prop_new,                         /* newfunc tp_new; */
1000         /*  Low-level free-memory routine */
1001         NULL,                       /* freefunc tp_free;  */
1002         /* For PyObject_IS_GC */
1003         NULL,                       /* inquiry tp_is_gc;  */
1004         NULL,                       /* PyObject *tp_bases; */
1005         /* method resolution order */
1006         NULL,                       /* PyObject *tp_mro;  */
1007         NULL,                       /* PyObject *tp_cache; */
1008         NULL,                       /* PyObject *tp_subclasses; */
1009         NULL,                       /* PyObject *tp_weaklist; */
1010         NULL
1011 };
1012
1013 PyObject* pyrna_struct_Subtype(PointerRNA *ptr)
1014 {
1015         PyObject *newclass = NULL;
1016         PropertyRNA *nameprop;
1017
1018         if (ptr->type==NULL) {
1019                 newclass= NULL; /* Nothing to do */
1020         } else if ((nameprop = RNA_struct_name_property(ptr))) {
1021                 /* for now, return the base RNA type rather then a real module */
1022                 
1023                 /* Assume BPy_RNA_PYTYPE(ptr->data) was alredy checked */
1024                 
1025                 /* subclass equivelents
1026                 - class myClass(myBase):
1027                         some='value' # or ...
1028                 - myClass = type(name='myClass', bases=(myBase,), dict={'some':'value'})
1029                 */
1030                 char name[256], *nameptr;
1031
1032                 PyObject *args = PyTuple_New(3);
1033                 PyObject *bases = PyTuple_New(1);
1034                 PyObject *dict = PyDict_New();
1035                 PyObject *rna;
1036                 
1037                 nameptr= RNA_property_string_get_alloc(ptr, nameprop, name, sizeof(name));
1038                 
1039                 // arg 1
1040                 //PyTuple_SET_ITEM(args, 0, PyUnicode_FromString(tp_name));
1041                 PyTuple_SET_ITEM(args, 0, PyUnicode_FromString(nameptr));
1042                 
1043                 // arg 2
1044                 PyTuple_SET_ITEM(bases, 0, (PyObject *)&pyrna_struct_Type);
1045                 Py_INCREF(&pyrna_struct_Type);
1046                 PyTuple_SET_ITEM(args, 1, bases);
1047                 
1048                 // arg 3 - add an instance of the rna 
1049                 PyTuple_SET_ITEM(args, 2, dict); // fill with useful subclass things!
1050                 
1051                 if (PyErr_Occurred()) {
1052                         PyErr_Print();
1053                         PyErr_Clear();
1054                 }
1055                 
1056                 newclass = PyObject_CallObject((PyObject *)&PyType_Type, args);
1057                 // Set this later
1058                 
1059                 if (newclass) {
1060                         BPy_RNA_PYTYPE(ptr->data) = newclass; /* Store for later use */
1061                         
1062                         /* Not 100% needed but useful,
1063                          * having an instance within a type looks wrong however this instance IS an rna type */
1064                         rna = pyrna_struct_CreatePyObject(ptr);
1065                         PyDict_SetItemString(((PyTypeObject *)newclass)->tp_dict, "__rna__", rna);
1066                         Py_DECREF(rna);
1067                         /* done with rna instance */
1068                 }
1069                 Py_DECREF(args);
1070                 
1071                 if ((char *)&name != nameptr)
1072                         MEM_freeN(nameptr);
1073                 
1074         }
1075         
1076         return newclass;
1077 }
1078
1079 /*-----------------------CreatePyObject---------------------------------*/
1080 PyObject *pyrna_struct_CreatePyObject( PointerRNA *ptr )
1081 {
1082         BPy_StructRNA *pyrna;
1083         
1084         if (ptr->data==NULL && ptr->type==NULL) { /* Operator RNA has NULL data */
1085                 Py_RETURN_NONE;
1086         }
1087         
1088         if (ptr->type && BPy_RNA_PYTYPE(ptr->type)) {
1089                 PyTypeObject *tp = BPy_RNA_PYTYPE(ptr->type);
1090                 pyrna = (BPy_StructRNA *) tp->tp_alloc(tp, 0);
1091         }
1092         else {
1093                 pyrna = ( BPy_StructRNA * ) PyObject_NEW( BPy_StructRNA, &pyrna_struct_Type );
1094         }
1095         
1096         if( !pyrna ) {
1097                 PyErr_SetString( PyExc_MemoryError, "couldn't create BPy_StructRNA object" );
1098                 return NULL;
1099         }
1100         
1101         pyrna->ptr= *ptr;
1102         pyrna->freeptr= 0;
1103         
1104         return ( PyObject * ) pyrna;
1105 }
1106
1107 PyObject *pyrna_prop_CreatePyObject( PointerRNA *ptr, PropertyRNA *prop )
1108 {
1109         BPy_PropertyRNA *pyrna;
1110
1111         pyrna = ( BPy_PropertyRNA * ) PyObject_NEW( BPy_PropertyRNA, &pyrna_prop_Type );
1112
1113         if( !pyrna ) {
1114                 PyErr_SetString( PyExc_MemoryError, "couldn't create BPy_rna object" );
1115                 return NULL;
1116         }
1117         
1118         pyrna->ptr = *ptr;
1119         pyrna->prop = prop;
1120                 
1121         return ( PyObject * ) pyrna;
1122 }
1123
1124
1125 PyObject *BPY_rna_module( void )
1126 {
1127         PointerRNA ptr;
1128         
1129         /* This can't be set in the pytype struct because some compilers complain */
1130         pyrna_prop_Type.tp_getattro = PyObject_GenericGetAttr; 
1131         pyrna_prop_Type.tp_setattro = PyObject_GenericSetAttr; 
1132         
1133         if( PyType_Ready( &pyrna_struct_Type ) < 0 )
1134                 return NULL;
1135         
1136         if( PyType_Ready( &pyrna_prop_Type ) < 0 )
1137                 return NULL;
1138
1139         
1140         /* for now, return the base RNA type rather then a real module */
1141         RNA_main_pointer_create(G.main, &ptr);
1142         
1143         return pyrna_struct_CreatePyObject(&ptr);
1144 }
1145
1146 #if 0
1147 /* This is a way we can access docstrings for RNA types
1148  * without having the datatypes in blender */
1149 PyObject *BPY_rna_doc( void )
1150 {
1151         PointerRNA ptr;
1152         
1153         /* for now, return the base RNA type rather then a real module */
1154         RNA_blender_rna_pointer_create(&ptr);
1155         
1156         return pyrna_struct_CreatePyObject(&ptr);
1157 }
1158 #endif
1159
1160  PyObject *BPY_rna_types(void)
1161  {
1162         /* Now initialize new subtypes based on pyrna_struct_Type */
1163         PointerRNA ptr;
1164
1165         CollectionPropertyIterator iter;
1166         PropertyRNA *prop;
1167
1168         PyObject *mod, *dict, *type, *name;
1169  
1170         mod = PyModule_New("types");
1171         dict = PyModule_GetDict(mod);
1172         
1173         /* for now, return the base RNA type rather then a real module */
1174         RNA_blender_rna_pointer_create(&ptr);
1175         prop = RNA_struct_find_property(&ptr, "structs");
1176         
1177         RNA_property_collection_begin(&ptr, prop, &iter);
1178         for(; iter.valid; RNA_property_collection_next(&iter)) {
1179                 if(iter.ptr.data) {
1180                         type = (PyObject *)BPy_RNA_PYTYPE(iter.ptr.data);
1181                         if (type==NULL) {
1182                                 type = pyrna_struct_Subtype(&iter.ptr);
1183                         }
1184                         if (type) {
1185                                 name = PyObject_GetAttrString(type, "__name__"); /* myClass.__name__ */
1186                                 if (name) {
1187                                         PyDict_SetItem(dict, name, type);
1188                                         Py_DECREF(name);
1189                                 }
1190                                 else {
1191                                         printf("could not get type __name__\n");
1192                                 }
1193                         }
1194                         else {
1195                                 printf("could not generate type\n");
1196                         }
1197                 }
1198         }
1199         RNA_property_collection_end(&iter);
1200         
1201         return mod;
1202 }