home *** CD-ROM | disk | FTP | other *** search
/ Maximum CD 2009 June / maximum-cd-2009-06.iso / DiscContents / OOo_3.0.1_Win32Intel_install_wJRE_en-US.exe / openofficeorg1.cab / uno.py < prev    next >
Encoding:
Python Source  |  2009-01-09  |  12.5 KB  |  359 lines

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