xref: /aoo41x/main/pyuno/source/module/uno.py (revision cdf0e10c)
1#*************************************************************************
2#
3# DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
4#
5# Copyright 2000, 2010 Oracle and/or its affiliates.
6#
7# OpenOffice.org - a multi-platform office productivity suite
8#
9# This file is part of OpenOffice.org.
10#
11# OpenOffice.org is free software: you can redistribute it and/or modify
12# it under the terms of the GNU Lesser General Public License version 3
13# only, as published by the Free Software Foundation.
14#
15# OpenOffice.org is distributed in the hope that it will be useful,
16# but WITHOUT ANY WARRANTY; without even the implied warranty of
17# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
18# GNU Lesser General Public License version 3 for more details
19# (a copy is included in the LICENSE file that accompanied this code).
20#
21# You should have received a copy of the GNU Lesser General Public License
22# version 3 along with OpenOffice.org.  If not, see
23# <http://www.openoffice.org/license.html>
24# for a copy of the LGPLv3 License.
25#
26#*************************************************************************
27import sys
28
29import pyuno
30import __builtin__
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
180# Suggested by Christian, but still some open problems which need to be solved first
181#
182#class ByteSequence(str):
183#
184#    def __repr__(self):
185#        return "<ByteSequence instance %s>" % str.__repr__(self)
186
187    # for a little bit compatitbility; setting value is not possible as
188    # strings are immutable
189#    def _get_value(self):
190#        return self
191#
192#    value = property(_get_value)
193
194class ByteSequence:
195    def __init__(self, value):
196        if isinstance(value, str):
197            self.value = value
198        elif isinstance(value, ByteSequence):
199            self.value = value.value
200        else:
201            raise TypeError("expected string or bytesequence")
202
203    def __repr__(self):
204        return "<ByteSequence instance '%s'>" % (self.value, )
205
206    def __eq__(self, that):
207        if isinstance( that, ByteSequence):
208            return self.value == that.value
209        if isinstance(that, str):
210            return self.value == that
211        return False
212
213    def __len__(self):
214        return len(self.value)
215
216    def __getitem__(self, index):
217        return self.value[index]
218
219    def __iter__( self ):
220        return self.value.__iter__()
221
222    def __add__( self , b ):
223        if isinstance( b, str ):
224            return ByteSequence( self.value + b )
225        elif isinstance( b, ByteSequence ):
226            return ByteSequence( self.value + b.value )
227        raise TypeError( "expected string or ByteSequence as operand" )
228
229    def __hash__( self ):
230        return self.value.hash()
231
232
233class Any:
234    "use only in connection with uno.invoke() to pass an explicit typed any"
235    def __init__(self, type, value ):
236        if isinstance( type, Type ):
237            self.type = type
238        else:
239            self.type = getTypeByName( type )
240        self.value = value
241
242def invoke( object, methodname, argTuple ):
243    "use this function to pass exactly typed anys to the callee (using uno.Any)"
244    return pyuno.invoke( object, methodname, argTuple )
245
246#---------------------------------------------------------------------------------------
247# don't use any functions beyond this point, private section, likely to change
248#---------------------------------------------------------------------------------------
249#def _uno_import( name, globals={}, locals={}, fromlist=[], level=-1 ):
250def _uno_import( name, *optargs, **kwargs ):
251    try:
252#       print "optargs = " + repr(optargs)
253        return _g_delegatee( name, *optargs, **kwargs )
254    except ImportError:
255        # process optargs
256        globals, locals, fromlist = list(optargs)[:3] + [kwargs.get('globals',{}), kwargs.get('locals',{}), kwargs.get('fromlist',[])][len(optargs):]
257        if not fromlist:
258            raise
259    modnames = name.split( "." )
260    mod = None
261    d = sys.modules
262    for x in modnames:
263        if d.has_key(x):
264           mod = d[x]
265        else:
266           mod = pyuno.__class__(x)  # How to create a module ??
267        d = mod.__dict__
268
269    RuntimeException = pyuno.getClass( "com.sun.star.uno.RuntimeException" )
270    for x in fromlist:
271       if not d.has_key(x):
272          if x.startswith( "typeOf" ):
273             try:
274                d[x] = pyuno.getTypeByName( name + "." + x[6:len(x)] )
275             except RuntimeException,e:
276                raise ImportError( "type " + name + "." + x[6:len(x)] +" is unknown" )
277          else:
278            try:
279                # check for structs, exceptions or interfaces
280                d[x] = pyuno.getClass( name + "." + x )
281            except RuntimeException,e:
282                # check for enums
283                try:
284                   d[x] = Enum( name , x )
285                except RuntimeException,e2:
286                   # check for constants
287                   try:
288                      d[x] = getConstantByName( name + "." + x )
289                   except RuntimeException,e3:
290                      # no known uno type !
291                      raise ImportError( "type "+ name + "." +x + " is unknown" )
292    return mod
293
294# hook into the __import__ chain
295__builtin__.__dict__["__import__"] = _uno_import
296
297# private function, don't use
298def _impl_extractName(name):
299    r = range (len(name)-1,0,-1)
300    for i in r:
301        if name[i] == ".":
302           name = name[i+1:len(name)]
303           break
304    return name
305
306# private, referenced from the pyuno shared library
307def _uno_struct__init__(self,*args):
308    if len(args) == 1 and hasattr(args[0], "__class__") and args[0].__class__ == self.__class__ :
309       self.__dict__["value"] = args[0]
310    else:
311       self.__dict__["value"] = pyuno._createUnoStructHelper(self.__class__.__pyunostruct__,args)
312
313# private, referenced from the pyuno shared library
314def _uno_struct__getattr__(self,name):
315    return __builtin__.getattr(self.__dict__["value"],name)
316
317# private, referenced from the pyuno shared library
318def _uno_struct__setattr__(self,name,value):
319    return __builtin__.setattr(self.__dict__["value"],name,value)
320
321# private, referenced from the pyuno shared library
322def _uno_struct__repr__(self):
323    return repr(self.__dict__["value"])
324
325def _uno_struct__str__(self):
326    return str(self.__dict__["value"])
327
328# private, referenced from the pyuno shared library
329def _uno_struct__eq__(self,cmp):
330    if hasattr(cmp,"value"):
331       return self.__dict__["value"] == cmp.__dict__["value"]
332    return False
333
334# referenced from pyuno shared lib and pythonscript.py
335def _uno_extract_printable_stacktrace( trace ):
336    mod = None
337    try:
338        mod = __import__("traceback")
339    except ImportError,e:
340        pass
341    ret = ""
342    if mod:
343        lst = mod.extract_tb( trace )
344        max = len(lst)
345        for j in range(max):
346            i = lst[max-j-1]
347            ret = ret + "  " + str(i[0]) + ":" + \
348                  str(i[1]) + " in function " + \
349                  str(i[2])  + "() [" + str(i[3]) + "]\n"
350    else:
351        ret = "Couldn't import traceback module"
352    return ret
353