diff options
Diffstat (limited to 'pyuno/source')
-rw-r--r-- | pyuno/source/loader/pythonloader.py | 200 | ||||
-rw-r--r-- | pyuno/source/module/uno.py | 94 | ||||
-rw-r--r-- | pyuno/source/module/unohelper.py | 225 |
3 files changed, 258 insertions, 261 deletions
diff --git a/pyuno/source/loader/pythonloader.py b/pyuno/source/loader/pythonloader.py index 8c81345c534b..986817c10d48 100644 --- a/pyuno/source/loader/pythonloader.py +++ b/pyuno/source/loader/pythonloader.py @@ -34,112 +34,110 @@ g_supportedServices = "com.sun.star.loader.Python", # referenced by the na g_implementationName = "org.openoffice.comp.pyuno.Loader" # referenced by the native C++ loader ! def splitUrl( url ): - nColon = url.find( ":" ) - if -1 == nColon: - raise RuntimeException( "PythonLoader: No protocol in url " + url, None ) - return url[0:nColon], url[nColon+1:len(url)] + nColon = url.find( ":" ) + if -1 == nColon: + raise RuntimeException( "PythonLoader: No protocol in url " + url, None ) + return url[0:nColon], url[nColon+1:len(url)] g_loadedComponents = {} def checkForPythonPathBesideComponent( url ): - path = unohelper.fileUrlToSystemPath( url+"/pythonpath.zip" ); - if DEBUG == 1: - print "checking for existence of " + encfile( path ) - if 1 == os.access( encfile( path ), os.F_OK) and not path in sys.path: - if DEBUG == 1: - print "adding " + encfile( path ) + " to sys.path" - sys.path.append( path ) - - path = unohelper.fileUrlToSystemPath( url+"/pythonpath" ); - if 1 == os.access( encfile( path ), os.F_OK) and not path in sys.path: - if DEBUG == 1: - print "adding " + encfile( path ) + " to sys.path" - sys.path.append( path ) + path = unohelper.fileUrlToSystemPath( url+"/pythonpath.zip" ); + if DEBUG == 1: + print("checking for existence of " + encfile( path )) + if 1 == os.access( encfile( path ), os.F_OK) and not path in sys.path: + if DEBUG == 1: + print("adding " + encfile( path ) + " to sys.path") + sys.path.append( path ) + + path = unohelper.fileUrlToSystemPath( url+"/pythonpath" ); + if 1 == os.access( encfile( path ), os.F_OK) and not path in sys.path: + if DEBUG == 1: + print("adding " + encfile( path ) + " to sys.path") + sys.path.append( path ) def encfile(uni): return uni.encode( sys.getfilesystemencoding()) class Loader( XImplementationLoader, XServiceInfo, unohelper.Base ): - def __init__(self, ctx ): - if DEBUG: - print "pythonloader.Loader ctor" - self.ctx = ctx - - def getModuleFromUrl( self, url ): - if DEBUG: - print "pythonloader: interpreting url " +url - protocol, dependent = splitUrl( url ) - if "vnd.sun.star.expand" == protocol: - exp = self.ctx.getValueByName( "/singletons/com.sun.star.util.theMacroExpander" ) - url = exp.expandMacros(dependent) - protocol,dependent = splitUrl( url ) - - if DEBUG: - print "pythonloader: after expansion " +protocol +":" + dependent - - try: - if "file" == protocol: - # remove \..\ sequence, which may be useful e.g. in the build env - url = unohelper.absolutize( url, url ) - - # did we load the module already ? - mod = g_loadedComponents.get( url ) - if not mod: - mod = imp.new_module("uno_component") - - # check for pythonpath.zip beside .py files - checkForPythonPathBesideComponent( url[0:url.rfind('/')] ) - - # read the file - filename = unohelper.fileUrlToSystemPath( url ) - fileHandle = file( filename ) - src = fileHandle.read().replace("\r","") - if not src.endswith( "\n" ): - src = src + "\n" - - # compile and execute the module - codeobject = compile( src, encfile(filename), "exec" ) - exec codeobject in mod.__dict__ - mod.__file__ = encfile(filename) - g_loadedComponents[url] = mod - return mod - elif "vnd.openoffice.pymodule" == protocol: - return __import__( dependent ) - else: - raise RuntimeException( "PythonLoader: Unknown protocol " + - protocol + " in url " +url, self ) - except ImportError, e: - raise RuntimeException( "Couldn't load "+url+ " for reason "+str(e), None) - return None - - def activate( self, implementationName, dummy, locationUrl, regKey ): - if DEBUG: - print "pythonloader.Loader.activate" - - mod = self.getModuleFromUrl( locationUrl ) - implHelper = mod.__dict__.get( "g_ImplementationHelper" , None ) - if implHelper == None: - return mod.getComponentFactory( implementationName, self.ctx.ServiceManager, regKey ) - else: - return implHelper.getComponentFactory( implementationName,regKey,self.ctx.ServiceManager) - - def writeRegistryInfo( self, regKey, dummy, locationUrl ): - if DEBUG: - print "pythonloader.Loader.writeRegistryInfo" - - mod = self.getModuleFromUrl( locationUrl ) - implHelper = mod.__dict__.get( "g_ImplementationHelper" , None ) - if implHelper == None: - return mod.writeRegistryInfo( self.ctx.ServiceManager, regKey ) - else: - return implHelper.writeRegistryInfo( regKey, self.ctx.ServiceManager ) - - def getImplementationName( self ): - return g_implementationName - - def supportsService( self, ServiceName ): - return ServiceName in self.serviceNames - - def getSupportedServiceNames( self ): - return g_supportedServices - - + def __init__(self, ctx ): + if DEBUG: + print("pythonloader.Loader ctor") + self.ctx = ctx + + def getModuleFromUrl( self, url ): + if DEBUG: + print("pythonloader: interpreting url " +url) + protocol, dependent = splitUrl( url ) + if "vnd.sun.star.expand" == protocol: + exp = self.ctx.getValueByName( "/singletons/com.sun.star.util.theMacroExpander" ) + url = exp.expandMacros(dependent) + protocol,dependent = splitUrl( url ) + + if DEBUG: + print("pythonloader: after expansion " +protocol +":" + dependent) + + try: + if "file" == protocol: + # remove \..\ sequence, which may be useful e.g. in the build env + url = unohelper.absolutize( url, url ) + + # did we load the module already ? + mod = g_loadedComponents.get( url ) + if not mod: + mod = imp.new_module("uno_component") + + # check for pythonpath.zip beside .py files + checkForPythonPathBesideComponent( url[0:url.rfind('/')] ) + + # read the file + filename = unohelper.fileUrlToSystemPath( url ) + fileHandle = file( filename ) + src = fileHandle.read().replace("\r","") + if not src.endswith( "\n" ): + src = src + "\n" + + # compile and execute the module + codeobject = compile( src, encfile(filename), "exec" ) + exec(codeobject, mod.__dict__) + mod.__file__ = encfile(filename) + g_loadedComponents[url] = mod + return mod + elif "vnd.openoffice.pymodule" == protocol: + return __import__( dependent ) + else: + raise RuntimeException( "PythonLoader: Unknown protocol " + + protocol + " in url " +url, self ) + except ImportError as e: + raise RuntimeException( "Couldn't load "+url+ " for reason "+str(e), None) + return None + + def activate( self, implementationName, dummy, locationUrl, regKey ): + if DEBUG: + print("pythonloader.Loader.activate") + + mod = self.getModuleFromUrl( locationUrl ) + implHelper = mod.__dict__.get( "g_ImplementationHelper" , None ) + if implHelper == None: + return mod.getComponentFactory( implementationName, self.ctx.ServiceManager, regKey ) + else: + return implHelper.getComponentFactory( implementationName,regKey,self.ctx.ServiceManager) + + def writeRegistryInfo( self, regKey, dummy, locationUrl ): + if DEBUG: + print("pythonloader.Loader.writeRegistryInfo") + + mod = self.getModuleFromUrl( locationUrl ) + implHelper = mod.__dict__.get( "g_ImplementationHelper" , None ) + if implHelper == None: + return mod.writeRegistryInfo( self.ctx.ServiceManager, regKey ) + else: + return implHelper.writeRegistryInfo( regKey, self.ctx.ServiceManager ) + + def getImplementationName( self ): + return g_implementationName + + def supportsService( self, ServiceName ): + return ServiceName in self.serviceNames + + def getSupportedServiceNames( self ): + return g_supportedServices diff --git a/pyuno/source/module/uno.py b/pyuno/source/module/uno.py index 8b049e43270d..d57163cc2919 100644 --- a/pyuno/source/module/uno.py +++ b/pyuno/source/module/uno.py @@ -31,8 +31,8 @@ _g_delegatee = __builtin__.__dict__["__import__"] def getComponentContext(): """ returns the UNO component context, that was used to initialize the python runtime. - """ - return _g_ctx + """ + return _g_ctx def getConstantByName( constant ): "Looks up the value of a idl constant by giving its explicit name" @@ -41,7 +41,7 @@ def 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 ): @@ -70,7 +70,7 @@ def isInterface( obj ): def generateUuid(): "returns a 16 byte sequence containing a newly generated uuid or guid, see rtl/uuid.h " - return pyuno.generateUuid() + return pyuno.generateUuid() def systemPathToFileUrl( systemPath ): "returns a file-url for the given system path" @@ -100,9 +100,9 @@ def setCurrentContext( newContext ): """ return pyuno.setCurrentContext( newContext ) - + class Enum: - "Represents a UNO idl enum, use an instance of this class to explicitly pass a boolean to UNO" + "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): @@ -138,7 +138,7 @@ class Type: return self.typeName.__hash__() class Bool(object): - """Represents a UNO boolean, use an instance of this class to explicitly + """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 """ @@ -161,13 +161,13 @@ class Char: 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): + if isinstance(that, Char): return self.value == that.value return False @@ -178,12 +178,12 @@ class Char: # def __repr__(self): # return "<ByteSequence instance %s>" % str.__repr__(self) - # for a little bit compatitbility; setting value is not possible as + # for a little bit compatibility; setting value is not possible as # strings are immutable # def _get_value(self): # return self # -# value = property(_get_value) +# value = property(_get_value) class ByteSequence: def __init__(self, value): @@ -236,7 +236,7 @@ class Any: 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 #--------------------------------------------------------------------------------------- @@ -254,56 +254,56 @@ def _uno_import( name, *optargs, **kwargs ): mod = None d = sys.modules for x in modnames: - if d.has_key(x): - mod = d[x] + if x in d: + mod = d[x] else: - mod = pyuno.__class__(x) # How to create a module ?? + 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 + if x not in d: + if x.startswith( "typeOf" ): 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" ) + d[x] = pyuno.getTypeByName( name + "." + x[6:len(x)] ) + except RuntimeException as e: + raise ImportError( "type " + name + "." + x[6:len(x)] +" is unknown" ) + else: + try: + # check for structs, exceptions or interfaces + d[x] = pyuno.getClass( name + "." + x ) + except RuntimeException as e: + # check for enums + try: + d[x] = Enum( name , x ) + except RuntimeException as e2: + # check for constants + try: + d[x] = getConstantByName( name + "." + x ) + except RuntimeException as e3: + # no known uno type ! + raise ImportError( "type "+ name + "." +x + " is unknown" ) return mod -# hook into the __import__ chain +# 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) + r = list(range(len(name)-1,0,-1)) for i in r: if name[i] == ".": - name = name[i+1:len(name)] - break - return name + 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] + self.__dict__["value"] = args[0] else: - self.__dict__["value"] = pyuno._createUnoStructHelper(self.__class__.__pyunostruct__,args) - + 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) @@ -315,14 +315,14 @@ def _uno_struct__setattr__(self,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 self.__dict__["value"] == cmp.__dict__["value"] return False # referenced from pyuno shared lib and pythonscript.py @@ -330,7 +330,7 @@ def _uno_extract_printable_stacktrace( trace ): mod = None try: mod = __import__("traceback") - except ImportError,e: + except ImportError as e: pass ret = "" if mod: diff --git a/pyuno/source/module/unohelper.py b/pyuno/source/module/unohelper.py index f79a544f6e2e..5c032159a0c2 100644 --- a/pyuno/source/module/unohelper.py +++ b/pyuno/source/module/unohelper.py @@ -72,7 +72,7 @@ def _propertymode_to_str( mode ): if PROP_ATTR_MAYBEVOID & mode: ret = ret + "maybevoid " return ret.rstrip() - + def inspect( obj , out ): if isinstance( obj, uno.Type ) or \ isinstance( obj, uno.Char ) or \ @@ -102,7 +102,7 @@ def inspect( obj , out ): out.write( " " + ii.typeName + "\n" ) else: out.write( " unknown\n" ) - + access = introspection.inspect( obj ) methods = access.getMethods( METHOD_CONCEPT_ALL ) out.write( "Methods:\n" ) @@ -126,56 +126,56 @@ def createSingleServiceFactory( clazz, implementationName, serviceNames ): return _FactoryHelper_( clazz, implementationName, serviceNames ) class _ImplementationHelperEntry: - def __init__(self, ctor,serviceNames): - self.ctor = ctor - self.serviceNames = serviceNames - + def __init__(self, ctor,serviceNames): + self.ctor = ctor + self.serviceNames = serviceNames + class ImplementationHelper: - def __init__(self): - self.impls = {} - - def addImplementation( self, ctor, implementationName, serviceNames ): - self.impls[implementationName] = _ImplementationHelperEntry(ctor,serviceNames) - - def writeRegistryInfo( self, regKey, smgr ): - for i in self.impls.items(): - keyName = "/"+ i[0] + "/UNO/SERVICES" - key = regKey.createKey( keyName ) - for serviceName in i[1].serviceNames: - key.createKey( serviceName ) - return 1 - - def getComponentFactory( self, implementationName , regKey, smgr ): - entry = self.impls.get( implementationName, None ) - if entry == None: - raise RuntimeException( implementationName + " is unknown" , None ) - return createSingleServiceFactory( entry.ctor, implementationName, entry.serviceNames ) - - def getSupportedServiceNames( self, implementationName ): - entry = self.impls.get( implementationName, None ) - if entry == None: - raise RuntimeException( implementationName + " is unknown" , None ) - return entry.serviceNames - - def supportsService( self, implementationName, serviceName ): - entry = self.impls.get( implementationName,None ) - if entry == None: - raise RuntimeException( implementationName + " is unknown", None ) - return serviceName in entry.serviceNames - - + def __init__(self): + self.impls = {} + + def addImplementation( self, ctor, implementationName, serviceNames ): + self.impls[implementationName] = _ImplementationHelperEntry(ctor,serviceNames) + + def writeRegistryInfo( self, regKey, smgr ): + for i in list(self.impls.items()): + keyName = "/"+ i[0] + "/UNO/SERVICES" + key = regKey.createKey( keyName ) + for serviceName in i[1].serviceNames: + key.createKey( serviceName ) + return 1 + + def getComponentFactory( self, implementationName , regKey, smgr ): + entry = self.impls.get( implementationName, None ) + if entry == None: + raise RuntimeException( implementationName + " is unknown" , None ) + return createSingleServiceFactory( entry.ctor, implementationName, entry.serviceNames ) + + def getSupportedServiceNames( self, implementationName ): + entry = self.impls.get( implementationName, None ) + if entry == None: + raise RuntimeException( implementationName + " is unknown" , None ) + return entry.serviceNames + + def supportsService( self, implementationName, serviceName ): + entry = self.impls.get( implementationName,None ) + if entry == None: + raise RuntimeException( implementationName + " is unknown", None ) + return serviceName in entry.serviceNames + + class ImplementationEntry: - def __init__(self, implName, supportedServices, clazz ): - self.implName = implName - self.supportedServices = supportedServices - self.clazz = clazz + def __init__(self, implName, supportedServices, clazz ): + self.implName = implName + self.supportedServices = supportedServices + self.clazz = clazz def writeRegistryInfoHelper( smgr, regKey, seqEntries ): for entry in seqEntries: keyName = "/"+ entry.implName + "/UNO/SERVICES" - key = regKey.createKey( keyName ) - for serviceName in entry.supportedServices: - key.createKey( serviceName ) + key = regKey.createKey( keyName ) + for serviceName in entry.supportedServices: + key.createKey( serviceName ) def systemPathToFileUrl( systemPath ): "returns a file-url for the given system path" @@ -188,11 +188,11 @@ def fileUrlToSystemPath( url ): def absolutize( path, relativeUrl ): "returns an absolute file url from the given urls" return pyuno.absolutize( path, relativeUrl ) - + def getComponentFactoryHelper( implementationName, smgr, regKey, seqEntries ): for x in seqEntries: - if x.implName == implementationName: - return createSingleServiceFactory( x.clazz, implementationName, x.supportedServices ) + if x.implName == implementationName: + return createSingleServiceFactory( x.clazz, implementationName, x.supportedServices ) def addComponentsToContext( toBeExtendedContext, contextRuntime, componentUrls, loaderName ): smgr = contextRuntime.ServiceManager @@ -204,56 +204,56 @@ def addComponentsToContext( toBeExtendedContext, contextRuntime, componentUrls, # create a temporary registry for componentUrl in componentUrls: reg = smgr.createInstanceWithContext( "com.sun.star.registry.SimpleRegistry", contextRuntime ) - reg.open( "", 0, 1 ) + reg.open( "", 0, 1 ) if not isWin and componentUrl.endswith( ".uno" ): # still allow platform independent naming if isMac: - componentUrl = componentUrl + ".dylib" + componentUrl = componentUrl + ".dylib" else: - componentUrl = componentUrl + ".so" - - implReg.registerImplementation( loaderName,componentUrl, reg ) - rootKey = reg.getRootKey() - implementationKey = rootKey.openKey( "IMPLEMENTATIONS" ) - implNames = implementationKey.getKeyNames() - extSMGR = toBeExtendedContext.ServiceManager - for x in implNames: - fac = loader.activate( max(x.split("/")),"",componentUrl,rootKey) - extSMGR.insert( fac ) - reg.close() - + componentUrl = componentUrl + ".so" + + implReg.registerImplementation( loaderName,componentUrl, reg ) + rootKey = reg.getRootKey() + implementationKey = rootKey.openKey( "IMPLEMENTATIONS" ) + implNames = implementationKey.getKeyNames() + extSMGR = toBeExtendedContext.ServiceManager + for x in implNames: + fac = loader.activate( max(x.split("/")),"",componentUrl,rootKey) + extSMGR.insert( fac ) + reg.close() + # never shrinks ! _g_typeTable = {} def _unohelper_getHandle( self): - ret = None - if _g_typeTable.has_key( self.__class__ ): - ret = _g_typeTable[self.__class__] - else: - names = {} - traverse = list(self.__class__.__bases__) - while len( traverse ) > 0: - item = traverse.pop() - bases = item.__bases__ - if uno.isInterface( item ): - names[item.__pyunointerface__] = None - elif len(bases) > 0: - # the "else if", because we only need the most derived interface - traverse = traverse + list(bases)# - - lst = names.keys() - types = [] - for x in lst: - t = uno.getTypeByName( x ) - types.append( t ) - - ret = tuple(types) , uno.generateUuid() - _g_typeTable[self.__class__] = ret - return ret - + ret = None + if self.__class__ in _g_typeTable: + ret = _g_typeTable[self.__class__] + else: + names = {} + traverse = list(self.__class__.__bases__) + while len( traverse ) > 0: + item = traverse.pop() + bases = item.__bases__ + if uno.isInterface( item ): + names[item.__pyunointerface__] = None + elif len(bases) > 0: + # the "else if", because we only need the most derived interface + traverse = traverse + list(bases)# + + lst = list(names.keys()) + types = [] + for x in lst: + t = uno.getTypeByName( x ) + types.append( t ) + + ret = tuple(types) , uno.generateUuid() + _g_typeTable[self.__class__] = ret + return ret + class Base(XTypeProvider): - def getTypes( self ): - return _unohelper_getHandle( self )[0] - def getImplementationId(self): - return _unohelper_getHandle( self )[1] + def getTypes( self ): + return _unohelper_getHandle( self )[0] + def getImplementationId(self): + return _unohelper_getHandle( self )[1] class CurrentContext(XCurrentContext, Base ): """a current context implementation, which first does a lookup in the given @@ -271,28 +271,27 @@ class CurrentContext(XCurrentContext, Base ): return self.oldContext.getValueByName( name ) else: return None - + # ------------------------------------------------- # implementation details # ------------------------------------------------- class _FactoryHelper_( XSingleComponentFactory, XServiceInfo, Base ): - def __init__( self, clazz, implementationName, serviceNames ): - self.clazz = clazz - self.implementationName = implementationName - self.serviceNames = serviceNames - - def getImplementationName( self ): - return self.implementationName - - def supportsService( self, ServiceName ): - return ServiceName in self.serviceNames - - def getSupportedServiceNames( self ): - return self.serviceNames - - def createInstanceWithContext( self, context ): - return self.clazz( context ) - - def createInstanceWithArgumentsAndContext( self, args, context ): - return self.clazz( context, *args ) - + def __init__( self, clazz, implementationName, serviceNames ): + self.clazz = clazz + self.implementationName = implementationName + self.serviceNames = serviceNames + + def getImplementationName( self ): + return self.implementationName + + def supportsService( self, ServiceName ): + return ServiceName in self.serviceNames + + def getSupportedServiceNames( self ): + return self.serviceNames + + def createInstanceWithContext( self, context ): + return self.clazz( context ) + + def createInstanceWithArgumentsAndContext( self, args, context ): + return self.clazz( context, *args ) |