unohelper.py 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297
  1. # -*- tab-width: 4; indent-tabs-mode: nil; py-indent-offset: 4 -*-
  2. #
  3. # This file is part of the LibreOffice project.
  4. #
  5. # This Source Code Form is subject to the terms of the Mozilla Public
  6. # License, v. 2.0. If a copy of the MPL was not distributed with this
  7. # file, You can obtain one at http://mozilla.org/MPL/2.0/.
  8. #
  9. # This file incorporates work covered by the following license notice:
  10. #
  11. # Licensed to the Apache Software Foundation (ASF) under one or more
  12. # contributor license agreements. See the NOTICE file distributed
  13. # with this work for additional information regarding copyright
  14. # ownership. The ASF licenses this file to you under the Apache
  15. # License, Version 2.0 (the "License"); you may not use this file
  16. # except in compliance with the License. You may obtain a copy of
  17. # the License at http://www.apache.org/licenses/LICENSE-2.0 .
  18. #
  19. import uno
  20. import pyuno
  21. import os
  22. import sys
  23. from com.sun.star.lang import XTypeProvider, XSingleComponentFactory, XServiceInfo
  24. from com.sun.star.uno import RuntimeException, XCurrentContext
  25. from com.sun.star.beans.MethodConcept import ALL as METHOD_CONCEPT_ALL
  26. from com.sun.star.beans.PropertyConcept import ALL as PROPERTY_CONCEPT_ALL
  27. from com.sun.star.reflection.ParamMode import \
  28. IN as PARAM_MODE_IN, \
  29. OUT as PARAM_MODE_OUT, \
  30. INOUT as PARAM_MODE_INOUT
  31. from com.sun.star.beans.PropertyAttribute import \
  32. MAYBEVOID as PROP_ATTR_MAYBEVOID, \
  33. BOUND as PROP_ATTR_BOUND, \
  34. CONSTRAINED as PROP_ATTR_CONSTRAINED, \
  35. TRANSIENT as PROP_ATTR_TRANSIENT, \
  36. READONLY as PROP_ATTR_READONLY, \
  37. MAYBEAMBIGUOUS as PROP_ATTR_MAYBEAMBIGUOUS, \
  38. MAYBEDEFAULT as PROP_ATTR_MAYBEDEFAULT, \
  39. REMOVABLE as PROP_ATTR_REMOVABLE
  40. def _mode_to_str( mode ):
  41. ret = "[]"
  42. if mode == PARAM_MODE_INOUT:
  43. ret = "[inout]"
  44. elif mode == PARAM_MODE_OUT:
  45. ret = "[out]"
  46. elif mode == PARAM_MODE_IN:
  47. ret = "[in]"
  48. return ret
  49. def _propertymode_to_str( mode ):
  50. ret = ""
  51. if PROP_ATTR_REMOVABLE & mode:
  52. ret = ret + "removable "
  53. if PROP_ATTR_MAYBEDEFAULT & mode:
  54. ret = ret + "maybedefault "
  55. if PROP_ATTR_MAYBEAMBIGUOUS & mode:
  56. ret = ret + "maybeambiguous "
  57. if PROP_ATTR_READONLY & mode:
  58. ret = ret + "readonly "
  59. if PROP_ATTR_TRANSIENT & mode:
  60. ret = ret + "transient "
  61. if PROP_ATTR_CONSTRAINED & mode:
  62. ret = ret + "constrained "
  63. if PROP_ATTR_BOUND & mode:
  64. ret = ret + "bound "
  65. if PROP_ATTR_MAYBEVOID & mode:
  66. ret = ret + "maybevoid "
  67. return ret.rstrip()
  68. def inspect( obj , out ):
  69. if isinstance( obj, uno.Type ) or \
  70. isinstance( obj, uno.Char ) or \
  71. isinstance( obj, uno.Bool ) or \
  72. isinstance( obj, uno.ByteSequence ) or \
  73. isinstance( obj, uno.Enum ) or \
  74. isinstance( obj, uno.Any ):
  75. out.write( str(obj) + "\n")
  76. return
  77. ctx = uno.getComponentContext()
  78. introspection = \
  79. ctx.ServiceManager.createInstanceWithContext( "com.sun.star.beans.Introspection", ctx )
  80. out.write( "Supported services:\n" )
  81. if hasattr( obj, "getSupportedServiceNames" ):
  82. names = obj.getSupportedServiceNames()
  83. for ii in names:
  84. out.write( " " + ii + "\n" )
  85. else:
  86. out.write( " unknown\n" )
  87. out.write( "Interfaces:\n" )
  88. if hasattr( obj, "getTypes" ):
  89. interfaces = obj.getTypes()
  90. for ii in interfaces:
  91. out.write( " " + ii.typeName + "\n" )
  92. else:
  93. out.write( " unknown\n" )
  94. access = introspection.inspect( obj )
  95. methods = access.getMethods( METHOD_CONCEPT_ALL )
  96. out.write( "Methods:\n" )
  97. for ii in methods:
  98. out.write( " " + ii.ReturnType.Name + " " + ii.Name )
  99. args = ii.ParameterTypes
  100. infos = ii.ParameterInfos
  101. out.write( "( " )
  102. for i in range( 0, len( args ) ):
  103. if i > 0:
  104. out.write( ", " )
  105. out.write( _mode_to_str( infos[i].aMode ) + " " + args[i].Name + " " + infos[i].aName )
  106. out.write( " )\n" )
  107. props = access.getProperties( PROPERTY_CONCEPT_ALL )
  108. out.write ("Properties:\n" )
  109. for ii in props:
  110. out.write( " ("+_propertymode_to_str( ii.Attributes ) + ") "+ii.Type.typeName+" "+ii.Name+ "\n" )
  111. def createSingleServiceFactory( clazz, implementationName, serviceNames ):
  112. return _FactoryHelper_( clazz, implementationName, serviceNames )
  113. class _ImplementationHelperEntry:
  114. def __init__(self, ctor,serviceNames):
  115. self.ctor = ctor
  116. self.serviceNames = serviceNames
  117. class ImplementationHelper:
  118. def __init__(self):
  119. self.impls = {}
  120. def addImplementation( self, ctor, implementationName, serviceNames ):
  121. self.impls[implementationName] = _ImplementationHelperEntry(ctor,serviceNames)
  122. def writeRegistryInfo( self, regKey, smgr ):
  123. for i in list(self.impls.items()):
  124. keyName = "/"+ i[0] + "/UNO/SERVICES"
  125. key = regKey.createKey( keyName )
  126. for serviceName in i[1].serviceNames:
  127. key.createKey( serviceName )
  128. return 1
  129. def getComponentFactory( self, implementationName , regKey, smgr ):
  130. entry = self.impls.get( implementationName, None )
  131. if entry is None:
  132. raise RuntimeException( implementationName + " is unknown" , None )
  133. return createSingleServiceFactory( entry.ctor, implementationName, entry.serviceNames )
  134. def getSupportedServiceNames( self, implementationName ):
  135. entry = self.impls.get( implementationName, None )
  136. if entry is None:
  137. raise RuntimeException( implementationName + " is unknown" , None )
  138. return entry.serviceNames
  139. def supportsService( self, implementationName, serviceName ):
  140. entry = self.impls.get( implementationName,None )
  141. if entry is None:
  142. raise RuntimeException( implementationName + " is unknown", None )
  143. return serviceName in entry.serviceNames
  144. class ImplementationEntry:
  145. def __init__(self, implName, supportedServices, clazz ):
  146. self.implName = implName
  147. self.supportedServices = supportedServices
  148. self.clazz = clazz
  149. def writeRegistryInfoHelper( smgr, regKey, seqEntries ):
  150. for entry in seqEntries:
  151. keyName = "/"+ entry.implName + "/UNO/SERVICES"
  152. key = regKey.createKey( keyName )
  153. for serviceName in entry.supportedServices:
  154. key.createKey( serviceName )
  155. def systemPathToFileUrl( systemPath ):
  156. "returns a file-url for the given system path"
  157. return pyuno.systemPathToFileUrl( systemPath )
  158. def fileUrlToSystemPath( url ):
  159. "returns a system path (determined by the system, the python interpreter is running on)"
  160. return pyuno.fileUrlToSystemPath( url )
  161. def absolutize( path, relativeUrl ):
  162. "returns an absolute file url from the given urls"
  163. return pyuno.absolutize( path, relativeUrl )
  164. def getComponentFactoryHelper( implementationName, smgr, regKey, seqEntries ):
  165. for x in seqEntries:
  166. if x.implName == implementationName:
  167. return createSingleServiceFactory( x.clazz, implementationName, x.supportedServices )
  168. def addComponentsToContext( toBeExtendedContext, contextRuntime, componentUrls, loaderName ):
  169. smgr = contextRuntime.ServiceManager
  170. loader = smgr.createInstanceWithContext( loaderName, contextRuntime )
  171. implReg = smgr.createInstanceWithContext( "com.sun.star.registry.ImplementationRegistration",contextRuntime)
  172. isWin = os.name == 'nt' or os.name == 'dos'
  173. isMac = sys.platform == 'darwin'
  174. # create a temporary registry
  175. for componentUrl in componentUrls:
  176. reg = smgr.createInstanceWithContext( "com.sun.star.registry.SimpleRegistry", contextRuntime )
  177. reg.open( "", 0, 1 )
  178. if not isWin and componentUrl.endswith( ".uno" ): # still allow platform independent naming
  179. if isMac:
  180. componentUrl = componentUrl + ".dylib"
  181. else:
  182. componentUrl = componentUrl + ".so"
  183. implReg.registerImplementation( loaderName,componentUrl, reg )
  184. rootKey = reg.getRootKey()
  185. implementationKey = rootKey.openKey( "IMPLEMENTATIONS" )
  186. implNames = implementationKey.getKeyNames()
  187. extSMGR = toBeExtendedContext.ServiceManager
  188. for x in implNames:
  189. fac = loader.activate( max(x.split("/")),"",componentUrl,rootKey)
  190. extSMGR.insert( fac )
  191. reg.close()
  192. # never shrinks !
  193. _g_typeTable = {}
  194. def _unohelper_getHandle( self):
  195. ret = None
  196. if self.__class__ in _g_typeTable:
  197. ret = _g_typeTable[self.__class__]
  198. else:
  199. names = {}
  200. traverse = list(self.__class__.__bases__)
  201. while len( traverse ) > 0:
  202. item = traverse.pop()
  203. bases = item.__bases__
  204. if uno.isInterface( item ):
  205. names[item.__pyunointerface__] = None
  206. elif len(bases) > 0:
  207. # the "else if", because we only need the most derived interface
  208. traverse = traverse + list(bases)#
  209. lst = list(names.keys())
  210. types = []
  211. for x in lst:
  212. t = uno.getTypeByName( x )
  213. types.append( t )
  214. ret = tuple(types)
  215. _g_typeTable[self.__class__] = ret
  216. return ret
  217. class Base(XTypeProvider):
  218. def getTypes( self ):
  219. return _unohelper_getHandle( self )
  220. def getImplementationId(self):
  221. return ()
  222. class CurrentContext(XCurrentContext, Base ):
  223. """a current context implementation, which first does a lookup in the given
  224. hashmap and if the key cannot be found, it delegates to the predecessor
  225. if available
  226. """
  227. def __init__( self, oldContext, hashMap ):
  228. self.hashMap = hashMap
  229. self.oldContext = oldContext
  230. def getValueByName( self, name ):
  231. if name in self.hashMap:
  232. return self.hashMap[name]
  233. elif self.oldContext is not None:
  234. return self.oldContext.getValueByName( name )
  235. else:
  236. return None
  237. # -------------------------------------------------
  238. # implementation details
  239. # -------------------------------------------------
  240. class _FactoryHelper_( XSingleComponentFactory, XServiceInfo, Base ):
  241. def __init__( self, clazz, implementationName, serviceNames ):
  242. self.clazz = clazz
  243. self.implementationName = implementationName
  244. self.serviceNames = serviceNames
  245. def getImplementationName( self ):
  246. return self.implementationName
  247. def supportsService( self, ServiceName ):
  248. return ServiceName in self.serviceNames
  249. def getSupportedServiceNames( self ):
  250. return self.serviceNames
  251. def createInstanceWithContext( self, context ):
  252. return self.clazz( context )
  253. def createInstanceWithArgumentsAndContext( self, args, context ):
  254. return self.clazz( context, *args )
  255. # vim: set shiftwidth=4 softtabstop=4 expandtab: