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"
45 #include "../generic/Mathutils.h" /* so we can have mathutils callbacks */
47 /* bpyrna vector callbacks */
48 static int mathutils_rna_vector_cb_index= -1; /* index for our callbacks */
50 static int mathutils_rna_generic_check(BPy_PropertyRNA *self)
52 return self->prop?1:0;
55 static int mathutils_rna_vector_get(BPy_PropertyRNA *self, int subtype, float *vec_from)
60 RNA_property_float_get_array(&self->ptr, self->prop, vec_from);
64 static int mathutils_rna_vector_set(BPy_PropertyRNA *self, int subtype, float *vec_to)
69 RNA_property_float_set_array(&self->ptr, self->prop, vec_to);
73 static int mathutils_rna_vector_get_index(BPy_PropertyRNA *self, int subtype, float *vec_from, int index)
78 vec_from[index]= RNA_property_float_get_index(&self->ptr, self->prop, index);
82 static int mathutils_rna_vector_set_index(BPy_PropertyRNA *self, int subtype, float *vec_to, int index)
87 RNA_property_float_set_index(&self->ptr, self->prop, index, vec_to[index]);
91 Mathutils_Callback mathutils_rna_vector_cb = {
92 mathutils_rna_generic_check,
93 mathutils_rna_vector_get,
94 mathutils_rna_vector_set,
95 mathutils_rna_vector_get_index,
96 mathutils_rna_vector_set_index
99 /* bpyrna matrix callbacks */
100 static int mathutils_rna_matrix_cb_index= -1; /* index for our callbacks */
102 static int mathutils_rna_matrix_get(BPy_PropertyRNA *self, int subtype, float *mat_from)
107 RNA_property_float_get_array(&self->ptr, self->prop, mat_from);
111 static int mathutils_rna_matrix_set(BPy_PropertyRNA *self, int subtype, float *mat_to)
116 RNA_property_float_set_array(&self->ptr, self->prop, mat_to);
120 Mathutils_Callback mathutils_rna_matrix_cb = {
121 mathutils_rna_generic_check,
122 mathutils_rna_matrix_get,
123 mathutils_rna_matrix_set,
130 static int pyrna_struct_compare( BPy_StructRNA * a, BPy_StructRNA * b )
132 return (a->ptr.data==b->ptr.data) ? 0 : -1;
135 static int pyrna_prop_compare( BPy_PropertyRNA * a, BPy_PropertyRNA * b )
137 return (a->prop==b->prop && a->ptr.data==b->ptr.data ) ? 0 : -1;
140 /* For some reason python3 needs these :/ */
141 static PyObject *pyrna_struct_richcmp(BPy_StructRNA * a, BPy_StructRNA * b, int op)
143 int cmp_result= -1; /* assume false */
144 if (BPy_StructRNA_Check(a) && BPy_StructRNA_Check(b)) {
145 cmp_result= pyrna_struct_compare(a, b);
148 return Py_CmpToRich(op, cmp_result);
151 static PyObject *pyrna_prop_richcmp(BPy_PropertyRNA * a, BPy_PropertyRNA * b, int op)
153 int cmp_result= -1; /* assume false */
154 if (BPy_PropertyRNA_Check(a) && BPy_PropertyRNA_Check(b)) {
155 cmp_result= pyrna_prop_compare(a, b);
158 return Py_CmpToRich(op, cmp_result);
161 /*----------------------repr--------------------------------------------*/
162 static PyObject *pyrna_struct_repr( BPy_StructRNA * self )
167 /* print name if available */
168 name= RNA_struct_name_get_alloc(&self->ptr, NULL, 0);
170 pyob= PyUnicode_FromFormat( "[BPy_StructRNA \"%s\" -> \"%s\"]", RNA_struct_identifier(self->ptr.type), name);
175 return PyUnicode_FromFormat( "[BPy_StructRNA \"%s\"]", RNA_struct_identifier(self->ptr.type));
178 static PyObject *pyrna_prop_repr( BPy_PropertyRNA * self )
184 /* if a pointer, try to print name of pointer target too */
185 if(RNA_property_type(self->prop) == PROP_POINTER) {
186 ptr= RNA_property_pointer_get(&self->ptr, self->prop);
187 name= RNA_struct_name_get_alloc(&ptr, NULL, 0);
190 pyob= PyUnicode_FromFormat( "[BPy_PropertyRNA \"%s\" -> \"%s\" -> \"%s\" ]", RNA_struct_identifier(self->ptr.type), RNA_property_identifier(self->prop), name);
196 return PyUnicode_FromFormat( "[BPy_PropertyRNA \"%s\" -> \"%s\"]", RNA_struct_identifier(self->ptr.type), RNA_property_identifier(self->prop));
199 static long pyrna_struct_hash( BPy_StructRNA * self )
201 return (long)self->ptr.data;
204 /* use our own dealloc so we can free a property if we use one */
205 static void pyrna_struct_dealloc( BPy_StructRNA * self )
207 /* Note!! for some weired reason calling PyObject_DEL() directly crashes blender! */
208 if (self->freeptr && self->ptr.data) {
209 IDP_FreeProperty(self->ptr.data);
210 MEM_freeN(self->ptr.data);
211 self->ptr.data= NULL;
214 Py_TYPE(self)->tp_free(self);
218 static char *pyrna_enum_as_string(PointerRNA *ptr, PropertyRNA *prop)
220 const EnumPropertyItem *item;
222 RNA_property_enum_items(ptr, prop, &item, NULL);
223 return (char*)BPy_enum_as_string((EnumPropertyItem*)item);
226 PyObject * pyrna_prop_to_py(PointerRNA *ptr, PropertyRNA *prop)
229 int type = RNA_property_type(prop);
230 int len = RNA_property_array_length(prop);
233 /* resolve the array from a new pytype */
234 PyObject *ret = pyrna_prop_CreatePyObject(ptr, prop);
237 /* return a mathutils vector where possible */
238 if(RNA_property_type(prop)==PROP_FLOAT) {
239 if(RNA_property_subtype(prop)==PROP_VECTOR) {
240 if(len>=2 && len <= 4) {
241 PyObject *vec_cb= newVectorObject_cb(ret, len, mathutils_rna_vector_cb_index, 0);
242 Py_DECREF(ret); /* the vector owns now */
243 ret= vec_cb; /* return the vector instead */
246 else if(RNA_property_subtype(prop)==PROP_MATRIX) {
248 PyObject *mat_cb= newMatrixObject_cb(ret, 4,4, mathutils_rna_vector_cb_index, 0);
249 Py_DECREF(ret); /* the matrix owns now */
250 ret= mat_cb; /* return the matrix instead */
253 PyObject *mat_cb= newMatrixObject_cb(ret, 3,3, mathutils_rna_vector_cb_index, 0);
254 Py_DECREF(ret); /* the matrix owns now */
255 ret= mat_cb; /* return the matrix instead */
265 /* see if we can coorce into a python type - PropertyType */
268 ret = PyBool_FromLong( RNA_property_boolean_get(ptr, prop) );
271 ret = PyLong_FromSsize_t( (Py_ssize_t)RNA_property_int_get(ptr, prop) );
274 ret = PyFloat_FromDouble( RNA_property_float_get(ptr, prop) );
279 buf = RNA_property_string_get_alloc(ptr, prop, NULL, -1);
280 ret = PyUnicode_FromString( buf );
286 const char *identifier;
287 int val = RNA_property_enum_get(ptr, prop);
289 if (RNA_property_enum_identifier(ptr, prop, val, &identifier)) {
290 ret = PyUnicode_FromString( identifier );
292 PyErr_Format(PyExc_AttributeError, "RNA Error: Current value \"%d\" matches no enum", val);
301 newptr= RNA_property_pointer_get(ptr, prop);
303 ret = pyrna_struct_CreatePyObject(&newptr);
310 case PROP_COLLECTION:
311 ret = pyrna_prop_CreatePyObject(ptr, prop);
314 PyErr_Format(PyExc_AttributeError, "RNA Error: unknown type \"%d\" (pyrna_prop_to_py)", type);
322 /* This function is only used by operators right now
323 * Its used for taking keyword args and filling in property values */
324 int pyrna_pydict_to_props(PointerRNA *ptr, PyObject *kw, const char *error_prefix)
328 const char *arg_name= NULL;
331 totkw = kw ? PyDict_Size(kw):0;
333 RNA_STRUCT_BEGIN(ptr, prop) {
334 arg_name= RNA_property_identifier(prop);
336 if (strcmp(arg_name, "rna_type")==0) continue;
339 PyErr_Format( PyExc_AttributeError, "%s: no keywords, expected \"%s\"", error_prefix, arg_name ? arg_name : "<UNKNOWN>");
344 item= PyDict_GetItemString(kw, arg_name);
347 PyErr_Format( PyExc_AttributeError, "%s: keyword \"%s\" missing", error_prefix, arg_name ? arg_name : "<UNKNOWN>");
348 error_val = -1; /* pyrna_py_to_prop sets the error */
352 if (pyrna_py_to_prop(ptr, prop, NULL, item)) {
361 if (error_val==0 && totkw > 0) { /* some keywords were given that were not used :/ */
362 PyObject *key, *value;
365 while (PyDict_Next(kw, &pos, &key, &value)) {
366 arg_name= _PyUnicode_AsString(key);
367 if (RNA_struct_find_property(ptr, arg_name) == NULL) break;
371 PyErr_Format( PyExc_AttributeError, "%s: keyword \"%s\" unrecognized", error_prefix, arg_name ? arg_name : "<UNKNOWN>");
378 static PyObject * pyrna_func_call(PyObject * self, PyObject *args, PyObject *kw);
380 PyObject *pyrna_func_to_py(PointerRNA *ptr, FunctionRNA *func)
382 static PyMethodDef func_meth = {"<generic rna function>", (PyCFunction)pyrna_func_call, METH_VARARGS|METH_KEYWORDS, "python rna function"};
383 PyObject *self= PyTuple_New(2);
385 PyTuple_SET_ITEM(self, 0, pyrna_struct_CreatePyObject(ptr));
386 PyTuple_SET_ITEM(self, 1, PyCObject_FromVoidPtr((void *)func, NULL));
388 ret= PyCFunction_New(&func_meth, self);
395 int pyrna_py_to_prop(PointerRNA *ptr, PropertyRNA *prop, void *data, PyObject *value)
397 /* XXX hard limits should be checked here */
398 int type = RNA_property_type(prop);
399 int len = RNA_property_array_length(prop);
408 if(MatrixObject_Check(value)) {
409 MatrixObject *mat = (MatrixObject*)value;
410 if(!Matrix_ReadCallback(mat))
413 py_len = mat->rowSize * mat->colSize;
414 } else // continue...
416 if (PySequence_Check(value)) {
417 py_len= (int)PySequence_Length(value);
420 PyErr_SetString(PyExc_TypeError, "expected a python sequence type assigned to an RNA array.");
423 /* done getting the length */
426 PyErr_SetString(PyExc_AttributeError, "python sequence length did not match the RNA array.");
430 /* for arrays we have a limited number of types */
435 if(data) param_arr= (int*)data;
436 else param_arr= MEM_mallocN(sizeof(char) * len, "pyrna bool array");
439 /* collect the variables before assigning, incase one of them is incorrect */
440 for (i=0; i<len; i++) {
441 item = PySequence_GetItem(value, i);
442 param_arr[i] = PyObject_IsTrue( item );
445 if (param_arr[i] < 0) {
447 MEM_freeN(param_arr);
448 PyErr_SetString(PyExc_AttributeError, "one or more of the values in the sequence is not a boolean");
453 RNA_property_boolean_set_array(ptr, prop, param_arr);
454 MEM_freeN(param_arr);
462 if(data) param_arr= (int*)data;
463 else param_arr= MEM_mallocN(sizeof(int) * len, "pyrna int array");
466 /* collect the variables */
467 for (i=0; i<len; i++) {
468 item = PySequence_GetItem(value, i);
469 param_arr[i] = (int)PyLong_AsSsize_t(item); /* deal with any errors later */
473 if (PyErr_Occurred()) {
475 MEM_freeN(param_arr);
476 PyErr_SetString(PyExc_AttributeError, "one or more of the values in the sequence could not be used as an int");
480 RNA_property_int_set_array(ptr, prop, param_arr);
481 MEM_freeN(param_arr);
488 if(data) param_arr = (float*)data;
489 else param_arr = MEM_mallocN(sizeof(float) * len, "pyrna float array");
493 if(MatrixObject_Check(value) && RNA_property_subtype(prop) == PROP_MATRIX) {
494 MatrixObject *mat = (MatrixObject*)value;
495 memcpy(param_arr, mat->contigPtr, sizeof(float) * len);
496 } else // continue...
499 /* collect the variables */
500 for (i=0; i<len; i++) {
501 item = PySequence_GetItem(value, i);
502 param_arr[i] = (float)PyFloat_AsDouble(item); /* deal with any errors later */
507 if (PyErr_Occurred()) {
509 MEM_freeN(param_arr);
510 PyErr_SetString(PyExc_AttributeError, "one or more of the values in the sequence could not be used as a float");
514 RNA_property_float_set_array(ptr, prop, param_arr);
515 MEM_freeN(param_arr);
521 /* Normal Property (not an array) */
523 /* see if we can coorce into a python type - PropertyType */
527 int param = PyObject_IsTrue( value );
530 PyErr_SetString(PyExc_TypeError, "expected True/False or 0/1");
533 if(data) *((int*)data)= param;
534 else RNA_property_boolean_set(ptr, prop, param);
540 int param = PyLong_AsSsize_t(value);
541 if (PyErr_Occurred()) {
542 PyErr_SetString(PyExc_TypeError, "expected an int type");
545 if(data) *((int*)data)= param;
546 else RNA_property_int_set(ptr, prop, param);
552 float param = PyFloat_AsDouble(value);
553 if (PyErr_Occurred()) {
554 PyErr_SetString(PyExc_TypeError, "expected a float type");
557 if(data) *((float*)data)= param;
558 else RNA_property_float_set(ptr, prop, param);
564 char *param = _PyUnicode_AsString(value);
567 PyErr_SetString(PyExc_TypeError, "expected a string type");
570 if(data) *((char**)data)= param;
571 else RNA_property_string_set(ptr, prop, param);
577 char *param = _PyUnicode_AsString(value);
580 char *enum_str= pyrna_enum_as_string(ptr, prop);
581 PyErr_Format(PyExc_TypeError, "expected a string enum type in (%s)", enum_str);
586 if (RNA_property_enum_value(ptr, prop, param, &val)) {
587 if(data) *((int*)data)= val;
588 else RNA_property_enum_set(ptr, prop, val);
590 char *enum_str= pyrna_enum_as_string(ptr, prop);
591 PyErr_Format(PyExc_AttributeError, "enum \"%s\" not found in (%s)", param, enum_str);
601 StructRNA *ptype= RNA_property_pointer_type(ptr, prop);
603 if(!BPy_StructRNA_Check(value) && value != Py_None) {
605 RNA_pointer_create(NULL, ptype, NULL, &tmp);
606 PyErr_Format(PyExc_TypeError, "expected a %s type", RNA_struct_identifier(tmp.type));
609 BPy_StructRNA *param= (BPy_StructRNA*)value;
612 int flag = RNA_property_flag(prop);
614 if(flag & PROP_RNAPTR) {
616 memset(data, 0, sizeof(PointerRNA));
618 *((PointerRNA*)data)= param->ptr;
620 else if(value == Py_None) {
621 *((void**)data)= NULL;
623 else if(RNA_struct_is_a(param->ptr.type, ptype)) {
624 *((void**)data)= param->ptr.data;
631 /* data==NULL, assign to RNA */
632 if(value == Py_None) {
634 memset(&valueptr, 0, sizeof(valueptr));
635 RNA_property_pointer_set(ptr, prop, valueptr);
637 else if(RNA_struct_is_a(param->ptr.type, ptype)) {
638 RNA_property_pointer_set(ptr, prop, param->ptr);
642 RNA_pointer_create(NULL, ptype, NULL, &tmp);
643 PyErr_Format(PyExc_TypeError, "expected a %s type", RNA_struct_identifier(tmp.type));
650 RNA_pointer_create(NULL, ptype, NULL, &tmp);
651 PyErr_Format(PyExc_TypeError, "expected a %s type", RNA_struct_identifier(tmp.type));
657 case PROP_COLLECTION:
663 /* convert a sequence of dict's into a collection */
664 if(!PySequence_Check(value)) {
665 PyErr_SetString(PyExc_TypeError, "expected a sequence of dicts for an RNA collection");
669 seq_len = PySequence_Length(value);
670 for(i=0; i<seq_len; i++) {
671 item= PySequence_GetItem(value, i);
672 if(item==NULL || PyDict_Check(item)==0) {
673 PyErr_SetString(PyExc_TypeError, "expected a sequence of dicts for an RNA collection");
678 RNA_property_collection_add(ptr, prop, &itemptr);
679 if(pyrna_pydict_to_props(&itemptr, item, "Converting a python list to an RNA collection")==-1) {
689 PyErr_SetString(PyExc_AttributeError, "unknown property type (pyrna_py_to_prop)");
698 static PyObject * pyrna_prop_to_py_index(PointerRNA *ptr, PropertyRNA *prop, int index)
701 int type = RNA_property_type(prop);
703 /* see if we can coorce into a python type - PropertyType */
706 ret = PyBool_FromLong( RNA_property_boolean_get_index(ptr, prop, index) );
709 ret = PyLong_FromSsize_t( (Py_ssize_t)RNA_property_int_get_index(ptr, prop, index) );
712 ret = PyFloat_FromDouble( RNA_property_float_get_index(ptr, prop, index) );
715 PyErr_SetString(PyExc_AttributeError, "not an array type");
723 static int pyrna_py_to_prop_index(PointerRNA *ptr, PropertyRNA *prop, int index, PyObject *value)
726 int type = RNA_property_type(prop);
728 /* see if we can coorce into a python type - PropertyType */
732 int param = PyObject_IsTrue( value );
735 PyErr_SetString(PyExc_TypeError, "expected True/False or 0/1");
738 RNA_property_boolean_set_index(ptr, prop, index, param);
744 int param = PyLong_AsSsize_t(value);
745 if (PyErr_Occurred()) {
746 PyErr_SetString(PyExc_TypeError, "expected an int type");
749 RNA_property_int_set_index(ptr, prop, index, param);
755 float param = PyFloat_AsDouble(value);
756 if (PyErr_Occurred()) {
757 PyErr_SetString(PyExc_TypeError, "expected a float type");
760 RNA_property_float_set_index(ptr, prop, index, param);
765 PyErr_SetString(PyExc_AttributeError, "not an array type");
773 //---------------sequence-------------------------------------------
774 static Py_ssize_t pyrna_prop_len( BPy_PropertyRNA * self )
778 if (RNA_property_type(self->prop) == PROP_COLLECTION) {
779 len = RNA_property_collection_length(&self->ptr, self->prop);
781 len = RNA_property_array_length(self->prop);
783 if (len==0) { /* not an array*/
784 PyErr_SetString(PyExc_AttributeError, "len() only available for collection RNA types");
792 static PyObject *pyrna_prop_subscript( BPy_PropertyRNA * self, PyObject *key )
797 char *keyname = NULL;
799 if (PyUnicode_Check(key)) {
800 keyname = _PyUnicode_AsString(key);
801 } else if (PyLong_Check(key)) {
802 keynum = PyLong_AsSsize_t(key);
804 PyErr_SetString(PyExc_AttributeError, "invalid key, key must be a string or an int");
808 if (RNA_property_type(self->prop) == PROP_COLLECTION) {
810 if (keyname) ok = RNA_property_collection_lookup_string(&self->ptr, self->prop, keyname, &newptr);
811 else ok = RNA_property_collection_lookup_int(&self->ptr, self->prop, keynum, &newptr);
814 ret = pyrna_struct_CreatePyObject(&newptr);
816 PyErr_SetString(PyExc_AttributeError, "out of range");
820 } else if (keyname) {
821 PyErr_SetString(PyExc_AttributeError, "string keys are only supported for collections");
824 int len = RNA_property_array_length(self->prop);
826 if (len==0) { /* not an array*/
827 PyErr_Format(PyExc_AttributeError, "not an array or collection %d", keynum);
832 PyErr_SetString(PyExc_AttributeError, "index out of range");
834 } else { /* not an array*/
835 ret = pyrna_prop_to_py_index(&self->ptr, self->prop, keynum);
843 static int pyrna_prop_assign_subscript( BPy_PropertyRNA * self, PyObject *key, PyObject *value )
847 char *keyname = NULL;
849 if (!RNA_property_editable(&self->ptr, self->prop)) {
850 PyErr_Format( PyExc_AttributeError, "PropertyRNA - attribute \"%s\" from \"%s\" is read-only", RNA_property_identifier(self->prop), RNA_struct_identifier(self->ptr.type) );
854 if (PyUnicode_Check(key)) {
855 keyname = _PyUnicode_AsString(key);
856 } else if (PyLong_Check(key)) {
857 keynum = PyLong_AsSsize_t(key);
859 PyErr_SetString(PyExc_AttributeError, "PropertyRNA - invalid key, key must be a string or an int");
863 if (RNA_property_type(self->prop) == PROP_COLLECTION) {
864 PyErr_SetString(PyExc_AttributeError, "PropertyRNA - assignment is not supported for collections (yet)");
866 } else if (keyname) {
867 PyErr_SetString(PyExc_AttributeError, "PropertyRNA - string keys are only supported for collections");
870 int len = RNA_property_array_length(self->prop);
872 if (len==0) { /* not an array*/
873 PyErr_Format(PyExc_AttributeError, "PropertyRNA - not an array or collection %d", keynum);
878 PyErr_SetString(PyExc_AttributeError, "PropertyRNA - index out of range");
881 ret = pyrna_py_to_prop_index(&self->ptr, self->prop, keynum, value);
890 static PyMappingMethods pyrna_prop_as_mapping = {
891 ( lenfunc ) pyrna_prop_len, /* mp_length */
892 ( binaryfunc ) pyrna_prop_subscript, /* mp_subscript */
893 ( objobjargproc ) pyrna_prop_assign_subscript, /* mp_ass_subscript */
896 static int pyrna_prop_contains(BPy_PropertyRNA * self, PyObject *value)
898 PointerRNA newptr; /* not used, just so RNA_property_collection_lookup_string runs */
899 char *keyname = _PyUnicode_AsString(value);
902 PyErr_SetString(PyExc_TypeError, "PropertyRNA - key in prop, key must be a string type");
906 if (RNA_property_type(self->prop) != PROP_COLLECTION) {
907 PyErr_SetString(PyExc_TypeError, "PropertyRNA - key in prop, is only valid for collection types");
912 if (RNA_property_collection_lookup_string(&self->ptr, self->prop, keyname, &newptr))
918 static PySequenceMethods pyrna_prop_as_sequence = {
919 NULL, /* Cant set the len otherwise it can evaluate as false */
920 NULL, /* sq_concat */
921 NULL, /* sq_repeat */
924 NULL, /* sq_ass_item */
925 NULL, /* sq_ass_slice */
926 (objobjproc)pyrna_prop_contains, /* sq_contains */
929 static PyObject *pyrna_struct_dir(BPy_StructRNA * self)
931 PyObject *ret, *dict;
934 /* for looping over attrs and funcs */
935 PropertyRNA *iterprop;
937 /* Include this incase this instance is a subtype of a python class
938 * In these instances we may want to return a function or variable provided by the subtype
941 if (BPy_StructRNA_CheckExact(self)) {
944 pystring = PyUnicode_FromString("__dict__");
945 dict = PyObject_GenericGetAttr((PyObject *)self, pystring);
953 ret = PyDict_Keys(dict);
958 /* Collect RNA items*/
961 * Collect RNA attributes
963 char name[256], *nameptr;
965 iterprop= RNA_struct_iterator_property(self->ptr.type);
967 RNA_PROP_BEGIN(&self->ptr, itemptr, iterprop) {
968 nameptr= RNA_struct_name_get_alloc(&itemptr, name, sizeof(name));
971 pystring = PyUnicode_FromString(nameptr);
972 PyList_Append(ret, pystring);
985 * Collect RNA function items
989 RNA_pointer_create(NULL, &RNA_Struct, self->ptr.type, &tptr);
990 iterprop= RNA_struct_find_property(&tptr, "functions");
992 RNA_PROP_BEGIN(&tptr, itemptr, iterprop) {
993 pystring = PyUnicode_FromString(RNA_function_identifier(itemptr.data));
994 PyList_Append(ret, pystring);
1000 if(self->ptr.type == &RNA_Context) {
1001 ListBase lb = CTX_data_dir_get(self->ptr.data);
1004 for(link=lb.first; link; link=link->next) {
1005 pystring = PyUnicode_FromString(link->data);
1006 PyList_Append(ret, pystring);
1007 Py_DECREF(pystring);
1017 //---------------getattr--------------------------------------------
1018 static PyObject *pyrna_struct_getattro( BPy_StructRNA * self, PyObject *pyname )
1020 char *name = _PyUnicode_AsString(pyname);
1025 /* Include this incase this instance is a subtype of a python class
1026 * In these instances we may want to return a function or variable provided by the subtype
1028 * Also needed to return methods when its not a subtype
1030 ret = PyObject_GenericGetAttr((PyObject *)self, pyname);
1031 if (ret) return ret;
1033 /* done with subtypes */
1035 if ((prop = RNA_struct_find_property(&self->ptr, name))) {
1036 ret = pyrna_prop_to_py(&self->ptr, prop);
1038 else if ((func = RNA_struct_find_function(&self->ptr, name))) {
1039 ret = pyrna_func_to_py(&self->ptr, func);
1041 else if (self->ptr.type == &RNA_Context) {
1045 CTX_data_get(self->ptr.data, name, &newptr, &newlb);
1048 ret = pyrna_struct_CreatePyObject(&newptr);
1050 else if (newlb.first) {
1051 CollectionPointerLink *link;
1054 ret = PyList_New(0);
1056 for(link=newlb.first; link; link=link->next) {
1057 linkptr= pyrna_struct_CreatePyObject(&link->ptr);
1058 PyList_Append(ret, linkptr);
1067 BLI_freelistN(&newlb);
1070 PyErr_Format( PyExc_AttributeError, "StructRNA - Attribute \"%s\" not found", name);
1077 //--------------- setattr-------------------------------------------
1078 static int pyrna_struct_setattro( BPy_StructRNA * self, PyObject *pyname, PyObject * value )
1080 char *name = _PyUnicode_AsString(pyname);
1081 PropertyRNA *prop = RNA_struct_find_property(&self->ptr, name);
1084 if (!BPy_StructRNA_CheckExact(self) && PyObject_GenericSetAttr((PyObject *)self, pyname, value) >= 0) {
1088 PyErr_Format( PyExc_AttributeError, "StructRNA - Attribute \"%s\" not found", name);
1093 if (!RNA_property_editable(&self->ptr, prop)) {
1094 PyErr_Format( PyExc_AttributeError, "StructRNA - Attribute \"%s\" from \"%s\" is read-only", RNA_property_identifier(prop), RNA_struct_identifier(self->ptr.type) );
1098 /* pyrna_py_to_prop sets its own exceptions */
1099 return pyrna_py_to_prop(&self->ptr, prop, NULL, value);
1102 PyObject *pyrna_prop_keys(BPy_PropertyRNA *self)
1105 if (RNA_property_type(self->prop) != PROP_COLLECTION) {
1106 PyErr_SetString( PyExc_TypeError, "keys() is only valid for collection types" );
1110 char name[256], *nameptr;
1112 ret = PyList_New(0);
1114 RNA_PROP_BEGIN(&self->ptr, itemptr, self->prop) {
1115 nameptr= RNA_struct_name_get_alloc(&itemptr, name, sizeof(name));
1118 /* add to python list */
1119 item = PyUnicode_FromString( nameptr );
1120 PyList_Append(ret, item);
1134 PyObject *pyrna_prop_items(BPy_PropertyRNA *self)
1137 if (RNA_property_type(self->prop) != PROP_COLLECTION) {
1138 PyErr_SetString( PyExc_TypeError, "items() is only valid for collection types" );
1142 char name[256], *nameptr;
1145 ret = PyList_New(0);
1147 RNA_PROP_BEGIN(&self->ptr, itemptr, self->prop) {
1149 /* add to python list */
1150 item= PyTuple_New(2);
1151 nameptr= RNA_struct_name_get_alloc(&itemptr, name, sizeof(name));
1153 PyTuple_SET_ITEM(item, 0, PyUnicode_FromString( nameptr ));
1158 PyTuple_SET_ITEM(item, 0, PyLong_FromSsize_t(i)); /* a bit strange but better then returning an empty list */
1160 PyTuple_SET_ITEM(item, 1, pyrna_struct_CreatePyObject(&itemptr));
1162 PyList_Append(ret, item);
1175 PyObject *pyrna_prop_values(BPy_PropertyRNA *self)
1179 if (RNA_property_type(self->prop) != PROP_COLLECTION) {
1180 PyErr_SetString( PyExc_TypeError, "values() is only valid for collection types" );
1184 ret = PyList_New(0);
1186 RNA_PROP_BEGIN(&self->ptr, itemptr, self->prop) {
1187 item = pyrna_struct_CreatePyObject(&itemptr);
1188 PyList_Append(ret, item);
1197 /* A bit of a kludge, make a list out of a collection or array,
1198 * then return the lists iter function, not especially fast but convenient for now */
1199 PyObject *pyrna_prop_iter(BPy_PropertyRNA *self)
1201 /* Try get values from a collection */
1202 PyObject *ret = pyrna_prop_values(self);
1205 /* collection did not work, try array */
1206 int len = RNA_property_array_length(self->prop);
1211 ret = PyList_New(len);
1213 for (i=0; i < len; i++) {
1214 PyList_SET_ITEM(ret, i, pyrna_prop_to_py_index(&self->ptr, self->prop, i));
1220 /* we know this is a list so no need to PyIter_Check */
1221 PyObject *iter = PyObject_GetIter(ret);
1226 PyErr_SetString( PyExc_TypeError, "this BPy_PropertyRNA object is not iterable" );
1230 static struct PyMethodDef pyrna_struct_methods[] = {
1231 {"__dir__", (PyCFunction)pyrna_struct_dir, METH_NOARGS, ""},
1232 {NULL, NULL, 0, NULL}
1235 static struct PyMethodDef pyrna_prop_methods[] = {
1236 {"keys", (PyCFunction)pyrna_prop_keys, METH_NOARGS, ""},
1237 {"items", (PyCFunction)pyrna_prop_items, METH_NOARGS, ""},
1238 {"values", (PyCFunction)pyrna_prop_values, METH_NOARGS, ""},
1239 {NULL, NULL, 0, NULL}
1242 /* only needed for subtyping, so a new class gets a valid BPy_StructRNA
1243 * todo - also accept useful args */
1244 static PyObject * pyrna_struct_new(PyTypeObject *type, PyObject *args, PyObject *kwds) {
1246 BPy_StructRNA *base = NULL;
1248 if (!PyArg_ParseTuple(args, "O!:Base BPy_StructRNA", &pyrna_struct_Type, &base))
1251 if (type == &pyrna_struct_Type) {
1252 return pyrna_struct_CreatePyObject(&base->ptr);
1254 BPy_StructRNA *ret = (BPy_StructRNA *) type->tp_alloc(type, 0);
1255 ret->ptr = base->ptr;
1256 return (PyObject *)ret;
1260 /* only needed for subtyping, so a new class gets a valid BPy_StructRNA
1261 * todo - also accept useful args */
1262 static PyObject * pyrna_prop_new(PyTypeObject *type, PyObject *args, PyObject *kwds) {
1264 BPy_PropertyRNA *base = NULL;
1266 if (!PyArg_ParseTuple(args, "O!:Base BPy_PropertyRNA", &pyrna_prop_Type, &base))
1269 if (type == &pyrna_prop_Type) {
1270 return pyrna_prop_CreatePyObject(&base->ptr, base->prop);
1272 BPy_PropertyRNA *ret = (BPy_PropertyRNA *) type->tp_alloc(type, 0);
1273 ret->ptr = base->ptr;
1274 ret->prop = base->prop;
1275 return (PyObject *)ret;
1279 PyObject *pyrna_param_to_py(PointerRNA *ptr, PropertyRNA *prop, void *data)
1282 int type = RNA_property_type(prop);
1283 int len = RNA_property_array_length(prop);
1288 /* resolve the array from a new pytype */
1289 ret = PyTuple_New(len);
1293 for(a=0; a<len; a++)
1294 PyTuple_SET_ITEM(ret, a, PyBool_FromLong( ((int*)data)[a] ));
1297 for(a=0; a<len; a++)
1298 PyTuple_SET_ITEM(ret, a, PyLong_FromSsize_t( (Py_ssize_t)((int*)data)[a] ));
1301 for(a=0; a<len; a++)
1302 PyTuple_SET_ITEM(ret, a, PyFloat_FromDouble( ((float*)data)[a] ));
1305 PyErr_Format(PyExc_AttributeError, "RNA Error: unknown array type \"%d\" (pyrna_param_to_py)", type);
1311 /* see if we can coorce into a python type - PropertyType */
1314 ret = PyBool_FromLong( *(int*)data );
1317 ret = PyLong_FromSsize_t( (Py_ssize_t)*(int*)data );
1320 ret = PyFloat_FromDouble( *(float*)data );
1324 ret = PyUnicode_FromString( *(char**)data );
1329 const char *identifier;
1330 int val = *(int*)data;
1332 if (RNA_property_enum_identifier(ptr, prop, val, &identifier)) {
1333 ret = PyUnicode_FromString( identifier );
1335 PyErr_Format(PyExc_AttributeError, "RNA Error: Current value \"%d\" matches no enum", val);
1344 StructRNA *type= RNA_property_pointer_type(ptr, prop);
1345 int flag = RNA_property_flag(prop);
1347 if(flag & PROP_RNAPTR) {
1348 /* in this case we get the full ptr */
1349 newptr= *(PointerRNA*)data;
1352 /* XXX this is missing the ID part! */
1353 RNA_pointer_create(NULL, type, *(void**)data, &newptr);
1357 ret = pyrna_struct_CreatePyObject(&newptr);
1364 case PROP_COLLECTION:
1365 /* XXX not supported yet
1366 * ret = pyrna_prop_CreatePyObject(ptr, prop); */
1370 PyErr_Format(PyExc_AttributeError, "RNA Error: unknown type \"%d\" (pyrna_param_to_py)", type);
1379 static PyObject * pyrna_func_call(PyObject * self, PyObject *args, PyObject *kw)
1381 PointerRNA *self_ptr= &(((BPy_StructRNA *)PyTuple_GET_ITEM(self, 0))->ptr);
1382 FunctionRNA *self_func= PyCObject_AsVoidPtr(PyTuple_GET_ITEM(self, 1));
1385 ParameterList *parms;
1386 ParameterIterator iter;
1387 PropertyRNA *pret, *parm;
1388 PyObject *ret, *item;
1389 int i, tlen, flag, err= 0;
1390 const char *tid, *fid, *pid;
1391 void *retdata= NULL;
1394 RNA_pointer_create(NULL, &RNA_Function, self_func, &funcptr);
1396 pret= RNA_function_return(self_func);
1397 tlen= PyTuple_GET_SIZE(args);
1399 parms= RNA_parameter_list_create(self_ptr, self_func);
1400 RNA_parameter_list_begin(parms, &iter);
1402 /* parse function parameters */
1403 for (i= 0; iter.valid; RNA_parameter_list_next(&iter)) {
1411 pid= RNA_property_identifier(parm);
1412 flag= RNA_property_flag(parm);
1415 if ((i < tlen) && (flag & PROP_REQUIRED)) {
1416 item= PyTuple_GET_ITEM(args, i);
1419 else if (kw != NULL)
1420 item= PyDict_GetItemString(kw, pid); /* borrow ref */
1423 if(flag & PROP_REQUIRED) {
1424 tid= RNA_struct_identifier(self_ptr->type);
1425 fid= RNA_function_identifier(self_func);
1427 PyErr_Format(PyExc_AttributeError, "%s.%s(): required parameter \"%s\" not specified", tid, fid, pid);
1435 err= pyrna_py_to_prop(&funcptr, parm, iter.data, item);
1445 bContext *C= BPy_GetContext();
1447 BKE_reports_init(&reports, RPT_STORE);
1448 RNA_function_call(C, &reports, self_ptr, self_func, parms);
1450 err= (BPy_reports_to_error(&reports))? -1: 0;
1451 BKE_reports_clear(&reports);
1456 ret= pyrna_param_to_py(&funcptr, pret, retdata);
1460 RNA_parameter_list_end(&iter);
1461 RNA_parameter_list_free(parms);
1472 /*-----------------------BPy_StructRNA method def------------------------------*/
1473 PyTypeObject pyrna_struct_Type = {
1474 #if (PY_VERSION_HEX >= 0x02060000)
1475 PyVarObject_HEAD_INIT(NULL, 0)
1477 /* python 2.5 and below */
1478 PyObject_HEAD_INIT( NULL ) /* required py macro */
1481 "StructRNA", /* tp_name */
1482 sizeof( BPy_StructRNA ), /* tp_basicsize */
1483 0, /* tp_itemsize */
1485 ( destructor ) pyrna_struct_dealloc,/* tp_dealloc */
1486 NULL, /* printfunc tp_print; */
1487 NULL, /* getattrfunc tp_getattr; */
1488 NULL, /* setattrfunc tp_setattr; */
1489 NULL, /* tp_compare */ /* DEPRECATED in python 3.0! */
1490 ( reprfunc ) pyrna_struct_repr, /* tp_repr */
1492 /* Method suites for standard classes */
1494 NULL, /* PyNumberMethods *tp_as_number; */
1495 NULL, /* PySequenceMethods *tp_as_sequence; */
1496 NULL, /* PyMappingMethods *tp_as_mapping; */
1498 /* More standard operations (here for binary compatibility) */
1500 ( hashfunc )pyrna_struct_hash, /* hashfunc tp_hash; */
1501 NULL, /* ternaryfunc tp_call; */
1502 NULL, /* reprfunc tp_str; */
1503 ( getattrofunc ) pyrna_struct_getattro, /* getattrofunc tp_getattro; */
1504 ( setattrofunc ) pyrna_struct_setattro, /* setattrofunc tp_setattro; */
1506 /* Functions to access object as input/output buffer */
1507 NULL, /* PyBufferProcs *tp_as_buffer; */
1509 /*** Flags to define presence of optional/expanded features ***/
1510 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE, /* long tp_flags; */
1512 NULL, /* char *tp_doc; Documentation string */
1513 /*** Assigned meaning in release 2.0 ***/
1514 /* call function for all accessible objects */
1515 NULL, /* traverseproc tp_traverse; */
1517 /* delete references to contained objects */
1518 NULL, /* inquiry tp_clear; */
1520 /*** Assigned meaning in release 2.1 ***/
1521 /*** rich comparisons ***/
1522 (richcmpfunc)pyrna_struct_richcmp, /* richcmpfunc tp_richcompare; */
1524 /*** weak reference enabler ***/
1525 0, /* long tp_weaklistoffset; */
1527 /*** Added in release 2.2 ***/
1529 NULL, /* getiterfunc tp_iter; */
1530 NULL, /* iternextfunc tp_iternext; */
1532 /*** Attribute descriptor and subclassing stuff ***/
1533 pyrna_struct_methods, /* struct PyMethodDef *tp_methods; */
1534 NULL, /* struct PyMemberDef *tp_members; */
1535 NULL, /* struct PyGetSetDef *tp_getset; */
1536 NULL, /* struct _typeobject *tp_base; */
1537 NULL, /* PyObject *tp_dict; */
1538 NULL, /* descrgetfunc tp_descr_get; */
1539 NULL, /* descrsetfunc tp_descr_set; */
1540 0, /* long tp_dictoffset; */
1541 NULL, /* initproc tp_init; */
1542 NULL, /* allocfunc tp_alloc; */
1543 pyrna_struct_new, /* newfunc tp_new; */
1544 /* Low-level free-memory routine */
1545 NULL, /* freefunc tp_free; */
1546 /* For PyObject_IS_GC */
1547 NULL, /* inquiry tp_is_gc; */
1548 NULL, /* PyObject *tp_bases; */
1549 /* method resolution order */
1550 NULL, /* PyObject *tp_mro; */
1551 NULL, /* PyObject *tp_cache; */
1552 NULL, /* PyObject *tp_subclasses; */
1553 NULL, /* PyObject *tp_weaklist; */
1557 /*-----------------------BPy_PropertyRNA method def------------------------------*/
1558 PyTypeObject pyrna_prop_Type = {
1559 #if (PY_VERSION_HEX >= 0x02060000)
1560 PyVarObject_HEAD_INIT(NULL, 0)
1562 /* python 2.5 and below */
1563 PyObject_HEAD_INIT( NULL ) /* required py macro */
1567 "PropertyRNA", /* tp_name */
1568 sizeof( BPy_PropertyRNA ), /* tp_basicsize */
1569 0, /* tp_itemsize */
1571 NULL, /* tp_dealloc */
1572 NULL, /* printfunc tp_print; */
1573 NULL, /* getattrfunc tp_getattr; */
1574 NULL, /* setattrfunc tp_setattr; */
1575 NULL, /* tp_compare */ /* DEPRECATED in python 3.0! */
1576 ( reprfunc ) pyrna_prop_repr, /* tp_repr */
1578 /* Method suites for standard classes */
1580 NULL, /* PyNumberMethods *tp_as_number; */
1581 &pyrna_prop_as_sequence, /* PySequenceMethods *tp_as_sequence; */
1582 &pyrna_prop_as_mapping, /* PyMappingMethods *tp_as_mapping; */
1584 /* More standard operations (here for binary compatibility) */
1586 NULL, /* hashfunc tp_hash; */
1587 NULL, /* ternaryfunc tp_call; */
1588 NULL, /* reprfunc tp_str; */
1589 NULL, /*PyObject_GenericGetAttr - MINGW Complains, assign later */ /* getattrofunc tp_getattro; */ /* will only use these if this is a subtype of a py class */
1590 NULL, /*PyObject_GenericSetAttr - MINGW Complains, assign later */ /* setattrofunc tp_setattro; */
1592 /* Functions to access object as input/output buffer */
1593 NULL, /* PyBufferProcs *tp_as_buffer; */
1595 /*** Flags to define presence of optional/expanded features ***/
1596 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE, /* long tp_flags; */
1598 NULL, /* char *tp_doc; Documentation string */
1599 /*** Assigned meaning in release 2.0 ***/
1600 /* call function for all accessible objects */
1601 NULL, /* traverseproc tp_traverse; */
1603 /* delete references to contained objects */
1604 NULL, /* inquiry tp_clear; */
1606 /*** Assigned meaning in release 2.1 ***/
1607 /*** rich comparisons ***/
1608 (richcmpfunc)pyrna_prop_richcmp, /* richcmpfunc tp_richcompare; */
1610 /*** weak reference enabler ***/
1611 0, /* long tp_weaklistoffset; */
1613 /*** Added in release 2.2 ***/
1615 (getiterfunc)pyrna_prop_iter, /* getiterfunc tp_iter; */
1616 NULL, /* iternextfunc tp_iternext; */
1618 /*** Attribute descriptor and subclassing stuff ***/
1619 pyrna_prop_methods, /* struct PyMethodDef *tp_methods; */
1620 NULL, /* struct PyMemberDef *tp_members; */
1621 NULL, /* struct PyGetSetDef *tp_getset; */
1622 NULL, /* struct _typeobject *tp_base; */
1623 NULL, /* PyObject *tp_dict; */
1624 NULL, /* descrgetfunc tp_descr_get; */
1625 NULL, /* descrsetfunc tp_descr_set; */
1626 0, /* long tp_dictoffset; */
1627 NULL, /* initproc tp_init; */
1628 NULL, /* allocfunc tp_alloc; */
1629 pyrna_prop_new, /* newfunc tp_new; */
1630 /* Low-level free-memory routine */
1631 NULL, /* freefunc tp_free; */
1632 /* For PyObject_IS_GC */
1633 NULL, /* inquiry tp_is_gc; */
1634 NULL, /* PyObject *tp_bases; */
1635 /* method resolution order */
1636 NULL, /* PyObject *tp_mro; */
1637 NULL, /* PyObject *tp_cache; */
1638 NULL, /* PyObject *tp_subclasses; */
1639 NULL, /* PyObject *tp_weaklist; */
1643 static void pyrna_subtype_set_rna(PyObject *newclass, StructRNA *srna)
1648 Py_INCREF(newclass);
1650 if (RNA_struct_py_type_get(srna))
1651 PyObSpit("RNA WAS SET - ", RNA_struct_py_type_get(srna));
1653 Py_XDECREF(((PyObject *)RNA_struct_py_type_get(srna)));
1655 RNA_struct_py_type_set(srna, (void *)newclass); /* Store for later use */
1657 /* Not 100% needed but useful,
1658 * having an instance within a type looks wrong however this instance IS an rna type */
1659 RNA_pointer_create(NULL, &RNA_Struct, srna, &ptr);
1660 item = pyrna_struct_CreatePyObject(&ptr);
1661 PyDict_SetItemString(((PyTypeObject *)newclass)->tp_dict, "__rna__", item);
1663 /* done with rna instance */
1666 PyObject* pyrna_struct_Subtype(PointerRNA *ptr)
1668 PyObject *newclass = NULL;
1669 PropertyRNA *nameprop;
1671 if (ptr->type==NULL) {
1672 newclass= NULL; /* Nothing to do */
1673 } else if ((newclass= RNA_struct_py_type_get(ptr->data))) {
1674 Py_INCREF(newclass);
1675 } else if ((nameprop = RNA_struct_name_property(ptr->type))) {
1676 /* for now, return the base RNA type rather then a real module */
1678 /* Assume RNA_struct_py_type_get(ptr->data) was alredy checked */
1680 /* subclass equivelents
1681 - class myClass(myBase):
1682 some='value' # or ...
1683 - myClass = type(name='myClass', bases=(myBase,), dict={'some':'value'})
1685 char name[256], *nameptr;
1686 const char *descr= RNA_struct_ui_description(ptr->type);
1688 PyObject *args = PyTuple_New(3);
1689 PyObject *bases = PyTuple_New(1);
1690 PyObject *dict = PyDict_New();
1694 nameptr= RNA_property_string_get_alloc(ptr, nameprop, name, sizeof(name));
1697 //PyTuple_SET_ITEM(args, 0, PyUnicode_FromString(tp_name));
1698 PyTuple_SET_ITEM(args, 0, PyUnicode_FromString(nameptr));
1701 PyTuple_SET_ITEM(bases, 0, (PyObject *)&pyrna_struct_Type);
1702 Py_INCREF(&pyrna_struct_Type);
1704 PyTuple_SET_ITEM(args, 1, bases);
1706 // arg 3 - add an instance of the rna
1708 item= PyUnicode_FromString(descr);
1709 PyDict_SetItemString(dict, "__doc__", item);
1713 PyTuple_SET_ITEM(args, 2, dict); // fill with useful subclass things!
1715 if (PyErr_Occurred()) {
1720 newclass = PyObject_CallObject((PyObject *)&PyType_Type, args);
1724 pyrna_subtype_set_rna(newclass, ptr->data);
1726 if (name != nameptr)
1733 /*-----------------------CreatePyObject---------------------------------*/
1734 PyObject *pyrna_struct_CreatePyObject( PointerRNA *ptr )
1736 BPy_StructRNA *pyrna= NULL;
1738 if (ptr->data==NULL && ptr->type==NULL) { /* Operator RNA has NULL data */
1742 if (ptr->type == &RNA_Struct) { /* always return a python subtype from rna struct types */
1743 PyTypeObject *tp = (PyTypeObject *)pyrna_struct_Subtype(ptr);
1746 pyrna = (BPy_StructRNA *) tp->tp_alloc(tp, 0);
1749 fprintf(stderr, "Could not make type\n");
1750 pyrna = ( BPy_StructRNA * ) PyObject_NEW( BPy_StructRNA, &pyrna_struct_Type );
1754 pyrna = ( BPy_StructRNA * ) PyObject_NEW( BPy_StructRNA, &pyrna_struct_Type );
1758 PyErr_SetString( PyExc_MemoryError, "couldn't create BPy_StructRNA object" );
1764 return ( PyObject * ) pyrna;
1767 PyObject *pyrna_prop_CreatePyObject( PointerRNA *ptr, PropertyRNA *prop )
1769 BPy_PropertyRNA *pyrna;
1771 pyrna = ( BPy_PropertyRNA * ) PyObject_NEW( BPy_PropertyRNA, &pyrna_prop_Type );
1774 PyErr_SetString( PyExc_MemoryError, "couldn't create BPy_rna object" );
1781 return ( PyObject * ) pyrna;
1784 PyObject *BPY_rna_module( void )
1788 #ifdef USE_MATHUTILS // register mathutils callbacks, ok to run more then once.
1789 mathutils_rna_vector_cb_index= Mathutils_RegisterCallback(&mathutils_rna_vector_cb);
1790 mathutils_rna_matrix_cb_index= Mathutils_RegisterCallback(&mathutils_rna_matrix_cb);
1793 /* This can't be set in the pytype struct because some compilers complain */
1794 pyrna_prop_Type.tp_getattro = PyObject_GenericGetAttr;
1795 pyrna_prop_Type.tp_setattro = PyObject_GenericSetAttr;
1797 if( PyType_Ready( &pyrna_struct_Type ) < 0 )
1800 if( PyType_Ready( &pyrna_prop_Type ) < 0 )
1803 /* for now, return the base RNA type rather then a real module */
1804 RNA_main_pointer_create(G.main, &ptr);
1806 return pyrna_struct_CreatePyObject(&ptr);
1810 /* This is a way we can access docstrings for RNA types
1811 * without having the datatypes in blender */
1812 PyObject *BPY_rna_doc( void )
1816 /* for now, return the base RNA type rather then a real module */
1817 RNA_blender_rna_pointer_create(&ptr);
1819 return pyrna_struct_CreatePyObject(&ptr);
1824 /* pyrna_basetype_* - BPy_BaseTypeRNA is just a BPy_PropertyRNA struct with a differnt type
1825 * the self->ptr and self->prop are always set to the "structs" collection */
1826 //---------------getattr--------------------------------------------
1827 static PyObject *pyrna_basetype_getattro( BPy_BaseTypeRNA * self, PyObject *pyname )
1832 ret = PyObject_GenericGetAttr((PyObject *)self, pyname);
1833 if (ret) return ret;
1836 if (RNA_property_collection_lookup_string(&self->ptr, self->prop, _PyUnicode_AsString(pyname), &newptr)) {
1837 ret= pyrna_struct_Subtype(&newptr);
1839 PyErr_Format(PyExc_SystemError, "bpy.types.%s subtype could not be generated, this is a bug!", _PyUnicode_AsString(pyname));
1843 else { /* Override the error */
1844 PyErr_Format(PyExc_AttributeError, "bpy.types.%s not a valid RNA_Struct", _PyUnicode_AsString(pyname));
1849 static PyObject *pyrna_basetype_dir(BPy_BaseTypeRNA *self);
1850 static struct PyMethodDef pyrna_basetype_methods[] = {
1851 {"__dir__", (PyCFunction)pyrna_basetype_dir, METH_NOARGS, ""},
1852 {"register", (PyCFunction)pyrna_basetype_register, METH_VARARGS, ""},
1853 {"unregister", (PyCFunction)pyrna_basetype_unregister, METH_VARARGS, ""},
1854 {NULL, NULL, 0, NULL}
1857 static PyObject *pyrna_basetype_dir(BPy_BaseTypeRNA *self)
1859 PyObject *list, *name;
1862 list= pyrna_prop_keys(self); /* like calling structs.keys(), avoids looping here */
1864 for(meth=pyrna_basetype_methods; meth->ml_name; meth++) {
1865 name = PyUnicode_FromString(meth->ml_name);
1866 PyList_Append(list, name);
1873 PyTypeObject pyrna_basetype_Type = BLANK_PYTHON_TYPE;
1875 PyObject *BPY_rna_types(void)
1877 BPy_BaseTypeRNA *self;
1879 if ((pyrna_basetype_Type.tp_flags & Py_TPFLAGS_READY)==0) {
1880 pyrna_basetype_Type.tp_name = "RNA_Types";
1881 pyrna_basetype_Type.tp_basicsize = sizeof( BPy_BaseTypeRNA );
1882 pyrna_basetype_Type.tp_getattro = ( getattrofunc )pyrna_basetype_getattro;
1883 pyrna_basetype_Type.tp_flags = Py_TPFLAGS_DEFAULT;
1884 pyrna_basetype_Type.tp_methods = pyrna_basetype_methods;
1886 if( PyType_Ready( &pyrna_basetype_Type ) < 0 )
1890 self= (BPy_BaseTypeRNA *)PyObject_NEW( BPy_BaseTypeRNA, &pyrna_basetype_Type );
1892 /* avoid doing this lookup for every getattr */
1893 RNA_blender_rna_pointer_create(&self->ptr);
1894 self->prop = RNA_struct_find_property(&self->ptr, "structs");
1896 return (PyObject *)self;
1899 static struct PyMethodDef props_methods[] = {
1900 {"FloatProperty", (PyCFunction)BPy_FloatProperty, METH_VARARGS|METH_KEYWORDS, ""},
1901 {"IntProperty", (PyCFunction)BPy_IntProperty, METH_VARARGS|METH_KEYWORDS, ""},
1902 {"BoolProperty", (PyCFunction)BPy_BoolProperty, METH_VARARGS|METH_KEYWORDS, ""},
1903 {"StringProperty", (PyCFunction)BPy_StringProperty, METH_VARARGS|METH_KEYWORDS, ""},
1904 {NULL, NULL, 0, NULL}
1907 #if PY_VERSION_HEX >= 0x03000000
1908 static struct PyModuleDef props_module = {
1909 PyModuleDef_HEAD_INIT,
1912 -1,/* multiple "initialization" just copies the module dict. */
1914 NULL, NULL, NULL, NULL
1918 PyObject *BPY_rna_props( void )
1920 PyObject *submodule, *mod;
1921 #if PY_VERSION_HEX >= 0x03000000
1922 submodule= PyModule_Create(&props_module);
1924 submodule= Py_InitModule3( "bpy.props", props_methods, "" );
1927 mod = PyModule_New("props");
1928 PyModule_AddObject( submodule, "props", mod );
1930 /* INCREF since its its assumed that all these functions return the
1931 * module with a new ref like PyDict_New, since they are passed to
1932 * PyModule_AddObject which steals a ref */
1933 Py_INCREF(submodule);
1938 /* Orphan functions, not sure where they should go */
1940 /* Function that sets RNA, NOTE - self is NULL when called from python, but being abused from C so we can pass the srna allong
1941 * This isnt incorrect since its a python object - but be careful */
1942 PyObject *BPy_FloatProperty(PyObject *self, PyObject *args, PyObject *kw)
1944 static char *kwlist[] = {"attr", "name", "description", "min", "max", "soft_min", "soft_max", "default", NULL};
1945 char *id, *name="", *description="";
1946 float min=FLT_MIN, max=FLT_MAX, soft_min=FLT_MIN, soft_max=FLT_MAX, def=0.0f;
1948 if (!PyArg_ParseTupleAndKeywords(args, kw, "s|ssfffff:FloatProperty", kwlist, &id, &name, &description, &min, &max, &soft_min, &soft_max, &def))
1951 if (PyTuple_Size(args) > 0) {
1952 PyErr_SetString(PyExc_ValueError, "all args must be keywors"); // TODO - py3 can enforce this.
1956 if (self && PyCObject_Check(self)) {
1957 StructRNA *srna = PyCObject_AsVoidPtr(self);
1958 RNA_def_float(srna, id, def, min, max, name, description, soft_min, soft_max);
1961 PyObject *ret = PyTuple_New(2);
1962 PyTuple_SET_ITEM(ret, 0, PyCObject_FromVoidPtr((void *)BPy_FloatProperty, NULL));
1963 PyTuple_SET_ITEM(ret, 1, kw);
1969 PyObject *BPy_IntProperty(PyObject *self, PyObject *args, PyObject *kw)
1971 static char *kwlist[] = {"attr", "name", "description", "min", "max", "soft_min", "soft_max", "default", NULL};
1972 char *id, *name="", *description="";
1973 int min=INT_MIN, max=INT_MAX, soft_min=INT_MIN, soft_max=INT_MAX, def=0;
1975 if (!PyArg_ParseTupleAndKeywords(args, kw, "s|ssiiiii:IntProperty", kwlist, &id, &name, &description, &min, &max, &soft_min, &soft_max, &def))
1978 if (PyTuple_Size(args) > 0) {
1979 PyErr_SetString(PyExc_ValueError, "all args must be keywors"); // TODO - py3 can enforce this.
1983 if (self && PyCObject_Check(self)) {
1984 StructRNA *srna = PyCObject_AsVoidPtr(self);
1985 RNA_def_int(srna, id, def, min, max, name, description, soft_min, soft_max);
1988 PyObject *ret = PyTuple_New(2);
1989 PyTuple_SET_ITEM(ret, 0, PyCObject_FromVoidPtr((void *)BPy_IntProperty, NULL));
1990 PyTuple_SET_ITEM(ret, 1, kw);
1996 PyObject *BPy_BoolProperty(PyObject *self, PyObject *args, PyObject *kw)
1998 static char *kwlist[] = {"attr", "name", "description", "default", NULL};
1999 char *id, *name="", *description="";
2002 if (!PyArg_ParseTupleAndKeywords(args, kw, "s|ssi:BoolProperty", kwlist, &id, &name, &description, &def))
2005 if (PyTuple_Size(args) > 0) {
2006 PyErr_SetString(PyExc_ValueError, "all args must be keywors"); // TODO - py3 can enforce this.
2010 if (self && PyCObject_Check(self)) {
2011 StructRNA *srna = PyCObject_AsVoidPtr(self);
2012 RNA_def_boolean(srna, id, def, name, description);
2015 PyObject *ret = PyTuple_New(2);
2016 PyTuple_SET_ITEM(ret, 0, PyCObject_FromVoidPtr((void *)BPy_BoolProperty, NULL));
2017 PyTuple_SET_ITEM(ret, 1, kw);
2023 PyObject *BPy_StringProperty(PyObject *self, PyObject *args, PyObject *kw)
2025 static char *kwlist[] = {"attr", "name", "description", "maxlen", "default", NULL};
2026 char *id, *name="", *description="", *def="";
2029 if (!PyArg_ParseTupleAndKeywords(args, kw, "s|ssis:StringProperty", kwlist, &id, &name, &description, &maxlen, &def))
2032 if (PyTuple_Size(args) > 0) {
2033 PyErr_SetString(PyExc_ValueError, "all args must be keywors"); // TODO - py3 can enforce this.
2037 if (self && PyCObject_Check(self)) {
2038 StructRNA *srna = PyCObject_AsVoidPtr(self);
2039 RNA_def_string(srna, id, def, maxlen, name, description);
2042 PyObject *ret = PyTuple_New(2);
2043 PyTuple_SET_ITEM(ret, 0, PyCObject_FromVoidPtr((void *)BPy_StringProperty, NULL));
2044 PyTuple_SET_ITEM(ret, 1, kw);
2050 /*-------------------- Type Registration ------------------------*/
2052 static int rna_function_arg_count(FunctionRNA *func)
2054 const ListBase *lb= RNA_function_defined_parameters(func);
2059 for(link=lb->first; link; link=link->next) {
2060 parm= (PropertyRNA*)link;
2061 if(!(RNA_property_flag(parm) & PROP_RETURN))
2068 static int bpy_class_validate(PointerRNA *dummyptr, void *py_data, int *have_function)
2074 StructRNA *srna= dummyptr->type;
2075 const char *class_type= RNA_struct_identifier(srna);
2076 PyObject *py_class= (PyObject*)py_data;
2077 PyObject *base_class= RNA_struct_py_type_get(srna);
2078 PyObject *item, *fitem;
2079 PyObject *py_arg_count;
2080 int i, flag, arg_count, func_arg_count;
2081 char identifier[128];
2084 if (!PyObject_IsSubclass(py_class, base_class)) {
2085 PyObject *name= PyObject_GetAttrString(base_class, "__name__");
2086 PyErr_Format( PyExc_AttributeError, "expected %s subclass of class \"%s\"", class_type, name ? _PyUnicode_AsString(name):"<UNKNOWN>");
2092 /* verify callback functions */
2093 lb= RNA_struct_defined_functions(srna);
2095 for(link=lb->first; link; link=link->next) {
2096 func= (FunctionRNA*)link;
2097 flag= RNA_function_flag(func);
2099 if(!(flag & FUNC_REGISTER))
2102 item = PyObject_GetAttrString(py_class, RNA_function_identifier(func));
2104 have_function[i]= (item != NULL);
2108 if ((flag & FUNC_REGISTER_OPTIONAL)==0) {
2109 PyErr_Format( PyExc_AttributeError, "expected %s class to have an \"%s\" attribute", class_type, RNA_function_identifier(func));
2116 Py_DECREF(item); /* no need to keep a ref, the class owns it */
2118 if (PyMethod_Check(item))
2119 fitem= PyMethod_Function(item); /* py 2.x */
2121 fitem= item; /* py 3.x */
2123 if (PyFunction_Check(fitem)==0) {
2124 PyErr_Format( PyExc_AttributeError, "expected %s class \"%s\" attribute to be a function", class_type, RNA_function_identifier(func));
2128 func_arg_count= rna_function_arg_count(func);
2130 if (func_arg_count >= 0) { /* -1 if we dont care*/
2131 py_arg_count = PyObject_GetAttrString(PyFunction_GET_CODE(fitem), "co_argcount");
2132 arg_count = PyLong_AsSsize_t(py_arg_count);
2133 Py_DECREF(py_arg_count);
2135 if (arg_count != func_arg_count) {
2136 PyErr_Format( PyExc_AttributeError, "expected %s class \"%s\" function to have %d args", class_type, RNA_function_identifier(func), func_arg_count);
2143 /* verify properties */
2144 lb= RNA_struct_defined_properties(srna);
2145 for(link=lb->first; link; link=link->next) {
2146 prop= (PropertyRNA*)link;
2147 flag= RNA_property_flag(prop);
2149 if(!(flag & PROP_REGISTER))
2152 BLI_snprintf(identifier, sizeof(identifier), "__%s__", RNA_property_identifier(prop));
2153 item = PyObject_GetAttrString(py_class, identifier);
2156 if(strcmp(identifier, "__idname__") == 0) {
2157 item= PyObject_GetAttrString(py_class, "__name__");
2160 Py_DECREF(item); /* no need to keep a ref, the class owns it */
2162 if(pyrna_py_to_prop(dummyptr, prop, NULL, item) != 0)
2167 if (item==NULL && (flag & PROP_REGISTER_OPTIONAL)==0) {
2168 PyErr_Format( PyExc_AttributeError, "expected %s class to have an \"%s\" attribute", class_type, identifier);
2175 Py_DECREF(item); /* no need to keep a ref, the class owns it */
2177 if(pyrna_py_to_prop(dummyptr, prop, NULL, item) != 0)
2185 extern void BPY_update_modules( void ); //XXX temp solution
2187 static int bpy_class_call(PointerRNA *ptr, FunctionRNA *func, ParameterList *parms)
2190 PyObject *ret= NULL, *py_class, *py_class_instance, *item, *parmitem;
2191 PropertyRNA *pret= NULL, *parm;
2192 ParameterIterator iter;
2194 void *retdata= NULL;
2195 int err= 0, i, flag;
2197 PyGILState_STATE gilstate = PyGILState_Ensure();
2199 BPY_update_modules(); // XXX - the RNA pointers can change so update before running, would like a nicer solution for this.
2201 py_class= RNA_struct_py_type_get(ptr->type);
2203 item = pyrna_struct_CreatePyObject(ptr);
2205 py_class_instance = NULL;
2207 else if(item == Py_None) { /* probably wont ever happen but possible */
2209 py_class_instance = NULL;
2212 args = PyTuple_New(1);
2213 PyTuple_SET_ITEM(args, 0, item);
2214 py_class_instance = PyObject_Call(py_class, args, NULL);
2218 if (py_class_instance) { /* Initializing the class worked, now run its invoke function */
2219 item= PyObject_GetAttrString(py_class, RNA_function_identifier(func));
2220 flag= RNA_function_flag(func);
2223 pret= RNA_function_return(func);
2224 RNA_pointer_create(NULL, &RNA_Function, func, &funcptr);
2226 args = PyTuple_New(rna_function_arg_count(func));
2227 PyTuple_SET_ITEM(args, 0, py_class_instance);
2229 RNA_parameter_list_begin(parms, &iter);
2231 /* parse function parameters */
2232 for (i= 1; iter.valid; RNA_parameter_list_next(&iter)) {
2240 parmitem= pyrna_param_to_py(&funcptr, parm, iter.data);
2241 PyTuple_SET_ITEM(args, i, parmitem);
2245 ret = PyObject_Call(item, args, NULL);
2251 Py_DECREF(py_class_instance);
2252 PyErr_Format(PyExc_AttributeError, "could not find function %s in %s to execute callback.", RNA_function_identifier(func), RNA_struct_identifier(ptr->type));
2257 PyErr_Format(PyExc_AttributeError, "could not create instance of %s to call callback function %s.", RNA_struct_identifier(ptr->type), RNA_function_identifier(func));
2261 if (ret == NULL) { /* covers py_class_instance failing too */
2262 PyErr_Print(); /* XXX use reporting api? */
2267 err= pyrna_py_to_prop(&funcptr, pret, retdata, ret);
2271 PyGILState_Release(gilstate);
2276 static void bpy_class_free(void *pyob_ptr)
2279 if(((PyObject *)pyob_ptr)->ob_refcnt > 1)
2280 PyObSpit("zombie class - ref should be 1", (PyObject *)pyob_ptr);
2282 Py_DECREF((PyObject *)pyob_ptr);
2285 PyObject *pyrna_basetype_register(PyObject *self, PyObject *args)
2288 PyObject *py_class, *item;
2290 StructRegisterFunc reg;
2291 BPy_StructRNA *py_srna;
2294 if(!PyArg_ParseTuple(args, "O:register", &py_class))
2297 if(!PyType_Check(py_class)) {
2298 PyErr_SetString(PyExc_AttributeError, "expected a Type subclassed from a registerable rna type (no a Type object).");
2302 /* check we got an __rna__ attribute */
2303 item= PyObject_GetAttrString(py_class, "__rna__");
2305 if(!item || !BPy_StructRNA_Check(item)) {
2307 PyErr_SetString(PyExc_AttributeError, "expected a Type subclassed from a registerable rna type (no __rna__ property).");
2311 /* check the __rna__ attribute has the right type */
2313 py_srna= (BPy_StructRNA*)item;
2315 if(py_srna->ptr.type != &RNA_Struct) {
2316 PyErr_SetString(PyExc_AttributeError, "expected a Type subclassed from a registerable rna type (not a Struct).");
2320 /* check that we have a register callback for this type */
2321 reg= RNA_struct_register(py_srna->ptr.data);
2324 PyErr_SetString(PyExc_AttributeError, "expected a Type subclassed from a registerable rna type (no register supported).");
2328 /* get the context, so register callback can do necessary refreshes */
2329 C= BPy_GetContext();
2331 /* call the register callback */
2332 BKE_reports_init(&reports, RPT_STORE);
2333 srna= reg(C, &reports, py_class, bpy_class_validate, bpy_class_call, bpy_class_free);
2336 BPy_reports_to_error(&reports);
2337 BKE_reports_clear(&reports);
2341 BKE_reports_clear(&reports);
2343 pyrna_subtype_set_rna(py_class, srna); /* takes a ref to py_class */
2348 PyObject *pyrna_basetype_unregister(PyObject *self, PyObject *args)
2351 PyObject *py_class, *item;
2352 BPy_StructRNA *py_srna;
2353 StructUnregisterFunc unreg;
2355 if(!PyArg_ParseTuple(args, "O:unregister", &py_class))
2358 if(!PyType_Check(py_class)) {
2359 PyErr_SetString(PyExc_AttributeError, "expected a Type subclassed from a registerable rna type (no a Type object).");
2363 /* check we got an __rna__ attribute */
2364 item= PyDict_GetItemString(((PyTypeObject*)py_class)->tp_dict, "__rna__"); /* borrow ref */
2366 if(!item || !BPy_StructRNA_Check(item)) {
2367 PyErr_SetString(PyExc_AttributeError, "expected a Type subclassed from a registerable rna type (no __rna__ property).");
2371 /* check the __rna__ attribute has the right type */
2372 py_srna= (BPy_StructRNA*)item;
2374 if(py_srna->ptr.type != &RNA_Struct) {
2375 PyErr_SetString(PyExc_AttributeError, "expected a Type subclassed from a registerable rna type (not a Struct).");
2379 /* check that we have a unregister callback for this type */
2380 unreg= RNA_struct_unregister(py_srna->ptr.data);
2383 PyErr_SetString(PyExc_AttributeError, "expected a Type subclassed from a registerable rna type (no unregister supported).");
2387 /* get the context, so register callback can do necessary refreshes */
2388 C= BPy_GetContext();
2391 /* call unregister */
2392 unreg(C, py_srna->ptr.data);
2394 /* remove reference to old type */
2395 Py_DECREF(py_class);