4 * ***** BEGIN GPL LICENSE BLOCK *****
6 * This program is free software; you can redistribute it and/or
7 * modify it under the terms of the GNU General Public License
8 * as published by the Free Software Foundation; either version 2
9 * of the License, or (at your option) any later version.
11 * This program is distributed in the hope that it will be useful,
12 * but WITHOUT ANY WARRANTY; without even the implied warranty of
13 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
14 * GNU General Public License for more details.
16 * You should have received a copy of the GNU General Public License
17 * along with this program; if not, write to the Free Software Foundation,
18 * Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
20 * Contributor(s): Campbell Barton
22 * ***** END GPL LICENSE BLOCK *****
27 //#include "blendef.h"
28 #include "BLI_dynstr.h"
29 #include "BLI_listbase.h"
30 #include "BLI_string.h"
31 #include "float.h" /* FLT_MIN/MAX */
33 #include "RNA_access.h"
34 #include "RNA_define.h" /* for defining our own rna */
36 #include "MEM_guardedalloc.h"
37 #include "BKE_utildefines.h"
38 #include "BKE_context.h"
39 #include "BKE_global.h" /* evil G.* */
40 #include "BKE_report.h"
42 /* only for keyframing */
43 #include "DNA_scene_types.h"
44 #include "DNA_anim_types.h"
45 #include "ED_keyframing.h"
50 #include "../generic/Mathutils.h" /* so we can have mathutils callbacks */
51 #include "../generic/IDProp.h" /* for IDprop lookups */
53 /* bpyrna vector/euler/quat callbacks */
54 static int mathutils_rna_array_cb_index= -1; /* index for our callbacks */
56 static int mathutils_rna_generic_check(BPy_PropertyRNA *self)
58 return self->prop?1:0;
61 static int mathutils_rna_vector_get(BPy_PropertyRNA *self, int subtype, float *vec_from)
66 RNA_property_float_get_array(&self->ptr, self->prop, vec_from);
70 static int mathutils_rna_vector_set(BPy_PropertyRNA *self, int subtype, float *vec_to)
75 RNA_property_float_set_array(&self->ptr, self->prop, vec_to);
76 RNA_property_update(BPy_GetContext(), &self->ptr, self->prop);
80 static int mathutils_rna_vector_get_index(BPy_PropertyRNA *self, int subtype, float *vec_from, int index)
85 vec_from[index]= RNA_property_float_get_index(&self->ptr, self->prop, index);
89 static int mathutils_rna_vector_set_index(BPy_PropertyRNA *self, int subtype, float *vec_to, int index)
94 RNA_property_float_set_index(&self->ptr, self->prop, index, vec_to[index]);
95 RNA_property_update(BPy_GetContext(), &self->ptr, self->prop);
99 Mathutils_Callback mathutils_rna_array_cb = {
100 (BaseMathCheckFunc) mathutils_rna_generic_check,
101 (BaseMathGetFunc) mathutils_rna_vector_get,
102 (BaseMathSetFunc) mathutils_rna_vector_set,
103 (BaseMathGetIndexFunc) mathutils_rna_vector_get_index,
104 (BaseMathSetIndexFunc) mathutils_rna_vector_set_index
108 /* bpyrna matrix callbacks */
109 static int mathutils_rna_matrix_cb_index= -1; /* index for our callbacks */
111 static int mathutils_rna_matrix_get(BPy_PropertyRNA *self, int subtype, float *mat_from)
116 RNA_property_float_get_array(&self->ptr, self->prop, mat_from);
120 static int mathutils_rna_matrix_set(BPy_PropertyRNA *self, int subtype, float *mat_to)
125 RNA_property_float_set_array(&self->ptr, self->prop, mat_to);
126 RNA_property_update(BPy_GetContext(), &self->ptr, self->prop);
130 Mathutils_Callback mathutils_rna_matrix_cb = {
131 (BaseMathCheckFunc) mathutils_rna_generic_check,
132 (BaseMathGetFunc) mathutils_rna_matrix_get,
133 (BaseMathSetFunc) mathutils_rna_matrix_set,
134 (BaseMathGetIndexFunc) NULL,
135 (BaseMathSetIndexFunc) NULL
138 PyObject *pyrna_math_object_from_array(PointerRNA *ptr, PropertyRNA *prop)
143 int type, subtype, totdim;
146 len= RNA_property_array_length(ptr, prop);
147 type= RNA_property_type(prop);
148 subtype= RNA_property_subtype(prop);
149 totdim= RNA_property_array_dimension(ptr, prop, NULL);
151 if (type != PROP_FLOAT) return NULL;
153 if (totdim == 1 || (totdim == 2 && subtype == PROP_MATRIX)) {
154 ret = pyrna_prop_CreatePyObject(ptr, prop);
156 switch(RNA_property_subtype(prop)) {
157 case PROP_TRANSLATION:
160 case PROP_ACCELERATION:
162 if(len>=2 && len <= 4) {
163 PyObject *vec_cb= newVectorObject_cb(ret, len, mathutils_rna_array_cb_index, FALSE);
164 Py_DECREF(ret); /* the vector owns now */
165 ret= vec_cb; /* return the vector instead */
170 PyObject *mat_cb= newMatrixObject_cb(ret, 4,4, mathutils_rna_matrix_cb_index, FALSE);
171 Py_DECREF(ret); /* the matrix owns now */
172 ret= mat_cb; /* return the matrix instead */
175 PyObject *mat_cb= newMatrixObject_cb(ret, 3,3, mathutils_rna_matrix_cb_index, FALSE);
176 Py_DECREF(ret); /* the matrix owns now */
177 ret= mat_cb; /* return the matrix instead */
181 case PROP_QUATERNION:
182 if(len==3) { /* euler */
183 PyObject *eul_cb= newEulerObject_cb(ret, mathutils_rna_array_cb_index, FALSE);
184 Py_DECREF(ret); /* the matrix owns now */
185 ret= eul_cb; /* return the matrix instead */
188 PyObject *quat_cb= newQuaternionObject_cb(ret, mathutils_rna_array_cb_index, FALSE);
189 Py_DECREF(ret); /* the matrix owns now */
190 ret= quat_cb; /* return the matrix instead */
204 static StructRNA *pyrna_struct_as_srna(PyObject *self);
206 static int pyrna_struct_compare( BPy_StructRNA * a, BPy_StructRNA * b )
208 return (a->ptr.data==b->ptr.data) ? 0 : -1;
211 static int pyrna_prop_compare( BPy_PropertyRNA * a, BPy_PropertyRNA * b )
213 return (a->prop==b->prop && a->ptr.data==b->ptr.data ) ? 0 : -1;
216 static PyObject *pyrna_struct_richcmp(PyObject *a, PyObject *b, int op)
219 int ok= -1; /* zero is true */
221 if (BPy_StructRNA_Check(a) && BPy_StructRNA_Check(b))
222 ok= pyrna_struct_compare((BPy_StructRNA *)a, (BPy_StructRNA *)b);
226 ok = !ok; /* pass through */
228 res = ok ? Py_False : Py_True;
235 res = Py_NotImplemented;
246 static PyObject *pyrna_prop_richcmp(PyObject *a, PyObject *b, int op)
249 int ok= -1; /* zero is true */
251 if (BPy_PropertyRNA_Check(a) && BPy_PropertyRNA_Check(b))
252 ok= pyrna_prop_compare((BPy_PropertyRNA *)a, (BPy_PropertyRNA *)b);
256 ok = !ok; /* pass through */
258 res = ok ? Py_False : Py_True;
265 res = Py_NotImplemented;
276 /*----------------------repr--------------------------------------------*/
277 static PyObject *pyrna_struct_repr( BPy_StructRNA *self )
282 /* print name if available */
283 name= RNA_struct_name_get_alloc(&self->ptr, NULL, FALSE);
285 pyob= PyUnicode_FromFormat( "[BPy_StructRNA \"%.200s\" -> \"%.200s\"]", RNA_struct_identifier(self->ptr.type), name);
290 return PyUnicode_FromFormat( "[BPy_StructRNA \"%.200s\"]", RNA_struct_identifier(self->ptr.type));
293 static PyObject *pyrna_prop_repr( BPy_PropertyRNA *self )
299 /* if a pointer, try to print name of pointer target too */
300 if(RNA_property_type(self->prop) == PROP_POINTER) {
301 ptr= RNA_property_pointer_get(&self->ptr, self->prop);
302 name= RNA_struct_name_get_alloc(&ptr, NULL, FALSE);
305 pyob= PyUnicode_FromFormat( "[BPy_PropertyRNA \"%.200s\" -> \"%.200s\" -> \"%.200s\" ]", RNA_struct_identifier(self->ptr.type), RNA_property_identifier(self->prop), name);
311 return PyUnicode_FromFormat( "[BPy_PropertyRNA \"%.200s\" -> \"%.200s\"]", RNA_struct_identifier(self->ptr.type), RNA_property_identifier(self->prop));
314 static long pyrna_struct_hash( BPy_StructRNA *self )
316 return (long)self->ptr.data;
319 /* use our own dealloc so we can free a property if we use one */
320 static void pyrna_struct_dealloc( BPy_StructRNA *self )
322 if (self->freeptr && self->ptr.data) {
323 IDP_FreeProperty(self->ptr.data);
324 if (self->ptr.type != &RNA_Context)
326 MEM_freeN(self->ptr.data);
327 self->ptr.data= NULL;
331 /* Note, for subclassed PyObjects we cant just call PyObject_DEL() directly or it will crash */
332 Py_TYPE(self)->tp_free(self);
336 static char *pyrna_enum_as_string(PointerRNA *ptr, PropertyRNA *prop)
338 EnumPropertyItem *item;
342 RNA_property_enum_items(BPy_GetContext(), ptr, prop, &item, NULL, &free);
344 result= (char*)BPy_enum_as_string(item);
356 static int pyrna_string_to_enum(PyObject *item, PointerRNA *ptr, PropertyRNA *prop, int *val, const char *error_prefix)
358 char *param= _PyUnicode_AsString(item);
361 char *enum_str= pyrna_enum_as_string(ptr, prop);
362 PyErr_Format(PyExc_TypeError, "%.200s expected a string enum type in (%.200s)", error_prefix, enum_str);
366 if (!RNA_property_enum_value(BPy_GetContext(), ptr, prop, param, val)) {
367 char *enum_str= pyrna_enum_as_string(ptr, prop);
368 PyErr_Format(PyExc_TypeError, "%.200s enum \"%.200s\" not found in (%.200s)", error_prefix, param, enum_str);
377 PyObject * pyrna_prop_to_py(PointerRNA *ptr, PropertyRNA *prop)
380 int type = RNA_property_type(prop);
382 if (RNA_property_array_check(ptr, prop)) {
383 return pyrna_py_from_array(ptr, prop);
386 /* see if we can coorce into a python type - PropertyType */
389 ret = PyBool_FromLong( RNA_property_boolean_get(ptr, prop) );
392 ret = PyLong_FromSsize_t( (Py_ssize_t)RNA_property_int_get(ptr, prop) );
395 ret = PyFloat_FromDouble( RNA_property_float_get(ptr, prop) );
400 buf = RNA_property_string_get_alloc(ptr, prop, NULL, -1);
401 ret = PyUnicode_FromString( buf );
407 const char *identifier;
408 int val = RNA_property_enum_get(ptr, prop);
410 if (RNA_property_enum_identifier(BPy_GetContext(), ptr, prop, val, &identifier)) {
411 ret = PyUnicode_FromString( identifier );
413 EnumPropertyItem *item;
416 /* don't throw error here, can't trust blender 100% to give the
417 * right values, python code should not generate error for that */
418 RNA_property_enum_items(BPy_GetContext(), ptr, prop, &item, NULL, &free);
419 if(item && item->identifier) {
420 ret = PyUnicode_FromString( item->identifier );
423 char *ptr_name= RNA_struct_name_get_alloc(ptr, NULL, FALSE);
425 /* prefer not fail silently incase of api errors, maybe disable it later */
426 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));
428 #if 0 // gives python decoding errors while generating docs :(
430 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));
431 PyErr_Warn(PyExc_RuntimeWarning, error_str);
437 ret = PyUnicode_FromString( "" );
443 /*PyErr_Format(PyExc_AttributeError, "RNA Error: Current value \"%d\" matches no enum", val);
452 newptr= RNA_property_pointer_get(ptr, prop);
454 ret = pyrna_struct_CreatePyObject(&newptr);
461 case PROP_COLLECTION:
462 ret = pyrna_prop_CreatePyObject(ptr, prop);
465 PyErr_Format(PyExc_TypeError, "RNA Error: unknown type \"%d\" (pyrna_prop_to_py)", type);
473 /* This function is used by operators and converting dicts into collections.
474 * Its takes keyword args and fills them with property values */
475 int pyrna_pydict_to_props(PointerRNA *ptr, PyObject *kw, int all_args, const char *error_prefix)
479 const char *arg_name= NULL;
482 totkw = kw ? PyDict_Size(kw):0;
484 RNA_STRUCT_BEGIN(ptr, prop) {
485 arg_name= RNA_property_identifier(prop);
487 if (strcmp(arg_name, "rna_type")==0) continue;
490 PyErr_Format( PyExc_TypeError, "%.200s: no keywords, expected \"%.200s\"", error_prefix, arg_name ? arg_name : "<UNKNOWN>");
495 item= PyDict_GetItemString(kw, arg_name); /* wont set an error */
499 PyErr_Format( PyExc_TypeError, "%.200s: keyword \"%.200s\" missing", error_prefix, arg_name ? arg_name : "<UNKNOWN>");
500 error_val = -1; /* pyrna_py_to_prop sets the error */
504 if (pyrna_py_to_prop(ptr, prop, NULL, item, error_prefix)) {
513 if (error_val==0 && totkw > 0) { /* some keywords were given that were not used :/ */
514 PyObject *key, *value;
517 while (PyDict_Next(kw, &pos, &key, &value)) {
518 arg_name= _PyUnicode_AsString(key);
519 if (RNA_struct_find_property(ptr, arg_name) == NULL) break;
523 PyErr_Format( PyExc_TypeError, "%.200s: keyword \"%.200s\" unrecognized", error_prefix, arg_name ? arg_name : "<UNKNOWN>");
530 static PyObject * pyrna_func_call(PyObject *self, PyObject *args, PyObject *kw);
532 PyObject *pyrna_func_to_py(BPy_DummyPointerRNA *pyrna, FunctionRNA *func)
534 static PyMethodDef func_meth = {"<generic rna function>", (PyCFunction)pyrna_func_call, METH_VARARGS|METH_KEYWORDS, "python rna function"};
539 PyErr_Format( PyExc_RuntimeError, "%.200s: type attempted to get NULL function", RNA_struct_identifier(pyrna->ptr.type));
543 self= PyTuple_New(2);
545 PyTuple_SET_ITEM(self, 0, (PyObject *)pyrna);
548 PyTuple_SET_ITEM(self, 1, PyCObject_FromVoidPtr((void *)func, NULL));
550 ret= PyCFunction_New(&func_meth, self);
557 int pyrna_py_to_prop(PointerRNA *ptr, PropertyRNA *prop, void *data, PyObject *value, const char *error_prefix)
559 /* XXX hard limits should be checked here */
560 int type = RNA_property_type(prop);
563 if (RNA_property_array_check(ptr, prop)) {
565 /* char error_str[512]; */
569 if(MatrixObject_Check(value)) {
570 MatrixObject *mat = (MatrixObject*)value;
571 if(!BaseMath_ReadCallback(mat))
573 } else /* continue... */
575 if (!PySequence_Check(value)) {
576 PyErr_Format(PyExc_TypeError, "%.200s RNA array assignment expected a sequence instead of %.200s instance.", error_prefix, Py_TYPE(value)->tp_name);
579 /* done getting the length */
580 ok= pyrna_py_to_array(ptr, prop, data, value, error_prefix);
583 /* PyErr_Format(PyExc_AttributeError, "%.200s %s", error_prefix, error_str); */
588 /* Normal Property (not an array) */
590 /* see if we can coorce into a python type - PropertyType */
594 int param = PyObject_IsTrue( value );
597 PyErr_Format(PyExc_TypeError, "%.200s expected True/False or 0/1", error_prefix);
600 if(data) *((int*)data)= param;
601 else RNA_property_boolean_set(ptr, prop, param);
607 int param = PyLong_AsSsize_t(value);
608 if (param==-1 && PyErr_Occurred()) {
609 PyErr_Format(PyExc_TypeError, "%.200s expected an int type", error_prefix);
612 if(data) *((int*)data)= param;
613 else RNA_property_int_set(ptr, prop, param);
619 float param = PyFloat_AsDouble(value);
620 if (PyErr_Occurred()) {
621 PyErr_Format(PyExc_TypeError, "%.200s expected a float type", error_prefix);
624 if(data) *((float*)data)= param;
625 else RNA_property_float_set(ptr, prop, param);
631 char *param = _PyUnicode_AsString(value);
634 PyErr_Format(PyExc_TypeError, "%.200s expected a string type", error_prefix);
637 if(data) *((char**)data)= param;
638 else RNA_property_string_set(ptr, prop, param);
646 if (PyUnicode_Check(value)) {
647 if (!pyrna_string_to_enum(value, ptr, prop, &val, error_prefix))
650 else if (PyTuple_Check(value)) {
651 /* tuple of enum items, concatenate all values with OR */
653 for (i= 0; i < PyTuple_Size(value); i++) {
656 /* PyTuple_GET_ITEM returns a borrowed reference */
657 if (!pyrna_string_to_enum(PyTuple_GET_ITEM(value, i), ptr, prop, &tmpval, error_prefix))
664 char *enum_str= pyrna_enum_as_string(ptr, prop);
665 PyErr_Format(PyExc_TypeError, "%.200s expected a string enum or a tuple of strings in (%.200s)", error_prefix, enum_str);
670 if(data) *((int*)data)= val;
671 else RNA_property_enum_set(ptr, prop, val);
677 StructRNA *ptype= RNA_property_pointer_type(ptr, prop);
678 int flag = RNA_property_flag(prop);
680 if(!BPy_StructRNA_Check(value) && value != Py_None) {
681 PyErr_Format(PyExc_TypeError, "%.200s expected a %.200s type", error_prefix, RNA_struct_identifier(ptype));
683 } else if((flag & PROP_NEVER_NULL) && value == Py_None) {
684 PyErr_Format(PyExc_TypeError, "property can't be assigned a None value");
687 BPy_StructRNA *param= (BPy_StructRNA*)value;
688 int raise_error= FALSE;
691 if(flag & PROP_RNAPTR) {
693 memset(data, 0, sizeof(PointerRNA));
695 *((PointerRNA*)data)= param->ptr;
697 else if(value == Py_None) {
698 *((void**)data)= NULL;
700 else if(RNA_struct_is_a(param->ptr.type, ptype)) {
701 *((void**)data)= param->ptr.data;
708 /* data==NULL, assign to RNA */
709 if(value == Py_None) {
711 memset(&valueptr, 0, sizeof(valueptr));
712 RNA_property_pointer_set(ptr, prop, valueptr);
714 else if(RNA_struct_is_a(param->ptr.type, ptype)) {
715 RNA_property_pointer_set(ptr, prop, param->ptr);
719 RNA_pointer_create(NULL, ptype, NULL, &tmp);
720 PyErr_Format(PyExc_TypeError, "%.200s expected a %.200s type", error_prefix, RNA_struct_identifier(tmp.type));
727 RNA_pointer_create(NULL, ptype, NULL, &tmp);
728 PyErr_Format(PyExc_TypeError, "%.200s expected a %.200s type", error_prefix, RNA_struct_identifier(tmp.type));
734 case PROP_COLLECTION:
740 CollectionPointerLink *link;
742 lb= (data)? (ListBase*)data: NULL;
744 /* convert a sequence of dict's into a collection */
745 if(!PySequence_Check(value)) {
746 PyErr_Format(PyExc_TypeError, "%.200s expected a sequence of dicts for an RNA collection", error_prefix);
750 seq_len = PySequence_Length(value);
751 for(i=0; i<seq_len; i++) {
752 item= PySequence_GetItem(value, i);
753 if(item==NULL || PyDict_Check(item)==0) {
754 PyErr_Format(PyExc_TypeError, "%.200s expected a sequence of dicts for an RNA collection", error_prefix);
760 link= MEM_callocN(sizeof(CollectionPointerLink), "PyCollectionPointerLink");
762 BLI_addtail(lb, link);
765 RNA_property_collection_add(ptr, prop, &itemptr);
767 if(pyrna_pydict_to_props(&itemptr, item, 1, "Converting a python list to an RNA collection")==-1) {
777 PyErr_Format(PyExc_AttributeError, "%.200s unknown property type (pyrna_py_to_prop)", error_prefix);
783 /* Run rna property functions */
784 RNA_property_update(BPy_GetContext(), ptr, prop);
789 static PyObject * pyrna_prop_to_py_index(BPy_PropertyRNA *self, int index)
791 return pyrna_py_from_array_index(self, index);
794 static int pyrna_py_to_prop_index(BPy_PropertyRNA *self, int index, PyObject *value)
798 PointerRNA *ptr= &self->ptr;
799 PropertyRNA *prop= self->prop;
800 int type = RNA_property_type(prop);
802 totdim= RNA_property_array_dimension(ptr, prop, NULL);
805 /* char error_str[512]; */
806 if (!pyrna_py_to_array_index(&self->ptr, self->prop, self->arraydim, self->arrayoffset, index, value, "")) {
807 /* PyErr_SetString(PyExc_AttributeError, error_str); */
812 /* see if we can coorce into a python type - PropertyType */
816 int param = PyObject_IsTrue( value );
819 PyErr_SetString(PyExc_TypeError, "expected True/False or 0/1");
822 RNA_property_boolean_set_index(ptr, prop, index, param);
828 int param = PyLong_AsSsize_t(value);
829 if (param==-1 && PyErr_Occurred()) {
830 PyErr_SetString(PyExc_TypeError, "expected an int type");
833 RNA_property_int_set_index(ptr, prop, index, param);
839 float param = PyFloat_AsDouble(value);
840 if (PyErr_Occurred()) {
841 PyErr_SetString(PyExc_TypeError, "expected a float type");
844 RNA_property_float_set_index(ptr, prop, index, param);
849 PyErr_SetString(PyExc_AttributeError, "not an array type");
858 //---------------sequence-------------------------------------------
859 static int pyrna_prop_array_length(BPy_PropertyRNA *self)
861 if (RNA_property_array_dimension(&self->ptr, self->prop, NULL) > 1)
862 return RNA_property_multi_array_length(&self->ptr, self->prop, self->arraydim);
864 return RNA_property_array_length(&self->ptr, self->prop);
867 static Py_ssize_t pyrna_prop_len( BPy_PropertyRNA *self )
871 if (RNA_property_type(self->prop) == PROP_COLLECTION) {
872 len = RNA_property_collection_length(&self->ptr, self->prop);
873 } else if (RNA_property_array_check(&self->ptr, self->prop)) {
874 len = pyrna_prop_array_length(self);
876 PyErr_SetString(PyExc_AttributeError, "len() only available for collection and array RNA types");
877 len = -1; /* error value */
883 /* internal use only */
884 static PyObject *prop_subscript_collection_int(BPy_PropertyRNA *self, int keynum)
888 if(keynum < 0) keynum += RNA_property_collection_length(&self->ptr, self->prop);
890 if(RNA_property_collection_lookup_int(&self->ptr, self->prop, keynum, &newptr))
891 return pyrna_struct_CreatePyObject(&newptr);
893 PyErr_Format(PyExc_IndexError, "index %d out of range", keynum);
897 static PyObject *prop_subscript_array_int(BPy_PropertyRNA *self, int keynum)
899 int len= pyrna_prop_array_length(self);
901 if(keynum < 0) keynum += len;
903 if(keynum >= 0 && keynum < len)
904 return pyrna_prop_to_py_index(self, keynum);
906 PyErr_Format(PyExc_IndexError, "index %d out of range", keynum);
910 static PyObject *prop_subscript_collection_str(BPy_PropertyRNA *self, char *keyname)
913 if(RNA_property_collection_lookup_string(&self->ptr, self->prop, keyname, &newptr))
914 return pyrna_struct_CreatePyObject(&newptr);
916 PyErr_Format(PyExc_KeyError, "key \"%.200s\" not found", keyname);
919 /* static PyObject *prop_subscript_array_str(BPy_PropertyRNA *self, char *keyname) */
921 static PyObject *prop_subscript_collection_slice(BPy_PropertyRNA *self, int start, int stop)
924 PyObject *list = PyList_New(stop - start);
927 start = MIN2(start,stop); /* values are clamped from */
929 for(count = start; count < stop; count++) {
930 if(RNA_property_collection_lookup_int(&self->ptr, self->prop, count - start, &newptr)) {
931 PyList_SetItem(list, count - start, pyrna_struct_CreatePyObject(&newptr));
936 PyErr_SetString(PyExc_RuntimeError, "error getting an rna struct from a collection");
943 static PyObject *prop_subscript_array_slice(BPy_PropertyRNA *self, int start, int stop)
945 PyObject *list = PyList_New(stop - start);
948 start = MIN2(start,stop); /* values are clamped from PySlice_GetIndicesEx */
950 for(count = start; count < stop; count++)
951 PyList_SetItem(list, count - start, pyrna_prop_to_py_index(self, count));
956 static PyObject *prop_subscript_collection(BPy_PropertyRNA *self, PyObject *key)
958 if (PyUnicode_Check(key)) {
959 return prop_subscript_collection_str(self, _PyUnicode_AsString(key));
961 else if (PyIndex_Check(key)) {
962 Py_ssize_t i = PyNumber_AsSsize_t(key, PyExc_IndexError);
963 if (i == -1 && PyErr_Occurred())
966 return prop_subscript_collection_int(self, i);
968 else if (PySlice_Check(key)) {
969 int len= RNA_property_collection_length(&self->ptr, self->prop);
970 Py_ssize_t start, stop, step, slicelength;
972 if (PySlice_GetIndicesEx((PySliceObject*)key, len, &start, &stop, &step, &slicelength) < 0)
975 if (slicelength <= 0) {
976 return PyList_New(0);
978 else if (step == 1) {
979 return prop_subscript_collection_slice(self, start, stop);
982 PyErr_SetString(PyExc_TypeError, "slice steps not supported with rna");
987 PyErr_Format(PyExc_TypeError, "invalid rna key, key must be a string or an int instead of %.200s instance.", Py_TYPE(key)->tp_name);
992 static PyObject *prop_subscript_array(BPy_PropertyRNA *self, PyObject *key)
994 /*if (PyUnicode_Check(key)) {
995 return prop_subscript_array_str(self, _PyUnicode_AsString(key));
997 if (PyIndex_Check(key)) {
998 Py_ssize_t i = PyNumber_AsSsize_t(key, PyExc_IndexError);
999 if (i == -1 && PyErr_Occurred())
1001 return prop_subscript_array_int(self, PyLong_AsSsize_t(key));
1003 else if (PySlice_Check(key)) {
1004 Py_ssize_t start, stop, step, slicelength;
1005 int len = pyrna_prop_array_length(self);
1007 if (PySlice_GetIndicesEx((PySliceObject*)key, len, &start, &stop, &step, &slicelength) < 0)
1010 if (slicelength <= 0) {
1011 return PyList_New(0);
1013 else if (step == 1) {
1014 return prop_subscript_array_slice(self, start, stop);
1017 PyErr_SetString(PyExc_TypeError, "slice steps not supported with rna");
1022 PyErr_SetString(PyExc_AttributeError, "invalid key, key must be an int");
1027 static PyObject *pyrna_prop_subscript( BPy_PropertyRNA *self, PyObject *key )
1029 if (RNA_property_type(self->prop) == PROP_COLLECTION) {
1030 return prop_subscript_collection(self, key);
1031 } else if (RNA_property_array_check(&self->ptr, self->prop)) {
1032 return prop_subscript_array(self, key);
1035 PyErr_SetString(PyExc_TypeError, "rna type is not an array or a collection");
1039 static int prop_subscript_ass_array_slice(BPy_PropertyRNA *self, int begin, int end, PyObject *value)
1043 /* values are clamped from */
1044 begin = MIN2(begin,end);
1046 for(count = begin; count < end; count++) {
1047 if(pyrna_py_to_prop_index(self, count - begin, value) == -1) {
1048 /* TODO - this is wrong since some values have been assigned... will need to fix that */
1049 return -1; /* pyrna_struct_CreatePyObject should set the error */
1056 static int prop_subscript_ass_array_int(BPy_PropertyRNA *self, int keynum, PyObject *value)
1058 int len= pyrna_prop_array_length(self);
1060 if(keynum < 0) keynum += len;
1062 if(keynum >= 0 && keynum < len)
1063 return pyrna_py_to_prop_index(self, keynum, value);
1065 PyErr_SetString(PyExc_IndexError, "out of range");
1069 static int pyrna_prop_ass_subscript( BPy_PropertyRNA *self, PyObject *key, PyObject *value )
1071 /* char *keyname = NULL; */ /* not supported yet */
1073 if (!RNA_property_editable(&self->ptr, self->prop)) {
1074 PyErr_Format( PyExc_AttributeError, "PropertyRNA - attribute \"%.200s\" from \"%.200s\" is read-only", RNA_property_identifier(self->prop), RNA_struct_identifier(self->ptr.type) );
1078 /* maybe one day we can support this... */
1079 if (RNA_property_type(self->prop) == PROP_COLLECTION) {
1080 PyErr_Format( PyExc_AttributeError, "PropertyRNA - attribute \"%.200s\" from \"%.200s\" is a collection, assignment not supported", RNA_property_identifier(self->prop), RNA_struct_identifier(self->ptr.type) );
1084 if (PyIndex_Check(key)) {
1085 Py_ssize_t i = PyNumber_AsSsize_t(key, PyExc_IndexError);
1086 if (i == -1 && PyErr_Occurred())
1089 return prop_subscript_ass_array_int(self, i, value);
1091 else if (PySlice_Check(key)) {
1092 int len= RNA_property_array_length(&self->ptr, self->prop);
1093 Py_ssize_t start, stop, step, slicelength;
1095 if (PySlice_GetIndicesEx((PySliceObject*)key, len, &start, &stop, &step, &slicelength) < 0)
1098 if (slicelength <= 0) {
1101 else if (step == 1) {
1102 return prop_subscript_ass_array_slice(self, start, stop, value);
1105 PyErr_SetString(PyExc_TypeError, "slice steps not supported with rna");
1110 PyErr_SetString(PyExc_AttributeError, "invalid key, key must be an int");
1116 static PyMappingMethods pyrna_prop_as_mapping = {
1117 ( lenfunc ) pyrna_prop_len, /* mp_length */
1118 ( binaryfunc ) pyrna_prop_subscript, /* mp_subscript */
1119 ( objobjargproc ) pyrna_prop_ass_subscript, /* mp_ass_subscript */
1122 static int pyrna_prop_contains(BPy_PropertyRNA *self, PyObject *value)
1124 PointerRNA newptr; /* not used, just so RNA_property_collection_lookup_string runs */
1125 char *keyname = _PyUnicode_AsString(value);
1128 PyErr_SetString(PyExc_TypeError, "PropertyRNA - key in prop, key must be a string type");
1132 if (RNA_property_type(self->prop) != PROP_COLLECTION) {
1133 PyErr_SetString(PyExc_TypeError, "PropertyRNA - key in prop, is only valid for collection types");
1138 if (RNA_property_collection_lookup_string(&self->ptr, self->prop, keyname, &newptr))
1144 static int pyrna_struct_contains(BPy_StructRNA *self, PyObject *value)
1147 char *name = _PyUnicode_AsString(value);
1150 PyErr_SetString( PyExc_TypeError, "expected a string");
1154 if(RNA_struct_idproperties_check(&self->ptr)==0) {
1155 PyErr_SetString( PyExc_TypeError, "this type doesnt support IDProperties");
1159 group= RNA_struct_idproperties(&self->ptr, 0);
1164 return IDP_GetPropertyFromGroup(group, name) ? 1:0;
1167 static PyObject *pyrna_prop_item(BPy_PropertyRNA *self, Py_ssize_t index)
1169 /* reuse subscript functions */
1170 if (RNA_property_type(self->prop) == PROP_COLLECTION) {
1171 return prop_subscript_collection_int(self, index);
1172 } else if (RNA_property_array_check(&self->ptr, self->prop)) {
1173 return prop_subscript_array_int(self, index);
1176 PyErr_SetString(PyExc_TypeError, "rna type is not an array or a collection");
1180 static PySequenceMethods pyrna_prop_as_sequence = {
1181 NULL, /* Cant set the len otherwise it can evaluate as false */
1182 NULL, /* sq_concat */
1183 NULL, /* sq_repeat */
1184 (ssizeargfunc)pyrna_prop_item, /* sq_item */ /* Only set this so PySequence_Check() returns True */
1185 NULL, /* sq_slice */
1186 NULL, /* sq_ass_item */
1187 NULL, /* sq_ass_slice */
1188 (objobjproc)pyrna_prop_contains, /* sq_contains */
1191 static PySequenceMethods pyrna_struct_as_sequence = {
1192 NULL, /* Cant set the len otherwise it can evaluate as false */
1193 NULL, /* sq_concat */
1194 NULL, /* sq_repeat */
1195 NULL, /* sq_item */ /* Only set this so PySequence_Check() returns True */
1196 NULL, /* sq_slice */
1197 NULL, /* sq_ass_item */
1198 NULL, /* sq_ass_slice */
1199 (objobjproc)pyrna_struct_contains, /* sq_contains */
1202 static PyObject *pyrna_struct_subscript( BPy_StructRNA *self, PyObject *key )
1204 /* mostly copied from BPy_IDGroup_Map_GetItem */
1205 IDProperty *group, *idprop;
1206 char *name= _PyUnicode_AsString(key);
1208 if(RNA_struct_idproperties_check(&self->ptr)==0) {
1209 PyErr_SetString( PyExc_TypeError, "this type doesn't support IDProperties");
1214 PyErr_SetString( PyExc_TypeError, "only strings are allowed as keys of ID properties");
1218 group= RNA_struct_idproperties(&self->ptr, 0);
1221 PyErr_Format( PyExc_TypeError, "key \"%s\" not found", name);
1225 idprop= IDP_GetPropertyFromGroup(group, name);
1228 PyErr_Format( PyExc_TypeError, "key \"%s\" not found", name);
1232 return BPy_IDGroup_WrapData(self->ptr.id.data, idprop);
1235 static int pyrna_struct_ass_subscript( BPy_StructRNA *self, PyObject *key, PyObject *value )
1237 IDProperty *group= RNA_struct_idproperties(&self->ptr, 1);
1240 PyErr_SetString(PyExc_TypeError, "id properties not supported for this type");
1244 return BPy_Wrap_SetMapItem(group, key, value);
1247 static PyMappingMethods pyrna_struct_as_mapping = {
1248 ( lenfunc ) NULL, /* mp_length */
1249 ( binaryfunc ) pyrna_struct_subscript, /* mp_subscript */
1250 ( objobjargproc ) pyrna_struct_ass_subscript, /* mp_ass_subscript */
1253 static PyObject *pyrna_struct_keys(BPy_PropertyRNA *self)
1257 if(RNA_struct_idproperties_check(&self->ptr)==0) {
1258 PyErr_SetString( PyExc_TypeError, "this type doesnt support IDProperties");
1262 group= RNA_struct_idproperties(&self->ptr, 0);
1265 return PyList_New(0);
1267 return BPy_Wrap_GetKeys(group);
1270 static PyObject *pyrna_struct_items(BPy_PropertyRNA *self)
1274 if(RNA_struct_idproperties_check(&self->ptr)==0) {
1275 PyErr_SetString( PyExc_TypeError, "this type doesnt support IDProperties");
1279 group= RNA_struct_idproperties(&self->ptr, 0);
1282 return PyList_New(0);
1284 return BPy_Wrap_GetItems(self->ptr.id.data, group);
1288 static PyObject *pyrna_struct_values(BPy_PropertyRNA *self)
1292 if(RNA_struct_idproperties_check(&self->ptr)==0) {
1293 PyErr_SetString( PyExc_TypeError, "this type doesnt support IDProperties");
1297 group= RNA_struct_idproperties(&self->ptr, 0);
1300 return PyList_New(0);
1302 return BPy_Wrap_GetValues(self->ptr.id.data, group);
1305 static PyObject *pyrna_struct_keyframe_insert(BPy_StructRNA *self, PyObject *args)
1307 char *path, *path_full;
1308 int index= -1; /* default to all */
1309 float cfra = CTX_data_scene(BPy_GetContext())->r.cfra;
1313 if (!PyArg_ParseTuple(args, "s|if:keyframe_insert", &path, &index, &cfra))
1316 if (self->ptr.data==NULL) {
1317 PyErr_Format( PyExc_TypeError, "keyframe_insert, this struct has no data, cant be animated", path);
1321 prop = RNA_struct_find_property(&self->ptr, path);
1324 PyErr_Format( PyExc_TypeError, "keyframe_insert, property \"%s\" not found", path);
1328 if (!RNA_property_animateable(&self->ptr, prop)) {
1329 PyErr_Format( PyExc_TypeError, "keyframe_insert, property \"%s\" not animatable", path);
1333 path_full= RNA_path_from_ID_to_property(&self->ptr, prop);
1335 if (path_full==NULL) {
1336 PyErr_Format( PyExc_TypeError, "keyframe_insert, could not make path to \"%s\"", path);
1340 result= PyBool_FromLong( insert_keyframe((ID *)self->ptr.id.data, NULL, NULL, path_full, index, cfra, 0));
1341 MEM_freeN(path_full);
1347 static PyObject *pyrna_struct_driver_add(BPy_StructRNA *self, PyObject *args)
1349 char *path, *path_full;
1350 int index= -1; /* default to all */
1354 if (!PyArg_ParseTuple(args, "s|i:driver_add", &path, &index))
1357 if (self->ptr.data==NULL) {
1358 PyErr_Format( PyExc_TypeError, "driver_add, this struct has no data, cant be animated", path);
1362 prop = RNA_struct_find_property(&self->ptr, path);
1365 PyErr_Format( PyExc_TypeError, "driver_add, property \"%s\" not found", path);
1369 if (!RNA_property_animateable(&self->ptr, prop)) {
1370 PyErr_Format( PyExc_TypeError, "driver_add, property \"%s\" not animatable", path);
1374 path_full= RNA_path_from_ID_to_property(&self->ptr, prop);
1376 if (path_full==NULL) {
1377 PyErr_Format( PyExc_TypeError, "driver_add, could not make path to \"%s\"", path);
1381 result= PyBool_FromLong( ANIM_add_driver((ID *)self->ptr.id.data, path_full, index, 0, DRIVER_TYPE_PYTHON));
1382 MEM_freeN(path_full);
1388 static PyObject *pyrna_struct_is_property_set(BPy_StructRNA *self, PyObject *args)
1392 if (!PyArg_ParseTuple(args, "s:is_property_set", &name))
1395 return PyBool_FromLong(RNA_property_is_set(&self->ptr, name));
1398 static PyObject *pyrna_struct_is_property_hidden(BPy_StructRNA *self, PyObject *args)
1404 if (!PyArg_ParseTuple(args, "s:is_property_hidden", &name))
1407 prop= RNA_struct_find_property(&self->ptr, name);
1408 hidden= (prop)? (RNA_property_flag(prop) & PROP_HIDDEN): 1;
1410 return PyBool_FromLong(hidden);
1413 static PyObject *pyrna_struct_path_resolve(BPy_StructRNA *self, PyObject *value)
1415 char *path= _PyUnicode_AsString(value);
1417 PropertyRNA *r_prop;
1420 PyErr_SetString( PyExc_TypeError, "items() is only valid for collection types" );
1424 if (RNA_path_resolve(&self->ptr, path, &r_ptr, &r_prop))
1425 return pyrna_prop_CreatePyObject(&r_ptr, r_prop);
1430 static PyObject *pyrna_struct_dir(BPy_StructRNA *self)
1432 PyObject *ret, *dict;
1435 /* for looping over attrs and funcs */
1436 PropertyRNA *iterprop;
1438 /* Include this incase this instance is a subtype of a python class
1439 * In these instances we may want to return a function or variable provided by the subtype
1442 if (BPy_StructRNA_CheckExact(self)) {
1443 ret = PyList_New(0);
1445 pystring = PyUnicode_FromString("__dict__");
1446 dict = PyObject_GenericGetAttr((PyObject *)self, pystring);
1447 Py_DECREF(pystring);
1451 ret = PyList_New(0);
1454 ret = PyDict_Keys(dict);
1459 /* Collect RNA items*/
1462 * Collect RNA attributes
1464 char name[256], *nameptr;
1466 iterprop= RNA_struct_iterator_property(self->ptr.type);
1468 RNA_PROP_BEGIN(&self->ptr, itemptr, iterprop) {
1469 nameptr= RNA_struct_name_get_alloc(&itemptr, name, sizeof(name));
1472 pystring = PyUnicode_FromString(nameptr);
1473 PyList_Append(ret, pystring);
1474 Py_DECREF(pystring);
1486 * Collect RNA function items
1491 RNA_pointer_create(NULL, &RNA_Struct, self->ptr.type, &tptr);
1492 iterprop= RNA_struct_find_property(&tptr, "functions");
1494 RNA_PROP_BEGIN(&tptr, itemptr, iterprop) {
1495 idname= RNA_function_identifier(itemptr.data);
1497 pystring = PyUnicode_FromString(idname);
1498 PyList_Append(ret, pystring);
1499 Py_DECREF(pystring);
1504 if(self->ptr.type == &RNA_Context) {
1505 ListBase lb = CTX_data_dir_get(self->ptr.data);
1508 for(link=lb.first; link; link=link->next) {
1509 pystring = PyUnicode_FromString(link->data);
1510 PyList_Append(ret, pystring);
1511 Py_DECREF(pystring);
1517 /* Hard coded names */
1518 if(self->ptr.id.data) {
1519 pystring = PyUnicode_FromString("id_data");
1520 PyList_Append(ret, pystring);
1521 Py_DECREF(pystring);
1527 //---------------getattr--------------------------------------------
1528 static PyObject *pyrna_struct_getattro( BPy_StructRNA *self, PyObject *pyname )
1530 char *name = _PyUnicode_AsString(pyname);
1535 if(name[0]=='_') { // rna can't start with a "_", so for __dict__ and similar we can skip using rna lookups
1536 /* annoying exception, maybe we need to have different types for this... */
1537 if((strcmp(name, "__getitem__")==0 || strcmp(name, "__setitem__")==0) && !RNA_struct_idproperties_check(&self->ptr)) {
1538 PyErr_SetString(PyExc_AttributeError, "StructRNA - no __getitem__ support for this type");
1542 ret = PyObject_GenericGetAttr((PyObject *)self, pyname);
1545 else if ((prop = RNA_struct_find_property(&self->ptr, name))) {
1546 ret = pyrna_prop_to_py(&self->ptr, prop);
1548 else if ((func = RNA_struct_find_function(&self->ptr, name))) {
1549 ret = pyrna_func_to_py((BPy_DummyPointerRNA *)self, func);
1551 else if (self->ptr.type == &RNA_Context) {
1556 done= CTX_data_get(self->ptr.data, name, &newptr, &newlb);
1558 if(done==1) { /* found */
1560 ret = pyrna_struct_CreatePyObject(&newptr);
1562 else if (newlb.first) {
1563 CollectionPointerLink *link;
1566 ret = PyList_New(0);
1568 for(link=newlb.first; link; link=link->next) {
1569 linkptr= pyrna_struct_CreatePyObject(&link->ptr);
1570 PyList_Append(ret, linkptr);
1579 else if (done==-1) { /* found but not set */
1583 else { /* not found in the context */
1584 /* lookup the subclass. raise an error if its not found */
1585 ret = PyObject_GenericGetAttr((PyObject *)self, pyname);
1588 BLI_freelistN(&newlb);
1590 else if (strcmp(name, "id_data")==0) { /* XXX - hard coded */
1591 if(self->ptr.id.data) {
1593 RNA_id_pointer_create((ID *)self->ptr.id.data, &id_ptr);
1594 ret = pyrna_struct_CreatePyObject(&id_ptr);
1603 PyErr_Format( PyExc_AttributeError, "StructRNA - Attribute \"%.200s\" not found", name);
1606 /* Include this incase this instance is a subtype of a python class
1607 * In these instances we may want to return a function or variable provided by the subtype
1609 * Also needed to return methods when its not a subtype
1612 /* The error raised here will be displayed */
1613 ret = PyObject_GenericGetAttr((PyObject *)self, pyname);
1619 //--------------- setattr-------------------------------------------
1620 static int pyrna_struct_setattro( BPy_StructRNA *self, PyObject *pyname, PyObject *value )
1622 char *name = _PyUnicode_AsString(pyname);
1623 PropertyRNA *prop = RNA_struct_find_property(&self->ptr, name);
1626 // XXX - This currently allows anything to be assigned to an rna prop, need to see how this should be used
1627 // but for now it makes porting scripts confusing since it fails silently.
1628 // edit: allowing this for setting classes internal attributes.
1629 if (name[0]=='_' && !BPy_StructRNA_CheckExact(self) && PyObject_GenericSetAttr((PyObject *)self, pyname, value) >= 0) {
1633 PyErr_Format( PyExc_AttributeError, "StructRNA - Attribute \"%.200s\" not found", name);
1638 if (!RNA_property_editable(&self->ptr, prop)) {
1639 PyErr_Format( PyExc_AttributeError, "StructRNA - Attribute \"%.200s\" from \"%.200s\" is read-only", RNA_property_identifier(prop), RNA_struct_identifier(self->ptr.type) );
1643 /* pyrna_py_to_prop sets its own exceptions */
1644 return pyrna_py_to_prop(&self->ptr, prop, NULL, value, "StructRNA - item.attr = val:");
1647 static PyObject *pyrna_prop_getattro( BPy_PropertyRNA *self, PyObject *pyname )
1649 char *name = _PyUnicode_AsString(pyname);
1651 if(name[0] != '_') {
1652 if (RNA_property_type(self->prop) == PROP_COLLECTION) {
1658 if(RNA_property_collection_type_get(&self->ptr, self->prop, &r_ptr)) {
1659 if ((prop = RNA_struct_find_property(&r_ptr, name))) {
1660 ret = pyrna_prop_to_py(&r_ptr, prop);
1664 else if ((func = RNA_struct_find_function(&r_ptr, name))) {
1665 PyObject *self_collection= pyrna_struct_CreatePyObject(&r_ptr);
1666 ret = pyrna_func_to_py((BPy_DummyPointerRNA *)self_collection, func);
1667 Py_DECREF(self_collection);
1675 /* The error raised here will be displayed */
1676 return PyObject_GenericGetAttr((PyObject *)self, pyname);
1679 //--------------- setattr-------------------------------------------
1680 static int pyrna_prop_setattro( BPy_PropertyRNA *self, PyObject *pyname, PyObject *value )
1682 char *name = _PyUnicode_AsString(pyname);
1685 if (RNA_property_type(self->prop) == PROP_COLLECTION) {
1687 if(RNA_property_collection_type_get(&self->ptr, self->prop, &r_ptr)) {
1688 if ((prop = RNA_struct_find_property(&r_ptr, name))) {
1689 /* pyrna_py_to_prop sets its own exceptions */
1690 return pyrna_py_to_prop(&r_ptr, prop, NULL, value, "BPy_PropertyRNA - Attribute (setattr):");
1695 PyErr_Format( PyExc_AttributeError, "BPy_PropertyRNA - Attribute \"%.200s\" not found", name);
1699 /* odd case, we need to be able return a python method from a tp_getset */
1700 static PyObject *pyrna_prop_add(BPy_PropertyRNA *self)
1704 RNA_property_collection_add(&self->ptr, self->prop, &r_ptr);
1706 PyErr_SetString( PyExc_TypeError, "add() not supported for this collection");
1710 return pyrna_struct_CreatePyObject(&r_ptr);
1714 static PyObject *pyrna_prop_remove(BPy_PropertyRNA *self, PyObject *value)
1717 int key= PyLong_AsSsize_t(value);
1719 if (key==-1 && PyErr_Occurred()) {
1720 PyErr_SetString( PyExc_TypeError, "remove() expected one int argument");
1724 if(!RNA_property_collection_remove(&self->ptr, self->prop, key)) {
1725 PyErr_SetString( PyExc_TypeError, "remove() not supported for this collection");
1735 /*****************************************************************************/
1736 /* Python attributes get/set structure: */
1737 /*****************************************************************************/
1739 static PyGetSetDef pyrna_prop_getseters[] = {
1740 {"active", (getter)pyrna_prop_get_active, (setter)pyrna_prop_set_active, "", NULL},
1741 {NULL,NULL,NULL,NULL,NULL} /* Sentinel */
1745 static PyObject *pyrna_prop_keys(BPy_PropertyRNA *self)
1748 if (RNA_property_type(self->prop) != PROP_COLLECTION) {
1749 PyErr_SetString( PyExc_TypeError, "keys() is only valid for collection types" );
1753 char name[256], *nameptr;
1755 ret = PyList_New(0);
1757 RNA_PROP_BEGIN(&self->ptr, itemptr, self->prop) {
1758 nameptr= RNA_struct_name_get_alloc(&itemptr, name, sizeof(name));
1761 /* add to python list */
1762 item = PyUnicode_FromString( nameptr );
1763 PyList_Append(ret, item);
1777 static PyObject *pyrna_prop_items(BPy_PropertyRNA *self)
1780 if (RNA_property_type(self->prop) != PROP_COLLECTION) {
1781 PyErr_SetString( PyExc_TypeError, "items() is only valid for collection types" );
1785 char name[256], *nameptr;
1788 ret = PyList_New(0);
1790 RNA_PROP_BEGIN(&self->ptr, itemptr, self->prop) {
1792 /* add to python list */
1793 item= PyTuple_New(2);
1794 nameptr= RNA_struct_name_get_alloc(&itemptr, name, sizeof(name));
1796 PyTuple_SET_ITEM(item, 0, PyUnicode_FromString( nameptr ));
1801 PyTuple_SET_ITEM(item, 0, PyLong_FromSsize_t(i)); /* a bit strange but better then returning an empty list */
1803 PyTuple_SET_ITEM(item, 1, pyrna_struct_CreatePyObject(&itemptr));
1805 PyList_Append(ret, item);
1818 static PyObject *pyrna_prop_values(BPy_PropertyRNA *self)
1822 if (RNA_property_type(self->prop) != PROP_COLLECTION) {
1823 PyErr_SetString( PyExc_TypeError, "values() is only valid for collection types" );
1827 ret = PyList_New(0);
1829 RNA_PROP_BEGIN(&self->ptr, itemptr, self->prop) {
1830 item = pyrna_struct_CreatePyObject(&itemptr);
1831 PyList_Append(ret, item);
1840 static PyObject *pyrna_prop_get(BPy_PropertyRNA *self, PyObject *args)
1845 PyObject* def = Py_None;
1847 if (!PyArg_ParseTuple(args, "s|O:get", &key, &def))
1850 if(RNA_property_collection_lookup_string(&self->ptr, self->prop, key, &newptr))
1851 return pyrna_struct_CreatePyObject(&newptr);
1857 static void foreach_attr_type( BPy_PropertyRNA *self, char *attr,
1858 /* values to assign */
1859 RawPropertyType *raw_type, int *attr_tot, int *attr_signed )
1864 *attr_signed= FALSE;
1866 RNA_PROP_BEGIN(&self->ptr, itemptr, self->prop) {
1867 prop = RNA_struct_find_property(&itemptr, attr);
1868 *raw_type= RNA_property_raw_type(prop);
1869 *attr_tot = RNA_property_array_length(&itemptr, prop);
1870 *attr_signed= (RNA_property_subtype(prop)==PROP_UNSIGNED) ? FALSE:TRUE;
1876 /* pyrna_prop_foreach_get/set both use this */
1877 static int foreach_parse_args(
1878 BPy_PropertyRNA *self, PyObject *args,
1880 /*values to assign */
1881 char **attr, PyObject **seq, int *tot, int *size, RawPropertyType *raw_type, int *attr_tot, int *attr_signed)
1888 *size= *raw_type= *attr_tot= *attr_signed= FALSE;
1890 if(!PyArg_ParseTuple(args, "sO", attr, seq) || (!PySequence_Check(*seq) && PyObject_CheckBuffer(*seq))) {
1891 PyErr_SetString( PyExc_TypeError, "foreach_get(attr, sequence) expects a string and a sequence" );
1895 *tot= PySequence_Length(*seq); // TODO - buffer may not be a sequence! array.array() is tho.
1898 foreach_attr_type(self, *attr, raw_type, attr_tot, attr_signed);
1899 *size= RNA_raw_type_sizeof(*raw_type);
1901 #if 0 // works fine but not strictly needed, we could allow RNA_property_collection_raw_* to do the checks
1905 if (RNA_property_type(self->prop) == PROP_COLLECTION)
1906 array_tot = RNA_property_collection_length(&self->ptr, self->prop);
1908 array_tot = RNA_property_array_length(&self->ptr, self->prop);
1911 target_tot= array_tot * (*attr_tot);
1913 /* rna_access.c - rna_raw_access(...) uses this same method */
1914 if(target_tot != (*tot)) {
1915 PyErr_Format( PyExc_TypeError, "foreach_get(attr, sequence) sequence length mismatch given %d, needed %d", *tot, target_tot);
1924 static int foreach_compat_buffer(RawPropertyType raw_type, int attr_signed, const char *format)
1926 char f = format ? *format:'B'; /* B is assumed when not set */
1930 if (attr_signed) return (f=='b') ? 1:0;
1931 else return (f=='B') ? 1:0;
1932 case PROP_RAW_SHORT:
1933 if (attr_signed) return (f=='h') ? 1:0;
1934 else return (f=='H') ? 1:0;
1936 if (attr_signed) return (f=='i') ? 1:0;
1937 else return (f=='I') ? 1:0;
1938 case PROP_RAW_FLOAT:
1939 return (f=='f') ? 1:0;
1940 case PROP_RAW_DOUBLE:
1941 return (f=='d') ? 1:0;
1947 static PyObject *foreach_getset(BPy_PropertyRNA *self, PyObject *args, int set)
1949 PyObject *item = NULL;
1950 int i=0, ok=0, buffer_is_compat;
1953 /* get/set both take the same args currently */
1956 int tot, size, attr_tot, attr_signed;
1957 RawPropertyType raw_type;
1959 if(foreach_parse_args(self, args, &attr, &seq, &tot, &size, &raw_type, &attr_tot, &attr_signed) < 0)
1967 if(set) { /* get the array from python */
1968 buffer_is_compat = FALSE;
1969 if(PyObject_CheckBuffer(seq)) {
1971 PyObject_GetBuffer(seq, &buf, PyBUF_SIMPLE | PyBUF_FORMAT);
1973 /* check if the buffer matches */
1975 buffer_is_compat = foreach_compat_buffer(raw_type, attr_signed, buf.format);
1977 if(buffer_is_compat) {
1978 ok = RNA_property_collection_raw_set(NULL, &self->ptr, self->prop, attr, buf.buf, raw_type, tot);
1981 PyBuffer_Release(&buf);
1984 /* could not use the buffer, fallback to sequence */
1985 if(!buffer_is_compat) {
1986 array= PyMem_Malloc(size * tot);
1988 for( ; i<tot; i++) {
1989 item= PySequence_GetItem(seq, i);
1992 ((char *)array)[i]= (char)PyLong_AsSsize_t(item);
1994 case PROP_RAW_SHORT:
1995 ((short *)array)[i]= (short)PyLong_AsSsize_t(item);
1998 ((int *)array)[i]= (int)PyLong_AsSsize_t(item);
2000 case PROP_RAW_FLOAT:
2001 ((float *)array)[i]= (float)PyFloat_AsDouble(item);
2003 case PROP_RAW_DOUBLE:
2004 ((double *)array)[i]= (double)PyFloat_AsDouble(item);
2011 ok = RNA_property_collection_raw_set(NULL, &self->ptr, self->prop, attr, array, raw_type, tot);
2015 buffer_is_compat = FALSE;
2016 if(PyObject_CheckBuffer(seq)) {
2018 PyObject_GetBuffer(seq, &buf, PyBUF_SIMPLE | PyBUF_FORMAT);
2020 /* check if the buffer matches, TODO - signed/unsigned types */
2022 buffer_is_compat = foreach_compat_buffer(raw_type, attr_signed, buf.format);
2024 if(buffer_is_compat) {
2025 ok = RNA_property_collection_raw_get(NULL, &self->ptr, self->prop, attr, buf.buf, raw_type, tot);
2028 PyBuffer_Release(&buf);
2031 /* could not use the buffer, fallback to sequence */
2032 if(!buffer_is_compat) {
2033 array= PyMem_Malloc(size * tot);
2035 ok = RNA_property_collection_raw_get(NULL, &self->ptr, self->prop, attr, array, raw_type, tot);
2037 if(!ok) i= tot; /* skip the loop */
2039 for( ; i<tot; i++) {
2043 item= PyLong_FromSsize_t( (Py_ssize_t) ((char *)array)[i] );
2045 case PROP_RAW_SHORT:
2046 item= PyLong_FromSsize_t( (Py_ssize_t) ((short *)array)[i] );
2049 item= PyLong_FromSsize_t( (Py_ssize_t) ((int *)array)[i] );
2051 case PROP_RAW_FLOAT:
2052 item= PyFloat_FromDouble( (double) ((float *)array)[i] );
2054 case PROP_RAW_DOUBLE:
2055 item= PyFloat_FromDouble( (double) ((double *)array)[i] );
2059 PySequence_SetItem(seq, i, item);
2065 if(PyErr_Occurred()) {
2066 /* Maybe we could make our own error */
2068 PyErr_SetString(PyExc_SystemError, "could not access the py sequence");
2072 PyErr_SetString(PyExc_SystemError, "internal error setting the array");
2082 static PyObject *pyrna_prop_foreach_get(BPy_PropertyRNA *self, PyObject *args)
2084 return foreach_getset(self, args, 0);
2087 static PyObject *pyrna_prop_foreach_set(BPy_PropertyRNA *self, PyObject *args)
2089 return foreach_getset(self, args, 1);
2092 /* A bit of a kludge, make a list out of a collection or array,
2093 * then return the lists iter function, not especially fast but convenient for now */
2094 PyObject *pyrna_prop_iter(BPy_PropertyRNA *self)
2096 /* Try get values from a collection */
2100 if(RNA_property_array_check(&self->ptr, self->prop)) {
2101 int len = pyrna_prop_array_length(self);
2104 ret = PyList_New(len);
2106 for (i=0; i < len; i++) {
2107 PyList_SET_ITEM(ret, i, pyrna_prop_to_py_index(self, i));
2110 else if ((ret = pyrna_prop_values(self))) {
2114 PyErr_SetString( PyExc_TypeError, "this BPy_PropertyRNA object is not iterable" );
2119 /* we know this is a list so no need to PyIter_Check */
2120 iter = PyObject_GetIter(ret);
2125 static struct PyMethodDef pyrna_struct_methods[] = {
2127 /* only for PointerRNA's with ID'props */
2128 {"keys", (PyCFunction)pyrna_struct_keys, METH_NOARGS, NULL},
2129 {"values", (PyCFunction)pyrna_struct_values, METH_NOARGS, NULL},
2130 {"items", (PyCFunction)pyrna_struct_items, METH_NOARGS, NULL},
2132 /* maybe this become and ID function */
2133 {"keyframe_insert", (PyCFunction)pyrna_struct_keyframe_insert, METH_VARARGS, NULL},
2134 {"driver_add", (PyCFunction)pyrna_struct_driver_add, METH_VARARGS, NULL},
2135 {"is_property_set", (PyCFunction)pyrna_struct_is_property_set, METH_VARARGS, NULL},
2136 {"is_property_hidden", (PyCFunction)pyrna_struct_is_property_hidden, METH_VARARGS, NULL},
2137 {"path_resolve", (PyCFunction)pyrna_struct_path_resolve, METH_O, NULL},
2138 {"__dir__", (PyCFunction)pyrna_struct_dir, METH_NOARGS, NULL},
2139 {NULL, NULL, 0, NULL}
2142 static struct PyMethodDef pyrna_prop_methods[] = {
2143 {"keys", (PyCFunction)pyrna_prop_keys, METH_NOARGS, NULL},
2144 {"items", (PyCFunction)pyrna_prop_items, METH_NOARGS,NULL},
2145 {"values", (PyCFunction)pyrna_prop_values, METH_NOARGS, NULL},
2147 {"get", (PyCFunction)pyrna_prop_get, METH_VARARGS, NULL},
2149 /* moved into a getset */
2150 {"add", (PyCFunction)pyrna_prop_add, METH_NOARGS, NULL},
2151 {"remove", (PyCFunction)pyrna_prop_remove, METH_O, NULL},
2153 /* array accessor function */
2154 {"foreach_get", (PyCFunction)pyrna_prop_foreach_get, METH_VARARGS, NULL},
2155 {"foreach_set", (PyCFunction)pyrna_prop_foreach_set, METH_VARARGS, NULL},
2156 {NULL, NULL, 0, NULL}
2159 /* only needed for subtyping, so a new class gets a valid BPy_StructRNA
2160 * todo - also accept useful args */
2161 static PyObject * pyrna_struct_new(PyTypeObject *type, PyObject *args, PyObject *kwds) {
2163 BPy_StructRNA *base = NULL;
2165 if (!PyArg_ParseTuple(args, "O!:Base BPy_StructRNA", &pyrna_struct_Type, &base))
2168 if (type == &pyrna_struct_Type) {
2169 return pyrna_struct_CreatePyObject(&base->ptr);
2171 BPy_StructRNA *ret = (BPy_StructRNA *) type->tp_alloc(type, 0);
2172 ret->ptr = base->ptr;
2173 return (PyObject *)ret;
2177 /* only needed for subtyping, so a new class gets a valid BPy_StructRNA
2178 * todo - also accept useful args */
2179 static PyObject * pyrna_prop_new(PyTypeObject *type, PyObject *args, PyObject *kwds) {
2181 BPy_PropertyRNA *base = NULL;
2183 if (!PyArg_ParseTuple(args, "O!:Base BPy_PropertyRNA", &pyrna_prop_Type, &base))
2186 if (type == &pyrna_prop_Type) {
2187 return pyrna_prop_CreatePyObject(&base->ptr, base->prop);
2189 BPy_PropertyRNA *ret = (BPy_PropertyRNA *) type->tp_alloc(type, 0);
2190 ret->ptr = base->ptr;
2191 ret->prop = base->prop;
2192 return (PyObject *)ret;
2196 PyObject *pyrna_param_to_py(PointerRNA *ptr, PropertyRNA *prop, void *data)
2199 int type = RNA_property_type(prop);
2203 if(RNA_property_array_check(ptr, prop)) {
2204 int len = RNA_property_array_length(ptr, prop);
2206 /* resolve the array from a new pytype */
2207 ret = PyTuple_New(len);
2209 /* kazanbas: TODO make multidim sequences here */
2213 for(a=0; a<len; a++)
2214 PyTuple_SET_ITEM(ret, a, PyBool_FromLong( ((int*)data)[a] ));
2217 for(a=0; a<len; a++)
2218 PyTuple_SET_ITEM(ret, a, PyLong_FromSsize_t( (Py_ssize_t)((int*)data)[a] ));
2221 for(a=0; a<len; a++)
2222 PyTuple_SET_ITEM(ret, a, PyFloat_FromDouble( ((float*)data)[a] ));
2225 PyErr_Format(PyExc_TypeError, "RNA Error: unknown array type \"%d\" (pyrna_param_to_py)", type);
2231 /* see if we can coorce into a python type - PropertyType */
2234 ret = PyBool_FromLong( *(int*)data );
2237 ret = PyLong_FromSsize_t( (Py_ssize_t)*(int*)data );
2240 ret = PyFloat_FromDouble( *(float*)data );
2244 ret = PyUnicode_FromString( *(char**)data );
2249 const char *identifier;
2250 int val = *(int*)data;
2252 if (RNA_property_enum_identifier(BPy_GetContext(), ptr, prop, val, &identifier)) {
2253 ret = PyUnicode_FromString( identifier );
2255 /* prefer not fail silently incase of api errors, maybe disable it later */
2256 char error_str[128];
2257 sprintf(error_str, "RNA Warning: Current value \"%d\" matches no enum", val);
2258 PyErr_Warn(PyExc_RuntimeWarning, error_str);
2260 ret = PyUnicode_FromString( "" );
2261 /*PyErr_Format(PyExc_AttributeError, "RNA Error: Current value \"%d\" matches no enum", val);
2270 StructRNA *type= RNA_property_pointer_type(ptr, prop);
2271 int flag = RNA_property_flag(prop);
2273 if(flag & PROP_RNAPTR) {
2274 /* in this case we get the full ptr */
2275 newptr= *(PointerRNA*)data;
2278 if(RNA_struct_is_ID(type)) {
2279 RNA_id_pointer_create(*(void**)data, &newptr);
2281 /* note: this is taken from the function's ID pointer
2282 * and will break if a function returns a pointer from
2283 * another ID block, watch this! - it should at least be
2284 * easy to debug since they are all ID's */
2285 RNA_pointer_create(ptr->id.data, type, *(void**)data, &newptr);
2290 ret = pyrna_struct_CreatePyObject(&newptr);
2297 case PROP_COLLECTION:
2299 ListBase *lb= (ListBase*)data;
2300 CollectionPointerLink *link;
2303 ret = PyList_New(0);
2305 for(link=lb->first; link; link=link->next) {
2306 linkptr= pyrna_struct_CreatePyObject(&link->ptr);
2307 PyList_Append(ret, linkptr);
2314 PyErr_Format(PyExc_TypeError, "RNA Error: unknown type \"%d\" (pyrna_param_to_py)", type);
2323 static PyObject * pyrna_func_call(PyObject *self, PyObject *args, PyObject *kw)
2325 /* Note, both BPy_StructRNA and BPy_PropertyRNA can be used here */
2326 PointerRNA *self_ptr= &(((BPy_DummyPointerRNA *)PyTuple_GET_ITEM(self, 0))->ptr);
2327 FunctionRNA *self_func= PyCObject_AsVoidPtr(PyTuple_GET_ITEM(self, 1));
2330 ParameterList parms;
2331 ParameterIterator iter;
2332 PropertyRNA *pret, *parm;
2333 PyObject *ret, *item;
2334 int i, args_len, parms_len, flag, err= 0, kw_tot= 0, kw_arg;
2335 const char *parm_id;
2336 void *retdata= NULL;
2338 /* Should never happen but it does in rare cases */
2339 if(self_ptr==NULL) {
2340 PyErr_SetString(PyExc_RuntimeError, "rna functions internal rna pointer is NULL, this is a bug. aborting");
2344 if(self_func==NULL) {
2345 PyErr_Format(PyExc_RuntimeError, "%.200s.<unknown>(): rna function internal function is NULL, this is a bug. aborting", RNA_struct_identifier(self_ptr->type));
2349 /* include the ID pointer for pyrna_param_to_py() so we can include the
2350 * ID pointer on return values, this only works when returned values have
2351 * the same ID as the functions. */
2352 RNA_pointer_create(self_ptr->id.data, &RNA_Function, self_func, &funcptr);
2354 pret= RNA_function_return(self_func);
2355 args_len= PyTuple_GET_SIZE(args);
2357 RNA_parameter_list_create(&parms, self_ptr, self_func);
2358 RNA_parameter_list_begin(&parms, &iter);
2359 parms_len = RNA_parameter_list_size(&parms);
2361 if(args_len + (kw ? PyDict_Size(kw):0) > parms_len) {
2362 PyErr_Format(PyExc_TypeError, "%.200s.%.200s(): takes at most %d arguments, got %d", RNA_struct_identifier(self_ptr->type), RNA_function_identifier(self_func), parms_len, args_len);
2366 /* parse function parameters */
2367 for (i= 0; iter.valid && err==0; RNA_parameter_list_next(&iter)) {
2375 parm_id= RNA_property_identifier(parm);
2376 flag= RNA_property_flag(parm);
2379 if ((i < args_len) && (flag & PROP_REQUIRED)) {
2380 item= PyTuple_GET_ITEM(args, i);
2385 else if (kw != NULL) {
2386 item= PyDict_GetItemString(kw, parm_id); /* borrow ref */
2388 kw_tot++; /* make sure invalid keywords are not given */
2394 if(flag & PROP_REQUIRED) {
2395 PyErr_Format(PyExc_TypeError, "%.200s.%.200s(): required parameter \"%.200s\" not specified", RNA_struct_identifier(self_ptr->type), RNA_function_identifier(self_func), parm_id);
2399 else /* PyDict_GetItemString wont raise an error */
2403 err= pyrna_py_to_prop(&funcptr, parm, iter.data, item, "");
2406 /* the error generated isnt that useful, so generate it again with a useful prefix
2407 * could also write a function to prepend to error messages */
2408 char error_prefix[512];
2409 PyErr_Clear(); /* re-raise */
2412 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);
2414 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);
2416 pyrna_py_to_prop(&funcptr, parm, iter.data, item, error_prefix);
2423 /* Check if we gave args that dont exist in the function
2424 * printing the error is slow but it should only happen when developing.
2425 * the if below is quick, checking if it passed less keyword args then we gave.
2426 * (Dont overwrite the error if we have one, otherwise can skip important messages and confuse with args)
2428 if(err == 0 && kw && (PyDict_Size(kw) > kw_tot)) {
2429 PyObject *key, *value;
2432 DynStr *bad_args= BLI_dynstr_new();
2433 DynStr *good_args= BLI_dynstr_new();
2435 char *arg_name, *bad_args_str, *good_args_str;
2436 int found= FALSE, first= TRUE;
2438 while (PyDict_Next(kw, &pos, &key, &value)) {
2440 arg_name= _PyUnicode_AsString(key);
2443 if(arg_name==NULL) { /* unlikely the argname is not a string but ignore if it is*/
2447 /* Search for arg_name */
2448 RNA_parameter_list_begin(&parms, &iter);
2449 for(; iter.valid; RNA_parameter_list_next(&iter)) {
2451 if (strcmp(arg_name, RNA_property_identifier(parm))==0) {
2457 RNA_parameter_list_end(&iter);
2460 BLI_dynstr_appendf(bad_args, first ? "%s" : ", %s", arg_name);
2466 /* list good args */
2469 RNA_parameter_list_begin(&parms, &iter);
2470 for(; iter.valid; RNA_parameter_list_next(&iter)) {
2472 BLI_dynstr_appendf(good_args, first ? "%s" : ", %s", RNA_property_identifier(parm));
2475 RNA_parameter_list_end(&iter);
2478 bad_args_str= BLI_dynstr_get_cstring(bad_args);
2479 good_args_str= BLI_dynstr_get_cstring(good_args);
2481 PyErr_Format(PyExc_TypeError, "%.200s.%.200s(): was called with invalid keyword arguments(s) (%s), expected (%s)", RNA_struct_identifier(self_ptr->type), RNA_function_identifier(self_func), bad_args_str, good_args_str);
2483 BLI_dynstr_free(bad_args);
2484 BLI_dynstr_free(good_args);
2485 MEM_freeN(bad_args_str);
2486 MEM_freeN(good_args_str);
2495 bContext *C= BPy_GetContext();
2497 BKE_reports_init(&reports, RPT_STORE);
2498 RNA_function_call(C, &reports, self_ptr, self_func, &parms);
2500 err= (BPy_reports_to_error(&reports))? -1: 0;
2501 BKE_reports_clear(&reports);
2506 ret= pyrna_param_to_py(&funcptr, pret, retdata);
2508 /* possible there is an error in conversion */
2516 RNA_parameter_list_end(&iter);
2517 RNA_parameter_list_free(&parms);
2528 /*-----------------------BPy_StructRNA method def------------------------------*/
2529 PyTypeObject pyrna_struct_Type = {
2530 PyVarObject_HEAD_INIT(NULL, 0)
2531 "StructRNA", /* tp_name */
2532 sizeof( BPy_StructRNA ), /* tp_basicsize */
2533 0, /* tp_itemsize */
2535 ( destructor ) pyrna_struct_dealloc,/* tp_dealloc */
2536 NULL, /* printfunc tp_print; */
2537 NULL, /* getattrfunc tp_getattr; */
2538 NULL, /* setattrfunc tp_setattr; */
2539 NULL, /* tp_compare */ /* DEPRECATED in python 3.0! */
2540 ( reprfunc ) pyrna_struct_repr, /* tp_repr */
2542 /* Method suites for standard classes */
2544 NULL, /* PyNumberMethods *tp_as_number; */
2545 &pyrna_struct_as_sequence, /* PySequenceMethods *tp_as_sequence; */
2546 &pyrna_struct_as_mapping, /* PyMappingMethods *tp_as_mapping; */
2548 /* More standard operations (here for binary compatibility) */
2550 ( hashfunc )pyrna_struct_hash, /* hashfunc tp_hash; */
2551 NULL, /* ternaryfunc tp_call; */
2552 NULL, /* reprfunc tp_str; */
2553 ( getattrofunc ) pyrna_struct_getattro, /* getattrofunc tp_getattro; */
2554 ( setattrofunc ) pyrna_struct_setattro, /* setattrofunc tp_setattro; */
2556 /* Functions to access object as input/output buffer */
2557 NULL, /* PyBufferProcs *tp_as_buffer; */
2559 /*** Flags to define presence of optional/expanded features ***/
2560 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE, /* long tp_flags; */
2562 NULL, /* char *tp_doc; Documentation string */
2563 /*** Assigned meaning in release 2.0 ***/
2564 /* call function for all accessible objects */
2565 NULL, /* traverseproc tp_traverse; */
2567 /* delete references to contained objects */
2568 NULL, /* inquiry tp_clear; */
2570 /*** Assigned meaning in release 2.1 ***/
2571 /*** rich comparisons ***/
2572 (richcmpfunc)pyrna_struct_richcmp, /* richcmpfunc tp_richcompare; */
2574 /*** weak reference enabler ***/
2575 0, /* long tp_weaklistoffset; */
2577 /*** Added in release 2.2 ***/
2579 NULL, /* getiterfunc tp_iter; */
2580 NULL, /* iternextfunc tp_iternext; */
2582 /*** Attribute descriptor and subclassing stuff ***/
2583 pyrna_struct_methods, /* struct PyMethodDef *tp_methods; */
2584 NULL, /* struct PyMemberDef *tp_members; */
2585 NULL, /* struct PyGetSetDef *tp_getset; */
2586 NULL, /* struct _typeobject *tp_base; */
2587 NULL, /* PyObject *tp_dict; */
2588 NULL, /* descrgetfunc tp_descr_get; */
2589 NULL, /* descrsetfunc tp_descr_set; */
2590 0, /* long tp_dictoffset; */
2591 NULL, /* initproc tp_init; */
2592 NULL, /* allocfunc tp_alloc; */
2593 pyrna_struct_new, /* newfunc tp_new; */
2594 /* Low-level free-memory routine */
2595 NULL, /* freefunc tp_free; */
2596 /* For PyObject_IS_GC */
2597 NULL, /* inquiry tp_is_gc; */
2598 NULL, /* PyObject *tp_bases; */
2599 /* method resolution order */
2600 NULL, /* PyObject *tp_mro; */
2601 NULL, /* PyObject *tp_cache; */
2602 NULL, /* PyObject *tp_subclasses; */
2603 NULL, /* PyObject *tp_weaklist; */
2607 /*-----------------------BPy_PropertyRNA method def------------------------------*/
2608 PyTypeObject pyrna_prop_Type = {
2609 PyVarObject_HEAD_INIT(NULL, 0)
2610 "PropertyRNA", /* tp_name */
2611 sizeof( BPy_PropertyRNA ), /* tp_basicsize */
2612 0, /* tp_itemsize */
2614 NULL, /* tp_dealloc */
2615 NULL, /* printfunc tp_print; */
2616 NULL, /* getattrfunc tp_getattr; */
2617 NULL, /* setattrfunc tp_setattr; */
2618 NULL, /* tp_compare */ /* DEPRECATED in python 3.0! */
2619 ( reprfunc ) pyrna_prop_repr, /* tp_repr */
2621 /* Method suites for standard classes */
2623 NULL, /* PyNumberMethods *tp_as_number; */
2624 &pyrna_prop_as_sequence, /* PySequenceMethods *tp_as_sequence; */
2625 &pyrna_prop_as_mapping, /* PyMappingMethods *tp_as_mapping; */
2627 /* More standard operations (here for binary compatibility) */
2629 NULL, /* hashfunc tp_hash; */
2630 NULL, /* ternaryfunc tp_call; */
2631 NULL, /* reprfunc tp_str; */
2633 /* will only use these if this is a subtype of a py class */
2634 ( getattrofunc ) pyrna_prop_getattro, /* getattrofunc tp_getattro; */
2635 ( setattrofunc ) pyrna_prop_setattro, /* setattrofunc tp_setattro; */
2637 /* Functions to access object as input/output buffer */
2638 NULL, /* PyBufferProcs *tp_as_buffer; */
2640 /*** Flags to define presence of optional/expanded features ***/
2641 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE, /* long tp_flags; */
2643 NULL, /* char *tp_doc; Documentation string */
2644 /*** Assigned meaning in release 2.0 ***/
2645 /* call function for all accessible objects */
2646 NULL, /* traverseproc tp_traverse; */
2648 /* delete references to contained objects */
2649 NULL, /* inquiry tp_clear; */
2651 /*** Assigned meaning in release 2.1 ***/
2652 /*** rich comparisons ***/
2653 (richcmpfunc)pyrna_prop_richcmp, /* richcmpfunc tp_richcompare; */
2655 /*** weak reference enabler ***/
2656 0, /* long tp_weaklistoffset; */
2658 /*** Added in release 2.2 ***/
2660 (getiterfunc)pyrna_prop_iter, /* getiterfunc tp_iter; */
2661 NULL, /* iternextfunc tp_iternext; */
2663 /*** Attribute descriptor and subclassing stuff ***/
2664 pyrna_prop_methods, /* struct PyMethodDef *tp_methods; */
2665 NULL, /* struct PyMemberDef *tp_members; */
2666 NULL /*pyrna_prop_getseters*/, /* struct PyGetSetDef *tp_getset; */
2667 NULL, /* struct _typeobject *tp_base; */
2668 NULL, /* PyObject *tp_dict; */
2669 NULL, /* descrgetfunc tp_descr_get; */
2670 NULL, /* descrsetfunc tp_descr_set; */
2671 0, /* long tp_dictoffset; */
2672 NULL, /* initproc tp_init; */
2673 NULL, /* allocfunc tp_alloc; */
2674 pyrna_prop_new, /* newfunc tp_new; */
2675 /* Low-level free-memory routine */
2676 NULL, /* freefunc tp_free; */
2677 /* For PyObject_IS_GC */
2678 NULL, /* inquiry tp_is_gc; */
2679 NULL, /* PyObject *tp_bases; */
2680 /* method resolution order */
2681 NULL, /* PyObject *tp_mro; */
2682 NULL, /* PyObject *tp_cache; */
2683 NULL, /* PyObject *tp_subclasses; */
2684 NULL, /* PyObject *tp_weaklist; */
2688 static struct PyMethodDef pyrna_struct_subtype_methods[] = {
2689 {"BoolProperty", (PyCFunction)BPy_BoolProperty, METH_VARARGS|METH_KEYWORDS, ""},
2690 {"IntProperty", (PyCFunction)BPy_IntProperty, METH_VARARGS|METH_KEYWORDS, ""},
2691 {"FloatProperty", (PyCFunction)BPy_FloatProperty, METH_VARARGS|METH_KEYWORDS, ""},
2692 {"StringProperty", (PyCFunction)BPy_StringProperty, METH_VARARGS|METH_KEYWORDS, ""},
2693 {"EnumProperty", (PyCFunction)BPy_EnumProperty, METH_VARARGS|METH_KEYWORDS, ""},
2694 {"PointerProperty", (PyCFunction)BPy_PointerProperty, METH_VARARGS|METH_KEYWORDS, ""},
2695 {"CollectionProperty", (PyCFunction)BPy_CollectionProperty, METH_VARARGS|METH_KEYWORDS, ""},
2697 // {"__get_rna", (PyCFunction)BPy_GetStructRNA, METH_NOARGS, ""},
2698 {NULL, NULL, 0, NULL}
2701 static void pyrna_subtype_set_rna(PyObject *newclass, StructRNA *srna)
2706 Py_INCREF(newclass);
2708 if (RNA_struct_py_type_get(srna))
2709 PyObSpit("RNA WAS SET - ", RNA_struct_py_type_get(srna));
2711 Py_XDECREF(((PyObject *)RNA_struct_py_type_get(srna)));
2713 RNA_struct_py_type_set(srna, (void *)newclass); /* Store for later use */
2715 /* Not 100% needed but useful,
2716 * having an instance within a type looks wrong however this instance IS an rna type */
2718 /* python deals with the curcular ref */
2719 RNA_pointer_create(NULL, &RNA_Struct, srna, &ptr);
2720 item = pyrna_struct_CreatePyObject(&ptr);
2722 //item = PyCObject_FromVoidPtr(srna, NULL);
2723 PyDict_SetItemString(((PyTypeObject *)newclass)->tp_dict, "bl_rna", item);
2725 /* done with rna instance */
2727 /* attach functions into the class
2728 * so you can do... bpy.types.Scene.SomeFunction()
2733 for(ml= pyrna_struct_subtype_methods; ml->ml_name; ml++){
2734 PyObject_SetAttrString(newclass, ml->ml_name, PyCFunction_New(ml, newclass));
2740 static StructRNA *srna_from_self(PyObject *self);
2741 PyObject *BPy_GetStructRNA(PyObject *self)
2743 StructRNA *srna= pyrna_struct_as_srna(self);
2747 RNA_pointer_create(NULL, &RNA_Struct, srna, &ptr);
2748 ret= pyrna_struct_CreatePyObject(&ptr);
2759 static PyObject* pyrna_srna_Subtype(StructRNA *srna);
2761 /* return a borrowed reference */
2762 static PyObject* pyrna_srna_PyBase(StructRNA *srna) //, PyObject *bpy_types_dict)
2764 /* Assume RNA_struct_py_type_get(srna) was already checked */
2767 PyObject *py_base= NULL;
2769 /* get the base type */
2770 base= RNA_struct_base(srna);
2772 if(base && base != srna) {
2773 /*/printf("debug subtype %s %p\n", RNA_struct_identifier(srna), srna); */
2774 py_base= pyrna_srna_Subtype(base); //, bpy_types_dict);
2775 Py_DECREF(py_base); /* srna owns, this is only to pass as an arg */
2779 py_base= (PyObject *)&pyrna_struct_Type;
2785 /* check if we have a native python subclass, use it when it exists
2786 * return a borrowed reference */
2787 static PyObject* pyrna_srna_ExternalType(StructRNA *srna)
2789 PyObject *bpy_types_dict= NULL;
2790 const char *idname= RNA_struct_identifier(srna);
2793 if(bpy_types_dict==NULL) {
2794 PyObject *bpy_types= PyImport_ImportModuleLevel("bpy_types", NULL, NULL, NULL, 0);
2796 if(bpy_types==NULL) {
2799 fprintf(stderr, "pyrna_srna_ExternalType: failed to find 'bpy_types' module\n");
2803 bpy_types_dict = PyModule_GetDict(bpy_types); // borrow
2804 Py_DECREF(bpy_types); // fairly safe to assume the dict is kept
2807 newclass= PyDict_GetItemString(bpy_types_dict, idname);
2809 /* sanity check, could skip this unless in debug mode */
2811 PyObject *base_compare= pyrna_srna_PyBase(srna);
2812 PyObject *bases= PyObject_GetAttrString(newclass, "__bases__");
2814 if(PyTuple_GET_SIZE(bases)) {
2815 PyObject *base= PyTuple_GET_ITEM(bases, 0);
2817 if(base_compare != base) {
2819 fprintf(stderr, "pyrna_srna_ExternalType: incorrect subclassing of SRNA '%s'\n", idname);
2820 PyObSpit("Expected! ", base_compare);
2825 fprintf(stderr, "SRNA Subclassed: '%s'\n", idname);
2835 static PyObject* pyrna_srna_Subtype(StructRNA *srna)
2837 PyObject *newclass = NULL;
2840 newclass= NULL; /* Nothing to do */
2841 } else if ((newclass= RNA_struct_py_type_get(srna))) {
2842 Py_INCREF(newclass);
2843 } else if ((newclass= pyrna_srna_ExternalType(srna))) {
2844 pyrna_subtype_set_rna(newclass, srna);
2845 Py_INCREF(newclass);
2847 /* subclass equivelents
2848 - class myClass(myBase):
2849 some='value' # or ...
2850 - myClass = type(name='myClass', bases=(myBase,), dict={'__module__':'bpy.types'})
2853 /* Assume RNA_struct_py_type_get(srna) was alredy checked */
2854 PyObject *py_base= pyrna_srna_PyBase(srna);
2856 const char *idname= RNA_struct_identifier(srna);
2857 const char *descr= RNA_struct_ui_description(srna);
2859 if(!descr) descr= "(no docs)";
2861 /* always use O not N when calling, N causes refcount errors */
2862 newclass = PyObject_CallFunction( (PyObject*)&PyType_Type, "s(O){ssss}", idname, py_base, "__module__","bpy.types", "__doc__",descr);
2863 /* newclass will now have 2 ref's, ???, probably 1 is internal since decrefing here segfaults */
2865 /* PyObSpit("new class ref", newclass); */
2869 /* srna owns one, and the other is owned by the caller */
2870 pyrna_subtype_set_rna(newclass, srna);
2872 Py_DECREF(newclass); /* let srna own */
2875 /* this should not happen */
2884 /* use for subtyping so we know which srna is used for a PointerRNA */
2885 static StructRNA *srna_from_ptr(PointerRNA *ptr)
2887 if(ptr->type == &RNA_Struct) {
2895 /* always returns a new ref, be sure to decref when done */
2896 static PyObject* pyrna_struct_Subtype(PointerRNA *ptr)
2898 return pyrna_srna_Subtype(srna_from_ptr(ptr));
2901 /*-----------------------CreatePyObject---------------------------------*/
2902 PyObject *pyrna_struct_CreatePyObject( PointerRNA *ptr )
2904 BPy_StructRNA *pyrna= NULL;
2906 if (ptr->data==NULL && ptr->type==NULL) { /* Operator RNA has NULL data */
2910 PyTypeObject *tp = (PyTypeObject *)pyrna_struct_Subtype(ptr);
2913 pyrna = (BPy_StructRNA *) tp->tp_alloc(tp, 0);
2914 Py_DECREF(tp); /* srna owns, cant hold a ref */
2917 fprintf(stderr, "Could not make type\n");
2918 pyrna = ( BPy_StructRNA * ) PyObject_NEW( BPy_StructRNA, &pyrna_struct_Type );
2923 PyErr_SetString( PyExc_MemoryError, "couldn't create BPy_StructRNA object" );
2928 pyrna->freeptr= FALSE;
2930 // PyObSpit("NewStructRNA: ", (PyObject *)pyrna);
2932 return ( PyObject * ) pyrna;
2935 PyObject *pyrna_prop_CreatePyObject( PointerRNA *ptr, PropertyRNA *prop )
2937 BPy_PropertyRNA *pyrna;
2939 pyrna = ( BPy_PropertyRNA * ) PyObject_NEW( BPy_PropertyRNA, &pyrna_prop_Type );
2942 PyErr_SetString( PyExc_MemoryError, "couldn't create BPy_rna object" );
2950 pyrna->arrayoffset= 0;
2952 return ( PyObject * ) pyrna;
2955 void BPY_rna_init(void)
2957 #ifdef USE_MATHUTILS // register mathutils callbacks, ok to run more then once.
2958 mathutils_rna_array_cb_index= Mathutils_RegisterCallback(&mathutils_rna_array_cb);
2959 mathutils_rna_matrix_cb_index= Mathutils_RegisterCallback(&mathutils_rna_matrix_cb);
2962 if( PyType_Ready( &pyrna_struct_Type ) < 0 )
2965 if( PyType_Ready( &pyrna_prop_Type ) < 0 )
2969 /* bpy.data from python */
2970 static PointerRNA *rna_module_ptr= NULL;
2971 PyObject *BPY_rna_module(void)
2973 BPy_StructRNA *pyrna;
2976 /* for now, return the base RNA type rather then a real module */
2977 RNA_main_pointer_create(G.main, &ptr);
2978 pyrna= (BPy_StructRNA *)pyrna_struct_CreatePyObject(&ptr);
2980 rna_module_ptr= &pyrna->ptr;
2981 return (PyObject *)pyrna;
2984 void BPY_update_rna_module(void)
2986 RNA_main_pointer_create(G.main, rna_module_ptr);
2990 /* This is a way we can access docstrings for RNA types
2991 * without having the datatypes in blender */
2992 PyObject *BPY_rna_doc( void )
2996 /* for now, return the base RNA type rather then a real module */
2997 RNA_blender_rna_pointer_create(&ptr);
2999 return pyrna_struct_CreatePyObject(&ptr);
3004 /* pyrna_basetype_* - BPy_BaseTypeRNA is just a BPy_PropertyRNA struct with a differnt type
3005 * the self->ptr and self->prop are always set to the "structs" collection */
3006 //---------------getattr--------------------------------------------
3007 static PyObject *pyrna_basetype_getattro( BPy_BaseTypeRNA *self, PyObject *pyname )
3012 if (RNA_property_collection_lookup_string(&self->ptr, self->prop, _PyUnicode_AsString(pyname), &newptr)) {
3013 ret= pyrna_struct_Subtype(&newptr);
3015 PyErr_Format(PyExc_SystemError, "bpy.types.%.200s subtype could not be generated, this is a bug!", _PyUnicode_AsString(pyname));
3020 PyErr_Format(PyExc_AttributeError, "bpy.types.%.200s RNA_Struct does not exist", _PyUnicode_AsString(pyname));
3023 /* The error raised here will be displayed */
3024 ret= PyObject_GenericGetAttr((PyObject *)self, pyname);
3030 static PyObject *pyrna_basetype_dir(BPy_BaseTypeRNA *self);
3031 static struct PyMethodDef pyrna_basetype_methods[] = {
3032 {"__dir__", (PyCFunction)pyrna_basetype_dir, METH_NOARGS, ""},
3033 {"register", (PyCFunction)pyrna_basetype_register, METH_O, ""},
3034 {"unregister", (PyCFunction)pyrna_basetype_unregister, METH_O, ""},
3035 {NULL, NULL, 0, NULL}
3038 static PyObject *pyrna_basetype_dir(BPy_BaseTypeRNA *self)
3040 PyObject *list, *name;
3043 list= pyrna_prop_keys(self); /* like calling structs.keys(), avoids looping here */
3045 for(meth=pyrna_basetype_methods; meth->ml_name; meth++) {
3046 name = PyUnicode_FromString(meth->ml_name);
3047 PyList_Append(list, name);
3054 PyTypeObject pyrna_basetype_Type = BLANK_PYTHON_TYPE;
3056 PyObject *BPY_rna_types(void)
3058 BPy_BaseTypeRNA *self;
3060 if ((pyrna_basetype_Type.tp_flags & Py_TPFLAGS_READY)==0) {
3061 pyrna_basetype_Type.tp_name = "RNA_Types";
3062 pyrna_basetype_Type.tp_basicsize = sizeof( BPy_BaseTypeRNA );
3063 pyrna_basetype_Type.tp_getattro = ( getattrofunc )pyrna_basetype_getattro;
3064 pyrna_basetype_Type.tp_flags = Py_TPFLAGS_DEFAULT;
3065 pyrna_basetype_Type.tp_methods = pyrna_basetype_methods;
3067 if( PyType_Ready( &pyrna_basetype_Type ) < 0 )
3071 self= (BPy_BaseTypeRNA *)PyObject_NEW( BPy_BaseTypeRNA, &pyrna_basetype_Type );
3073 /* avoid doing this lookup for every getattr */
3074 RNA_blender_rna_pointer_create(&self->ptr);
3075 self->prop = RNA_struct_find_property(&self->ptr, "structs");
3077 return (PyObject *)self;
3080 static struct PyMethodDef props_methods[] = {
3081 {"BoolProperty", (PyCFunction)BPy_BoolProperty, METH_VARARGS|METH_KEYWORDS, ""},
3082 {"IntProperty", (PyCFunction)BPy_IntProperty, METH_VARARGS|METH_KEYWORDS, ""},
3083 {"FloatProperty", (PyCFunction)BPy_FloatProperty, METH_VARARGS|METH_KEYWORDS, ""},
3084 {"StringProperty", (PyCFunction)BPy_StringProperty, METH_VARARGS|METH_KEYWORDS, ""},
3085 {"EnumProperty", (PyCFunction)BPy_EnumProperty, METH_VARARGS|METH_KEYWORDS, ""},
3086 {"PointerProperty", (PyCFunction)BPy_PointerProperty, METH_VARARGS|METH_KEYWORDS, ""},
3087 {"CollectionProperty", (PyCFunction)BPy_CollectionProperty, METH_VARARGS|METH_KEYWORDS, ""},
3088 {NULL, NULL, 0, NULL}
3091 static struct PyModuleDef props_module = {
3092 PyModuleDef_HEAD_INIT,
3095 -1,/* multiple "initialization" just copies the module dict. */
3097 NULL, NULL, NULL, NULL
3100 PyObject *BPY_rna_props( void )
3102 PyObject *submodule;
3103 submodule= PyModule_Create(&props_module);
3104 PyDict_SetItemString(PySys_GetObject("modules"), props_module.m_name, submodule);
3106 /* INCREF since its its assumed that all these functions return the
3107 * module with a new ref like PyDict_New, since they are passed to
3108 * PyModule_AddObject which steals a ref */
3109 Py_INCREF(submodule);
3114 static StructRNA *pyrna_struct_as_srna(PyObject *self)
3116 BPy_StructRNA *py_srna = NULL;
3119 /* ack, PyObject_GetAttrString wont look up this types tp_dict first :/ */
3120 if(PyType_Check(self)) {
3121 py_srna = (BPy_StructRNA *)PyDict_GetItemString(((PyTypeObject *)self)->tp_dict, "bl_rna");
3122 Py_XINCREF(py_srna);
3126 py_srna = (BPy_StructRNA*)PyObject_GetAttrString(self, "bl_rna");
3129 PyErr_SetString(PyExc_SystemError, "internal error, self had no bl_rna attribute, should never happen.");
3133 if(!BPy_StructRNA_Check(py_srna)) {
3134 PyErr_Format(PyExc_SystemError, "internal error, bl_rna was of type %.200s, instead of %.200s instance.", Py_TYPE(py_srna)->tp_name, pyrna_struct_Type.tp_name);
3139 if(py_srna->ptr.type != &RNA_Struct) {
3140 PyErr_SetString(PyExc_SystemError, "internal error, bl_rna was not a RNA_Struct type of rna struct.");
3145 srna= py_srna->ptr.data;
3152 /* Orphan functions, not sure where they should go */
3153 /* get the srna for methods attached to types */
3155 static StructRNA *srna_from_self(PyObject *self)
3157 /* a bit sloppy but would cause a very confusing bug if
3158 * an error happened to be set here */
3164 else if (PyCObject_Check(self)) {
3165 return PyCObject_AsVoidPtr(self);
3167 else if (PyType_Check(self)==0) {
3170 /* These cases above not errors, they just mean the type was not compatible
3171 * After this any errors will be raised in the script */
3173 return pyrna_struct_as_srna(self);
3176 /* operators use this so it can store the args given but defer running
3177 * it until the operator runs where these values are used to setup the
3178 * default args for that operator instance */
3179 static PyObject *bpy_prop_deferred_return(void *func, PyObject *kw)
3181 PyObject *ret = PyTuple_New(2);
3182 PyTuple_SET_ITEM(ret, 0, PyCObject_FromVoidPtr(func, NULL));
3183 PyTuple_SET_ITEM(ret, 1, kw);
3188 /* Function that sets RNA, NOTE - self is NULL when called from python, but being abused from C so we can pass the srna allong
3189 * This isnt incorrect since its a python object - but be careful */
3191 PyObject *BPy_BoolProperty(PyObject *self, PyObject *args, PyObject *kw)
3193 static char *kwlist[] = {"attr", "name", "description", "default", NULL};