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