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