RNA: python support for REQUIRED flag for function parameters.
[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 "float.h" /* FLT_MIN/MAX */
32
33 #include "RNA_define.h" /* for defining our own rna */
34
35 #include "MEM_guardedalloc.h"
36 #include "BKE_context.h"
37 #include "BKE_global.h" /* evil G.* */
38
39 static int pyrna_struct_compare( BPy_StructRNA * a, BPy_StructRNA * b )
40 {
41         return (a->ptr.data==b->ptr.data) ? 0 : -1;
42 }
43
44 static int pyrna_prop_compare( BPy_PropertyRNA * a, BPy_PropertyRNA * b )
45 {
46         return (a->prop==b->prop && a->ptr.data==b->ptr.data ) ? 0 : -1;
47 }
48
49 /* For some reason python3 needs these :/ */
50 static PyObject *pyrna_struct_richcmp(BPy_StructRNA * a, BPy_StructRNA * b, int op)
51 {
52         int cmp_result= -1; /* assume false */
53         if (BPy_StructRNA_Check(a) && BPy_StructRNA_Check(b)) {
54                 cmp_result= pyrna_struct_compare(a, b);
55         }
56
57         return Py_CmpToRich(op, cmp_result);
58 }
59
60 static PyObject *pyrna_prop_richcmp(BPy_PropertyRNA * a, BPy_PropertyRNA * b, int op)
61 {
62         int cmp_result= -1; /* assume false */
63         if (BPy_PropertyRNA_Check(a) && BPy_PropertyRNA_Check(b)) {
64                 cmp_result= pyrna_prop_compare(a, b);
65         }
66
67         return Py_CmpToRich(op, cmp_result);
68 }
69
70 /*----------------------repr--------------------------------------------*/
71 static PyObject *pyrna_struct_repr( BPy_StructRNA * self )
72 {
73         PropertyRNA *prop;
74         char str[512];
75
76         /* print name if available */
77         prop= RNA_struct_name_property(&self->ptr);
78         if(prop) {
79                 RNA_property_string_get(&self->ptr, prop, str);
80                 return PyUnicode_FromFormat( "[BPy_StructRNA \"%s\" -> \"%s\"]", RNA_struct_identifier(&self->ptr), str);
81         }
82
83         return PyUnicode_FromFormat( "[BPy_StructRNA \"%s\"]", RNA_struct_identifier(&self->ptr));
84 }
85
86 static PyObject *pyrna_prop_repr( BPy_PropertyRNA * self )
87 {
88         PropertyRNA *prop;
89         PointerRNA ptr;
90         char str[512];
91
92         /* if a pointer, try to print name of pointer target too */
93         if(RNA_property_type(&self->ptr, self->prop) == PROP_POINTER) {
94                 ptr= RNA_property_pointer_get(&self->ptr, self->prop);
95
96                 if(ptr.data) {
97                         prop= RNA_struct_name_property(&ptr);
98                         if(prop) {
99                                 RNA_property_string_get(&ptr, prop, str);
100                                 return PyUnicode_FromFormat( "[BPy_PropertyRNA \"%s\" -> \"%s\" -> \"%s\" ]", RNA_struct_identifier(&self->ptr), RNA_property_identifier(&self->ptr, self->prop), str);
101                         }
102                 }
103         }
104
105         return PyUnicode_FromFormat( "[BPy_PropertyRNA \"%s\" -> \"%s\"]", RNA_struct_identifier(&self->ptr), RNA_property_identifier(&self->ptr, self->prop));
106 }
107
108 static long pyrna_struct_hash( BPy_StructRNA * self )
109 {
110         return (long)self->ptr.data;
111 }
112
113 /* use our own dealloc so we can free a property if we use one */
114 static void pyrna_struct_dealloc( BPy_StructRNA * self )
115 {
116         /* Note!! for some weired reason calling PyObject_DEL() directly crashes blender! */
117         if (self->freeptr && self->ptr.data) {
118                 IDP_FreeProperty(self->ptr.data);
119                 MEM_freeN(self->ptr.data);
120                 self->ptr.data= NULL;
121         }
122
123         Py_TYPE(self)->tp_free(self);
124         return;
125 }
126
127 static char *pyrna_enum_as_string(PointerRNA *ptr, PropertyRNA *prop)
128 {
129         const EnumPropertyItem *item;
130         int totitem;
131         
132         RNA_property_enum_items(ptr, prop, &item, &totitem);
133         return (char*)BPy_enum_as_string((EnumPropertyItem*)item);
134 }
135
136 PyObject * pyrna_prop_to_py(PointerRNA *ptr, PropertyRNA *prop)
137 {
138         PyObject *ret;
139         int type = RNA_property_type(ptr, prop);
140         int len = RNA_property_array_length(ptr, prop);
141
142         if (len > 0) {
143                 /* resolve the array from a new pytype */
144                 return pyrna_prop_CreatePyObject(ptr, prop);
145         }
146         
147         /* see if we can coorce into a python type - PropertyType */
148         switch (type) {
149         case PROP_BOOLEAN:
150                 ret = PyBool_FromLong( RNA_property_boolean_get(ptr, prop) );
151                 break;
152         case PROP_INT:
153                 ret = PyLong_FromSsize_t( (Py_ssize_t)RNA_property_int_get(ptr, prop) );
154                 break;
155         case PROP_FLOAT:
156                 ret = PyFloat_FromDouble( RNA_property_float_get(ptr, prop) );
157                 break;
158         case PROP_STRING:
159         {
160                 char *buf;
161                 buf = RNA_property_string_get_alloc(ptr, prop, NULL, -1);
162                 ret = PyUnicode_FromString( buf );
163                 MEM_freeN(buf);
164                 break;
165         }
166         case PROP_ENUM:
167         {
168                 const char *identifier;
169                 int val = RNA_property_enum_get(ptr, prop);
170                 
171                 if (RNA_property_enum_identifier(ptr, prop, val, &identifier)) {
172                         ret = PyUnicode_FromString( identifier );
173                 } else {
174                         PyErr_Format(PyExc_AttributeError, "RNA Error: Current value \"%d\" matches no enum", val);
175                         ret = NULL;
176                 }
177
178                 break;
179         }
180         case PROP_POINTER:
181         {
182                 PointerRNA newptr;
183                 newptr= RNA_property_pointer_get(ptr, prop);
184                 if (newptr.data) {
185                         ret = pyrna_struct_CreatePyObject(&newptr);
186                 } else {
187                         ret = Py_None;
188                         Py_INCREF(ret);
189                 }
190                 break;
191         }
192         case PROP_COLLECTION:
193                 ret = pyrna_prop_CreatePyObject(ptr, prop);
194                 break;
195         default:
196                 PyErr_Format(PyExc_AttributeError, "RNA Error: unknown type \"%d\" (pyrna_prop_to_py)", type);
197                 ret = NULL;
198                 break;
199         }
200         
201         return ret;
202 }
203
204 static PyObject * pyrna_func_call(PyObject * self, PyObject *args, PyObject *kw);
205
206 PyObject *pyrna_func_to_py(PointerRNA *ptr, FunctionRNA *func)
207 {
208         static PyMethodDef func_meth = {"<generic rna function>", (PyCFunction)pyrna_func_call, METH_VARARGS|METH_KEYWORDS, "python rna function"};
209         PyObject *self= PyTuple_New(2);
210         PyObject *ret;
211         PyTuple_SET_ITEM(self, 0, pyrna_struct_CreatePyObject(ptr));
212         PyTuple_SET_ITEM(self, 1, PyCObject_FromVoidPtr((void *)func, NULL));
213         
214         ret= PyCFunction_New(&func_meth, self);
215         Py_DECREF(self);
216         
217         return ret;
218 }
219
220 int pyrna_py_to_prop(PointerRNA *ptr, PropertyRNA *prop, PyObject *value)
221 {
222         int type = RNA_property_type(ptr, prop);
223         int len = RNA_property_array_length(ptr, prop);
224         
225         if (len > 0) {
226                 PyObject *item;
227                 int i;
228                 
229                 if (!PySequence_Check(value)) {
230                         PyErr_SetString(PyExc_TypeError, "expected a python sequence type assigned to an RNA array.");
231                         return -1;
232                 }
233                 
234                 if ((int)PySequence_Length(value) != len) {
235                         PyErr_SetString(PyExc_AttributeError, "python sequence length did not match the RNA array.");
236                         return -1;
237                 }
238                 
239                 /* for arrays we have a limited number of types */
240                 switch (type) {
241                 case PROP_BOOLEAN:
242                 {
243                         int *param_arr = MEM_mallocN(sizeof(char) * len, "pyrna bool array");
244                         
245                         /* collect the variables before assigning, incase one of them is incorrect */
246                         for (i=0; i<len; i++) {
247                                 item = PySequence_GetItem(value, i);
248                                 param_arr[i] = PyObject_IsTrue( item );
249                                 Py_DECREF(item);
250                                 
251                                 if (param_arr[i] < 0) {
252                                         MEM_freeN(param_arr);
253                                         PyErr_SetString(PyExc_AttributeError, "one or more of the values in the sequence is not a boolean");
254                                         return -1;
255                                 }
256                         }
257                         
258                         RNA_property_boolean_set_array(ptr, prop, param_arr);
259                         
260                         MEM_freeN(param_arr);
261                         break;
262                 }
263                 case PROP_INT:
264                 {
265                         int *param_arr = MEM_mallocN(sizeof(int) * len, "pyrna int array");
266                         
267                         /* collect the variables before assigning, incase one of them is incorrect */
268                         for (i=0; i<len; i++) {
269                                 item = PySequence_GetItem(value, i);
270                                 param_arr[i] = (int)PyLong_AsSsize_t(item); /* deal with any errors later */
271                                 Py_DECREF(item);
272                         }
273                         
274                         if (PyErr_Occurred()) {
275                                 MEM_freeN(param_arr);
276                                 PyErr_SetString(PyExc_AttributeError, "one or more of the values in the sequence could not be used as an int");
277                                 return -1;
278                         }
279                         
280                         RNA_property_int_set_array(ptr, prop, param_arr);
281                         
282                         MEM_freeN(param_arr);
283                         break;
284                 }
285                 case PROP_FLOAT:
286                 {
287                         float *param_arr = MEM_mallocN(sizeof(float) * len, "pyrna float array");
288                         
289                         /* collect the variables before assigning, incase one of them is incorrect */
290                         for (i=0; i<len; i++) {
291                                 item = PySequence_GetItem(value, i);
292                                 param_arr[i] = (float)PyFloat_AsDouble(item); /* deal with any errors later */
293                                 Py_DECREF(item);
294                         }
295                         
296                         if (PyErr_Occurred()) {
297                                 MEM_freeN(param_arr);
298                                 PyErr_SetString(PyExc_AttributeError, "one or more of the values in the sequence could not be used as a float");
299                                 return -1;
300                         }
301                         
302                         RNA_property_float_set_array(ptr, prop, param_arr);
303                         
304                         MEM_freeN(param_arr);
305                         break;
306                 }
307                 }
308         } else {
309                 /* Normal Property (not an array) */
310                 
311                 /* see if we can coorce into a python type - PropertyType */
312                 switch (type) {
313                 case PROP_BOOLEAN:
314                 {
315                         int param = PyObject_IsTrue( value );
316                         
317                         if( param < 0 ) {
318                                 PyErr_SetString(PyExc_TypeError, "expected True/False or 0/1");
319                                 return -1;
320                         } else {
321                                 RNA_property_boolean_set(ptr, prop, param);
322                         }
323                         break;
324                 }
325                 case PROP_INT:
326                 {
327                         int param = PyLong_AsSsize_t(value);
328                         if (PyErr_Occurred()) {
329                                 PyErr_SetString(PyExc_TypeError, "expected an int type");
330                                 return -1;
331                         } else {
332                                 RNA_property_int_set(ptr, prop, param);
333                         }
334                         break;
335                 }
336                 case PROP_FLOAT:
337                 {
338                         float param = PyFloat_AsDouble(value);
339                         if (PyErr_Occurred()) {
340                                 PyErr_SetString(PyExc_TypeError, "expected a float type");
341                                 return -1;
342                         } else {
343                                 RNA_property_float_set(ptr, prop, param);
344                         }
345                         break;
346                 }
347                 case PROP_STRING:
348                 {
349                         char *param = _PyUnicode_AsString(value);
350                         
351                         if (param==NULL) {
352                                 PyErr_SetString(PyExc_TypeError, "expected a string type");
353                                 return -1;
354                         } else {
355                                 RNA_property_string_set(ptr, prop, param);
356                         }
357                         break;
358                 }
359                 case PROP_ENUM:
360                 {
361                         char *param = _PyUnicode_AsString(value);
362                         
363                         if (param==NULL) {
364                                 char *enum_str= pyrna_enum_as_string(ptr, prop);
365                                 PyErr_Format(PyExc_TypeError, "expected a string enum type in (%s)", enum_str);
366                                 MEM_freeN(enum_str);
367                                 return -1;
368                         } else {
369                                 int val;
370                                 if (RNA_property_enum_value(ptr, prop, param, &val)) {
371                                         RNA_property_enum_set(ptr, prop, val);
372                                 } else {
373                                         char *enum_str= pyrna_enum_as_string(ptr, prop);
374                                         PyErr_Format(PyExc_AttributeError, "enum \"%s\" not found in (%s)", param, enum_str);
375                                         MEM_freeN(enum_str);
376                                         return -1;
377                                 }
378                         }
379                         
380                         break;
381                 }
382                 case PROP_POINTER:
383                 {
384                         StructRNA *ptype= RNA_property_pointer_type(ptr, prop);
385
386                         if(!BPy_StructRNA_Check(value)) {
387                                 PointerRNA tmp;
388                                 RNA_pointer_create(NULL, ptype, NULL, &tmp);
389                                 PyErr_Format(PyExc_TypeError, "expected a %s type", RNA_struct_identifier(&tmp));
390                                 return -1;
391                         } else {
392                                 BPy_StructRNA *param= (BPy_StructRNA*)value;
393
394                                 if(RNA_struct_is_a(&param->ptr, ptype)) {
395                                         RNA_property_pointer_set(ptr, prop, param->ptr);
396                                 } else {
397                                         PointerRNA tmp;
398                                         RNA_pointer_create(NULL, ptype, NULL, &tmp);
399                                         PyErr_Format(PyExc_TypeError, "expected a %s type", RNA_struct_identifier(&tmp));
400                                         return -1;
401                                 }
402                         }
403                         break;
404                 }
405                 case PROP_COLLECTION:
406                         PyErr_SetString(PyExc_AttributeError, "cant assign to collections");
407                         return -1;
408                         break;
409                 default:
410                         PyErr_SetString(PyExc_AttributeError, "unknown property type (pyrna_py_to_prop)");
411                         return -1;
412                         break;
413                 }
414         }
415         
416         return 0;
417 }
418
419 static PyObject * pyrna_prop_to_py_index(PointerRNA *ptr, PropertyRNA *prop, int index)
420 {
421         PyObject *ret;
422         int type = RNA_property_type(ptr, prop);
423         
424         /* see if we can coorce into a python type - PropertyType */
425         switch (type) {
426         case PROP_BOOLEAN:
427                 ret = PyBool_FromLong( RNA_property_boolean_get_index(ptr, prop, index) );
428                 break;
429         case PROP_INT:
430                 ret = PyLong_FromSsize_t( (Py_ssize_t)RNA_property_int_get_index(ptr, prop, index) );
431                 break;
432         case PROP_FLOAT:
433                 ret = PyFloat_FromDouble( RNA_property_float_get_index(ptr, prop, index) );
434                 break;
435         default:
436                 PyErr_SetString(PyExc_AttributeError, "not an array type");
437                 ret = NULL;
438                 break;
439         }
440         
441         return ret;
442 }
443
444 static int pyrna_py_to_prop_index(PointerRNA *ptr, PropertyRNA *prop, int index, PyObject *value)
445 {
446         int ret = 0;
447         int type = RNA_property_type(ptr, prop);
448         
449         /* see if we can coorce into a python type - PropertyType */
450         switch (type) {
451         case PROP_BOOLEAN:
452         {
453                 int param = PyObject_IsTrue( value );
454                 
455                 if( param < 0 ) {
456                         PyErr_SetString(PyExc_TypeError, "expected True/False or 0/1");
457                         ret = -1;
458                 } else {
459                         RNA_property_boolean_set_index(ptr, prop, index, param);
460                 }
461                 break;
462         }
463         case PROP_INT:
464         {
465                 int param = PyLong_AsSsize_t(value);
466                 if (PyErr_Occurred()) {
467                         PyErr_SetString(PyExc_TypeError, "expected an int type");
468                         ret = -1;
469                 } else {
470                         RNA_property_int_set_index(ptr, prop, index, param);
471                 }
472                 break;
473         }
474         case PROP_FLOAT:
475         {
476                 float param = PyFloat_AsDouble(value);
477                 if (PyErr_Occurred()) {
478                         PyErr_SetString(PyExc_TypeError, "expected a float type");
479                         ret = -1;
480                 } else {
481                         RNA_property_float_set_index(ptr, prop, index, param);
482                 }
483                 break;
484         }
485         default:
486                 PyErr_SetString(PyExc_AttributeError, "not an array type");
487                 ret = -1;
488                 break;
489         }
490         
491         return ret;
492 }
493
494 //---------------sequence-------------------------------------------
495 static Py_ssize_t pyrna_prop_len( BPy_PropertyRNA * self )
496 {
497         Py_ssize_t len;
498         
499         if (RNA_property_type(&self->ptr, self->prop) == PROP_COLLECTION) {
500                 len = RNA_property_collection_length(&self->ptr, self->prop);
501         } else {
502                 len = RNA_property_array_length(&self->ptr, self->prop);
503                 
504                 if (len==0) { /* not an array*/
505                         PyErr_SetString(PyExc_AttributeError, "len() only available for collection RNA types");
506                         return -1;
507                 }
508         }
509         
510         return len;
511 }
512
513 static PyObject *pyrna_prop_subscript( BPy_PropertyRNA * self, PyObject *key )
514 {
515         PyObject *ret;
516         PointerRNA newptr;
517         int keynum = 0;
518         char *keyname = NULL;
519         
520         if (PyUnicode_Check(key)) {
521                 keyname = _PyUnicode_AsString(key);
522         } else if (PyLong_Check(key)) {
523                 keynum = PyLong_AsSsize_t(key);
524         } else {
525                 PyErr_SetString(PyExc_AttributeError, "invalid key, key must be a string or an int");
526                 return NULL;
527         }
528         
529         if (RNA_property_type(&self->ptr, self->prop) == PROP_COLLECTION) {
530                 int ok;
531                 if (keyname)    ok = RNA_property_collection_lookup_string(&self->ptr, self->prop, keyname, &newptr);
532                 else                    ok = RNA_property_collection_lookup_int(&self->ptr, self->prop, keynum, &newptr);
533                 
534                 if (ok) {
535                         ret = pyrna_struct_CreatePyObject(&newptr);
536                 } else {
537                         PyErr_SetString(PyExc_AttributeError, "out of range");
538                         ret = NULL;
539                 }
540                 
541         } else if (keyname) {
542                 PyErr_SetString(PyExc_AttributeError, "string keys are only supported for collections");
543                 ret = NULL;
544         } else {
545                 int len = RNA_property_array_length(&self->ptr, self->prop);
546                 
547                 if (len==0) { /* not an array*/
548                         PyErr_Format(PyExc_AttributeError, "not an array or collection %d", keynum);
549                         ret = NULL;
550                 }
551                 
552                 if (keynum >= len){
553                         PyErr_SetString(PyExc_AttributeError, "index out of range");
554                         ret = NULL;
555                 } else { /* not an array*/
556                         ret = pyrna_prop_to_py_index(&self->ptr, self->prop, keynum);
557                 }
558         }
559         
560         return ret;
561 }
562
563
564 static int pyrna_prop_assign_subscript( BPy_PropertyRNA * self, PyObject *key, PyObject *value )
565 {
566         int ret = 0;
567         int keynum = 0;
568         char *keyname = NULL;
569         
570         if (!RNA_property_editable(&self->ptr, self->prop)) {
571                 PyErr_Format( PyExc_AttributeError, "PropertyRNA - attribute \"%s\" from \"%s\" is read-only", RNA_property_identifier(&self->ptr, self->prop), RNA_struct_identifier(&self->ptr) );
572                 return -1;
573         }
574         
575         if (PyUnicode_Check(key)) {
576                 keyname = _PyUnicode_AsString(key);
577         } else if (PyLong_Check(key)) {
578                 keynum = PyLong_AsSsize_t(key);
579         } else {
580                 PyErr_SetString(PyExc_AttributeError, "PropertyRNA - invalid key, key must be a string or an int");
581                 return -1;
582         }
583         
584         if (RNA_property_type(&self->ptr, self->prop) == PROP_COLLECTION) {
585                 PyErr_SetString(PyExc_AttributeError, "PropertyRNA - assignment is not supported for collections (yet)");
586                 ret = -1;
587         } else if (keyname) {
588                 PyErr_SetString(PyExc_AttributeError, "PropertyRNA - string keys are only supported for collections");
589                 ret = -1;
590         } else {
591                 int len = RNA_property_array_length(&self->ptr, self->prop);
592                 
593                 if (len==0) { /* not an array*/
594                         PyErr_Format(PyExc_AttributeError, "PropertyRNA - not an array or collection %d", keynum);
595                         ret = -1;
596                 }
597                 
598                 if (keynum >= len){
599                         PyErr_SetString(PyExc_AttributeError, "PropertyRNA - index out of range");
600                         ret = -1;
601                 } else {
602                         ret = pyrna_py_to_prop_index(&self->ptr, self->prop, keynum, value);
603                 }
604         }
605         
606         return ret;
607 }
608
609
610
611 static PyMappingMethods pyrna_prop_as_mapping = {
612         ( lenfunc ) pyrna_prop_len,     /* mp_length */
613         ( binaryfunc ) pyrna_prop_subscript,    /* mp_subscript */
614         ( objobjargproc ) pyrna_prop_assign_subscript,  /* mp_ass_subscript */
615 };
616
617 static PyObject *pyrna_struct_dir(BPy_StructRNA * self)
618 {
619         PyObject *ret, *dict;
620         PyObject *pystring;
621         
622         /* for looping over attrs and funcs */
623         CollectionPropertyIterator iter;
624         PropertyRNA *iterprop;
625         
626         /* Include this incase this instance is a subtype of a python class
627          * In these instances we may want to return a function or variable provided by the subtype
628          * */
629
630         if (BPy_StructRNA_CheckExact(self)) {
631                 ret = PyList_New(0);
632         } else {
633                 pystring = PyUnicode_FromString("__dict__");
634                 dict = PyObject_GenericGetAttr((PyObject *)self, pystring);
635                 Py_DECREF(pystring);
636
637                 if (dict==NULL) {
638                         PyErr_Clear();
639                         ret = PyList_New(0);
640                 }
641                 else {
642                         ret = PyDict_Keys(dict);
643                         Py_DECREF(dict);
644                 }
645         }
646         
647         /* Collect RNA items*/
648         {
649                 /*
650                  * Collect RNA attributes
651                  */
652                 PropertyRNA *nameprop;
653                 char name[256], *nameptr;
654
655                 iterprop= RNA_struct_iterator_property(&self->ptr);
656                 RNA_property_collection_begin(&self->ptr, iterprop, &iter);
657
658                 for(; iter.valid; RNA_property_collection_next(&iter)) {
659                         if(iter.ptr.data && (nameprop = RNA_struct_name_property(&iter.ptr))) {
660                                 nameptr= RNA_property_string_get_alloc(&iter.ptr, nameprop, name, sizeof(name));
661                                 
662                                 pystring = PyUnicode_FromString(nameptr);
663                                 PyList_Append(ret, pystring);
664                                 Py_DECREF(pystring);
665                                 
666                                 if ((char *)&name != nameptr)
667                                         MEM_freeN(nameptr);
668                         }
669                 }
670                 RNA_property_collection_end(&iter);
671         
672         }
673         
674         
675         {
676                 /*
677                  * Collect RNA function items
678                  */
679                 PointerRNA tptr;
680
681                 RNA_pointer_create(NULL, &RNA_Struct, self->ptr.type, &tptr);
682                 iterprop= RNA_struct_find_property(&tptr, "functions");
683
684                 RNA_property_collection_begin(&tptr, iterprop, &iter);
685
686                 for(; iter.valid; RNA_property_collection_next(&iter)) {
687                         pystring = PyUnicode_FromString(RNA_function_identifier(&tptr, iter.ptr.data));
688                         PyList_Append(ret, pystring);
689                         Py_DECREF(pystring);
690                 }
691
692                 RNA_property_collection_end(&iter);
693         }
694         
695         return ret;
696 }
697
698
699 //---------------getattr--------------------------------------------
700 static PyObject *pyrna_struct_getattro( BPy_StructRNA * self, PyObject *pyname )
701 {
702         char *name = _PyUnicode_AsString(pyname);
703         PyObject *ret;
704         PropertyRNA *prop;
705         FunctionRNA *func;
706         
707         /* Include this incase this instance is a subtype of a python class
708          * In these instances we may want to return a function or variable provided by the subtype
709          * 
710          * Also needed to return methods when its not a subtype
711          * */
712         ret = PyObject_GenericGetAttr((PyObject *)self, pyname);
713         if (ret)        return ret;
714         else            PyErr_Clear();
715         /* done with subtypes */
716         
717         if ((prop = RNA_struct_find_property(&self->ptr, name))) {
718                 ret = pyrna_prop_to_py(&self->ptr, prop);
719         }
720         else if ((func = RNA_struct_find_function(&self->ptr, name))) {
721                 ret = pyrna_func_to_py(&self->ptr, func);
722         }
723         else if (self->ptr.type == &RNA_Context) {
724                 PointerRNA newptr;
725                 ListBase newlb;
726
727                 CTX_data_get(self->ptr.data, name, &newptr, &newlb);
728
729         if (newptr.data) {
730             ret = pyrna_struct_CreatePyObject(&newptr);
731                 }
732                 else if (newlb.first) {
733                         CollectionPointerLink *link;
734                         PyObject *linkptr;
735
736                         ret = PyList_New(0);
737
738                         for(link=newlb.first; link; link=link->next) {
739                                 linkptr= pyrna_struct_CreatePyObject(&link->ptr);
740                                 PyList_Append(ret, linkptr);
741                                 Py_DECREF(linkptr);
742                         }
743                 }
744         else {
745             ret = Py_None;
746             Py_INCREF(ret);
747         }
748
749                 BLI_freelistN(&newlb);
750         }
751         else {
752                 PyErr_Format( PyExc_AttributeError, "StructRNA - Attribute \"%s\" not found", name);
753                 ret = NULL;
754         }
755         
756         return ret;
757 }
758
759 //--------------- setattr-------------------------------------------
760 static int pyrna_struct_setattro( BPy_StructRNA * self, PyObject *pyname, PyObject * value )
761 {
762         char *name = _PyUnicode_AsString(pyname);
763         PropertyRNA *prop = RNA_struct_find_property(&self->ptr, name);
764         
765         if (prop==NULL) {
766                 if (!BPy_StructRNA_CheckExact(self) && PyObject_GenericSetAttr((PyObject *)self, pyname, value) >= 0) {
767                         return 0;
768                 }
769                 else {
770                         PyErr_Format( PyExc_AttributeError, "StructRNA - Attribute \"%s\" not found", name);
771                         return -1;
772                 }
773         }               
774         
775         if (!RNA_property_editable(&self->ptr, prop)) {
776                 PyErr_Format( PyExc_AttributeError, "StructRNA - Attribute \"%s\" from \"%s\" is read-only", RNA_property_identifier(&self->ptr, prop), RNA_struct_identifier(&self->ptr) );
777                 return -1;
778         }
779                 
780         /* pyrna_py_to_prop sets its own exceptions */
781         return pyrna_py_to_prop(&self->ptr, prop, value);
782 }
783
784 PyObject *pyrna_prop_keys(BPy_PropertyRNA *self)
785 {
786         PyObject *ret;
787         if (RNA_property_type(&self->ptr, self->prop) != PROP_COLLECTION) {
788                 PyErr_SetString( PyExc_TypeError, "keys() is only valid for collection types" );
789                 ret = NULL;
790         } else {
791                 PyObject *item;
792                 CollectionPropertyIterator iter;
793                 PropertyRNA *nameprop;
794                 char name[256], *nameptr;
795
796                 ret = PyList_New(0);
797                 
798                 RNA_property_collection_begin(&self->ptr, self->prop, &iter);
799                 for(; iter.valid; RNA_property_collection_next(&iter)) {
800                         if(iter.ptr.data && (nameprop = RNA_struct_name_property(&iter.ptr))) {
801                                 nameptr= RNA_property_string_get_alloc(&iter.ptr, nameprop, name, sizeof(name));                                
802                                 
803                                 /* add to python list */
804                                 item = PyUnicode_FromString( nameptr );
805                                 PyList_Append(ret, item);
806                                 Py_DECREF(item);
807                                 /* done */
808                                 
809                                 if ((char *)&name != nameptr)
810                                         MEM_freeN(nameptr);
811                         }
812                 }
813                 RNA_property_collection_end(&iter);
814         }
815         
816         return ret;
817 }
818
819 PyObject *pyrna_prop_items(BPy_PropertyRNA *self)
820 {
821         PyObject *ret;
822         if (RNA_property_type(&self->ptr, self->prop) != PROP_COLLECTION) {
823                 PyErr_SetString( PyExc_TypeError, "items() is only valid for collection types" );
824                 ret = NULL;
825         } else {
826                 PyObject *item;
827                 CollectionPropertyIterator iter;
828                 PropertyRNA *nameprop;
829                 char name[256], *nameptr;
830
831                 ret = PyList_New(0);
832                 
833                 RNA_property_collection_begin(&self->ptr, self->prop, &iter);
834                 for(; iter.valid; RNA_property_collection_next(&iter)) {
835                         if(iter.ptr.data && (nameprop = RNA_struct_name_property(&iter.ptr))) {
836                                 nameptr= RNA_property_string_get_alloc(&iter.ptr, nameprop, name, sizeof(name));
837                                 
838                                 /* add to python list */
839                                 item = Py_BuildValue("(NN)", PyUnicode_FromString( nameptr ), pyrna_struct_CreatePyObject(&iter.ptr));
840                                 PyList_Append(ret, item);
841                                 Py_DECREF(item);
842                                 /* done */
843                                 
844                                 if ((char *)&name != nameptr)
845                                         MEM_freeN(nameptr);
846                         }
847                 }
848                 RNA_property_collection_end(&iter);
849         }
850         
851         return ret;
852 }
853
854
855 PyObject *pyrna_prop_values(BPy_PropertyRNA *self)
856 {
857         PyObject *ret;
858         if (RNA_property_type(&self->ptr, self->prop) != PROP_COLLECTION) {
859                 PyErr_SetString( PyExc_TypeError, "values() is only valid for collection types" );
860                 ret = NULL;
861         } else {
862                 PyObject *item;
863                 CollectionPropertyIterator iter;
864                 PropertyRNA *nameprop;
865                 
866                 ret = PyList_New(0);
867                 
868                 RNA_property_collection_begin(&self->ptr, self->prop, &iter);
869                 for(; iter.valid; RNA_property_collection_next(&iter)) {
870                         if(iter.ptr.data && (nameprop = RNA_struct_name_property(&iter.ptr))) {
871                                 item = pyrna_struct_CreatePyObject(&iter.ptr);
872                                 PyList_Append(ret, item);
873                                 Py_DECREF(item);
874                         }
875                 }
876                 RNA_property_collection_end(&iter);
877         }
878         
879         return ret;
880 }
881
882 /* A bit of a kludge, make a list out of a collection or array,
883  * then return the lists iter function, not especially fast but convenient for now */
884 PyObject *pyrna_prop_iter(BPy_PropertyRNA *self)
885 {
886         /* Try get values from a collection */
887         PyObject *ret = pyrna_prop_values(self);
888         
889         if (ret==NULL) {
890                 /* collection did not work, try array */
891                 int len = RNA_property_array_length(&self->ptr, self->prop);
892                 
893                 if (len) {
894                         int i;
895                         PyErr_Clear();
896                         ret = PyList_New(len);
897                         
898                         for (i=0; i < len; i++) {
899                                 PyList_SET_ITEM(ret, i, pyrna_prop_to_py_index(&self->ptr, self->prop, i));
900                         }
901                 }
902         }
903         
904         if (ret) {
905                 /* we know this is a list so no need to PyIter_Check */
906                 PyObject *iter = PyObject_GetIter(ret); 
907                 Py_DECREF(ret);
908                 return iter;
909         }
910         
911         PyErr_SetString( PyExc_TypeError, "this BPy_PropertyRNA object is not iterable" );
912         return NULL;
913 }
914
915 static struct PyMethodDef pyrna_struct_methods[] = {
916         {"__dir__", (PyCFunction)pyrna_struct_dir, METH_NOARGS, ""},
917         {NULL, NULL, 0, NULL}
918 };
919
920 static struct PyMethodDef pyrna_prop_methods[] = {
921         {"keys", (PyCFunction)pyrna_prop_keys, METH_NOARGS, ""},
922         {"items", (PyCFunction)pyrna_prop_items, METH_NOARGS, ""},
923         {"values", (PyCFunction)pyrna_prop_values, METH_NOARGS, ""},
924         {NULL, NULL, 0, NULL}
925 };
926
927 /* only needed for subtyping, so a new class gets a valid BPy_StructRNA
928  * todo - also accept useful args */
929 static PyObject * pyrna_struct_new(PyTypeObject *type, PyObject *args, PyObject *kwds) {
930
931         BPy_StructRNA *base = NULL;
932         
933         if (!PyArg_ParseTuple(args, "O!:Base BPy_StructRNA", &pyrna_struct_Type, &base))
934                 return NULL;
935         
936         if (type == &pyrna_struct_Type) {
937                 return pyrna_struct_CreatePyObject(&base->ptr);
938         } else {
939                 BPy_StructRNA *ret = (BPy_StructRNA *) type->tp_alloc(type, 0);
940                 ret->ptr = base->ptr;
941                 return (PyObject *)ret;
942         }
943 }
944
945 /* only needed for subtyping, so a new class gets a valid BPy_StructRNA
946  * todo - also accept useful args */
947 static PyObject * pyrna_prop_new(PyTypeObject *type, PyObject *args, PyObject *kwds) {
948
949         BPy_PropertyRNA *base = NULL;
950         
951         if (!PyArg_ParseTuple(args, "O!:Base BPy_PropertyRNA", &pyrna_prop_Type, &base))
952                 return NULL;
953         
954         if (type == &pyrna_prop_Type) {
955                 return pyrna_prop_CreatePyObject(&base->ptr, base->prop);
956         } else {
957                 BPy_PropertyRNA *ret = (BPy_PropertyRNA *) type->tp_alloc(type, 0);
958                 ret->ptr = base->ptr;
959                 ret->prop = base->prop;
960                 return (PyObject *)ret;
961         }
962 }
963
964 int pyrna_py_to_param(PointerRNA *ptr, PropertyRNA *prop, void *data, PyObject *value)
965 {
966         /* XXX hard limits should be checked here */
967         int type = RNA_property_type(ptr, prop);
968         int len = RNA_property_array_length(ptr, prop);
969         
970         if (len > 0) {
971                 PyObject *item;
972                 int i;
973                 
974                 if (!PySequence_Check(value)) {
975                         PyErr_SetString(PyExc_TypeError, "expected a python sequence type assigned to an RNA array.");
976                         return -1;
977                 }
978                 
979                 if ((int)PySequence_Length(value) != len) {
980                         PyErr_SetString(PyExc_AttributeError, "python sequence length did not match the RNA array.");
981                         return -1;
982                 }
983                 
984                 /* for arrays we have a limited number of types */
985                 switch (type) {
986                 case PROP_BOOLEAN:
987                 {
988                         int *param_arr = (int*)data;
989                         
990                         /* collect the variables before assigning, incase one of them is incorrect */
991                         for (i=0; i<len; i++) {
992                                 item = PySequence_GetItem(value, i);
993                                 param_arr[i] = PyObject_IsTrue( item );
994                                 Py_DECREF(item);
995                                 
996                                 if (param_arr[i] < 0) {
997                                         PyErr_SetString(PyExc_AttributeError, "one or more of the values in the sequence is not a boolean");
998                                         return -1;
999                                 }
1000                         }
1001                         
1002                         break;
1003                 }
1004                 case PROP_INT:
1005                 {
1006                         int *param_arr = (int*)data;
1007                         
1008                         /* collect the variables */
1009                         for (i=0; i<len; i++) {
1010                                 item = PySequence_GetItem(value, i);
1011                                 param_arr[i] = (int)PyLong_AsSsize_t(item); /* deal with any errors later */
1012                                 Py_DECREF(item);
1013                         }
1014                         
1015                         if (PyErr_Occurred()) {
1016                                 PyErr_SetString(PyExc_AttributeError, "one or more of the values in the sequence could not be used as an int");
1017                                 return -1;
1018                         }
1019
1020                         break;
1021                 }
1022                 case PROP_FLOAT:
1023                 {
1024                         float *param_arr = (float*)data;
1025                         
1026                         /* collect the variables */
1027                         for (i=0; i<len; i++) {
1028                                 item = PySequence_GetItem(value, i);
1029                                 param_arr[i] = (float)PyFloat_AsDouble(item); /* deal with any errors later */
1030                                 Py_DECREF(item);
1031                         }
1032                         
1033                         if (PyErr_Occurred()) {
1034                                 PyErr_SetString(PyExc_AttributeError, "one or more of the values in the sequence could not be used as a float");
1035                                 return -1;
1036                         }
1037                         
1038                         break;
1039                 }
1040                 }
1041         } else {
1042                 /* Normal Property (not an array) */
1043                 
1044                 /* see if we can coorce into a python type - PropertyType */
1045                 switch (type) {
1046                 case PROP_BOOLEAN:
1047                 {
1048                         int param = PyObject_IsTrue( value );
1049                         
1050                         if( param < 0 ) {
1051                                 PyErr_SetString(PyExc_TypeError, "expected True/False or 0/1");
1052                                 return -1;
1053                         } else {
1054                                 *((int*)data)= param;
1055                         }
1056                         break;
1057                 }
1058                 case PROP_INT:
1059                 {
1060                         int param = PyLong_AsSsize_t(value);
1061                         if (PyErr_Occurred()) {
1062                                 PyErr_SetString(PyExc_TypeError, "expected an int type");
1063                                 return -1;
1064                         } else {
1065                                 *((int*)data)= param;
1066                         }
1067                         break;
1068                 }
1069                 case PROP_FLOAT:
1070                 {
1071                         float param = PyFloat_AsDouble(value);
1072                         if (PyErr_Occurred()) {
1073                                 PyErr_SetString(PyExc_TypeError, "expected a float type");
1074                                 return -1;
1075                         } else {
1076                                 *((float*)data)= param;
1077                         }
1078                         break;
1079                 }
1080                 case PROP_STRING:
1081                 {
1082                         char *param = _PyUnicode_AsString(value);
1083                         
1084                         if (param==NULL) {
1085                                 PyErr_SetString(PyExc_TypeError, "expected a string type");
1086                                 return -1;
1087                         } else {
1088                                 *((char**)data)= param;
1089                         }
1090                         break;
1091                 }
1092                 case PROP_ENUM:
1093                 {
1094                         char *param = _PyUnicode_AsString(value);
1095                         
1096                         if (param==NULL) {
1097                                 char *enum_str= pyrna_enum_as_string(ptr, prop);
1098                                 PyErr_Format(PyExc_TypeError, "expected a string enum type in (%s)", enum_str);
1099                                 MEM_freeN(enum_str);
1100                                 return -1;
1101                         } else {
1102                                 int val;
1103                                 if (RNA_property_enum_value(ptr, prop, param, &val)) {
1104                                         *((int*)data)= val;
1105                                 } else {
1106                                         char *enum_str= pyrna_enum_as_string(ptr, prop);
1107                                         PyErr_Format(PyExc_AttributeError, "enum \"%s\" not found in (%s)", param, enum_str);
1108                                         MEM_freeN(enum_str);
1109                                         return -1;
1110                                 }
1111                         }
1112                         
1113                         break;
1114                 }
1115                 case PROP_POINTER:
1116                 {
1117                         StructRNA *ptype= RNA_property_pointer_type(ptr, prop);
1118
1119                         if(!BPy_StructRNA_Check(value)) {
1120                                 PointerRNA tmp;
1121                                 RNA_pointer_create(NULL, ptype, NULL, &tmp);
1122                                 PyErr_Format(PyExc_TypeError, "expected a %s type", RNA_struct_identifier(&tmp));
1123                                 return -1;
1124                         } else {
1125                                 BPy_StructRNA *param= (BPy_StructRNA*)value;
1126
1127                                 if(ptype == &RNA_AnyType) {
1128                                         *((PointerRNA*)data)= param->ptr;
1129                                 }
1130                                 else if(RNA_struct_is_a(&param->ptr, ptype)) {
1131                                         *((void**)data)= param->ptr.data;
1132                                 } else {
1133                                         PointerRNA tmp;
1134                                         RNA_pointer_create(NULL, ptype, NULL, &tmp);
1135                                         PyErr_Format(PyExc_TypeError, "expected a %s type", RNA_struct_identifier(&tmp));
1136                                         return -1;
1137                                 }
1138                         }
1139                         break;
1140                 }
1141                 case PROP_COLLECTION:
1142                         PyErr_SetString(PyExc_AttributeError, "cant pass collections yet");
1143                         return -1;
1144                         break;
1145                 default:
1146                         PyErr_SetString(PyExc_AttributeError, "unknown property type (pyrna_py_to_param)");
1147                         return -1;
1148                         break;
1149                 }
1150         }
1151         
1152         return 0;
1153 }
1154
1155 PyObject *pyrna_param_to_py(PointerRNA *ptr, PropertyRNA *prop, void *data)
1156 {
1157         PyObject *ret;
1158         int type = RNA_property_type(ptr, prop);
1159         int len = RNA_property_array_length(ptr, prop);
1160         int a;
1161
1162         if(len > 0) {
1163                 /* resolve the array from a new pytype */
1164                 ret = PyTuple_New(len);
1165
1166                 switch (type) {
1167                 case PROP_BOOLEAN:
1168                         for(a=0; a<len; a++)
1169                                 PyTuple_SET_ITEM(ret, a, PyBool_FromLong( ((int*)data)[a] ));
1170                         break;
1171                 case PROP_INT:
1172                         for(a=0; a<len; a++)
1173                                 PyTuple_SET_ITEM(ret, a, PyLong_FromSsize_t( (Py_ssize_t)((int*)data)[a] ));
1174                         break;
1175                 case PROP_FLOAT:
1176                         for(a=0; a<len; a++)
1177                                 PyTuple_SET_ITEM(ret, a, PyFloat_FromDouble( ((float*)data)[a] ));
1178                         break;
1179                 default:
1180                         PyErr_Format(PyExc_AttributeError, "RNA Error: unknown array type \"%d\" (pyrna_param_to_py)", type);
1181                         ret = NULL;
1182                         break;
1183                 }
1184         }
1185         else {
1186                 /* see if we can coorce into a python type - PropertyType */
1187                 switch (type) {
1188                 case PROP_BOOLEAN:
1189                         ret = PyBool_FromLong( *(int*)data );
1190                         break;
1191                 case PROP_INT:
1192                         ret = PyLong_FromSsize_t( (Py_ssize_t)*(int*)data );
1193                         break;
1194                 case PROP_FLOAT:
1195                         ret = PyFloat_FromDouble( *(float*)data );
1196                         break;
1197                 case PROP_STRING:
1198                 {
1199                         ret = PyUnicode_FromString( *(char**)data );
1200                         break;
1201                 }
1202                 case PROP_ENUM:
1203                 {
1204                         const char *identifier;
1205                         int val = *(int*)data;
1206                         
1207                         if (RNA_property_enum_identifier(ptr, prop, val, &identifier)) {
1208                                 ret = PyUnicode_FromString( identifier );
1209                         } else {
1210                                 PyErr_Format(PyExc_AttributeError, "RNA Error: Current value \"%d\" matches no enum", val);
1211                                 ret = NULL;
1212                         }
1213
1214                         break;
1215                 }
1216                 case PROP_POINTER:
1217                 {
1218                         PointerRNA newptr;
1219                         StructRNA *type= RNA_property_pointer_type(ptr, prop);
1220
1221                         if(type == &RNA_AnyType) {
1222                                 /* in this case we get the full ptr */
1223                                 newptr= *(PointerRNA*)data;
1224                         }
1225                         else {
1226                                 /* XXX this is missing the ID part! */
1227                                 RNA_pointer_create(NULL, type, *(void**)data, &newptr);
1228                         }
1229
1230                         if (newptr.data) {
1231                                 ret = pyrna_struct_CreatePyObject(&newptr);
1232                         } else {
1233                                 ret = Py_None;
1234                                 Py_INCREF(ret);
1235                         }
1236                         break;
1237                 }
1238                 case PROP_COLLECTION:
1239                         /* XXX not supported yet
1240                          * ret = pyrna_prop_CreatePyObject(ptr, prop); */
1241                         break;
1242                 default:
1243                         PyErr_Format(PyExc_AttributeError, "RNA Error: unknown type \"%d\" (pyrna_param_to_py)", type);
1244                         ret = NULL;
1245                         break;
1246                 }
1247         }
1248
1249         return ret;
1250 }
1251
1252 static PyObject * pyrna_func_call(PyObject * self, PyObject *args, PyObject *kw)
1253 {
1254         PointerRNA *self_ptr= &(((BPy_StructRNA *)PyTuple_GET_ITEM(self, 0))->ptr);
1255         FunctionRNA *self_func=  PyCObject_AsVoidPtr(PyTuple_GET_ITEM(self, 1));
1256
1257         PointerRNA funcptr;
1258         ParameterList *parms;
1259         ParameterIterator iter;
1260         PropertyRNA *pret, *parm;
1261         PyObject *ret, *item;
1262         int i, tlen, flag, err= 0;
1263         const char *tid, *fid, *pid;
1264         void *retdata= NULL;
1265
1266         /* setup */
1267         RNA_pointer_create(NULL, &RNA_Function, self_func, &funcptr);
1268
1269         pret= RNA_function_return(self_ptr, self_func);
1270         tlen= PyTuple_GET_SIZE(args);
1271
1272         parms= RNA_parameter_list_create(self_ptr, self_func);
1273         RNA_parameter_list_begin(parms, &iter);
1274
1275         /* parse function parameters */
1276         for (i= 0; iter.valid; RNA_parameter_list_next(&iter)) {
1277                 parm= iter.parm;
1278
1279                 if (parm==pret) {
1280                         retdata= iter.data;
1281                         continue;
1282                 }
1283
1284                 pid= RNA_property_identifier(&funcptr, parm);
1285                 flag= RNA_property_flag(&funcptr, parm);
1286                 item= NULL;
1287
1288                 if ((i < tlen) && (flag & PROP_REQUIRED)) {
1289                         item= PyTuple_GET_ITEM(args, i);
1290                         i++;
1291                 }
1292                 else if (kw != NULL)
1293                         item= PyDict_GetItemString(kw, pid);
1294
1295                 if (item==NULL) {
1296                         if(flag & PROP_REQUIRED) {
1297                                 tid= RNA_struct_identifier(self_ptr);
1298                                 fid= RNA_function_identifier(self_ptr, self_func);
1299
1300                                 PyErr_Format(PyExc_AttributeError, "%s.%s(): required parameter \"%s\" not specified", tid, fid, pid);
1301                                 err= -1;
1302                                 break;
1303                         }
1304                         else
1305                                 continue;
1306                 }
1307
1308                 err= pyrna_py_to_param(&funcptr, parm, iter.data, item);
1309
1310                 if(err!=0)
1311                         break;
1312         }
1313
1314         ret= NULL;
1315         if (err==0) {
1316                 /* call function */
1317                 RNA_function_call(self_ptr, self_func, parms);
1318
1319                 /* return value */
1320                 if(pret)
1321                         ret= pyrna_param_to_py(&funcptr, pret, retdata);
1322         }
1323
1324         /* cleanup */
1325         RNA_parameter_list_end(&iter);
1326         RNA_parameter_list_free(parms);
1327
1328         if (ret)
1329                 return ret;
1330
1331         if (err==-1)
1332                 return NULL;
1333
1334         Py_RETURN_NONE;
1335 }
1336
1337 /*-----------------------BPy_StructRNA method def------------------------------*/
1338 PyTypeObject pyrna_struct_Type = {
1339 #if (PY_VERSION_HEX >= 0x02060000)
1340         PyVarObject_HEAD_INIT(NULL, 0)
1341 #else
1342         /* python 2.5 and below */
1343         PyObject_HEAD_INIT( NULL )  /* required py macro */
1344         0,                          /* ob_size */
1345 #endif
1346         "StructRNA",                    /* tp_name */
1347         sizeof( BPy_StructRNA ),        /* tp_basicsize */
1348         0,                      /* tp_itemsize */
1349         /* methods */
1350         ( destructor ) pyrna_struct_dealloc,/* tp_dealloc */
1351         NULL,                       /* printfunc tp_print; */
1352         NULL,                                           /* getattrfunc tp_getattr; */
1353         NULL,                                           /* setattrfunc tp_setattr; */
1354         NULL,                                           /* tp_compare */ /* DEPRECATED in python 3.0! */
1355         ( reprfunc ) pyrna_struct_repr, /* tp_repr */
1356
1357         /* Method suites for standard classes */
1358
1359         NULL,                       /* PyNumberMethods *tp_as_number; */
1360         NULL,                                           /* PySequenceMethods *tp_as_sequence; */
1361         NULL,                                           /* PyMappingMethods *tp_as_mapping; */
1362
1363         /* More standard operations (here for binary compatibility) */
1364
1365         ( hashfunc )pyrna_struct_hash,  /* hashfunc tp_hash; */
1366         NULL,                                           /* ternaryfunc tp_call; */
1367         NULL,                       /* reprfunc tp_str; */
1368         ( getattrofunc ) pyrna_struct_getattro, /* getattrofunc tp_getattro; */
1369         ( setattrofunc ) pyrna_struct_setattro, /* setattrofunc tp_setattro; */
1370
1371         /* Functions to access object as input/output buffer */
1372         NULL,                       /* PyBufferProcs *tp_as_buffer; */
1373
1374   /*** Flags to define presence of optional/expanded features ***/
1375         Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE,         /* long tp_flags; */
1376
1377         NULL,                                           /*  char *tp_doc;  Documentation string */
1378   /*** Assigned meaning in release 2.0 ***/
1379         /* call function for all accessible objects */
1380         NULL,                       /* traverseproc tp_traverse; */
1381
1382         /* delete references to contained objects */
1383         NULL,                       /* inquiry tp_clear; */
1384
1385   /***  Assigned meaning in release 2.1 ***/
1386   /*** rich comparisons ***/
1387         (richcmpfunc)pyrna_struct_richcmp,      /* richcmpfunc tp_richcompare; */
1388
1389   /***  weak reference enabler ***/
1390         0,                          /* long tp_weaklistoffset; */
1391
1392   /*** Added in release 2.2 ***/
1393         /*   Iterators */
1394         NULL,                       /* getiterfunc tp_iter; */
1395         NULL,                       /* iternextfunc tp_iternext; */
1396
1397   /*** Attribute descriptor and subclassing stuff ***/
1398         pyrna_struct_methods,                   /* struct PyMethodDef *tp_methods; */
1399         NULL,                       /* struct PyMemberDef *tp_members; */
1400         NULL,                                           /* struct PyGetSetDef *tp_getset; */
1401         NULL,                       /* struct _typeobject *tp_base; */
1402         NULL,                       /* PyObject *tp_dict; */
1403         NULL,                       /* descrgetfunc tp_descr_get; */
1404         NULL,                       /* descrsetfunc tp_descr_set; */
1405         0,                          /* long tp_dictoffset; */
1406         NULL,                       /* initproc tp_init; */
1407         NULL,                       /* allocfunc tp_alloc; */
1408         pyrna_struct_new,                       /* newfunc tp_new; */
1409         /*  Low-level free-memory routine */
1410         NULL,                       /* freefunc tp_free;  */
1411         /* For PyObject_IS_GC */
1412         NULL,                       /* inquiry tp_is_gc;  */
1413         NULL,                       /* PyObject *tp_bases; */
1414         /* method resolution order */
1415         NULL,                       /* PyObject *tp_mro;  */
1416         NULL,                       /* PyObject *tp_cache; */
1417         NULL,                       /* PyObject *tp_subclasses; */
1418         NULL,                       /* PyObject *tp_weaklist; */
1419         NULL
1420 };
1421
1422 /*-----------------------BPy_PropertyRNA method def------------------------------*/
1423 PyTypeObject pyrna_prop_Type = {
1424 #if (PY_VERSION_HEX >= 0x02060000)
1425         PyVarObject_HEAD_INIT(NULL, 0)
1426 #else
1427         /* python 2.5 and below */
1428         PyObject_HEAD_INIT( NULL )  /* required py macro */
1429         0,                          /* ob_size */
1430 #endif
1431         
1432         "PropertyRNA",          /* tp_name */
1433         sizeof( BPy_PropertyRNA ),                      /* tp_basicsize */
1434         0,                      /* tp_itemsize */
1435         /* methods */
1436         NULL,                                           /* tp_dealloc */
1437         NULL,                       /* printfunc tp_print; */
1438         NULL,                                           /* getattrfunc tp_getattr; */
1439         NULL,                       /* setattrfunc tp_setattr; */
1440         NULL,                                           /* tp_compare */ /* DEPRECATED in python 3.0! */
1441         ( reprfunc ) pyrna_prop_repr,   /* tp_repr */
1442
1443         /* Method suites for standard classes */
1444
1445         NULL,                       /* PyNumberMethods *tp_as_number; */
1446         NULL,                                           /* PySequenceMethods *tp_as_sequence; */
1447         &pyrna_prop_as_mapping,         /* PyMappingMethods *tp_as_mapping; */
1448
1449         /* More standard operations (here for binary compatibility) */
1450
1451         NULL,                                           /* hashfunc tp_hash; */
1452         NULL,                       /* ternaryfunc tp_call; */
1453         NULL,                       /* reprfunc tp_str; */
1454         NULL, /*PyObject_GenericGetAttr - MINGW Complains, assign later */      /* getattrofunc tp_getattro; */ /* will only use these if this is a subtype of a py class */
1455         NULL, /*PyObject_GenericSetAttr - MINGW Complains, assign later */      /* setattrofunc tp_setattro; */
1456
1457         /* Functions to access object as input/output buffer */
1458         NULL,                       /* PyBufferProcs *tp_as_buffer; */
1459
1460   /*** Flags to define presence of optional/expanded features ***/
1461         Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE,         /* long tp_flags; */
1462
1463         NULL,                                           /*  char *tp_doc;  Documentation string */
1464   /*** Assigned meaning in release 2.0 ***/
1465         /* call function for all accessible objects */
1466         NULL,                       /* traverseproc tp_traverse; */
1467
1468         /* delete references to contained objects */
1469         NULL,                       /* inquiry tp_clear; */
1470
1471   /***  Assigned meaning in release 2.1 ***/
1472   /*** rich comparisons ***/
1473         (richcmpfunc)pyrna_prop_richcmp,        /* richcmpfunc tp_richcompare; */
1474
1475   /***  weak reference enabler ***/
1476         0,                          /* long tp_weaklistoffset; */
1477
1478   /*** Added in release 2.2 ***/
1479         /*   Iterators */
1480         (getiterfunc)pyrna_prop_iter,   /* getiterfunc tp_iter; */
1481         NULL,                       /* iternextfunc tp_iternext; */
1482
1483   /*** Attribute descriptor and subclassing stuff ***/
1484         pyrna_prop_methods,                     /* struct PyMethodDef *tp_methods; */
1485         NULL,                       /* struct PyMemberDef *tp_members; */
1486         NULL,                                           /* struct PyGetSetDef *tp_getset; */
1487         NULL,                       /* struct _typeobject *tp_base; */
1488         NULL,                       /* PyObject *tp_dict; */
1489         NULL,                       /* descrgetfunc tp_descr_get; */
1490         NULL,                       /* descrsetfunc tp_descr_set; */
1491         0,                          /* long tp_dictoffset; */
1492         NULL,                       /* initproc tp_init; */
1493         NULL,                       /* allocfunc tp_alloc; */
1494         pyrna_prop_new,                         /* newfunc tp_new; */
1495         /*  Low-level free-memory routine */
1496         NULL,                       /* freefunc tp_free;  */
1497         /* For PyObject_IS_GC */
1498         NULL,                       /* inquiry tp_is_gc;  */
1499         NULL,                       /* PyObject *tp_bases; */
1500         /* method resolution order */
1501         NULL,                       /* PyObject *tp_mro;  */
1502         NULL,                       /* PyObject *tp_cache; */
1503         NULL,                       /* PyObject *tp_subclasses; */
1504         NULL,                       /* PyObject *tp_weaklist; */
1505         NULL
1506 };
1507
1508
1509 PyObject* pyrna_struct_Subtype(PointerRNA *ptr)
1510 {
1511         PyObject *newclass = NULL;
1512         PropertyRNA *nameprop;
1513
1514         if (ptr->type==NULL) {
1515                 newclass= NULL; /* Nothing to do */
1516         } else if ((newclass= RNA_struct_py_type_get(ptr->data))) {
1517                 Py_INCREF(newclass);
1518         } else if ((nameprop = RNA_struct_name_property(ptr))) {
1519                 /* for now, return the base RNA type rather then a real module */
1520                 
1521                 /* Assume RNA_struct_py_type_get(ptr->data) was alredy checked */
1522                 
1523                 /* subclass equivelents
1524                 - class myClass(myBase):
1525                         some='value' # or ...
1526                 - myClass = type(name='myClass', bases=(myBase,), dict={'some':'value'})
1527                 */
1528                 char name[256], *nameptr;
1529
1530                 PyObject *args = PyTuple_New(3);
1531                 PyObject *bases = PyTuple_New(1);
1532                 PyObject *dict = PyDict_New();
1533                 
1534                 nameptr= RNA_property_string_get_alloc(ptr, nameprop, name, sizeof(name));
1535                 
1536                 // arg 1
1537                 //PyTuple_SET_ITEM(args, 0, PyUnicode_FromString(tp_name));
1538                 PyTuple_SET_ITEM(args, 0, PyUnicode_FromString(nameptr));
1539                 
1540                 // arg 2
1541                 PyTuple_SET_ITEM(bases, 0, (PyObject *)&pyrna_struct_Type);
1542                 Py_INCREF(&pyrna_struct_Type);
1543
1544                 PyTuple_SET_ITEM(args, 1, bases);
1545                 
1546                 // arg 3 - add an instance of the rna 
1547                 PyTuple_SET_ITEM(args, 2, dict); // fill with useful subclass things!
1548                 
1549                 if (PyErr_Occurred()) {
1550                         PyErr_Print();
1551                         PyErr_Clear();
1552                 }
1553                 
1554                 newclass = PyObject_CallObject((PyObject *)&PyType_Type, args);
1555                 // Set this later
1556                 
1557
1558                 if (newclass) {
1559                         PyObject *rna;
1560                         RNA_struct_py_type_set(ptr->data, (void *)newclass); /* Store for later use */
1561
1562                         /* Not 100% needed but useful,
1563                          * having an instance within a type looks wrong however this instance IS an rna type */
1564                         rna = pyrna_struct_CreatePyObject(ptr);
1565                         PyDict_SetItemString(((PyTypeObject *)newclass)->tp_dict, "__rna__", rna);
1566                         Py_DECREF(rna);
1567                         /* done with rna instance */
1568                 }
1569                 
1570                 Py_DECREF(args);
1571                 
1572                 if (name != nameptr)
1573                         MEM_freeN(nameptr);
1574         }
1575         
1576         return newclass;
1577 }
1578
1579 /*-----------------------CreatePyObject---------------------------------*/
1580 PyObject *pyrna_struct_CreatePyObject( PointerRNA *ptr )
1581 {
1582         BPy_StructRNA *pyrna= NULL;
1583         
1584         if (ptr->data==NULL && ptr->type==NULL) { /* Operator RNA has NULL data */
1585                 Py_RETURN_NONE;
1586         }
1587         
1588         if (ptr->type == &RNA_Struct) { /* always return a python subtype from rna struct types */
1589                 PyTypeObject *tp = (PyTypeObject *)pyrna_struct_Subtype(ptr);
1590                 
1591                 if (tp) {
1592                         pyrna = (BPy_StructRNA *) tp->tp_alloc(tp, 0);
1593                 }
1594                 else {
1595                         fprintf(stderr, "Could not make type\n");
1596                         pyrna = ( BPy_StructRNA * ) PyObject_NEW( BPy_StructRNA, &pyrna_struct_Type );
1597                 }
1598         }
1599         else {
1600                 pyrna = ( BPy_StructRNA * ) PyObject_NEW( BPy_StructRNA, &pyrna_struct_Type );
1601         }
1602         
1603         if( !pyrna ) {
1604                 PyErr_SetString( PyExc_MemoryError, "couldn't create BPy_StructRNA object" );
1605                 return NULL;
1606         }
1607         
1608         pyrna->ptr= *ptr;
1609         pyrna->freeptr= 0;
1610         return ( PyObject * ) pyrna;
1611 }
1612
1613 PyObject *pyrna_prop_CreatePyObject( PointerRNA *ptr, PropertyRNA *prop )
1614 {
1615         BPy_PropertyRNA *pyrna;
1616
1617         pyrna = ( BPy_PropertyRNA * ) PyObject_NEW( BPy_PropertyRNA, &pyrna_prop_Type );
1618
1619         if( !pyrna ) {
1620                 PyErr_SetString( PyExc_MemoryError, "couldn't create BPy_rna object" );
1621                 return NULL;
1622         }
1623         
1624         pyrna->ptr = *ptr;
1625         pyrna->prop = prop;
1626                 
1627         return ( PyObject * ) pyrna;
1628 }
1629
1630 PyObject *BPY_rna_module( void )
1631 {
1632         PointerRNA ptr;
1633         
1634         /* This can't be set in the pytype struct because some compilers complain */
1635         pyrna_prop_Type.tp_getattro = PyObject_GenericGetAttr; 
1636         pyrna_prop_Type.tp_setattro = PyObject_GenericSetAttr; 
1637         
1638         if( PyType_Ready( &pyrna_struct_Type ) < 0 )
1639                 return NULL;
1640         
1641         if( PyType_Ready( &pyrna_prop_Type ) < 0 )
1642                 return NULL;
1643
1644         /* for now, return the base RNA type rather then a real module */
1645         RNA_main_pointer_create(G.main, &ptr);
1646         
1647         return pyrna_struct_CreatePyObject(&ptr);
1648 }
1649
1650 #if 0
1651 /* This is a way we can access docstrings for RNA types
1652  * without having the datatypes in blender */
1653 PyObject *BPY_rna_doc( void )
1654 {
1655         PointerRNA ptr;
1656         
1657         /* for now, return the base RNA type rather then a real module */
1658         RNA_blender_rna_pointer_create(&ptr);
1659         
1660         return pyrna_struct_CreatePyObject(&ptr);
1661 }
1662 #endif
1663
1664
1665 /* pyrna_basetype_* - BPy_BaseTypeRNA is just a BPy_PropertyRNA struct with a differnt type
1666  * the self->ptr and self->prop are always set to the "structs" collection */
1667 //---------------getattr--------------------------------------------
1668 static PyObject *pyrna_basetype_getattro( BPy_BaseTypeRNA * self, PyObject *pyname )
1669 {
1670         PointerRNA newptr;
1671         PyObject *ret;
1672         
1673         ret = PyObject_GenericGetAttr((PyObject *)self, pyname);
1674         if (ret)        return ret;
1675         else            PyErr_Clear();
1676         
1677         if (RNA_property_collection_lookup_string(&self->ptr, self->prop, _PyUnicode_AsString(pyname), &newptr)) {
1678                 return pyrna_struct_Subtype(&newptr);
1679         }
1680         else { /* Override the error */
1681                 PyErr_Format(PyExc_AttributeError, "bpy.types.%s not a valid RNA_Struct", _PyUnicode_AsString(pyname));
1682                 return NULL;
1683         }
1684 }
1685
1686 static PyObject *pyrna_basetype_dir(BPy_BaseTypeRNA *self);
1687 static struct PyMethodDef pyrna_basetype_methods[] = {
1688         {"__dir__", (PyCFunction)pyrna_basetype_dir, METH_NOARGS, ""},
1689         {NULL, NULL, 0, NULL}
1690 };
1691
1692 static PyObject *pyrna_basetype_dir(BPy_BaseTypeRNA *self)
1693 {
1694         PyObject *list, *name;
1695         PyMethodDef *meth;
1696         
1697         list= pyrna_prop_keys(self); /* like calling structs.keys(), avoids looping here */
1698
1699         for(meth=pyrna_basetype_methods; meth->ml_name; meth++) {
1700                 name = PyUnicode_FromString(meth->ml_name);
1701                 PyList_Append(list, name);
1702                 Py_DECREF(name);
1703         }
1704         
1705         return list;
1706 }
1707
1708 PyTypeObject pyrna_basetype_Type;
1709
1710 PyObject *BPY_rna_types(void)
1711 {
1712         BPy_BaseTypeRNA *self;
1713
1714         memset(&pyrna_basetype_Type, 0, sizeof(pyrna_basetype_Type));
1715         pyrna_basetype_Type.tp_name = "RNA_Types";
1716         pyrna_basetype_Type.tp_basicsize = sizeof( BPy_BaseTypeRNA );
1717         pyrna_basetype_Type.tp_getattro = ( getattrofunc )pyrna_basetype_getattro;
1718         pyrna_basetype_Type.tp_flags = Py_TPFLAGS_DEFAULT;
1719         pyrna_basetype_Type.tp_methods = pyrna_basetype_methods;
1720         
1721         if( PyType_Ready( &pyrna_basetype_Type ) < 0 )
1722                 return NULL;
1723         
1724         self= (BPy_BaseTypeRNA *)PyObject_NEW( BPy_BaseTypeRNA, &pyrna_basetype_Type );
1725         
1726         /* avoid doing this lookup for every getattr */
1727         RNA_blender_rna_pointer_create(&self->ptr);
1728         self->prop = RNA_struct_find_property(&self->ptr, "structs");
1729         
1730         return (PyObject *)self;
1731 }
1732
1733
1734
1735 /* Orphan functions, not sure where they should go */
1736
1737 /* Function that sets RNA, NOTE - self is NULL when called from python, but being abused from C so we can pass the srna allong
1738  * This isnt incorrect since its a python object - but be careful */
1739 PyObject *BPy_FloatProperty(PyObject *self, PyObject *args, PyObject *kw)
1740 {
1741         static char *kwlist[] = {"attr", "name", "description", "min", "max", "soft_min", "soft_max", "default", NULL};
1742         char *id, *name="", *description="";
1743         float min=FLT_MIN, max=FLT_MAX, soft_min=FLT_MIN, soft_max=FLT_MAX, def=0.0f;
1744         
1745         if (!PyArg_ParseTupleAndKeywords(args, kw, "s|ssfffff:FloatProperty", kwlist, &id, &name, &description, &min, &max, &soft_min, &soft_max, &def))
1746                 return NULL;
1747         
1748         if (PyTuple_Size(args) > 0) {
1749                 PyErr_SetString(PyExc_ValueError, "all args must be keywors"); // TODO - py3 can enforce this.
1750                 return NULL;
1751         }
1752         
1753         if (self) {
1754                 StructRNA *srna = PyCObject_AsVoidPtr(self);
1755                 RNA_def_float(srna, id, def, min, max, name, description, soft_min, soft_max);
1756                 Py_RETURN_NONE;
1757         } else {
1758                 PyObject *ret = PyTuple_New(2);
1759                 PyTuple_SET_ITEM(ret, 0, PyCObject_FromVoidPtr((void *)BPy_FloatProperty, NULL));
1760                 PyTuple_SET_ITEM(ret, 1, kw);
1761                 Py_INCREF(kw);
1762                 return ret;
1763         }
1764 }
1765
1766 PyObject *BPy_IntProperty(PyObject *self, PyObject *args, PyObject *kw)
1767 {
1768         static char *kwlist[] = {"attr", "name", "description", "min", "max", "soft_min", "soft_max", "default", NULL};
1769         char *id, *name="", *description="";
1770         int min=INT_MIN, max=INT_MAX, soft_min=INT_MIN, soft_max=INT_MAX, def=0;
1771         
1772         if (!PyArg_ParseTupleAndKeywords(args, kw, "s|ssiiiii:IntProperty", kwlist, &id, &name, &description, &min, &max, &soft_min, &soft_max, &def))
1773                 return NULL;
1774         
1775         if (PyTuple_Size(args) > 0) {
1776                 PyErr_SetString(PyExc_ValueError, "all args must be keywors"); // TODO - py3 can enforce this.
1777                 return NULL;
1778         }
1779         
1780         if (self) {
1781                 StructRNA *srna = PyCObject_AsVoidPtr(self);
1782                 RNA_def_int(srna, id, def, min, max, name, description, soft_min, soft_max);
1783                 Py_RETURN_NONE;
1784         } else {
1785                 PyObject *ret = PyTuple_New(2);
1786                 PyTuple_SET_ITEM(ret, 0, PyCObject_FromVoidPtr((void *)BPy_IntProperty, NULL));
1787                 PyTuple_SET_ITEM(ret, 1, kw);
1788                 Py_INCREF(kw);
1789                 return ret;
1790         }
1791 }
1792
1793 PyObject *BPy_BoolProperty(PyObject *self, PyObject *args, PyObject *kw)
1794 {
1795         static char *kwlist[] = {"attr", "name", "description", "default", NULL};
1796         char *id, *name="", *description="";
1797         int def=0;
1798         
1799         if (!PyArg_ParseTupleAndKeywords(args, kw, "s|ssi:IntProperty", kwlist, &id, &name, &description, &def))
1800                 return NULL;
1801         
1802         if (PyTuple_Size(args) > 0) {
1803                 PyErr_SetString(PyExc_ValueError, "all args must be keywors"); // TODO - py3 can enforce this.
1804                 return NULL;
1805         }
1806         
1807         if (self) {
1808                 StructRNA *srna = PyCObject_AsVoidPtr(self);
1809                 RNA_def_boolean(srna, id, def, name, description);
1810                 Py_RETURN_NONE;
1811         } else {
1812                 PyObject *ret = PyTuple_New(2);
1813                 PyTuple_SET_ITEM(ret, 0, PyCObject_FromVoidPtr((void *)BPy_IntProperty, NULL));
1814                 PyTuple_SET_ITEM(ret, 1, kw);
1815                 Py_INCREF(kw);
1816                 return ret;
1817         }
1818 }