home *** CD-ROM | disk | FTP | other *** search
/ Maximum CD 2011 June / maximum-cd-2011-06.iso / DiscContents / LibO_3.3.1_Win_x86_install_multi.exe / libreoffice1.cab / unohelper.py < prev    next >
Encoding:
Python Source  |  2011-02-16  |  10.8 KB  |  305 lines

  1. #*************************************************************************
  2. #
  3. # DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  4. # Copyright 2000, 2010 Oracle and/or its affiliates.
  5. #
  6. # OpenOffice.org - a multi-platform office productivity suite
  7. #
  8. # This file is part of OpenOffice.org.
  9. #
  10. # OpenOffice.org is free software: you can redistribute it and/or modify
  11. # it under the terms of the GNU Lesser General Public License version 3
  12. # only, as published by the Free Software Foundation.
  13. #
  14. # OpenOffice.org is distributed in the hope that it will be useful,
  15. # but WITHOUT ANY WARRANTY; without even the implied warranty of
  16. # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
  17. # GNU Lesser General Public License version 3 for more details
  18. # (a copy is included in the LICENSE file that accompanied this code).
  19. #
  20. # You should have received a copy of the GNU Lesser General Public License
  21. # version 3 along with OpenOffice.org.  If not, see
  22. # <http://www.openoffice.org/license.html>
  23. # for a copy of the LGPLv3 License.
  24. #
  25. #*************************************************************************
  26. import uno
  27. import pyuno
  28. import os
  29. import sys
  30.  
  31. from com.sun.star.lang import XTypeProvider, XSingleComponentFactory, XServiceInfo
  32. from com.sun.star.uno import RuntimeException, XCurrentContext
  33. from com.sun.star.beans.MethodConcept import ALL as METHOD_CONCEPT_ALL
  34. from com.sun.star.beans.PropertyConcept import ALL as PROPERTY_CONCEPT_ALL
  35.  
  36. from com.sun.star.reflection.ParamMode import \
  37.      IN as PARAM_MODE_IN, \
  38.      OUT as PARAM_MODE_OUT, \
  39.      INOUT as PARAM_MODE_INOUT
  40.  
  41. from com.sun.star.beans.PropertyAttribute import \
  42.      MAYBEVOID as PROP_ATTR_MAYBEVOID, \
  43.      BOUND as PROP_ATTR_BOUND, \
  44.      CONSTRAINED as PROP_ATTR_CONSTRAINED, \
  45.      TRANSIENT as PROP_ATTR_TRANSIENT, \
  46.      READONLY as PROP_ATTR_READONLY, \
  47.      MAYBEAMBIGUOUS as PROP_ATTR_MAYBEAMBIGUOUS, \
  48.      MAYBEDEFAULT as PROP_ATTR_MAYBEDEFAULT, \
  49.      REMOVEABLE as PROP_ATTR_REMOVEABLE
  50.  
  51. def _mode_to_str( mode ):
  52.     ret = "[]"
  53.     if mode == PARAM_MODE_INOUT:
  54.         ret = "[inout]"
  55.     elif mode == PARAM_MODE_OUT:
  56.         ret = "[out]"
  57.     elif mode == PARAM_MODE_IN:
  58.         ret = "[in]"
  59.     return ret
  60.  
  61. def _propertymode_to_str( mode ):
  62.     ret = ""
  63.     if PROP_ATTR_REMOVEABLE & mode:
  64.         ret = ret + "removeable "
  65.     if PROP_ATTR_MAYBEDEFAULT & mode:
  66.         ret = ret + "maybedefault "
  67.     if PROP_ATTR_MAYBEAMBIGUOUS & mode:
  68.         ret = ret + "maybeambigous "
  69.     if PROP_ATTR_READONLY & mode:
  70.         ret = ret + "readonly "
  71.     if PROP_ATTR_TRANSIENT & mode:
  72.         ret = ret + "tranient "
  73.     if PROP_ATTR_CONSTRAINED & mode:
  74.         ret = ret + "constrained "
  75.     if PROP_ATTR_BOUND & mode:
  76.         ret = ret + "bound "
  77.     if PROP_ATTR_MAYBEVOID & mode:
  78.         ret = ret + "maybevoid "
  79.     return ret.rstrip()
  80.     
  81. def inspect( obj , out ):
  82.     if isinstance( obj, uno.Type ) or \
  83.        isinstance( obj, uno.Char ) or \
  84.        isinstance( obj, uno.Bool ) or \
  85.        isinstance( obj, uno.ByteSequence ) or \
  86.        isinstance( obj, uno.Enum ) or \
  87.        isinstance( obj, uno.Any ):
  88.         out.write( str(obj) + "\n")
  89.         return
  90.  
  91.     ctx = uno.getComponentContext()
  92.     introspection = \
  93.          ctx.ServiceManager.createInstanceWithContext( "com.sun.star.beans.Introspection", ctx )
  94.  
  95.     out.write( "Supported services:\n" )
  96.     if hasattr( obj, "getSupportedServiceNames" ):
  97.         names = obj.getSupportedServiceNames()
  98.         for ii in names:
  99.             out.write( "  " + ii + "\n" )
  100.     else:
  101.         out.write( "  unknown\n" )
  102.  
  103.     out.write( "Interfaces:\n" )
  104.     if hasattr( obj, "getTypes" ):
  105.         interfaces = obj.getTypes()
  106.         for ii in interfaces:
  107.             out.write( "  " + ii.typeName + "\n" )
  108.     else:
  109.         out.write( "  unknown\n" )
  110.         
  111.     access = introspection.inspect( obj )
  112.     methods = access.getMethods( METHOD_CONCEPT_ALL )
  113.     out.write( "Methods:\n" )
  114.     for ii in methods:
  115.         out.write( "  " + ii.ReturnType.Name + " " + ii.Name )
  116.         args = ii.ParameterTypes
  117.         infos = ii.ParameterInfos
  118.         out.write( "( " )
  119.         for i in range( 0, len( args ) ):
  120.             if i > 0:
  121.                 out.write( ", " )
  122.             out.write( _mode_to_str( infos[i].aMode ) + " " + args[i].Name + " " + infos[i].aName )
  123.         out.write( " )\n" )
  124.  
  125.     props = access.getProperties( PROPERTY_CONCEPT_ALL )
  126.     out.write ("Properties:\n" )
  127.     for ii in props:
  128.         out.write( "  ("+_propertymode_to_str( ii.Attributes ) + ") "+ii.Type.typeName+" "+ii.Name+ "\n" )
  129.  
  130. def createSingleServiceFactory( clazz, implementationName, serviceNames ):
  131.     return _FactoryHelper_( clazz, implementationName, serviceNames )
  132.  
  133. class _ImplementationHelperEntry:
  134.       def __init__(self, ctor,serviceNames):
  135.       self.ctor = ctor
  136.       self.serviceNames = serviceNames
  137.       
  138. class ImplementationHelper:
  139.       def __init__(self):
  140.       self.impls = {}
  141.       
  142.       def addImplementation( self, ctor, implementationName, serviceNames ):
  143.           self.impls[implementationName] =  _ImplementationHelperEntry(ctor,serviceNames)
  144.       
  145.       def writeRegistryInfo( self, regKey, smgr ):
  146.           for i in self.impls.items():
  147.           keyName = "/"+ i[0] + "/UNO/SERVICES"
  148.           key = regKey.createKey( keyName )
  149.           for serviceName in i[1].serviceNames:
  150.           key.createKey( serviceName )
  151.           return 1
  152.  
  153.       def getComponentFactory( self, implementationName , regKey, smgr ):
  154.       entry = self.impls.get( implementationName, None )
  155.       if entry == None:
  156.          raise RuntimeException( implementationName + " is unknown" , None )
  157.       return createSingleServiceFactory( entry.ctor, implementationName, entry.serviceNames )
  158.  
  159.       def getSupportedServiceNames( self, implementationName ):
  160.       entry = self.impls.get( implementationName, None )
  161.       if entry == None:
  162.          raise RuntimeException( implementationName + " is unknown" , None )
  163.       return entry.serviceNames         
  164.       
  165.       def supportsService( self, implementationName, serviceName ):
  166.       entry = self.impls.get( implementationName,None )
  167.       if entry == None:
  168.          raise RuntimeException( implementationName + " is unknown", None )
  169.           return serviceName in entry.serviceNames         
  170.  
  171.       
  172. class ImplementationEntry:
  173.       def __init__(self, implName, supportedServices, clazz ):
  174.       self.implName = implName
  175.       self.supportedServices = supportedServices
  176.       self.clazz = clazz
  177.  
  178. def writeRegistryInfoHelper( smgr, regKey, seqEntries ):
  179.     for entry in seqEntries:
  180.         keyName = "/"+ entry.implName + "/UNO/SERVICES"
  181.     key = regKey.createKey( keyName )
  182.     for serviceName in entry.supportedServices:
  183.         key.createKey( serviceName )
  184.  
  185. def systemPathToFileUrl( systemPath ):
  186.     "returns a file-url for the given system path"
  187.     return pyuno.systemPathToFileUrl( systemPath )
  188.  
  189. def fileUrlToSystemPath( url ):
  190.     "returns a system path (determined by the system, the python interpreter is running on)"
  191.     return pyuno.fileUrlToSystemPath( url )
  192.  
  193. def absolutize( path, relativeUrl ):
  194.     "returns an absolute file url from the given urls"
  195.     return pyuno.absolutize( path, relativeUrl )
  196.         
  197. def getComponentFactoryHelper( implementationName, smgr, regKey, seqEntries ):
  198.     for x in seqEntries:
  199.     if x.implName == implementationName:
  200.        return createSingleServiceFactory( x.clazz, implementationName, x.supportedServices )
  201.  
  202. def addComponentsToContext( toBeExtendedContext, contextRuntime, componentUrls, loaderName ):
  203.     smgr = contextRuntime.ServiceManager
  204.     loader = smgr.createInstanceWithContext( loaderName, contextRuntime )
  205.     implReg = smgr.createInstanceWithContext( "com.sun.star.registry.ImplementationRegistration",contextRuntime)
  206.  
  207.     isWin = os.name == 'nt' or os.name == 'dos'
  208.     isMac = sys.platform == 'darwin'
  209.     #   create a temporary registry
  210.     for componentUrl in componentUrls:
  211.         reg = smgr.createInstanceWithContext( "com.sun.star.registry.SimpleRegistry", contextRuntime )
  212.     reg.open( "", 0, 1 )
  213.         if not isWin and componentUrl.endswith( ".uno" ):  # still allow platform independent naming
  214.             if isMac:
  215.                componentUrl = componentUrl + ".dylib"
  216.             else:
  217.                componentUrl = componentUrl + ".so"
  218.  
  219.     implReg.registerImplementation( loaderName,componentUrl, reg )
  220.     rootKey = reg.getRootKey()
  221.     implementationKey = rootKey.openKey( "IMPLEMENTATIONS" )
  222.     implNames = implementationKey.getKeyNames()
  223.     extSMGR = toBeExtendedContext.ServiceManager
  224.     for x in implNames:
  225.         fac = loader.activate( max(x.split("/")),"",componentUrl,rootKey)
  226.         extSMGR.insert( fac )
  227.     reg.close()
  228.                 
  229. # never shrinks !
  230. _g_typeTable = {}
  231. def _unohelper_getHandle( self):
  232.    ret = None
  233.    if _g_typeTable.has_key( self.__class__ ):
  234.      ret = _g_typeTable[self.__class__]
  235.    else:
  236.      names = {}
  237.      traverse = list(self.__class__.__bases__)
  238.      while len( traverse ) > 0:
  239.          item = traverse.pop()
  240.          bases = item.__bases__
  241.          if uno.isInterface( item ):
  242.              names[item.__pyunointerface__] = None
  243.          elif len(bases) > 0:
  244.              # the "else if", because we only need the most derived interface
  245.              traverse = traverse + list(bases)#
  246.  
  247.      lst = names.keys()
  248.      types = []
  249.      for x in lst:
  250.          t = uno.getTypeByName( x )
  251.          types.append( t )
  252.          
  253.      ret = tuple(types) , uno.generateUuid()
  254.      _g_typeTable[self.__class__] = ret
  255.    return ret
  256.   
  257. class Base(XTypeProvider):
  258.       def getTypes( self ):
  259.       return _unohelper_getHandle( self )[0]
  260.       def getImplementationId(self):
  261.       return _unohelper_getHandle( self )[1]
  262.  
  263. class CurrentContext(XCurrentContext, Base ):
  264.     """a current context implementation, which first does a lookup in the given
  265.        hashmap and if the key cannot be found, it delegates to the predecessor
  266.        if available
  267.     """
  268.     def __init__( self, oldContext, hashMap ):
  269.         self.hashMap = hashMap
  270.         self.oldContext = oldContext
  271.  
  272.     def getValueByName( self, name ):
  273.         if name in self.hashMap:
  274.             return self.hashMap[name]
  275.         elif self.oldContext != None:
  276.             return self.oldContext.getValueByName( name )
  277.         else:
  278.             return None
  279.         
  280. # -------------------------------------------------
  281. # implementation details
  282. # -------------------------------------------------
  283. class _FactoryHelper_( XSingleComponentFactory, XServiceInfo, Base ):
  284.       def __init__( self, clazz, implementationName, serviceNames ):
  285.       self.clazz = clazz
  286.       self.implementationName = implementationName
  287.       self.serviceNames = serviceNames
  288.       
  289.       def getImplementationName( self ):
  290.       return self.implementationName
  291.  
  292.       def supportsService( self, ServiceName ):
  293.       return ServiceName in self.serviceNames
  294.  
  295.       def getSupportedServiceNames( self ):
  296.       return self.serviceNames
  297.  
  298.       def createInstanceWithContext( self, context ):
  299.       return self.clazz( context )
  300.           
  301.       def createInstanceWithArgumentsAndContext( self, args, context ):
  302.       return self.clazz( context, *args )
  303.       
  304.