merge with 2.5 at r20307. note there were some python hacking necassary for this to work, so um hopefully there's not too much cruft from that.

[[Split portion of a mixed commit.]]
This commit is contained in:
Joseph Eagar
2009-05-23 03:24:15 +00:00
parent b7fe3258b6
commit f026266e18
1037 changed files with 66726 additions and 65353 deletions

View File

@@ -99,7 +99,9 @@ extern "C" {
/* 2.5 UI Scripts */
int BPY_run_python_script( struct bContext *C, const char *filename, struct Text *text ); // 2.5 working
int BPY_run_script_space_draw(struct bContext *C, struct SpaceScript * sc); // 2.5 working
void BPY_run_ui_scripts(struct bContext *C, int reload);
// int BPY_run_script_space_listener(struct bContext *C, struct SpaceScript * sc, struct ARegion *ar, struct wmNotifier *wmn); // 2.5 working
void BPY_update_modules( void ); // XXX - annoying, need this for pointers that get out of date
@@ -124,7 +126,6 @@ extern "C" {
void BPY_pydriver_update(void);
float BPY_pydriver_eval(struct ChannelDriver *driver);
struct Object **BPY_pydriver_get_objects(struct ChannelDriver *driver);
int BPY_button_eval(char *expr, double *value);
@@ -139,7 +140,8 @@ extern "C" {
void BPY_scripts_clear_pyobjects( void );
void error_pyscript( void );
void BPY_DECREF(void *pyob_ptr); /* Py_DECREF() */
/* void BPY_Err_Handle(struct Text *text); */
/* void BPY_clear_bad_scriptlink(struct ID *id, struct Text *byebye); */
/* void BPY_clear_bad_scriptlist(struct ListBase *, struct Text *byebye); */

View File

@@ -47,8 +47,3 @@ ENDIF(WITH_FFMPEG)
ADD_DEFINITIONS(-DWITH_CCGSUBSURF)
BLENDERLIB(bf_python "${SRC}" "${INC}")
IF(WITH_INTERNATIONAL)
ADD_DEFINITIONS(-DWITH_FREETYPE2)
ENDIF(WITH_INTERNATIONAL)

View File

@@ -14,3 +14,4 @@ if env['OURPLATFORM'] in ('win32-mingw', 'win32-vc') and env['BF_DEBUG']:
defs.append('Py_TRACE_REFS')
env.BlenderLib( libname = 'bf_python', sources = Split(sources), includes = Split(incs), defines = defs, libtype = ['core'], priority = [140])

View File

@@ -18,13 +18,23 @@
#
# #**** END GPL LICENSE BLOCK #****
# Usage,
# run this script from blenders root path once you have compiled blender
# ./blender.bin -b -P source/blender/python/epy_doc_gen.py
#
# This will generate rna.py, generate html docs by running...
# epydoc source/blender/python/doc/rna.py -o source/blender/python/doc/html -v --no-sourcecode --name="RNA API" --url="http://brechtvanlommelfanclub.com" --graph=classtree
#
script_help_msg = '''
Usage,
run this script from blenders root path once you have compiled blender
./blender.bin -P source/blender/python/epy_doc_gen.py
This will generate rna.py and bpyoperator.py in "./source/blender/python/doc/"
Generate html docs by running...
epydoc source/blender/python/doc/*.py -v \\
-o source/blender/python/doc/html \\
--inheritance=included \\
--no-sourcecode \\
--graph=classtree \\
--graph-font-size=8
'''
# if you dont have graphvis installed ommit the --graph arg.
def range_str(val):
@@ -49,6 +59,125 @@ def full_rna_struct_path(rna_struct):
else:
return rna_struct.identifier
def write_func(rna, ident, out, func_type):
# Keyword attributes
kw_args = [] # "foo = 1", "bar=0.5", "spam='ENUM'"
kw_arg_attrs = [] # "@type mode: int"
rna_struct= rna.rna_type
# Operators and functions work differently
if func_type=='OPERATOR':
rna_func_name = rna_struct.identifier
rna_func_desc = rna_struct.description
items = rna_struct.properties.items()
else:
rna_func_name = rna.identifier
rna_func_desc = rna.description
items = rna.parameters.items()
for rna_prop_identifier, rna_prop in items:
if rna_prop_identifier=='rna_type':
continue
# clear vars
val = val_error = val_str = rna_prop_type = None
# ['rna_type', 'name', 'array_length', 'description', 'hard_max', 'hard_min', 'identifier', 'precision', 'readonly', 'soft_max', 'soft_min', 'step', 'subtype', 'type']
#rna_prop= op_rna.rna_type.properties[attr]
rna_prop_type = rna_prop.type.lower() # enum, float, int, boolean
try: length = rna_prop.array_length
except: length = 0
array_str = get_array_str(length)
kw_type_str= "@type %s: %s%s" % (rna_prop_identifier, rna_prop_type, array_str)
kw_param_str= "@param %s: %s" % (rna_prop_identifier, rna_prop.description)
kw_param_set = False
if func_type=='OPERATOR':
try:
val = getattr(rna, rna_prop_identifier)
val_error = False
except:
val = "'<UNDEFINED>'"
val_error = True
if val_error:
val_str = val
elif rna_prop_type=='float':
if length==0:
val_str= '%g' % val
if '.' not in val_str:
val_str += '.0'
else:
# array
val_str = str(tuple(val))
kw_param_str += (' in (%s, %s)' % (range_str(rna_prop.hard_min), range_str(rna_prop.hard_max)))
kw_param_set= True
elif rna_prop_type=='int':
if length==0:
val_str='%d' % val
else:
val_str = str(tuple(val))
# print(dir(rna_prop))
kw_param_str += (' in (%s, %s)' % (range_str(rna_prop.hard_min), range_str(rna_prop.hard_max)))
# These strings dont have a max length???
#kw_param_str += ' (maximum length of %s)' % (rna_prop.max_length)
kw_param_set= True
elif rna_prop_type=='boolean':
if length==0:
if val: val_str='True'
else: val_str='False'
else:
val_str = str(tuple(val))
elif rna_prop_type=='enum':
# no array here?
val_str="'%s'" % val
# Too cramped
kw_param_str += (' in (%s)' % ', '.join(rna_prop.items.keys()))
kw_param_set= True
elif rna_prop_type=='string':
# no array here?
val_str='"%s"' % val
# todo - collection - array
# print (rna_prop.type)
kw_args.append('%s = %s' % (rna_prop_identifier, val_str))
# stora
else:
# currently functions dont have a default value
kw_args.append('%s' % (rna_prop_identifier))
# Same for operators and functions
kw_arg_attrs.append(kw_type_str)
if kw_param_set:
kw_arg_attrs.append(kw_param_str)
out.write(ident+'def %s(%s):\n' % (rna_func_name, ', '.join(kw_args)))
out.write(ident+'\t"""\n')
out.write(ident+'\t%s\n' % rna_func_desc)
for desc in kw_arg_attrs:
out.write(ident+'\t%s\n' % desc)
out.write(ident+'\t@rtype: None\n')
out.write(ident+'\t"""\n')
def rna2epy(target_path):
@@ -57,8 +186,12 @@ def rna2epy(target_path):
rna_full_path_dict = {} # store the result of full_rna_struct_path(rna_struct)
rna_children_dict = {} # store all rna_structs nested from here
rna_references_dict = {} # store a list of rna path strings that reference this type
rna_functions_dict = {} # store all functions directly in this type (not inherited)
rna_words = set()
# def write_func(rna_func, ident):
def write_struct(rna_struct, ident):
identifier = rna_struct.identifier
@@ -132,7 +265,13 @@ def rna2epy(target_path):
out.write(ident+ '\t@type %s: %sL{%s}%s%s\n' % (rna_prop_identifier, collection_str, rna_prop_ptr.identifier, array_str, readonly_str))
else:
if rna_prop_type == 'enum':
out.write(ident+ '\t@ivar %s: %s in (%s)\n' % (rna_prop_identifier, rna_desc, ', '.join(rna_prop.items.keys())))
if 0:
out.write(ident+ '\t@ivar %s: %s in (%s)\n' % (rna_prop_identifier, rna_desc, ', '.join(rna_prop.items.keys())))
else:
out.write(ident+ '\t@ivar %s: %s in...\n' % (rna_prop_identifier, rna_desc))
for e in rna_prop.items.keys():
out.write(ident+ '\t\t- %s\n' % e)
out.write(ident+ '\t@type %s: %s%s%s\n' % (rna_prop_identifier, rna_prop_type, array_str, readonly_str))
elif rna_prop_type == 'int' or rna_prop_type == 'float':
out.write(ident+ '\t@ivar %s: %s\n' % (rna_prop_identifier, rna_desc))
@@ -147,6 +286,14 @@ def rna2epy(target_path):
out.write(ident+ '\t"""\n\n')
# Write functions
# for rna_func in rna_struct.functions: # Better ignore inherited (line below)
for rna_func in rna_functions_dict[identifier]:
write_func(rna_func, ident+'\t', out, 'FUNCTION')
out.write('\n')
# Now write children recursively
for child in rna_children_dict[identifier]:
write_struct(child, ident + '\t')
@@ -177,14 +324,24 @@ def rna2epy(target_path):
# Store full rna path 'GameObjectSettings' -> 'Object.GameObjectSettings'
rna_full_path_dict[identifier] = full_rna_struct_path(rna_struct)
# Store a list of functions, remove inherited later
rna_functions_dict[identifier]= list(rna_struct.functions)
# fill in these later
rna_children_dict[identifier]= []
rna_references_dict[identifier]= []
else:
print("Ignoring", rna_type_name)
# Sucks but we need to copy this so we can check original parent functions
rna_functions_dict__copy = {}
for key, val in rna_functions_dict.items():
rna_functions_dict__copy[key] = val[:]
structs.sort() # not needed but speeds up sort below, setting items without an inheritance first
@@ -244,6 +401,17 @@ def rna2epy(target_path):
nested = rna_struct.nested
if nested:
rna_children_dict[nested.identifier].append(rna_struct)
if rna_base:
rna_funcs = rna_functions_dict[identifier]
if rna_funcs:
# Remove inherited functions if we have any
rna_base_funcs = rna_functions_dict__copy[rna_base]
rna_funcs[:] = [f for f in rna_funcs if f not in rna_base_funcs]
rna_functions_dict__copy.clear()
del rna_functions_dict__copy
# Sort the refs, just reads nicer
for rna_refs in rna_references_dict.values():
@@ -316,8 +484,7 @@ def rna2epy(target_path):
ref = rna_ref_string.split('.')[-2]
out.write('\t"%s" -> "%s" [label="%s" weight=0.01];\n' % (ref, identifier, rna_ref_string))
out.write('}\n')
out.close()
@@ -332,9 +499,6 @@ def rna2epy(target_path):
for w in rna_words:
out.write('%s\n' % w)
def op2epy(target_path):
out = open(target_path, 'w')
@@ -349,108 +513,22 @@ def op2epy(target_path):
if op.startswith('__'):
continue
# Keyword attributes
kw_args = [] # "foo = 1", "bar=0.5", "spam='ENUM'"
kw_arg_attrs = [] # "@type mode: int"
# rna = getattr(bpy.types, op).__rna__
rna = bpy.ops.__rna__(op)
rna_struct = rna.rna_type
# print (dir(rna))
# print (dir(rna_struct))
for rna_prop_identifier, rna_prop in rna_struct.properties.items():
if rna_prop_identifier=='rna_type':
continue
# ['rna_type', 'name', 'array_length', 'description', 'hard_max', 'hard_min', 'identifier', 'precision', 'readonly', 'soft_max', 'soft_min', 'step', 'subtype', 'type']
#rna_prop= op_rna.rna_type.properties[attr]
rna_prop_type = rna_prop.type.lower() # enum, float, int, boolean
try: length = rna_prop.array_length
except: length = 0
array_str = get_array_str(length)
try:
val = getattr(rna, rna_prop_identifier)
val_error = False
except:
val = "'<UNDEFINED>'"
val_error = True
kw_type_str= "@type %s: %s%s" % (rna_prop_identifier, rna_prop_type, array_str)
kw_param_str= "@param %s: %s" % (rna_prop_identifier, rna_prop.description)
kw_param_set = False
if val_error:
val_str = val
elif rna_prop_type=='float':
if length==0:
val_str= '%g' % val
if '.' not in val_str:
val_str += '.0'
else:
# array
val_str = str(tuple(val))
kw_param_str += (' in (%s, %s)' % (range_str(rna_prop.hard_min), range_str(rna_prop.hard_max)))
kw_param_set= True
elif rna_prop_type=='int':
if length==0:
val_str='%d' % val
else:
val_str = str(tuple(val))
# print(dir(rna_prop))
kw_param_str += (' in (%s, %s)' % (range_str(rna_prop.hard_min), range_str(rna_prop.hard_max)))
# These strings dont have a max length???
#kw_param_str += ' (maximum length of %s)' % (rna_prop.max_length)
kw_param_set= True
elif rna_prop_type=='boolean':
if length==0:
if val: val_str='True'
else: val_str='False'
else:
val_str = str(tuple(val))
elif rna_prop_type=='enum':
# no array here?
val_str="'%s'" % val
kw_param_str += (' in (%s)' % ', '.join(rna_prop.items.keys()))
kw_param_set= True
elif rna_prop_type=='string':
# no array here?
val_str='"%s"' % val
# todo - collection - array
# print (rna_prop.type)
kw_args.append('%s = %s' % (rna_prop_identifier, val_str))
# stora
kw_arg_attrs.append(kw_type_str)
if kw_param_set:
kw_arg_attrs.append(kw_param_str)
out.write('def %s(%s):\n' % (op, ', '.join(kw_args)))
out.write('\t"""\n')
out.write('\t%s\n' % rna_struct.description)
for desc in kw_arg_attrs:
out.write('\t%s\n' % desc)
out.write('\t@rtype: None\n')
out.write('\t"""\n')
write_func(rna, '', out, 'OPERATOR')
out.write('\n')
out.close()
if __name__ == '__main__':
rna2epy('source/blender/python/doc/rna.py')
op2epy('source/blender/python/doc/bpyoperator.py')
if 'bpy' not in dir():
print("\nError, this script must run from inside blender2.5")
print(script_help_msg)
else:
rna2epy('source/blender/python/doc/rna.py')
op2epy('source/blender/python/doc/bpyoperator.py')
import sys
sys.exit()

View File

@@ -42,7 +42,6 @@ CPPFLAGS += -I$(NAN_PYTHON)/include/python$(NAN_PYTHON_VERSION)
# PreProcessor stuff
CPPFLAGS += -I$(NAN_GHOST)/include
CPPFLAGS += -I$(NAN_BMFONT)/include
CPPFLAGS += -I$(NAN_SOUNDSYSTEM)/include $(NAN_SDLCFLAGS)
# modules

View File

@@ -75,6 +75,7 @@
/* older then python 2.5 - define these */
#if (PY_VERSION_HEX < 0x02050000)
#define Py_ssize_t ssize_t
typedef Py_ssize_t (*lenfunc)(PyObject *);
#ifndef Py_RETURN_NONE
#define Py_RETURN_NONE return Py_BuildValue("O", Py_None)
#endif

View File

@@ -1,25 +1,40 @@
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/stat.h>
#ifndef WIN32
#include <dirent.h>
#else
#include "BLI_winstuff.h"
#endif
#include <Python.h>
#include "compile.h" /* for the PyCodeObject */
#include "eval.h" /* for PyEval_EvalCode */
#include "BKE_context.h"
#include "bpy_compat.h"
#include "bpy_rna.h"
#include "bpy_operator.h"
#include "bpy_ui.h"
#include "DNA_anim_types.h"
#include "DNA_space_types.h"
#include "BKE_text.h"
#include "DNA_text_types.h"
#include "MEM_guardedalloc.h"
#include "BLI_util.h"
#include "BLI_string.h"
#include "BKE_context.h"
#include "BKE_fcurve.h"
#include "BKE_text.h"
#include "BPY_extern.h"
void BPY_free_compiled_text( struct Text *text )
{
if( text->compiled ) {
@@ -28,10 +43,43 @@ void BPY_free_compiled_text( struct Text *text )
}
}
/*****************************************************************************
* Description: Creates the bpy module and adds it to sys.modules for importing
*****************************************************************************/
static void bpy_init_modules( void )
{
PyObject *mod;
mod = PyModule_New("bpy");
PyModule_AddObject( mod, "data", BPY_rna_module() );
/* PyModule_AddObject( mod, "doc", BPY_rna_doc() ); */
PyModule_AddObject( mod, "types", BPY_rna_types() );
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
/* add the module so we can import it */
PyDict_SetItemString(PySys_GetObject("modules"), "bpy", mod);
Py_DECREF(mod);
}
#if (PY_VERSION_HEX < 0x02050000)
PyObject *PyImport_ImportModuleLevel(char *name, void *a, void *b, void *c, int d)
{
return PyImport_ImportModule(name);
}
#endif
void BPY_update_modules( void )
{
PyObject *mod= PyImport_ImportModuleLevel("bpy", NULL, NULL, NULL, 0);
PyModule_AddObject( mod, "data", BPY_rna_module() );
PyModule_AddObject( mod, "types", BPY_rna_types() );
}
/*****************************************************************************
* Description: This function creates a new Python dictionary object.
*****************************************************************************/
static PyObject *CreateGlobalDictionary( bContext *C )
{
PyObject *mod;
@@ -41,23 +89,11 @@ static PyObject *CreateGlobalDictionary( bContext *C )
PyDict_SetItemString( dict, "__name__", item );
Py_DECREF(item);
/* add bpy to global namespace */
mod = PyModule_New("bpy");
PyDict_SetItemString( dict, "bpy", mod );
Py_DECREF(mod);
PyModule_AddObject( mod, "data", BPY_rna_module() );
/* PyModule_AddObject( mod, "doc", BPY_rna_doc() ); */
PyModule_AddObject( mod, "types", BPY_rna_types() );
PyModule_AddObject( mod, "ops", BPY_operator_module(C) );
PyModule_AddObject( mod, "ui", BPY_ui_module() ); // XXX very experemental, consider this a test, especially PyCObject is not meant to be perminant
// XXX - evil, need to access context
item = PyCObject_FromVoidPtr( C, NULL );
PyDict_SetItemString( dict, "__bpy_context__", item );
Py_DECREF(item);
// XXX - put somewhere more logical
{
PyMethodDef *ml;
@@ -73,13 +109,18 @@ static PyObject *CreateGlobalDictionary( bContext *C )
}
}
/* add bpy to global namespace */
mod= PyImport_ImportModuleLevel("bpy", NULL, NULL, NULL, 0);
PyDict_SetItemString( dict, "bpy", mod );
Py_DECREF(mod);
return dict;
}
void BPY_start_python( void )
void BPY_start_python( int argc, char **argv )
{
PyThreadState *py_tstate = NULL;
Py_Initialize( );
//PySys_SetArgv( argc_copy, argv_copy );
@@ -87,7 +128,10 @@ void BPY_start_python( void )
/* Initialize thread support (also acquires lock) */
PyEval_InitThreads();
// todo - sys paths - our own imports
/* bpy.* and lets us import it */
bpy_init_modules();
py_tstate = PyGILState_GetThisThreadState();
PyEval_ReleaseThread(py_tstate);
@@ -120,6 +164,8 @@ 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 */
py_dict = CreateGlobalDictionary(C);
if (text) {
@@ -133,7 +179,7 @@ int BPY_run_python_script( bContext *C, const char *fn, struct Text *text )
MEM_freeN( buf );
if( PyErr_Occurred( ) ) {
PyErr_Print();
PyErr_Print(); PyErr_Clear();
BPY_free_compiled_text( text );
PyGILState_Release(gilstate);
return 0;
@@ -149,10 +195,12 @@ int BPY_run_python_script( bContext *C, const char *fn, struct Text *text )
}
if (!py_result) {
PyErr_Print();
PyErr_Print(); PyErr_Clear();
} else {
Py_DECREF( py_result );
}
Py_DECREF(py_dict);
PyGILState_Release(gilstate);
//BPY_end_python();
@@ -174,7 +222,7 @@ static void exit_pydraw( SpaceScript * sc, short err )
script = sc->script;
if( err ) {
PyErr_Print( );
PyErr_Print(); PyErr_Clear();
script->flags = 0; /* mark script struct for deletion */
SCRIPT_SET_NULL(script);
script->scriptname[0] = '\0';
@@ -211,7 +259,7 @@ static int bpy_run_script_init(bContext *C, SpaceScript * sc)
return 1;
}
int BPY_run_script_space_draw(bContext *C, SpaceScript * sc)
int BPY_run_script_space_draw(struct bContext *C, SpaceScript * sc)
{
if (bpy_run_script_init(C, sc)) {
PyGILState_STATE gilstate = PyGILState_Ensure();
@@ -241,6 +289,11 @@ int BPY_run_script_space_listener(bContext *C, SpaceScript * sc)
return 1;
}
void BPY_DECREF(void *pyob_ptr)
{
Py_DECREF((PyObject *)pyob_ptr);
}
#if 0
/* called from the the scripts window, assume context is ok */
int BPY_run_python_script_space(const char *modulename, const char *func)
@@ -276,15 +329,295 @@ int BPY_run_python_script_space(const char *modulename, const char *func)
}
}
if (!py_result)
PyErr_Print();
else
if (!py_result) {
PyErr_Print(); PyErr_Clear();
} else
Py_DECREF( py_result );
Py_XDECREF(module);
Py_DECREF(py_dict);
PyGILState_Release(gilstate);
return 1;
}
#endif
// #define TIME_REGISTRATION
#ifdef TIME_REGISTRATION
#include "PIL_time.h"
#endif
/* XXX this is temporary, need a proper script registration system for 2.5 */
void BPY_run_ui_scripts(bContext *C, int reload)
{
#ifdef TIME_REGISTRATION
double time = PIL_check_seconds_timer();
#endif
DIR *dir;
struct dirent *de;
char *file_extension;
char path[FILE_MAX];
char *dirname= BLI_gethome_folder("ui");
int filelen; /* filename length */
PyGILState_STATE gilstate;
PyObject *mod;
PyObject *sys_path_orig;
PyObject *sys_path_new;
if(!dirname)
return;
dir = opendir(dirname);
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);
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') {
filelen = strlen(de->d_name);
BLI_strncpy(path, de->d_name, filelen-2); /* 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);
}
}
}
closedir(dir);
PySys_SetObject("path", sys_path_orig);
Py_DECREF(sys_path_orig);
PyGILState_Release(gilstate);
#ifdef TIME_REGISTRATION
printf("script time %f\n", (PIL_check_seconds_timer()-time));
#endif
}
/* ****************************************** */
/* Drivers - PyExpression Evaluation */
/* for pydrivers (drivers using one-line Python expressions to express relationships between targets) */
PyObject *bpy_pydriver_Dict = NULL;
/* For faster execution we keep a special dictionary for pydrivers, with
* the needed modules and aliases.
*/
static int bpy_pydriver_create_dict(void)
{
PyObject *d, *mod;
/* validate namespace for driver evaluation */
if (bpy_pydriver_Dict) return -1;
d = PyDict_New();
if (d == NULL)
return -1;
else
bpy_pydriver_Dict = d;
/* import some modules: builtins, bpy, math, (Blender.noise )*/
PyDict_SetItemString(d, "__builtins__", PyEval_GetBuiltins());
mod = PyImport_ImportModule("math");
if (mod) {
PyDict_Merge(d, PyModule_GetDict(mod), 0); /* 0 - dont overwrite existing values */
/* Only keep for backwards compat! - just import all math into root, they are standard */
PyDict_SetItemString(d, "math", mod);
PyDict_SetItemString(d, "m", mod);
Py_DECREF(mod);
}
/* add bpy to global namespace */
mod= PyImport_ImportModuleLevel("bpy", NULL, NULL, NULL, 0);
if (mod) {
PyDict_SetItemString(bpy_pydriver_Dict, "bpy", mod);
Py_DECREF(mod);
}
#if 0 // non existant yet
mod = PyImport_ImportModule("Blender.Noise");
if (mod) {
PyDict_SetItemString(d, "noise", mod);
PyDict_SetItemString(d, "n", mod);
Py_DECREF(mod);
} else {
PyErr_Clear();
}
/* If there's a Blender text called pydrivers.py, import it.
* Users can add their own functions to this module.
*/
if (G.f & G_DOSCRIPTLINKS) {
mod = importText("pydrivers"); /* can also use PyImport_Import() */
if (mod) {
PyDict_SetItemString(d, "pydrivers", mod);
PyDict_SetItemString(d, "p", mod);
Py_DECREF(mod);
} else {
PyErr_Clear();
}
}
#endif // non existant yet
return 0;
}
/* Update function, it gets rid of pydrivers global dictionary, forcing
* BPY_pydriver_eval to recreate it. This function is used to force
* reloading the Blender text module "pydrivers.py", if available, so
* updates in it reach pydriver evaluation.
*/
void BPY_pydriver_update(void)
{
PyGILState_STATE gilstate = PyGILState_Ensure();
if (bpy_pydriver_Dict) { /* free the global dict used by pydrivers */
PyDict_Clear(bpy_pydriver_Dict);
Py_DECREF(bpy_pydriver_Dict);
bpy_pydriver_Dict = NULL;
}
PyGILState_Release(gilstate);
return;
}
/* error return function for BPY_eval_pydriver */
static float pydriver_error(ChannelDriver *driver)
{
if (bpy_pydriver_Dict) { /* free the global dict used by pydrivers */
PyDict_Clear(bpy_pydriver_Dict);
Py_DECREF(bpy_pydriver_Dict);
bpy_pydriver_Dict = NULL;
}
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();
return 0.0f;
}
/* This evals py driver expressions, 'expr' is a Python expression that
* should evaluate to a float number, which is returned.
*/
float BPY_pydriver_eval (ChannelDriver *driver)
{
PyObject *driver_vars=NULL;
PyObject *retval;
PyGILState_STATE gilstate;
DriverTarget *dtar;
float result = 0.0f; /* default return */
char *expr = NULL;
short targets_ok= 1;
/* sanity checks - should driver be executed? */
if ((driver == NULL) /*|| (G.f & G_DOSCRIPTLINKS)==0*/)
return result;
/* get the py expression to be evaluated */
expr = driver->expression;
if ((expr == NULL) || (expr[0]=='\0'))
return result;
gilstate = PyGILState_Ensure();
/* init global dictionary for py-driver evaluation settings */
if (!bpy_pydriver_Dict) {
if (bpy_pydriver_create_dict() != 0) {
fprintf(stderr, "Pydriver error: couldn't create Python dictionary");
PyGILState_Release(gilstate);
return result;
}
}
/* add target values to a dict that will be used as '__locals__' dict */
driver_vars = PyDict_New(); // XXX do we need to decref this?
for (dtar= driver->targets.first; dtar; dtar= dtar->next) {
PyObject *driver_arg = NULL;
float tval = 0.0f;
/* try to get variable value */
tval= driver_get_target_value(driver, dtar);
driver_arg= PyFloat_FromDouble((double)tval);
/* try to add to dictionary */
if (PyDict_SetItemString(driver_vars, dtar->name, driver_arg)) {
/* this target failed - bad name */
if (targets_ok) {
/* first one - print some extra info for easier identification */
fprintf(stderr, "\nBPY_pydriver_eval() - Error while evaluating PyDriver:\n");
targets_ok= 0;
}
fprintf(stderr, "\tBPY_pydriver_eval() - couldn't add variable '%s' to namespace \n", dtar->name);
PyErr_Print(); PyErr_Clear();
}
}
/* execute expression to get a value */
retval = PyRun_String(expr, Py_eval_input, bpy_pydriver_Dict, driver_vars);
/* decref the driver vars first... */
Py_DECREF(driver_vars);
/* process the result */
if (retval == NULL) {
result = pydriver_error(driver);
PyGILState_Release(gilstate);
return result;
}
result = (float)PyFloat_AsDouble(retval);
Py_DECREF(retval);
if ((result == -1) && PyErr_Occurred()) {
result = pydriver_error(driver);
PyGILState_Release(gilstate);
return result;
}
/* all fine, make sure the "invalid expression" flag is cleared */
driver->flag &= ~DRIVER_FLAG_INVALID;
PyGILState_Release(gilstate);
return result;
}

View File

@@ -24,9 +24,10 @@
*/
#include "bpy_operator.h"
#include "bpy_opwrapper.h"
#include "bpy_operator_wrap.h"
#include "bpy_rna.h" /* for setting arg props only - pyrna_py_to_prop() */
#include "bpy_compat.h"
#include "bpy_util.h"
//#include "blendef.h"
#include "BLI_dynstr.h"
@@ -54,7 +55,7 @@ int PYOP_props_from_dict(PointerRNA *ptr, PyObject *kw)
PropertyRNA *prop, *iterprop;
CollectionPropertyIterator iter;
iterprop= RNA_struct_iterator_property(ptr);
iterprop= RNA_struct_iterator_property(ptr->type);
RNA_property_collection_begin(ptr, iterprop, &iter);
totkw = kw ? PyDict_Size(kw):0;
@@ -62,7 +63,7 @@ int PYOP_props_from_dict(PointerRNA *ptr, PyObject *kw)
for(; iter.valid; RNA_property_collection_next(&iter)) {
prop= iter.ptr.data;
arg_name= RNA_property_identifier(&iter.ptr, prop);
arg_name= RNA_property_identifier(prop);
if (strcmp(arg_name, "rna_type")==0) continue;
@@ -80,7 +81,7 @@ int PYOP_props_from_dict(PointerRNA *ptr, PyObject *kw)
break;
}
if (pyrna_py_to_prop(ptr, prop, item)) {
if (pyrna_py_to_prop(ptr, prop, NULL, item)) {
error_val= -1;
break;
}
@@ -128,7 +129,6 @@ static PyObject *pyop_base_call( PyObject * self, PyObject * args, PyObject * k
bContext *C = (bContext *)PyCObject_AsVoidPtr(PyDict_GetItemString(PyEval_GetGlobals(), "__bpy_context__"));
char *opname = _PyUnicode_AsString(self);
char *report_str= NULL;
if (PyTuple_Size(args)) {
PyErr_SetString( PyExc_AttributeError, "All operator args must be keywords");
@@ -157,16 +157,10 @@ static PyObject *pyop_base_call( PyObject * self, PyObject * args, PyObject * k
WM_operator_call_py(C, ot, &ptr, &reports);
report_str= BKE_reports_string(&reports, RPT_ERROR);
if (report_str) {
PyErr_SetString(PyExc_SystemError, report_str);
MEM_freeN(report_str);
if(BPy_reports_to_error(&reports))
error_val = -1;
}
if (reports.list.first)
BKE_reports_clear(&reports);
BKE_reports_clear(&reports);
}
WM_operator_properties_free(&ptr);
@@ -262,7 +256,7 @@ static PyObject *pyop_base_rna(PyObject *self, PyObject *pyname)
PyTypeObject pyop_base_Type = {NULL};
PyObject *BPY_operator_module( bContext *C )
PyObject *BPY_operator_module( void )
{
pyop_base_Type.tp_name = "OperatorBase";
pyop_base_Type.tp_basicsize = sizeof( BPy_OperatorBase );

View File

@@ -40,7 +40,7 @@ typedef struct {
PyObject_HEAD /* required python macro */
} BPy_OperatorBase;
PyObject *BPY_operator_module(bContext *C );
PyObject *BPY_operator_module(void);
/* fill in properties from a python dict */
int PYOP_props_from_dict(PointerRNA *ptr, PyObject *kw);

View File

@@ -24,7 +24,7 @@
*/
#include "bpy_opwrapper.h"
#include "bpy_operator_wrap.h"
#include "BLI_listbase.h"
#include "BKE_context.h"
#include "BKE_report.h"
@@ -45,14 +45,6 @@
#define PYOP_ATTR_IDNAME "__name__" /* use pythons class name */
#define PYOP_ATTR_DESCRIPTION "__doc__" /* use pythons docstring */
typedef struct PyOperatorType {
void *next, *prev;
char idname[OP_MAX_TYPENAME];
char name[OP_MAX_TYPENAME];
char description[OP_MAX_TYPENAME]; // XXX should be longer?
PyObject *py_class;
} PyOperatorType;
static PyObject *pyop_dict_from_event(wmEvent *event)
{
PyObject *dict= PyDict_New();
@@ -189,16 +181,22 @@ static struct BPY_flag_def pyop_ret_flags[] = {
#define PYOP_INVOKE 2
#define PYOP_POLL 3
extern void BPY_update_modules( void ); //XXX temp solution
static int PYTHON_OT_generic(int mode, bContext *C, wmOperator *op, wmEvent *event)
{
PyOperatorType *pyot = op->type->pyop_data;
PyObject *py_class = op->type->pyop_data;
PyObject *args;
PyObject *ret= NULL, *py_class_instance, *item;
PyObject *ret= NULL, *py_class_instance, *item= NULL;
int ret_flag= (mode==PYOP_POLL ? 0:OPERATOR_CANCELLED);
PyGILState_STATE gilstate = PyGILState_Ensure();
BPY_update_modules(); // XXX - the RNA pointers can change so update before running, would like a nicer solutuon for this.
args = PyTuple_New(1);
PyTuple_SET_ITEM(args, 0, PyObject_GetAttrString(pyot->py_class, "__rna__")); // need to use an rna instance as the first arg
py_class_instance = PyObject_Call(pyot->py_class, args, NULL);
PyTuple_SET_ITEM(args, 0, PyObject_GetAttrString(py_class, "__rna__")); // need to use an rna instance as the first arg
py_class_instance = PyObject_Call(py_class, args, NULL);
Py_DECREF(args);
if (py_class_instance) { /* Initializing the class worked, now run its invoke function */
@@ -210,12 +208,12 @@ static int PYTHON_OT_generic(int mode, bContext *C, wmOperator *op, wmEvent *eve
CollectionPropertyIterator iter;
const char *arg_name;
iterprop= RNA_struct_iterator_property(op->ptr);
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;
arg_name= RNA_property_identifier(&iter.ptr, prop);
arg_name= RNA_property_identifier(prop);
if (strcmp(arg_name, "rna_type")==0) continue;
@@ -229,16 +227,16 @@ static int PYTHON_OT_generic(int mode, bContext *C, wmOperator *op, wmEvent *eve
if (mode==PYOP_INVOKE) {
item= PyObject_GetAttrString(pyot->py_class, "invoke");
item= PyObject_GetAttrString(py_class, "invoke");
args = PyTuple_New(2);
PyTuple_SET_ITEM(args, 1, pyop_dict_from_event(event));
}
else if (mode==PYOP_EXEC) {
item= PyObject_GetAttrString(pyot->py_class, "exec");
item= PyObject_GetAttrString(py_class, "exec");
args = PyTuple_New(1);
}
else if (mode==PYOP_POLL) {
item= PyObject_GetAttrString(pyot->py_class, "poll");
item= PyObject_GetAttrString(py_class, "poll");
args = PyTuple_New(2);
//XXX Todo - wrap context in a useful way, None for now.
PyTuple_SET_ITEM(args, 1, Py_None);
@@ -251,7 +249,7 @@ static int PYTHON_OT_generic(int mode, bContext *C, wmOperator *op, wmEvent *eve
Py_DECREF(item);
}
if (ret == NULL) {
if (ret == NULL) { /* covers py_class_instance failing too */
pyop_error_report(op->reports);
}
else {
@@ -280,6 +278,8 @@ static int PYTHON_OT_generic(int mode, bContext *C, wmOperator *op, wmEvent *eve
Py_DECREF(ret);
}
PyGILState_Release(gilstate);
return ret_flag;
}
@@ -302,15 +302,29 @@ static int PYTHON_OT_poll(bContext *C)
void PYTHON_OT_wrapper(wmOperatorType *ot, void *userdata)
{
PyOperatorType *pyot = (PyOperatorType *)userdata;
PyObject *py_class = pyot->py_class;
PyObject *py_class = (PyObject *)userdata;
PyObject *props, *item;
/* identifiers */
ot->name= pyot->name;
ot->idname= pyot->idname;
ot->description= pyot->description;
item= PyObject_GetAttrString(py_class, PYOP_ATTR_IDNAME);
Py_DECREF(item);
ot->idname= _PyUnicode_AsString(item);
item= PyObject_GetAttrString(py_class, PYOP_ATTR_UINAME);
if (item) {
Py_DECREF(item);
ot->name= _PyUnicode_AsString(item);
}
else {
ot->name= ot->idname;
PyErr_Clear();
}
item= PyObject_GetAttrString(py_class, PYOP_ATTR_DESCRIPTION);
Py_DECREF(item);
ot->description= (item && PyUnicode_Check(item)) ? _PyUnicode_AsString(item):"";
/* api callbacks, detailed checks dont on adding */
if (PyObject_HasAttrString(py_class, "invoke"))
ot->invoke= PYTHON_OT_invoke;
@@ -364,105 +378,48 @@ void PYTHON_OT_wrapper(wmOperatorType *ot, void *userdata)
/* pyOperators - Operators defined IN Python */
PyObject *PYOP_wrap_add(PyObject *self, PyObject *value)
PyObject *PYOP_wrap_add(PyObject *self, PyObject *py_class)
{
PyObject *optype, *item;
PyObject *base_class, *item;
PyOperatorType *pyot;
char *idname= NULL;
char *name= NULL;
char *description= NULL;
static char *pyop_func_names[] = {"exec", "invoke", "poll", NULL};
static int pyop_func_nargs[] = {1, 2, 2, 0};
PyObject *pyargcount;
int i, argcount;
int i;
static struct BPY_class_attr_check pyop_class_attr_values[]= {
{PYOP_ATTR_IDNAME, 's', 0, 0},
{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', 1, BPY_CLASS_ATTR_OPTIONAL},
{"invoke", 'f', 2, BPY_CLASS_ATTR_OPTIONAL},
{"poll", 'f', 2, BPY_CLASS_ATTR_OPTIONAL},
{NULL, 0, 0, 0}
};
// in python would be...
//PyObject *optype = PyObject_GetAttrString(PyObject_GetAttrString(PyDict_GetItemString(PyEval_GetGlobals(), "bpy"), "types"), "Operator");
optype = PyObject_GetAttrStringArgs(PyDict_GetItemString(PyEval_GetGlobals(), "bpy"), 2, "types", "Operator");
Py_DECREF(optype);
base_class = PyObject_GetAttrStringArgs(PyDict_GetItemString(PyEval_GetGlobals(), "bpy"), 2, "types", "Operator");
Py_DECREF(base_class);
if (!PyObject_IsSubclass(value, optype)) {
PyErr_SetString( PyExc_AttributeError, "expected Operator subclass of bpy.types.Operator");
return NULL;
if(BPY_class_validate("Operator", py_class, base_class, pyop_class_attr_values, NULL) < 0) {
return NULL; /* BPY_class_validate sets the error */
}
/* class name is used for operator ID - this can be changed later if we want */
item = PyObject_GetAttrString(value, PYOP_ATTR_IDNAME);
item= PyObject_GetAttrString(py_class, PYOP_ATTR_IDNAME);
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;
}
/* Operator user readible name */
item = PyObject_GetAttrString(value, PYOP_ATTR_UINAME);
if (item) {
Py_DECREF(item);
name = _PyUnicode_AsString(item);
}
if (name == NULL) {
name = idname;
PyErr_Clear();
}
/* use py docstring for description, should always be None or a string */
item = PyObject_GetAttrString(value, PYOP_ATTR_DESCRIPTION);
Py_DECREF(item);
if (PyUnicode_Check(item)) {
description = _PyUnicode_AsString(item);
}
else {
description = "";
}
/* Check known functions and argument lengths */
for (i=0; pyop_func_names[i]; i++) {
item=PyObject_GetAttrString(value, pyop_func_names[i]);
if (item) {
Py_DECREF(item);
/* check its callable */
if (!PyFunction_Check(item)) {
PyErr_Format(PyExc_ValueError, "Cant register operator class - %s.%s() is not a function", idname, pyop_func_names[i]);
return NULL;
}
/* check the number of args is correct */
/* MyClass.exec.func_code.co_argcount */
pyargcount = PyObject_GetAttrString(PyFunction_GET_CODE(item), "co_argcount");
Py_DECREF(pyargcount);
argcount = PyLong_AsSsize_t(pyargcount);
if (argcount != pyop_func_nargs[i]) {
PyErr_Format(PyExc_ValueError, "Cant register operator class - %s.%s() takes %d args, should be %d", idname, pyop_func_names[i], argcount, pyop_func_nargs[i]);
return NULL;
}
} else {
PyErr_Clear();
}
}
/* If we have properties set, check its a list of dicts */
item = PyObject_GetAttrString(value, PYOP_ATTR_PROP);
item= PyObject_GetAttrString(py_class, PYOP_ATTR_PROP);
if (item) {
Py_DECREF(item);
if (!PyList_Check(item)) {
PyErr_Format(PyExc_ValueError, "Cant register operator class - %s.properties must be a list", idname);
return NULL;
}
for(i=0; i<PyList_Size(item); i++) {
PyObject *py_args = PyList_GET_ITEM(item, i);
PyObject *py_func_ptr, *py_kw; /* place holders */
@@ -477,24 +434,18 @@ PyObject *PYOP_wrap_add(PyObject *self, PyObject *value)
PyErr_Clear();
}
pyot= MEM_callocN(sizeof(PyOperatorType), "PyOperatorType");
strncpy(pyot->idname, idname, sizeof(pyot->idname));
strncpy(pyot->name, name, sizeof(pyot->name));
strncpy(pyot->description, description, sizeof(pyot->description));
pyot->py_class= value;
Py_INCREF(value);
WM_operatortype_append_ptr(PYTHON_OT_wrapper, pyot);
Py_INCREF(py_class);
WM_operatortype_append_ptr(PYTHON_OT_wrapper, py_class);
Py_RETURN_NONE;
}
PyObject *PYOP_wrap_remove(PyObject *self, PyObject *value)
{
PyObject *py_class;
char *idname= NULL;
wmOperatorType *ot;
PyOperatorType *pyot;
if (PyUnicode_Check(value))
idname = _PyUnicode_AsString(value);
@@ -514,13 +465,12 @@ PyObject *PYOP_wrap_remove(PyObject *self, PyObject *value)
return NULL;
}
if (!(pyot= (PyOperatorType *)ot->pyop_data)) {
if (!(py_class= (PyObject *)ot->pyop_data)) {
PyErr_Format( PyExc_AttributeError, "Operator \"%s\" was not created by python", idname);
return NULL;
}
Py_XDECREF(pyot->py_class);
MEM_freeN(pyot);
Py_XDECREF(py_class);
WM_operatortype_remove(idname);

View File

@@ -22,8 +22,8 @@
*
* ***** END GPL LICENSE BLOCK *****
*/
#ifndef BPY_OPWRAPPER_H
#define BPY_OPWRAPPER_H
#ifndef BPY_OPERATOR_WRAP_H
#define BPY_OPERATOR_WRAP_H
#include <Python.h>

View File

@@ -24,16 +24,28 @@
#include "bpy_rna.h"
#include "bpy_compat.h"
#include "bpy_util.h"
//#include "blendef.h"
#include "BLI_dynstr.h"
#include "BLI_listbase.h"
#include "BLI_string.h"
#include "float.h" /* FLT_MIN/MAX */
#include "RNA_access.h"
#include "RNA_define.h" /* for defining our own rna */
#include "MEM_guardedalloc.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)
#endif
static int pyrna_struct_compare( BPy_StructRNA * a, BPy_StructRNA * b )
{
@@ -45,7 +57,6 @@ static int pyrna_prop_compare( BPy_PropertyRNA * a, BPy_PropertyRNA * b )
return (a->prop==b->prop && a->ptr.data==b->ptr.data ) ? 0 : -1;
}
/* For some reason python3 needs these :/ */
static PyObject *pyrna_struct_richcmp(BPy_StructRNA * a, BPy_StructRNA * b, int op)
{
@@ -74,13 +85,13 @@ static PyObject *pyrna_struct_repr( BPy_StructRNA * self )
char str[512];
/* print name if available */
prop= RNA_struct_name_property(&self->ptr);
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), str);
return PyUnicode_FromFormat( "[BPy_StructRNA \"%s\" -> \"%s\"]", RNA_struct_identifier(self->ptr.type), str);
}
return PyUnicode_FromFormat( "[BPy_StructRNA \"%s\"]", RNA_struct_identifier(&self->ptr));
return PyUnicode_FromFormat( "[BPy_StructRNA \"%s\"]", RNA_struct_identifier(self->ptr.type));
}
static PyObject *pyrna_prop_repr( BPy_PropertyRNA * self )
@@ -90,19 +101,19 @@ static PyObject *pyrna_prop_repr( BPy_PropertyRNA * self )
char str[512];
/* if a pointer, try to print name of pointer target too */
if(RNA_property_type(&self->ptr, self->prop) == PROP_POINTER) {
if(RNA_property_type(self->prop) == PROP_POINTER) {
ptr= RNA_property_pointer_get(&self->ptr, self->prop);
if(ptr.data) {
prop= RNA_struct_name_property(&ptr);
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), RNA_property_identifier(&self->ptr, self->prop), str);
return PyUnicode_FromFormat( "[BPy_PropertyRNA \"%s\" -> \"%s\" -> \"%s\" ]", RNA_struct_identifier(self->ptr.type), RNA_property_identifier(self->prop), str);
}
}
}
return PyUnicode_FromFormat( "[BPy_PropertyRNA \"%s\" -> \"%s\"]", RNA_struct_identifier(&self->ptr), RNA_property_identifier(&self->ptr, self->prop));
return PyUnicode_FromFormat( "[BPy_PropertyRNA \"%s\" -> \"%s\"]", RNA_struct_identifier(self->ptr.type), RNA_property_identifier(self->prop));
}
static long pyrna_struct_hash( BPy_StructRNA * self )
@@ -127,28 +138,17 @@ static void pyrna_struct_dealloc( BPy_StructRNA * self )
static char *pyrna_enum_as_string(PointerRNA *ptr, PropertyRNA *prop)
{
const EnumPropertyItem *item;
int totitem, i;
DynStr *dynstr= BLI_dynstr_new();
char *cstring;
RNA_property_enum_items(ptr, prop, &item, &totitem);
for (i=0; i<totitem; i++) {
BLI_dynstr_appendf(dynstr, i?", '%s'":"'%s'", item[i].identifier);
}
int totitem;
cstring = BLI_dynstr_get_cstring(dynstr);
BLI_dynstr_free(dynstr);
return cstring;
RNA_property_enum_items(ptr, prop, &item, &totitem);
return (char*)BPy_enum_as_string((EnumPropertyItem*)item);
}
PyObject * pyrna_prop_to_py(PointerRNA *ptr, PropertyRNA *prop)
{
PyObject *ret;
int type = RNA_property_type(ptr, prop);
int len = RNA_property_array_length(ptr, prop);
int type = RNA_property_type(prop);
int len = RNA_property_array_length(prop);
if (len > 0) {
/* resolve the array from a new pytype */
@@ -212,11 +212,28 @@ PyObject * pyrna_prop_to_py(PointerRNA *ptr, PropertyRNA *prop)
return ret;
}
static PyObject * pyrna_func_call(PyObject * self, PyObject *args, PyObject *kw);
int pyrna_py_to_prop(PointerRNA *ptr, PropertyRNA *prop, PyObject *value)
PyObject *pyrna_func_to_py(PointerRNA *ptr, FunctionRNA *func)
{
int type = RNA_property_type(ptr, prop);
int len = RNA_property_array_length(ptr, prop);
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, 1, PyCObject_FromVoidPtr((void *)func, NULL));
ret= PyCFunction_New(&func_meth, self);
Py_DECREF(self);
return ret;
}
int pyrna_py_to_prop(PointerRNA *ptr, PropertyRNA *prop, void *data, PyObject *value)
{
/* XXX hard limits should be checked here */
int type = RNA_property_type(prop);
int len = RNA_property_array_length(prop);
if (len > 0) {
PyObject *item;
@@ -236,7 +253,10 @@ int pyrna_py_to_prop(PointerRNA *ptr, PropertyRNA *prop, PyObject *value)
switch (type) {
case PROP_BOOLEAN:
{
int *param_arr = MEM_mallocN(sizeof(char) * len, "pyrna bool array");
int *param_arr;
if(data) param_arr= (int*)data;
else param_arr= MEM_mallocN(sizeof(char) * len, "pyrna bool array");
/* collect the variables before assigning, incase one of them is incorrect */
for (i=0; i<len; i++) {
@@ -245,22 +265,27 @@ int pyrna_py_to_prop(PointerRNA *ptr, PropertyRNA *prop, PyObject *value)
Py_DECREF(item);
if (param_arr[i] < 0) {
MEM_freeN(param_arr);
if(data==NULL)
MEM_freeN(param_arr);
PyErr_SetString(PyExc_AttributeError, "one or more of the values in the sequence is not a boolean");
return -1;
}
}
RNA_property_boolean_set_array(ptr, prop, param_arr);
MEM_freeN(param_arr);
if(data==NULL) {
RNA_property_boolean_set_array(ptr, prop, param_arr);
MEM_freeN(param_arr);
}
break;
}
case PROP_INT:
{
int *param_arr = MEM_mallocN(sizeof(int) * len, "pyrna int array");
int *param_arr;
if(data) param_arr= (int*)data;
else param_arr= MEM_mallocN(sizeof(int) * len, "pyrna int array");
/* collect the variables before assigning, incase one of them is incorrect */
/* collect the variables */
for (i=0; i<len; i++) {
item = PySequence_GetItem(value, i);
param_arr[i] = (int)PyLong_AsSsize_t(item); /* deal with any errors later */
@@ -268,21 +293,26 @@ int pyrna_py_to_prop(PointerRNA *ptr, PropertyRNA *prop, PyObject *value)
}
if (PyErr_Occurred()) {
MEM_freeN(param_arr);
if(data==NULL)
MEM_freeN(param_arr);
PyErr_SetString(PyExc_AttributeError, "one or more of the values in the sequence could not be used as an int");
return -1;
}
RNA_property_int_set_array(ptr, prop, param_arr);
MEM_freeN(param_arr);
if(data==NULL) {
RNA_property_int_set_array(ptr, prop, param_arr);
MEM_freeN(param_arr);
}
break;
}
case PROP_FLOAT:
{
float *param_arr = MEM_mallocN(sizeof(float) * len, "pyrna float array");
float *param_arr;
if(data) param_arr = (float*)data;
else param_arr = MEM_mallocN(sizeof(float) * len, "pyrna float array");
/* collect the variables before assigning, incase one of them is incorrect */
/* 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 */
@@ -290,14 +320,15 @@ int pyrna_py_to_prop(PointerRNA *ptr, PropertyRNA *prop, PyObject *value)
}
if (PyErr_Occurred()) {
MEM_freeN(param_arr);
if(data==NULL)
MEM_freeN(param_arr);
PyErr_SetString(PyExc_AttributeError, "one or more of the values in the sequence could not be used as a float");
return -1;
}
RNA_property_float_set_array(ptr, prop, param_arr);
MEM_freeN(param_arr);
if(data==NULL) {
RNA_property_float_set_array(ptr, prop, param_arr);
MEM_freeN(param_arr);
}
break;
}
}
@@ -314,7 +345,8 @@ int pyrna_py_to_prop(PointerRNA *ptr, PropertyRNA *prop, PyObject *value)
PyErr_SetString(PyExc_TypeError, "expected True/False or 0/1");
return -1;
} else {
RNA_property_boolean_set(ptr, prop, param);
if(data) *((int*)data)= param;
else RNA_property_boolean_set(ptr, prop, param);
}
break;
}
@@ -325,7 +357,8 @@ int pyrna_py_to_prop(PointerRNA *ptr, PropertyRNA *prop, PyObject *value)
PyErr_SetString(PyExc_TypeError, "expected an int type");
return -1;
} else {
RNA_property_int_set(ptr, prop, param);
if(data) *((int*)data)= param;
else RNA_property_int_set(ptr, prop, param);
}
break;
}
@@ -336,7 +369,8 @@ int pyrna_py_to_prop(PointerRNA *ptr, PropertyRNA *prop, PyObject *value)
PyErr_SetString(PyExc_TypeError, "expected a float type");
return -1;
} else {
RNA_property_float_set(ptr, prop, param);
if(data) *((float*)data)= param;
else RNA_property_float_set(ptr, prop, param);
}
break;
}
@@ -348,7 +382,8 @@ int pyrna_py_to_prop(PointerRNA *ptr, PropertyRNA *prop, PyObject *value)
PyErr_SetString(PyExc_TypeError, "expected a string type");
return -1;
} else {
RNA_property_string_set(ptr, prop, param);
if(data) *((char**)data)= param;
else RNA_property_string_set(ptr, prop, param);
}
break;
}
@@ -364,7 +399,8 @@ int pyrna_py_to_prop(PointerRNA *ptr, PropertyRNA *prop, PyObject *value)
} else {
int val;
if (RNA_property_enum_value(ptr, prop, param, &val)) {
RNA_property_enum_set(ptr, prop, 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);
@@ -377,29 +413,49 @@ int pyrna_py_to_prop(PointerRNA *ptr, PropertyRNA *prop, PyObject *value)
}
case PROP_POINTER:
{
StructRNA *ptype= RNA_property_pointer_type(ptr, prop);
StructRNA *ptype= RNA_property_pointer_type(prop);
if(!BPy_StructRNA_Check(value)) {
PointerRNA tmp;
RNA_pointer_create(NULL, ptype, NULL, &tmp);
PyErr_Format(PyExc_TypeError, "expected a %s type", RNA_struct_identifier(&tmp));
PyErr_Format(PyExc_TypeError, "expected a %s type", RNA_struct_identifier(tmp.type));
return -1;
} else {
BPy_StructRNA *param= (BPy_StructRNA*)value;
if(RNA_struct_is_a(&param->ptr, ptype)) {
RNA_property_pointer_set(ptr, prop, param->ptr);
} else {
int raise_error= 0;
if(data) {
if(ptype == &RNA_AnyType) {
*((PointerRNA*)data)= param->ptr;
}
else if(RNA_struct_is_a(param->ptr.type, ptype)) {
*((void**)data)= param->ptr.data;
} else {
raise_error= 1;
}
}
else {
/* data==NULL, assign to RNA */
if(RNA_struct_is_a(param->ptr.type, ptype)) {
RNA_property_pointer_set(ptr, prop, param->ptr);
} else {
PointerRNA tmp;
RNA_pointer_create(NULL, ptype, NULL, &tmp);
PyErr_Format(PyExc_TypeError, "expected a %s type", RNA_struct_identifier(tmp.type));
return -1;
}
}
if(raise_error) {
PointerRNA tmp;
RNA_pointer_create(NULL, ptype, NULL, &tmp);
PyErr_Format(PyExc_TypeError, "expected a %s type", RNA_struct_identifier(&tmp));
PyErr_Format(PyExc_TypeError, "expected a %s type", RNA_struct_identifier(tmp.type));
return -1;
}
}
break;
}
case PROP_COLLECTION:
PyErr_SetString(PyExc_AttributeError, "cant assign to collections");
PyErr_SetString(PyExc_AttributeError, "cant convert collections yet");
return -1;
break;
default:
@@ -412,11 +468,10 @@ int pyrna_py_to_prop(PointerRNA *ptr, PropertyRNA *prop, PyObject *value)
return 0;
}
static PyObject * pyrna_prop_to_py_index(PointerRNA *ptr, PropertyRNA *prop, int index)
{
PyObject *ret;
int type = RNA_property_type(ptr, prop);
int type = RNA_property_type(prop);
/* see if we can coorce into a python type - PropertyType */
switch (type) {
@@ -441,7 +496,7 @@ static PyObject * pyrna_prop_to_py_index(PointerRNA *ptr, PropertyRNA *prop, int
static int pyrna_py_to_prop_index(PointerRNA *ptr, PropertyRNA *prop, int index, PyObject *value)
{
int ret = 0;
int type = RNA_property_type(ptr, prop);
int type = RNA_property_type(prop);
/* see if we can coorce into a python type - PropertyType */
switch (type) {
@@ -493,10 +548,10 @@ static Py_ssize_t pyrna_prop_len( BPy_PropertyRNA * self )
{
Py_ssize_t len;
if (RNA_property_type(&self->ptr, self->prop) == PROP_COLLECTION) {
if (RNA_property_type(self->prop) == PROP_COLLECTION) {
len = RNA_property_collection_length(&self->ptr, self->prop);
} else {
len = RNA_property_array_length(&self->ptr, self->prop);
len = RNA_property_array_length(self->prop);
if (len==0) { /* not an array*/
PyErr_SetString(PyExc_AttributeError, "len() only available for collection RNA types");
@@ -523,7 +578,7 @@ static PyObject *pyrna_prop_subscript( BPy_PropertyRNA * self, PyObject *key )
return NULL;
}
if (RNA_property_type(&self->ptr, self->prop) == PROP_COLLECTION) {
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);
@@ -539,7 +594,7 @@ static PyObject *pyrna_prop_subscript( BPy_PropertyRNA * self, PyObject *key )
PyErr_SetString(PyExc_AttributeError, "string keys are only supported for collections");
ret = NULL;
} else {
int len = RNA_property_array_length(&self->ptr, self->prop);
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);
@@ -565,7 +620,7 @@ static int pyrna_prop_assign_subscript( BPy_PropertyRNA * self, PyObject *key, P
char *keyname = NULL;
if (!RNA_property_editable(&self->ptr, self->prop)) {
PyErr_Format( PyExc_AttributeError, "PropertyRNA - attribute \"%s\" from \"%s\" is read-only", RNA_property_identifier(&self->ptr, self->prop), RNA_struct_identifier(&self->ptr) );
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;
}
@@ -578,14 +633,14 @@ static int pyrna_prop_assign_subscript( BPy_PropertyRNA * self, PyObject *key, P
return -1;
}
if (RNA_property_type(&self->ptr, self->prop) == PROP_COLLECTION) {
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->ptr, self->prop);
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);
@@ -606,7 +661,7 @@ static int pyrna_prop_assign_subscript( BPy_PropertyRNA * self, PyObject *key, P
static PyMappingMethods pyrna_prop_as_mapping = {
( inquiry ) pyrna_prop_len, /* mp_length */
( lenfunc ) pyrna_prop_len, /* mp_length */
( binaryfunc ) pyrna_prop_subscript, /* mp_subscript */
( objobjargproc ) pyrna_prop_assign_subscript, /* mp_ass_subscript */
};
@@ -616,6 +671,10 @@ 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
* In these instances we may want to return a function or variable provided by the subtype
* */
@@ -639,15 +698,17 @@ static PyObject *pyrna_struct_dir(BPy_StructRNA * self)
/* Collect RNA items*/
{
PropertyRNA *iterprop, *nameprop;
CollectionPropertyIterator iter;
/*
* Collect RNA attributes
*/
PropertyRNA *nameprop;
char name[256], *nameptr;
iterprop= RNA_struct_iterator_property(&self->ptr);
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))) {
if(iter.ptr.data && (nameprop = RNA_struct_name_property(iter.ptr.type))) {
nameptr= RNA_property_string_get_alloc(&iter.ptr, nameprop, name, sizeof(name));
pystring = PyUnicode_FromString(nameptr);
@@ -658,7 +719,28 @@ static PyObject *pyrna_struct_dir(BPy_StructRNA * self)
MEM_freeN(nameptr);
}
}
RNA_property_collection_end(&iter);
}
{
/*
* Collect RNA function items
*/
PointerRNA tptr;
RNA_pointer_create(NULL, &RNA_Struct, self->ptr.type, &tptr);
iterprop= RNA_struct_find_property(&tptr, "functions");
RNA_property_collection_begin(&tptr, iterprop, &iter);
for(; iter.valid; RNA_property_collection_next(&iter)) {
pystring = PyUnicode_FromString(RNA_function_identifier(iter.ptr.data));
PyList_Append(ret, pystring);
Py_DECREF(pystring);
}
RNA_property_collection_end(&iter);
}
@@ -672,6 +754,7 @@ static PyObject *pyrna_struct_getattro( BPy_StructRNA * self, PyObject *pyname )
char *name = _PyUnicode_AsString(pyname);
PyObject *ret;
PropertyRNA *prop;
FunctionRNA *func;
/* Include this incase this instance is a subtype of a python class
* In these instances we may want to return a function or variable provided by the subtype
@@ -682,13 +765,14 @@ static PyObject *pyrna_struct_getattro( BPy_StructRNA * self, PyObject *pyname )
if (ret) return ret;
else PyErr_Clear();
/* done with subtypes */
prop = RNA_struct_find_property(&self->ptr, name);
if (prop) {
ret = pyrna_prop_to_py(&self->ptr, prop);
if ((prop = RNA_struct_find_property(&self->ptr, name))) {
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);
}
else if (/*self->ptr.type == &RNA_Context*/0) {
else if (self->ptr.type == &RNA_Context) {
PointerRNA newptr;
ListBase newlb;
@@ -741,18 +825,18 @@ static int pyrna_struct_setattro( BPy_StructRNA * self, PyObject *pyname, PyObje
}
if (!RNA_property_editable(&self->ptr, prop)) {
PyErr_Format( PyExc_AttributeError, "StructRNA - Attribute \"%s\" from \"%s\" is read-only", RNA_property_identifier(&self->ptr, prop), RNA_struct_identifier(&self->ptr) );
PyErr_Format( PyExc_AttributeError, "StructRNA - Attribute \"%s\" from \"%s\" is read-only", RNA_property_identifier(prop), RNA_struct_identifier(self->ptr.type) );
return -1;
}
/* pyrna_py_to_prop sets its own exceptions */
return pyrna_py_to_prop(&self->ptr, prop, value);
return pyrna_py_to_prop(&self->ptr, prop, NULL, value);
}
PyObject *pyrna_prop_keys(BPy_PropertyRNA *self)
{
PyObject *ret;
if (RNA_property_type(&self->ptr, self->prop) != PROP_COLLECTION) {
if (RNA_property_type(self->prop) != PROP_COLLECTION) {
PyErr_SetString( PyExc_TypeError, "keys() is only valid for collection types" );
ret = NULL;
} else {
@@ -765,7 +849,7 @@ PyObject *pyrna_prop_keys(BPy_PropertyRNA *self)
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))) {
if(iter.ptr.data && (nameprop = RNA_struct_name_property(iter.ptr.type))) {
nameptr= RNA_property_string_get_alloc(&iter.ptr, nameprop, name, sizeof(name));
/* add to python list */
@@ -787,7 +871,7 @@ PyObject *pyrna_prop_keys(BPy_PropertyRNA *self)
PyObject *pyrna_prop_items(BPy_PropertyRNA *self)
{
PyObject *ret;
if (RNA_property_type(&self->ptr, self->prop) != PROP_COLLECTION) {
if (RNA_property_type(self->prop) != PROP_COLLECTION) {
PyErr_SetString( PyExc_TypeError, "items() is only valid for collection types" );
ret = NULL;
} else {
@@ -800,7 +884,7 @@ PyObject *pyrna_prop_items(BPy_PropertyRNA *self)
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))) {
if(iter.ptr.data && (nameprop = RNA_struct_name_property(iter.ptr.type))) {
nameptr= RNA_property_string_get_alloc(&iter.ptr, nameprop, name, sizeof(name));
/* add to python list */
@@ -823,7 +907,7 @@ PyObject *pyrna_prop_items(BPy_PropertyRNA *self)
PyObject *pyrna_prop_values(BPy_PropertyRNA *self)
{
PyObject *ret;
if (RNA_property_type(&self->ptr, self->prop) != PROP_COLLECTION) {
if (RNA_property_type(self->prop) != PROP_COLLECTION) {
PyErr_SetString( PyExc_TypeError, "values() is only valid for collection types" );
ret = NULL;
} else {
@@ -835,7 +919,7 @@ PyObject *pyrna_prop_values(BPy_PropertyRNA *self)
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))) {
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);
@@ -856,7 +940,7 @@ PyObject *pyrna_prop_iter(BPy_PropertyRNA *self)
if (ret==NULL) {
/* collection did not work, try array */
int len = RNA_property_array_length(&self->ptr, self->prop);
int len = RNA_property_array_length(self->prop);
if (len) {
int i;
@@ -929,6 +1013,190 @@ static PyObject * pyrna_prop_new(PyTypeObject *type, PyObject *args, PyObject *k
}
}
PyObject *pyrna_param_to_py(PointerRNA *ptr, PropertyRNA *prop, void *data)
{
PyObject *ret;
int type = RNA_property_type(prop);
int len = RNA_property_array_length(prop);
int a;
if(len > 0) {
/* resolve the array from a new pytype */
ret = PyTuple_New(len);
switch (type) {
case PROP_BOOLEAN:
for(a=0; a<len; a++)
PyTuple_SET_ITEM(ret, a, PyBool_FromLong( ((int*)data)[a] ));
break;
case PROP_INT:
for(a=0; a<len; a++)
PyTuple_SET_ITEM(ret, a, PyLong_FromSsize_t( (Py_ssize_t)((int*)data)[a] ));
break;
case PROP_FLOAT:
for(a=0; a<len; a++)
PyTuple_SET_ITEM(ret, a, PyFloat_FromDouble( ((float*)data)[a] ));
break;
default:
PyErr_Format(PyExc_AttributeError, "RNA Error: unknown array type \"%d\" (pyrna_param_to_py)", type);
ret = NULL;
break;
}
}
else {
/* see if we can coorce into a python type - PropertyType */
switch (type) {
case PROP_BOOLEAN:
ret = PyBool_FromLong( *(int*)data );
break;
case PROP_INT:
ret = PyLong_FromSsize_t( (Py_ssize_t)*(int*)data );
break;
case PROP_FLOAT:
ret = PyFloat_FromDouble( *(float*)data );
break;
case PROP_STRING:
{
ret = PyUnicode_FromString( *(char**)data );
break;
}
case PROP_ENUM:
{
const char *identifier;
int val = *(int*)data;
if (RNA_property_enum_identifier(ptr, prop, val, &identifier)) {
ret = PyUnicode_FromString( identifier );
} else {
PyErr_Format(PyExc_AttributeError, "RNA Error: Current value \"%d\" matches no enum", val);
ret = NULL;
}
break;
}
case PROP_POINTER:
{
PointerRNA newptr;
StructRNA *type= RNA_property_pointer_type(prop);
if(type == &RNA_AnyType) {
/* in this case we get the full ptr */
newptr= *(PointerRNA*)data;
}
else {
/* XXX this is missing the ID part! */
RNA_pointer_create(NULL, type, *(void**)data, &newptr);
}
if (newptr.data) {
ret = pyrna_struct_CreatePyObject(&newptr);
} else {
ret = Py_None;
Py_INCREF(ret);
}
break;
}
case PROP_COLLECTION:
/* XXX not supported yet
* ret = pyrna_prop_CreatePyObject(ptr, prop); */
ret = NULL;
break;
default:
PyErr_Format(PyExc_AttributeError, "RNA Error: unknown type \"%d\" (pyrna_param_to_py)", type);
ret = NULL;
break;
}
}
return ret;
}
static PyObject * pyrna_func_call(PyObject * self, PyObject *args, PyObject *kw)
{
PointerRNA *self_ptr= &(((BPy_StructRNA *)PyTuple_GET_ITEM(self, 0))->ptr);
FunctionRNA *self_func= PyCObject_AsVoidPtr(PyTuple_GET_ITEM(self, 1));
PointerRNA funcptr;
ParameterList *parms;
ParameterIterator iter;
PropertyRNA *pret, *parm;
PyObject *ret, *item;
int i, tlen, flag, err= 0;
const char *tid, *fid, *pid;
void *retdata= NULL;
/* setup */
RNA_pointer_create(NULL, &RNA_Function, self_func, &funcptr);
pret= RNA_function_return(self_func);
tlen= PyTuple_GET_SIZE(args);
parms= RNA_parameter_list_create(self_ptr, self_func);
RNA_parameter_list_begin(parms, &iter);
/* parse function parameters */
for (i= 0; iter.valid; RNA_parameter_list_next(&iter)) {
parm= iter.parm;
if (parm==pret) {
retdata= iter.data;
continue;
}
pid= RNA_property_identifier(parm);
flag= RNA_property_flag(parm);
item= NULL;
if ((i < tlen) && (flag & PROP_REQUIRED)) {
item= PyTuple_GET_ITEM(args, i);
i++;
}
else if (kw != NULL)
item= PyDict_GetItemString(kw, pid); /* borrow ref */
if (item==NULL) {
if(flag & PROP_REQUIRED) {
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);
err= -1;
break;
}
else
continue;
}
err= pyrna_py_to_prop(&funcptr, parm, iter.data, item);
if(err!=0)
break;
}
ret= NULL;
if (err==0) {
/* call function */
RNA_function_call(self_ptr, self_func, parms);
/* return value */
if(pret)
ret= pyrna_param_to_py(&funcptr, pret, retdata);
}
/* cleanup */
RNA_parameter_list_end(&iter);
RNA_parameter_list_free(parms);
if (ret)
return ret;
if (err==-1)
return NULL;
Py_RETURN_NONE;
}
/*-----------------------BPy_StructRNA method def------------------------------*/
PyTypeObject pyrna_struct_Type = {
#if (PY_VERSION_HEX >= 0x02060000)
@@ -1002,7 +1270,7 @@ PyTypeObject pyrna_struct_Type = {
NULL, /* allocfunc tp_alloc; */
pyrna_struct_new, /* newfunc tp_new; */
/* Low-level free-memory routine */
NULL, /* freefunc tp_free; */
NULL, //MEM_freeN, /* freefunc tp_free; */
/* For PyObject_IS_GC */
NULL, /* inquiry tp_is_gc; */
NULL, /* PyObject *tp_bases; */
@@ -1028,7 +1296,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; */
@@ -1088,7 +1356,7 @@ PyTypeObject pyrna_prop_Type = {
NULL, /* allocfunc tp_alloc; */
pyrna_prop_new, /* newfunc tp_new; */
/* Low-level free-memory routine */
NULL, /* freefunc tp_free; */
NULL, //MEM_freeN, /* freefunc tp_free; */
/* For PyObject_IS_GC */
NULL, /* inquiry tp_is_gc; */
NULL, /* PyObject *tp_bases; */
@@ -1100,6 +1368,22 @@ PyTypeObject pyrna_prop_Type = {
NULL
};
static void pyrna_subtype_set_rna(PyObject *newclass, StructRNA *srna)
{
PointerRNA ptr;
PyObject *item;
RNA_struct_py_type_set(srna, (void *)newclass); /* Store for later use */
/* Not 100% needed but useful,
* having an instance within a type looks wrong however this instance IS an rna type */
RNA_pointer_create(NULL, &RNA_Struct, srna, &ptr);
item = pyrna_struct_CreatePyObject(&ptr);
PyDict_SetItemString(((PyTypeObject *)newclass)->tp_dict, "__rna__", item);
Py_DECREF(item);
/* done with rna instance */
}
PyObject* pyrna_struct_Subtype(PointerRNA *ptr)
{
PyObject *newclass = NULL;
@@ -1107,12 +1391,12 @@ PyObject* pyrna_struct_Subtype(PointerRNA *ptr)
if (ptr->type==NULL) {
newclass= NULL; /* Nothing to do */
} else if ((newclass= (PyObject *)BPy_RNA_PYTYPE(ptr->data))) {
} else if ((newclass= RNA_struct_py_type_get(ptr->data))) {
Py_INCREF(newclass);
} else if ((nameprop = RNA_struct_name_property(ptr))) {
} else if ((nameprop = RNA_struct_name_property(ptr->type))) {
/* for now, return the base RNA type rather then a real module */
/* Assume BPy_RNA_PYTYPE(ptr->data) was alredy checked */
/* Assume RNA_struct_py_type_get(ptr->data) was alredy checked */
/* subclass equivelents
- class myClass(myBase):
@@ -1120,10 +1404,13 @@ PyObject* pyrna_struct_Subtype(PointerRNA *ptr)
- myClass = type(name='myClass', bases=(myBase,), dict={'some':'value'})
*/
char name[256], *nameptr;
const char *descr= RNA_struct_ui_description(ptr->type);
PyObject *args = PyTuple_New(3);
PyObject *bases = PyTuple_New(1);
PyObject *dict = PyDict_New();
PyObject *item;
nameptr= RNA_property_string_get_alloc(ptr, nameprop, name, sizeof(name));
@@ -1138,6 +1425,12 @@ PyObject* pyrna_struct_Subtype(PointerRNA *ptr)
PyTuple_SET_ITEM(args, 1, bases);
// arg 3 - add an instance of the rna
if(descr) {
item= PyUnicode_FromString(descr);
PyDict_SetItemString(dict, "__doc__", item);
Py_DECREF(item);
}
PyTuple_SET_ITEM(args, 2, dict); // fill with useful subclass things!
if (PyErr_Occurred()) {
@@ -1146,26 +1439,13 @@ PyObject* pyrna_struct_Subtype(PointerRNA *ptr)
}
newclass = PyObject_CallObject((PyObject *)&PyType_Type, args);
// Set this later
if (newclass) {
PyObject *rna;
BPy_RNA_PYTYPE(ptr->data) = (void *)newclass; /* Store for later use */
/* Not 100% needed but useful,
* having an instance within a type looks wrong however this instance IS an rna type */
rna = pyrna_struct_CreatePyObject(ptr);
PyDict_SetItemString(((PyTypeObject *)newclass)->tp_dict, "__rna__", rna);
Py_DECREF(rna);
/* done with rna instance */
}
Py_DECREF(args);
if (newclass)
pyrna_subtype_set_rna(newclass, ptr->data);
if ((char *)&name != nameptr)
if (name != nameptr)
MEM_freeN(nameptr);
}
return newclass;
@@ -1188,11 +1468,11 @@ PyObject *pyrna_struct_CreatePyObject( PointerRNA *ptr )
}
else {
fprintf(stderr, "Could not make type\n");
pyrna = ( BPy_StructRNA * ) PyObject_NEW( BPy_StructRNA, &pyrna_struct_Type );
pyrna = ( BPy_StructRNA * ) bpy_PyObject_New( BPy_StructRNA, &pyrna_struct_Type );
}
}
else {
pyrna = ( BPy_StructRNA * ) PyObject_NEW( BPy_StructRNA, &pyrna_struct_Type );
pyrna = ( BPy_StructRNA * ) bpy_PyObject_New( BPy_StructRNA, &pyrna_struct_Type );
}
if( !pyrna ) {
@@ -1209,7 +1489,7 @@ PyObject *pyrna_prop_CreatePyObject( PointerRNA *ptr, PropertyRNA *prop )
{
BPy_PropertyRNA *pyrna;
pyrna = ( BPy_PropertyRNA * ) PyObject_NEW( BPy_PropertyRNA, &pyrna_prop_Type );
pyrna = ( BPy_PropertyRNA * ) bpy_PyObject_New( BPy_PropertyRNA, &pyrna_prop_Type );
if( !pyrna ) {
PyErr_SetString( PyExc_MemoryError, "couldn't create BPy_rna object" );
@@ -1222,7 +1502,6 @@ PyObject *pyrna_prop_CreatePyObject( PointerRNA *ptr, PropertyRNA *prop )
return ( PyObject * ) pyrna;
}
PyObject *BPY_rna_module( void )
{
PointerRNA ptr;
@@ -1237,7 +1516,6 @@ PyObject *BPY_rna_module( void )
if( PyType_Ready( &pyrna_prop_Type ) < 0 )
return NULL;
/* for now, return the base RNA type rather then a real module */
RNA_main_pointer_create(G.main, &ptr);
@@ -1272,7 +1550,11 @@ static PyObject *pyrna_basetype_getattro( BPy_BaseTypeRNA * self, PyObject *pyna
else PyErr_Clear();
if (RNA_property_collection_lookup_string(&self->ptr, self->prop, _PyUnicode_AsString(pyname), &newptr)) {
return pyrna_struct_Subtype(&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));
}
return ret;
}
else { /* Override the error */
PyErr_Format(PyExc_AttributeError, "bpy.types.%s not a valid RNA_Struct", _PyUnicode_AsString(pyname));
@@ -1283,6 +1565,8 @@ static PyObject *pyrna_basetype_getattro( BPy_BaseTypeRNA * self, PyObject *pyna
static PyObject *pyrna_basetype_dir(BPy_BaseTypeRNA *self);
static struct PyMethodDef pyrna_basetype_methods[] = {
{"__dir__", (PyCFunction)pyrna_basetype_dir, METH_NOARGS, ""},
{"register", (PyCFunction)pyrna_basetype_register, METH_VARARGS, ""},
{"unregister", (PyCFunction)pyrna_basetype_unregister, METH_VARARGS, ""},
{NULL, NULL, 0, NULL}
};
@@ -1302,21 +1586,25 @@ static PyObject *pyrna_basetype_dir(BPy_BaseTypeRNA *self)
return list;
}
PyTypeObject pyrna_basetype_Type = {NULL};
PyTypeObject pyrna_basetype_Type = BLANK_PYTHON_TYPE;
PyObject *BPY_rna_types(void)
{
BPy_BaseTypeRNA *self;
pyrna_basetype_Type.tp_name = "RNA_Types";
pyrna_basetype_Type.tp_basicsize = sizeof( BPy_BaseTypeRNA );
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;
if ((pyrna_basetype_Type.tp_flags & Py_TPFLAGS_READY)==0) {
pyrna_basetype_Type.tp_name = "RNA_Types";
pyrna_basetype_Type.tp_basicsize = sizeof( BPy_BaseTypeRNA );
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;
}
if( PyType_Ready( &pyrna_basetype_Type ) < 0 )
return NULL;
self= (BPy_BaseTypeRNA *)PyObject_NEW( BPy_BaseTypeRNA, &pyrna_basetype_Type );
self= (BPy_BaseTypeRNA *)bpy_PyObject_New( BPy_BaseTypeRNA, &pyrna_basetype_Type );
/* avoid doing this lookup for every getattr */
RNA_blender_rna_pointer_create(&self->ptr);
@@ -1411,3 +1699,358 @@ PyObject *BPy_BoolProperty(PyObject *self, PyObject *args, PyObject *kw)
return ret;
}
}
/*-------------------- Type Registration ------------------------*/
static int rna_function_arg_count(FunctionRNA *func)
{
const ListBase *lb= RNA_function_defined_parameters(func);
PropertyRNA *parm;
Link *link;
int count= 1;
for(link=lb->first; link; link=link->next) {
parm= (PropertyRNA*)link;
if(!(RNA_property_flag(parm) & PROP_RETURN))
count++;
}
return count;
}
static int bpy_class_validate(PointerRNA *dummyptr, void *py_data, int *have_function)
{
const ListBase *lb;
Link *link;
FunctionRNA *func;
PropertyRNA *prop;
StructRNA *srna= dummyptr->type;
const char *class_type= RNA_struct_identifier(srna);
PyObject *py_class= (PyObject*)py_data;
PyObject *base_class= RNA_struct_py_type_get(srna);
PyObject *item, *fitem;
PyObject *py_arg_count;
int i, flag, arg_count, func_arg_count;
char identifier[128];
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>");
Py_XDECREF(name);
return -1;
}
}
/* verify callback functions */
lb= RNA_struct_defined_functions(srna);
i= 0;
for(link=lb->first; link; link=link->next) {
func= (FunctionRNA*)link;
flag= RNA_function_flag(func);
if(!(flag & FUNC_REGISTER))
continue;
item = PyObject_GetAttrString(py_class, RNA_function_identifier(func));
have_function[i]= (item != NULL);
i++;
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));
return -1;
}
PyErr_Clear();
}
else {
Py_DECREF(item); /* no need to keep a ref, the class owns it */
if (PyMethod_Check(item))
fitem= PyMethod_Function(item); /* py 2.x */
else
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));
return -1;
}
func_arg_count= rna_function_arg_count(func);
if (func_arg_count >= 0) { /* -1 if we dont care*/
py_arg_count = PyObject_GetAttrString(PyFunction_GET_CODE(fitem), "co_argcount");
arg_count = PyLong_AsSsize_t(py_arg_count);
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);
return -1;
}
}
}
}
/* verify properties */
lb= RNA_struct_defined_properties(srna);
for(link=lb->first; link; link=link->next) {
prop= (PropertyRNA*)link;
flag= RNA_property_flag(prop);
if(!(flag & PROP_REGISTER))
continue;
BLI_snprintf(identifier, sizeof(identifier), "__%s__", RNA_property_identifier(prop));
item = PyObject_GetAttrString(py_class, identifier);
if (item==NULL) {
if(strcmp(identifier, "__idname__") == 0) {
item= PyObject_GetAttrString(py_class, "__name__");
if(item) {
Py_DECREF(item); /* no need to keep a ref, the class owns it */
if(pyrna_py_to_prop(dummyptr, prop, NULL, item) != 0)
return -1;
}
}
if (item==NULL && (flag & PROP_REGISTER_OPTIONAL)==0) {
PyErr_Format( PyExc_AttributeError, "expected %s class to have an \"%s\" attribute", class_type, identifier);
return -1;
}
PyErr_Clear();
}
else {
Py_DECREF(item); /* no need to keep a ref, the class owns it */
if(pyrna_py_to_prop(dummyptr, prop, NULL, item) != 0)
return -1;
}
}
return 0;
}
extern void BPY_update_modules( void ); //XXX temp solution
static int bpy_class_call(PointerRNA *ptr, FunctionRNA *func, ParameterList *parms)
{
PyObject *args;
PyObject *ret= NULL, *py_class, *py_class_instance, *item, *parmitem;
PropertyRNA *pret= NULL, *parm;
ParameterIterator iter;
PointerRNA funcptr;
void *retdata= NULL;
int err= 0, i, flag;
PyGILState_STATE gilstate = PyGILState_Ensure();
BPY_update_modules(); // XXX - the RNA pointers can change so update before running, would like a nicer solution for this.
py_class= RNA_struct_py_type_get(ptr->type);
item = pyrna_struct_CreatePyObject(ptr);
if(item == NULL) {
py_class_instance = NULL;
}
else if(item == Py_None) { /* probably wont ever happen but possible */
Py_DECREF(item);
py_class_instance = NULL;
}
else {
args = PyTuple_New(1);
PyTuple_SET_ITEM(args, 0, item);
py_class_instance = PyObject_Call(py_class, args, NULL);
Py_DECREF(args);
}
if (py_class_instance) { /* Initializing the class worked, now run its invoke function */
item= PyObject_GetAttrString(py_class, RNA_function_identifier(func));
flag= RNA_function_flag(func);
if(item) {
pret= RNA_function_return(func);
RNA_pointer_create(NULL, &RNA_Function, func, &funcptr);
args = PyTuple_New(rna_function_arg_count(func));
PyTuple_SET_ITEM(args, 0, py_class_instance);
RNA_parameter_list_begin(parms, &iter);
/* parse function parameters */
for (i= 1; iter.valid; RNA_parameter_list_next(&iter)) {
parm= iter.parm;
if (parm==pret) {
retdata= iter.data;
continue;
}
parmitem= pyrna_param_to_py(&funcptr, parm, iter.data);
PyTuple_SET_ITEM(args, i, parmitem);
i++;
}
ret = PyObject_Call(item, args, NULL);
Py_DECREF(item);
Py_DECREF(args);
}
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));
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));
err= -1;
}
if (ret == NULL) { /* covers py_class_instance failing too */
PyErr_Print(); /* XXX use reporting api? */
err= -1;
}
else {
if(retdata)
err= pyrna_py_to_prop(&funcptr, pret, retdata, ret);
Py_DECREF(ret);
}
PyGILState_Release(gilstate);
return err;
}
static void bpy_class_free(void *pyob_ptr)
{
Py_DECREF((PyObject *)pyob_ptr);
}
PyObject *pyrna_basetype_register(PyObject *self, PyObject *args)
{
bContext *C= NULL;
PyObject *py_class, *item;
ReportList reports;
StructRegisterFunc reg;
BPy_StructRNA *py_srna;
StructRNA *srna;
if(!PyArg_ParseTuple(args, "O:register", &py_class))
return NULL;
if(!PyType_Check(py_class)) {
PyErr_SetString(PyExc_AttributeError, "expected a Type subclassed from a registerable rna type (no a Type object).");
return NULL;
}
/* check we got an __rna__ attribute */
item= PyObject_GetAttrString(py_class, "__rna__");
if(!item || !BPy_StructRNA_Check(item)) {
if(item) {
Py_DECREF(item);
}
PyErr_SetString(PyExc_AttributeError, "expected a Type subclassed from a registerable rna type (no __rna__ property).");
return NULL;
}
/* check the __rna__ attribute has the right type */
Py_DECREF(item);
py_srna= (BPy_StructRNA*)item;
if(py_srna->ptr.type != &RNA_Struct) {
PyErr_SetString(PyExc_AttributeError, "expected a Type subclassed from a registerable rna type (not a Struct).");
return NULL;
}
/* check that we have a register callback for this type */
reg= RNA_struct_register(py_srna->ptr.data);
if(!reg) {
PyErr_SetString(PyExc_AttributeError, "expected a Type subclassed from a registerable rna type (no register supported).");
return NULL;
}
/* get the context, so register callback can do necessary refreshes */
item= PyDict_GetItemString(PyEval_GetGlobals(), "__bpy_context__"); /* borrow ref */
if(item)
C= (bContext*)PyCObject_AsVoidPtr(item);
/* call the register callback */
BKE_reports_init(&reports, RPT_PRINT);
srna= reg(C, &reports, py_class, bpy_class_validate, bpy_class_call, bpy_class_free);
if(!srna) {
BPy_reports_to_error(&reports);
BKE_reports_clear(&reports);
return NULL;
}
BKE_reports_clear(&reports);
pyrna_subtype_set_rna(py_class, srna);
Py_INCREF(py_class);
Py_RETURN_NONE;
}
PyObject *pyrna_basetype_unregister(PyObject *self, PyObject *args)
{
bContext *C= NULL;
PyObject *py_class, *item;
BPy_StructRNA *py_srna;
StructUnregisterFunc unreg;
if(!PyArg_ParseTuple(args, "O:unregister", &py_class))
return NULL;
if(!PyType_Check(py_class)) {
PyErr_SetString(PyExc_AttributeError, "expected a Type subclassed from a registerable rna type (no a Type object).");
return NULL;
}
/* check we got an __rna__ attribute */
item= PyDict_GetItemString(((PyTypeObject*)py_class)->tp_dict, "__rna__"); /* borrow ref */
if(!item || !BPy_StructRNA_Check(item)) {
PyErr_SetString(PyExc_AttributeError, "expected a Type subclassed from a registerable rna type (no __rna__ property).");
return NULL;
}
/* check the __rna__ attribute has the right type */
py_srna= (BPy_StructRNA*)item;
if(py_srna->ptr.type != &RNA_Struct) {
PyErr_SetString(PyExc_AttributeError, "expected a Type subclassed from a registerable rna type (not a Struct).");
return NULL;
}
/* check that we have a unregister callback for this type */
unreg= RNA_struct_unregister(py_srna->ptr.data);
if(!unreg) {
PyErr_SetString(PyExc_AttributeError, "expected a Type subclassed from a registerable rna type (no unregister supported).");
return NULL;
}
/* get the context, so register callback can do necessary refreshes */
item= PyDict_GetItemString(PyEval_GetGlobals(), "__bpy_context__"); /* borrow ref */
if(item)
C= (bContext*)PyCObject_AsVoidPtr(item);
/* call unregister */
unreg(C, py_srna->ptr.data);
/* remove reference to old type */
Py_DECREF(py_class);
Py_RETURN_NONE;
}

View File

@@ -38,10 +38,6 @@ extern PyTypeObject pyrna_prop_Type;
#define BPy_PropertyRNA_Check(v) (PyObject_TypeCheck(v, &pyrna_prop_Type))
#define BPy_PropertyRNA_CheckExact(v) (Py_TYPE(v) == &pyrna_prop_Type)
//XXX add propper accessor function, we know this is just after next/prev pointers
#define BPy_RNA_PYTYPE( _data ) (((BPy_StructFakeType *)(_data))->py_type)
typedef struct {
void * _a;
void * _b;
@@ -72,7 +68,7 @@ PyObject *pyrna_struct_CreatePyObject( PointerRNA *ptr );
PyObject *pyrna_prop_CreatePyObject( PointerRNA *ptr, PropertyRNA *prop );
/* operators also need this to set args */
int pyrna_py_to_prop(PointerRNA *ptr, PropertyRNA *prop, PyObject *value);
int pyrna_py_to_prop(PointerRNA *ptr, PropertyRNA *prop, void *data, PyObject *value);
PyObject * pyrna_prop_to_py(PointerRNA *ptr, PropertyRNA *prop);
/* functions for setting up new props - experemental */
@@ -80,5 +76,8 @@ 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);
/* function for registering types */
PyObject *pyrna_basetype_register(PyObject *self, PyObject *args);
PyObject *pyrna_basetype_unregister(PyObject *self, PyObject *args);
#endif

View File

@@ -27,6 +27,7 @@
#include "bpy_rna.h" /* for rna buttons */
#include "bpy_operator.h" /* for setting button operator properties */
#include "bpy_compat.h"
#include "WM_types.h" /* for WM_OP_INVOKE_DEFAULT & friends */
#include "BLI_dynstr.h"
@@ -42,12 +43,13 @@
static PyObject *Method_pupMenuBegin( PyObject * self, PyObject * args )
{
PyObject *py_context;
char *title; int icon;
if( !PyArg_ParseTuple( args, "si:pupMenuBegin", &title, &icon))
if( !PyArg_ParseTuple( args, "O!si:pupMenuBegin", &PyCObject_Type, &py_context, &title, &icon))
return NULL;
return PyCObject_FromVoidPtr( uiPupMenuBegin(title, icon), NULL );
return PyCObject_FromVoidPtr( uiPupMenuBegin(PyCObject_AsVoidPtr(py_context), title, icon), NULL );
}
static PyObject *Method_pupMenuEnd( PyObject * self, PyObject * args )
@@ -62,20 +64,6 @@ static PyObject *Method_pupMenuEnd( PyObject * self, PyObject * args )
Py_RETURN_NONE;
}
static PyObject *Method_menuItemO( PyObject * self, PyObject * args )
{
PyObject *py_head;
char *opname;
int icon;
if( !PyArg_ParseTuple( args, "O!is:menuItemO", &PyCObject_Type, &py_head, &icon, &opname))
return NULL;
uiMenuItemO(PyCObject_AsVoidPtr(py_head), icon, opname);
Py_RETURN_NONE;
}
static PyObject *Method_defButO( PyObject * self, PyObject * args )
{
uiBut *but;
@@ -156,7 +144,9 @@ static PyObject *Method_pupBlock( PyObject * self, PyObject * args )
Py_RETURN_NONE;
}
static PyObject *Method_beginBlock( PyObject * self, PyObject * args ) // XXX missing 2 args - UI_EMBOSS, UI_HELV, do we care?
// XXX missing arg - UI_EMBOSS, do we care?
// XXX well, right now this only is to distinguish whether we have regular buttons or for pulldowns (ton)
static PyObject *Method_beginBlock( PyObject * self, PyObject * args )
{
PyObject *py_context, *py_ar;
char *name;
@@ -164,7 +154,7 @@ static PyObject *Method_beginBlock( PyObject * self, PyObject * args ) // XXX mi
if( !PyArg_ParseTuple( args, "O!O!s:beginBlock", &PyCObject_Type, &py_context, &PyCObject_Type, &py_ar, &name) )
return NULL;
return PyCObject_FromVoidPtr(uiBeginBlock(PyCObject_AsVoidPtr(py_context), PyCObject_AsVoidPtr(py_ar), name, UI_EMBOSS, UI_HELV), NULL);
return PyCObject_FromVoidPtr(uiBeginBlock(PyCObject_AsVoidPtr(py_context), PyCObject_AsVoidPtr(py_ar), name, UI_EMBOSS), NULL);
}
static PyObject *Method_endBlock( PyObject * self, PyObject * args )
@@ -189,29 +179,6 @@ static PyObject *Method_drawBlock( PyObject * self, PyObject * args )
Py_RETURN_NONE;
}
static PyObject *Method_drawPanels( PyObject * self, PyObject * args )
{
PyObject *py_context;
int align;
if( !PyArg_ParseTuple( args, "O!i:drawPanels", &PyCObject_Type, &py_context, &align) )
return NULL;
uiDrawPanels(PyCObject_AsVoidPtr(py_context), align);
Py_RETURN_NONE;
}
static PyObject *Method_matchPanelsView2d( PyObject * self, PyObject * args )
{
PyObject *py_ar;
if( !PyArg_ParseTuple( args, "O!:matchPanelsView2d", &PyCObject_Type, &py_ar) )
return NULL;
uiMatchPanelsView2d(PyCObject_AsVoidPtr(py_ar));
Py_RETURN_NONE;
}
static PyObject *Method_popupBoundsBlock( PyObject * self, PyObject * args )
{
PyObject *py_block;
@@ -258,18 +225,6 @@ static PyObject *Method_blockSetFlag( PyObject * self, PyObject * args )
Py_RETURN_NONE;
}
static PyObject *Method_newPanel( PyObject * self, PyObject * args )
{
PyObject *py_context, *py_area, *py_block;
char *panelname, *tabname;
int ofsx, ofsy, sizex, sizey;
if( !PyArg_ParseTuple( args, "O!O!O!ssiiii:newPanel", &PyCObject_Type, &py_context, &PyCObject_Type, &py_area, &PyCObject_Type, &py_block, &panelname, &tabname, &ofsx, &ofsy, &sizex, &sizey))
return NULL;
return PyLong_FromSsize_t(uiNewPanel(PyCObject_AsVoidPtr(py_context), PyCObject_AsVoidPtr(py_area), PyCObject_AsVoidPtr(py_block), panelname, tabname, ofsx, ofsy, sizex, sizey));
}
/* similar to Draw.c */
static PyObject *Method_register( PyObject * self, PyObject * args )
{
@@ -352,7 +307,7 @@ static PyObject *Method_registerKey( PyObject * self, PyObject * args )
static bContext *get_py_context__internal(void)
{
PyObject *globals = PyEval_GetGlobals();
PyObject *val= PyDict_GetItemString(globals, "__bpy_context__");
PyObject *val= PyDict_GetItemString(globals, "__bpy_context__"); /* borrow ref */
return PyCObject_AsVoidPtr(val);
}
@@ -399,7 +354,6 @@ static PyObject *Method_getWindowPtr( PyObject * self )
static struct PyMethodDef ui_methods[] = {
{"pupMenuBegin", (PyCFunction)Method_pupMenuBegin, METH_VARARGS, ""},
{"pupMenuEnd", (PyCFunction)Method_pupMenuEnd, METH_VARARGS, ""},
{"menuItemO", (PyCFunction)Method_menuItemO, METH_VARARGS, ""},
{"defButO", (PyCFunction)Method_defButO, METH_VARARGS, ""},
{"defAutoButR", (PyCFunction)Method_defAutoButR, METH_VARARGS, ""},
{"pupBlock", (PyCFunction)Method_pupBlock, METH_VARARGS, ""},
@@ -410,9 +364,6 @@ static struct PyMethodDef ui_methods[] = {
{"blockBeginAlign", (PyCFunction)Method_blockBeginAlign, METH_VARARGS, ""},
{"blockEndAlign", (PyCFunction)Method_blockEndAlign, METH_VARARGS, ""},
{"blockSetFlag", (PyCFunction)Method_blockSetFlag, METH_VARARGS, ""},
{"newPanel", (PyCFunction)Method_newPanel, METH_VARARGS, ""},
{"drawPanels", (PyCFunction)Method_drawPanels, METH_VARARGS, ""},
{"matchPanelsView2d", (PyCFunction)Method_matchPanelsView2d, METH_VARARGS, ""},
{"register", (PyCFunction)Method_register, METH_VARARGS, ""}, // XXX not sure about this - registers current script with the ScriptSpace, like Draw.Register()
{"registerKey", (PyCFunction)Method_registerKey, METH_VARARGS, ""}, // XXX could have this in another place too
@@ -423,6 +374,7 @@ static struct PyMethodDef ui_methods[] = {
{"getScreenPtr", (PyCFunction)Method_getScreenPtr, METH_NOARGS, ""},
{"getSpacePtr", (PyCFunction)Method_getSpacePtr, METH_NOARGS, ""},
{"getWindowPtr", (PyCFunction)Method_getWindowPtr, METH_NOARGS, ""},
{NULL, NULL, 0, NULL}
};

View File

@@ -22,11 +22,12 @@
* ***** END GPL LICENSE BLOCK *****
*/
#include "DNA_listBase.h"
#include "RNA_access.h"
#include "bpy_util.h"
#include "BLI_dynstr.h"
#include "MEM_guardedalloc.h"
#include "bpy_compat.h"
#include "BKE_report.h"
PyObject *BPY_flag_to_list(struct BPY_flag_def *flagdef, int flag)
{
@@ -241,3 +242,110 @@ PyObject *PyObject_GetAttrStringArgs(PyObject *o, Py_ssize_t n, ...)
Py_XINCREF(item); /* final value has is increfed, to match PyObject_GetAttrString */
return item;
}
int BPY_class_validate(const char *class_type, PyObject *class, PyObject *base_class, BPY_class_attr_check* class_attrs, PyObject **py_class_attrs)
{
PyObject *item, *fitem;
PyObject *py_arg_count;
int i, arg_count;
if (base_class) {
if (!PyObject_IsSubclass(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>");
Py_XDECREF(name);
return -1;
}
}
for(i= 0;class_attrs->name; class_attrs++, i++) {
item = PyObject_GetAttrString(class, class_attrs->name);
if (py_class_attrs)
py_class_attrs[i]= item;
if (item==NULL) {
if ((class_attrs->flag & BPY_CLASS_ATTR_OPTIONAL)==0) {
PyErr_Format( PyExc_AttributeError, "expected %s class to have an \"%s\" attribute", class_type, class_attrs->name);
return -1;
}
PyErr_Clear();
}
else {
Py_DECREF(item); /* no need to keep a ref, the class owns it */
if((item==Py_None) && (class_attrs->flag & BPY_CLASS_ATTR_NONE_OK)) {
/* dont do anything, this is ok, dont bother checking other types */
}
else {
switch(class_attrs->type) {
case 's':
if (PyUnicode_Check(item)==0) {
PyErr_Format( PyExc_AttributeError, "expected %s class \"%s\" attribute to be a string", class_type, class_attrs->name);
return -1;
}
break;
case 'l':
if (PyList_Check(item)==0) {
PyErr_Format( PyExc_AttributeError, "expected %s class \"%s\" attribute to be a list", class_type, class_attrs->name);
return -1;
}
break;
case 'f':
if (PyMethod_Check(item))
fitem= PyMethod_Function(item); /* py 2.x */
else
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, class_attrs->name);
return -1;
}
if (class_attrs->arg_count >= 0) { /* -1 if we dont care*/
py_arg_count = PyObject_GetAttrString(PyFunction_GET_CODE(fitem), "co_argcount");
arg_count = PyLong_AsSsize_t(py_arg_count);
Py_DECREF(py_arg_count);
if (arg_count != class_attrs->arg_count) {
PyErr_Format( PyExc_AttributeError, "expected %s class \"%s\" function to have %d args", class_type, class_attrs->name, class_attrs->arg_count);
return -1;
}
}
break;
}
}
}
}
return 0;
}
char *BPy_enum_as_string(EnumPropertyItem *item)
{
DynStr *dynstr= BLI_dynstr_new();
EnumPropertyItem *e;
char *cstring;
for (e= item; item->identifier; item++) {
BLI_dynstr_appendf(dynstr, (e==item)?"'%s'":", '%s'", item->identifier);
}
cstring = BLI_dynstr_get_cstring(dynstr);
BLI_dynstr_free(dynstr);
return cstring;
}
int BPy_reports_to_error(ReportList *reports)
{
char *report_str;
report_str= BKE_reports_string(reports, RPT_ERROR);
if(report_str) {
PyErr_SetString(PyExc_SystemError, report_str);
MEM_freeN(report_str);
}
return (report_str != NULL);
}

View File

@@ -28,6 +28,10 @@
#define BPY_UTIL_H
#include "bpy_compat.h"
#include "RNA_types.h" /* for EnumPropertyItem only */
struct EnumPropertyItem;
struct ReportList;
/* for internal use only, so python can interchange a sequence of strings with flags */
typedef struct BPY_flag_def {
@@ -46,4 +50,28 @@ void BPY_getFileAndNum(char **filename, int *lineno);
/* own python like utility function */
PyObject *PyObject_GetAttrStringArgs(PyObject *o, Py_ssize_t n, ...);
/* Class type checking, use for checking classes can be added as operators, panels etc */
typedef struct BPY_class_attr_check {
const char *name; /* name of the class attribute */
char type; /* 's' = string, 'f' = function, 'l' = list, (add as needed) */
int arg_count; /* only for function types, -1 for undefined, includes self arg */
int flag; /* other options */
} BPY_class_attr_check;
/* BPY_class_attr_check, flag */
#define BPY_CLASS_ATTR_OPTIONAL 1
#define BPY_CLASS_ATTR_NONE_OK 2
int BPY_class_validate(const char *class_type, PyObject *class, PyObject *base_class, BPY_class_attr_check* class_attrs, PyObject **py_class_attrs);
char *BPy_enum_as_string(struct EnumPropertyItem *item);
#define BLANK_PYTHON_TYPE {0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0}
/* error reporting */
int BPy_reports_to_error(struct ReportList *reports);
#endif

View File

@@ -33,8 +33,6 @@ void BPY_post_start_python() {}
void BPY_do_all_scripts() {}
void BPY_call_importloader() {}
void BPY_do_pyscript() {}
void BPY_pydriver_eval() {}
void BPY_pydriver_get_objects() {}
void BPY_clear_script() {}
//void BPY_free_compiled_text() {}
void BPY_pyconstraint_eval() {}