1 #*************************************************************************
3 # DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
5 # Copyright 2008 by Sun Microsystems, Inc.
7 # OpenOffice.org - a multi-platform office productivity suite
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 #*************************************************************************
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"
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.
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.
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.
75 return getClass(typeName
)( *args
)
77 def getClass( typeName
):
78 """returns the class of a concrete uno exception, struct or interface
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
)
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
)
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
126 pyuno
.checkEnum( self
)
129 return "<uno.Enum %s (%r)>" % (self
.typeName
, self
.value
)
131 def __eq__(self
, that
):
132 if not isinstance(that
, Enum
):
134 return (self
.typeName
== that
.typeName
) and (self
.value
== that
.value
)
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
)
145 return "<Type instance %s (%r)>" % (self
.typeName
, self
.typeClass
)
147 def __eq__(self
, that
):
148 if not isinstance(that
, Type
):
150 return self
.typeClass
== that
.typeClass
and self
.typeName
== that
.typeName
153 return self
.typeName
.__hash
__()
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":
163 if isinstance(value
, (str, unicode)) and value
== "false":
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
178 return "<Char instance %s>" % (self
.value
, )
180 def __eq__(self
, that
):
181 if isinstance(that
, (str, unicode)):
184 return self
.value
== that
[0]
185 if isinstance(that
, Char
):
186 return self
.value
== that
.value
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):
201 # value = property(_get_value)
204 def __init__(self
, value
):
205 if isinstance(value
, str):
207 elif isinstance(value
, ByteSequence
):
208 self
.value
= value
.value
210 raise TypeError("expected string or bytesequence")
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
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()
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
):
248 self
.type = getTypeByName( type )
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
):
261 # print "optargs = " + repr(optargs)
262 return _g_delegatee( name
, *optargs
, **kwargs
)
265 globals, locals, fromlist
= list(optargs
)[:3] + [kwargs
.get('globals',{}), kwargs
.get('locals',{}), kwargs
.get('fromlist',[])][len(optargs
):]
268 modnames
= name
.split( "." )
275 mod
= pyuno
.__class
__(x
) # How to create a module ??
278 RuntimeException
= pyuno
.getClass( "com.sun.star.uno.RuntimeException" )
281 if x
.startswith( "typeOf" ):
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" )
288 # check for structs, exceptions or interfaces
289 d
[x
] = pyuno
.getClass( name
+ "." + x
)
290 except RuntimeException
,e
:
293 d
[x
] = Enum( name
, x
)
294 except RuntimeException
,e2
:
295 # check for constants
297 d
[x
] = getConstantByName( name
+ "." + x
)
298 except RuntimeException
,e3
:
299 # no known uno type !
300 raise ImportError( "type "+ name
+ "." +x
+ " is unknown" )
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)
311 name
= name
[i
+1:len(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]
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"]
343 # referenced from pyuno shared lib and pythonscript.py
344 def _uno_extract_printable_stacktrace( trace
):
347 mod
= __import__("traceback")
348 except ImportError,e
:
352 lst
= mod
.extract_tb( trace
)
356 ret
= ret
+ " " + str(i
[0]) + ":" + \
357 str(i
[1]) + " in function " + \
358 str(i
[2]) + "() [" + str(i
[3]) + "]\n"
360 ret
= "Couldn't import traceback module"