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 *****
26 #include "bpy_compat.h"
28 //#include "blendef.h"
29 #include "BLI_dynstr.h"
30 #include "BLI_listbase.h"
31 #include "BLI_string.h"
32 #include "float.h" /* FLT_MIN/MAX */
34 #include "RNA_access.h"
35 #include "RNA_define.h" /* for defining our own rna */
37 #include "MEM_guardedalloc.h"
38 #include "BKE_context.h"
39 #include "BKE_global.h" /* evil G.* */
40 #include "BKE_report.h"
42 static int pyrna_struct_compare( BPy_StructRNA * a, BPy_StructRNA * b )
44 return (a->ptr.data==b->ptr.data) ? 0 : -1;
47 static int pyrna_prop_compare( BPy_PropertyRNA * a, BPy_PropertyRNA * b )
49 return (a->prop==b->prop && a->ptr.data==b->ptr.data ) ? 0 : -1;
52 /* For some reason python3 needs these :/ */
53 static PyObject *pyrna_struct_richcmp(BPy_StructRNA * a, BPy_StructRNA * b, int op)
55 int cmp_result= -1; /* assume false */
56 if (BPy_StructRNA_Check(a) && BPy_StructRNA_Check(b)) {
57 cmp_result= pyrna_struct_compare(a, b);
60 return Py_CmpToRich(op, cmp_result);
63 static PyObject *pyrna_prop_richcmp(BPy_PropertyRNA * a, BPy_PropertyRNA * b, int op)
65 int cmp_result= -1; /* assume false */
66 if (BPy_PropertyRNA_Check(a) && BPy_PropertyRNA_Check(b)) {
67 cmp_result= pyrna_prop_compare(a, b);
70 return Py_CmpToRich(op, cmp_result);
73 /*----------------------repr--------------------------------------------*/
74 static PyObject *pyrna_struct_repr( BPy_StructRNA * self )
79 /* print name if available */
80 prop= RNA_struct_name_property(self->ptr.type);
82 RNA_property_string_get(&self->ptr, prop, str);
83 return PyUnicode_FromFormat( "[BPy_StructRNA \"%s\" -> \"%s\"]", RNA_struct_identifier(self->ptr.type), str);
86 return PyUnicode_FromFormat( "[BPy_StructRNA \"%s\"]", RNA_struct_identifier(self->ptr.type));
89 static PyObject *pyrna_prop_repr( BPy_PropertyRNA * self )
95 /* if a pointer, try to print name of pointer target too */
96 if(RNA_property_type(self->prop) == PROP_POINTER) {
97 ptr= RNA_property_pointer_get(&self->ptr, self->prop);
100 prop= RNA_struct_name_property(ptr.type);
102 RNA_property_string_get(&ptr, prop, str);
103 return PyUnicode_FromFormat( "[BPy_PropertyRNA \"%s\" -> \"%s\" -> \"%s\" ]", RNA_struct_identifier(self->ptr.type), RNA_property_identifier(self->prop), str);
108 return PyUnicode_FromFormat( "[BPy_PropertyRNA \"%s\" -> \"%s\"]", RNA_struct_identifier(self->ptr.type), RNA_property_identifier(self->prop));
111 static long pyrna_struct_hash( BPy_StructRNA * self )
113 return (long)self->ptr.data;
116 /* use our own dealloc so we can free a property if we use one */
117 static void pyrna_struct_dealloc( BPy_StructRNA * self )
119 /* Note!! for some weired reason calling PyObject_DEL() directly crashes blender! */
120 if (self->freeptr && self->ptr.data) {
121 IDP_FreeProperty(self->ptr.data);
122 MEM_freeN(self->ptr.data);
123 self->ptr.data= NULL;
126 Py_TYPE(self)->tp_free(self);
130 static char *pyrna_enum_as_string(PointerRNA *ptr, PropertyRNA *prop)
132 const EnumPropertyItem *item;
135 RNA_property_enum_items(ptr, prop, &item, &totitem);
136 return (char*)BPy_enum_as_string((EnumPropertyItem*)item);
139 PyObject * pyrna_prop_to_py(PointerRNA *ptr, PropertyRNA *prop)
142 int type = RNA_property_type(prop);
143 int len = RNA_property_array_length(prop);
146 /* resolve the array from a new pytype */
147 return pyrna_prop_CreatePyObject(ptr, prop);
150 /* see if we can coorce into a python type - PropertyType */
153 ret = PyBool_FromLong( RNA_property_boolean_get(ptr, prop) );
156 ret = PyLong_FromSsize_t( (Py_ssize_t)RNA_property_int_get(ptr, prop) );
159 ret = PyFloat_FromDouble( RNA_property_float_get(ptr, prop) );
164 buf = RNA_property_string_get_alloc(ptr, prop, NULL, -1);
165 ret = PyUnicode_FromString( buf );
171 const char *identifier;
172 int val = RNA_property_enum_get(ptr, prop);
174 if (RNA_property_enum_identifier(ptr, prop, val, &identifier)) {
175 ret = PyUnicode_FromString( identifier );
177 PyErr_Format(PyExc_AttributeError, "RNA Error: Current value \"%d\" matches no enum", val);
186 newptr= RNA_property_pointer_get(ptr, prop);
188 ret = pyrna_struct_CreatePyObject(&newptr);
195 case PROP_COLLECTION:
196 ret = pyrna_prop_CreatePyObject(ptr, prop);
199 PyErr_Format(PyExc_AttributeError, "RNA Error: unknown type \"%d\" (pyrna_prop_to_py)", type);
207 /* This function is only used by operators right now
208 * Its used for taking keyword args and filling in property values */
209 int pyrna_pydict_to_props(PointerRNA *ptr, PyObject *kw, const char *error_prefix)
213 const char *arg_name= NULL;
216 PropertyRNA *prop, *iterprop;
217 CollectionPropertyIterator iter;
219 iterprop= RNA_struct_iterator_property(ptr->type);
220 RNA_property_collection_begin(ptr, iterprop, &iter);
222 totkw = kw ? PyDict_Size(kw):0;
224 for(; iter.valid; RNA_property_collection_next(&iter)) {
227 arg_name= RNA_property_identifier(prop);
229 if (strcmp(arg_name, "rna_type")==0) continue;
232 PyErr_Format( PyExc_AttributeError, "%s: no keywords, expected \"%s\"", error_prefix, arg_name ? arg_name : "<UNKNOWN>");
237 item= PyDict_GetItemString(kw, arg_name);
240 PyErr_Format( PyExc_AttributeError, "%s: keyword \"%s\" missing", error_prefix, arg_name ? arg_name : "<UNKNOWN>");
241 error_val = -1; /* pyrna_py_to_prop sets the error */
245 if (pyrna_py_to_prop(ptr, prop, NULL, item)) {
253 RNA_property_collection_end(&iter);
255 if (error_val==0 && totkw > 0) { /* some keywords were given that were not used :/ */
256 PyObject *key, *value;
259 while (PyDict_Next(kw, &pos, &key, &value)) {
260 arg_name= _PyUnicode_AsString(key);
261 if (RNA_struct_find_property(ptr, arg_name) == NULL) break;
265 PyErr_Format( PyExc_AttributeError, "%s: keyword \"%s\" unrecognized", error_prefix, arg_name ? arg_name : "<UNKNOWN>");
272 static PyObject * pyrna_func_call(PyObject * self, PyObject *args, PyObject *kw);
274 PyObject *pyrna_func_to_py(PointerRNA *ptr, FunctionRNA *func)
276 static PyMethodDef func_meth = {"<generic rna function>", (PyCFunction)pyrna_func_call, METH_VARARGS|METH_KEYWORDS, "python rna function"};
277 PyObject *self= PyTuple_New(2);
279 PyTuple_SET_ITEM(self, 0, pyrna_struct_CreatePyObject(ptr));
280 PyTuple_SET_ITEM(self, 1, PyCObject_FromVoidPtr((void *)func, NULL));
282 ret= PyCFunction_New(&func_meth, self);
289 int pyrna_py_to_prop(PointerRNA *ptr, PropertyRNA *prop, void *data, PyObject *value)
291 /* XXX hard limits should be checked here */
292 int type = RNA_property_type(prop);
293 int len = RNA_property_array_length(prop);
299 if (!PySequence_Check(value)) {
300 PyErr_SetString(PyExc_TypeError, "expected a python sequence type assigned to an RNA array.");
304 if ((int)PySequence_Length(value) != len) {
305 PyErr_SetString(PyExc_AttributeError, "python sequence length did not match the RNA array.");
309 /* for arrays we have a limited number of types */
314 if(data) param_arr= (int*)data;
315 else param_arr= MEM_mallocN(sizeof(char) * len, "pyrna bool array");
318 /* collect the variables before assigning, incase one of them is incorrect */
319 for (i=0; i<len; i++) {
320 item = PySequence_GetItem(value, i);
321 param_arr[i] = PyObject_IsTrue( item );
324 if (param_arr[i] < 0) {
326 MEM_freeN(param_arr);
327 PyErr_SetString(PyExc_AttributeError, "one or more of the values in the sequence is not a boolean");
332 RNA_property_boolean_set_array(ptr, prop, param_arr);
333 MEM_freeN(param_arr);
341 if(data) param_arr= (int*)data;
342 else param_arr= MEM_mallocN(sizeof(int) * len, "pyrna int array");
345 /* collect the variables */
346 for (i=0; i<len; i++) {
347 item = PySequence_GetItem(value, i);
348 param_arr[i] = (int)PyLong_AsSsize_t(item); /* deal with any errors later */
352 if (PyErr_Occurred()) {
354 MEM_freeN(param_arr);
355 PyErr_SetString(PyExc_AttributeError, "one or more of the values in the sequence could not be used as an int");
359 RNA_property_int_set_array(ptr, prop, param_arr);
360 MEM_freeN(param_arr);
367 if(data) param_arr = (float*)data;
368 else param_arr = MEM_mallocN(sizeof(float) * len, "pyrna float array");
372 /* collect the variables */
373 for (i=0; i<len; i++) {
374 item = PySequence_GetItem(value, i);
375 param_arr[i] = (float)PyFloat_AsDouble(item); /* deal with any errors later */
379 if (PyErr_Occurred()) {
381 MEM_freeN(param_arr);
382 PyErr_SetString(PyExc_AttributeError, "one or more of the values in the sequence could not be used as a float");
386 RNA_property_float_set_array(ptr, prop, param_arr);
387 MEM_freeN(param_arr);
393 /* Normal Property (not an array) */
395 /* see if we can coorce into a python type - PropertyType */
399 int param = PyObject_IsTrue( value );
402 PyErr_SetString(PyExc_TypeError, "expected True/False or 0/1");
405 if(data) *((int*)data)= param;
406 else RNA_property_boolean_set(ptr, prop, param);
412 int param = PyLong_AsSsize_t(value);
413 if (PyErr_Occurred()) {
414 PyErr_SetString(PyExc_TypeError, "expected an int type");
417 if(data) *((int*)data)= param;
418 else RNA_property_int_set(ptr, prop, param);
424 float param = PyFloat_AsDouble(value);
425 if (PyErr_Occurred()) {
426 PyErr_SetString(PyExc_TypeError, "expected a float type");
429 if(data) *((float*)data)= param;
430 else RNA_property_float_set(ptr, prop, param);
436 char *param = _PyUnicode_AsString(value);
439 PyErr_SetString(PyExc_TypeError, "expected a string type");
442 if(data) *((char**)data)= param;
443 else RNA_property_string_set(ptr, prop, param);
449 char *param = _PyUnicode_AsString(value);
452 char *enum_str= pyrna_enum_as_string(ptr, prop);
453 PyErr_Format(PyExc_TypeError, "expected a string enum type in (%s)", enum_str);
458 if (RNA_property_enum_value(ptr, prop, param, &val)) {
459 if(data) *((int*)data)= val;
460 else RNA_property_enum_set(ptr, prop, val);
462 char *enum_str= pyrna_enum_as_string(ptr, prop);
463 PyErr_Format(PyExc_AttributeError, "enum \"%s\" not found in (%s)", param, enum_str);
473 StructRNA *ptype= RNA_property_pointer_type(ptr, prop);
475 if(!BPy_StructRNA_Check(value) && value != Py_None) {
477 RNA_pointer_create(NULL, ptype, NULL, &tmp);
478 PyErr_Format(PyExc_TypeError, "expected a %s type", RNA_struct_identifier(tmp.type));
481 BPy_StructRNA *param= (BPy_StructRNA*)value;
484 int flag = RNA_property_flag(prop);
486 if(flag & PROP_RNAPTR) {
488 memset(data, 0, sizeof(PointerRNA));
490 *((PointerRNA*)data)= param->ptr;
492 else if(value == Py_None) {
493 *((void**)data)= NULL;
495 else if(RNA_struct_is_a(param->ptr.type, ptype)) {
496 *((void**)data)= param->ptr.data;
503 /* data==NULL, assign to RNA */
504 if(value == Py_None) {
506 memset(&valueptr, 0, sizeof(valueptr));
507 RNA_property_pointer_set(ptr, prop, valueptr);
509 else if(RNA_struct_is_a(param->ptr.type, ptype)) {
510 RNA_property_pointer_set(ptr, prop, param->ptr);
514 RNA_pointer_create(NULL, ptype, NULL, &tmp);
515 PyErr_Format(PyExc_TypeError, "expected a %s type", RNA_struct_identifier(tmp.type));
522 RNA_pointer_create(NULL, ptype, NULL, &tmp);
523 PyErr_Format(PyExc_TypeError, "expected a %s type", RNA_struct_identifier(tmp.type));
529 case PROP_COLLECTION:
535 /* convert a sequence of dict's into a collection */
536 if(!PySequence_Check(value)) {
537 PyErr_SetString(PyExc_TypeError, "expected a sequence of dicts for an RNA collection");
541 seq_len = PySequence_Length(value);
542 for(i=0; i<seq_len; i++) {
543 item= PySequence_GetItem(value, i);
544 if(item==NULL || PyDict_Check(item)==0) {
545 PyErr_SetString(PyExc_TypeError, "expected a sequence of dicts for an RNA collection");
550 RNA_property_collection_add(ptr, prop, &itemptr);
551 if(pyrna_pydict_to_props(&itemptr, item, "Converting a python list to an RNA collection")==-1) {
561 PyErr_SetString(PyExc_AttributeError, "unknown property type (pyrna_py_to_prop)");
570 static PyObject * pyrna_prop_to_py_index(PointerRNA *ptr, PropertyRNA *prop, int index)
573 int type = RNA_property_type(prop);
575 /* see if we can coorce into a python type - PropertyType */
578 ret = PyBool_FromLong( RNA_property_boolean_get_index(ptr, prop, index) );
581 ret = PyLong_FromSsize_t( (Py_ssize_t)RNA_property_int_get_index(ptr, prop, index) );
584 ret = PyFloat_FromDouble( RNA_property_float_get_index(ptr, prop, index) );
587 PyErr_SetString(PyExc_AttributeError, "not an array type");
595 static int pyrna_py_to_prop_index(PointerRNA *ptr, PropertyRNA *prop, int index, PyObject *value)
598 int type = RNA_property_type(prop);
600 /* see if we can coorce into a python type - PropertyType */
604 int param = PyObject_IsTrue( value );
607 PyErr_SetString(PyExc_TypeError, "expected True/False or 0/1");
610 RNA_property_boolean_set_index(ptr, prop, index, param);
616 int param = PyLong_AsSsize_t(value);
617 if (PyErr_Occurred()) {
618 PyErr_SetString(PyExc_TypeError, "expected an int type");
621 RNA_property_int_set_index(ptr, prop, index, param);
627 float param = PyFloat_AsDouble(value);
628 if (PyErr_Occurred()) {
629 PyErr_SetString(PyExc_TypeError, "expected a float type");
632 RNA_property_float_set_index(ptr, prop, index, param);
637 PyErr_SetString(PyExc_AttributeError, "not an array type");
645 //---------------sequence-------------------------------------------
646 static Py_ssize_t pyrna_prop_len( BPy_PropertyRNA * self )
650 if (RNA_property_type(self->prop) == PROP_COLLECTION) {
651 len = RNA_property_collection_length(&self->ptr, self->prop);
653 len = RNA_property_array_length(self->prop);
655 if (len==0) { /* not an array*/
656 PyErr_SetString(PyExc_AttributeError, "len() only available for collection RNA types");
664 static PyObject *pyrna_prop_subscript( BPy_PropertyRNA * self, PyObject *key )
669 char *keyname = NULL;
671 if (PyUnicode_Check(key)) {
672 keyname = _PyUnicode_AsString(key);
673 } else if (PyLong_Check(key)) {
674 keynum = PyLong_AsSsize_t(key);
676 PyErr_SetString(PyExc_AttributeError, "invalid key, key must be a string or an int");
680 if (RNA_property_type(self->prop) == PROP_COLLECTION) {
682 if (keyname) ok = RNA_property_collection_lookup_string(&self->ptr, self->prop, keyname, &newptr);
683 else ok = RNA_property_collection_lookup_int(&self->ptr, self->prop, keynum, &newptr);
686 ret = pyrna_struct_CreatePyObject(&newptr);
688 PyErr_SetString(PyExc_AttributeError, "out of range");
692 } else if (keyname) {
693 PyErr_SetString(PyExc_AttributeError, "string keys are only supported for collections");
696 int len = RNA_property_array_length(self->prop);
698 if (len==0) { /* not an array*/
699 PyErr_Format(PyExc_AttributeError, "not an array or collection %d", keynum);
704 PyErr_SetString(PyExc_AttributeError, "index out of range");
706 } else { /* not an array*/
707 ret = pyrna_prop_to_py_index(&self->ptr, self->prop, keynum);
715 static int pyrna_prop_assign_subscript( BPy_PropertyRNA * self, PyObject *key, PyObject *value )
719 char *keyname = NULL;
721 if (!RNA_property_editable(&self->ptr, self->prop)) {
722 PyErr_Format( PyExc_AttributeError, "PropertyRNA - attribute \"%s\" from \"%s\" is read-only", RNA_property_identifier(self->prop), RNA_struct_identifier(self->ptr.type) );
726 if (PyUnicode_Check(key)) {
727 keyname = _PyUnicode_AsString(key);
728 } else if (PyLong_Check(key)) {
729 keynum = PyLong_AsSsize_t(key);
731 PyErr_SetString(PyExc_AttributeError, "PropertyRNA - invalid key, key must be a string or an int");
735 if (RNA_property_type(self->prop) == PROP_COLLECTION) {
736 PyErr_SetString(PyExc_AttributeError, "PropertyRNA - assignment is not supported for collections (yet)");
738 } else if (keyname) {
739 PyErr_SetString(PyExc_AttributeError, "PropertyRNA - string keys are only supported for collections");
742 int len = RNA_property_array_length(self->prop);
744 if (len==0) { /* not an array*/
745 PyErr_Format(PyExc_AttributeError, "PropertyRNA - not an array or collection %d", keynum);
750 PyErr_SetString(PyExc_AttributeError, "PropertyRNA - index out of range");
753 ret = pyrna_py_to_prop_index(&self->ptr, self->prop, keynum, value);
762 static PyMappingMethods pyrna_prop_as_mapping = {
763 ( lenfunc ) pyrna_prop_len, /* mp_length */
764 ( binaryfunc ) pyrna_prop_subscript, /* mp_subscript */
765 ( objobjargproc ) pyrna_prop_assign_subscript, /* mp_ass_subscript */
768 static int pyrna_prop_contains(BPy_PropertyRNA * self, PyObject *value)
770 PointerRNA newptr; /* not used, just so RNA_property_collection_lookup_string runs */
771 char *keyname = _PyUnicode_AsString(value);
774 PyErr_SetString(PyExc_SystemError, "PropertyRNA - key in prop, key must be a string type");
778 if (RNA_property_type(self->prop) != PROP_COLLECTION) {
779 PyErr_SetString(PyExc_SystemError, "PropertyRNA - key in prop, is only valid for collection types");
784 if (RNA_property_collection_lookup_string(&self->ptr, self->prop, keyname, &newptr))
790 static PySequenceMethods pyrna_prop_as_sequence = {
791 NULL, /* Cant set the len otherwise it can evaluate as false */
792 NULL, /* sq_concat */
793 NULL, /* sq_repeat */
796 NULL, /* sq_ass_item */
797 NULL, /* sq_ass_slice */
798 (objobjproc)pyrna_prop_contains, /* sq_contains */
801 static PyObject *pyrna_struct_dir(BPy_StructRNA * self)
803 PyObject *ret, *dict;
806 /* for looping over attrs and funcs */
807 CollectionPropertyIterator iter;
808 PropertyRNA *iterprop;
810 /* Include this incase this instance is a subtype of a python class
811 * In these instances we may want to return a function or variable provided by the subtype
814 if (BPy_StructRNA_CheckExact(self)) {
817 pystring = PyUnicode_FromString("__dict__");
818 dict = PyObject_GenericGetAttr((PyObject *)self, pystring);
826 ret = PyDict_Keys(dict);
831 /* Collect RNA items*/
834 * Collect RNA attributes
836 PropertyRNA *nameprop;
837 char name[256], *nameptr;
839 iterprop= RNA_struct_iterator_property(self->ptr.type);
840 RNA_property_collection_begin(&self->ptr, iterprop, &iter);
842 for(; iter.valid; RNA_property_collection_next(&iter)) {
843 if(iter.ptr.data && (nameprop = RNA_struct_name_property(iter.ptr.type))) {
844 nameptr= RNA_property_string_get_alloc(&iter.ptr, nameprop, name, sizeof(name));
846 pystring = PyUnicode_FromString(nameptr);
847 PyList_Append(ret, pystring);
850 if ((char *)&name != nameptr)
854 RNA_property_collection_end(&iter);
861 * Collect RNA function items
865 RNA_pointer_create(NULL, &RNA_Struct, self->ptr.type, &tptr);
866 iterprop= RNA_struct_find_property(&tptr, "functions");
868 RNA_property_collection_begin(&tptr, iterprop, &iter);
870 for(; iter.valid; RNA_property_collection_next(&iter)) {
871 pystring = PyUnicode_FromString(RNA_function_identifier(iter.ptr.data));
872 PyList_Append(ret, pystring);
876 RNA_property_collection_end(&iter);
883 //---------------getattr--------------------------------------------
884 static PyObject *pyrna_struct_getattro( BPy_StructRNA * self, PyObject *pyname )
886 char *name = _PyUnicode_AsString(pyname);
891 /* Include this incase this instance is a subtype of a python class
892 * In these instances we may want to return a function or variable provided by the subtype
894 * Also needed to return methods when its not a subtype
896 ret = PyObject_GenericGetAttr((PyObject *)self, pyname);
899 /* done with subtypes */
901 if ((prop = RNA_struct_find_property(&self->ptr, name))) {
902 ret = pyrna_prop_to_py(&self->ptr, prop);
904 else if ((func = RNA_struct_find_function(&self->ptr, name))) {
905 ret = pyrna_func_to_py(&self->ptr, func);
907 else if (self->ptr.type == &RNA_Context) {
911 CTX_data_get(self->ptr.data, name, &newptr, &newlb);
914 ret = pyrna_struct_CreatePyObject(&newptr);
916 else if (newlb.first) {
917 CollectionPointerLink *link;
922 for(link=newlb.first; link; link=link->next) {
923 linkptr= pyrna_struct_CreatePyObject(&link->ptr);
924 PyList_Append(ret, linkptr);
933 BLI_freelistN(&newlb);
936 PyErr_Format( PyExc_AttributeError, "StructRNA - Attribute \"%s\" not found", name);
943 //--------------- setattr-------------------------------------------
944 static int pyrna_struct_setattro( BPy_StructRNA * self, PyObject *pyname, PyObject * value )
946 char *name = _PyUnicode_AsString(pyname);
947 PropertyRNA *prop = RNA_struct_find_property(&self->ptr, name);
950 if (!BPy_StructRNA_CheckExact(self) && PyObject_GenericSetAttr((PyObject *)self, pyname, value) >= 0) {
954 PyErr_Format( PyExc_AttributeError, "StructRNA - Attribute \"%s\" not found", name);
959 if (!RNA_property_editable(&self->ptr, prop)) {
960 PyErr_Format( PyExc_AttributeError, "StructRNA - Attribute \"%s\" from \"%s\" is read-only", RNA_property_identifier(prop), RNA_struct_identifier(self->ptr.type) );
964 /* pyrna_py_to_prop sets its own exceptions */
965 return pyrna_py_to_prop(&self->ptr, prop, NULL, value);
968 PyObject *pyrna_prop_keys(BPy_PropertyRNA *self)
971 if (RNA_property_type(self->prop) != PROP_COLLECTION) {
972 PyErr_SetString( PyExc_TypeError, "keys() is only valid for collection types" );
976 CollectionPropertyIterator iter;
977 PropertyRNA *nameprop;
978 char name[256], *nameptr;
982 RNA_property_collection_begin(&self->ptr, self->prop, &iter);
983 for(; iter.valid; RNA_property_collection_next(&iter)) {
984 if(iter.ptr.data && (nameprop = RNA_struct_name_property(iter.ptr.type))) {
985 nameptr= RNA_property_string_get_alloc(&iter.ptr, nameprop, name, sizeof(name));
987 /* add to python list */
988 item = PyUnicode_FromString( nameptr );
989 PyList_Append(ret, item);
993 if ((char *)&name != nameptr)
997 RNA_property_collection_end(&iter);
1003 PyObject *pyrna_prop_items(BPy_PropertyRNA *self)
1006 if (RNA_property_type(self->prop) != PROP_COLLECTION) {
1007 PyErr_SetString( PyExc_TypeError, "items() is only valid for collection types" );
1011 CollectionPropertyIterator iter;
1012 PropertyRNA *nameprop;
1013 char name[256], *nameptr;
1015 ret = PyList_New(0);
1017 RNA_property_collection_begin(&self->ptr, self->prop, &iter);
1018 for(; iter.valid; RNA_property_collection_next(&iter)) {
1019 if(iter.ptr.data && (nameprop = RNA_struct_name_property(iter.ptr.type))) {
1020 nameptr= RNA_property_string_get_alloc(&iter.ptr, nameprop, name, sizeof(name));
1022 /* add to python list */
1023 item = Py_BuildValue("(NN)", PyUnicode_FromString( nameptr ), pyrna_struct_CreatePyObject(&iter.ptr));
1024 PyList_Append(ret, item);
1028 if ((char *)&name != nameptr)
1032 RNA_property_collection_end(&iter);
1039 PyObject *pyrna_prop_values(BPy_PropertyRNA *self)
1042 if (RNA_property_type(self->prop) != PROP_COLLECTION) {
1043 PyErr_SetString( PyExc_TypeError, "values() is only valid for collection types" );
1047 CollectionPropertyIterator iter;
1048 PropertyRNA *nameprop;
1050 ret = PyList_New(0);
1052 RNA_property_collection_begin(&self->ptr, self->prop, &iter);
1053 for(; iter.valid; RNA_property_collection_next(&iter)) {
1054 if(iter.ptr.data && (nameprop = RNA_struct_name_property(iter.ptr.type))) {
1055 item = pyrna_struct_CreatePyObject(&iter.ptr);
1056 PyList_Append(ret, item);
1060 RNA_property_collection_end(&iter);
1066 /* A bit of a kludge, make a list out of a collection or array,
1067 * then return the lists iter function, not especially fast but convenient for now */
1068 PyObject *pyrna_prop_iter(BPy_PropertyRNA *self)
1070 /* Try get values from a collection */
1071 PyObject *ret = pyrna_prop_values(self);
1074 /* collection did not work, try array */
1075 int len = RNA_property_array_length(self->prop);
1080 ret = PyList_New(len);
1082 for (i=0; i < len; i++) {
1083 PyList_SET_ITEM(ret, i, pyrna_prop_to_py_index(&self->ptr, self->prop, i));
1089 /* we know this is a list so no need to PyIter_Check */
1090 PyObject *iter = PyObject_GetIter(ret);
1095 PyErr_SetString( PyExc_TypeError, "this BPy_PropertyRNA object is not iterable" );
1099 static struct PyMethodDef pyrna_struct_methods[] = {
1100 {"__dir__", (PyCFunction)pyrna_struct_dir, METH_NOARGS, ""},
1101 {NULL, NULL, 0, NULL}
1104 static struct PyMethodDef pyrna_prop_methods[] = {
1105 {"keys", (PyCFunction)pyrna_prop_keys, METH_NOARGS, ""},
1106 {"items", (PyCFunction)pyrna_prop_items, METH_NOARGS, ""},
1107 {"values", (PyCFunction)pyrna_prop_values, METH_NOARGS, ""},
1108 {NULL, NULL, 0, NULL}
1111 /* only needed for subtyping, so a new class gets a valid BPy_StructRNA
1112 * todo - also accept useful args */
1113 static PyObject * pyrna_struct_new(PyTypeObject *type, PyObject *args, PyObject *kwds) {
1115 BPy_StructRNA *base = NULL;
1117 if (!PyArg_ParseTuple(args, "O!:Base BPy_StructRNA", &pyrna_struct_Type, &base))
1120 if (type == &pyrna_struct_Type) {
1121 return pyrna_struct_CreatePyObject(&base->ptr);
1123 BPy_StructRNA *ret = (BPy_StructRNA *) type->tp_alloc(type, 0);
1124 ret->ptr = base->ptr;
1125 return (PyObject *)ret;
1129 /* only needed for subtyping, so a new class gets a valid BPy_StructRNA
1130 * todo - also accept useful args */
1131 static PyObject * pyrna_prop_new(PyTypeObject *type, PyObject *args, PyObject *kwds) {
1133 BPy_PropertyRNA *base = NULL;
1135 if (!PyArg_ParseTuple(args, "O!:Base BPy_PropertyRNA", &pyrna_prop_Type, &base))
1138 if (type == &pyrna_prop_Type) {
1139 return pyrna_prop_CreatePyObject(&base->ptr, base->prop);
1141 BPy_PropertyRNA *ret = (BPy_PropertyRNA *) type->tp_alloc(type, 0);
1142 ret->ptr = base->ptr;
1143 ret->prop = base->prop;
1144 return (PyObject *)ret;
1148 PyObject *pyrna_param_to_py(PointerRNA *ptr, PropertyRNA *prop, void *data)
1151 int type = RNA_property_type(prop);
1152 int len = RNA_property_array_length(prop);
1157 /* resolve the array from a new pytype */
1158 ret = PyTuple_New(len);
1162 for(a=0; a<len; a++)
1163 PyTuple_SET_ITEM(ret, a, PyBool_FromLong( ((int*)data)[a] ));
1166 for(a=0; a<len; a++)
1167 PyTuple_SET_ITEM(ret, a, PyLong_FromSsize_t( (Py_ssize_t)((int*)data)[a] ));
1170 for(a=0; a<len; a++)
1171 PyTuple_SET_ITEM(ret, a, PyFloat_FromDouble( ((float*)data)[a] ));
1174 PyErr_Format(PyExc_AttributeError, "RNA Error: unknown array type \"%d\" (pyrna_param_to_py)", type);
1180 /* see if we can coorce into a python type - PropertyType */
1183 ret = PyBool_FromLong( *(int*)data );
1186 ret = PyLong_FromSsize_t( (Py_ssize_t)*(int*)data );
1189 ret = PyFloat_FromDouble( *(float*)data );
1193 ret = PyUnicode_FromString( *(char**)data );
1198 const char *identifier;
1199 int val = *(int*)data;
1201 if (RNA_property_enum_identifier(ptr, prop, val, &identifier)) {
1202 ret = PyUnicode_FromString( identifier );
1204 PyErr_Format(PyExc_AttributeError, "RNA Error: Current value \"%d\" matches no enum", val);
1213 StructRNA *type= RNA_property_pointer_type(ptr, prop);
1214 int flag = RNA_property_flag(prop);
1216 if(flag & PROP_RNAPTR) {
1217 /* in this case we get the full ptr */
1218 newptr= *(PointerRNA*)data;
1221 /* XXX this is missing the ID part! */
1222 RNA_pointer_create(NULL, type, *(void**)data, &newptr);
1226 ret = pyrna_struct_CreatePyObject(&newptr);
1233 case PROP_COLLECTION:
1234 /* XXX not supported yet
1235 * ret = pyrna_prop_CreatePyObject(ptr, prop); */
1239 PyErr_Format(PyExc_AttributeError, "RNA Error: unknown type \"%d\" (pyrna_param_to_py)", type);
1248 static PyObject * pyrna_func_call(PyObject * self, PyObject *args, PyObject *kw)
1250 PointerRNA *self_ptr= &(((BPy_StructRNA *)PyTuple_GET_ITEM(self, 0))->ptr);
1251 FunctionRNA *self_func= PyCObject_AsVoidPtr(PyTuple_GET_ITEM(self, 1));
1254 ParameterList *parms;
1255 ParameterIterator iter;
1256 PropertyRNA *pret, *parm;
1257 PyObject *ret, *item;
1258 int i, tlen, flag, err= 0;
1259 const char *tid, *fid, *pid;
1260 void *retdata= NULL;
1263 RNA_pointer_create(NULL, &RNA_Function, self_func, &funcptr);
1265 pret= RNA_function_return(self_func);
1266 tlen= PyTuple_GET_SIZE(args);
1268 parms= RNA_parameter_list_create(self_ptr, self_func);
1269 RNA_parameter_list_begin(parms, &iter);
1271 /* parse function parameters */
1272 for (i= 0; iter.valid; RNA_parameter_list_next(&iter)) {
1280 pid= RNA_property_identifier(parm);
1281 flag= RNA_property_flag(parm);
1284 if ((i < tlen) && (flag & PROP_REQUIRED)) {
1285 item= PyTuple_GET_ITEM(args, i);
1288 else if (kw != NULL)
1289 item= PyDict_GetItemString(kw, pid); /* borrow ref */
1292 if(flag & PROP_REQUIRED) {
1293 tid= RNA_struct_identifier(self_ptr->type);
1294 fid= RNA_function_identifier(self_func);
1296 PyErr_Format(PyExc_AttributeError, "%s.%s(): required parameter \"%s\" not specified", tid, fid, pid);
1304 err= pyrna_py_to_prop(&funcptr, parm, iter.data, item);
1314 bContext *C= BPy_GetContext();
1316 BKE_reports_init(&reports, RPT_STORE);
1317 RNA_function_call(C, &reports, self_ptr, self_func, parms);
1319 err= (BPy_reports_to_error(&reports))? -1: 0;
1320 BKE_reports_clear(&reports);
1325 ret= pyrna_param_to_py(&funcptr, pret, retdata);
1329 RNA_parameter_list_end(&iter);
1330 RNA_parameter_list_free(parms);
1341 /*-----------------------BPy_StructRNA method def------------------------------*/
1342 PyTypeObject pyrna_struct_Type = {
1343 #if (PY_VERSION_HEX >= 0x02060000)
1344 PyVarObject_HEAD_INIT(NULL, 0)
1346 /* python 2.5 and below */
1347 PyObject_HEAD_INIT( NULL ) /* required py macro */
1350 "StructRNA", /* tp_name */
1351 sizeof( BPy_StructRNA ), /* tp_basicsize */
1352 0, /* tp_itemsize */
1354 ( destructor ) pyrna_struct_dealloc,/* tp_dealloc */
1355 NULL, /* printfunc tp_print; */
1356 NULL, /* getattrfunc tp_getattr; */
1357 NULL, /* setattrfunc tp_setattr; */
1358 NULL, /* tp_compare */ /* DEPRECATED in python 3.0! */
1359 ( reprfunc ) pyrna_struct_repr, /* tp_repr */
1361 /* Method suites for standard classes */
1363 NULL, /* PyNumberMethods *tp_as_number; */
1364 NULL, /* PySequenceMethods *tp_as_sequence; */
1365 NULL, /* PyMappingMethods *tp_as_mapping; */
1367 /* More standard operations (here for binary compatibility) */
1369 ( hashfunc )pyrna_struct_hash, /* hashfunc tp_hash; */
1370 NULL, /* ternaryfunc tp_call; */
1371 NULL, /* reprfunc tp_str; */
1372 ( getattrofunc ) pyrna_struct_getattro, /* getattrofunc tp_getattro; */
1373 ( setattrofunc ) pyrna_struct_setattro, /* setattrofunc tp_setattro; */
1375 /* Functions to access object as input/output buffer */
1376 NULL, /* PyBufferProcs *tp_as_buffer; */
1378 /*** Flags to define presence of optional/expanded features ***/
1379 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE, /* long tp_flags; */
1381 NULL, /* char *tp_doc; Documentation string */
1382 /*** Assigned meaning in release 2.0 ***/
1383 /* call function for all accessible objects */
1384 NULL, /* traverseproc tp_traverse; */
1386 /* delete references to contained objects */
1387 NULL, /* inquiry tp_clear; */
1389 /*** Assigned meaning in release 2.1 ***/
1390 /*** rich comparisons ***/
1391 (richcmpfunc)pyrna_struct_richcmp, /* richcmpfunc tp_richcompare; */
1393 /*** weak reference enabler ***/
1394 0, /* long tp_weaklistoffset; */
1396 /*** Added in release 2.2 ***/
1398 NULL, /* getiterfunc tp_iter; */
1399 NULL, /* iternextfunc tp_iternext; */
1401 /*** Attribute descriptor and subclassing stuff ***/
1402 pyrna_struct_methods, /* struct PyMethodDef *tp_methods; */
1403 NULL, /* struct PyMemberDef *tp_members; */
1404 NULL, /* struct PyGetSetDef *tp_getset; */
1405 NULL, /* struct _typeobject *tp_base; */
1406 NULL, /* PyObject *tp_dict; */
1407 NULL, /* descrgetfunc tp_descr_get; */
1408 NULL, /* descrsetfunc tp_descr_set; */
1409 0, /* long tp_dictoffset; */
1410 NULL, /* initproc tp_init; */
1411 NULL, /* allocfunc tp_alloc; */
1412 pyrna_struct_new, /* newfunc tp_new; */
1413 /* Low-level free-memory routine */
1414 NULL, /* freefunc tp_free; */
1415 /* For PyObject_IS_GC */
1416 NULL, /* inquiry tp_is_gc; */
1417 NULL, /* PyObject *tp_bases; */
1418 /* method resolution order */
1419 NULL, /* PyObject *tp_mro; */
1420 NULL, /* PyObject *tp_cache; */
1421 NULL, /* PyObject *tp_subclasses; */
1422 NULL, /* PyObject *tp_weaklist; */
1426 /*-----------------------BPy_PropertyRNA method def------------------------------*/
1427 PyTypeObject pyrna_prop_Type = {
1428 #if (PY_VERSION_HEX >= 0x02060000)
1429 PyVarObject_HEAD_INIT(NULL, 0)
1431 /* python 2.5 and below */
1432 PyObject_HEAD_INIT( NULL ) /* required py macro */
1436 "PropertyRNA", /* tp_name */
1437 sizeof( BPy_PropertyRNA ), /* tp_basicsize */
1438 0, /* tp_itemsize */
1440 NULL, /* tp_dealloc */
1441 NULL, /* printfunc tp_print; */
1442 NULL, /* getattrfunc tp_getattr; */
1443 NULL, /* setattrfunc tp_setattr; */
1444 NULL, /* tp_compare */ /* DEPRECATED in python 3.0! */
1445 ( reprfunc ) pyrna_prop_repr, /* tp_repr */
1447 /* Method suites for standard classes */
1449 NULL, /* PyNumberMethods *tp_as_number; */
1450 &pyrna_prop_as_sequence, /* PySequenceMethods *tp_as_sequence; */
1451 &pyrna_prop_as_mapping, /* PyMappingMethods *tp_as_mapping; */
1453 /* More standard operations (here for binary compatibility) */
1455 NULL, /* hashfunc tp_hash; */
1456 NULL, /* ternaryfunc tp_call; */
1457 NULL, /* reprfunc tp_str; */
1458 NULL, /*PyObject_GenericGetAttr - MINGW Complains, assign later */ /* getattrofunc tp_getattro; */ /* will only use these if this is a subtype of a py class */
1459 NULL, /*PyObject_GenericSetAttr - MINGW Complains, assign later */ /* setattrofunc tp_setattro; */
1461 /* Functions to access object as input/output buffer */
1462 NULL, /* PyBufferProcs *tp_as_buffer; */
1464 /*** Flags to define presence of optional/expanded features ***/
1465 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE, /* long tp_flags; */
1467 NULL, /* char *tp_doc; Documentation string */
1468 /*** Assigned meaning in release 2.0 ***/
1469 /* call function for all accessible objects */
1470 NULL, /* traverseproc tp_traverse; */
1472 /* delete references to contained objects */
1473 NULL, /* inquiry tp_clear; */
1475 /*** Assigned meaning in release 2.1 ***/
1476 /*** rich comparisons ***/
1477 (richcmpfunc)pyrna_prop_richcmp, /* richcmpfunc tp_richcompare; */
1479 /*** weak reference enabler ***/
1480 0, /* long tp_weaklistoffset; */
1482 /*** Added in release 2.2 ***/
1484 (getiterfunc)pyrna_prop_iter, /* getiterfunc tp_iter; */
1485 NULL, /* iternextfunc tp_iternext; */
1487 /*** Attribute descriptor and subclassing stuff ***/
1488 pyrna_prop_methods, /* struct PyMethodDef *tp_methods; */
1489 NULL, /* struct PyMemberDef *tp_members; */
1490 NULL, /* struct PyGetSetDef *tp_getset; */
1491 NULL, /* struct _typeobject *tp_base; */
1492 NULL, /* PyObject *tp_dict; */
1493 NULL, /* descrgetfunc tp_descr_get; */
1494 NULL, /* descrsetfunc tp_descr_set; */
1495 0, /* long tp_dictoffset; */
1496 NULL, /* initproc tp_init; */
1497 NULL, /* allocfunc tp_alloc; */
1498 pyrna_prop_new, /* newfunc tp_new; */
1499 /* Low-level free-memory routine */
1500 NULL, /* freefunc tp_free; */
1501 /* For PyObject_IS_GC */
1502 NULL, /* inquiry tp_is_gc; */
1503 NULL, /* PyObject *tp_bases; */
1504 /* method resolution order */
1505 NULL, /* PyObject *tp_mro; */
1506 NULL, /* PyObject *tp_cache; */
1507 NULL, /* PyObject *tp_subclasses; */
1508 NULL, /* PyObject *tp_weaklist; */
1512 static void pyrna_subtype_set_rna(PyObject *newclass, StructRNA *srna)
1517 Py_INCREF(newclass);
1519 if (RNA_struct_py_type_get(srna))
1520 PyObSpit("RNA WAS SET - ", RNA_struct_py_type_get(srna));
1522 Py_XDECREF(((PyObject *)RNA_struct_py_type_get(srna)));
1524 RNA_struct_py_type_set(srna, (void *)newclass); /* Store for later use */
1526 /* Not 100% needed but useful,
1527 * having an instance within a type looks wrong however this instance IS an rna type */
1528 RNA_pointer_create(NULL, &RNA_Struct, srna, &ptr);
1529 item = pyrna_struct_CreatePyObject(&ptr);
1530 PyDict_SetItemString(((PyTypeObject *)newclass)->tp_dict, "__rna__", item);
1532 /* done with rna instance */
1535 PyObject* pyrna_struct_Subtype(PointerRNA *ptr)
1537 PyObject *newclass = NULL;
1538 PropertyRNA *nameprop;
1540 if (ptr->type==NULL) {
1541 newclass= NULL; /* Nothing to do */
1542 } else if ((newclass= RNA_struct_py_type_get(ptr->data))) {
1543 Py_INCREF(newclass);
1544 } else if ((nameprop = RNA_struct_name_property(ptr->type))) {
1545 /* for now, return the base RNA type rather then a real module */
1547 /* Assume RNA_struct_py_type_get(ptr->data) was alredy checked */
1549 /* subclass equivelents
1550 - class myClass(myBase):
1551 some='value' # or ...
1552 - myClass = type(name='myClass', bases=(myBase,), dict={'some':'value'})
1554 char name[256], *nameptr;
1555 const char *descr= RNA_struct_ui_description(ptr->type);
1557 PyObject *args = PyTuple_New(3);
1558 PyObject *bases = PyTuple_New(1);
1559 PyObject *dict = PyDict_New();
1563 nameptr= RNA_property_string_get_alloc(ptr, nameprop, name, sizeof(name));
1566 //PyTuple_SET_ITEM(args, 0, PyUnicode_FromString(tp_name));
1567 PyTuple_SET_ITEM(args, 0, PyUnicode_FromString(nameptr));
1570 PyTuple_SET_ITEM(bases, 0, (PyObject *)&pyrna_struct_Type);
1571 Py_INCREF(&pyrna_struct_Type);
1573 PyTuple_SET_ITEM(args, 1, bases);
1575 // arg 3 - add an instance of the rna
1577 item= PyUnicode_FromString(descr);
1578 PyDict_SetItemString(dict, "__doc__", item);
1582 PyTuple_SET_ITEM(args, 2, dict); // fill with useful subclass things!
1584 if (PyErr_Occurred()) {
1589 newclass = PyObject_CallObject((PyObject *)&PyType_Type, args);
1593 pyrna_subtype_set_rna(newclass, ptr->data);
1595 if (name != nameptr)
1602 /*-----------------------CreatePyObject---------------------------------*/
1603 PyObject *pyrna_struct_CreatePyObject( PointerRNA *ptr )
1605 BPy_StructRNA *pyrna= NULL;
1607 if (ptr->data==NULL && ptr->type==NULL) { /* Operator RNA has NULL data */
1611 if (ptr->type == &RNA_Struct) { /* always return a python subtype from rna struct types */
1612 PyTypeObject *tp = (PyTypeObject *)pyrna_struct_Subtype(ptr);
1615 pyrna = (BPy_StructRNA *) tp->tp_alloc(tp, 0);
1618 fprintf(stderr, "Could not make type\n");
1619 pyrna = ( BPy_StructRNA * ) PyObject_NEW( BPy_StructRNA, &pyrna_struct_Type );
1623 pyrna = ( BPy_StructRNA * ) PyObject_NEW( BPy_StructRNA, &pyrna_struct_Type );
1627 PyErr_SetString( PyExc_MemoryError, "couldn't create BPy_StructRNA object" );
1633 return ( PyObject * ) pyrna;
1636 PyObject *pyrna_prop_CreatePyObject( PointerRNA *ptr, PropertyRNA *prop )
1638 BPy_PropertyRNA *pyrna;
1640 pyrna = ( BPy_PropertyRNA * ) PyObject_NEW( BPy_PropertyRNA, &pyrna_prop_Type );
1643 PyErr_SetString( PyExc_MemoryError, "couldn't create BPy_rna object" );
1650 return ( PyObject * ) pyrna;
1653 PyObject *BPY_rna_module( void )
1657 /* This can't be set in the pytype struct because some compilers complain */
1658 pyrna_prop_Type.tp_getattro = PyObject_GenericGetAttr;
1659 pyrna_prop_Type.tp_setattro = PyObject_GenericSetAttr;
1661 if( PyType_Ready( &pyrna_struct_Type ) < 0 )
1664 if( PyType_Ready( &pyrna_prop_Type ) < 0 )
1667 /* for now, return the base RNA type rather then a real module */
1668 RNA_main_pointer_create(G.main, &ptr);
1670 return pyrna_struct_CreatePyObject(&ptr);
1674 /* This is a way we can access docstrings for RNA types
1675 * without having the datatypes in blender */
1676 PyObject *BPY_rna_doc( void )
1680 /* for now, return the base RNA type rather then a real module */
1681 RNA_blender_rna_pointer_create(&ptr);
1683 return pyrna_struct_CreatePyObject(&ptr);
1688 /* pyrna_basetype_* - BPy_BaseTypeRNA is just a BPy_PropertyRNA struct with a differnt type
1689 * the self->ptr and self->prop are always set to the "structs" collection */
1690 //---------------getattr--------------------------------------------
1691 static PyObject *pyrna_basetype_getattro( BPy_BaseTypeRNA * self, PyObject *pyname )
1696 ret = PyObject_GenericGetAttr((PyObject *)self, pyname);
1697 if (ret) return ret;
1700 if (RNA_property_collection_lookup_string(&self->ptr, self->prop, _PyUnicode_AsString(pyname), &newptr)) {
1701 ret= pyrna_struct_Subtype(&newptr);
1703 PyErr_Format(PyExc_SystemError, "bpy.types.%s subtype could not be generated, this is a bug!", _PyUnicode_AsString(pyname));
1707 else { /* Override the error */
1708 PyErr_Format(PyExc_AttributeError, "bpy.types.%s not a valid RNA_Struct", _PyUnicode_AsString(pyname));
1713 static PyObject *pyrna_basetype_dir(BPy_BaseTypeRNA *self);
1714 static struct PyMethodDef pyrna_basetype_methods[] = {
1715 {"__dir__", (PyCFunction)pyrna_basetype_dir, METH_NOARGS, ""},
1716 {"register", (PyCFunction)pyrna_basetype_register, METH_VARARGS, ""},
1717 {"unregister", (PyCFunction)pyrna_basetype_unregister, METH_VARARGS, ""},
1718 {NULL, NULL, 0, NULL}
1721 static PyObject *pyrna_basetype_dir(BPy_BaseTypeRNA *self)
1723 PyObject *list, *name;
1726 list= pyrna_prop_keys(self); /* like calling structs.keys(), avoids looping here */
1728 for(meth=pyrna_basetype_methods; meth->ml_name; meth++) {
1729 name = PyUnicode_FromString(meth->ml_name);
1730 PyList_Append(list, name);
1737 PyTypeObject pyrna_basetype_Type = BLANK_PYTHON_TYPE;
1739 PyObject *BPY_rna_types(void)
1741 BPy_BaseTypeRNA *self;
1743 if ((pyrna_basetype_Type.tp_flags & Py_TPFLAGS_READY)==0) {
1744 pyrna_basetype_Type.tp_name = "RNA_Types";
1745 pyrna_basetype_Type.tp_basicsize = sizeof( BPy_BaseTypeRNA );
1746 pyrna_basetype_Type.tp_getattro = ( getattrofunc )pyrna_basetype_getattro;
1747 pyrna_basetype_Type.tp_flags = Py_TPFLAGS_DEFAULT;
1748 pyrna_basetype_Type.tp_methods = pyrna_basetype_methods;
1750 if( PyType_Ready( &pyrna_basetype_Type ) < 0 )
1754 self= (BPy_BaseTypeRNA *)PyObject_NEW( BPy_BaseTypeRNA, &pyrna_basetype_Type );
1756 /* avoid doing this lookup for every getattr */
1757 RNA_blender_rna_pointer_create(&self->ptr);
1758 self->prop = RNA_struct_find_property(&self->ptr, "structs");
1760 return (PyObject *)self;
1763 static struct PyMethodDef props_methods[] = {
1764 {"FloatProperty", (PyCFunction)BPy_FloatProperty, METH_VARARGS|METH_KEYWORDS, ""},
1765 {"IntProperty", (PyCFunction)BPy_IntProperty, METH_VARARGS|METH_KEYWORDS, ""},
1766 {"BoolProperty", (PyCFunction)BPy_BoolProperty, METH_VARARGS|METH_KEYWORDS, ""},
1767 {"StringProperty", (PyCFunction)BPy_StringProperty, METH_VARARGS|METH_KEYWORDS, ""},
1768 {NULL, NULL, 0, NULL}
1771 #if PY_VERSION_HEX >= 0x03000000
1772 static struct PyModuleDef props_module = {
1773 PyModuleDef_HEAD_INIT,
1776 -1,/* multiple "initialization" just copies the module dict. */
1778 NULL, NULL, NULL, NULL
1782 PyObject *BPY_rna_props( void )
1784 PyObject *submodule, *mod;
1785 #if PY_VERSION_HEX >= 0x03000000
1786 submodule= PyModule_Create(&props_module);
1788 submodule= Py_InitModule3( "bpy.props", props_methods, "" );
1791 mod = PyModule_New("props");
1792 PyModule_AddObject( submodule, "props", mod );
1794 /* INCREF since its its assumed that all these functions return the
1795 * module with a new ref like PyDict_New, since they are passed to
1796 * PyModule_AddObject which steals a ref */
1797 Py_INCREF(submodule);
1802 /* Orphan functions, not sure where they should go */
1804 /* Function that sets RNA, NOTE - self is NULL when called from python, but being abused from C so we can pass the srna allong
1805 * This isnt incorrect since its a python object - but be careful */
1806 PyObject *BPy_FloatProperty(PyObject *self, PyObject *args, PyObject *kw)
1808 static char *kwlist[] = {"attr", "name", "description", "min", "max", "soft_min", "soft_max", "default", NULL};
1809 char *id, *name="", *description="";
1810 float min=FLT_MIN, max=FLT_MAX, soft_min=FLT_MIN, soft_max=FLT_MAX, def=0.0f;
1812 if (!PyArg_ParseTupleAndKeywords(args, kw, "s|ssfffff:FloatProperty", kwlist, &id, &name, &description, &min, &max, &soft_min, &soft_max, &def))
1815 if (PyTuple_Size(args) > 0) {
1816 PyErr_SetString(PyExc_ValueError, "all args must be keywors"); // TODO - py3 can enforce this.
1820 if (self && PyCObject_Check(self)) {
1821 StructRNA *srna = PyCObject_AsVoidPtr(self);
1822 RNA_def_float(srna, id, def, min, max, name, description, soft_min, soft_max);
1825 PyObject *ret = PyTuple_New(2);
1826 PyTuple_SET_ITEM(ret, 0, PyCObject_FromVoidPtr((void *)BPy_FloatProperty, NULL));
1827 PyTuple_SET_ITEM(ret, 1, kw);
1833 PyObject *BPy_IntProperty(PyObject *self, PyObject *args, PyObject *kw)
1835 static char *kwlist[] = {"attr", "name", "description", "min", "max", "soft_min", "soft_max", "default", NULL};
1836 char *id, *name="", *description="";
1837 int min=INT_MIN, max=INT_MAX, soft_min=INT_MIN, soft_max=INT_MAX, def=0;
1839 if (!PyArg_ParseTupleAndKeywords(args, kw, "s|ssiiiii:IntProperty", kwlist, &id, &name, &description, &min, &max, &soft_min, &soft_max, &def))
1842 if (PyTuple_Size(args) > 0) {
1843 PyErr_SetString(PyExc_ValueError, "all args must be keywors"); // TODO - py3 can enforce this.
1847 if (self && PyCObject_Check(self)) {
1848 StructRNA *srna = PyCObject_AsVoidPtr(self);
1849 RNA_def_int(srna, id, def, min, max, name, description, soft_min, soft_max);
1852 PyObject *ret = PyTuple_New(2);
1853 PyTuple_SET_ITEM(ret, 0, PyCObject_FromVoidPtr((void *)BPy_IntProperty, NULL));
1854 PyTuple_SET_ITEM(ret, 1, kw);
1860 PyObject *BPy_BoolProperty(PyObject *self, PyObject *args, PyObject *kw)
1862 static char *kwlist[] = {"attr", "name", "description", "default", NULL};
1863 char *id, *name="", *description="";
1866 if (!PyArg_ParseTupleAndKeywords(args, kw, "s|ssi:IntProperty", kwlist, &id, &name, &description, &def))
1869 if (PyTuple_Size(args) > 0) {
1870 PyErr_SetString(PyExc_ValueError, "all args must be keywors"); // TODO - py3 can enforce this.
1874 if (self && PyCObject_Check(self)) {
1875 StructRNA *srna = PyCObject_AsVoidPtr(self);
1876 RNA_def_boolean(srna, id, def, name, description);
1879 PyObject *ret = PyTuple_New(2);
1880 PyTuple_SET_ITEM(ret, 0, PyCObject_FromVoidPtr((void *)BPy_IntProperty, NULL));
1881 PyTuple_SET_ITEM(ret, 1, kw);
1887 PyObject *BPy_StringProperty(PyObject *self, PyObject *args, PyObject *kw)
1889 static char *kwlist[] = {"attr", "name", "description", "maxlen", "default", NULL};
1890 char *id, *name="", *description="", *def="";
1893 if (!PyArg_ParseTupleAndKeywords(args, kw, "s|ssis:StringProperty", kwlist, &id, &name, &description, &maxlen, &def))
1896 if (PyTuple_Size(args) > 0) {
1897 PyErr_SetString(PyExc_ValueError, "all args must be keywors"); // TODO - py3 can enforce this.
1901 if (self && PyCObject_Check(self)) {
1902 StructRNA *srna = PyCObject_AsVoidPtr(self);
1903 RNA_def_string(srna, id, def, maxlen, name, description);
1906 PyObject *ret = PyTuple_New(2);
1907 PyTuple_SET_ITEM(ret, 0, PyCObject_FromVoidPtr((void *)BPy_StringProperty, NULL));
1908 PyTuple_SET_ITEM(ret, 1, kw);
1914 /*-------------------- Type Registration ------------------------*/
1916 static int rna_function_arg_count(FunctionRNA *func)
1918 const ListBase *lb= RNA_function_defined_parameters(func);
1923 for(link=lb->first; link; link=link->next) {
1924 parm= (PropertyRNA*)link;
1925 if(!(RNA_property_flag(parm) & PROP_RETURN))
1932 static int bpy_class_validate(PointerRNA *dummyptr, void *py_data, int *have_function)
1938 StructRNA *srna= dummyptr->type;
1939 const char *class_type= RNA_struct_identifier(srna);
1940 PyObject *py_class= (PyObject*)py_data;
1941 PyObject *base_class= RNA_struct_py_type_get(srna);
1942 PyObject *item, *fitem;
1943 PyObject *py_arg_count;
1944 int i, flag, arg_count, func_arg_count;
1945 char identifier[128];
1948 if (!PyObject_IsSubclass(py_class, base_class)) {
1949 PyObject *name= PyObject_GetAttrString(base_class, "__name__");
1950 PyErr_Format( PyExc_AttributeError, "expected %s subclass of class \"%s\"", class_type, name ? _PyUnicode_AsString(name):"<UNKNOWN>");
1956 /* verify callback functions */
1957 lb= RNA_struct_defined_functions(srna);
1959 for(link=lb->first; link; link=link->next) {
1960 func= (FunctionRNA*)link;
1961 flag= RNA_function_flag(func);
1963 if(!(flag & FUNC_REGISTER))
1966 item = PyObject_GetAttrString(py_class, RNA_function_identifier(func));
1968 have_function[i]= (item != NULL);
1972 if ((flag & FUNC_REGISTER_OPTIONAL)==0) {
1973 PyErr_Format( PyExc_AttributeError, "expected %s class to have an \"%s\" attribute", class_type, RNA_function_identifier(func));
1980 Py_DECREF(item); /* no need to keep a ref, the class owns it */
1982 if (PyMethod_Check(item))
1983 fitem= PyMethod_Function(item); /* py 2.x */
1985 fitem= item; /* py 3.x */
1987 if (PyFunction_Check(fitem)==0) {
1988 PyErr_Format( PyExc_AttributeError, "expected %s class \"%s\" attribute to be a function", class_type, RNA_function_identifier(func));
1992 func_arg_count= rna_function_arg_count(func);
1994 if (func_arg_count >= 0) { /* -1 if we dont care*/
1995 py_arg_count = PyObject_GetAttrString(PyFunction_GET_CODE(fitem), "co_argcount");
1996 arg_count = PyLong_AsSsize_t(py_arg_count);
1997 Py_DECREF(py_arg_count);
1999 if (arg_count != func_arg_count) {
2000 PyErr_Format( PyExc_AttributeError, "expected %s class \"%s\" function to have %d args", class_type, RNA_function_identifier(func), func_arg_count);
2007 /* verify properties */
2008 lb= RNA_struct_defined_properties(srna);
2009 for(link=lb->first; link; link=link->next) {
2010 prop= (PropertyRNA*)link;
2011 flag= RNA_property_flag(prop);
2013 if(!(flag & PROP_REGISTER))
2016 BLI_snprintf(identifier, sizeof(identifier), "__%s__", RNA_property_identifier(prop));
2017 item = PyObject_GetAttrString(py_class, identifier);
2020 if(strcmp(identifier, "__idname__") == 0) {
2021 item= PyObject_GetAttrString(py_class, "__name__");
2024 Py_DECREF(item); /* no need to keep a ref, the class owns it */
2026 if(pyrna_py_to_prop(dummyptr, prop, NULL, item) != 0)
2031 if (item==NULL && (flag & PROP_REGISTER_OPTIONAL)==0) {
2032 PyErr_Format( PyExc_AttributeError, "expected %s class to have an \"%s\" attribute", class_type, identifier);
2039 Py_DECREF(item); /* no need to keep a ref, the class owns it */
2041 if(pyrna_py_to_prop(dummyptr, prop, NULL, item) != 0)
2049 extern void BPY_update_modules( void ); //XXX temp solution
2051 static int bpy_class_call(PointerRNA *ptr, FunctionRNA *func, ParameterList *parms)
2054 PyObject *ret= NULL, *py_class, *py_class_instance, *item, *parmitem;
2055 PropertyRNA *pret= NULL, *parm;
2056 ParameterIterator iter;
2058 void *retdata= NULL;
2059 int err= 0, i, flag;
2061 PyGILState_STATE gilstate = PyGILState_Ensure();
2063 BPY_update_modules(); // XXX - the RNA pointers can change so update before running, would like a nicer solution for this.
2065 py_class= RNA_struct_py_type_get(ptr->type);
2067 item = pyrna_struct_CreatePyObject(ptr);
2069 py_class_instance = NULL;
2071 else if(item == Py_None) { /* probably wont ever happen but possible */
2073 py_class_instance = NULL;
2076 args = PyTuple_New(1);
2077 PyTuple_SET_ITEM(args, 0, item);
2078 py_class_instance = PyObject_Call(py_class, args, NULL);
2082 if (py_class_instance) { /* Initializing the class worked, now run its invoke function */
2083 item= PyObject_GetAttrString(py_class, RNA_function_identifier(func));
2084 flag= RNA_function_flag(func);
2087 pret= RNA_function_return(func);
2088 RNA_pointer_create(NULL, &RNA_Function, func, &funcptr);
2090 args = PyTuple_New(rna_function_arg_count(func));
2091 PyTuple_SET_ITEM(args, 0, py_class_instance);
2093 RNA_parameter_list_begin(parms, &iter);
2095 /* parse function parameters */
2096 for (i= 1; iter.valid; RNA_parameter_list_next(&iter)) {
2104 parmitem= pyrna_param_to_py(&funcptr, parm, iter.data);
2105 PyTuple_SET_ITEM(args, i, parmitem);
2109 ret = PyObject_Call(item, args, NULL);
2115 Py_DECREF(py_class_instance);
2116 PyErr_Format(PyExc_AttributeError, "could not find function %s in %s to execute callback.", RNA_function_identifier(func), RNA_struct_identifier(ptr->type));
2121 PyErr_Format(PyExc_AttributeError, "could not create instance of %s to call callback function %s.", RNA_struct_identifier(ptr->type), RNA_function_identifier(func));
2125 if (ret == NULL) { /* covers py_class_instance failing too */
2126 PyErr_Print(); /* XXX use reporting api? */
2131 err= pyrna_py_to_prop(&funcptr, pret, retdata, ret);
2135 PyGILState_Release(gilstate);
2140 static void bpy_class_free(void *pyob_ptr)
2143 if(((PyObject *)pyob_ptr)->ob_refcnt > 1)
2144 PyObSpit("zombie class - ref should be 1", (PyObject *)pyob_ptr);
2146 Py_DECREF((PyObject *)pyob_ptr);
2149 PyObject *pyrna_basetype_register(PyObject *self, PyObject *args)
2152 PyObject *py_class, *item;
2154 StructRegisterFunc reg;
2155 BPy_StructRNA *py_srna;
2158 if(!PyArg_ParseTuple(args, "O:register", &py_class))
2161 if(!PyType_Check(py_class)) {
2162 PyErr_SetString(PyExc_AttributeError, "expected a Type subclassed from a registerable rna type (no a Type object).");
2166 /* check we got an __rna__ attribute */
2167 item= PyObject_GetAttrString(py_class, "__rna__");
2169 if(!item || !BPy_StructRNA_Check(item)) {
2171 PyErr_SetString(PyExc_AttributeError, "expected a Type subclassed from a registerable rna type (no __rna__ property).");
2175 /* check the __rna__ attribute has the right type */
2177 py_srna= (BPy_StructRNA*)item;
2179 if(py_srna->ptr.type != &RNA_Struct) {
2180 PyErr_SetString(PyExc_AttributeError, "expected a Type subclassed from a registerable rna type (not a Struct).");
2184 /* check that we have a register callback for this type */
2185 reg= RNA_struct_register(py_srna->ptr.data);
2188 PyErr_SetString(PyExc_AttributeError, "expected a Type subclassed from a registerable rna type (no register supported).");
2192 /* get the context, so register callback can do necessary refreshes */
2193 C= BPy_GetContext();
2195 /* call the register callback */
2196 BKE_reports_init(&reports, RPT_STORE);
2197 srna= reg(C, &reports, py_class, bpy_class_validate, bpy_class_call, bpy_class_free);
2200 BPy_reports_to_error(&reports);
2201 BKE_reports_clear(&reports);
2205 BKE_reports_clear(&reports);
2207 pyrna_subtype_set_rna(py_class, srna); /* takes a ref to py_class */
2212 PyObject *pyrna_basetype_unregister(PyObject *self, PyObject *args)
2215 PyObject *py_class, *item;
2216 BPy_StructRNA *py_srna;
2217 StructUnregisterFunc unreg;
2219 if(!PyArg_ParseTuple(args, "O:unregister", &py_class))
2222 if(!PyType_Check(py_class)) {
2223 PyErr_SetString(PyExc_AttributeError, "expected a Type subclassed from a registerable rna type (no a Type object).");
2227 /* check we got an __rna__ attribute */
2228 item= PyDict_GetItemString(((PyTypeObject*)py_class)->tp_dict, "__rna__"); /* borrow ref */
2230 if(!item || !BPy_StructRNA_Check(item)) {
2231 PyErr_SetString(PyExc_AttributeError, "expected a Type subclassed from a registerable rna type (no __rna__ property).");
2235 /* check the __rna__ attribute has the right type */
2236 py_srna= (BPy_StructRNA*)item;
2238 if(py_srna->ptr.type != &RNA_Struct) {
2239 PyErr_SetString(PyExc_AttributeError, "expected a Type subclassed from a registerable rna type (not a Struct).");
2243 /* check that we have a unregister callback for this type */
2244 unreg= RNA_struct_unregister(py_srna->ptr.data);
2247 PyErr_SetString(PyExc_AttributeError, "expected a Type subclassed from a registerable rna type (no unregister supported).");
2251 /* get the context, so register callback can do necessary refreshes */
2252 C= BPy_GetContext();
2255 /* call unregister */
2256 unreg(C, py_srna->ptr.data);
2258 /* remove reference to old type */
2259 Py_DECREF(py_class);