home *** CD-ROM | disk | FTP | other *** search
/ Freelog 52 / Freelog052.iso / Dossier / OpenOffice / f_0395 / uno.py
Text File  |  2003-07-18  |  13KB  |  366 lines

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