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