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