uno.py (a0428e9e) uno.py (d912c6c5)
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

--- 17 unchanged lines hidden (view full) ---

26
27# all functions and variables starting with a underscore (_) must be considered private
28# and can be changed at any time. Don't use them
29_g_ctx = pyuno.getComponentContext( )
30_g_delegatee = __builtin__.__dict__["__import__"]
31
32def getComponentContext():
33 """ returns the UNO component context, that was used to initialize the python runtime.
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

--- 17 unchanged lines hidden (view full) ---

26
27# all functions and variables starting with a underscore (_) must be considered private
28# and can be changed at any time. Don't use them
29_g_ctx = pyuno.getComponentContext( )
30_g_delegatee = __builtin__.__dict__["__import__"]
31
32def getComponentContext():
33 """ returns the UNO component context, that was used to initialize the python runtime.
34 """
35 return _g_ctx
34 """
35 return _g_ctx
36
37def getConstantByName( constant ):
38 "Looks up the value of a idl constant by giving its explicit name"
39 return pyuno.getConstantByName( constant )
40
41def getTypeByName( typeName):
42 """ returns a uno.Type instance of the type given by typeName. In case the
43 type does not exist, a com.sun.star.uno.RuntimeException is raised.
36
37def getConstantByName( constant ):
38 "Looks up the value of a idl constant by giving its explicit name"
39 return pyuno.getConstantByName( constant )
40
41def getTypeByName( typeName):
42 """ returns a uno.Type instance of the type given by typeName. In case the
43 type does not exist, a com.sun.star.uno.RuntimeException is raised.
44 """
44 """
45 return pyuno.getTypeByName( typeName )
46
47def createUnoStruct( typeName, *args ):
48 """creates a uno struct or exception given by typeName. The parameter args may
49 1) be empty. In this case, you get a default constructed uno structure.
50 ( e.g. createUnoStruct( "com.sun.star.uno.Exception" ) )
51 2) be a sequence with exactly one element, that contains an instance of typeName.
52 In this case, a copy constructed instance of typeName is returned

--- 12 unchanged lines hidden (view full) ---

65 return pyuno.getClass(typeName)
66
67def isInterface( obj ):
68 """returns true, when obj is a class of a uno interface"""
69 return pyuno.isInterface( obj )
70
71def generateUuid():
72 "returns a 16 byte sequence containing a newly generated uuid or guid, see rtl/uuid.h "
45 return pyuno.getTypeByName( typeName )
46
47def createUnoStruct( typeName, *args ):
48 """creates a uno struct or exception given by typeName. The parameter args may
49 1) be empty. In this case, you get a default constructed uno structure.
50 ( e.g. createUnoStruct( "com.sun.star.uno.Exception" ) )
51 2) be a sequence with exactly one element, that contains an instance of typeName.
52 In this case, a copy constructed instance of typeName is returned

--- 12 unchanged lines hidden (view full) ---

65 return pyuno.getClass(typeName)
66
67def isInterface( obj ):
68 """returns true, when obj is a class of a uno interface"""
69 return pyuno.isInterface( obj )
70
71def generateUuid():
72 "returns a 16 byte sequence containing a newly generated uuid or guid, see rtl/uuid.h "
73 return pyuno.generateUuid()
73 return pyuno.generateUuid()
74
75def systemPathToFileUrl( systemPath ):
76 "returns a file-url for the given system path"
77 return pyuno.systemPathToFileUrl( systemPath )
78
79def fileUrlToSystemPath( url ):
80 "returns a system path (determined by the system, the python interpreter is running on)"
81 return pyuno.fileUrlToSystemPath( url )

--- 13 unchanged lines hidden (view full) ---

95 """Sets newContext as new uno current context. The newContext must
96 implement the XCurrentContext interface. The implemenation should
97 handle the desired properties and delegate unknown properties to the
98 old context. Ensure to reset the old one when you leave your stack ...
99 see http://udk.openoffice.org/common/man/concept/uno_contexts.html#current_context
100 """
101 return pyuno.setCurrentContext( newContext )
102
74
75def systemPathToFileUrl( systemPath ):
76 "returns a file-url for the given system path"
77 return pyuno.systemPathToFileUrl( systemPath )
78
79def fileUrlToSystemPath( url ):
80 "returns a system path (determined by the system, the python interpreter is running on)"
81 return pyuno.fileUrlToSystemPath( url )

--- 13 unchanged lines hidden (view full) ---

95 """Sets newContext as new uno current context. The newContext must
96 implement the XCurrentContext interface. The implemenation should
97 handle the desired properties and delegate unknown properties to the
98 old context. Ensure to reset the old one when you leave your stack ...
99 see http://udk.openoffice.org/common/man/concept/uno_contexts.html#current_context
100 """
101 return pyuno.setCurrentContext( newContext )
102
103
103
104class Enum:
104class Enum:
105 "Represents a UNO idl enum, use an instance of this class to explicitly pass a boolean to UNO"
105 "Represents a UNO idl enum, use an instance of this class to explicitly pass a boolean to UNO"
106 #typeName the name of the enum as a string
107 #value the actual value of this enum as a string
108 def __init__(self,typeName, value):
109 self.typeName = typeName
110 self.value = value
111 pyuno.checkEnum( self )
112
113 def __repr__(self):

--- 19 unchanged lines hidden (view full) ---

133 if not isinstance(that, Type):
134 return False
135 return self.typeClass == that.typeClass and self.typeName == that.typeName
136
137 def __hash__(self):
138 return self.typeName.__hash__()
139
140class Bool(object):
106 #typeName the name of the enum as a string
107 #value the actual value of this enum as a string
108 def __init__(self,typeName, value):
109 self.typeName = typeName
110 self.value = value
111 pyuno.checkEnum( self )
112
113 def __repr__(self):

--- 19 unchanged lines hidden (view full) ---

133 if not isinstance(that, Type):
134 return False
135 return self.typeClass == that.typeClass and self.typeName == that.typeName
136
137 def __hash__(self):
138 return self.typeName.__hash__()
139
140class Bool(object):
141 """Represents a UNO boolean, use an instance of this class to explicitly
141 """Represents a UNO boolean, use an instance of this class to explicitly
142 pass a boolean to UNO.
143 Note: This class is deprecated. Use python's True and False directly instead
144 """
145 def __new__(cls, value):
146 if isinstance(value, (str, unicode)) and value == "true":
147 return True
148 if isinstance(value, (str, unicode)) and value == "false":
149 return False

--- 6 unchanged lines hidden (view full) ---

156 # @param value pass a Unicode string with length 1
157 def __init__(self,value):
158 assert isinstance(value, unicode)
159 assert len(value) == 1
160 self.value=value
161
162 def __repr__(self):
163 return "<Char instance %s>" % (self.value, )
142 pass a boolean to UNO.
143 Note: This class is deprecated. Use python's True and False directly instead
144 """
145 def __new__(cls, value):
146 if isinstance(value, (str, unicode)) and value == "true":
147 return True
148 if isinstance(value, (str, unicode)) and value == "false":
149 return False

--- 6 unchanged lines hidden (view full) ---

156 # @param value pass a Unicode string with length 1
157 def __init__(self,value):
158 assert isinstance(value, unicode)
159 assert len(value) == 1
160 self.value=value
161
162 def __repr__(self):
163 return "<Char instance %s>" % (self.value, )
164
164
165 def __eq__(self, that):
166 if isinstance(that, (str, unicode)):
167 if len(that) > 1:
168 return False
169 return self.value == that[0]
165 def __eq__(self, that):
166 if isinstance(that, (str, unicode)):
167 if len(that) > 1:
168 return False
169 return self.value == that[0]
170 if isinstance(that, Char):
170 if isinstance(that, Char):
171 return self.value == that.value
172 return False
173
174# Suggested by Christian, but still some open problems which need to be solved first
175#
176#class ByteSequence(str):
177#
178# def __repr__(self):
179# return "<ByteSequence instance %s>" % str.__repr__(self)
180
171 return self.value == that.value
172 return False
173
174# Suggested by Christian, but still some open problems which need to be solved first
175#
176#class ByteSequence(str):
177#
178# def __repr__(self):
179# return "<ByteSequence instance %s>" % str.__repr__(self)
180
181 # for a little bit compatitbility; setting value is not possible as
181 # for a little bit compatibility; setting value is not possible as
182 # strings are immutable
183# def _get_value(self):
184# return self
185#
182 # strings are immutable
183# def _get_value(self):
184# return self
185#
186# value = property(_get_value)
186# value = property(_get_value)
187
188class ByteSequence:
189 def __init__(self, value):
190 if isinstance(value, str):
191 self.value = value
192 elif isinstance(value, ByteSequence):
193 self.value = value.value
194 else:

--- 36 unchanged lines hidden (view full) ---

231 self.type = type
232 else:
233 self.type = getTypeByName( type )
234 self.value = value
235
236def invoke( object, methodname, argTuple ):
237 "use this function to pass exactly typed anys to the callee (using uno.Any)"
238 return pyuno.invoke( object, methodname, argTuple )
187
188class ByteSequence:
189 def __init__(self, value):
190 if isinstance(value, str):
191 self.value = value
192 elif isinstance(value, ByteSequence):
193 self.value = value.value
194 else:

--- 36 unchanged lines hidden (view full) ---

231 self.type = type
232 else:
233 self.type = getTypeByName( type )
234 self.value = value
235
236def invoke( object, methodname, argTuple ):
237 "use this function to pass exactly typed anys to the callee (using uno.Any)"
238 return pyuno.invoke( object, methodname, argTuple )
239
239
240#---------------------------------------------------------------------------------------
241# don't use any functions beyond this point, private section, likely to change
242#---------------------------------------------------------------------------------------
243#def _uno_import( name, globals={}, locals={}, fromlist=[], level=-1 ):
244def _uno_import( name, *optargs, **kwargs ):
245 try:
246# print "optargs = " + repr(optargs)
247 return _g_delegatee( name, *optargs, **kwargs )
248 except ImportError:
249 # process optargs
250 globals, locals, fromlist = list(optargs)[:3] + [kwargs.get('globals',{}), kwargs.get('locals',{}), kwargs.get('fromlist',[])][len(optargs):]
251 if not fromlist:
252 raise
253 modnames = name.split( "." )
254 mod = None
255 d = sys.modules
256 for x in modnames:
240#---------------------------------------------------------------------------------------
241# don't use any functions beyond this point, private section, likely to change
242#---------------------------------------------------------------------------------------
243#def _uno_import( name, globals={}, locals={}, fromlist=[], level=-1 ):
244def _uno_import( name, *optargs, **kwargs ):
245 try:
246# print "optargs = " + repr(optargs)
247 return _g_delegatee( name, *optargs, **kwargs )
248 except ImportError:
249 # process optargs
250 globals, locals, fromlist = list(optargs)[:3] + [kwargs.get('globals',{}), kwargs.get('locals',{}), kwargs.get('fromlist',[])][len(optargs):]
251 if not fromlist:
252 raise
253 modnames = name.split( "." )
254 mod = None
255 d = sys.modules
256 for x in modnames:
257 if d.has_key(x):
258 mod = d[x]
257 if x in d:
258 mod = d[x]
259 else:
259 else:
260 mod = pyuno.__class__(x) # How to create a module ??
260 mod = pyuno.__class__(x) # How to create a module ??
261 d = mod.__dict__
262
263 RuntimeException = pyuno.getClass( "com.sun.star.uno.RuntimeException" )
264 for x in fromlist:
261 d = mod.__dict__
262
263 RuntimeException = pyuno.getClass( "com.sun.star.uno.RuntimeException" )
264 for x in fromlist:
265 if not d.has_key(x):
266 if x.startswith( "typeOf" ):
267 try:
268 d[x] = pyuno.getTypeByName( name + "." + x[6:len(x)] )
269 except RuntimeException,e:
270 raise ImportError( "type " + name + "." + x[6:len(x)] +" is unknown" )
271 else:
272 try:
273 # check for structs, exceptions or interfaces
274 d[x] = pyuno.getClass( name + "." + x )
275 except RuntimeException,e:
276 # check for enums
265 if x not in d:
266 if x.startswith( "typeOf" ):
277 try:
267 try:
278 d[x] = Enum( name , x )
279 except RuntimeException,e2:
280 # check for constants
281 try:
282 d[x] = getConstantByName( name + "." + x )
283 except RuntimeException,e3:
284 # no known uno type !
285 raise ImportError( "type "+ name + "." +x + " is unknown" )
268 d[x] = pyuno.getTypeByName( name + "." + x[6:len(x)] )
269 except RuntimeException as e:
270 raise ImportError( "type " + name + "." + x[6:len(x)] +" is unknown" )
271 else:
272 try:
273 # check for structs, exceptions or interfaces
274 d[x] = pyuno.getClass( name + "." + x )
275 except RuntimeException as e:
276 # check for enums
277 try:
278 d[x] = Enum( name , x )
279 except RuntimeException as e2:
280 # check for constants
281 try:
282 d[x] = getConstantByName( name + "." + x )
283 except RuntimeException as e3:
284 # no known uno type !
285 raise ImportError( "type "+ name + "." +x + " is unknown" )
286 return mod
287
286 return mod
287
288# hook into the __import__ chain
288# hook into the __import__ chain
289__builtin__.__dict__["__import__"] = _uno_import
289__builtin__.__dict__["__import__"] = _uno_import
290
290
291# private function, don't use
292def _impl_extractName(name):
291# private function, don't use
292def _impl_extractName(name):
293 r = range (len(name)-1,0,-1)
293 r = list(range(len(name)-1,0,-1))
294 for i in r:
295 if name[i] == ".":
294 for i in r:
295 if name[i] == ".":
296 name = name[i+1:len(name)]
297 break
298 return name
296 name = name[i+1:len(name)]
297 break
298 return name
299
300# private, referenced from the pyuno shared library
301def _uno_struct__init__(self,*args):
302 if len(args) == 1 and hasattr(args[0], "__class__") and args[0].__class__ == self.__class__ :
299
300# private, referenced from the pyuno shared library
301def _uno_struct__init__(self,*args):
302 if len(args) == 1 and hasattr(args[0], "__class__") and args[0].__class__ == self.__class__ :
303 self.__dict__["value"] = args[0]
303 self.__dict__["value"] = args[0]
304 else:
304 else:
305 self.__dict__["value"] = pyuno._createUnoStructHelper(self.__class__.__pyunostruct__,args)
306
305 self.__dict__["value"] = pyuno._createUnoStructHelper(self.__class__.__pyunostruct__,args)
306
307# private, referenced from the pyuno shared library
308def _uno_struct__getattr__(self,name):
309 return __builtin__.getattr(self.__dict__["value"],name)
310
311# private, referenced from the pyuno shared library
312def _uno_struct__setattr__(self,name,value):
313 return __builtin__.setattr(self.__dict__["value"],name,value)
314
315# private, referenced from the pyuno shared library
316def _uno_struct__repr__(self):
317 return repr(self.__dict__["value"])
307# private, referenced from the pyuno shared library
308def _uno_struct__getattr__(self,name):
309 return __builtin__.getattr(self.__dict__["value"],name)
310
311# private, referenced from the pyuno shared library
312def _uno_struct__setattr__(self,name,value):
313 return __builtin__.setattr(self.__dict__["value"],name,value)
314
315# private, referenced from the pyuno shared library
316def _uno_struct__repr__(self):
317 return repr(self.__dict__["value"])
318
318
319def _uno_struct__str__(self):
320 return str(self.__dict__["value"])
321
322# private, referenced from the pyuno shared library
323def _uno_struct__eq__(self,cmp):
324 if hasattr(cmp,"value"):
319def _uno_struct__str__(self):
320 return str(self.__dict__["value"])
321
322# private, referenced from the pyuno shared library
323def _uno_struct__eq__(self,cmp):
324 if hasattr(cmp,"value"):
325 return self.__dict__["value"] == cmp.__dict__["value"]
325 return self.__dict__["value"] == cmp.__dict__["value"]
326 return False
327
328# referenced from pyuno shared lib and pythonscript.py
329def _uno_extract_printable_stacktrace( trace ):
330 mod = None
331 try:
332 mod = __import__("traceback")
326 return False
327
328# referenced from pyuno shared lib and pythonscript.py
329def _uno_extract_printable_stacktrace( trace ):
330 mod = None
331 try:
332 mod = __import__("traceback")
333 except ImportError,e:
333 except ImportError as e:
334 pass
335 ret = ""
336 if mod:
337 lst = mod.extract_tb( trace )
338 max = len(lst)
339 for j in range(max):
340 i = lst[max-j-1]
341 ret = ret + " " + str(i[0]) + ":" + \
342 str(i[1]) + " in function " + \
343 str(i[2]) + "() [" + str(i[3]) + "]\n"
344 else:
345 ret = "Couldn't import traceback module"
346 return ret
334 pass
335 ret = ""
336 if mod:
337 lst = mod.extract_tb( trace )
338 max = len(lst)
339 for j in range(max):
340 i = lst[max-j-1]
341 ret = ret + " " + str(i[0]) + ":" + \
342 str(i[1]) + " in function " + \
343 str(i[2]) + "() [" + str(i[3]) + "]\n"
344 else:
345 ret = "Couldn't import traceback module"
346 return ret