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