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