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