1 # -*- tab-width: 4; indent-tabs-mode: nil; py-indent-offset: 4 -*-
3 # This file is part of the LibreOffice project.
5 # This Source Code Form is subject to the terms of the Mozilla Public
6 # License, v. 2.0. If a copy of the MPL was not distributed with this
7 # file, You can obtain one at http://mozilla.org/MPL/2.0/.
9 # This file incorporates work covered by the following license notice:
11 # Licensed to the Apache Software Foundation (ASF) under one or more
12 # contributor license agreements. See the NOTICE file distributed
13 # with this work for additional information regarding copyright
14 # ownership. The ASF licenses this file to you under the Apache
15 # License, Version 2.0 (the "License"); you may not use this file
16 # except in compliance with the License. You may obtain a copy of
17 # the License at http://www.apache.org/licenses/LICENSE-2.0 .
24 # since on Windows sal3.dll no longer calls WSAStartup
27 # All functions and variables starting with a underscore (_) must be
28 # considered private and can be changed at any time. Don't use them.
29 _component_context
= pyuno
.getComponentContext()
32 def getComponentContext():
33 """Returns the UNO component context used to initialize the Python runtime."""
35 return _component_context
38 def getCurrentContext():
39 """Returns the current context.
41 See http://udk.openoffice.org/common/man/concept/uno_contexts.html#current_context
42 for an explanation on the current context concept.
45 return pyuno
.getCurrentContext()
48 def setCurrentContext(newContext
):
49 """Sets newContext as new UNO context.
51 The newContext must implement the XCurrentContext interface. The
52 implementation should handle the desired properties and delegate
53 unknown properties to the old context. Ensure that the old one
54 is reset when you leave your stack, see
55 http://udk.openoffice.org/common/man/concept/uno_contexts.html#current_context
58 return pyuno
.setCurrentContext(newContext
)
61 def getConstantByName(constant
):
62 """Looks up the value of an IDL constant by giving its explicit name."""
64 return pyuno
.getConstantByName(constant
)
67 def getTypeByName(typeName
):
68 """Returns a `uno.Type` instance of the type given by typeName.
70 If the type does not exist, a `com.sun.star.uno.RuntimeException` is raised.
73 return pyuno
.getTypeByName(typeName
)
76 def createUnoStruct(typeName
, *args
, **kwargs
):
77 """Creates a UNO struct or exception given by typeName.
81 1) No additional argument.
82 In this case, you get a default constructed UNO structure.
83 (e.g. `createUnoStruct("com.sun.star.uno.Exception")`)
84 2) Exactly one additional argument that is an instance of typeName.
85 In this case, a copy constructed instance of typeName is returned
86 (e.g. `createUnoStruct("com.sun.star.uno.Exception" , e)`)
87 3) As many additional arguments as the number of elements within typeName
88 (e.g. `createUnoStruct("com.sun.star.uno.Exception", "foo error" , self)`).
89 4) Keyword arguments to give values for each element of the struct by name.
90 5) A mix of 3) and 4), such that each struct element is given a value exactly once,
91 either by a positional argument or by a keyword argument.
93 The additional and/or keyword arguments must match the type of each struct element,
94 otherwise an exception is thrown.
97 return getClass(typeName
)(*args
, **kwargs
)
100 def getClass(typeName
):
101 """Returns the class of a concrete UNO exception, struct, or interface."""
103 return pyuno
.getClass(typeName
)
106 def isInterface(obj
):
107 """Returns True, when obj is a class of a UNO interface."""
109 return pyuno
.isInterface(obj
)
113 """Returns a 16 byte sequence containing a newly generated uuid or guid.
115 For more information, see rtl/uuid.h.
118 return pyuno
.generateUuid()
121 def systemPathToFileUrl(systemPath
):
122 """Returns a file URL for the given system path."""
124 return pyuno
.systemPathToFileUrl(systemPath
)
127 def fileUrlToSystemPath(url
):
128 """Returns a system path.
130 This path is determined by the system that the Python interpreter is running on.
133 return pyuno
.fileUrlToSystemPath(url
)
136 def absolutize(path
, relativeUrl
):
137 """Returns an absolute file url from the given urls."""
139 return pyuno
.absolutize(path
, relativeUrl
)
143 """Represents a UNO enum.
145 Use an instance of this class to explicitly pass an enum to UNO.
147 :param typeName: The name of the enum as a string.
148 :param value: The actual value of this enum as a string.
151 def __init__(self
, typeName
, value
):
152 self
.typeName
= typeName
154 pyuno
.checkEnum(self
)
157 return "<Enum instance %s (%r)>" % (self
.typeName
, self
.value
)
159 def __eq__(self
, that
):
160 if not isinstance(that
, Enum
):
163 return (self
.typeName
== that
.typeName
) and (self
.value
== that
.value
)
165 def __ne__(self
,other
):
166 return not self
.__eq
__(other
)
170 """Represents a UNO type.
172 Use an instance of this class to explicitly pass a type to UNO.
174 :param typeName: Name of the UNO type
175 :param typeClass: Python Enum of TypeClass, see com/sun/star/uno/TypeClass.idl
178 def __init__(self
, typeName
, typeClass
):
179 self
.typeName
= typeName
180 self
.typeClass
= typeClass
181 pyuno
.checkType(self
)
184 return "<Type instance %s (%r)>" % (self
.typeName
, self
.typeClass
)
186 def __eq__(self
, that
):
187 if not isinstance(that
, Type
):
190 return self
.typeClass
== that
.typeClass
and self
.typeName
== that
.typeName
192 def __ne__(self
,other
):
193 return not self
.__eq
__(other
)
196 return self
.typeName
.__hash
__()
200 """Represents a UNO boolean.
202 Use an instance of this class to explicitly pass a boolean to UNO.
204 Note: This class is deprecated. Use Python's True and False directly instead.
207 def __new__(cls
, value
):
208 message
= "The Bool class is deprecated. Use Python's True and False directly instead."
209 warnings
.warn(message
, DeprecationWarning)
211 if isinstance(value
, str) and value
== "true":
214 if isinstance(value
, str) and value
== "false":
224 """Represents a UNO char.
226 Use an instance of this class to explicitly pass a char to UNO.
228 For Python 2, this class only works with unicode objects. Creating
229 a Char instance with a normal str object or comparing a Char instance
230 to a normal str object will raise an AssertionError.
232 :param value: A Unicode string with length 1
235 def __init__(self
, value
):
236 assert isinstance(value
, str), "Expected str object, got %s instead." % type(value
)
238 assert len(value
) == 1, "Char value must have length of 1."
243 return "<Char instance %s>" % (self
.value
,)
245 def __eq__(self
, that
):
246 if isinstance(that
, str):
250 return self
.value
== that
[0]
252 if isinstance(that
, Char
):
253 return self
.value
== that
.value
257 def __ne__(self
,other
):
258 return not self
.__eq
__(other
)
262 """Represents a UNO ByteSequence value.
264 Use an instance of this class to explicitly pass a byte sequence to UNO.
266 :param value: A string or bytesequence
269 def __init__(self
, value
):
270 if isinstance(value
, bytes
):
273 elif isinstance(value
, ByteSequence
):
274 self
.value
= value
.value
277 raise TypeError("Expected bytes object or ByteSequence, got %s instead." % type(value
))
280 return "<ByteSequence instance '%s'>" % (self
.value
,)
282 def __eq__(self
, that
):
283 if isinstance(that
, bytes
):
284 return self
.value
== that
286 if isinstance(that
, ByteSequence
):
287 return self
.value
== that
.value
292 return len(self
.value
)
294 def __getitem__(self
, index
):
295 return self
.value
[index
]
298 return self
.value
.__iter
__()
300 def __add__(self
, b
):
301 if isinstance(b
, bytes
):
302 return ByteSequence(self
.value
+ b
)
304 elif isinstance(b
, ByteSequence
):
305 return ByteSequence(self
.value
+ b
.value
)
308 raise TypeError("Can't add ByteString and %s." % type(b
))
311 return self
.value
.hash()
315 """Represents a UNO Any value.
317 Use only in connection with uno.invoke() to pass an explicit typed Any.
320 def __init__(self
, type, value
):
321 if isinstance(type, Type
):
324 self
.type = getTypeByName(type)
329 def invoke(object, methodname
, argTuple
):
330 """Use this function to pass exactly typed Anys to the callee (using uno.Any)."""
332 return pyuno
.invoke(object, methodname
, argTuple
)
335 # -----------------------------------------------------------------------------
336 # Don't use any functions beyond this point; private section, likely to change.
337 # -----------------------------------------------------------------------------
338 _builtin_import
= __import__
341 def _uno_import(name
, *optargs
, **kwargs
):
342 """Overrides built-in import to allow directly importing LibreOffice classes."""
345 return _builtin_import(name
, *optargs
, **kwargs
)
346 except ImportError as e
:
348 globals, locals, fromlist
= list(optargs
)[:3] + [kwargs
.get('globals', {}), kwargs
.get('locals', {}),
349 kwargs
.get('fromlist', [])][len(optargs
):]
351 # from import form only, but skip if a uno lookup has already failed
352 if not fromlist
or hasattr(e
, '_uno_import_failed'):
355 # hang onto exception for possible use on subsequent uno lookup failure
361 for module
in name
.split("."):
365 # How to create a module ??
366 mod
= pyuno
.__class
__(module
)
370 RuntimeException
= pyuno
.getClass("com.sun.star.uno.RuntimeException")
372 for class_name
in fromlist
:
373 if class_name
not in d
:
377 # check for structs, exceptions or interfaces
378 d
[class_name
] = pyuno
.getClass(name
+ "." + class_name
)
379 except RuntimeException
:
382 d
[class_name
] = Enum(name
, class_name
)
383 except RuntimeException
:
384 # check for constants
386 d
[class_name
] = getConstantByName(name
+ "." + class_name
)
387 except RuntimeException
:
388 # check for constant group
390 d
[class_name
] = _impl_getConstantGroupByName(name
, class_name
)
395 # We have an import failure, but cannot distinguish between
396 # uno and non-uno errors as uno lookups are attempted for all
397 # "from xxx import yyy" imports following a python failure.
399 # In Python 3, the original python exception traceback is reused
400 # to help pinpoint the actual failing location. Its original
401 # message, unlike Python 2, is unlikely to be helpful for uno
402 # failures, as it most commonly is just a top level module like
403 # 'com'. So our exception appends the uno lookup failure.
404 # This is more ambiguous, but it plus the traceback should be
405 # sufficient to identify a root cause for python or uno issues.
407 # Our exception is raised outside of the nested exception
408 # handlers above, to avoid Python 3 nested exception
409 # information for the RuntimeExceptions during lookups.
411 # Finally, a private attribute is used to prevent further
412 # processing if this failure was in a nested import. That
413 # keeps the exception relevant to the primary failure point,
414 # preventing us from re-processing our own import errors.
416 uno_import_exc
= ImportError("%s (or '%s.%s' is unknown)" %
417 (py_import_exc
, name
, class_name
))
419 uno_import_exc
= uno_import_exc
.with_traceback(py_import_exc
.__traceback
__)
421 uno_import_exc
._uno
_import
_failed
= True
430 import builtins
as __builtin__
432 # hook into the __import__ chain
433 __builtin__
.__dict
__['__import__'] = _uno_import
436 class _ConstantGroup(object):
437 """Represents a group of UNOIDL constants."""
439 __slots__
= ['_constants']
441 def __init__(self
, constants
):
442 self
._constants
= constants
445 return self
._constants
.keys()
447 def __getattr__(self
, name
):
448 if name
in self
._constants
:
449 return self
._constants
[name
]
451 raise AttributeError("The constant '%s' could not be found." % name
)
454 def _impl_getConstantGroupByName(module
, group
):
455 """Gets UNOIDL constant group by name."""
457 constants
= Enum('com.sun.star.uno.TypeClass', 'CONSTANTS')
458 one
= Enum('com.sun.star.reflection.TypeDescriptionSearchDepth', 'ONE')
459 type_desc_mgr
= _component_context
.getValueByName('/singletons/com.sun.star.reflection.theTypeDescriptionManager')
460 type_descs
= type_desc_mgr
.createTypeDescriptionEnumeration(module
, (constants
,), one
)
461 qualified_name
= module
+ '.' + group
463 for type_desc
in type_descs
:
464 if type_desc
.Name
== qualified_name
:
465 return _ConstantGroup(dict(
466 (c
.Name
.split('.')[-1], c
.ConstantValue
)
467 for c
in type_desc
.Constants
))
469 raise ValueError("The constant group '%s' could not be found." % qualified_name
)
472 def _uno_struct__init__(self
, *args
, **kwargs
):
473 """Initializes a UNO struct.
475 Referenced from the pyuno shared library.
477 This function can be called with either an already constructed UNO struct, which it
478 will then just reference without copying, or with arguments to create a new UNO struct.
481 # Check to see if this function was passed an existing UNO struct
482 if len(kwargs
) == 0 and len(args
) == 1 and getattr(args
[0], "__class__", None) == self
.__class
__:
483 self
.__dict
__['value'] = args
[0]
485 struct
, used
= pyuno
._createUnoStructHelper
(self
.__class
__.__pyunostruct
__, args
, **kwargs
)
487 for kwarg
in kwargs
.keys():
488 if not used
.get(kwarg
):
489 RuntimeException
= pyuno
.getClass("com.sun.star.uno.RuntimeException")
490 raise RuntimeException("_uno_struct__init__: unused keyword argument '%s'." % kwarg
, None)
492 self
.__dict
__["value"] = struct
495 def _uno_struct__getattr__(self
, name
):
496 """Gets attribute from UNO struct.
498 Referenced from the pyuno shared library.
501 return getattr(self
.__dict
__["value"], name
)
504 def _uno_struct__setattr__(self
, name
, value
):
505 """Sets attribute on UNO struct.
507 Referenced from the pyuno shared library.
510 return setattr(self
.__dict
__["value"], name
, value
)
513 def _uno_struct__repr__(self
):
514 """Converts a UNO struct to a printable string.
516 Referenced from the pyuno shared library.
519 return repr(self
.__dict
__["value"])
522 def _uno_struct__str__(self
):
523 """Converts a UNO struct to a string."""
525 return str(self
.__dict
__["value"])
527 def _uno_struct__ne__(self
, other
):
528 return not self
.__eq
__(other
)
530 def _uno_struct__eq__(self
, that
):
531 """Compares two UNO structs.
533 Referenced from the pyuno shared library.
536 if hasattr(that
, "value"):
537 return self
.__dict
__["value"] == that
.__dict
__["value"]
542 def _uno_extract_printable_stacktrace(trace
):
543 """Extracts a printable stacktrace.
545 Referenced from pyuno shared lib and pythonscript.py.
548 return ''.join(traceback
.format_tb(trace
))
550 # vim: set shiftwidth=4 softtabstop=4 expandtab: