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