Update ooo320-m1
[ooovba.git] / pyuno / source / module / uno.py
blobaa40c0c936567e9e54b57e41f97964f2ea3fdfe4
1 #*************************************************************************
3 # DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
4 #
5 # Copyright 2008 by Sun Microsystems, Inc.
7 # OpenOffice.org - a multi-platform office productivity suite
9 # $RCSfile: uno.py,v $
11 # $Revision: 1.9 $
13 # This file is part of OpenOffice.org.
15 # OpenOffice.org is free software: you can redistribute it and/or modify
16 # it under the terms of the GNU Lesser General Public License version 3
17 # only, as published by the Free Software Foundation.
19 # OpenOffice.org is distributed in the hope that it will be useful,
20 # but WITHOUT ANY WARRANTY; without even the implied warranty of
21 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
22 # GNU Lesser General Public License version 3 for more details
23 # (a copy is included in the LICENSE file that accompanied this code).
25 # You should have received a copy of the GNU Lesser General Public License
26 # version 3 along with OpenOffice.org. If not, see
27 # <http://www.openoffice.org/license.html>
28 # for a copy of the LGPLv3 License.
30 #*************************************************************************
31 import os
32 import sys
34 sys.path.append('${exec_prefix}/lib/ooo-3.2/basis-link/program')
35 if getattr(os.environ, 'URE_BOOTSTRAP', None) is None:
36 os.environ['URE_BOOTSTRAP'] = "vnd.sun.star.pathname:${exec_prefix}/lib/ooo-3.2/program/fundamentalrc"
38 import pyuno
39 import __builtin__
40 import socket # since on Windows sal3.dll no longer calls WSAStartup
42 # all functions and variables starting with a underscore (_) must be considered private
43 # and can be changed at any time. Don't use them
44 _g_ctx = pyuno.getComponentContext( )
45 _g_delegatee = __builtin__.__dict__["__import__"]
47 def getComponentContext():
48 """ returns the UNO component context, that was used to initialize the python runtime.
49 """
50 return _g_ctx
52 def getConstantByName( constant ):
53 "Looks up the value of a idl constant by giving its explicit name"
54 return pyuno.getConstantByName( constant )
56 def getTypeByName( typeName):
57 """ returns a uno.Type instance of the type given by typeName. In case the
58 type does not exist, a com.sun.star.uno.RuntimeException is raised.
59 """
60 return pyuno.getTypeByName( typeName )
62 def createUnoStruct( typeName, *args ):
63 """creates a uno struct or exception given by typeName. The parameter args may
64 1) be empty. In this case, you get a default constructed uno structure.
65 ( e.g. createUnoStruct( "com.sun.star.uno.Exception" ) )
66 2) be a sequence with exactly one element, that contains an instance of typeName.
67 In this case, a copy constructed instance of typeName is returned
68 ( e.g. createUnoStruct( "com.sun.star.uno.Exception" , e ) )
69 3) be a sequence, where the length of the sequence must match the number of
70 elements within typeName (e.g.
71 createUnoStruct( "com.sun.star.uno.Exception", "foo error" , self) ). The
72 elements with in the sequence must match the type of each struct element,
73 otherwise an exception is thrown.
74 """
75 return getClass(typeName)( *args )
77 def getClass( typeName ):
78 """returns the class of a concrete uno exception, struct or interface
79 """
80 return pyuno.getClass(typeName)
82 def isInterface( obj ):
83 """returns true, when obj is a class of a uno interface"""
84 return pyuno.isInterface( obj )
86 def generateUuid():
87 "returns a 16 byte sequence containing a newly generated uuid or guid, see rtl/uuid.h "
88 return pyuno.generateUuid()
90 def systemPathToFileUrl( systemPath ):
91 "returns a file-url for the given system path"
92 return pyuno.systemPathToFileUrl( systemPath )
94 def fileUrlToSystemPath( url ):
95 "returns a system path (determined by the system, the python interpreter is running on)"
96 return pyuno.fileUrlToSystemPath( url )
98 def absolutize( path, relativeUrl ):
99 "returns an absolute file url from the given urls"
100 return pyuno.absolutize( path, relativeUrl )
102 def getCurrentContext():
103 """Returns the currently valid current context.
104 see http://udk.openoffice.org/common/man/concept/uno_contexts.html#current_context
105 for an explanation on the current context concept
107 return pyuno.getCurrentContext()
109 def setCurrentContext( newContext ):
110 """Sets newContext as new uno current context. The newContext must
111 implement the XCurrentContext interface. The implemenation should
112 handle the desired properties and delegate unknown properties to the
113 old context. Ensure to reset the old one when you leave your stack ...
114 see http://udk.openoffice.org/common/man/concept/uno_contexts.html#current_context
116 return pyuno.setCurrentContext( newContext )
119 class Enum:
120 "Represents a UNO idl enum, use an instance of this class to explicitly pass a boolean to UNO"
121 #typeName the name of the enum as a string
122 #value the actual value of this enum as a string
123 def __init__(self,typeName, value):
124 self.typeName = typeName
125 self.value = value
126 pyuno.checkEnum( self )
128 def __repr__(self):
129 return "<uno.Enum %s (%r)>" % (self.typeName, self.value)
131 def __eq__(self, that):
132 if not isinstance(that, Enum):
133 return False
134 return (self.typeName == that.typeName) and (self.value == that.value)
136 class Type:
137 "Represents a UNO type, use an instance of this class to explicitly pass a boolean to UNO"
138 # typeName # Name of the UNO type
139 # typeClass # python Enum of TypeClass, see com/sun/star/uno/TypeClass.idl
140 def __init__(self, typeName, typeClass):
141 self.typeName = typeName
142 self.typeClass = typeClass
143 pyuno.checkType(self)
144 def __repr__(self):
145 return "<Type instance %s (%r)>" % (self.typeName, self.typeClass)
147 def __eq__(self, that):
148 if not isinstance(that, Type):
149 return False
150 return self.typeClass == that.typeClass and self.typeName == that.typeName
152 def __hash__(self):
153 return self.typeName.__hash__()
155 class Bool(object):
156 """Represents a UNO boolean, use an instance of this class to explicitly
157 pass a boolean to UNO.
158 Note: This class is deprecated. Use python's True and False directly instead
160 def __new__(cls, value):
161 if isinstance(value, (str, unicode)) and value == "true":
162 return True
163 if isinstance(value, (str, unicode)) and value == "false":
164 return False
165 if value:
166 return True
167 return False
169 class Char:
170 "Represents a UNO char, use an instance of this class to explicitly pass a char to UNO"
171 # @param value pass a Unicode string with length 1
172 def __init__(self,value):
173 assert isinstance(value, unicode)
174 assert len(value) == 1
175 self.value=value
177 def __repr__(self):
178 return "<Char instance %s>" % (self.value, )
180 def __eq__(self, that):
181 if isinstance(that, (str, unicode)):
182 if len(that) > 1:
183 return False
184 return self.value == that[0]
185 if isinstance(that, Char):
186 return self.value == that.value
187 return False
189 # Suggested by Christian, but still some open problems which need to be solved first
191 #class ByteSequence(str):
193 # def __repr__(self):
194 # return "<ByteSequence instance %s>" % str.__repr__(self)
196 # for a little bit compatitbility; setting value is not possible as
197 # strings are immutable
198 # def _get_value(self):
199 # return self
201 # value = property(_get_value)
203 class ByteSequence:
204 def __init__(self, value):
205 if isinstance(value, str):
206 self.value = value
207 elif isinstance(value, ByteSequence):
208 self.value = value.value
209 else:
210 raise TypeError("expected string or bytesequence")
212 def __repr__(self):
213 return "<ByteSequence instance '%s'>" % (self.value, )
215 def __eq__(self, that):
216 if isinstance( that, ByteSequence):
217 return self.value == that.value
218 if isinstance(that, str):
219 return self.value == that
220 return False
222 def __len__(self):
223 return len(self.value)
225 def __getitem__(self, index):
226 return self.value[index]
228 def __iter__( self ):
229 return self.value.__iter__()
231 def __add__( self , b ):
232 if isinstance( b, str ):
233 return ByteSequence( self.value + b )
234 elif isinstance( b, ByteSequence ):
235 return ByteSequence( self.value + b.value )
236 raise TypeError( "expected string or ByteSequence as operand" )
238 def __hash__( self ):
239 return self.value.hash()
242 class Any:
243 "use only in connection with uno.invoke() to pass an explicit typed any"
244 def __init__(self, type, value ):
245 if isinstance( type, Type ):
246 self.type = type
247 else:
248 self.type = getTypeByName( type )
249 self.value = value
251 def invoke( object, methodname, argTuple ):
252 "use this function to pass exactly typed anys to the callee (using uno.Any)"
253 return pyuno.invoke( object, methodname, argTuple )
255 #---------------------------------------------------------------------------------------
256 # don't use any functions beyond this point, private section, likely to change
257 #---------------------------------------------------------------------------------------
258 #def _uno_import( name, globals={}, locals={}, fromlist=[], level=-1 ):
259 def _uno_import( name, *optargs, **kwargs ):
260 try:
261 # print "optargs = " + repr(optargs)
262 return _g_delegatee( name, *optargs, **kwargs )
263 except ImportError:
264 # process optargs
265 globals, locals, fromlist = list(optargs)[:3] + [kwargs.get('globals',{}), kwargs.get('locals',{}), kwargs.get('fromlist',[])][len(optargs):]
266 if not fromlist:
267 raise
268 modnames = name.split( "." )
269 mod = None
270 d = sys.modules
271 for x in modnames:
272 if d.has_key(x):
273 mod = d[x]
274 else:
275 mod = pyuno.__class__(x) # How to create a module ??
276 d = mod.__dict__
278 RuntimeException = pyuno.getClass( "com.sun.star.uno.RuntimeException" )
279 for x in fromlist:
280 if not d.has_key(x):
281 if x.startswith( "typeOf" ):
282 try:
283 d[x] = pyuno.getTypeByName( name + "." + x[6:len(x)] )
284 except RuntimeException,e:
285 raise ImportError( "type " + name + "." + x[6:len(x)] +" is unknown" )
286 else:
287 try:
288 # check for structs, exceptions or interfaces
289 d[x] = pyuno.getClass( name + "." + x )
290 except RuntimeException,e:
291 # check for enums
292 try:
293 d[x] = Enum( name , x )
294 except RuntimeException,e2:
295 # check for constants
296 try:
297 d[x] = getConstantByName( name + "." + x )
298 except RuntimeException,e3:
299 # no known uno type !
300 raise ImportError( "type "+ name + "." +x + " is unknown" )
301 return mod
303 # hook into the __import__ chain
304 __builtin__.__dict__["__import__"] = _uno_import
306 # private function, don't use
307 def _impl_extractName(name):
308 r = range (len(name)-1,0,-1)
309 for i in r:
310 if name[i] == ".":
311 name = name[i+1:len(name)]
312 break
313 return name
315 # private, referenced from the pyuno shared library
316 def _uno_struct__init__(self,*args):
317 if len(args) == 1 and hasattr(args[0], "__class__") and args[0].__class__ == self.__class__ :
318 self.__dict__["value"] = args[0]
319 else:
320 self.__dict__["value"] = pyuno._createUnoStructHelper(self.__class__.__pyunostruct__,args)
322 # private, referenced from the pyuno shared library
323 def _uno_struct__getattr__(self,name):
324 return __builtin__.getattr(self.__dict__["value"],name)
326 # private, referenced from the pyuno shared library
327 def _uno_struct__setattr__(self,name,value):
328 return __builtin__.setattr(self.__dict__["value"],name,value)
330 # private, referenced from the pyuno shared library
331 def _uno_struct__repr__(self):
332 return repr(self.__dict__["value"])
334 def _uno_struct__str__(self):
335 return str(self.__dict__["value"])
337 # private, referenced from the pyuno shared library
338 def _uno_struct__eq__(self,cmp):
339 if hasattr(cmp,"value"):
340 return self.__dict__["value"] == cmp.__dict__["value"]
341 return False
343 # referenced from pyuno shared lib and pythonscript.py
344 def _uno_extract_printable_stacktrace( trace ):
345 mod = None
346 try:
347 mod = __import__("traceback")
348 except ImportError,e:
349 pass
350 ret = ""
351 if mod:
352 lst = mod.extract_tb( trace )
353 max = len(lst)
354 for j in range(max):
355 i = lst[max-j-1]
356 ret = ret + " " + str(i[0]) + ":" + \
357 str(i[1]) + " in function " + \
358 str(i[2]) + "() [" + str(i[3]) + "]\n"
359 else:
360 ret = "Couldn't import traceback module"
361 return ret