Re: weird error with pyblio-1.3.4
Sébastien Barthélemy <[email protected]> Tue, 27 Nov 2007 09:42:36 +0100
| Newsgroups | gmane.comp.gnome.apps.pybliographer |
|---|---|
| Message-ID | <1196152956.6729.9.camel@thinbox> |
--=-HQar2Ckuj37LGV+pU+pP Content-Type: text/plain; charset=utf-8 Content-Transfer-Encoding: quoted-printable Le lundi 26 novembre 2007 =C3=A0 22:01 +0000, Fr=C3=A9d=C3=A9ric Gobry a = =C3=A9crit : > 2007/11/26, S=C3=A9bastien Barth=C3=A9lemy <[email protected]>: > > > > I still don't know, but commenting the lines 42-47 in > > Legacy/GnomeUI/Citation.py prevent uno to be loaded and then it works= ! > > > > #try: > > # from Pyblio.Cite.WP.OpenOffice import OOo > > # available.append((OOo, _('OpenOffice.org'))) > > # > > #except ImportError, msg: > > # log.warn('cannot import OpenOffice.org support: %s' % msg) > > > > If there is a better way to do the same thing, I'm interested >=20 > Hmm, fixing the uno install?=20 Hmm, I was thinking of some "disable_uno" configuration option ;) > I reckon it plays with the import path > somehow (which pyblio already tweaked beforehand). I don't have this > issue on my box, so it's hard for me to guess what's going on. Could > you have a look at the uno module and see if it does something to > sys.path? I though about something like that and tried to add the pyblio dirs to the python path but it didn't helped ~/share/pyblio-1.3/Legacy:~/share/pyblio-1.3/Legacy/GnomeUI My python-uno package comes from ubuntu and is version 1:2.3.0-1ubuntu5, the files are attached. There is no sys.path, but they are playing with sys.modules around line 256, maybe this is related. ++ --=-HQar2Ckuj37LGV+pU+pP Content-Disposition: attachment; filename=uno.py Content-Type: text/x-python; name=uno.py; charset=utf-8 Content-Transfer-Encoding: 7bit #************************************************************************* # # OpenOffice.org - a multi-platform office productivity suite # # $RCSfile: uno.py,v $ # # $Revision: 1.7 $ # # last change: $Author: obo $ $Date: 2006/03/22 10:52:57 $ # # The Contents of this file are made available subject to # the terms of GNU Lesser General Public License Version 2.1. # # # GNU Lesser General Public License Version 2.1 # ============================================= # Copyright 2005 by Sun Microsystems, Inc. # 901 San Antonio Road, Palo Alto, CA 94303, USA # # This library is free software; you can redistribute it and/or # modify it under the terms of the GNU Lesser General Public # License version 2.1, as published by the Free Software Foundation. # # This library is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU # Lesser General Public License for more details. # # You should have received a copy of the GNU Lesser General Public # License along with this library; if not, write to the Free Software # Foundation, Inc., 59 Temple Place, Suite 330, Boston, # MA 02111-1307 USA # #************************************************************************* import sys import pyuno import __builtin__ # 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__"] def getComponentContext(): """ returns the UNO component context, that was used to initialize the python runtime. """ return _g_ctx def getConstantByName( constant ): "Looks up the value of a idl constant by giving its explicit name" return pyuno.getConstantByName( constant ) def getTypeByName( typeName): """ returns a uno.Type instance of the type given by typeName. In case the type does not exist, a com.sun.star.uno.RuntimeException is raised. """ 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. ( e.g. createUnoStruct( "com.sun.star.uno.Exception" ) ) 2) be a sequence with exactly one element, that contains 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. """ return getClass(typeName)( *args ) def getClass( typeName ): """returns the class of a concrete uno exception, struct or interface """ return pyuno.getClass(typeName) def isInterface( obj ): """returns true, when obj is a class of a uno interface""" return pyuno.isInterface( obj ) def generateUuid(): "returns a 16 byte sequence containing a newly generated uuid or guid, see rtl/uuid.h " return pyuno.generateUuid() def systemPathToFileUrl( systemPath ): "returns a file-url for the given system path" return pyuno.systemPathToFileUrl( systemPath ) def fileUrlToSystemPath( url ): "returns a system path (determined by the system, the python interpreter is running on)" return pyuno.fileUrlToSystemPath( url ) def absolutize( path, relativeUrl ): "returns an absolute file url from the given urls" return pyuno.absolutize( path, relativeUrl ) def getCurrentContext(): """Returns the currently valid current context. see http://udk.openoffice.org/common/man/concept/uno_contexts.html#current_context for an explanation on the current context concept """ return pyuno.getCurrentContext() def setCurrentContext( newContext ): """Sets newContext as new uno current context. The newContext must implement the XCurrentContext interface. The implemenation should handle the desired properties and delegate unknown properties to the old context. Ensure to reset the old one when you leave your stack ... see http://udk.openoffice.org/common/man/concept/uno_contexts.html#current_context """ return pyuno.setCurrentContext( newContext ) class Enum: "Represents a UNO idl enum, use an instance of this class to explicitly pass a boolean to UNO" #typeName the name of the enum as a string #value the actual value of this enum as a string def __init__(self,typeName, value): self.typeName = typeName self.value = value pyuno.checkEnum( self ) def __repr__(self): return "<uno.Enum %s (%r)>" % (self.typeName, self.value) def __eq__(self, that): if not isinstance(that, Enum): return False return (self.typeName == that.typeName) and (self.value == that.value) class Type: "Represents a UNO type, use an instance of this class to explicitly pass a boolean to UNO" # typeName # Name of the UNO type # typeClass # python Enum of TypeClass, see com/sun/star/uno/TypeClass.idl def __init__(self, typeName, typeClass): self.typeName = typeName self.typeClass = typeClass pyuno.checkType(self) def __repr__(self): return "<Type instance %s (%r)>" % (self.typeName, self.typeClass) def __eq__(self, that): if not isinstance(that, Type): return False return self.typeClass == that.typeClass and self.typeName == that.typeName def __hash__(self): return self.typeName.__hash__() class Bool(object): """Represents a UNO boolean, use an instance of this class to explicitly pass a boolean to UNO. 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": return True if isinstance(value, (str, unicode)) and value == "false": return False if value: return True return False 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 len(value) == 1 self.value=value def __repr__(self): return "<Char instance %s>" % (self.value, ) def __eq__(self, that): if isinstance(that, (str, unicode)): if len(that) > 1: return False return self.value == that[0] if isinstance(that, Char): return self.value == that.value return False # Suggested by Christian, but still some open problems which need to be solved first # #class ByteSequence(str): # # def __repr__(self): # return "<ByteSequence instance %s>" % str.__repr__(self) # for a little bit compatitbility; setting value is not possible as # strings are immutable # def _get_value(self): # return self # # value = property(_get_value) class ByteSequence: def __init__(self, value): if isinstance(value, str): self.value = value elif isinstance(value, ByteSequence): self.value = value.value else: raise TypeError("expected string or bytesequence") def __repr__(self): return "<ByteSequence instance '%s'>" % (self.value, ) def __eq__(self, that): if isinstance( that, ByteSequence): return self.value == that.value if isinstance(that, str): return self.value == that return False def __len__(self): return len(self.value) def __getitem__(self, index): return self.value[index] def __iter__( self ): return self.value.__iter__() def __add__( self , b ): if isinstance( b, str ): return ByteSequence( self.value + b ) elif isinstance( b, ByteSequence ): return ByteSequence( self.value + b.value ) raise TypeError( "expected string or ByteSequence as operand" ) def __hash__( self ): return self.value.hash() class Any: "use only in connection with uno.invoke() to pass an explicit typed any" def __init__(self, type, value ): if isinstance( type, Type ): self.type = type else: self.type = getTypeByName( type ) self.value = value def invoke( object, methodname, argTuple ): "use this function to pass exactly typed anys to the callee (using uno.Any)" return pyuno.invoke( object, methodname, argTuple ) #--------------------------------------------------------------------------------------- # don't use any functions beyond this point, private section, likely to change #--------------------------------------------------------------------------------------- def _uno_import( name, *optargs ): try: # print "optargs = " + repr(optargs) if len(optargs) == 0: return _g_delegatee( name ) #print _g_delegatee return _g_delegatee( name, *optargs ) except ImportError: if len(optargs) != 3 or not optargs[2]: raise globals = optargs[0] locals = optargs[1] fromlist = optargs[2] modnames = name.split( "." ) mod = None d = sys.modules for x in modnames: if d.has_key(x): mod = d[x] 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 not d.has_key(x): if x.startswith( "typeOf" ): try: d[x] = pyuno.getTypeByName( name + "." + x[6:len(x)] ) except RuntimeException,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: # check for enums try: d[x] = Enum( name , x ) except RuntimeException,e2: # check for constants try: d[x] = getConstantByName( name + "." + x ) except RuntimeException,e3: # no known uno type ! 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 = range (len(name)-1,0,-1) for i in r: if name[i] == ".": name = name[i+1:len(name)] break 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] else: self.__dict__["value"] = pyuno._createUnoStructHelper(self.__class__.__pyunostruct__,args) # private, referenced from the pyuno shared library def _uno_struct__getattr__(self,name): return __builtin__.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) # private, referenced from the pyuno shared library def _uno_struct__repr__(self): return repr(self.__dict__["value"]) def _uno_struct__str__(self): return str(self.__dict__["value"]) # private, referenced from the pyuno shared library def _uno_struct__eq__(self,cmp): if hasattr(cmp,"value"): return self.__dict__["value"] == cmp.__dict__["value"] return False def _uno_extract_printable_stacktrace( trace ): mod = None try: mod = __import__("traceback") except ImportError,e: pass ret = "" if mod: lst = mod.format_tb( trace ) for i in lst: ret = ret + i else: ret = "Coludn't import traceback module" return ret --=-HQar2Ckuj37LGV+pU+pP Content-Disposition: attachment; filename=unohelper.py Content-Type: text/x-python; name=unohelper.py; charset=utf-8 Content-Transfer-Encoding: 7bit #************************************************************************* # # OpenOffice.org - a multi-platform office productivity suite # # $RCSfile: unohelper.py,v $ # # $Revision: 1.5 $ # # last change: $Author: obo $ $Date: 2006/03/22 10:53:27 $ # # The Contents of this file are made available subject to # the terms of GNU Lesser General Public License Version 2.1. # # # GNU Lesser General Public License Version 2.1 # ============================================= # Copyright 2005 by Sun Microsystems, Inc. # 901 San Antonio Road, Palo Alto, CA 94303, USA # # This library is free software; you can redistribute it and/or # modify it under the terms of the GNU Lesser General Public # License version 2.1, as published by the Free Software Foundation. # # This library is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU # Lesser General Public License for more details. # # You should have received a copy of the GNU Lesser General Public # License along with this library; if not, write to the Free Software # Foundation, Inc., 59 Temple Place, Suite 330, Boston, # MA 02111-1307 USA # #************************************************************************* import uno import pyuno import os import sys from com.sun.star.lang import XTypeProvider, XSingleComponentFactory, XServiceInfo from com.sun.star.uno import RuntimeException, XCurrentContext from com.sun.star.beans.MethodConcept import ALL as METHOD_CONCEPT_ALL from com.sun.star.beans.PropertyConcept import ALL as PROPERTY_CONCEPT_ALL from com.sun.star.reflection.ParamMode import \ IN as PARAM_MODE_IN, \ OUT as PARAM_MODE_OUT, \ INOUT as PARAM_MODE_INOUT from com.sun.star.beans.PropertyAttribute import \ MAYBEVOID as PROP_ATTR_MAYBEVOID, \ BOUND as PROP_ATTR_BOUND, \ CONSTRAINED as PROP_ATTR_CONSTRAINED, \ TRANSIENT as PROP_ATTR_TRANSIENT, \ READONLY as PROP_ATTR_READONLY, \ MAYBEAMBIGUOUS as PROP_ATTR_MAYBEAMBIGUOUS, \ MAYBEDEFAULT as PROP_ATTR_MAYBEDEFAULT, \ REMOVEABLE as PROP_ATTR_REMOVEABLE def _mode_to_str( mode ): ret = "[]" if mode == PARAM_MODE_INOUT: ret = "[inout]" elif mode == PARAM_MODE_OUT: ret = "[out]" elif mode == PARAM_MODE_IN: ret = "[in]" return ret def _propertymode_to_str( mode ): ret = "" if PROP_ATTR_REMOVEABLE & mode: ret = ret + "removeable " if PROP_ATTR_MAYBEDEFAULT & mode: ret = ret + "maybedefault " if PROP_ATTR_MAYBEAMBIGUOUS & mode: ret = ret + "maybeambigous " if PROP_ATTR_READONLY & mode: ret = ret + "readonly " if PROP_ATTR_TRANSIENT & mode: ret = ret + "tranient " if PROP_ATTR_CONSTRAINED & mode: ret = ret + "constrained " if PROP_ATTR_BOUND & mode: ret = ret + "bound " if PROP_ATTR_MAYBEVOID & mode: ret = ret + "maybevoid " return ret.rstrip() def inspect( obj , out ): ctx = uno.getComponentContext() introspection = \ ctx.ServiceManager.createInstanceWithContext( "com.sun.star.beans.Introspection", ctx ) out.write( "Supported services:\n" ) if hasattr( obj, "getSupportedServiceNames" ): names = obj.getSupportedServiceNames() for ii in names: out.write( " " + ii + "\n" ) else: out.write( " unknown\n" ) out.write( "Interfaces:\n" ) if hasattr( obj, "getTypes" ): interfaces = obj.getTypes() for ii in interfaces: out.write( " " + ii.typeName + "\n" ) else: out.write( " unknown\n" ) access = introspection.inspect( obj ) methods = access.getMethods( METHOD_CONCEPT_ALL ) out.write( "Methods:\n" ) for ii in methods: out.write( " " + ii.ReturnType.Name + " " + ii.Name ) args = ii.ParameterTypes infos = ii.ParameterInfos out.write( "( " ) for i in range( 0, len( args ) ): if i > 0: out.write( ", " ) out.write( _mode_to_str( infos[i].aMode ) + " " + args[i].Name + " " + infos[i].aName ) out.write( " )\n" ) props = access.getProperties( PROPERTY_CONCEPT_ALL ) out.write ("Properties:\n" ) for ii in props: out.write( " ("+_propertymode_to_str( ii.Attributes ) + ") "+ii.Type.typeName+" "+ii.Name+ "\n" ) def createSingleServiceFactory( clazz, implementationName, serviceNames ): return _FactoryHelper_( clazz, implementationName, serviceNames ) class _ImplementationHelperEntry: 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 class ImplementationEntry: 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 ) def systemPathToFileUrl( systemPath ): "returns a file-url for the given system path" return pyuno.systemPathToFileUrl( systemPath ) def fileUrlToSystemPath( url ): "returns a system path (determined by the system, the python interpreter is running on)" return pyuno.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 ) def addComponentsToContext( toBeExtendedContext, contextRuntime, componentUrls, loaderName ): smgr = contextRuntime.ServiceManager loader = smgr.createInstanceWithContext( loaderName, contextRuntime ) implReg = smgr.createInstanceWithContext( "com.sun.star.registry.ImplementationRegistration",contextRuntime) isWin = os.name == 'nt' or os.name == 'dos' isMac = sys.platform == 'darwin' # create a temporary registry for componentUrl in componentUrls: reg = smgr.createInstanceWithContext( "com.sun.star.registry.SimpleRegistry", contextRuntime ) reg.open( "", 0, 1 ) if not isWin and componentUrl.endswith( ".uno" ): # still allow platform independent naming if isMac: 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() # 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 class Base(XTypeProvider): 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 hashmap and if the key cannot be found, it delegates to the predecessor if available """ def __init__( self, oldContext, hashMap ): self.hashMap = hashMap self.oldContext = oldContext def getValueByName( self, name ): if name in self.hashMap: return self.hashMap[name] elif self.oldContext != None: 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 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 ) --=-HQar2Ckuj37LGV+pU+pP Content-Type: text/plain; charset="us-ascii" MIME-Version: 1.0 Content-Transfer-Encoding: 7bit Content-Disposition: inline ------------------------------------------------------------------------- This SF.net email is sponsored by: Microsoft Defy all challenges. Microsoft(R) Visual Studio 2005. http://clk.atdmt.com/MRT/go/vse0120000070mrt/direct/01/ --=-HQar2Ckuj37LGV+pU+pP Content-Type: text/plain; charset="us-ascii" MIME-Version: 1.0 Content-Transfer-Encoding: 7bit Content-Disposition: inline _______________________________________________ Pybliographer-general mailing list Pybliographer-general-5NWGOfrQmneRv+LV9MX5uipxlwaOVQ5f@public.gmane.org https://lists.sourceforge.net/lists/listinfo/pybliographer-general --=-HQar2Ckuj37LGV+pU+pP--