uno.py 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553
  1. # -*- tab-width: 4; indent-tabs-mode: nil; py-indent-offset: 4 -*-
  2. #
  3. # This file is part of the LibreOffice project.
  4. #
  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/.
  8. #
  9. # This file incorporates work covered by the following license notice:
  10. #
  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 .
  18. #
  19. import pyuno
  20. import sys
  21. import traceback
  22. import warnings
  23. # since on Windows sal3.dll no longer calls WSAStartup
  24. import socket
  25. # All functions and variables starting with a underscore (_) must be
  26. # considered private and can be changed at any time. Don't use them.
  27. _component_context = pyuno.getComponentContext()
  28. def getComponentContext():
  29. """Returns the UNO component context used to initialize the Python runtime."""
  30. return _component_context
  31. def getCurrentContext():
  32. """Returns the current context.
  33. See http://udk.openoffice.org/common/man/concept/uno_contexts.html#current_context
  34. for an explanation on the current context concept.
  35. """
  36. return pyuno.getCurrentContext()
  37. def setCurrentContext(newContext):
  38. """Sets newContext as new UNO context.
  39. The newContext must implement the XCurrentContext interface. The
  40. implementation should handle the desired properties and delegate
  41. unknown properties to the old context. Ensure that the old one
  42. is reset when you leave your stack, see
  43. http://udk.openoffice.org/common/man/concept/uno_contexts.html#current_context
  44. """
  45. return pyuno.setCurrentContext(newContext)
  46. def getConstantByName(constant):
  47. """Looks up the value of an IDL constant by giving its explicit name."""
  48. return pyuno.getConstantByName(constant)
  49. def getTypeByName(typeName):
  50. """Returns a `uno.Type` instance of the type given by typeName.
  51. If the type does not exist, a `com.sun.star.uno.RuntimeException` is raised.
  52. """
  53. return pyuno.getTypeByName(typeName)
  54. def createUnoStruct(typeName, *args, **kwargs):
  55. """Creates a UNO struct or exception given by typeName.
  56. Can be called with:
  57. 1) No additional argument.
  58. In this case, you get a default constructed UNO structure.
  59. (e.g. `createUnoStruct("com.sun.star.uno.Exception")`)
  60. 2) Exactly one additional argument that is an instance of typeName.
  61. In this case, a copy constructed instance of typeName is returned
  62. (e.g. `createUnoStruct("com.sun.star.uno.Exception" , e)`)
  63. 3) As many additional arguments as the number of elements within typeName
  64. (e.g. `createUnoStruct("com.sun.star.uno.Exception", "foo error" , self)`).
  65. 4) Keyword arguments to give values for each element of the struct by name.
  66. 5) A mix of 3) and 4), such that each struct element is given a value exactly once,
  67. either by a positional argument or by a keyword argument.
  68. The additional and/or keyword arguments must match the type of each struct element,
  69. otherwise an exception is thrown.
  70. """
  71. return getClass(typeName)(*args, **kwargs)
  72. def getClass(typeName):
  73. """Returns the class of a concrete UNO exception, struct, or interface."""
  74. return pyuno.getClass(typeName)
  75. def isInterface(obj):
  76. """Returns True, when obj is a class of a UNO interface."""
  77. return pyuno.isInterface(obj)
  78. def generateUuid():
  79. """Returns a 16 byte sequence containing a newly generated uuid or guid.
  80. For more information, see rtl/uuid.h.
  81. """
  82. return pyuno.generateUuid()
  83. def systemPathToFileUrl(systemPath):
  84. """Returns a file URL for the given system path."""
  85. return pyuno.systemPathToFileUrl(systemPath)
  86. def fileUrlToSystemPath(url):
  87. """Returns a system path.
  88. This path is determined by the system that the Python interpreter is running on.
  89. """
  90. return pyuno.fileUrlToSystemPath(url)
  91. def absolutize(path, relativeUrl):
  92. """Returns an absolute file url from the given urls."""
  93. return pyuno.absolutize(path, relativeUrl)
  94. class Enum:
  95. """Represents a UNO enum.
  96. Use an instance of this class to explicitly pass an enum to UNO.
  97. :param typeName: The name of the enum as a string.
  98. :param value: The actual value of this enum as a string.
  99. """
  100. def __init__(self, typeName, value):
  101. self.typeName = typeName
  102. self.value = value
  103. pyuno.checkEnum(self)
  104. def __repr__(self):
  105. return "<Enum instance %s (%r)>" % (self.typeName, self.value)
  106. def __eq__(self, that):
  107. if not isinstance(that, Enum):
  108. return False
  109. return (self.typeName == that.typeName) and (self.value == that.value)
  110. def __ne__(self,other):
  111. return not self.__eq__(other)
  112. class Type:
  113. """Represents a UNO type.
  114. Use an instance of this class to explicitly pass a type to UNO.
  115. :param typeName: Name of the UNO type
  116. :param typeClass: Python Enum of TypeClass, see com/sun/star/uno/TypeClass.idl
  117. """
  118. def __init__(self, typeName, typeClass):
  119. self.typeName = typeName
  120. self.typeClass = typeClass
  121. pyuno.checkType(self)
  122. def __repr__(self):
  123. return "<Type instance %s (%r)>" % (self.typeName, self.typeClass)
  124. def __eq__(self, that):
  125. if not isinstance(that, Type):
  126. return False
  127. return self.typeClass == that.typeClass and self.typeName == that.typeName
  128. def __ne__(self,other):
  129. return not self.__eq__(other)
  130. def __hash__(self):
  131. return self.typeName.__hash__()
  132. class Bool(object):
  133. """Represents a UNO boolean.
  134. Use an instance of this class to explicitly pass a boolean to UNO.
  135. Note: This class is deprecated. Use Python's True and False directly instead.
  136. """
  137. def __new__(cls, value):
  138. message = "The Bool class is deprecated. Use Python's True and False directly instead."
  139. warnings.warn(message, DeprecationWarning)
  140. if isinstance(value, str) and value == "true":
  141. return True
  142. if isinstance(value, str) and value == "false":
  143. return False
  144. if value:
  145. return True
  146. return False
  147. class Char:
  148. """Represents a UNO char.
  149. Use an instance of this class to explicitly pass a char to UNO.
  150. For Python 3, this class only works with unicode (str) objects. Creating
  151. a Char instance with a bytes object or comparing a Char instance
  152. to a bytes object will raise an AssertionError.
  153. :param value: A Unicode string with length 1
  154. """
  155. def __init__(self, value):
  156. assert isinstance(value, str), "Expected str object, got %s instead." % type(value)
  157. assert len(value) == 1, "Char value must have length of 1."
  158. assert ord(value[0]) <= 0xFFFF, "Char value must be UTF-16 code unit"
  159. self.value = value
  160. def __repr__(self):
  161. return "<Char instance %s>" % (self.value,)
  162. def __eq__(self, that):
  163. if isinstance(that, str):
  164. if len(that) > 1:
  165. return False
  166. return self.value == that[0]
  167. if isinstance(that, Char):
  168. return self.value == that.value
  169. return False
  170. def __ne__(self,other):
  171. return not self.__eq__(other)
  172. class ByteSequence:
  173. """Represents a UNO ByteSequence value.
  174. Use an instance of this class to explicitly pass a byte sequence to UNO.
  175. :param value: A string or bytesequence
  176. """
  177. def __init__(self, value):
  178. if isinstance(value, bytes):
  179. self.value = value
  180. elif isinstance(value, ByteSequence):
  181. self.value = value.value
  182. else:
  183. raise TypeError("Expected bytes object or ByteSequence, got %s instead." % type(value))
  184. def __repr__(self):
  185. return "<ByteSequence instance '%s'>" % (self.value,)
  186. def __eq__(self, that):
  187. if isinstance(that, bytes):
  188. return self.value == that
  189. if isinstance(that, ByteSequence):
  190. return self.value == that.value
  191. return False
  192. def __len__(self):
  193. return len(self.value)
  194. def __getitem__(self, index):
  195. return self.value[index]
  196. def __iter__(self):
  197. return self.value.__iter__()
  198. def __add__(self, b):
  199. if isinstance(b, bytes):
  200. return ByteSequence(self.value + b)
  201. elif isinstance(b, ByteSequence):
  202. return ByteSequence(self.value + b.value)
  203. else:
  204. raise TypeError("Can't add ByteString and %s." % type(b))
  205. def __hash__(self):
  206. return self.value.hash()
  207. class Any:
  208. """Represents a UNO Any value.
  209. Use only in connection with uno.invoke() to pass an explicit typed Any.
  210. """
  211. def __init__(self, type, value):
  212. if isinstance(type, Type):
  213. self.type = type
  214. else:
  215. self.type = getTypeByName(type)
  216. self.value = value
  217. def invoke(object, methodname, argTuple):
  218. """Use this function to pass exactly typed Anys to the callee (using uno.Any)."""
  219. return pyuno.invoke(object, methodname, argTuple)
  220. # -----------------------------------------------------------------------------
  221. # Don't use any functions beyond this point; private section, likely to change.
  222. # -----------------------------------------------------------------------------
  223. _builtin_import = __import__
  224. def _uno_import(name, *optargs, **kwargs):
  225. """Overrides built-in import to allow directly importing LibreOffice classes."""
  226. try:
  227. return _builtin_import(name, *optargs, **kwargs)
  228. except ImportError as e:
  229. # process optargs
  230. globals, locals, fromlist = list(optargs)[:3] + [kwargs.get('globals', {}), kwargs.get('locals', {}),
  231. kwargs.get('fromlist', [])][len(optargs):]
  232. # from import form only, but skip if a uno lookup has already failed
  233. if not fromlist or hasattr(e, '_uno_import_failed'):
  234. raise
  235. # hang onto exception for possible use on subsequent uno lookup failure
  236. py_import_exc = e
  237. mod = None
  238. d = sys.modules
  239. for module in name.split("."):
  240. if module in d:
  241. mod = d[module]
  242. else:
  243. # How to create a module ??
  244. mod = pyuno.__class__(module)
  245. if mod is None:
  246. raise py_import_exc
  247. d = mod.__dict__
  248. RuntimeException = pyuno.getClass("com.sun.star.uno.RuntimeException")
  249. for class_name in fromlist:
  250. if class_name not in d:
  251. failed = False
  252. try:
  253. # check for structs, exceptions or interfaces
  254. d[class_name] = pyuno.getClass(name + "." + class_name)
  255. except RuntimeException:
  256. # check for enums
  257. try:
  258. d[class_name] = Enum(name, class_name)
  259. except RuntimeException:
  260. # check for constants
  261. try:
  262. d[class_name] = getConstantByName(name + "." + class_name)
  263. except RuntimeException:
  264. # check for constant group
  265. try:
  266. d[class_name] = _impl_getConstantGroupByName(name, class_name)
  267. except ValueError:
  268. failed = True
  269. if failed:
  270. # We have an import failure, but cannot distinguish between
  271. # uno and non-uno errors as uno lookups are attempted for all
  272. # "from xxx import yyy" imports following a python failure.
  273. #
  274. # In Python 3, the original python exception traceback is reused
  275. # to help pinpoint the actual failing location. Its original
  276. # message, unlike Python 2, is unlikely to be helpful for uno
  277. # failures, as it most commonly is just a top level module like
  278. # 'com'. So our exception appends the uno lookup failure.
  279. # This is more ambiguous, but it plus the traceback should be
  280. # sufficient to identify a root cause for python or uno issues.
  281. #
  282. # Our exception is raised outside of the nested exception
  283. # handlers above, to avoid Python 3 nested exception
  284. # information for the RuntimeExceptions during lookups.
  285. #
  286. # Finally, a private attribute is used to prevent further
  287. # processing if this failure was in a nested import. That
  288. # keeps the exception relevant to the primary failure point,
  289. # preventing us from re-processing our own import errors.
  290. uno_import_exc = ImportError("%s (or '%s.%s' is unknown)" %
  291. (py_import_exc, name, class_name))
  292. uno_import_exc = uno_import_exc.with_traceback(py_import_exc.__traceback__)
  293. uno_import_exc._uno_import_failed = True
  294. raise uno_import_exc
  295. return mod
  296. try:
  297. import __builtin__
  298. except ImportError:
  299. import builtins as __builtin__
  300. # hook into the __import__ chain
  301. __builtin__.__dict__['__import__'] = _uno_import
  302. class _ConstantGroup(object):
  303. """Represents a group of UNOIDL constants."""
  304. __slots__ = ['_constants']
  305. def __init__(self, constants):
  306. self._constants = constants
  307. def __dir__(self):
  308. return self._constants.keys()
  309. def __getattr__(self, name):
  310. if name in self._constants:
  311. return self._constants[name]
  312. raise AttributeError("The constant '%s' could not be found." % name)
  313. def _impl_getConstantGroupByName(module, group):
  314. """Gets UNOIDL constant group by name."""
  315. constants = Enum('com.sun.star.uno.TypeClass', 'CONSTANTS')
  316. one = Enum('com.sun.star.reflection.TypeDescriptionSearchDepth', 'ONE')
  317. type_desc_mgr = _component_context.getValueByName('/singletons/com.sun.star.reflection.theTypeDescriptionManager')
  318. type_descs = type_desc_mgr.createTypeDescriptionEnumeration(module, (constants,), one)
  319. qualified_name = module + '.' + group
  320. for type_desc in type_descs:
  321. if type_desc.Name == qualified_name:
  322. return _ConstantGroup(dict(
  323. (c.Name.split('.')[-1], c.ConstantValue)
  324. for c in type_desc.Constants))
  325. raise ValueError("The constant group '%s' could not be found." % qualified_name)
  326. def _uno_struct__init__(self, *args, **kwargs):
  327. """Initializes a UNO struct.
  328. Referenced from the pyuno shared library.
  329. This function can be called with either an already constructed UNO struct, which it
  330. will then just reference without copying, or with arguments to create a new UNO struct.
  331. """
  332. # Check to see if this function was passed an existing UNO struct
  333. if len(kwargs) == 0 and len(args) == 1 and getattr(args[0], "__class__", None) == self.__class__:
  334. self.__dict__['value'] = args[0]
  335. else:
  336. struct, used = pyuno._createUnoStructHelper(self.__class__.__pyunostruct__, args, **kwargs)
  337. for kwarg in kwargs.keys():
  338. if not used.get(kwarg):
  339. RuntimeException = pyuno.getClass("com.sun.star.uno.RuntimeException")
  340. raise RuntimeException("_uno_struct__init__: unused keyword argument '%s'." % kwarg, None)
  341. self.__dict__["value"] = struct
  342. def _uno_struct__getattr__(self, name):
  343. """Gets attribute from UNO struct.
  344. Referenced from the pyuno shared library.
  345. """
  346. return getattr(self.__dict__["value"], name)
  347. def _uno_struct__setattr__(self, name, value):
  348. """Sets attribute on UNO struct.
  349. Referenced from the pyuno shared library.
  350. """
  351. return setattr(self.__dict__["value"], name, value)
  352. def _uno_struct__repr__(self):
  353. """Converts a UNO struct to a printable string.
  354. Referenced from the pyuno shared library.
  355. """
  356. return repr(self.__dict__["value"])
  357. def _uno_struct__str__(self):
  358. """Converts a UNO struct to a string."""
  359. return str(self.__dict__["value"])
  360. def _uno_struct__ne__(self, other):
  361. return not self.__eq__(other)
  362. def _uno_struct__eq__(self, that):
  363. """Compares two UNO structs.
  364. Referenced from the pyuno shared library.
  365. """
  366. if hasattr(that, "value"):
  367. return self.__dict__["value"] == that.__dict__["value"]
  368. return False
  369. def _uno_extract_printable_stacktrace(trace):
  370. """Extracts a printable stacktrace.
  371. Referenced from pyuno shared lib and pythonscript.py.
  372. """
  373. return ''.join(traceback.format_tb(trace))
  374. # vim: set shiftwidth=4 softtabstop=4 expandtab: