tdf#130857 qt weld: Support mail merge "Server Auth" dialog
[LibreOffice.git] / pyuno / source / module / uno.py
blobb2a75bd039825ee13c8b49f6a7a9b5bdaf430179
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 .
19 import pyuno
20 import sys
21 import traceback
22 import warnings
24 # since on Windows sal3.dll no longer calls WSAStartup
25 import socket
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.
43 """
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
56 """
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.
71 """
73 return pyuno.getTypeByName(typeName)
76 def createUnoStruct(typeName, *args, **kwargs):
77 """Creates a UNO struct or exception given by typeName.
79 Can be called with:
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.
95 """
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)
112 def generateUuid():
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)
142 class Enum:
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
153 self.value = value
154 pyuno.checkEnum(self)
156 def __repr__(self):
157 return "<Enum instance %s (%r)>" % (self.typeName, self.value)
159 def __eq__(self, that):
160 if not isinstance(that, Enum):
161 return False
163 return (self.typeName == that.typeName) and (self.value == that.value)
165 def __ne__(self,other):
166 return not self.__eq__(other)
169 class Type:
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)
183 def __repr__(self):
184 return "<Type instance %s (%r)>" % (self.typeName, self.typeClass)
186 def __eq__(self, that):
187 if not isinstance(that, Type):
188 return False
190 return self.typeClass == that.typeClass and self.typeName == that.typeName
192 def __ne__(self,other):
193 return not self.__eq__(other)
195 def __hash__(self):
196 return self.typeName.__hash__()
199 class Bool(object):
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":
212 return True
214 if isinstance(value, str) and value == "false":
215 return False
217 if value:
218 return True
220 return False
223 class Char:
224 """Represents a UNO char.
226 Use an instance of this class to explicitly pass a char to UNO.
228 For Python 3, this class only works with unicode (str) objects. Creating
229 a Char instance with a bytes object or comparing a Char instance
230 to a bytes 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."
239 assert ord(value[0]) <= 0xFFFF, "Char value must be UTF-16 code unit"
241 self.value = value
243 def __repr__(self):
244 return "<Char instance %s>" % (self.value,)
246 def __eq__(self, that):
247 if isinstance(that, str):
248 if len(that) > 1:
249 return False
251 return self.value == that[0]
253 if isinstance(that, Char):
254 return self.value == that.value
256 return False
258 def __ne__(self,other):
259 return not self.__eq__(other)
262 class ByteSequence:
263 """Represents a UNO ByteSequence value.
265 Use an instance of this class to explicitly pass a byte sequence to UNO.
267 :param value: A string or bytesequence
270 def __init__(self, value):
271 if isinstance(value, bytes):
272 self.value = value
274 elif isinstance(value, ByteSequence):
275 self.value = value.value
277 else:
278 raise TypeError("Expected bytes object or ByteSequence, got %s instead." % type(value))
280 def __repr__(self):
281 return "<ByteSequence instance '%s'>" % (self.value,)
283 def __eq__(self, that):
284 if isinstance(that, bytes):
285 return self.value == that
287 if isinstance(that, ByteSequence):
288 return self.value == that.value
290 return False
292 def __len__(self):
293 return len(self.value)
295 def __getitem__(self, index):
296 return self.value[index]
298 def __iter__(self):
299 return self.value.__iter__()
301 def __add__(self, b):
302 if isinstance(b, bytes):
303 return ByteSequence(self.value + b)
305 elif isinstance(b, ByteSequence):
306 return ByteSequence(self.value + b.value)
308 else:
309 raise TypeError("Can't add ByteString and %s." % type(b))
311 def __hash__(self):
312 return self.value.hash()
315 class Any:
316 """Represents a UNO Any value.
318 Use only in connection with uno.invoke() to pass an explicit typed Any.
321 def __init__(self, type, value):
322 if isinstance(type, Type):
323 self.type = type
324 else:
325 self.type = getTypeByName(type)
327 self.value = value
330 def invoke(object, methodname, argTuple):
331 """Use this function to pass exactly typed Anys to the callee (using uno.Any)."""
333 return pyuno.invoke(object, methodname, argTuple)
336 # -----------------------------------------------------------------------------
337 # Don't use any functions beyond this point; private section, likely to change.
338 # -----------------------------------------------------------------------------
339 _builtin_import = __import__
342 def _uno_import(name, *optargs, **kwargs):
343 """Overrides built-in import to allow directly importing LibreOffice classes."""
345 try:
346 return _builtin_import(name, *optargs, **kwargs)
347 except ImportError as e:
348 # process optargs
349 globals, locals, fromlist = list(optargs)[:3] + [kwargs.get('globals', {}), kwargs.get('locals', {}),
350 kwargs.get('fromlist', [])][len(optargs):]
352 # from import form only, but skip if a uno lookup has already failed
353 if not fromlist or hasattr(e, '_uno_import_failed'):
354 raise
356 # hang onto exception for possible use on subsequent uno lookup failure
357 py_import_exc = e
359 mod = None
360 d = sys.modules
362 for module in name.split("."):
363 if module in d:
364 mod = d[module]
365 else:
366 # How to create a module ??
367 mod = pyuno.__class__(module)
368 if mod is None:
369 raise py_import_exc
371 d = mod.__dict__
373 RuntimeException = pyuno.getClass("com.sun.star.uno.RuntimeException")
375 for class_name in fromlist:
376 if class_name not in d:
377 failed = False
379 try:
380 # check for structs, exceptions or interfaces
381 d[class_name] = pyuno.getClass(name + "." + class_name)
382 except RuntimeException:
383 # check for enums
384 try:
385 d[class_name] = Enum(name, class_name)
386 except RuntimeException:
387 # check for constants
388 try:
389 d[class_name] = getConstantByName(name + "." + class_name)
390 except RuntimeException:
391 # check for constant group
392 try:
393 d[class_name] = _impl_getConstantGroupByName(name, class_name)
394 except ValueError:
395 failed = True
397 if failed:
398 # We have an import failure, but cannot distinguish between
399 # uno and non-uno errors as uno lookups are attempted for all
400 # "from xxx import yyy" imports following a python failure.
402 # In Python 3, the original python exception traceback is reused
403 # to help pinpoint the actual failing location. Its original
404 # message, unlike Python 2, is unlikely to be helpful for uno
405 # failures, as it most commonly is just a top level module like
406 # 'com'. So our exception appends the uno lookup failure.
407 # This is more ambiguous, but it plus the traceback should be
408 # sufficient to identify a root cause for python or uno issues.
410 # Our exception is raised outside of the nested exception
411 # handlers above, to avoid Python 3 nested exception
412 # information for the RuntimeExceptions during lookups.
414 # Finally, a private attribute is used to prevent further
415 # processing if this failure was in a nested import. That
416 # keeps the exception relevant to the primary failure point,
417 # preventing us from re-processing our own import errors.
419 uno_import_exc = ImportError("%s (or '%s.%s' is unknown)" %
420 (py_import_exc, name, class_name))
422 uno_import_exc = uno_import_exc.with_traceback(py_import_exc.__traceback__)
424 uno_import_exc._uno_import_failed = True
425 raise uno_import_exc
427 return mod
430 try:
431 import __builtin__
432 except ImportError:
433 import builtins as __builtin__
435 # hook into the __import__ chain
436 __builtin__.__dict__['__import__'] = _uno_import
439 class _ConstantGroup(object):
440 """Represents a group of UNOIDL constants."""
442 __slots__ = ['_constants']
444 def __init__(self, constants):
445 self._constants = constants
447 def __dir__(self):
448 return self._constants.keys()
450 def __getattr__(self, name):
451 if name in self._constants:
452 return self._constants[name]
454 raise AttributeError("The constant '%s' could not be found." % name)
457 def _impl_getConstantGroupByName(module, group):
458 """Gets UNOIDL constant group by name."""
460 constants = Enum('com.sun.star.uno.TypeClass', 'CONSTANTS')
461 one = Enum('com.sun.star.reflection.TypeDescriptionSearchDepth', 'ONE')
462 type_desc_mgr = _component_context.getValueByName('/singletons/com.sun.star.reflection.theTypeDescriptionManager')
463 type_descs = type_desc_mgr.createTypeDescriptionEnumeration(module, (constants,), one)
464 qualified_name = module + '.' + group
466 for type_desc in type_descs:
467 if type_desc.Name == qualified_name:
468 return _ConstantGroup(dict(
469 (c.Name.split('.')[-1], c.ConstantValue)
470 for c in type_desc.Constants))
472 raise ValueError("The constant group '%s' could not be found." % qualified_name)
475 def _uno_struct__init__(self, *args, **kwargs):
476 """Initializes a UNO struct.
478 Referenced from the pyuno shared library.
480 This function can be called with either an already constructed UNO struct, which it
481 will then just reference without copying, or with arguments to create a new UNO struct.
484 # Check to see if this function was passed an existing UNO struct
485 if len(kwargs) == 0 and len(args) == 1 and getattr(args[0], "__class__", None) == self.__class__:
486 self.__dict__['value'] = args[0]
487 else:
488 struct, used = pyuno._createUnoStructHelper(self.__class__.__pyunostruct__, args, **kwargs)
490 for kwarg in kwargs.keys():
491 if not used.get(kwarg):
492 RuntimeException = pyuno.getClass("com.sun.star.uno.RuntimeException")
493 raise RuntimeException("_uno_struct__init__: unused keyword argument '%s'." % kwarg, None)
495 self.__dict__["value"] = struct
498 def _uno_struct__getattr__(self, name):
499 """Gets attribute from UNO struct.
501 Referenced from the pyuno shared library.
504 return getattr(self.__dict__["value"], name)
507 def _uno_struct__setattr__(self, name, value):
508 """Sets attribute on UNO struct.
510 Referenced from the pyuno shared library.
513 return setattr(self.__dict__["value"], name, value)
516 def _uno_struct__repr__(self):
517 """Converts a UNO struct to a printable string.
519 Referenced from the pyuno shared library.
522 return repr(self.__dict__["value"])
525 def _uno_struct__str__(self):
526 """Converts a UNO struct to a string."""
528 return str(self.__dict__["value"])
530 def _uno_struct__ne__(self, other):
531 return not self.__eq__(other)
533 def _uno_struct__eq__(self, that):
534 """Compares two UNO structs.
536 Referenced from the pyuno shared library.
539 if hasattr(that, "value"):
540 return self.__dict__["value"] == that.__dict__["value"]
542 return False
545 def _uno_extract_printable_stacktrace(trace):
546 """Extracts a printable stacktrace.
548 Referenced from pyuno shared lib and pythonscript.py.
551 return ''.join(traceback.format_tb(trace))
553 # vim: set shiftwidth=4 softtabstop=4 expandtab: