odd, this didn't get committed before

This commit is contained in:
Joseph Eagar
2009-07-16 22:23:01 +00:00
parent 4aa15cd216
commit 479c970375
34 changed files with 11046 additions and 483 deletions

View File

@@ -1,5 +1,5 @@
#
# $Id: Makefile 11904 2007-08-31 16:16:33Z sirdude $
# $Id: Makefile 21094 2009-06-23 00:09:26Z gsrb3d $
#
# ***** BEGIN GPL LICENSE BLOCK *****
#
@@ -37,6 +37,7 @@ CFLAGS += $(LEVEL_1_C_WARNINGS)
# OpenGL and Python
CPPFLAGS += $(OGL_CPPFLAGS)
CPPFLAGS += -I$(NAN_GLEW)/include
CPPFLAGS += -I$(NAN_PYTHON)/include/python$(NAN_PYTHON_VERSION)
# PreProcessor stuff

View File

@@ -1,5 +1,5 @@
/**
* $Id$
* $Id: bpy_compat.h 21427 2009-07-08 14:26:43Z ton $
*
* ***** BEGIN GPL LICENSE BLOCK *****
*
@@ -85,9 +85,35 @@ typedef Py_ssize_t (*lenfunc)(PyObject *);
#ifndef Py_RETURN_TRUE
#define Py_RETURN_TRUE return PyBool_FromLong(1)
#endif
#define PyInt_FromSsize_t PyInt_FromLong
#define PyNumber_AsSsize_t(ob, exc) PyInt_AsLong(ob)
#define PyIndex_Check(ob) PyInt_Check(ob)
#endif
#if PY_VERSION_HEX < 0x03000000
#ifndef ssizeargfunc
#define ssizeargfunc intargfunc
#endif
#ifndef ssizessizeargfunc
#define ssizessizeargfunc intintargfunc
#endif
#ifndef ssizeobjargproc
#define ssizeobjargproc intobjargproc
#endif
#ifndef ssizessizeobjargproc
#define ssizessizeobjargproc intintobjargproc
#endif
#endif
/* defined in bpy_util.c */
#if PY_VERSION_HEX < 0x03000000
PyObject *Py_CmpToRich(int op, int cmp);

View File

@@ -36,6 +36,14 @@
#include "BPY_extern.h"
#include "../generic/bpy_internal_import.h" // our own imports
/* external util modules */
#include "../generic/Mathutils.h"
#include "../generic/Geometry.h"
#include "../generic/BGL.h"
void BPY_free_compiled_text( struct Text *text )
{
if( text->compiled ) {
@@ -56,12 +64,19 @@ static void bpy_init_modules( void )
PyModule_AddObject( mod, "data", BPY_rna_module() );
/* PyModule_AddObject( mod, "doc", BPY_rna_doc() ); */
PyModule_AddObject( mod, "types", BPY_rna_types() );
PyModule_AddObject( mod, "props", BPY_rna_props() );
PyModule_AddObject( mod, "ops", BPY_operator_module() );
PyModule_AddObject( mod, "ui", BPY_ui_module() ); // XXX very experemental, consider this a test, especially PyCObject is not meant to be perminant
PyModule_AddObject( mod, "ui", BPY_ui_module() ); // XXX very experimental, consider this a test, especially PyCObject is not meant to be permanent
/* add the module so we can import it */
PyDict_SetItemString(PySys_GetObject("modules"), "bpy", mod);
Py_DECREF(mod);
/* stand alone utility modules not related to blender directly */
Geometry_Init("Geometry");
Mathutils_Init("Mathutils");
BGL_Init("BGL");
}
#if (PY_VERSION_HEX < 0x02050000)
@@ -100,6 +115,7 @@ static PyObject *CreateGlobalDictionary( bContext *C )
{"FloatProperty", (PyCFunction)BPy_FloatProperty, METH_VARARGS|METH_KEYWORDS, ""},
{"IntProperty", (PyCFunction)BPy_IntProperty, METH_VARARGS|METH_KEYWORDS, ""},
{"BoolProperty", (PyCFunction)BPy_BoolProperty, METH_VARARGS|METH_KEYWORDS, ""},
{"StringProperty", (PyCFunction)BPy_StringProperty, METH_VARARGS|METH_KEYWORDS, ""},
{NULL, NULL, 0, NULL}
};
@@ -116,13 +132,81 @@ static PyObject *CreateGlobalDictionary( bContext *C )
return dict;
}
/* Use this so we can include our own python bundle */
#if 0
wchar_t* Py_GetPath(void)
{
int i;
static wchar_t py_path[FILE_MAXDIR] = L"";
char *dirname= BLI_gethome_folder("python");
if(dirname) {
i= mbstowcs(py_path, dirname, FILE_MAXDIR);
printf("py path %s, %d\n", dirname, i);
}
return py_path;
}
#endif
/* must be called before Py_Initialize */
void BPY_start_python_path(void)
{
char *py_path_bundle= BLI_gethome_folder("python");
if(py_path_bundle==NULL)
return;
/* set the environment path */
printf("found bundled python: %s\n", py_path_bundle);
#if (defined(WIN32) || defined(WIN64))
#if defined(FREE_WINDOWS)
{
char py_path[FILE_MAXDIR + 11] = "";
sprintf(py_path, "PYTHONPATH=%s", py_path_bundle);
putenv(py_path);
}
#else
_putenv_s("PYTHONPATH", py_path_bundle);
#endif
#else
#ifdef __sgi
{
char py_path[FILE_MAXDIR + 11] = "";
sprintf(py_path, "PYTHONPATH=%s", py_path_bundle);
putenv(py_path);
}
#else
setenv("PYTHONPATH", py_path_bundle, 1);
#endif
#endif
}
void BPY_start_python( int argc, char **argv )
{
PyThreadState *py_tstate = NULL;
BPY_start_python_path(); /* allow to use our own included python */
Py_Initialize( );
//PySys_SetArgv( argc_copy, argv_copy );
#if (PY_VERSION_HEX < 0x03000000)
PySys_SetArgv( argc, argv);
#else
/* sigh, why do python guys not have a char** version anymore? :( */
{
int i;
PyObject *py_argv= PyList_New(argc);
for (i=0; i<argc; i++)
PyList_SET_ITEM(py_argv, i, PyUnicode_FromString(argv[i]));
PySys_SetObject("argv", py_argv);
Py_DECREF(py_argv);
}
#endif
/* Initialize thread support (also acquires lock) */
PyEval_InitThreads();
@@ -131,10 +215,17 @@ void BPY_start_python( int argc, char **argv )
/* bpy.* and lets us import it */
bpy_init_modules();
{ /* our own import and reload functions */
PyObject *item;
//PyObject *m = PyImport_AddModule("__builtin__");
//PyObject *d = PyModule_GetDict(m);
PyObject *d = PyEval_GetBuiltins( );
PyDict_SetItemString(d, "reload", item=PyCFunction_New(bpy_reload_meth, NULL)); Py_DECREF(item);
PyDict_SetItemString(d, "__import__", item=PyCFunction_New(bpy_import_meth, NULL)); Py_DECREF(item);
}
py_tstate = PyGILState_GetThisThreadState();
PyEval_ReleaseThread(py_tstate);
}
void BPY_end_python( void )
@@ -150,7 +241,7 @@ void BPY_end_python( void )
}
/* Can run a file or text block */
int BPY_run_python_script( bContext *C, const char *fn, struct Text *text )
int BPY_run_python_script( bContext *C, const char *fn, struct Text *text, struct ReportList *reports)
{
PyObject *py_dict, *py_result;
PyGILState_STATE gilstate;
@@ -164,6 +255,7 @@ int BPY_run_python_script( bContext *C, const char *fn, struct Text *text )
gilstate = PyGILState_Ensure();
BPY_update_modules(); /* can give really bad results if this isnt here */
bpy_import_main_set(CTX_data_main(C));
py_dict = CreateGlobalDictionary(C);
@@ -178,7 +270,7 @@ int BPY_run_python_script( bContext *C, const char *fn, struct Text *text )
MEM_freeN( buf );
if( PyErr_Occurred( ) ) {
PyErr_Print(); PyErr_Clear();
BPy_errors_to_report(reports);
BPY_free_compiled_text( text );
PyGILState_Release(gilstate);
return 0;
@@ -194,13 +286,14 @@ int BPY_run_python_script( bContext *C, const char *fn, struct Text *text )
}
if (!py_result) {
PyErr_Print(); PyErr_Clear();
BPy_errors_to_report(reports);
} else {
Py_DECREF( py_result );
}
Py_DECREF(py_dict);
PyGILState_Release(gilstate);
bpy_import_main_set(NULL);
//BPY_end_python();
return py_result ? 1:0;
@@ -221,7 +314,7 @@ static void exit_pydraw( SpaceScript * sc, short err )
script = sc->script;
if( err ) {
PyErr_Print(); PyErr_Clear();
BPy_errors_to_report(NULL); // TODO, reports
script->flags = 0; /* mark script struct for deletion */
SCRIPT_SET_NULL(script);
script->scriptname[0] = '\0';
@@ -250,7 +343,7 @@ static int bpy_run_script_init(bContext *C, SpaceScript * sc)
return 0;
if (sc->script->py_draw==NULL && sc->script->scriptname[0] != '\0')
BPY_run_python_script(C, sc->script->scriptname, NULL);
BPY_run_python_script(C, sc->script->scriptname, NULL, NULL);
if (sc->script->py_draw==NULL)
return 0;
@@ -258,9 +351,9 @@ static int bpy_run_script_init(bContext *C, SpaceScript * sc)
return 1;
}
int BPY_run_script_space_draw(struct bContext *C, SpaceScript * sc)
int BPY_run_script_space_draw(const struct bContext *C, SpaceScript * sc)
{
if (bpy_run_script_init(C, sc)) {
if (bpy_run_script_init( (bContext *)C, sc)) {
PyGILState_STATE gilstate = PyGILState_Ensure();
PyObject *result = PyObject_CallObject( sc->script->py_draw, NULL );
@@ -329,7 +422,7 @@ int BPY_run_python_script_space(const char *modulename, const char *func)
}
if (!py_result) {
PyErr_Print(); PyErr_Clear();
BPy_errors_to_report(NULL); // TODO - reports
} else
Py_DECREF( py_result );
@@ -357,69 +450,72 @@ void BPY_run_ui_scripts(bContext *C, int reload)
DIR *dir;
struct dirent *de;
char *file_extension;
char *dirname;
char path[FILE_MAX];
char *dirname= BLI_gethome_folder("ui");
int filelen; /* filename length */
char *dirs[] = {"io", "ui", NULL};
int a;
PyGILState_STATE gilstate;
PyObject *mod;
PyObject *sys_path_orig;
PyObject *sys_path_new;
if(!dirname)
return;
dir = opendir(dirname);
PyObject *sys_path;
if(!dir)
return;
gilstate = PyGILState_Ensure();
/* backup sys.path */
sys_path_orig= PySys_GetObject("path");
Py_INCREF(sys_path_orig); /* dont free it */
sys_path_new= PyList_New(1);
PyList_SET_ITEM(sys_path_new, 0, PyUnicode_FromString(dirname));
PySys_SetObject("path", sys_path_new);
Py_DECREF(sys_path_new);
// XXX - evil, need to access context
BPy_SetContext(C);
while((de = readdir(dir)) != NULL) {
/* We could stat the file but easier just to let python
* import it and complain if theres a problem */
bpy_import_main_set(CTX_data_main(C));
sys_path= PySys_GetObject("path"); /* borrow */
PyList_Insert(sys_path, 0, Py_None); /* place holder, resizes the list */
for(a=0; dirs[a]; a++) {
dirname= BLI_gethome_folder(dirs[a]);
if(!dirname)
continue;
dir = opendir(dirname);
if(!dir)
continue;
file_extension = strstr(de->d_name, ".py");
if(file_extension && *(file_extension + 3) == '\0') {
filelen = strlen(de->d_name);
BLI_strncpy(path, de->d_name, filelen-2); /* cut off the .py on copy */
/* set the first dir in the sys.path for fast importing of modules */
PyList_SetItem(sys_path, 0, PyUnicode_FromString(dirname)); /* steals the ref */
mod= PyImport_ImportModuleLevel(path, NULL, NULL, NULL, 0);
if (mod) {
if (reload) {
PyObject *mod_orig= mod;
mod= PyImport_ReloadModule(mod);
Py_DECREF(mod_orig);
while((de = readdir(dir)) != NULL) {
/* We could stat the file but easier just to let python
* import it and complain if theres a problem */
file_extension = strstr(de->d_name, ".py");
if(file_extension && file_extension[3] == '\0') {
BLI_strncpy(path, de->d_name, (file_extension - de->d_name) + 1); /* cut off the .py on copy */
mod= PyImport_ImportModuleLevel(path, NULL, NULL, NULL, 0);
if (mod) {
if (reload) {
PyObject *mod_orig= mod;
mod= PyImport_ReloadModule(mod);
Py_DECREF(mod_orig);
}
}
}
if(mod) {
Py_DECREF(mod); /* could be NULL from reloading */
} else {
PyErr_Print(); PyErr_Clear();
fprintf(stderr, "unable to import \"%s\" %s/%s\n", path, dirname, de->d_name);
if(mod) {
Py_DECREF(mod); /* could be NULL from reloading */
} else {
BPy_errors_to_report(NULL);
fprintf(stderr, "unable to import \"%s\" %s/%s\n", path, dirname, de->d_name);
}
}
}
}
closedir(dir);
closedir(dir);
}
PySys_SetObject("path", sys_path_orig);
Py_DECREF(sys_path_orig);
PyList_SetSlice(sys_path, 0, 1, NULL); /* remove the first item */
bpy_import_main_set(NULL);
PyGILState_Release(gilstate);
#ifdef TIME_REGISTRATION
@@ -530,7 +626,7 @@ static float pydriver_error(ChannelDriver *driver)
driver->flag |= DRIVER_FLAG_INVALID; /* py expression failed */
fprintf(stderr, "\nError in Driver: The following Python expression failed:\n\t'%s'\n\n", driver->expression);
PyErr_Print(); PyErr_Clear();
BPy_errors_to_report(NULL); // TODO - reports
return 0.0f;
}
@@ -589,7 +685,7 @@ float BPY_pydriver_eval (ChannelDriver *driver)
}
fprintf(stderr, "\tBPY_pydriver_eval() - couldn't add variable '%s' to namespace \n", dtar->name);
PyErr_Print(); PyErr_Clear();
BPy_errors_to_report(NULL); // TODO - reports
}
}

View File

@@ -1,6 +1,6 @@
/**
* $Id$
* $Id: bpy_operator.c 21554 2009-07-13 08:33:51Z campbellbarton $
*
* ***** BEGIN GPL LICENSE BLOCK *****
*
@@ -68,7 +68,7 @@ static PyObject *pyop_base_call( PyObject * self, PyObject * args, PyObject * k
return NULL;
}
ot= WM_operatortype_find(opname);
ot= WM_operatortype_find(opname, 1);
if (ot == NULL) {
PyErr_Format( PyExc_SystemError, "Operator \"%s\"could not be found", opname);
return NULL;
@@ -130,11 +130,18 @@ static PyObject *pyop_base_getattro( BPy_OperatorBase * self, PyObject *pyname )
PyObject *ret;
wmOperatorType *ot;
if ((ot= WM_operatortype_find(name))) {
/* First look for the operator, then our own methods if that fails.
* when methods are searched first, PyObject_GenericGetAttr will raise an error
* each time we want to call an operator, we could clear the error but I prefer
* not to since calling operators is a lot more common then adding and removing. - Campbell */
if ((ot= WM_operatortype_find(name, 1))) {
ret = PyCFunction_New( pyop_base_call_meth, pyname); /* set the name string as self, PyCFunction_New incref's self */
}
else if ((ret = PyObject_GenericGetAttr((PyObject *)self, pyname))) {
/* do nothing, this accounts for methoddef's add and remove */
/* do nothing, this accounts for methoddef's add and remove
* An exception is raised when PyObject_GenericGetAttr fails
* but its ok because its overwritten below */
}
else {
PyErr_Format( PyExc_AttributeError, "Operator \"%s\" not found", name);
@@ -170,7 +177,7 @@ static PyObject *pyop_base_rna(PyObject *self, PyObject *pyname)
char *name = _PyUnicode_AsString(pyname);
wmOperatorType *ot;
if ((ot= WM_operatortype_find(name))) {
if ((ot= WM_operatortype_find(name, 1))) {
BPy_StructRNA *pyrna;
PointerRNA ptr;
@@ -191,6 +198,8 @@ PyTypeObject pyop_base_Type = {NULL};
PyObject *BPY_operator_module( void )
{
PyObject *ob;
pyop_base_Type.tp_name = "OperatorBase";
pyop_base_Type.tp_basicsize = sizeof( BPy_OperatorBase );
pyop_base_Type.tp_getattro = ( getattrofunc )pyop_base_getattro;
@@ -201,6 +210,9 @@ PyObject *BPY_operator_module( void )
return NULL;
//submodule = Py_InitModule3( "operator", M_rna_methods, "rna module" );
return (PyObject *)PyObject_NEW( BPy_OperatorBase, &pyop_base_Type );
ob = PyObject_NEW( BPy_OperatorBase, &pyop_base_Type );
Py_INCREF(ob);
return ob;
}

View File

@@ -1,6 +1,6 @@
/**
* $Id$
* $Id: bpy_operator.h 21094 2009-06-23 00:09:26Z gsrb3d $
*
* ***** BEGIN GPL LICENSE BLOCK *****
*

View File

@@ -1,6 +1,6 @@
/**
* $Id$
* $Id: bpy_operator_wrap.c 21440 2009-07-08 21:31:28Z blendix $
*
* ***** BEGIN GPL LICENSE BLOCK *****
*
@@ -40,116 +40,13 @@
#include "bpy_compat.h"
#include "bpy_util.h"
#include "../generic/bpy_internal_import.h" // our own imports
#define PYOP_ATTR_PROP "__props__"
#define PYOP_ATTR_UINAME "__label__"
#define PYOP_ATTR_IDNAME "__name__" /* use pythons class name */
#define PYOP_ATTR_DESCRIPTION "__doc__" /* use pythons docstring */
static PyObject *pyop_dict_from_event(wmEvent *event)
{
PyObject *dict= PyDict_New();
PyObject *item;
char *cstring, ascii[2];
/* type */
item= PyUnicode_FromString(WM_key_event_string(event->type));
PyDict_SetItemString(dict, "type", item); Py_DECREF(item);
/* val */
switch(event->val) {
case KM_ANY:
cstring = "ANY";
break;
case KM_RELEASE:
cstring = "RELEASE";
break;
case KM_PRESS:
cstring = "PRESS";
break;
default:
cstring = "UNKNOWN";
break;
}
item= PyUnicode_FromString(cstring);
PyDict_SetItemString(dict, "val", item); Py_DECREF(item);
/* x, y (mouse) */
item= PyLong_FromLong(event->x);
PyDict_SetItemString(dict, "x", item); Py_DECREF(item);
item= PyLong_FromLong(event->y);
PyDict_SetItemString(dict, "y", item); Py_DECREF(item);
item= PyLong_FromLong(event->prevx);
PyDict_SetItemString(dict, "prevx", item); Py_DECREF(item);
item= PyLong_FromLong(event->prevy);
PyDict_SetItemString(dict, "prevy", item); Py_DECREF(item);
/* ascii */
ascii[0]= event->ascii;
ascii[1]= '\0';
item= PyUnicode_FromString(ascii);
PyDict_SetItemString(dict, "ascii", item); Py_DECREF(item);
/* modifier keys */
item= PyLong_FromLong(event->shift);
PyDict_SetItemString(dict, "shift", item); Py_DECREF(item);
item= PyLong_FromLong(event->ctrl);
PyDict_SetItemString(dict, "ctrl", item); Py_DECREF(item);
item= PyLong_FromLong(event->alt);
PyDict_SetItemString(dict, "alt", item); Py_DECREF(item);
item= PyLong_FromLong(event->oskey);
PyDict_SetItemString(dict, "oskey", item); Py_DECREF(item);
/* modifier */
#if 0
item= PyTuple_New(0);
if(event->keymodifier & KM_SHIFT) {
_PyTuple_Resize(&item, size+1);
PyTuple_SET_ITEM(item, size, _PyUnicode_AsString("SHIFT"));
size++;
}
if(event->keymodifier & KM_CTRL) {
_PyTuple_Resize(&item, size+1);
PyTuple_SET_ITEM(item, size, _PyUnicode_AsString("CTRL"));
size++;
}
if(event->keymodifier & KM_ALT) {
_PyTuple_Resize(&item, size+1);
PyTuple_SET_ITEM(item, size, _PyUnicode_AsString("ALT"));
size++;
}
if(event->keymodifier & KM_OSKEY) {
_PyTuple_Resize(&item, size+1);
PyTuple_SET_ITEM(item, size, _PyUnicode_AsString("OSKEY"));
size++;
}
PyDict_SetItemString(dict, "keymodifier", item); Py_DECREF(item);
#endif
return dict;
}
/* TODO - a whole traceback would be ideal */
static void pyop_error_report(ReportList *reports)
{
PyObject *exception, *v, *tb;
PyErr_Fetch(&exception, &v, &tb);
if (exception == NULL)
return;
/* Now we know v != NULL too */
BKE_report(reports, RPT_ERROR, _PyUnicode_AsString(v));
PyErr_Print();
}
static struct BPY_flag_def pyop_ret_flags[] = {
{"RUNNING_MODAL", OPERATOR_RUNNING_MODAL},
{"CANCELLED", OPERATOR_CANCELLED},
@@ -190,9 +87,13 @@ static int PYTHON_OT_generic(int mode, bContext *C, wmOperator *op, wmEvent *eve
PyObject *ret= NULL, *py_class_instance, *item= NULL;
int ret_flag= (mode==PYOP_POLL ? 0:OPERATOR_CANCELLED);
PointerRNA ptr_context;
PyObject *py_context;
PointerRNA ptr_operator;
PointerRNA ptr_event;
PyObject *py_operator;
PyGILState_STATE gilstate = PyGILState_Ensure();
bpy_import_main_set(CTX_data_main(C));
BPY_update_modules(); // XXX - the RNA pointers can change so update before running, would like a nicer solutuon for this.
@@ -206,15 +107,9 @@ static int PYTHON_OT_generic(int mode, bContext *C, wmOperator *op, wmEvent *eve
/* Assign instance attributes from operator properties */
{
PropertyRNA *prop, *iterprop;
CollectionPropertyIterator iter;
const char *arg_name;
iterprop= RNA_struct_iterator_property(op->ptr->type);
RNA_property_collection_begin(op->ptr, iterprop, &iter);
for(; iter.valid; RNA_property_collection_next(&iter)) {
prop= iter.ptr.data;
RNA_STRUCT_BEGIN(op->ptr, prop) {
arg_name= RNA_property_identifier(prop);
if (strcmp(arg_name, "rna_type")==0) continue;
@@ -223,23 +118,33 @@ static int PYTHON_OT_generic(int mode, bContext *C, wmOperator *op, wmEvent *eve
PyObject_SetAttrString(py_class_instance, arg_name, item);
Py_DECREF(item);
}
RNA_property_collection_end(&iter);
RNA_STRUCT_END;
}
/* set operator pointer RNA as instance "__operator__" attribute */
RNA_pointer_create(NULL, &RNA_Operator, op, &ptr_operator);
py_operator= pyrna_struct_CreatePyObject(&ptr_operator);
PyObject_SetAttrString(py_class_instance, "__operator__", py_operator);
Py_DECREF(py_operator);
RNA_pointer_create(NULL, &RNA_Context, C, &ptr_context);
if (mode==PYOP_INVOKE) {
item= PyObject_GetAttrString(py_class, "invoke");
args = PyTuple_New(2);
PyTuple_SET_ITEM(args, 1, pyop_dict_from_event(event));
args = PyTuple_New(3);
RNA_pointer_create(NULL, &RNA_Event, event, &ptr_event);
// PyTuple_SET_ITEM "steals" object reference, it is
// an object passed shouldn't be DECREF'ed
PyTuple_SET_ITEM(args, 1, pyrna_struct_CreatePyObject(&ptr_context));
PyTuple_SET_ITEM(args, 2, pyrna_struct_CreatePyObject(&ptr_event));
}
else if (mode==PYOP_EXEC) {
item= PyObject_GetAttrString(py_class, "exec");
item= PyObject_GetAttrString(py_class, "execute");
args = PyTuple_New(2);
RNA_pointer_create(NULL, &RNA_Context, C, &ptr_context);
py_context = pyrna_struct_CreatePyObject(&ptr_context);
PyTuple_SET_ITEM(args, 1, py_context);
PyTuple_SET_ITEM(args, 1, pyrna_struct_CreatePyObject(&ptr_context));
}
else if (mode==PYOP_POLL) {
item= PyObject_GetAttrString(py_class, "poll");
@@ -256,13 +161,13 @@ static int PYTHON_OT_generic(int mode, bContext *C, wmOperator *op, wmEvent *eve
}
if (ret == NULL) { /* covers py_class_instance failing too */
pyop_error_report(op->reports);
BPy_errors_to_report(op->reports);
}
else {
if (mode==PYOP_POLL) {
if (PyBool_Check(ret) == 0) {
PyErr_SetString(PyExc_ValueError, "Python poll function return value ");
pyop_error_report(op->reports);
BPy_errors_to_report(op->reports);
}
else {
ret_flag= ret==Py_True ? 1:0;
@@ -270,8 +175,9 @@ static int PYTHON_OT_generic(int mode, bContext *C, wmOperator *op, wmEvent *eve
} else if (BPY_flag_from_seq(pyop_ret_flags, ret, &ret_flag) == -1) {
/* the returned value could not be converted into a flag */
pyop_error_report(op->reports);
BPy_errors_to_report(op->reports);
ret_flag = OPERATOR_CANCELLED;
}
/* there is no need to copy the py keyword dict modified by
* pyot->py_invoke(), back to the operator props since they are just
@@ -284,7 +190,34 @@ static int PYTHON_OT_generic(int mode, bContext *C, wmOperator *op, wmEvent *eve
Py_DECREF(ret);
}
/* print operator return value */
if (mode != PYOP_POLL) {
char flag_str[100];
char class_name[100];
BPY_flag_def *flag_def = pyop_ret_flags;
strcpy(flag_str, "");
while(flag_def->name) {
if (ret_flag & flag_def->flag) {
if(flag_str[1])
sprintf(flag_str, "%s | %s", flag_str, flag_def->name);
else
strcpy(flag_str, flag_def->name);
}
flag_def++;
}
/* get class name */
item= PyObject_GetAttrString(py_class, PYOP_ATTR_IDNAME);
Py_DECREF(item);
strcpy(class_name, _PyUnicode_AsString(item));
fprintf(stderr, "%s's %s returned %s\n", class_name, mode == PYOP_EXEC ? "execute" : "invoke", flag_str);
}
PyGILState_Release(gilstate);
bpy_import_main_set(NULL);
return ret_flag;
}
@@ -334,7 +267,7 @@ void PYTHON_OT_wrapper(wmOperatorType *ot, void *userdata)
/* api callbacks, detailed checks dont on adding */
if (PyObject_HasAttrString(py_class, "invoke"))
ot->invoke= PYTHON_OT_invoke;
if (PyObject_HasAttrString(py_class, "exec"))
if (PyObject_HasAttrString(py_class, "execute"))
ot->exec= PYTHON_OT_exec;
if (PyObject_HasAttrString(py_class, "poll"))
ot->poll= PYTHON_OT_poll;
@@ -387,6 +320,7 @@ void PYTHON_OT_wrapper(wmOperatorType *ot, void *userdata)
PyObject *PYOP_wrap_add(PyObject *self, PyObject *py_class)
{
PyObject *base_class, *item;
wmOperatorType *ot;
char *idname= NULL;
@@ -397,8 +331,8 @@ PyObject *PYOP_wrap_add(PyObject *self, PyObject *py_class)
{PYOP_ATTR_UINAME, 's', 0, BPY_CLASS_ATTR_OPTIONAL},
{PYOP_ATTR_PROP, 'l', 0, BPY_CLASS_ATTR_OPTIONAL},
{PYOP_ATTR_DESCRIPTION, 's', 0, BPY_CLASS_ATTR_NONE_OK},
{"exec", 'f', 2, BPY_CLASS_ATTR_OPTIONAL},
{"invoke", 'f', 2, BPY_CLASS_ATTR_OPTIONAL},
{"execute", 'f', 2, BPY_CLASS_ATTR_OPTIONAL},
{"invoke", 'f', 3, BPY_CLASS_ATTR_OPTIONAL},
{"poll", 'f', 2, BPY_CLASS_ATTR_OPTIONAL},
{NULL, 0, 0, 0}
};
@@ -417,9 +351,12 @@ PyObject *PYOP_wrap_add(PyObject *self, PyObject *py_class)
Py_DECREF(item);
idname = _PyUnicode_AsString(item);
if (WM_operatortype_find(idname)) {
PyErr_Format( PyExc_AttributeError, "Operator alredy exists with this name \"%s\"", idname);
return NULL;
/* remove if it already exists */
if ((ot=WM_operatortype_exists(idname))) {
if(ot->pyop_data) {
Py_XDECREF((PyObject*)ot->pyop_data);
}
WM_operatortype_remove(idname);
}
/* If we have properties set, check its a list of dicts */
@@ -466,7 +403,7 @@ PyObject *PYOP_wrap_remove(PyObject *self, PyObject *value)
return NULL;
}
if (!(ot= WM_operatortype_find(idname))) {
if (!(ot= WM_operatortype_exists(idname))) {
PyErr_Format( PyExc_AttributeError, "Operator \"%s\" does not exists, cant remove", idname);
return NULL;
}

View File

@@ -1,6 +1,6 @@
/**
* $Id$
* $Id: bpy_operator_wrap.h 21094 2009-06-23 00:09:26Z gsrb3d $
*
* ***** BEGIN GPL LICENSE BLOCK *****
*

View File

@@ -1,5 +1,5 @@
/**
* $Id$
* $Id: bpy_rna.c 21564 2009-07-13 19:33:59Z campbellbarton $
*
* ***** BEGIN GPL LICENSE BLOCK *****
*
@@ -35,16 +35,102 @@
#include "RNA_define.h" /* for defining our own rna */
#include "MEM_guardedalloc.h"
#include "BKE_utildefines.h"
#include "BKE_context.h"
#include "BKE_global.h" /* evil G.* */
#include "BKE_report.h"
#if 0
#define bpy_PyObject_New(type, typeobj) \
( (type *) PyObject_Init( \
(PyObject *) MEM_callocN( _PyObject_SIZE(typeobj), "python memory from bpy_rna.c" ), (typeobj)) )
#else
#define bpy_PyObject_New(type, typeobj) PyObject_New(type, typeobj)
/* only for keyframing */
#include "DNA_scene_types.h"
#include "ED_keyframing.h"
#define USE_MATHUTILS
#ifdef USE_MATHUTILS
#include "../generic/Mathutils.h" /* so we can have mathutils callbacks */
/* bpyrna vector/euler/quat callbacks */
static int mathutils_rna_array_cb_index= -1; /* index for our callbacks */
static int mathutils_rna_generic_check(BPy_PropertyRNA *self)
{
return self->prop?1:0;
}
static int mathutils_rna_vector_get(BPy_PropertyRNA *self, int subtype, float *vec_from)
{
if(self->prop==NULL)
return 0;
RNA_property_float_get_array(&self->ptr, self->prop, vec_from);
return 1;
}
static int mathutils_rna_vector_set(BPy_PropertyRNA *self, int subtype, float *vec_to)
{
if(self->prop==NULL)
return 0;
RNA_property_float_set_array(&self->ptr, self->prop, vec_to);
return 1;
}
static int mathutils_rna_vector_get_index(BPy_PropertyRNA *self, int subtype, float *vec_from, int index)
{
if(self->prop==NULL)
return 0;
vec_from[index]= RNA_property_float_get_index(&self->ptr, self->prop, index);
return 1;
}
static int mathutils_rna_vector_set_index(BPy_PropertyRNA *self, int subtype, float *vec_to, int index)
{
if(self->prop==NULL)
return 0;
RNA_property_float_set_index(&self->ptr, self->prop, index, vec_to[index]);
return 1;
}
Mathutils_Callback mathutils_rna_array_cb = {
(BaseMathCheckFunc) mathutils_rna_generic_check,
(BaseMathGetFunc) mathutils_rna_vector_get,
(BaseMathSetFunc) mathutils_rna_vector_set,
(BaseMathGetIndexFunc) mathutils_rna_vector_get_index,
(BaseMathSetIndexFunc) mathutils_rna_vector_set_index
};
/* bpyrna matrix callbacks */
static int mathutils_rna_matrix_cb_index= -1; /* index for our callbacks */
static int mathutils_rna_matrix_get(BPy_PropertyRNA *self, int subtype, float *mat_from)
{
if(self->prop==NULL)
return 0;
RNA_property_float_get_array(&self->ptr, self->prop, mat_from);
return 1;
}
static int mathutils_rna_matrix_set(BPy_PropertyRNA *self, int subtype, float *mat_to)
{
if(self->prop==NULL)
return 0;
RNA_property_float_set_array(&self->ptr, self->prop, mat_to);
return 1;
}
Mathutils_Callback mathutils_rna_matrix_cb = {
(BaseMathCheckFunc) mathutils_rna_generic_check,
(BaseMathGetFunc) mathutils_rna_matrix_get,
(BaseMathSetFunc) mathutils_rna_matrix_set,
(BaseMathGetIndexFunc) NULL,
(BaseMathSetIndexFunc) NULL
};
#endif
static int pyrna_struct_compare( BPy_StructRNA * a, BPy_StructRNA * b )
@@ -81,39 +167,39 @@ static PyObject *pyrna_prop_richcmp(BPy_PropertyRNA * a, BPy_PropertyRNA * b, in
/*----------------------repr--------------------------------------------*/
static PyObject *pyrna_struct_repr( BPy_StructRNA * self )
{
PropertyRNA *prop;
char str[512];
PyObject *pyob;
char *name;
/* print name if available */
prop= RNA_struct_name_property(self->ptr.type);
if(prop) {
RNA_property_string_get(&self->ptr, prop, str);
return PyUnicode_FromFormat( "[BPy_StructRNA \"%s\" -> \"%s\"]", RNA_struct_identifier(self->ptr.type), str);
name= RNA_struct_name_get_alloc(&self->ptr, NULL, 0);
if(name) {
pyob= PyUnicode_FromFormat( "[BPy_StructRNA \"%.200s\" -> \"%.200s\"]", RNA_struct_identifier(self->ptr.type), name);
MEM_freeN(name);
return pyob;
}
return PyUnicode_FromFormat( "[BPy_StructRNA \"%s\"]", RNA_struct_identifier(self->ptr.type));
return PyUnicode_FromFormat( "[BPy_StructRNA \"%.200s\"]", RNA_struct_identifier(self->ptr.type));
}
static PyObject *pyrna_prop_repr( BPy_PropertyRNA * self )
{
PropertyRNA *prop;
PyObject *pyob;
PointerRNA ptr;
char str[512];
char *name;
/* if a pointer, try to print name of pointer target too */
if(RNA_property_type(self->prop) == PROP_POINTER) {
ptr= RNA_property_pointer_get(&self->ptr, self->prop);
name= RNA_struct_name_get_alloc(&ptr, NULL, 0);
if(ptr.data) {
prop= RNA_struct_name_property(ptr.type);
if(prop) {
RNA_property_string_get(&ptr, prop, str);
return PyUnicode_FromFormat( "[BPy_PropertyRNA \"%s\" -> \"%s\" -> \"%s\" ]", RNA_struct_identifier(self->ptr.type), RNA_property_identifier(self->prop), str);
}
if(name) {
pyob= PyUnicode_FromFormat( "[BPy_PropertyRNA \"%.200s\" -> \"%.200s\" -> \"%.200s\" ]", RNA_struct_identifier(self->ptr.type), RNA_property_identifier(self->prop), name);
MEM_freeN(name);
return pyob;
}
}
return PyUnicode_FromFormat( "[BPy_PropertyRNA \"%s\" -> \"%s\"]", RNA_struct_identifier(self->ptr.type), RNA_property_identifier(self->prop));
return PyUnicode_FromFormat( "[BPy_PropertyRNA \"%.200s\" -> \"%.200s\"]", RNA_struct_identifier(self->ptr.type), RNA_property_identifier(self->prop));
}
static long pyrna_struct_hash( BPy_StructRNA * self )
@@ -124,24 +210,35 @@ static long pyrna_struct_hash( BPy_StructRNA * self )
/* use our own dealloc so we can free a property if we use one */
static void pyrna_struct_dealloc( BPy_StructRNA * self )
{
/* Note!! for some weired reason calling PyObject_DEL() directly crashes blender! */
if (self->freeptr && self->ptr.data) {
IDP_FreeProperty(self->ptr.data);
MEM_freeN(self->ptr.data);
self->ptr.data= NULL;
}
/* Note, for subclassed PyObjects we cant just call PyObject_DEL() directly or it will crash */
Py_TYPE(self)->tp_free(self);
return;
}
static char *pyrna_enum_as_string(PointerRNA *ptr, PropertyRNA *prop)
{
const EnumPropertyItem *item;
int totitem;
EnumPropertyItem *item;
char *result;
int free= 0;
RNA_property_enum_items(ptr, prop, &item, &totitem);
return (char*)BPy_enum_as_string((EnumPropertyItem*)item);
RNA_property_enum_items(BPy_GetContext(), ptr, prop, &item, NULL, &free);
if(item) {
result= (char*)BPy_enum_as_string(item);
}
else {
result= "";
}
if(free)
MEM_freeN(item);
return result;
}
PyObject * pyrna_prop_to_py(PointerRNA *ptr, PropertyRNA *prop)
@@ -152,7 +249,52 @@ PyObject * pyrna_prop_to_py(PointerRNA *ptr, PropertyRNA *prop)
if (len > 0) {
/* resolve the array from a new pytype */
return pyrna_prop_CreatePyObject(ptr, prop);
PyObject *ret = pyrna_prop_CreatePyObject(ptr, prop);
#ifdef USE_MATHUTILS
/* return a mathutils vector where possible */
if(RNA_property_type(prop)==PROP_FLOAT) {
switch(RNA_property_subtype(prop)) {
case PROP_VECTOR:
if(len>=2 && len <= 4) {
PyObject *vec_cb= newVectorObject_cb(ret, len, mathutils_rna_array_cb_index, 0);
Py_DECREF(ret); /* the vector owns now */
ret= vec_cb; /* return the vector instead */
}
break;
case PROP_MATRIX:
if(len==16) {
PyObject *mat_cb= newMatrixObject_cb(ret, 4,4, mathutils_rna_matrix_cb_index, 0);
Py_DECREF(ret); /* the matrix owns now */
ret= mat_cb; /* return the matrix instead */
}
else if (len==9) {
PyObject *mat_cb= newMatrixObject_cb(ret, 3,3, mathutils_rna_matrix_cb_index, 0);
Py_DECREF(ret); /* the matrix owns now */
ret= mat_cb; /* return the matrix instead */
}
break;
case PROP_ROTATION:
if(len==3) { /* euler */
PyObject *eul_cb= newEulerObject_cb(ret, mathutils_rna_array_cb_index, 0);
Py_DECREF(ret); /* the matrix owns now */
ret= eul_cb; /* return the matrix instead */
}
else if (len==4) {
PyObject *quat_cb= newQuaternionObject_cb(ret, mathutils_rna_array_cb_index, 0);
Py_DECREF(ret); /* the matrix owns now */
ret= quat_cb; /* return the matrix instead */
}
break;
default:
break;
}
}
#endif
return ret;
}
/* see if we can coorce into a python type - PropertyType */
@@ -179,11 +321,32 @@ PyObject * pyrna_prop_to_py(PointerRNA *ptr, PropertyRNA *prop)
const char *identifier;
int val = RNA_property_enum_get(ptr, prop);
if (RNA_property_enum_identifier(ptr, prop, val, &identifier)) {
if (RNA_property_enum_identifier(BPy_GetContext(), ptr, prop, val, &identifier)) {
ret = PyUnicode_FromString( identifier );
} else {
PyErr_Format(PyExc_AttributeError, "RNA Error: Current value \"%d\" matches no enum", val);
ret = NULL;
EnumPropertyItem *item;
int free= 0;
/* don't throw error here, can't trust blender 100% to give the
* right values, python code should not generate error for that */
RNA_property_enum_items(BPy_GetContext(), ptr, prop, &item, NULL, &free);
if(item && item->identifier) {
ret = PyUnicode_FromString( item->identifier );
}
else {
/* prefer not fail silently incase of api errors, maybe disable it later */
char error_str[128];
sprintf(error_str, "RNA Warning: Current value \"%d\" matches no enum", val);
PyErr_Warn(PyExc_RuntimeWarning, error_str);
ret = PyUnicode_FromString( "" );
}
if(free)
MEM_freeN(item);
/*PyErr_Format(PyExc_AttributeError, "RNA Error: Current value \"%d\" matches no enum", val);
ret = NULL;*/
}
break;
@@ -221,23 +384,15 @@ int pyrna_pydict_to_props(PointerRNA *ptr, PyObject *kw, const char *error_prefi
const char *arg_name= NULL;
PyObject *item;
PropertyRNA *prop, *iterprop;
CollectionPropertyIterator iter;
iterprop= RNA_struct_iterator_property(ptr->type);
RNA_property_collection_begin(ptr, iterprop, &iter);
totkw = kw ? PyDict_Size(kw):0;
for(; iter.valid; RNA_property_collection_next(&iter)) {
prop= iter.ptr.data;
RNA_STRUCT_BEGIN(ptr, prop) {
arg_name= RNA_property_identifier(prop);
if (strcmp(arg_name, "rna_type")==0) continue;
if (kw==NULL) {
PyErr_Format( PyExc_AttributeError, "%s: no keywords, expected \"%s\"", error_prefix, arg_name ? arg_name : "<UNKNOWN>");
PyErr_Format( PyExc_AttributeError, "%.200s: no keywords, expected \"%.200s\"", error_prefix, arg_name ? arg_name : "<UNKNOWN>");
error_val= -1;
break;
}
@@ -245,7 +400,7 @@ int pyrna_pydict_to_props(PointerRNA *ptr, PyObject *kw, const char *error_prefi
item= PyDict_GetItemString(kw, arg_name);
if (item == NULL) {
PyErr_Format( PyExc_AttributeError, "%s: keyword \"%s\" missing", error_prefix, arg_name ? arg_name : "<UNKNOWN>");
PyErr_Format( PyExc_AttributeError, "%.200s: keyword \"%.200s\" missing", error_prefix, arg_name ? arg_name : "<UNKNOWN>");
error_val = -1; /* pyrna_py_to_prop sets the error */
break;
}
@@ -257,8 +412,7 @@ int pyrna_pydict_to_props(PointerRNA *ptr, PyObject *kw, const char *error_prefi
totkw--;
}
RNA_property_collection_end(&iter);
RNA_STRUCT_END;
if (error_val==0 && totkw > 0) { /* some keywords were given that were not used :/ */
PyObject *key, *value;
@@ -270,7 +424,7 @@ int pyrna_pydict_to_props(PointerRNA *ptr, PyObject *kw, const char *error_prefi
arg_name= NULL;
}
PyErr_Format( PyExc_AttributeError, "%s: keyword \"%s\" unrecognized", error_prefix, arg_name ? arg_name : "<UNKNOWN>");
PyErr_Format( PyExc_AttributeError, "%.200s: keyword \"%.200s\" unrecognized", error_prefix, arg_name ? arg_name : "<UNKNOWN>");
error_val = -1;
}
@@ -279,12 +433,15 @@ int pyrna_pydict_to_props(PointerRNA *ptr, PyObject *kw, const char *error_prefi
static PyObject * pyrna_func_call(PyObject * self, PyObject *args, PyObject *kw);
PyObject *pyrna_func_to_py(PointerRNA *ptr, FunctionRNA *func)
PyObject *pyrna_func_to_py(BPy_StructRNA *pyrna, FunctionRNA *func)
{
static PyMethodDef func_meth = {"<generic rna function>", (PyCFunction)pyrna_func_call, METH_VARARGS|METH_KEYWORDS, "python rna function"};
PyObject *self= PyTuple_New(2);
PyObject *ret;
PyTuple_SET_ITEM(self, 0, pyrna_struct_CreatePyObject(ptr));
PyTuple_SET_ITEM(self, 0, (PyObject *)pyrna);
Py_INCREF(pyrna);
PyTuple_SET_ITEM(self, 1, PyCObject_FromVoidPtr((void *)func, NULL));
ret= PyCFunction_New(&func_meth, self);
@@ -302,15 +459,30 @@ int pyrna_py_to_prop(PointerRNA *ptr, PropertyRNA *prop, void *data, PyObject *v
if (len > 0) {
PyObject *item;
int py_len = -1;
int i;
if (!PySequence_Check(value)) {
PyErr_SetString(PyExc_TypeError, "expected a python sequence type assigned to an RNA array.");
#ifdef USE_MATHUTILS
if(MatrixObject_Check(value)) {
MatrixObject *mat = (MatrixObject*)value;
if(!BaseMath_ReadCallback(mat))
return -1;
py_len = mat->rowSize * mat->colSize;
} else /* continue... */
#endif
if (PySequence_Check(value)) {
py_len= (int)PySequence_Length(value);
}
else {
PyErr_Format(PyExc_TypeError, "RNA array assignment expected a sequence instead of %.200s instance.", Py_TYPE(value)->tp_name);
return -1;
}
/* done getting the length */
if ((int)PySequence_Length(value) != len) {
PyErr_SetString(PyExc_AttributeError, "python sequence length did not match the RNA array.");
if (py_len != len) {
PyErr_Format(PyExc_AttributeError, "python sequence length %d did not match the RNA array length %d.", py_len, len);
return -1;
}
@@ -376,14 +548,21 @@ int pyrna_py_to_prop(PointerRNA *ptr, PropertyRNA *prop, void *data, PyObject *v
else param_arr = MEM_mallocN(sizeof(float) * len, "pyrna float array");
/* collect the variables */
for (i=0; i<len; i++) {
item = PySequence_GetItem(value, i);
param_arr[i] = (float)PyFloat_AsDouble(item); /* deal with any errors later */
Py_DECREF(item);
#ifdef USE_MATHUTILS
if(MatrixObject_Check(value) && RNA_property_subtype(prop) == PROP_MATRIX) {
MatrixObject *mat = (MatrixObject*)value;
memcpy(param_arr, mat->contigPtr, sizeof(float) * len);
} else /* continue... */
#endif
{
/* collect the variables */
for (i=0; i<len; i++) {
item = PySequence_GetItem(value, i);
param_arr[i] = (float)PyFloat_AsDouble(item); /* deal with any errors later */
Py_DECREF(item);
}
}
if (PyErr_Occurred()) {
if(data==NULL)
MEM_freeN(param_arr);
@@ -458,17 +637,17 @@ int pyrna_py_to_prop(PointerRNA *ptr, PropertyRNA *prop, void *data, PyObject *v
if (param==NULL) {
char *enum_str= pyrna_enum_as_string(ptr, prop);
PyErr_Format(PyExc_TypeError, "expected a string enum type in (%s)", enum_str);
PyErr_Format(PyExc_TypeError, "expected a string enum type in (%.200s)", enum_str);
MEM_freeN(enum_str);
return -1;
} else {
int val;
if (RNA_property_enum_value(ptr, prop, param, &val)) {
if (RNA_property_enum_value(BPy_GetContext(), ptr, prop, param, &val)) {
if(data) *((int*)data)= val;
else RNA_property_enum_set(ptr, prop, val);
} else {
char *enum_str= pyrna_enum_as_string(ptr, prop);
PyErr_Format(PyExc_AttributeError, "enum \"%s\" not found in (%s)", param, enum_str);
PyErr_Format(PyExc_AttributeError, "enum \"%.200s\" not found in (%.200s)", param, enum_str);
MEM_freeN(enum_str);
return -1;
}
@@ -483,13 +662,15 @@ int pyrna_py_to_prop(PointerRNA *ptr, PropertyRNA *prop, void *data, PyObject *v
if(!BPy_StructRNA_Check(value) && value != Py_None) {
PointerRNA tmp;
RNA_pointer_create(NULL, ptype, NULL, &tmp);
PyErr_Format(PyExc_TypeError, "expected a %s type", RNA_struct_identifier(tmp.type));
PyErr_Format(PyExc_TypeError, "expected a %.200s type", RNA_struct_identifier(tmp.type));
return -1;
} else {
BPy_StructRNA *param= (BPy_StructRNA*)value;
int raise_error= 0;
if(data) {
if(ptype == &RNA_AnyType) {
int flag = RNA_property_flag(prop);
if(flag & PROP_RNAPTR) {
if(value == Py_None)
memset(data, 0, sizeof(PointerRNA));
else
@@ -518,7 +699,7 @@ int pyrna_py_to_prop(PointerRNA *ptr, PropertyRNA *prop, void *data, PyObject *v
else {
PointerRNA tmp;
RNA_pointer_create(NULL, ptype, NULL, &tmp);
PyErr_Format(PyExc_TypeError, "expected a %s type", RNA_struct_identifier(tmp.type));
PyErr_Format(PyExc_TypeError, "expected a %.200s type", RNA_struct_identifier(tmp.type));
return -1;
}
}
@@ -526,7 +707,7 @@ int pyrna_py_to_prop(PointerRNA *ptr, PropertyRNA *prop, void *data, PyObject *v
if(raise_error) {
PointerRNA tmp;
RNA_pointer_create(NULL, ptype, NULL, &tmp);
PyErr_Format(PyExc_TypeError, "expected a %s type", RNA_struct_identifier(tmp.type));
PyErr_Format(PyExc_TypeError, "expected a %.200s type", RNA_struct_identifier(tmp.type));
return -1;
}
}
@@ -537,6 +718,10 @@ int pyrna_py_to_prop(PointerRNA *ptr, PropertyRNA *prop, void *data, PyObject *v
int seq_len, i;
PyObject *item;
PointerRNA itemptr;
ListBase *lb;
CollectionPointerLink *link;
lb= (data)? (ListBase*)data: NULL;
/* convert a sequence of dict's into a collection */
if(!PySequence_Check(value)) {
@@ -552,8 +737,15 @@ int pyrna_py_to_prop(PointerRNA *ptr, PropertyRNA *prop, void *data, PyObject *v
Py_XDECREF(item);
return -1;
}
RNA_property_collection_add(ptr, prop, &itemptr);
if(lb) {
link= MEM_callocN(sizeof(CollectionPointerLink), "PyCollectionPointerLink");
link->ptr= itemptr;
BLI_addtail(lb, link);
}
else
RNA_property_collection_add(ptr, prop, &itemptr);
if(pyrna_pydict_to_props(&itemptr, item, "Converting a python list to an RNA collection")==-1) {
Py_DECREF(item);
return -1;
@@ -667,117 +859,317 @@ static Py_ssize_t pyrna_prop_len( BPy_PropertyRNA * self )
return len;
}
static PyObject *pyrna_prop_subscript( BPy_PropertyRNA * self, PyObject *key )
/* internal use only */
static PyObject *prop_subscript_collection_int(BPy_PropertyRNA * self, int keynum)
{
PyObject *ret;
PointerRNA newptr;
int keynum = 0;
char *keyname = NULL;
if(keynum < 0) keynum += RNA_property_collection_length(&self->ptr, self->prop);
if(RNA_property_collection_lookup_int(&self->ptr, self->prop, keynum, &newptr))
return pyrna_struct_CreatePyObject(&newptr);
PyErr_Format(PyExc_IndexError, "index %d out of range", keynum);
return NULL;
}
static PyObject *prop_subscript_array_int(BPy_PropertyRNA * self, int keynum)
{
int len= RNA_property_array_length(self->prop);
if(keynum < 0) keynum += len;
if(keynum >= 0 && keynum < len)
return pyrna_prop_to_py_index(&self->ptr, self->prop, keynum);
PyErr_Format(PyExc_IndexError, "index %d out of range", keynum);
return NULL;
}
static PyObject *prop_subscript_collection_str(BPy_PropertyRNA * self, char *keyname)
{
PointerRNA newptr;
if(RNA_property_collection_lookup_string(&self->ptr, self->prop, keyname, &newptr))
return pyrna_struct_CreatePyObject(&newptr);
PyErr_Format(PyExc_KeyError, "key \"%.200s\" not found", keyname);
return NULL;
}
/* static PyObject *prop_subscript_array_str(BPy_PropertyRNA * self, char *keyname) */
#if PY_VERSION_HEX >= 0x03000000
static PyObject *prop_subscript_collection_slice(BPy_PropertyRNA * self, int start, int stop)
{
PointerRNA newptr;
PyObject *list = PyList_New(stop - start);
int count;
start = MIN2(start,stop); /* values are clamped from */
for(count = start; count < stop; count++) {
if(RNA_property_collection_lookup_int(&self->ptr, self->prop, count - start, &newptr)) {
PyList_SetItem(list, count - start, pyrna_struct_CreatePyObject(&newptr));
}
else {
Py_DECREF(list);
PyErr_SetString(PyExc_RuntimeError, "error getting an rna struct from a collection");
return NULL;
}
}
return list;
}
static PyObject *prop_subscript_array_slice(BPy_PropertyRNA * self, int start, int stop)
{
PyObject *list = PyList_New(stop - start);
int count;
start = MIN2(start,stop); /* values are clamped from PySlice_GetIndicesEx */
for(count = start; count < stop; count++)
PyList_SetItem(list, count - start, pyrna_prop_to_py_index(&self->ptr, self->prop, count));
return list;
}
#endif
static PyObject *prop_subscript_collection(BPy_PropertyRNA * self, PyObject *key)
{
if (PyUnicode_Check(key)) {
keyname = _PyUnicode_AsString(key);
} else if (PyLong_Check(key)) {
keynum = PyLong_AsSsize_t(key);
} else {
PyErr_SetString(PyExc_AttributeError, "invalid key, key must be a string or an int");
return prop_subscript_collection_str(self, _PyUnicode_AsString(key));
}
else if (PyIndex_Check(key)) {
Py_ssize_t i = PyNumber_AsSsize_t(key, PyExc_IndexError);
if (i == -1 && PyErr_Occurred())
return NULL;
return prop_subscript_collection_int(self, i);
}
#if PY_VERSION_HEX >= 0x03000000
else if (PySlice_Check(key)) {
int len= RNA_property_collection_length(&self->ptr, self->prop);
Py_ssize_t start, stop, step, slicelength;
if (PySlice_GetIndicesEx((PySliceObject*)key, len, &start, &stop, &step, &slicelength) < 0)
return NULL;
if (slicelength <= 0) {
return PyList_New(0);
}
else if (step == 1) {
return prop_subscript_collection_slice(self, start, stop);
}
else {
PyErr_SetString(PyExc_TypeError, "slice steps not supported with rna");
return NULL;
}
}
#endif
else {
PyErr_Format(PyExc_TypeError, "invalid rna key, key must be a string or an int instead of %.200s instance.", Py_TYPE(key)->tp_name);
return NULL;
}
if (RNA_property_type(self->prop) == PROP_COLLECTION) {
int ok;
if (keyname) ok = RNA_property_collection_lookup_string(&self->ptr, self->prop, keyname, &newptr);
else ok = RNA_property_collection_lookup_int(&self->ptr, self->prop, keynum, &newptr);
if (ok) {
ret = pyrna_struct_CreatePyObject(&newptr);
} else {
PyErr_SetString(PyExc_AttributeError, "out of range");
ret = NULL;
}
} else if (keyname) {
PyErr_SetString(PyExc_AttributeError, "string keys are only supported for collections");
ret = NULL;
} else {
int len = RNA_property_array_length(self->prop);
if (len==0) { /* not an array*/
PyErr_Format(PyExc_AttributeError, "not an array or collection %d", keynum);
ret = NULL;
}
if (keynum >= len){
PyErr_SetString(PyExc_AttributeError, "index out of range");
ret = NULL;
} else { /* not an array*/
ret = pyrna_prop_to_py_index(&self->ptr, self->prop, keynum);
}
}
return ret;
}
static int pyrna_prop_assign_subscript( BPy_PropertyRNA * self, PyObject *key, PyObject *value )
static PyObject *prop_subscript_array(BPy_PropertyRNA * self, PyObject *key)
{
int ret = 0;
int keynum = 0;
char *keyname = NULL;
/*if (PyUnicode_Check(key)) {
return prop_subscript_array_str(self, _PyUnicode_AsString(key));
} else*/
if (PyIndex_Check(key)) {
Py_ssize_t i = PyNumber_AsSsize_t(key, PyExc_IndexError);
if (i == -1 && PyErr_Occurred())
return NULL;
return prop_subscript_array_int(self, PyLong_AsSsize_t(key));
}
#if PY_VERSION_HEX >= 0x03000000
else if (PySlice_Check(key)) {
int len= RNA_property_array_length(self->prop);
Py_ssize_t start, stop, step, slicelength;
if (PySlice_GetIndicesEx((PySliceObject*)key, len, &start, &stop, &step, &slicelength) < 0)
return NULL;
if (slicelength <= 0) {
return PyList_New(0);
}
else if (step == 1) {
return prop_subscript_array_slice(self, start, stop);
}
else {
PyErr_SetString(PyExc_TypeError, "slice steps not supported with rna");
return NULL;
}
}
#endif
else {
PyErr_SetString(PyExc_AttributeError, "invalid key, key must be an int");
return NULL;
}
}
static PyObject *pyrna_prop_subscript( BPy_PropertyRNA * self, PyObject *key )
{
if (RNA_property_type(self->prop) == PROP_COLLECTION) {
return prop_subscript_collection(self, key);
} else if (RNA_property_array_length(self->prop)) { /* arrays are currently fixed length, zero length means its not an array */
return prop_subscript_array(self, key);
} else {
PyErr_SetString(PyExc_TypeError, "rna type is not an array or a collection");
return NULL;
}
}
#if PY_VERSION_HEX >= 0x03000000
static int prop_subscript_ass_array_slice(BPy_PropertyRNA * self, int begin, int end, PyObject *value)
{
int count;
/* values are clamped from */
begin = MIN2(begin,end);
for(count = begin; count < end; count++) {
if(pyrna_py_to_prop_index(&self->ptr, self->prop, count - begin, value) == -1) {
/* TODO - this is wrong since some values have been assigned... will need to fix that */
return -1; /* pyrna_struct_CreatePyObject should set the error */
}
}
return 0;
}
#endif
static int prop_subscript_ass_array_int(BPy_PropertyRNA * self, int keynum, PyObject *value)
{
int len= RNA_property_array_length(self->prop);
if(keynum < 0) keynum += len;
if(keynum >= 0 && keynum < len)
return pyrna_py_to_prop_index(&self->ptr, self->prop, keynum, value);
PyErr_SetString(PyExc_IndexError, "out of range");
return -1;
}
static int pyrna_prop_ass_subscript( BPy_PropertyRNA * self, PyObject *key, PyObject *value )
{
/* char *keyname = NULL; */ /* not supported yet */
if (!RNA_property_editable(&self->ptr, self->prop)) {
PyErr_Format( PyExc_AttributeError, "PropertyRNA - attribute \"%s\" from \"%s\" is read-only", RNA_property_identifier(self->prop), RNA_struct_identifier(self->ptr.type) );
return -1;
}
if (PyUnicode_Check(key)) {
keyname = _PyUnicode_AsString(key);
} else if (PyLong_Check(key)) {
keynum = PyLong_AsSsize_t(key);
} else {
PyErr_SetString(PyExc_AttributeError, "PropertyRNA - invalid key, key must be a string or an int");
PyErr_Format( PyExc_AttributeError, "PropertyRNA - attribute \"%.200s\" from \"%.200s\" is read-only", RNA_property_identifier(self->prop), RNA_struct_identifier(self->ptr.type) );
return -1;
}
/* maybe one day we can support this... */
if (RNA_property_type(self->prop) == PROP_COLLECTION) {
PyErr_SetString(PyExc_AttributeError, "PropertyRNA - assignment is not supported for collections (yet)");
ret = -1;
} else if (keyname) {
PyErr_SetString(PyExc_AttributeError, "PropertyRNA - string keys are only supported for collections");
ret = -1;
} else {
int len = RNA_property_array_length(self->prop);
if (len==0) { /* not an array*/
PyErr_Format(PyExc_AttributeError, "PropertyRNA - not an array or collection %d", keynum);
ret = -1;
PyErr_Format( PyExc_AttributeError, "PropertyRNA - attribute \"%.200s\" from \"%.200s\" is a collection, assignment not supported", RNA_property_identifier(self->prop), RNA_struct_identifier(self->ptr.type) );
return -1;
}
if (PyIndex_Check(key)) {
Py_ssize_t i = PyNumber_AsSsize_t(key, PyExc_IndexError);
if (i == -1 && PyErr_Occurred())
return -1;
return prop_subscript_ass_array_int(self, i, value);
}
#if PY_VERSION_HEX >= 0x03000000
else if (PySlice_Check(key)) {
int len= RNA_property_array_length(self->prop);
Py_ssize_t start, stop, step, slicelength;
if (PySlice_GetIndicesEx((PySliceObject*)key, len, &start, &stop, &step, &slicelength) < 0)
return -1;
if (slicelength <= 0) {
return 0;
}
if (keynum >= len){
PyErr_SetString(PyExc_AttributeError, "PropertyRNA - index out of range");
ret = -1;
} else {
ret = pyrna_py_to_prop_index(&self->ptr, self->prop, keynum, value);
else if (step == 1) {
return prop_subscript_ass_array_slice(self, start, stop, value);
}
else {
PyErr_SetString(PyExc_TypeError, "slice steps not supported with rna");
return -1;
}
}
return ret;
#endif
else {
PyErr_SetString(PyExc_AttributeError, "invalid key, key must be an int");
return -1;
}
}
static PyMappingMethods pyrna_prop_as_mapping = {
( lenfunc ) pyrna_prop_len, /* mp_length */
( binaryfunc ) pyrna_prop_subscript, /* mp_subscript */
( objobjargproc ) pyrna_prop_assign_subscript, /* mp_ass_subscript */
( objobjargproc ) pyrna_prop_ass_subscript, /* mp_ass_subscript */
};
static int pyrna_prop_contains(BPy_PropertyRNA * self, PyObject *value)
{
PointerRNA newptr; /* not used, just so RNA_property_collection_lookup_string runs */
char *keyname = _PyUnicode_AsString(value);
if(keyname==NULL) {
PyErr_SetString(PyExc_TypeError, "PropertyRNA - key in prop, key must be a string type");
return -1;
}
if (RNA_property_type(self->prop) != PROP_COLLECTION) {
PyErr_SetString(PyExc_TypeError, "PropertyRNA - key in prop, is only valid for collection types");
return -1;
}
if (RNA_property_collection_lookup_string(&self->ptr, self->prop, keyname, &newptr))
return 1;
return 0;
}
static PySequenceMethods pyrna_prop_as_sequence = {
NULL, /* Cant set the len otherwise it can evaluate as false */
NULL, /* sq_concat */
NULL, /* sq_repeat */
NULL, /* sq_item */
NULL, /* sq_slice */
NULL, /* sq_ass_item */
NULL, /* sq_ass_slice */
(objobjproc)pyrna_prop_contains, /* sq_contains */
};
static PyObject *pyrna_struct_keyframe_insert(BPy_StructRNA * self, PyObject *args)
{
char *path;
int index= 0;
float cfra = CTX_data_scene(BPy_GetContext())->r.cfra;
if(!RNA_struct_is_ID(self->ptr.type)) {
PyErr_SetString( PyExc_TypeError, "StructRNA - keyframe_insert only for ID type");
return NULL;
}
if (!PyArg_ParseTuple(args, "s|if:keyframe_insert", &path, &index, &cfra))
return NULL;
return PyBool_FromLong( insert_keyframe((ID *)self->ptr.data, NULL, NULL, path, index, cfra, 0));
}
static PyObject *pyrna_struct_dir(BPy_StructRNA * self)
{
PyObject *ret, *dict;
PyObject *pystring;
/* for looping over attrs and funcs */
CollectionPropertyIterator iter;
PropertyRNA *iterprop;
/* Include this incase this instance is a subtype of a python class
@@ -806,26 +1198,23 @@ static PyObject *pyrna_struct_dir(BPy_StructRNA * self)
/*
* Collect RNA attributes
*/
PropertyRNA *nameprop;
char name[256], *nameptr;
iterprop= RNA_struct_iterator_property(self->ptr.type);
RNA_property_collection_begin(&self->ptr, iterprop, &iter);
for(; iter.valid; RNA_property_collection_next(&iter)) {
if(iter.ptr.data && (nameprop = RNA_struct_name_property(iter.ptr.type))) {
nameptr= RNA_property_string_get_alloc(&iter.ptr, nameprop, name, sizeof(name));
RNA_PROP_BEGIN(&self->ptr, itemptr, iterprop) {
nameptr= RNA_struct_name_get_alloc(&itemptr, name, sizeof(name));
if(nameptr) {
pystring = PyUnicode_FromString(nameptr);
PyList_Append(ret, pystring);
Py_DECREF(pystring);
if ((char *)&name != nameptr)
if(name != nameptr)
MEM_freeN(nameptr);
}
}
RNA_property_collection_end(&iter);
RNA_PROP_END;
}
@@ -838,15 +1227,25 @@ static PyObject *pyrna_struct_dir(BPy_StructRNA * self)
RNA_pointer_create(NULL, &RNA_Struct, self->ptr.type, &tptr);
iterprop= RNA_struct_find_property(&tptr, "functions");
RNA_property_collection_begin(&tptr, iterprop, &iter);
RNA_PROP_BEGIN(&tptr, itemptr, iterprop) {
pystring = PyUnicode_FromString(RNA_function_identifier(itemptr.data));
PyList_Append(ret, pystring);
Py_DECREF(pystring);
}
RNA_PROP_END;
}
for(; iter.valid; RNA_property_collection_next(&iter)) {
pystring = PyUnicode_FromString(RNA_function_identifier(iter.ptr.data));
if(self->ptr.type == &RNA_Context) {
ListBase lb = CTX_data_dir_get(self->ptr.data);
LinkData *link;
for(link=lb.first; link; link=link->next) {
pystring = PyUnicode_FromString(link->data);
PyList_Append(ret, pystring);
Py_DECREF(pystring);
}
RNA_property_collection_end(&iter);
BLI_freelistN(&lb);
}
return ret;
@@ -875,7 +1274,7 @@ static PyObject *pyrna_struct_getattro( BPy_StructRNA * self, PyObject *pyname )
ret = pyrna_prop_to_py(&self->ptr, prop);
}
else if ((func = RNA_struct_find_function(&self->ptr, name))) {
ret = pyrna_func_to_py(&self->ptr, func);
ret = pyrna_func_to_py(self, func);
}
else if (self->ptr.type == &RNA_Context) {
PointerRNA newptr;
@@ -906,7 +1305,7 @@ static PyObject *pyrna_struct_getattro( BPy_StructRNA * self, PyObject *pyname )
BLI_freelistN(&newlb);
}
else {
PyErr_Format( PyExc_AttributeError, "StructRNA - Attribute \"%s\" not found", name);
PyErr_Format( PyExc_AttributeError, "StructRNA - Attribute \"%.200s\" not found", name);
ret = NULL;
}
@@ -924,13 +1323,13 @@ static int pyrna_struct_setattro( BPy_StructRNA * self, PyObject *pyname, PyObje
return 0;
}
else {
PyErr_Format( PyExc_AttributeError, "StructRNA - Attribute \"%s\" not found", name);
PyErr_Format( PyExc_AttributeError, "StructRNA - Attribute \"%.200s\" not found", name);
return -1;
}
}
if (!RNA_property_editable(&self->ptr, prop)) {
PyErr_Format( PyExc_AttributeError, "StructRNA - Attribute \"%s\" from \"%s\" is read-only", RNA_property_identifier(prop), RNA_struct_identifier(self->ptr.type) );
PyErr_Format( PyExc_AttributeError, "StructRNA - Attribute \"%.200s\" from \"%.200s\" is read-only", RNA_property_identifier(prop), RNA_struct_identifier(self->ptr.type) );
return -1;
}
@@ -938,7 +1337,7 @@ static int pyrna_struct_setattro( BPy_StructRNA * self, PyObject *pyname, PyObje
return pyrna_py_to_prop(&self->ptr, prop, NULL, value);
}
PyObject *pyrna_prop_keys(BPy_PropertyRNA *self)
static PyObject *pyrna_prop_keys(BPy_PropertyRNA *self)
{
PyObject *ret;
if (RNA_property_type(self->prop) != PROP_COLLECTION) {
@@ -946,34 +1345,31 @@ PyObject *pyrna_prop_keys(BPy_PropertyRNA *self)
ret = NULL;
} else {
PyObject *item;
CollectionPropertyIterator iter;
PropertyRNA *nameprop;
char name[256], *nameptr;
ret = PyList_New(0);
RNA_property_collection_begin(&self->ptr, self->prop, &iter);
for(; iter.valid; RNA_property_collection_next(&iter)) {
if(iter.ptr.data && (nameprop = RNA_struct_name_property(iter.ptr.type))) {
nameptr= RNA_property_string_get_alloc(&iter.ptr, nameprop, name, sizeof(name));
RNA_PROP_BEGIN(&self->ptr, itemptr, self->prop) {
nameptr= RNA_struct_name_get_alloc(&itemptr, name, sizeof(name));
if(nameptr) {
/* add to python list */
item = PyUnicode_FromString( nameptr );
PyList_Append(ret, item);
Py_DECREF(item);
/* done */
if ((char *)&name != nameptr)
if(name != nameptr)
MEM_freeN(nameptr);
}
}
RNA_property_collection_end(&iter);
RNA_PROP_END;
}
return ret;
}
PyObject *pyrna_prop_items(BPy_PropertyRNA *self)
static PyObject *pyrna_prop_items(BPy_PropertyRNA *self)
{
PyObject *ret;
if (RNA_property_type(self->prop) != PROP_COLLECTION) {
@@ -981,61 +1377,316 @@ PyObject *pyrna_prop_items(BPy_PropertyRNA *self)
ret = NULL;
} else {
PyObject *item;
CollectionPropertyIterator iter;
PropertyRNA *nameprop;
char name[256], *nameptr;
int i= 0;
ret = PyList_New(0);
RNA_property_collection_begin(&self->ptr, self->prop, &iter);
for(; iter.valid; RNA_property_collection_next(&iter)) {
if(iter.ptr.data && (nameprop = RNA_struct_name_property(iter.ptr.type))) {
nameptr= RNA_property_string_get_alloc(&iter.ptr, nameprop, name, sizeof(name));
RNA_PROP_BEGIN(&self->ptr, itemptr, self->prop) {
if(itemptr.data) {
/* add to python list */
item = Py_BuildValue("(NN)", PyUnicode_FromString( nameptr ), pyrna_struct_CreatePyObject(&iter.ptr));
item= PyTuple_New(2);
nameptr= RNA_struct_name_get_alloc(&itemptr, name, sizeof(name));
if(nameptr) {
PyTuple_SET_ITEM(item, 0, PyUnicode_FromString( nameptr ));
if(name != nameptr)
MEM_freeN(nameptr);
}
else {
PyTuple_SET_ITEM(item, 0, PyLong_FromSsize_t(i)); /* a bit strange but better then returning an empty list */
}
PyTuple_SET_ITEM(item, 1, pyrna_struct_CreatePyObject(&itemptr));
PyList_Append(ret, item);
Py_DECREF(item);
/* done */
if ((char *)&name != nameptr)
MEM_freeN(nameptr);
i++;
}
}
RNA_property_collection_end(&iter);
RNA_PROP_END;
}
return ret;
}
PyObject *pyrna_prop_values(BPy_PropertyRNA *self)
static PyObject *pyrna_prop_values(BPy_PropertyRNA *self)
{
PyObject *ret;
if (RNA_property_type(self->prop) != PROP_COLLECTION) {
PyErr_SetString( PyExc_TypeError, "values() is only valid for collection types" );
ret = NULL;
} else {
PyObject *item;
CollectionPropertyIterator iter;
PropertyRNA *nameprop;
ret = PyList_New(0);
RNA_property_collection_begin(&self->ptr, self->prop, &iter);
for(; iter.valid; RNA_property_collection_next(&iter)) {
if(iter.ptr.data && (nameprop = RNA_struct_name_property(iter.ptr.type))) {
item = pyrna_struct_CreatePyObject(&iter.ptr);
PyList_Append(ret, item);
Py_DECREF(item);
}
RNA_PROP_BEGIN(&self->ptr, itemptr, self->prop) {
item = pyrna_struct_CreatePyObject(&itemptr);
PyList_Append(ret, item);
Py_DECREF(item);
}
RNA_property_collection_end(&iter);
RNA_PROP_END;
}
return ret;
}
static PyObject *pyrna_prop_get(BPy_PropertyRNA *self, PyObject *args)
{
PointerRNA newptr;
char *key;
PyObject* def = Py_None;
if (!PyArg_ParseTuple(args, "s|O:get", &key, &def))
return NULL;
if(RNA_property_collection_lookup_string(&self->ptr, self->prop, key, &newptr))
return pyrna_struct_CreatePyObject(&newptr);
Py_INCREF(def);
return def;
}
#if (PY_VERSION_HEX >= 0x03000000) /* foreach needs py3 */
static void foreach_attr_type( BPy_PropertyRNA *self, char *attr,
/* values to assign */
RawPropertyType *raw_type, int *attr_tot, int *attr_signed )
{
PropertyRNA *prop;
*raw_type= -1;
*attr_tot= 0;
*attr_signed= 0;
RNA_PROP_BEGIN(&self->ptr, itemptr, self->prop) {
prop = RNA_struct_find_property(&itemptr, attr);
*raw_type= RNA_property_raw_type(prop);
*attr_tot = RNA_property_array_length(prop);
*attr_signed= (RNA_property_subtype(prop)==PROP_UNSIGNED) ? 0:1;
break;
}
RNA_PROP_END;
}
/* pyrna_prop_foreach_get/set both use this */
static int foreach_parse_args(
BPy_PropertyRNA *self, PyObject *args,
/*values to assign */
char **attr, PyObject **seq, int *tot, int *size, RawPropertyType *raw_type, int *attr_tot, int *attr_signed)
{
#if 0
int array_tot;
int target_tot;
#endif
*size= *raw_type= *attr_tot= *attr_signed= 0;
if(!PyArg_ParseTuple(args, "sO", attr, seq) || (!PySequence_Check(*seq) && PyObject_CheckBuffer(*seq))) {
PyErr_SetString( PyExc_TypeError, "foreach_get(attr, sequence) expects a string and a sequence" );
return -1;
}
*tot= PySequence_Length(*seq); // TODO - buffer may not be a sequence! array.array() is tho.
if(*tot>0) {
foreach_attr_type(self, *attr, raw_type, attr_tot, attr_signed);
*size= RNA_raw_type_sizeof(*raw_type);
#if 0 // works fine but not strictly needed, we could allow RNA_property_collection_raw_* to do the checks
if((*attr_tot) < 1)
*attr_tot= 1;
if (RNA_property_type(self->prop) == PROP_COLLECTION)
array_tot = RNA_property_collection_length(&self->ptr, self->prop);
else
array_tot = RNA_property_array_length(self->prop);
target_tot= array_tot * (*attr_tot);
/* rna_access.c - rna_raw_access(...) uses this same method */
if(target_tot != (*tot)) {
PyErr_Format( PyExc_TypeError, "foreach_get(attr, sequence) sequence length mismatch given %d, needed %d", *tot, target_tot);
return -1;
}
#endif
}
return 0;
}
static int foreach_compat_buffer(RawPropertyType raw_type, int attr_signed, const char *format)
{
char f = format ? *format:'B'; /* B is assumed when not set */
switch(raw_type) {
case PROP_RAW_CHAR:
if (attr_signed) return (f=='b') ? 1:0;
else return (f=='B') ? 1:0;
case PROP_RAW_SHORT:
if (attr_signed) return (f=='h') ? 1:0;
else return (f=='H') ? 1:0;
case PROP_RAW_INT:
if (attr_signed) return (f=='i') ? 1:0;
else return (f=='I') ? 1:0;
case PROP_RAW_FLOAT:
return (f=='f') ? 1:0;
case PROP_RAW_DOUBLE:
return (f=='d') ? 1:0;
}
return 0;
}
static PyObject *foreach_getset(BPy_PropertyRNA *self, PyObject *args, int set)
{
PyObject *item;
int i=0, ok, buffer_is_compat;
void *array= NULL;
/* get/set both take the same args currently */
char *attr;
PyObject *seq;
int tot, size, attr_tot, attr_signed;
RawPropertyType raw_type;
if(foreach_parse_args(self, args, &attr, &seq, &tot, &size, &raw_type, &attr_tot, &attr_signed) < 0)
return NULL;
if(tot==0)
Py_RETURN_NONE;
if(set) { /* get the array from python */
buffer_is_compat = 0;
if(PyObject_CheckBuffer(seq)) {
Py_buffer buf;
PyObject_GetBuffer(seq, &buf, PyBUF_SIMPLE | PyBUF_FORMAT);
/* check if the buffer matches */
buffer_is_compat = foreach_compat_buffer(raw_type, attr_signed, buf.format);
if(buffer_is_compat) {
ok = RNA_property_collection_raw_set(NULL, &self->ptr, self->prop, attr, buf.buf, raw_type, tot);
}
PyBuffer_Release(&buf);
}
/* could not use the buffer, fallback to sequence */
if(!buffer_is_compat) {
array= PyMem_Malloc(size * tot);
for( ; i<tot; i++) {
item= PySequence_GetItem(seq, i);
switch(raw_type) {
case PROP_RAW_CHAR:
((char *)array)[i]= (char)PyLong_AsSsize_t(item);
break;
case PROP_RAW_SHORT:
((short *)array)[i]= (short)PyLong_AsSsize_t(item);
break;
case PROP_RAW_INT:
((int *)array)[i]= (int)PyLong_AsSsize_t(item);
break;
case PROP_RAW_FLOAT:
((float *)array)[i]= (float)PyFloat_AsDouble(item);
break;
case PROP_RAW_DOUBLE:
((double *)array)[i]= (double)PyFloat_AsDouble(item);
break;
}
Py_DECREF(item);
}
ok = RNA_property_collection_raw_set(NULL, &self->ptr, self->prop, attr, array, raw_type, tot);
}
}
else {
buffer_is_compat = 0;
if(PyObject_CheckBuffer(seq)) {
Py_buffer buf;
PyObject_GetBuffer(seq, &buf, PyBUF_SIMPLE | PyBUF_FORMAT);
/* check if the buffer matches, TODO - signed/unsigned types */
buffer_is_compat = foreach_compat_buffer(raw_type, attr_signed, buf.format);
if(buffer_is_compat) {
ok = RNA_property_collection_raw_get(NULL, &self->ptr, self->prop, attr, buf.buf, raw_type, tot);
}
PyBuffer_Release(&buf);
}
/* could not use the buffer, fallback to sequence */
if(!buffer_is_compat) {
array= PyMem_Malloc(size * tot);
ok = RNA_property_collection_raw_get(NULL, &self->ptr, self->prop, attr, array, raw_type, tot);
if(!ok) i= tot; /* skip the loop */
for( ; i<tot; i++) {
switch(raw_type) {
case PROP_RAW_CHAR:
item= PyLong_FromSsize_t( (Py_ssize_t) ((char *)array)[i] );
break;
case PROP_RAW_SHORT:
item= PyLong_FromSsize_t( (Py_ssize_t) ((short *)array)[i] );
break;
case PROP_RAW_INT:
item= PyLong_FromSsize_t( (Py_ssize_t) ((int *)array)[i] );
break;
case PROP_RAW_FLOAT:
item= PyFloat_FromDouble( (double) ((float *)array)[i] );
break;
case PROP_RAW_DOUBLE:
item= PyFloat_FromDouble( (double) ((double *)array)[i] );
break;
}
PySequence_SetItem(seq, i, item);
Py_DECREF(item);
}
}
}
if(PyErr_Occurred()) {
/* Maybe we could make our own error */
PyErr_Print();
PyErr_SetString(PyExc_SystemError, "could not access the py sequence");
return NULL;
}
if (!ok) {
PyErr_SetString(PyExc_SystemError, "internal error setting the array");
return NULL;
}
if(array)
PyMem_Free(array);
Py_RETURN_NONE;
}
static PyObject *pyrna_prop_foreach_get(BPy_PropertyRNA *self, PyObject *args)
{
return foreach_getset(self, args, 0);
}
static PyObject *pyrna_prop_foreach_set(BPy_PropertyRNA *self, PyObject *args)
{
return foreach_getset(self, args, 1);
}
#endif /* #if (PY_VERSION_HEX >= 0x03000000) */
/* A bit of a kludge, make a list out of a collection or array,
* then return the lists iter function, not especially fast but convenient for now */
PyObject *pyrna_prop_iter(BPy_PropertyRNA *self)
@@ -1070,14 +1721,26 @@ PyObject *pyrna_prop_iter(BPy_PropertyRNA *self)
}
static struct PyMethodDef pyrna_struct_methods[] = {
{"__dir__", (PyCFunction)pyrna_struct_dir, METH_NOARGS, ""},
/* maybe this become and ID function */
{"keyframe_insert", (PyCFunction)pyrna_struct_keyframe_insert, METH_VARARGS, NULL},
{"__dir__", (PyCFunction)pyrna_struct_dir, METH_NOARGS, NULL},
{NULL, NULL, 0, NULL}
};
static struct PyMethodDef pyrna_prop_methods[] = {
{"keys", (PyCFunction)pyrna_prop_keys, METH_NOARGS, ""},
{"items", (PyCFunction)pyrna_prop_items, METH_NOARGS, ""},
{"values", (PyCFunction)pyrna_prop_values, METH_NOARGS, ""},
{"keys", (PyCFunction)pyrna_prop_keys, METH_NOARGS, NULL},
{"items", (PyCFunction)pyrna_prop_items, METH_NOARGS,NULL},
{"values", (PyCFunction)pyrna_prop_values, METH_NOARGS, NULL},
{"get", (PyCFunction)pyrna_prop_get, METH_VARARGS, NULL},
#if (PY_VERSION_HEX >= 0x03000000)
/* array accessor function */
{"foreach_get", (PyCFunction)pyrna_prop_foreach_get, METH_VARARGS, NULL},
{"foreach_set", (PyCFunction)pyrna_prop_foreach_set, METH_VARARGS, NULL},
#endif
{NULL, NULL, 0, NULL}
};
@@ -1171,11 +1834,17 @@ PyObject *pyrna_param_to_py(PointerRNA *ptr, PropertyRNA *prop, void *data)
const char *identifier;
int val = *(int*)data;
if (RNA_property_enum_identifier(ptr, prop, val, &identifier)) {
if (RNA_property_enum_identifier(BPy_GetContext(), ptr, prop, val, &identifier)) {
ret = PyUnicode_FromString( identifier );
} else {
PyErr_Format(PyExc_AttributeError, "RNA Error: Current value \"%d\" matches no enum", val);
ret = NULL;
/* prefer not fail silently incase of api errors, maybe disable it later */
char error_str[128];
sprintf(error_str, "RNA Warning: Current value \"%d\" matches no enum", val);
PyErr_Warn(PyExc_RuntimeWarning, error_str);
ret = PyUnicode_FromString( "" );
/*PyErr_Format(PyExc_AttributeError, "RNA Error: Current value \"%d\" matches no enum", val);
ret = NULL;*/
}
break;
@@ -1184,8 +1853,9 @@ PyObject *pyrna_param_to_py(PointerRNA *ptr, PropertyRNA *prop, void *data)
{
PointerRNA newptr;
StructRNA *type= RNA_property_pointer_type(ptr, prop);
int flag = RNA_property_flag(prop);
if(type == &RNA_AnyType) {
if(flag & PROP_RNAPTR) {
/* in this case we get the full ptr */
newptr= *(PointerRNA*)data;
}
@@ -1203,10 +1873,21 @@ PyObject *pyrna_param_to_py(PointerRNA *ptr, PropertyRNA *prop, void *data)
break;
}
case PROP_COLLECTION:
/* XXX not supported yet
* ret = pyrna_prop_CreatePyObject(ptr, prop); */
ret = NULL;
{
ListBase *lb= (ListBase*)data;
CollectionPointerLink *link;
PyObject *linkptr;
ret = PyList_New(0);
for(link=lb->first; link; link=link->next) {
linkptr= pyrna_struct_CreatePyObject(&link->ptr);
PyList_Append(ret, linkptr);
Py_DECREF(linkptr);
}
break;
}
default:
PyErr_Format(PyExc_AttributeError, "RNA Error: unknown type \"%d\" (pyrna_param_to_py)", type);
ret = NULL;
@@ -1265,7 +1946,7 @@ static PyObject * pyrna_func_call(PyObject * self, PyObject *args, PyObject *kw)
tid= RNA_struct_identifier(self_ptr->type);
fid= RNA_function_identifier(self_func);
PyErr_Format(PyExc_AttributeError, "%s.%s(): required parameter \"%s\" not specified", tid, fid, pid);
PyErr_Format(PyExc_AttributeError, "%.200s.%.200s(): required parameter \"%.200s\" not specified", tid, fid, pid);
err= -1;
break;
}
@@ -1282,11 +1963,19 @@ static PyObject * pyrna_func_call(PyObject * self, PyObject *args, PyObject *kw)
ret= NULL;
if (err==0) {
/* call function */
RNA_function_call(self_ptr, self_func, parms);
ReportList reports;
bContext *C= BPy_GetContext();
BKE_reports_init(&reports, RPT_STORE);
RNA_function_call(C, &reports, self_ptr, self_func, parms);
err= (BPy_reports_to_error(&reports))? -1: 0;
BKE_reports_clear(&reports);
/* return value */
if(pret)
ret= pyrna_param_to_py(&funcptr, pret, retdata);
if(err==0)
if(pret)
ret= pyrna_param_to_py(&funcptr, pret, retdata);
}
/* cleanup */
@@ -1375,7 +2064,7 @@ PyTypeObject pyrna_struct_Type = {
NULL, /* allocfunc tp_alloc; */
pyrna_struct_new, /* newfunc tp_new; */
/* Low-level free-memory routine */
NULL, //MEM_freeN, /* freefunc tp_free; */
NULL, /* freefunc tp_free; */
/* For PyObject_IS_GC */
NULL, /* inquiry tp_is_gc; */
NULL, /* PyObject *tp_bases; */
@@ -1401,7 +2090,7 @@ PyTypeObject pyrna_prop_Type = {
sizeof( BPy_PropertyRNA ), /* tp_basicsize */
0, /* tp_itemsize */
/* methods */
NULL, /* tp_dealloc */
NULL, /* tp_dealloc */
NULL, /* printfunc tp_print; */
NULL, /* getattrfunc tp_getattr; */
NULL, /* setattrfunc tp_setattr; */
@@ -1411,7 +2100,7 @@ PyTypeObject pyrna_prop_Type = {
/* Method suites for standard classes */
NULL, /* PyNumberMethods *tp_as_number; */
NULL, /* PySequenceMethods *tp_as_sequence; */
&pyrna_prop_as_sequence, /* PySequenceMethods *tp_as_sequence; */
&pyrna_prop_as_mapping, /* PyMappingMethods *tp_as_mapping; */
/* More standard operations (here for binary compatibility) */
@@ -1461,7 +2150,7 @@ PyTypeObject pyrna_prop_Type = {
NULL, /* allocfunc tp_alloc; */
pyrna_prop_new, /* newfunc tp_new; */
/* Low-level free-memory routine */
NULL, //MEM_freeN, /* freefunc tp_free; */
NULL, /* freefunc tp_free; */
/* For PyObject_IS_GC */
NULL, /* inquiry tp_is_gc; */
NULL, /* PyObject *tp_bases; */
@@ -1496,43 +2185,52 @@ static void pyrna_subtype_set_rna(PyObject *newclass, StructRNA *srna)
/* done with rna instance */
}
PyObject* pyrna_struct_Subtype(PointerRNA *ptr)
PyObject* pyrna_srna_Subtype(StructRNA *srna)
{
PyObject *newclass = NULL;
PropertyRNA *nameprop;
if (ptr->type==NULL) {
if (srna == NULL) {
newclass= NULL; /* Nothing to do */
} else if ((newclass= RNA_struct_py_type_get(ptr->data))) {
} else if ((newclass= RNA_struct_py_type_get(srna))) {
Py_INCREF(newclass);
} else if ((nameprop = RNA_struct_name_property(ptr->type))) {
} else {
StructRNA *base;
/* for now, return the base RNA type rather then a real module */
/* Assume RNA_struct_py_type_get(ptr->data) was alredy checked */
/* Assume RNA_struct_py_type_get(srna) was alredy checked */
/* subclass equivelents
- class myClass(myBase):
some='value' # or ...
- myClass = type(name='myClass', bases=(myBase,), dict={'some':'value'})
- myClass = type(name='myClass', bases=(myBase,), dict={'__module__':'bpy.types'})
*/
char name[256], *nameptr;
const char *descr= RNA_struct_ui_description(ptr->type);
const char *descr= RNA_struct_ui_description(srna);
PyObject *args = PyTuple_New(3);
PyObject *bases = PyTuple_New(1);
PyObject *py_base= NULL;
PyObject *dict = PyDict_New();
PyObject *item;
nameptr= RNA_property_string_get_alloc(ptr, nameprop, name, sizeof(name));
// arg 1
//PyTuple_SET_ITEM(args, 0, PyUnicode_FromString(tp_name));
PyTuple_SET_ITEM(args, 0, PyUnicode_FromString(nameptr));
PyTuple_SET_ITEM(args, 0, PyUnicode_FromString(RNA_struct_identifier(srna)));
// arg 2
PyTuple_SET_ITEM(bases, 0, (PyObject *)&pyrna_struct_Type);
Py_INCREF(&pyrna_struct_Type);
base= RNA_struct_base(srna);
if(base && base != srna) {
/*/printf("debug subtype %s %p\n", RNA_struct_identifier(srna), srna); */
py_base= pyrna_srna_Subtype(base);
}
if(py_base==NULL) {
py_base= (PyObject *)&pyrna_struct_Type;
Py_INCREF(py_base);
}
PyTuple_SET_ITEM(bases, 0, py_base);
PyTuple_SET_ITEM(args, 1, bases);
@@ -1543,6 +2241,13 @@ PyObject* pyrna_struct_Subtype(PointerRNA *ptr)
Py_DECREF(item);
}
/* this isnt needed however its confusing if we get python script names in blender types,
* because the __module__ is used when printing the class */
item= PyUnicode_FromString("bpy.types"); /* just to know its an internal type */
PyDict_SetItemString(dict, "__module__", item);
Py_DECREF(item);
PyTuple_SET_ITEM(args, 2, dict); // fill with useful subclass things!
if (PyErr_Occurred()) {
@@ -1553,16 +2258,25 @@ PyObject* pyrna_struct_Subtype(PointerRNA *ptr)
newclass = PyObject_CallObject((PyObject *)&PyType_Type, args);
Py_DECREF(args);
if (newclass)
pyrna_subtype_set_rna(newclass, ptr->data);
if (name != nameptr)
MEM_freeN(nameptr);
if (newclass) {
pyrna_subtype_set_rna(newclass, srna);
// PyObSpit("NewStructRNA Type: ", (PyObject *)newclass);
}
else {
/* this should not happen */
PyErr_Print();
PyErr_Clear();
}
}
return newclass;
}
PyObject* pyrna_struct_Subtype(PointerRNA *ptr)
{
return pyrna_srna_Subtype((ptr->type == &RNA_Struct) ? ptr->data : ptr->type);
}
/*-----------------------CreatePyObject---------------------------------*/
PyObject *pyrna_struct_CreatePyObject( PointerRNA *ptr )
{
@@ -1571,8 +2285,7 @@ PyObject *pyrna_struct_CreatePyObject( PointerRNA *ptr )
if (ptr->data==NULL && ptr->type==NULL) { /* Operator RNA has NULL data */
Py_RETURN_NONE;
}
if (ptr->type == &RNA_Struct) { /* always return a python subtype from rna struct types */
else {
PyTypeObject *tp = (PyTypeObject *)pyrna_struct_Subtype(ptr);
if (tp) {
@@ -1580,13 +2293,11 @@ PyObject *pyrna_struct_CreatePyObject( PointerRNA *ptr )
}
else {
fprintf(stderr, "Could not make type\n");
pyrna = ( BPy_StructRNA * ) bpy_PyObject_New( BPy_StructRNA, &pyrna_struct_Type );
pyrna = ( BPy_StructRNA * ) PyObject_NEW( BPy_StructRNA, &pyrna_struct_Type );
Py_INCREF(pyrna);
}
}
else {
pyrna = ( BPy_StructRNA * ) bpy_PyObject_New( BPy_StructRNA, &pyrna_struct_Type );
}
if( !pyrna ) {
PyErr_SetString( PyExc_MemoryError, "couldn't create BPy_StructRNA object" );
return NULL;
@@ -1594,6 +2305,9 @@ PyObject *pyrna_struct_CreatePyObject( PointerRNA *ptr )
pyrna->ptr= *ptr;
pyrna->freeptr= 0;
// PyObSpit("NewStructRNA: ", (PyObject *)pyrna);
return ( PyObject * ) pyrna;
}
@@ -1601,7 +2315,8 @@ PyObject *pyrna_prop_CreatePyObject( PointerRNA *ptr, PropertyRNA *prop )
{
BPy_PropertyRNA *pyrna;
pyrna = ( BPy_PropertyRNA * ) bpy_PyObject_New( BPy_PropertyRNA, &pyrna_prop_Type );
pyrna = ( BPy_PropertyRNA * ) PyObject_NEW( BPy_PropertyRNA, &pyrna_prop_Type );
Py_INCREF(pyrna);
if( !pyrna ) {
PyErr_SetString( PyExc_MemoryError, "couldn't create BPy_rna object" );
@@ -1618,6 +2333,11 @@ PyObject *BPY_rna_module( void )
{
PointerRNA ptr;
#ifdef USE_MATHUTILS // register mathutils callbacks, ok to run more then once.
mathutils_rna_array_cb_index= Mathutils_RegisterCallback(&mathutils_rna_array_cb);
mathutils_rna_matrix_cb_index= Mathutils_RegisterCallback(&mathutils_rna_matrix_cb);
#endif
/* This can't be set in the pytype struct because some compilers complain */
pyrna_prop_Type.tp_getattro = PyObject_GenericGetAttr;
pyrna_prop_Type.tp_setattro = PyObject_GenericSetAttr;
@@ -1664,12 +2384,12 @@ static PyObject *pyrna_basetype_getattro( BPy_BaseTypeRNA * self, PyObject *pyna
if (RNA_property_collection_lookup_string(&self->ptr, self->prop, _PyUnicode_AsString(pyname), &newptr)) {
ret= pyrna_struct_Subtype(&newptr);
if (ret==NULL) {
PyErr_Format(PyExc_SystemError, "bpy.types.%s subtype could not be generated, this is a bug!", _PyUnicode_AsString(pyname));
PyErr_Format(PyExc_SystemError, "bpy.types.%.200s subtype could not be generated, this is a bug!", _PyUnicode_AsString(pyname));
}
return ret;
}
else { /* Override the error */
PyErr_Format(PyExc_AttributeError, "bpy.types.%s not a valid RNA_Struct", _PyUnicode_AsString(pyname));
PyErr_Format(PyExc_AttributeError, "bpy.types.%.200s not a valid RNA_Struct", _PyUnicode_AsString(pyname));
return NULL;
}
}
@@ -1710,14 +2430,14 @@ PyObject *BPY_rna_types(void)
pyrna_basetype_Type.tp_getattro = ( getattrofunc )pyrna_basetype_getattro;
pyrna_basetype_Type.tp_flags = Py_TPFLAGS_DEFAULT;
pyrna_basetype_Type.tp_methods = pyrna_basetype_methods;
//pyrna_basetype_Type.tp_free = MEM_freeN;
if( PyType_Ready( &pyrna_basetype_Type ) < 0 )
return NULL;
}
self= (BPy_BaseTypeRNA *)bpy_PyObject_New( BPy_BaseTypeRNA, &pyrna_basetype_Type );
self= (BPy_BaseTypeRNA *)PyObject_NEW( BPy_BaseTypeRNA, &pyrna_basetype_Type );
Py_INCREF(self);
/* avoid doing this lookup for every getattr */
RNA_blender_rna_pointer_create(&self->ptr);
self->prop = RNA_struct_find_property(&self->ptr, "structs");
@@ -1725,7 +2445,44 @@ PyObject *BPY_rna_types(void)
return (PyObject *)self;
}
static struct PyMethodDef props_methods[] = {
{"FloatProperty", (PyCFunction)BPy_FloatProperty, METH_VARARGS|METH_KEYWORDS, ""},
{"IntProperty", (PyCFunction)BPy_IntProperty, METH_VARARGS|METH_KEYWORDS, ""},
{"BoolProperty", (PyCFunction)BPy_BoolProperty, METH_VARARGS|METH_KEYWORDS, ""},
{"StringProperty", (PyCFunction)BPy_StringProperty, METH_VARARGS|METH_KEYWORDS, ""},
{NULL, NULL, 0, NULL}
};
#if PY_VERSION_HEX >= 0x03000000
static struct PyModuleDef props_module = {
PyModuleDef_HEAD_INIT,
"bpyprops",
"",
-1,/* multiple "initialization" just copies the module dict. */
props_methods,
NULL, NULL, NULL, NULL
};
#endif
PyObject *BPY_rna_props( void )
{
PyObject *submodule, *mod;
#if PY_VERSION_HEX >= 0x03000000
submodule= PyModule_Create(&props_module);
#else /* Py2.x */
submodule= Py_InitModule3( "bpy.props", props_methods, "" );
#endif
mod = PyModule_New("props");
PyModule_AddObject( submodule, "props", mod );
/* INCREF since its its assumed that all these functions return the
* module with a new ref like PyDict_New, since they are passed to
* PyModule_AddObject which steals a ref */
Py_INCREF(submodule);
return submodule;
}
/* Orphan functions, not sure where they should go */
@@ -1745,7 +2502,7 @@ PyObject *BPy_FloatProperty(PyObject *self, PyObject *args, PyObject *kw)
return NULL;
}
if (self) {
if (self && PyCObject_Check(self)) {
StructRNA *srna = PyCObject_AsVoidPtr(self);
RNA_def_float(srna, id, def, min, max, name, description, soft_min, soft_max);
Py_RETURN_NONE;
@@ -1772,7 +2529,7 @@ PyObject *BPy_IntProperty(PyObject *self, PyObject *args, PyObject *kw)
return NULL;
}
if (self) {
if (self && PyCObject_Check(self)) {
StructRNA *srna = PyCObject_AsVoidPtr(self);
RNA_def_int(srna, id, def, min, max, name, description, soft_min, soft_max);
Py_RETURN_NONE;
@@ -1791,7 +2548,7 @@ PyObject *BPy_BoolProperty(PyObject *self, PyObject *args, PyObject *kw)
char *id, *name="", *description="";
int def=0;
if (!PyArg_ParseTupleAndKeywords(args, kw, "s|ssi:IntProperty", kwlist, &id, &name, &description, &def))
if (!PyArg_ParseTupleAndKeywords(args, kw, "s|ssi:BoolProperty", kwlist, &id, &name, &description, &def))
return NULL;
if (PyTuple_Size(args) > 0) {
@@ -1799,13 +2556,40 @@ PyObject *BPy_BoolProperty(PyObject *self, PyObject *args, PyObject *kw)
return NULL;
}
if (self) {
if (self && PyCObject_Check(self)) {
StructRNA *srna = PyCObject_AsVoidPtr(self);
RNA_def_boolean(srna, id, def, name, description);
Py_RETURN_NONE;
} else {
PyObject *ret = PyTuple_New(2);
PyTuple_SET_ITEM(ret, 0, PyCObject_FromVoidPtr((void *)BPy_IntProperty, NULL));
PyTuple_SET_ITEM(ret, 0, PyCObject_FromVoidPtr((void *)BPy_BoolProperty, NULL));
PyTuple_SET_ITEM(ret, 1, kw);
Py_INCREF(kw);
return ret;
}
}
PyObject *BPy_StringProperty(PyObject *self, PyObject *args, PyObject *kw)
{
static char *kwlist[] = {"attr", "name", "description", "maxlen", "default", NULL};
char *id, *name="", *description="", *def="";
int maxlen=0;
if (!PyArg_ParseTupleAndKeywords(args, kw, "s|ssis:StringProperty", kwlist, &id, &name, &description, &maxlen, &def))
return NULL;
if (PyTuple_Size(args) > 0) {
PyErr_SetString(PyExc_ValueError, "all args must be keywors"); // TODO - py3 can enforce this.
return NULL;
}
if (self && PyCObject_Check(self)) {
StructRNA *srna = PyCObject_AsVoidPtr(self);
RNA_def_string(srna, id, def, maxlen, name, description);
Py_RETURN_NONE;
} else {
PyObject *ret = PyTuple_New(2);
PyTuple_SET_ITEM(ret, 0, PyCObject_FromVoidPtr((void *)BPy_StringProperty, NULL));
PyTuple_SET_ITEM(ret, 1, kw);
Py_INCREF(kw);
return ret;
@@ -1848,7 +2632,7 @@ static int bpy_class_validate(PointerRNA *dummyptr, void *py_data, int *have_fun
if (base_class) {
if (!PyObject_IsSubclass(py_class, base_class)) {
PyObject *name= PyObject_GetAttrString(base_class, "__name__");
PyErr_Format( PyExc_AttributeError, "expected %s subclass of class \"%s\"", class_type, name ? _PyUnicode_AsString(name):"<UNKNOWN>");
PyErr_Format( PyExc_AttributeError, "expected %.200s subclass of class \"%.200s\"", class_type, name ? _PyUnicode_AsString(name):"<UNKNOWN>");
Py_XDECREF(name);
return -1;
}
@@ -1871,7 +2655,7 @@ static int bpy_class_validate(PointerRNA *dummyptr, void *py_data, int *have_fun
if (item==NULL) {
if ((flag & FUNC_REGISTER_OPTIONAL)==0) {
PyErr_Format( PyExc_AttributeError, "expected %s class to have an \"%s\" attribute", class_type, RNA_function_identifier(func));
PyErr_Format( PyExc_AttributeError, "expected %.200s class to have an \"%.200s\" attribute", class_type, RNA_function_identifier(func));
return -1;
}
@@ -1886,7 +2670,7 @@ static int bpy_class_validate(PointerRNA *dummyptr, void *py_data, int *have_fun
fitem= item; /* py 3.x */
if (PyFunction_Check(fitem)==0) {
PyErr_Format( PyExc_AttributeError, "expected %s class \"%s\" attribute to be a function", class_type, RNA_function_identifier(func));
PyErr_Format( PyExc_AttributeError, "expected %.200s class \"%.200s\" attribute to be a function", class_type, RNA_function_identifier(func));
return -1;
}
@@ -1898,7 +2682,7 @@ static int bpy_class_validate(PointerRNA *dummyptr, void *py_data, int *have_fun
Py_DECREF(py_arg_count);
if (arg_count != func_arg_count) {
PyErr_Format( PyExc_AttributeError, "expected %s class \"%s\" function to have %d args", class_type, RNA_function_identifier(func), func_arg_count);
PyErr_Format( PyExc_AttributeError, "expected %.200s class \"%.200s\" function to have %d args", class_type, RNA_function_identifier(func), func_arg_count);
return -1;
}
}
@@ -1930,7 +2714,7 @@ static int bpy_class_validate(PointerRNA *dummyptr, void *py_data, int *have_fun
}
if (item==NULL && (flag & PROP_REGISTER_OPTIONAL)==0) {
PyErr_Format( PyExc_AttributeError, "expected %s class to have an \"%s\" attribute", class_type, identifier);
PyErr_Format( PyExc_AttributeError, "expected %.200s class to have an \"%.200s\" attribute", class_type, identifier);
return -1;
}
@@ -2014,12 +2798,12 @@ static int bpy_class_call(PointerRNA *ptr, FunctionRNA *func, ParameterList *par
}
else {
Py_DECREF(py_class_instance);
PyErr_Format(PyExc_AttributeError, "could not find function %s in %s to execute callback.", RNA_function_identifier(func), RNA_struct_identifier(ptr->type));
PyErr_Format(PyExc_AttributeError, "could not find function %.200s in %.200s to execute callback.", RNA_function_identifier(func), RNA_struct_identifier(ptr->type));
err= -1;
}
}
else {
PyErr_Format(PyExc_AttributeError, "could not create instance of %s to call callback function %s.", RNA_struct_identifier(ptr->type), RNA_function_identifier(func));
PyErr_Format(PyExc_AttributeError, "could not create instance of %.200s to call callback function %.200s.", RNA_struct_identifier(ptr->type), RNA_function_identifier(func));
err= -1;
}
@@ -2094,7 +2878,7 @@ PyObject *pyrna_basetype_register(PyObject *self, PyObject *args)
C= BPy_GetContext();
/* call the register callback */
BKE_reports_init(&reports, RPT_PRINT);
BKE_reports_init(&reports, RPT_STORE);
srna= reg(C, &reports, py_class, bpy_class_validate, bpy_class_call, bpy_class_free);
if(!srna) {

View File

@@ -1,5 +1,5 @@
/**
* $Id$
* $Id: bpy_rna.h 21094 2009-06-23 00:09:26Z gsrb3d $
*
* ***** BEGIN GPL LICENSE BLOCK *****
*
@@ -63,6 +63,7 @@ typedef struct {
PyObject *BPY_rna_module( void );
/*PyObject *BPY_rna_doc( void );*/
PyObject *BPY_rna_types( void );
PyObject *BPY_rna_props( void );
PyObject *pyrna_struct_CreatePyObject( PointerRNA *ptr );
PyObject *pyrna_prop_CreatePyObject( PointerRNA *ptr, PropertyRNA *prop );
@@ -76,6 +77,7 @@ PyObject * pyrna_prop_to_py(PointerRNA *ptr, PropertyRNA *prop);
PyObject *BPy_FloatProperty(PyObject *self, PyObject *args, PyObject *kw);
PyObject *BPy_IntProperty(PyObject *self, PyObject *args, PyObject *kw);
PyObject *BPy_BoolProperty(PyObject *self, PyObject *args, PyObject *kw);
PyObject *BPy_StringProperty(PyObject *self, PyObject *args, PyObject *kw);
/* function for registering types */
PyObject *pyrna_basetype_register(PyObject *self, PyObject *args);

View File

@@ -1,5 +1,5 @@
/**
* $Id$
* $Id: bpy_ui.c 21611 2009-07-16 00:50:27Z campbellbarton $
*
* ***** BEGIN GPL LICENSE BLOCK *****
*
@@ -373,7 +373,7 @@ static struct PyMethodDef ui_methods[] = {
#if PY_VERSION_HEX >= 0x03000000
static struct PyModuleDef ui_module = {
PyModuleDef_HEAD_INIT,
"bpyui",
"bpy.ui",
"",
-1,/* multiple "initialization" just copies the module dict. */
ui_methods,
@@ -557,6 +557,7 @@ PyObject *BPY_ui_module( void )
PyModule_AddObject( mod, "SCRIPT", PyLong_FromSsize_t(SPACE_SCRIPT) );
PyModule_AddObject( mod, "TIME", PyLong_FromSsize_t(SPACE_TIME) );
PyModule_AddObject( mod, "NODE", PyLong_FromSsize_t(SPACE_NODE) );
//PyModule_AddObject( mod, "CONSOLE", PyLong_FromSsize_t(SPACE_CONSOLE) );
/* INCREF since its its assumed that all these functions return the
* module with a new ref like PyDict_New, since they are passed to

View File

@@ -1,5 +1,5 @@
/**
* $Id$
* $Id: bpy_ui.h 21094 2009-06-23 00:09:26Z gsrb3d $
*
* ***** BEGIN GPL LICENSE BLOCK *****
*

View File

@@ -1,5 +1,5 @@
/**
* $Id$
* $Id: bpy_util.c 21526 2009-07-11 13:57:56Z campbellbarton $
*
* ***** BEGIN GPL LICENSE BLOCK *****
*
@@ -81,6 +81,7 @@ int BPY_flag_from_seq(BPY_flag_def *flagdef, PyObject *seq, int *flag)
char *cstring;
PyObject *item;
BPY_flag_def *fd;
*flag = 0;
if (PySequence_Check(seq)) {
i= PySequence_Length(seq);
@@ -108,6 +109,9 @@ int BPY_flag_from_seq(BPY_flag_def *flagdef, PyObject *seq, int *flag)
error_val= 1;
}
if (*flag == 0)
error_val = 1;
if (error_val) {
char *buf = bpy_flag_error_str(flagdef);
PyErr_SetString(PyExc_AttributeError, buf);
@@ -167,7 +171,13 @@ void PyObSpit(char *name, PyObject *var) {
else {
PyObject_Print(var, stderr, 0);
fprintf(stderr, " ref:%d ", var->ob_refcnt);
fprintf(stderr, " ptr:%ld", (long)var);
fprintf(stderr, " ptr:%p", (void *)var);
fprintf(stderr, " type:");
if(Py_TYPE(var))
fprintf(stderr, "%s", Py_TYPE(var)->tp_name);
else
fprintf(stderr, "<NIL>");
}
fprintf(stderr, "\n");
}
@@ -329,6 +339,81 @@ int BPY_class_validate(const char *class_type, PyObject *class, PyObject *base_c
return 0;
}
/* returns the exception string as a new PyUnicode object, depends on external StringIO module */
PyObject *BPY_exception_buffer(void)
{
PyObject *stdout_backup = PySys_GetObject("stdout"); /* borrowed */
PyObject *stderr_backup = PySys_GetObject("stderr"); /* borrowed */
PyObject *string_io = NULL;
PyObject *string_io_buf = NULL;
PyObject *string_io_mod= NULL;
PyObject *string_io_getvalue= NULL;
PyObject *error_type, *error_value, *error_traceback;
if (!PyErr_Occurred())
return NULL;
PyErr_Fetch(&error_type, &error_value, &error_traceback);
PyErr_Clear();
/* import StringIO / io
* string_io = StringIO.StringIO()
*/
#if PY_VERSION_HEX < 0x03000000
if(! (string_io_mod= PyImport_ImportModule("StringIO")) ) {
#else
if(! (string_io_mod= PyImport_ImportModule("io")) ) {
#endif
goto error_cleanup;
} else if (! (string_io = PyObject_CallMethod(string_io_mod, "StringIO", NULL))) {
goto error_cleanup;
} else if (! (string_io_getvalue= PyObject_GetAttrString(string_io, "getvalue"))) {
goto error_cleanup;
}
Py_INCREF(stdout_backup); // since these were borrowed we dont want them freed when replaced.
Py_INCREF(stderr_backup);
PySys_SetObject("stdout", string_io); // both of these are free'd when restoring
PySys_SetObject("stderr", string_io);
PyErr_Restore(error_type, error_value, error_traceback);
PyErr_Print(); /* print the error */
PyErr_Clear();
string_io_buf = PyObject_CallObject(string_io_getvalue, NULL);
PySys_SetObject("stdout", stdout_backup);
PySys_SetObject("stderr", stderr_backup);
Py_DECREF(stdout_backup); /* now sys owns the ref again */
Py_DECREF(stderr_backup);
Py_DECREF(string_io_mod);
Py_DECREF(string_io_getvalue);
Py_DECREF(string_io); /* free the original reference */
PyErr_Clear();
return string_io_buf;
error_cleanup:
/* could not import the module so print the error and close */
Py_XDECREF(string_io_mod);
Py_XDECREF(string_io);
PyErr_Restore(error_type, error_value, error_traceback);
PyErr_Print(); /* print the error */
PyErr_Clear();
return NULL;
}
char *BPy_enum_as_string(EnumPropertyItem *item)
{
DynStr *dynstr= BLI_dynstr_new();
@@ -336,7 +421,8 @@ char *BPy_enum_as_string(EnumPropertyItem *item)
char *cstring;
for (e= item; item->identifier; item++) {
BLI_dynstr_appendf(dynstr, (e==item)?"'%s'":", '%s'", item->identifier);
if(item->identifier[0])
BLI_dynstr_appendf(dynstr, (e==item)?"'%s'":", '%s'", item->identifier);
}
cstring = BLI_dynstr_get_cstring(dynstr);
@@ -358,3 +444,33 @@ int BPy_reports_to_error(ReportList *reports)
return (report_str != NULL);
}
int BPy_errors_to_report(ReportList *reports)
{
PyObject *pystring;
char *cstring;
if (!PyErr_Occurred())
return 1;
/* less hassle if we allow NULL */
if(reports==NULL) {
PyErr_Print();
PyErr_Clear();
return 1;
}
pystring= BPY_exception_buffer();
if(pystring==NULL) {
BKE_report(reports, RPT_ERROR, "unknown py-exception, could not convert");
return 0;
}
cstring= _PyUnicode_AsString(pystring);
BKE_report(reports, RPT_ERROR, cstring);
fprintf(stderr, "%s\n", cstring); // not exactly needed. just for testing
Py_DECREF(pystring);
return 1;
}

View File

@@ -1,5 +1,5 @@
/**
* $Id$
* $Id: bpy_util.h 21094 2009-06-23 00:09:26Z gsrb3d $
*
* ***** BEGIN GPL LICENSE BLOCK *****
*
@@ -47,6 +47,8 @@ void PyObSpit(char *name, PyObject *var);
void PyLineSpit(void);
void BPY_getFileAndNum(char **filename, int *lineno);
PyObject *BPY_exception_buffer(void);
/* own python like utility function */
PyObject *PyObject_GetAttrStringArgs(PyObject *o, Py_ssize_t n, ...);
@@ -73,6 +75,7 @@ char *BPy_enum_as_string(struct EnumPropertyItem *item);
/* error reporting */
int BPy_reports_to_error(struct ReportList *reports);
int BPy_errors_to_report(struct ReportList *reports);
/* TODO - find a better solution! */
struct bContext *BPy_GetContext(void);