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