[Libreoffice-commits] .: 9 commits - i18npool/source pyuno/source scripting/source

Lionel Elie Mamane lmamane at kemper.freedesktop.org
Sat Aug 20 23:08:12 PDT 2011


 i18npool/source/breakiterator/gendict.cxx   |    2 
 pyuno/source/loader/pyuno_loader.cxx        |    2 
 pyuno/source/module/pyuno.cxx               |    4 
 pyuno/source/module/pyuno_callable.cxx      |    2 
 pyuno/source/module/pyuno_except.cxx        |   26 +--
 pyuno/source/module/pyuno_module.cxx        |  216 ++++++++++++++++++++--------
 pyuno/source/module/pyuno_runtime.cxx       |   70 +++++----
 pyuno/source/module/pyuno_type.cxx          |   12 -
 pyuno/source/module/uno.py                  |   43 +++--
 scripting/source/provider/ProviderCache.cxx |    3 
 10 files changed, 255 insertions(+), 125 deletions(-)

New commits:
commit 2fa3cac022c6003b2e3268ad8289a413b2c7c687
Author: Lionel Elie Mamane <lionel at mamane.lu>
Date:   Sun Aug 21 07:59:22 2011 +0200

    check array index *before* using it in array, not *after*

diff --git a/i18npool/source/breakiterator/gendict.cxx b/i18npool/source/breakiterator/gendict.cxx
index 5c2f382..a582cd5 100644
--- a/i18npool/source/breakiterator/gendict.cxx
+++ b/i18npool/source/breakiterator/gendict.cxx
@@ -169,7 +169,7 @@ static inline void printIndex2(FILE *source_fp, sal_Int16 *set)
             for (sal_Int32 j = 0; j < 0x100; j++) {
                 sal_Int32 k = (i<<8) + j;
                 if (prev != 0 )
-                    while( charArray[k] == 0 && k < 0x10000 )
+                    while( k < 0x10000 && charArray[k] == 0 )
                         k++;
 
                 prev = charArray[(i<<8) + j];
commit eb6621d43753b07d002aaaa8ce1ae22e8d2ab316
Author: Lionel Elie Mamane <lionel at mamane.lu>
Date:   Sat Aug 20 18:03:34 2011 +0200

    scripting: make a debug build log uncaught exception when loading a provider
    
    Also put a newline between "Error creating provider from factory" and message of the exception raised by the provider load

diff --git a/scripting/source/provider/ProviderCache.cxx b/scripting/source/provider/ProviderCache.cxx
index 26b7746..5a3e420 100644
--- a/scripting/source/provider/ProviderCache.cxx
+++ b/scripting/source/provider/ProviderCache.cxx
@@ -128,6 +128,7 @@ ProviderCache::getAllProviders() throw ( RuntimeException )
                 {
                     ::rtl::OUString temp = OUSTR( "ProviderCache::getAllProviders: failed to create provider, " );
                     temp.concat( e.Message );
+                    DBG_UNHANDLED_EXCEPTION();
                     //throw RuntimeException( temp.concat( e.Message ),
                     //    Reference< XInterface >() );
                 }
@@ -207,7 +208,7 @@ ProviderCache::createProvider( ProviderDetails& details ) throw ( RuntimeExcepti
     }
     catch ( RuntimeException& e )
     {
-        ::rtl::OUString temp(RTL_CONSTASCII_USTRINGPARAM("ProviderCache::createProvider() Error creating provider from factory!!!"));
+        ::rtl::OUString temp(RTL_CONSTASCII_USTRINGPARAM("ProviderCache::createProvider() Error creating provider from factory!!!\n"));
         throw RuntimeException( temp.concat( e.Message ), Reference< XInterface >() );
     }
 
commit ac2359cf8440c3e04c08566fdf576850f83e6601
Author: Lionel Elie Mamane <lionel at mamane.lu>
Date:   Sat Aug 20 18:00:52 2011 +0200

    pyuno: close opened parenthesis in raised exception message

diff --git a/pyuno/source/module/pyuno_runtime.cxx b/pyuno/source/module/pyuno_runtime.cxx
index b62181e..c09cc5c 100644
--- a/pyuno/source/module/pyuno_runtime.cxx
+++ b/pyuno/source/module/pyuno_runtime.cxx
@@ -166,6 +166,7 @@ static PyRef importUnoModule( ) throw ( RuntimeException )
         PyRef valueRep( PyObject_Repr( excValue.get() ), SAL_NO_ACQUIRE );
         buf.appendAscii( PyString_AsString( valueRep.get())).appendAscii( ", traceback follows\n" );
         buf.appendAscii( PyString_AsString( str.get() ) );
+        buf.appendAscii( ")" );
         throw RuntimeException( buf.makeStringAndClear(), Reference< XInterface > () );
     }
     PyRef dict( PyModule_GetDict( module.get() ) );
commit 21192c6ea981a7f2abb03b53381ecf67980ddb65
Author: Lionel Elie Mamane <lionel at mamane.lu>
Date:   Sat Aug 20 17:44:53 2011 +0200

    pyuno: some comments

diff --git a/pyuno/source/module/pyuno_runtime.cxx b/pyuno/source/module/pyuno_runtime.cxx
index 5cac9a6..b62181e 100644
--- a/pyuno/source/module/pyuno_runtime.cxx
+++ b/pyuno/source/module/pyuno_runtime.cxx
@@ -156,7 +156,10 @@ static PyRef importUnoModule( ) throw ( RuntimeException )
     {
         PyRef excType, excValue, excTraceback;
         PyErr_Fetch( (PyObject **)&excType, (PyObject**)&excValue,(PyObject**)&excTraceback);
-        PyRef str( PyObject_Repr( excTraceback.get() ), SAL_NO_ACQUIRE );
+        // As of Python 2.7 this gives a rather non-useful "<traceback object at 0xADDRESS>",
+        // but it is the best we can do in the absence of uno._uno_extract_printable_stacktrace
+        // Who knows, a future Python might print something better.
+        PyRef str( PyObject_Str( excTraceback.get() ), SAL_NO_ACQUIRE );
 
         OUStringBuffer buf;
         buf.appendAscii( "python object raised an unknown exception (" );
commit 58aa95c94459aec8cb467f3d6ec8ac9491c7a46c
Author: Lionel Elie Mamane <lionel at mamane.lu>
Date:   Sat Aug 20 17:33:37 2011 +0200

    Janitorial: remove unnecessary const_casts
    
    The python C API has consts at these places

diff --git a/pyuno/source/loader/pyuno_loader.cxx b/pyuno/source/loader/pyuno_loader.cxx
index 4e65202..f7a909f 100644
--- a/pyuno/source/loader/pyuno_loader.cxx
+++ b/pyuno/source/loader/pyuno_loader.cxx
@@ -76,7 +76,7 @@ static void raiseRuntimeExceptionWhenNeeded() throw ( RuntimeException )
 static PyRef getLoaderModule() throw( RuntimeException )
 {
     PyRef module(
-        PyImport_ImportModule( const_cast< char * >("pythonloader") ),
+        PyImport_ImportModule( "pythonloader" ),
         SAL_NO_ACQUIRE );
     raiseRuntimeExceptionWhenNeeded();
     if( !module.is() )
diff --git a/pyuno/source/module/pyuno.cxx b/pyuno/source/module/pyuno.cxx
index 2df863d..2bfbe7b 100644
--- a/pyuno/source/module/pyuno.cxx
+++ b/pyuno/source/module/pyuno.cxx
@@ -373,7 +373,7 @@ PyObject *PyUNO_invoke( PyObject *object, const char *name , PyObject *args )
                 if( PyObject_IsInstance( element , getAnyClass( runtime ).get() ) )
                 {
                     element = PyObject_GetAttrString(
-                        element, const_cast< char * >("value") );
+                        element, "value" );
                 }
                 else
                 {
@@ -647,7 +647,7 @@ static PyObject* PyUNO_cmp( PyObject *self, PyObject *that, int op )
 static PyTypeObject PyUNOType =
 {
     PyVarObject_HEAD_INIT( &PyType_Type, 0 )
-    const_cast< char * >("pyuno"),
+    "pyuno",
     sizeof (PyUNO),
     0,
     (destructor) PyUNO_del,
diff --git a/pyuno/source/module/pyuno_callable.cxx b/pyuno/source/module/pyuno_callable.cxx
index 2bd2a7d..e5c943f 100644
--- a/pyuno/source/module/pyuno_callable.cxx
+++ b/pyuno/source/module/pyuno_callable.cxx
@@ -197,7 +197,7 @@ PyObject* PyUNO_callable_call (PyObject* self, PyObject* args, PyObject*)
 static PyTypeObject PyUNO_callable_Type =
 {
     PyVarObject_HEAD_INIT( &PyType_Type, 0 )
-    const_cast< char * >("PyUNO_callable"),
+    "PyUNO_callable",
     sizeof (PyUNO_callable),
     0,
     (destructor) ::pyuno::PyUNO_callable_del,
diff --git a/pyuno/source/module/pyuno_except.cxx b/pyuno/source/module/pyuno_except.cxx
index 16aed89..97b876f 100644
--- a/pyuno/source/module/pyuno_except.cxx
+++ b/pyuno/source/module/pyuno_except.cxx
@@ -174,7 +174,7 @@ static PyRef createClass( const OUString & name, const Runtime &runtime )
     if( isInterface )
     {
         PyObject_SetAttrString(
-            ret.get(), const_cast< char * >("__pyunointerface__"),
+            ret.get(), "__pyunointerface__",
             ustring2PyString(name).get() );
     }
     else
@@ -186,23 +186,23 @@ static PyRef createClass( const OUString & name, const Runtime &runtime )
         PyRef eq = getObjectFromUnoModule( runtime,"_uno_struct__eq__" );
 
         PyObject_SetAttrString(
-            ret.get(), const_cast< char * >("__pyunostruct__"),
+            ret.get(), "__pyunostruct__",
             ustring2PyString(name).get() );
         PyObject_SetAttrString(
-            ret.get(), const_cast< char * >("typeName"),
+            ret.get(), "typeName",
             ustring2PyString(name).get() );
         PyObject_SetAttrString(
-            ret.get(), const_cast< char * >("__init__"), ctor.get() );
+            ret.get(), "__init__", ctor.get() );
         PyObject_SetAttrString(
-            ret.get(), const_cast< char * >("__getattr__"), getter.get() );
+            ret.get(), "__getattr__", getter.get() );
         PyObject_SetAttrString(
-            ret.get(), const_cast< char * >("__setattr__"), setter.get() );
+            ret.get(), "__setattr__", setter.get() );
         PyObject_SetAttrString(
-            ret.get(), const_cast< char * >("__repr__"), repr.get() );
+            ret.get(), "__repr__", repr.get() );
         PyObject_SetAttrString(
-            ret.get(), const_cast< char * >("__str__"), repr.get() );
+            ret.get(), "__str__", repr.get() );
         PyObject_SetAttrString(
-            ret.get(), const_cast< char * >("__eq__"), eq.get() );
+            ret.get(), "__eq__", eq.get() );
     }
     return ret;
 }
@@ -210,10 +210,10 @@ static PyRef createClass( const OUString & name, const Runtime &runtime )
 bool isInstanceOfStructOrException( PyObject *obj)
 {
     PyRef attr(
-        PyObject_GetAttrString(obj, const_cast< char * >("__class__")),
+        PyObject_GetAttrString(obj, "__class__"),
         SAL_NO_ACQUIRE );
     return PyObject_HasAttrString(
-        attr.get(), const_cast< char * >("__pyunostruct__"));
+        attr.get(), "__pyunostruct__");
 }
 
 sal_Bool isInterfaceClass( const Runtime &runtime, PyObject * obj )
@@ -233,11 +233,11 @@ PyRef getClass( const OUString & name , const Runtime &runtime)
         ret = createClass( name, runtime );
         cargo->exceptionMap[name] = ret;
         if( PyObject_HasAttrString(
-                ret.get(), const_cast< char * >("__pyunointerface__") ) )
+                ret.get(), "__pyunointerface__" ) )
             cargo->interfaceSet.insert( ret );
 
         PyObject_SetAttrString(
-            ret.get(), const_cast< char * >("__pyunointerface__"),
+            ret.get(), "__pyunointerface__",
             ustring2PyString(name).get() );
     }
     else
diff --git a/pyuno/source/module/pyuno_module.cxx b/pyuno/source/module/pyuno_module.cxx
index 973ef00..a4144d9 100644
--- a/pyuno/source/module/pyuno_module.cxx
+++ b/pyuno/source/module/pyuno_module.cxx
@@ -447,7 +447,7 @@ static PyObject *getTypeByName( PyObject *, PyObject *args )
     {
         char *name;
 
-        if (PyArg_ParseTuple (args, const_cast< char * >("s"), &name))
+        if (PyArg_ParseTuple (args, "s", &name))
         {
             OUString typeName ( OUString::createFromAscii( name ) );
             TypeDescription typeDesc( typeName );
@@ -479,7 +479,7 @@ static PyObject *getConstantByName( PyObject *, PyObject *args )
     {
         char *name;
 
-        if (PyArg_ParseTuple (args, const_cast< char * >("s"), &name))
+        if (PyArg_ParseTuple (args, "s", &name))
         {
             OUString typeName ( OUString::createFromAscii( name ) );
             Runtime runtime;
@@ -801,21 +801,21 @@ static PyObject *setCurrentContext( PyObject *, PyObject * args )
 
 struct PyMethodDef PyUNOModule_methods [] =
 {
-    {const_cast< char * >("getComponentContext"), getComponentContext, METH_VARARGS, NULL},
-    {const_cast< char * >("_createUnoStructHelper"), reinterpret_cast<PyCFunction>(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},
+    {"getComponentContext", getComponentContext, METH_VARARGS, NULL},
+    {"_createUnoStructHelper", reinterpret_cast<PyCFunction>(createUnoStructHelper), METH_VARARGS | METH_KEYWORDS, NULL},
+    {"getTypeByName", getTypeByName, METH_VARARGS, NULL},
+    {"getConstantByName", getConstantByName, METH_VARARGS, NULL},
+    {"getClass", getClass, METH_VARARGS, NULL},
+    {"checkEnum", checkEnum, METH_VARARGS, NULL},
+    {"checkType", checkType, METH_VARARGS, NULL},
+    {"generateUuid", generateUuid, METH_VARARGS, NULL},
+    {"systemPathToFileUrl", systemPathToFileUrl, METH_VARARGS, NULL},
+    {"fileUrlToSystemPath", fileUrlToSystemPath, METH_VARARGS, NULL},
+    {"absolutize", absolutize, METH_VARARGS | METH_KEYWORDS, NULL},
+    {"isInterface", isInterface, METH_VARARGS, NULL},
+    {"invoke", invoke, METH_VARARGS | METH_KEYWORDS, NULL},
+    {"setCurrentContext", setCurrentContext, METH_VARARGS, NULL},
+    {"getCurrentContext", getCurrentContext, METH_VARARGS, NULL},
     {NULL, NULL, 0, NULL}
 };
 
@@ -845,7 +845,7 @@ PyObject* PyInit_pyuno()
 void initpyuno()
 {
     PyEval_InitThreads();
-    Py_InitModule (const_cast< char * >("pyuno"), PyUNOModule_methods);
+    Py_InitModule ("pyuno", PyUNOModule_methods);
 }
 #endif /* PY_MAJOR_VERSION >= 3 */
 
diff --git a/pyuno/source/module/pyuno_runtime.cxx b/pyuno/source/module/pyuno_runtime.cxx
index 3670e42..5cac9a6 100644
--- a/pyuno/source/module/pyuno_runtime.cxx
+++ b/pyuno/source/module/pyuno_runtime.cxx
@@ -74,7 +74,7 @@ namespace pyuno
 static PyTypeObject RuntimeImpl_Type =
 {
     PyVarObject_HEAD_INIT (&PyType_Type, 0)
-    const_cast< char * >("pyuno_runtime"),
+    "pyuno_runtime",
     sizeof (RuntimeImpl),
     0,
     (destructor) RuntimeImpl::del,
@@ -138,7 +138,7 @@ static void getRuntimeImpl( PyRef & globalDict, PyRef &runtimeImpl )
                                 Reference< XInterface > () );
     }
 
-    globalDict = PyRef( PyModule_GetDict(PyImport_AddModule(const_cast< char * >("__main__"))));
+    globalDict = PyRef( PyModule_GetDict(PyImport_AddModule("__main__")));
 
     if( ! globalDict.is() ) // FATAL !
     {
@@ -151,7 +151,7 @@ static void getRuntimeImpl( PyRef & globalDict, PyRef &runtimeImpl )
 static PyRef importUnoModule( ) throw ( RuntimeException )
 {
     // import the uno module
-    PyRef module( PyImport_ImportModule( const_cast< char * >("uno") ), SAL_NO_ACQUIRE );
+    PyRef module( PyImport_ImportModule( "uno" ), SAL_NO_ACQUIRE );
     if( PyErr_Occurred() )
     {
         PyRef excType, excValue, excTraceback;
@@ -551,7 +551,7 @@ PyRef Runtime::any2PyObject (const Any &a ) const
             PyTuple_SetItem( args.get(), 0 , pymsg.getAcquired() );
             // the exception base functions want to have an "args" tuple,
             // which contains the message
-            PyObject_SetAttrString( ret.get(), const_cast< char * >("args"), args.get() );
+            PyObject_SetAttrString( ret.get(), "args", args.get() );
         }
         return ret;
     }
@@ -626,7 +626,7 @@ static Sequence< Type > invokeGetTypes( const Runtime & r , PyObject * o )
 {
     Sequence< Type > ret;
 
-    PyRef method( PyObject_GetAttrString( o , const_cast< char * >("getTypes") ), SAL_NO_ACQUIRE );
+    PyRef method( PyObject_GetAttrString( o , "getTypes" ), SAL_NO_ACQUIRE );
     raiseInvocationTargetExceptionWhenNeeded( r );
     if( method.is() && PyCallable_Check( method.get() ) )
     {
@@ -765,7 +765,7 @@ Any Runtime::pyObject2Any ( const PyRef & source, enum ConversionMode mode ) con
         // should be removed, in case ByteSequence gets derived from String
         if( PyObject_IsInstance( o, getByteSequenceClass( runtime ).get() ) )
         {
-            PyRef str(PyObject_GetAttrString( o , const_cast< char * >("value") ),SAL_NO_ACQUIRE);
+            PyRef str(PyObject_GetAttrString( o , "value" ),SAL_NO_ACQUIRE);
             Sequence< sal_Int8 > seq;
             if( PyString_Check( str.get() ) )
             {
@@ -786,7 +786,7 @@ Any Runtime::pyObject2Any ( const PyRef & source, enum ConversionMode mode ) con
         }
         else if( isInstanceOfStructOrException( o ) )
         {
-            PyRef struc(PyObject_GetAttrString( o , const_cast< char * >("value") ),SAL_NO_ACQUIRE);
+            PyRef struc(PyObject_GetAttrString( o , "value" ),SAL_NO_ACQUIRE);
             PyUNO * obj = (PyUNO*)struc.get();
             Reference< XMaterialHolder > holder( obj->members->xInvocation, UNO_QUERY );
             if( holder.is( ) )
@@ -832,9 +832,9 @@ Any Runtime::pyObject2Any ( const PyRef & source, enum ConversionMode mode ) con
         {
             if( ACCEPT_UNO_ANY == mode )
             {
-                a = pyObject2Any( PyRef( PyObject_GetAttrString( o , const_cast< char * >("value") ), SAL_NO_ACQUIRE) );
+                a = pyObject2Any( PyRef( PyObject_GetAttrString( o , "value" ), SAL_NO_ACQUIRE) );
                 Type t;
-                pyObject2Any( PyRef( PyObject_GetAttrString( o, const_cast< char * >("type") ), SAL_NO_ACQUIRE ) ) >>= t;
+                pyObject2Any( PyRef( PyObject_GetAttrString( o, "type" ), SAL_NO_ACQUIRE ) ) >>= t;
 
                 try
                 {
diff --git a/pyuno/source/module/pyuno_type.cxx b/pyuno/source/module/pyuno_type.cxx
index 3f9f004..8dac1a1 100644
--- a/pyuno/source/module/pyuno_type.cxx
+++ b/pyuno/source/module/pyuno_type.cxx
@@ -147,7 +147,7 @@ PyRef getAnyClass( const Runtime & r )
 
 sal_Unicode PyChar2Unicode( PyObject *obj ) throw ( RuntimeException )
 {
-    PyRef value( PyObject_GetAttrString( obj, const_cast< char * >("value") ), SAL_NO_ACQUIRE );
+    PyRef value( PyObject_GetAttrString( obj, "value" ), SAL_NO_ACQUIRE );
     if( ! PyUnicode_Check( value.get() ) )
     {
         throw RuntimeException(
@@ -169,8 +169,8 @@ sal_Unicode PyChar2Unicode( PyObject *obj ) throw ( RuntimeException )
 Any PyEnum2Enum( PyObject *obj ) throw ( RuntimeException )
 {
     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);
+    PyRef typeName( PyObject_GetAttrString( obj,"typeName" ), SAL_NO_ACQUIRE);
+    PyRef value( PyObject_GetAttrString( obj, "value" ), SAL_NO_ACQUIRE);
     if( !PyString_Check( typeName.get() ) || ! PyString_Check( value.get() ) )
     {
         throw RuntimeException(
@@ -226,7 +226,7 @@ Any PyEnum2Enum( PyObject *obj ) throw ( RuntimeException )
 
 Type PyType2Type( PyObject * o ) throw(RuntimeException )
 {
-    PyRef pyName( PyObject_GetAttrString( o, const_cast< char * >("typeName") ), SAL_NO_ACQUIRE);
+    PyRef pyName( PyObject_GetAttrString( o, "typeName" ), SAL_NO_ACQUIRE);
     if( !PyString_Check( pyName.get() ) )
     {
         throw RuntimeException(
@@ -234,7 +234,7 @@ Type PyType2Type( PyObject * o ) throw(RuntimeException )
             Reference< XInterface > () );
     }
 
-    PyRef pyTC( PyObject_GetAttrString( o, const_cast< char * >("typeClass") ), SAL_NO_ACQUIRE );
+    PyRef pyTC( PyObject_GetAttrString( o, "typeClass" ), SAL_NO_ACQUIRE );
     Any enumValue = PyEnum2Enum( pyTC.get() );
 
     OUString name( OUString::createFromAscii( PyString_AsString( pyName.get() ) ) );
@@ -277,7 +277,7 @@ PyObject *importToGlobal(PyObject *str, PyObject *dict, PyObject *target)
             PyRef typesModule( PyDict_GetItemString( dict, "unotypes" ) );
             if( ! typesModule.is() || ! PyModule_Check( typesModule.get() ))
             {
-                typesModule = PyRef( PyModule_New( const_cast< char * >("unotypes") ), SAL_NO_ACQUIRE );
+                typesModule = PyRef( PyModule_New( "unotypes" ), SAL_NO_ACQUIRE );
                 Py_INCREF( typesModule.get() );
                 PyDict_SetItemString( dict, "unotypes" , typesModule.get() );
             }
commit d269a182506cad8f11e9631229d4dc20f5e33abe
Author: Lionel Elie Mamane <lionel at mamane.lu>
Date:   Sat Aug 20 17:24:15 2011 +0200

    Janitorial: remove unused variable

diff --git a/pyuno/source/module/pyuno_runtime.cxx b/pyuno/source/module/pyuno_runtime.cxx
index 0e339f0..3670e42 100644
--- a/pyuno/source/module/pyuno_runtime.cxx
+++ b/pyuno/source/module/pyuno_runtime.cxx
@@ -150,7 +150,6 @@ static void getRuntimeImpl( PyRef & globalDict, PyRef &runtimeImpl )
 
 static PyRef importUnoModule( ) throw ( RuntimeException )
 {
-    PyRef globalDict = PyRef( PyModule_GetDict(PyImport_AddModule(const_cast< char * >("__main__"))));
     // import the uno module
     PyRef module( PyImport_ImportModule( const_cast< char * >("uno") ), SAL_NO_ACQUIRE );
     if( PyErr_Occurred() )
commit fa43b7742227a74c2bfb83c5147ac6eb69e7ef20
Author: Lionel Elie Mamane <lionel at mamane.lu>
Date:   Sat Aug 20 17:14:24 2011 +0200

    pyuno: make extractUnoException handle exceptions raised by uno.py loading
    
    This allows having a meaningful error message when extractUnoException
    is called from pyuno_loader::getLoaderModule() (via
    raiseRuntimeExceptionWhenNeeded()). If it is called to treat an error
    that cropped up in loading uno.py, the old code would abort the whole
    operation by throwing an exception because... it gets essentially the
    same error. The new code leads to a sensible message on the Python
    debug console.

diff --git a/pyuno/source/module/pyuno_runtime.cxx b/pyuno/source/module/pyuno_runtime.cxx
index 61d05d8..0e339f0 100644
--- a/pyuno/source/module/pyuno_runtime.cxx
+++ b/pyuno/source/module/pyuno_runtime.cxx
@@ -1,4 +1,4 @@
-/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */
+/* -*- Mode: C++; eval:(c-set-style "bsd"); tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */
 /*************************************************************************
  *
  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
@@ -53,6 +53,7 @@ using com::sun::star::uno::TypeDescription;
 using com::sun::star::uno::Sequence;
 using com::sun::star::uno::Type;
 using com::sun::star::uno::UNO_QUERY;
+using com::sun::star::uno::Exception;
 using com::sun::star::uno::RuntimeException;
 using com::sun::star::uno::XComponentContext;
 using com::sun::star::lang::XSingleServiceFactory;
@@ -914,41 +915,56 @@ Any Runtime::pyObject2Any ( const PyRef & source, enum ConversionMode mode ) con
 
 Any Runtime::extractUnoException( const PyRef & excType, const PyRef &excValue, const PyRef &excTraceback) const
 {
-    PyRef str;
+    OUString str;
     Any ret;
     if( excTraceback.is() )
     {
-        PyRef unoModule( impl ? impl->cargo->getUnoModule() : 0 );
+        Exception e;
+        PyRef unoModule;
+        if ( impl )
+        {
+            try
+            {
+                unoModule = impl->cargo->getUnoModule();
+            }
+            catch (Exception ei)
+            {
+                e=ei;
+            }
+        }
         if( unoModule.is() )
         {
             PyRef extractTraceback(
                 PyDict_GetItemString(unoModule.get(),"_uno_extract_printable_stacktrace" ) );
 
-            if( extractTraceback.is() )
+            if( PyCallable_Check(extractTraceback.get()) )
             {
                 PyRef args( PyTuple_New( 1), SAL_NO_ACQUIRE );
                 PyTuple_SetItem( args.get(), 0, excTraceback.getAcquired() );
-                str = PyRef( PyObject_CallObject( extractTraceback.get(),args.get() ), SAL_NO_ACQUIRE);
+                PyRef pyStr( PyObject_CallObject( extractTraceback.get(),args.get() ), SAL_NO_ACQUIRE);
+                str = rtl::OUString::createFromAscii( PyString_AsString(pyStr.get()) );
             }
             else
             {
-                str = PyRef(
-                    PyString_FromString( "Couldn't find uno._uno_extract_printable_stacktrace" ),
-                    SAL_NO_ACQUIRE );
+                str = OUString(RTL_CONSTASCII_USTRINGPARAM("Couldn't find uno._uno_extract_printable_stacktrace"));
             }
         }
         else
         {
-            str = PyRef(
-                PyString_FromString( "Couldn't find uno.py, no stacktrace available" ),
-                SAL_NO_ACQUIRE );
+            str = OUString(RTL_CONSTASCII_USTRINGPARAM("Could not load uno.py, no stacktrace available"));
+            if ( e.Message.getLength() > 0 )
+            {
+                str += OUString (RTL_CONSTASCII_USTRINGPARAM(" (Error loading uno.py: "));
+                str += e.Message;
+                str += OUString (RTL_CONSTASCII_USTRINGPARAM(")"));
+            }
         }
 
     }
     else
     {
         // it may occur, that no traceback is given (e.g. only native code below)
-        str = PyRef( PyString_FromString( "no traceback available" ), SAL_NO_ACQUIRE);
+        str = OUString( RTL_CONSTASCII_USTRINGPARAM( "no traceback available" ) );
     }
 
     if( isInstanceOfStructOrException( excValue.get() ) )
@@ -978,9 +994,10 @@ Any Runtime::extractUnoException( const PyRef & excType, const PyRef &excValue,
             buf.appendAscii( "Couldn't convert exception value to a string" );
         }
         buf.appendAscii( ", traceback follows\n" );
-        if( str.is() )
+        if( str.getLength() > 0 )
         {
-            buf.appendAscii( PyString_AsString( str.get() ) );
+            buf.append( str );
+            buf.appendAscii( "\n" );
         }
         else
         {
commit 41a68a4f77a639def35d778b86b6aeda8fe60a7b
Author: Lionel Elie Mamane <lionel at mamane.lu>
Date:   Sat Aug 20 17:00:29 2011 +0200

    pyuno: hook into import *after* the _whole_ uno module is successfully loaded
    
    This avoids breaking the whole python process module importing
    when an uno.py import failure happens after the hooking point.
    In that case, _uno_import is still the python module loader,
    but _g_delegatee is not anymore bound to the previously installed
    importer, and thus any module import fails with:
      File "/home/master/src/libreoffice/core/install/basis3.5/program/uno.py", line 260, in _uno_import
        return _g_delegatee( name, *optargs, **kwargs )
    TypeError: 'NoneType' object is not callable

diff --git a/pyuno/source/module/uno.py b/pyuno/source/module/uno.py
index 99fd0f0..e82d9d6 100644
--- a/pyuno/source/module/uno.py
+++ b/pyuno/source/module/uno.py
@@ -301,9 +301,6 @@ def _uno_import( name, *optargs, **kwargs ):
                       raise ImportError( "type "+ name + "." +x + " is unknown" )
     return mod
 
-# hook into the __import__ chain    
-__builtin__.__dict__["__import__"] = _uno_import
-        
 # private function, don't use
 def _impl_extractName(name):
     r = list(range(len(name)-1,0,-1))
@@ -366,4 +363,7 @@ def _uno_extract_printable_stacktrace( trace ):
         ret = "Couldn't import traceback module"
     return ret
 
+# hook into the __import__ chain    
+__builtin__.__dict__["__import__"] = _uno_import
+        
 # vim:set shiftwidth=4 softtabstop=4 expandtab:
commit a9b9b40570e6cf26ac23cd49b043d8bc2e878240
Author: Lionel Elie Mamane <lionel at mamane.lu>
Date:   Sat Aug 20 11:39:13 2011 +0200

    pyuno: allow uno structs to be initliased with keyword arguments

diff --git a/pyuno/source/module/pyuno_module.cxx b/pyuno/source/module/pyuno_module.cxx
index 1bada6d..973ef00 100644
--- a/pyuno/source/module/pyuno_module.cxx
+++ b/pyuno/source/module/pyuno_module.cxx
@@ -1,4 +1,4 @@
-/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */
+/* -*- Mode: C++; eval:(c-set-style "bsd"); tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */
 /*************************************************************************
  *
  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
@@ -28,12 +28,16 @@
 
 #include "pyuno_impl.hxx"
 
+#include <unordered_map>
+#include <utility>
+
 #include <osl/module.hxx>
 #include <osl/thread.h>
 #include <osl/file.hxx>
 
 #include <typelib/typedescription.hxx>
 
+#include <rtl/ustring.hxx>
 #include <rtl/strbuf.hxx>
 #include <rtl/ustrbuf.hxx>
 #include <rtl/uuid.h>
@@ -50,6 +54,7 @@ using osl::Module;
 
 using rtl::OString;
 using rtl::OUString;
+using rtl::OUStringHash;
 using rtl::OUStringToOString;
 using rtl::OUStringBuffer;
 using rtl::OStringBuffer;
@@ -83,35 +88,133 @@ namespace {
 // dictionary of all extra keyword arguments; the keys are strings,
 // which are the names that were used to identify the arguments. If
 // they exist, these arguments must be the last one in the list.
-sal_Int32 fillStructWithInitializer(
+
+class fillStructState
+{
+    typedef std::unordered_map <const OUString, bool, OUStringHash> initialised_t;
+    // Keyword arguments used
+    PyObject *used;
+    // Which structure members are initialised
+    std::unordered_map <const OUString, bool, OUStringHash> initialised;
+    // How many positional arguments are consumed
+    // This is always the so-many first ones
+    sal_Int32 nPosConsumed;
+    // The total number of members set, either by a keyword argument or a positional argument
+    unsigned int nMembersSet;
+
+public:
+    fillStructState()
+        : used (PyDict_New())
+        , initialised ()
+        , nPosConsumed (0)
+        , nMembersSet (0)
+    {
+        if ( ! used )
+            throw RuntimeException(OUString(RTL_CONSTASCII_USTRINGPARAM("pyuno._createUnoStructHelper failed to create new dictionary")), Reference< XInterface > ());
+    }
+    ~fillStructState()
+    {
+        Py_DECREF(used);
+    }
+    void setUsed(PyObject *key)
+    {
+        PyDict_SetItem(used, key, Py_True);
+    }
+    bool isUsed(PyObject *key) const
+    {
+        return Py_True == PyDict_GetItem(used, key);
+    }
+    void setInitialised(OUString key, int pos = -1)
+    {
+        if (initialised[key])
+        {
+            OUStringBuffer buf;
+            buf.appendAscii( "pyuno._createUnoStructHelper: member '");
+            buf.append(key);
+            buf.appendAscii( "'");
+            if ( pos >= 0 )
+            {
+                buf.appendAscii( " at position ");
+                buf.append(pos);
+            }
+            buf.appendAscii( " initialised multiple times.");
+            throw RuntimeException(buf.makeStringAndClear(), Reference< XInterface > ());
+        }
+        initialised[key] = true;
+        ++nMembersSet;
+        if ( pos >= 0 )
+            ++nPosConsumed;
+    }
+    bool isInitialised(OUString key)
+    {
+        return initialised[key];
+    }
+    PyObject *getUsed() const
+    {
+        return used;
+    }
+    sal_Int32 getCntConsumed() const
+    {
+        return nPosConsumed;
+    }
+    int getCntMembersSet() const
+    {
+        return nMembersSet;
+    }
+};
+
+static void fillStruct(
     const Reference< XInvocation2 > &inv,
     typelib_CompoundTypeDescription *pCompType,
     PyObject *initializer,
+    PyObject *kwinitializer,
+    fillStructState &state,
     const Runtime &runtime) throw ( RuntimeException )
 {
-    sal_Int32 nIndex = 0;
     if( pCompType->pBaseTypeDescription )
-        nIndex = fillStructWithInitializer(
-            inv, pCompType->pBaseTypeDescription, initializer, runtime );
+        fillStruct( inv, pCompType->pBaseTypeDescription, initializer, kwinitializer, state, runtime );
 
-    sal_Int32 nTupleSize =  PyTuple_Size(initializer);
-    int i;
-    for( i = 0 ; i < pCompType->nMembers ; i ++ )
+    const sal_Int32 nMembers = pCompType->nMembers;
+    {
+        for( int i = 0 ; i < nMembers ; i ++ )
+        {
+            const OUString OUMemberName (pCompType->ppMemberNames[i]);
+            PyObject *pyMemberName = PyString_FromString(::rtl::OUStringToOString( OUMemberName, RTL_TEXTENCODING_UTF8 ).getStr());
+            if ( PyObject *element = PyDict_GetItem(kwinitializer, pyMemberName ) )
+            {
+                state.setInitialised(OUMemberName);
+                state.setUsed(pyMemberName);
+                Any a = runtime.pyObject2Any( element, ACCEPT_UNO_ANY );
+                inv->setValue( OUMemberName, a );
+            }
+        }
+    }
+    {
+        const int remainingPosInitialisers = PyTuple_Size(initializer) - state.getCntConsumed();
+        for( int i = 0 ; i < remainingPosInitialisers && i < nMembers ; i ++ )
+        {
+            const int tupleIndex = state.getCntConsumed();
+            const OUString pMemberName (pCompType->ppMemberNames[i]);
+            state.setInitialised(pMemberName, tupleIndex);
+            PyObject *element = PyTuple_GetItem( initializer, tupleIndex );
+            Any a = runtime.pyObject2Any( element, ACCEPT_UNO_ANY );
+            inv->setValue( pMemberName, a );
+        }
+    }
+    for ( int i = 0; i < nMembers ; ++i)
     {
-        // LEM TODO: and if too many? Silently ignored?
-        if( i + nIndex >= nTupleSize )
+        const OUString memberName (pCompType->ppMemberNames[i]);
+        if ( ! state.isInitialised( memberName ) )
         {
             OUStringBuffer buf;
-            buf.appendAscii( "pyuno._createUnoStructHelper: too few elements in the initializer tuple,");
-            buf.appendAscii( "expected at least " ).append( nIndex + pCompType->nMembers );
-            buf.appendAscii( ", got " ).append( nTupleSize );
+            buf.appendAscii( "pyuno._createUnoStructHelper: member '");
+            buf.append(memberName);
+            buf.appendAscii( "' of struct type '");
+            buf.append(pCompType->aBase.pTypeName);
+            buf.appendAscii( "' not given a value.");
             throw RuntimeException(buf.makeStringAndClear(), Reference< XInterface > ());
         }
-        PyObject *element = PyTuple_GetItem( initializer, i + nIndex );
-        Any a = runtime.pyObject2Any( element, ACCEPT_UNO_ANY );
-        inv->setValue( pCompType->ppMemberNames[i], a );
     }
-    return i+nIndex;
 }
 
 OUString getLibDir()
@@ -249,7 +352,7 @@ PyObject * extractOneStringArg( PyObject *args, char const *funcName )
     return obj;
 }
 
-static PyObject *createUnoStructHelper(PyObject *, PyObject* args )
+static PyObject *createUnoStructHelper(PyObject *, PyObject* args, PyObject* keywordArgs)
 {
     Any IdlStruct;
     PyRef ret;
@@ -265,7 +368,7 @@ static PyObject *createUnoStructHelper(PyObject *, PyObject* args )
             // in Python 2, only PyString_Check returns true.
             if(PyString_Check(structName) || PyUnicode_Check(structName))
             {
-                if( PyTuple_Check( initializer ) )
+                if( PyTuple_Check( initializer ) && PyDict_Check ( keywordArgs ) )
                 {
                     OUString typeName( OUString::createFromAscii(PyString_AsString(structName)));
                     RuntimeCargo *c = runtime.getImpl()->cargo;
@@ -275,28 +378,25 @@ static PyObject *createUnoStructHelper(PyObject *, PyObject* args )
                         idl_class->createObject (IdlStruct);
                         PyUNO *me = (PyUNO*)PyUNO_new_UNCHECKED( IdlStruct, c->xInvocation );
                         PyRef returnCandidate( (PyObject*)me, SAL_NO_ACQUIRE );
-                        if( PyTuple_Size( initializer ) > 0 )
+                        TypeDescription desc( typeName );
+                        OSL_ASSERT( desc.is() ); // could already instantiate an XInvocation2 !
+
+                        typelib_CompoundTypeDescription *pCompType =
+                            ( typelib_CompoundTypeDescription * ) desc.get();
+                        fillStructState state;
+                        if ( PyTuple_Size( initializer ) > 0 || PyDict_Size( keywordArgs ) > 0 )
+                            fillStruct( me->members->xInvocation, pCompType, initializer, keywordArgs, state, runtime );
+                        if( state.getCntConsumed() != PyTuple_Size(initializer) )
                         {
-                            TypeDescription desc( typeName );
-                            OSL_ASSERT( desc.is() ); // could already instantiate an XInvocation2 !
-
-                            typelib_CompoundTypeDescription *pCompType =
-                                ( typelib_CompoundTypeDescription * ) desc.get();
-                            sal_Int32 n = fillStructWithInitializer(
-                                me->members->xInvocation, pCompType, initializer, runtime );
-                            if( n != PyTuple_Size(initializer) )
-                            {
-                                OUStringBuffer buf;
-                                buf.appendAscii( "pyuno._createUnoStructHelper: wrong number of ");
-                                buf.appendAscii( "elements in the initializer list, expected " );
-                                buf.append( n );
-                                buf.appendAscii( ", got " );
-                                buf.append( (sal_Int32) PyTuple_Size(initializer) );
-                                throw RuntimeException(
-                                    buf.makeStringAndClear(), Reference< XInterface > ());
-                            }
+                            OUStringBuffer buf;
+                            buf.appendAscii( "pyuno._createUnoStructHelper: too many ");
+                            buf.appendAscii( "elements in the initializer list, expected " );
+                            buf.append( state.getCntConsumed() );
+                            buf.appendAscii( ", got " );
+                            buf.append( (sal_Int32) PyTuple_Size(initializer) );
+                            throw RuntimeException( buf.makeStringAndClear(), Reference< XInterface > ());
                         }
-                        ret = returnCandidate;
+                        ret = PyRef( PyTuple_Pack(2, returnCandidate.get(), state.getUsed()), SAL_NO_ACQUIRE);
                     }
                     else
                     {
@@ -321,7 +421,7 @@ static PyObject *createUnoStructHelper(PyObject *, PyObject* args )
         }
         else
         {
-            PyErr_SetString (PyExc_AttributeError, "1 Arguments: Structure Name");
+            PyErr_SetString (PyExc_AttributeError, "pyuno._createUnoStructHelper: expects exactly two non-keyword arguments:\n\tStructure Name\n\tinitialiser tuple; may be the empty tuple");
         }
     }
     catch( com::sun::star::uno::RuntimeException & e )
@@ -702,7 +802,7 @@ static PyObject *setCurrentContext( PyObject *, PyObject * args )
 struct PyMethodDef PyUNOModule_methods [] =
 {
     {const_cast< char * >("getComponentContext"), getComponentContext, METH_VARARGS, NULL},
-    {const_cast< char * >("_createUnoStructHelper"), createUnoStructHelper, METH_VARARGS | METH_KEYWORDS, NULL},
+    {const_cast< char * >("_createUnoStructHelper"), reinterpret_cast<PyCFunction>(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},
diff --git a/pyuno/source/module/uno.py b/pyuno/source/module/uno.py
index bb97205..99fd0f0 100644
--- a/pyuno/source/module/uno.py
+++ b/pyuno/source/module/uno.py
@@ -4,6 +4,7 @@
 # DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
 # 
 # Copyright 2000, 2010 Oracle and/or its affiliates.
+#                 2011 Lionel Elie Mamane <lionel at mamane.lu>
 #
 # OpenOffice.org - a multi-platform office productivity suite
 #
@@ -56,20 +57,23 @@ def getTypeByName( typeName):
     """ 
     return pyuno.getTypeByName( typeName )
 
-def createUnoStruct( typeName, *args ):
-    """creates a uno struct or exception given by typeName. The parameter args may
-    1) be empty. In this case, you get a default constructed uno structure.
+def createUnoStruct( typeName, *args, **kwargs ):
+    """creates a uno struct or exception given by typeName. Can be called with:
+    1) No additional argument.
+       In this case, you get a default constructed uno structure.
        ( e.g. createUnoStruct( "com.sun.star.uno.Exception" ) )
-    2) be a sequence with exactly one element, that contains an instance of typeName.
+    2) Exactly one additional argument that is an instance of typeName.
        In this case, a copy constructed instance of typeName is returned
        ( e.g. createUnoStruct( "com.sun.star.uno.Exception" , e ) )
-    3) be a sequence, where the length of the sequence must match the number of
-       elements within typeName (e.g.
-       createUnoStruct( "com.sun.star.uno.Exception", "foo error" , self) ). The
-       elements with in the sequence must match the type of each struct element,
-       otherwise an exception is thrown.
+    3) As many additional arguments as the number of elements within typeName
+       (e.g. createUnoStruct( "com.sun.star.uno.Exception", "foo error" , self) ).
+    4) Keyword arguments to give values for each element of the struct by name.
+    5) A mix of 3) and 4), such that each struct element is given a value exactly once,
+       either by a positional argument or by a keyword argument.
+    The additional and/or keyword arguments must match the type of each struct element,
+    otherwise an exception is thrown.
     """
-    return getClass(typeName)( *args )
+    return getClass(typeName)( *args, **kwargs )
 
 def getClass( typeName ):
     """returns the class of a concrete uno exception, struct or interface
@@ -310,11 +314,16 @@ def _impl_extractName(name):
     return name            
 
 # private, referenced from the pyuno shared library
-def _uno_struct__init__(self,*args):
-    if len(args) == 1 and hasattr(args[0], "__class__") and args[0].__class__ == self.__class__ :
-       self.__dict__["value"] = args[0]
+def _uno_struct__init__(self,*args, **kwargs):
+    if len(kwargs) == 0 and len(args) == 1 and hasattr(args[0], "__class__") and args[0].__class__ == self.__class__ :
+        self.__dict__["value"] = args[0]
     else:
-       self.__dict__["value"] = pyuno._createUnoStructHelper(self.__class__.__pyunostruct__,args)
+        struct, used = pyuno._createUnoStructHelper(self.__class__.__pyunostruct__,args,**kwargs)
+        for kw in kwargs.keys():
+            if not (kw in used and used[kw]):
+                RuntimeException = pyuno.getClass( "com.sun.star.uno.RuntimeException" )
+                raise RuntimeException("_uno_struct__init__: unused keyword argument '" + kw + "'", None)
+        self.__dict__["value"] = struct
     
 # private, referenced from the pyuno shared library
 def _uno_struct__getattr__(self,name):


More information about the Libreoffice-commits mailing list