converted more mixed tab/space indentations to tabs. only whitespace changes.
[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., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
19  *
20  * Contributor(s): Campbell Barton
21  *
22  * ***** END GPL LICENSE BLOCK *****
23  */
24
25 /** \file blender/python/intern/bpy_rna.c
26  *  \ingroup pythonintern
27  */
28
29
30 #include <Python.h>
31
32 #include <stddef.h>
33 #include <float.h> /* FLT_MIN/MAX */
34
35 #include "RNA_types.h"
36
37 #include "bpy_rna.h"
38 #include "bpy_rna_anim.h"
39 #include "bpy_props.h"
40 #include "bpy_util.h"
41 #include "bpy_rna_callback.h"
42
43 #ifdef USE_PYRNA_INVALIDATE_WEAKREF
44 #include "MEM_guardedalloc.h"
45 #endif
46
47 #include "BLI_dynstr.h"
48 #include "BLI_string.h"
49 #include "BLI_listbase.h"
50 #include "BLI_math_rotation.h"
51 #include "BLI_utildefines.h"
52
53 #ifdef USE_PYRNA_INVALIDATE_WEAKREF
54 #include "BLI_ghash.h"
55 #endif
56
57 #include "RNA_enum_types.h"
58 #include "RNA_define.h" /* RNA_def_property_free_identifier */
59 #include "RNA_access.h"
60
61 #include "MEM_guardedalloc.h"
62
63 #include "BKE_idcode.h"
64 #include "BKE_context.h"
65 #include "BKE_global.h" /* evil G.* */
66 #include "BKE_report.h"
67 #include "BKE_idprop.h"
68
69 #include "BKE_animsys.h"
70 #include "BKE_fcurve.h"
71
72 #include "../generic/IDProp.h" /* for IDprop lookups */
73 #include "../generic/py_capi_utils.h"
74
75 #define USE_PEDANTIC_WRITE
76 #define USE_MATHUTILS
77 #define USE_STRING_COERCE
78
79 static PyObject* pyrna_struct_Subtype(PointerRNA *ptr);
80 static PyObject *pyrna_prop_collection_values(BPy_PropertyRNA *self);
81
82 int pyrna_struct_validity_check(BPy_StructRNA *pysrna)
83 {
84         if(pysrna->ptr.type)
85                 return 0;
86         PyErr_Format(PyExc_ReferenceError, "StructRNA of type %.200s has been removed", Py_TYPE(pysrna)->tp_name);
87         return -1;
88 }
89
90 int pyrna_prop_validity_check(BPy_PropertyRNA *self)
91 {
92         if(self->ptr.type)
93                 return 0;
94         PyErr_Format(PyExc_ReferenceError, "PropertyRNA of type %.200s.%.200s has been removed", Py_TYPE(self)->tp_name, RNA_property_identifier(self->prop));
95         return -1;
96 }
97
98 #if defined(USE_PYRNA_INVALIDATE_GC) || defined(USE_PYRNA_INVALIDATE_WEAKREF)
99 static void pyrna_invalidate(BPy_DummyPointerRNA *self)
100 {
101         self->ptr.type= NULL; /* this is checked for validity */
102         self->ptr.id.data= NULL; /* should not be needed but prevent bad pointer access, just incase */
103 }
104 #endif
105
106 #ifdef USE_PYRNA_INVALIDATE_GC
107 #define FROM_GC(g) ((PyObject *)(((PyGC_Head *)g)+1))
108
109 /* only for sizeof() */
110 struct gc_generation {
111         PyGC_Head head;
112         int threshold;
113         int count;
114 } gc_generation;
115
116 static void id_release_gc(struct ID *id)
117 {
118         unsigned int j;
119         // unsigned int i= 0;
120         for(j=0; j<3; j++) {
121                 /* hack below to get the 2 other lists from _PyGC_generation0 that are normally not exposed */
122                 PyGC_Head *gen= (PyGC_Head *)(((char *)_PyGC_generation0) + (sizeof(gc_generation) * j));
123                 PyGC_Head *g= gen->gc.gc_next;
124                 while ((g= g->gc.gc_next) != gen) {
125                         PyObject *ob= FROM_GC(g);
126                         if(PyType_IsSubtype(Py_TYPE(ob), &pyrna_struct_Type) || PyType_IsSubtype(Py_TYPE(ob), &pyrna_prop_Type)) {
127                                 BPy_DummyPointerRNA *ob_ptr= (BPy_DummyPointerRNA *)ob;
128                                 if(ob_ptr->ptr.id.data == id) {
129                                         pyrna_invalidate(ob_ptr);
130                                         // printf("freeing: %p %s, %.200s\n", (void *)ob, id->name, Py_TYPE(ob)->tp_name);
131                                         // i++;
132                                 }
133                         }
134                 }
135         }
136         // printf("id_release_gc freed '%s': %d\n", id->name, i);
137 }
138 #endif
139
140 #ifdef USE_PYRNA_INVALIDATE_WEAKREF
141 //#define DEBUG_RNA_WEAKREF
142
143 struct GHash *id_weakref_pool= NULL;
144 static PyObject *id_free_weakref_cb(PyObject *weakinfo_pair, PyObject *weakref);
145 static PyMethodDef id_free_weakref_cb_def= {"id_free_weakref_cb", (PyCFunction)id_free_weakref_cb, METH_O, NULL};
146
147 /* adds a reference to the list, remember to decref */
148 static GHash *id_weakref_pool_get(ID *id)
149 {
150         GHash *weakinfo_hash= NULL;
151
152         if(id_weakref_pool) {
153                 weakinfo_hash= BLI_ghash_lookup(id_weakref_pool, (void *)id);
154         }
155         else {
156                 /* first time, allocate pool */
157                 id_weakref_pool= BLI_ghash_new(BLI_ghashutil_ptrhash, BLI_ghashutil_ptrcmp, "rna_global_pool");
158                 weakinfo_hash= NULL;
159         }
160
161         if(weakinfo_hash==NULL) {
162                 /* we're using a ghash as a set, could use libHX's HXMAP_SINGULAR but would be an extra dep. */
163                 weakinfo_hash= BLI_ghash_new(BLI_ghashutil_ptrhash, BLI_ghashutil_ptrcmp, "rna_id");
164                 BLI_ghash_insert(id_weakref_pool, (void *)id, weakinfo_hash);
165         }
166
167         return weakinfo_hash;
168 }
169
170 /* called from pyrna_struct_CreatePyObject() and pyrna_prop_CreatePyObject() */
171 void id_weakref_pool_add(ID *id, BPy_DummyPointerRNA *pyrna)
172 {
173         PyObject *weakref;
174         PyObject *weakref_capsule;
175         PyObject *weakref_cb_py;
176
177         /* create a new function instance and insert the list as 'self' so we can remove ourself from it */
178         GHash *weakinfo_hash= id_weakref_pool_get(id); /* new or existing */
179
180         weakref_capsule= PyCapsule_New(weakinfo_hash, NULL, NULL);
181         weakref_cb_py= PyCFunction_New(&id_free_weakref_cb_def, weakref_capsule);
182         Py_DECREF(weakref_capsule);
183
184         /* add weakref to weakinfo_hash list */
185         weakref= PyWeakref_NewRef((PyObject *)pyrna, weakref_cb_py);
186
187         Py_DECREF(weakref_cb_py); /* function owned by the weakref now */
188
189         /* important to add at the end, since first removal looks at the end */
190         BLI_ghash_insert(weakinfo_hash, (void *)weakref, id); /* using a hash table as a set, all 'id's are the same */
191         /* weakinfo_hash owns the weakref */
192
193 }
194
195 /* workaround to get the last id without a lookup */
196 static ID *_id_tmp_ptr;
197 static void value_id_set(void *id)
198 {
199         _id_tmp_ptr= (ID *)id;
200 }
201
202 static void id_release_weakref_list(struct ID *id, GHash *weakinfo_hash);
203 static PyObject *id_free_weakref_cb(PyObject *weakinfo_capsule, PyObject *weakref)
204 {
205         /* important to search backwards */
206         GHash *weakinfo_hash= PyCapsule_GetPointer(weakinfo_capsule, NULL);
207
208
209         if(BLI_ghash_size(weakinfo_hash) > 1) {
210                 BLI_ghash_remove(weakinfo_hash, weakref, NULL, NULL);
211         }
212         else { /* get the last id and free it */
213                 BLI_ghash_remove(weakinfo_hash, weakref, NULL, value_id_set);
214                 id_release_weakref_list(_id_tmp_ptr, weakinfo_hash);
215         }
216
217         Py_DECREF(weakref);
218
219         Py_RETURN_NONE;
220 }
221
222 static void id_release_weakref_list(struct ID *id, GHash *weakinfo_hash)
223 {
224         GHashIterator weakinfo_hash_iter;
225
226         BLI_ghashIterator_init(&weakinfo_hash_iter, weakinfo_hash);
227
228 #ifdef DEBUG_RNA_WEAKREF
229         fprintf(stdout, "id_release_weakref: '%s', %d items\n", id->name, BLI_ghash_size(weakinfo_hash));
230 #endif
231
232         while (!BLI_ghashIterator_isDone(&weakinfo_hash_iter)) {
233                 PyObject *weakref= (PyObject *)BLI_ghashIterator_getKey(&weakinfo_hash_iter);
234                 PyObject *item= PyWeakref_GET_OBJECT(weakref);
235                 if(item != Py_None) {
236
237 #ifdef DEBUG_RNA_WEAKREF
238                         PyC_ObSpit("id_release_weakref item ", item);
239 #endif
240
241                         pyrna_invalidate((BPy_DummyPointerRNA *)item);
242                 }
243
244                 Py_DECREF(weakref);
245
246                 BLI_ghashIterator_step(&weakinfo_hash_iter);
247         }
248
249         BLI_ghash_remove(id_weakref_pool, (void *)id, NULL, NULL);
250         BLI_ghash_free(weakinfo_hash, NULL, NULL);
251
252         if(BLI_ghash_size(id_weakref_pool) == 0) {
253                 BLI_ghash_free(id_weakref_pool, NULL, NULL);
254                 id_weakref_pool= NULL;
255 #ifdef DEBUG_RNA_WEAKREF
256                 printf("id_release_weakref freeing pool\n");
257 #endif
258         }
259 }
260
261 static void id_release_weakref(struct ID *id)
262 {
263         GHash *weakinfo_hash= BLI_ghash_lookup(id_weakref_pool, (void *)id);
264         if(weakinfo_hash) {
265                 id_release_weakref_list(id, weakinfo_hash);
266         }
267 }
268
269 #endif /* USE_PYRNA_INVALIDATE_WEAKREF */
270
271 void BPY_id_release(struct ID *id)
272 {
273 #ifdef USE_PYRNA_INVALIDATE_GC
274         id_release_gc(id);
275 #endif
276
277 #ifdef USE_PYRNA_INVALIDATE_WEAKREF
278         if(id_weakref_pool) {
279                 PyGILState_STATE gilstate= PyGILState_Ensure();
280
281                 id_release_weakref(id);
282
283                 PyGILState_Release(gilstate);
284         }
285 #endif /* USE_PYRNA_INVALIDATE_WEAKREF */
286
287         (void)id;
288 }
289
290 #ifdef USE_PEDANTIC_WRITE
291 static short rna_disallow_writes= FALSE;
292
293 static int rna_id_write_error(PointerRNA *ptr, PyObject *key)
294 {
295         ID *id= ptr->id.data;
296         if(id) {
297                 const short idcode= GS(id->name);
298                 if(!ELEM(idcode, ID_WM, ID_SCR)) { /* may need more added here */
299                         const char *idtype= BKE_idcode_to_name(idcode);
300                         const char *pyname;
301                         if(key && PyUnicode_Check(key)) pyname= _PyUnicode_AsString(key);
302                         else                                                    pyname= "<UNKNOWN>";
303
304                         /* make a nice string error */
305                         BLI_assert(idtype != NULL);
306                         PyErr_Format(PyExc_AttributeError, "Writing to ID classes in this context is not allowed: %.200s, %.200s datablock, error setting %.200s.%.200s", id->name+2, idtype, RNA_struct_identifier(ptr->type), pyname);
307
308                         return TRUE;
309                 }
310         }
311         return FALSE;
312 }
313 #endif // USE_PEDANTIC_WRITE
314
315
316 #ifdef USE_PEDANTIC_WRITE
317 int pyrna_write_check(void)
318 {
319         return !rna_disallow_writes;
320 }
321 #else // USE_PEDANTIC_WRITE
322 int pyrna_write_check(void)
323 {
324         return TRUE;
325 }
326 #endif // USE_PEDANTIC_WRITE
327
328 static Py_ssize_t pyrna_prop_collection_length(BPy_PropertyRNA *self);
329 static Py_ssize_t pyrna_prop_array_length(BPy_PropertyArrayRNA *self);
330 static int pyrna_py_to_prop(PointerRNA *ptr, PropertyRNA *prop, void *data, PyObject *value, const char *error_prefix);
331 static int deferred_register_prop(StructRNA *srna, PyObject *key, PyObject *item);
332
333 #ifdef USE_MATHUTILS
334 #include "../generic/mathutils.h" /* so we can have mathutils callbacks */
335
336 static PyObject *pyrna_prop_array_subscript_slice(BPy_PropertyArrayRNA *self, PointerRNA *ptr, PropertyRNA *prop, Py_ssize_t start, Py_ssize_t stop, Py_ssize_t length);
337 static short pyrna_rotation_euler_order_get(PointerRNA *ptr, PropertyRNA **prop_eul_order, short order_fallback);
338
339 /* bpyrna vector/euler/quat callbacks */
340 static int mathutils_rna_array_cb_index= -1; /* index for our callbacks */
341
342 /* subtype not used much yet */
343 #define MATHUTILS_CB_SUBTYPE_EUL 0
344 #define MATHUTILS_CB_SUBTYPE_VEC 1
345 #define MATHUTILS_CB_SUBTYPE_QUAT 2
346 #define MATHUTILS_CB_SUBTYPE_COLOR 3
347
348 static int mathutils_rna_generic_check(BaseMathObject *bmo)
349 {
350         BPy_PropertyRNA *self= (BPy_PropertyRNA *)bmo->cb_user;
351
352         PYRNA_PROP_CHECK_INT(self)
353
354         return self->prop ? 0 : -1;
355 }
356
357 static int mathutils_rna_vector_get(BaseMathObject *bmo, int subtype)
358 {
359         BPy_PropertyRNA *self= (BPy_PropertyRNA *)bmo->cb_user;
360
361         PYRNA_PROP_CHECK_INT(self)
362
363         if(self->prop==NULL)
364                 return -1;
365
366         RNA_property_float_get_array(&self->ptr, self->prop, bmo->data);
367
368         /* Euler order exception */
369         if(subtype==MATHUTILS_CB_SUBTYPE_EUL) {
370                 EulerObject *eul= (EulerObject *)bmo;
371                 PropertyRNA *prop_eul_order= NULL;
372                 eul->order= pyrna_rotation_euler_order_get(&self->ptr, &prop_eul_order, eul->order);
373         }
374
375         return 0;
376 }
377
378 static int mathutils_rna_vector_set(BaseMathObject *bmo, int subtype)
379 {
380         BPy_PropertyRNA *self= (BPy_PropertyRNA *)bmo->cb_user;
381         float min, max;
382
383         PYRNA_PROP_CHECK_INT(self)
384
385         if(self->prop==NULL)
386                 return -1;
387
388 #ifdef USE_PEDANTIC_WRITE
389         if(rna_disallow_writes && rna_id_write_error(&self->ptr, NULL)) {
390                 return -1;
391         }
392 #endif // USE_PEDANTIC_WRITE
393
394         if (!RNA_property_editable_flag(&self->ptr, self->prop)) {
395                 PyErr_Format(PyExc_AttributeError, "bpy_prop \"%.200s.%.200s\" is read-only", RNA_struct_identifier(self->ptr.type), RNA_property_identifier(self->prop));
396                 return -1;
397         }
398
399         RNA_property_float_range(&self->ptr, self->prop, &min, &max);
400
401         if(min != FLT_MIN || max != FLT_MAX) {
402                 int i, len= RNA_property_array_length(&self->ptr, self->prop);
403                 for(i=0; i<len; i++) {
404                         CLAMP(bmo->data[i], min, max);
405                 }
406         }
407
408         RNA_property_float_set_array(&self->ptr, self->prop, bmo->data);
409         if(RNA_property_update_check(self->prop)) {
410                 RNA_property_update(BPy_GetContext(), &self->ptr, self->prop);
411         }
412
413         /* Euler order exception */
414         if(subtype==MATHUTILS_CB_SUBTYPE_EUL) {
415                 EulerObject *eul= (EulerObject *)bmo;
416                 PropertyRNA *prop_eul_order= NULL;
417                 short order= pyrna_rotation_euler_order_get(&self->ptr, &prop_eul_order, eul->order);
418                 if(order != eul->order) {
419                         RNA_property_enum_set(&self->ptr, prop_eul_order, eul->order);
420                         if(RNA_property_update_check(prop_eul_order)) {
421                                 RNA_property_update(BPy_GetContext(), &self->ptr, prop_eul_order);
422                         }
423                 }
424         }
425         return 0;
426 }
427
428 static int mathutils_rna_vector_get_index(BaseMathObject *bmo, int UNUSED(subtype), int index)
429 {
430         BPy_PropertyRNA *self= (BPy_PropertyRNA *)bmo->cb_user;
431
432         PYRNA_PROP_CHECK_INT(self)
433
434         if(self->prop==NULL)
435                 return -1;
436
437         bmo->data[index]= RNA_property_float_get_index(&self->ptr, self->prop, index);
438         return 0;
439 }
440
441 static int mathutils_rna_vector_set_index(BaseMathObject *bmo, int UNUSED(subtype), int index)
442 {
443         BPy_PropertyRNA *self= (BPy_PropertyRNA *)bmo->cb_user;
444
445         PYRNA_PROP_CHECK_INT(self)
446
447         if(self->prop==NULL)
448                 return -1;
449
450 #ifdef USE_PEDANTIC_WRITE
451         if(rna_disallow_writes && rna_id_write_error(&self->ptr, NULL)) {
452                 return -1;
453         }
454 #endif // USE_PEDANTIC_WRITE
455
456         if (!RNA_property_editable_flag(&self->ptr, self->prop)) {
457                 PyErr_Format(PyExc_AttributeError, "bpy_prop \"%.200s.%.200s\" is read-only", RNA_struct_identifier(self->ptr.type), RNA_property_identifier(self->prop));
458                 return -1;
459         }
460
461         RNA_property_float_clamp(&self->ptr, self->prop, &bmo->data[index]);
462         RNA_property_float_set_index(&self->ptr, self->prop, index, bmo->data[index]);
463
464         if(RNA_property_update_check(self->prop)) {
465                 RNA_property_update(BPy_GetContext(), &self->ptr, self->prop);
466         }
467
468         return 0;
469 }
470
471 static Mathutils_Callback mathutils_rna_array_cb= {
472         (BaseMathCheckFunc)             mathutils_rna_generic_check,
473         (BaseMathGetFunc)               mathutils_rna_vector_get,
474         (BaseMathSetFunc)               mathutils_rna_vector_set,
475         (BaseMathGetIndexFunc)  mathutils_rna_vector_get_index,
476         (BaseMathSetIndexFunc)  mathutils_rna_vector_set_index
477 };
478
479
480 /* bpyrna matrix callbacks */
481 static int mathutils_rna_matrix_cb_index= -1; /* index for our callbacks */
482
483 static int mathutils_rna_matrix_get(BaseMathObject *bmo, int UNUSED(subtype))
484 {
485         BPy_PropertyRNA *self= (BPy_PropertyRNA *)bmo->cb_user;
486
487         PYRNA_PROP_CHECK_INT(self)
488
489         if(self->prop==NULL)
490                 return -1;
491
492         RNA_property_float_get_array(&self->ptr, self->prop, bmo->data);
493         return 0;
494 }
495
496 static int mathutils_rna_matrix_set(BaseMathObject *bmo, int UNUSED(subtype))
497 {
498         BPy_PropertyRNA *self= (BPy_PropertyRNA *)bmo->cb_user;
499
500         PYRNA_PROP_CHECK_INT(self)
501
502         if(self->prop==NULL)
503                 return -1;
504
505 #ifdef USE_PEDANTIC_WRITE
506         if(rna_disallow_writes && rna_id_write_error(&self->ptr, NULL)) {
507                 return -1;
508         }
509 #endif // USE_PEDANTIC_WRITE
510
511         if (!RNA_property_editable_flag(&self->ptr, self->prop)) {
512                 PyErr_Format(PyExc_AttributeError, "bpy_prop \"%.200s.%.200s\" is read-only", RNA_struct_identifier(self->ptr.type), RNA_property_identifier(self->prop));
513                 return -1;
514         }
515
516         /* can ignore clamping here */
517         RNA_property_float_set_array(&self->ptr, self->prop, bmo->data);
518
519         if(RNA_property_update_check(self->prop)) {
520                 RNA_property_update(BPy_GetContext(), &self->ptr, self->prop);
521         }
522         return 0;
523 }
524
525 static Mathutils_Callback mathutils_rna_matrix_cb= {
526         mathutils_rna_generic_check,
527         mathutils_rna_matrix_get,
528         mathutils_rna_matrix_set,
529         NULL,
530         NULL
531 };
532
533 static short pyrna_rotation_euler_order_get(PointerRNA *ptr, PropertyRNA **prop_eul_order, short order_fallback)
534 {
535         /* attempt to get order */
536         if(*prop_eul_order==NULL)
537                 *prop_eul_order= RNA_struct_find_property(ptr, "rotation_mode");
538
539         if(*prop_eul_order) {
540                 short order= RNA_property_enum_get(ptr, *prop_eul_order);
541                 if (order >= EULER_ORDER_XYZ && order <= EULER_ORDER_ZYX) /* could be quat or axisangle */
542                         return order;
543         }
544
545         return order_fallback;
546 }
547
548 #endif // USE_MATHUTILS
549
550 /* note that PROP_NONE is included as a vector subtype. this is because its handy to
551  * have x/y access to fcurve keyframes and other fixed size float arrays of length 2-4. */
552 #define PROP_ALL_VECTOR_SUBTYPES PROP_COORDS: case PROP_TRANSLATION: case PROP_DIRECTION: case PROP_VELOCITY: case PROP_ACCELERATION: case PROP_XYZ: case PROP_XYZ_LENGTH
553
554 PyObject *pyrna_math_object_from_array(PointerRNA *ptr, PropertyRNA *prop)
555 {
556         PyObject *ret= NULL;
557
558 #ifdef USE_MATHUTILS
559         int subtype, totdim;
560         int len;
561         int is_thick;
562         int flag= RNA_property_flag(prop);
563
564         /* disallow dynamic sized arrays to be wrapped since the size could change
565          * to a size mathutils does not support */
566         if ((RNA_property_type(prop) != PROP_FLOAT) || (flag & PROP_DYNAMIC))
567                 return NULL;
568
569         len= RNA_property_array_length(ptr, prop);
570         subtype= RNA_property_subtype(prop);
571         totdim= RNA_property_array_dimension(ptr, prop, NULL);
572         is_thick= (flag & PROP_THICK_WRAP);
573
574         if (totdim == 1 || (totdim == 2 && subtype == PROP_MATRIX)) {
575                 if(!is_thick)
576                         ret= pyrna_prop_CreatePyObject(ptr, prop); /* owned by the mathutils PyObject */
577
578                 switch(RNA_property_subtype(prop)) {
579                 case PROP_ALL_VECTOR_SUBTYPES:
580                         if(len>=2 && len <= 4) {
581                                 if(is_thick) {
582                                         ret= newVectorObject(NULL, len, Py_NEW, NULL);
583                                         RNA_property_float_get_array(ptr, prop, ((VectorObject *)ret)->vec);
584                                 }
585                                 else {
586                                         PyObject *vec_cb= newVectorObject_cb(ret, len, mathutils_rna_array_cb_index, MATHUTILS_CB_SUBTYPE_VEC);
587                                         Py_DECREF(ret); /* the vector owns now */
588                                         ret= vec_cb; /* return the vector instead */
589                                 }
590                         }
591                         break;
592                 case PROP_MATRIX:
593                         if(len==16) {
594                                 if(is_thick) {
595                                         ret= newMatrixObject(NULL, 4, 4, Py_NEW, NULL);
596                                         RNA_property_float_get_array(ptr, prop, ((MatrixObject *)ret)->contigPtr);
597                                 }
598                                 else {
599                                         PyObject *mat_cb= newMatrixObject_cb(ret, 4,4, mathutils_rna_matrix_cb_index, FALSE);
600                                         Py_DECREF(ret); /* the matrix owns now */
601                                         ret= mat_cb; /* return the matrix instead */
602                                 }
603                         }
604                         else if (len==9) {
605                                 if(is_thick) {
606                                         ret= newMatrixObject(NULL, 3, 3, Py_NEW, NULL);
607                                         RNA_property_float_get_array(ptr, prop, ((MatrixObject *)ret)->contigPtr);
608                                 }
609                                 else {
610                                         PyObject *mat_cb= newMatrixObject_cb(ret, 3,3, mathutils_rna_matrix_cb_index, FALSE);
611                                         Py_DECREF(ret); /* the matrix owns now */
612                                         ret= mat_cb; /* return the matrix instead */
613                                 }
614                         }
615                         break;
616                 case PROP_EULER:
617                 case PROP_QUATERNION:
618                         if(len==3) { /* euler */
619                                 if(is_thick) {
620                                         /* attempt to get order, only needed for thick types since wrapped with update via callbacks */
621                                         PropertyRNA *prop_eul_order= NULL;
622                                         short order= pyrna_rotation_euler_order_get(ptr, &prop_eul_order, EULER_ORDER_XYZ);
623
624                                         ret= newEulerObject(NULL, order, Py_NEW, NULL); // TODO, get order from RNA
625                                         RNA_property_float_get_array(ptr, prop, ((EulerObject *)ret)->eul);
626                                 }
627                                 else {
628                                         /* order will be updated from callback on use */
629                                         PyObject *eul_cb= newEulerObject_cb(ret, EULER_ORDER_XYZ, mathutils_rna_array_cb_index, MATHUTILS_CB_SUBTYPE_EUL); // TODO, get order from RNA
630                                         Py_DECREF(ret); /* the euler owns now */
631                                         ret= eul_cb; /* return the euler instead */
632                                 }
633                         }
634                         else if (len==4) {
635                                 if(is_thick) {
636                                         ret= newQuaternionObject(NULL, Py_NEW, NULL);
637                                         RNA_property_float_get_array(ptr, prop, ((QuaternionObject *)ret)->quat);
638                                 }
639                                 else {
640                                         PyObject *quat_cb= newQuaternionObject_cb(ret, mathutils_rna_array_cb_index, MATHUTILS_CB_SUBTYPE_QUAT);
641                                         Py_DECREF(ret); /* the quat owns now */
642                                         ret= quat_cb; /* return the quat instead */
643                                 }
644                         }
645                         break;
646                 case PROP_COLOR:
647                 case PROP_COLOR_GAMMA:
648                         if(len==3) { /* color */
649                                 if(is_thick) {
650                                         ret= newColorObject(NULL, Py_NEW, NULL); // TODO, get order from RNA
651                                         RNA_property_float_get_array(ptr, prop, ((ColorObject *)ret)->col);
652                                 }
653                                 else {
654                                         PyObject *col_cb= newColorObject_cb(ret, mathutils_rna_array_cb_index, MATHUTILS_CB_SUBTYPE_COLOR);
655                                         Py_DECREF(ret); /* the color owns now */
656                                         ret= col_cb; /* return the color instead */
657                                 }
658                         }
659                 default:
660                         break;
661                 }
662         }
663
664         if(ret==NULL) {
665                 if(is_thick) {
666                         /* this is an array we cant reference (since its not thin wrappable)
667                          * and cannot be coerced into a mathutils type, so return as a list */
668                         ret= pyrna_prop_array_subscript_slice(NULL, ptr, prop, 0, len, len);
669                 }
670                 else {
671                         ret= pyrna_prop_CreatePyObject(ptr, prop); /* owned by the mathutils PyObject */
672                 }
673         }
674 #else // USE_MATHUTILS
675         (void)ptr;
676         (void)prop;
677 #endif // USE_MATHUTILS
678
679         return ret;
680 }
681
682 /* same as RNA_enum_value_from_id but raises an exception */
683 int pyrna_enum_value_from_id(EnumPropertyItem *item, const char *identifier, int *value, const char *error_prefix)
684 {
685         if(RNA_enum_value_from_id(item, identifier, value) == 0) {
686                 const char *enum_str= BPy_enum_as_string(item);
687                 PyErr_Format(PyExc_TypeError, "%s: '%.200s' not found in (%s)", error_prefix, identifier, enum_str);
688                 MEM_freeN((void *)enum_str);
689                 return -1;
690         }
691
692         return 0;
693 }
694
695 static int pyrna_struct_compare(BPy_StructRNA *a, BPy_StructRNA *b)
696 {
697         return (a->ptr.data==b->ptr.data) ? 0 : -1;
698 }
699
700 static int pyrna_prop_compare(BPy_PropertyRNA *a, BPy_PropertyRNA *b)
701 {
702         return (a->prop==b->prop && a->ptr.data==b->ptr.data) ? 0 : -1;
703 }
704
705 static PyObject *pyrna_struct_richcmp(PyObject *a, PyObject *b, int op)
706 {
707         PyObject *res;
708         int ok= -1; /* zero is true */
709
710         if (BPy_StructRNA_Check(a) && BPy_StructRNA_Check(b))
711                 ok= pyrna_struct_compare((BPy_StructRNA *)a, (BPy_StructRNA *)b);
712
713         switch (op) {
714         case Py_NE:
715                 ok= !ok; /* pass through */
716         case Py_EQ:
717                 res= ok ? Py_False : Py_True;
718                 break;
719
720         case Py_LT:
721         case Py_LE:
722         case Py_GT:
723         case Py_GE:
724                 res= Py_NotImplemented;
725                 break;
726         default:
727                 PyErr_BadArgument();
728                 return NULL;
729         }
730
731         return Py_INCREF(res), res;
732 }
733
734 static PyObject *pyrna_prop_richcmp(PyObject *a, PyObject *b, int op)
735 {
736         PyObject *res;
737         int ok= -1; /* zero is true */
738
739         if (BPy_PropertyRNA_Check(a) && BPy_PropertyRNA_Check(b))
740                 ok= pyrna_prop_compare((BPy_PropertyRNA *)a, (BPy_PropertyRNA *)b);
741
742         switch (op) {
743         case Py_NE:
744                 ok= !ok; /* pass through */
745         case Py_EQ:
746                 res= ok ? Py_False : Py_True;
747                 break;
748
749         case Py_LT:
750         case Py_LE:
751         case Py_GT:
752         case Py_GE:
753                 res= Py_NotImplemented;
754                 break;
755         default:
756                 PyErr_BadArgument();
757                 return NULL;
758         }
759
760         return Py_INCREF(res), res;
761 }
762
763 /*----------------------repr--------------------------------------------*/
764 static PyObject *pyrna_struct_str(BPy_StructRNA *self)
765 {
766         PyObject *ret;
767         const char *name;
768
769         if(!PYRNA_STRUCT_IS_VALID(self)) {
770                 return PyUnicode_FromFormat("<bpy_struct, %.200s dead>", Py_TYPE(self)->tp_name);
771         }
772
773         /* print name if available */
774         name= RNA_struct_name_get_alloc(&self->ptr, NULL, FALSE);
775         if(name) {
776                 ret= PyUnicode_FromFormat("<bpy_struct, %.200s(\"%.200s\")>", RNA_struct_identifier(self->ptr.type), name);
777                 MEM_freeN((void *)name);
778                 return ret;
779         }
780
781         return PyUnicode_FromFormat("<bpy_struct, %.200s at %p>", RNA_struct_identifier(self->ptr.type), self->ptr.data);
782 }
783
784 static PyObject *pyrna_struct_repr(BPy_StructRNA *self)
785 {
786         ID *id= self->ptr.id.data;
787         if(id == NULL || !PYRNA_STRUCT_IS_VALID(self))
788                 return pyrna_struct_str(self); /* fallback */
789
790         if(RNA_struct_is_ID(self->ptr.type)) {
791                 return PyUnicode_FromFormat("bpy.data.%s[\"%s\"]", BKE_idcode_to_name_plural(GS(id->name)), id->name+2);
792         }
793         else {
794                 PyObject *ret;
795                 const char *path;
796                 path= RNA_path_from_ID_to_struct(&self->ptr);
797                 if(path) {
798                         ret= PyUnicode_FromFormat("bpy.data.%s[\"%s\"].%s", BKE_idcode_to_name_plural(GS(id->name)), id->name+2, path);
799                         MEM_freeN((void *)path);
800                 }
801                 else { /* cant find, print something sane */
802                         ret= PyUnicode_FromFormat("bpy.data.%s[\"%s\"]...%s", BKE_idcode_to_name_plural(GS(id->name)), id->name+2, RNA_struct_identifier(self->ptr.type));
803                 }
804
805                 return ret;
806         }
807 }
808
809 static PyObject *pyrna_prop_str(BPy_PropertyRNA *self)
810 {
811         PyObject *ret;
812         PointerRNA ptr;
813         const char *name;
814         const char *type_id= NULL;
815         char type_fmt[64]= "";
816         int type;
817
818         PYRNA_PROP_CHECK_OBJ(self)
819
820         type= RNA_property_type(self->prop);
821
822         if(RNA_enum_id_from_value(property_type_items, type, &type_id)==0) {
823                 PyErr_SetString(PyExc_RuntimeError, "could not use property type, internal error"); /* should never happen */
824                 return NULL;
825         }
826         else {
827                 /* this should never fail */
828                 int len= -1;
829                 char *c= type_fmt;
830
831                 while ((*c++= tolower(*type_id++))) {} ;
832
833                 if(type==PROP_COLLECTION) {
834                         len= pyrna_prop_collection_length(self);
835                 }
836                 else if (RNA_property_array_check(&self->ptr, self->prop)) {
837                         len= pyrna_prop_array_length((BPy_PropertyArrayRNA *)self);
838                 }
839
840                 if(len != -1)
841                         sprintf(--c, "[%d]", len);
842         }
843
844         /* if a pointer, try to print name of pointer target too */
845         if(RNA_property_type(self->prop) == PROP_POINTER) {
846                 ptr= RNA_property_pointer_get(&self->ptr, self->prop);
847                 name= RNA_struct_name_get_alloc(&ptr, NULL, FALSE);
848
849                 if(name) {
850                         ret= PyUnicode_FromFormat("<bpy_%.200s, %.200s.%.200s(\"%.200s\")>", type_fmt, RNA_struct_identifier(self->ptr.type), RNA_property_identifier(self->prop), name);
851                         MEM_freeN((void *)name);
852                         return ret;
853                 }
854         }
855         if(RNA_property_type(self->prop) == PROP_COLLECTION) {
856                 PointerRNA r_ptr;
857                 if(RNA_property_collection_type_get(&self->ptr, self->prop, &r_ptr)) {
858                         return PyUnicode_FromFormat("<bpy_%.200s, %.200s>", type_fmt, RNA_struct_identifier(r_ptr.type));
859                 }
860         }
861
862         return PyUnicode_FromFormat("<bpy_%.200s, %.200s.%.200s>", type_fmt, RNA_struct_identifier(self->ptr.type), RNA_property_identifier(self->prop));
863 }
864
865 static PyObject *pyrna_prop_repr(BPy_PropertyRNA *self)
866 {
867         ID *id;
868         PyObject *ret;
869         const char *path;
870
871         PYRNA_PROP_CHECK_OBJ(self)
872
873         if((id= self->ptr.id.data) == NULL)
874                 return pyrna_prop_str(self); /* fallback */
875
876         path= RNA_path_from_ID_to_property(&self->ptr, self->prop);
877         if(path) {
878                 ret= PyUnicode_FromFormat("bpy.data.%s[\"%s\"].%s", BKE_idcode_to_name_plural(GS(id->name)), id->name+2, path);
879                 MEM_freeN((void *)path);
880         }
881         else { /* cant find, print something sane */
882                 ret= PyUnicode_FromFormat("bpy.data.%s[\"%s\"]...%s", BKE_idcode_to_name_plural(GS(id->name)), id->name+2, RNA_property_identifier(self->prop));
883         }
884
885         return ret;
886 }
887
888 static long pyrna_struct_hash(BPy_StructRNA *self)
889 {
890         return _Py_HashPointer(self->ptr.data);
891 }
892
893 /* from python's meth_hash v3.1.2 */
894 static long pyrna_prop_hash(BPy_PropertyRNA *self)
895 {
896         long x, y;
897         if (self->ptr.data == NULL)
898                 x= 0;
899         else {
900                 x= _Py_HashPointer(self->ptr.data);
901                 if (x == -1)
902                         return -1;
903         }
904         y= _Py_HashPointer((void*)(self->prop));
905         if (y == -1)
906                 return -1;
907         x ^= y;
908         if (x == -1)
909                 x= -2;
910         return x;
911 }
912
913 #ifdef USE_PYRNA_STRUCT_REFERENCE
914 static int pyrna_struct_traverse(BPy_StructRNA *self, visitproc visit, void *arg)
915 {
916         Py_VISIT(self->reference);
917         return 0;
918 }
919
920 static int pyrna_struct_clear(BPy_StructRNA *self)
921 {
922         Py_CLEAR(self->reference);
923         return 0;
924 }
925 #endif /* !USE_PYRNA_STRUCT_REFERENCE */
926
927 /* use our own dealloc so we can free a property if we use one */
928 static void pyrna_struct_dealloc(BPy_StructRNA *self)
929 {
930         if (self->freeptr && self->ptr.data) {
931                 IDP_FreeProperty(self->ptr.data);
932                 MEM_freeN(self->ptr.data);
933                 self->ptr.data= NULL;
934         }
935
936 #ifdef USE_WEAKREFS
937         if (self->in_weakreflist != NULL) {
938                 PyObject_ClearWeakRefs((PyObject *)self);
939         }
940 #endif
941
942 #ifdef USE_PYRNA_STRUCT_REFERENCE
943         if(self->reference) {
944                 PyObject_GC_UnTrack(self);
945                 pyrna_struct_clear(self);
946         }
947 #endif /* !USE_PYRNA_STRUCT_REFERENCE */
948
949         /* Note, for subclassed PyObjects we cant just call PyObject_DEL() directly or it will crash */
950         Py_TYPE(self)->tp_free(self);
951 }
952
953 #ifdef USE_PYRNA_STRUCT_REFERENCE
954 static void pyrna_struct_reference_set(BPy_StructRNA *self, PyObject *reference)
955 {
956         if(self->reference) {
957 //              PyObject_GC_UnTrack(self); /* INITIALIZED TRACKED? */
958                 pyrna_struct_clear(self);
959         }
960         /* reference is now NULL */
961
962         if(reference) {
963                 self->reference= reference;
964                 Py_INCREF(reference);
965 //              PyObject_GC_Track(self);  /* INITIALIZED TRACKED? */
966         }
967 }
968 #endif /* !USE_PYRNA_STRUCT_REFERENCE */
969
970 /* use our own dealloc so we can free a property if we use one */
971 static void pyrna_prop_dealloc(BPy_PropertyRNA *self)
972 {
973 #ifdef USE_WEAKREFS
974         if (self->in_weakreflist != NULL) {
975                 PyObject_ClearWeakRefs((PyObject *)self);
976         }
977 #endif
978         /* Note, for subclassed PyObjects we cant just call PyObject_DEL() directly or it will crash */
979         Py_TYPE(self)->tp_free(self);
980 }
981
982 static void pyrna_prop_array_dealloc(BPy_PropertyRNA *self)
983 {
984 #ifdef USE_WEAKREFS
985         if (self->in_weakreflist != NULL) {
986                 PyObject_ClearWeakRefs((PyObject *)self);
987         }
988 #endif
989         /* Note, for subclassed PyObjects we cant just call PyObject_DEL() directly or it will crash */
990         Py_TYPE(self)->tp_free(self);
991 }
992
993 static const char *pyrna_enum_as_string(PointerRNA *ptr, PropertyRNA *prop)
994 {
995         EnumPropertyItem *item;
996         const char *result;
997         int free= FALSE;
998
999         RNA_property_enum_items(BPy_GetContext(), ptr, prop, &item, NULL, &free);
1000         if(item) {
1001                 result= BPy_enum_as_string(item);
1002         }
1003         else {
1004                 result= "";
1005         }
1006
1007         if(free)
1008                 MEM_freeN(item);
1009
1010         return result;
1011 }
1012
1013
1014 static int pyrna_string_to_enum(PyObject *item, PointerRNA *ptr, PropertyRNA *prop, int *val, const char *error_prefix)
1015 {
1016         const char *param= _PyUnicode_AsString(item);
1017
1018         if (param==NULL) {
1019                 const char *enum_str= pyrna_enum_as_string(ptr, prop);
1020                 PyErr_Format(PyExc_TypeError, "%.200s expected a string enum type in (%.200s)", error_prefix, enum_str);
1021                 MEM_freeN((void *)enum_str);
1022                 return 0;
1023         }
1024         else {
1025                 /* hack so that dynamic enums used for operator properties will be able to be built (i.e. context will be supplied to itemf)
1026                  * and thus running defining operator buttons for such operators in UI will work */
1027                 RNA_def_property_clear_flag(prop, PROP_ENUM_NO_CONTEXT);
1028
1029                 if (!RNA_property_enum_value(BPy_GetContext(), ptr, prop, param, val)) {
1030                         const char *enum_str= pyrna_enum_as_string(ptr, prop);
1031                         PyErr_Format(PyExc_TypeError, "%.200s enum \"%.200s\" not found in (%.200s)", error_prefix, param, enum_str);
1032                         MEM_freeN((void *)enum_str);
1033                         return 0;
1034                 }
1035         }
1036
1037         return 1;
1038 }
1039
1040 int pyrna_set_to_enum_bitfield(EnumPropertyItem *items, PyObject *value, int *r_value, const char *error_prefix)
1041 {
1042         /* set of enum items, concatenate all values with OR */
1043         int ret, flag= 0;
1044
1045         /* set looping */
1046         Py_ssize_t pos= 0;
1047         Py_ssize_t hash= 0;
1048         PyObject *key;
1049
1050         *r_value= 0;
1051
1052         while (_PySet_NextEntry(value, &pos, &key, &hash)) {
1053                 const char *param= _PyUnicode_AsString(key);
1054
1055                 if(param==NULL) {
1056                         PyErr_Format(PyExc_TypeError, "%.200s expected a string, not %.200s", error_prefix, Py_TYPE(key)->tp_name);
1057                         return -1;
1058                 }
1059                 if(pyrna_enum_value_from_id(items, param, &ret, error_prefix) < 0)
1060                         return -1;
1061
1062                 flag |= ret;
1063         }
1064
1065         *r_value= flag;
1066         return 0;
1067 }
1068
1069 static int pyrna_prop_to_enum_bitfield(PointerRNA *ptr, PropertyRNA *prop, PyObject *value, int *r_value, const char *error_prefix)
1070 {
1071         EnumPropertyItem *item;
1072         int ret;
1073         int free= FALSE;
1074
1075         *r_value= 0;
1076
1077         RNA_property_enum_items(BPy_GetContext(), ptr, prop, &item, NULL, &free);
1078
1079         if(item) {
1080                 ret= pyrna_set_to_enum_bitfield(item, value, r_value, error_prefix);
1081         }
1082         else {
1083                 if(PySet_GET_SIZE(value)) {
1084                         PyErr_Format(PyExc_TypeError, "%.200s: empty enum \"%.200s\" could not have any values assigned", error_prefix, RNA_property_identifier(prop));
1085                         ret= -1;
1086                 }
1087                 else {
1088                         ret= 0;
1089                 }
1090         }
1091
1092         if(free)
1093                 MEM_freeN(item);
1094
1095         return ret;
1096 }
1097
1098 PyObject *pyrna_enum_bitfield_to_py(EnumPropertyItem *items, int value)
1099 {
1100         PyObject *ret= PySet_New(NULL);
1101         const char *identifier[RNA_ENUM_BITFLAG_SIZE + 1];
1102
1103         if(RNA_enum_bitflag_identifiers(items, value, identifier)) {
1104                 PyObject *item;
1105                 int index;
1106                 for(index=0; identifier[index]; index++) {
1107                         item= PyUnicode_FromString(identifier[index]);
1108                         PySet_Add(ret, item);
1109                         Py_DECREF(item);
1110                 }
1111         }
1112
1113         return ret;
1114 }
1115
1116 static PyObject *pyrna_enum_to_py(PointerRNA *ptr, PropertyRNA *prop, int val)
1117 {
1118         PyObject *item, *ret= NULL;
1119
1120         if(RNA_property_flag(prop) & PROP_ENUM_FLAG) {
1121                 const char *identifier[RNA_ENUM_BITFLAG_SIZE + 1];
1122
1123                 ret= PySet_New(NULL);
1124
1125                 if (RNA_property_enum_bitflag_identifiers(BPy_GetContext(), ptr, prop, val, identifier)) {
1126                         int index;
1127
1128                         for(index=0; identifier[index]; index++) {
1129                                 item= PyUnicode_FromString(identifier[index]);
1130                                 PySet_Add(ret, item);
1131                                 Py_DECREF(item);
1132                         }
1133
1134                 }
1135         }
1136         else {
1137                 const char *identifier;
1138                 if (RNA_property_enum_identifier(BPy_GetContext(), ptr, prop, val, &identifier)) {
1139                         ret= PyUnicode_FromString(identifier);
1140                 }
1141                 else {
1142                         EnumPropertyItem *enum_item;
1143                         int free= FALSE;
1144
1145                         /* don't throw error here, can't trust blender 100% to give the
1146                          * right values, python code should not generate error for that */
1147                         RNA_property_enum_items(BPy_GetContext(), ptr, prop, &enum_item, NULL, &free);
1148                         if(enum_item && enum_item->identifier) {
1149                                 ret= PyUnicode_FromString(enum_item->identifier);
1150                         }
1151                         else {
1152                                 const char *ptr_name= RNA_struct_name_get_alloc(ptr, NULL, FALSE);
1153
1154                                 /* prefer not fail silently incase of api errors, maybe disable it later */
1155                                 printf("RNA Warning: Current value \"%d\" matches no enum in '%s', '%s', '%s'\n", val, RNA_struct_identifier(ptr->type), ptr_name, RNA_property_identifier(prop));
1156
1157 #if 0                   // gives python decoding errors while generating docs :(
1158                                 char error_str[256];
1159                                 snprintf(error_str, sizeof(error_str), "RNA Warning: Current value \"%d\" matches no enum in '%s', '%s', '%s'", val, RNA_struct_identifier(ptr->type), ptr_name, RNA_property_identifier(prop));
1160                                 PyErr_Warn(PyExc_RuntimeWarning, error_str);
1161 #endif
1162
1163                                 if(ptr_name)
1164                                         MEM_freeN((void *)ptr_name);
1165
1166                                 ret= PyUnicode_FromString("");
1167                         }
1168
1169                         if(free)
1170                                 MEM_freeN(enum_item);
1171
1172                         /*PyErr_Format(PyExc_AttributeError, "RNA Error: Current value \"%d\" matches no enum", val);
1173                         ret= NULL;*/
1174                 }
1175         }
1176
1177         return ret;
1178 }
1179
1180 PyObject * pyrna_prop_to_py(PointerRNA *ptr, PropertyRNA *prop)
1181 {
1182         PyObject *ret;
1183         int type= RNA_property_type(prop);
1184
1185         if (RNA_property_array_check(ptr, prop)) {
1186                 return pyrna_py_from_array(ptr, prop);
1187         }
1188
1189         /* see if we can coorce into a python type - PropertyType */
1190         switch (type) {
1191         case PROP_BOOLEAN:
1192                 ret= PyBool_FromLong(RNA_property_boolean_get(ptr, prop));
1193                 break;
1194         case PROP_INT:
1195                 ret= PyLong_FromSsize_t((Py_ssize_t)RNA_property_int_get(ptr, prop));
1196                 break;
1197         case PROP_FLOAT:
1198                 ret= PyFloat_FromDouble(RNA_property_float_get(ptr, prop));
1199                 break;
1200         case PROP_STRING:
1201         {
1202                 int subtype= RNA_property_subtype(prop);
1203                 const char *buf;
1204                 buf= RNA_property_string_get_alloc(ptr, prop, NULL, -1);
1205 #ifdef USE_STRING_COERCE
1206                 /* only file paths get special treatment, they may contain non utf-8 chars */
1207                 if(ELEM3(subtype, PROP_FILEPATH, PROP_DIRPATH, PROP_FILENAME)) {
1208                         ret= PyC_UnicodeFromByte(buf);
1209                 }
1210                 else {
1211                         ret= PyUnicode_FromString(buf);
1212                 }
1213 #else // USE_STRING_COERCE
1214                 ret= PyUnicode_FromString(buf);
1215 #endif // USE_STRING_COERCE
1216                 MEM_freeN((void *)buf);
1217                 break;
1218         }
1219         case PROP_ENUM:
1220         {
1221                 ret= pyrna_enum_to_py(ptr, prop, RNA_property_enum_get(ptr, prop));
1222                 break;
1223         }
1224         case PROP_POINTER:
1225         {
1226                 PointerRNA newptr;
1227                 newptr= RNA_property_pointer_get(ptr, prop);
1228                 if (newptr.data) {
1229                         ret= pyrna_struct_CreatePyObject(&newptr);
1230                 }
1231                 else {
1232                         ret= Py_None;
1233                         Py_INCREF(ret);
1234                 }
1235                 break;
1236         }
1237         case PROP_COLLECTION:
1238                 ret= pyrna_prop_CreatePyObject(ptr, prop);
1239                 break;
1240         default:
1241                 PyErr_Format(PyExc_TypeError, "bpy_struct internal error: unknown type '%d' (pyrna_prop_to_py)", type);
1242                 ret= NULL;
1243                 break;
1244         }
1245
1246         return ret;
1247 }
1248
1249 /* This function is used by operators and converting dicts into collections.
1250  * Its takes keyword args and fills them with property values */
1251 int pyrna_pydict_to_props(PointerRNA *ptr, PyObject *kw, int all_args, const char *error_prefix)
1252 {
1253         int error_val= 0;
1254         int totkw;
1255         const char *arg_name= NULL;
1256         PyObject *item;
1257
1258         totkw= kw ? PyDict_Size(kw):0;
1259
1260         RNA_STRUCT_BEGIN(ptr, prop) {
1261                 arg_name= RNA_property_identifier(prop);
1262
1263                 if (strcmp(arg_name, "rna_type")==0) continue;
1264
1265                 if (kw==NULL) {
1266                         PyErr_Format(PyExc_TypeError, "%.200s: no keywords, expected \"%.200s\"", error_prefix, arg_name ? arg_name : "<UNKNOWN>");
1267                         error_val= -1;
1268                         break;
1269                 }
1270
1271                 item= PyDict_GetItemString(kw, arg_name); /* wont set an error */
1272
1273                 if (item == NULL) {
1274                         if(all_args) {
1275                                 PyErr_Format(PyExc_TypeError, "%.200s: keyword \"%.200s\" missing", error_prefix, arg_name ? arg_name : "<UNKNOWN>");
1276                                 error_val= -1; /* pyrna_py_to_prop sets the error */
1277                                 break;
1278                         }
1279                 }
1280                 else {
1281                         if (pyrna_py_to_prop(ptr, prop, NULL, item, error_prefix)) {
1282                                 error_val= -1;
1283                                 break;
1284                         }
1285                         totkw--;
1286                 }
1287         }
1288         RNA_STRUCT_END;
1289
1290         if (error_val==0 && totkw > 0) { /* some keywords were given that were not used :/ */
1291                 PyObject *key, *value;
1292                 Py_ssize_t pos= 0;
1293
1294                 while (PyDict_Next(kw, &pos, &key, &value)) {
1295                         arg_name= _PyUnicode_AsString(key);
1296                         if (RNA_struct_find_property(ptr, arg_name) == NULL) break;
1297                         arg_name= NULL;
1298                 }
1299
1300                 PyErr_Format(PyExc_TypeError, "%.200s: keyword \"%.200s\" unrecognized", error_prefix, arg_name ? arg_name : "<UNKNOWN>");
1301                 error_val= -1;
1302         }
1303
1304         return error_val;
1305 }
1306
1307 static PyObject * pyrna_func_call(PyObject *self, PyObject *args, PyObject *kw);
1308
1309 static PyObject *pyrna_func_to_py(BPy_DummyPointerRNA *pyrna, FunctionRNA *func)
1310 {
1311         static PyMethodDef func_meth= {"<generic rna function>", (PyCFunction)pyrna_func_call, METH_VARARGS|METH_KEYWORDS, "python rna function"};
1312         PyObject *self;
1313         PyObject *ret;
1314
1315         if(func==NULL) {
1316                 PyErr_Format(PyExc_RuntimeError, "%.200s: type attempted to get NULL function", RNA_struct_identifier(pyrna->ptr.type));
1317                 return NULL;
1318         }
1319
1320         self= PyTuple_New(2);
1321
1322         PyTuple_SET_ITEM(self, 0, (PyObject *)pyrna);
1323         Py_INCREF(pyrna);
1324
1325         PyTuple_SET_ITEM(self, 1, PyCapsule_New((void *)func, NULL, NULL));
1326
1327         ret= PyCFunction_New(&func_meth, self);
1328         Py_DECREF(self);
1329
1330         return ret;
1331 }
1332
1333
1334
1335 static int pyrna_py_to_prop(PointerRNA *ptr, PropertyRNA *prop, void *data, PyObject *value, const char *error_prefix)
1336 {
1337         /* XXX hard limits should be checked here */
1338         int type= RNA_property_type(prop);
1339
1340
1341         if (RNA_property_array_check(ptr, prop)) {
1342                 int ok= 1;
1343
1344                 /* done getting the length */
1345                 ok= pyrna_py_to_array(ptr, prop, data, value, error_prefix);
1346
1347                 if (!ok) {
1348                         return -1;
1349                 }
1350         }
1351         else {
1352                 /* Normal Property (not an array) */
1353
1354                 /* see if we can coorce into a python type - PropertyType */
1355                 switch (type) {
1356                 case PROP_BOOLEAN:
1357                 {
1358                         int param;
1359                         /* prefer not to have an exception here
1360                          * however so many poll functions return None or a valid Object.
1361                          * its a hassle to convert these into a bool before returning, */
1362                         if(RNA_property_flag(prop) & PROP_OUTPUT)
1363                                 param= PyObject_IsTrue(value);
1364                         else
1365                                 param= PyLong_AsLong(value);
1366
1367                         if(param < 0) {
1368                                 PyErr_Format(PyExc_TypeError, "%.200s %.200s.%.200s expected True/False or 0/1, not %.200s", error_prefix, RNA_struct_identifier(ptr->type), RNA_property_identifier(prop), Py_TYPE(value)->tp_name);
1369                                 return -1;
1370                         }
1371                         else {
1372                                 if(data)        *((int*)data)= param;
1373                                 else            RNA_property_boolean_set(ptr, prop, param);
1374                         }
1375                         break;
1376                 }
1377                 case PROP_INT:
1378                 {
1379                         int overflow;
1380                         long param= PyLong_AsLongAndOverflow(value, &overflow);
1381                         if(overflow || (param > INT_MAX) || (param < INT_MIN)) {
1382                                 PyErr_Format(PyExc_ValueError, "%.200s %.200s.%.200s value not in 'int' range (" STRINGIFY(INT_MIN) ", " STRINGIFY(INT_MAX) ")", error_prefix, RNA_struct_identifier(ptr->type), RNA_property_identifier(prop));
1383                                 return -1;
1384                         }
1385                         else if (param==-1 && PyErr_Occurred()) {
1386                                 PyErr_Format(PyExc_TypeError, "%.200s %.200s.%.200s expected an int type, not %.200s", error_prefix, RNA_struct_identifier(ptr->type), RNA_property_identifier(prop), Py_TYPE(value)->tp_name);
1387                                 return -1;
1388                         }
1389                         else {
1390                                 int param_i= (int)param;
1391                                 RNA_property_int_clamp(ptr, prop, &param_i);
1392                                 if(data)        *((int*)data)= param_i;
1393                                 else            RNA_property_int_set(ptr, prop, param_i);
1394                         }
1395                         break;
1396                 }
1397                 case PROP_FLOAT:
1398                 {
1399                         float param= PyFloat_AsDouble(value);
1400                         if (PyErr_Occurred()) {
1401                                 PyErr_Format(PyExc_TypeError, "%.200s %.200s.%.200s expected a float type, not %.200s", error_prefix, RNA_struct_identifier(ptr->type), RNA_property_identifier(prop), Py_TYPE(value)->tp_name);
1402                                 return -1;
1403                         }
1404                         else {
1405                                 RNA_property_float_clamp(ptr, prop, (float *)&param);
1406                                 if(data)        *((float*)data)= param;
1407                                 else            RNA_property_float_set(ptr, prop, param);
1408                         }
1409                         break;
1410                 }
1411                 case PROP_STRING:
1412                 {
1413                         const char *param;
1414 #ifdef USE_STRING_COERCE
1415                         PyObject *value_coerce= NULL;
1416                         int subtype= RNA_property_subtype(prop);
1417                         if(ELEM3(subtype, PROP_FILEPATH, PROP_DIRPATH, PROP_FILENAME)) {
1418                                 /* TODO, get size */
1419                                 param= PyC_UnicodeAsByte(value, &value_coerce);
1420                         }
1421                         else {
1422                                 param= _PyUnicode_AsString(value);
1423                         }
1424 #else // USE_STRING_COERCE
1425                         param= _PyUnicode_AsStringSize(value);
1426 #endif // USE_STRING_COERCE
1427
1428                         if (param==NULL) {
1429                                 PyErr_Format(PyExc_TypeError, "%.200s %.200s.%.200s expected a string type, not %.200s", error_prefix, RNA_struct_identifier(ptr->type), RNA_property_identifier(prop), Py_TYPE(value)->tp_name);
1430                                 return -1;
1431                         }
1432                         else {
1433                                 if(data)        *((char**)data)= (char *)param; /*XXX, this is suspect but needed for function calls, need to see if theres a better way */
1434                                 else            RNA_property_string_set(ptr, prop, param);
1435                         }
1436 #ifdef USE_STRING_COERCE
1437                         Py_XDECREF(value_coerce);
1438 #endif // USE_STRING_COERCE
1439                         break;
1440                 }
1441                 case PROP_ENUM:
1442                 {
1443                         int val= 0;
1444
1445                         if (PyUnicode_Check(value)) {
1446                                 if (!pyrna_string_to_enum(value, ptr, prop, &val, error_prefix))
1447                                         return -1;
1448                         }
1449                         else if (PyAnySet_Check(value)) {
1450                                 if(RNA_property_flag(prop) & PROP_ENUM_FLAG) {
1451                                         /* set of enum items, concatenate all values with OR */
1452                                         if(pyrna_prop_to_enum_bitfield(ptr, prop, value, &val, error_prefix) < 0)
1453                                                 return -1;
1454                                 }
1455                                 else {
1456                                         PyErr_Format(PyExc_TypeError, "%.200s, %.200s.%.200s is not a bitflag enum type", error_prefix, RNA_struct_identifier(ptr->type), RNA_property_identifier(prop));
1457                                         return -1;
1458                                 }
1459                         }
1460                         else {
1461                                 const char *enum_str= pyrna_enum_as_string(ptr, prop);
1462                                 PyErr_Format(PyExc_TypeError, "%.200s %.200s.%.200s expected a string enum or a set of strings in (%.2000s), not %.200s", error_prefix, RNA_struct_identifier(ptr->type), RNA_property_identifier(prop), enum_str, Py_TYPE(value)->tp_name);
1463                                 MEM_freeN((void *)enum_str);
1464                                 return -1;
1465                         }
1466
1467                         if(data)        *((int*)data)= val;
1468                         else            RNA_property_enum_set(ptr, prop, val);
1469
1470                         break;
1471                 }
1472                 case PROP_POINTER:
1473                 {
1474                         PyObject *value_new= NULL;
1475
1476                         StructRNA *ptr_type= RNA_property_pointer_type(ptr, prop);
1477                         int flag= RNA_property_flag(prop);
1478
1479                         /* this is really nasty!, so we can fake the operator having direct properties eg:
1480                          * layout.prop(self, "filepath")
1481                          * ... which infact should be
1482                          * layout.prop(self.properties, "filepath")
1483                          *
1484                          * we need to do this trick.
1485                          * if the prop is not an operator type and the pyobject is an operator, use its properties in place of its self.
1486                          *
1487                          * this is so bad that its almost a good reason to do away with fake 'self.properties -> self' class mixing
1488                          * if this causes problems in the future it should be removed.
1489                          */
1490                         if(     (ptr_type == &RNA_AnyType) &&
1491                                 (BPy_StructRNA_Check(value)) &&
1492                                 (RNA_struct_is_a(((BPy_StructRNA *)value)->ptr.type, &RNA_Operator))
1493                         ) {
1494                                 value= PyObject_GetAttrString(value, "properties");
1495                                 value_new= value;
1496                         }
1497
1498
1499                         /* if property is an OperatorProperties pointer and value is a map, forward back to pyrna_pydict_to_props */
1500                         if (RNA_struct_is_a(ptr_type, &RNA_OperatorProperties) && PyDict_Check(value)) {
1501                                 PointerRNA opptr= RNA_property_pointer_get(ptr, prop);
1502                                 return pyrna_pydict_to_props(&opptr, value, 0, error_prefix);
1503                         }
1504
1505                         /* another exception, allow to pass a collection as an RNA property */
1506                         if(Py_TYPE(value)==&pyrna_prop_collection_Type) { /* ok to ignore idprop collections */
1507                                 PointerRNA c_ptr;
1508                                 BPy_PropertyRNA *value_prop= (BPy_PropertyRNA *)value;
1509                                 if(RNA_property_collection_type_get(&value_prop->ptr, value_prop->prop, &c_ptr)) {
1510                                         value= pyrna_struct_CreatePyObject(&c_ptr);
1511                                         value_new= value;
1512                                 }
1513                                 else {
1514                                         PyErr_Format(PyExc_TypeError, "%.200s %.200s.%.200s collection has no type, cant be used as a %.200s type", error_prefix, RNA_struct_identifier(ptr->type), RNA_property_identifier(prop), RNA_struct_identifier(ptr_type));
1515                                         return -1;
1516                                 }
1517                         }
1518
1519                         if(!BPy_StructRNA_Check(value) && value != Py_None) {
1520                                 PyErr_Format(PyExc_TypeError, "%.200s %.200s.%.200s expected a %.200s type, not %.200s", error_prefix, RNA_struct_identifier(ptr->type), RNA_property_identifier(prop), RNA_struct_identifier(ptr_type), Py_TYPE(value)->tp_name);
1521                                 Py_XDECREF(value_new); return -1;
1522                         }
1523                         else if((flag & PROP_NEVER_NULL) && value == Py_None) {
1524                                 PyErr_Format(PyExc_TypeError, "%.200s %.200s.%.200s does not support a 'None' assignment %.200s type", error_prefix, RNA_struct_identifier(ptr->type), RNA_property_identifier(prop), RNA_struct_identifier(ptr_type));
1525                                 Py_XDECREF(value_new); return -1;
1526                         }
1527                         else if(value != Py_None && ((flag & PROP_ID_SELF_CHECK) && ptr->id.data == ((BPy_StructRNA*)value)->ptr.id.data)) {
1528                                 PyErr_Format(PyExc_TypeError, "%.200s %.200s.%.200s ID type does not support assignment to its self", error_prefix, RNA_struct_identifier(ptr->type), RNA_property_identifier(prop));
1529                                 Py_XDECREF(value_new); return -1;
1530                         }
1531                         else {
1532                                 BPy_StructRNA *param= (BPy_StructRNA*)value;
1533                                 int raise_error= FALSE;
1534                                 if(data) {
1535
1536                                         if(flag & PROP_RNAPTR) {
1537                                                 if(value == Py_None)
1538                                                         memset(data, 0, sizeof(PointerRNA));
1539                                                 else
1540                                                         *((PointerRNA*)data)= param->ptr;
1541                                         }
1542                                         else if(value == Py_None) {
1543                                                 *((void**)data)= NULL;
1544                                         }
1545                                         else if(RNA_struct_is_a(param->ptr.type, ptr_type)) {
1546                                                 *((void**)data)= param->ptr.data;
1547                                         }
1548                                         else {
1549                                                 raise_error= TRUE;
1550                                         }
1551                                 }
1552                                 else {
1553                                         /* data==NULL, assign to RNA */
1554                                         if(value == Py_None) {
1555                                                 PointerRNA valueptr= {{NULL}};
1556                                                 RNA_property_pointer_set(ptr, prop, valueptr);
1557                                         }
1558                                         else if(RNA_struct_is_a(param->ptr.type, ptr_type)) {
1559                                                 RNA_property_pointer_set(ptr, prop, param->ptr);
1560                                         }
1561                                         else {
1562                                                 PointerRNA tmp;
1563                                                 RNA_pointer_create(NULL, ptr_type, NULL, &tmp);
1564                                                 PyErr_Format(PyExc_TypeError, "%.200s %.200s.%.200s expected a %.200s type. not %.200s", error_prefix, RNA_struct_identifier(ptr->type), RNA_property_identifier(prop), RNA_struct_identifier(tmp.type), RNA_struct_identifier(param->ptr.type));
1565                                                 Py_XDECREF(value_new); return -1;
1566                                         }
1567                                 }
1568
1569                                 if(raise_error) {
1570                                         PointerRNA tmp;
1571                                         RNA_pointer_create(NULL, ptr_type, NULL, &tmp);
1572                                         PyErr_Format(PyExc_TypeError, "%.200s %.200s.%.200s expected a %.200s type, not %.200s", error_prefix, RNA_struct_identifier(ptr->type), RNA_property_identifier(prop), RNA_struct_identifier(tmp.type), RNA_struct_identifier(param->ptr.type));
1573                                         Py_XDECREF(value_new); return -1;
1574                                 }
1575                         }
1576
1577                         Py_XDECREF(value_new);
1578
1579                         break;
1580                 }
1581                 case PROP_COLLECTION:
1582                 {
1583                         int seq_len, i;
1584                         PyObject *item;
1585                         PointerRNA itemptr;
1586                         ListBase *lb;
1587                         CollectionPointerLink *link;
1588
1589                         lb= (data)? (ListBase*)data: NULL;
1590
1591                         /* convert a sequence of dict's into a collection */
1592                         if(!PySequence_Check(value)) {
1593                                 PyErr_Format(PyExc_TypeError, "%.200s %.200s.%.200s expected a sequence for an RNA collection, not %.200s", error_prefix, RNA_struct_identifier(ptr->type), RNA_property_identifier(prop), Py_TYPE(value)->tp_name);
1594                                 return -1;
1595                         }
1596
1597                         seq_len= PySequence_Size(value);
1598                         for(i=0; i<seq_len; i++) {
1599                                 item= PySequence_GetItem(value, i);
1600
1601                                 if(item==NULL) {
1602                                         PyErr_Format(PyExc_TypeError, "%.200s %.200s.%.200s failed to get sequence index '%d' for an RNA collection", error_prefix, RNA_struct_identifier(ptr->type), RNA_property_identifier(prop), i);
1603                                         Py_XDECREF(item);
1604                                         return -1;
1605                                 }
1606
1607                                 if(PyDict_Check(item)==0) {
1608                                         PyErr_Format(PyExc_TypeError, "%.200s %.200s.%.200s expected a each sequence member to be a dict for an RNA collection, not %.200s", error_prefix, RNA_struct_identifier(ptr->type), RNA_property_identifier(prop), Py_TYPE(item)->tp_name);
1609                                         Py_XDECREF(item);
1610                                         return -1;
1611                                 }
1612
1613                                 if(lb) {
1614                                         link= MEM_callocN(sizeof(CollectionPointerLink), "PyCollectionPointerLink");
1615                                         link->ptr= itemptr;
1616                                         BLI_addtail(lb, link);
1617                                 }
1618                                 else
1619                                         RNA_property_collection_add(ptr, prop, &itemptr);
1620
1621                                 if(pyrna_pydict_to_props(&itemptr, item, 1, "Converting a python list to an RNA collection")==-1) {
1622                                         PyObject *msg= PyC_ExceptionBuffer();
1623                                         const char *msg_char= _PyUnicode_AsString(msg);
1624
1625                                         PyErr_Format(PyExc_TypeError, "%.200s %.200s.%.200s error converting a member of a collection from a dicts into an RNA collection, failed with: %s", error_prefix, RNA_struct_identifier(ptr->type), RNA_property_identifier(prop), msg_char);
1626
1627                                         Py_DECREF(item);
1628                                         Py_DECREF(msg);
1629                                         return -1;
1630                                 }
1631                                 Py_DECREF(item);
1632                         }
1633
1634                         break;
1635                 }
1636                 default:
1637                         PyErr_Format(PyExc_AttributeError, "%.200s %.200s.%.200s unknown property type (pyrna_py_to_prop)", error_prefix, RNA_struct_identifier(ptr->type), RNA_property_identifier(prop));
1638                         return -1;
1639                         break;
1640                 }
1641         }
1642
1643         /* Run rna property functions */
1644         if(RNA_property_update_check(prop)) {
1645                 RNA_property_update(BPy_GetContext(), ptr, prop);
1646         }
1647
1648         return 0;
1649 }
1650
1651 static PyObject *pyrna_prop_array_to_py_index(BPy_PropertyArrayRNA *self, int index)
1652 {
1653         PYRNA_PROP_CHECK_OBJ((BPy_PropertyRNA *)self)
1654         return pyrna_py_from_array_index(self, &self->ptr, self->prop, index);
1655 }
1656
1657 static int pyrna_py_to_prop_array_index(BPy_PropertyArrayRNA *self, int index, PyObject *value)
1658 {
1659         int ret= 0;
1660         PointerRNA *ptr= &self->ptr;
1661         PropertyRNA *prop= self->prop;
1662
1663         const int totdim= RNA_property_array_dimension(ptr, prop, NULL);
1664
1665         if (totdim > 1) {
1666                 /* char error_str[512]; */
1667                 if (!pyrna_py_to_array_index(&self->ptr, self->prop, self->arraydim, self->arrayoffset, index, value, "")) {
1668                         /* PyErr_SetString(PyExc_AttributeError, error_str); */
1669                         ret= -1;
1670                 }
1671         }
1672         else {
1673                 /* see if we can coerce into a python type - PropertyType */
1674                 switch (RNA_property_type(prop)) {
1675                 case PROP_BOOLEAN:
1676                         {
1677                                 int param= PyLong_AsLong(value);
1678
1679                                 if(param < 0 || param > 1) {
1680                                         PyErr_SetString(PyExc_TypeError, "expected True/False or 0/1");
1681                                         ret= -1;
1682                                 }
1683                                 else {
1684                                         RNA_property_boolean_set_index(ptr, prop, index, param);
1685                                 }
1686                                 break;
1687                         }
1688                 case PROP_INT:
1689                         {
1690                                 int param= PyLong_AsLong(value);
1691                                 if (param==-1 && PyErr_Occurred()) {
1692                                         PyErr_SetString(PyExc_TypeError, "expected an int type");
1693                                         ret= -1;
1694                                 }
1695                                 else {
1696                                         RNA_property_int_clamp(ptr, prop, &param);
1697                                         RNA_property_int_set_index(ptr, prop, index, param);
1698                                 }
1699                                 break;
1700                         }
1701                 case PROP_FLOAT:
1702                         {
1703                                 float param= PyFloat_AsDouble(value);
1704                                 if (PyErr_Occurred()) {
1705                                         PyErr_SetString(PyExc_TypeError, "expected a float type");
1706                                         ret= -1;
1707                                 }
1708                                 else {
1709                                         RNA_property_float_clamp(ptr, prop, &param);
1710                                         RNA_property_float_set_index(ptr, prop, index, param);
1711                                 }
1712                                 break;
1713                         }
1714                 default:
1715                         PyErr_SetString(PyExc_AttributeError, "not an array type");
1716                         ret= -1;
1717                         break;
1718                 }
1719         }
1720
1721         /* Run rna property functions */
1722         if(RNA_property_update_check(prop)) {
1723                 RNA_property_update(BPy_GetContext(), ptr, prop);
1724         }
1725
1726         return ret;
1727 }
1728
1729 //---------------sequence-------------------------------------------
1730 static Py_ssize_t pyrna_prop_array_length(BPy_PropertyArrayRNA *self)
1731 {
1732         PYRNA_PROP_CHECK_INT((BPy_PropertyRNA *)self)
1733
1734         if (RNA_property_array_dimension(&self->ptr, self->prop, NULL) > 1)
1735                 return RNA_property_multi_array_length(&self->ptr, self->prop, self->arraydim);
1736         else
1737                 return RNA_property_array_length(&self->ptr, self->prop);
1738 }
1739
1740 static Py_ssize_t pyrna_prop_collection_length(BPy_PropertyRNA *self)
1741 {
1742         PYRNA_PROP_CHECK_INT(self)
1743
1744         return RNA_property_collection_length(&self->ptr, self->prop);
1745 }
1746
1747 /* bool functions are for speed, so we can avoid getting the length
1748  * of 1000's of items in a linked list for eg. */
1749 static int pyrna_prop_array_bool(BPy_PropertyRNA *self)
1750 {
1751         PYRNA_PROP_CHECK_INT(self)
1752
1753         return RNA_property_array_length(&self->ptr, self->prop) ? 1 : 0;
1754 }
1755
1756 static int pyrna_prop_collection_bool(BPy_PropertyRNA *self)
1757 {
1758         /* no callback defined, just iterate and find the nth item */
1759         CollectionPropertyIterator iter;
1760         int test;
1761
1762         PYRNA_PROP_CHECK_INT(self)
1763
1764         RNA_property_collection_begin(&self->ptr, self->prop, &iter);
1765         test= iter.valid;
1766         RNA_property_collection_end(&iter);
1767         return test;
1768 }
1769
1770 /* internal use only */
1771 static PyObject *pyrna_prop_collection_subscript_int(BPy_PropertyRNA *self, Py_ssize_t keynum)
1772 {
1773         PointerRNA newptr;
1774         Py_ssize_t keynum_abs= keynum;
1775
1776         PYRNA_PROP_CHECK_OBJ(self)
1777
1778         /* notice getting the length of the collection is avoided unless negative index is used
1779          * or to detect internal error with a valid index.
1780          * This is done for faster lookups. */
1781         if(keynum < 0) {
1782                 keynum_abs += RNA_property_collection_length(&self->ptr, self->prop);
1783
1784                 if(keynum_abs < 0) {
1785                         PyErr_Format(PyExc_IndexError, "bpy_prop_collection[%d]: out of range.", keynum);
1786                         return NULL;
1787                 }
1788         }
1789
1790         if(RNA_property_collection_lookup_int(&self->ptr, self->prop, keynum_abs, &newptr)) {
1791                 return pyrna_struct_CreatePyObject(&newptr);
1792         }
1793         else {
1794                 const int len= RNA_property_collection_length(&self->ptr, self->prop);
1795                 if(keynum_abs >= len) {
1796                         PyErr_Format(PyExc_IndexError, "bpy_prop_collection[index]: index %d out of range, size %d", keynum, len);
1797                 }
1798                 else {
1799                         PyErr_Format(PyExc_RuntimeError, "bpy_prop_collection[index]: internal error, valid index %d given in %d sized collection but value not found", keynum_abs, len);
1800                 }
1801
1802                 return NULL;
1803         }
1804 }
1805
1806 static PyObject *pyrna_prop_array_subscript_int(BPy_PropertyArrayRNA *self, int keynum)
1807 {
1808         int len;
1809
1810         PYRNA_PROP_CHECK_OBJ((BPy_PropertyRNA *)self)
1811
1812         len= pyrna_prop_array_length(self);
1813
1814         if(keynum < 0) keynum += len;
1815
1816         if(keynum >= 0 && keynum < len)
1817                 return pyrna_prop_array_to_py_index(self, keynum);
1818
1819         PyErr_Format(PyExc_IndexError, "bpy_prop_array[index]: index %d out of range", keynum);
1820         return NULL;
1821 }
1822
1823 static PyObject *pyrna_prop_collection_subscript_str(BPy_PropertyRNA *self, const char *keyname)
1824 {
1825         PointerRNA newptr;
1826
1827         PYRNA_PROP_CHECK_OBJ(self)
1828
1829         if(RNA_property_collection_lookup_string(&self->ptr, self->prop, keyname, &newptr))
1830                 return pyrna_struct_CreatePyObject(&newptr);
1831
1832         PyErr_Format(PyExc_KeyError, "bpy_prop_collection[key]: key \"%.200s\" not found", keyname);
1833         return NULL;
1834 }
1835 /* static PyObject *pyrna_prop_array_subscript_str(BPy_PropertyRNA *self, char *keyname) */
1836
1837 static PyObject *pyrna_prop_collection_subscript_slice(BPy_PropertyRNA *self, Py_ssize_t start, Py_ssize_t stop)
1838 {
1839         CollectionPropertyIterator rna_macro_iter;
1840         int count= 0;
1841
1842         PyObject *list;
1843         PyObject *item;
1844
1845         PYRNA_PROP_CHECK_OBJ(self)
1846
1847         list= PyList_New(0);
1848
1849         /* first loop up-until the start */
1850         for(RNA_property_collection_begin(&self->ptr, self->prop, &rna_macro_iter); rna_macro_iter.valid; RNA_property_collection_next(&rna_macro_iter)) {
1851                 /* PointerRNA itemptr= rna_macro_iter.ptr; */
1852                 if(count == start) {
1853                         break;
1854                 }
1855                 count++;
1856         }
1857
1858         /* add items until stop */
1859         for(; rna_macro_iter.valid; RNA_property_collection_next(&rna_macro_iter)) {
1860                 item= pyrna_struct_CreatePyObject(&rna_macro_iter.ptr);
1861                 PyList_Append(list, item);
1862                 Py_DECREF(item);
1863
1864                 count++;
1865                 if(count == stop) {
1866                         break;
1867                 }
1868         }
1869
1870         RNA_property_collection_end(&rna_macro_iter);
1871
1872         return list;
1873 }
1874
1875 /* TODO - dimensions
1876  * note: could also use pyrna_prop_array_to_py_index(self, count) in a loop but its a lot slower
1877  * since at the moment it reads (and even allocates) the entire array for each index.
1878  */
1879 static PyObject *pyrna_prop_array_subscript_slice(BPy_PropertyArrayRNA *self, PointerRNA *ptr, PropertyRNA *prop, Py_ssize_t start, Py_ssize_t stop, Py_ssize_t length)
1880 {
1881         int count, totdim;
1882         PyObject *tuple;
1883
1884         PYRNA_PROP_CHECK_OBJ((BPy_PropertyRNA *)self)
1885
1886         tuple= PyTuple_New(stop - start);
1887
1888         /* PYRNA_PROP_CHECK_OBJ(self) isn't needed, internal use only */
1889
1890         totdim= RNA_property_array_dimension(ptr, prop, NULL);
1891
1892         if (totdim > 1) {
1893                 for (count= start; count < stop; count++)
1894                         PyTuple_SET_ITEM(tuple, count - start, pyrna_prop_array_to_py_index(self, count));
1895         }
1896         else {
1897                 switch (RNA_property_type(prop)) {
1898                 case PROP_FLOAT:
1899                         {
1900                                 float values_stack[PYRNA_STACK_ARRAY];
1901                                 float *values;
1902                                 if(length > PYRNA_STACK_ARRAY)  {       values= PyMem_MALLOC(sizeof(float) * length); }
1903                                 else                                                    {       values= values_stack; }
1904                                 RNA_property_float_get_array(ptr, prop, values);
1905
1906                                 for(count=start; count<stop; count++)
1907                                         PyTuple_SET_ITEM(tuple, count-start, PyFloat_FromDouble(values[count]));
1908
1909                                 if(values != values_stack) {
1910                                         PyMem_FREE(values);
1911                                 }
1912                                 break;
1913                         }
1914                 case PROP_BOOLEAN:
1915                         {
1916                                 int values_stack[PYRNA_STACK_ARRAY];
1917                                 int *values;
1918                                 if(length > PYRNA_STACK_ARRAY)  {       values= PyMem_MALLOC(sizeof(int) * length); }
1919                                 else                                                    {       values= values_stack; }
1920
1921                                 RNA_property_boolean_get_array(ptr, prop, values);
1922                                 for(count=start; count<stop; count++)
1923                                         PyTuple_SET_ITEM(tuple, count-start, PyBool_FromLong(values[count]));
1924
1925                                 if(values != values_stack) {
1926                                         PyMem_FREE(values);
1927                                 }
1928                                 break;
1929                         }
1930                 case PROP_INT:
1931                         {
1932                                 int values_stack[PYRNA_STACK_ARRAY];
1933                                 int *values;
1934                                 if(length > PYRNA_STACK_ARRAY)  {       values= PyMem_MALLOC(sizeof(int) * length); }
1935                                 else                                                    {       values= values_stack; }
1936
1937                                 RNA_property_int_get_array(ptr, prop, values);
1938                                 for(count=start; count<stop; count++)
1939                                         PyTuple_SET_ITEM(tuple, count-start, PyLong_FromSsize_t(values[count]));
1940
1941                                 if(values != values_stack) {
1942                                         PyMem_FREE(values);
1943                                 }
1944                                 break;
1945                         }
1946                 default:
1947                         BLI_assert(!"Invalid array type");
1948
1949                         PyErr_SetString(PyExc_TypeError, "not an array type");
1950                         Py_DECREF(tuple);
1951                         tuple= NULL;
1952                 }
1953         }
1954         return tuple;
1955 }
1956
1957 static PyObject *pyrna_prop_collection_subscript(BPy_PropertyRNA *self, PyObject *key)
1958 {
1959         PYRNA_PROP_CHECK_OBJ(self)
1960
1961         if (PyUnicode_Check(key)) {
1962                 return pyrna_prop_collection_subscript_str(self, _PyUnicode_AsString(key));
1963         }
1964         else if (PyIndex_Check(key)) {
1965                 Py_ssize_t i= PyNumber_AsSsize_t(key, PyExc_IndexError);
1966                 if (i == -1 && PyErr_Occurred())
1967                         return NULL;
1968
1969                 return pyrna_prop_collection_subscript_int(self, i);
1970         }
1971         else if (PySlice_Check(key)) {
1972                 PySliceObject *key_slice= (PySliceObject *)key;
1973                 Py_ssize_t step= 1;
1974
1975                 if(key_slice->step != Py_None && !_PyEval_SliceIndex(key, &step)) {
1976                         return NULL;
1977                 }
1978                 else if (step != 1) {
1979                         PyErr_SetString(PyExc_TypeError, "bpy_prop_collection[slice]: slice steps not supported");
1980                         return NULL;
1981                 }
1982                 else if(key_slice->start == Py_None && key_slice->stop == Py_None) {
1983                         return pyrna_prop_collection_subscript_slice(self, 0, PY_SSIZE_T_MAX);
1984                 }
1985                 else {
1986                         Py_ssize_t start= 0, stop= PY_SSIZE_T_MAX;
1987
1988                         /* avoid PySlice_GetIndicesEx because it needs to know the length ahead of time. */
1989                         if(key_slice->start != Py_None && !_PyEval_SliceIndex(key_slice->start, &start))        return NULL;
1990                         if(key_slice->stop != Py_None && !_PyEval_SliceIndex(key_slice->stop, &stop))           return NULL;
1991
1992                         if(start < 0 || stop < 0) {
1993                                 /* only get the length for negative values */
1994                                 Py_ssize_t len= (Py_ssize_t)RNA_property_collection_length(&self->ptr, self->prop);
1995                                 if(start < 0) start += len;
1996                                 if(stop < 0) start += len;
1997                         }
1998
1999                         if (stop - start <= 0) {
2000                                 return PyList_New(0);
2001                         }
2002                         else {
2003                                 return pyrna_prop_collection_subscript_slice(self, start, stop);
2004                         }
2005                 }
2006         }
2007         else {
2008                 PyErr_Format(PyExc_TypeError, "bpy_prop_collection[key]: invalid key, must be a string or an int, not %.200s", Py_TYPE(key)->tp_name);
2009                 return NULL;
2010         }
2011 }
2012
2013 static PyObject *pyrna_prop_array_subscript(BPy_PropertyArrayRNA *self, PyObject *key)
2014 {
2015         PYRNA_PROP_CHECK_OBJ((BPy_PropertyRNA *)self)
2016
2017         /*if (PyUnicode_Check(key)) {
2018                 return pyrna_prop_array_subscript_str(self, _PyUnicode_AsString(key));
2019         }
2020         else */
2021         if (PyIndex_Check(key)) {
2022                 Py_ssize_t i= PyNumber_AsSsize_t(key, PyExc_IndexError);
2023                 if (i == -1 && PyErr_Occurred())
2024                         return NULL;
2025                 return pyrna_prop_array_subscript_int(self, PyLong_AsLong(key));
2026         }
2027         else if (PySlice_Check(key)) {
2028                 Py_ssize_t step= 1;
2029                 PySliceObject *key_slice= (PySliceObject *)key;
2030
2031                 if(key_slice->step != Py_None && !_PyEval_SliceIndex(key, &step)) {
2032                         return NULL;
2033                 }
2034                 else if (step != 1) {
2035                         PyErr_SetString(PyExc_TypeError, "bpy_prop_array[slice]: slice steps not supported");
2036                         return NULL;
2037                 }
2038                 else if(key_slice->start == Py_None && key_slice->stop == Py_None) {
2039                         /* note, no significant advantage with optimizing [:] slice as with collections but include here for consistency with collection slice func */
2040                         Py_ssize_t len= (Py_ssize_t)pyrna_prop_array_length(self);
2041                         return pyrna_prop_array_subscript_slice(self, &self->ptr, self->prop, 0, len, len);
2042                 }
2043                 else {
2044                         int len= pyrna_prop_array_length(self);
2045                         Py_ssize_t start, stop, slicelength;
2046
2047                         if (PySlice_GetIndicesEx((void *)key, len, &start, &stop, &step, &slicelength) < 0)
2048                                 return NULL;
2049
2050                         if (slicelength <= 0) {
2051                                 return PyTuple_New(0);
2052                         }
2053                         else {
2054                                 return pyrna_prop_array_subscript_slice(self, &self->ptr, self->prop, start, stop, len);
2055                         }
2056                 }
2057         }
2058         else {
2059                 PyErr_SetString(PyExc_AttributeError, "bpy_prop_array[key]: invalid key, key must be an int");
2060                 return NULL;
2061         }
2062 }
2063
2064 /* could call (pyrna_py_to_prop_array_index(self, i, value) in a loop but it is slow */
2065 static int prop_subscript_ass_array_slice(PointerRNA *ptr, PropertyRNA *prop, int start, int stop, int length, PyObject *value_orig)
2066 {
2067         PyObject *value;
2068         int count;
2069         void *values_alloc= NULL;
2070         int ret= 0;
2071
2072         if(value_orig == NULL) {
2073                 PyErr_SetString(PyExc_TypeError, "bpy_prop_array[slice]= value: deleting with list types is not supported by bpy_struct");
2074                 return -1;
2075         }
2076
2077         if(!(value=PySequence_Fast(value_orig, "bpy_prop_array[slice]= value: assignment is not a sequence type"))) {
2078                 return -1;
2079         }
2080
2081         if(PySequence_Fast_GET_SIZE(value) != stop-start) {
2082                 Py_DECREF(value);
2083                 PyErr_SetString(PyExc_TypeError, "bpy_prop_array[slice]= value: resizing bpy_struct arrays isn't supported");
2084                 return -1;
2085         }
2086
2087         switch (RNA_property_type(prop)) {
2088                 case PROP_FLOAT:
2089                 {
2090                         float values_stack[PYRNA_STACK_ARRAY];
2091                         float *values, fval;
2092
2093                         float min, max;
2094                         RNA_property_float_range(ptr, prop, &min, &max);
2095
2096                         if(length > PYRNA_STACK_ARRAY)  {       values= values_alloc= PyMem_MALLOC(sizeof(float) * length); }
2097                         else                                                    {       values= values_stack; }
2098                         if(start != 0 || stop != length) /* partial assignment? - need to get the array */
2099                                 RNA_property_float_get_array(ptr, prop, values);
2100
2101                         for(count=start; count<stop; count++) {
2102                                 fval= PyFloat_AsDouble(PySequence_Fast_GET_ITEM(value, count-start));
2103                                 CLAMP(fval, min, max);
2104                                 values[count]= fval;
2105                         }
2106
2107                         if(PyErr_Occurred())    ret= -1;
2108                         else                                    RNA_property_float_set_array(ptr, prop, values);
2109                         break;
2110                 }
2111                 case PROP_BOOLEAN:
2112                 {
2113                         int values_stack[PYRNA_STACK_ARRAY];
2114                         int *values;
2115                         if(length > PYRNA_STACK_ARRAY)  {       values= values_alloc= PyMem_MALLOC(sizeof(int) * length); }
2116                         else                                                    {       values= values_stack; }
2117
2118                         if(start != 0 || stop != length) /* partial assignment? - need to get the array */
2119                                 RNA_property_boolean_get_array(ptr, prop, values);
2120
2121                         for(count=start; count<stop; count++)
2122                                 values[count]= PyLong_AsLong(PySequence_Fast_GET_ITEM(value, count-start));
2123
2124                         if(PyErr_Occurred())    ret= -1;
2125                         else                                    RNA_property_boolean_set_array(ptr, prop, values);
2126                         break;
2127                 }
2128                 case PROP_INT:
2129                 {
2130                         int values_stack[PYRNA_STACK_ARRAY];
2131                         int *values, ival;
2132
2133                         int min, max;
2134                         RNA_property_int_range(ptr, prop, &min, &max);
2135
2136                         if(length > PYRNA_STACK_ARRAY)  {       values= values_alloc= PyMem_MALLOC(sizeof(int) * length); }
2137                         else                                                    {       values= values_stack; }
2138
2139                         if(start != 0 || stop != length) /* partial assignment? - need to get the array */
2140                                 RNA_property_int_get_array(ptr, prop, values);
2141
2142                         for(count=start; count<stop; count++) {
2143                                 ival= PyLong_AsLong(PySequence_Fast_GET_ITEM(value, count-start));
2144                                 CLAMP(ival, min, max);
2145                                 values[count]= ival;
2146                         }
2147
2148                         if(PyErr_Occurred())    ret= -1;
2149                         else                                    RNA_property_int_set_array(ptr, prop, values);
2150                         break;
2151                 }
2152                 default:
2153                         PyErr_SetString(PyExc_TypeError, "not an array type");
2154                         ret= -1;
2155         }
2156
2157         Py_DECREF(value);
2158
2159         if(values_alloc) {
2160                 PyMem_FREE(values_alloc);
2161         }
2162
2163         return ret;
2164
2165 }
2166
2167 static int prop_subscript_ass_array_int(BPy_PropertyArrayRNA *self, Py_ssize_t keynum, PyObject *value)
2168 {
2169         int len;
2170
2171         PYRNA_PROP_CHECK_INT((BPy_PropertyRNA *)self)
2172
2173         len= pyrna_prop_array_length(self);
2174
2175         if(keynum < 0) keynum += len;
2176
2177         if(keynum >= 0 && keynum < len)
2178                 return pyrna_py_to_prop_array_index(self, keynum, value);
2179
2180         PyErr_SetString(PyExc_IndexError, "bpy_prop_array[index] = value: index out of range");
2181         return -1;
2182 }
2183
2184 static int pyrna_prop_array_ass_subscript(BPy_PropertyArrayRNA *self, PyObject *key, PyObject *value)
2185 {
2186         /* char *keyname= NULL; */ /* not supported yet */
2187         int ret= -1;
2188
2189         PYRNA_PROP_CHECK_INT((BPy_PropertyRNA *)self)
2190
2191         if (!RNA_property_editable_flag(&self->ptr, self->prop)) {
2192                 PyErr_Format(PyExc_AttributeError, "bpy_prop_collection: attribute \"%.200s\" from \"%.200s\" is read-only", RNA_property_identifier(self->prop), RNA_struct_identifier(self->ptr.type));
2193                 ret= -1;
2194         }
2195
2196         else if (PyIndex_Check(key)) {
2197                 Py_ssize_t i= PyNumber_AsSsize_t(key, PyExc_IndexError);
2198                 if (i == -1 && PyErr_Occurred()) {
2199                         ret= -1;
2200                 }
2201                 else {
2202                         ret= prop_subscript_ass_array_int(self, i, value);
2203                 }
2204         }
2205         else if (PySlice_Check(key)) {
2206                 int len= RNA_property_array_length(&self->ptr, self->prop);
2207                 Py_ssize_t start, stop, step, slicelength;
2208
2209                 if (PySlice_GetIndicesEx((void *)key, len, &start, &stop, &step, &slicelength) < 0) {
2210                         ret= -1;
2211                 }
2212                 else if (slicelength <= 0) {
2213                         ret= 0; /* do nothing */
2214                 }
2215                 else if (step == 1) {
2216                         ret= prop_subscript_ass_array_slice(&self->ptr, self->prop, start, stop, len, value);
2217                 }
2218                 else {
2219                         PyErr_SetString(PyExc_TypeError, "slice steps not supported with rna");
2220                         ret= -1;
2221                 }
2222         }
2223         else {
2224                 PyErr_SetString(PyExc_AttributeError, "invalid key, key must be an int");
2225                 ret= -1;
2226         }
2227
2228         if(ret != -1) {
2229                 if(RNA_property_update_check(self->prop)) {
2230                         RNA_property_update(BPy_GetContext(), &self->ptr, self->prop);
2231                 }
2232         }
2233
2234         return ret;
2235 }
2236
2237 /* for slice only */
2238 static PyMappingMethods pyrna_prop_array_as_mapping= {
2239         (lenfunc) pyrna_prop_array_length,      /* mp_length */
2240         (binaryfunc) pyrna_prop_array_subscript,        /* mp_subscript */
2241         (objobjargproc) pyrna_prop_array_ass_subscript, /* mp_ass_subscript */
2242 };
2243
2244 static PyMappingMethods pyrna_prop_collection_as_mapping= {
2245         (lenfunc) pyrna_prop_collection_length, /* mp_length */
2246         (binaryfunc) pyrna_prop_collection_subscript,   /* mp_subscript */
2247         (objobjargproc) NULL,   /* mp_ass_subscript */
2248 };
2249
2250 /* only for fast bool's, large structs, assign nb_bool on init */
2251 static PyNumberMethods pyrna_prop_array_as_number= {
2252         NULL, /* nb_add */
2253         NULL, /* nb_subtract */
2254         NULL, /* nb_multiply */
2255         NULL, /* nb_remainder */
2256         NULL, /* nb_divmod */
2257         NULL, /* nb_power */
2258         NULL, /* nb_negative */
2259         NULL, /* nb_positive */
2260         NULL, /* nb_absolute */
2261         (inquiry) pyrna_prop_array_bool, /* nb_bool */
2262 };
2263 static PyNumberMethods pyrna_prop_collection_as_number= {
2264         NULL, /* nb_add */
2265         NULL, /* nb_subtract */
2266         NULL, /* nb_multiply */
2267         NULL, /* nb_remainder */
2268         NULL, /* nb_divmod */
2269         NULL, /* nb_power */
2270         NULL, /* nb_negative */
2271         NULL, /* nb_positive */
2272         NULL, /* nb_absolute */
2273         (inquiry) pyrna_prop_collection_bool, /* nb_bool */
2274 };
2275
2276 static int pyrna_prop_array_contains(BPy_PropertyRNA *self, PyObject *value)
2277 {
2278         return pyrna_array_contains_py(&self->ptr, self->prop, value);
2279 }
2280
2281 static int pyrna_prop_collection_contains(BPy_PropertyRNA *self, PyObject *value)
2282 {
2283         PointerRNA newptr; /* not used, just so RNA_property_collection_lookup_string runs */
2284
2285         /* key in dict style check */
2286         const char *keyname= _PyUnicode_AsString(value);
2287
2288         if(keyname==NULL) {
2289                 PyErr_SetString(PyExc_TypeError, "bpy_prop_collection.__contains__: expected a string");
2290                 return -1;
2291         }
2292
2293         if (RNA_property_collection_lookup_string(&self->ptr, self->prop, keyname, &newptr))
2294                 return 1;
2295
2296         return 0;
2297 }
2298
2299 static int pyrna_struct_contains(BPy_StructRNA *self, PyObject *value)
2300 {
2301         IDProperty *group;
2302         const char *name= _PyUnicode_AsString(value);
2303
2304         PYRNA_STRUCT_CHECK_INT(self)
2305
2306         if (!name) {
2307                 PyErr_SetString(PyExc_TypeError, "bpy_struct.__contains__: expected a string");
2308                 return -1;
2309         }
2310
2311         if(RNA_struct_idprops_check(self->ptr.type)==0) {
2312                 PyErr_SetString(PyExc_TypeError, "bpy_struct: this type doesn't support IDProperties");
2313                 return -1;
2314         }
2315
2316         group= RNA_struct_idprops(&self->ptr, 0);
2317
2318         if(!group)
2319                 return 0;
2320
2321         return IDP_GetPropertyFromGroup(group, name) ? 1:0;
2322 }
2323
2324 static PySequenceMethods pyrna_prop_array_as_sequence= {
2325         (lenfunc)pyrna_prop_array_length,               /* Cant set the len otherwise it can evaluate as false */
2326         NULL,           /* sq_concat */
2327         NULL,           /* sq_repeat */
2328         (ssizeargfunc)pyrna_prop_array_subscript_int, /* sq_item */ /* Only set this so PySequence_Check() returns True */
2329         NULL,           /* sq_slice */
2330         (ssizeobjargproc)prop_subscript_ass_array_int,          /* sq_ass_item */
2331         NULL,           /* *was* sq_ass_slice */
2332         (objobjproc)pyrna_prop_array_contains,  /* sq_contains */
2333         (binaryfunc) NULL, /* sq_inplace_concat */
2334         (ssizeargfunc) NULL, /* sq_inplace_repeat */
2335 };
2336
2337 static PySequenceMethods pyrna_prop_collection_as_sequence= {
2338         (lenfunc)pyrna_prop_collection_length,          /* Cant set the len otherwise it can evaluate as false */
2339         NULL,           /* sq_concat */
2340         NULL,           /* sq_repeat */
2341         (ssizeargfunc)pyrna_prop_collection_subscript_int, /* sq_item */ /* Only set this so PySequence_Check() returns True */
2342         NULL,           /* *was* sq_slice */
2343         NULL,           /* sq_ass_item */
2344         NULL,           /* *was* sq_ass_slice */
2345         (objobjproc)pyrna_prop_collection_contains,     /* sq_contains */
2346         (binaryfunc) NULL, /* sq_inplace_concat */
2347         (ssizeargfunc) NULL, /* sq_inplace_repeat */
2348 };
2349
2350 static PySequenceMethods pyrna_struct_as_sequence= {
2351         NULL,           /* Cant set the len otherwise it can evaluate as false */
2352         NULL,           /* sq_concat */
2353         NULL,           /* sq_repeat */
2354         NULL,           /* sq_item */ /* Only set this so PySequence_Check() returns True */
2355         NULL,           /* *was* sq_slice */
2356         NULL,           /* sq_ass_item */
2357         NULL,           /* *was* sq_ass_slice */
2358         (objobjproc)pyrna_struct_contains,      /* sq_contains */
2359         (binaryfunc) NULL, /* sq_inplace_concat */
2360         (ssizeargfunc) NULL, /* sq_inplace_repeat */
2361 };
2362
2363 static PyObject *pyrna_struct_subscript(BPy_StructRNA *self, PyObject *key)
2364 {
2365         /* mostly copied from BPy_IDGroup_Map_GetItem */
2366         IDProperty *group, *idprop;
2367         const char *name= _PyUnicode_AsString(key);
2368
2369         PYRNA_STRUCT_CHECK_OBJ(self)
2370
2371         if(RNA_struct_idprops_check(self->ptr.type)==0) {
2372                 PyErr_SetString(PyExc_TypeError, "this type doesn't support IDProperties");
2373                 return NULL;
2374         }
2375
2376         if(name==NULL) {
2377                 PyErr_SetString(PyExc_TypeError, "bpy_struct[key]: only strings are allowed as keys of ID properties");
2378                 return NULL;
2379         }
2380
2381         group= RNA_struct_idprops(&self->ptr, 0);
2382
2383         if(group==NULL) {
2384                 PyErr_Format(PyExc_KeyError, "bpy_struct[key]: key \"%s\" not found", name);
2385                 return NULL;
2386         }
2387
2388         idprop= IDP_GetPropertyFromGroup(group, name);
2389
2390         if(idprop==NULL) {
2391                 PyErr_Format(PyExc_KeyError, "bpy_struct[key]: key \"%s\" not found", name);
2392                 return NULL;
2393         }
2394
2395         return BPy_IDGroup_WrapData(self->ptr.id.data, idprop);
2396 }
2397
2398 static int pyrna_struct_ass_subscript(BPy_StructRNA *self, PyObject *key, PyObject *value)
2399 {
2400         IDProperty *group;
2401
2402         PYRNA_STRUCT_CHECK_INT(self)
2403
2404         group= RNA_struct_idprops(&self->ptr, 1);
2405
2406 #ifdef USE_PEDANTIC_WRITE
2407         if(rna_disallow_writes && rna_id_write_error(&self->ptr, key)) {
2408                 return -1;
2409         }
2410 #endif // USE_STRING_COERCE
2411
2412         if(group==NULL) {
2413                 PyErr_SetString(PyExc_TypeError, "bpy_struct[key]= val: id properties not supported for this type");
2414                 return -1;
2415         }
2416
2417         return BPy_Wrap_SetMapItem(group, key, value);
2418 }
2419
2420 static PyMappingMethods pyrna_struct_as_mapping= {
2421         (lenfunc) NULL, /* mp_length */
2422         (binaryfunc) pyrna_struct_subscript,    /* mp_subscript */
2423         (objobjargproc) pyrna_struct_ass_subscript,     /* mp_ass_subscript */
2424 };
2425
2426 static char pyrna_struct_keys_doc[] =
2427 ".. method:: keys()\n"
2428 "\n"
2429 "   Returns the keys of this objects custom properties (matches pythons dictionary function of the same name).\n"
2430 "\n"
2431 "   :return: custom property keys.\n"
2432 "   :rtype: list of strings\n"
2433 "\n"
2434 "   .. note:: Only :class:`ID`, :class:`Bone` and :class:`PoseBone` classes support custom properties.\n";
2435
2436 static PyObject *pyrna_struct_keys(BPy_PropertyRNA *self)
2437 {
2438         IDProperty *group;
2439
2440         if(RNA_struct_idprops_check(self->ptr.type)==0) {
2441                 PyErr_SetString(PyExc_TypeError, "bpy_struct.keys(): this type doesn't support IDProperties");
2442                 return NULL;
2443         }
2444
2445         group= RNA_struct_idprops(&self->ptr, 0);
2446
2447         if(group==NULL)
2448                 return PyList_New(0);
2449
2450         return BPy_Wrap_GetKeys(group);
2451 }
2452
2453 static char pyrna_struct_items_doc[] =
2454 ".. method:: items()\n"
2455 "\n"
2456 "   Returns the items of this objects custom properties (matches pythons dictionary function of the same name).\n"
2457 "\n"
2458 "   :return: custom property key, value pairs.\n"
2459 "   :rtype: list of key, value tuples\n"
2460 "\n"
2461 "   .. note:: Only :class:`ID`, :class:`Bone` and :class:`PoseBone` classes support custom properties.\n";
2462
2463 static PyObject *pyrna_struct_items(BPy_PropertyRNA *self)
2464 {
2465         IDProperty *group;
2466
2467         if(RNA_struct_idprops_check(self->ptr.type)==0) {
2468                 PyErr_SetString(PyExc_TypeError, "bpy_struct.items(): this type doesn't support IDProperties");
2469                 return NULL;
2470         }
2471
2472         group= RNA_struct_idprops(&self->ptr, 0);
2473
2474         if(group==NULL)
2475                 return PyList_New(0);
2476
2477         return BPy_Wrap_GetItems(self->ptr.id.data, group);
2478 }
2479
2480 static char pyrna_struct_values_doc[] =
2481 ".. method:: values()\n"
2482 "\n"
2483 "   Returns the values of this objects custom properties (matches pythons dictionary function of the same name).\n"
2484 "\n"
2485 "   :return: custom property values.\n"
2486 "   :rtype: list\n"
2487 "\n"
2488 "   .. note:: Only :class:`ID`, :class:`Bone` and :class:`PoseBone` classes support custom properties.\n";
2489
2490 static PyObject *pyrna_struct_values(BPy_PropertyRNA *self)
2491 {
2492         IDProperty *group;
2493
2494         if(RNA_struct_idprops_check(self->ptr.type)==0) {
2495                 PyErr_SetString(PyExc_TypeError, "bpy_struct.values(): this type doesn't support IDProperties");
2496                 return NULL;
2497         }
2498
2499         group= RNA_struct_idprops(&self->ptr, 0);
2500
2501         if(group==NULL)
2502                 return PyList_New(0);
2503
2504         return BPy_Wrap_GetValues(self->ptr.id.data, group);
2505 }
2506
2507
2508 static char pyrna_struct_is_property_set_doc[] =
2509 ".. method:: is_property_set(property)\n"
2510 "\n"
2511 "   Check if a property is set, use for testing operator properties.\n"
2512 "\n"
2513 "   :return: True when the property has been set.\n"
2514 "   :rtype: boolean\n"
2515 ;
2516 static PyObject *pyrna_struct_is_property_set(BPy_StructRNA *self, PyObject *args)
2517 {
2518         PropertyRNA *prop;
2519         const char *name;
2520         int ret;
2521
2522         PYRNA_STRUCT_CHECK_OBJ(self)
2523
2524         if (!PyArg_ParseTuple(args, "s:is_property_set", &name))
2525                 return NULL;
2526
2527         if((prop= RNA_struct_find_property(&self->ptr, name)) == NULL) {
2528                 PyErr_Format(PyExc_TypeError, "%.200s.is_property_set(\"%.200s\") not found", RNA_struct_identifier(self->ptr.type), name);
2529                 return NULL;
2530         }
2531
2532         /* double property lookup, could speed up */
2533         /* return PyBool_FromLong(RNA_property_is_set(&self->ptr, name)); */
2534         if(RNA_property_flag(prop) & PROP_IDPROPERTY) {
2535                 IDProperty *group= RNA_struct_idprops(&self->ptr, 0);
2536                 if(group) {
2537                         ret= IDP_GetPropertyFromGroup(group, name) ? 1:0;
2538                 }
2539                 else {
2540                         ret= 0;
2541                 }
2542         }
2543         else {
2544                 ret= 1;
2545         }
2546
2547         return PyBool_FromLong(ret);
2548 }
2549
2550 static char pyrna_struct_is_property_hidden_doc[] =
2551 ".. method:: is_property_hidden(property)\n"
2552 "\n"
2553 "   Check if a property is hidden.\n"
2554 "\n"
2555 "   :return: True when the property is hidden.\n"
2556 "   :rtype: boolean\n"
2557 ;
2558 static PyObject *pyrna_struct_is_property_hidden(BPy_StructRNA *self, PyObject *args)
2559 {
2560         PropertyRNA *prop;
2561         const char *name;
2562
2563         PYRNA_STRUCT_CHECK_OBJ(self)
2564
2565         if (!PyArg_ParseTuple(args, "s:is_property_hidden", &name))
2566                 return NULL;
2567
2568         if((prop= RNA_struct_find_property(&self->ptr, name)) == NULL) {
2569                 PyErr_Format(PyExc_TypeError, "%.200s.is_property_hidden(\"%.200s\") not found", RNA_struct_identifier(self->ptr.type), name);
2570                 return NULL;
2571         }
2572
2573         return PyBool_FromLong(RNA_property_flag(prop) & PROP_HIDDEN);
2574 }
2575
2576 static char pyrna_struct_path_resolve_doc[] =
2577 ".. method:: path_resolve(path, coerce=True)\n"
2578 "\n"
2579 "   Returns the property from the path, raise an exception when not found.\n"
2580 "\n"
2581 "   :arg path: path which this property resolves.\n"
2582 "   :type path: string\n"
2583 "   :arg coerce: optional argument, when True, the property will be converted into its python representation.\n"
2584 "   :type coerce: boolean\n"
2585 ;
2586 static PyObject *pyrna_struct_path_resolve(BPy_StructRNA *self, PyObject *args)
2587 {
2588         const char *path;
2589         PyObject *coerce= Py_True;
2590         PointerRNA r_ptr;
2591         PropertyRNA *r_prop;
2592         int index= -1;
2593
2594         PYRNA_STRUCT_CHECK_OBJ(self)
2595
2596         if (!PyArg_ParseTuple(args, "s|O!:path_resolve", &path, &PyBool_Type, &coerce))
2597                 return NULL;
2598
2599         if (RNA_path_resolve_full(&self->ptr, path, &r_ptr, &r_prop, &index)) {
2600                 if(r_prop) {
2601                         if(index != -1) {
2602                                 if(index >= RNA_property_array_length(&r_ptr, r_prop) || index < 0) {
2603                                         PyErr_Format(PyExc_TypeError, "%.200s.path_resolve(\"%.200s\") index out of range", RNA_struct_identifier(self->ptr.type), path);
2604                                         return NULL;
2605                                 }
2606                                 else {
2607                                         return pyrna_array_index(&r_ptr, r_prop, index);
2608                                 }
2609                         }
2610                         else {
2611                                 if(coerce == Py_False) {
2612                                         return pyrna_prop_CreatePyObject(&r_ptr, r_prop);
2613                                 }
2614                                 else {
2615                                         return pyrna_prop_to_py(&r_ptr, r_prop);
2616                                 }
2617                         }
2618                 }
2619                 else {
2620                         return pyrna_struct_CreatePyObject(&r_ptr);
2621                 }
2622         }
2623         else {
2624                 PyErr_Format(PyExc_TypeError, "%.200s.path_resolve(\"%.200s\") could not be resolved", RNA_struct_identifier(self->ptr.type), path);
2625                 return NULL;
2626         }
2627 }
2628
2629 static char pyrna_struct_path_from_id_doc[] =
2630 ".. method:: path_from_id(property=\"\")\n"
2631 "\n"
2632 "   Returns the data path from the ID to this object (string).\n"
2633 "\n"
2634 "   :arg property: Optional property name which can be used if the path is to a property of this object.\n"
2635 "   :type property: string\n"
2636 "   :return: The path from :class:`bpy_struct.id_data` to this struct and property (when given).\n"
2637 "   :rtype: str\n"
2638 ;
2639 static PyObject *pyrna_struct_path_from_id(BPy_StructRNA *self, PyObject *args)
2640 {
2641         const char *name= NULL;
2642         const char *path;
2643         PropertyRNA *prop;
2644         PyObject *ret;
2645
2646         PYRNA_STRUCT_CHECK_OBJ(self)
2647
2648         if (!PyArg_ParseTuple(args, "|s:path_from_id", &name))
2649                 return NULL;
2650
2651         if(name) {
2652                 prop= RNA_struct_find_property(&self->ptr, name);
2653                 if(prop==NULL) {
2654                         PyErr_Format(PyExc_TypeError, "%.200s.path_from_id(\"%.200s\") not found", RNA_struct_identifier(self->ptr.type), name);
2655                         return NULL;
2656                 }
2657
2658                 path= RNA_path_from_ID_to_property(&self->ptr, prop);
2659         }
2660         else {
2661                 path= RNA_path_from_ID_to_struct(&self->ptr);
2662         }
2663
2664         if(path==NULL) {
2665                 if(name)        PyErr_Format(PyExc_TypeError, "%.200s.path_from_id(\"%s\") found but does not support path creation", RNA_struct_identifier(self->ptr.type), name);
2666                 else            PyErr_Format(PyExc_TypeError, "%.200s.path_from_id() does not support path creation for this type", RNA_struct_identifier(self->ptr.type));
2667                 return NULL;
2668         }
2669
2670         ret= PyUnicode_FromString(path);
2671         MEM_freeN((void *)path);
2672
2673         return ret;
2674 }
2675
2676 static char pyrna_prop_path_from_id_doc[] =
2677 ".. method:: path_from_id()\n"
2678 "\n"
2679 "   Returns the data path from the ID to this property (string).\n"
2680 "\n"
2681 "   :return: The path from :class:`bpy_struct.id_data` to this property.\n"
2682 "   :rtype: str\n"
2683 ;
2684 static PyObject *pyrna_prop_path_from_id(BPy_PropertyRNA *self)
2685 {
2686         const char *path;
2687         PropertyRNA *prop= self->prop;
2688         PyObject *ret;
2689
2690         path= RNA_path_from_ID_to_property(&self->ptr, self->prop);
2691
2692         if(path==NULL) {
2693                 PyErr_Format(PyExc_TypeError, "%.200s.%.200s.path_from_id() does not support path creation for this type", RNA_struct_identifier(self->ptr.type), RNA_property_identifier(prop));
2694                 return NULL;
2695         }
2696
2697         ret= PyUnicode_FromString(path);
2698         MEM_freeN((void *)path);
2699
2700         return ret;
2701 }
2702
2703 static char pyrna_struct_type_recast_doc[] =
2704 ".. method:: type_recast()\n"
2705 "\n"
2706 "   Return a new instance, this is needed because types such as textures can be changed at runtime.\n"
2707 "\n"
2708 "   :return: a new instance of this object with the type initialized again.\n"
2709 "   :rtype: subclass of :class:`bpy_struct`\n"
2710 ;
2711 static PyObject *pyrna_struct_type_recast(BPy_StructRNA *self)
2712 {
2713         PointerRNA r_ptr;
2714
2715         PYRNA_STRUCT_CHECK_OBJ(self)
2716
2717         RNA_pointer_recast(&self->ptr, &r_ptr);
2718         return pyrna_struct_CreatePyObject(&r_ptr);
2719 }
2720
2721 static void pyrna_dir_members_py(PyObject *list, PyObject *self)
2722 {
2723         PyObject *dict;
2724         PyObject **dict_ptr;
2725         PyObject *list_tmp;
2726
2727         dict_ptr= _PyObject_GetDictPtr((PyObject *)self);
2728
2729         if(dict_ptr && (dict=*dict_ptr)) {
2730                 list_tmp= PyDict_Keys(dict);
2731                 PyList_SetSlice(list, INT_MAX, INT_MAX, list_tmp);
2732                 Py_DECREF(list_tmp);
2733         }
2734
2735         dict= ((PyTypeObject *)Py_TYPE(self))->tp_dict;
2736         if(dict) {
2737                 list_tmp= PyDict_Keys(dict);
2738                 PyList_SetSlice(list, INT_MAX, INT_MAX, list_tmp);
2739                 Py_DECREF(list_tmp);
2740         }
2741 }
2742
2743 static void pyrna_dir_members_rna(PyObject *list, PointerRNA *ptr)
2744 {
2745         PyObject *pystring;
2746         const char *idname;
2747
2748         /* for looping over attrs and funcs */
2749         PointerRNA tptr;
2750         PropertyRNA *iterprop;
2751
2752         {
2753                 RNA_pointer_create(NULL, &RNA_Struct, ptr->type, &tptr);
2754                 iterprop= RNA_struct_find_property(&tptr, "functions");
2755
2756                 RNA_PROP_BEGIN(&tptr, itemptr, iterprop) {
2757                         idname= RNA_function_identifier(itemptr.data);
2758
2759                         pystring= PyUnicode_FromString(idname);
2760                         PyList_Append(list, pystring);
2761                         Py_DECREF(pystring);
2762                 }
2763                 RNA_PROP_END;
2764         }
2765
2766         {
2767                 /*
2768                  * Collect RNA attributes
2769                  */
2770                 char name[256], *nameptr;
2771
2772                 iterprop= RNA_struct_iterator_property(ptr->type);
2773
2774                 RNA_PROP_BEGIN(ptr, itemptr, iterprop) {
2775                         nameptr= RNA_struct_name_get_alloc(&itemptr, name, sizeof(name));
2776
2777                         if(nameptr) {
2778                                 pystring= PyUnicode_FromString(nameptr);
2779                                 PyList_Append(list, pystring);
2780                                 Py_DECREF(pystring);
2781
2782                                 if(name != nameptr)
2783                                         MEM_freeN(nameptr);
2784                         }
2785                 }
2786                 RNA_PROP_END;
2787         }
2788 }
2789
2790
2791 static PyObject *pyrna_struct_dir(BPy_StructRNA *self)
2792 {
2793         PyObject *ret;
2794         PyObject *pystring;
2795
2796         PYRNA_STRUCT_CHECK_OBJ(self)
2797
2798         /* Include this incase this instance is a subtype of a python class
2799          * In these instances we may want to return a function or variable provided by the subtype
2800          * */
2801         ret= PyList_New(0);
2802
2803         if (!BPy_StructRNA_CheckExact(self))
2804                 pyrna_dir_members_py(ret, (PyObject *)self);
2805
2806         pyrna_dir_members_rna(ret, &self->ptr);
2807
2808         if(self->ptr.type == &RNA_Context) {
2809                 ListBase lb= CTX_data_dir_get(self->ptr.data);
2810                 LinkData *link;
2811
2812                 for(link=lb.first; link; link=link->next) {
2813                         pystring= PyUnicode_FromString(link->data);
2814                         PyList_Append(ret, pystring);
2815                         Py_DECREF(pystring);
2816                 }
2817
2818                 BLI_freelistN(&lb);
2819         }
2820
2821         {
2822                 /* set(), this is needed to remove-doubles because the deferred
2823                  * register-props will be in both the python __dict__ and accessed as RNA */
2824
2825                 PyObject *set= PySet_New(ret);
2826
2827                 Py_DECREF(ret);
2828                 ret= PySequence_List(set);
2829                 Py_DECREF(set);
2830         }
2831
2832         return ret;
2833 }
2834
2835 //---------------getattr--------------------------------------------
2836 static PyObject *pyrna_struct_getattro(BPy_StructRNA *self, PyObject *pyname)
2837 {
2838         const char *name= _PyUnicode_AsString(pyname);
2839         PyObject *ret;
2840         PropertyRNA *prop;
2841         FunctionRNA *func;
2842
2843         PYRNA_STRUCT_CHECK_OBJ(self)
2844
2845         if(name == NULL) {
2846                 PyErr_SetString(PyExc_AttributeError, "bpy_struct: __getattr__ must be a string");
2847                 ret= NULL;
2848         }
2849         else if(name[0]=='_') { // rna can't start with a "_", so for __dict__ and similar we can skip using rna lookups
2850                 /* annoying exception, maybe we need to have different types for this... */
2851                 if((strcmp(name, "__getitem__")==0 || strcmp(name, "__setitem__")==0) && !RNA_struct_idprops_check(self->ptr.type)) {
2852                         PyErr_SetString(PyExc_AttributeError, "bpy_struct: no __getitem__ support for this type");
2853                         ret= NULL;
2854                 }
2855                 else {
2856                         ret= PyObject_GenericGetAttr((PyObject *)self, pyname);
2857                 }
2858         }
2859         else if ((prop= RNA_struct_find_property(&self->ptr, name))) {
2860                 ret= pyrna_prop_to_py(&self->ptr, prop);
2861         }
2862         /* RNA function only if callback is declared (no optional functions) */
2863         else if ((func= RNA_struct_find_function(&self->ptr, name)) && RNA_function_defined(func)) {
2864                 ret= pyrna_func_to_py((BPy_DummyPointerRNA *)self, func);
2865         }
2866         else if (self->ptr.type == &RNA_Context) {
2867                 bContext *C= self->ptr.data;
2868                 if(C==NULL) {
2869                         PyErr_Format(PyExc_AttributeError, "bpy_struct: Context is 'NULL', can't get \"%.200s\" from context", name);
2870                         ret= NULL;
2871                 }
2872                 else {
2873                         PointerRNA newptr;
2874                         ListBase newlb;
2875                         short newtype;
2876
2877                         int done= CTX_data_get(C, name, &newptr, &newlb, &newtype);
2878
2879                         if(done==1) { /* found */
2880                                 switch(newtype) {
2881                                 case CTX_DATA_TYPE_POINTER:
2882                                         if(newptr.data == NULL) {
2883                                                 ret= Py_None;
2884                                                 Py_INCREF(ret);
2885                                         }
2886                                         else {
2887                                                 ret= pyrna_struct_CreatePyObject(&newptr);
2888                                         }
2889                                         break;
2890                                 case CTX_DATA_TYPE_COLLECTION:
2891                                         {
2892                                                 CollectionPointerLink *link;
2893                                                 PyObject *linkptr;
2894
2895                                                 ret= PyList_New(0);
2896
2897                                                 for(link=newlb.first; link; link=link->next) {
2898                                                         linkptr= pyrna_struct_CreatePyObject(&link->ptr);
2899                                                         PyList_Append(ret, linkptr);
2900                                                         Py_DECREF(linkptr);
2901                                                 }
2902                                         }
2903                                         break;
2904                                 default:
2905                                         /* should never happen */
2906                                         BLI_assert(!"Invalid context type");
2907
2908                                         PyErr_Format(PyExc_AttributeError, "bpy_struct: Context type invalid %d, can't get \"%.200s\" from context", newtype, name);
2909                                         ret= NULL;
2910                                 }
2911                         }
2912                         else if (done==-1) { /* found but not set */
2913                                 ret= Py_None;
2914                                 Py_INCREF(ret);
2915                         }
2916                         else { /* not found in the context */
2917                                 /* lookup the subclass. raise an error if its not found */
2918                                 ret= PyObject_GenericGetAttr((PyObject *)self, pyname);
2919                         }
2920
2921                         BLI_freelistN(&newlb);
2922                 }
2923         }
2924         else {
2925 #if 0
2926                 PyErr_Format(PyExc_AttributeError, "bpy_struct: attribute \"%.200s\" not found", name);
2927                 ret= NULL;
2928 #endif
2929                 /* Include this incase this instance is a subtype of a python class
2930                  * In these instances we may want to return a function or variable provided by the subtype
2931                  *
2932                  * Also needed to return methods when its not a subtype
2933                  * */
2934
2935                 /* The error raised here will be displayed */
2936                 ret= PyObject_GenericGetAttr((PyObject *)self, pyname);
2937         }
2938
2939         return ret;
2940 }
2941
2942 #if 0
2943 static int pyrna_struct_pydict_contains(PyObject *self, PyObject *pyname)
2944 {
2945         PyObject *dict= *(_PyObject_GetDictPtr((PyObject *)self));
2946         if (dict==NULL) /* unlikely */
2947                 return 0;
2948
2949         return PyDict_Contains(dict, pyname);
2950 }
2951 #endif
2952
2953 //--------------- setattr-------------------------------------------
2954 static int pyrna_is_deferred_prop(PyObject *value)
2955 {
2956         return PyTuple_CheckExact(value) && PyTuple_GET_SIZE(value)==2 && PyCallable_Check(PyTuple_GET_ITEM(value, 0)) && PyDict_CheckExact(PyTuple_GET_ITEM(value, 1));
2957 }
2958
2959 #if 0
2960 static PyObject *pyrna_struct_meta_idprop_getattro(PyObject *cls, PyObject *attr)
2961 {
2962         PyObject *ret= PyType_Type.tp_getattro(cls, attr);
2963
2964         /* Allows:
2965          * >>> bpy.types.Scene.foo= BoolProperty()
2966          * >>> bpy.types.Scene.foo
2967          * <bpy_struct, BooleanProperty("foo")>
2968          * ...rather then returning the deferred class register tuple as checked by pyrna_is_deferred_prop()
2969          *
2970          * Disable for now, this is faking internal behavior in a way thats too tricky to maintain well. */
2971 #if 0
2972         if(ret == NULL) { // || pyrna_is_deferred_prop(ret)
2973                 StructRNA *srna= srna_from_self(cls, "StructRNA.__getattr__");
2974                 if(srna) {
2975                         PropertyRNA *prop= RNA_struct_type_find_property(srna, _PyUnicode_AsString(attr));
2976                         if(prop) {
2977                                 PointerRNA tptr;
2978                                 PyErr_Clear(); /* clear error from tp_getattro */
2979                                 RNA_pointer_create(NULL, &RNA_Property, prop, &tptr);
2980                                 ret= pyrna_struct_CreatePyObject(&tptr);
2981                         }
2982                 }
2983         }
2984 #endif
2985
2986         return ret;
2987 }
2988 #endif
2989
2990 static int pyrna_struct_meta_idprop_setattro(PyObject *cls, PyObject *attr, PyObject *value)
2991 {
2992         StructRNA *srna= srna_from_self(cls, "StructRNA.__setattr__");
2993         const int is_deferred_prop= (value && pyrna_is_deferred_prop(value));
2994
2995         if(srna && !pyrna_write_check() && (is_deferred_prop || RNA_struct_type_find_property(srna, _PyUnicode_AsString(attr)))) {
2996                 PyErr_Format(PyExc_AttributeError, "pyrna_struct_meta_idprop_setattro() can't set in readonly state '%.200s.%S'", ((PyTypeObject *)cls)->tp_name, attr);
2997                 return -1;
2998         }
2999
3000         if(srna == NULL) {
3001                 /* allow setting on unregistered classes which can be registered later on */
3002                 /*
3003                 if(value && is_deferred_prop) {
3004                         PyErr_Format(PyExc_AttributeError, "pyrna_struct_meta_idprop_setattro() unable to get srna from class '%.200s'", ((PyTypeObject *)cls)->tp_name);
3005                         return -1;
3006                 }
3007                 */
3008                 /* srna_from_self may set an error */
3009                 PyErr_Clear();
3010                 return PyType_Type.tp_setattro(cls, attr, value);
3011         }
3012
3013         if(value) {
3014                 /* check if the value is a property */
3015                 if(is_deferred_prop) {
3016                         int ret= deferred_register_prop(srna, attr, value);
3017                         if(ret == -1) {
3018                                 /* error set */
3019                                 return ret;
3020                         }
3021
3022                         /* pass through and assign to the classes __dict__ as well
3023                          * when the value isn't assigned it still creates the RNA property
3024                          * but gets confusing from script writers POV if the assigned value cant be read back. */
3025                 }
3026                 else {
3027                         /* remove existing property if its set or we also end up with confusion */
3028                         const char *attr_str= _PyUnicode_AsString(attr);
3029                         RNA_def_property_free_identifier(srna, attr_str); /* ignore on failure */
3030                 }
3031         }
3032         else { /* __delattr__ */
3033                 /* first find if this is a registered property */
3034                 const char *attr_str= _PyUnicode_AsString(attr);
3035                 int ret= RNA_def_property_free_identifier(srna, attr_str);
3036                 if (ret == -1) {
3037                         PyErr_Format(PyExc_TypeError, "struct_meta_idprop.detattr(): '%s' not a dynamic property", attr_str);
3038                         return -1;
3039                 }
3040         }
3041
3042         /* fallback to standard py, delattr/setattr */
3043         return PyType_Type.tp_setattro(cls, attr, value);
3044 }
3045
3046 static int pyrna_struct_setattro(BPy_StructRNA *self, PyObject *pyname, PyObject *value)
3047 {
3048         const char *name= _PyUnicode_AsString(pyname);
3049         PropertyRNA *prop= NULL;
3050
3051         PYRNA_STRUCT_CHECK_INT(self)
3052
3053 #ifdef USE_PEDANTIC_WRITE
3054         if(rna_disallow_writes && rna_id_write_error(&self->ptr, pyname)) {
3055                 return -1;
3056         }
3057 #endif // USE_STRING_COERCE
3058
3059         if(name == NULL) {
3060                 PyErr_SetString(PyExc_AttributeError, "bpy_struct: __setattr__ must be a string");
3061                 return -1;
3062         }
3063         else if (name[0] != '_' && (prop= RNA_struct_find_property(&self->ptr, name))) {
3064                 if (!RNA_property_editable_flag(&self->ptr, prop)) {
3065                         PyErr_Format(PyExc_AttributeError, "bpy_struct: attribute \"%.200s\" from \"%.200s\" is read-only", RNA_property_identifier(prop), RNA_struct_identifier(self->ptr.type));
3066                         return -1;
3067                 }
3068         }
3069         else if (self->ptr.type == &RNA_Context) {
3070                 /* code just raises correct error, context prop's cant be set, unless its apart of the py class */
3071                 bContext *C= self->ptr.data;
3072                 if(C==NULL) {
3073                         PyErr_Format(PyExc_AttributeError, "bpy_struct: Context is 'NULL', can't set \"%.200s\" from context", name);
3074                         return -1;
3075                 }
3076                 else {
3077                         PointerRNA newptr;
3078                         ListBase newlb;
3079                         short newtype;
3080
3081                         int done= CTX_data_get(C, name, &newptr, &newlb, &newtype);
3082
3083                         if(done==1) {
3084                                 PyErr_Format(PyExc_AttributeError, "bpy_struct: Context property \"%.200s\" is read-only", name);
3085                                 BLI_freelistN(&newlb);
3086                                 return -1;
3087                         }
3088
3089                         BLI_freelistN(&newlb);
3090                 }
3091         }
3092
3093         /* pyrna_py_to_prop sets its own exceptions */
3094         if(prop) {
3095                 if(value == NULL) {
3096                         PyErr_SetString(PyExc_AttributeError, "bpy_struct: del not supported");
3097                         return -1;
3098                 }
3099                 return pyrna_py_to_prop(&self->ptr, prop, NULL, value, "bpy_struct: item.attr= val:");
3100         }
3101         else {
3102                 return PyObject_GenericSetAttr((PyObject *)self, pyname, value);
3103         }
3104 }
3105
3106 static PyObject *pyrna_prop_dir(BPy_PropertyRNA *self)
3107 {
3108         PyObject *ret;
3109         PointerRNA r_ptr;
3110
3111         /* Include this incase this instance is a subtype of a python class
3112          * In these instances we may want to return a function or variable provided by the subtype
3113          * */
3114         ret= PyList_New(0);
3115
3116         if (!BPy_PropertyRNA_CheckExact(self))
3117                 pyrna_dir_members_py(ret, (PyObject *)self);
3118
3119         if(RNA_property_collection_type_get(&self->ptr, self->prop, &r_ptr))
3120                 pyrna_dir_members_rna(ret, &r_ptr);
3121
3122         return ret;
3123 }
3124
3125
3126 static PyObject *pyrna_prop_array_getattro(BPy_PropertyRNA *self, PyObject *pyname)
3127 {
3128         return PyObject_GenericGetAttr((PyObject *)self, pyname);
3129 }
3130
3131 static PyObject *pyrna_prop_collection_getattro(BPy_PropertyRNA *self, PyObject *pyname)
3132 {
3133         const char *name= _PyUnicode_AsString(pyname);
3134
3135         if(name == NULL) {
3136                 PyErr_SetString(PyExc_AttributeError, "bpy_prop_collection: __getattr__ must be a string");
3137                 return NULL;
3138         }
3139         else if(name[0] != '_') {
3140                 PyObject *ret;
3141                 PropertyRNA *prop;
3142                 FunctionRNA *func;
3143
3144                 PointerRNA r_ptr;
3145                 if(RNA_property_collection_type_get(&self->ptr, self->prop, &r_ptr)) {
3146                         if ((prop= RNA_struct_find_property(&r_ptr, name))) {
3147                                 ret= pyrna_prop_to_py(&r_ptr, prop);
3148
3149                                 return ret;
3150                         }
3151                         else if ((func= RNA_struct_find_function(&r_ptr, name))) {
3152                                 PyObject *self_collection= pyrna_struct_CreatePyObject(&r_ptr);
3153                                 ret= pyrna_func_to_py((BPy_DummyPointerRNA *)self_collection, func);
3154                                 Py_DECREF(self_collection);
3155
3156                                 return ret;
3157                         }
3158                 }
3159         }
3160
3161 #if 0
3162         return PyObject_GenericGetAttr((PyObject *)self, pyname);
3163 #else
3164         {
3165                 /* Could just do this except for 1 awkward case.
3166                  * PyObject_GenericGetAttr((PyObject *)self, pyname);
3167                  * so as to support 'bpy.data.library.load()'
3168                  * note, this _only_ supports static methods */
3169
3170                 PyObject *ret= PyObject_GenericGetAttr((PyObject *)self, pyname);
3171
3172                 if(ret == NULL && name[0] != '_') { /* avoid inheriting __call__ and similar */
3173                         /* since this is least common case, handle it last */
3174                         PointerRNA r_ptr;
3175                         if(RNA_property_collection_type_get(&self->ptr, self->prop, &r_ptr)) {
3176                                 PyObject *cls;
3177
3178                                 PyObject *error_type, *error_value, *error_traceback;
3179                                 PyErr_Fetch(&error_type, &error_value, &error_traceback);
3180                                 PyErr_Clear();
3181
3182                                 cls= pyrna_struct_Subtype(&r_ptr); /* borrows */
3183                                 ret= PyObject_GenericGetAttr(cls, pyname);
3184                                 /* restore the original error */
3185                                 if(ret == NULL) {
3186                                         PyErr_Restore(error_type, error_value, error_traceback);
3187                                 }
3188                         }
3189                 }
3190
3191                 return ret;
3192         }
3193 #endif
3194 }
3195
3196 //--------------- setattr-------------------------------------------
3197 static int pyrna_prop_collection_setattro(BPy_PropertyRNA *self, PyObject *pyname, PyObject *value)
3198 {
3199         const char *name= _PyUnicode_AsString(pyname);
3200         PropertyRNA *prop;
3201         PointerRNA r_ptr;
3202
3203 #ifdef USE_PEDANTIC_WRITE
3204         if(rna_disallow_writes && rna_id_write_error(&self->ptr, pyname)) {
3205                 return -1;
3206         }
3207 #endif // USE_STRING_COERCE