diff options
author | Andreas Becker <atayoohoo@googlemail.com> | 2011-05-07 20:35:03 +0100 |
---|---|---|
committer | Michael Meeks <michael.meeks@novell.com> | 2011-05-07 20:35:03 +0100 |
commit | a09ce46818fd4d5e08b3af9a478501cd8ef5b4fe (patch) | |
tree | 187c9164d436201442794dee227627e2b9173124 /pyuno/source/module | |
parent | 7cf799064f5d64bca62626dc73723c2c5e95ca00 (diff) |
Port PyUno to support Python 3
Diffstat (limited to 'pyuno/source/module')
-rw-r--r-- | pyuno/source/module/makefile.mk | 94 | ||||
-rw-r--r-- | pyuno/source/module/pyuno.cxx | 39 | ||||
-rw-r--r-- | pyuno/source/module/pyuno_callable.cxx | 7 | ||||
-rw-r--r-- | pyuno/source/module/pyuno_except.cxx | 2 | ||||
-rw-r--r-- | pyuno/source/module/pyuno_impl.hxx | 48 | ||||
-rw-r--r-- | pyuno/source/module/pyuno_module.cxx | 101 | ||||
-rw-r--r-- | pyuno/source/module/pyuno_runtime.cxx | 38 | ||||
-rw-r--r-- | pyuno/source/module/uno.py | 31 | ||||
-rw-r--r-- | pyuno/source/module/unohelper.py | 226 |
9 files changed, 327 insertions, 259 deletions
diff --git a/pyuno/source/module/makefile.mk b/pyuno/source/module/makefile.mk index ecad6bca0220..ecfe994c59d3 100644 --- a/pyuno/source/module/makefile.mk +++ b/pyuno/source/module/makefile.mk @@ -36,6 +36,7 @@ LINKFLAGSDEFS = # do not fail with missing symbols .INCLUDE : settings.mk .IF "$(L10N_framework)"=="" + #------------------------------------------------------------------- .IF "$(OS)$(COMEX)" == "SOLARIS4" @@ -49,9 +50,6 @@ EXTRA_FRAMEWORK_FLAG=-framework Python .ENDIF # .IF "$(EXTRA_CFLAGS)"!="" .IF "$(GUI)" == "UNX" -# python expects modules without the lib prefix -# pyuno.so even on Mac OS X, because it is a python module -PYUNO_MODULE=$(DLLDEST)$/pyuno.so PYUNORC=pyunorc .ELSE .INCLUDE : pyversion.mk @@ -69,38 +67,37 @@ CFLAGS+=-I$(SOLARINCDIR)$/python SHL1TARGET=$(TARGET) SLOFILES= \ - $(SLO)$/pyuno_runtime.obj \ - $(SLO)$/pyuno.obj \ - $(SLO)$/pyuno_callable.obj \ - $(SLO)$/pyuno_module.obj \ - $(SLO)$/pyuno_type.obj \ - $(SLO)$/pyuno_util.obj \ - $(SLO)$/pyuno_except.obj \ - $(SLO)$/pyuno_adapter.obj \ + $(SLO)$/pyuno_runtime.obj \ + $(SLO)$/pyuno.obj \ + $(SLO)$/pyuno_callable.obj \ + $(SLO)$/pyuno_module.obj \ + $(SLO)$/pyuno_type.obj \ + $(SLO)$/pyuno_util.obj \ + $(SLO)$/pyuno_except.obj \ + $(SLO)$/pyuno_adapter.obj \ $(SLO)$/pyuno_gc.obj # remove this, when issue i35064 is integrated .IF "$(COM)"=="GCC" NOOPTFILES= \ $(SLO)$/pyuno_module.obj -.ENDIF # "$(COM)"=="GCC" - +.ENDIF # "$(COM)"=="GCC" SHL1STDLIBS= \ - $(CPPULIB) \ - $(CPPUHELPERLIB) \ - $(SALLIB) \ - $(PYTHONLIB) \ - $(EXTRA_FRAMEWORK_FLAG) + $(CPPULIB) \ + $(CPPUHELPERLIB) \ + $(SALLIB) \ + $(PYTHONLIB) \ + $(EXTRA_FRAMEWORK_FLAG) SHL1DEPN= -SHL1LIBS=$(SLB)$/$(TARGET).lib -SHL1IMPLIB=i$(TARGET) +SHL1LIBS= $(SLB)$/$(TARGET).lib +SHL1IMPLIB= i$(TARGET) -SHL1DEF= $(MISC)$/$(SHL1TARGET).def +SHL1DEF= $(MISC)$/$(SHL1TARGET).def -DEF1NAME= $(SHL1TARGET) -DEF1DEPN= $(MISC)$/pyuno.flt +DEF1NAME= $(SHL1TARGET) +DEF1DEPN= $(MISC)$/pyuno.flt DEFLIB1NAME=$(TARGET) @@ -108,21 +105,20 @@ DEFLIB1NAME=$(TARGET) .IF "$(GUI)$(COM)"=="WNTGCC" ALLTAR : \ - $(DLLDEST)$/uno.py \ - $(DLLDEST)$/unohelper.py \ - $(PYUNO_MODULE) \ - $(MISC)$/$(PYUNORC) \ + $(DLLDEST)$/uno.py \ + $(DLLDEST)$/unohelper.py \ + $(MISC)$/$(PYUNORC) \ $(LB)$/lib$(TARGET).a $(LB)$/lib$(TARGET).a: $(MISC)$/$(TARGET).def dlltool --dllname $(TARGET)$(DLLPOST) --input-def=$(MISC)$/$(TARGET).def --kill-at --output-lib=$(LB)$/lib$(TARGET).a .ELSE ALLTAR : \ - $(DLLDEST)$/uno.py \ - $(DLLDEST)$/unohelper.py \ - $(PYUNO_MODULE) \ - $(MISC)$/$(PYUNORC) -.ENDIF + $(DLLDEST)$/uno.py \ + $(DLLDEST)$/unohelper.py \ + $(MISC)$/$(PYUNORC) \ + $(LB)$/$(TARGET)$(DLLPOST) +.ENDIF .ENDIF .INCLUDE : target.mk @@ -130,37 +126,19 @@ ALLTAR : \ $(DLLDEST)$/%.py: %.py cp $? $@ - -.IF "$(GUI)" == "UNX" -$(PYUNO_MODULE) : $(SLO)$/pyuno_dlopenwrapper.obj -.IF "$(OS)" == "LINUX" - @echo $(LINK) $(LINKFLAGS) $(LINKFLAGSRUNPATH_OOO) $(LINKFLAGSSHLCUI) -ldl -o $@ $(SLO)$/pyuno_dlopenwrapper.o > $(MISC)$/$(@:b).cmd -.ELIF "$(OS)" == "SOLARIS" - @echo ld -G -ldl -o $@ $(SLO)$/pyuno_dlopenwrapper.o > $(MISC)$/$(@:b).cmd -.ELIF "$(OS)" == "FREEBSD" - @echo ld -shared -o $@ $(SLO)$/pyuno_dlopenwrapper.o > $(MISC)$/$(@:b).cmd -.ELIF "$(OS)" == "NETBSD" - @echo $(LINK) $(LINKFLAGSSHLCUI) -o $@ $(SLO)$/pyuno_dlopenwrapper.o > $(MISC)$/$(@:b).cmd -.ELIF "$(OS)" == "OPENBSD" - @echo ld -shared -o $@ $(SLO)$/pyuno_dlopenwrapper.o > $(MISC)$/$(@:b).cmd -.ELIF "$(OS)" == "DRAGONFLY" - @echo ld -shared -o $@ $(SLO)$/pyuno_dlopenwrapper.o > $(MISC)$/$(@:b).cmd -.ELIF "$(OS)" == "MACOSX" - @echo $(CC) -bundle -ldl -o $@ $(SLO)$/pyuno_dlopenwrapper.o $(EXTRA_LINKFLAGS) $(EXTRA_FRAMEWORK_FLAG) > $(MISC)$/$(@:b).cmd -.ELSE - @echo $(LINK) $(LINKFLAGSSHLCUI) -o $@ $(SLO)$/pyuno_dlopenwrapper.o > $(MISC)$/$(@:b).cmd -.ENDIF - cat $(MISC)$/$(@:b).cmd - @+source $(MISC)$/$(@:b).cmd -.ENDIF - - $(MISC)$/$(PYUNORC) : pyuno -rm -f $@ - cat pyuno > $@ + cat pyuno > $@ $(MISC)$/pyuno.flt : pyuno.flt -rm -f $@ cat $? > $@ + +# python does not accept the "lib" prefix in the module library +$(LB)$/$(TARGET)$(DLLPOST) : $(LB)$/$(DLLPRE)$(TARGET)$(DLLPOST) + -rm -f $@ + ln -s $? $@ + .ENDIF # L10N_framework +# vim:set shiftwidth=4 softtabstop=4 expandtab: diff --git a/pyuno/source/module/pyuno.cxx b/pyuno/source/module/pyuno.cxx index 1e43f317d819..dbdddac470b3 100644 --- a/pyuno/source/module/pyuno.cxx +++ b/pyuno/source/module/pyuno.cxx @@ -135,13 +135,6 @@ OUString val2str( const void * pVal, typelib_TypeDescriptionReference * pTypeRef } case typelib_TypeClass_UNION: { -// typelib_TypeDescription * pTypeDescr = 0; -// TYPELIB_DANGER_GET( &pTypeDescr, pTypeRef ); -// buf.appendAscii( RTL_CONSTASCII_STRINGPARAM("{ ") ); -// buf.append( val2str( (char *)pVal + ((typelib_UnionTypeDescription *)pTypeDescr)->nValueOffset, -// union_getSetType( pVal, pTypeDescr ) ) ); -// buf.appendAscii( RTL_CONSTASCII_STRINGPARAM(" }") ); -// TYPELIB_DANGER_RELEASE( pTypeDescr ); break; } case typelib_TypeClass_STRUCT: @@ -193,7 +186,7 @@ OUString val2str( const void * pVal, typelib_TypeDescriptionReference * pTypeRef TYPELIB_DANGER_GET( &pElementTypeDescr, ((typelib_IndirectTypeDescription *)pTypeDescr)->pType ); sal_Int32 nElementSize = pElementTypeDescr->nSize; - sal_Int32 nElements = pSequence->nElements; + sal_Int32 nElements = pSequence->nElements; if (nElements) { @@ -600,11 +593,17 @@ int PyUNO_setattr (PyObject* self, char* name, PyObject* value) } // ensure object identity and struct equality -static int PyUNO_cmp( PyObject *self, PyObject *that ) +static PyObject* PyUNO_cmp( PyObject *self, PyObject *that, int op ) { - if( self == that ) + if(op != Py_EQ && op != Py_NE) + { + PyErr_SetString(PyExc_TypeError, "only '==' and '!=' comparisions are defined"); return 0; - int retDefault = self > that ? 1 : -1; + } + if( self == that ) + { + return (op == Py_EQ ? Py_True : Py_False); + } try { Runtime runtime; @@ -624,13 +623,16 @@ static int PyUNO_cmp( PyObject *self, PyObject *that ) Reference< XMaterialHolder > xMe( me->members->xInvocation,UNO_QUERY); Reference< XMaterialHolder > xOther( other->members->xInvocation,UNO_QUERY ); if( xMe->getMaterial() == xOther->getMaterial() ) - return 0; + { + return (op == Py_EQ ? Py_True : Py_False); + } } else if( tcMe == com::sun::star::uno::TypeClass_INTERFACE ) { if( me->members->wrappedObject == other->members->wrappedObject ) -// if( me->members->xInvocation == other->members->xInvocation ) - return 0; + { + return (op == Py_EQ ? Py_True : Py_False); + } } } } @@ -639,13 +641,12 @@ static int PyUNO_cmp( PyObject *self, PyObject *that ) { raisePyExceptionWithAny( makeAny( e ) ); } - return retDefault; + return Py_False; } static PyTypeObject PyUNOType = { - PyObject_HEAD_INIT (&PyType_Type) - 0, + PyVarObject_HEAD_INIT( &PyType_Type, 0 ) const_cast< char * >("pyuno"), sizeof (PyUNO), 0, @@ -653,7 +654,7 @@ static PyTypeObject PyUNOType = (printfunc) 0, (getattrfunc) PyUNO_getattr, (setattrfunc) PyUNO_setattr, - (cmpfunc) PyUNO_cmp, + 0, (reprfunc) PyUNO_repr, 0, 0, @@ -668,7 +669,7 @@ static PyTypeObject PyUNOType = NULL, (traverseproc)0, (inquiry)0, - (richcmpfunc)0, + (richcmpfunc) PyUNO_cmp, 0, (getiterfunc)0, (iternextfunc)0, diff --git a/pyuno/source/module/pyuno_callable.cxx b/pyuno/source/module/pyuno_callable.cxx index 68b2f39e30a5..c1451683f17f 100644 --- a/pyuno/source/module/pyuno_callable.cxx +++ b/pyuno/source/module/pyuno_callable.cxx @@ -196,8 +196,7 @@ PyObject* PyUNO_callable_call (PyObject* self, PyObject* args, PyObject*) static PyTypeObject PyUNO_callable_Type = { - PyObject_HEAD_INIT (&PyType_Type) - 0, + PyVarObject_HEAD_INIT( &PyType_Type, 0 ) const_cast< char * >("PyUNO_callable"), sizeof (PyUNO_callable), 0, @@ -205,7 +204,7 @@ static PyTypeObject PyUNO_callable_Type = (printfunc) 0, (getattrfunc) 0, (setattrfunc) 0, - (cmpfunc) 0, + 0, (reprfunc) 0, 0, 0, @@ -213,7 +212,7 @@ static PyTypeObject PyUNO_callable_Type = (hashfunc) 0, (ternaryfunc) ::pyuno::PyUNO_callable_call, (reprfunc) 0, - (getattrofunc)0, + (getattrofunc)0, (setattrofunc)0, NULL, 0, diff --git a/pyuno/source/module/pyuno_except.cxx b/pyuno/source/module/pyuno_except.cxx index e276be6ee451..16aed8935e4f 100644 --- a/pyuno/source/module/pyuno_except.cxx +++ b/pyuno/source/module/pyuno_except.cxx @@ -167,7 +167,7 @@ static PyRef createClass( const OUString & name, const Runtime &runtime ) PyTuple_SetItem( args.get(), 2, PyDict_New() ); PyRef ret( - PyObject_CallObject(reinterpret_cast<PyObject *>(&PyClass_Type) , args.get()), + PyObject_CallObject(reinterpret_cast<PyObject *>(&PyType_Type) , args.get()), SAL_NO_ACQUIRE ); // now overwrite ctor and attrib functions diff --git a/pyuno/source/module/pyuno_impl.hxx b/pyuno/source/module/pyuno_impl.hxx index c1a38b5e06aa..51bc10a3df4d 100644 --- a/pyuno/source/module/pyuno_impl.hxx +++ b/pyuno/source/module/pyuno_impl.hxx @@ -28,6 +28,8 @@ #ifndef _PYUNO_IMPL_ #define _PYUNO_IMPL_ +#include <Python.h> + #include <pyuno/pyuno.hxx> #include <boost/unordered_map.hpp> @@ -48,6 +50,49 @@ #include <cppuhelper/implbase2.hxx> #include <cppuhelper/weakref.hxx> +// In Python 3, the PyString_* functions have been replaced by PyBytes_* +// and PyUnicode_* functions. +#if PY_MAJOR_VERSION >= 3 +inline char* PyString_AsString(PyObject *object) +{ + // check whether object is already of type "PyBytes" + if(PyBytes_Check(object)) + { + return PyBytes_AsString(object); + } + + // object is not encoded yet, so encode it to utf-8 + PyObject *pystring; + pystring = PyUnicode_AsUTF8String(object); + if(!pystring) + { + PyErr_SetString(PyExc_ValueError, "cannot utf-8 decode string"); + return 0; + } + return PyBytes_AsString(pystring); +} + +inline PyObject* PyString_FromString(const char *string) +{ + return PyUnicode_FromString(string); +} + +inline int PyString_Check(PyObject *object) +{ + return PyBytes_Check(object); +} + +inline Py_ssize_t PyString_Size(PyObject *object) +{ + return PyBytes_Size(object); +} + +inline PyObject* PyString_FromStringAndSize(const char *string, Py_ssize_t len) +{ + return PyBytes_FromStringAndSize(string, len); +} +#endif /* PY_MAJOR_VERSION >= 3 */ + namespace pyuno { @@ -142,9 +187,6 @@ com::sun::star::uno::Any PyObjectToAny (PyObject* o) void raiseInvocationTargetExceptionWhenNeeded( const Runtime &runtime ) throw ( com::sun::star::reflection::InvocationTargetException ); -// bool CheckPyObjectTypes (PyObject* o, Sequence<Type> types); -// bool CheckPyObjectType (PyObject* o, Type type); //Only check 1 object. - com::sun::star::uno::TypeClass StringToTypeClass (char* string); PyRef PyUNO_callable_new ( diff --git a/pyuno/source/module/pyuno_module.cxx b/pyuno/source/module/pyuno_module.cxx index 7a9327894c21..4788a2f1846b 100644 --- a/pyuno/source/module/pyuno_module.cxx +++ b/pyuno/source/module/pyuno_module.cxx @@ -230,7 +230,7 @@ PyObject * extractOneStringArg( PyObject *args, char const *funcName ) return NULL; } PyObject *obj = PyTuple_GetItem( args, 0 ); - if( !PyString_Check( obj ) && ! PyUnicode_Check(obj)) + if(!PyString_Check(obj) && !PyUnicode_Check(obj)) { OStringBuffer buf; buf.append( funcName ).append( ": expecting one string argument" ); @@ -244,16 +244,17 @@ static PyObject *createUnoStructHelper(PyObject *, PyObject* args ) { Any IdlStruct; PyRef ret; - try { Runtime runtime; if( PyTuple_Size( args ) == 2 ) { - PyObject *structName = PyTuple_GetItem( args,0 ); - PyObject *initializer = PyTuple_GetItem( args ,1 ); + PyObject *structName = PyTuple_GetItem(args, 0); + PyObject *initializer = PyTuple_GetItem(args, 1); - if( PyString_Check( structName ) ) + // Perhaps in Python 3, only PyUnicode_Check returns true and + // in Python 2, only PyString_Check returns true. + if(PyString_Check(structName) || PyUnicode_Check(structName)) { if( PyTuple_Check( initializer ) ) { @@ -491,9 +492,9 @@ static PyObject *isInterface( PyObject *, PyObject *args ) { PyObject *obj = PyTuple_GetItem( args, 0 ); Runtime r; - return PyInt_FromLong( isInterfaceClass( r, obj ) ); + return PyLong_FromLong( isInterfaceClass( r, obj ) ); } - return PyInt_FromLong( 0 ); + return PyLong_FromLong( 0 ); } static PyObject * generateUuid( PyObject *, PyObject * ) @@ -592,41 +593,42 @@ static PyObject * absolutize( PyObject *, PyObject * args ) return 0; } -static PyObject * invoke ( PyObject *, PyObject * args ) +static PyObject * invoke(PyObject *, PyObject *args) { PyObject *ret = 0; - if( PyTuple_Check( args ) && PyTuple_Size( args ) == 3 ) + if(PyTuple_Check(args) && PyTuple_Size(args) == 3) { - PyObject *object = PyTuple_GetItem( args, 0 ); - - if( PyString_Check( PyTuple_GetItem( args, 1 ) ) ) + PyObject *object = PyTuple_GetItem(args, 0); + PyObject *item1 = PyTuple_GetItem(args, 1); + if(PyString_Check(item1) || PyUnicode_Check(item1)) { - const char *name = PyString_AsString( PyTuple_GetItem( args, 1 ) ); - if( PyTuple_Check( PyTuple_GetItem( args , 2 ))) + const char *name = PyString_AsString(item1); + PyObject *item2 = PyTuple_GetItem(args, 2); + if(PyTuple_Check(item2)) { - ret = PyUNO_invoke( object, name , PyTuple_GetItem( args, 2 ) ); + ret = PyUNO_invoke(object, name, item2); } else { OStringBuffer buf; - buf.append( "uno.invoke expects a tuple as 3rd argument, got " ); - buf.append( PyString_AsString( PyObject_Str( PyTuple_GetItem( args, 2) ) ) ); - PyErr_SetString( PyExc_RuntimeError, buf.makeStringAndClear() ); + buf.append("uno.invoke expects a tuple as 3rd argument, got "); + buf.append(PyString_AsString(PyObject_Str(item2))); + PyErr_SetString(PyExc_RuntimeError, buf.makeStringAndClear()); } } else { OStringBuffer buf; - buf.append( "uno.invoke expected a string as 2nd argument, got " ); - buf.append( PyString_AsString( PyObject_Str( PyTuple_GetItem( args, 1) ) ) ); - PyErr_SetString( PyExc_RuntimeError, buf.makeStringAndClear() ); + buf.append("uno.invoke expected a string as 2nd argument, got "); + buf.append(PyString_AsString(PyObject_Str(item1))); + PyErr_SetString(PyExc_RuntimeError, buf.makeStringAndClear()); } } else { OStringBuffer buf; - buf.append( "uno.invoke expects object, name, (arg1, arg2, ... )\n" ); - PyErr_SetString( PyExc_RuntimeError, buf.makeStringAndClear() ); + buf.append("uno.invoke expects object, name, (arg1, arg2, ... )\n"); + PyErr_SetString(PyExc_RuntimeError, buf.makeStringAndClear()); } return ret; } @@ -690,31 +692,52 @@ static PyObject *setCurrentContext( PyObject *, PyObject * args ) struct PyMethodDef PyUNOModule_methods [] = { - {const_cast< char * >("getComponentContext"), getComponentContext, 1, NULL}, - {const_cast< char * >("_createUnoStructHelper"), createUnoStructHelper, 2, NULL}, - {const_cast< char * >("getTypeByName"), getTypeByName, 1, NULL}, - {const_cast< char * >("getConstantByName"), getConstantByName,1, NULL}, - {const_cast< char * >("getClass"), getClass,1, NULL}, - {const_cast< char * >("checkEnum"), checkEnum, 1, NULL}, - {const_cast< char * >("checkType"), checkType, 1, NULL}, - {const_cast< char * >("generateUuid"), generateUuid,0, NULL}, - {const_cast< char * >("systemPathToFileUrl"),systemPathToFileUrl,1, NULL}, - {const_cast< char * >("fileUrlToSystemPath"),fileUrlToSystemPath,1, NULL}, - {const_cast< char * >("absolutize"),absolutize,2, NULL}, - {const_cast< char * >("isInterface"),isInterface,1, NULL}, - {const_cast< char * >("invoke"),invoke, 2, NULL}, - {const_cast< char * >("setCurrentContext"),setCurrentContext,1, NULL}, - {const_cast< char * >("getCurrentContext"),getCurrentContext,1, NULL}, + {const_cast< char * >("getComponentContext"), getComponentContext, METH_VARARGS, NULL}, + {const_cast< char * >("_createUnoStructHelper"), createUnoStructHelper, METH_VARARGS | METH_KEYWORDS, NULL}, + {const_cast< char * >("getTypeByName"), getTypeByName, METH_VARARGS, NULL}, + {const_cast< char * >("getConstantByName"), getConstantByName, METH_VARARGS, NULL}, + {const_cast< char * >("getClass"), getClass, METH_VARARGS, NULL}, + {const_cast< char * >("checkEnum"), checkEnum, METH_VARARGS, NULL}, + {const_cast< char * >("checkType"), checkType, METH_VARARGS, NULL}, + {const_cast< char * >("generateUuid"), generateUuid, METH_VARARGS, NULL}, + {const_cast< char * >("systemPathToFileUrl"), systemPathToFileUrl, METH_VARARGS, NULL}, + {const_cast< char * >("fileUrlToSystemPath"), fileUrlToSystemPath, METH_VARARGS, NULL}, + {const_cast< char * >("absolutize"), absolutize, METH_VARARGS | METH_KEYWORDS, NULL}, + {const_cast< char * >("isInterface"), isInterface, METH_VARARGS, NULL}, + {const_cast< char * >("invoke"), invoke, METH_VARARGS | METH_KEYWORDS, NULL}, + {const_cast< char * >("setCurrentContext"), setCurrentContext, METH_VARARGS, NULL}, + {const_cast< char * >("getCurrentContext"), getCurrentContext, METH_VARARGS, NULL}, {NULL, NULL, 0, NULL} }; } -extern "C" PY_DLLEXPORT void initpyuno() +extern "C" PY_DLLEXPORT +#if PY_MAJOR_VERSION >= 3 +PyObject* PyInit_pyuno() { // noop when called already, otherwise needed to allow multiple threads PyEval_InitThreads(); + static struct PyModuleDef moduledef = + { + PyModuleDef_HEAD_INIT, + "pyuno", // module name + 0, // module documentation + -1, // module keeps state in global variables, + PyUNOModule_methods, // modules methods + 0, // m_reload (must be 0) + 0, // m_traverse + 0, // m_clear + 0, // m_free + }; + return PyModule_Create(&moduledef); +} +#else +void initpyuno() +{ + PyEval_InitThreads(); Py_InitModule (const_cast< char * >("pyuno"), PyUNOModule_methods); } +#endif /* PY_MAJOR_VERSION >= 3 */ /* vim:set shiftwidth=4 softtabstop=4 expandtab: */ diff --git a/pyuno/source/module/pyuno_runtime.cxx b/pyuno/source/module/pyuno_runtime.cxx index ed34ddf3b6cf..61d05d8321f5 100644 --- a/pyuno/source/module/pyuno_runtime.cxx +++ b/pyuno/source/module/pyuno_runtime.cxx @@ -72,8 +72,7 @@ namespace pyuno static PyTypeObject RuntimeImpl_Type = { - PyObject_HEAD_INIT (&PyType_Type) - 0, + PyVarObject_HEAD_INIT (&PyType_Type, 0) const_cast< char * >("pyuno_runtime"), sizeof (RuntimeImpl), 0, @@ -81,7 +80,7 @@ static PyTypeObject RuntimeImpl_Type = (printfunc) 0, (getattrfunc) 0, (setattrfunc) 0, - (cmpfunc) 0, + 0, (reprfunc) 0, 0, 0, @@ -445,7 +444,7 @@ PyRef Runtime::any2PyObject (const Any &a ) const { sal_Int32 l = 0; a >>= l; - return PyRef( PyInt_FromLong (l), SAL_NO_ACQUIRE ); + return PyRef( PyLong_FromLong (l), SAL_NO_ACQUIRE ); } case typelib_TypeClass_UNSIGNED_LONG: { @@ -666,6 +665,8 @@ Any Runtime::pyObject2Any ( const PyRef & source, enum ConversionMode mode ) con { } + // In Python 3, there is no PyInt type. +#if PY_MAJOR_VERSION < 3 else if (PyInt_Check (o)) { if( o == Py_True ) @@ -680,7 +681,7 @@ Any Runtime::pyObject2Any ( const PyRef & source, enum ConversionMode mode ) con } else { - sal_Int32 l = (sal_Int32) PyInt_AsLong( o ); + sal_Int32 l = (sal_Int32) PyLong_AsLong( o ); if( l < 128 && l >= -128 ) { sal_Int8 b = (sal_Int8 ) l; @@ -697,8 +698,24 @@ Any Runtime::pyObject2Any ( const PyRef & source, enum ConversionMode mode ) con } } } +#endif /* PY_MAJOR_VERSION < 3 */ else if (PyLong_Check (o)) { +#if PY_MAJOR_VERSION >= 3 + // Convert the Python 3 booleans that are actually of type PyLong. + if(o == Py_True) + { + sal_Bool b = sal_True; + a = Any(&b, getBooleanCppuType()); + } + else if(o == Py_False) + { + sal_Bool b = sal_False; + a = Any(&b, getBooleanCppuType()); + } + else + { +#endif /* PY_MAJOR_VERSION >= 3 */ sal_Int64 l = (sal_Int64)PyLong_AsLong (o); if( l < 128 && l >= -128 ) { @@ -720,16 +737,19 @@ Any Runtime::pyObject2Any ( const PyRef & source, enum ConversionMode mode ) con { a <<= l; } +#if PY_MAJOR_VERSION >= 3 + } +#endif } else if (PyFloat_Check (o)) { double d = PyFloat_AsDouble (o); a <<= d; } - else if (PyString_Check (o)) - a <<= pyString2ustring(o); - else if( PyUnicode_Check( o ) ) - a <<= pyString2ustring(o); + else if (PyString_Check(o) || PyUnicode_Check(o)) + { + a <<= pyString2ustring(o); + } else if (PyTuple_Check (o)) { Sequence<Any> s (PyTuple_Size (o)); diff --git a/pyuno/source/module/uno.py b/pyuno/source/module/uno.py index f61b3c925d36..bca8892fbdb3 100644 --- a/pyuno/source/module/uno.py +++ b/pyuno/source/module/uno.py @@ -27,7 +27,12 @@ import sys import pyuno -import __builtin__ + +try: + import __builtin__ +except ImportError: + import builtins as __builtin__ + import socket # since on Windows sal3.dll no longer calls WSAStartup # all functions and variables starting with a underscore (_) must be considered private @@ -149,9 +154,9 @@ class Bool(object): Note: This class is deprecated. Use python's True and False directly instead """ def __new__(cls, value): - if isinstance(value, (str, unicode)) and value == "true": + if isinstance(value, str) and value == "true": return True - if isinstance(value, (str, unicode)) and value == "false": + if isinstance(value, str) and value == "false": return False if value: return True @@ -161,7 +166,7 @@ class Char: "Represents a UNO char, use an instance of this class to explicitly pass a char to UNO" # @param value pass a Unicode string with length 1 def __init__(self,value): - assert isinstance(value, unicode) + assert isinstance(value, str) assert len(value) == 1 self.value=value @@ -169,7 +174,7 @@ class Char: return "<Char instance %s>" % (self.value, ) def __eq__(self, that): - if isinstance(that, (str, unicode)): + if isinstance(that, str): if len(that) > 1: return False return self.value == that[0] @@ -260,7 +265,7 @@ def _uno_import( name, *optargs, **kwargs ): mod = None d = sys.modules for x in modnames: - if d.has_key(x): + if x in d: mod = d[x] else: mod = pyuno.__class__(x) # How to create a module ?? @@ -268,25 +273,25 @@ def _uno_import( name, *optargs, **kwargs ): RuntimeException = pyuno.getClass( "com.sun.star.uno.RuntimeException" ) for x in fromlist: - if not d.has_key(x): + if x not in d: if x.startswith( "typeOf" ): try: d[x] = pyuno.getTypeByName( name + "." + x[6:len(x)] ) - except RuntimeException,e: + except RuntimeException as e: raise ImportError( "type " + name + "." + x[6:len(x)] +" is unknown" ) else: try: # check for structs, exceptions or interfaces d[x] = pyuno.getClass( name + "." + x ) - except RuntimeException,e: + except RuntimeException as e: # check for enums try: d[x] = Enum( name , x ) - except RuntimeException,e2: + except RuntimeException as e2: # check for constants try: d[x] = getConstantByName( name + "." + x ) - except RuntimeException,e3: + except RuntimeException as e3: # no known uno type ! raise ImportError( "type "+ name + "." +x + " is unknown" ) return mod @@ -296,7 +301,7 @@ __builtin__.__dict__["__import__"] = _uno_import # private function, don't use def _impl_extractName(name): - r = range (len(name)-1,0,-1) + r = list(range(len(name)-1,0,-1)) for i in r: if name[i] == ".": name = name[i+1:len(name)] @@ -336,7 +341,7 @@ def _uno_extract_printable_stacktrace( trace ): mod = None try: mod = __import__("traceback") - except ImportError,e: + except ImportError as e: pass ret = "" if mod: diff --git a/pyuno/source/module/unohelper.py b/pyuno/source/module/unohelper.py index c59df0597a73..112d0d97ebca 100644 --- a/pyuno/source/module/unohelper.py +++ b/pyuno/source/module/unohelper.py @@ -78,7 +78,7 @@ def _propertymode_to_str( mode ): if PROP_ATTR_MAYBEVOID & mode: ret = ret + "maybevoid " return ret.rstrip() - + def inspect( obj , out ): if isinstance( obj, uno.Type ) or \ isinstance( obj, uno.Char ) or \ @@ -108,7 +108,7 @@ def inspect( obj , out ): out.write( " " + ii.typeName + "\n" ) else: out.write( " unknown\n" ) - + access = introspection.inspect( obj ) methods = access.getMethods( METHOD_CONCEPT_ALL ) out.write( "Methods:\n" ) @@ -132,56 +132,56 @@ def createSingleServiceFactory( clazz, implementationName, serviceNames ): return _FactoryHelper_( clazz, implementationName, serviceNames ) class _ImplementationHelperEntry: - def __init__(self, ctor,serviceNames): - self.ctor = ctor - self.serviceNames = serviceNames - + def __init__(self, ctor,serviceNames): + self.ctor = ctor + self.serviceNames = serviceNames + class ImplementationHelper: - def __init__(self): - self.impls = {} - - def addImplementation( self, ctor, implementationName, serviceNames ): - self.impls[implementationName] = _ImplementationHelperEntry(ctor,serviceNames) - - def writeRegistryInfo( self, regKey, smgr ): - for i in self.impls.items(): - keyName = "/"+ i[0] + "/UNO/SERVICES" - key = regKey.createKey( keyName ) - for serviceName in i[1].serviceNames: - key.createKey( serviceName ) - return 1 - - def getComponentFactory( self, implementationName , regKey, smgr ): - entry = self.impls.get( implementationName, None ) - if entry == None: - raise RuntimeException( implementationName + " is unknown" , None ) - return createSingleServiceFactory( entry.ctor, implementationName, entry.serviceNames ) - - def getSupportedServiceNames( self, implementationName ): - entry = self.impls.get( implementationName, None ) - if entry == None: - raise RuntimeException( implementationName + " is unknown" , None ) - return entry.serviceNames - - def supportsService( self, implementationName, serviceName ): - entry = self.impls.get( implementationName,None ) - if entry == None: - raise RuntimeException( implementationName + " is unknown", None ) - return serviceName in entry.serviceNames - - + def __init__(self): + self.impls = {} + + def addImplementation( self, ctor, implementationName, serviceNames ): + self.impls[implementationName] = _ImplementationHelperEntry(ctor,serviceNames) + + def writeRegistryInfo( self, regKey, smgr ): + for i in list(self.impls.items()): + keyName = "/"+ i[0] + "/UNO/SERVICES" + key = regKey.createKey( keyName ) + for serviceName in i[1].serviceNames: + key.createKey( serviceName ) + return 1 + + def getComponentFactory( self, implementationName , regKey, smgr ): + entry = self.impls.get( implementationName, None ) + if entry == None: + raise RuntimeException( implementationName + " is unknown" , None ) + return createSingleServiceFactory( entry.ctor, implementationName, entry.serviceNames ) + + def getSupportedServiceNames( self, implementationName ): + entry = self.impls.get( implementationName, None ) + if entry == None: + raise RuntimeException( implementationName + " is unknown" , None ) + return entry.serviceNames + + def supportsService( self, implementationName, serviceName ): + entry = self.impls.get( implementationName,None ) + if entry == None: + raise RuntimeException( implementationName + " is unknown", None ) + return serviceName in entry.serviceNames + + class ImplementationEntry: - def __init__(self, implName, supportedServices, clazz ): - self.implName = implName - self.supportedServices = supportedServices - self.clazz = clazz + def __init__(self, implName, supportedServices, clazz ): + self.implName = implName + self.supportedServices = supportedServices + self.clazz = clazz def writeRegistryInfoHelper( smgr, regKey, seqEntries ): for entry in seqEntries: keyName = "/"+ entry.implName + "/UNO/SERVICES" - key = regKey.createKey( keyName ) - for serviceName in entry.supportedServices: - key.createKey( serviceName ) + key = regKey.createKey( keyName ) + for serviceName in entry.supportedServices: + key.createKey( serviceName ) def systemPathToFileUrl( systemPath ): "returns a file-url for the given system path" @@ -194,11 +194,11 @@ def fileUrlToSystemPath( url ): def absolutize( path, relativeUrl ): "returns an absolute file url from the given urls" return pyuno.absolutize( path, relativeUrl ) - + def getComponentFactoryHelper( implementationName, smgr, regKey, seqEntries ): for x in seqEntries: - if x.implName == implementationName: - return createSingleServiceFactory( x.clazz, implementationName, x.supportedServices ) + if x.implName == implementationName: + return createSingleServiceFactory( x.clazz, implementationName, x.supportedServices ) def addComponentsToContext( toBeExtendedContext, contextRuntime, componentUrls, loaderName ): smgr = contextRuntime.ServiceManager @@ -210,56 +210,56 @@ def addComponentsToContext( toBeExtendedContext, contextRuntime, componentUrls, # create a temporary registry for componentUrl in componentUrls: reg = smgr.createInstanceWithContext( "com.sun.star.registry.SimpleRegistry", contextRuntime ) - reg.open( "", 0, 1 ) + reg.open( "", 0, 1 ) if not isWin and componentUrl.endswith( ".uno" ): # still allow platform independent naming if isMac: - componentUrl = componentUrl + ".dylib" + componentUrl = componentUrl + ".dylib" else: - componentUrl = componentUrl + ".so" - - implReg.registerImplementation( loaderName,componentUrl, reg ) - rootKey = reg.getRootKey() - implementationKey = rootKey.openKey( "IMPLEMENTATIONS" ) - implNames = implementationKey.getKeyNames() - extSMGR = toBeExtendedContext.ServiceManager - for x in implNames: - fac = loader.activate( max(x.split("/")),"",componentUrl,rootKey) - extSMGR.insert( fac ) - reg.close() - + componentUrl = componentUrl + ".so" + + implReg.registerImplementation( loaderName,componentUrl, reg ) + rootKey = reg.getRootKey() + implementationKey = rootKey.openKey( "IMPLEMENTATIONS" ) + implNames = implementationKey.getKeyNames() + extSMGR = toBeExtendedContext.ServiceManager + for x in implNames: + fac = loader.activate( max(x.split("/")),"",componentUrl,rootKey) + extSMGR.insert( fac ) + reg.close() + # never shrinks ! _g_typeTable = {} def _unohelper_getHandle( self): - ret = None - if _g_typeTable.has_key( self.__class__ ): - ret = _g_typeTable[self.__class__] - else: - names = {} - traverse = list(self.__class__.__bases__) - while len( traverse ) > 0: - item = traverse.pop() - bases = item.__bases__ - if uno.isInterface( item ): - names[item.__pyunointerface__] = None - elif len(bases) > 0: - # the "else if", because we only need the most derived interface - traverse = traverse + list(bases)# - - lst = names.keys() - types = [] - for x in lst: - t = uno.getTypeByName( x ) - types.append( t ) - - ret = tuple(types) , uno.generateUuid() - _g_typeTable[self.__class__] = ret - return ret - + ret = None + if self.__class__ in _g_typeTable: + ret = _g_typeTable[self.__class__] + else: + names = {} + traverse = list(self.__class__.__bases__) + while len( traverse ) > 0: + item = traverse.pop() + bases = item.__bases__ + if uno.isInterface( item ): + names[item.__pyunointerface__] = None + elif len(bases) > 0: + # the "else if", because we only need the most derived interface + traverse = traverse + list(bases)# + + lst = list(names.keys()) + types = [] + for x in lst: + t = uno.getTypeByName( x ) + types.append( t ) + + ret = tuple(types) , uno.generateUuid() + _g_typeTable[self.__class__] = ret + return ret + class Base(XTypeProvider): - def getTypes( self ): - return _unohelper_getHandle( self )[0] - def getImplementationId(self): - return _unohelper_getHandle( self )[1] + def getTypes( self ): + return _unohelper_getHandle( self )[0] + def getImplementationId(self): + return _unohelper_getHandle( self )[1] class CurrentContext(XCurrentContext, Base ): """a current context implementation, which first does a lookup in the given @@ -277,28 +277,28 @@ class CurrentContext(XCurrentContext, Base ): return self.oldContext.getValueByName( name ) else: return None - + # ------------------------------------------------- # implementation details # ------------------------------------------------- class _FactoryHelper_( XSingleComponentFactory, XServiceInfo, Base ): - def __init__( self, clazz, implementationName, serviceNames ): - self.clazz = clazz - self.implementationName = implementationName - self.serviceNames = serviceNames - - def getImplementationName( self ): - return self.implementationName - - def supportsService( self, ServiceName ): - return ServiceName in self.serviceNames - - def getSupportedServiceNames( self ): - return self.serviceNames - - def createInstanceWithContext( self, context ): - return self.clazz( context ) - - def createInstanceWithArgumentsAndContext( self, args, context ): - return self.clazz( context, *args ) - + def __init__( self, clazz, implementationName, serviceNames ): + self.clazz = clazz + self.implementationName = implementationName + self.serviceNames = serviceNames + + def getImplementationName( self ): + return self.implementationName + + def supportsService( self, ServiceName ): + return ServiceName in self.serviceNames + + def getSupportedServiceNames( self ): + return self.serviceNames + + def createInstanceWithContext( self, context ): + return self.clazz( context ) + + def createInstanceWithArgumentsAndContext( self, args, context ): + return self.clazz( context, *args ) + |