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