dbus-fast 3.1.2__cp310-cp310-macosx_11_0_arm64.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (51) hide show
  1. dbus_fast/__init__.py +82 -0
  2. dbus_fast/__version__.py +10 -0
  3. dbus_fast/_private/__init__.py +1 -0
  4. dbus_fast/_private/_cython_compat.py +14 -0
  5. dbus_fast/_private/address.cpython-310-darwin.so +0 -0
  6. dbus_fast/_private/address.pxd +15 -0
  7. dbus_fast/_private/address.py +119 -0
  8. dbus_fast/_private/constants.py +20 -0
  9. dbus_fast/_private/marshaller.cpython-310-darwin.so +0 -0
  10. dbus_fast/_private/marshaller.pxd +110 -0
  11. dbus_fast/_private/marshaller.py +231 -0
  12. dbus_fast/_private/unmarshaller.cpython-310-darwin.so +0 -0
  13. dbus_fast/_private/unmarshaller.pxd +261 -0
  14. dbus_fast/_private/unmarshaller.py +904 -0
  15. dbus_fast/_private/util.py +177 -0
  16. dbus_fast/aio/__init__.py +5 -0
  17. dbus_fast/aio/message_bus.py +578 -0
  18. dbus_fast/aio/message_reader.cpython-310-darwin.so +0 -0
  19. dbus_fast/aio/message_reader.pxd +13 -0
  20. dbus_fast/aio/message_reader.py +51 -0
  21. dbus_fast/aio/proxy_object.py +208 -0
  22. dbus_fast/auth.py +125 -0
  23. dbus_fast/constants.py +152 -0
  24. dbus_fast/errors.py +81 -0
  25. dbus_fast/glib/__init__.py +3 -0
  26. dbus_fast/glib/message_bus.py +513 -0
  27. dbus_fast/glib/proxy_object.py +318 -0
  28. dbus_fast/introspection.py +686 -0
  29. dbus_fast/message.cpython-310-darwin.so +0 -0
  30. dbus_fast/message.pxd +76 -0
  31. dbus_fast/message.py +389 -0
  32. dbus_fast/message_bus.cpython-310-darwin.so +0 -0
  33. dbus_fast/message_bus.pxd +75 -0
  34. dbus_fast/message_bus.py +1332 -0
  35. dbus_fast/proxy_object.py +357 -0
  36. dbus_fast/py.typed +0 -0
  37. dbus_fast/send_reply.py +61 -0
  38. dbus_fast/service.cpython-310-darwin.so +0 -0
  39. dbus_fast/service.pxd +50 -0
  40. dbus_fast/service.py +727 -0
  41. dbus_fast/signature.cpython-310-darwin.so +0 -0
  42. dbus_fast/signature.pxd +31 -0
  43. dbus_fast/signature.py +484 -0
  44. dbus_fast/unpack.cpython-310-darwin.so +0 -0
  45. dbus_fast/unpack.pxd +13 -0
  46. dbus_fast/unpack.py +28 -0
  47. dbus_fast/validators.py +199 -0
  48. dbus_fast-3.1.2.dist-info/METADATA +262 -0
  49. dbus_fast-3.1.2.dist-info/RECORD +51 -0
  50. dbus_fast-3.1.2.dist-info/WHEEL +6 -0
  51. dbus_fast-3.1.2.dist-info/licenses/LICENSE +22 -0
@@ -0,0 +1,357 @@
1
+ from __future__ import annotations
2
+
3
+ import asyncio
4
+ import inspect
5
+ import logging
6
+ import re
7
+ import xml.etree.ElementTree as ET
8
+ from collections.abc import Callable, Coroutine
9
+ from dataclasses import dataclass
10
+ from functools import lru_cache
11
+
12
+ from . import introspection as intr
13
+ from . import message_bus
14
+ from ._private.util import replace_idx_with_fds
15
+ from .constants import ErrorType, MessageType
16
+ from .errors import DBusError, InterfaceNotFoundError
17
+ from .message import Message
18
+ from .unpack import unpack_variants as unpack
19
+ from .validators import assert_bus_name_valid, assert_object_path_valid
20
+
21
+ _LOGGER = logging.getLogger(__name__)
22
+
23
+
24
+ @dataclass
25
+ class SignalHandler:
26
+ """Signal handler."""
27
+
28
+ fn: Callable | Coroutine
29
+ unpack_variants: bool
30
+
31
+
32
+ class BaseProxyInterface:
33
+ """An abstract class representing a proxy to an interface exported on the bus by another client.
34
+
35
+ Implementations of this class are not meant to be constructed directly by
36
+ users. Use :func:`BaseProxyObject.get_interface` to get a proxy interface.
37
+ Each message bus implementation provides its own proxy interface
38
+ implementation that will be returned by that method.
39
+
40
+ Proxy interfaces can be used to call methods, get properties, and listen to
41
+ signals on the interface. Proxy interfaces are created dynamically with a
42
+ family of methods for each of these operations based on what members the
43
+ interface exposes. Each proxy interface implementation exposes these
44
+ members in a different way depending on the features of the backend. See
45
+ the documentation of the proxy interface implementation you use for more
46
+ details.
47
+
48
+ :ivar bus_name: The name of the bus this interface is exported on.
49
+ :vartype bus_name: str
50
+ :ivar path: The object path exported on the client that owns the bus name.
51
+ :vartype path: str
52
+ :ivar introspection: Parsed introspection data for the proxy interface.
53
+ :vartype introspection: :class:`Node <dbus_fast.introspection.Interface>`
54
+ :ivar bus: The message bus this proxy interface is connected to.
55
+ :vartype bus: :class:`BaseMessageBus <dbus_fast.message_bus.BaseMessageBus>`
56
+ """
57
+
58
+ def __init__(
59
+ self,
60
+ bus_name: str,
61
+ path: str,
62
+ introspection: intr.Interface,
63
+ bus: message_bus.BaseMessageBus,
64
+ ) -> None:
65
+ self.bus_name = bus_name
66
+ self.path = path
67
+ self.introspection = introspection
68
+ self.bus = bus
69
+ self._signal_handlers: dict[str, list[SignalHandler]] = {}
70
+ self._signal_match_rule = f"type='signal',sender={bus_name},interface={introspection.name},path={path}"
71
+ self._background_tasks: set[asyncio.Task] = set()
72
+
73
+ _underscorer1 = re.compile(r"(.)([A-Z][a-z]+)")
74
+ _underscorer2 = re.compile(r"([a-z0-9])([A-Z])")
75
+
76
+ @staticmethod
77
+ @lru_cache(maxsize=128)
78
+ def _to_snake_case(member: str) -> str:
79
+ subbed = BaseProxyInterface._underscorer1.sub(r"\1_\2", member)
80
+ return BaseProxyInterface._underscorer2.sub(r"\1_\2", subbed).lower()
81
+
82
+ @staticmethod
83
+ def _check_method_return(msg: Message, signature: str | None = None):
84
+ if msg.message_type == MessageType.ERROR:
85
+ raise DBusError._from_message(msg)
86
+ if msg.message_type != MessageType.METHOD_RETURN:
87
+ raise DBusError(
88
+ ErrorType.CLIENT_ERROR, "method call didnt return a method return", msg
89
+ )
90
+ if signature is not None and msg.signature != signature:
91
+ raise DBusError(
92
+ ErrorType.CLIENT_ERROR,
93
+ f'method call returned unexpected signature: "{msg.signature}"',
94
+ msg,
95
+ )
96
+
97
+ def _add_method(self, intr_method: intr.Method) -> None:
98
+ raise NotImplementedError("this must be implemented in the inheriting class")
99
+
100
+ def _add_property(self, intr_property: intr.Property) -> None:
101
+ raise NotImplementedError("this must be implemented in the inheriting class")
102
+
103
+ def _message_handler(self, msg: Message) -> None:
104
+ if (
105
+ msg.message_type != MessageType.SIGNAL
106
+ or msg.interface != self.introspection.name
107
+ or msg.path != self.path
108
+ or msg.member not in self._signal_handlers
109
+ ):
110
+ return
111
+
112
+ if (
113
+ msg.sender != self.bus_name
114
+ and self.bus._name_owners.get(self.bus_name, "") != msg.sender
115
+ ):
116
+ # The sender is always a unique name, but the bus name given might
117
+ # be a well known name. If the sender isn't an exact match, check
118
+ # to see if it owns the bus_name we were given from the cache kept
119
+ # on the bus for this purpose.
120
+ return
121
+
122
+ match = [s for s in self.introspection.signals if s.name == msg.member]
123
+ if not match:
124
+ return
125
+ intr_signal = match[0]
126
+ if intr_signal.signature != msg.signature:
127
+ _LOGGER.warning(
128
+ f'got signal "{self.introspection.name}.{msg.member}" with unexpected signature "{msg.signature}"'
129
+ )
130
+ return
131
+
132
+ body = replace_idx_with_fds(msg.signature, msg.body, msg.unix_fds)
133
+ no_sig = None
134
+ for handler in self._signal_handlers[msg.member]:
135
+ if handler.unpack_variants:
136
+ if not no_sig:
137
+ no_sig = unpack(body)
138
+ data = no_sig
139
+ else:
140
+ data = body
141
+
142
+ cb_result = handler.fn(*data)
143
+ if isinstance(cb_result, Coroutine):
144
+ # Save a strong reference to the task so it doesn't get garbage
145
+ # collected before it finishes.
146
+ task = asyncio.create_task(cb_result)
147
+ self._background_tasks.add(task)
148
+ task.add_done_callback(self._background_tasks.remove)
149
+
150
+ def _add_signal(self, intr_signal: intr.Signal, interface: intr.Interface) -> None:
151
+ def on_signal_fn(fn: Callable | Coroutine, *, unpack_variants: bool = False):
152
+ fn_signature = inspect.signature(fn)
153
+ if (
154
+ len(
155
+ [
156
+ par
157
+ for par in fn_signature.parameters.values()
158
+ if par.kind == inspect.Parameter.KEYWORD_ONLY
159
+ and par.default == inspect.Parameter.empty
160
+ ]
161
+ )
162
+ > 0
163
+ ):
164
+ raise TypeError(
165
+ "reply_notify cannot have required keyword only parameters"
166
+ )
167
+
168
+ positional_params = [
169
+ par.kind
170
+ for par in fn_signature.parameters.values()
171
+ if par.kind
172
+ not in [inspect.Parameter.KEYWORD_ONLY, inspect.Parameter.VAR_KEYWORD]
173
+ ]
174
+ if len(positional_params) != len(intr_signal.args) and (
175
+ inspect.Parameter.VAR_POSITIONAL not in positional_params
176
+ or len(positional_params) - 1 > len(intr_signal.args)
177
+ ):
178
+ raise TypeError(
179
+ f"reply_notify must be a function with {len(intr_signal.args)} positional parameters"
180
+ )
181
+
182
+ if not self._signal_handlers:
183
+ self.bus._add_match_rule(self._signal_match_rule)
184
+ self.bus.add_message_handler(self._message_handler)
185
+
186
+ if intr_signal.name not in self._signal_handlers:
187
+ self._signal_handlers[intr_signal.name] = []
188
+
189
+ self._signal_handlers[intr_signal.name].append(
190
+ SignalHandler(fn, unpack_variants)
191
+ )
192
+
193
+ def off_signal_fn(
194
+ fn: Callable | Coroutine, *, unpack_variants: bool = False
195
+ ) -> None:
196
+ try:
197
+ i = self._signal_handlers[intr_signal.name].index(
198
+ SignalHandler(fn, unpack_variants)
199
+ )
200
+ del self._signal_handlers[intr_signal.name][i]
201
+ if not self._signal_handlers[intr_signal.name]:
202
+ del self._signal_handlers[intr_signal.name]
203
+ except (KeyError, ValueError):
204
+ return
205
+
206
+ if not self._signal_handlers:
207
+ self.bus._remove_match_rule(self._signal_match_rule)
208
+ self.bus.remove_message_handler(self._message_handler)
209
+
210
+ snake_case = BaseProxyInterface._to_snake_case(intr_signal.name)
211
+ setattr(interface, f"on_{snake_case}", on_signal_fn)
212
+ setattr(interface, f"off_{snake_case}", off_signal_fn)
213
+
214
+
215
+ class BaseProxyObject:
216
+ """An abstract class representing a proxy to an object exported on the bus by another client.
217
+
218
+ Implementations of this class are not meant to be constructed directly. Use
219
+ :func:`BaseMessageBus.get_proxy_object()
220
+ <dbus_fast.message_bus.BaseMessageBus.get_proxy_object>` to get a proxy
221
+ object. Each message bus implementation provides its own proxy object
222
+ implementation that will be returned by that method.
223
+
224
+ The primary use of the proxy object is to select a proxy interface to act
225
+ on. Information on what interfaces are available is provided by
226
+ introspection data provided to this class. This introspection data can
227
+ either be included in your project as an XML file (recommended) or
228
+ retrieved from the ``org.freedesktop.DBus.Introspectable`` interface at
229
+ runtime.
230
+
231
+ :ivar bus_name: The name of the bus this object is exported on.
232
+ :vartype bus_name: str
233
+ :ivar path: The object path exported on the client that owns the bus name.
234
+ :vartype path: str
235
+ :ivar introspection: Parsed introspection data for the proxy object.
236
+ :vartype introspection: :class:`Node <dbus_fast.introspection.Node>`
237
+ :ivar bus: The message bus this proxy object is connected to.
238
+ :vartype bus: :class:`BaseMessageBus <dbus_fast.message_bus.BaseMessageBus>`
239
+ :ivar ProxyInterface: The proxy interface class this proxy object uses.
240
+ :vartype ProxyInterface: Type[:class:`BaseProxyInterface <dbus_fast.proxy_object.BaseProxyInterface>`]
241
+ :ivar child_paths: A list of absolute object paths of the children of this object.
242
+ :vartype child_paths: list(str)
243
+
244
+ :raises:
245
+ - :class:`InvalidBusNameError <dbus_fast.InvalidBusNameError>` - If the given bus name is not valid.
246
+ - :class:`InvalidObjectPathError <dbus_fast.InvalidObjectPathError>` - If the given object path is not valid.
247
+ - :class:`InvalidIntrospectionError <dbus_fast.InvalidIntrospectionError>` - If the introspection data for the node is not valid.
248
+ """
249
+
250
+ def __init__(
251
+ self,
252
+ bus_name: str,
253
+ path: str,
254
+ introspection: intr.Node | str | ET.Element,
255
+ bus: message_bus.BaseMessageBus,
256
+ ProxyInterface: type[BaseProxyInterface],
257
+ ) -> None:
258
+ assert_object_path_valid(path)
259
+ assert_bus_name_valid(bus_name)
260
+
261
+ if not isinstance(bus, message_bus.BaseMessageBus):
262
+ raise TypeError("bus must be an instance of BaseMessageBus")
263
+ if not issubclass(ProxyInterface, BaseProxyInterface):
264
+ raise TypeError("ProxyInterface must be an instance of BaseProxyInterface")
265
+
266
+ if type(introspection) is intr.Node:
267
+ self.introspection = introspection
268
+ elif type(introspection) is str:
269
+ self.introspection = intr.Node.parse(introspection)
270
+ elif type(introspection) is ET.Element:
271
+ self.introspection = intr.Node.from_xml(introspection)
272
+ else:
273
+ raise TypeError(
274
+ "introspection must be xml node introspection or introspection.Node class"
275
+ )
276
+
277
+ self.bus_name = bus_name
278
+ self.path = path
279
+ self.bus = bus
280
+ self.ProxyInterface = ProxyInterface
281
+ self.child_paths = [f"{path}/{n.name}" for n in self.introspection.nodes]
282
+
283
+ self._interfaces = {}
284
+
285
+ # lazy loaded by get_children()
286
+ self._children = None
287
+
288
+ def get_interface(self, name: str) -> BaseProxyInterface:
289
+ """Get an interface exported on this proxy object and connect it to the bus.
290
+
291
+ :param name: The name of the interface to retrieve.
292
+ :type name: str
293
+
294
+ :raises:
295
+ - :class:`InterfaceNotFoundError <dbus_fast.InterfaceNotFoundError>` - If there is no interface by this name exported on the bus.
296
+ """
297
+ if name in self._interfaces:
298
+ return self._interfaces[name]
299
+
300
+ try:
301
+ intr_interface = next(
302
+ i for i in self.introspection.interfaces if i.name == name
303
+ )
304
+ except StopIteration as ex:
305
+ raise InterfaceNotFoundError(
306
+ f"interface not found on this object: {name}"
307
+ ) from ex
308
+
309
+ interface = self.ProxyInterface(
310
+ self.bus_name, self.path, intr_interface, self.bus
311
+ )
312
+
313
+ for intr_method in intr_interface.methods:
314
+ interface._add_method(intr_method)
315
+ for intr_property in intr_interface.properties:
316
+ interface._add_property(intr_property)
317
+ for intr_signal in intr_interface.signals:
318
+ interface._add_signal(intr_signal, interface)
319
+
320
+ def get_owner_notify(msg: Message, err: Exception | None) -> None:
321
+ if err:
322
+ _LOGGER.error(f'getting name owner for "{name}" failed, {err}')
323
+ return
324
+ if msg.message_type == MessageType.ERROR:
325
+ if msg.error_name != ErrorType.NAME_HAS_NO_OWNER.value:
326
+ _LOGGER.error(
327
+ f'getting name owner for "{name}" failed, {msg.body[0]}'
328
+ )
329
+ return
330
+
331
+ self.bus._name_owners[self.bus_name] = msg.body[0]
332
+
333
+ if self.bus_name[0] != ":" and not self.bus._name_owners.get(self.bus_name, ""):
334
+ self.bus._call(
335
+ Message(
336
+ destination="org.freedesktop.DBus",
337
+ interface="org.freedesktop.DBus",
338
+ path="/org/freedesktop/DBus",
339
+ member="GetNameOwner",
340
+ signature="s",
341
+ body=[self.bus_name],
342
+ ),
343
+ get_owner_notify,
344
+ )
345
+
346
+ self._interfaces[name] = interface
347
+ return interface
348
+
349
+ def get_children(self) -> list[BaseProxyObject]:
350
+ """Get the child nodes of this proxy object according to the introspection data."""
351
+ if self._children is None:
352
+ self._children = [
353
+ self.__class__(self.bus_name, self.path, child, self.bus)
354
+ for child in self.introspection.nodes
355
+ ]
356
+
357
+ return self._children
dbus_fast/py.typed ADDED
File without changes
@@ -0,0 +1,61 @@
1
+ from __future__ import annotations
2
+
3
+ import traceback
4
+ from types import TracebackType
5
+ from typing import TYPE_CHECKING
6
+
7
+ from .constants import ErrorType
8
+ from .errors import DBusError
9
+ from .message import Message
10
+
11
+ if TYPE_CHECKING:
12
+ from .message_bus import BaseMessageBus
13
+
14
+
15
+ class SendReply:
16
+ """A context manager to send a reply to a message."""
17
+
18
+ __slots__ = ("_bus", "_msg")
19
+
20
+ def __init__(self, bus: BaseMessageBus, msg: Message) -> None:
21
+ """Create a new reply context manager."""
22
+ self._bus = bus
23
+ self._msg = msg
24
+
25
+ def __enter__(self) -> SendReply:
26
+ return self
27
+
28
+ def __call__(self, reply: Message) -> None:
29
+ self._bus.send(reply)
30
+
31
+ def _exit(
32
+ self,
33
+ exc_type: type[Exception] | None,
34
+ exc_value: Exception | None,
35
+ tb: TracebackType | None,
36
+ ) -> bool:
37
+ if exc_value:
38
+ if isinstance(exc_value, DBusError):
39
+ self(exc_value._as_message(self._msg))
40
+ else:
41
+ self(
42
+ Message.new_error(
43
+ self._msg,
44
+ ErrorType.SERVICE_ERROR,
45
+ f"The service interface raised an error: {exc_value}.\n{traceback.format_tb(tb)}",
46
+ )
47
+ )
48
+ return True
49
+
50
+ return False
51
+
52
+ def __exit__(
53
+ self,
54
+ exc_type: type[Exception] | None,
55
+ exc_value: Exception | None,
56
+ tb: TracebackType | None,
57
+ ) -> bool:
58
+ return self._exit(exc_type, exc_value, tb)
59
+
60
+ def send_error(self, exc: Exception) -> None:
61
+ self._exit(exc.__class__, exc, exc.__traceback__)
Binary file
dbus_fast/service.pxd ADDED
@@ -0,0 +1,50 @@
1
+ """cdefs for service.py"""
2
+
3
+ import cython
4
+
5
+ from .message cimport Message
6
+ from .signature cimport SignatureTree
7
+
8
+
9
+ cdef class _Method:
10
+
11
+ cdef public str name
12
+ cdef public object fn
13
+ cdef public bint disabled
14
+ cdef public object introspection
15
+ cdef public str in_signature
16
+ cdef public str out_signature
17
+ cdef public SignatureTree in_signature_tree
18
+ cdef public SignatureTree out_signature_tree
19
+
20
+
21
+
22
+ cdef tuple _real_fn_result_to_body(
23
+ object result,
24
+ SignatureTree signature_tree,
25
+ bint replace_fds
26
+ )
27
+
28
+ cdef class ServiceInterface:
29
+
30
+ cdef public str name
31
+ cdef list __methods
32
+ cdef list __properties
33
+ cdef list __signals
34
+ cdef set __buses
35
+ cdef dict __handlers
36
+ cdef dict __handlers_by_name_signature
37
+
38
+ @cython.locals(handlers=dict,in_signature=str,method=_Method)
39
+ @staticmethod
40
+ cdef object _get_enabled_handler_by_name_signature(ServiceInterface interface, object bus, object name, object signature)
41
+
42
+ @staticmethod
43
+ cdef list _c_msg_body_to_args(Message msg)
44
+
45
+ @staticmethod
46
+ cdef tuple _c_fn_result_to_body(
47
+ object result,
48
+ SignatureTree signature_tree,
49
+ bint replace_fds,
50
+ )