xref: /AOO41X/main/pyuno/source/module/uno.py (revision 15745147782c03d17d5c7b69b18cf5a1fc42fd4c)
1a0428e9eSAndrew Rist#**************************************************************
2cdf0e10cSrcweir#
3a0428e9eSAndrew Rist#  Licensed to the Apache Software Foundation (ASF) under one
4a0428e9eSAndrew Rist#  or more contributor license agreements.  See the NOTICE file
5a0428e9eSAndrew Rist#  distributed with this work for additional information
6a0428e9eSAndrew Rist#  regarding copyright ownership.  The ASF licenses this file
7a0428e9eSAndrew Rist#  to you under the Apache License, Version 2.0 (the
8a0428e9eSAndrew Rist#  "License"); you may not use this file except in compliance
9a0428e9eSAndrew Rist#  with the License.  You may obtain a copy of the License at
10cdf0e10cSrcweir#
11a0428e9eSAndrew Rist#    http://www.apache.org/licenses/LICENSE-2.0
12cdf0e10cSrcweir#
13a0428e9eSAndrew Rist#  Unless required by applicable law or agreed to in writing,
14a0428e9eSAndrew Rist#  software distributed under the License is distributed on an
15a0428e9eSAndrew Rist#  "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
16a0428e9eSAndrew Rist#  KIND, either express or implied.  See the License for the
17a0428e9eSAndrew Rist#  specific language governing permissions and limitations
18a0428e9eSAndrew Rist#  under the License.
19cdf0e10cSrcweir#
20a0428e9eSAndrew Rist#**************************************************************
21cdf0e10cSrcweirimport sys
22cdf0e10cSrcweir
23cdf0e10cSrcweirimport pyuno
24*15745147SPedro Giffuni
25*15745147SPedro Giffunitry:
26*15745147SPedro Giffuni    import __builtin__ as builtin
27*15745147SPedro Giffuniexcept ImportError:
28*15745147SPedro Giffuni    import builtins
29*15745147SPedro Giffuni
30*15745147SPedro Giffunitry:
31*15745147SPedro Giffuni    unicode
32*15745147SPedro Giffuniexcept NameError:
33*15745147SPedro Giffuni    unicode = str
34*15745147SPedro Giffuni
35cdf0e10cSrcweirimport socket # since on Windows sal3.dll no longer calls WSAStartup
36cdf0e10cSrcweir
37cdf0e10cSrcweir# all functions and variables starting with a underscore (_) must be considered private
38cdf0e10cSrcweir# and can be changed at any time. Don't use them
39cdf0e10cSrcweir_g_ctx = pyuno.getComponentContext( )
40*15745147SPedro Giffuni_g_delegatee = builtin.__dict__["__import__"]
41cdf0e10cSrcweir
42cdf0e10cSrcweirdef getComponentContext():
43cdf0e10cSrcweir    """ returns the UNO component context, that was used to initialize the python runtime.
44cdf0e10cSrcweir    """
45cdf0e10cSrcweir    return _g_ctx
46cdf0e10cSrcweir
47cdf0e10cSrcweirdef getConstantByName( constant ):
48cdf0e10cSrcweir    "Looks up the value of a idl constant by giving its explicit name"
49cdf0e10cSrcweir    return pyuno.getConstantByName( constant )
50cdf0e10cSrcweir
51cdf0e10cSrcweirdef getTypeByName( typeName):
52cdf0e10cSrcweir    """ returns a uno.Type instance of the type given by typeName. In case the
53cdf0e10cSrcweir        type does not exist, a com.sun.star.uno.RuntimeException is raised.
54cdf0e10cSrcweir    """
55cdf0e10cSrcweir    return pyuno.getTypeByName( typeName )
56cdf0e10cSrcweir
57cdf0e10cSrcweirdef createUnoStruct( typeName, *args ):
58cdf0e10cSrcweir    """creates a uno struct or exception given by typeName. The parameter args may
59cdf0e10cSrcweir    1) be empty. In this case, you get a default constructed uno structure.
60cdf0e10cSrcweir       ( e.g. createUnoStruct( "com.sun.star.uno.Exception" ) )
61cdf0e10cSrcweir    2) be a sequence with exactly one element, that contains an instance of typeName.
62cdf0e10cSrcweir       In this case, a copy constructed instance of typeName is returned
63cdf0e10cSrcweir       ( e.g. createUnoStruct( "com.sun.star.uno.Exception" , e ) )
64cdf0e10cSrcweir    3) be a sequence, where the length of the sequence must match the number of
65cdf0e10cSrcweir       elements within typeName (e.g.
66cdf0e10cSrcweir       createUnoStruct( "com.sun.star.uno.Exception", "foo error" , self) ). The
67cdf0e10cSrcweir       elements with in the sequence must match the type of each struct element,
68cdf0e10cSrcweir       otherwise an exception is thrown.
69cdf0e10cSrcweir    """
70cdf0e10cSrcweir    return getClass(typeName)( *args )
71cdf0e10cSrcweir
72cdf0e10cSrcweirdef getClass( typeName ):
73cdf0e10cSrcweir    """returns the class of a concrete uno exception, struct or interface
74cdf0e10cSrcweir    """
75cdf0e10cSrcweir    return pyuno.getClass(typeName)
76cdf0e10cSrcweir
77cdf0e10cSrcweirdef isInterface( obj ):
78cdf0e10cSrcweir    """returns true, when obj is a class of a uno interface"""
79cdf0e10cSrcweir    return pyuno.isInterface( obj )
80cdf0e10cSrcweir
81cdf0e10cSrcweirdef generateUuid():
82cdf0e10cSrcweir    "returns a 16 byte sequence containing a newly generated uuid or guid, see rtl/uuid.h "
83cdf0e10cSrcweir    return pyuno.generateUuid()
84cdf0e10cSrcweir
85cdf0e10cSrcweirdef systemPathToFileUrl( systemPath ):
86cdf0e10cSrcweir    "returns a file-url for the given system path"
87cdf0e10cSrcweir    return pyuno.systemPathToFileUrl( systemPath )
88cdf0e10cSrcweir
89cdf0e10cSrcweirdef fileUrlToSystemPath( url ):
90cdf0e10cSrcweir    "returns a system path (determined by the system, the python interpreter is running on)"
91cdf0e10cSrcweir    return pyuno.fileUrlToSystemPath( url )
92cdf0e10cSrcweir
93cdf0e10cSrcweirdef absolutize( path, relativeUrl ):
94cdf0e10cSrcweir    "returns an absolute file url from the given urls"
95cdf0e10cSrcweir    return pyuno.absolutize( path, relativeUrl )
96cdf0e10cSrcweir
97cdf0e10cSrcweirdef getCurrentContext():
98cdf0e10cSrcweir    """Returns the currently valid current context.
99cdf0e10cSrcweir       see http://udk.openoffice.org/common/man/concept/uno_contexts.html#current_context
100cdf0e10cSrcweir       for an explanation on the current context concept
101cdf0e10cSrcweir    """
102cdf0e10cSrcweir    return pyuno.getCurrentContext()
103cdf0e10cSrcweir
104cdf0e10cSrcweirdef setCurrentContext( newContext ):
105cdf0e10cSrcweir    """Sets newContext as new uno current context. The newContext must
106cdf0e10cSrcweir    implement the XCurrentContext interface. The implemenation should
107cdf0e10cSrcweir    handle the desired properties and delegate unknown properties to the
108cdf0e10cSrcweir    old context. Ensure to reset the old one when you leave your stack ...
109cdf0e10cSrcweir    see http://udk.openoffice.org/common/man/concept/uno_contexts.html#current_context
110cdf0e10cSrcweir    """
111cdf0e10cSrcweir    return pyuno.setCurrentContext( newContext )
112cdf0e10cSrcweir
113cdf0e10cSrcweir
114cdf0e10cSrcweirclass Enum:
115cdf0e10cSrcweir    "Represents a UNO idl enum, use an instance of this class to explicitly pass a boolean to UNO"
116cdf0e10cSrcweir    #typeName the name of the enum as a string
117cdf0e10cSrcweir    #value    the actual value of this enum as a string
118cdf0e10cSrcweir    def __init__(self,typeName, value):
119cdf0e10cSrcweir        self.typeName = typeName
120cdf0e10cSrcweir        self.value = value
121cdf0e10cSrcweir        pyuno.checkEnum( self )
122cdf0e10cSrcweir
123cdf0e10cSrcweir    def __repr__(self):
124cdf0e10cSrcweir        return "<uno.Enum %s (%r)>" % (self.typeName, self.value)
125cdf0e10cSrcweir
126cdf0e10cSrcweir    def __eq__(self, that):
127cdf0e10cSrcweir        if not isinstance(that, Enum):
128cdf0e10cSrcweir            return False
129cdf0e10cSrcweir        return (self.typeName == that.typeName) and (self.value == that.value)
130cdf0e10cSrcweir
131cdf0e10cSrcweirclass Type:
132cdf0e10cSrcweir    "Represents a UNO type, use an instance of this class to explicitly pass a boolean to UNO"
133cdf0e10cSrcweir#    typeName                 # Name of the UNO type
134cdf0e10cSrcweir#    typeClass                # python Enum of TypeClass,  see com/sun/star/uno/TypeClass.idl
135cdf0e10cSrcweir    def __init__(self, typeName, typeClass):
136cdf0e10cSrcweir        self.typeName = typeName
137cdf0e10cSrcweir        self.typeClass = typeClass
138cdf0e10cSrcweir        pyuno.checkType(self)
139cdf0e10cSrcweir    def __repr__(self):
140cdf0e10cSrcweir        return "<Type instance %s (%r)>" % (self.typeName, self.typeClass)
141cdf0e10cSrcweir
142cdf0e10cSrcweir    def __eq__(self, that):
143cdf0e10cSrcweir        if not isinstance(that, Type):
144cdf0e10cSrcweir            return False
145cdf0e10cSrcweir        return self.typeClass == that.typeClass and self.typeName == that.typeName
146cdf0e10cSrcweir
147cdf0e10cSrcweir    def __hash__(self):
148cdf0e10cSrcweir        return self.typeName.__hash__()
149cdf0e10cSrcweir
150cdf0e10cSrcweirclass Bool(object):
151cdf0e10cSrcweir    """Represents a UNO boolean, use an instance of this class to explicitly
152cdf0e10cSrcweir       pass a boolean to UNO.
153cdf0e10cSrcweir       Note: This class is deprecated. Use python's True and False directly instead
154cdf0e10cSrcweir    """
155cdf0e10cSrcweir    def __new__(cls, value):
156cdf0e10cSrcweir        if isinstance(value, (str, unicode)) and value == "true":
157cdf0e10cSrcweir            return True
158cdf0e10cSrcweir        if isinstance(value, (str, unicode)) and value == "false":
159cdf0e10cSrcweir            return False
160cdf0e10cSrcweir        if value:
161cdf0e10cSrcweir            return True
162cdf0e10cSrcweir        return False
163cdf0e10cSrcweir
164cdf0e10cSrcweirclass Char:
165cdf0e10cSrcweir    "Represents a UNO char, use an instance of this class to explicitly pass a char to UNO"
166cdf0e10cSrcweir    # @param value pass a Unicode string with length 1
167cdf0e10cSrcweir    def __init__(self,value):
168cdf0e10cSrcweir        assert isinstance(value, unicode)
169cdf0e10cSrcweir        assert len(value) == 1
170cdf0e10cSrcweir        self.value=value
171cdf0e10cSrcweir
172cdf0e10cSrcweir    def __repr__(self):
173cdf0e10cSrcweir        return "<Char instance %s>" % (self.value, )
174cdf0e10cSrcweir
175cdf0e10cSrcweir    def __eq__(self, that):
176cdf0e10cSrcweir        if isinstance(that, (str, unicode)):
177cdf0e10cSrcweir            if len(that) > 1:
178cdf0e10cSrcweir                return False
179cdf0e10cSrcweir            return self.value == that[0]
180cdf0e10cSrcweir        if isinstance(that, Char):
181cdf0e10cSrcweir            return self.value == that.value
182cdf0e10cSrcweir        return False
183cdf0e10cSrcweir
184cdf0e10cSrcweirclass ByteSequence:
185cdf0e10cSrcweir    def __init__(self, value):
186cdf0e10cSrcweir        if isinstance(value, str):
187cdf0e10cSrcweir            self.value = value
188cdf0e10cSrcweir        elif isinstance(value, ByteSequence):
189cdf0e10cSrcweir            self.value = value.value
190cdf0e10cSrcweir        else:
191cdf0e10cSrcweir            raise TypeError("expected string or bytesequence")
192cdf0e10cSrcweir
193cdf0e10cSrcweir    def __repr__(self):
194cdf0e10cSrcweir        return "<ByteSequence instance '%s'>" % (self.value, )
195cdf0e10cSrcweir
196cdf0e10cSrcweir    def __eq__(self, that):
197cdf0e10cSrcweir        if isinstance( that, ByteSequence):
198cdf0e10cSrcweir            return self.value == that.value
199cdf0e10cSrcweir        if isinstance(that, str):
200cdf0e10cSrcweir            return self.value == that
201cdf0e10cSrcweir        return False
202cdf0e10cSrcweir
203cdf0e10cSrcweir    def __len__(self):
204cdf0e10cSrcweir        return len(self.value)
205cdf0e10cSrcweir
206cdf0e10cSrcweir    def __getitem__(self, index):
207cdf0e10cSrcweir        return self.value[index]
208cdf0e10cSrcweir
209cdf0e10cSrcweir    def __iter__( self ):
210cdf0e10cSrcweir        return self.value.__iter__()
211cdf0e10cSrcweir
212cdf0e10cSrcweir    def __add__( self , b ):
213cdf0e10cSrcweir        if isinstance( b, str ):
214cdf0e10cSrcweir            return ByteSequence( self.value + b )
215cdf0e10cSrcweir        elif isinstance( b, ByteSequence ):
216cdf0e10cSrcweir            return ByteSequence( self.value + b.value )
217cdf0e10cSrcweir        raise TypeError( "expected string or ByteSequence as operand" )
218cdf0e10cSrcweir
219cdf0e10cSrcweir    def __hash__( self ):
220cdf0e10cSrcweir        return self.value.hash()
221cdf0e10cSrcweir
222cdf0e10cSrcweir
223cdf0e10cSrcweirclass Any:
224cdf0e10cSrcweir    "use only in connection with uno.invoke() to pass an explicit typed any"
225cdf0e10cSrcweir    def __init__(self, type, value ):
226cdf0e10cSrcweir        if isinstance( type, Type ):
227cdf0e10cSrcweir            self.type = type
228cdf0e10cSrcweir        else:
229cdf0e10cSrcweir            self.type = getTypeByName( type )
230cdf0e10cSrcweir        self.value = value
231cdf0e10cSrcweir
232cdf0e10cSrcweirdef invoke( object, methodname, argTuple ):
233cdf0e10cSrcweir    "use this function to pass exactly typed anys to the callee (using uno.Any)"
234cdf0e10cSrcweir    return pyuno.invoke( object, methodname, argTuple )
235cdf0e10cSrcweir
236cdf0e10cSrcweir#---------------------------------------------------------------------------------------
237cdf0e10cSrcweir# don't use any functions beyond this point, private section, likely to change
238cdf0e10cSrcweir#---------------------------------------------------------------------------------------
239cdf0e10cSrcweir#def _uno_import( name, globals={}, locals={}, fromlist=[], level=-1 ):
240cdf0e10cSrcweirdef _uno_import( name, *optargs, **kwargs ):
241cdf0e10cSrcweir    try:
242cdf0e10cSrcweir#       print "optargs = " + repr(optargs)
243cdf0e10cSrcweir        return _g_delegatee( name, *optargs, **kwargs )
244cdf0e10cSrcweir    except ImportError:
245cdf0e10cSrcweir        # process optargs
246cdf0e10cSrcweir        globals, locals, fromlist = list(optargs)[:3] + [kwargs.get('globals',{}), kwargs.get('locals',{}), kwargs.get('fromlist',[])][len(optargs):]
247cdf0e10cSrcweir        if not fromlist:
248cdf0e10cSrcweir            raise
249cdf0e10cSrcweir    modnames = name.split( "." )
250cdf0e10cSrcweir    mod = None
251cdf0e10cSrcweir    d = sys.modules
252cdf0e10cSrcweir    for x in modnames:
253d912c6c5SPedro Giffuni        if x in d:
254cdf0e10cSrcweir            mod = d[x]
255cdf0e10cSrcweir        else:
256cdf0e10cSrcweir            mod = pyuno.__class__(x)  # How to create a module ??
257cdf0e10cSrcweir        d = mod.__dict__
258cdf0e10cSrcweir
259cdf0e10cSrcweir    RuntimeException = pyuno.getClass( "com.sun.star.uno.RuntimeException" )
260cdf0e10cSrcweir    for x in fromlist:
261d912c6c5SPedro Giffuni        if x not in d:
262cdf0e10cSrcweir            if x.startswith( "typeOf" ):
263cdf0e10cSrcweir                try:
264cdf0e10cSrcweir                    d[x] = pyuno.getTypeByName( name + "." + x[6:len(x)] )
265d912c6c5SPedro Giffuni                except RuntimeException as e:
266cdf0e10cSrcweir                    raise ImportError( "type " + name + "." + x[6:len(x)] +" is unknown" )
267cdf0e10cSrcweir            else:
268cdf0e10cSrcweir                try:
269cdf0e10cSrcweir                    # check for structs, exceptions or interfaces
270cdf0e10cSrcweir                    d[x] = pyuno.getClass( name + "." + x )
271d912c6c5SPedro Giffuni                except RuntimeException as e:
272cdf0e10cSrcweir                    # check for enums
273cdf0e10cSrcweir                    try:
274cdf0e10cSrcweir                        d[x] = Enum( name , x )
275d912c6c5SPedro Giffuni                    except RuntimeException as e2:
276cdf0e10cSrcweir                        # check for constants
277cdf0e10cSrcweir                        try:
278cdf0e10cSrcweir                            d[x] = getConstantByName( name + "." + x )
279d912c6c5SPedro Giffuni                        except RuntimeException as e3:
280cdf0e10cSrcweir                            # no known uno type !
281cdf0e10cSrcweir                            raise ImportError( "type "+ name + "." +x + " is unknown" )
282cdf0e10cSrcweir    return mod
283cdf0e10cSrcweir
284cdf0e10cSrcweir# hook into the __import__ chain
285*15745147SPedro Giffunibuiltin.__dict__["__import__"] = _uno_import
286cdf0e10cSrcweir
287cdf0e10cSrcweir# private, referenced from the pyuno shared library
288cdf0e10cSrcweirdef _uno_struct__init__(self,*args):
289cdf0e10cSrcweir    if len(args) == 1 and hasattr(args[0], "__class__") and args[0].__class__ == self.__class__ :
290cdf0e10cSrcweir        self.__dict__["value"] = args[0]
291cdf0e10cSrcweir    else:
292cdf0e10cSrcweir        self.__dict__["value"] = pyuno._createUnoStructHelper(self.__class__.__pyunostruct__,args)
293cdf0e10cSrcweir
294cdf0e10cSrcweir# private, referenced from the pyuno shared library
295cdf0e10cSrcweirdef _uno_struct__getattr__(self,name):
296*15745147SPedro Giffuni    return builtin.getattr(self.__dict__["value"],name)
297cdf0e10cSrcweir
298cdf0e10cSrcweir# private, referenced from the pyuno shared library
299cdf0e10cSrcweirdef _uno_struct__setattr__(self,name,value):
300*15745147SPedro Giffuni    return builtin.setattr(self.__dict__["value"],name,value)
301cdf0e10cSrcweir
302cdf0e10cSrcweir# private, referenced from the pyuno shared library
303cdf0e10cSrcweirdef _uno_struct__repr__(self):
304cdf0e10cSrcweir    return repr(self.__dict__["value"])
305cdf0e10cSrcweir
306cdf0e10cSrcweirdef _uno_struct__str__(self):
307cdf0e10cSrcweir    return str(self.__dict__["value"])
308cdf0e10cSrcweir
309cdf0e10cSrcweir# private, referenced from the pyuno shared library
310cdf0e10cSrcweirdef _uno_struct__eq__(self,cmp):
311cdf0e10cSrcweir    if hasattr(cmp,"value"):
312cdf0e10cSrcweir        return self.__dict__["value"] == cmp.__dict__["value"]
313cdf0e10cSrcweir    return False
314cdf0e10cSrcweir
315cdf0e10cSrcweir# referenced from pyuno shared lib and pythonscript.py
316cdf0e10cSrcweirdef _uno_extract_printable_stacktrace( trace ):
317cdf0e10cSrcweir    mod = None
318cdf0e10cSrcweir    try:
319cdf0e10cSrcweir        mod = __import__("traceback")
320d912c6c5SPedro Giffuni    except ImportError as e:
321cdf0e10cSrcweir        pass
322cdf0e10cSrcweir    ret = ""
323cdf0e10cSrcweir    if mod:
324cdf0e10cSrcweir        lst = mod.extract_tb( trace )
325cdf0e10cSrcweir        max = len(lst)
326cdf0e10cSrcweir        for j in range(max):
327cdf0e10cSrcweir            i = lst[max-j-1]
328cdf0e10cSrcweir            ret = ret + "  " + str(i[0]) + ":" + \
329cdf0e10cSrcweir                  str(i[1]) + " in function " + \
330cdf0e10cSrcweir                  str(i[2])  + "() [" + str(i[3]) + "]\n"
331cdf0e10cSrcweir    else:
332cdf0e10cSrcweir        ret = "Couldn't import traceback module"
333cdf0e10cSrcweir    return ret
334