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