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