home *** CD-ROM | disk | FTP | other *** search
/ Enter 2005 October / enter-2005-10.iso / files / OOo_2.0_windows_install_fi.exe / openofficeorg3.cab / uno.py < prev    next >
Encoding:
Python Source  |  2005-10-15  |  11.8 KB  |  341 lines

  1. #*************************************************************************
  2. #
  3. #   OpenOffice.org - a multi-platform office productivity suite
  4. #
  5. #   $RCSfile: uno.py,v $
  6. #
  7. #   $Revision: 1.6 $
  8. #
  9. #   last change: $Author: rt $ $Date: 2005/09/08 16:54:32 $
  10. #
  11. #   The Contents of this file are made available subject to
  12. #   the terms of GNU Lesser General Public License Version 2.1.
  13. #
  14. #
  15. #     GNU Lesser General Public License Version 2.1
  16. #     =============================================
  17. #     Copyright 2005 by Sun Microsystems, Inc.
  18. #     901 San Antonio Road, Palo Alto, CA 94303, USA
  19. #
  20. #     This library is free software; you can redistribute it and/or
  21. #     modify it under the terms of the GNU Lesser General Public
  22. #     License version 2.1, as published by the Free Software Foundation.
  23. #
  24. #     This library is distributed in the hope that it will be useful,
  25. #     but WITHOUT ANY WARRANTY; without even the implied warranty of
  26. #     MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
  27. #     Lesser General Public License for more details.
  28. #
  29. #     You should have received a copy of the GNU Lesser General Public
  30. #     License along with this library; if not, write to the Free Software
  31. #     Foundation, Inc., 59 Temple Place, Suite 330, Boston,
  32. #     MA  02111-1307  USA
  33. #
  34. #*************************************************************************
  35. import sys
  36.  
  37. import pyuno
  38. import __builtin__
  39.  
  40. # all functions and variables starting with a underscore (_) must be considered private
  41. # and can be changed at any time. Don't use them
  42. _g_ctx = pyuno.getComponentContext( )
  43. _g_delegatee = __builtin__.__dict__["__import__"]
  44.  
  45. def getComponentContext():
  46.     """ returns the UNO component context, that was used to initialize the python runtime.
  47.     """ 
  48.     return _g_ctx      
  49.  
  50. def getConstantByName( constant ):
  51.     "Looks up the value of a idl constant by giving its explicit name"
  52.     return pyuno.getConstantByName( constant )
  53.  
  54. def getTypeByName( typeName):
  55.     """ returns a uno.Type instance of the type given by typeName. In case the
  56.         type does not exist, a com.sun.star.uno.RuntimeException is raised.
  57.     """ 
  58.     return pyuno.getTypeByName( typeName )
  59.  
  60. def createUnoStruct( typeName, *args ):
  61.     """creates a uno struct or exception given by typeName. The parameter args may
  62.     1) be empty. In this case, you get a default constructed uno structure.
  63.        ( e.g. createUnoStruct( "com.sun.star.uno.Exception" ) )
  64.     2) be a sequence with exactly one element, that contains an instance of typeName.
  65.        In this case, a copy constructed instance of typeName is returned
  66.        ( e.g. createUnoStruct( "com.sun.star.uno.Exception" , e ) )
  67.     3) be a sequence, where the length of the sequence must match the number of
  68.        elements within typeName (e.g.
  69.        createUnoStruct( "com.sun.star.uno.Exception", "foo error" , self) ). The
  70.        elements with in the sequence must match the type of each struct element,
  71.        otherwise an exception is thrown.
  72.     """
  73.     return getClass(typeName)( *args )
  74.  
  75. def getClass( typeName ):
  76.     """returns the class of a concrete uno exception, struct or interface
  77.     """
  78.     return pyuno.getClass(typeName)
  79.  
  80. def isInterface( obj ):
  81.     """returns true, when obj is a class of a uno interface"""
  82.     return pyuno.isInterface( obj )
  83.  
  84. def generateUuid():
  85.     "returns a 16 byte sequence containing a newly generated uuid or guid, see rtl/uuid.h "
  86.     return pyuno.generateUuid()        
  87.  
  88. def systemPathToFileUrl( systemPath ):
  89.     "returns a file-url for the given system path"
  90.     return pyuno.systemPathToFileUrl( systemPath )
  91.  
  92. def fileUrlToSystemPath( url ):
  93.     "returns a system path (determined by the system, the python interpreter is running on)"
  94.     return pyuno.fileUrlToSystemPath( url )
  95.  
  96. def absolutize( path, relativeUrl ):
  97.     "returns an absolute file url from the given urls"
  98.     return pyuno.absolutize( path, relativeUrl )
  99.         
  100. class Enum:
  101.     "Represents a UNO idl enum, use an instance of this class to explicitly pass a boolean to UNO" 
  102.     #typeName the name of the enum as a string
  103.     #value    the actual value of this enum as a string
  104.     def __init__(self,typeName, value):
  105.         self.typeName = typeName
  106.         self.value = value
  107.         pyuno.checkEnum( self )
  108.  
  109.     def __repr__(self):
  110.         return "<uno.Enum %s (%r)>" % (self.typeName, self.value)
  111.  
  112.     def __eq__(self, that):
  113.         if not isinstance(that, Enum):
  114.             return False
  115.         return (self.typeName == that.typeName) and (self.value == that.value)
  116.  
  117. class Type:
  118.     "Represents a UNO type, use an instance of this class to explicitly pass a boolean to UNO"
  119. #    typeName                 # Name of the UNO type
  120. #    typeClass                # python Enum of TypeClass,  see com/sun/star/uno/TypeClass.idl
  121.     def __init__(self, typeName, typeClass):
  122.         self.typeName = typeName
  123.         self.typeClass = typeClass
  124.         pyuno.checkType(self)
  125.     def __repr__(self):
  126.         return "<Type instance %s (%r)>" % (self.typeName, self.typeClass)
  127.  
  128.     def __eq__(self, that):
  129.         if not isinstance(that, Type):
  130.             return False
  131.         return self.typeClass == that.typeClass and self.typeName == that.typeName
  132.  
  133.     def __hash__(self):
  134.         return self.typeName.__hash__()
  135.  
  136. class Bool(object):
  137.     """Represents a UNO boolean, use an instance of this class to explicitly 
  138.        pass a boolean to UNO.
  139.        Note: This class is deprecated. Use python's True and False directly instead
  140.     """
  141.     def __new__(cls, value):
  142.         if isinstance(value, (str, unicode)) and value == "true":
  143.             return True
  144.         if isinstance(value, (str, unicode)) and value == "false":
  145.             return False
  146.         if value:
  147.             return True
  148.         return False
  149.  
  150. class Char:
  151.     "Represents a UNO char, use an instance of this class to explicitly pass a char to UNO"
  152.     # @param value pass a Unicode string with length 1
  153.     def __init__(self,value):
  154.         assert isinstance(value, unicode)
  155.         assert len(value) == 1
  156.         self.value=value
  157.  
  158.     def __repr__(self):
  159.         return "<Char instance %s>" % (self.value, )
  160.         
  161.     def __eq__(self, that):
  162.         if isinstance(that, (str, unicode)):
  163.             if len(that) > 1:
  164.                 return False
  165.             return self.value == that[0]
  166.         if isinstance(that, Char):        
  167.             return self.value == that.value
  168.         return False
  169.  
  170. # Suggested by Christian, but still some open problems which need to be solved first
  171. #
  172. #class ByteSequence(str):
  173. #
  174. #    def __repr__(self):
  175. #        return "<ByteSequence instance %s>" % str.__repr__(self)
  176.  
  177.     # for a little bit compatitbility; setting value is not possible as 
  178.     # strings are immutable
  179. #    def _get_value(self):
  180. #        return self
  181. #
  182. #    value = property(_get_value)        
  183.  
  184. class ByteSequence:
  185.     def __init__(self, value):
  186.         if isinstance(value, str):
  187.             self.value = value
  188.         elif isinstance(value, ByteSequence):
  189.             self.value = value.value
  190.         else:
  191.             raise TypeError("expected string or bytesequence")
  192.  
  193.     def __repr__(self):
  194.         return "<ByteSequence instance '%s'>" % (self.value, )
  195.  
  196.     def __eq__(self, that):
  197.         if isinstance( that, ByteSequence):
  198.             return self.value == that.value
  199.         if isinstance(that, str):
  200.             return self.value == that
  201.         return False
  202.  
  203.     def __len__(self):
  204.         return len(self.value)
  205.  
  206.     def __getitem__(self, index):
  207.         return self.value[index]
  208.  
  209.     def __iter__( self ):
  210.         return self.value.__iter__()
  211.  
  212.     def __add__( self , b ):
  213.         if isinstance( b, str ):
  214.             return ByteSequence( self.value + b )
  215.         elif isinstance( b, ByteSequence ):
  216.             return ByteSequence( self.value + b.value )
  217.         raise TypeError( "expected string or ByteSequence as operand" )
  218.  
  219.     def __hash__( self ):
  220.         return self.value.hash()
  221.  
  222.  
  223. class Any:
  224.     "use only in connection with uno.invoke() to pass an explicit typed any"
  225.     def __init__(self, type, value ):
  226.         if isinstance( type, Type ):
  227.             self.type = type
  228.         else:
  229.             self.type = getTypeByName( type )
  230.         self.value = value
  231.  
  232. def invoke( object, methodname, argTuple ):
  233.     "use this function to pass exactly typed anys to the callee (using uno.Any)"
  234.     return pyuno.invoke( object, methodname, argTuple )
  235.     
  236. #---------------------------------------------------------------------------------------
  237. # don't use any functions beyond this point, private section, likely to change
  238. #---------------------------------------------------------------------------------------
  239. def _uno_import( name, *optargs ):
  240.     try:
  241. #       print "optargs = " + repr(optargs)
  242.         if len(optargs) == 0:
  243.            return _g_delegatee( name )
  244.            #print _g_delegatee
  245.         return _g_delegatee( name, *optargs )
  246.     except ImportError:
  247.         if len(optargs) != 3 or not optargs[2]:
  248.            raise
  249.     globals = optargs[0]
  250.     locals = optargs[1]
  251.     fromlist = optargs[2]
  252.     modnames = name.split( "." )
  253.     mod = None
  254.     d = sys.modules
  255.     for x in modnames:
  256.         if d.has_key(x):
  257.            mod = d[x]
  258.         else:
  259.            mod = pyuno.__class__(x)  # How to create a module ??
  260.         d = mod.__dict__
  261.  
  262.     RuntimeException = pyuno.getClass( "com.sun.star.uno.RuntimeException" )
  263.     for x in fromlist:
  264.        if not d.has_key(x):
  265.           if x.startswith( "typeOf" ):
  266.              try: 
  267.                 d[x] = pyuno.getTypeByName( name + "." + x[6:len(x)] )
  268.              except RuntimeException,e:
  269.                 raise ImportError( "type " + name + "." + x[6:len(x)] +" is unknown" )
  270.           else:
  271.             try:
  272.                 # check for structs, exceptions or interfaces
  273.                 d[x] = pyuno.getClass( name + "." + x )
  274.             except RuntimeException,e:
  275.                 # check for enums 
  276.                 try:
  277.                    d[x] = Enum( name , x )
  278.                 except RuntimeException,e2:
  279.                    # check for constants
  280.                    try:
  281.                       d[x] = getConstantByName( name + "." + x )
  282.                    except RuntimeException,e3:
  283.                       # no known uno type !
  284.                       raise ImportError( "type "+ name + "." +x + " is unknown" )
  285.     return mod
  286.  
  287. # hook into the __import__ chain    
  288. __builtin__.__dict__["__import__"] = _uno_import
  289.         
  290. # private function, don't use
  291. def _impl_extractName(name):
  292.     r = range (len(name)-1,0,-1)
  293.     for i in r:
  294.         if name[i] == ".":
  295.            name = name[i+1:len(name)]
  296.            break
  297.     return name            
  298.  
  299. # private, referenced from the pyuno shared library
  300. def _uno_struct__init__(self,*args):
  301.     if len(args) == 1 and hasattr(args[0], "__class__") and args[0].__class__ == self.__class__ :
  302.        self.__dict__["value"] = args[0]
  303.     else:
  304.        self.__dict__["value"] = pyuno._createUnoStructHelper(self.__class__.__pyunostruct__,args)
  305.     
  306. # private, referenced from the pyuno shared library
  307. def _uno_struct__getattr__(self,name):
  308.     return __builtin__.getattr(self.__dict__["value"],name)
  309.  
  310. # private, referenced from the pyuno shared library
  311. def _uno_struct__setattr__(self,name,value):
  312.     return __builtin__.setattr(self.__dict__["value"],name,value)
  313.  
  314. # private, referenced from the pyuno shared library
  315. def _uno_struct__repr__(self):
  316.     return repr(self.__dict__["value"])
  317.     
  318. def _uno_struct__str__(self):
  319.     return str(self.__dict__["value"])
  320.  
  321. # private, referenced from the pyuno shared library
  322. def _uno_struct__eq__(self,cmp):
  323.     if hasattr(cmp,"value"):
  324.        return self.__dict__["value"] == cmp.__dict__["value"]
  325.     return False
  326.      
  327. def _uno_extract_printable_stacktrace( trace ):
  328.     mod = None
  329.     try:
  330.         mod = __import__("traceback")
  331.     except ImportError,e:
  332.         pass
  333.     ret = ""
  334.     if mod:
  335.         lst = mod.format_tb( trace )
  336.         for i in lst:
  337.             ret = ret + i
  338.     else:
  339.         ret = "Coludn't import traceback module"
  340.     return ret
  341.