Blender V2.61 - r43446

bpy_rna.c

Go to the documentation of this file.
00001 /*
00002  * ***** BEGIN GPL LICENSE BLOCK *****
00003  *
00004  * This program is free software; you can redistribute it and/or
00005  * modify it under the terms of the GNU General Public License
00006  * as published by the Free Software Foundation; either version 2
00007  * of the License, or (at your option) any later version.
00008  *
00009  * This program is distributed in the hope that it will be useful,
00010  * but WITHOUT ANY WARRANTY; without even the implied warranty of
00011  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
00012  * GNU General Public License for more details.
00013  *
00014  * You should have received a copy of the GNU General Public License
00015  * along with this program; if not, write to the Free Software Foundation,
00016  * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
00017  *
00018  * Contributor(s): Campbell Barton
00019  *
00020  * ***** END GPL LICENSE BLOCK *****
00021  */
00022 
00033 #include <Python.h>
00034 
00035 #include <stddef.h>
00036 #include <float.h> /* FLT_MIN/MAX */
00037 
00038 #include "RNA_types.h"
00039 
00040 #include "bpy_rna.h"
00041 #include "bpy_rna_anim.h"
00042 #include "bpy_props.h"
00043 #include "bpy_util.h"
00044 #include "bpy_rna_callback.h"
00045 #include "bpy_intern_string.h"
00046 
00047 #ifdef USE_PYRNA_INVALIDATE_WEAKREF
00048 #include "MEM_guardedalloc.h"
00049 #endif
00050 
00051 #include "BLI_dynstr.h"
00052 #include "BLI_string.h"
00053 #include "BLI_listbase.h"
00054 #include "BLI_math_rotation.h"
00055 #include "BLI_utildefines.h"
00056 
00057 #ifdef USE_PYRNA_INVALIDATE_WEAKREF
00058 #include "BLI_ghash.h"
00059 #endif
00060 
00061 #include "RNA_enum_types.h"
00062 #include "RNA_define.h" /* RNA_def_property_free_identifier */
00063 #include "RNA_access.h"
00064 
00065 #include "MEM_guardedalloc.h"
00066 
00067 #include "BKE_main.h"
00068 #include "BKE_idcode.h"
00069 #include "BKE_context.h"
00070 #include "BKE_global.h" /* evil G.* */
00071 #include "BKE_report.h"
00072 #include "BKE_idprop.h"
00073 
00074 #include "BKE_animsys.h"
00075 #include "BKE_fcurve.h"
00076 
00077 #include "../generic/idprop_py_api.h" /* for IDprop lookups */
00078 #include "../generic/py_capi_utils.h"
00079 
00080 #ifdef WITH_INTERNATIONAL
00081 #include "BLF_translation.h"
00082 #endif
00083 
00084 #define USE_PEDANTIC_WRITE
00085 #define USE_MATHUTILS
00086 #define USE_STRING_COERCE
00087 
00088 static PyObject* pyrna_struct_Subtype(PointerRNA *ptr);
00089 static PyObject *pyrna_prop_collection_values(BPy_PropertyRNA *self);
00090 
00091 #define BPY_DOC_ID_PROP_TYPE_NOTE                                             \
00092 "   .. note::\n"                                                              \
00093 "\n"                                                                          \
00094 "      Only :class:`bpy.types.ID`, :class:`bpy.types.Bone` and \n"            \
00095 "      :class:`bpy.types.PoseBone` classes support custom properties.\n"
00096 
00097 
00098 int pyrna_struct_validity_check(BPy_StructRNA *pysrna)
00099 {
00100     if (pysrna->ptr.type) {
00101         return 0;
00102     }
00103     PyErr_Format(PyExc_ReferenceError,
00104                  "StructRNA of type %.200s has been removed",
00105                  Py_TYPE(pysrna)->tp_name);
00106     return -1;
00107 }
00108 
00109 int pyrna_prop_validity_check(BPy_PropertyRNA *self)
00110 {
00111     if (self->ptr.type) {
00112         return 0;
00113     }
00114     PyErr_Format(PyExc_ReferenceError,
00115                  "PropertyRNA of type %.200s.%.200s has been removed",
00116                  Py_TYPE(self)->tp_name, RNA_property_identifier(self->prop));
00117     return -1;
00118 }
00119 
00120 #if defined(USE_PYRNA_INVALIDATE_GC) || defined(USE_PYRNA_INVALIDATE_WEAKREF)
00121 static void pyrna_invalidate(BPy_DummyPointerRNA *self)
00122 {
00123     self->ptr.type = NULL; /* this is checked for validity */
00124     self->ptr.id.data = NULL; /* should not be needed but prevent bad pointer access, just incase */
00125 }
00126 #endif
00127 
00128 #ifdef USE_PYRNA_INVALIDATE_GC
00129 #define FROM_GC(g) ((PyObject *)(((PyGC_Head *)g) + 1))
00130 
00131 /* only for sizeof() */
00132 struct gc_generation {
00133     PyGC_Head head;
00134     int threshold;
00135     int count;
00136 } gc_generation;
00137 
00138 static void id_release_gc(struct ID *id)
00139 {
00140     unsigned int j;
00141     // unsigned int i = 0;
00142     for (j = 0; j < 3; j++) {
00143         /* hack below to get the 2 other lists from _PyGC_generation0 that are normally not exposed */
00144         PyGC_Head *gen = (PyGC_Head *)(((char *)_PyGC_generation0) + (sizeof(gc_generation) * j));
00145         PyGC_Head *g = gen->gc.gc_next;
00146         while ((g = g->gc.gc_next) != gen) {
00147             PyObject *ob = FROM_GC(g);
00148             if (PyType_IsSubtype(Py_TYPE(ob), &pyrna_struct_Type) || PyType_IsSubtype(Py_TYPE(ob), &pyrna_prop_Type)) {
00149                 BPy_DummyPointerRNA *ob_ptr = (BPy_DummyPointerRNA *)ob;
00150                 if (ob_ptr->ptr.id.data == id) {
00151                     pyrna_invalidate(ob_ptr);
00152                     // printf("freeing: %p %s, %.200s\n", (void *)ob, id->name, Py_TYPE(ob)->tp_name);
00153                     // i++;
00154                 }
00155             }
00156         }
00157     }
00158     // printf("id_release_gc freed '%s': %d\n", id->name, i);
00159 }
00160 #endif
00161 
00162 #ifdef USE_PYRNA_INVALIDATE_WEAKREF
00163 //#define DEBUG_RNA_WEAKREF
00164 
00165 struct GHash *id_weakref_pool = NULL;
00166 static PyObject *id_free_weakref_cb(PyObject *weakinfo_pair, PyObject *weakref);
00167 static PyMethodDef id_free_weakref_cb_def = {"id_free_weakref_cb", (PyCFunction)id_free_weakref_cb, METH_O, NULL};
00168 
00169 /* adds a reference to the list, remember to decref */
00170 static GHash *id_weakref_pool_get(ID *id)
00171 {
00172     GHash *weakinfo_hash = NULL;
00173 
00174     if (id_weakref_pool) {
00175         weakinfo_hash = BLI_ghash_lookup(id_weakref_pool, (void *)id);
00176     }
00177     else {
00178         /* first time, allocate pool */
00179         id_weakref_pool = BLI_ghash_new(BLI_ghashutil_ptrhash, BLI_ghashutil_ptrcmp, "rna_global_pool");
00180         weakinfo_hash = NULL;
00181     }
00182 
00183     if (weakinfo_hash == NULL) {
00184         /* we're using a ghash as a set, could use libHX's HXMAP_SINGULAR but would be an extra dep. */
00185         weakinfo_hash = BLI_ghash_new(BLI_ghashutil_ptrhash, BLI_ghashutil_ptrcmp, "rna_id");
00186         BLI_ghash_insert(id_weakref_pool, (void *)id, weakinfo_hash);
00187     }
00188 
00189     return weakinfo_hash;
00190 }
00191 
00192 /* called from pyrna_struct_CreatePyObject() and pyrna_prop_CreatePyObject() */
00193 void id_weakref_pool_add(ID *id, BPy_DummyPointerRNA *pyrna)
00194 {
00195     PyObject *weakref;
00196     PyObject *weakref_capsule;
00197     PyObject *weakref_cb_py;
00198 
00199     /* create a new function instance and insert the list as 'self' so we can remove ourself from it */
00200     GHash *weakinfo_hash = id_weakref_pool_get(id); /* new or existing */
00201 
00202     weakref_capsule = PyCapsule_New(weakinfo_hash, NULL, NULL);
00203     weakref_cb_py = PyCFunction_New(&id_free_weakref_cb_def, weakref_capsule);
00204     Py_DECREF(weakref_capsule);
00205 
00206     /* add weakref to weakinfo_hash list */
00207     weakref = PyWeakref_NewRef((PyObject *)pyrna, weakref_cb_py);
00208 
00209     Py_DECREF(weakref_cb_py); /* function owned by the weakref now */
00210 
00211     /* important to add at the end, since first removal looks at the end */
00212     BLI_ghash_insert(weakinfo_hash, (void *)weakref, id); /* using a hash table as a set, all 'id's are the same */
00213     /* weakinfo_hash owns the weakref */
00214 
00215 }
00216 
00217 /* workaround to get the last id without a lookup */
00218 static ID *_id_tmp_ptr;
00219 static void value_id_set(void *id)
00220 {
00221     _id_tmp_ptr = (ID *)id;
00222 }
00223 
00224 static void id_release_weakref_list(struct ID *id, GHash *weakinfo_hash);
00225 static PyObject *id_free_weakref_cb(PyObject *weakinfo_capsule, PyObject *weakref)
00226 {
00227     /* important to search backwards */
00228     GHash *weakinfo_hash = PyCapsule_GetPointer(weakinfo_capsule, NULL);
00229 
00230 
00231     if (BLI_ghash_size(weakinfo_hash) > 1) {
00232         BLI_ghash_remove(weakinfo_hash, weakref, NULL, NULL);
00233     }
00234     else { /* get the last id and free it */
00235         BLI_ghash_remove(weakinfo_hash, weakref, NULL, value_id_set);
00236         id_release_weakref_list(_id_tmp_ptr, weakinfo_hash);
00237     }
00238 
00239     Py_DECREF(weakref);
00240 
00241     Py_RETURN_NONE;
00242 }
00243 
00244 static void id_release_weakref_list(struct ID *id, GHash *weakinfo_hash)
00245 {
00246     GHashIterator weakinfo_hash_iter;
00247 
00248     BLI_ghashIterator_init(&weakinfo_hash_iter, weakinfo_hash);
00249 
00250 #ifdef DEBUG_RNA_WEAKREF
00251     fprintf(stdout, "id_release_weakref: '%s', %d items\n", id->name, BLI_ghash_size(weakinfo_hash));
00252 #endif
00253 
00254     while (!BLI_ghashIterator_isDone(&weakinfo_hash_iter)) {
00255         PyObject *weakref = (PyObject *)BLI_ghashIterator_getKey(&weakinfo_hash_iter);
00256         PyObject *item = PyWeakref_GET_OBJECT(weakref);
00257         if (item != Py_None) {
00258 
00259 #ifdef DEBUG_RNA_WEAKREF
00260             PyC_ObSpit("id_release_weakref item ", item);
00261 #endif
00262 
00263             pyrna_invalidate((BPy_DummyPointerRNA *)item);
00264         }
00265 
00266         Py_DECREF(weakref);
00267 
00268         BLI_ghashIterator_step(&weakinfo_hash_iter);
00269     }
00270 
00271     BLI_ghash_remove(id_weakref_pool, (void *)id, NULL, NULL);
00272     BLI_ghash_free(weakinfo_hash, NULL, NULL);
00273 
00274     if (BLI_ghash_size(id_weakref_pool) == 0) {
00275         BLI_ghash_free(id_weakref_pool, NULL, NULL);
00276         id_weakref_pool = NULL;
00277 #ifdef DEBUG_RNA_WEAKREF
00278         printf("id_release_weakref freeing pool\n");
00279 #endif
00280     }
00281 }
00282 
00283 static void id_release_weakref(struct ID *id)
00284 {
00285     GHash *weakinfo_hash = BLI_ghash_lookup(id_weakref_pool, (void *)id);
00286     if (weakinfo_hash) {
00287         id_release_weakref_list(id, weakinfo_hash);
00288     }
00289 }
00290 
00291 #endif /* USE_PYRNA_INVALIDATE_WEAKREF */
00292 
00293 void BPY_id_release(struct ID *id)
00294 {
00295 #ifdef USE_PYRNA_INVALIDATE_GC
00296     id_release_gc(id);
00297 #endif
00298 
00299 #ifdef USE_PYRNA_INVALIDATE_WEAKREF
00300     if (id_weakref_pool) {
00301         PyGILState_STATE gilstate = PyGILState_Ensure();
00302 
00303         id_release_weakref(id);
00304 
00305         PyGILState_Release(gilstate);
00306     }
00307 #endif /* USE_PYRNA_INVALIDATE_WEAKREF */
00308 
00309     (void)id;
00310 }
00311 
00312 #ifdef USE_PEDANTIC_WRITE
00313 static short rna_disallow_writes = FALSE;
00314 
00315 static int rna_id_write_error(PointerRNA *ptr, PyObject *key)
00316 {
00317     ID *id = ptr->id.data;
00318     if (id) {
00319         const short idcode = GS(id->name);
00320         if (!ELEM(idcode, ID_WM, ID_SCR)) { /* may need more added here */
00321             const char *idtype = BKE_idcode_to_name(idcode);
00322             const char *pyname;
00323             if (key && PyUnicode_Check(key)) pyname = _PyUnicode_AsString(key);
00324             else                             pyname = "<UNKNOWN>";
00325 
00326             /* make a nice string error */
00327             BLI_assert(idtype != NULL);
00328             PyErr_Format(PyExc_AttributeError,
00329                          "Writing to ID classes in this context is not allowed: "
00330                          "%.200s, %.200s datablock, error setting %.200s.%.200s",
00331                          id->name + 2, idtype, RNA_struct_identifier(ptr->type), pyname);
00332 
00333             return TRUE;
00334         }
00335     }
00336     return FALSE;
00337 }
00338 #endif // USE_PEDANTIC_WRITE
00339 
00340 
00341 #ifdef USE_PEDANTIC_WRITE
00342 int pyrna_write_check(void)
00343 {
00344     return !rna_disallow_writes;
00345 }
00346 
00347 void pyrna_write_set(int val)
00348 {
00349     rna_disallow_writes = !val;
00350 }
00351 #else // USE_PEDANTIC_WRITE
00352 int pyrna_write_check(void)
00353 {
00354     return TRUE;
00355 }
00356 void pyrna_write_set(int UNUSED(val))
00357 {
00358     /* nothing */
00359 }
00360 #endif // USE_PEDANTIC_WRITE
00361 
00362 static Py_ssize_t pyrna_prop_collection_length(BPy_PropertyRNA *self);
00363 static Py_ssize_t pyrna_prop_array_length(BPy_PropertyArrayRNA *self);
00364 static int pyrna_py_to_prop(PointerRNA *ptr, PropertyRNA *prop, void *data, PyObject *value, const char *error_prefix);
00365 static int deferred_register_prop(StructRNA *srna, PyObject *key, PyObject *item);
00366 
00367 #ifdef USE_MATHUTILS
00368 #include "../mathutils/mathutils.h" /* so we can have mathutils callbacks */
00369 
00370 static PyObject *pyrna_prop_array_subscript_slice(BPy_PropertyArrayRNA *self, PointerRNA *ptr, PropertyRNA *prop,
00371                                                   Py_ssize_t start, Py_ssize_t stop, Py_ssize_t length);
00372 static short pyrna_rotation_euler_order_get(PointerRNA *ptr, PropertyRNA **prop_eul_order, short order_fallback);
00373 
00374 /* bpyrna vector/euler/quat callbacks */
00375 static int mathutils_rna_array_cb_index = -1; /* index for our callbacks */
00376 
00377 /* subtype not used much yet */
00378 #define MATHUTILS_CB_SUBTYPE_EUL 0
00379 #define MATHUTILS_CB_SUBTYPE_VEC 1
00380 #define MATHUTILS_CB_SUBTYPE_QUAT 2
00381 #define MATHUTILS_CB_SUBTYPE_COLOR 3
00382 
00383 static int mathutils_rna_generic_check(BaseMathObject *bmo)
00384 {
00385     BPy_PropertyRNA *self = (BPy_PropertyRNA *)bmo->cb_user;
00386 
00387     PYRNA_PROP_CHECK_INT(self);
00388 
00389     return self->prop ? 0 : -1;
00390 }
00391 
00392 static int mathutils_rna_vector_get(BaseMathObject *bmo, int subtype)
00393 {
00394     BPy_PropertyRNA *self = (BPy_PropertyRNA *)bmo->cb_user;
00395 
00396     PYRNA_PROP_CHECK_INT(self);
00397 
00398     if (self->prop == NULL)
00399         return -1;
00400 
00401     RNA_property_float_get_array(&self->ptr, self->prop, bmo->data);
00402 
00403     /* Euler order exception */
00404     if (subtype == MATHUTILS_CB_SUBTYPE_EUL) {
00405         EulerObject *eul = (EulerObject *)bmo;
00406         PropertyRNA *prop_eul_order = NULL;
00407         eul->order = pyrna_rotation_euler_order_get(&self->ptr, &prop_eul_order, eul->order);
00408     }
00409 
00410     return 0;
00411 }
00412 
00413 static int mathutils_rna_vector_set(BaseMathObject *bmo, int subtype)
00414 {
00415     BPy_PropertyRNA *self = (BPy_PropertyRNA *)bmo->cb_user;
00416     float min, max;
00417 
00418     PYRNA_PROP_CHECK_INT(self);
00419 
00420     if (self->prop == NULL)
00421         return -1;
00422 
00423 #ifdef USE_PEDANTIC_WRITE
00424     if (rna_disallow_writes && rna_id_write_error(&self->ptr, NULL)) {
00425         return -1;
00426     }
00427 #endif // USE_PEDANTIC_WRITE
00428 
00429     if (!RNA_property_editable_flag(&self->ptr, self->prop)) {
00430         PyErr_Format(PyExc_AttributeError,
00431                      "bpy_prop \"%.200s.%.200s\" is read-only",
00432                      RNA_struct_identifier(self->ptr.type), RNA_property_identifier(self->prop));
00433         return -1;
00434     }
00435 
00436     RNA_property_float_range(&self->ptr, self->prop, &min, &max);
00437 
00438     if (min != FLT_MIN || max != FLT_MAX) {
00439         int i, len = RNA_property_array_length(&self->ptr, self->prop);
00440         for (i = 0; i < len; i++) {
00441             CLAMP(bmo->data[i], min, max);
00442         }
00443     }
00444 
00445     RNA_property_float_set_array(&self->ptr, self->prop, bmo->data);
00446     if (RNA_property_update_check(self->prop)) {
00447         RNA_property_update(BPy_GetContext(), &self->ptr, self->prop);
00448     }
00449 
00450     /* Euler order exception */
00451     if (subtype == MATHUTILS_CB_SUBTYPE_EUL) {
00452         EulerObject *eul = (EulerObject *)bmo;
00453         PropertyRNA *prop_eul_order = NULL;
00454         short order = pyrna_rotation_euler_order_get(&self->ptr, &prop_eul_order, eul->order);
00455         if (order != eul->order) {
00456             RNA_property_enum_set(&self->ptr, prop_eul_order, eul->order);
00457             if (RNA_property_update_check(prop_eul_order)) {
00458                 RNA_property_update(BPy_GetContext(), &self->ptr, prop_eul_order);
00459             }
00460         }
00461     }
00462     return 0;
00463 }
00464 
00465 static int mathutils_rna_vector_get_index(BaseMathObject *bmo, int UNUSED(subtype), int index)
00466 {
00467     BPy_PropertyRNA *self = (BPy_PropertyRNA *)bmo->cb_user;
00468 
00469     PYRNA_PROP_CHECK_INT(self);
00470 
00471     if (self->prop == NULL)
00472         return -1;
00473 
00474     bmo->data[index] = RNA_property_float_get_index(&self->ptr, self->prop, index);
00475     return 0;
00476 }
00477 
00478 static int mathutils_rna_vector_set_index(BaseMathObject *bmo, int UNUSED(subtype), int index)
00479 {
00480     BPy_PropertyRNA *self = (BPy_PropertyRNA *)bmo->cb_user;
00481 
00482     PYRNA_PROP_CHECK_INT(self);
00483 
00484     if (self->prop == NULL)
00485         return -1;
00486 
00487 #ifdef USE_PEDANTIC_WRITE
00488     if (rna_disallow_writes && rna_id_write_error(&self->ptr, NULL)) {
00489         return -1;
00490     }
00491 #endif // USE_PEDANTIC_WRITE
00492 
00493     if (!RNA_property_editable_flag(&self->ptr, self->prop)) {
00494         PyErr_Format(PyExc_AttributeError,
00495                      "bpy_prop \"%.200s.%.200s\" is read-only",
00496                      RNA_struct_identifier(self->ptr.type), RNA_property_identifier(self->prop));
00497         return -1;
00498     }
00499 
00500     RNA_property_float_clamp(&self->ptr, self->prop, &bmo->data[index]);
00501     RNA_property_float_set_index(&self->ptr, self->prop, index, bmo->data[index]);
00502 
00503     if (RNA_property_update_check(self->prop)) {
00504         RNA_property_update(BPy_GetContext(), &self->ptr, self->prop);
00505     }
00506 
00507     return 0;
00508 }
00509 
00510 static Mathutils_Callback mathutils_rna_array_cb = {
00511     (BaseMathCheckFunc)     mathutils_rna_generic_check,
00512     (BaseMathGetFunc)       mathutils_rna_vector_get,
00513     (BaseMathSetFunc)       mathutils_rna_vector_set,
00514     (BaseMathGetIndexFunc)  mathutils_rna_vector_get_index,
00515     (BaseMathSetIndexFunc)  mathutils_rna_vector_set_index
00516 };
00517 
00518 
00519 /* bpyrna matrix callbacks */
00520 static int mathutils_rna_matrix_cb_index = -1; /* index for our callbacks */
00521 
00522 static int mathutils_rna_matrix_get(BaseMathObject *bmo, int UNUSED(subtype))
00523 {
00524     BPy_PropertyRNA *self = (BPy_PropertyRNA *)bmo->cb_user;
00525 
00526     PYRNA_PROP_CHECK_INT(self);
00527 
00528     if (self->prop == NULL)
00529         return -1;
00530 
00531     RNA_property_float_get_array(&self->ptr, self->prop, bmo->data);
00532     return 0;
00533 }
00534 
00535 static int mathutils_rna_matrix_set(BaseMathObject *bmo, int UNUSED(subtype))
00536 {
00537     BPy_PropertyRNA *self = (BPy_PropertyRNA *)bmo->cb_user;
00538 
00539     PYRNA_PROP_CHECK_INT(self);
00540 
00541     if (self->prop == NULL)
00542         return -1;
00543 
00544 #ifdef USE_PEDANTIC_WRITE
00545     if (rna_disallow_writes && rna_id_write_error(&self->ptr, NULL)) {
00546         return -1;
00547     }
00548 #endif // USE_PEDANTIC_WRITE
00549 
00550     if (!RNA_property_editable_flag(&self->ptr, self->prop)) {
00551         PyErr_Format(PyExc_AttributeError,
00552                      "bpy_prop \"%.200s.%.200s\" is read-only",
00553                      RNA_struct_identifier(self->ptr.type), RNA_property_identifier(self->prop));
00554         return -1;
00555     }
00556 
00557     /* can ignore clamping here */
00558     RNA_property_float_set_array(&self->ptr, self->prop, bmo->data);
00559 
00560     if (RNA_property_update_check(self->prop)) {
00561         RNA_property_update(BPy_GetContext(), &self->ptr, self->prop);
00562     }
00563     return 0;
00564 }
00565 
00566 static Mathutils_Callback mathutils_rna_matrix_cb = {
00567     mathutils_rna_generic_check,
00568     mathutils_rna_matrix_get,
00569     mathutils_rna_matrix_set,
00570     NULL,
00571     NULL
00572 };
00573 
00574 static short pyrna_rotation_euler_order_get(PointerRNA *ptr, PropertyRNA **prop_eul_order, short order_fallback)
00575 {
00576     /* attempt to get order */
00577     if (*prop_eul_order == NULL)
00578         *prop_eul_order = RNA_struct_find_property(ptr, "rotation_mode");
00579 
00580     if (*prop_eul_order) {
00581         short order = RNA_property_enum_get(ptr, *prop_eul_order);
00582         if (order >= EULER_ORDER_XYZ && order <= EULER_ORDER_ZYX) /* could be quat or axisangle */
00583             return order;
00584     }
00585 
00586     return order_fallback;
00587 }
00588 
00589 #endif // USE_MATHUTILS
00590 
00591 /* note that PROP_NONE is included as a vector subtype. this is because its handy to
00592  * have x/y access to fcurve keyframes and other fixed size float arrays of length 2-4. */
00593 #define PROP_ALL_VECTOR_SUBTYPES                                              \
00594          PROP_COORDS:                                                         \
00595     case PROP_TRANSLATION:                                                    \
00596     case PROP_DIRECTION:                                                      \
00597     case PROP_VELOCITY:                                                       \
00598     case PROP_ACCELERATION:                                                   \
00599     case PROP_XYZ:                                                            \
00600     case PROP_XYZ_LENGTH                                                      \
00601 
00602 
00603 PyObject *pyrna_math_object_from_array(PointerRNA *ptr, PropertyRNA *prop)
00604 {
00605     PyObject *ret = NULL;
00606 
00607 #ifdef USE_MATHUTILS
00608     int subtype, totdim;
00609     int len;
00610     int is_thick;
00611     const int flag = RNA_property_flag(prop);
00612 
00613     /* disallow dynamic sized arrays to be wrapped since the size could change
00614      * to a size mathutils does not support */
00615     if ((RNA_property_type(prop) != PROP_FLOAT) || (flag & PROP_DYNAMIC))
00616         return NULL;
00617 
00618     len = RNA_property_array_length(ptr, prop);
00619     subtype = RNA_property_subtype(prop);
00620     totdim = RNA_property_array_dimension(ptr, prop, NULL);
00621     is_thick = (flag & PROP_THICK_WRAP);
00622 
00623     if (totdim == 1 || (totdim == 2 && subtype == PROP_MATRIX)) {
00624         if (!is_thick)
00625             ret = pyrna_prop_CreatePyObject(ptr, prop); /* owned by the mathutils PyObject */
00626 
00627         switch (subtype) {
00628         case PROP_ALL_VECTOR_SUBTYPES:
00629             if (len >= 2 && len <= 4) {
00630                 if (is_thick) {
00631                     ret = Vector_CreatePyObject(NULL, len, Py_NEW, NULL);
00632                     RNA_property_float_get_array(ptr, prop, ((VectorObject *)ret)->vec);
00633                 }
00634                 else {
00635                     PyObject *vec_cb = Vector_CreatePyObject_cb(ret, len, mathutils_rna_array_cb_index, MATHUTILS_CB_SUBTYPE_VEC);
00636                     Py_DECREF(ret); /* the vector owns now */
00637                     ret = vec_cb; /* return the vector instead */
00638                 }
00639             }
00640             break;
00641         case PROP_MATRIX:
00642             if (len == 16) {
00643                 if (is_thick) {
00644                     ret = Matrix_CreatePyObject(NULL, 4, 4, Py_NEW, NULL);
00645                     RNA_property_float_get_array(ptr, prop, ((MatrixObject *)ret)->matrix);
00646                 }
00647                 else {
00648                     PyObject *mat_cb = Matrix_CreatePyObject_cb(ret, 4,4, mathutils_rna_matrix_cb_index, FALSE);
00649                     Py_DECREF(ret); /* the matrix owns now */
00650                     ret = mat_cb; /* return the matrix instead */
00651                 }
00652             }
00653             else if (len == 9) {
00654                 if (is_thick) {
00655                     ret = Matrix_CreatePyObject(NULL, 3, 3, Py_NEW, NULL);
00656                     RNA_property_float_get_array(ptr, prop, ((MatrixObject *)ret)->matrix);
00657                 }
00658                 else {
00659                     PyObject *mat_cb = Matrix_CreatePyObject_cb(ret, 3,3, mathutils_rna_matrix_cb_index, FALSE);
00660                     Py_DECREF(ret); /* the matrix owns now */
00661                     ret = mat_cb; /* return the matrix instead */
00662                 }
00663             }
00664             break;
00665         case PROP_EULER:
00666         case PROP_QUATERNION:
00667             if (len == 3) { /* euler */
00668                 if (is_thick) {
00669                     /* attempt to get order, only needed for thick types since wrapped with update via callbacks */
00670                     PropertyRNA *prop_eul_order = NULL;
00671                     short order = pyrna_rotation_euler_order_get(ptr, &prop_eul_order, EULER_ORDER_XYZ);
00672 
00673                     ret = Euler_CreatePyObject(NULL, order, Py_NEW, NULL); // TODO, get order from RNA
00674                     RNA_property_float_get_array(ptr, prop, ((EulerObject *)ret)->eul);
00675                 }
00676                 else {
00677                     /* order will be updated from callback on use */
00678                     PyObject *eul_cb = Euler_CreatePyObject_cb(ret, EULER_ORDER_XYZ, mathutils_rna_array_cb_index, MATHUTILS_CB_SUBTYPE_EUL); // TODO, get order from RNA
00679                     Py_DECREF(ret); /* the euler owns now */
00680                     ret = eul_cb; /* return the euler instead */
00681                 }
00682             }
00683             else if (len == 4) {
00684                 if (is_thick) {
00685                     ret = Quaternion_CreatePyObject(NULL, Py_NEW, NULL);
00686                     RNA_property_float_get_array(ptr, prop, ((QuaternionObject *)ret)->quat);
00687                 }
00688                 else {
00689                     PyObject *quat_cb = Quaternion_CreatePyObject_cb(ret, mathutils_rna_array_cb_index, MATHUTILS_CB_SUBTYPE_QUAT);
00690                     Py_DECREF(ret); /* the quat owns now */
00691                     ret = quat_cb; /* return the quat instead */
00692                 }
00693             }
00694             break;
00695         case PROP_COLOR:
00696         case PROP_COLOR_GAMMA:
00697             if (len == 3) { /* color */
00698                 if (is_thick) {
00699                     ret = Color_CreatePyObject(NULL, Py_NEW, NULL); // TODO, get order from RNA
00700                     RNA_property_float_get_array(ptr, prop, ((ColorObject *)ret)->col);
00701                 }
00702                 else {
00703                     PyObject *col_cb = Color_CreatePyObject_cb(ret, mathutils_rna_array_cb_index, MATHUTILS_CB_SUBTYPE_COLOR);
00704                     Py_DECREF(ret); /* the color owns now */
00705                     ret = col_cb; /* return the color instead */
00706                 }
00707             }
00708         default:
00709             break;
00710         }
00711     }
00712 
00713     if (ret == NULL) {
00714         if (is_thick) {
00715             /* this is an array we cant reference (since its not thin wrappable)
00716              * and cannot be coerced into a mathutils type, so return as a list */
00717             ret = pyrna_prop_array_subscript_slice(NULL, ptr, prop, 0, len, len);
00718         }
00719         else {
00720             ret = pyrna_prop_CreatePyObject(ptr, prop); /* owned by the mathutils PyObject */
00721         }
00722     }
00723 #else // USE_MATHUTILS
00724     (void)ptr;
00725     (void)prop;
00726 #endif // USE_MATHUTILS
00727 
00728     return ret;
00729 }
00730 
00731 /* same as RNA_enum_value_from_id but raises an exception */
00732 int pyrna_enum_value_from_id(EnumPropertyItem *item, const char *identifier, int *value, const char *error_prefix)
00733 {
00734     if (RNA_enum_value_from_id(item, identifier, value) == 0) {
00735         const char *enum_str = BPy_enum_as_string(item);
00736         PyErr_Format(PyExc_TypeError,
00737                      "%s: '%.200s' not found in (%s)",
00738                      error_prefix, identifier, enum_str);
00739         MEM_freeN((void *)enum_str);
00740         return -1;
00741     }
00742 
00743     return 0;
00744 }
00745 
00746 /* note on __cmp__:
00747  * checking the 'ptr->data' matches works in almost all cases,
00748  * however there are a few RNA properties that are fake sub-structs and
00749  * share the pointer with the parent, in those cases this happens 'a.b == a'
00750  * see: r43352 for example.
00751  *
00752  * So compare the 'ptr->type' as well to avoid this problem.
00753  * It's highly unlikely this would happen that 'ptr->data' and 'ptr->prop' would match,
00754  * but _not_ 'ptr->type' but include this check for completeness.
00755  * - campbell */
00756 
00757 static int pyrna_struct_compare(BPy_StructRNA *a, BPy_StructRNA *b)
00758 {
00759     return ( (a->ptr.data == b->ptr.data) &&
00760              (a->ptr.type == b->ptr.type)) ? 0 : -1;
00761 }
00762 
00763 static int pyrna_prop_compare(BPy_PropertyRNA *a, BPy_PropertyRNA *b)
00764 {
00765     return ( (a->prop == b->prop) &&
00766              (a->ptr.data == b->ptr.data) &&
00767              (a->ptr.type == b->ptr.type) ) ? 0 : -1;
00768 }
00769 
00770 static PyObject *pyrna_struct_richcmp(PyObject *a, PyObject *b, int op)
00771 {
00772     PyObject *res;
00773     int ok = -1; /* zero is true */
00774 
00775     if (BPy_StructRNA_Check(a) && BPy_StructRNA_Check(b))
00776         ok = pyrna_struct_compare((BPy_StructRNA *)a, (BPy_StructRNA *)b);
00777 
00778     switch (op) {
00779     case Py_NE:
00780         ok = !ok; /* pass through */
00781     case Py_EQ:
00782         res = ok ? Py_False : Py_True;
00783         break;
00784 
00785     case Py_LT:
00786     case Py_LE:
00787     case Py_GT:
00788     case Py_GE:
00789         res = Py_NotImplemented;
00790         break;
00791     default:
00792         PyErr_BadArgument();
00793         return NULL;
00794     }
00795 
00796     return Py_INCREF(res), res;
00797 }
00798 
00799 static PyObject *pyrna_prop_richcmp(PyObject *a, PyObject *b, int op)
00800 {
00801     PyObject *res;
00802     int ok = -1; /* zero is true */
00803 
00804     if (BPy_PropertyRNA_Check(a) && BPy_PropertyRNA_Check(b))
00805         ok = pyrna_prop_compare((BPy_PropertyRNA *)a, (BPy_PropertyRNA *)b);
00806 
00807     switch (op) {
00808     case Py_NE:
00809         ok = !ok; /* pass through */
00810     case Py_EQ:
00811         res = ok ? Py_False : Py_True;
00812         break;
00813 
00814     case Py_LT:
00815     case Py_LE:
00816     case Py_GT:
00817     case Py_GE:
00818         res = Py_NotImplemented;
00819         break;
00820     default:
00821         PyErr_BadArgument();
00822         return NULL;
00823     }
00824 
00825     return Py_INCREF(res), res;
00826 }
00827 
00828 /*----------------------repr--------------------------------------------*/
00829 static PyObject *pyrna_struct_str(BPy_StructRNA *self)
00830 {
00831     PyObject *ret;
00832     const char *name;
00833 
00834     if (!PYRNA_STRUCT_IS_VALID(self)) {
00835         return PyUnicode_FromFormat("<bpy_struct, %.200s dead>",
00836                                     Py_TYPE(self)->tp_name);
00837     }
00838 
00839     /* print name if available */
00840     name = RNA_struct_name_get_alloc(&self->ptr, NULL, 0, NULL);
00841     if (name) {
00842         ret = PyUnicode_FromFormat("<bpy_struct, %.200s(\"%.200s\")>",
00843                                   RNA_struct_identifier(self->ptr.type),
00844                                   name);
00845         MEM_freeN((void *)name);
00846         return ret;
00847     }
00848 
00849     return PyUnicode_FromFormat("<bpy_struct, %.200s at %p>",
00850                                 RNA_struct_identifier(self->ptr.type),
00851                                 self->ptr.data);
00852 }
00853 
00854 static PyObject *pyrna_struct_repr(BPy_StructRNA *self)
00855 {
00856     ID *id = self->ptr.id.data;
00857     PyObject *tmp_str;
00858     PyObject *ret;
00859 
00860     if (id == NULL || !PYRNA_STRUCT_IS_VALID(self))
00861         return pyrna_struct_str(self); /* fallback */
00862 
00863     tmp_str = PyUnicode_FromString(id->name + 2);
00864 
00865     if (RNA_struct_is_ID(self->ptr.type)) {
00866         ret = PyUnicode_FromFormat("bpy.data.%s[%R]",
00867                                     BKE_idcode_to_name_plural(GS(id->name)),
00868                                     tmp_str);
00869     }
00870     else {
00871         const char *path;
00872         path = RNA_path_from_ID_to_struct(&self->ptr);
00873         if (path) {
00874             ret = PyUnicode_FromFormat("bpy.data.%s[%R].%s",
00875                                       BKE_idcode_to_name_plural(GS(id->name)),
00876                                       tmp_str,
00877                                       path);
00878             MEM_freeN((void *)path);
00879         }
00880         else { /* cant find, print something sane */
00881             ret = PyUnicode_FromFormat("bpy.data.%s[%R]...%s",
00882                                       BKE_idcode_to_name_plural(GS(id->name)),
00883                                       tmp_str,
00884                                       RNA_struct_identifier(self->ptr.type));
00885         }
00886     }
00887 
00888     Py_DECREF(tmp_str);
00889 
00890     return ret;
00891 }
00892 
00893 static PyObject *pyrna_prop_str(BPy_PropertyRNA *self)
00894 {
00895     PyObject *ret;
00896     PointerRNA ptr;
00897     const char *name;
00898     const char *type_id = NULL;
00899     char type_fmt[64] = "";
00900     int type;
00901 
00902     PYRNA_PROP_CHECK_OBJ(self);
00903 
00904     type = RNA_property_type(self->prop);
00905 
00906     if (RNA_enum_id_from_value(property_type_items, type, &type_id) == 0) {
00907         PyErr_SetString(PyExc_RuntimeError, "could not use property type, internal error"); /* should never happen */
00908         return NULL;
00909     }
00910     else {
00911         /* this should never fail */
00912         int len = -1;
00913         char *c = type_fmt;
00914 
00915         while ((*c++= tolower(*type_id++))) {} ;
00916 
00917         if (type == PROP_COLLECTION) {
00918             len = pyrna_prop_collection_length(self);
00919         }
00920         else if (RNA_property_array_check(self->prop)) {
00921             len = pyrna_prop_array_length((BPy_PropertyArrayRNA *)self);
00922         }
00923 
00924         if (len != -1)
00925             sprintf(--c, "[%d]", len);
00926     }
00927 
00928     /* if a pointer, try to print name of pointer target too */
00929     if (type == PROP_POINTER) {
00930         ptr = RNA_property_pointer_get(&self->ptr, self->prop);
00931         name = RNA_struct_name_get_alloc(&ptr, NULL, 0, NULL);
00932 
00933         if (name) {
00934             ret = PyUnicode_FromFormat("<bpy_%.200s, %.200s.%.200s(\"%.200s\")>",
00935                                       type_fmt,
00936                                       RNA_struct_identifier(self->ptr.type),
00937                                       RNA_property_identifier(self->prop),
00938                                       name);
00939             MEM_freeN((void *)name);
00940             return ret;
00941         }
00942     }
00943     if (type == PROP_COLLECTION) {
00944         PointerRNA r_ptr;
00945         if (RNA_property_collection_type_get(&self->ptr, self->prop, &r_ptr)) {
00946             return PyUnicode_FromFormat("<bpy_%.200s, %.200s>",
00947                                         type_fmt,
00948                                         RNA_struct_identifier(r_ptr.type));
00949         }
00950     }
00951 
00952     return PyUnicode_FromFormat("<bpy_%.200s, %.200s.%.200s>",
00953                                 type_fmt,
00954                                 RNA_struct_identifier(self->ptr.type),
00955                                 RNA_property_identifier(self->prop));
00956 }
00957 
00958 static PyObject *pyrna_prop_repr(BPy_PropertyRNA *self)
00959 {
00960     ID *id = self->ptr.id.data;
00961     PyObject *tmp_str;
00962     PyObject *ret;
00963     const char *path;
00964 
00965     PYRNA_PROP_CHECK_OBJ(self);
00966 
00967     if (id == NULL)
00968         return pyrna_prop_str(self); /* fallback */
00969 
00970     tmp_str = PyUnicode_FromString(id->name + 2);
00971 
00972     path = RNA_path_from_ID_to_property(&self->ptr, self->prop);
00973     if (path) {
00974         ret = PyUnicode_FromFormat("bpy.data.%s[%R].%s",
00975                                   BKE_idcode_to_name_plural(GS(id->name)),
00976                                   tmp_str,
00977                                   path);
00978         MEM_freeN((void *)path);
00979     }
00980     else { /* cant find, print something sane */
00981         ret = PyUnicode_FromFormat("bpy.data.%s[%R]...%s",
00982                                   BKE_idcode_to_name_plural(GS(id->name)),
00983                                   tmp_str,
00984                                   RNA_property_identifier(self->prop));
00985     }
00986 
00987     Py_DECREF(tmp_str);
00988 
00989     return ret;
00990 }
00991 
00992 
00993 static PyObject *pyrna_func_repr(BPy_FunctionRNA *self)
00994 {
00995     return PyUnicode_FromFormat("<%.200s %.200s.%.200s()>",
00996                                 Py_TYPE(self)->tp_name,
00997                                 RNA_struct_identifier(self->ptr.type),
00998                                 RNA_function_identifier(self->func));
00999 }
01000 
01001 
01002 static long pyrna_struct_hash(BPy_StructRNA *self)
01003 {
01004     return _Py_HashPointer(self->ptr.data);
01005 }
01006 
01007 /* from python's meth_hash v3.1.2 */
01008 static long pyrna_prop_hash(BPy_PropertyRNA *self)
01009 {
01010     long x, y;
01011     if (self->ptr.data == NULL)
01012         x = 0;
01013     else {
01014         x = _Py_HashPointer(self->ptr.data);
01015         if (x == -1)
01016             return -1;
01017     }
01018     y = _Py_HashPointer((void *)(self->prop));
01019     if (y == -1)
01020         return -1;
01021     x ^= y;
01022     if (x == -1)
01023         x = -2;
01024     return x;
01025 }
01026 
01027 #ifdef USE_PYRNA_STRUCT_REFERENCE
01028 static int pyrna_struct_traverse(BPy_StructRNA *self, visitproc visit, void *arg)
01029 {
01030     Py_VISIT(self->reference);
01031     return 0;
01032 }
01033 
01034 static int pyrna_struct_clear(BPy_StructRNA *self)
01035 {
01036     Py_CLEAR(self->reference);
01037     return 0;
01038 }
01039 #endif /* !USE_PYRNA_STRUCT_REFERENCE */
01040 
01041 /* use our own dealloc so we can free a property if we use one */
01042 static void pyrna_struct_dealloc(BPy_StructRNA *self)
01043 {
01044 #ifdef PYRNA_FREE_SUPPORT
01045     if (self->freeptr && self->ptr.data) {
01046         IDP_FreeProperty(self->ptr.data);
01047         MEM_freeN(self->ptr.data);
01048         self->ptr.data = NULL;
01049     }
01050 #endif /* PYRNA_FREE_SUPPORT */
01051 
01052 #ifdef USE_WEAKREFS
01053     if (self->in_weakreflist != NULL) {
01054         PyObject_ClearWeakRefs((PyObject *)self);
01055     }
01056 #endif
01057 
01058 #ifdef USE_PYRNA_STRUCT_REFERENCE
01059     if (self->reference) {
01060         PyObject_GC_UnTrack(self);
01061         pyrna_struct_clear(self);
01062     }
01063 #endif /* !USE_PYRNA_STRUCT_REFERENCE */
01064 
01065     /* Note, for subclassed PyObjects we cant just call PyObject_DEL() directly or it will crash */
01066     Py_TYPE(self)->tp_free(self);
01067 }
01068 
01069 #ifdef USE_PYRNA_STRUCT_REFERENCE
01070 static void pyrna_struct_reference_set(BPy_StructRNA *self, PyObject *reference)
01071 {
01072     if (self->reference) {
01073 //      PyObject_GC_UnTrack(self); /* INITIALIZED TRACKED ? */
01074         pyrna_struct_clear(self);
01075     }
01076     /* reference is now NULL */
01077 
01078     if (reference) {
01079         self->reference = reference;
01080         Py_INCREF(reference);
01081 //      PyObject_GC_Track(self);  /* INITIALIZED TRACKED ? */
01082     }
01083 }
01084 #endif /* !USE_PYRNA_STRUCT_REFERENCE */
01085 
01086 /* use our own dealloc so we can free a property if we use one */
01087 static void pyrna_prop_dealloc(BPy_PropertyRNA *self)
01088 {
01089 #ifdef USE_WEAKREFS
01090     if (self->in_weakreflist != NULL) {
01091         PyObject_ClearWeakRefs((PyObject *)self);
01092     }
01093 #endif
01094     /* Note, for subclassed PyObjects we cant just call PyObject_DEL() directly or it will crash */
01095     Py_TYPE(self)->tp_free(self);
01096 }
01097 
01098 static void pyrna_prop_array_dealloc(BPy_PropertyRNA *self)
01099 {
01100 #ifdef USE_WEAKREFS
01101     if (self->in_weakreflist != NULL) {
01102         PyObject_ClearWeakRefs((PyObject *)self);
01103     }
01104 #endif
01105     /* Note, for subclassed PyObjects we cant just call PyObject_DEL() directly or it will crash */
01106     Py_TYPE(self)->tp_free(self);
01107 }
01108 
01109 static const char *pyrna_enum_as_string(PointerRNA *ptr, PropertyRNA *prop)
01110 {
01111     EnumPropertyItem *item;
01112     const char *result;
01113     int free = FALSE;
01114 
01115     RNA_property_enum_items(BPy_GetContext(), ptr, prop, &item, NULL, &free);
01116     if (item) {
01117         result = BPy_enum_as_string(item);
01118     }
01119     else {
01120         result = "";
01121     }
01122 
01123     if (free)
01124         MEM_freeN(item);
01125 
01126     return result;
01127 }
01128 
01129 
01130 static int pyrna_string_to_enum(PyObject *item, PointerRNA *ptr, PropertyRNA *prop, int *val, const char *error_prefix)
01131 {
01132     const char *param = _PyUnicode_AsString(item);
01133 
01134     if (param == NULL) {
01135         PyErr_Format(PyExc_TypeError,
01136                      "%.200s expected a string enum, not %.200s",
01137                      error_prefix, Py_TYPE(item)->tp_name);
01138         return -1;
01139     }
01140     else {
01141         /* hack so that dynamic enums used for operator properties will be able to be built (i.e. context will be supplied to itemf)
01142          * and thus running defining operator buttons for such operators in UI will work */
01143         RNA_def_property_clear_flag(prop, PROP_ENUM_NO_CONTEXT);
01144 
01145         if (!RNA_property_enum_value(BPy_GetContext(), ptr, prop, param, val)) {
01146             const char *enum_str = pyrna_enum_as_string(ptr, prop);
01147             PyErr_Format(PyExc_TypeError,
01148                          "%.200s enum \"%.200s\" not found in (%.200s)",
01149                          error_prefix, param, enum_str);
01150             MEM_freeN((void *)enum_str);
01151             return -1;
01152         }
01153     }
01154 
01155     return 0;
01156 }
01157 
01158 /* 'value' _must_ be a set type, error check before calling */
01159 int pyrna_set_to_enum_bitfield(EnumPropertyItem *items, PyObject *value, int *r_value, const char *error_prefix)
01160 {
01161     /* set of enum items, concatenate all values with OR */
01162     int ret, flag = 0;
01163 
01164     /* set looping */
01165     Py_ssize_t pos = 0;
01166     Py_ssize_t hash = 0;
01167     PyObject *key;
01168 
01169     *r_value = 0;
01170 
01171     while (_PySet_NextEntry(value, &pos, &key, &hash)) {
01172         const char *param = _PyUnicode_AsString(key);
01173 
01174         if (param == NULL) {
01175             PyErr_Format(PyExc_TypeError,
01176                          "%.200s expected a string, not %.200s",
01177                          error_prefix, Py_TYPE(key)->tp_name);
01178             return -1;
01179         }
01180 
01181         if (pyrna_enum_value_from_id(items, param, &ret, error_prefix) < 0) {
01182             return -1;
01183         }
01184 
01185         flag |= ret;
01186     }
01187 
01188     *r_value = flag;
01189     return 0;
01190 }
01191 
01192 static int pyrna_prop_to_enum_bitfield(PointerRNA *ptr, PropertyRNA *prop, PyObject *value, int *r_value, const char *error_prefix)
01193 {
01194     EnumPropertyItem *item;
01195     int ret;
01196     int free = FALSE;
01197 
01198     *r_value = 0;
01199 
01200     if (!PyAnySet_Check(value)) {
01201         PyErr_Format(PyExc_TypeError,
01202                      "%.200s, %.200s.%.200s expected a set, not a %.200s",
01203                      error_prefix, RNA_struct_identifier(ptr->type),
01204                      RNA_property_identifier(prop), Py_TYPE(value)->tp_name);
01205         return -1;
01206     }
01207 
01208     RNA_property_enum_items(BPy_GetContext(), ptr, prop, &item, NULL, &free);
01209 
01210     if (item) {
01211         ret = pyrna_set_to_enum_bitfield(item, value, r_value, error_prefix);
01212     }
01213     else {
01214         if (PySet_GET_SIZE(value)) {
01215             PyErr_Format(PyExc_TypeError,
01216                          "%.200s: empty enum \"%.200s\" could not have any values assigned",
01217                          error_prefix, RNA_property_identifier(prop));
01218             ret = -1;
01219         }
01220         else {
01221             ret = 0;
01222         }
01223     }
01224 
01225     if (free)
01226         MEM_freeN(item);
01227 
01228     return ret;
01229 }
01230 
01231 PyObject *pyrna_enum_bitfield_to_py(EnumPropertyItem *items, int value)
01232 {
01233     PyObject *ret = PySet_New(NULL);
01234     const char *identifier[RNA_ENUM_BITFLAG_SIZE + 1];
01235 
01236     if (RNA_enum_bitflag_identifiers(items, value, identifier)) {
01237         PyObject *item;
01238         int index;
01239         for (index = 0; identifier[index]; index++) {
01240             item = PyUnicode_FromString(identifier[index]);
01241             PySet_Add(ret, item);
01242             Py_DECREF(item);
01243         }
01244     }
01245 
01246     return ret;
01247 }
01248 
01249 static PyObject *pyrna_enum_to_py(PointerRNA *ptr, PropertyRNA *prop, int val)
01250 {
01251     PyObject *item, *ret = NULL;
01252 
01253     if (RNA_property_flag(prop) & PROP_ENUM_FLAG) {
01254         const char *identifier[RNA_ENUM_BITFLAG_SIZE + 1];
01255 
01256         ret = PySet_New(NULL);
01257 
01258         if (RNA_property_enum_bitflag_identifiers(BPy_GetContext(), ptr, prop, val, identifier)) {
01259             int index;
01260 
01261             for (index = 0; identifier[index]; index++) {
01262                 item = PyUnicode_FromString(identifier[index]);
01263                 PySet_Add(ret, item);
01264                 Py_DECREF(item);
01265             }
01266 
01267         }
01268     }
01269     else {
01270         const char *identifier;
01271         if (RNA_property_enum_identifier(BPy_GetContext(), ptr, prop, val, &identifier)) {
01272             ret = PyUnicode_FromString(identifier);
01273         }
01274         else {
01275             EnumPropertyItem *enum_item;
01276             int free = FALSE;
01277 
01278             /* don't throw error here, can't trust blender 100% to give the
01279              * right values, python code should not generate error for that */
01280             RNA_property_enum_items(BPy_GetContext(), ptr, prop, &enum_item, NULL, &free);
01281             if (enum_item && enum_item->identifier) {
01282                 ret = PyUnicode_FromString(enum_item->identifier);
01283             }
01284             else {
01285                 const char *ptr_name = RNA_struct_name_get_alloc(ptr, NULL, 0, NULL);
01286 
01287                 /* prefer not fail silently incase of api errors, maybe disable it later */
01288                 printf("RNA Warning: Current value \"%d\" "
01289                        "matches no enum in '%s', '%s', '%s'\n",
01290                        val, RNA_struct_identifier(ptr->type),
01291                        ptr_name, RNA_property_identifier(prop));
01292 
01293 #if 0           // gives python decoding errors while generating docs :(
01294                 char error_str[256];
01295                 BLI_snprintf(error_str, sizeof(error_str),
01296                              "RNA Warning: Current value \"%d\" "
01297                              "matches no enum in '%s', '%s', '%s'",
01298                              val, RNA_struct_identifier(ptr->type),
01299                              ptr_name, RNA_property_identifier(prop));
01300 
01301                 PyErr_Warn(PyExc_RuntimeWarning, error_str);
01302 #endif
01303 
01304                 if (ptr_name)
01305                     MEM_freeN((void *)ptr_name);
01306 
01307                 ret = PyUnicode_FromString("");
01308             }
01309 
01310             if (free)
01311                 MEM_freeN(enum_item);
01312             /*
01313             PyErr_Format(PyExc_AttributeError,
01314                          "RNA Error: Current value \"%d\" matches no enum", val);
01315             ret = NULL;
01316             */
01317         }
01318     }
01319 
01320     return ret;
01321 }
01322 
01323 PyObject *pyrna_prop_to_py(PointerRNA *ptr, PropertyRNA *prop)
01324 {
01325     PyObject *ret;
01326     const int type = RNA_property_type(prop);
01327 
01328     if (RNA_property_array_check(prop)) {
01329         return pyrna_py_from_array(ptr, prop);
01330     }
01331 
01332     /* see if we can coorce into a python type - PropertyType */
01333     switch (type) {
01334     case PROP_BOOLEAN:
01335         ret = PyBool_FromLong(RNA_property_boolean_get(ptr, prop));
01336         break;
01337     case PROP_INT:
01338         ret = PyLong_FromSsize_t((Py_ssize_t)RNA_property_int_get(ptr, prop));
01339         break;
01340     case PROP_FLOAT:
01341         ret = PyFloat_FromDouble(RNA_property_float_get(ptr, prop));
01342         break;
01343     case PROP_STRING:
01344     {
01345         const int subtype = RNA_property_subtype(prop);
01346         const char *buf;
01347         int buf_len;
01348         char buf_fixed[32];
01349 
01350         buf = RNA_property_string_get_alloc(ptr, prop, buf_fixed, sizeof(buf_fixed), &buf_len);
01351 #ifdef USE_STRING_COERCE
01352         /* only file paths get special treatment, they may contain non utf-8 chars */
01353         if (subtype == PROP_BYTESTRING) {
01354             ret = PyBytes_FromStringAndSize(buf, buf_len);
01355         }
01356         else if (ELEM3(subtype, PROP_FILEPATH, PROP_DIRPATH, PROP_FILENAME)) {
01357             ret = PyC_UnicodeFromByteAndSize(buf, buf_len);
01358         }
01359         else {
01360             ret = PyUnicode_FromStringAndSize(buf, buf_len);
01361         }
01362 #else // USE_STRING_COERCE
01363         if (subtype == PROP_BYTESTRING) {
01364             ret = PyBytes_FromStringAndSize(buf, buf_len);
01365         }
01366         else {
01367             ret = PyUnicode_FromStringAndSize(buf, buf_len);
01368         }
01369 #endif // USE_STRING_COERCE
01370         if (buf_fixed != buf) {
01371             MEM_freeN((void *)buf);
01372         }
01373         break;
01374     }
01375     case PROP_ENUM:
01376     {
01377         ret = pyrna_enum_to_py(ptr, prop, RNA_property_enum_get(ptr, prop));
01378         break;
01379     }
01380     case PROP_POINTER:
01381     {
01382         PointerRNA newptr;
01383         newptr = RNA_property_pointer_get(ptr, prop);
01384         if (newptr.data) {
01385             ret = pyrna_struct_CreatePyObject(&newptr);
01386         }
01387         else {
01388             ret = Py_None;
01389             Py_INCREF(ret);
01390         }
01391         break;
01392     }
01393     case PROP_COLLECTION:
01394         ret = pyrna_prop_CreatePyObject(ptr, prop);
01395         break;
01396     default:
01397         PyErr_Format(PyExc_TypeError,
01398                      "bpy_struct internal error: unknown type '%d' (pyrna_prop_to_py)", type);
01399         ret = NULL;
01400         break;
01401     }
01402 
01403     return ret;
01404 }
01405 
01406 /* This function is used by operators and converting dicts into collections.
01407  * Its takes keyword args and fills them with property values */
01408 int pyrna_pydict_to_props(PointerRNA *ptr, PyObject *kw, int all_args, const char *error_prefix)
01409 {
01410     int error_val = 0;
01411     int totkw;
01412     const char *arg_name = NULL;
01413     PyObject *item;
01414 
01415     totkw = kw ? PyDict_Size(kw):0;
01416 
01417     RNA_STRUCT_BEGIN(ptr, prop) {
01418         arg_name = RNA_property_identifier(prop);
01419 
01420         if (strcmp(arg_name, "rna_type") == 0) continue;
01421 
01422         if (kw == NULL) {
01423             PyErr_Format(PyExc_TypeError,
01424                          "%.200s: no keywords, expected \"%.200s\"",
01425                          error_prefix, arg_name ? arg_name : "<UNKNOWN>");
01426             error_val = -1;
01427             break;
01428         }
01429 
01430         item = PyDict_GetItemString(kw, arg_name); /* wont set an error */
01431 
01432         if (item == NULL) {
01433             if (all_args) {
01434                 PyErr_Format(PyExc_TypeError,
01435                              "%.200s: keyword \"%.200s\" missing",
01436                              error_prefix, arg_name ? arg_name : "<UNKNOWN>");
01437                 error_val = -1; /* pyrna_py_to_prop sets the error */
01438                 break;
01439             }
01440         }
01441         else {
01442             if (pyrna_py_to_prop(ptr, prop, NULL, item, error_prefix)) {
01443                 error_val = -1;
01444                 break;
01445             }
01446             totkw--;
01447         }
01448     }
01449     RNA_STRUCT_END;
01450 
01451     if (error_val == 0 && totkw > 0) { /* some keywords were given that were not used :/ */
01452         PyObject *key, *value;
01453         Py_ssize_t pos = 0;
01454 
01455         while (PyDict_Next(kw, &pos, &key, &value)) {
01456             arg_name = _PyUnicode_AsString(key);
01457             if (RNA_struct_find_property(ptr, arg_name) == NULL) break;
01458             arg_name = NULL;
01459         }
01460 
01461         PyErr_Format(PyExc_TypeError,
01462                      "%.200s: keyword \"%.200s\" unrecognized",
01463                      error_prefix, arg_name ? arg_name : "<UNKNOWN>");
01464         error_val = -1;
01465     }
01466 
01467     return error_val;
01468 }
01469 
01470 
01471 static PyObject *pyrna_func_to_py(PointerRNA *ptr, FunctionRNA *func)
01472 {
01473     BPy_FunctionRNA* pyfunc = (BPy_FunctionRNA *) PyObject_NEW(BPy_FunctionRNA, &pyrna_func_Type);
01474     pyfunc->ptr = *ptr;
01475     pyfunc->func = func;
01476     return (PyObject *)pyfunc;
01477 }
01478 
01479 
01480 static int pyrna_py_to_prop(PointerRNA *ptr, PropertyRNA *prop, void *data, PyObject *value, const char *error_prefix)
01481 {
01482     /* XXX hard limits should be checked here */
01483     const int type = RNA_property_type(prop);
01484 
01485 
01486     if (RNA_property_array_check(prop)) {
01487         /* done getting the length */
01488         if (pyrna_py_to_array(ptr, prop, data, value, error_prefix) == -1) {
01489             return -1;
01490         }
01491     }
01492     else {
01493         /* Normal Property (not an array) */
01494 
01495         /* see if we can coorce into a python type - PropertyType */
01496         switch (type) {
01497         case PROP_BOOLEAN:
01498         {
01499             int param;
01500             /* prefer not to have an exception here
01501              * however so many poll functions return None or a valid Object.
01502              * its a hassle to convert these into a bool before returning, */
01503             if (RNA_property_flag(prop) & PROP_OUTPUT)
01504                 param = PyObject_IsTrue(value);
01505             else
01506                 param = PyLong_AsLong(value);
01507 
01508             if (param < 0) {
01509                 PyErr_Format(PyExc_TypeError,
01510                              "%.200s %.200s.%.200s expected True/False or 0/1, not %.200s",
01511                              error_prefix, RNA_struct_identifier(ptr->type),
01512                              RNA_property_identifier(prop), Py_TYPE(value)->tp_name);
01513                 return -1;
01514             }
01515             else {
01516                 if (data)  *((int *)data)= param;
01517                 else       RNA_property_boolean_set(ptr, prop, param);
01518             }
01519             break;
01520         }
01521         case PROP_INT:
01522         {
01523             int overflow;
01524             long param = PyLong_AsLongAndOverflow(value, &overflow);
01525             if (overflow || (param > INT_MAX) || (param < INT_MIN)) {
01526                 PyErr_Format(PyExc_ValueError,
01527                              "%.200s %.200s.%.200s value not in 'int' range "
01528                              "(" STRINGIFY(INT_MIN) ", " STRINGIFY(INT_MAX) ")",
01529                              error_prefix, RNA_struct_identifier(ptr->type),
01530                              RNA_property_identifier(prop));
01531                 return -1;
01532             }
01533             else if (param == -1 && PyErr_Occurred()) {
01534                 PyErr_Format(PyExc_TypeError,
01535                              "%.200s %.200s.%.200s expected an int type, not %.200s",
01536                              error_prefix, RNA_struct_identifier(ptr->type),
01537                              RNA_property_identifier(prop), Py_TYPE(value)->tp_name);
01538                 return -1;
01539             }
01540             else {
01541                 int param_i = (int)param;
01542                 RNA_property_int_clamp(ptr, prop, &param_i);
01543                 if (data)  *((int *)data)= param_i;
01544                 else       RNA_property_int_set(ptr, prop, param_i);
01545             }
01546             break;
01547         }
01548         case PROP_FLOAT:
01549         {
01550             float param = PyFloat_AsDouble(value);
01551             if (PyErr_Occurred()) {
01552                 PyErr_Format(PyExc_TypeError,
01553                              "%.200s %.200s.%.200s expected a float type, not %.200s",
01554                              error_prefix, RNA_struct_identifier(ptr->type),
01555                              RNA_property_identifier(prop), Py_TYPE(value)->tp_name);
01556                 return -1;
01557             }
01558             else {
01559                 RNA_property_float_clamp(ptr, prop, (float *)&param);
01560                 if (data)   *((float *)data)= param;
01561                 else        RNA_property_float_set(ptr, prop, param);
01562             }
01563             break;
01564         }
01565         case PROP_STRING:
01566         {
01567             const int subtype = RNA_property_subtype(prop);
01568             const char *param;
01569 
01570             if (subtype == PROP_BYTESTRING) {
01571 
01572                 /* Byte String */
01573 
01574                 param = PyBytes_AsString(value);
01575 
01576                 if (param == NULL) {
01577                     if (PyBytes_Check(value)) {
01578                         /* there was an error assigning a string type,
01579                          * rather than setting a new error, prefix the existing one
01580                          */
01581                         PyC_Err_Format_Prefix(PyExc_TypeError,
01582                                               "%.200s %.200s.%.200s error assigning bytes",
01583                                               error_prefix, RNA_struct_identifier(ptr->type),
01584                                               RNA_property_identifier(prop));
01585                     }
01586                     else {
01587                         PyErr_Format(PyExc_TypeError,
01588                                      "%.200s %.200s.%.200s expected a bytes type, not %.200s",
01589                                      error_prefix, RNA_struct_identifier(ptr->type),
01590                                      RNA_property_identifier(prop), Py_TYPE(value)->tp_name);
01591                     }
01592 
01593                     return -1;
01594                 }
01595                 else {
01596                     /* same as unicode */
01597                     if (data)   *((char **)data)= (char *)param; /*XXX, this is suspect but needed for function calls, need to see if theres a better way */
01598                     else        RNA_property_string_set(ptr, prop, param);
01599                 }
01600             }
01601             else {
01602 
01603                 /* Unicode String */
01604 
01605 #ifdef USE_STRING_COERCE
01606                 PyObject *value_coerce = NULL;
01607                 if (ELEM3(subtype, PROP_FILEPATH, PROP_DIRPATH, PROP_FILENAME)) {
01608                     /* TODO, get size */
01609                     param = PyC_UnicodeAsByte(value, &value_coerce);
01610                 }
01611                 else {
01612                     param = _PyUnicode_AsString(value);
01613 #ifdef WITH_INTERNATIONAL
01614                     if (subtype == PROP_TRANSLATE) {
01615                         param = IFACE_(param);
01616                     }
01617 #endif // WITH_INTERNATIONAL
01618 
01619                 }
01620 #else // USE_STRING_COERCE
01621                 param = _PyUnicode_AsString(value);
01622 #endif // USE_STRING_COERCE
01623 
01624                 if (param == NULL) {
01625                     if (PyUnicode_Check(value)) {
01626                         /* there was an error assigning a string type,
01627                          * rather than setting a new error, prefix the existing one
01628                          */
01629                         PyC_Err_Format_Prefix(PyExc_TypeError,
01630                                               "%.200s %.200s.%.200s error assigning string",
01631                                               error_prefix, RNA_struct_identifier(ptr->type),
01632                                               RNA_property_identifier(prop));
01633                     }
01634                     else {
01635                         PyErr_Format(PyExc_TypeError,
01636                                      "%.200s %.200s.%.200s expected a string type, not %.200s",
01637                                      error_prefix, RNA_struct_identifier(ptr->type),
01638                                      RNA_property_identifier(prop), Py_TYPE(value)->tp_name);
01639                     }
01640 
01641                     return -1;
01642                 }
01643                 else {
01644                     /* same as bytes */
01645                     if (data)   *((char **)data)= (char *)param; /*XXX, this is suspect but needed for function calls, need to see if theres a better way */
01646                     else        RNA_property_string_set(ptr, prop, param);
01647                 }
01648 #ifdef USE_STRING_COERCE
01649                 Py_XDECREF(value_coerce);
01650 #endif // USE_STRING_COERCE
01651             }
01652             break;
01653         }
01654         case PROP_ENUM:
01655         {
01656             int val = 0;
01657 
01658             /* type checkins is done by each function */
01659             if (RNA_property_flag(prop) & PROP_ENUM_FLAG) {
01660                 /* set of enum items, concatenate all values with OR */
01661                 if (pyrna_prop_to_enum_bitfield(ptr, prop, value, &val, error_prefix) < 0) {
01662                     return -1;
01663                 }
01664             }
01665             else {
01666                 /* simple enum string */
01667                 if (pyrna_string_to_enum(value, ptr, prop, &val, error_prefix) < 0) {
01668                     return -1;
01669                 }
01670             }
01671 
01672             if (data)  *((int *)data)= val;
01673             else       RNA_property_enum_set(ptr, prop, val);
01674 
01675             break;
01676         }
01677         case PROP_POINTER:
01678         {
01679             PyObject *value_new = NULL;
01680 
01681             StructRNA *ptr_type = RNA_property_pointer_type(ptr, prop);
01682             int flag = RNA_property_flag(prop);
01683 
01684             /* this is really nasty!, so we can fake the operator having direct properties eg:
01685              * layout.prop(self, "filepath")
01686              * ... which infact should be
01687              * layout.prop(self.properties, "filepath")
01688              *
01689              * we need to do this trick.
01690              * if the prop is not an operator type and the pyobject is an operator,
01691              * use its properties in place of its self.
01692              *
01693              * this is so bad that its almost a good reason to do away with fake 'self.properties -> self' class mixing
01694              * if this causes problems in the future it should be removed.
01695              */
01696             if ((ptr_type == &RNA_AnyType) &&
01697                 (BPy_StructRNA_Check(value)) &&
01698                 (RNA_struct_is_a(((BPy_StructRNA *)value)->ptr.type, &RNA_Operator))
01699             ) {
01700                 value = PyObject_GetAttrString(value, "properties");
01701                 value_new = value;
01702             }
01703 
01704 
01705             /* if property is an OperatorProperties pointer and value is a map,
01706              * forward back to pyrna_pydict_to_props */
01707             if (RNA_struct_is_a(ptr_type, &RNA_OperatorProperties) && PyDict_Check(value)) {
01708                 PointerRNA opptr = RNA_property_pointer_get(ptr, prop);
01709                 return pyrna_pydict_to_props(&opptr, value, 0, error_prefix);
01710             }
01711 
01712             /* another exception, allow to pass a collection as an RNA property */
01713             if (Py_TYPE(value) == &pyrna_prop_collection_Type) { /* ok to ignore idprop collections */
01714                 PointerRNA c_ptr;
01715                 BPy_PropertyRNA *value_prop = (BPy_PropertyRNA *)value;
01716                 if (RNA_property_collection_type_get(&value_prop->ptr, value_prop->prop, &c_ptr)) {
01717                     value = pyrna_struct_CreatePyObject(&c_ptr);
01718                     value_new = value;
01719                 }
01720                 else {
01721                     PyErr_Format(PyExc_TypeError,
01722                                  "%.200s %.200s.%.200s collection has no type, "
01723                                  "cant be used as a %.200s type",
01724                                  error_prefix, RNA_struct_identifier(ptr->type),
01725                                  RNA_property_identifier(prop), RNA_struct_identifier(ptr_type));
01726                     return -1;
01727                 }
01728             }
01729 
01730             if (!BPy_StructRNA_Check(value) && value != Py_None) {
01731                 PyErr_Format(PyExc_TypeError,
01732                              "%.200s %.200s.%.200s expected a %.200s type, not %.200s",
01733                              error_prefix, RNA_struct_identifier(ptr->type),
01734                              RNA_property_identifier(prop), RNA_struct_identifier(ptr_type),
01735                              Py_TYPE(value)->tp_name);
01736                 Py_XDECREF(value_new); return -1;
01737             }
01738             else if ((flag & PROP_NEVER_NULL) && value == Py_None) {
01739                 PyErr_Format(PyExc_TypeError,
01740                              "%.200s %.200s.%.200s does not support a 'None' assignment %.200s type",
01741                              error_prefix, RNA_struct_identifier(ptr->type),
01742                              RNA_property_identifier(prop), RNA_struct_identifier(ptr_type));
01743                 Py_XDECREF(value_new); return -1;
01744             }
01745             else if ((value != Py_None) &&
01746                      ((flag & PROP_ID_SELF_CHECK) && ptr->id.data == ((BPy_StructRNA *)value)->ptr.id.data))
01747             {
01748                 PyErr_Format(PyExc_TypeError,
01749                              "%.200s %.200s.%.200s ID type does not support assignment to its self",
01750                              error_prefix, RNA_struct_identifier(ptr->type),
01751                              RNA_property_identifier(prop));
01752                 Py_XDECREF(value_new); return -1;
01753             }
01754             else {
01755                 BPy_StructRNA *param = (BPy_StructRNA *)value;
01756                 int raise_error = FALSE;
01757                 if (data) {
01758 
01759                     if (flag & PROP_RNAPTR) {
01760                         if (value == Py_None)
01761                             memset(data, 0, sizeof(PointerRNA));
01762                         else
01763                             *((PointerRNA *)data)= param->ptr;
01764                     }
01765                     else if (value == Py_None) {
01766                         *((void **)data)= NULL;
01767                     }
01768                     else if (RNA_struct_is_a(param->ptr.type, ptr_type)) {
01769                         *((void **)data)= param->ptr.data;
01770                     }
01771                     else {
01772                         raise_error = TRUE;
01773                     }
01774                 }
01775                 else {
01776                     /* data == NULL, assign to RNA */
01777                     if (value == Py_None) {
01778                         PointerRNA valueptr = {{NULL}};
01779                         RNA_property_pointer_set(ptr, prop, valueptr);
01780                     }
01781                     else if (RNA_struct_is_a(param->ptr.type, ptr_type)) {
01782                         RNA_property_pointer_set(ptr, prop, param->ptr);
01783                     }
01784                     else {
01785                         PointerRNA tmp;
01786                         RNA_pointer_create(NULL, ptr_type, NULL, &tmp);
01787                         PyErr_Format(PyExc_TypeError,
01788                                      "%.200s %.200s.%.200s expected a %.200s type. not %.200s",
01789                                      error_prefix, RNA_struct_identifier(ptr->type),
01790                                      RNA_property_identifier(prop), RNA_struct_identifier(tmp.type),
01791                                      RNA_struct_identifier(param->ptr.type));
01792                         Py_XDECREF(value_new); return -1;
01793                     }
01794                 }
01795 
01796                 if (raise_error) {
01797                     PointerRNA tmp;
01798                     RNA_pointer_create(NULL, ptr_type, NULL, &tmp);
01799                     PyErr_Format(PyExc_TypeError,
01800                                  "%.200s %.200s.%.200s expected a %.200s type, not %.200s",
01801                                  error_prefix, RNA_struct_identifier(ptr->type),
01802                                  RNA_property_identifier(prop), RNA_struct_identifier(tmp.type),
01803                                  RNA_struct_identifier(param->ptr.type));
01804                     Py_XDECREF(value_new); return -1;
01805                 }
01806             }
01807 
01808             Py_XDECREF(value_new);
01809 
01810             break;
01811         }
01812         case PROP_COLLECTION:
01813         {
01814             Py_ssize_t seq_len, i;
01815             PyObject *item;
01816             PointerRNA itemptr;
01817             ListBase *lb;
01818             CollectionPointerLink *link;
01819 
01820             lb = (data) ? (ListBase *)data : NULL;
01821 
01822             /* convert a sequence of dict's into a collection */
01823             if (!PySequence_Check(value)) {
01824                 PyErr_Format(PyExc_TypeError,
01825                              "%.200s %.200s.%.200s expected a sequence for an RNA collection, not %.200s",
01826                              error_prefix, RNA_struct_identifier(ptr->type),
01827                              RNA_property_identifier(prop), Py_TYPE(value)->tp_name);
01828                 return -1;
01829             }
01830 
01831             seq_len = PySequence_Size(value);
01832             for (i = 0; i < seq_len; i++) {
01833                 item = PySequence_GetItem(value, i);
01834 
01835                 if (item == NULL) {
01836                     PyErr_Format(PyExc_TypeError,
01837                                  "%.200s %.200s.%.200s failed to get sequence index '%d' for an RNA collection",
01838                                  error_prefix, RNA_struct_identifier(ptr->type),
01839                                  RNA_property_identifier(prop), i);
01840                     Py_XDECREF(item);
01841                     return -1;
01842                 }
01843 
01844                 if (PyDict_Check(item) == 0) {
01845                     PyErr_Format(PyExc_TypeError,
01846                                  "%.200s %.200s.%.200s expected a each sequence "
01847                                  "member to be a dict for an RNA collection, not %.200s",
01848                                  error_prefix, RNA_struct_identifier(ptr->type),
01849                                  RNA_property_identifier(prop), Py_TYPE(item)->tp_name);
01850                     Py_XDECREF(item);
01851                     return -1;
01852                 }
01853 
01854                 if (lb) {
01855                     link = MEM_callocN(sizeof(CollectionPointerLink), "PyCollectionPointerLink");
01856                     link->ptr = itemptr;
01857                     BLI_addtail(lb, link);
01858                 }
01859                 else
01860                     RNA_property_collection_add(ptr, prop, &itemptr);
01861 
01862                 if (pyrna_pydict_to_props(&itemptr, item, 1, "Converting a python list to an RNA collection") == -1) {
01863                     PyObject *msg = PyC_ExceptionBuffer();
01864                     const char *msg_char = _PyUnicode_AsString(msg);
01865 
01866                     PyErr_Format(PyExc_TypeError,
01867                                  "%.200s %.200s.%.200s error converting a member of a collection "
01868                                  "from a dicts into an RNA collection, failed with: %s",
01869                                  error_prefix, RNA_struct_identifier(ptr->type),
01870                                  RNA_property_identifier(prop), msg_char);
01871 
01872                     Py_DECREF(item);
01873                     Py_DECREF(msg);
01874                     return -1;
01875                 }
01876                 Py_DECREF(item);
01877             }
01878 
01879             break;
01880         }
01881         default:
01882             PyErr_Format(PyExc_AttributeError,
01883                          "%.200s %.200s.%.200s unknown property type (pyrna_py_to_prop)",
01884                          error_prefix, RNA_struct_identifier(ptr->type),
01885                          RNA_property_identifier(prop));
01886             return -1;
01887             break;
01888         }
01889     }
01890 
01891     /* Run rna property functions */
01892     if (RNA_property_update_check(prop)) {
01893         RNA_property_update(BPy_GetContext(), ptr, prop);
01894     }
01895 
01896     return 0;
01897 }
01898 
01899 static PyObject *pyrna_prop_array_to_py_index(BPy_PropertyArrayRNA *self, int index)
01900 {
01901     PYRNA_PROP_CHECK_OBJ((BPy_PropertyRNA *)self);
01902     return pyrna_py_from_array_index(self, &self->ptr, self->prop, index);
01903 }
01904 
01905 static int pyrna_py_to_prop_array_index(BPy_PropertyArrayRNA *self, int index, PyObject *value)
01906 {
01907     int ret = 0;
01908     PointerRNA *ptr = &self->ptr;
01909     PropertyRNA *prop = self->prop;
01910 
01911     const int totdim = RNA_property_array_dimension(ptr, prop, NULL);
01912 
01913     if (totdim > 1) {
01914         /* char error_str[512]; */
01915         if (pyrna_py_to_array_index(&self->ptr, self->prop, self->arraydim, self->arrayoffset, index, value, "") == -1) {
01916             /* error is set */
01917             ret = -1;
01918         }
01919     }
01920     else {
01921         /* see if we can coerce into a python type - PropertyType */
01922         switch (RNA_property_type(prop)) {
01923         case PROP_BOOLEAN:
01924             {
01925                 int param = PyLong_AsLong(value);
01926 
01927                 if (param < 0 || param > 1) {
01928                     PyErr_SetString(PyExc_TypeError, "expected True/False or 0/1");
01929                     ret = -1;
01930                 }
01931                 else {
01932                     RNA_property_boolean_set_index(ptr, prop, index, param);
01933                 }
01934                 break;
01935             }
01936         case PROP_INT:
01937             {
01938                 int param = PyLong_AsLong(value);
01939                 if (param == -1 && PyErr_Occurred()) {
01940                     PyErr_SetString(PyExc_TypeError, "expected an int type");
01941                     ret = -1;
01942                 }
01943                 else {
01944                     RNA_property_int_clamp(ptr, prop, &param);
01945                     RNA_property_int_set_index(ptr, prop, index, param);
01946                 }
01947                 break;
01948             }
01949         case PROP_FLOAT:
01950             {
01951                 float param = PyFloat_AsDouble(value);
01952                 if (PyErr_Occurred()) {
01953                     PyErr_SetString(PyExc_TypeError, "expected a float type");
01954                     ret = -1;
01955                 }
01956                 else {
01957                     RNA_property_float_clamp(ptr, prop, &param);
01958                     RNA_property_float_set_index(ptr, prop, index, param);
01959                 }
01960                 break;
01961             }
01962         default:
01963             PyErr_SetString(PyExc_AttributeError, "not an array type");
01964             ret = -1;
01965             break;
01966         }
01967     }
01968 
01969     /* Run rna property functions */
01970     if (RNA_property_update_check(prop)) {
01971         RNA_property_update(BPy_GetContext(), ptr, prop);
01972     }
01973 
01974     return ret;
01975 }
01976 
01977 //---------------sequence-------------------------------------------
01978 static Py_ssize_t pyrna_prop_array_length(BPy_PropertyArrayRNA *self)
01979 {
01980     PYRNA_PROP_CHECK_INT((BPy_PropertyRNA *)self);
01981 
01982     if (RNA_property_array_dimension(&self->ptr, self->prop, NULL) > 1)
01983         return RNA_property_multi_array_length(&self->ptr, self->prop, self->arraydim);
01984     else
01985         return RNA_property_array_length(&self->ptr, self->prop);
01986 }
01987 
01988 static Py_ssize_t pyrna_prop_collection_length(BPy_PropertyRNA *self)
01989 {
01990     PYRNA_PROP_CHECK_INT(self);
01991 
01992     return RNA_property_collection_length(&self->ptr, self->prop);
01993 }
01994 
01995 /* bool functions are for speed, so we can avoid getting the length
01996  * of 1000's of items in a linked list for eg. */
01997 static int pyrna_prop_array_bool(BPy_PropertyRNA *self)
01998 {
01999     PYRNA_PROP_CHECK_INT(self);
02000 
02001     return RNA_property_array_length(&self->ptr, self->prop) ? 1 : 0;
02002 }
02003 
02004 static int pyrna_prop_collection_bool(BPy_PropertyRNA *self)
02005 {
02006     /* no callback defined, just iterate and find the nth item */
02007     CollectionPropertyIterator iter;
02008     int test;
02009 
02010     PYRNA_PROP_CHECK_INT(self);
02011 
02012     RNA_property_collection_begin(&self->ptr, self->prop, &iter);
02013     test = iter.valid;
02014     RNA_property_collection_end(&iter);
02015     return test;
02016 }
02017 
02018 
02019 /* notice getting the length of the collection is avoided unless negative
02020  * index is used or to detect internal error with a valid index.
02021  * This is done for faster lookups. */
02022 #define PYRNA_PROP_COLLECTION_ABS_INDEX(ret_err)                              \
02023     if (keynum < 0) {                                                         \
02024         keynum_abs += RNA_property_collection_length(&self->ptr, self->prop); \
02025         if (keynum_abs < 0) {                                                 \
02026             PyErr_Format(PyExc_IndexError,                                    \
02027                          "bpy_prop_collection[%d]: out of range.", keynum);   \
02028             return ret_err;                                                   \
02029         }                                                                     \
02030     }                                                                         \
02031 
02032 
02033 /* internal use only */
02034 static PyObject *pyrna_prop_collection_subscript_int(BPy_PropertyRNA *self, Py_ssize_t keynum)
02035 {
02036     PointerRNA newptr;
02037     Py_ssize_t keynum_abs = keynum;
02038 
02039     PYRNA_PROP_CHECK_OBJ(self);
02040 
02041     PYRNA_PROP_COLLECTION_ABS_INDEX(NULL);
02042 
02043     if (RNA_property_collection_lookup_int(&self->ptr, self->prop, keynum_abs, &newptr)) {
02044         return pyrna_struct_CreatePyObject(&newptr);
02045     }
02046     else {
02047         const int len = RNA_property_collection_length(&self->ptr, self->prop);
02048         if (keynum_abs >= len) {
02049             PyErr_Format(PyExc_IndexError,
02050                          "bpy_prop_collection[index]: "
02051                          "index %d out of range, size %d", keynum, len);
02052         }
02053         else {
02054             PyErr_Format(PyExc_RuntimeError,
02055                          "bpy_prop_collection[index]: internal error, "
02056                          "valid index %d given in %d sized collection but value not found",
02057                          keynum_abs, len);
02058         }
02059 
02060         return NULL;
02061     }
02062 }
02063 
02064 /* values type must have been already checked */
02065 static int pyrna_prop_collection_ass_subscript_int(BPy_PropertyRNA *self, Py_ssize_t keynum, PyObject *value)
02066 {
02067     Py_ssize_t keynum_abs = keynum;
02068     const PointerRNA *ptr = (value == Py_None) ? (&PointerRNA_NULL) : &((BPy_StructRNA *)value)->ptr;
02069 
02070     PYRNA_PROP_CHECK_INT(self);
02071 
02072     PYRNA_PROP_COLLECTION_ABS_INDEX(-1);
02073 
02074     if (RNA_property_collection_assign_int(&self->ptr, self->prop, keynum_abs, ptr) == 0) {
02075         const int len = RNA_property_collection_length(&self->ptr, self->prop);
02076         if (keynum_abs >= len) {
02077             PyErr_Format(PyExc_IndexError,
02078                          "bpy_prop_collection[index] = value: "
02079                          "index %d out of range, size %d", keynum, len);
02080         }
02081         else {
02082 
02083             PyErr_Format(PyExc_IndexError,
02084                          "bpy_prop_collection[index] = value: "
02085                          "failed assignment (unknown reason)", keynum);
02086         }
02087         return -1;
02088     }
02089 
02090     return 0;
02091 }
02092 
02093 static PyObject *pyrna_prop_array_subscript_int(BPy_PropertyArrayRNA *self, int keynum)
02094 {
02095     int len;
02096 
02097     PYRNA_PROP_CHECK_OBJ((BPy_PropertyRNA *)self);
02098 
02099     len = pyrna_prop_array_length(self);
02100 
02101     if (keynum < 0) keynum += len;
02102 
02103     if (keynum >= 0 && keynum < len)
02104         return pyrna_prop_array_to_py_index(self, keynum);
02105 
02106     PyErr_Format(PyExc_IndexError,
02107                  "bpy_prop_array[index]: index %d out of range", keynum);
02108     return NULL;
02109 }
02110 
02111 static PyObject *pyrna_prop_collection_subscript_str(BPy_PropertyRNA *self, const char *keyname)
02112 {
02113     PointerRNA newptr;
02114 
02115     PYRNA_PROP_CHECK_OBJ(self);
02116 
02117     if (RNA_property_collection_lookup_string(&self->ptr, self->prop, keyname, &newptr))
02118         return pyrna_struct_CreatePyObject(&newptr);
02119 
02120     PyErr_Format(PyExc_KeyError, "bpy_prop_collection[key]: key \"%.200s\" not found", keyname);
02121     return NULL;
02122 }
02123 /* static PyObject *pyrna_prop_array_subscript_str(BPy_PropertyRNA *self, char *keyname) */
02124 
02125 /* special case: bpy.data.objects["some_id_name", "//some_lib_name.blend"]
02126  * also for:     bpy.data.objects.get(("some_id_name", "//some_lib_name.blend"), fallback)
02127  *
02128  * note:
02129  * error codes since this is not to be called directly from python,
02130  * this matches pythons __contains__ values capi.
02131  * -1: exception set
02132  *  0: not found
02133  *  1: found */
02134 int pyrna_prop_collection_subscript_str_lib_pair_ptr(BPy_PropertyRNA *self, PyObject *key,
02135                                                      const char *err_prefix, const short err_not_found,
02136                                                      PointerRNA *r_ptr
02137                                                      )
02138 {
02139     char *keyname;
02140 
02141     /* first validate the args, all we know is that they are a tuple */
02142     if (PyTuple_GET_SIZE(key) != 2) {
02143         PyErr_Format(PyExc_KeyError,
02144                      "%s: tuple key must be a pair, not size %d",
02145                      err_prefix, PyTuple_GET_SIZE(key));
02146         return -1;
02147     }
02148     else if (self->ptr.type != &RNA_BlendData) {
02149         PyErr_Format(PyExc_KeyError,
02150                      "%s: is only valid for bpy.data collections, not %.200s",
02151                      err_prefix, RNA_struct_identifier(self->ptr.type));
02152         return -1;
02153     }
02154     else if ((keyname = _PyUnicode_AsString(PyTuple_GET_ITEM(key, 0))) == NULL) {
02155         PyErr_Format(PyExc_KeyError,
02156                      "%s: id must be a string, not %.200s",
02157                      err_prefix, Py_TYPE(PyTuple_GET_ITEM(key, 0))->tp_name);
02158         return -1;
02159     }
02160     else {
02161         PyObject *keylib = PyTuple_GET_ITEM(key, 1);
02162         Library *lib;
02163         int found = FALSE;
02164 
02165         if (keylib == Py_None) {
02166             lib = NULL;
02167         }
02168         else if (PyUnicode_Check(keylib)) {
02169             Main *bmain = self->ptr.data;
02170             const char *keylib_str = _PyUnicode_AsString(keylib);
02171             lib = BLI_findstring(&bmain->library, keylib_str, offsetof(Library, name));
02172             if (lib == NULL) {
02173                 if (err_not_found) {
02174                     PyErr_Format(PyExc_KeyError,
02175                                  "%s: lib name '%.240s' "
02176                                  "does not reference a valid library",
02177                                  err_prefix, keylib_str);
02178                     return -1;
02179                 }
02180                 else {
02181                     return 0;
02182                 }
02183 
02184             }
02185         }
02186         else {
02187             PyErr_Format(PyExc_KeyError,
02188                          "%s: lib must be a sting or None, not %.200s",
02189                          err_prefix, Py_TYPE(keylib)->tp_name);
02190             return -1;
02191         }
02192 
02193         /* lib is either a valid poniter or NULL,
02194          * either way can do direct comparison with id.lib */
02195 
02196         RNA_PROP_BEGIN(&self->ptr, itemptr, self->prop) {
02197             ID *id = itemptr.data; /* always an ID */
02198             if (id->lib == lib && (strncmp(keyname, id->name + 2, sizeof(id->name) - 2) == 0)) {
02199                 found = TRUE;
02200                 if (r_ptr) {
02201                     *r_ptr = itemptr;
02202                 }
02203                 break;
02204             }
02205         }
02206         RNA_PROP_END;
02207 
02208         /* we may want to fail silently as with collection.get() */
02209         if ((found == FALSE) && err_not_found) {
02210             /* only runs for getitem access so use fixed string */
02211             PyErr_SetString(PyExc_KeyError,
02212                             "bpy_prop_collection[key, lib]: not found");
02213             return -1;
02214         }
02215         else {
02216             return found; /* 1 / 0, no exception */
02217         }
02218     }
02219 }
02220 
02221 static PyObject *pyrna_prop_collection_subscript_str_lib_pair(BPy_PropertyRNA *self, PyObject *key,
02222                                                               const char *err_prefix, const short err_not_found)
02223 {
02224     PointerRNA ptr;
02225     const int contains = pyrna_prop_collection_subscript_str_lib_pair_ptr(self, key, err_prefix, err_not_found, &ptr);
02226 
02227     if (contains == 1) {
02228         return pyrna_struct_CreatePyObject(&ptr);
02229     }
02230     else {
02231         return NULL;
02232     }
02233 }
02234 
02235 
02236 static PyObject *pyrna_prop_collection_subscript_slice(BPy_PropertyRNA *self, Py_ssize_t start, Py_ssize_t stop)
02237 {
02238     CollectionPropertyIterator rna_macro_iter;
02239     int count = 0;
02240 
02241     PyObject *list;
02242     PyObject *item;
02243 
02244     PYRNA_PROP_CHECK_OBJ(self);
02245 
02246     list = PyList_New(0);
02247 
02248     /* first loop up-until the start */
02249     for (RNA_property_collection_begin(&self->ptr, self->prop, &rna_macro_iter);
02250          rna_macro_iter.valid;
02251          RNA_property_collection_next(&rna_macro_iter))
02252     {
02253         /* PointerRNA itemptr = rna_macro_iter.ptr; */
02254         if (count == start) {
02255             break;
02256         }
02257         count++;
02258     }
02259 
02260     /* add items until stop */
02261     for (; rna_macro_iter.valid;
02262          RNA_property_collection_next(&rna_macro_iter))
02263     {
02264         item = pyrna_struct_CreatePyObject(&rna_macro_iter.ptr);
02265         PyList_Append(list, item);
02266         Py_DECREF(item);
02267 
02268         count++;
02269         if (count == stop) {
02270             break;
02271         }
02272     }
02273 
02274     RNA_property_collection_end(&rna_macro_iter);
02275 
02276     return list;
02277 }
02278 
02279 /* TODO - dimensions
02280  * note: could also use pyrna_prop_array_to_py_index(self, count) in a loop but its a lot slower
02281  * since at the moment it reads (and even allocates) the entire array for each index.
02282  */
02283 static PyObject *pyrna_prop_array_subscript_slice(BPy_PropertyArrayRNA *self, PointerRNA *ptr, PropertyRNA *prop,
02284                                                   Py_ssize_t start, Py_ssize_t stop, Py_ssize_t length)
02285 {
02286     int count, totdim;
02287     PyObject *tuple;
02288 
02289     PYRNA_PROP_CHECK_OBJ((BPy_PropertyRNA *)self);
02290 
02291     tuple = PyTuple_New(stop - start);
02292 
02293     /* PYRNA_PROP_CHECK_OBJ(self); isn't needed, internal use only */
02294 
02295     totdim = RNA_property_array_dimension(ptr, prop, NULL);
02296 
02297     if (totdim > 1) {
02298         for (count = start; count < stop; count++)
02299             PyTuple_SET_ITEM(tuple, count - start, pyrna_prop_array_to_py_index(self, count));
02300     }
02301     else {
02302         switch (RNA_property_type(prop)) {
02303         case PROP_FLOAT:
02304             {
02305                 float values_stack[PYRNA_STACK_ARRAY];
02306                 float *values;
02307                 if (length > PYRNA_STACK_ARRAY) { values = PyMem_MALLOC(sizeof(float) * length); }
02308                 else                            { values = values_stack; }
02309                 RNA_property_float_get_array(ptr, prop, values);
02310 
02311                 for (count = start; count < stop; count++)
02312                     PyTuple_SET_ITEM(tuple, count-start, PyFloat_FromDouble(values[count]));
02313 
02314                 if (values != values_stack) {
02315                     PyMem_FREE(values);
02316                 }
02317                 break;
02318             }
02319         case PROP_BOOLEAN:
02320             {
02321                 int values_stack[PYRNA_STACK_ARRAY];
02322                 int *values;
02323                 if (length > PYRNA_STACK_ARRAY) { values = PyMem_MALLOC(sizeof(int) * length); }
02324                 else                            { values = values_stack; }
02325 
02326                 RNA_property_boolean_get_array(ptr, prop, values);
02327                 for (count = start; count < stop; count++)
02328                     PyTuple_SET_ITEM(tuple, count-start, PyBool_FromLong(values[count]));
02329 
02330                 if (values != values_stack) {
02331                     PyMem_FREE(values);
02332                 }
02333                 break;
02334             }
02335         case PROP_INT:
02336             {
02337                 int values_stack[PYRNA_STACK_ARRAY];
02338                 int *values;
02339                 if (length > PYRNA_STACK_ARRAY) { values = PyMem_MALLOC(sizeof(int) * length); }
02340                 else                            { values = values_stack; }
02341 
02342                 RNA_property_int_get_array(ptr, prop, values);
02343                 for (count = start; count < stop; count++)
02344                     PyTuple_SET_ITEM(tuple, count-start, PyLong_FromSsize_t(values[count]));
02345 
02346                 if (values != values_stack) {
02347                     PyMem_FREE(values);
02348                 }
02349                 break;
02350             }
02351         default:
02352             BLI_assert(!"Invalid array type");
02353 
02354             PyErr_SetString(PyExc_TypeError, "not an array type");
02355             Py_DECREF(tuple);
02356             tuple = NULL;
02357         }
02358     }
02359     return tuple;
02360 }
02361 
02362 static PyObject *pyrna_prop_collection_subscript(BPy_PropertyRNA *self, PyObject *key)
02363 {
02364     PYRNA_PROP_CHECK_OBJ(self);
02365 
02366     if (PyUnicode_Check(key)) {
02367         return pyrna_prop_collection_subscript_str(self, _PyUnicode_AsString(key));
02368     }
02369     else if (PyIndex_Check(key)) {
02370         Py_ssize_t i = PyNumber_AsSsize_t(key, PyExc_IndexError);
02371         if (i == -1 && PyErr_Occurred())
02372             return NULL;
02373 
02374         return pyrna_prop_collection_subscript_int(self, i);
02375     }
02376     else if (PySlice_Check(key)) {
02377         PySliceObject *key_slice = (PySliceObject *)key;
02378         Py_ssize_t step = 1;
02379 
02380         if (key_slice->step != Py_None && !_PyEval_SliceIndex(key, &step)) {
02381             return NULL;
02382         }
02383         else if (step != 1) {
02384             PyErr_SetString(PyExc_TypeError, "bpy_prop_collection[slice]: slice steps not supported");
02385             return NULL;
02386         }
02387         else if (key_slice->start == Py_None && key_slice->stop == Py_None) {
02388             return pyrna_prop_collection_subscript_slice(self, 0, PY_SSIZE_T_MAX);
02389         }
02390         else {
02391             Py_ssize_t start = 0, stop = PY_SSIZE_T_MAX;
02392 
02393             /* avoid PySlice_GetIndicesEx because it needs to know the length ahead of time. */
02394             if (key_slice->start != Py_None && !_PyEval_SliceIndex(key_slice->start, &start)) return NULL;
02395             if (key_slice->stop != Py_None && !_PyEval_SliceIndex(key_slice->stop, &stop))    return NULL;
02396 
02397             if (start < 0 || stop < 0) {
02398                 /* only get the length for negative values */
02399                 Py_ssize_t len = (Py_ssize_t)RNA_property_collection_length(&self->ptr, self->prop);
02400                 if (start < 0) start += len;
02401                 if (stop < 0) start += len;
02402             }
02403 
02404             if (stop - start <= 0) {
02405                 return PyList_New(0);
02406             }
02407             else {
02408                 return pyrna_prop_collection_subscript_slice(self, start, stop);
02409             }
02410         }
02411     }
02412     else if (PyTuple_Check(key)) {
02413         /* special case, for ID datablocks we */
02414         return pyrna_prop_collection_subscript_str_lib_pair(self, key,
02415                                                             "bpy_prop_collection[id, lib]", TRUE);
02416     }
02417     else {
02418         PyErr_Format(PyExc_TypeError,
02419                      "bpy_prop_collection[key]: invalid key, "
02420                      "must be a string or an int, not %.200s",
02421                      Py_TYPE(key)->tp_name);
02422         return NULL;
02423     }
02424 }
02425 
02426 /* generic check to see if a PyObject is compatible with a collection
02427  * -1 on failure, 0 on success, sets the error */
02428 static int pyrna_prop_collection_type_check(BPy_PropertyRNA *self, PyObject *value)
02429 {
02430     StructRNA *prop_srna;
02431 
02432     if (value == Py_None) {
02433         if (RNA_property_flag(self->prop) & PROP_NEVER_NULL) {
02434             PyErr_Format(PyExc_TypeError,
02435                          "bpy_prop_collection[key] = value: invalid, "
02436                          "this collection doesnt support None assignment");
02437             return -1;
02438         }
02439         else {
02440             return 0; /* None is OK */
02441         }
02442     }
02443     else if (BPy_StructRNA_Check(value) == 0) {
02444         PyErr_Format(PyExc_TypeError,
02445                      "bpy_prop_collection[key] = value: invalid, "
02446                      "expected a StructRNA type or None, not a %.200s",
02447                      Py_TYPE(value)->tp_name);
02448         return -1;
02449     }
02450     else if ((prop_srna = RNA_property_pointer_type(&self->ptr, self->prop))) {
02451         StructRNA *value_srna = ((BPy_StructRNA *)value)->ptr.type;
02452         if (RNA_struct_is_a(value_srna, prop_srna) == 0) {
02453             PyErr_Format(PyExc_TypeError,
02454                          "bpy_prop_collection[key] = value: invalid, "
02455                          "expected a '%.200s' type or None, not a '%.200s'",
02456                          RNA_struct_identifier(prop_srna),
02457                          RNA_struct_identifier(value_srna)
02458                          );
02459             return -1;
02460         }
02461         else {
02462             return 0; /* OK, this is the correct type!*/
02463         }
02464     }
02465 
02466     PyErr_Format(PyExc_TypeError,
02467                  "bpy_prop_collection[key] = value: internal error, "
02468                  "failed to get the collection type");
02469     return -1;
02470 }
02471 
02472 /* note: currently this is a copy of 'pyrna_prop_collection_subscript' with
02473  * large blocks commented, we may support slice/key indicies later */
02474 static int pyrna_prop_collection_ass_subscript(BPy_PropertyRNA *self, PyObject *key, PyObject *value)
02475 {
02476     PYRNA_PROP_CHECK_INT(self);
02477 
02478     /* validate the assigned value */
02479     if (value == NULL) {
02480         PyErr_SetString(PyExc_TypeError,
02481                         "del bpy_prop_collection[key]: not supported");
02482         return -1;
02483     }
02484     else if (pyrna_prop_collection_type_check(self, value) == -1) {
02485         return -1; /* exception is set */
02486     }
02487 
02488 #if 0
02489     if (PyUnicode_Check(key)) {
02490         return pyrna_prop_collection_subscript_str(self, _PyUnicode_AsString(key));
02491     }
02492     else
02493 #endif
02494     if (PyIndex_Check(key)) {
02495         Py_ssize_t i = PyNumber_AsSsize_t(key, PyExc_IndexError);
02496         if (i == -1 && PyErr_Occurred())
02497             return -1;
02498 
02499         return pyrna_prop_collection_ass_subscript_int(self, i, value);
02500     }
02501 #if 0 /* TODO, fake slice assignment */
02502     else if (PySlice_Check(key)) {
02503         PySliceObject *key_slice = (PySliceObject *)key;
02504         Py_ssize_t step = 1;
02505 
02506         if (key_slice->step != Py_None && !_PyEval_SliceIndex(key, &step)) {
02507             return NULL;
02508         }
02509         else if (step != 1) {
02510             PyErr_SetString(PyExc_TypeError, "bpy_prop_collection[slice]: slice steps not supported");
02511             return NULL;
02512         }
02513         else if (key_slice->start == Py_None && key_slice->stop == Py_None) {
02514             return pyrna_prop_collection_subscript_slice(self, 0, PY_SSIZE_T_MAX);
02515         }
02516         else {
02517             Py_ssize_t start = 0, stop = PY_SSIZE_T_MAX;
02518 
02519             /* avoid PySlice_GetIndicesEx because it needs to know the length ahead of time. */
02520             if (key_slice->start != Py_None && !_PyEval_SliceIndex(key_slice->start, &start))   return NULL;
02521             if (key_slice->stop != Py_None && !_PyEval_SliceIndex(key_slice->stop, &stop))      return NULL;
02522 
02523             if (start < 0 || stop < 0) {
02524                 /* only get the length for negative values */
02525                 Py_ssize_t len = (Py_ssize_t)RNA_property_collection_length(&self->ptr, self->prop);
02526                 if (start < 0) start += len;
02527                 if (stop < 0) start += len;
02528             }
02529 
02530             if (stop - start <= 0) {
02531                 return PyList_New(0);
02532             }
02533             else {
02534                 return pyrna_prop_collection_subscript_slice(self, start, stop);
02535             }
02536         }
02537     }
02538 #endif
02539     else {
02540         PyErr_Format(PyExc_TypeError,
02541                      "bpy_prop_collection[key]: invalid key, "
02542                      "must be a string or an int, not %.200s",
02543                      Py_TYPE(key)->tp_name);
02544         return -1;
02545     }
02546 }
02547 
02548 static PyObject *pyrna_prop_array_subscript(BPy_PropertyArrayRNA *self, PyObject *key)
02549 {
02550     PYRNA_PROP_CHECK_OBJ((BPy_PropertyRNA *)self);
02551 
02552     /*if (PyUnicode_Check(key)) {
02553         return pyrna_prop_array_subscript_str(self, _PyUnicode_AsString(key));
02554     }
02555     else */
02556     if (PyIndex_Check(key)) {
02557         Py_ssize_t i = PyNumber_AsSsize_t(key, PyExc_IndexError);
02558         if (i == -1 && PyErr_Occurred())
02559             return NULL;
02560         return pyrna_prop_array_subscript_int(self, PyLong_AsLong(key));
02561     }
02562     else if (PySlice_Check(key)) {
02563         Py_ssize_t step = 1;
02564         PySliceObject *key_slice = (PySliceObject *)key;
02565 
02566         if (key_slice->step != Py_None && !_PyEval_SliceIndex(key, &step)) {
02567             return NULL;
02568         }
02569         else if (step != 1) {
02570             PyErr_SetString(PyExc_TypeError, "bpy_prop_array[slice]: slice steps not supported");
02571             return NULL;
02572         }
02573         else if (key_slice->start == Py_None && key_slice->stop == Py_None) {
02574             /* note, no significant advantage with optimizing [:] slice as with collections but include here for consistency with collection slice func */
02575             Py_ssize_t len = (Py_ssize_t)pyrna_prop_array_length(self);
02576             return pyrna_prop_array_subscript_slice(self, &self->ptr, self->prop, 0, len, len);
02577         }
02578         else {
02579             int len = pyrna_prop_array_length(self);
02580             Py_ssize_t start, stop, slicelength;
02581 
02582             if (PySlice_GetIndicesEx((void *)key, len, &start, &stop, &step, &slicelength) < 0)
02583                 return NULL;
02584 
02585             if (slicelength <= 0) {
02586                 return PyTuple_New(0);
02587             }
02588             else {
02589                 return pyrna_prop_array_subscript_slice(self, &self->ptr, self->prop, start, stop, len);
02590             }
02591         }
02592     }
02593     else {
02594         PyErr_SetString(PyExc_AttributeError, "bpy_prop_array[key]: invalid key, key must be an int");
02595         return NULL;
02596     }
02597 }
02598 
02599 /* could call (pyrna_py_to_prop_array_index(self, i, value) in a loop but it is slow */
02600 static int prop_subscript_ass_array_slice(PointerRNA *ptr, PropertyRNA *prop,
02601                                           int start, int stop, int length, PyObject *value_orig)
02602 {
02603     PyObject *value;
02604     int count;
02605     void *values_alloc = NULL;
02606     int ret = 0;
02607 
02608     if (value_orig == NULL) {
02609         PyErr_SetString(PyExc_TypeError,
02610                         "bpy_prop_array[slice] = value: deleting with list types is not supported by bpy_struct");
02611         return -1;
02612     }
02613 
02614     if (!(value = PySequence_Fast(value_orig, "bpy_prop_array[slice] = value: assignment is not a sequence type"))) {
02615         return -1;
02616     }
02617 
02618     if (PySequence_Fast_GET_SIZE(value) != stop-start) {
02619         Py_DECREF(value);
02620         PyErr_SetString(PyExc_TypeError,
02621                         "bpy_prop_array[slice] = value: resizing bpy_struct arrays isn't supported");
02622         return -1;
02623     }
02624 
02625     switch (RNA_property_type(prop)) {
02626         case PROP_FLOAT:
02627         {
02628             float values_stack[PYRNA_STACK_ARRAY];
02629             float *values, fval;
02630 
02631             float min, max;
02632             RNA_property_float_range(ptr, prop, &min, &max);
02633 
02634             if (length > PYRNA_STACK_ARRAY) { values = values_alloc = PyMem_MALLOC(sizeof(float) * length); }
02635             else                            { values = values_stack; }
02636             if (start != 0 || stop != length) /* partial assignment? - need to get the array */
02637                 RNA_property_float_get_array(ptr, prop, values);
02638 
02639             for (count = start; count < stop; count++) {
02640                 fval = PyFloat_AsDouble(PySequence_Fast_GET_ITEM(value, count-start));
02641                 CLAMP(fval, min, max);
02642                 values[count] = fval;
02643             }
02644 
02645             if (PyErr_Occurred()) ret = -1;
02646             else                  RNA_property_float_set_array(ptr, prop, values);
02647             break;
02648         }
02649         case PROP_BOOLEAN:
02650         {
02651             int values_stack[PYRNA_STACK_ARRAY];
02652             int *values;
02653             if (length > PYRNA_STACK_ARRAY) { values = values_alloc = PyMem_MALLOC(sizeof(int) * length); }
02654             else                            { values = values_stack; }
02655 
02656             if (start != 0 || stop != length) /* partial assignment? - need to get the array */
02657                 RNA_property_boolean_get_array(ptr, prop, values);
02658 
02659             for (count = start; count < stop; count++)
02660                 values[count] = PyLong_AsLong(PySequence_Fast_GET_ITEM(value, count-start));
02661 
02662             if (PyErr_Occurred()) ret = -1;
02663             else                  RNA_property_boolean_set_array(ptr, prop, values);
02664             break;
02665         }
02666         case PROP_INT:
02667         {
02668             int values_stack[PYRNA_STACK_ARRAY];
02669             int *values, ival;
02670 
02671             int min, max;
02672             RNA_property_int_range(ptr, prop, &min, &max);
02673 
02674             if (length > PYRNA_STACK_ARRAY) { values = values_alloc = PyMem_MALLOC(sizeof(int) * length); }
02675             else                            { values = values_stack; }
02676 
02677             if (start != 0 || stop != length) /* partial assignment? - need to get the array */
02678                 RNA_property_int_get_array(ptr, prop, values);
02679 
02680             for (count = start; count < stop; count++) {
02681                 ival = PyLong_AsLong(PySequence_Fast_GET_ITEM(value, count-start));
02682                 CLAMP(ival, min, max);
02683                 values[count] = ival;
02684             }
02685 
02686             if (PyErr_Occurred()) ret = -1;
02687             else                  RNA_property_int_set_array(ptr, prop, values);
02688             break;
02689         }
02690         default:
02691             PyErr_SetString(PyExc_TypeError, "not an array type");
02692             ret = -1;
02693     }
02694 
02695     Py_DECREF(value);
02696 
02697     if (values_alloc) {
02698         PyMem_FREE(values_alloc);
02699     }
02700 
02701     return ret;
02702 
02703 }
02704 
02705 static int prop_subscript_ass_array_int(BPy_PropertyArrayRNA *self, Py_ssize_t keynum, PyObject *value)
02706 {
02707     int len;
02708 
02709     PYRNA_PROP_CHECK_INT((BPy_PropertyRNA *)self);
02710 
02711     len = pyrna_prop_array_length(self);
02712 
02713     if (keynum < 0) keynum += len;
02714 
02715     if (keynum >= 0 && keynum < len)
02716         return pyrna_py_to_prop_array_index(self, keynum, value);
02717 
02718     PyErr_SetString(PyExc_IndexError,
02719                     "bpy_prop_array[index] = value: index out of range");
02720     return -1;
02721 }
02722 
02723 static int pyrna_prop_array_ass_subscript(BPy_PropertyArrayRNA *self, PyObject *key, PyObject *value)
02724 {
02725     /* char *keyname = NULL; */ /* not supported yet */
02726     int ret = -1;
02727 
02728     PYRNA_PROP_CHECK_INT((BPy_PropertyRNA *)self);
02729 
02730     if (!RNA_property_editable_flag(&self->ptr, self->prop)) {
02731         PyErr_Format(PyExc_AttributeError,
02732                      "bpy_prop_collection: attribute \"%.200s\" from \"%.200s\" is read-only",
02733                      RNA_property_identifier(self->prop), RNA_struct_identifier(self->ptr.type));
02734         ret = -1;
02735     }
02736 
02737     else if (PyIndex_Check(key)) {
02738         Py_ssize_t i = PyNumber_AsSsize_t(key, PyExc_IndexError);
02739         if (i == -1 && PyErr_Occurred()) {
02740             ret = -1;
02741         }
02742         else {
02743             ret = prop_subscript_ass_array_int(self, i, value);
02744         }
02745     }
02746     else if (PySlice_Check(key)) {
02747         int len = RNA_property_array_length(&self->ptr, self->prop);
02748         Py_ssize_t start, stop, step, slicelength;
02749 
02750         if (PySlice_GetIndicesEx((void *)key, len, &start, &stop, &step, &slicelength) < 0) {
02751             ret = -1;
02752         }
02753         else if (slicelength <= 0) {
02754             ret = 0; /* do nothing */
02755         }
02756         else if (step == 1) {
02757             ret = prop_subscript_ass_array_slice(&self->ptr, self->prop, start, stop, len, value);
02758         }
02759         else {
02760             PyErr_SetString(PyExc_TypeError, "slice steps not supported with rna");
02761             ret = -1;
02762         }
02763     }
02764     else {
02765         PyErr_SetString(PyExc_AttributeError, "invalid key, key must be an int");
02766         ret = -1;
02767     }
02768 
02769     if (ret != -1) {
02770         if (RNA_property_update_check(self->prop)) {
02771             RNA_property_update(BPy_GetContext(), &self->ptr, self->prop);
02772         }
02773     }
02774 
02775     return ret;
02776 }
02777 
02778 /* for slice only */
02779 static PyMappingMethods pyrna_prop_array_as_mapping = {
02780     (lenfunc) pyrna_prop_array_length,  /* mp_length */
02781     (binaryfunc) pyrna_prop_array_subscript,    /* mp_subscript */
02782     (objobjargproc) pyrna_prop_array_ass_subscript, /* mp_ass_subscript */
02783 };
02784 
02785 static PyMappingMethods pyrna_prop_collection_as_mapping = {
02786     (lenfunc) pyrna_prop_collection_length, /* mp_length */
02787     (binaryfunc) pyrna_prop_collection_subscript,   /* mp_subscript */
02788     (objobjargproc) pyrna_prop_collection_ass_subscript,    /* mp_ass_subscript */
02789 };
02790 
02791 /* only for fast bool's, large structs, assign nb_bool on init */
02792 static PyNumberMethods pyrna_prop_array_as_number = {
02793     NULL, /* nb_add */
02794     NULL, /* nb_subtract */
02795     NULL, /* nb_multiply */
02796     NULL, /* nb_remainder */
02797     NULL, /* nb_divmod */
02798     NULL, /* nb_power */
02799     NULL, /* nb_negative */
02800     NULL, /* nb_positive */
02801     NULL, /* nb_absolute */
02802     (inquiry) pyrna_prop_array_bool, /* nb_bool */
02803 };
02804 static PyNumberMethods pyrna_prop_collection_as_number = {
02805     NULL, /* nb_add */
02806     NULL, /* nb_subtract */
02807     NULL, /* nb_multiply */
02808     NULL, /* nb_remainder */
02809     NULL, /* nb_divmod */
02810     NULL, /* nb_power */
02811     NULL, /* nb_negative */
02812     NULL, /* nb_positive */
02813     NULL, /* nb_absolute */
02814     (inquiry) pyrna_prop_collection_bool, /* nb_bool */
02815 };
02816 
02817 static int pyrna_prop_array_contains(BPy_PropertyRNA *self, PyObject *value)
02818 {
02819     return pyrna_array_contains_py(&self->ptr, self->prop, value);
02820 }
02821 
02822 static int pyrna_prop_collection_contains(BPy_PropertyRNA *self, PyObject *key)
02823 {
02824     PointerRNA newptr; /* not used, just so RNA_property_collection_lookup_string runs */
02825 
02826     if (PyTuple_Check(key)) {
02827         /* special case, for ID datablocks we */
02828         return pyrna_prop_collection_subscript_str_lib_pair_ptr(self, key,
02829                                                                 "(id, lib) in bpy_prop_collection", FALSE, NULL);
02830     }
02831     else {
02832 
02833         /* key in dict style check */
02834         const char *keyname = _PyUnicode_AsString(key);
02835 
02836         if (keyname == NULL) {
02837             PyErr_SetString(PyExc_TypeError, "bpy_prop_collection.__contains__: expected a string or a typle of strings");
02838             return -1;
02839         }
02840 
02841         if (RNA_property_collection_lookup_string(&self->ptr, self->prop, keyname, &newptr))
02842             return 1;
02843 
02844         return 0;
02845     }
02846 }
02847 
02848 static int pyrna_struct_contains(BPy_StructRNA *self, PyObject *value)
02849 {
02850     IDProperty *group;
02851     const char *name = _PyUnicode_AsString(value);
02852 
02853     PYRNA_STRUCT_CHECK_INT(self);
02854 
02855     if (!name) {
02856         PyErr_SetString(PyExc_TypeError, "bpy_struct.__contains__: expected a string");
02857         return -1;
02858     }
02859 
02860     if (RNA_struct_idprops_check(self->ptr.type) == 0) {
02861         PyErr_SetString(PyExc_TypeError, "bpy_struct: this type doesn't support IDProperties");
02862         return -1;
02863     }
02864 
02865     group = RNA_struct_idprops(&self->ptr, 0);
02866 
02867     if (!group)
02868         return 0;
02869 
02870     return IDP_GetPropertyFromGroup(group, name) ? 1:0;
02871 }
02872 
02873 static PySequenceMethods pyrna_prop_array_as_sequence = {
02874     (lenfunc)pyrna_prop_array_length,       /* Cant set the len otherwise it can evaluate as false */
02875     NULL,       /* sq_concat */
02876     NULL,       /* sq_repeat */
02877     (ssizeargfunc)pyrna_prop_array_subscript_int, /* sq_item */ /* Only set this so PySequence_Check() returns True */
02878     NULL,       /* sq_slice */
02879     (ssizeobjargproc)prop_subscript_ass_array_int,      /* sq_ass_item */
02880     NULL,       /* *was* sq_ass_slice */
02881     (objobjproc)pyrna_prop_array_contains,  /* sq_contains */
02882     (binaryfunc) NULL, /* sq_inplace_concat */
02883     (ssizeargfunc) NULL, /* sq_inplace_repeat */
02884 };
02885 
02886 static PySequenceMethods pyrna_prop_collection_as_sequence = {
02887     (lenfunc)pyrna_prop_collection_length,      /* Cant set the len otherwise it can evaluate as false */
02888     NULL,       /* sq_concat */
02889     NULL,       /* sq_repeat */
02890     (ssizeargfunc)pyrna_prop_collection_subscript_int, /* sq_item */ /* Only set this so PySequence_Check() returns True */
02891     NULL,       /* *was* sq_slice */
02892     (ssizeobjargproc)/* pyrna_prop_collection_ass_subscript_int */ NULL /* let mapping take this one */, /* sq_ass_item */
02893     NULL,       /* *was* sq_ass_slice */
02894     (objobjproc)pyrna_prop_collection_contains, /* sq_contains */
02895     (binaryfunc) NULL, /* sq_inplace_concat */
02896     (ssizeargfunc) NULL, /* sq_inplace_repeat */
02897 };
02898 
02899 static PySequenceMethods pyrna_struct_as_sequence = {
02900     NULL,       /* Cant set the len otherwise it can evaluate as false */
02901     NULL,       /* sq_concat */
02902     NULL,       /* sq_repeat */
02903     NULL,       /* sq_item */ /* Only set this so PySequence_Check() returns True */
02904     NULL,       /* *was* sq_slice */
02905     NULL,       /* sq_ass_item */
02906     NULL,       /* *was* sq_ass_slice */
02907     (objobjproc)pyrna_struct_contains,  /* sq_contains */
02908     (binaryfunc) NULL, /* sq_inplace_concat */
02909     (ssizeargfunc) NULL, /* sq_inplace_repeat */
02910 };
02911 
02912 static PyObject *pyrna_struct_subscript(BPy_StructRNA *self, PyObject *key)
02913 {
02914     /* mostly copied from BPy_IDGroup_Map_GetItem */
02915     IDProperty *group, *idprop;
02916     const char *name = _PyUnicode_AsString(key);
02917 
02918     PYRNA_STRUCT_CHECK_OBJ(self);
02919 
02920     if (RNA_struct_idprops_check(self->ptr.type) == 0) {
02921         PyErr_SetString(PyExc_TypeError, "this type doesn't support IDProperties");
02922         return NULL;
02923     }
02924 
02925     if (name == NULL) {
02926         PyErr_SetString(PyExc_TypeError, "bpy_struct[key]: only strings are allowed as keys of ID properties");
02927         return NULL;
02928     }
02929 
02930     group = RNA_struct_idprops(&self->ptr, 0);
02931 
02932     if (group == NULL) {
02933         PyErr_Format(PyExc_KeyError, "bpy_struct[key]: key \"%s\" not found", name);
02934         return NULL;
02935     }
02936 
02937     idprop = IDP_GetPropertyFromGroup(group, name);
02938 
02939     if (idprop == NULL) {
02940         PyErr_Format(PyExc_KeyError, "bpy_struct[key]: key \"%s\" not found", name);
02941         return NULL;
02942     }
02943 
02944     return BPy_IDGroup_WrapData(self->ptr.id.data, idprop, group);
02945 }
02946 
02947 static int pyrna_struct_ass_subscript(BPy_StructRNA *self, PyObject *key, PyObject *value)
02948 {
02949     IDProperty *group;
02950 
02951     PYRNA_STRUCT_CHECK_INT(self);
02952 
02953     group = RNA_struct_idprops(&self->ptr, 1);
02954 
02955 #ifdef USE_PEDANTIC_WRITE
02956     if (rna_disallow_writes && rna_id_write_error(&self->ptr, key)) {
02957         return -1;
02958     }
02959 #endif // USE_PEDANTIC_WRITE
02960 
02961     if (group == NULL) {
02962         PyErr_SetString(PyExc_TypeError, "bpy_struct[key] = val: id properties not supported for this type");
02963         return -1;
02964     }
02965 
02966     return BPy_Wrap_SetMapItem(group, key, value);
02967 }
02968 
02969 static PyMappingMethods pyrna_struct_as_mapping = {
02970     (lenfunc) NULL, /* mp_length */
02971     (binaryfunc) pyrna_struct_subscript,    /* mp_subscript */
02972     (objobjargproc) pyrna_struct_ass_subscript, /* mp_ass_subscript */
02973 };
02974 
02975 PyDoc_STRVAR(pyrna_struct_keys_doc,
02976 ".. method:: keys()\n"
02977 "\n"
02978 "   Returns the keys of this objects custom properties (matches pythons\n"
02979 "   dictionary function of the same name).\n"
02980 "\n"
02981 "   :return: custom property keys.\n"
02982 "   :rtype: list of strings\n"
02983 "\n"
02984 BPY_DOC_ID_PROP_TYPE_NOTE
02985 );
02986 static PyObject *pyrna_struct_keys(BPy_PropertyRNA *self)
02987 {
02988     IDProperty *group;
02989 
02990     if (RNA_struct_idprops_check(self->ptr.type) == 0) {
02991         PyErr_SetString(PyExc_TypeError, "bpy_struct.keys(): this type doesn't support IDProperties");
02992         return NULL;
02993     }
02994 
02995     group = RNA_struct_idprops(&self->ptr, 0);
02996 
02997     if (group == NULL)
02998         return PyList_New(0);
02999 
03000     return BPy_Wrap_GetKeys(group);
03001 }
03002 
03003 PyDoc_STRVAR(pyrna_struct_items_doc,
03004 ".. method:: items()\n"
03005 "\n"
03006 "   Returns the items of this objects custom properties (matches pythons\n"
03007 "   dictionary function of the same name).\n"
03008 "\n"
03009 "   :return: custom property key, value pairs.\n"
03010 "   :rtype: list of key, value tuples\n"
03011 "\n"
03012 BPY_DOC_ID_PROP_TYPE_NOTE
03013 );
03014 static PyObject *pyrna_struct_items(BPy_PropertyRNA *self)
03015 {
03016     IDProperty *group;
03017 
03018     if (RNA_struct_idprops_check(self->ptr.type) == 0) {
03019         PyErr_SetString(PyExc_TypeError, "bpy_struct.items(): this type doesn't support IDProperties");
03020         return NULL;
03021     }
03022 
03023     group = RNA_struct_idprops(&self->ptr, 0);
03024 
03025     if (group == NULL)
03026         return PyList_New(0);
03027 
03028     return BPy_Wrap_GetItems(self->ptr.id.data, group);
03029 }
03030 
03031 PyDoc_STRVAR(pyrna_struct_values_doc,
03032 ".. method:: values()\n"
03033 "\n"
03034 "   Returns the values of this objects custom properties (matches pythons\n"
03035 "   dictionary function of the same name).\n"
03036 "\n"
03037 "   :return: custom property values.\n"
03038 "   :rtype: list\n"
03039 "\n"
03040 BPY_DOC_ID_PROP_TYPE_NOTE
03041 );
03042 static PyObject *pyrna_struct_values(BPy_PropertyRNA *self)
03043 {
03044     IDProperty *group;
03045 
03046     if (RNA_struct_idprops_check(self->ptr.type) == 0) {
03047         PyErr_SetString(PyExc_TypeError, "bpy_struct.values(): this type doesn't support IDProperties");
03048         return NULL;
03049     }
03050 
03051     group = RNA_struct_idprops(&self->ptr, 0);
03052 
03053     if (group == NULL)
03054         return PyList_New(0);
03055 
03056     return BPy_Wrap_GetValues(self->ptr.id.data, group);
03057 }
03058 
03059 
03060 PyDoc_STRVAR(pyrna_struct_is_property_set_doc,
03061 ".. method:: is_property_set(property)\n"
03062 "\n"
03063 "   Check if a property is set, use for testing operator properties.\n"
03064 "\n"
03065 "   :return: True when the property has been set.\n"
03066 "   :rtype: boolean\n"
03067 );
03068 static PyObject *pyrna_struct_is_property_set(BPy_StructRNA *self, PyObject *args)
03069 {
03070     PropertyRNA *prop;
03071     const char *name;
03072 
03073     PYRNA_STRUCT_CHECK_OBJ(self);
03074 
03075     if (!PyArg_ParseTuple(args, "s:is_property_set", &name))
03076         return NULL;
03077 
03078     if ((prop = RNA_struct_find_property(&self->ptr, name)) == NULL) {
03079         PyErr_Format(PyExc_TypeError,
03080                      "%.200s.is_property_set(\"%.200s\") not found",
03081                      RNA_struct_identifier(self->ptr.type), name);
03082         return NULL;
03083     }
03084 
03085     return PyBool_FromLong(RNA_property_is_set(&self->ptr, prop));
03086 }
03087 
03088 PyDoc_STRVAR(pyrna_struct_is_property_hidden_doc,
03089 ".. method:: is_property_hidden(property)\n"
03090 "\n"
03091 "   Check if a property is hidden.\n"
03092 "\n"
03093 "   :return: True when the property is hidden.\n"
03094 "   :rtype: boolean\n"
03095 );
03096 static PyObject *pyrna_struct_is_property_hidden(BPy_StructRNA *self, PyObject *args)
03097 {
03098     PropertyRNA *prop;
03099     const char *name;
03100 
03101     PYRNA_STRUCT_CHECK_OBJ(self);
03102 
03103     if (!PyArg_ParseTuple(args, "s:is_property_hidden", &name))
03104         return NULL;
03105 
03106     if ((prop = RNA_struct_find_property(&self->ptr, name)) == NULL) {
03107         PyErr_Format(PyExc_TypeError,
03108                      "%.200s.is_property_hidden(\"%.200s\") not found",
03109                      RNA_struct_identifier(self->ptr.type), name);
03110         return NULL;
03111     }
03112 
03113     return PyBool_FromLong(RNA_property_flag(prop) & PROP_HIDDEN);
03114 }
03115 
03116 PyDoc_STRVAR(pyrna_struct_path_resolve_doc,
03117 ".. method:: path_resolve(path, coerce=True)\n"
03118 "\n"
03119 "   Returns the property from the path, raise an exception when not found.\n"
03120 "\n"
03121 "   :arg path: path which this property resolves.\n"
03122 "   :type path: string\n"
03123 "   :arg coerce: optional argument, when True, the property will be converted\n"
03124 "      into its python representation.\n"
03125 "   :type coerce: boolean\n"
03126 );
03127 static PyObject *pyrna_struct_path_resolve(BPy_StructRNA *self, PyObject *args)
03128 {
03129     const char *path;
03130     PyObject *coerce = Py_True;
03131     PointerRNA r_ptr;
03132     PropertyRNA *r_prop;
03133     int index = -1;
03134 
03135     PYRNA_STRUCT_CHECK_OBJ(self);
03136 
03137     if (!PyArg_ParseTuple(args, "s|O!:path_resolve", &path, &PyBool_Type, &coerce))
03138         return NULL;
03139 
03140     if (RNA_path_resolve_full(&self->ptr, path, &r_ptr, &r_prop, &index)) {
03141         if (r_prop) {
03142             if (index != -1) {
03143                 if (index >= RNA_property_array_length(&r_ptr, r_prop) || index < 0) {
03144                     PyErr_Format(PyExc_IndexError,
03145                                  "%.200s.path_resolve(\"%.200s\") index out of range",
03146                                  RNA_struct_identifier(self->ptr.type), path);
03147                     return NULL;
03148                 }
03149                 else {
03150                     return pyrna_array_index(&r_ptr, r_prop, index);
03151                 }
03152             }
03153             else {
03154                 if (coerce == Py_False) {
03155                     return pyrna_prop_CreatePyObject(&r_ptr, r_prop);
03156                 }
03157                 else {
03158                     return pyrna_prop_to_py(&r_ptr, r_prop);
03159                 }
03160             }
03161         }
03162         else {
03163             return pyrna_struct_CreatePyObject(&r_ptr);
03164         }
03165     }
03166     else {
03167         PyErr_Format(PyExc_ValueError,
03168                      "%.200s.path_resolve(\"%.200s\") could not be resolved",
03169                      RNA_struct_identifier(self->ptr.type), path);
03170         return NULL;
03171     }
03172 }
03173 
03174 PyDoc_STRVAR(pyrna_struct_path_from_id_doc,
03175 ".. method:: path_from_id(property=\"\")\n"
03176 "\n"
03177 "   Returns the data path from the ID to this object (string).\n"
03178 "\n"
03179 "   :arg property: Optional property name which can be used if the path is\n"
03180 "      to a property of this object.\n"
03181 "   :type property: string\n"
03182 "   :return: The path from :class:`bpy.types.bpy_struct.id_data`\n"
03183 "      to this struct and property (when given).\n"
03184 "   :rtype: str\n"
03185 );
03186 static PyObject *pyrna_struct_path_from_id(BPy_StructRNA *self, PyObject *args)
03187 {
03188     const char *name = NULL;
03189     const char *path;
03190     PropertyRNA *prop;
03191     PyObject *ret;
03192 
03193     PYRNA_STRUCT_CHECK_OBJ(self);
03194 
03195     if (!PyArg_ParseTuple(args, "|s:path_from_id", &name))
03196         return NULL;
03197 
03198     if (name) {
03199         prop = RNA_struct_find_property(&self->ptr, name);
03200         if (prop == NULL) {
03201             PyErr_Format(PyExc_AttributeError,
03202                          "%.200s.path_from_id(\"%.200s\") not found",
03203                          RNA_struct_identifier(self->ptr.type), name);
03204             return NULL;
03205         }
03206 
03207         path = RNA_path_from_ID_to_property(&self->ptr, prop);
03208     }
03209     else {
03210         path = RNA_path_from_ID_to_struct(&self->ptr);
03211     }
03212 
03213     if (path == NULL) {
03214         if (name) {
03215             PyErr_Format(PyExc_ValueError,
03216                          "%.200s.path_from_id(\"%s\") found but does not support path creation",
03217                          RNA_struct_identifier(self->ptr.type), name);
03218         }
03219         else {
03220             PyErr_Format(PyExc_ValueError,
03221                          "%.200s.path_from_id() does not support path creation for this type",
03222                          RNA_struct_identifier(self->ptr.type));
03223         }
03224         return NULL;
03225     }
03226 
03227     ret = PyUnicode_FromString(path);
03228     MEM_freeN((void *)path);
03229 
03230     return ret;
03231 }
03232 
03233 PyDoc_STRVAR(pyrna_prop_path_from_id_doc,
03234 ".. method:: path_from_id()\n"
03235 "\n"
03236 "   Returns the data path from the ID to this property (string).\n"
03237 "\n"
03238 "   :return: The path from :class:`bpy.types.bpy_struct.id_data` to this property.\n"
03239 "   :rtype: str\n"
03240 );
03241 static PyObject *pyrna_prop_path_from_id(BPy_PropertyRNA *self)
03242 {
03243     const char *path;
03244     PropertyRNA *prop = self->prop;
03245     PyObject *ret;
03246 
03247     path = RNA_path_from_ID_to_property(&self->ptr, self->prop);
03248 
03249     if (path == NULL) {
03250         PyErr_Format(PyExc_ValueError,
03251                      "%.200s.%.200s.path_from_id() does not support path creation for this type",
03252                      RNA_struct_identifier(self->ptr.type), RNA_property_identifier(prop));
03253         return NULL;
03254     }
03255 
03256     ret = PyUnicode_FromString(path);
03257     MEM_freeN((void *)path);
03258 
03259     return ret;
03260 }
03261 
03262 PyDoc_STRVAR(pyrna_struct_type_recast_doc,
03263 ".. method:: type_recast()\n"
03264 "\n"
03265 "   Return a new instance, this is needed because types\n"
03266 "   such as textures can be changed at runtime.\n"
03267 "\n"
03268 "   :return: a new instance of this object with the type initialized again.\n"
03269 "   :rtype: subclass of :class:`bpy.types.bpy_struct`\n"
03270 );
03271 static PyObject *pyrna_struct_type_recast(BPy_StructRNA *self)
03272 {
03273     PointerRNA r_ptr;
03274 
03275     PYRNA_STRUCT_CHECK_OBJ(self);
03276 
03277     RNA_pointer_recast(&self->ptr, &r_ptr);
03278     return pyrna_struct_CreatePyObject(&r_ptr);
03279 }
03280 
03281 static void pyrna_dir_members_py(PyObject *list, PyObject *self)
03282 {
03283     PyObject *dict;
03284     PyObject **dict_ptr;
03285     PyObject *list_tmp;
03286 
03287     dict_ptr = _PyObject_GetDictPtr((PyObject *)self);
03288 
03289     if (dict_ptr && (dict = *dict_ptr)) {
03290         list_tmp = PyDict_Keys(dict);
03291         PyList_SetSlice(list, INT_MAX, INT_MAX, list_tmp);
03292         Py_DECREF(list_tmp);
03293     }
03294 
03295     dict = ((PyTypeObject *)Py_TYPE(self))->tp_dict;
03296     if (dict) {
03297         list_tmp = PyDict_Keys(dict);
03298         PyList_SetSlice(list, INT_MAX, INT_MAX, list_tmp);
03299         Py_DECREF(list_tmp);
03300     }
03301 }
03302 
03303 static void pyrna_dir_members_rna(PyObject *list, PointerRNA *ptr)
03304 {
03305     PyObject *pystring;
03306     const char *idname;
03307 
03308     /* for looping over attrs and funcs */
03309     PointerRNA tptr;
03310     PropertyRNA *iterprop;
03311 
03312     {
03313         RNA_pointer_create(NULL, &RNA_Struct, ptr->type, &tptr);
03314         iterprop = RNA_struct_find_property(&tptr, "functions");
03315 
03316         RNA_PROP_BEGIN(&tptr, itemptr, iterprop) {
03317             idname = RNA_function_identifier(itemptr.data);
03318 
03319             pystring = PyUnicode_FromString(idname);
03320             PyList_Append(list, pystring);
03321             Py_DECREF(pystring);
03322         }
03323         RNA_PROP_END;
03324     }
03325 
03326     {
03327         /*
03328          * Collect RNA attributes
03329          */
03330         char name[256], *nameptr;
03331         int namelen;
03332 
03333         iterprop = RNA_struct_iterator_property(ptr->type);
03334 
03335         RNA_PROP_BEGIN(ptr, itemptr, iterprop) {
03336             nameptr = RNA_struct_name_get_alloc(&itemptr, name, sizeof(name), &namelen);
03337 
03338             if (nameptr) {
03339                 pystring = PyUnicode_FromStringAndSize(nameptr, namelen);
03340                 PyList_Append(list, pystring);
03341                 Py_DECREF(pystring);
03342 
03343                 if (name != nameptr) {
03344                     MEM_freeN(nameptr);
03345                 }
03346             }
03347         }
03348         RNA_PROP_END;
03349     }
03350 }
03351 
03352 
03353 static PyObject *pyrna_struct_dir(BPy_StructRNA *self)
03354 {
03355     PyObject *ret;
03356     PyObject *pystring;
03357 
03358     PYRNA_STRUCT_CHECK_OBJ(self);
03359 
03360     /* Include this incase this instance is a subtype of a python class
03361      * In these instances we may want to return a function or variable provided by the subtype
03362      * */
03363     ret = PyList_New(0);
03364 
03365     if (!BPy_StructRNA_CheckExact(self))
03366         pyrna_dir_members_py(ret, (PyObject *)self);
03367 
03368     pyrna_dir_members_rna(ret, &self->ptr);
03369 
03370     if (self->ptr.type == &RNA_Context) {
03371         ListBase lb = CTX_data_dir_get(self->ptr.data);
03372         LinkData *link;
03373 
03374         for (link = lb.first; link; link = link->next) {
03375             pystring = PyUnicode_FromString(link->data);
03376             PyList_Append(ret, pystring);
03377             Py_DECREF(pystring);
03378         }
03379 
03380         BLI_freelistN(&lb);
03381     }
03382 
03383     {
03384         /* set(), this is needed to remove-doubles because the deferred
03385          * register-props will be in both the python __dict__ and accessed as RNA */
03386 
03387         PyObject *set = PySet_New(ret);
03388 
03389         Py_DECREF(ret);
03390         ret = PySequence_List(set);
03391         Py_DECREF(set);
03392     }
03393 
03394     return ret;
03395 }
03396 
03397 //---------------getattr--------------------------------------------
03398 static PyObject *pyrna_struct_getattro(BPy_StructRNA *self, PyObject *pyname)
03399 {
03400     const char *name = _PyUnicode_AsString(pyname);
03401     PyObject *ret;
03402     PropertyRNA *prop;
03403     FunctionRNA *func;
03404 
03405     PYRNA_STRUCT_CHECK_OBJ(self);
03406 
03407     if (name == NULL) {
03408         PyErr_SetString(PyExc_AttributeError, "bpy_struct: __getattr__ must be a string");
03409         ret = NULL;
03410     }
03411     else if (name[0] == '_') { // rna can't start with a "_", so for __dict__ and similar we can skip using rna lookups
03412         /* annoying exception, maybe we need to have different types for this... */
03413         if ((strcmp(name, "__getitem__") == 0 || strcmp(name, "__setitem__") == 0) && !RNA_struct_idprops_check(self->ptr.type)) {
03414             PyErr_SetString(PyExc_AttributeError, "bpy_struct: no __getitem__ support for this type");
03415             ret = NULL;
03416         }
03417         else {
03418             ret = PyObject_GenericGetAttr((PyObject *)self, pyname);
03419         }
03420     }
03421     else if ((prop = RNA_struct_find_property(&self->ptr, name))) {
03422         ret = pyrna_prop_to_py(&self->ptr, prop);
03423     }
03424     /* RNA function only if callback is declared (no optional functions) */
03425     else if ((func = RNA_struct_find_function(&self->ptr, name)) && RNA_function_defined(func)) {
03426         ret = pyrna_func_to_py(&self->ptr, func);
03427     }
03428     else if (self->ptr.type == &RNA_Context) {
03429         bContext *C = self->ptr.data;
03430         if (C == NULL) {
03431             PyErr_Format(PyExc_AttributeError,
03432                          "bpy_struct: Context is 'NULL', can't get \"%.200s\" from context",
03433                          name);
03434             ret = NULL;
03435         }
03436         else {
03437             PointerRNA newptr;
03438             ListBase newlb;
03439             short newtype;
03440 
03441             int done = CTX_data_get(C, name, &newptr, &newlb, &newtype);
03442 
03443             if (done == 1) { /* found */
03444                 switch (newtype) {
03445                 case CTX_DATA_TYPE_POINTER:
03446                     if (newptr.data == NULL) {
03447                         ret = Py_None;
03448                         Py_INCREF(ret);
03449                     }
03450                     else {
03451                         ret = pyrna_struct_CreatePyObject(&newptr);
03452                     }
03453                     break;
03454                 case CTX_DATA_TYPE_COLLECTION:
03455                     {
03456                         CollectionPointerLink *link;
03457                         PyObject *linkptr;
03458 
03459                         ret = PyList_New(0);
03460 
03461                         for (link = newlb.first; link; link = link->next) {
03462                             linkptr = pyrna_struct_CreatePyObject(&link->ptr);
03463                             PyList_Append(ret, linkptr);
03464                             Py_DECREF(linkptr);
03465                         }
03466                     }
03467                     break;
03468                 default:
03469                     /* should never happen */
03470                     BLI_assert(!"Invalid context type");
03471 
03472                     PyErr_Format(PyExc_AttributeError,
03473                                  "bpy_struct: Context type invalid %d, can't get \"%.200s\" from context",
03474                                  newtype, name);
03475                     ret = NULL;
03476                 }
03477             }
03478             else if (done == -1) { /* found but not set */
03479                 ret = Py_None;
03480                 Py_INCREF(ret);
03481             }
03482             else { /* not found in the context */
03483                 /* lookup the subclass. raise an error if its not found */
03484                 ret = PyObject_GenericGetAttr((PyObject *)self, pyname);
03485             }
03486 
03487             BLI_freelistN(&newlb);
03488         }
03489     }
03490     else {
03491 #if 0
03492         PyErr_Format(PyExc_AttributeError,
03493                      "bpy_struct: attribute \"%.200s\" not found",
03494                      name);
03495         ret = NULL;
03496 #endif
03497         /* Include this incase this instance is a subtype of a python class
03498          * In these instances we may want to return a function or variable provided by the subtype
03499          *
03500          * Also needed to return methods when its not a subtype
03501          * */
03502 
03503         /* The error raised here will be displayed */
03504         ret = PyObject_GenericGetAttr((PyObject *)self, pyname);
03505     }
03506 
03507     return ret;
03508 }
03509 
03510 #if 0
03511 static int pyrna_struct_pydict_contains(PyObject *self, PyObject *pyname)
03512 {
03513     PyObject *dict = *(_PyObject_GetDictPtr((PyObject *)self));
03514     if (dict == NULL) /* unlikely */
03515         return 0;
03516 
03517     return PyDict_Contains(dict, pyname);
03518 }
03519 #endif
03520 
03521 //--------------- setattr-------------------------------------------
03522 static int pyrna_is_deferred_prop(const PyObject *value)
03523 {
03524     return  PyTuple_CheckExact(value) &&
03525             PyTuple_GET_SIZE(value) == 2 &&
03526             PyCFunction_Check(PyTuple_GET_ITEM(value, 0)) &&
03527             PyDict_CheckExact(PyTuple_GET_ITEM(value, 1));
03528 }
03529 
03530 #if 0
03531 static PyObject *pyrna_struct_meta_idprop_getattro(PyObject *cls, PyObject *attr)
03532 {
03533     PyObject *ret = PyType_Type.tp_getattro(cls, attr);
03534 
03535     /* Allows:
03536      * >>> bpy.types.Scene.foo = BoolProperty()
03537      * >>> bpy.types.Scene.foo
03538      * <bpy_struct, BoolProperty("foo")>
03539      * ...rather than returning the deferred class register tuple as checked by pyrna_is_deferred_prop()
03540      *
03541      * Disable for now, this is faking internal behavior in a way thats too tricky to maintain well. */
03542 #if 0
03543     if (ret == NULL) { // || pyrna_is_deferred_prop(ret)
03544         StructRNA *srna = srna_from_self(cls, "StructRNA.__getattr__");
03545         if (srna) {
03546             PropertyRNA *prop = RNA_struct_type_find_property(srna, _PyUnicode_AsString(attr));
03547             if (prop) {
03548                 PointerRNA tptr;
03549                 PyErr_Clear(); /* clear error from tp_getattro */
03550                 RNA_pointer_create(NULL, &RNA_Property, prop, &tptr);
03551                 ret = pyrna_struct_CreatePyObject(&tptr);
03552             }
03553         }
03554     }
03555 #endif
03556 
03557     return ret;
03558 }
03559 #endif
03560 
03561 static int pyrna_struct_meta_idprop_setattro(PyObject *cls, PyObject *attr, PyObject *value)
03562 {
03563     StructRNA *srna = srna_from_self(cls, "StructRNA.__setattr__");
03564     const int is_deferred_prop = (value && pyrna_is_deferred_prop(value));
03565     const char *attr_str = _PyUnicode_AsString(attr);
03566 
03567     if (srna && !pyrna_write_check() && (is_deferred_prop || RNA_struct_type_find_property(srna, attr_str))) {
03568         PyErr_Format(PyExc_AttributeError,
03569                      "pyrna_struct_meta_idprop_setattro() "
03570                      "can't set in readonly state '%.200s.%S'",
03571                      ((PyTypeObject *)cls)->tp_name, attr);
03572         return -1;
03573     }
03574 
03575     if (srna == NULL) {
03576         /* allow setting on unregistered classes which can be registered later on */
03577         /*
03578         if (value && is_deferred_prop) {
03579             PyErr_Format(PyExc_AttributeError,
03580                          "pyrna_struct_meta_idprop_setattro() unable to get srna from class '%.200s'",
03581                          ((PyTypeObject *)cls)->tp_name);
03582             return -1;
03583         }
03584         */
03585         /* srna_from_self may set an error */
03586         PyErr_Clear();
03587         return PyType_Type.tp_setattro(cls, attr, value);
03588     }
03589 
03590     if (value) {
03591         /* check if the value is a property */
03592         if (is_deferred_prop) {
03593             int ret = deferred_register_prop(srna, attr, value);
03594             if (ret == -1) {
03595                 /* error set */
03596                 return ret;
03597             }
03598 
03599             /* pass through and assign to the classes __dict__ as well
03600              * when the value isn't assigned it still creates the RNA property
03601              * but gets confusing from script writers POV if the assigned value cant be read back. */
03602         }
03603         else {
03604             /* remove existing property if its set or we also end up with confusion */
03605             RNA_def_property_free_identifier(srna, attr_str); /* ignore on failure */
03606         }
03607     }
03608     else { /* __delattr__ */
03609         /* first find if this is a registered property */
03610         const int ret = RNA_def_property_free_identifier(srna, attr_str);
03611         if (ret == -1) {
03612             PyErr_Format(PyExc_TypeError,
03613                          "struct_meta_idprop.detattr(): '%s' not a dynamic property",
03614                          attr_str);
03615             return -1;
03616         }
03617     }
03618 
03619     /* fallback to standard py, delattr/setattr */
03620     return PyType_Type.tp_setattro(cls, attr, value);
03621 }
03622 
03623 static int pyrna_struct_setattro(BPy_StructRNA *self, PyObject *pyname, PyObject *value)
03624 {
03625     const char *name = _PyUnicode_AsString(pyname);
03626     PropertyRNA *prop = NULL;
03627 
03628     PYRNA_STRUCT_CHECK_INT(self);
03629 
03630 #ifdef USE_PEDANTIC_WRITE
03631     if (rna_disallow_writes && rna_id_write_error(&self->ptr, pyname)) {
03632         return -1;
03633     }
03634 #endif // USE_PEDANTIC_WRITE
03635 
03636     if (name == NULL) {
03637         PyErr_SetString(PyExc_AttributeError, "bpy_struct: __setattr__ must be a string");
03638         return -1;
03639     }
03640     else if (name[0] != '_' && (prop = RNA_struct_find_property(&self->ptr, name))) {
03641         if (!RNA_property_editable_flag(&self->ptr, prop)) {
03642             PyErr_Format(PyExc_AttributeError,
03643                          "bpy_struct: attribute \"%.200s\" from \"%.200s\" is read-only",
03644                          RNA_property_identifier(prop), RNA_struct_identifier(self->ptr.type));
03645             return -1;
03646         }
03647     }
03648     else if (self->ptr.type == &RNA_Context) {
03649         /* code just raises correct error, context prop's cant be set, unless its apart of the py class */
03650         bContext *C = self->ptr.data;
03651         if (C == NULL) {
03652             PyErr_Format(PyExc_AttributeError,
03653                          "bpy_struct: Context is 'NULL', can't set \"%.200s\" from context",
03654                          name);
03655             return -1;
03656         }
03657         else {
03658             PointerRNA newptr;
03659             ListBase newlb;
03660             short newtype;
03661 
03662             int done = CTX_data_get(C, name, &newptr, &newlb, &newtype);
03663 
03664             if (done == 1) {
03665                 PyErr_Format(PyExc_AttributeError,
03666                              "bpy_struct: Context property \"%.200s\" is read-only",
03667                              name);
03668                 BLI_freelistN(&newlb);
03669                 return -1;
03670             }
03671 
03672             BLI_freelistN(&newlb);
03673         }
03674     }
03675 
03676     /* pyrna_py_to_prop sets its own exceptions */
03677     if (prop) {
03678         if (value == NULL) {
03679             PyErr_SetString(PyExc_AttributeError, "bpy_struct: del not supported");
03680             return -1;
03681         }
03682         return pyrna_py_to_prop(&self->ptr, prop, NULL, value, "bpy_struct: item.attr = val:");
03683     }
03684     else {
03685         return PyObject_GenericSetAttr((PyObject *)self, pyname, value);
03686     }
03687 }
03688 
03689 static PyObject *pyrna_prop_dir(BPy_PropertyRNA *self)
03690 {
03691     PyObject *ret;
03692     PointerRNA r_ptr;
03693 
03694     /* Include this incase this instance is a subtype of a python class
03695      * In these instances we may want to return a function or variable provided by the subtype
03696      * */
03697     ret = PyList_New(0);
03698 
03699     if (!BPy_PropertyRNA_CheckExact(self)) {
03700         pyrna_dir_members_py(ret, (PyObject *)self);
03701     }
03702 
03703     if (RNA_property_type(self->prop) == PROP_COLLECTION) {
03704         if (RNA_property_collection_type_get(&self->ptr, self->prop, &r_ptr)) {
03705             pyrna_dir_members_rna(ret, &r_ptr);
03706         }
03707     }
03708 
03709     return ret;
03710 }
03711 
03712 
03713 static PyObject *pyrna_prop_array_getattro(BPy_PropertyRNA *self, PyObject *pyname)
03714 {
03715     return PyObject_GenericGetAttr((PyObject *)self, pyname);
03716 }
03717 
03718 static PyObject *pyrna_prop_collection_getattro(BPy_PropertyRNA *self, PyObject *pyname)
03719 {
03720     const char *name = _PyUnicode_AsString(pyname);
03721 
03722     if (name == NULL) {
03723         PyErr_SetString(PyExc_AttributeError, "bpy_prop_collection: __getattr__ must be a string");
03724         return NULL;
03725     }
03726     else if (name[0] != '_') {
03727         PyObject *ret;
03728         PropertyRNA *prop;
03729         FunctionRNA *func;
03730 
03731         PointerRNA r_ptr;
03732         if (RNA_property_collection_type_get(&self->ptr, self->prop, &r_ptr)) {
03733             if ((prop = RNA_struct_find_property(&r_ptr, name))) {
03734                 ret = pyrna_prop_to_py(&r_ptr, prop);
03735 
03736                 return ret;
03737             }
03738             else if ((func = RNA_struct_find_function(&r_ptr, name))) {
03739                 PyObject *self_collection = pyrna_struct_CreatePyObject(&r_ptr);
03740                 ret = pyrna_func_to_py(&((BPy_DummyPointerRNA *)self_collection)->ptr, func);
03741                 Py_DECREF(self_collection);
03742 
03743                 return ret;
03744             }
03745         }
03746     }
03747 
03748 #if 0
03749     return PyObject_GenericGetAttr((PyObject *)self, pyname);
03750 #else
03751     {
03752         /* Could just do this except for 1 awkward case.
03753          * PyObject_GenericGetAttr((PyObject *)self, pyname);
03754          * so as to support 'bpy.data.library.load()'
03755          * note, this _only_ supports static methods */
03756 
03757         PyObject *ret = PyObject_GenericGetAttr((PyObject *)self, pyname);
03758 
03759         if (ret == NULL && name[0] != '_') { /* avoid inheriting __call__ and similar */
03760             /* since this is least common case, handle it last */
03761             PointerRNA r_ptr;
03762             if (RNA_property_collection_type_get(&self->ptr, self->prop, &r_ptr)) {
03763                 PyObject *cls;
03764 
03765                 PyObject *error_type, *error_value, *error_traceback;
03766                 PyErr_Fetch(&error_type, &error_value, &error_traceback);
03767                 PyErr_Clear();
03768 
03769                 cls = pyrna_struct_Subtype(&r_ptr); /* borrows */
03770                 ret = PyObject_GenericGetAttr(cls, pyname);
03771                 /* restore the original error */
03772                 if (ret == NULL) {
03773                     PyErr_Restore(error_type, error_value, error_traceback);
03774                 }
03775             }
03776         }
03777 
03778         return ret;
03779     }
03780 #endif
03781 }
03782 
03783 //--------------- setattr-------------------------------------------
03784 static int pyrna_prop_collection_setattro(BPy_PropertyRNA *self, PyObject *pyname, PyObject *value)
03785 {
03786     const char *name = _PyUnicode_AsString(pyname);
03787     PropertyRNA *prop;
03788     PointerRNA r_ptr;
03789 
03790 #ifdef USE_PEDANTIC_WRITE
03791     if (rna_disallow_writes && rna_id_write_error(&self->ptr, pyname)) {
03792         return -1;
03793     }
03794 #endif // USE_PEDANTIC_WRITE
03795 
03796     if (name == NULL) {
03797         PyErr_SetString(PyExc_AttributeError, "bpy_prop: __setattr__ must be a string");
03798         return -1;
03799     }
03800     else if (value == NULL) {
03801         PyErr_SetString(PyExc_AttributeError, "bpy_prop: del not supported");
03802         return -1;
03803     }
03804     else if (RNA_property_collection_type_get(&self->ptr, self->prop, &r_ptr)) {
03805         if ((prop = RNA_struct_find_property(&r_ptr, name))) {
03806             /* pyrna_py_to_prop sets its own exceptions */
03807             return pyrna_py_to_prop(&r_ptr, prop, NULL, value, "BPy_PropertyRNA - Attribute (setattr):");
03808         }
03809     }
03810 
03811     PyErr_Format(PyExc_AttributeError,
03812                  "bpy_prop_collection: attribute \"%.200s\" not found",
03813                  name);
03814     return -1;
03815 }
03816 
03817 /* odd case, we need to be able return a python method from a tp_getset */
03818 static PyObject *pyrna_prop_collection_idprop_add(BPy_PropertyRNA *self)
03819 {
03820     PointerRNA r_ptr;
03821 
03822     RNA_property_collection_add(&self->ptr, self->prop, &r_ptr);
03823     if (!r_ptr.data) {
03824         PyErr_SetString(PyExc_TypeError, "bpy_prop_collection.add(): not supported for this collection");
03825         return NULL;
03826     }
03827     else {
03828         return pyrna_struct_CreatePyObject(&r_ptr);
03829     }
03830 }
03831 
03832 static PyObject *pyrna_prop_collection_idprop_remove(BPy_PropertyRNA *self, PyObject *value)
03833 {
03834     int key = PyLong_AsLong(value);
03835 
03836     if (key == -1 && PyErr_Occurred()) {
03837         PyErr_SetString(PyExc_TypeError, "bpy_prop_collection.remove(): expected one int argument");
03838         return NULL;
03839     }
03840 
03841     if (!RNA_property_collection_remove(&self->ptr, self->prop, key)) {
03842         PyErr_SetString(PyExc_TypeError, "bpy_prop_collection.remove() not supported for this collection");
03843         return NULL;
03844     }
03845 
03846     Py_RETURN_NONE;
03847 }
03848 
03849 static PyObject *pyrna_prop_collection_idprop_move(BPy_PropertyRNA *self, PyObject *args)
03850 {
03851     int key = 0, pos = 0;
03852 
03853     if (!PyArg_ParseTuple(args, "ii", &key, &pos)) {
03854         PyErr_SetString(PyExc_TypeError, "bpy_prop_collection.move(): expected two ints as arguments");
03855         return NULL;
03856     }
03857 
03858     if (!RNA_property_collection_move(&self->ptr, self->prop, key, pos)) {
03859         PyErr_SetString(PyExc_TypeError, "bpy_prop_collection.move() not supported for this collection");
03860         return NULL;
03861     }
03862 
03863     Py_RETURN_NONE;
03864 }
03865 
03866 
03867 PyDoc_STRVAR(pyrna_struct_get_id_data_doc,
03868 "The :class:`bpy.types.ID` object this datablock is from or None, (not available for all data types)"
03869 );
03870 static PyObject *pyrna_struct_get_id_data(BPy_DummyPointerRNA *self)
03871 {
03872     /* used for struct and pointer since both have a ptr */
03873     if (self->ptr.id.data) {
03874         PointerRNA id_ptr;
03875         RNA_id_pointer_create((ID *)self->ptr.id.data, &id_ptr);
03876         return pyrna_struct_CreatePyObject(&id_ptr);
03877     }
03878 
03879     Py_RETURN_NONE;
03880 }
03881 
03882 PyDoc_STRVAR(pyrna_struct_get_data_doc,
03883 "The data this property is using, *type* :class:`bpy.types.bpy_struct`"
03884 );
03885 static PyObject *pyrna_struct_get_data(BPy_DummyPointerRNA *self)
03886 {
03887     return pyrna_struct_CreatePyObject(&self->ptr);
03888 }
03889 
03890 PyDoc_STRVAR(pyrna_struct_get_rna_type_doc,
03891 "The property type for introspection"
03892 );
03893 static PyObject *pyrna_struct_get_rna_type(BPy_PropertyRNA *self)
03894 {
03895     PointerRNA tptr;
03896     RNA_pointer_create(NULL, &RNA_Property, self->prop, &tptr);
03897     return pyrna_struct_Subtype(&tptr);
03898 }
03899 
03900 
03901 
03902 /*****************************************************************************/
03903 /* Python attributes get/set structure:                                      */
03904 /*****************************************************************************/
03905 
03906 static PyGetSetDef pyrna_prop_getseters[] = {
03907     {(char *)"id_data", (getter)pyrna_struct_get_id_data, (setter)NULL, (char *)pyrna_struct_get_id_data_doc, NULL},
03908     {(char *)"data", (getter)pyrna_struct_get_data, (setter)NULL, (char *)pyrna_struct_get_data_doc, NULL},
03909     {(char *)"rna_type", (getter)pyrna_struct_get_rna_type, (setter)NULL, (char *)pyrna_struct_get_rna_type_doc, NULL},
03910     {NULL, NULL, NULL, NULL, NULL} /* Sentinel */
03911 };
03912 
03913 static PyGetSetDef pyrna_struct_getseters[] = {
03914     {(char *)"id_data", (getter)pyrna_struct_get_id_data, (setter)NULL, (char *)pyrna_struct_get_id_data_doc, NULL},
03915     {NULL, NULL, NULL, NULL, NULL} /* Sentinel */
03916 };
03917 
03918 
03919 PyDoc_STRVAR(pyrna_prop_collection_keys_doc,
03920 ".. method:: keys()\n"
03921 "\n"
03922 "   Return the identifiers of collection members\n"
03923 "   (matching pythons dict.keys() functionality).\n"
03924 "\n"
03925 "   :return: the identifiers for each member of this collection.\n"
03926 "   :rtype: list of stings\n"
03927 );
03928 static PyObject *pyrna_prop_collection_keys(BPy_PropertyRNA *self)
03929 {
03930     PyObject *ret = PyList_New(0);
03931     PyObject *item;
03932     char name[256], *nameptr;
03933     int namelen;
03934 
03935     RNA_PROP_BEGIN(&self->ptr, itemptr, self->prop) {
03936         nameptr = RNA_struct_name_get_alloc(&itemptr, name, sizeof(name), &namelen);
03937 
03938         if (nameptr) {
03939             /* add to python list */
03940             item = PyUnicode_FromStringAndSize(nameptr, namelen);
03941             PyList_Append(ret, item);
03942             Py_DECREF(item);
03943             /* done */
03944 
03945             if (name != nameptr) {
03946                 MEM_freeN(nameptr);
03947             }
03948         }
03949     }
03950     RNA_PROP_END;
03951 
03952     return ret;
03953 }
03954 
03955 PyDoc_STRVAR(pyrna_prop_collection_items_doc,
03956 ".. method:: items()\n"
03957 "\n"
03958 "   Return the identifiers of collection members\n"
03959 "   (matching pythons dict.items() functionality).\n"
03960 "\n"
03961 "   :return: (key, value) pairs for each member of this collection.\n"
03962 "   :rtype: list of tuples\n"
03963 );
03964 static PyObject *pyrna_prop_collection_items(BPy_PropertyRNA *self)
03965 {
03966     PyObject *ret = PyList_New(0);
03967     PyObject *item;
03968     char name[256], *nameptr;
03969     int namelen;
03970     int i = 0;
03971 
03972     RNA_PROP_BEGIN(&self->ptr, itemptr, self->prop) {
03973         if (itemptr.data) {
03974             /* add to python list */
03975             item = PyTuple_New(2);
03976             nameptr = RNA_struct_name_get_alloc(&itemptr, name, sizeof(name), &namelen);
03977             if (nameptr) {
03978                 PyTuple_SET_ITEM(item, 0, PyUnicode_FromStringAndSize(nameptr, namelen));
03979                 if (name != nameptr)
03980                     MEM_freeN(nameptr);
03981             }
03982             else {
03983                 /* a bit strange but better then returning an empty list */
03984                 PyTuple_SET_ITEM(item, 0, PyLong_FromSsize_t(i));
03985             }
03986             PyTuple_SET_ITEM(item, 1, pyrna_struct_CreatePyObject(&itemptr));
03987 
03988             PyList_Append(ret, item);
03989             Py_DECREF(item);
03990 
03991             i++;
03992         }
03993     }
03994     RNA_PROP_END;
03995 
03996     return ret;
03997 }
03998 
03999 PyDoc_STRVAR(pyrna_prop_collection_values_doc,
04000 ".. method:: values()\n"
04001 "\n"
04002 "   Return the values of collection\n"
04003 "   (matching pythons dict.values() functionality).\n"
04004 "\n"
04005 "   :return: the members of this collection.\n"
04006 "   :rtype: list\n"
04007 );
04008 static PyObject *pyrna_prop_collection_values(BPy_PropertyRNA *self)
04009 {
04010     /* re-use slice*/
04011     return pyrna_prop_collection_subscript_slice(self, 0, PY_SSIZE_T_MAX);
04012 }
04013 
04014 PyDoc_STRVAR(pyrna_struct_get_doc,
04015 ".. method:: get(key, default=None)\n"
04016 "\n"
04017 "   Returns the value of the custom property assigned to key or default\n"
04018 "   when not found (matches pythons dictionary function of the same name).\n"
04019 "\n"
04020 "   :arg key: The key associated with the custom property.\n"
04021 "   :type key: string\n"
04022 "   :arg default: Optional argument for the value to return if\n"
04023 "      *key* is not found.\n"
04024 "   :type default: Undefined\n"
04025 "\n"
04026 BPY_DOC_ID_PROP_TYPE_NOTE
04027 );
04028 static PyObject *pyrna_struct_get(BPy_StructRNA *self, PyObject *args)
04029 {
04030     IDProperty *group, *idprop;
04031 
04032     const char *key;
04033     PyObject* def = Py_None;
04034 
04035     PYRNA_STRUCT_CHECK_OBJ(self);
04036 
04037     if (!PyArg_ParseTuple(args, "s|O:get", &key, &def))
04038         return NULL;
04039 
04040     /* mostly copied from BPy_IDGroup_Map_GetItem */
04041     if (RNA_struct_idprops_check(self->ptr.type) == 0) {
04042         PyErr_SetString(PyExc_TypeError, "this type doesn't support IDProperties");
04043         return NULL;
04044     }
04045 
04046     group = RNA_struct_idprops(&self->ptr, 0);
04047     if (group) {
04048         idprop = IDP_GetPropertyFromGroup(group, key);
04049 
04050         if (idprop) {
04051             return BPy_IDGroup_WrapData(self->ptr.id.data, idprop, group);
04052         }
04053     }
04054 
04055     return Py_INCREF(def), def;
04056 }
04057 
04058 PyDoc_STRVAR(pyrna_struct_as_pointer_doc,
04059 ".. method:: as_pointer()\n"
04060 "\n"
04061 "   Returns the memory address which holds a pointer to blenders internal data\n"
04062 "\n"
04063 "   :return: int (memory address).\n"
04064 "   :rtype: int\n"
04065 "\n"
04066 "   .. note:: This is intended only for advanced script writers who need to\n"
04067 "      pass blender data to their own C/Python modules.\n"
04068 );
04069 static PyObject *pyrna_struct_as_pointer(BPy_StructRNA *self)
04070 {
04071     return PyLong_FromVoidPtr(self->ptr.data);
04072 }
04073 
04074 PyDoc_STRVAR(pyrna_prop_collection_get_doc,
04075 ".. method:: get(key, default=None)\n"
04076 "\n"
04077 "   Returns the value of the item assigned to key or default when not found\n"
04078 "   (matches pythons dictionary function of the same name).\n"
04079 "\n"
04080 "   :arg key: The identifier for the collection member.\n"
04081 "   :type key: string\n"
04082 "   :arg default: Optional argument for the value to return if\n"
04083 "      *key* is not found.\n"
04084 "   :type default: Undefined\n"
04085 );
04086 static PyObject *pyrna_prop_collection_get(BPy_PropertyRNA *self, PyObject *args)
04087 {
04088     PointerRNA newptr;
04089 
04090     PyObject *key_ob;
04091     PyObject* def = Py_None;
04092 
04093     PYRNA_PROP_CHECK_OBJ(self);
04094 
04095     if (!PyArg_ParseTuple(args, "O|O:get", &key_ob, &def))
04096         return NULL;
04097 
04098     if (PyUnicode_Check(key_ob)) {
04099         const char *key = _PyUnicode_AsString(key_ob);
04100 
04101         if (RNA_property_collection_lookup_string(&self->ptr, self->prop, key, &newptr))
04102             return pyrna_struct_CreatePyObject(&newptr);
04103     }
04104     else if (PyTuple_Check(key_ob)) {
04105         PyObject *ret = pyrna_prop_collection_subscript_str_lib_pair(self, key_ob,
04106                                                                     "bpy_prop_collection.get((id, lib))", FALSE);
04107         if (ret) {
04108             return ret;
04109         }
04110     }
04111     else {
04112         PyErr_Format(PyExc_KeyError,
04113                      "bpy_prop_collection.get(key, ...): key must be a string or tuple, not %.200s",
04114                      Py_TYPE(key_ob)->tp_name);
04115     }
04116 
04117     return Py_INCREF(def), def;
04118 }
04119 
04120 PyDoc_STRVAR(pyrna_prop_collection_find_doc,
04121 ".. method:: find(key)\n"
04122 "\n"
04123 "   Returns the index of a key in a collection or -1 when not found\n"
04124 "   (matches pythons string find function of the same name).\n"
04125 "\n"
04126 "   :arg key: The identifier for the collection member.\n"
04127 "   :type key: string\n"
04128 "   :return: index of the key.\n"
04129 "   :rtype: int\n"
04130 );
04131 static PyObject *pyrna_prop_collection_find(BPy_PropertyRNA *self, PyObject *key_ob)
04132 {
04133     Py_ssize_t key_len_ssize_t;
04134     const char *key = _PyUnicode_AsStringAndSize(key_ob, &key_len_ssize_t);
04135     const int key_len = (int)key_len_ssize_t; /* comare with same type */
04136 
04137     char name[256], *nameptr;
04138     int namelen;
04139     int i = 0;
04140     int index = -1;
04141 
04142     PYRNA_PROP_CHECK_OBJ(self);
04143 
04144     RNA_PROP_BEGIN(&self->ptr, itemptr, self->prop) {
04145         nameptr = RNA_struct_name_get_alloc(&itemptr, name, sizeof(name), &namelen);
04146 
04147         if (nameptr) {
04148             if ((key_len == namelen) && memcmp(nameptr, key, key_len) == 0) {
04149                 index = i;
04150                 break;
04151             }
04152 
04153             if (name != nameptr) {
04154                 MEM_freeN(nameptr);
04155             }
04156         }
04157 
04158         i++;
04159     }
04160     RNA_PROP_END;
04161 
04162     return PyLong_FromSsize_t(index);
04163 }
04164 
04165 static void foreach_attr_type(  BPy_PropertyRNA *self, const char *attr,
04166                                     /* values to assign */
04167                                     RawPropertyType *raw_type, int *attr_tot, int *attr_signed)
04168 {
04169     PropertyRNA *prop;
04170     *raw_type = PROP_RAW_UNSET;
04171     *attr_tot = 0;
04172     *attr_signed = FALSE;
04173 
04174     /* note: this is fail with zero length lists, so dont let this get caled in that case */
04175     RNA_PROP_BEGIN(&self->ptr, itemptr, self->prop) {
04176         prop = RNA_struct_find_property(&itemptr, attr);
04177         *raw_type = RNA_property_raw_type(prop);
04178         *attr_tot = RNA_property_array_length(&itemptr, prop);
04179         *attr_signed = (RNA_property_subtype(prop) == PROP_UNSIGNED) ? FALSE:TRUE;
04180         break;
04181     }
04182     RNA_PROP_END;
04183 }
04184 
04185 /* pyrna_prop_collection_foreach_get/set both use this */
04186 static int foreach_parse_args(
04187         BPy_PropertyRNA *self, PyObject *args,
04188 
04189         /*values to assign */
04190         const char **attr, PyObject **seq, int *tot, int *size,
04191         RawPropertyType *raw_type, int *attr_tot, int *attr_signed
04192         )
04193 {
04194 #if 0
04195     int array_tot;
04196     int target_tot;
04197 #endif
04198 
04199     *size = *attr_tot = *attr_signed = FALSE;
04200     *raw_type = PROP_RAW_UNSET;
04201 
04202     if (!PyArg_ParseTuple(args, "sO", attr, seq) || (!PySequence_Check(*seq) && PyObject_CheckBuffer(*seq))) {
04203         PyErr_SetString(PyExc_TypeError, "foreach_get(attr, sequence) expects a string and a sequence");
04204         return -1;
04205     }
04206 
04207     *tot = PySequence_Size(*seq); // TODO - buffer may not be a sequence! array.array() is tho.
04208 
04209     if (*tot > 0) {
04210         foreach_attr_type(self, *attr, raw_type, attr_tot, attr_signed);
04211         *size = RNA_raw_type_sizeof(*raw_type);
04212 
04213 #if 0   // works fine but not strictly needed, we could allow RNA_property_collection_raw_* to do the checks
04214         if ((*attr_tot) < 1)
04215             *attr_tot = 1;
04216 
04217         if (RNA_property_type(self->prop) == PROP_COLLECTION)
04218             array_tot = RNA_property_collection_length(&self->ptr, self->prop);
04219         else
04220             array_tot = RNA_property_array_length(&self->ptr, self->prop);
04221 
04222 
04223         target_tot = array_tot * (*attr_tot);
04224 
04225         /* rna_access.c - rna_raw_access(...) uses this same method */
04226         if (target_tot != (*tot)) {
04227             PyErr_Format(PyExc_TypeError,
04228                          "foreach_get(attr, sequence) sequence length mismatch given %d, needed %d",
04229                          *tot, target_tot);
04230             return -1;
04231         }
04232 #endif
04233     }
04234 
04235     /* check 'attr_tot' otherwise we dont know if any values were set
04236      * this isn't ideal because it means running on an empty list may fail silently when its not compatible. */
04237     if (*size == 0 && *attr_tot != 0) {
04238         PyErr_SetString(PyExc_AttributeError, "attribute does not support foreach method");
04239         return -1;
04240     }
04241     return 0;
04242 }
04243 
04244 static int foreach_compat_buffer(RawPropertyType raw_type, int attr_signed, const char *format)
04245 {
04246     char f = format ? *format:'B'; /* B is assumed when not set */
04247 
04248     switch (raw_type) {
04249     case PROP_RAW_CHAR:
04250         if (attr_signed)  return (f == 'b') ? 1:0;
04251         else              return (f == 'B') ? 1:0;
04252     case PROP_RAW_SHORT:
04253         if (attr_signed)  return (f == 'h') ? 1:0;
04254         else              return (f == 'H') ? 1:0;
04255     case PROP_RAW_INT:
04256         if (attr_signed)  return (f == 'i') ? 1:0;
04257         else              return (f == 'I') ? 1:0;
04258     case PROP_RAW_FLOAT:
04259         return (f == 'f') ? 1:0;
04260     case PROP_RAW_DOUBLE:
04261         return (f == 'd') ? 1:0;
04262     case PROP_RAW_UNSET:
04263         return 0;
04264     }
04265 
04266     return 0;
04267 }
04268 
04269 static PyObject *foreach_getset(BPy_PropertyRNA *self, PyObject *args, int set)
04270 {
04271     PyObject *item = NULL;
04272     int i = 0, ok = 0, buffer_is_compat;
04273     void *array = NULL;
04274 
04275     /* get/set both take the same args currently */
04276     const char *attr;
04277     PyObject *seq;
04278     int tot, size, attr_tot, attr_signed;
04279     RawPropertyType raw_type;
04280 
04281     if (foreach_parse_args(self, args, &attr, &seq, &tot, &size, &raw_type, &attr_tot, &attr_signed) < 0)
04282         return NULL;
04283 
04284     if (tot == 0)
04285         Py_RETURN_NONE;
04286 
04287 
04288 
04289     if (set) { /* get the array from python */
04290         buffer_is_compat = FALSE;
04291         if (PyObject_CheckBuffer(seq)) {
04292             Py_buffer buf;
04293             PyObject_GetBuffer(seq, &buf, PyBUF_SIMPLE | PyBUF_FORMAT);
04294 
04295             /* check if the buffer matches */
04296 
04297             buffer_is_compat = foreach_compat_buffer(raw_type, attr_signed, buf.format);
04298 
04299             if (buffer_is_compat) {
04300                 ok = RNA_property_collection_raw_set(NULL, &self->ptr, self->prop, attr, buf.buf, raw_type, tot);
04301             }
04302 
04303             PyBuffer_Release(&buf);
04304         }
04305 
04306         /* could not use the buffer, fallback to sequence */
04307         if (!buffer_is_compat) {
04308             array = PyMem_Malloc(size * tot);
04309 
04310             for ( ; i < tot; i++) {
04311                 item = PySequence_GetItem(seq, i);
04312                 switch (raw_type) {
04313                 case PROP_RAW_CHAR:
04314                     ((char *)array)[i] = (char)PyLong_AsLong(item);
04315                     break;
04316                 case PROP_RAW_SHORT:
04317                     ((short *)array)[i] = (short)PyLong_AsLong(item);
04318                     break;
04319                 case PROP_RAW_INT:
04320                     ((int *)array)[i] = (int)PyLong_AsLong(item);
04321                     break;
04322                 case PROP_RAW_FLOAT:
04323                     ((float *)array)[i] = (float)PyFloat_AsDouble(item);
04324                     break;
04325                 case PROP_RAW_DOUBLE:
04326                     ((double *)array)[i] = (double)PyFloat_AsDouble(item);
04327                     break;
04328                 case PROP_RAW_UNSET:
04329                     /* should never happen */
04330                     BLI_assert(!"Invalid array type - set");
04331                     break;
04332                 }
04333 
04334                 Py_DECREF(item);
04335             }
04336 
04337             ok = RNA_property_collection_raw_set(NULL, &self->ptr, self->prop, attr, array, raw_type, tot);
04338         }
04339     }
04340     else {
04341         buffer_is_compat = FALSE;
04342         if (PyObject_CheckBuffer(seq)) {
04343             Py_buffer buf;
04344             PyObject_GetBuffer(seq, &buf, PyBUF_SIMPLE | PyBUF_FORMAT);
04345 
04346             /* check if the buffer matches, TODO - signed/unsigned types */
04347 
04348             buffer_is_compat = foreach_compat_buffer(raw_type, attr_signed, buf.format);
04349 
04350             if (buffer_is_compat) {
04351                 ok = RNA_property_collection_raw_get(NULL, &self->ptr, self->prop, attr, buf.buf, raw_type, tot);
04352             }
04353 
04354             PyBuffer_Release(&buf);
04355         }
04356 
04357         /* could not use the buffer, fallback to sequence */
04358         if (!buffer_is_compat) {
04359             array = PyMem_Malloc(size * tot);
04360 
04361             ok = RNA_property_collection_raw_get(NULL, &self->ptr, self->prop, attr, array, raw_type, tot);
04362 
04363             if (!ok) i = tot; /* skip the loop */
04364 
04365             for ( ; i < tot; i++) {
04366 
04367                 switch (raw_type) {
04368                 case PROP_RAW_CHAR:
04369                     item = PyLong_FromSsize_t((Py_ssize_t) ((char *)array)[i]);
04370                     break;
04371                 case PROP_RAW_SHORT:
04372                     item = PyLong_FromSsize_t((Py_ssize_t) ((short *)array)[i]);
04373                     break;
04374                 case PROP_RAW_INT:
04375                     item = PyLong_FromSsize_t((Py_ssize_t) ((int *)array)[i]);
04376                     break;
04377                 case PROP_RAW_FLOAT:
04378                     item = PyFloat_FromDouble((double) ((float *)array)[i]);
04379                     break;
04380                 case PROP_RAW_DOUBLE:
04381                     item = PyFloat_FromDouble((double) ((double *)array)[i]);
04382                     break;
04383                 default: /* PROP_RAW_UNSET */
04384                     /* should never happen */
04385                     BLI_assert(!"Invalid array type - get");
04386                     item = Py_None;
04387                     Py_INCREF(item);
04388                     break;
04389                 }
04390 
04391                 PySequence_SetItem(seq, i, item);
04392                 Py_DECREF(item);
04393             }
04394         }
04395     }
04396 
04397     if (array)
04398         PyMem_Free(array);
04399 
04400     if (PyErr_Occurred()) {
04401         /* Maybe we could make our own error */
04402         PyErr_Print();
04403         PyErr_SetString(PyExc_TypeError, "couldn't access the py sequence");
04404         return NULL;
04405     }
04406     if (!ok) {
04407         PyErr_SetString(PyExc_RuntimeError, "internal error setting the array");
04408         return NULL;
04409     }
04410 
04411     Py_RETURN_NONE;
04412 }
04413 
04414 PyDoc_STRVAR(pyrna_prop_collection_foreach_get_doc,
04415 ".. method:: foreach_get(attr, seq)\n"
04416 "\n"
04417 "   This is a function to give fast access to attributes within a collection.\n"
04418 "\n"
04419 "   .. code-block:: python\n"
04420 "\n"
04421 "      collection.foreach_get(someseq, attr)\n"
04422 "\n"
04423 "      # Python equivalent\n"
04424 "      for i in range(len(seq)): someseq[i] = getattr(collection, attr)\n"
04425 "\n"
04426 );
04427 static PyObject *pyrna_prop_collection_foreach_get(BPy_PropertyRNA *self, PyObject *args)
04428 {
04429     PYRNA_PROP_CHECK_OBJ(self);
04430 
04431     return foreach_getset(self, args, 0);
04432 }
04433 
04434 PyDoc_STRVAR(pyrna_prop_collection_foreach_set_doc,
04435 ".. method:: foreach_set(attr, seq)\n"
04436 "\n"
04437 "   This is a function to give fast access to attributes within a collection.\n"
04438 "\n"
04439 "   .. code-block:: python\n"
04440 "\n"
04441 "      collection.foreach_set(seq, attr)\n"
04442 "\n"
04443 "      # Python equivalent\n"
04444 "      for i in range(len(seq)): setattr(collection[i], attr, seq[i])\n"
04445 "\n"
04446 );
04447 static PyObject *pyrna_prop_collection_foreach_set(BPy_PropertyRNA *self, PyObject *args)
04448 {
04449     PYRNA_PROP_CHECK_OBJ(self);
04450 
04451     return foreach_getset(self, args, 1);
04452 }
04453 
04454 /* A bit of a kludge, make a list out of a collection or array,
04455  * then return the lists iter function, not especially fast but convenient for now */
04456 static PyObject *pyrna_prop_array_iter(BPy_PropertyArrayRNA *self)
04457 {
04458     /* Try get values from a collection */
04459     PyObject *ret;
04460     PyObject *iter = NULL;
04461     int len;
04462 
04463     PYRNA_PROP_CHECK_OBJ((BPy_PropertyRNA *)self);
04464 
04465     len = pyrna_prop_array_length(self);
04466     ret = pyrna_prop_array_subscript_slice(self, &self->ptr, self->prop, 0, len, len);
04467 
04468     /* we know this is a list so no need to PyIter_Check
04469      * otherwise it could be NULL (unlikely) if conversion failed */
04470     if (ret) {
04471         iter = PyObject_GetIter(ret);
04472         Py_DECREF(ret);
04473     }
04474 
04475     return iter;
04476 }
04477 
04478 static PyObject *pyrna_prop_collection_iter(BPy_PropertyRNA *self);
04479 
04480 #ifndef USE_PYRNA_ITER
04481 static PyObject *pyrna_prop_collection_iter(BPy_PropertyRNA *self)
04482 {
04483     /* Try get values from a collection */
04484     PyObject *ret;
04485     PyObject *iter = NULL;
04486     ret = pyrna_prop_collection_values(self);
04487 
04488     /* we know this is a list so no need to PyIter_Check
04489      * otherwise it could be NULL (unlikely) if conversion failed */
04490     if (ret) {
04491         iter = PyObject_GetIter(ret);
04492         Py_DECREF(ret);
04493     }
04494 
04495     return iter;
04496 }
04497 #endif /* # !USE_PYRNA_ITER */
04498 
04499 static struct PyMethodDef pyrna_struct_methods[] = {
04500 
04501     /* only for PointerRNA's with ID'props */
04502     {"keys", (PyCFunction)pyrna_struct_keys, METH_NOARGS, pyrna_struct_keys_doc},
04503     {"values", (PyCFunction)pyrna_struct_values, METH_NOARGS, pyrna_struct_values_doc},
04504     {"items", (PyCFunction)pyrna_struct_items, METH_NOARGS, pyrna_struct_items_doc},
04505 
04506     {"get", (PyCFunction)pyrna_struct_get, METH_VARARGS, pyrna_struct_get_doc},
04507 
04508     {"as_pointer", (PyCFunction)pyrna_struct_as_pointer, METH_NOARGS, pyrna_struct_as_pointer_doc},
04509 
04510     /* bpy_rna_anim.c */
04511     {"keyframe_insert", (PyCFunction)pyrna_struct_keyframe_insert, METH_VARARGS|METH_KEYWORDS, pyrna_struct_keyframe_insert_doc},
04512     {"keyframe_delete", (PyCFunction)pyrna_struct_keyframe_delete, METH_VARARGS|METH_KEYWORDS, pyrna_struct_keyframe_delete_doc},
04513     {"driver_add", (PyCFunction)pyrna_struct_driver_add, METH_VARARGS, pyrna_struct_driver_add_doc},
04514     {"driver_remove", (PyCFunction)pyrna_struct_driver_remove, METH_VARARGS, pyrna_struct_driver_remove_doc},
04515 
04516     {"is_property_set", (PyCFunction)pyrna_struct_is_property_set, METH_VARARGS, pyrna_struct_is_property_set_doc},
04517     {"is_property_hidden", (PyCFunction)pyrna_struct_is_property_hidden, METH_VARARGS, pyrna_struct_is_property_hidden_doc},
04518     {"path_resolve", (PyCFunction)pyrna_struct_path_resolve, METH_VARARGS, pyrna_struct_path_resolve_doc},
04519     {"path_from_id", (PyCFunction)pyrna_struct_path_from_id, METH_VARARGS, pyrna_struct_path_from_id_doc},
04520     {"type_recast", (PyCFunction)pyrna_struct_type_recast, METH_NOARGS, pyrna_struct_type_recast_doc},
04521     {"__dir__", (PyCFunction)pyrna_struct_dir, METH_NOARGS, NULL},
04522 
04523     /* experemental */
04524     {"callback_add", (PyCFunction)pyrna_callback_add, METH_VARARGS, NULL},
04525     {"callback_remove", (PyCFunction)pyrna_callback_remove, METH_VARARGS, NULL},
04526     {NULL, NULL, 0, NULL}
04527 };
04528 
04529 static struct PyMethodDef pyrna_prop_methods[] = {
04530     {"path_from_id", (PyCFunction)pyrna_prop_path_from_id, METH_NOARGS, pyrna_prop_path_from_id_doc},
04531     {"__dir__", (PyCFunction)pyrna_prop_dir, METH_NOARGS, NULL},
04532     {NULL, NULL, 0, NULL}
04533 };
04534 
04535 static struct PyMethodDef pyrna_prop_array_methods[] = {
04536     {NULL, NULL, 0, NULL}
04537 };
04538 
04539 static struct PyMethodDef pyrna_prop_collection_methods[] = {
04540     {"foreach_get", (PyCFunction)pyrna_prop_collection_foreach_get, METH_VARARGS, pyrna_prop_collection_foreach_get_doc},
04541     {"foreach_set", (PyCFunction)pyrna_prop_collection_foreach_set, METH_VARARGS, pyrna_prop_collection_foreach_set_doc},
04542 
04543     {"keys", (PyCFunction)pyrna_prop_collection_keys, METH_NOARGS, pyrna_prop_collection_keys_doc},
04544     {"items", (PyCFunction)pyrna_prop_collection_items, METH_NOARGS, pyrna_prop_collection_items_doc},
04545     {"values", (PyCFunction)pyrna_prop_collection_values, METH_NOARGS, pyrna_prop_collection_values_doc},
04546 
04547     {"get", (PyCFunction)pyrna_prop_collection_get, METH_VARARGS, pyrna_prop_collection_get_doc},
04548     {"find", (PyCFunction)pyrna_prop_collection_find, METH_O, pyrna_prop_collection_find_doc},
04549     {NULL, NULL, 0, NULL}
04550 };
04551 
04552 static struct PyMethodDef pyrna_prop_collection_idprop_methods[] = {
04553     {"add", (PyCFunction)pyrna_prop_collection_idprop_add, METH_NOARGS, NULL},
04554     {"remove", (PyCFunction)pyrna_prop_collection_idprop_remove, METH_O, NULL},
04555     {"move", (PyCFunction)pyrna_prop_collection_idprop_move, METH_VARARGS, NULL},
04556     {NULL, NULL, 0, NULL}
04557 };
04558 
04559 /* only needed for subtyping, so a new class gets a valid BPy_StructRNA
04560  * todo - also accept useful args */
04561 static PyObject *pyrna_struct_new(PyTypeObject *type, PyObject *args, PyObject *UNUSED(kwds))
04562 {
04563     if (PyTuple_GET_SIZE(args) == 1) {
04564         BPy_StructRNA *base = (BPy_StructRNA *)PyTuple_GET_ITEM(args, 0);
04565         if (Py_TYPE(base) == type) {
04566             Py_INCREF(base);
04567             return (PyObject *)base;
04568         }
04569         else if (PyType_IsSubtype(Py_TYPE(base), &pyrna_struct_Type)) {
04570             /* this almost never runs, only when using user defined subclasses of built-in object.
04571              * this isn't common since its NOT related to registerable subclasses. eg:
04572 
04573                 >>> class MyObSubclass(bpy.types.Object):
04574                 ...     def test_func(self):
04575                 ...         print(100)
04576                 ...
04577                 >>> myob = MyObSubclass(bpy.context.object)
04578                 >>> myob.test_func()
04579                 100
04580              *
04581              * Keep this since it could be useful.
04582              */
04583             BPy_StructRNA *ret;
04584             if ((ret = (BPy_StructRNA *)type->tp_alloc(type, 0))) {
04585                 ret->ptr = base->ptr;
04586             }
04587             /* pass on exception & NULL if tp_alloc fails */
04588             return (PyObject *)ret;
04589         }
04590 
04591         /* error, invalid type given */
04592         PyErr_Format(PyExc_TypeError,
04593                      "bpy_struct.__new__(type): type '%.200s' is not a subtype of bpy_struct",
04594                      type->tp_name);
04595         return NULL;
04596     }
04597     else {
04598         PyErr_Format(PyExc_TypeError,
04599                      "bpy_struct.__new__(type): expected a single argument");
04600         return NULL;
04601     }
04602 }
04603 
04604 /* only needed for subtyping, so a new class gets a valid BPy_StructRNA
04605  * todo - also accept useful args */
04606 static PyObject *pyrna_prop_new(PyTypeObject *type, PyObject *args, PyObject *UNUSED(kwds))
04607 {
04608     BPy_PropertyRNA *base;
04609 
04610     if (!PyArg_ParseTuple(args, "O!:bpy_prop.__new__", &pyrna_prop_Type, &base))
04611         return NULL;
04612 
04613     if (type == Py_TYPE(base)) {
04614         Py_INCREF(base);
04615         return (PyObject *)base;
04616     }
04617     else if (PyType_IsSubtype(type, &pyrna_prop_Type)) {
04618         BPy_PropertyRNA *ret = (BPy_PropertyRNA *) type->tp_alloc(type, 0);
04619         ret->ptr = base->ptr;
04620         ret->prop = base->prop;
04621         return (PyObject *)ret;
04622     }
04623     else {
04624         PyErr_Format(PyExc_TypeError,
04625                      "bpy_prop.__new__(type): type '%.200s' is not a subtype of bpy_prop",
04626                      type->tp_name);
04627         return NULL;
04628     }
04629 }
04630 
04631 static PyObject *pyrna_param_to_py(PointerRNA *ptr, PropertyRNA *prop, void *data)
04632 {
04633     PyObject *ret;
04634     const int type = RNA_property_type(prop);
04635     const int flag = RNA_property_flag(prop);
04636 
04637     if (RNA_property_array_check(prop)) {
04638         int a, len;
04639 
04640         if (flag & PROP_DYNAMIC) {
04641             ParameterDynAlloc *data_alloc = data;
04642             len = data_alloc->array_tot;
04643             data = data_alloc->array;
04644         }
04645         else
04646             len = RNA_property_array_length(ptr, prop);
04647 
04648         /* resolve the array from a new pytype */
04649 
04650         /* kazanbas: TODO make multidim sequences here */
04651 
04652         switch (type) {
04653         case PROP_BOOLEAN:
04654             ret = PyTuple_New(len);
04655             for (a = 0; a < len; a++)
04656                 PyTuple_SET_ITEM(ret, a, PyBool_FromLong(((int *)data)[a]));
04657             break;
04658         case PROP_INT:
04659             ret = PyTuple_New(len);
04660             for (a = 0; a < len; a++)
04661                 PyTuple_SET_ITEM(ret, a, PyLong_FromSsize_t((Py_ssize_t)((int *)data)[a]));
04662             break;
04663         case PROP_FLOAT:
04664             switch (RNA_property_subtype(prop)) {
04665 #ifdef USE_MATHUTILS
04666                 case PROP_ALL_VECTOR_SUBTYPES:
04667                     ret = Vector_CreatePyObject(data, len, Py_NEW, NULL);
04668                     break;
04669                 case PROP_MATRIX:
04670                     if (len == 16) {
04671                         ret = Matrix_CreatePyObject(data, 4, 4, Py_NEW, NULL);
04672                         break;
04673                     }
04674                     else if (len == 9) {
04675                         ret = Matrix_CreatePyObject(data, 3, 3, Py_NEW, NULL);
04676                         break;
04677                     }
04678                     /* pass through */
04679 #endif
04680                 default:
04681                     ret = PyTuple_New(len);
04682                     for (a = 0; a < len; a++)
04683                         PyTuple_SET_ITEM(ret, a, PyFloat_FromDouble(((float *)data)[a]));
04684 
04685             }
04686             break;
04687         default:
04688             PyErr_Format(PyExc_TypeError,
04689                          "RNA Error: unknown array type \"%d\" (pyrna_param_to_py)",
04690                          type);
04691             ret = NULL;
04692             break;
04693         }
04694     }
04695     else {
04696         /* see if we can coorce into a python type - PropertyType */
04697         switch (type) {
04698         case PROP_BOOLEAN:
04699             ret = PyBool_FromLong(*(int *)data);
04700             break;
04701         case PROP_INT:
04702             ret = PyLong_FromSsize_t((Py_ssize_t)*(int *)data);
04703             break;
04704         case PROP_FLOAT:
04705             ret = PyFloat_FromDouble(*(float *)data);
04706             break;
04707         case PROP_STRING:
04708         {
04709             char *data_ch;
04710             PyObject *value_coerce = NULL;
04711             const int subtype = RNA_property_subtype(prop);
04712 
04713             if (flag & PROP_THICK_WRAP)
04714                 data_ch = (char *)data;
04715             else
04716                 data_ch = *(char **)data;
04717 
04718 #ifdef USE_STRING_COERCE
04719             if (subtype == PROP_BYTESTRING) {
04720                 ret = PyBytes_FromString(data_ch);
04721             }
04722             else if (ELEM3(subtype, PROP_FILEPATH, PROP_DIRPATH, PROP_FILENAME)) {
04723                 ret = PyC_UnicodeFromByte(data_ch);
04724             }
04725             else {
04726                 ret = PyUnicode_FromString(data_ch);
04727             }
04728 #else
04729             if (subtype == PROP_BYTESTRING) {
04730                 ret = PyBytes_FromString(buf);
04731             }
04732             else {
04733                 ret = PyUnicode_FromString(data_ch);
04734             }
04735 #endif
04736 
04737 #ifdef USE_STRING_COERCE
04738             Py_XDECREF(value_coerce);
04739 #endif
04740 
04741             break;
04742         }
04743         case PROP_ENUM:
04744         {
04745             ret = pyrna_enum_to_py(ptr, prop, *(int *)data);
04746             break;
04747         }
04748         case PROP_POINTER:
04749         {
04750             PointerRNA newptr;
04751             StructRNA *ptype = RNA_property_pointer_type(ptr, prop);
04752 
04753             if (flag & PROP_RNAPTR) {
04754                 /* in this case we get the full ptr */
04755                 newptr = *(PointerRNA *)data;
04756             }
04757             else {
04758                 if (RNA_struct_is_ID(ptype)) {
04759                     RNA_id_pointer_create(*(void **)data, &newptr);
04760                 }
04761                 else {
04762                     /* note: this is taken from the function's ID pointer
04763                      * and will break if a function returns a pointer from
04764                      * another ID block, watch this! - it should at least be
04765                      * easy to debug since they are all ID's */
04766                     RNA_pointer_create(ptr->id.data, ptype, *(void **)data, &newptr);
04767                 }
04768             }
04769 
04770             if (newptr.data) {
04771                 ret = pyrna_struct_CreatePyObject(&newptr);
04772             }
04773             else {
04774                 ret = Py_None;
04775                 Py_INCREF(ret);
04776             }
04777             break;
04778         }
04779         case PROP_COLLECTION:
04780         {
04781             ListBase *lb = (ListBase *)data;
04782             CollectionPointerLink *link;
04783             PyObject *linkptr;
04784 
04785             ret = PyList_New(0);
04786 
04787             for (link = lb->first; link; link = link->next) {
04788                 linkptr = pyrna_struct_CreatePyObject(&link->ptr);
04789                 PyList_Append(ret, linkptr);
04790                 Py_DECREF(linkptr);
04791             }
04792 
04793             break;
04794         }
04795         default:
04796             PyErr_Format(PyExc_TypeError,
04797                          "RNA Error: unknown type \"%d\" (pyrna_param_to_py)",
04798                          type);
04799             ret = NULL;
04800             break;
04801         }
04802     }
04803 
04804     return ret;
04805 }
04806 
04807 /* Use to replace PyDict_GetItemString() when the overhead of converting a
04808  * string into a python unicode is higher than a non hash lookup.
04809  * works on small dict's such as keyword args. */
04810 static PyObject *small_dict_get_item_string(PyObject *dict, const char *key_lookup)
04811 {
04812     PyObject *key = NULL;
04813     Py_ssize_t pos = 0;
04814     PyObject *value = NULL;
04815 
04816     while (PyDict_Next(dict, &pos, &key, &value)) {
04817         if (PyUnicode_Check(key)) {
04818             if (strcmp(key_lookup, _PyUnicode_AsString(key)) == 0) {
04819                 return value;
04820             }
04821         }
04822     }
04823 
04824     return NULL;
04825 }
04826 
04827 static PyObject *pyrna_func_call(BPy_FunctionRNA *self, PyObject *args, PyObject *kw)
04828 {
04829     /* Note, both BPy_StructRNA and BPy_PropertyRNA can be used here */
04830     PointerRNA *self_ptr = &self->ptr;
04831     FunctionRNA *self_func = self->func;
04832 
04833     PointerRNA funcptr;
04834     ParameterList parms;
04835     ParameterIterator iter;
04836     PropertyRNA *parm;
04837     PyObject *ret, *item;
04838     int i, pyargs_len, pykw_len, parms_len, ret_len, flag, err = 0, kw_tot = 0, kw_arg;
04839 
04840     PropertyRNA *pret_single = NULL;
04841     void *retdata_single = NULL;
04842 
04843     /* enable this so all strings are copied and freed after calling.
04844      * this exposes bugs where the pointer to the string is held and re-used */
04845 // #define DEBUG_STRING_FREE
04846 
04847 #ifdef DEBUG_STRING_FREE
04848     PyObject *string_free_ls = PyList_New(0);
04849 #endif
04850 
04851     /* Should never happen but it does in rare cases */
04852     BLI_assert(self_ptr != NULL);
04853 
04854     if (self_ptr == NULL) {
04855         PyErr_SetString(PyExc_RuntimeError, "rna functions internal rna pointer is NULL, this is a bug. aborting");
04856         return NULL;
04857     }
04858 
04859     if (self_func == NULL) {
04860         PyErr_Format(PyExc_RuntimeError,
04861                      "%.200s.<unknown>(): rna function internal function is NULL, this is a bug. aborting",
04862                      RNA_struct_identifier(self_ptr->type));
04863         return NULL;
04864     }
04865 
04866     /* for testing */
04867     /*
04868     {
04869         const char *fn;
04870         int lineno;
04871         PyC_FileAndNum(&fn, &lineno);
04872         printf("pyrna_func_call > %.200s.%.200s : %.200s:%d\n",
04873                RNA_struct_identifier(self_ptr->type), RNA_function_identifier(self_func), fn, lineno);
04874     }
04875     */
04876 
04877     /* include the ID pointer for pyrna_param_to_py() so we can include the
04878      * ID pointer on return values, this only works when returned values have
04879      * the same ID as the functions. */
04880     RNA_pointer_create(self_ptr->id.data, &RNA_Function, self_func, &funcptr);
04881 
04882     pyargs_len = PyTuple_GET_SIZE(args);
04883     pykw_len = kw ? PyDict_Size(kw) : 0;
04884 
04885     RNA_parameter_list_create(&parms, self_ptr, self_func);
04886     RNA_parameter_list_begin(&parms, &iter);
04887     parms_len = RNA_parameter_list_arg_count(&parms);
04888     ret_len = 0;
04889 
04890     if (pyargs_len + pykw_len > parms_len) {
04891         RNA_parameter_list_end(&iter);
04892         PyErr_Format(PyExc_TypeError,
04893                      "%.200s.%.200s(): takes at most %d arguments, got %d",
04894                      RNA_struct_identifier(self_ptr->type), RNA_function_identifier(self_func),
04895                      parms_len, pyargs_len + pykw_len);
04896         err = -1;
04897     }
04898 
04899     /* parse function parameters */
04900     for (i = 0; iter.valid && err == 0; RNA_parameter_list_next(&iter)) {
04901         parm = iter.parm;
04902         flag = RNA_property_flag(parm);
04903 
04904         /* only useful for single argument returns, we'll need another list loop for multiple */
04905         if (flag & PROP_OUTPUT) {
04906             ret_len++;
04907             if (pret_single == NULL) {
04908                 pret_single = parm;
04909                 retdata_single = iter.data;
04910             }
04911 
04912             continue;
04913         }
04914 
04915         item = NULL;
04916 
04917         if (i < pyargs_len) {
04918             item = PyTuple_GET_ITEM(args, i);
04919             kw_arg = FALSE;
04920         }
04921         else if (kw != NULL) {
04922 #if 0
04923             item = PyDict_GetItemString(kw, RNA_property_identifier(parm)); /* borrow ref */
04924 #else
04925             item = small_dict_get_item_string(kw, RNA_property_identifier(parm)); /* borrow ref */
04926 #endif
04927             if (item)
04928                 kw_tot++; /* make sure invalid keywords are not given */
04929 
04930             kw_arg = TRUE;
04931         }
04932 
04933         i++; /* current argument */
04934 
04935         if (item == NULL) {
04936             if (flag & PROP_REQUIRED) {
04937                 PyErr_Format(PyExc_TypeError,
04938                              "%.200s.%.200s(): required parameter \"%.200s\" not specified",
04939                              RNA_struct_identifier(self_ptr->type),
04940                              RNA_function_identifier(self_func),
04941                              RNA_property_identifier(parm));
04942                 err = -1;
04943                 break;
04944             }
04945             else { /* PyDict_GetItemString wont raise an error */
04946                 continue;
04947             }
04948         }
04949 
04950 #ifdef DEBUG_STRING_FREE
04951         if (item) {
04952             if (PyUnicode_Check(item)) {
04953                 item = PyUnicode_FromString(_PyUnicode_AsString(item));
04954                 PyList_Append(string_free_ls, item);
04955                 Py_DECREF(item);
04956             }
04957         }
04958 #endif
04959         err = pyrna_py_to_prop(&funcptr, parm, iter.data, item, "");
04960 
04961         if (err != 0) {
04962             /* the error generated isn't that useful, so generate it again with a useful prefix
04963              * could also write a function to prepend to error messages */
04964             char error_prefix[512];
04965             PyErr_Clear(); /* re-raise */
04966 
04967             if (kw_arg == TRUE)
04968                 BLI_snprintf(error_prefix, sizeof(error_prefix),
04969                              "%.200s.%.200s(): error with keyword argument \"%.200s\" - ",
04970                              RNA_struct_identifier(self_ptr->type),
04971                              RNA_function_identifier(self_func),
04972                              RNA_property_identifier(parm));
04973             else
04974                 BLI_snprintf(error_prefix, sizeof(error_prefix),
04975                              "%.200s.%.200s(): error with argument %d, \"%.200s\" - ",
04976                              RNA_struct_identifier(self_ptr->type),
04977                              RNA_function_identifier(self_func),
04978                              i,
04979                              RNA_property_identifier(parm));
04980 
04981             pyrna_py_to_prop(&funcptr, parm, iter.data, item, error_prefix);
04982 
04983             break;
04984         }
04985     }
04986 
04987     RNA_parameter_list_end(&iter);
04988 
04989     /* Check if we gave args that don't exist in the function
04990      * printing the error is slow but it should only happen when developing.
04991      * the if below is quick, checking if it passed less keyword args then we gave.
04992      * (Dont overwrite the error if we have one, otherwise can skip important messages and confuse with args)
04993      */
04994     if (err == 0 && kw && (pykw_len > kw_tot)) {
04995         PyObject *key, *value;
04996         Py_ssize_t pos = 0;
04997 
04998         DynStr *bad_args = BLI_dynstr_new();
04999         DynStr *good_args = BLI_dynstr_new();
05000 
05001         const char *arg_name, *bad_args_str, *good_args_str;
05002         int found = FALSE, first = TRUE;
05003 
05004         while (PyDict_Next(kw, &pos, &key, &value)) {
05005 
05006             arg_name = _PyUnicode_AsString(key);
05007             found = FALSE;
05008 
05009             if (arg_name == NULL) { /* unlikely the argname is not a string but ignore if it is*/
05010                 PyErr_Clear();
05011             }
05012             else {
05013                 /* Search for arg_name */
05014                 RNA_parameter_list_begin(&parms, &iter);
05015                 for (; iter.valid; RNA_parameter_list_next(&iter)) {
05016                     parm = iter.parm;
05017                     if (strcmp(arg_name, RNA_property_identifier(parm)) == 0) {
05018                         found = TRUE;
05019                         break;
05020                     }
05021                 }
05022 
05023                 RNA_parameter_list_end(&iter);
05024 
05025                 if (found == FALSE) {
05026                     BLI_dynstr_appendf(bad_args, first ? "%s" : ", %s", arg_name);
05027                     first = FALSE;
05028                 }
05029             }
05030         }
05031 
05032         /* list good args */
05033         first = TRUE;
05034 
05035         RNA_parameter_list_begin(&parms, &iter);
05036         for (; iter.valid; RNA_parameter_list_next(&iter)) {
05037             parm = iter.parm;
05038             if (RNA_property_flag(parm) & PROP_OUTPUT)
05039                 continue;
05040 
05041             BLI_dynstr_appendf(good_args, first ? "%s" : ", %s", RNA_property_identifier(parm));
05042             first = FALSE;
05043         }
05044         RNA_parameter_list_end(&iter);
05045 
05046 
05047         bad_args_str = BLI_dynstr_get_cstring(bad_args);
05048         good_args_str = BLI_dynstr_get_cstring(good_args);
05049 
05050         PyErr_Format(PyExc_TypeError,
05051                      "%.200s.%.200s(): was called with invalid keyword arguments(s) (%s), expected (%s)",
05052                      RNA_struct_identifier(self_ptr->type), RNA_function_identifier(self_func),
05053                      bad_args_str, good_args_str);
05054 
05055         BLI_dynstr_free(bad_args);
05056         BLI_dynstr_free(good_args);
05057         MEM_freeN((void *)bad_args_str);
05058         MEM_freeN((void *)good_args_str);
05059 
05060         err = -1;
05061     }
05062 
05063     ret = NULL;
05064     if (err == 0) {
05065         /* call function */
05066         ReportList reports;
05067         bContext *C = BPy_GetContext();
05068 
05069         BKE_reports_init(&reports, RPT_STORE);
05070         RNA_function_call(C, &reports, self_ptr, self_func, &parms);
05071 
05072         err = (BPy_reports_to_error(&reports, PyExc_RuntimeError, TRUE));
05073 
05074         /* return value */
05075         if (err != -1) {
05076             if (ret_len > 0) {
05077                 if (ret_len > 1) {
05078                     ret = PyTuple_New(ret_len);
05079                     i = 0; /* arg index */
05080 
05081                     RNA_parameter_list_begin(&parms, &iter);
05082 
05083                     for (; iter.valid; RNA_parameter_list_next(&iter)) {
05084                         parm = iter.parm;
05085                         flag = RNA_property_flag(parm);
05086 
05087                         if (flag & PROP_OUTPUT)
05088                             PyTuple_SET_ITEM(ret, i++, pyrna_param_to_py(&funcptr, parm, iter.data));
05089                     }
05090 
05091                     RNA_parameter_list_end(&iter);
05092                 }
05093                 else
05094                     ret = pyrna_param_to_py(&funcptr, pret_single, retdata_single);
05095 
05096                 /* possible there is an error in conversion */
05097                 if (ret == NULL)
05098                     err = -1;
05099             }
05100         }
05101     }
05102 
05103 
05104 #ifdef DEBUG_STRING_FREE
05105     // if (PyList_GET_SIZE(string_free_ls)) printf("%.200s.%.200s():  has %d strings\n", RNA_struct_identifier(self_ptr->type), RNA_function_identifier(self_func), (int)PyList_GET_SIZE(string_free_ls));
05106     Py_DECREF(string_free_ls);
05107 #undef DEBUG_STRING_FREE
05108 #endif
05109 
05110     /* cleanup */
05111     RNA_parameter_list_end(&iter);
05112     RNA_parameter_list_free(&parms);
05113 
05114     if (ret)
05115         return ret;
05116 
05117     if (err == -1)
05118         return NULL;
05119 
05120     Py_RETURN_NONE;
05121 }
05122 
05123 
05124 /* subclasses of pyrna_struct_Type which support idprop definitions use this as a metaclass */
05125 /* note: tp_base member is set to &PyType_Type on init */
05126 PyTypeObject pyrna_struct_meta_idprop_Type = {
05127     PyVarObject_HEAD_INIT(NULL, 0)
05128     "bpy_struct_meta_idprop",   /* tp_name */
05129     sizeof(PyHeapTypeObject),   /* tp_basicsize */ // XXX, would be PyTypeObject, but subtypes of Type must be PyHeapTypeObject's
05130     0,                          /* tp_itemsize */
05131     /* methods */
05132     NULL,                       /* tp_dealloc */
05133     NULL,                       /* printfunc tp_print; */
05134     NULL,                       /* getattrfunc tp_getattr; */
05135     NULL,                       /* setattrfunc tp_setattr; */
05136     NULL,                       /* tp_compare */ /* deprecated in python 3.0! */
05137     NULL,                       /* tp_repr */
05138 
05139     /* Method suites for standard classes */
05140     NULL,                       /* PyNumberMethods *tp_as_number; */
05141     NULL,                       /* PySequenceMethods *tp_as_sequence; */
05142     NULL,                       /* PyMappingMethods *tp_as_mapping; */
05143 
05144     /* More standard operations (here for binary compatibility) */
05145     NULL,                       /* hashfunc tp_hash; */
05146     NULL,                       /* ternaryfunc tp_call; */
05147     NULL,                       /* reprfunc tp_str; */
05148     NULL /*(getattrofunc) pyrna_struct_meta_idprop_getattro*/, /* getattrofunc tp_getattro; */
05149     (setattrofunc) pyrna_struct_meta_idprop_setattro, /* setattrofunc tp_setattro; */
05150 
05151     /* Functions to access object as input/output buffer */
05152     NULL,                       /* PyBufferProcs *tp_as_buffer; */
05153 
05154   /*** Flags to define presence of optional/expanded features ***/
05155     Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE,         /* long tp_flags; */
05156 
05157     NULL,                       /*  char *tp_doc;  Documentation string */
05158   /*** Assigned meaning in release 2.0 ***/
05159     /* call function for all accessible objects */
05160     NULL,                       /* traverseproc tp_traverse; */
05161 
05162     /* delete references to contained objects */
05163     NULL,                       /* inquiry tp_clear; */
05164 
05165   /***  Assigned meaning in release 2.1 ***/
05166   /*** rich comparisons ***/
05167     NULL,                       /* richcmpfunc tp_richcompare; */
05168 
05169   /***  weak reference enabler ***/
05170     0,                          /* long tp_weaklistoffset; */
05171 
05172   /*** Added in release 2.2 ***/
05173     /*   Iterators */
05174     NULL,                       /* getiterfunc tp_iter; */
05175     NULL,                       /* iternextfunc tp_iternext; */
05176 
05177   /*** Attribute descriptor and subclassing stuff ***/
05178     NULL,                       /* struct PyMethodDef *tp_methods; */
05179     NULL,                       /* struct PyMemberDef *tp_members; */
05180     NULL,                       /* struct PyGetSetDef *tp_getset; */
05181 #if defined(_MSC_VER) || defined(FREE_WINDOWS)
05182     NULL, /* defer assignment */
05183 #else
05184     &PyType_Type,                       /* struct _typeobject *tp_base; */
05185 #endif
05186     NULL,                       /* PyObject *tp_dict; */
05187     NULL,                       /* descrgetfunc tp_descr_get; */
05188     NULL,                       /* descrsetfunc tp_descr_set; */
05189     0,                          /* long tp_dictoffset; */
05190     NULL,                       /* initproc tp_init; */
05191     NULL,                       /* allocfunc tp_alloc; */
05192     NULL,                       /* newfunc tp_new; */
05193     /*  Low-level free-memory routine */
05194     NULL,                       /* freefunc tp_free;  */
05195     /* For PyObject_IS_GC */
05196     NULL,                       /* inquiry tp_is_gc;  */
05197     NULL,                       /* PyObject *tp_bases; */
05198     /* method resolution order */
05199     NULL,                       /* PyObject *tp_mro;  */
05200     NULL,                       /* PyObject *tp_cache; */
05201     NULL,                       /* PyObject *tp_subclasses; */
05202     NULL,                       /* PyObject *tp_weaklist; */
05203     NULL
05204 };
05205 
05206 
05207 /*-----------------------BPy_StructRNA method def------------------------------*/
05208 PyTypeObject pyrna_struct_Type = {
05209     PyVarObject_HEAD_INIT(NULL, 0)
05210     "bpy_struct",               /* tp_name */
05211     sizeof(BPy_StructRNA),      /* tp_basicsize */
05212     0,                          /* tp_itemsize */
05213     /* methods */
05214     (destructor) pyrna_struct_dealloc,/* tp_dealloc */
05215     NULL,                       /* printfunc tp_print; */
05216     NULL,                       /* getattrfunc tp_getattr; */
05217     NULL,                       /* setattrfunc tp_setattr; */
05218     NULL,                       /* tp_compare */ /* DEPRECATED in python 3.0! */
05219     (reprfunc) pyrna_struct_repr, /* tp_repr */
05220 
05221     /* Method suites for standard classes */
05222 
05223     NULL,                       /* PyNumberMethods *tp_as_number; */
05224     &pyrna_struct_as_sequence,  /* PySequenceMethods *tp_as_sequence; */
05225     &pyrna_struct_as_mapping,   /* PyMappingMethods *tp_as_mapping; */
05226 
05227     /* More standard operations (here for binary compatibility) */
05228 
05229     (hashfunc) pyrna_struct_hash, /* hashfunc tp_hash; */
05230     NULL,                       /* ternaryfunc tp_call; */
05231     (reprfunc) pyrna_struct_str, /* reprfunc tp_str; */
05232     (getattrofunc) pyrna_struct_getattro, /* getattrofunc tp_getattro; */
05233     (setattrofunc) pyrna_struct_setattro, /* setattrofunc tp_setattro; */
05234 
05235     /* Functions to access object as input/output buffer */
05236     NULL,                       /* PyBufferProcs *tp_as_buffer; */
05237 
05238   /*** Flags to define presence of optional/expanded features ***/
05239     Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE | Py_TPFLAGS_HAVE_GC, /* long tp_flags; */
05240 
05241     NULL,                       /*  char *tp_doc;  Documentation string */
05242   /*** Assigned meaning in release 2.0 ***/
05243     /* call function for all accessible objects */
05244 #ifdef USE_PYRNA_STRUCT_REFERENCE
05245     (traverseproc) pyrna_struct_traverse, /* traverseproc tp_traverse; */
05246 
05247     /* delete references to contained objects */
05248     (inquiry)pyrna_struct_clear, /* inquiry tp_clear; */
05249 #else
05250     NULL,                       /* traverseproc tp_traverse; */
05251 
05252 /* delete references to contained objects */
05253     NULL,                       /* inquiry tp_clear; */
05254 #endif /* !USE_PYRNA_STRUCT_REFERENCE */
05255 
05256   /***  Assigned meaning in release 2.1 ***/
05257   /*** rich comparisons ***/
05258     (richcmpfunc)pyrna_struct_richcmp, /* richcmpfunc tp_richcompare; */
05259 
05260   /***  weak reference enabler ***/
05261 #ifdef USE_WEAKREFS
05262     offsetof(BPy_StructRNA, in_weakreflist), /* long tp_weaklistoffset; */
05263 #else
05264     0,
05265 #endif
05266   /*** Added in release 2.2 ***/
05267     /*   Iterators */
05268     NULL,                       /* getiterfunc tp_iter; */
05269     NULL,                       /* iternextfunc tp_iternext; */
05270 
05271   /*** Attribute descriptor and subclassing stuff ***/
05272     pyrna_struct_methods,       /* struct PyMethodDef *tp_methods; */
05273     NULL,                       /* struct PyMemberDef *tp_members; */
05274     pyrna_struct_getseters,     /* struct PyGetSetDef *tp_getset; */
05275     NULL,                       /* struct _typeobject *tp_base; */
05276     NULL,                       /* PyObject *tp_dict; */
05277     NULL,                       /* descrgetfunc tp_descr_get; */
05278     NULL,                       /* descrsetfunc tp_descr_set; */
05279     0,                          /* long tp_dictoffset; */
05280     NULL,                       /* initproc tp_init; */
05281     NULL,                       /* allocfunc tp_alloc; */
05282     pyrna_struct_new,           /* newfunc tp_new; */
05283     /*  Low-level free-memory routine */
05284     NULL,                       /* freefunc tp_free;  */
05285     /* For PyObject_IS_GC */
05286     NULL,                       /* inquiry tp_is_gc;  */
05287     NULL,                       /* PyObject *tp_bases; */
05288     /* method resolution order */
05289     NULL,                       /* PyObject *tp_mro;  */
05290     NULL,                       /* PyObject *tp_cache; */
05291     NULL,                       /* PyObject *tp_subclasses; */
05292     NULL,                       /* PyObject *tp_weaklist; */
05293     NULL
05294 };
05295 
05296 /*-----------------------BPy_PropertyRNA method def------------------------------*/
05297 PyTypeObject pyrna_prop_Type = {
05298     PyVarObject_HEAD_INIT(NULL, 0)
05299     "bpy_prop",                 /* tp_name */
05300     sizeof(BPy_PropertyRNA),    /* tp_basicsize */
05301     0,                          /* tp_itemsize */
05302     /* methods */
05303     (destructor) pyrna_prop_dealloc, /* tp_dealloc */
05304     NULL,                       /* printfunc tp_print; */
05305     NULL,                       /* getattrfunc tp_getattr; */
05306     NULL,                       /* setattrfunc tp_setattr; */
05307     NULL,                       /* tp_compare */ /* DEPRECATED in python 3.0! */
05308     (reprfunc) pyrna_prop_repr, /* tp_repr */
05309 
05310     /* Method suites for standard classes */
05311 
05312     NULL,                       /* PyNumberMethods *tp_as_number; */
05313     NULL,                       /* PySequenceMethods *tp_as_sequence; */
05314     NULL,                       /* PyMappingMethods *tp_as_mapping; */
05315 
05316     /* More standard operations (here for binary compatibility) */
05317 
05318     (hashfunc) pyrna_prop_hash, /* hashfunc tp_hash; */
05319     NULL,                       /* ternaryfunc tp_call; */
05320     (reprfunc) pyrna_prop_str,  /* reprfunc tp_str; */
05321 
05322     /* will only use these if this is a subtype of a py class */
05323     NULL,                       /* getattrofunc tp_getattro; */
05324     NULL,                       /* setattrofunc tp_setattro; */
05325 
05326     /* Functions to access object as input/output buffer */
05327     NULL,                       /* PyBufferProcs *tp_as_buffer; */
05328 
05329   /*** Flags to define presence of optional/expanded features ***/
05330     Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE,         /* long tp_flags; */
05331 
05332     NULL,                       /*  char *tp_doc;  Documentation string */
05333   /*** Assigned meaning in release 2.0 ***/
05334     /* call function for all accessible objects */
05335     NULL,                       /* traverseproc tp_traverse; */
05336 
05337     /* delete references to contained objects */
05338     NULL,                       /* inquiry tp_clear; */
05339 
05340   /***  Assigned meaning in release 2.1 ***/
05341   /*** rich comparisons ***/
05342     (richcmpfunc)pyrna_prop_richcmp,    /* richcmpfunc tp_richcompare; */
05343 
05344   /***  weak reference enabler ***/
05345 #ifdef USE_WEAKREFS
05346     offsetof(BPy_PropertyRNA, in_weakreflist),  /* long tp_weaklistoffset; */
05347 #else
05348     0,
05349 #endif
05350 
05351   /*** Added in release 2.2 ***/
05352     /*   Iterators */
05353     NULL,                       /* getiterfunc tp_iter; */
05354     NULL,                       /* iternextfunc tp_iternext; */
05355 
05356   /*** Attribute descriptor and subclassing stuff ***/
05357     pyrna_prop_methods,         /* struct PyMethodDef *tp_methods; */
05358     NULL,                       /* struct PyMemberDef *tp_members; */
05359     pyrna_prop_getseters,       /* struct PyGetSetDef *tp_getset; */
05360     NULL,                       /* struct _typeobject *tp_base; */
05361     NULL,                       /* PyObject *tp_dict; */
05362     NULL,                       /* descrgetfunc tp_descr_get; */
05363     NULL,                       /* descrsetfunc tp_descr_set; */
05364     0,                          /* long tp_dictoffset; */
05365     NULL,                       /* initproc tp_init; */
05366     NULL,                       /* allocfunc tp_alloc; */
05367     pyrna_prop_new,             /* newfunc tp_new; */
05368     /*  Low-level free-memory routine */
05369     NULL,                       /* freefunc tp_free;  */
05370     /* For PyObject_IS_GC */
05371     NULL,                       /* inquiry tp_is_gc;  */
05372     NULL,                       /* PyObject *tp_bases; */
05373     /* method resolution order */
05374     NULL,                       /* PyObject *tp_mro;  */
05375     NULL,                       /* PyObject *tp_cache; */
05376     NULL,                       /* PyObject *tp_subclasses; */
05377     NULL,                       /* PyObject *tp_weaklist; */
05378     NULL
05379 };
05380 
05381 PyTypeObject pyrna_prop_array_Type = {
05382     PyVarObject_HEAD_INIT(NULL, 0)
05383     "bpy_prop_array",       /* tp_name */
05384     sizeof(BPy_PropertyArrayRNA),           /* tp_basicsize */
05385     0,                          /* tp_itemsize */
05386     /* methods */
05387     (destructor)pyrna_prop_array_dealloc, /* tp_dealloc */
05388     NULL,                       /* printfunc tp_print; */
05389     NULL,                       /* getattrfunc tp_getattr; */
05390     NULL,                       /* setattrfunc tp_setattr; */
05391     NULL,                       /* tp_compare */ /* DEPRECATED in python 3.0! */
05392     NULL,/* subclassed */       /* tp_repr */
05393 
05394     /* Method suites for standard classes */
05395 
05396     &pyrna_prop_array_as_number,   /* PyNumberMethods *tp_as_number; */
05397     &pyrna_prop_array_as_sequence, /* PySequenceMethods *tp_as_sequence; */
05398     &pyrna_prop_array_as_mapping,  /* PyMappingMethods *tp_as_mapping; */
05399 
05400     /* More standard operations (here for binary compatibility) */
05401 
05402     NULL,                       /* hashfunc tp_hash; */
05403     NULL,                       /* ternaryfunc tp_call; */
05404     NULL,                       /* reprfunc tp_str; */
05405 
05406     /* will only use these if this is a subtype of a py class */
05407     (getattrofunc) pyrna_prop_array_getattro, /* getattrofunc tp_getattro; */
05408     NULL,                       /* setattrofunc tp_setattro; */
05409 
05410     /* Functions to access object as input/output buffer */
05411     NULL,                       /* PyBufferProcs *tp_as_buffer; */
05412 
05413   /*** Flags to define presence of optional/expanded features ***/
05414     Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE, /* long tp_flags; */
05415 
05416     NULL,                       /*  char *tp_doc;  Documentation string */
05417   /*** Assigned meaning in release 2.0 ***/
05418     /* call function for all accessible objects */
05419     NULL,                       /* traverseproc tp_traverse; */
05420 
05421     /* delete references to contained objects */
05422     NULL,                       /* inquiry tp_clear; */
05423 
05424   /***  Assigned meaning in release 2.1 ***/
05425   /*** rich comparisons ***/
05426     NULL, /* subclassed */ /* richcmpfunc tp_richcompare; */
05427 
05428   /***  weak reference enabler ***/
05429 #ifdef USE_WEAKREFS
05430     offsetof(BPy_PropertyArrayRNA, in_weakreflist), /* long tp_weaklistoffset; */
05431 #else
05432     0,
05433 #endif
05434   /*** Added in release 2.2 ***/
05435     /*   Iterators */
05436     (getiterfunc)pyrna_prop_array_iter, /* getiterfunc tp_iter; */
05437     NULL,                       /* iternextfunc tp_iternext; */
05438 
05439   /*** Attribute descriptor and subclassing stuff ***/
05440     pyrna_prop_array_methods,   /* struct PyMethodDef *tp_methods; */
05441     NULL,                       /* struct PyMemberDef *tp_members; */
05442     NULL /*pyrna_prop_getseters*/, /* struct PyGetSetDef *tp_getset; */
05443     &pyrna_prop_Type,           /* struct _typeobject *tp_base; */
05444     NULL,                       /* PyObject *tp_dict; */
05445     NULL,                       /* descrgetfunc tp_descr_get; */
05446     NULL,                       /* descrsetfunc tp_descr_set; */
05447     0,                          /* long tp_dictoffset; */
05448     NULL,                       /* initproc tp_init; */
05449     NULL,                       /* allocfunc tp_alloc; */
05450     NULL,                       /* newfunc tp_new; */
05451     /*  Low-level free-memory routine */
05452     NULL,                       /* freefunc tp_free;  */
05453     /* For PyObject_IS_GC */
05454     NULL,                       /* inquiry tp_is_gc;  */
05455     NULL,                       /* PyObject *tp_bases; */
05456     /* method resolution order */
05457     NULL,                       /* PyObject *tp_mro;  */
05458     NULL,                       /* PyObject *tp_cache; */
05459     NULL,                       /* PyObject *tp_subclasses; */
05460     NULL,                       /* PyObject *tp_weaklist; */
05461     NULL
05462 };
05463 
05464 PyTypeObject pyrna_prop_collection_Type = {
05465     PyVarObject_HEAD_INIT(NULL, 0)
05466     "bpy_prop_collection",      /* tp_name */
05467     sizeof(BPy_PropertyRNA),    /* tp_basicsize */
05468     0,                          /* tp_itemsize */
05469     /* methods */
05470     (destructor)pyrna_prop_dealloc, /* tp_dealloc */
05471     NULL,                       /* printfunc tp_print; */
05472     NULL,                       /* getattrfunc tp_getattr; */
05473     NULL,                       /* setattrfunc tp_setattr; */
05474     NULL,                       /* tp_compare */ /* DEPRECATED in python 3.0! */
05475     NULL, /* subclassed */      /* tp_repr */
05476 
05477     /* Method suites for standard classes */
05478 
05479     &pyrna_prop_collection_as_number,   /* PyNumberMethods *tp_as_number; */
05480     &pyrna_prop_collection_as_sequence, /* PySequenceMethods *tp_as_sequence; */
05481     &pyrna_prop_collection_as_mapping,  /* PyMappingMethods *tp_as_mapping; */
05482 
05483     /* More standard operations (here for binary compatibility) */
05484 
05485     NULL,                       /* hashfunc tp_hash; */
05486     NULL,                       /* ternaryfunc tp_call; */
05487     NULL,                       /* reprfunc tp_str; */
05488 
05489     /* will only use these if this is a subtype of a py class */
05490     (getattrofunc) pyrna_prop_collection_getattro, /* getattrofunc tp_getattro; */
05491     (setattrofunc) pyrna_prop_collection_setattro, /* setattrofunc tp_setattro; */
05492 
05493     /* Functions to access object as input/output buffer */
05494     NULL,                       /* PyBufferProcs *tp_as_buffer; */
05495 
05496   /*** Flags to define presence of optional/expanded features ***/
05497     Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE,         /* long tp_flags; */
05498 
05499     NULL,                       /*  char *tp_doc;  Documentation string */
05500   /*** Assigned meaning in release 2.0 ***/
05501     /* call function for all accessible objects */
05502     NULL,                       /* traverseproc tp_traverse; */
05503 
05504     /* delete references to contained objects */
05505     NULL,                       /* inquiry tp_clear; */
05506 
05507   /***  Assigned meaning in release 2.1 ***/
05508   /*** rich comparisons ***/
05509     NULL, /* subclassed */      /* richcmpfunc tp_richcompare; */
05510 
05511   /***  weak reference enabler ***/
05512 #ifdef USE_WEAKREFS
05513     offsetof(BPy_PropertyRNA, in_weakreflist), /* long tp_weaklistoffset; */
05514 #else
05515     0,
05516 #endif
05517 
05518   /*** Added in release 2.2 ***/
05519     /*   Iterators */
05520     (getiterfunc)pyrna_prop_collection_iter, /* getiterfunc tp_iter; */
05521     NULL,                       /* iternextfunc tp_iternext; */
05522 
05523   /*** Attribute descriptor and subclassing stuff ***/
05524     pyrna_prop_collection_methods, /* struct PyMethodDef *tp_methods; */
05525     NULL,                       /* struct PyMemberDef *tp_members; */
05526     NULL /*pyrna_prop_getseters*/, /* struct PyGetSetDef *tp_getset; */
05527     &pyrna_prop_Type,           /* struct _typeobject *tp_base; */
05528     NULL,                       /* PyObject *tp_dict; */
05529     NULL,                       /* descrgetfunc tp_descr_get; */
05530     NULL,                       /* descrsetfunc tp_descr_set; */
05531     0,                          /* long tp_dictoffset; */
05532     NULL,                       /* initproc tp_init; */
05533     NULL,                       /* allocfunc tp_alloc; */
05534     NULL,                       /* newfunc tp_new; */
05535     /*  Low-level free-memory routine */
05536     NULL,                       /* freefunc tp_free;  */
05537     /* For PyObject_IS_GC */
05538     NULL,                       /* inquiry tp_is_gc;  */
05539     NULL,                       /* PyObject *tp_bases; */
05540     /* method resolution order */
05541     NULL,                       /* PyObject *tp_mro;  */
05542     NULL,                       /* PyObject *tp_cache; */
05543     NULL,                       /* PyObject *tp_subclasses; */
05544     NULL,                       /* PyObject *tp_weaklist; */
05545     NULL
05546 };
05547 
05548 /* only for add/remove/move methods */
05549 static PyTypeObject pyrna_prop_collection_idprop_Type = {
05550     PyVarObject_HEAD_INIT(NULL, 0)
05551     "bpy_prop_collection_idprop", /* tp_name */
05552     sizeof(BPy_PropertyRNA),    /* tp_basicsize */
05553     0,                          /* tp_itemsize */
05554     /* methods */
05555     (destructor)pyrna_prop_dealloc, /* tp_dealloc */
05556     NULL,                       /* printfunc tp_print; */
05557     NULL,                       /* getattrfunc tp_getattr; */
05558     NULL,                       /* setattrfunc tp_setattr; */
05559     NULL,                       /* tp_compare */ /* DEPRECATED in python 3.0! */
05560     NULL, /* subclassed */      /* tp_repr */
05561 
05562     /* Method suites for standard classes */
05563 
05564     NULL,                       /* PyNumberMethods *tp_as_number; */
05565     NULL,                       /* PySequenceMethods *tp_as_sequence; */
05566     NULL,                       /* PyMappingMethods *tp_as_mapping; */
05567 
05568     /* More standard operations (here for binary compatibility) */
05569 
05570     NULL,                       /* hashfunc tp_hash; */
05571     NULL,                       /* ternaryfunc tp_call; */
05572     NULL,                       /* reprfunc tp_str; */
05573 
05574     /* will only use these if this is a subtype of a py class */
05575     NULL,                       /* getattrofunc tp_getattro; */
05576     NULL,                       /* setattrofunc tp_setattro; */
05577 
05578     /* Functions to access object as input/output buffer */
05579     NULL,                       /* PyBufferProcs *tp_as_buffer; */
05580 
05581   /*** Flags to define presence of optional/expanded features ***/
05582     Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE,         /* long tp_flags; */
05583 
05584     NULL,                       /*  char *tp_doc;  Documentation string */
05585   /*** Assigned meaning in release 2.0 ***/
05586     /* call function for all accessible objects */
05587     NULL,                       /* traverseproc tp_traverse; */
05588 
05589     /* delete references to contained objects */
05590     NULL,                       /* inquiry tp_clear; */
05591 
05592   /***  Assigned meaning in release 2.1 ***/
05593   /*** rich comparisons ***/
05594     NULL, /* subclassed */      /* richcmpfunc tp_richcompare; */
05595 
05596   /***  weak reference enabler ***/
05597 #ifdef USE_WEAKREFS
05598     offsetof(BPy_PropertyRNA, in_weakreflist), /* long tp_weaklistoffset; */
05599 #else
05600     0,
05601 #endif
05602 
05603   /*** Added in release 2.2 ***/
05604     /*   Iterators */
05605     NULL,                       /* getiterfunc tp_iter; */
05606     NULL,                       /* iternextfunc tp_iternext; */
05607 
05608   /*** Attribute descriptor and subclassing stuff ***/
05609     pyrna_prop_collection_idprop_methods, /* struct PyMethodDef *tp_methods; */
05610     NULL,                       /* struct PyMemberDef *tp_members; */
05611     NULL /*pyrna_prop_getseters*/, /* struct PyGetSetDef *tp_getset; */
05612     &pyrna_prop_collection_Type,/* struct _typeobject *tp_base; */
05613     NULL,                       /* PyObject *tp_dict; */
05614     NULL,                       /* descrgetfunc tp_descr_get; */
05615     NULL,                       /* descrsetfunc tp_descr_set; */
05616     0,                          /* long tp_dictoffset; */
05617     NULL,                       /* initproc tp_init; */
05618     NULL,                       /* allocfunc tp_alloc; */
05619     NULL,                       /* newfunc tp_new; */
05620     /*  Low-level free-memory routine */
05621     NULL,                       /* freefunc tp_free;  */
05622     /* For PyObject_IS_GC */
05623     NULL,                       /* inquiry tp_is_gc;  */
05624     NULL,                       /* PyObject *tp_bases; */
05625     /* method resolution order */
05626     NULL,                       /* PyObject *tp_mro;  */
05627     NULL,                       /* PyObject *tp_cache; */
05628     NULL,                       /* PyObject *tp_subclasses; */
05629     NULL,                       /* PyObject *tp_weaklist; */
05630     NULL
05631 };
05632 
05633 /*-----------------------BPy_PropertyRNA method def------------------------------*/
05634 PyTypeObject pyrna_func_Type = {
05635     PyVarObject_HEAD_INIT(NULL, 0)
05636     "bpy_func",                 /* tp_name */
05637     sizeof(BPy_FunctionRNA),    /* tp_basicsize */
05638     0,                          /* tp_itemsize */
05639     /* methods */
05640     NULL,                       /* tp_dealloc */
05641     NULL,                       /* printfunc tp_print; */
05642     NULL,                       /* getattrfunc tp_getattr; */
05643     NULL,                       /* setattrfunc tp_setattr; */
05644     NULL,                       /* tp_compare */ /* DEPRECATED in python 3.0! */
05645     (reprfunc) pyrna_func_repr, /* tp_repr */
05646 
05647     /* Method suites for standard classes */
05648 
05649     NULL,                       /* PyNumberMethods *tp_as_number; */
05650     NULL,                       /* PySequenceMethods *tp_as_sequence; */
05651     NULL,                       /* PyMappingMethods *tp_as_mapping; */
05652 
05653     /* More standard operations (here for binary compatibility) */
05654 
05655     NULL,                       /* hashfunc tp_hash; */
05656     (ternaryfunc)pyrna_func_call, /* ternaryfunc tp_call; */
05657     NULL,                       /* reprfunc tp_str; */
05658 
05659     /* will only use these if this is a subtype of a py class */
05660     NULL,                       /* getattrofunc tp_getattro; */
05661     NULL,                       /* setattrofunc tp_setattro; */
05662 
05663     /* Functions to access object as input/output buffer */
05664     NULL,                       /* PyBufferProcs *tp_as_buffer; */
05665 
05666   /*** Flags to define presence of optional/expanded features ***/
05667     Py_TPFLAGS_DEFAULT,         /* long tp_flags; */
05668 
05669     NULL,                       /*  char *tp_doc;  Documentation string */
05670   /*** Assigned meaning in release 2.0 ***/
05671     /* call function for all accessible objects */
05672     NULL,                       /* traverseproc tp_traverse; */
05673 
05674     /* delete references to contained objects */
05675     NULL,                       /* inquiry tp_clear; */
05676 
05677   /***  Assigned meaning in release 2.1 ***/
05678   /*** rich comparisons ***/
05679     NULL,                       /* richcmpfunc tp_richcompare; */
05680 
05681   /***  weak reference enabler ***/
05682 #ifdef USE_WEAKREFS
05683     offsetof(BPy_PropertyRNA, in_weakreflist),  /* long tp_weaklistoffset; */
05684 #else
05685     0,
05686 #endif
05687 
05688   /*** Added in release 2.2 ***/
05689     /*   Iterators */
05690     NULL,                       /* getiterfunc tp_iter; */
05691     NULL,                       /* iternextfunc tp_iternext; */
05692 
05693   /*** Attribute descriptor and subclassing stuff ***/
05694     NULL,                       /* struct PyMethodDef *tp_methods; */
05695     NULL,                       /* struct PyMemberDef *tp_members; */
05696     NULL,                       /* struct PyGetSetDef *tp_getset; */
05697     NULL,                       /* struct _typeobject *tp_base; */
05698     NULL,                       /* PyObject *tp_dict; */
05699     NULL,                       /* descrgetfunc tp_descr_get; */
05700     NULL,                       /* descrsetfunc tp_descr_set; */
05701     0,                          /* long tp_dictoffset; */
05702     NULL,                       /* initproc tp_init; */
05703     NULL,                       /* allocfunc tp_alloc; */
05704     NULL,                       /* newfunc tp_new; */
05705     /*  Low-level free-memory routine */
05706     NULL,                       /* freefunc tp_free;  */
05707     /* For PyObject_IS_GC */
05708     NULL,                       /* inquiry tp_is_gc;  */
05709     NULL,                       /* PyObject *tp_bases; */
05710     /* method resolution order */
05711     NULL,                       /* PyObject *tp_mro;  */
05712     NULL,                       /* PyObject *tp_cache; */
05713     NULL,                       /* PyObject *tp_subclasses; */
05714     NULL,                       /* PyObject *tp_weaklist; */
05715     NULL
05716 };
05717 
05718 #ifdef USE_PYRNA_ITER
05719 /* --- collection iterator: start --- */
05720 /* wrap rna collection iterator functions */
05721 /*
05722  * RNA_property_collection_begin(...)
05723  * RNA_property_collection_next(...)
05724  * RNA_property_collection_end(...)
05725  */
05726 
05727 static void pyrna_prop_collection_iter_dealloc(BPy_PropertyCollectionIterRNA *self);
05728 static PyObject *pyrna_prop_collection_iter_next(BPy_PropertyCollectionIterRNA *self);
05729 
05730 PyTypeObject pyrna_prop_collection_iter_Type = {
05731     PyVarObject_HEAD_INIT(NULL, 0)
05732     "bpy_prop_collection_iter", /* tp_name */
05733     sizeof(BPy_PropertyCollectionIterRNA), /* tp_basicsize */
05734     0,                          /* tp_itemsize */
05735     /* methods */
05736     (destructor)pyrna_prop_collection_iter_dealloc, /* tp_dealloc */
05737     NULL,                       /* printfunc tp_print; */
05738     NULL,                       /* getattrfunc tp_getattr; */
05739     NULL,                       /* setattrfunc tp_setattr; */
05740     NULL,                       /* tp_compare */ /* DEPRECATED in python 3.0! */
05741     NULL,/* subclassed */       /* tp_repr */
05742 
05743     /* Method suites for standard classes */
05744 
05745     NULL,    /* PyNumberMethods *tp_as_number; */
05746     NULL,                       /* PySequenceMethods *tp_as_sequence; */
05747     NULL,                       /* PyMappingMethods *tp_as_mapping; */
05748 
05749     /* More standard operations (here for binary compatibility) */
05750 
05751     NULL,                       /* hashfunc tp_hash; */
05752     NULL,                       /* ternaryfunc tp_call; */
05753     NULL,                       /* reprfunc tp_str; */
05754 
05755     /* will only use these if this is a subtype of a py class */
05756 #if defined(_MSC_VER) || defined(FREE_WINDOWS)
05757     NULL, /* defer assignment */
05758 #else
05759     PyObject_GenericGetAttr,    /* getattrofunc tp_getattro; */
05760 #endif
05761     NULL,                       /* setattrofunc tp_setattro; */
05762 
05763     /* Functions to access object as input/output buffer */
05764     NULL,                       /* PyBufferProcs *tp_as_buffer; */
05765 
05766   /*** Flags to define presence of optional/expanded features ***/
05767     Py_TPFLAGS_DEFAULT,         /* long tp_flags; */
05768 
05769     NULL,                       /*  char *tp_doc;  Documentation string */
05770   /*** Assigned meaning in release 2.0 ***/
05771     /* call function for all accessible objects */
05772     NULL,                       /* traverseproc tp_traverse; */
05773 
05774     /* delete references to contained objects */
05775     NULL,                       /* inquiry tp_clear; */
05776 
05777   /***  Assigned meaning in release 2.1 ***/
05778   /*** rich comparisons ***/
05779     NULL, /* subclassed */      /* richcmpfunc tp_richcompare; */
05780 
05781   /***  weak reference enabler ***/
05782 #ifdef USE_WEAKREFS
05783     offsetof(BPy_PropertyCollectionIterRNA, in_weakreflist), /* long tp_weaklistoffset; */
05784 #else
05785     0,
05786 #endif
05787   /*** Added in release 2.2 ***/
05788     /*   Iterators */
05789 #if defined(_MSC_VER) || defined(FREE_WINDOWS)
05790     NULL, /* defer assignment */
05791 #else
05792     PyObject_SelfIter,          /* getiterfunc tp_iter; */
05793 #endif
05794     (iternextfunc) pyrna_prop_collection_iter_next, /* iternextfunc tp_iternext; */
05795 
05796   /*** Attribute descriptor and subclassing stuff ***/
05797     NULL,                       /* struct PyMethodDef *tp_methods; */
05798     NULL,                       /* struct PyMemberDef *tp_members; */
05799     NULL,                       /* struct PyGetSetDef *tp_getset; */
05800     NULL,                       /* struct _typeobject *tp_base; */
05801     NULL,                       /* PyObject *tp_dict; */
05802     NULL,                       /* descrgetfunc tp_descr_get; */
05803     NULL,                       /* descrsetfunc tp_descr_set; */
05804     0,                          /* long tp_dictoffset; */
05805     NULL,                       /* initproc tp_init; */
05806     NULL,                       /* allocfunc tp_alloc; */
05807     NULL,                       /* newfunc tp_new; */
05808     /*  Low-level free-memory routine */
05809     NULL,                       /* freefunc tp_free;  */
05810     /* For PyObject_IS_GC */
05811     NULL,                       /* inquiry tp_is_gc;  */
05812     NULL,                       /* PyObject *tp_bases; */
05813     /* method resolution order */
05814     NULL,                       /* PyObject *tp_mro;  */
05815     NULL,                       /* PyObject *tp_cache; */
05816     NULL,                       /* PyObject *tp_subclasses; */
05817     NULL,                       /* PyObject *tp_weaklist; */
05818     NULL
05819 };
05820 
05821 PyObject *pyrna_prop_collection_iter_CreatePyObject(PointerRNA *ptr, PropertyRNA *prop)
05822 {
05823     BPy_PropertyCollectionIterRNA *self = PyObject_New(BPy_PropertyCollectionIterRNA, &pyrna_prop_collection_iter_Type);
05824 
05825 #ifdef USE_WEAKREFS
05826     self->in_weakreflist = NULL;
05827 #endif
05828 
05829     RNA_property_collection_begin(ptr, prop, &self->iter);
05830 
05831     return (PyObject *)self;
05832 }
05833 
05834 static PyObject *pyrna_prop_collection_iter(BPy_PropertyRNA *self)
05835 {
05836     return pyrna_prop_collection_iter_CreatePyObject(&self->ptr, self->prop);
05837 }
05838 
05839 static PyObject *pyrna_prop_collection_iter_next(BPy_PropertyCollectionIterRNA *self)
05840 {
05841     if (self->iter.valid == FALSE) {
05842         PyErr_SetString(PyExc_StopIteration, "pyrna_prop_collection_iter stop");
05843         return NULL;
05844     }
05845     else {
05846         BPy_StructRNA *pyrna = (BPy_StructRNA *)pyrna_struct_CreatePyObject(&self->iter.ptr);
05847 
05848 #ifdef USE_PYRNA_STRUCT_REFERENCE
05849         if (pyrna) { /* unlikely but may fail */
05850             if ((PyObject *)pyrna != Py_None) {
05851                 /* hold a reference to the iterator since it may have
05852                  * allocated memory 'pyrna' needs. eg: introspecting dynamic enum's  */
05853                 /* TODO, we could have an api call to know if this is needed since most collections don't */
05854                 pyrna_struct_reference_set(pyrna, (PyObject *)self);
05855             }
05856         }
05857 #endif /* !USE_PYRNA_STRUCT_REFERENCE */
05858 
05859         RNA_property_collection_next(&self->iter);
05860 
05861         return (PyObject *)pyrna;
05862     }
05863 }
05864 
05865 
05866 static void pyrna_prop_collection_iter_dealloc(BPy_PropertyCollectionIterRNA *self)
05867 {
05868 #ifdef USE_WEAKREFS
05869     if (self->in_weakreflist != NULL) {
05870         PyObject_ClearWeakRefs((PyObject *)self);
05871     }
05872 #endif
05873 
05874     RNA_property_collection_end(&self->iter);
05875 
05876     PyObject_DEL(self);
05877 }
05878 
05879 /* --- collection iterator: end --- */
05880 #endif /* !USE_PYRNA_ITER */
05881 
05882 
05883 static void pyrna_subtype_set_rna(PyObject *newclass, StructRNA *srna)
05884 {
05885     PointerRNA ptr;
05886     PyObject *item;
05887 
05888     Py_INCREF(newclass);
05889 
05890     if (RNA_struct_py_type_get(srna))
05891         PyC_ObSpit("RNA WAS SET - ", RNA_struct_py_type_get(srna));
05892 
05893     Py_XDECREF(((PyObject *)RNA_struct_py_type_get(srna)));
05894 
05895     RNA_struct_py_type_set(srna, (void *)newclass); /* Store for later use */
05896 
05897     /* Not 100% needed but useful,
05898      * having an instance within a type looks wrong however this instance IS an rna type */
05899 
05900     /* python deals with the circular ref */
05901     RNA_pointer_create(NULL, &RNA_Struct, srna, &ptr);
05902     item = pyrna_struct_CreatePyObject(&ptr);
05903 
05904     /* note, must set the class not the __dict__ else the internal slots are not updated correctly */
05905     PyObject_SetAttr(newclass, bpy_intern_str_bl_rna, item);
05906     Py_DECREF(item);
05907 
05908     /* done with rna instance */
05909 }
05910 
05911 static PyObject* pyrna_srna_Subtype(StructRNA *srna);
05912 
05913 /* return a borrowed reference */
05914 static PyObject* pyrna_srna_PyBase(StructRNA *srna) //, PyObject *bpy_types_dict)
05915 {
05916     /* Assume RNA_struct_py_type_get(srna) was already checked */
05917     StructRNA *base;
05918 
05919     PyObject *py_base = NULL;
05920 
05921     /* get the base type */
05922     base = RNA_struct_base(srna);
05923 
05924     if (base && base != srna) {
05925         /*/printf("debug subtype %s %p\n", RNA_struct_identifier(srna), srna); */
05926         py_base = pyrna_srna_Subtype(base); //, bpy_types_dict);
05927         Py_DECREF(py_base); /* srna owns, this is only to pass as an arg */
05928     }
05929 
05930     if (py_base == NULL) {
05931         py_base = (PyObject *)&pyrna_struct_Type;
05932     }
05933 
05934     return py_base;
05935 }
05936 
05937 /* check if we have a native python subclass, use it when it exists
05938  * return a borrowed reference */
05939 static PyObject *bpy_types_dict = NULL;
05940 
05941 static PyObject* pyrna_srna_ExternalType(StructRNA *srna)
05942 {
05943     const char *idname = RNA_struct_identifier(srna);
05944     PyObject *newclass;
05945 
05946     if (bpy_types_dict == NULL) {
05947         PyObject *bpy_types = PyImport_ImportModuleLevel((char *)"bpy_types", NULL, NULL, NULL, 0);
05948 
05949         if (bpy_types == NULL) {
05950             PyErr_Print();
05951             PyErr_Clear();
05952             fprintf(stderr, "%s: failed to find 'bpy_types' module\n", __func__);
05953             return NULL;
05954         }
05955         bpy_types_dict = PyModule_GetDict(bpy_types); // borrow
05956         Py_DECREF(bpy_types); // fairly safe to assume the dict is kept
05957     }
05958 
05959     newclass = PyDict_GetItemString(bpy_types_dict, idname);
05960 
05961     /* sanity check, could skip this unless in debug mode */
05962     if (newclass) {
05963         PyObject *base_compare = pyrna_srna_PyBase(srna);
05964         //PyObject *slots = PyObject_GetAttrString(newclass, "__slots__"); // cant do this because it gets superclasses values!
05965         //PyObject *bases = PyObject_GetAttrString(newclass, "__bases__"); // can do this but faster not to.
05966         PyObject *tp_bases = ((PyTypeObject *)newclass)->tp_bases;
05967         PyObject *tp_slots = PyDict_GetItem(((PyTypeObject *)newclass)->tp_dict, bpy_intern_str___slots__);
05968 
05969         if (tp_slots == NULL) {
05970             fprintf(stderr, "%s: expected class '%s' to have __slots__ defined\n\nSee bpy_types.py\n", __func__, idname);
05971             newclass = NULL;
05972         }
05973         else if (PyTuple_GET_SIZE(tp_bases)) {
05974             PyObject *base = PyTuple_GET_ITEM(tp_bases, 0);
05975 
05976             if (base_compare != base) {
05977                 fprintf(stderr, "%s: incorrect subclassing of SRNA '%s'\nSee bpy_types.py\n", __func__, idname);
05978                 PyC_ObSpit("Expected! ", base_compare);
05979                 newclass = NULL;
05980             }
05981             else {
05982                 if (G.f & G_DEBUG)
05983                     fprintf(stderr, "SRNA Subclassed: '%s'\n", idname);
05984             }
05985         }
05986     }
05987 
05988     return newclass;
05989 }
05990 
05991 static PyObject* pyrna_srna_Subtype(StructRNA *srna)
05992 {
05993     PyObject *newclass = NULL;
05994 
05995         /* stupid/simple case */
05996     if (srna == NULL) {
05997         newclass = NULL; /* Nothing to do */
05998     }   /* the class may have already been declared & allocated */
05999     else if ((newclass = RNA_struct_py_type_get(srna))) {
06000         Py_INCREF(newclass);
06001     }   /* check if bpy_types.py module has the class defined in it */
06002     else if ((newclass = pyrna_srna_ExternalType(srna))) {
06003         pyrna_subtype_set_rna(newclass, srna);
06004         Py_INCREF(newclass);
06005     }   /* create a new class instance with the C api
06006          * mainly for the purposing of matching the C/rna type hierarchy */
06007     else {
06008         /* subclass equivalents
06009         - class myClass(myBase):
06010             some = 'value' # or ...
06011         - myClass = type(name='myClass', bases=(myBase,), dict={'__module__':'bpy.types'})
06012         */
06013 
06014         /* Assume RNA_struct_py_type_get(srna) was already checked */
06015         PyObject *py_base = pyrna_srna_PyBase(srna);
06016         PyObject *metaclass;
06017         const char *idname = RNA_struct_identifier(srna);
06018 
06019         /* remove __doc__ for now */
06020         // const char *descr = RNA_struct_ui_description(srna);
06021         // if (!descr) descr = "(no docs)";
06022         // "__doc__", descr
06023 
06024         if ( RNA_struct_idprops_check(srna) &&
06025              !PyObject_IsSubclass(py_base, (PyObject *)&pyrna_struct_meta_idprop_Type))
06026         {
06027             metaclass = (PyObject *)&pyrna_struct_meta_idprop_Type;
06028         }
06029         else {
06030             metaclass = (PyObject *)&PyType_Type;
06031         }
06032 
06033         /* always use O not N when calling, N causes refcount errors */
06034         newclass = PyObject_CallFunction(metaclass, (char *)"s(O){sss()}",
06035                                          idname, py_base, "__module__","bpy.types", "__slots__");
06036 
06037         /* newclass will now have 2 ref's, ???, probably 1 is internal since decrefing here segfaults */
06038 
06039         /* PyC_ObSpit("new class ref", newclass); */
06040 
06041         if (newclass) {
06042             /* srna owns one, and the other is owned by the caller */
06043             pyrna_subtype_set_rna(newclass, srna);
06044 
06045             // XXX, adding this back segfaults blender on load.
06046             // Py_DECREF(newclass); /* let srna own */
06047         }
06048         else {
06049             /* this should not happen */
06050             printf("%s: error registering '%s'\n", __func__, idname);
06051             PyErr_Print();
06052             PyErr_Clear();
06053         }
06054     }
06055 
06056     return newclass;
06057 }
06058 
06059 /* use for subtyping so we know which srna is used for a PointerRNA */
06060 static StructRNA *srna_from_ptr(PointerRNA *ptr)
06061 {
06062     if (ptr->type == &RNA_Struct) {
06063         return ptr->data;
06064     }
06065     else {
06066         return ptr->type;
06067     }
06068 }
06069 
06070 /* always returns a new ref, be sure to decref when done */
06071 static PyObject* pyrna_struct_Subtype(PointerRNA *ptr)
06072 {
06073     return pyrna_srna_Subtype(srna_from_ptr(ptr));
06074 }
06075 
06076 /*-----------------------CreatePyObject---------------------------------*/
06077 PyObject *pyrna_struct_CreatePyObject(PointerRNA *ptr)
06078 {
06079     BPy_StructRNA *pyrna = NULL;
06080 
06081     /* note: don't rely on this to return None since NULL data with a valid type can often crash */
06082     if (ptr->data == NULL && ptr->type == NULL) { /* Operator RNA has NULL data */
06083         Py_RETURN_NONE;
06084     }
06085     else {
06086         PyTypeObject *tp = (PyTypeObject *)pyrna_struct_Subtype(ptr);
06087 
06088         if (tp) {
06089             pyrna = (BPy_StructRNA *) tp->tp_alloc(tp, 0);
06090             Py_DECREF(tp); /* srna owns, cant hold a ref */
06091         }
06092         else {
06093             fprintf(stderr, "%s: could not make type\n", __func__);
06094             pyrna = (BPy_StructRNA *) PyObject_GC_New(BPy_StructRNA, &pyrna_struct_Type);
06095 #ifdef USE_WEAKREFS
06096             pyrna->in_weakreflist = NULL;
06097 #endif
06098         }
06099     }
06100 
06101     if (pyrna == NULL) {
06102         PyErr_SetString(PyExc_MemoryError, "couldn't create bpy_struct object");
06103         return NULL;
06104     }
06105 
06106     pyrna->ptr = *ptr;
06107 #ifdef PYRNA_FREE_SUPPORT
06108     pyrna->freeptr = FALSE;
06109 #endif
06110 
06111 #ifdef USE_PYRNA_STRUCT_REFERENCE
06112     pyrna->reference = NULL;
06113 #endif
06114 
06115     // PyC_ObSpit("NewStructRNA: ", (PyObject *)pyrna);
06116 
06117 #ifdef USE_PYRNA_INVALIDATE_WEAKREF
06118     if (ptr->id.data) {
06119         id_weakref_pool_add(ptr->id.data, (BPy_DummyPointerRNA *)pyrna);
06120     }
06121 #endif
06122     return (PyObject *)pyrna;
06123 }
06124 
06125 PyObject *pyrna_prop_CreatePyObject(PointerRNA *ptr, PropertyRNA *prop)
06126 {
06127     BPy_PropertyRNA *pyrna;
06128 
06129     if (RNA_property_array_check(prop) == 0) {
06130         PyTypeObject *type;
06131 
06132         if (RNA_property_type(prop) != PROP_COLLECTION) {
06133             type = &pyrna_prop_Type;
06134         }
06135         else {
06136             if ((RNA_property_flag(prop) & PROP_IDPROPERTY) == 0) {
06137                 type = &pyrna_prop_collection_Type;
06138             }
06139             else {
06140                 type = &pyrna_prop_collection_idprop_Type;
06141             }
06142         }
06143 
06144         pyrna = (BPy_PropertyRNA *) PyObject_NEW(BPy_PropertyRNA, type);
06145 #ifdef USE_WEAKREFS
06146         pyrna->in_weakreflist = NULL;
06147 #endif
06148     }
06149     else {
06150         pyrna = (BPy_PropertyRNA *) PyObject_NEW(BPy_PropertyArrayRNA, &pyrna_prop_array_Type);
06151         ((BPy_PropertyArrayRNA *)pyrna)->arraydim = 0;
06152         ((BPy_PropertyArrayRNA *)pyrna)->arrayoffset = 0;
06153 #ifdef USE_WEAKREFS
06154         ((BPy_PropertyArrayRNA *)pyrna)->in_weakreflist = NULL;
06155 #endif
06156     }
06157 
06158     if (pyrna == NULL) {
06159         PyErr_SetString(PyExc_MemoryError, "couldn't create BPy_rna object");
06160         return NULL;
06161     }
06162 
06163     pyrna->ptr = *ptr;
06164     pyrna->prop = prop;
06165 
06166 #ifdef USE_PYRNA_INVALIDATE_WEAKREF
06167     if (ptr->id.data) {
06168         id_weakref_pool_add(ptr->id.data, (BPy_DummyPointerRNA *)pyrna);
06169     }
06170 #endif
06171 
06172     return (PyObject *)pyrna;
06173 }
06174 
06175 void BPY_rna_init(void)
06176 {
06177 #ifdef USE_MATHUTILS // register mathutils callbacks, ok to run more then once.
06178     mathutils_rna_array_cb_index = Mathutils_RegisterCallback(&mathutils_rna_array_cb);
06179     mathutils_rna_matrix_cb_index = Mathutils_RegisterCallback(&mathutils_rna_matrix_cb);
06180 #endif
06181 
06182     /* for some reason MSVC complains of these */
06183 #if defined(_MSC_VER) || defined(FREE_WINDOWS)
06184     pyrna_struct_meta_idprop_Type.tp_base = &PyType_Type;
06185 
06186     pyrna_prop_collection_iter_Type.tp_iter = PyObject_SelfIter;
06187     pyrna_prop_collection_iter_Type.tp_getattro = PyObject_GenericGetAttr;
06188 #endif
06189 
06190     /* metaclass */
06191     if (PyType_Ready(&pyrna_struct_meta_idprop_Type) < 0)
06192         return;
06193 
06194     if (PyType_Ready(&pyrna_struct_Type) < 0)
06195         return;
06196 
06197     if (PyType_Ready(&pyrna_prop_Type) < 0)
06198         return;
06199 
06200     if (PyType_Ready(&pyrna_prop_array_Type) < 0)
06201         return;
06202 
06203     if (PyType_Ready(&pyrna_prop_collection_Type) < 0)
06204         return;
06205 
06206     if (PyType_Ready(&pyrna_prop_collection_idprop_Type) < 0)
06207         return;
06208 
06209     if (PyType_Ready(&pyrna_func_Type) < 0)
06210         return;
06211 
06212 #ifdef USE_PYRNA_ITER
06213     if (PyType_Ready(&pyrna_prop_collection_iter_Type) < 0)
06214         return;
06215 #endif
06216 }
06217 
06218 /* bpy.data from python */
06219 static PointerRNA *rna_module_ptr = NULL;
06220 PyObject *BPY_rna_module(void)
06221 {
06222     BPy_StructRNA *pyrna;
06223     PointerRNA ptr;
06224 
06225     /* for now, return the base RNA type rather than a real module */
06226     RNA_main_pointer_create(G.main, &ptr);
06227     pyrna = (BPy_StructRNA *)pyrna_struct_CreatePyObject(&ptr);
06228 
06229     rna_module_ptr = &pyrna->ptr;
06230     return (PyObject *)pyrna;
06231 }
06232 
06233 void BPY_update_rna_module(void)
06234 {
06235 #if 0
06236     RNA_main_pointer_create(G.main, rna_module_ptr);
06237 #else
06238     rna_module_ptr->data = G.main; /* just set data is enough */
06239 #endif
06240 }
06241 
06242 #if 0
06243 /* This is a way we can access docstrings for RNA types
06244  * without having the datatypes in blender */
06245 PyObject *BPY_rna_doc(void)
06246 {
06247     PointerRNA ptr;
06248 
06249     /* for now, return the base RNA type rather than a real module */
06250     RNA_blender_rna_pointer_create(&ptr);
06251 
06252     return pyrna_struct_CreatePyObject(&ptr);
06253 }
06254 #endif
06255 
06256 
06257 /* pyrna_basetype_* - BPy_BaseTypeRNA is just a BPy_PropertyRNA struct with a different type
06258  * the self->ptr and self->prop are always set to the "structs" collection */
06259 //---------------getattr--------------------------------------------
06260 static PyObject *pyrna_basetype_getattro(BPy_BaseTypeRNA *self, PyObject *pyname)
06261 {
06262     PointerRNA newptr;
06263     PyObject *ret;
06264     const char *name = _PyUnicode_AsString(pyname);
06265 
06266     if (name == NULL) {
06267         PyErr_SetString(PyExc_AttributeError, "bpy.types: __getattr__ must be a string");
06268         ret = NULL;
06269     }
06270     else if (RNA_property_collection_lookup_string(&self->ptr, self->prop, name, &newptr)) {
06271         ret = pyrna_struct_Subtype(&newptr);
06272         if (ret == NULL) {
06273             PyErr_Format(PyExc_RuntimeError,
06274                          "bpy.types.%.200s subtype could not be generated, this is a bug!",
06275                          _PyUnicode_AsString(pyname));
06276         }
06277     }
06278     else {
06279 #if 0
06280         PyErr_Format(PyExc_AttributeError,
06281                      "bpy.types.%.200s RNA_Struct does not exist",
06282                      _PyUnicode_AsString(pyname));
06283         return NULL;
06284 #endif
06285         /* The error raised here will be displayed */
06286         ret = PyObject_GenericGetAttr((PyObject *)self, pyname);
06287     }
06288 
06289     return ret;
06290 }
06291 
06292 static PyObject *pyrna_basetype_dir(BPy_BaseTypeRNA *self);
06293 static PyObject *pyrna_register_class(PyObject *self, PyObject *py_class);
06294 static PyObject *pyrna_unregister_class(PyObject *self, PyObject *py_class);
06295 
06296 static struct PyMethodDef pyrna_basetype_methods[] = {
06297     {"__dir__", (PyCFunction)pyrna_basetype_dir, METH_NOARGS, ""},
06298     {NULL, NULL, 0, NULL}
06299 };
06300 
06301 static PyObject *pyrna_basetype_dir(BPy_BaseTypeRNA *self)
06302 {
06303     PyObject *list;
06304 #if 0
06305     PyObject *name;
06306     PyMethodDef *meth;
06307 #endif
06308 
06309     list = pyrna_prop_collection_keys(self); /* like calling structs.keys(), avoids looping here */
06310 
06311 #if 0 /* for now only contains __dir__ */
06312     for (meth = pyrna_basetype_methods; meth->ml_name; meth++) {
06313         name = PyUnicode_FromString(meth->ml_name);
06314         PyList_Append(list, name);
06315         Py_DECREF(name);
06316     }
06317 #endif
06318     return list;
06319 }
06320 
06321 static PyTypeObject pyrna_basetype_Type = BLANK_PYTHON_TYPE;
06322 
06323 PyObject *BPY_rna_types(void)
06324 {
06325     BPy_BaseTypeRNA *self;
06326 
06327     if ((pyrna_basetype_Type.tp_flags & Py_TPFLAGS_READY) == 0) {
06328         pyrna_basetype_Type.tp_name = "RNA_Types";
06329         pyrna_basetype_Type.tp_basicsize = sizeof(BPy_BaseTypeRNA);
06330         pyrna_basetype_Type.tp_getattro = (getattrofunc) pyrna_basetype_getattro;
06331         pyrna_basetype_Type.tp_flags = Py_TPFLAGS_DEFAULT;
06332         pyrna_basetype_Type.tp_methods = pyrna_basetype_methods;
06333 
06334         if (PyType_Ready(&pyrna_basetype_Type) < 0)
06335             return NULL;
06336     }
06337 
06338     self = (BPy_BaseTypeRNA *)PyObject_NEW(BPy_BaseTypeRNA, &pyrna_basetype_Type);
06339 
06340     /* avoid doing this lookup for every getattr */
06341     RNA_blender_rna_pointer_create(&self->ptr);
06342     self->prop = RNA_struct_find_property(&self->ptr, "structs");
06343 #ifdef USE_WEAKREFS
06344     self->in_weakreflist = NULL;
06345 #endif
06346     return (PyObject *)self;
06347 }
06348 
06349 StructRNA *pyrna_struct_as_srna(PyObject *self, int parent, const char *error_prefix)
06350 {
06351     BPy_StructRNA *py_srna = NULL;
06352     StructRNA *srna;
06353 
06354     /* ack, PyObject_GetAttrString wont look up this types tp_dict first :/ */
06355     if (PyType_Check(self)) {
06356         py_srna = (BPy_StructRNA *)PyDict_GetItem(((PyTypeObject *)self)->tp_dict, bpy_intern_str_bl_rna);
06357         Py_XINCREF(py_srna);
06358     }
06359 
06360     if (parent) {
06361         /* be very careful with this since it will return a parent classes srna.
06362          * modifying this will do confusing stuff! */
06363         if (py_srna == NULL)
06364             py_srna = (BPy_StructRNA *)PyObject_GetAttr(self, bpy_intern_str_bl_rna);
06365     }
06366 
06367     if (py_srna == NULL) {
06368         PyErr_Format(PyExc_RuntimeError,
06369                      "%.200s, missing bl_rna attribute from '%.200s' instance (may not be registered)",
06370                      error_prefix, Py_TYPE(self)->tp_name);
06371         return NULL;
06372     }
06373 
06374     if (!BPy_StructRNA_Check(py_srna)) {
06375         PyErr_Format(PyExc_TypeError,
06376                      "%.200s, bl_rna attribute wrong type '%.200s' on '%.200s'' instance",
06377                      error_prefix, Py_TYPE(py_srna)->tp_name,
06378                      Py_TYPE(self)->tp_name);
06379         Py_DECREF(py_srna);
06380         return NULL;
06381     }
06382 
06383     if (py_srna->ptr.type != &RNA_Struct) {
06384         PyErr_Format(PyExc_TypeError,
06385                      "%.200s, bl_rna attribute not a RNA_Struct, on '%.200s'' instance",
06386                      error_prefix, Py_TYPE(self)->tp_name);
06387         Py_DECREF(py_srna);
06388         return NULL;
06389     }
06390 
06391     srna = py_srna->ptr.data;
06392     Py_DECREF(py_srna);
06393 
06394     return srna;
06395 }
06396 
06397 /* Orphan functions, not sure where they should go */
06398 /* get the srna for methods attached to types */
06399 /*
06400  * Caller needs to raise error.*/
06401 StructRNA *srna_from_self(PyObject *self, const char *error_prefix)
06402 {
06403 
06404     if (self == NULL) {
06405         return NULL;
06406     }
06407     else if (PyCapsule_CheckExact(self)) {
06408         return PyCapsule_GetPointer(self, NULL);
06409     }
06410     else if (PyType_Check(self) == 0) {
06411         return NULL;
06412     }
06413     else {
06414         /* These cases above not errors, they just mean the type was not compatible
06415          * After this any errors will be raised in the script */
06416 
06417         PyObject *error_type, *error_value, *error_traceback;
06418         StructRNA *srna;
06419 
06420         PyErr_Fetch(&error_type, &error_value, &error_traceback);
06421         PyErr_Clear();
06422 
06423         srna = pyrna_struct_as_srna(self, 0, error_prefix);
06424 
06425         if (!PyErr_Occurred()) {
06426             PyErr_Restore(error_type, error_value, error_traceback);
06427         }
06428 
06429         return srna;
06430     }
06431 }
06432 
06433 static int deferred_register_prop(StructRNA *srna, PyObject *key, PyObject *item)
06434 {
06435     /* We only care about results from C which
06436      * are for sure types, save some time with error */
06437     if (pyrna_is_deferred_prop(item)) {
06438 
06439         PyObject *py_func, *py_kw, *py_srna_cobject, *py_ret;
06440 
06441         if (PyArg_ParseTuple(item, "OO!", &py_func, &PyDict_Type, &py_kw)) {
06442             PyObject *args_fake;
06443 
06444             if (*_PyUnicode_AsString(key) == '_') {
06445                 PyErr_Format(PyExc_ValueError,
06446                              "bpy_struct \"%.200s\" registration error: "
06447                              "%.200s could not register because the property starts with an '_'\n",
06448                              RNA_struct_identifier(srna), _PyUnicode_AsString(key));
06449                 return -1;
06450             }
06451             py_srna_cobject = PyCapsule_New(srna, NULL, NULL);
06452 
06453             /* not 100% nice :/, modifies the dict passed, should be ok */
06454             PyDict_SetItem(py_kw, bpy_intern_str_attr, key);
06455 
06456             args_fake = PyTuple_New(1);
06457             PyTuple_SET_ITEM(args_fake, 0, py_srna_cobject);
06458 
06459             py_ret = PyObject_Call(py_func, args_fake, py_kw);
06460 
06461             Py_DECREF(args_fake); /* free's py_srna_cobject too */
06462 
06463             if (py_ret) {
06464                 Py_DECREF(py_ret);
06465             }
06466             else {
06467                 PyErr_Print();
06468                 PyErr_Clear();
06469 
06470                 // PyC_LineSpit();
06471                 PyErr_Format(PyExc_ValueError,
06472                              "bpy_struct \"%.200s\" registration error: "
06473                              "%.200s could not register\n",
06474                              RNA_struct_identifier(srna), _PyUnicode_AsString(key));
06475                 return -1;
06476             }
06477         }
06478         else {
06479             /* Since this is a class dict, ignore args that can't be passed */
06480 
06481             /* for testing only */
06482             /* PyC_ObSpit("Why doesn't this work??", item);
06483             PyErr_Print(); */
06484             PyErr_Clear();
06485         }
06486     }
06487 
06488     return 0;
06489 }
06490 
06491 static int pyrna_deferred_register_props(StructRNA *srna, PyObject *class_dict)
06492 {
06493     PyObject *item, *key;
06494     PyObject *order;
06495     Py_ssize_t pos = 0;
06496     int ret = 0;
06497 
06498     /* in both cases PyDict_CheckExact(class_dict) will be true even
06499      * though Operators have a metaclass dict namespace */
06500 
06501     if ((order = PyDict_GetItem(class_dict, bpy_intern_str_order)) && PyList_CheckExact(order)) {
06502         for (pos = 0; pos < PyList_GET_SIZE(order); pos++) {
06503             key = PyList_GET_ITEM(order, pos);
06504             /* however unlikely its possible
06505              * fails in py 3.3 beta with __qualname__ */
06506             if ((item = PyDict_GetItem(class_dict, key))) {
06507                 ret = deferred_register_prop(srna, key, item);
06508                 if (ret != 0) {
06509                     break;
06510                 }
06511             }
06512         }
06513     }
06514     else {
06515         while (PyDict_Next(class_dict, &pos, &key, &item)) {
06516             ret = deferred_register_prop(srna, key, item);
06517 
06518             if (ret != 0)
06519                 break;
06520         }
06521     }
06522 
06523     return ret;
06524 }
06525 
06526 static int pyrna_deferred_register_class_recursive(StructRNA *srna, PyTypeObject *py_class)
06527 {
06528     const int len = PyTuple_GET_SIZE(py_class->tp_bases);
06529     int i, ret;
06530 
06531     /* first scan base classes for registerable properties */
06532     for (i = 0; i < len; i++) {
06533         PyTypeObject *py_superclass = (PyTypeObject *)PyTuple_GET_ITEM(py_class->tp_bases, i);
06534 
06535         /* the rules for using these base classes are not clear,
06536          * 'object' is of course not worth looking into and
06537          * existing subclasses of RNA would cause a lot more dictionary
06538          * looping then is needed (SomeOperator would scan Operator.__dict__)
06539          * which is harmless but not at all useful.
06540          *
06541          * So only scan base classes which are not subclasses if blender types.
06542          * This best fits having 'mix-in' classes for operators and render engines.
06543          * */
06544         if (py_superclass != &PyBaseObject_Type &&
06545             !PyObject_IsSubclass((PyObject *)py_superclass, (PyObject *)&pyrna_struct_Type)
06546         ) {
06547             ret = pyrna_deferred_register_class_recursive(srna, py_superclass);
06548 
06549             if (ret != 0) {
06550                 return ret;
06551             }
06552         }
06553     }
06554 
06555     /* not register out own properties */
06556     return pyrna_deferred_register_props(srna, py_class->tp_dict); /* getattr(..., "__dict__") returns a proxy */
06557 }
06558 
06559 int pyrna_deferred_register_class(StructRNA *srna, PyObject *py_class)
06560 {
06561     /* Panels and Menus dont need this
06562      * save some time and skip the checks here */
06563     if (!RNA_struct_idprops_register_check(srna))
06564         return 0;
06565 
06566     return pyrna_deferred_register_class_recursive(srna, (PyTypeObject *)py_class);
06567 }
06568 
06569 /*-------------------- Type Registration ------------------------*/
06570 
06571 static int rna_function_arg_count(FunctionRNA *func)
06572 {
06573     const ListBase *lb = RNA_function_defined_parameters(func);
06574     PropertyRNA *parm;
06575     Link *link;
06576     int count = (RNA_function_flag(func) & FUNC_NO_SELF) ? 0 : 1;
06577 
06578     for (link = lb->first; link; link = link->next) {
06579         parm = (PropertyRNA *)link;
06580         if (!(RNA_property_flag(parm) & PROP_OUTPUT))
06581             count++;
06582     }
06583 
06584     return count;
06585 }
06586 
06587 static int bpy_class_validate(PointerRNA *dummyptr, void *py_data, int *have_function)
06588 {
06589     const ListBase *lb;
06590     Link *link;
06591     FunctionRNA *func;
06592     PropertyRNA *prop;
06593     StructRNA *srna = dummyptr->type;
06594     const char *class_type = RNA_struct_identifier(srna);
06595     PyObject *py_class = (PyObject *)py_data;
06596     PyObject *base_class = RNA_struct_py_type_get(srna);
06597     PyObject *item;
06598     int i, flag, arg_count, func_arg_count;
06599     const char *py_class_name = ((PyTypeObject *)py_class)->tp_name; // __name__
06600 
06601 
06602     if (base_class) {
06603         if (!PyObject_IsSubclass(py_class, base_class)) {
06604             PyErr_Format(PyExc_TypeError,
06605                          "expected %.200s subclass of class \"%.200s\"",
06606                          class_type, py_class_name);
06607             return -1;
06608         }
06609     }
06610 
06611     /* verify callback functions */
06612     lb = RNA_struct_type_functions(srna);
06613     i = 0;
06614     for (link = lb->first; link; link = link->next) {
06615         func = (FunctionRNA *)link;
06616         flag = RNA_function_flag(func);
06617 
06618         if (!(flag & FUNC_REGISTER))
06619             continue;
06620 
06621         item = PyObject_GetAttrString(py_class, RNA_function_identifier(func));
06622 
06623         have_function[i] = (item != NULL);
06624         i++;
06625 
06626         if (item == NULL) {
06627             if ((flag & FUNC_REGISTER_OPTIONAL) == 0) {
06628                 PyErr_Format(PyExc_AttributeError,
06629                              "expected %.200s, %.200s class to have an \"%.200s\" attribute",
06630                              class_type, py_class_name,
06631                              RNA_function_identifier(func));
06632                 return -1;
06633             }
06634 
06635             PyErr_Clear();
06636         }
06637         else {
06638             Py_DECREF(item); /* no need to keep a ref, the class owns it (technically we should keep a ref but...) */
06639             if (flag & FUNC_NO_SELF) {
06640                 if (PyMethod_Check(item) == 0) {
06641                     PyErr_Format(PyExc_TypeError,
06642                                  "expected %.200s, %.200s class \"%.200s\" attribute to be a method, not a %.200s",
06643                                  class_type, py_class_name, RNA_function_identifier(func), Py_TYPE(item)->tp_name);
06644                     return -1;
06645                 }
06646                 item = ((PyMethodObject *)item)->im_func;
06647             }
06648             else {
06649                 if (PyFunction_Check(item) == 0) {
06650                     PyErr_Format(PyExc_TypeError,
06651                                  "expected %.200s, %.200s class \"%.200s\" attribute to be a function, not a %.200s",
06652                                  class_type, py_class_name, RNA_function_identifier(func), Py_TYPE(item)->tp_name);
06653                     return -1;
06654                 }
06655             }
06656 
06657             func_arg_count = rna_function_arg_count(func);
06658 
06659             if (func_arg_count >= 0) { /* -1 if we dont care*/
06660                 arg_count = ((PyCodeObject *)PyFunction_GET_CODE(item))->co_argcount;
06661 
06662                 /* note, the number of args we check for and the number of args we give to
06663                  * @classmethods are different (quirk of python),
06664                  * this is why rna_function_arg_count() doesn't return the value -1*/
06665                 if (flag & FUNC_NO_SELF)
06666                     func_arg_count++;
06667 
06668                 if (arg_count != func_arg_count) {
06669                     PyErr_Format(PyExc_ValueError,
06670                                  "expected %.200s, %.200s class \"%.200s\" function to have %d args, found %d",
06671                                  class_type, py_class_name, RNA_function_identifier(func),
06672                                  func_arg_count, arg_count);
06673                     return -1;
06674                 }
06675             }
06676         }
06677     }
06678 
06679     /* verify properties */
06680     lb = RNA_struct_type_properties(srna);
06681     for (link = lb->first; link; link = link->next) {
06682         const char *identifier;
06683         prop = (PropertyRNA *)link;
06684         flag = RNA_property_flag(prop);
06685 
06686         if (!(flag & PROP_REGISTER))
06687             continue;
06688 
06689         identifier = RNA_property_identifier(prop);
06690         item = PyObject_GetAttrString(py_class, identifier);
06691 
06692         if (item == NULL) {
06693             /* Sneaky workaround to use the class name as the bl_idname */
06694 
06695 #define     BPY_REPLACEMENT_STRING(rna_attr, py_attr)                         \
06696             if (strcmp(identifier, rna_attr) == 0) {                          \
06697                 item = PyObject_GetAttrString(py_class, py_attr);              \
06698                 if (item && item != Py_None) {                                \
06699                     if (pyrna_py_to_prop(dummyptr, prop, NULL,                \
06700                                          item, "validating class:") != 0)     \
06701                     {                                                         \
06702                         Py_DECREF(item);                                      \
06703                         return -1;                                            \
06704                     }                                                         \
06705                 }                                                             \
06706                 Py_XDECREF(item);                                             \
06707             }                                                                 \
06708 
06709 
06710             BPY_REPLACEMENT_STRING("bl_idname", "__name__");
06711             BPY_REPLACEMENT_STRING("bl_description", "__doc__");
06712 
06713 #undef      BPY_REPLACEMENT_STRING
06714 
06715             if (item == NULL && (((flag & PROP_REGISTER_OPTIONAL) != PROP_REGISTER_OPTIONAL))) {
06716                 PyErr_Format(PyExc_AttributeError,
06717                              "expected %.200s, %.200s class to have an \"%.200s\" attribute",
06718                              class_type, py_class_name, identifier);
06719                 return -1;
06720             }
06721 
06722             PyErr_Clear();
06723         }
06724         else {
06725             Py_DECREF(item); /* no need to keep a ref, the class owns it */
06726 
06727             if (pyrna_py_to_prop(dummyptr, prop, NULL, item, "validating class:") != 0)
06728                 return -1;
06729         }
06730     }
06731 
06732     return 0;
06733 }
06734 
06735 /* TODO - multiple return values like with rna functions */
06736 static int bpy_class_call(bContext *C, PointerRNA *ptr, FunctionRNA *func, ParameterList *parms)
06737 {
06738     PyObject *args;
06739     PyObject *ret = NULL, *py_srna = NULL, *py_class_instance = NULL, *parmitem;
06740     PyTypeObject *py_class;
06741     void **py_class_instance_store = NULL;
06742     PropertyRNA *parm;
06743     ParameterIterator iter;
06744     PointerRNA funcptr;
06745     int err = 0, i, flag, ret_len = 0;
06746     const char is_static = (RNA_function_flag(func) & FUNC_NO_SELF) != 0;
06747 
06748     /* annoying!, need to check if the screen gets set to NULL which is a
06749      * hint that the file was actually re-loaded. */
06750     char is_valid_wm;
06751 
06752     PropertyRNA *pret_single = NULL;
06753     void *retdata_single = NULL;
06754 
06755     PyGILState_STATE gilstate;
06756 
06757 #ifdef USE_PEDANTIC_WRITE
06758     const int is_operator = RNA_struct_is_a(ptr->type, &RNA_Operator);
06759     const char *func_id = RNA_function_identifier(func);
06760     /* testing, for correctness, not operator and not draw function */
06761     const short is_readonly = ((strncmp("draw", func_id, 4) == 0) || /* draw or draw_header */
06762                              /*strstr("render", func_id) ||*/
06763                              !is_operator);
06764 #endif
06765 
06766     py_class = RNA_struct_py_type_get(ptr->type);
06767     /* rare case. can happen when registering subclasses */
06768     if (py_class == NULL) {
06769         fprintf(stderr, "%s: unable to get python class for rna struct '%.200s'\n",
06770                 __func__, RNA_struct_identifier(ptr->type));
06771         return -1;
06772     }
06773 
06774     /* XXX, this is needed because render engine calls without a context
06775      * this should be supported at some point but at the moment its not! */
06776     if (C == NULL)
06777         C = BPy_GetContext();
06778 
06779     is_valid_wm = (CTX_wm_manager(C) != NULL);
06780 
06781     bpy_context_set(C, &gilstate);
06782 
06783     if (!is_static) {
06784         /* some datatypes (operator, render engine) can store PyObjects for re-use */
06785         if (ptr->data) {
06786             void **instance = RNA_struct_instance(ptr);
06787 
06788             if (instance) {
06789                 if (*instance) {
06790                     py_class_instance = *instance;
06791                     Py_INCREF(py_class_instance);
06792                 }
06793                 else {
06794                     /* store the instance here once its created */
06795                     py_class_instance_store = instance;
06796                 }
06797             }
06798         }
06799         /* end exception */
06800 
06801         if (py_class_instance == NULL)
06802             py_srna = pyrna_struct_CreatePyObject(ptr);
06803 
06804         if (py_class_instance) {
06805             /* special case, instance is cached */
06806         }
06807         else if (py_srna == NULL) {
06808             py_class_instance = NULL;
06809         }
06810         else if (py_srna == Py_None) { /* probably wont ever happen but possible */
06811             Py_DECREF(py_srna);
06812             py_class_instance = NULL;
06813         }
06814         else {
06815 #if 1
06816             /* Skip the code below and call init directly on the allocated 'py_srna'
06817              * otherwise __init__() always needs to take a second self argument, see pyrna_struct_new().
06818              * Although this is annoying to have to impliment a part of pythons typeobject.c:type_call().
06819              */
06820             if (py_class->tp_init) {
06821 #ifdef USE_PEDANTIC_WRITE
06822                 const int prev_write = rna_disallow_writes;
06823                 rna_disallow_writes = is_operator ? FALSE : TRUE; /* only operators can write on __init__ */
06824 #endif
06825 
06826                 /* true in most cases even when the class its self doesn't define an __init__ function. */
06827                 args = PyTuple_New(0);
06828                 if (py_class->tp_init(py_srna, args, NULL) < 0) {
06829                     Py_DECREF(py_srna);
06830                     py_srna = NULL;
06831                     /* err set below */
06832                 }
06833                 Py_DECREF(args);
06834 #ifdef USE_PEDANTIC_WRITE
06835                 rna_disallow_writes = prev_write;
06836 #endif
06837             }
06838             py_class_instance = py_srna;
06839 
06840 #else
06841             const int prev_write = rna_disallow_writes;
06842             rna_disallow_writes = TRUE;
06843 
06844             /* 'almost' all the time calling the class isn't needed.
06845              * We could just do...
06846             py_class_instance = py_srna;
06847             Py_INCREF(py_class_instance);
06848              * This would work fine but means __init__ functions wouldnt run.
06849              * none of blenders default scripts use __init__ but its nice to call it
06850              * for general correctness. just to note why this is here when it could be safely removed.
06851              */
06852             args = PyTuple_New(1);
06853             PyTuple_SET_ITEM(args, 0, py_srna);
06854             py_class_instance = PyObject_Call(py_class, args, NULL);
06855             Py_DECREF(args);
06856 
06857             rna_disallow_writes = prev_write;
06858 
06859 #endif
06860 
06861             if (py_class_instance == NULL) {
06862                 err = -1; /* so the error is not overridden below */
06863             }
06864             else if (py_class_instance_store) {
06865                 *py_class_instance_store = py_class_instance;
06866                 Py_INCREF(py_class_instance);
06867             }
06868         }
06869     }
06870 
06871     if (err != -1 && (is_static || py_class_instance)) { /* Initializing the class worked, now run its invoke function */
06872         PyObject *item = PyObject_GetAttrString((PyObject *)py_class, RNA_function_identifier(func));
06873 //      flag = RNA_function_flag(func);
06874 
06875         if (item) {
06876             RNA_pointer_create(NULL, &RNA_Function, func, &funcptr);
06877 
06878             args = PyTuple_New(rna_function_arg_count(func)); /* first arg is included in 'item' */
06879 
06880             if (is_static) {
06881                 i = 0;
06882             }
06883             else {
06884                 PyTuple_SET_ITEM(args, 0, py_class_instance);
06885                 i = 1;
06886             }
06887 
06888             RNA_parameter_list_begin(parms, &iter);
06889 
06890             /* parse function parameters */
06891             for (; iter.valid; RNA_parameter_list_next(&iter)) {
06892                 parm = iter.parm;
06893                 flag = RNA_property_flag(parm);
06894 
06895                 /* only useful for single argument returns, we'll need another list loop for multiple */
06896                 if (flag & PROP_OUTPUT) {
06897                     ret_len++;
06898                     if (pret_single == NULL) {
06899                         pret_single = parm;
06900                         retdata_single = iter.data;
06901                     }
06902 
06903                     continue;
06904                 }
06905 
06906                 parmitem = pyrna_param_to_py(&funcptr, parm, iter.data);
06907                 PyTuple_SET_ITEM(args, i, parmitem);
06908                 i++;
06909             }
06910 
06911 #ifdef USE_PEDANTIC_WRITE
06912             rna_disallow_writes = is_readonly ? TRUE:FALSE;
06913 #endif
06914             /* *** Main Caller *** */
06915 
06916             ret = PyObject_Call(item, args, NULL);
06917 
06918             /* *** Done Calling *** */
06919 
06920 #ifdef USE_PEDANTIC_WRITE
06921             rna_disallow_writes = FALSE;
06922 #endif
06923 
06924             RNA_parameter_list_end(&iter);
06925             Py_DECREF(item);
06926             Py_DECREF(args);
06927         }
06928         else {
06929             PyErr_Print();
06930             PyErr_Clear();
06931             PyErr_Format(PyExc_TypeError,
06932                          "could not find function %.200s in %.200s to execute callback",
06933                          RNA_function_identifier(func), RNA_struct_identifier(ptr->type));
06934             err = -1;
06935         }
06936     }
06937     else {
06938         /* the error may be already set if the class instance couldn't be created */
06939         if (err != -1) {
06940             PyErr_Format(PyExc_RuntimeError,
06941                          "could not create instance of %.200s to call callback function %.200s",
06942                          RNA_struct_identifier(ptr->type), RNA_function_identifier(func));
06943             err = -1;
06944         }
06945     }
06946 
06947     if (ret == NULL) { /* covers py_class_instance failing too */
06948         err = -1;
06949     }
06950     else {
06951         if (ret_len == 0 && ret != Py_None) {
06952             PyErr_Format(PyExc_RuntimeError,
06953                          "expected class %.200s, function %.200s to return None, not %.200s",
06954                          RNA_struct_identifier(ptr->type), RNA_function_identifier(func),
06955                          Py_TYPE(ret)->tp_name);
06956             err = -1;
06957         }
06958         else if (ret_len == 1) {
06959             err = pyrna_py_to_prop(&funcptr, pret_single, retdata_single, ret, "");
06960 
06961             /* when calling operator funcs only gives Function.result with
06962              * no line number since the func has finished calling on error,
06963              * re-raise the exception with more info since it would be slow to
06964              * create prefix on every call (when there are no errors) */
06965             if (err == -1) {
06966                 PyC_Err_Format_Prefix(PyExc_RuntimeError,
06967                                       "class %.200s, function %.200s: incompatible return value ",
06968                                       RNA_struct_identifier(ptr->type), RNA_function_identifier(func)
06969                                       );
06970             }
06971         }
06972         else if (ret_len > 1) {
06973 
06974             if (PyTuple_Check(ret) == 0) {
06975                 PyErr_Format(PyExc_RuntimeError,
06976                              "expected class %.200s, function %.200s to return a tuple of size %d, not %.200s",
06977                              RNA_struct_identifier(ptr->type), RNA_function_identifier(func),
06978                              ret_len, Py_TYPE(ret)->tp_name);
06979                 err = -1;
06980             }
06981             else if (PyTuple_GET_SIZE(ret) != ret_len) {
06982                 PyErr_Format(PyExc_RuntimeError,
06983                              "class %.200s, function %.200s to returned %d items, expected %d",
06984                              RNA_struct_identifier(ptr->type), RNA_function_identifier(func),
06985                              PyTuple_GET_SIZE(ret), ret_len);
06986                 err = -1;
06987             }
06988             else {
06989 
06990                 RNA_parameter_list_begin(parms, &iter);
06991 
06992                 /* parse function parameters */
06993                 for (i = 0; iter.valid; RNA_parameter_list_next(&iter)) {
06994                     parm = iter.parm;
06995                     flag = RNA_property_flag(parm);
06996 
06997                     /* only useful for single argument returns, we'll need another list loop for multiple */
06998                     if (flag & PROP_OUTPUT) {
06999                         err = pyrna_py_to_prop(&funcptr, parm, iter.data,
07000                                               PyTuple_GET_ITEM(ret, i++),
07001                                               "calling class function:");
07002                         if (err) {
07003                             break;
07004                         }
07005                     }
07006                 }
07007 
07008                 RNA_parameter_list_end(&iter);
07009             }
07010         }
07011         Py_DECREF(ret);
07012     }
07013 
07014     if (err != 0) {
07015         ReportList *reports;
07016         /* alert the user, else they wont know unless they see the console. */
07017         if ( (!is_static) &&
07018              (ptr->data) &&
07019              (RNA_struct_is_a(ptr->type, &RNA_Operator)) &&
07020              (is_valid_wm == (CTX_wm_manager(C) != NULL)))
07021         {
07022             wmOperator *op = ptr->data;
07023             reports = op->reports;
07024         }
07025         else {
07026             /* wont alert users but they can view in 'info' space */
07027             reports = CTX_wm_reports(C);
07028         }
07029 
07030         BPy_errors_to_report(reports);
07031 
07032         /* also print in the console for py */
07033         PyErr_Print();
07034         PyErr_Clear();
07035     }
07036 
07037     bpy_context_clear(C, &gilstate);
07038 
07039     return err;
07040 }
07041 
07042 static void bpy_class_free(void *pyob_ptr)
07043 {
07044     PyObject *self = (PyObject *)pyob_ptr;
07045     PyGILState_STATE gilstate;
07046 
07047     gilstate = PyGILState_Ensure();
07048 
07049     // breaks re-registering classes
07050     // PyDict_Clear(((PyTypeObject *)self)->tp_dict);
07051     //
07052     // remove the rna attribute instead.
07053     PyDict_DelItem(((PyTypeObject *)self)->tp_dict, bpy_intern_str_bl_rna);
07054     if (PyErr_Occurred())
07055         PyErr_Clear();
07056 
07057 #if 0 /* needs further investigation, too annoying so quiet for now */
07058     if (G.f&G_DEBUG) {
07059         if (self->ob_refcnt > 1) {
07060             PyC_ObSpit("zombie class - ref should be 1", self);
07061         }
07062     }
07063 #endif
07064     Py_DECREF((PyObject *)pyob_ptr);
07065 
07066     PyGILState_Release(gilstate);
07067 }
07068 
07069 void pyrna_alloc_types(void)
07070 {
07071     PyGILState_STATE gilstate;
07072 
07073     PointerRNA ptr;
07074     PropertyRNA *prop;
07075 
07076     gilstate = PyGILState_Ensure();
07077 
07078     /* avoid doing this lookup for every getattr */
07079     RNA_blender_rna_pointer_create(&ptr);
07080     prop = RNA_struct_find_property(&ptr, "structs");
07081 
07082     RNA_PROP_BEGIN(&ptr, itemptr, prop) {
07083         PyObject *item = pyrna_struct_Subtype(&itemptr);
07084         if (item == NULL) {
07085             if (PyErr_Occurred()) {
07086                 PyErr_Print();
07087                 PyErr_Clear();
07088             }
07089         }
07090         else {
07091             Py_DECREF(item);
07092         }
07093     }
07094     RNA_PROP_END;
07095 
07096     PyGILState_Release(gilstate);
07097 }
07098 
07099 
07100 void pyrna_free_types(void)
07101 {
07102     PointerRNA ptr;
07103     PropertyRNA *prop;
07104 
07105     /* avoid doing this lookup for every getattr */
07106     RNA_blender_rna_pointer_create(&ptr);
07107     prop = RNA_struct_find_property(&ptr, "structs");
07108 
07109 
07110     RNA_PROP_BEGIN(&ptr, itemptr, prop) {
07111         StructRNA *srna = srna_from_ptr(&itemptr);
07112         void *py_ptr = RNA_struct_py_type_get(srna);
07113 
07114         if (py_ptr) {
07115 #if 0   // XXX - should be able to do this but makes python crash on exit
07116             bpy_class_free(py_ptr);
07117 #endif
07118             RNA_struct_py_type_set(srna, NULL);
07119         }
07120     }
07121     RNA_PROP_END;
07122 
07123 }
07124 
07125 /* Note! MemLeak XXX
07126  *
07127  * There is currently a bug where moving registering a python class does
07128  * not properly manage refcounts from the python class, since the srna owns
07129  * the python class this should not be so tricky but changing the references as
07130  * you'd expect when changing ownership crashes blender on exit so I had to comment out
07131  * the decref. This is not so bad because the leak only happens when re-registering (hold F8)
07132  * - Should still be fixed - Campbell
07133  * */
07134 PyDoc_STRVAR(pyrna_register_class_doc,
07135 ".. method:: register_class(cls)\n"
07136 "\n"
07137 "   Register a subclass of a blender type in (:class:`bpy.types.Panel`,\n"
07138 "   :class:`bpy.types.Menu`, :class:`bpy.types.Header`, :class:`bpy.types.Operator`,\n"
07139 "   :class:`bpy.types.KeyingSetInfo`, :class:`bpy.types.RenderEngine`).\n"
07140 "\n"
07141 "   If the class has a *register* class method it will be called\n"
07142 "   before registration.\n"
07143 "\n"
07144 "   .. note::\n"
07145 "\n"
07146 "      :exc:`ValueError` exception is raised if the class is not a\n"
07147 "      subclass of a registerable blender class.\n"
07148 "\n"
07149 );
07150 PyMethodDef meth_bpy_register_class = {"register_class", pyrna_register_class, METH_O, pyrna_register_class_doc};
07151 static PyObject *pyrna_register_class(PyObject *UNUSED(self), PyObject *py_class)
07152 {
07153     bContext *C = NULL;
07154     ReportList reports;
07155     StructRegisterFunc reg;
07156     StructRNA *srna;
07157     StructRNA *srna_new;
07158     const char *identifier;
07159     PyObject *py_cls_meth;
07160 
07161     if (PyDict_GetItem(((PyTypeObject *)py_class)->tp_dict, bpy_intern_str_bl_rna)) {
07162         PyErr_SetString(PyExc_AttributeError, "register_class(...): already registered as a subclass");
07163         return NULL;
07164     }
07165 
07166     /* warning: gets parent classes srna, only for the register function */
07167     srna = pyrna_struct_as_srna(py_class, 1, "register_class(...):");
07168     if (srna == NULL)
07169         return NULL;
07170 
07171     /* fails in cases, cant use this check but would like to :| */
07172     /*
07173     if (RNA_struct_py_type_get(srna)) {
07174         PyErr_Format(PyExc_ValueError,
07175                      "register_class(...): %.200s's parent class %.200s is already registered, this is not allowed",
07176                      ((PyTypeObject *)py_class)->tp_name, RNA_struct_identifier(srna));
07177         return NULL;
07178     }
07179     */
07180 
07181     /* check that we have a register callback for this type */
07182     reg = RNA_struct_register(srna);
07183 
07184     if (!reg) {
07185         PyErr_Format(PyExc_ValueError,
07186                      "register_class(...): expected a subclass of a registerable "
07187                      "rna type (%.200s does not support registration)",
07188                      RNA_struct_identifier(srna));
07189         return NULL;
07190     }
07191 
07192     /* get the context, so register callback can do necessary refreshes */
07193     C = BPy_GetContext();
07194 
07195     /* call the register callback with reports & identifier */
07196     BKE_reports_init(&reports, RPT_STORE);
07197 
07198     identifier = ((PyTypeObject *)py_class)->tp_name;
07199 
07200     srna_new = reg(CTX_data_main(C), &reports, py_class, identifier,
07201                    bpy_class_validate, bpy_class_call, bpy_class_free);
07202 
07203     if (BPy_reports_to_error(&reports, PyExc_RuntimeError, TRUE) == -1)
07204         return NULL;
07205 
07206     /* python errors validating are not converted into reports so the check above will fail.
07207      * the cause for returning NULL will be printed as an error */
07208     if (srna_new == NULL)
07209         return NULL;
07210 
07211     pyrna_subtype_set_rna(py_class, srna_new); /* takes a ref to py_class */
07212 
07213     /* old srna still references us, keep the check incase registering somehow can free it */
07214     if (RNA_struct_py_type_get(srna)) {
07215         RNA_struct_py_type_set(srna, NULL);
07216         // Py_DECREF(py_class); // should be able to do this XXX since the old rna adds a new ref.
07217     }
07218 
07219     /* Can't use this because it returns a dict proxy
07220      *
07221      * item = PyObject_GetAttrString(py_class, "__dict__");
07222      */
07223     if (pyrna_deferred_register_class(srna_new, py_class) != 0)
07224         return NULL;
07225 
07226     /* call classed register method () */
07227     py_cls_meth = PyObject_GetAttr(py_class, bpy_intern_str_register);
07228     if (py_cls_meth == NULL) {
07229         PyErr_Clear();
07230     }
07231     else {
07232         PyObject *ret = PyObject_CallObject(py_cls_meth, NULL);
07233         if (ret) {
07234             Py_DECREF(ret);
07235         }
07236         else {
07237             return NULL;
07238         }
07239     }
07240 
07241     Py_RETURN_NONE;
07242 }
07243 
07244 
07245 static int pyrna_srna_contains_pointer_prop_srna(StructRNA *srna_props, StructRNA *srna, const char **prop_identifier)
07246 {
07247     PropertyRNA *prop;
07248     LinkData *link;
07249 
07250     /* verify properties */
07251     const ListBase *lb = RNA_struct_type_properties(srna);
07252 
07253     for (link = lb->first; link; link = link->next) {
07254         prop = (PropertyRNA *)link;
07255         if (RNA_property_type(prop) == PROP_POINTER && !(RNA_property_flag(prop) & PROP_BUILTIN)) {
07256             PointerRNA tptr;
07257             RNA_pointer_create(NULL, &RNA_Struct, srna_props, &tptr);
07258 
07259             if (RNA_property_pointer_type(&tptr, prop) == srna) {
07260                 *prop_identifier = RNA_property_identifier(prop);
07261                 return 1;
07262             }
07263         }
07264     }
07265 
07266     return 0;
07267 }
07268 
07269 PyDoc_STRVAR(pyrna_unregister_class_doc,
07270 ".. method:: unregister_class(cls)\n"
07271 "\n"
07272 "   Unload the python class from blender.\n"
07273 "\n"
07274 "   If the class has an *unregister* class method it will be called\n"
07275 "   before unregistering.\n"
07276 );
07277 PyMethodDef meth_bpy_unregister_class = {
07278     "unregister_class", pyrna_unregister_class, METH_O, pyrna_unregister_class_doc
07279 };
07280 static PyObject *pyrna_unregister_class(PyObject *UNUSED(self), PyObject *py_class)
07281 {
07282     bContext *C = NULL;
07283     StructUnregisterFunc unreg;
07284     StructRNA *srna;
07285     PyObject *py_cls_meth;
07286 
07287     /*if (PyDict_GetItem(((PyTypeObject *)py_class)->tp_dict, bpy_intern_str_bl_rna) == NULL) {
07288         PWM_cursor_wait(0);
07289         PyErr_SetString(PyExc_ValueError, "unregister_class(): not a registered as a subclass");
07290         return NULL;
07291     }*/
07292 
07293     srna = pyrna_struct_as_srna(py_class, 0, "unregister_class(...):");
07294     if (srna == NULL)
07295         return NULL;
07296 
07297     /* check that we have a unregister callback for this type */
07298     unreg = RNA_struct_unregister(srna);
07299 
07300     if (!unreg) {
07301         PyErr_SetString(PyExc_ValueError,
07302                         "unregister_class(...): "
07303                         "expected a Type subclassed from a registerable rna type (no unregister supported)");
07304         return NULL;
07305     }
07306 
07307     /* call classed unregister method */
07308     py_cls_meth = PyObject_GetAttr(py_class, bpy_intern_str_unregister);
07309     if (py_cls_meth == NULL) {
07310         PyErr_Clear();
07311     }
07312     else {
07313         PyObject *ret = PyObject_CallObject(py_cls_meth, NULL);
07314         if (ret) {
07315             Py_DECREF(ret);
07316         }
07317         else {
07318             return NULL;
07319         }
07320     }
07321 
07322     /* should happen all the time but very slow */
07323     if (G.f & G_DEBUG) {
07324         /* remove all properties using this class */
07325         StructRNA *srna_iter;
07326         PointerRNA ptr_rna;
07327         PropertyRNA *prop_rna;
07328         const char *prop_identifier = NULL;
07329 
07330         RNA_blender_rna_pointer_create(&ptr_rna);
07331         prop_rna = RNA_struct_find_property(&ptr_rna, "structs");
07332 
07333 
07334 
07335         /* loop over all structs */
07336         RNA_PROP_BEGIN(&ptr_rna, itemptr, prop_rna) {
07337             srna_iter = itemptr.data;
07338             if (pyrna_srna_contains_pointer_prop_srna(srna_iter, srna, &prop_identifier)) {
07339                 break;
07340             }
07341         }
07342         RNA_PROP_END;
07343 
07344         if (prop_identifier) {
07345             PyErr_Format(PyExc_RuntimeError,
07346                          "unregister_class(...): can't unregister %s because %s.%s pointer property is using this",
07347                          RNA_struct_identifier(srna), RNA_struct_identifier(srna_iter), prop_identifier);
07348             return NULL;
07349         }
07350     }
07351 
07352     /* get the context, so register callback can do necessary refreshes */
07353     C = BPy_GetContext();
07354 
07355     /* call unregister */
07356     unreg(CTX_data_main(C), srna); /* calls bpy_class_free, this decref's py_class */
07357 
07358     PyDict_DelItem(((PyTypeObject *)py_class)->tp_dict, bpy_intern_str_bl_rna);
07359     if (PyErr_Occurred())
07360         PyErr_Clear(); //return NULL;
07361 
07362     Py_RETURN_NONE;
07363 }