Author: pfg
Date: Tue Dec 18 04:43:25 2012
New Revision: 1423272

URL: http://svn.apache.org/viewvc?rev=1423272&view=rev
Log:
i121296 - Python3 support for pyuno.

Add support to pyuno so that it will build with and support modern versions
of the system Python.

This is a huge step forward for developers and users of operating systems
that are in the process of migrating to Python 3.x.

Author: hanya

Modified:
    openoffice/trunk/main/pyuno/source/module/pyuno.cxx
    openoffice/trunk/main/pyuno/source/module/pyuno_adapter.cxx
    openoffice/trunk/main/pyuno/source/module/pyuno_callable.cxx
    openoffice/trunk/main/pyuno/source/module/pyuno_except.cxx
    openoffice/trunk/main/pyuno/source/module/pyuno_impl.hxx
    openoffice/trunk/main/pyuno/source/module/pyuno_module.cxx
    openoffice/trunk/main/pyuno/source/module/pyuno_runtime.cxx
    openoffice/trunk/main/pyuno/source/module/pyuno_type.cxx
    openoffice/trunk/main/pyuno/source/module/pyuno_util.cxx
    openoffice/trunk/main/pyuno/source/module/uno.py

Modified: openoffice/trunk/main/pyuno/source/module/pyuno.cxx
URL: 
http://svn.apache.org/viewvc/openoffice/trunk/main/pyuno/source/module/pyuno.cxx?rev=1423272&r1=1423271&r2=1423272&view=diff
==============================================================================
--- openoffice/trunk/main/pyuno/source/module/pyuno.cxx (original)
+++ openoffice/trunk/main/pyuno/source/module/pyuno.cxx Tue Dec 18 04:43:25 2012
@@ -342,7 +342,7 @@ PyObject *PyUNO_invoke( PyObject *object
         Runtime runtime;
 
         PyRef paras,callable;
-        if( PyObject_IsInstance( object, getPyUnoClass( runtime ).get() ) )
+        if( PyObject_IsInstance( object, getPyUnoClass().get() ) )
         {
             PyUNO* me = (PyUNO*) object;
             OUString attrName = OUString::createFromAscii(name);
@@ -441,19 +441,30 @@ PyObject *PyUNO_str( PyObject * self )
         buf.append( OUStringToOString(s,RTL_TEXTENCODING_ASCII_US) );
     }
 
-    return PyBytes_FromString( buf.getStr());
+    return PYSTR_FROMSTR( buf.getStr() );
 }
 
+#if PY_MAJOR_VERSION >= 3
+PyObject* PyUNO_getattr (PyObject* self, PyObject* attr_name)
+#else
 PyObject* PyUNO_getattr (PyObject* self, char* name)
+#endif
 {
     PyUNO* me;
 
+#if PY_VERSION_HEX >= 0x03030000
+    char *name = PyUnicode_AsUTF8(attr_name);
+#elif PY_MAJOR_VERSION >= 3
+    PyRef pUtf8(PyUnicode_AsUTF8String(attr_name), SAL_NO_ACQUIRE);
+    char *name = PyBytes_AsString(pUtf8.get());
+#endif
     try
     {
 
         Runtime runtime;
     
         me = (PyUNO*) self;
+#if PY_MAJOR_VERSION < 3
         //Handle Python dir () stuff first...
         if (strcmp (name, "__members__") == 0)
         {
@@ -469,17 +480,20 @@ PyObject* PyUNO_getattr (PyObject* self,
             }
             return member_list;
         }
-        
+#endif
+
         if (strcmp (name, "__dict__") == 0)
         {
             Py_INCREF (Py_None);
             return Py_None;
         }
+#if PY_MAJOR_VERSION < 3
         if (strcmp (name, "__methods__") == 0)
         {
             Py_INCREF (Py_None);
             return Py_None;
         }
+#endif
         if (strcmp (name, "__class__") == 0)
         {
             if( me->members->wrappedObject.getValueTypeClass() ==
@@ -550,10 +564,20 @@ PyObject* PyUNO_getattr (PyObject* self,
     return NULL;
 }
 
+#if PY_MAJOR_VERSION >= 3
+int PyUNO_setattr (PyObject* self, PyObject* attr_name, PyObject* value)
+#else
 int PyUNO_setattr (PyObject* self, char* name, PyObject* value)
+#endif
 {
     PyUNO* me;
 
+#if PY_VERSION_HEX >= 0x03030000
+    char *name = PyUnicode_AsUTF8(attr_name);
+#elif PY_MAJOR_VERSION >= 3
+    PyRef pUtf8(PyUnicode_AsUTF8String(attr_name), SAL_NO_ACQUIRE);
+    char *name = PyBytes_AsString(pUtf8.get());
+#endif
     me = (PyUNO*) self;
     try
     {
@@ -594,6 +618,99 @@ int PyUNO_setattr (PyObject* self, char*
     return 1; //as above.
 }
 
+#if PY_MAJOR_VERSION >= 3
+static PyObject *PyUNO_dir( PyObject *self, PyObject *that )
+{
+    PyUNO* me;
+    PyObject* member_list;
+    Sequence<OUString> oo_member_list;
+    
+    me = (PyUNO*) self;
+    oo_member_list = me->members->xInvocation->getMemberNames ();
+    member_list = PyList_New (oo_member_list.getLength ());
+    for (int i = 0; i < oo_member_list.getLength (); i++)
+    {
+        // setitem steals a reference
+        PyList_SetItem (member_list, i, 
ustring2PyUnicode(oo_member_list[i]).getAcquired() );
+    }
+    return member_list;
+}
+
+static PyObject *PyUNO_richcompare( PyObject *self, PyObject *that, int op )
+{
+    switch (op)
+    {
+    case Py_EQ:
+    case Py_NE:
+        if( self == that )
+        {
+            if (op == Py_EQ)
+                Py_RETURN_TRUE;
+            else
+                Py_RETURN_FALSE;
+        }
+        try
+        {
+            Runtime runtime;
+            if( PyObject_IsInstance( that, getPyUnoClass().get() ) )
+            {
+                PyUNO *me = reinterpret_cast< PyUNO*> ( self );
+                PyUNO *other = reinterpret_cast< PyUNO *> (that );
+                com::sun::star::uno::TypeClass tcMe = 
me->members->wrappedObject.getValueTypeClass();
+                com::sun::star::uno::TypeClass tcOther = 
other->members->wrappedObject.getValueTypeClass();
+            
+                if( tcMe == tcOther )
+                {
+                    if( tcMe == com::sun::star::uno::TypeClass_STRUCT ||
+                        tcMe == com::sun::star::uno::TypeClass_EXCEPTION )
+                    {
+                        Reference< XMaterialHolder > xMe( 
me->members->xInvocation,UNO_QUERY);
+                        Reference< XMaterialHolder > xOther( 
other->members->xInvocation,UNO_QUERY );
+                        if( xMe->getMaterial() == xOther->getMaterial() )
+                        {
+                            if (op == Py_EQ)
+                                Py_RETURN_TRUE;
+                            else
+                                Py_RETURN_FALSE;
+                        }
+                    }
+                    else if( tcMe == com::sun::star::uno::TypeClass_INTERFACE )
+                    {
+                        if( me->members->wrappedObject == 
other->members->wrappedObject )
+                        {
+                            if (op == Py_EQ)
+                                Py_RETURN_TRUE;
+                            else
+                                Py_RETURN_FALSE;
+                        }
+                    }
+                }
+            }
+            if (op == Py_EQ)
+                Py_RETURN_FALSE;
+            else
+                Py_RETURN_TRUE;
+        }
+        catch( com::sun::star::uno::RuntimeException & e)
+        {
+            raisePyExceptionWithAny( makeAny( e ) );
+        }
+        break;
+    default:
+        PyErr_SetString(Py_NotImplemented, "not implemented");
+        break;
+    }
+    
+    return NULL;
+}
+
+
+static struct PyMethodDef PyUNO_methods[] = {
+    { "__dir__", (PyCFunction)PyUNO_dir, METH_VARARGS, NULL},
+    { NULL, NULL }
+};
+
+#else
 // ensure object identity and struct equality
 static int PyUNO_cmp( PyObject *self, PyObject *that )
 {
@@ -603,7 +720,7 @@ static int PyUNO_cmp( PyObject *self, Py
     try
     {
         Runtime runtime;
-        if( PyObject_IsInstance( that, getPyUnoClass( runtime ).get() ) )
+        if( PyObject_IsInstance( that, getPyUnoClass().get() ) )
         {
 
             PyUNO *me = reinterpret_cast< PyUNO*> ( self );
@@ -636,6 +753,7 @@ static int PyUNO_cmp( PyObject *self, Py
     }
     return retDefault;
 }
+#endif
 
 static PyTypeObject PyUNOType =
 {
@@ -645,9 +763,15 @@ static PyTypeObject PyUNOType =
     0,
     (destructor) PyUNO_del,
     (printfunc) 0,
-    (getattrfunc) PyUNO_getattr,
-    (setattrfunc) PyUNO_setattr,
-    PyUNO_cmp,
+#if PY_MAJOR_VERSION >= 3
+    (getattrfunc) 0,
+    (setattrfunc) 0,
+    0, 
+#else
+    (getattrfunc) PyUNO_getattr, /* tp_getattr */
+    (setattrfunc) PyUNO_setattr, /* tp_setattr */
+    (cmpfunc) PyUNO_cmp,
+#endif
     (reprfunc) PyUNO_repr,
     0,
     0,
@@ -655,18 +779,31 @@ static PyTypeObject PyUNOType =
     (hashfunc) 0,
     (ternaryfunc) 0,
     (reprfunc) PyUNO_str,
+#if PY_MAJOR_VERSION >= 3
+    (getattrofunc)PyUNO_getattr, /* tp_getattro */
+    (setattrofunc)PyUNO_setattr, /* tp_setattro */
+#else
     (getattrofunc)0,
     (setattrofunc)0,
+#endif
     NULL,
     0,
     NULL,
     (traverseproc)0,
     (inquiry)0,
+#if PY_MAJOR_VERSION >= 3
+    PyUNO_richcompare, /* tp_richcompare */
+#else
     (richcmpfunc)0,
+#endif
     0,
     (getiterfunc)0,
     (iternextfunc)0,
+#if PY_MAJOR_VERSION >= 3
+    PyUNO_methods, /* tp_methods */
+#else
     NULL,
+#endif
     NULL,
     NULL,
     NULL,
@@ -690,7 +827,7 @@ static PyTypeObject PyUNOType =
 #endif
 };
 
-PyRef getPyUnoClass( const Runtime &)
+PyRef getPyUnoClass()
 {
     return PyRef( reinterpret_cast< PyObject * > ( &PyUNOType ) );
 }

Modified: openoffice/trunk/main/pyuno/source/module/pyuno_adapter.cxx
URL: 
http://svn.apache.org/viewvc/openoffice/trunk/main/pyuno/source/module/pyuno_adapter.cxx?rev=1423272&r1=1423271&r2=1423272&view=diff
==============================================================================
--- openoffice/trunk/main/pyuno/source/module/pyuno_adapter.cxx (original)
+++ openoffice/trunk/main/pyuno/source/module/pyuno_adapter.cxx Tue Dec 18 
04:43:25 2012
@@ -246,7 +246,7 @@ Any Adapter::invoke( const OUString &aFu
             buf.appendAscii( "pyuno::Adapater: Method " ).append( 
aFunctionName );
             buf.appendAscii( " is not implemented at object " );
             PyRef str( PyObject_Repr( mWrappedObject.get() ), SAL_NO_ACQUIRE );
-            buf.appendAscii( PyBytes_AsString( str.get() ));
+            buf.append( pyString2ustring( str.get() ) );
             throw IllegalArgumentException( buf.makeStringAndClear(), 
Reference< XInterface > (),0 );
         }
 

Modified: openoffice/trunk/main/pyuno/source/module/pyuno_callable.cxx
URL: 
http://svn.apache.org/viewvc/openoffice/trunk/main/pyuno/source/module/pyuno_callable.cxx?rev=1423272&r1=1423271&r2=1423272&view=diff
==============================================================================
--- openoffice/trunk/main/pyuno/source/module/pyuno_callable.cxx (original)
+++ openoffice/trunk/main/pyuno/source/module/pyuno_callable.cxx Tue Dec 18 
04:43:25 2012
@@ -199,7 +199,11 @@ static PyTypeObject PyUNO_callable_Type 
     (printfunc) 0,
     (getattrfunc) 0,
     (setattrfunc) 0,
+#if PY_MAJOR_VERSION >= 3
+    0, 
+#else
     (cmpfunc) 0,
+#endif
     (reprfunc) 0,
     0,
     0,

Modified: openoffice/trunk/main/pyuno/source/module/pyuno_except.cxx
URL: 
http://svn.apache.org/viewvc/openoffice/trunk/main/pyuno/source/module/pyuno_except.cxx?rev=1423272&r1=1423271&r2=1423272&view=diff
==============================================================================
--- openoffice/trunk/main/pyuno/source/module/pyuno_except.cxx (original)
+++ openoffice/trunk/main/pyuno/source/module/pyuno_except.cxx Tue Dec 18 
04:43:25 2012
@@ -142,7 +142,7 @@ static PyRef createClass( const OUString
     }
     PyRef args( PyTuple_New( 3 ), SAL_NO_ACQUIRE );
 
-    PyRef pyTypeName = ustring2PyString( name /*.replace( '.', '_' )*/ );
+    PyRef pyTypeName = USTR_TO_PYSTR( name /*.replace( '.', '_' )*/ );
 
     PyRef bases;
     if( base.is() )
@@ -162,7 +162,7 @@ static PyRef createClass( const OUString
     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
@@ -170,7 +170,7 @@ static PyRef createClass( const OUString
     {
         PyObject_SetAttrString(
             ret.get(), const_cast< char * >("__pyunointerface__"),
-            ustring2PyString(name).get() );
+            USTR_TO_PYSTR(name).get() );
     }
     else
     {
@@ -179,13 +179,16 @@ static PyRef createClass( const OUString
         PyRef getter = getObjectFromUnoModule( 
runtime,"_uno_struct__getattr__" );
         PyRef repr = getObjectFromUnoModule( runtime,"_uno_struct__repr__" );
         PyRef eq = getObjectFromUnoModule( runtime,"_uno_struct__eq__" );
+#if PY_MAJOR_VERSION >= 3
+        PyRef dir = getObjectFromUnoModule( runtime, "_uno_struct__dir__" );
+#endif
         
         PyObject_SetAttrString(
             ret.get(), const_cast< char * >("__pyunostruct__"),
-            ustring2PyString(name).get() );
+            USTR_TO_PYSTR(name).get() );
         PyObject_SetAttrString(
             ret.get(), const_cast< char * >("typeName"),
-            ustring2PyString(name).get() );
+            USTR_TO_PYSTR(name).get() );
         PyObject_SetAttrString(
             ret.get(), const_cast< char * >("__init__"), ctor.get() );
         PyObject_SetAttrString(
@@ -198,6 +201,10 @@ static PyRef createClass( const OUString
             ret.get(), const_cast< char * >("__str__"), repr.get() );
         PyObject_SetAttrString(
             ret.get(), const_cast< char * >("__eq__"), eq.get() );
+#if PY_MAJOR_VERSION >= 3
+        PyObject_SetAttrString(
+            ret.get(), const_cast< char * >("__dir__"), dir.get() );
+#endif
     }
     return ret;
 }
@@ -233,7 +240,7 @@ PyRef getClass( const OUString & name , 
         
         PyObject_SetAttrString(
             ret.get(), const_cast< char * >("__pyunointerface__"),
-            ustring2PyString(name).get() );
+            USTR_TO_PYSTR(name).get() );
     }
     else
     {

Modified: openoffice/trunk/main/pyuno/source/module/pyuno_impl.hxx
URL: 
http://svn.apache.org/viewvc/openoffice/trunk/main/pyuno/source/module/pyuno_impl.hxx?rev=1423272&r1=1423271&r2=1423272&view=diff
==============================================================================
--- openoffice/trunk/main/pyuno/source/module/pyuno_impl.hxx (original)
+++ openoffice/trunk/main/pyuno/source/module/pyuno_impl.hxx Tue Dec 18 
04:43:25 2012
@@ -43,6 +43,19 @@
 #include <cppuhelper/implbase2.hxx>
 #include <cppuhelper/weakref.hxx>
 
+//
+// Local workarounds for compatibility issues
+//
+#if PY_MAJOR_VERSION >= 3
+    #define PYSTR_FROMSTR               PyUnicode_FromString
+    #define USTR_TO_PYSTR               ustring2PyUnicode
+    #define PYSTR_CHECK                 PyUnicode_Check
+#else
+    #define PYSTR_FROMSTR               PyBytes_FromString
+    #define USTR_TO_PYSTR               ustring2PyString
+    #define PYSTR_CHECK                 PyBytes_Check
+#endif
+
 namespace pyuno
 {
 
@@ -161,7 +174,7 @@ PyRef getEnumClass( const Runtime &);
 PyRef getBoolClass( const Runtime &);
 PyRef getCharClass( const Runtime &);
 PyRef getByteSequenceClass( const Runtime & );
-PyRef getPyUnoClass( const Runtime &);
+PyRef getPyUnoClass();
 PyRef getClass( const rtl::OUString & name , const Runtime & runtime );
 PyRef getAnyClass( const Runtime &);
 PyObject *PyUNO_invoke( PyObject *object, const char *name , PyObject *args );

Modified: openoffice/trunk/main/pyuno/source/module/pyuno_module.cxx
URL: 
http://svn.apache.org/viewvc/openoffice/trunk/main/pyuno/source/module/pyuno_module.cxx?rev=1423272&r1=1423271&r2=1423272&view=diff
==============================================================================
--- openoffice/trunk/main/pyuno/source/module/pyuno_module.cxx (original)
+++ openoffice/trunk/main/pyuno/source/module/pyuno_module.cxx Tue Dec 18 
04:43:25 2012
@@ -225,7 +225,11 @@ PyObject * extractOneStringArg( PyObject
         return NULL;
     }
     PyObject *obj = PyTuple_GetItem( args, 0 );
+#if PY_MAJOR_VERSION >= 3
+    if( ! PyUnicode_Check(obj) )
+#else
     if( !PyBytes_Check( obj ) && ! PyUnicode_Check(obj))
+#endif
     {
         OStringBuffer buf;
         buf.append( funcName ).append( ": expecting one string argument" );
@@ -248,11 +252,11 @@ static PyObject *createUnoStructHelper(P
             PyObject *structName = PyTuple_GetItem( args,0 );
             PyObject *initializer = PyTuple_GetItem( args ,1 );
             
-            if( PyBytes_Check( structName ) )
+            if( PYSTR_CHECK( structName ) )
             {
                 if( PyTuple_Check( initializer ) )
                 {
-                    OUString typeName( 
OUString::createFromAscii(PyBytes_AsString(structName)));
+                    OUString typeName( pyString2ustring( structName ) );
                     RuntimeCargo *c = runtime.getImpl()->cargo;
                     Reference<XIdlClass> idl_class ( 
c->xCoreReflection->forName (typeName),UNO_QUERY);
                     if (idl_class.is ())
@@ -287,7 +291,7 @@ static PyObject *createUnoStructHelper(P
                     {
                         OStringBuffer buf;
                         buf.append( "UNO struct " );
-                        buf.append( PyBytes_AsString(structName) );
+                        buf.append( OUStringToOString( typeName, 
RTL_TEXTENCODING_ASCII_US ) );
                         buf.append( " is unkown" );
                         PyErr_SetString (PyExc_RuntimeError, buf.getStr());
                     }
@@ -462,9 +466,7 @@ static PyObject *getClass( PyObject *, P
     try
     {
         Runtime runtime;
-        PyRef ret = getClass(
-            OUString( PyBytes_AsString( obj), 
strlen(PyBytes_AsString(obj)),RTL_TEXTENCODING_ASCII_US),
-            runtime );
+        PyRef ret = getClass( pyString2ustring(obj), runtime );
         Py_XINCREF( ret.get() );
         return ret.get();
     }
@@ -603,9 +605,16 @@ static PyObject * invoke ( PyObject *, P
     {
         PyObject *object = PyTuple_GetItem( args, 0 );
 
-        if( PyBytes_Check( PyTuple_GetItem( args, 1 ) ) )
+        if( PYSTR_CHECK( PyTuple_GetItem( args, 1 ) ) )
         {
+#if PY_VERSION_HEX >= 0x03030000
+            const char *name = PyUnicode_AsUTF8( PyTuple_GetItem( args, 1 ) );
+#elif PY_MAJOR_VERSION >= 3
+            PyRef pUtf8(PyUnicode_AsUTF8String( PyTuple_GetItem( args, 1 ) ), 
SAL_NO_ACQUIRE);
+            const char *name = PyBytes_AsString( pUtf8.get() );
+#else
             const char *name = PyBytes_AsString( PyTuple_GetItem( args, 1 ) );
+#endif
             if( PyTuple_Check( PyTuple_GetItem( args , 2 )))
             {
                 ret = PyUNO_invoke( object, name , PyTuple_GetItem( args, 2 ) 
);
@@ -614,7 +623,11 @@ static PyObject * invoke ( PyObject *, P
             {
                 OStringBuffer buf;
                 buf.append( "uno.invoke expects a tuple as 3rd argument, got " 
);
+#if PY_MAJOR_VERSION >= 3
+                buf.append( OUStringToOString( pyString2ustring( 
PyTuple_GetItem( args, 2 ) ), RTL_TEXTENCODING_ASCII_US) );
+#else
                 buf.append( PyBytes_AsString( PyObject_Str( PyTuple_GetItem( 
args, 2) ) ) );
+#endif
                 PyErr_SetString( PyExc_RuntimeError, buf.makeStringAndClear() 
);
             }
         }
@@ -622,7 +635,11 @@ static PyObject * invoke ( PyObject *, P
         {
             OStringBuffer buf;
             buf.append( "uno.invoke expected a string as 2nd argument, got " );
+#if PY_MAJOR_VERSION >= 3
+            buf.append( OUStringToOString( pyString2ustring( PyTuple_GetItem( 
args, 1 ) ), RTL_TEXTENCODING_ASCII_US ) );
+#else
             buf.append( PyBytes_AsString( PyObject_Str( PyTuple_GetItem( args, 
1) ) ) );
+#endif
             PyErr_SetString( PyExc_RuntimeError, buf.makeStringAndClear() );
         }
     }
@@ -672,7 +689,11 @@ static PyObject *setCurrentContext( PyOb
             {
                 OStringBuffer buf;
                 buf.append( "uno.setCurrentContext expects an 
XComponentContext implementation, got " );
+#if PY_MAJOR_VERSION >= 3
+                buf.append( OUStringToOString( pyString2ustring( 
PyTuple_GetItem( args, 0 ) ), RTL_TEXTENCODING_ASCII_US ) );
+#else
                 buf.append( PyBytes_AsString( PyObject_Str( PyTuple_GetItem( 
args, 0) ) ) );
+#endif
                 PyErr_SetString( PyExc_RuntimeError, buf.makeStringAndClear() 
);
             }
         }
@@ -694,26 +715,52 @@ static PyObject *setCurrentContext( PyOb
 
 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_NOARGS, NULL}, 
+    {const_cast< char * >("_createUnoStructHelper"), createUnoStructHelper, 
METH_VARARGS, 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_NOARGS, NULL},
+    {const_cast< char * >("systemPathToFileUrl"), systemPathToFileUrl, 
METH_VARARGS, NULL},
+    {const_cast< char * >("fileUrlToSystemPath"), fileUrlToSystemPath, 
METH_VARARGS, NULL},
+    {const_cast< char * >("absolutize"), absolutize, METH_VARARGS, NULL},
+    {const_cast< char * >("isInterface"), isInterface, METH_VARARGS, NULL},
+    {const_cast< char * >("invoke"), invoke, METH_VARARGS, NULL},
+    {const_cast< char * >("setCurrentContext"), setCurrentContext, 
METH_VARARGS, NULL},
+    {const_cast< char * >("getCurrentContext"), getCurrentContext, 
METH_NOARGS, NULL},
     {NULL, NULL, 0, NULL}
 };
 
+#if PY_MAJOR_VERSION >= 3
+static struct PyModuleDef PyUNOModule =
+{
+    PyModuleDef_HEAD_INIT,
+    const_cast< char * >("pyuno"),
+    NULL,
+    -1,
+    PyUNOModule_methods
+};
+#endif
 }
 
+#if PY_MAJOR_VERSION >= 3
+extern "C" PyMODINIT_FUNC PyInit_pyuno(void)
+{
+    PyObject *m;
+    
+    PyEval_InitThreads();
+    
+    m = PyModule_Create(&PyUNOModule);
+    if (m == NULL)
+        return NULL;
+    
+    if (PyType_Ready((PyTypeObject *)getPyUnoClass().get()))
+        return NULL;
+    return m;
+}
+#else
 extern "C" PY_DLLEXPORT void initpyuno()
 {
     // noop when called already, otherwise needed to allow multiple threads
@@ -721,3 +768,4 @@ extern "C" PY_DLLEXPORT void initpyuno()
     PyEval_InitThreads();
     Py_InitModule (const_cast< char * >("pyuno"), PyUNOModule_methods);
 }
+#endif

Modified: openoffice/trunk/main/pyuno/source/module/pyuno_runtime.cxx
URL: 
http://svn.apache.org/viewvc/openoffice/trunk/main/pyuno/source/module/pyuno_runtime.cxx?rev=1423272&r1=1423271&r2=1423272&view=diff
==============================================================================
--- openoffice/trunk/main/pyuno/source/module/pyuno_runtime.cxx (original)
+++ openoffice/trunk/main/pyuno/source/module/pyuno_runtime.cxx Tue Dec 18 
04:43:25 2012
@@ -73,7 +73,11 @@ static PyTypeObject RuntimeImpl_Type =
     (printfunc) 0,
     (getattrfunc) 0,
     (setattrfunc) 0,
+#if PY_MAJOR_VERSION >= 3
+    0, 
+#else
     (cmpfunc) 0,
+#endif
     (reprfunc) 0,
     0,
     0,
@@ -154,8 +158,9 @@ static PyRef importUnoModule( ) throw ( 
         OUStringBuffer buf;
         buf.appendAscii( "python object raised an unknown exception (" );
         PyRef valueRep( PyObject_Repr( excValue.get() ), SAL_NO_ACQUIRE );
-        buf.appendAscii( PyBytes_AsString( valueRep.get())).appendAscii( ", 
traceback follows\n" );
-        buf.appendAscii( PyBytes_AsString( str.get() ) );
+        
+        buf.append( pyString2ustring( valueRep.get() ) ).appendAscii( ", 
traceback follows\n" );
+        buf.append( pyString2ustring( str.get() ) );
         throw RuntimeException( buf.makeStringAndClear(), Reference< 
XInterface > () );
     }
     PyRef dict( PyModule_GetDict( module.get() ) );
@@ -544,7 +549,7 @@ PyRef Runtime::any2PyObject (const Any &
             // assuming that the Message is always the first member, wuuuu
             void *pData = (void*)a.getValue();
             OUString message = *(OUString * )pData;
-            PyRef pymsg = ustring2PyString( message );
+            PyRef pymsg = USTR_TO_PYSTR( message );
             PyTuple_SetItem( args.get(), 0 , pymsg.getAcquired() );
             // the exception base functions want to have an "args" tuple,
             // which contains the message
@@ -662,7 +667,21 @@ Any Runtime::pyObject2Any ( const PyRef 
     {
 
     }
-#if PY_MAJOR_VERSION < 3       // Python 3 has no PyInt
+#if PY_MAJOR_VERSION >= 3      // Python 3 has no PyInt
+    else if (PyBool_Check(o))
+    {
+        if( o == Py_True )
+        {
+            sal_Bool b = sal_True;
+            a = Any( &b, getBooleanCppuType() );
+        }
+        else
+        {
+            sal_Bool b = sal_False;
+            a = Any( &b, getBooleanCppuType() );
+        }
+    }
+#else
     else if (PyInt_Check (o))
     {
         if( o == Py_True )
@@ -724,8 +743,10 @@ Any Runtime::pyObject2Any ( const PyRef 
         double d = PyFloat_AsDouble (o);
         a <<= d;
     }
+#if PY_MAJOR_VERSION < 3
     else if (PyBytes_Check (o))
        a <<= pyString2ustring(o);
+#endif
     else if( PyUnicode_Check( o ) )
        a <<= pyString2ustring(o);
     else if (PyTuple_Check (o))
@@ -750,6 +771,13 @@ Any Runtime::pyObject2Any ( const PyRef 
                 seq = Sequence<sal_Int8 > (
                     (sal_Int8*) PyBytes_AsString(str.get()), 
PyBytes_Size(str.get()));
             }
+#if PY_MAJOR_VERSION >= 3
+            else if ( PyByteArray_Check( str.get() ) )
+            {
+                seq = Sequence< sal_Int8 >(
+                    (sal_Int8 *) PyByteArray_AS_STRING(str.get()), 
PyByteArray_GET_SIZE(str.get()));
+            }
+#endif
             a <<= seq;                                                         
 
         }
         else
@@ -776,7 +804,7 @@ Any Runtime::pyObject2Any ( const PyRef 
                     Reference< XInterface > () );
             }
         }
-        else if( PyObject_IsInstance( o, getPyUnoClass( runtime ).get() ) )
+        else if( PyObject_IsInstance( o, getPyUnoClass().get() ) )
         {
             PyUNO* o_pi;
             o_pi = (PyUNO*) o;
@@ -881,7 +909,7 @@ Any Runtime::pyObject2Any ( const PyRef 
                 OUStringBuffer buf;
                 buf.appendAscii( "Couldn't convert " );
                 PyRef reprString( PyObject_Str( o ) , SAL_NO_ACQUIRE );
-                buf.appendAscii( PyBytes_AsString( reprString.get() ) );
+                buf.append( pyString2ustring( reprString.get() ) );
                 buf.appendAscii( " to a UNO type" );
                 throw RuntimeException( buf.makeStringAndClear(), Reference< 
XInterface > () );
             }
@@ -939,7 +967,7 @@ Any Runtime::extractUnoException( const 
         PyRef typeName( PyObject_Str( excType.get() ), SAL_NO_ACQUIRE );
         if( typeName.is() )
         {
-            buf.appendAscii( PyBytes_AsString( typeName.get() ) );
+            buf.append( pyString2ustring( typeName.get() ) );
         }
         else
         {
@@ -949,7 +977,7 @@ Any Runtime::extractUnoException( const 
         PyRef valueRep( PyObject_Str( excValue.get() ), SAL_NO_ACQUIRE );
         if( valueRep.is() )
         {
-            buf.appendAscii( PyBytes_AsString( valueRep.get()));
+            buf.append( pyString2ustring( valueRep.get()));
         }
         else
         {
@@ -958,7 +986,7 @@ Any Runtime::extractUnoException( const 
         buf.appendAscii( ", traceback follows\n" );
         if( str.is() )
         {
-            buf.appendAscii( PyBytes_AsString( str.get() ) );
+            buf.append( pyString2ustring( str.get() ) );
         }
         else
         {

Modified: openoffice/trunk/main/pyuno/source/module/pyuno_type.cxx
URL: 
http://svn.apache.org/viewvc/openoffice/trunk/main/pyuno/source/module/pyuno_type.cxx?rev=1423272&r1=1423271&r2=1423272&view=diff
==============================================================================
--- openoffice/trunk/main/pyuno/source/module/pyuno_type.cxx (original)
+++ openoffice/trunk/main/pyuno/source/module/pyuno_type.cxx Tue Dec 18 
04:43:25 2012
@@ -156,8 +156,11 @@ sal_Unicode PyChar2Unicode( PyObject *ob
             USTR_ASCII( "uno.Char contains an empty unicode string" ),
             Reference< XInterface > () );
     }
-
+#if PY_VERSION_HEX >= 0x03030000
+    sal_Unicode c = (sal_Unicode)PyUnicode_ReadChar( value.get(), 0 );
+#else
     sal_Unicode c = (sal_Unicode)PyUnicode_AsUnicode( value.get() )[0];
+#endif
     return c;
 }
 
@@ -166,23 +169,23 @@ Any PyEnum2Enum( PyObject *obj ) throw (
     Any ret;
     PyRef typeName( PyObject_GetAttrString( obj,const_cast< char * 
>("typeName") ), SAL_NO_ACQUIRE);
     PyRef value( PyObject_GetAttrString( obj, const_cast< char * >("value") ), 
SAL_NO_ACQUIRE);
-    if( !PyBytes_Check( typeName.get() ) || ! PyBytes_Check( value.get() ) )
+    if( !PYSTR_CHECK( typeName.get() ) || ! PYSTR_CHECK( value.get() ) )
     {
         throw RuntimeException(
             USTR_ASCII( "attributes typeName and/or value of uno.Enum are not 
strings" ),
             Reference< XInterface > () );
     }
     
-    OUString strTypeName( OUString::createFromAscii( PyBytes_AsString( 
typeName.get() ) ) );
-    char *stringValue = PyBytes_AsString( value.get() );
-
+    OUString strTypeName( pyString2ustring( typeName.get() ) );
+    OUString strValue( pyString2ustring( value.get() ) );
+    
     TypeDescription desc( strTypeName );
     if( desc.is() )
     {
         if(desc.get()->eTypeClass != typelib_TypeClass_ENUM )
         {
             OUStringBuffer buf;
-            buf.appendAscii( "pyuno.checkEnum: " 
).append(strTypeName).appendAscii( "is a " );
+            buf.appendAscii( "pyuno.checkEnum: " ).append( strTypeName 
).appendAscii( " is a " );
             buf.appendAscii(
                 typeClassToString( (com::sun::star::uno::TypeClass) 
desc.get()->eTypeClass));
             buf.appendAscii( ", expected ENUM" );
@@ -195,7 +198,7 @@ Any PyEnum2Enum( PyObject *obj ) throw (
         int i = 0;
         for( i = 0; i < pEnumDesc->nEnumValues ; i ++ )
         {
-            if( (*((OUString *)&pEnumDesc->ppEnumNames[i])).compareToAscii( 
stringValue ) == 0 )
+            if( (*((OUString *)&pEnumDesc->ppEnumNames[i])).compareTo( 
strValue ) == 0 )
             {
                 break;
             }
@@ -203,8 +206,8 @@ Any PyEnum2Enum( PyObject *obj ) throw (
         if( i == pEnumDesc->nEnumValues )
         {
             OUStringBuffer buf;
-            buf.appendAscii( "value " ).appendAscii( stringValue 
).appendAscii( "is unknown in enum " );
-            buf.appendAscii( PyBytes_AsString( typeName.get() ) );
+            buf.appendAscii( "value " ).append( strValue ).appendAscii( " is 
unknown in enum " );
+            buf.append( strTypeName );
             throw RuntimeException( buf.makeStringAndClear(), 
Reference<XInterface> () );
         }
         ret = Any( &pEnumDesc->pEnumValues[i], desc.get()->pWeakRef );
@@ -212,7 +215,7 @@ Any PyEnum2Enum( PyObject *obj ) throw (
     else
     {
         OUStringBuffer buf;
-        buf.appendAscii( "enum " ).appendAscii( 
PyBytes_AsString(typeName.get()) ).appendAscii( " is unknown" );
+        buf.appendAscii( "enum " ).append( strTypeName ).appendAscii( " is 
unknown" );
         throw RuntimeException( buf.makeStringAndClear(), Reference< 
XInterface>  () );
     }
     return ret;
@@ -222,7 +225,7 @@ Any PyEnum2Enum( PyObject *obj ) throw (
 Type PyType2Type( PyObject * o ) throw(RuntimeException )
 {
     PyRef pyName( PyObject_GetAttrString( o, const_cast< char * >("typeName") 
), SAL_NO_ACQUIRE);
-    if( !PyBytes_Check( pyName.get() ) )
+    if( !PYSTR_CHECK( pyName.get() ) )
     {
         throw RuntimeException(
             USTR_ASCII( "type object does not have typeName property" ),
@@ -232,7 +235,7 @@ Type PyType2Type( PyObject * o ) throw(R
     PyRef pyTC( PyObject_GetAttrString( o, const_cast< char * >("typeClass") 
), SAL_NO_ACQUIRE );
     Any enumValue = PyEnum2Enum( pyTC.get() );
 
-    OUString name( OUString::createFromAscii( PyBytes_AsString( pyName.get() ) 
) );
+    OUString name( pyString2ustring( pyName.get() ) );
     TypeDescription desc( name );
     if( ! desc.is() )
     {
@@ -276,10 +279,22 @@ PyObject *importToGlobal(PyObject *str, 
                 Py_INCREF( typesModule.get() );
                 PyDict_SetItemString( dict, "unotypes" , typesModule.get() );
             }
+#if PY_VERSION_HEX >= 0x03030000
+            const char *targetName = PyUnicode_AsUTF8( target );
+            const char *typeName = PyUnicode_AsUTF8( str );
+#elif PY_MAJOR_VERSION > 3
+            PyRef pUtf8( PyUnicode_AsUTF8String( target ), SAL_NO_ACQUIRE );
+            const char *targetName = PyBytes_AsString( pUtf8.get() );
+            PyRef pTypeName( PyUnicode_AsUTF8String( str ), SAL_NO_ACQUIRE );
+            const char *typeName = PyBytes_AsString( pTypeName.get() );
+#else
+            const char *targetName = PyBytes_AsString( target );
+            const char *typeName = PyBytes_AsString( str );
+#endif
             PyModule_AddObject(
                 typesModule.get(),
-                PyBytes_AsString( target ),
-                PyUNO_Type_new( PyBytes_AsString(str),tc,runtime ) );
+                targetName,
+                PyUNO_Type_new( typeName, tc, runtime ) );
 
             if( com::sun::star::uno::TypeClass_EXCEPTION == tc ||
                 com::sun::star::uno::TypeClass_STRUCT    == tc )
@@ -296,9 +311,17 @@ PyObject *importToGlobal(PyObject *str, 
                 {
                     OString enumElementName(
                         OUStringToOString( pDesc->ppEnumNames[i], 
RTL_TEXTENCODING_ASCII_US) );
+#if PY_VERSION_HEX >= 0x03030000
+                    const char *name = PyUnicode_AsUTF8(str);
+#elif PY_MAJOR_VERSION > 3
+                    PyRef *pUtf8( PyUnicode_AsUTF8String( str ), 
SAL_NO_ACQUIRE );
+                    const char *name = PyBytes_AsString( pUtf8.get() );
+#else
+                    const char *name = PyBytes_AsString(str);
+#endif
                     PyDict_SetItemString(
                         dict, (char*)enumElementName.getStr(),
-                        PyUNO_Enum_new(PyBytes_AsString(str) , 
enumElementName.getStr(), runtime ) );
+                        PyUNO_Enum_new(name, enumElementName.getStr(), runtime 
) );
                 }
             }
             Py_INCREF( Py_None );
@@ -318,9 +341,11 @@ PyObject *importToGlobal(PyObject *str, 
                 }
                 else
                 {
-                    OStringBuffer buf;
-                    buf.append( "constant " 
).append(PyBytes_AsString(str)).append(  " unknown" );
-                    PyErr_SetString( PyExc_RuntimeError, buf.getStr() );
+                    OUStringBuffer buf;
+                    buf.appendAscii( "constant " 
).append(pyString2ustring(str)).appendAscii(  " unknown" );
+                    PyErr_SetString( 
+                        PyExc_RuntimeError, 
+                        OUStringToOString( buf.makeStringAndClear(), 
RTL_TEXTENCODING_UTF8).getStr() );
                 }
             }
             else
@@ -379,8 +404,8 @@ static PyObject* callCtor( const Runtime
 PyObject *PyUNO_Enum_new( const char *enumBase, const char *enumValue, const 
Runtime &r )
 {
     PyRef args( PyTuple_New( 2 ), SAL_NO_ACQUIRE );
-    PyTuple_SetItem( args.get() , 0 , PyBytes_FromString( enumBase ) );
-    PyTuple_SetItem( args.get() , 1 , PyBytes_FromString( enumValue ) );
+    PyTuple_SetItem( args.get() , 0 , PYSTR_FROMSTR( enumBase ) );
+    PyTuple_SetItem( args.get() , 1 , PYSTR_FROMSTR( enumValue ) );
 
     return callCtor( r, "Enum" , args );
 }
@@ -391,7 +416,7 @@ PyObject* PyUNO_Type_new (const char *ty
     // retrieve type object
     PyRef args( PyTuple_New( 2 ), SAL_NO_ACQUIRE );
 
-    PyTuple_SetItem( args.get() , 0 , PyBytes_FromString( typeName ) );
+    PyTuple_SetItem( args.get() , 0 , PYSTR_FROMSTR( typeName ) );
     PyObject *typeClass = PyUNO_Enum_new( "com.sun.star.uno.TypeClass" , 
typeClassToString(t), r );
     if( ! typeClass )
         return NULL;
@@ -405,10 +430,16 @@ PyObject* PyUNO_char_new ( sal_Unicode v
     // retrieve type object
     PyRef args( PyTuple_New( 1 ), SAL_NO_ACQUIRE );
 
+#if PY_VERSION_HEX >= 0x03030000
+    Py_UCS2 u[1];
+    u[0] = val;
+    PyTuple_SetItem( args.get(), 0, PyUnicode_FromKindAndData( 
PyUnicode_2BYTE_KIND, u, 1 ) );
+#else
     Py_UNICODE u[2];
     u[0] = val;
     u[1] = 0;
     PyTuple_SetItem( args.get() , 0 , PyUnicode_FromUnicode( u ,1) );
+#endif
 
     return callCtor( r, "Char" , args );
 }

Modified: openoffice/trunk/main/pyuno/source/module/pyuno_util.cxx
URL: 
http://svn.apache.org/viewvc/openoffice/trunk/main/pyuno/source/module/pyuno_util.cxx?rev=1423272&r1=1423271&r2=1423272&view=diff
==============================================================================
--- openoffice/trunk/main/pyuno/source/module/pyuno_util.cxx (original)
+++ openoffice/trunk/main/pyuno/source/module/pyuno_util.cxx Tue Dec 18 
04:43:25 2012
@@ -61,6 +61,7 @@ namespace pyuno
 PyRef ustring2PyUnicode( const OUString & str )
 {
     PyRef ret;
+
 #if Py_UNICODE_SIZE == 2
     // YD force conversion since python/2 uses wchar_t
     ret = PyRef( PyUnicode_FromUnicode( (const Py_UNICODE*)str.getStr(), 
str.getLength() ), SAL_NO_ACQUIRE );
@@ -85,10 +86,16 @@ OUString pyString2ustring( PyObject *pys
 #if Py_UNICODE_SIZE == 2
        ret = OUString( (sal_Unicode * ) PyUnicode_AS_UNICODE( pystr ) );
 #else
+#if PY_VERSION_HEX >= 0x03030000
+    Py_ssize_t size;
+    char *pUtf8 = PyUnicode_AsUTF8AndSize(pystr, &size);
+    ret = OUString(pUtf8, size, RTL_TEXTENCODING_UTF8);
+#else
        PyObject* pUtf8 = PyUnicode_AsUTF8String(pystr);
        ret = OUString(PyBytes_AsString(pUtf8), PyBytes_Size(pUtf8), 
RTL_TEXTENCODING_UTF8);
        Py_DECREF(pUtf8);
 #endif
+#endif
     }
     else
     {

Modified: openoffice/trunk/main/pyuno/source/module/uno.py
URL: 
http://svn.apache.org/viewvc/openoffice/trunk/main/pyuno/source/module/uno.py?rev=1423272&r1=1423271&r2=1423272&view=diff
==============================================================================
--- openoffice/trunk/main/pyuno/source/module/uno.py (original)
+++ openoffice/trunk/main/pyuno/source/module/uno.py Tue Dec 18 04:43:25 2012
@@ -21,10 +21,15 @@
 import sys
 
 import pyuno
-import __builtin__
+try:
+    import __builtin__ as builtins
+except:
+    import builtins
 
 try:
     unicode
+    bytes = str
+    bytearray = str
 except NameError:
     unicode = str
 
@@ -33,7 +38,7 @@ import socket # since on Windows sal3.dl
 # all functions and variables starting with a underscore (_) must be 
considered private
 # and can be changed at any time. Don't use them
 _g_ctx = pyuno.getComponentContext( )
-_g_delegatee = __builtin__.__dict__["__import__"]
+_g_delegatee = builtins.__dict__["__import__"]
 
 def getComponentContext():
     """ returns the UNO component context, that was used to initialize the 
python runtime.
@@ -179,7 +184,7 @@ class Char:
 
 class ByteSequence:
     def __init__(self, value):
-        if isinstance(value, str):
+        if isinstance(value, (bytes, bytearray)):
             self.value = value
         elif isinstance(value, ByteSequence):
             self.value = value.value
@@ -192,7 +197,7 @@ class ByteSequence:
     def __eq__(self, that):
         if isinstance( that, ByteSequence):
             return self.value == that.value
-        if isinstance(that, str):
+        elif isinstance(that, (bytes, bytearray)):
             return self.value == that
         return False
 
@@ -206,7 +211,7 @@ class ByteSequence:
         return self.value.__iter__()
 
     def __add__( self , b ):
-        if isinstance( b, str ):
+        if isinstance( b, (bytes, bytearray) ):
             return ByteSequence( self.value + b )
         elif isinstance( b, ByteSequence ):
             return ByteSequence( self.value + b.value )
@@ -251,7 +256,7 @@ def _uno_import( name, *optargs, **kwarg
         else:
             mod = pyuno.__class__(x)  # How to create a module ??
         d = mod.__dict__
-
+    
     RuntimeException = pyuno.getClass( "com.sun.star.uno.RuntimeException" )
     for x in fromlist:
         if x not in d:
@@ -278,7 +283,7 @@ def _uno_import( name, *optargs, **kwarg
     return mod
 
 # hook into the __import__ chain
-__builtin__.__dict__["__import__"] = _uno_import
+builtins.__dict__["__import__"] = _uno_import
 
 # private, referenced from the pyuno shared library
 def _uno_struct__init__(self,*args):
@@ -289,11 +294,11 @@ def _uno_struct__init__(self,*args):
 
 # private, referenced from the pyuno shared library
 def _uno_struct__getattr__(self,name):
-    return __builtin__.getattr(self.__dict__["value"],name)
+    return getattr(self.__dict__["value"],name)
 
 # private, referenced from the pyuno shared library
 def _uno_struct__setattr__(self,name,value):
-    return __builtin__.setattr(self.__dict__["value"],name,value)
+    return setattr(self.__dict__["value"],name,value)
 
 # private, referenced from the pyuno shared library
 def _uno_struct__repr__(self):
@@ -308,6 +313,10 @@ def _uno_struct__eq__(self,cmp):
         return self.__dict__["value"] == cmp.__dict__["value"]
     return False
 
+def _uno_struct__dir__(self):
+    return dir(self.__dict__["value"]) + list(self.__dict__.keys()) + \
+                list(self.__class__.__dict__.keys())
+
 # referenced from pyuno shared lib and pythonscript.py
 def _uno_extract_printable_stacktrace( trace ):
     mod = None


Reply via email to