Debian Codegraph @

ravel.py

raw symbols SCIP
1 """
2 Simplified higher-level Python binding for D-Bus on top of dbussy.
3 Provides a framework for dispatching method and signal calls, and also
4 for on-the-fly invocation of method calls in the server from the
5 client using proxy objects, all with the option of running via an
6 asyncio event loop.
7 """
8 #+
9 # Copyright 2017-2020 Lawrence D'Oliveiro <[email protected]>.
10 # Licensed under the GNU Lesser General Public License v2.1 or later.
11 #-
12
13 import enum
14 from weakref import \
15 ref as weak_ref, \
16 WeakValueDictionary
17 import asyncio
18 import atexit
19 import dbussy as dbus
20 from dbussy import \
21 DBUS, \
22 DBUSX, \
23 Introspection
24
25 #+
26 # High-level bus connection
27 #-
28
29 class ErrorReturn(Exception) :
30 "Dispatch handlers can raise this to report an error that will be returned" \
31 " in a message back to the other end of the connection."
32
33 def __init__(self, name, message) :
34 self.args = (name, message)
35 #end __init__
36
37 def as_error(self) :
38 "fills in and returns an Error object that reports the specified error name and message."
39 result = dbus.Error.init()
40 result.set(self.args[0], self.args[1])
41 return \
42 result
43 #end as_error
44
45 #end ErrorReturn
46
47 def _signal_key(fallback, interface, name) :
48 # constructs a key for the signal-listener dictionary from the
49 # given args.
50 return \
51 (fallback, interface, name)
52 #end _signal_key
53
54 def _signal_rule(path, fallback, interface, name) :
55 # constructs a D-Bus match rule from the given args.
56 return \
57 dbus.format_rule \
58 (
59 {
60 "type" : "signal",
61 ("path", "path_namespace")[fallback] : dbus.unsplit_path(path),
62 "interface" : interface,
63 "member" : name,
64 }
65 )
66 #end _signal_rule
67
68 class _DispatchNode :
69
70 __slots__ = ("children", "signal_listeners")
71
72 class _Interface :
73
74 __slots__ = ("interface", "fallback", "listening")
75
76 def __init__(self, interface, fallback) :
77 self.interface = interface
78 self.fallback = fallback
79 self.listening = set() # of match rule strings
80 #end __init
81
82 #end _Interface
83
84 def __init__(self) :
85 self.children = {} # dict of path component => _DispatchNode
86 self.signal_listeners = {} # dict of _signal_key() => list of functions
87 #end __init__
88
89 @property
90 def is_empty(self) :
91 return \
92 (
93 len(self.children) == 0
94 and
95 len(self.signal_listeners) == 0
96 )
97 #end _is_empty
98
99 #end _DispatchNode
100
101 class _ClientDispatchNode(_DispatchNode) :
102
103 __slots__ = ()
104
105 def __init__(self, bus) :
106 # bus arg ignored, only accepted for compatibility with _ServerDispatchNode
107 super().__init__()
108 #end __init__
109
110 #end _ClientDispatchNode
111
112 class _ServerDispatchNode(_DispatchNode) :
113
114 __slots__ = ("interfaces", "user_data")
115
116 class _UserDataDict(dict) :
117 # for holding user data, does automatic cleaning up of object
118 # tree as items are removed.
119
120 __slots__ = ("_ravel_bus",)
121
122 def __init__(self, bus) :
123 super().__init__()
124 self._ravel_bus = weak_ref(bus)
125 #end __init
126
127 def __delitem__(self, key) :
128 super().__delitem__(key)
129 if len(self) == 0 :
130 bus = self._ravel_bus()
131 assert bus != None, "parent Connection has gone"
132 bus._trim_dispatch(True)
133 #end if
134 #end __delitem__
135
136 #end _UserDataDict
137
138 def __init__(self, bus) :
139 super().__init__()
140 self.interfaces = {} # dict of interface name => _Interface
141 self.user_data = self._UserDataDict(bus) # for caller use
142 #end __init__
143
144 @property
145 def is_empty(self) :
146 return \
147 (
148 super().is_empty
149 and
150 len(self.interfaces) == 0
151 and
152 len(self.user_data) == 0
153 )
154 #end is_empty
155
156 #end _ServerDispatchNode
157
158 class _UserData :
159
160 __slots__ = ("_w_conn",)
161
162 def __init__(self, conn) :
163 self._w_conn = weak_ref(conn)
164 #end __init__
165
166 @property
167 def conn(self) :
168 result = self._w_conn()
169 assert result != None
170 return \
171 result
172 #end conn
173
174 def __getitem__(self, path) :
175 node = self.conn._get_dispatch_node(path, True, True)
176 return \
177 node.user_data
178 #end __getitem__
179
180 #end _UserData
181
182 class Connection(dbus.TaskKeeper) :
183 "higher-level wrapper around dbussy.Connection. Do not instantiate directly: use" \
184 " the session_bus() and system_bus() calls in this module, or obtain from accepting" \
185 " connections on a Server().\n" \
186 "\n" \
187 "This class provides various functions, some more suited to client-side use and" \
188 " some more suitable to the server side. Allows for registering of @interface()" \
189 " classes for automatic dispatching of method calls at appropriate points in" \
190 " the object hierarchy."
191
192 __slots__ = \
193 (
194 "connection",
195 "notify_delay",
196 "user_data",
197 "_direct_connect",
198 "bus_names_acquired",
199 "bus_names_pending",
200 "_client_dispatch",
201 "_server_dispatch",
202 "_managed_objects",
203 "_registered_bus_names_listeners",
204 "_bus_name_acquired_action",
205 "_bus_name_acquired_action_arg",
206 "_bus_name_lost_action",
207 "_bus_name_lost_action_arg",
208 "_props_changed",
209 "_objects_added",
210 "_objects_removed",
211 ) # to forestall typos
212
213 _instances = WeakValueDictionary()
214
215 def __new__(celf, connection, direct_connect) :
216 # always return the same Connection for the same dbus.Connection.
217 if not isinstance(connection, dbus.Connection) :
218 raise TypeError("connection must be a Connection")
219 #end if
220 self = celf._instances.get(connection)
221 if self == None :
222 self = super().__new__(celf)
223 super()._init(self)
224 self.connection = connection
225 self.loop = connection.loop
226 self.notify_delay = 0
227 self._client_dispatch = None # for signal listeners
228 self._server_dispatch = None # for registered classes that field method calls
229 self._managed_objects = None
230 self._direct_connect = direct_connect
231 unique_name = connection.bus_unique_name
232 if direct_connect :
233 assert unique_name == None, "connection already registered"
234 self.bus_names_acquired = None
235 self.bus_names_pending = None
236 else :
237 assert unique_name != None, "connection not yet registered"
238 self.bus_names_acquired = {unique_name}
239 self.bus_names_pending = set()
240 #end if
241 self._registered_bus_names_listeners = False
242 self._props_changed = None
243 self._objects_added = None
244 self._objects_removed = None
245 self._bus_name_acquired_action = None
246 self._bus_name_acquired_action_arg = None
247 self._bus_name_lost_action = None
248 self._bus_name_lost_action_arg = None
249 self.user_data = _UserData(self)
250 celf._instances[connection] = self
251 for interface in \
252 (
253 PeerStub,
254 IntrospectionHandler,
255 PropertyHandler,
256 ) \
257 :
258 self.register \
259 (
260 path = "/",
261 interface = interface(),
262 fallback = True
263 )
264 #end for
265 else :
266 assert self._direct_connect == direct_connect
267 #end if
268 return \
269 self
270 #end __new__
271
272 def __del__(self) :
273
274 # Note: if remove_listeners refers directly to outer “self",
275 # then Connection object is not disposed immediately. Passing
276 # reference as explicit arg seems to fix this.
277 def remove_listeners(self, is_server, level, path) :
278 for node, child in level.children.items() :
279 remove_listeners(self, is_server, child, path + [node])
280 #end for
281 if not self._direct_connect :
282 if is_server :
283 for interface in level.interfaces.values() :
284 for rulestr in interface.listening :
285 ignore = dbus.Error.init()
286 self.connection.bus_remove_match(rulestr, ignore)
287 #end for
288 #end for
289 #end if
290 for rulekey in level.signal_listeners :
291 fallback, interface, name = rulekey
292 ignore = dbus.Error.init()
293 self.connection.bus_remove_match \
294 (
295 _signal_rule(path, fallback, interface, name),
296 ignore
297 )
298 #end for
299 #end if
300 #end remove_listeners
301
302 #begin __del__
303 if self.connection != None :
304 if self._server_dispatch != None :
305 remove_listeners(self, True, self._server_dispatch, [])
306 #end if
307 if self._client_dispatch != None :
308 remove_listeners(self, False, self._client_dispatch, [])
309 #end if
310 self.connection = None
311 #end if
312 #end __del__
313
314 def attach_asyncio(self, loop = None) :
315 "attaches this Connection object to an asyncio event loop. If none is" \
316 " specified, the default event loop (as returned from asyncio.get_event_loop()" \
317 " is used."
318 self.connection.attach_asyncio(loop)
319 self.loop = self.connection.loop
320 return \
321 self
322 #end attach_asyncio
323
324 @staticmethod
325 def _bus_name_acquired(conn, msg, w_self) :
326 # internal callback which keeps track of bus names and dispatches
327 # to user-specified action.
328 self = w_self()
329 assert self != None
330 assert not self._direct_connect, "shouldn’t be acquiring bus names on direct server connection"
331 bus_name = msg.expect_objects("s")[0]
332 self.bus_names_pending.discard(bus_name)
333 if bus_name not in self.bus_names_acquired :
334 self.bus_names_acquired.add(bus_name)
335 if self._bus_name_acquired_action != None :
336 result = self._bus_name_acquired_action(self, bus_name, self._bus_name_acquired_action_arg)
337 if asyncio.iscoroutine(result) :
338 self.create_task(result)
339 #end if
340 #end if
341 #end if
342 #end _bus_name_acquired
343
344 @staticmethod
345 def _bus_name_lost(conn, msg, w_self) :
346 # internal callback which keeps track of bus names and dispatches
347 # to user-specified action.
348 self = w_self()
349 assert self != None
350 assert not self._direct_connect, "shouldn’t be losing bus names on direct server connection"
351 bus_name = msg.expect_objects("s")[0]
352 self.bus_names_pending.discard(bus_name)
353 if bus_name in self.bus_names_acquired :
354 self.bus_names_acquired.remove(bus_name)
355 if self._bus_name_lost_action != None :
356 result = self._bus_name_lost_action(self, bus_name, self._bus_name_lost_action_arg)
357 if asyncio.iscoroutine(result) :
358 self.create_task(result)
359 #end if
360 #end if
361 #end if
362 #end _bus_name_lost
363
364 def set_bus_name_acquired_action(self, action, action_arg) :
365 "sets the action (if not None) to be called on receiving a bus-name-acquired" \
366 " signal. action is invoked as\n" \
367 "\n" \
368 " action(conn, bus_name, action_arg)\n" \
369 "\n" \
370 "where conn is the Connection object and bus_name is the name."
371 assert not self._direct_connect, "cannot acquire bus names on direct server connection"
372 self._bus_name_acquired_action = action
373 self._bus_name_acquired_action_arg = action_arg
374 #end set_bus_name_acquired_action
375
376 def set_bus_name_lost_action(self, action, action_arg) :
377 "sets the action (if not None) to be called on receiving a bus-name-lost" \
378 " signal. action is invoked as\n" \
379 "\n" \
380 " action(conn, bus_name, action_arg)\n" \
381 "\n" \
382 "where conn is the Connection object and bus_name is the name."
383 assert not self._direct_connect, "cannot acquire bus names on direct server connection"
384 self._bus_name_lost_action = action
385 self._bus_name_lost_action_arg = action_arg
386 #end set_bus_name_lost_action
387
388 def request_name(self, bus_name, flags) :
389 "registers a bus name."
390 assert not self._direct_connect, "cannot register bus names on direct server connection"
391 if not self._registered_bus_names_listeners :
392 self.connection.bus_add_match_action \
393 (
394 rule = "type=signal,interface=org.freedesktop.DBus,member=NameAcquired",
395 func = self._bus_name_acquired,
396 user_data = weak_ref(self)
397 )
398 self.connection.bus_add_match_action \
399 (
400 rule = "type=signal,interface=org.freedesktop.DBus,member=NameLost",
401 func = self._bus_name_lost,
402 user_data = weak_ref(self)
403 )
404 self._registered_bus_names_listeners = True
405 #end if
406 return \
407 self.connection.bus_request_name(bus_name, flags)
408 #end request_name
409
410 async def request_name_async(self, bus_name, flags, error = None, timeout = DBUS.TIMEOUT_USE_DEFAULT) :
411 "registers a bus name."
412 assert not self._direct_connect, "cannot register bus names on direct server connection"
413 assert self.loop != None, "no event loop to attach coroutine to"
414 if not self._registered_bus_names_listeners :
415 self._registered_bus_names_listeners = True # do first in case of reentrant call
416 await self.connection.bus_add_match_action_async \
417 (
418 rule = "type=signal,interface=org.freedesktop.DBus,member=NameAcquired",
419 func = self._bus_name_acquired,
420 user_data = weak_ref(self)
421 )
422 await self.connection.bus_add_match_action_async \
423 (
424 rule = "type=signal,interface=org.freedesktop.DBus,member=NameLost",
425 func = self._bus_name_lost,
426 user_data = weak_ref(self)
427 )
428 #end if
429 is_acquired = bus_name in self.bus_names_acquired
430 is_pending = bus_name in self.bus_names_pending
431 if not (is_acquired or is_pending) :
432 self.bus_names_pending.add(bus_name)
433 result = await self.connection.bus_request_name_async(bus_name, flags, error = error, timeout = timeout)
434 if error != None and error.is_set or result != DBUS.REQUEST_NAME_REPLY_IN_QUEUE :
435 self.bus_names_pending.discard(bus_name)
436 #end if
437 elif is_pending :
438 result = DBUS.REQUEST_NAME_REPLY_IN_QUEUE
439 else :
440 result = DBUS.REQUEST_NAME_REPLY_ALREADY_OWNER
441 #end if
442 return \
443 result
444 #end request_name_async
445
446 def release_name(self, bus_name) :
447 "releases a registered bus name."
448 assert not self._direct_connect, "cannot register bus names on direct server connection"
449 return \
450 self.connection.bus_release_name(bus_name)
451 #end release_name
452
453 async def release_name_async(self, bus_name, error = None, timeout = DBUS.TIMEOUT_USE_DEFAULT) :
454 "releases a registered bus name."
455 assert not self._direct_connect, "cannot register bus names on direct server connection"
456 assert self.loop != None, "no event loop to attach coroutine to"
457 return \
458 await self.connection.bus_release_name_async(bus_name, error = error, timeout = timeout)
459 #end release_name_async
460
461 def _trim_dispatch(self, is_server) :
462 # removes empty subtrees from the object tree.
463
464 def trim_dispatch_node(level) :
465 to_delete = set()
466 for node, child in level.children.items() :
467 trim_dispatch_node(child)
468 if child.is_empty :
469 to_delete.add(node)
470 #end if
471 #end for
472 for node in to_delete :
473 del level.children[node]
474 #end for
475 #end trim_dispatch_node
476
477 #begin _trim_dispatch
478 dispatch = (self._client_dispatch, self._server_dispatch)[is_server]
479 if dispatch != None :
480 trim_dispatch_node(dispatch)
481 if dispatch.is_empty :
482 if is_server :
483 self._server_dispatch = None
484 else :
485 self._client_dispatch = None
486 #end if
487 #end if
488 #end if
489 #end _trim_dispatch
490
491 def _get_dispatch_node(self, path, is_server, create_if) :
492 # returns the appropriate _DispatchNode entry in the
493 # client or server dispatch tree (depending on is_server) for
494 # the specified path, or None if no such and not create_if.
495 if create_if :
496 if is_server and self._server_dispatch == None :
497 self._server_dispatch = _ServerDispatchNode(self)
498 elif not is_server and self._client_dispatch == None :
499 self._client_dispatch = _ClientDispatchNode(self)
500 #end if
501 #end if
502 level = (self._client_dispatch, self._server_dispatch)[is_server]
503 DispatchNode = (_ClientDispatchNode, _ServerDispatchNode)[is_server]
504 if level != None :
505 levels = iter(dbus.split_path(path))
506 while True :
507 component = next(levels, None)
508 if component == None :
509 break # found if level != None
510 if component not in level.children :
511 if not create_if :
512 level = None
513 break
514 #end if
515 level.children[component] = DispatchNode(self)
516 #end if
517 level = level.children[component]
518 # search another step down the path
519 #end while
520 #end if
521 return \
522 level
523 #end _get_dispatch_node
524
525 def _remove_matches(self, dispatch) :
526 if not self._direct_connect :
527 for rulestr in dispatch.listening :
528 ignore = dbus.Error.init()
529 self.connection.bus_remove_match(rulestr, ignore)
530 #end for
531 #end if
532 #end _remove_matches
533
534 def register_additional_standard(self, **kwargs) :
535 "registers additional standard interfaces that are not automatically" \
536 " installed at Connection creation time. Currently the only one is" \
537 " the object-manager interface, registered with\n" \
538 "\n" \
539 " «conn».register_additional_standard(managed_objects = True)\n"
540 for key in kwargs :
541 if kwargs[key] :
542 if key == "managed_objects" :
543 if self._managed_objects != None :
544 raise asyncio.InvalidStateError \
545 (
546 "object manager interface already registered"
547 )
548 #end if
549 self.register \
550 (
551 path = "/",
552 interface = ManagedObjectsHandler(),
553 fallback = True
554 )
555 self._managed_objects = {}
556 else :
557 raise TypeError("unrecognized argument keyword “%s”" % key)
558 #end if
559 #end if
560 #end for
561 return \
562 self
563 #end register_additional_standard
564
565 def register(self, path, fallback, interface, replace = True) :
566 "for server-side use; registers the specified instance of an @interface()" \
567 " class for handling method calls on the specified path, and also on subpaths" \
568 " if fallback."
569 if is_interface_instance(interface) :
570 iface_type = type(interface)
571 elif is_interface(interface) :
572 # assume can instantiate without arguments
573 iface_type = interface
574 interface = iface_type()
575 else :
576 raise TypeError("interface must be an @interface() class or instance thereof")
577 #end if
578 if self._server_dispatch == None :
579 self._server_dispatch = _ServerDispatchNode(self)
580 self.connection.add_filter(_message_interface_dispatch, weak_ref(self))
581 #end if
582 level = self._server_dispatch
583 for component in dbus.split_path(path) :
584 if component not in level.children :
585 level.children[component] = _ServerDispatchNode(self)
586 #end if
587 level = level.children[component]
588 #end for
589 interface_name = iface_type._interface_name
590 if interface_name in level.interfaces :
591 entry = level.interfaces[interface_name]
592 existing_kind = type(entry.interface)._interface_kind
593 if not replace or existing_kind != iface_type._interface_kind :
594 raise KeyError \
595 (
596 "already registered an interface named “%s” of kind %s"
597 %
598 (interface_name, existing_kind)
599 )
600 #end if
601 self._remove_matches(entry)
602 #end if
603 entry = _ServerDispatchNode._Interface(interface, fallback)
604 if iface_type._interface_kind != INTERFACE.SERVER and not self._direct_connect :
605 signals = iface_type._interface_signals
606 for name in signals :
607 if not iface_type._interface_signals[name]._signal_info["stub"] :
608 rulestr = _signal_rule(path, fallback, interface_name, name)
609 self.connection.bus_add_match(rulestr)
610 entry.listening.add(rulestr)
611 #end if
612 #end for
613 #end for
614 level.interfaces[interface_name] = entry
615 #end register
616
617 def unregister(self, path, interface = None) :
618 "for server-side use; unregisters the specified interface class (or all" \
619 " registered interface classes, if None) from handling method calls on path."
620 if interface != None :
621 if is_interface_instance(interface) :
622 interface = type(interface)
623 elif not is_interface(interface) :
624 raise TypeError("interface must be None or an @interface() class or instance thereof")
625 #end if
626 #end if
627 if self._server_dispatch != None :
628 level = self._server_dispatch
629 levels = iter(dbus.split_path(path))
630 while True :
631 component = next(levels, None)
632 if component == None :
633 if interface != None :
634 interfaces = {interface._interface_name}
635 else :
636 interfaces = set(level.interfaces.keys())
637 #end if
638 for iface_name in interfaces :
639 self._remove_matches(level.interfaces[iface_name])
640 del level.interfaces[iface_name]
641 #end for
642 break
643 #end if
644 if component not in level.children :
645 break
646 level = level.children[component]
647 #end while
648 self._trim_dispatch(True)
649 #end if
650 #end unregister
651
652 def listen_signal(self, path, fallback, interface, name, func) :
653 "for client-side use; registers a callback which will be invoked when a" \
654 " signal is received for the specified path, interface and name."
655 if not hasattr(func, "_signal_info") :
656 raise TypeError("callback must have @signal() decorator applied")
657 #end if
658 signal_info = func._signal_info
659 entry = self._get_dispatch_node(path, False, True)
660 # Should I bother to check it matches a registered interface and
661 # defined signal therein?
662 # Also, should I pay any attention to signal_info["name"]? Perhaps
663 # default if name arg is None?
664 listeners = entry.signal_listeners
665 rulekey = _signal_key(fallback, interface, name)
666 if rulekey not in listeners :
667 if not self._direct_connect :
668 self.connection.bus_add_match(_signal_rule(path, fallback, interface, name))
669 #end if
670 listeners[rulekey] = []
671 #end if
672 listeners[rulekey].append(func)
673 #end listen_signal
674
675 def unlisten_signal(self, path, fallback, interface, name, func) :
676 "for client-side use; unregisters a previously-registered callback" \
677 " which would have been invoked when a signal is received for the" \
678 " specified path, interface and name."
679 entry = self._get_dispatch_node(path, False, False)
680 if entry != None :
681 signal_listeners = entry.signal_listeners
682 rulekey = _signal_key(fallback, interface, name)
683 if rulekey in signal_listeners :
684 listeners = signal_listeners[rulekey]
685 try :
686 listeners.pop(listeners.index(func))
687 except ValueError :
688 pass
689 #end try
690 if len(listeners) == 0 :
691 if not self._direct_connect :
692 ignore = dbus.Error.init()
693 self.connection.bus_remove_match \
694 (
695 _signal_rule(path, fallback, interface, name),
696 ignore
697 )
698 #end if
699 del signal_listeners[rulekey]
700 # as a note to myself that I will need to call bus_add_match
701 # if a new listener is added
702 #end if
703 #end if
704 self._trim_dispatch(False)
705 #end if
706 #end unlisten_signal
707
708 def listen_propchanged(self, path, fallback, interface, func) :
709 "special case of Connection.listen_signal specifically for listening" \
710 " for properties-changed signals. The interface is ignored for now;" \
711 " your listener will have to check for matches on this itself."
712 self.listen_signal \
713 (
714 path = path,
715 fallback = fallback,
716 interface = DBUS.INTERFACE_PROPERTIES,
717 name = "PropertiesChanged",
718 func = func,
719 )
720 #end listen_propchanged
721
722 def unlisten_propchanged(self, path, fallback, interface, func) :
723 "special case of Connection.unlisten_signal specifically for listening" \
724 " for properties-changed signals. The interface is ignored for now;" \
725 " your listener has to check for matches on this itself."
726 self.unlisten_signal \
727 (
728 path = path,
729 fallback = fallback,
730 interface = DBUS.INTERFACE_PROPERTIES,
731 name = "PropertiesChanged",
732 func = func,
733 )
734 #end unlisten_propchanged
735
736 def listen_objects_added(self, func) :
737 self.listen_signal \
738 (
739 path = "/",
740 fallback = True,
741 interface = DBUSX.INTERFACE_OBJECT_MANAGER,
742 name = "InterfacesAdded",
743 func = func,
744 )
745 #end listen_objects_added
746
747 def unlisten_objects_added(self, func) :
748 self.unlisten_signal \
749 (
750 path = "/",
751 fallback = True,
752 interface = DBUSX.INTERFACE_OBJECT_MANAGER,
753 name = "InterfacesAdded",
754 func = func,
755 )
756 #end unlisten_objects_added
757
758 def listen_objects_removed(self, func) :
759 self.listen_signal \
760 (
761 path = "/",
762 fallback = True,
763 interface = DBUSX.INTERFACE_OBJECT_MANAGER,
764 name = "InterfacesRemoved",
765 func = func,
766 )
767 #end listen_objects_removed
768
769 def unlisten_objects_removed(self, func) :
770 self.unlisten_signal \
771 (
772 path = "/",
773 fallback = True,
774 interface = DBUSX.INTERFACE_OBJECT_MANAGER,
775 name = "InterfacesRemoved",
776 func = func,
777 )
778 #end unlisten_objects_removed
779
780 def get_dispatch_interface(self, path, interface_name) :
781 "returns the appropriate instance of a previously-registered interface" \
782 " class for handling calls to the specified interface name for the" \
783 " specified object path, or None if no such."
784 fallback = None # to begin with
785 level = self._server_dispatch
786 if level != None :
787 levels = iter(dbus.split_path(path))
788 while True :
789 component = next(levels, None)
790 if (
791 interface_name in level.interfaces
792 and
793 (level.interfaces[interface_name].fallback or component == None)
794 ) :
795 iface = level.interfaces[interface_name].interface
796 else :
797 iface = fallback
798 #end if
799 if (
800 component == None
801 # reached bottom of path
802 or
803 component not in level.children
804 # no handlers to be found further down path
805 ) :
806 break
807 #end if
808 fallback = iface
809 level = level.children[component]
810 # search another step down the path
811 #end while
812 else :
813 iface = None
814 #end if
815 return \
816 iface
817 #end get_dispatch_interface
818
819 def _get_iface_entry(self, path, interface, name, namekind) :
820 iface = self.get_dispatch_interface(path, interface)
821 if iface == None :
822 raise TypeError \
823 (
824 "no suitable interface %s for object %s" % (interface, dbus.unsplit_path(path))
825 )
826 #end if
827 iface_type = type(iface)
828 if iface_type._interface_kind == (INTERFACE.SERVER, INTERFACE.CLIENT)[namekind == "signal"] :
829 raise TypeError \
830 (
831 "cannot send %s call from %s side"
832 %
833 (("method", "server"), ("signal", "client"))[namekind == "signal"]
834 )
835 #end if
836 lookup = getattr \
837 (
838 iface_type,
839 {
840 "method" : "_interface_methods",
841 "signal" : "_interface_signals",
842 "property" : "_interface_props",
843 }[namekind]
844 )
845 if name not in lookup :
846 raise KeyError \
847 (
848 "name “%s” is not a %s of interface “%s”" % (name, namekind, interface)
849 )
850 #end if
851 return \
852 lookup[name]
853 #end _get_iface_entry
854
855 def _notify_props_changed(self) :
856 # callback that is queued on the event loop to actually send the
857 # properties-changed notification signals.
858 if self._props_changed != None :
859 done = set()
860 now = self.loop.time()
861 for key in self._props_changed :
862 entry = self._props_changed[key]
863 path, interface = key
864 if entry["at"] <= now :
865 self.send_signal \
866 (
867 path = path,
868 interface = DBUS.INTERFACE_PROPERTIES,
869 name = "PropertiesChanged",
870 args = (interface, entry["changed"], sorted(entry["invalidated"]))
871 )
872 done.add(key)
873 #end if
874 #end for
875 for key in done :
876 del self._props_changed[key]
877 #end for
878 if len(self._props_changed) == 0 :
879 # all done for now
880 self._props_changed = None # indicates I am not pending to be called any more
881 else :
882 # another notification waiting to be sent later
883 next_time = min(entry["at"] for entry in self._props_changed.values())
884 self.loop.call_at(next_time, self._notify_props_changed)
885 #end if
886 #end if
887 #end _notify_props_changed
888
889 def _get_all_my_props(self, message, path, interface_name) :
890 # utility wrapper that retrieves all property values for the specified
891 # object path defined by the specified interface. Returns two results:
892 # property values, and list of (propname, coroutine) tuples for async
893 # propgetters. Could raise ErrorReturn if a propgetter does so.
894 dispatch = self.get_dispatch_interface(path, interface_name)
895 props = type(dispatch)._interface_props
896 propnames = iter(props.keys())
897 properror = None
898 propvalues = {}
899 to_await = []
900 while True :
901 propname = next(propnames, None)
902 if propname == None :
903 break
904 propentry = props[propname]
905 if "getter" in propentry :
906 getter = getattr(dispatch, propentry["getter"].__name__)
907 kwargs = {}
908 for keyword_keyword, value in \
909 (
910 ("name_keyword", lambda : propname),
911 ("connection_keyword", lambda : self.connection),
912 ("message_keyword", lambda : message),
913 ("path_keyword", lambda : path),
914 ("bus_keyword", lambda : bus),
915 ) \
916 :
917 if getter._propgetter_info[keyword_keyword] != None :
918 value = value()
919 if value == None :
920 raise ValueError \
921 (
922 "getter for prop “%s” expects a %s arg but"
923 " no value supplied for that"
924 %
925 (propname, keyword_keyword)
926 )
927 #end if
928 kwargs[getter._propgetter_info[keyword_keyword]] = value
929 #end if
930 #end for
931 propvalue = getter(**kwargs)
932 # could raise ErrorReturn
933 if asyncio.iscoroutine(propvalue) :
934 if self.loop == None :
935 raise TypeError \
936 (
937 "not expecting getter for prop “%s” to be coroutine" % propname
938 )
939 #end if
940 to_await.append((propname, propvalue))
941 #end if
942 propvalues[propname] = (propentry["type"], propvalue)
943 #end if
944 #end for
945 return \
946 propvalues, to_await
947 #end _get_all_my_props
948
949 def prop_changed(self, path, interface, propname, proptype, propvalue) :
950 "indicates that a signal should be sent notifying of a change to the specified" \
951 " property of the specified object path in the specified interface. propvalue" \
952 " is either the new value to be included in the signal, or None to indicate" \
953 " that the property has merely become invalidated, and its new value needs" \
954 " to be obtained explicitly.\n" \
955 "\n" \
956 "If there is an event loop attached, then multiple calls to this with different" \
957 " properties on the same path and interface can be batched up into a single" \
958 " signal notification."
959 assert (proptype != None) == (propvalue != None), \
960 "either specify both of proptype and propvalue, or neither"
961 if self.loop != None :
962 queue_task = False
963 if self._props_changed == None :
964 self._props_changed = {}
965 queue_task = True
966 #end if
967 key = (dbus.unsplit_path(path), interface)
968 if key not in self._props_changed :
969 self._props_changed[key] = \
970 {
971 "at" : self.loop.time() + self.notify_delay,
972 "changed" : {},
973 "invalidated" : set(),
974 }
975 #end if
976 if propvalue != None :
977 self._props_changed[key]["changed"][propname] = (proptype, propvalue)
978 else :
979 self._props_changed[key]["invalidated"].add(propname)
980 #end if
981 if queue_task :
982 if self.notify_delay != 0 :
983 self.loop.call_later(self.notify_delay, self._notify_props_changed)
984 else :
985 self.loop.call_soon(self._notify_props_changed)
986 #end if
987 #end if
988 else :
989 # cannot batch them up--send message immediately
990 changed = {}
991 invalidated = []
992 if propvalue != None :
993 changed[propname] = (proptype, propvalue)
994 else :
995 invalidated.append(propname)
996 #end if
997 self.send_signal \
998 (
999 path = path,
1000 interface = DBUS.INTERFACE_PROPERTIES,
1001 name = "PropertiesChanged",
1002 args = (interface, changed, invalidated)
1003 )
1004 #end if
1005 #end prop_changed
1006
1007 def _notify_objects_added(self) :
1008 # callback that is queued on the event loop to actually send the
1009 # objects-added notification signals.
1010 if self._objects_added != None :
1011 notify_again = None
1012 if self.loop != None :
1013 now = self.loop.time()
1014 else :
1015 now = None
1016 #end if
1017 paths_to_delete = set()
1018 for path in sorted(self._objects_added.keys()) :
1019 entry = self._objects_added[path]
1020 added = {}
1021 for interface, iface_entry in entry.items() :
1022 when = iface_entry["at"]
1023 if when == None or when <= now :
1024 added[interface] = iface_entry["props"]
1025 else :
1026 if notify_again == None :
1027 notify_again = when
1028 else :
1029 notify_again = min(notify_again, when)
1030 #end if
1031 #end if
1032 #end for
1033 if len(added) != 0 :
1034 self.send_signal \
1035 (
1036 path = path,
1037 interface = DBUSX.INTERFACE_OBJECT_MANAGER,
1038 name = "InterfacesAdded",
1039 args = (path, added)
1040 )
1041 for interface in added :
1042 del entry[interface]
1043 #end for
1044 #end if
1045 if len(entry) == 0 :
1046 paths_to_delete.add(path)
1047 #end if
1048 #end for
1049 for path in paths_to_delete :
1050 del self._objects_added[path]
1051 #end for
1052 if len(self._objects_added) == 0 :
1053 self._objects_added = None
1054 #end if
1055 if notify_again != None :
1056 self.loop.call_later(notify_again - now, self._notify_objects_added)
1057 #end if
1058 #end if
1059 #end _notify_objects_added
1060
1061 def _notify_objects_removed(self) :
1062 # callback that is queued on the event loop to actually send the
1063 # objects-removed notification signals.
1064 if self._objects_removed != None :
1065 notify_again = None
1066 if self.loop != None :
1067 now = self.loop.time()
1068 else :
1069 now = None
1070 #end if
1071 paths_to_delete = set()
1072 for path in sorted(self._objects_removed.keys()) :
1073 entry = self._objects_removed[path]
1074 removed = set()
1075 for interface in entry :
1076 when = entry[interface]["at"]
1077 if when == None or when <= now :
1078 removed.add(interface)
1079 else :
1080 if notify_again == None :
1081 notify_again = when
1082 else :
1083 notify_again = min(notify_again, when)
1084 #end if
1085 #end if
1086 #end for
1087 if len(removed) != 0 :
1088 self.send_signal \
1089 (
1090 path = path,
1091 interface = DBUSX.INTERFACE_OBJECT_MANAGER,
1092 name = "InterfacesRemoved",
1093 args = (path, sorted(removed))
1094 )
1095 for interface in removed :
1096 del entry[interface]
1097 #end for
1098 #end if
1099 if len(entry) == 0 :
1100 paths_to_delete.add(path)
1101 #end if
1102 #end for
1103 for path in paths_to_delete :
1104 del self._objects_removed[path]
1105 #end for
1106 if len(self._objects_removed) == 0 :
1107 self._objects_removed = None
1108 #end if
1109 if notify_again != None :
1110 self.loop.call_later(notify_again - now, self._notify_objects_removed)
1111 #end if
1112 #end if
1113 #end _notify_objects_removed
1114
1115 def find_interfaces_for_object(self, path) :
1116 "returns a dict of interfaces, keyed by name, applicable to the" \
1117 " given object path."
1118 level = self._server_dispatch
1119 result = {}
1120 if level != None :
1121 levels = iter(dbus.split_path(path))
1122 while True :
1123 component = next(levels, None)
1124 for interface_name, interface in level.interfaces.items() :
1125 if component == None or interface.fallback :
1126 result[interface_name] = interface.interface
1127 # Note that a fallback entry might be replaced
1128 # by a more specific one further down the path.
1129 #end if
1130 #end for
1131 if (
1132 component == None
1133 # reached bottom of path
1134 or
1135 component not in level.children
1136 # no handlers to be found further down path
1137 ) :
1138 break
1139 #end if
1140 level = level.children[component]
1141 # search another step down the path
1142 #end while
1143 #end if
1144 return \
1145 result
1146 #end find_interfaces_for_object
1147
1148 def object_added(self, path, interfaces_and_props = None) :
1149 "Call this to send an ObjectManager notification about the addition of" \
1150 " the specified interfaces and property values to the specified object" \
1151 " path. The ObjectManager interface must already have been registered on" \
1152 " this Connection, by calling" \
1153 " «conn».register_additional_standard(managed_objects = True)."
1154
1155 added_entry = None
1156 to_await = []
1157 queue_task = False
1158 notify_when = None
1159
1160 def queue_notify(deferred) :
1161 if queue_task :
1162 if deferred :
1163 delay = notify_when - self.loop.time()
1164 else :
1165 delay = self.notify_delay
1166 #end if
1167 if delay > 0 :
1168 self.loop.call_later(delay, self._notify_objects_added)
1169 else :
1170 self.loop.call_soon(self._notify_objects_added)
1171 #end if
1172 #end if
1173 #end queue_notify
1174
1175 async def await_propvalues() :
1176 nonlocal queue_task
1177 for path, interface_name, propname, fute in to_await :
1178 propvalue = await fute # don’t trap ErrorReturn
1179 propvalues = added_entry[interface_name]["props"]
1180 propvalues[propname] = (propvalues[propname][0], propvalue)
1181 #end for
1182 if self._objects_added == None : # might have happened in meantime
1183 self._objects_added = {}
1184 queue_task = True
1185 #end if
1186 self._objects_added[path] = added_entry # all prop values now complete
1187 queue_notify(True)
1188 #end await_propvalues
1189
1190 #begin object_added
1191 path = dbus.unsplit_path(path)
1192 if self._managed_objects == None :
1193 raise RuntimeError("ObjectManager interface needs to be registered on this Connection")
1194 #end if
1195 if interfaces_and_props == None :
1196 # get all applicable interface names, props will be retrieved below
1197 intfs = self.find_interfaces_for_object(path)
1198 interfaces_and_props = dict \
1199 (
1200 (iface_name, None)
1201 for iface_name in intfs
1202 if len(intfs[iface_name]._interface_props) != 0
1203 )
1204 #end if
1205 if path in self._managed_objects :
1206 obj_entry = self._managed_objects[path]
1207 else :
1208 obj_entry = set()
1209 self._managed_objects[path] = obj_entry
1210 #end if
1211 if self._objects_added == None :
1212 self._objects_added = {}
1213 queue_task = True
1214 #end if
1215 if path in self._objects_added :
1216 added_entry = self._objects_added[path]
1217 else :
1218 added_entry = {}
1219 #end if
1220 if self.loop != None :
1221 notify_when = self.loop.time() + self.notify_delay
1222 else :
1223 notify_when = None
1224 #end if
1225 for interface, props in interfaces_and_props.items() :
1226 if props != None :
1227 added_props = {}
1228 for propname, propvalue in props.items() :
1229 if not isinstance(propvalue, (list, tuple)) or len(propvalue) != 2 :
1230 raise TypeError \
1231 (
1232 "value for property “%s” must be (type, value) pair" % propname
1233 )
1234 #end if
1235 proptype = dbus.parse_single_signature(propvalue[0])
1236 propvalue = proptype.validate(propvalue[1])
1237 proptype = dbus.unparse_signature(proptype)
1238 added_props[propname] = (proptype, propvalue)
1239 #end for
1240 else :
1241 added_props, await_props = self._get_all_my_props(None, path, interface)
1242 # propgetters should not expect a message arg
1243 for propname, propvalue in await_props :
1244 to_await.append((path, interface, propname, propvalue))
1245 #end for
1246 #end if
1247 added_entry[interface] = \
1248 {
1249 "at" : notify_when,
1250 "props" : added_props,
1251 }
1252 obj_entry.add(interface)
1253 #end for
1254 if len(to_await) == 0 :
1255 self._objects_added[path] = added_entry # all prop values complete
1256 #end if
1257 if self.loop != None :
1258 if len(to_await) != 0 :
1259 self.create_task(await_propvalues())
1260 else :
1261 queue_notify(False)
1262 #end if
1263 else :
1264 # cannot queue, notify immediately
1265 self._notify_objects_added()
1266 #end if
1267 #end object_added
1268
1269 def object_removed(self, path, interfaces = None) :
1270 "Call this to send an ObjectManager notification about the removal of the" \
1271 " specified set/sequence of interfaces from the specified object path. The" \
1272 " ObjectManager interface must already have been registered on this Connection," \
1273 " by calling «conn».register_additional_standard(managed_objects = True)."
1274 path = dbus.unsplit_path(path)
1275 if self._managed_objects == None :
1276 raise RuntimeError("ObjectManager interface not registered on this Connection")
1277 #end if
1278 queue_task = False
1279 if self._objects_removed == None :
1280 self._objects_removed = {}
1281 queue_task = True
1282 #end if
1283 if self._objects_added != None :
1284 added_entry = self._objects_added.get(path)
1285 else :
1286 added_entry = None
1287 #end if
1288 obj_entry = self._managed_objects[path]
1289 if path in self._objects_removed :
1290 removed_entry = self._objects_removed[path]
1291 else :
1292 removed_entry = {}
1293 self._objects_removed[path] = removed_entry
1294 #end if
1295 if self.loop != None :
1296 when = self.loop.time() + self.notify_delay
1297 else :
1298 when = None
1299 #end if
1300 if interfaces == None :
1301 intfs = self.find_interfaces_for_object(path)
1302 interfaces = set \
1303 (
1304 iface_name
1305 for iface_name in intfs
1306 if len(intfs[iface_name]._interface_props) != 0
1307 )
1308 #end if
1309 for interface in interfaces :
1310 if added_entry != None and interface in added_entry :
1311 # object-added notification was never sent, just cancel
1312 # it and don’t send object-removed notification
1313 del added_entry[interface]
1314 else :
1315 removed_entry[interface] = {"at" : when}
1316 #end if
1317 if self._props_changed != None :
1318 props_key = (path, interface)
1319 if self._props_changed != None and props_key in self._props_changed :
1320 # cancel pending properties-changed notification
1321 del self._props_changed[key]
1322 if len(self._props_changed) == 0 :
1323 self._props_changed = None
1324 #end if
1325 #end if
1326 #end if
1327 obj_entry.remove(interface)
1328 #end for
1329 if len(obj_entry) == 0 :
1330 del self._managed_objects[path]
1331 #end if
1332 if added_entry != None and len(added_entry) == 0 :
1333 del self._objects_added[path]
1334 if len(self._objects_added) == 0 :
1335 self._objects_added = None
1336 #end if
1337 #end if
1338 if len(removed_entry) != 0 :
1339 if self.loop != None :
1340 if queue_task :
1341 if self.notify_delay != 0 :
1342 self.loop.call_later(self.notify_delay, self._notify_objects_removed)
1343 else :
1344 self.loop.call_soon(self._notify_objects_removed)
1345 #end if
1346 #end if
1347 else :
1348 # cannot queue, notify immediately
1349 self._notify_objects_removed()
1350 #end if
1351 #end if
1352 #end object_removed
1353
1354 def send_signal(self, *, path, interface, name, args) :
1355 "intended for server-side use: sends a signal with the specified" \
1356 " interface and name from the specified object path. There must" \
1357 " already be a registered interface instance with that name which" \
1358 " defines that signal for that path."
1359 call_info = self._get_iface_entry(path, interface, name, "signal")._signal_info
1360 message = dbus.Message.new_signal \
1361 (
1362 path = dbus.unsplit_path(path),
1363 iface = interface,
1364 name = name
1365 )
1366 message.append_objects(call_info["in_signature"], *args)
1367 self.connection.send(message)
1368 #end send_signal
1369
1370 def introspect(self, destination, path, timeout = DBUS.TIMEOUT_USE_DEFAULT) :
1371 "sends an Introspect request to the specified bus name and object path," \
1372 " and returns the resulting parsed Introspection structure."
1373 message = dbus.Message.new_method_call \
1374 (
1375 destination = destination,
1376 path = dbus.unsplit_path(path),
1377 iface = DBUS.INTERFACE_INTROSPECTABLE,
1378 method = "Introspect"
1379 )
1380 reply = self.connection.send_with_reply_and_block(message, timeout)
1381 return \
1382 Introspection.parse(reply.expect_return_objects("s")[0])
1383 #end introspect
1384
1385 async def introspect_async(self, destination, path, timeout = DBUS.TIMEOUT_USE_DEFAULT) :
1386 "sends an Introspect request to the specified bus name and object path," \
1387 " and returns the resulting parsed Introspection structure."
1388 assert self.loop != None, "no event loop to attach coroutine to"
1389 message = dbus.Message.new_method_call \
1390 (
1391 destination = destination,
1392 path = dbus.unsplit_path(path),
1393 iface = DBUS.INTERFACE_INTROSPECTABLE,
1394 method = "Introspect"
1395 )
1396 reply = await self.connection.send_await_reply(message, timeout)
1397 return \
1398 Introspection.parse(reply.expect_return_objects("s")[0])
1399 #end introspect_async
1400
1401 def __getitem__(self, bus_name) :
1402 "for client-side use; lets you obtain references to bus peers by" \
1403 " looking up their names in this Connection object as though it" \
1404 " were a mapping."
1405 return \
1406 BusPeer(self, bus_name)
1407 #end __getitem__
1408
1409 def get_proxy_object(self, bus_name, path) :
1410 "for client-side use; returns a BusPeer.Object instance for communicating" \
1411 " with a specified server object. You can then call get_interface" \
1412 " on the result to create an interface object that can be used to" \
1413 " call any method defined on the server by that interface."
1414 return \
1415 BusPeer(self, bus_name)[path]
1416 #end get_proxy_object
1417
1418 def get_proxy_interface(self, destination, path, interface, timeout = DBUS.TIMEOUT_USE_DEFAULT) :
1419 "sends an Introspect request to the specified bus name and object path" \
1420 " (if interface is not an Interface object or the name of one of the standard" \
1421 " interfaces), and generates a client-side proxy interface for that interface."
1422 if isinstance(interface, Introspection.Interface) :
1423 definition = interface
1424 interface = definition.name
1425 elif isinstance(interface, str) :
1426 if interface in dbus.standard_interfaces :
1427 definition = dbus.standard_interfaces[interface]
1428 else :
1429 introspection = self.introspect(destination, path, timeout)
1430 interfaces = introspection.interfaces_by_name
1431 if interface not in interfaces :
1432 raise dbus.DBusError \
1433 (
1434 DBUS.ERROR_UNKNOWN_INTERFACE,
1435 "peer “%s” object “%s” does not understand interface “%s”"
1436 %
1437 (destination, path, interface)
1438 )
1439 #end if
1440 definition = interfaces[interface]
1441 #end if
1442 else :
1443 raise TypeError("interface must be an Interface or name of one")
1444 #end if
1445 return \
1446 def_proxy_interface \
1447 (
1448 name = interface,
1449 kind = INTERFACE.CLIENT,
1450 introspected = definition,
1451 is_async = False
1452 )
1453 #end get_proxy_interface
1454
1455 async def get_proxy_interface_async(self, destination, path, interface, timeout = DBUS.TIMEOUT_USE_DEFAULT) :
1456 "sends an Introspect request to the specified bus name and object path" \
1457 " (if interface is not an Interface object or the name of one of the standard" \
1458 " interfaces), and generates a client-side proxy interface for that interface."
1459 assert self.loop != None, "no event loop to attach coroutine to"
1460 if isinstance(interface, Introspection.Interface) :
1461 definition = interface
1462 interface = definition.name
1463 elif isinstance(interface, str) :
1464 if interface in dbus.standard_interfaces :
1465 definition = dbus.standard_interfaces[interface]
1466 else :
1467 introspection = await self.introspect_async(destination, path, timeout)
1468 interfaces = introspection.interfaces_by_name
1469 if interface not in interfaces :
1470 raise dbus.DBusError \
1471 (
1472 DBUS.ERROR_UNKNOWN_INTERFACE,
1473 "peer “%s” object “%s” does not understand interface “%s”"
1474 %
1475 (destination, path, interface)
1476 )
1477 #end if
1478 definition = interfaces[interface]
1479 #end if
1480 else :
1481 raise TypeError("interface must be an Interface or name of one")
1482 #end if
1483 return \
1484 def_proxy_interface \
1485 (
1486 name = interface,
1487 kind = INTERFACE.CLIENT,
1488 introspected = definition,
1489 is_async = True
1490 )
1491 #end get_proxy_interface_async
1492
1493 #end Connection
1494
1495 def session_bus(**kwargs) :
1496 "returns a Connection object for the current D-Bus session bus."
1497 return \
1498 Connection(dbus.Connection.bus_get(DBUS.BUS_SESSION, private = False), False) \
1499 .register_additional_standard(**kwargs)
1500 #end session_bus
1501
1502 def system_bus(**kwargs) :
1503 "returns a Connection object for the D-Bus system bus."
1504 return \
1505 Connection(dbus.Connection.bus_get(DBUS.BUS_SYSTEM, private = False), False) \
1506 .register_additional_standard(**kwargs)
1507 #end system_bus
1508
1509 def starter_bus(**kwargs) :
1510 "returns a Connection object for the D-Bus starter bus."
1511 return \
1512 Connection(dbus.Connection.bus_get(DBUS.BUS_STARTER, private = False), False) \
1513 .register_additional_standard(**kwargs)
1514 #end starter_bus
1515
1516 async def session_bus_async(loop = None, **kwargs) :
1517 "returns a Connection object for the current D-Bus session bus."
1518 return \
1519 Connection \
1520 (
1521 await dbus.Connection.bus_get_async(DBUS.BUS_SESSION, private = False, loop = loop),
1522 False
1523 ) \
1524 .register_additional_standard(**kwargs)
1525 #end session_bus_async
1526
1527 async def system_bus_async(loop = None, **kwargs) :
1528 "returns a Connection object for the D-Bus system bus."
1529 return \
1530 Connection \
1531 (
1532 await dbus.Connection.bus_get_async(DBUS.BUS_SYSTEM, private = False, loop = loop),
1533 False
1534 ) \
1535 .register_additional_standard(**kwargs)
1536 #end system_bus_async
1537
1538 async def starter_bus_async(loop = None, **kwargs) :
1539 "returns a Connection object for the D-Bus starter bus."
1540 return \
1541 Connection \
1542 (
1543 await dbus.Connection.bus_get_async(DBUS.BUS_STARTER, private = False, loop = loop),
1544 False
1545 ) \
1546 .register_additional_standard(**kwargs)
1547 #end starter_bus_async
1548
1549 def connect_server(address, private, **kwargs) :
1550 "opens a connection to a server at the specified network address and" \
1551 " returns a Connection object for the connection."
1552 return \
1553 Connection(dbus.Connection.open(address, private = private), True) \
1554 .register_additional_standard(**kwargs)
1555 #end connect_server
1556
1557 async def connect_server_async(address, private, loop = None, timeout = DBUS.TIMEOUT_INFINITE, **kwargs) :
1558 "opens a connection to a server at the specified network address and" \
1559 " returns a Connection object for the connection."
1560 return \
1561 Connection \
1562 (
1563 await dbus.Connection.open_async(address, private = private, loop = loop, timeout = timeout),
1564 True
1565 ) \
1566 .register_additional_standard(**kwargs)
1567 #end connect_server_async
1568
1569 class Server :
1570 "listens for connections on a particular socket address, separate from" \
1571 " the D-Bus daemon. Requires asyncio."
1572
1573 __slots__ = ("server",)
1574
1575 def __init__(self, address, loop = None) :
1576 self.server = dbus.Server.listen(address)
1577 self.server.attach_asyncio(loop)
1578 #end __init__
1579
1580 def __del__(self) :
1581 self.server.disconnect()
1582 #end __del__
1583
1584 async def await_new_connection(self, timeout = DBUS.TIMEOUT_INFINITE) :
1585 "waits for a new connection attempt and returns a wrapping Connection object." \
1586 " If no connection appears within the specified timeout, returns None."
1587 conn = await self.server.await_new_connection(timeout)
1588 if conn != None :
1589 result = Connection(conn, True)
1590 else :
1591 result = None
1592 #end if
1593 return \
1594 result
1595 #end await_new_connection
1596
1597 #end Server
1598
1599 #+
1600 # Proxy interface objects -- for client-side use
1601 #-
1602
1603 class BusPeer :
1604 "Intended for client-side use: a proxy for a D-Bus peer. These offer two" \
1605 " different ways to traverse the bus-name/path/interface hierarchy. Start" \
1606 " by obtaining a BusPeer object from a Connection:\n" \
1607 "\n" \
1608 " peer = conn[«bus_name»]\n" \
1609 "\n" \
1610 "Now you can either reference a proxy object by specifying its path:\n" \
1611 "\n" \
1612 " obj = peer[«object_path»]\n" \
1613 "\n" \
1614 "from which you can get a proxy interface thus:\n" \
1615 "\n" \
1616 " iface = obj.get_interface(«iface_name»)\n" \
1617 "\n" \
1618 "Or you can get a root proxy interface from the bus peer by" \
1619 " introspecting some arbitrary (but suitable) reference path:\n" \
1620 "\n" \
1621 " iface_root = peer.get_interface(«reference_path», «iface_name»)\n" \
1622 "\n" \
1623 "from which you can obtain a proxy interface for a specific object thus:\n" \
1624 "\n" \
1625 " iface = iface_root[«object_path»]\n" \
1626 "\n" \
1627 "Whichever way you do it, you can now make method calls on the iface object" \
1628 " which will automatically be communicated as method calls to the peer via" \
1629 " the D-Bus."
1630
1631 __slots__ = ("conn", "bus_name")
1632
1633 class RootProxy :
1634 "abstract base class for identifying root proxy classes."
1635 pass
1636 #end RootProxy
1637
1638 class Object :
1639 "identifies a proxy object by a bus, a bus name and a path."
1640
1641 __slots__ = ("conn", "peer", "bus_name", "path")
1642
1643 class ProxyInterface :
1644 "abstract base class for identifying proxy interface classes."
1645 pass
1646 #end ProxyInterface
1647
1648 def __init__(self, conn, bus_name, path) :
1649 if not isinstance(conn, Connection) :
1650 raise TypeError("conn must be a Connection")
1651 #end if
1652 dbus.validate_bus_name(bus_name)
1653 self.conn = conn
1654 self.bus_name = bus_name
1655 self.path = path
1656 #end __init__
1657
1658 def introspect(self, timeout = DBUS.TIMEOUT_USE_DEFAULT) :
1659 "sends an Introspect request to the specified bus name and object path," \
1660 " and returns the resulting parsed Introspection structure."
1661 return \
1662 self.conn.introspect \
1663 (
1664 destination = self.bus_name,
1665 path = self.path,
1666 timeout = timeout,
1667 )
1668 #end introspect
1669
1670 async def introspect_async(self, timeout = DBUS.TIMEOUT_USE_DEFAULT) :
1671 "sends an Introspect request to the specified bus name and object path," \
1672 " and returns the resulting parsed Introspection structure."
1673 return await \
1674 self.conn.introspect_async \
1675 (
1676 destination = self.bus_name,
1677 path = self.path,
1678 timeout = timeout,
1679 )
1680 #end introspect_async
1681
1682 def get_interface(self, interface, timeout = DBUS.TIMEOUT_USE_DEFAULT) :
1683 "sends an Introspect request to the specified bus name and object path" \
1684 " (if interface is not one of the standard interfaces), and generates" \
1685 " a client-side proxy interface for the interface with the specified name."
1686 return \
1687 self.conn.get_proxy_interface \
1688 (
1689 destination = self.bus_name,
1690 path = self.path,
1691 interface = interface,
1692 timeout = timeout
1693 )(
1694 connection = self.conn.connection,
1695 dest = self.bus_name,
1696 timeout = timeout,
1697 )[self.path]
1698 #end get_interface
1699
1700 async def get_async_interface(self, interface, timeout = DBUS.TIMEOUT_USE_DEFAULT) :
1701 "sends an Introspect request to the specified bus name and object path" \
1702 " (if interface is not one of the standard interfaces), and generates" \
1703 " a client-side proxy interface for the interface with the specified name."
1704 return \
1705 (await self.conn.get_proxy_interface_async
1706 (
1707 destination = self.bus_name,
1708 path = self.path,
1709 interface = interface,
1710 timeout = timeout
1711 ))(
1712 connection = self.conn.connection,
1713 dest = self.bus_name,
1714 timeout = timeout,
1715 )[self.path]
1716 #end get_async_interface
1717
1718 #end Object
1719
1720 def __init__(self, conn, bus_name) :
1721 self.conn = conn
1722 self.bus_name = bus_name
1723 #end __init__
1724
1725 def __getitem__(self, path) :
1726 "lets you obtain references to objects implemented by this bus peer" \
1727 " by using their paths as lookup keys in a mapping. Of course, there" \
1728 " is no guarantee such an object actually exists within the peer."
1729 return \
1730 type(self).Object(self.conn, self.bus_name, path)
1731 #end __getitem__
1732
1733 def introspect(self, path, timeout = DBUS.TIMEOUT_USE_DEFAULT) :
1734 "sends an Introspect request to the specified bus name and object path," \
1735 " and returns the resulting parsed Introspection structure."
1736 return \
1737 self.conn.introspect \
1738 (
1739 destination = self.bus_name,
1740 path = path,
1741 timeout = timeout,
1742 )
1743 #end introspect
1744
1745 async def introspect_async(self, path, timeout = DBUS.TIMEOUT_USE_DEFAULT) :
1746 "sends an Introspect request to the specified bus name and object path," \
1747 " and returns the resulting parsed Introspection structure."
1748 return await \
1749 self.conn.introspect_async \
1750 (
1751 destination = self.bus_name,
1752 path = path,
1753 timeout = timeout,
1754 )
1755 #end introspect_async
1756
1757 def get_interface(self, path, interface, timeout = DBUS.TIMEOUT_USE_DEFAULT) :
1758 "sends an Introspect request to the specified bus name and object path" \
1759 " (if interface is not one of the standard interfaces), and generates" \
1760 " a client-side proxy interface for the interface with the specified name."
1761 return \
1762 self.conn.get_proxy_interface \
1763 (
1764 destination = self.bus_name,
1765 path = path,
1766 interface = interface,
1767 timeout = timeout,
1768 )(
1769 connection = self.conn.connection,
1770 dest = self.bus_name,
1771 timeout = timeout,
1772 )
1773 #end get_interface
1774
1775 async def get_interface_async(self, path, interface, timeout = DBUS.TIMEOUT_USE_DEFAULT) :
1776 "sends an Introspect request to the specified bus name and object path" \
1777 " (if interface is not one of the standard interfaces), and generates" \
1778 " a client-side proxy interface for the interface with the specified name."
1779 return \
1780 (await self.conn.get_proxy_interface_async
1781 (
1782 destination = self.bus_name,
1783 path = path,
1784 interface = interface,
1785 timeout = timeout,
1786 ))(
1787 connection = self.conn.connection,
1788 dest = self.bus_name,
1789 timeout = timeout,
1790 )
1791 #end get_interface_async
1792
1793 #end BusPeer
1794
1795 #+
1796 # Interface-dispatch mechanism
1797 #-
1798
1799 class INTERFACE(enum.Enum) :
1800 "what kind of @interface() is this:\n" \
1801 " * CLIENT -- client-side, for sending method calls to server and" \
1802 " receiving signals from server\n" \
1803 " * SERVER -- server-side, for receiving method calls from clients and" \
1804 " sending signals to clients\n" \
1805 " * CLIENT_AND_SERVER -- this side is both client and server."
1806
1807 CLIENT = 1
1808 SERVER = 2
1809 CLIENT_AND_SERVER = 3 # CLIENT | SERVER
1810 #end INTERFACE
1811
1812 def _send_method_return(connection, message, sig, args) :
1813 reply = message.new_method_return()
1814 reply.append_objects(sig, *args)
1815 connection.send(reply)
1816 #end _send_method_return
1817
1818 def _message_interface_dispatch(connection, message, w_bus) :
1819 # installed as message filter on a connection to handle dispatch
1820 # to registered @interface() classes.
1821
1822 bus = w_bus()
1823 assert bus != None, "parent Connection has gone"
1824
1825 def dispatch_signal(level, path) :
1826 # Note I ignore handled/not handled status and pass the signal
1827 # to all registered handlers.
1828 if len(path) != 0 and path[0] in level.children :
1829 # call lower-level (more-specific) signal handlers first,
1830 # not that it’s important
1831 dispatch_signal(level.children[path[0]], path[1:])
1832 #end if
1833 signal_listeners = level.signal_listeners
1834 name = message.member
1835 for fallback in (False, True) :
1836 # again, call more-specific (fallback = False) handlers first,
1837 # not that it’s important
1838 rulekey = _signal_key(fallback, message.interface, name)
1839 if rulekey in signal_listeners and (len(path) == 0 or fallback) :
1840 funcs = signal_listeners[rulekey]
1841 for func in funcs :
1842 try :
1843 call_info = func._signal_info
1844 try :
1845 args = message.expect_objects(call_info["in_signature"])
1846 except (TypeError, ValueError) :
1847 raise ErrorReturn \
1848 (
1849 name = DBUS.ERROR_INVALID_ARGS,
1850 message = "message arguments do not match expected signature"
1851 )
1852 #end try
1853 kwargs = {}
1854 for keyword_keyword, value in \
1855 (
1856 ("connection_keyword", lambda : connection),
1857 ("message_keyword", lambda : message),
1858 ("path_keyword", lambda : message.path),
1859 ("bus_keyword", lambda : bus),
1860 ) \
1861 :
1862 if call_info[keyword_keyword] != None :
1863 kwargs[call_info[keyword_keyword]] = value()
1864 #end if
1865 #end for
1866 if call_info["args_keyword"] != None :
1867 if call_info["arg_keys"] != None :
1868 args = dict \
1869 (
1870 (key, value)
1871 for key, value in zip(call_info["arg_keys"], args)
1872 )
1873 if "args_constructor" in call_info :
1874 args = call_info["args_constructor"](**args)
1875 #end if
1876 #end if
1877 kwargs[call_info["args_keyword"]] = args
1878 args = ()
1879 else :
1880 if call_info["arg_keys"] != None :
1881 for key, value in zip(call_info["arg_keys"], args) :
1882 kwargs[key] = value
1883 #end for
1884 args = ()
1885 #end if
1886 #end if
1887 result = func(*args, **kwargs)
1888 if asyncio.iscoroutine(result) :
1889 async def await_result(coro) :
1890 # just to gobble any ErrorReturn
1891 try :
1892 await coro
1893 except ErrorReturn :
1894 pass
1895 #end try
1896 #end await_result
1897 bus.create_task(await_result(result))
1898 elif result != None :
1899 raise ValueError \
1900 (
1901 "invalid result from signal handler: %s" % repr(result)
1902 )
1903 #end if
1904 except ErrorReturn :
1905 pass
1906 #end try
1907 #end for
1908 #end if
1909 #end for
1910 #end dispatch_signal
1911
1912 def return_result_common(call_info, result) :
1913 # handles list, tuple, dict or Error returned from method handler;
1914 # packs into reply message and sends it off.
1915 if isinstance(result, dbus.Error) :
1916 assert result.is_set, "unset Error object returned from handler"
1917 reply = message.new_error(result.name, result.message)
1918 connection.send(reply)
1919 else :
1920 sig = dbus.parse_signature(call_info["out_signature"])
1921 if isinstance(result, dict) and call_info["result_keys"] != None :
1922 result = list(result[key] for key in call_info["result_keys"])
1923 # convert result items to list in right order
1924 elif (
1925 "result_constructor" in call_info
1926 and
1927 isinstance(result, call_info["result_constructor"])
1928 ) :
1929 result = list(result)
1930 elif len(sig) == 0 and result == None :
1931 # might as well allow method call to not bother returning an empty result
1932 result = []
1933 elif not isinstance(result, (tuple, list)) :
1934 raise ValueError("invalid handler result %s" % repr(result))
1935 #end if
1936 _send_method_return \
1937 (
1938 connection = connection,
1939 message = message,
1940 sig = sig,
1941 args = result
1942 )
1943 #end if
1944 #end return_result_common
1945
1946 #begin _message_interface_dispatch
1947 result = DBUS.HANDLER_RESULT_NOT_YET_HANDLED # to begin with
1948 if message.type in (DBUS.MESSAGE_TYPE_METHOD_CALL, DBUS.MESSAGE_TYPE_SIGNAL) :
1949 is_method = message.type == DBUS.MESSAGE_TYPE_METHOD_CALL
1950 if not is_method and bus._client_dispatch != None :
1951 dispatch_signal(bus._client_dispatch, dbus.split_path(message.path))
1952 #end if
1953 iface = bus.get_dispatch_interface(message.path, message.interface)
1954 if iface != None :
1955 method_name = message.member
1956 methods = (iface._interface_signals, iface._interface_methods)[is_method]
1957 if (
1958 iface._interface_kind != (INTERFACE.SERVER, INTERFACE.CLIENT)[is_method]
1959 and
1960 method_name in methods
1961 ) :
1962 method = methods[method_name]
1963 call_info = getattr(method, ("_signal_info", "_method_info")[is_method])
1964 if is_method or not call_info["stub"] :
1965 to_return_result = None
1966 try :
1967 try :
1968 args = message.expect_objects(call_info["in_signature"])
1969 except (TypeError, ValueError) :
1970 raise ErrorReturn \
1971 (
1972 name = DBUS.ERROR_INVALID_ARGS,
1973 message = "message arguments do not match expected signature"
1974 )
1975 #end try
1976 kwargs = {}
1977 for keyword_keyword, value in \
1978 (
1979 ("connection_keyword", lambda : connection),
1980 ("message_keyword", lambda : message),
1981 ("path_keyword", lambda : message.path),
1982 ("bus_keyword", lambda : bus),
1983 ) \
1984 :
1985 if call_info[keyword_keyword] != None :
1986 kwargs[call_info[keyword_keyword]] = value()
1987 #end if
1988 #end for
1989 if call_info["args_keyword"] != None :
1990 if call_info["arg_keys"] != None :
1991 args = dict \
1992 (
1993 (key, value)
1994 for key, value in zip(call_info["arg_keys"], args)
1995 )
1996 if "args_constructor" in call_info :
1997 args = call_info["args_constructor"](**args)
1998 #end if
1999 #end if
2000 kwargs[call_info["args_keyword"]] = args
2001 args = ()
2002 else :
2003 if call_info["arg_keys"] != None :
2004 for key, value in zip(call_info["arg_keys"], args) :
2005 kwargs[key] = value
2006 #end for
2007 args = ()
2008 #end if
2009 #end if
2010 if is_method :
2011 # additional ways of returning method result
2012 if call_info["result_keyword"] != None :
2013 # construct a mutable result object that handler will update in place
2014 to_return_result = [None] * len(call_info["out_signature"])
2015 if call_info["result_keys"] != None :
2016 to_return_result = dict \
2017 (
2018 (key, val)
2019 for key, val in zip(call_info["result_keys"], to_return_result)
2020 )
2021 if "result_constructor" in call_info :
2022 to_return_result = call_info["result_constructor"](**to_return_result)
2023 #end if
2024 #end if
2025 kwargs[call_info["result_keyword"]] = to_return_result
2026 elif call_info["set_result_keyword"] != None :
2027 # caller wants to return result via callback
2028 def set_result(the_result) :
2029 "Call this to set the args for the reply message."
2030 nonlocal to_return_result
2031 to_return_result = the_result
2032 #end set_result
2033 kwargs[call_info["set_result_keyword"]] = set_result
2034 #end if
2035 #end if
2036 result = method(iface, *args, **kwargs)
2037 except ErrorReturn as err :
2038 result = err.as_error()
2039 #end try
2040 if result == None :
2041 if to_return_result != None or is_method :
2042 # method handler possibly used set_result mechanism
2043 return_result_common(call_info, to_return_result)
2044 #end if
2045 result = DBUS.HANDLER_RESULT_HANDLED
2046 elif asyncio.iscoroutine(result) :
2047 assert bus.loop != None, "no event loop to attach coroutine to"
2048 if is_method :
2049 # wait for result
2050 async def await_result(coro) :
2051 try :
2052 result = await coro
2053 except ErrorReturn as err :
2054 result = err.as_error()
2055 #end try
2056 if result == None and to_return_result != None :
2057 # method handler used set_result mechanism
2058 result = to_return_result
2059 #end if
2060 return_result_common(call_info, result)
2061 #end await_result
2062 bus.create_task(await_result(result))
2063 else :
2064 bus.create_task(result)
2065 #end if
2066 result = DBUS.HANDLER_RESULT_HANDLED
2067 elif isinstance(result, bool) :
2068 # slightly tricky: interpret True as handled, False as not handled,
2069 # even though DBUS.HANDLER_RESULT_HANDLED is zero and
2070 # DBUS.HANDLER_RESULT_NOT_YET_HANDLED is nonzero.
2071 result = \
2072 (DBUS.HANDLER_RESULT_NOT_YET_HANDLED, DBUS.HANDLER_RESULT_HANDLED)[result]
2073 elif (
2074 result
2075 in
2076 (
2077 DBUS.HANDLER_RESULT_HANDLED,
2078 DBUS.HANDLER_RESULT_NOT_YET_HANDLED,
2079 DBUS.HANDLER_RESULT_NEED_MEMORY,
2080 )
2081 ) :
2082 pass
2083 else :
2084 return_result_common(call_info, result)
2085 result = DBUS.HANDLER_RESULT_HANDLED
2086 #end if
2087 #end if
2088 #end if
2089 #end if
2090 #end if
2091 dispatch_signal = None # remove reference circularity
2092 return \
2093 result
2094 #end _message_interface_dispatch
2095
2096 def def_attr_class(name, attrs) :
2097 "defines a class with read/write attributes with names from the sequence attrs." \
2098 " Objects of this class can be coerced to lists or tuples, and attributes can" \
2099 " also be accessed by index, like a list."
2100
2101 class result :
2102 __slots__ = tuple(attrs)
2103
2104 def __init__(self, **kwargs) :
2105 for name in type(self).__slots__ :
2106 setattr(self, name, None)
2107 #end for
2108 for name in kwargs :
2109 setattr(self, name, kwargs[name])
2110 #end for
2111 #end __init__
2112
2113 def __repr__(self) :
2114 return \
2115 (
2116 "%s(%s)"
2117 %
2118 (
2119 type(self).__name__,
2120 ", ".join
2121 (
2122 "%s = %s"
2123 %
2124 (name, repr(getattr(self, name)))
2125 for name in type(self).__slots__
2126 ),
2127 )
2128 )
2129 #end __repr__
2130
2131 def __len__(self) :
2132 return \
2133 len(type(self).__slots__)
2134 #end __len__
2135
2136 def __getitem__(self, i) :
2137 return \
2138 getattr(self, type(self).__slots__[i])
2139 #end __getitem__
2140
2141 def __setitem__(self, i, val) :
2142 setattr(self, type(self).__slots__[i], val)
2143 #end __setitem__
2144
2145 #end class
2146
2147 #begin def_attr_class
2148 result.__name__ = name
2149 return \
2150 result
2151 #end def_attr_class
2152
2153 def interface \
2154 (
2155 kind, *,
2156 name,
2157 property_change_notification = Introspection.PROP_CHANGE_NOTIFICATION.NEW_VALUE,
2158 deprecated = False
2159 ) :
2160 "class decorator creator for defining interface classes. “kind” is an" \
2161 " INTERFACE.xxx value indicating whether this is for use on the client side" \
2162 " (send methods, receive signals), server side (receive methods, send signals)" \
2163 " or both. “name” (required) is the interface name that will be known to D-Bus." \
2164 " Interface methods and signals should be invocable as\n" \
2165 "\n" \
2166 " method(self, ...)\n" \
2167 "\n" \
2168 " and definitions should be prefixed with calls to the “@method()” or “@signal()”" \
2169 " decorator to identify them. The return result can be a DBUS.HANDLER_RESULT_xxx" \
2170 " code, or None (equivalent to DBUS.HANDLER_RESULT_HANDLED), or a coroutine" \
2171 " to queue for execution after indicating that the message has been handled. Note" \
2172 " that if you declare the method with “async def”, then the return result seen" \
2173 " will be such a coroutine."
2174
2175 if not isinstance(kind, INTERFACE) :
2176 raise TypeError("kind must be an INTERFACE enum value")
2177 #end if
2178 if not isinstance(name, str) :
2179 raise ValueError("name is required")
2180 #end if
2181 dbus.validate_interface(name)
2182
2183 def decorate(celf) :
2184 if not isinstance(celf, type) :
2185 raise TypeError("only apply decorator to classes.")
2186 #end if
2187 if not isinstance(property_change_notification, Introspection.PROP_CHANGE_NOTIFICATION) :
2188 raise TypeError \
2189 (
2190 "property_change_notification must be an Introspection."
2191 "PROP_CHANGE_NOTIFICATION value"
2192 )
2193 #end if
2194 celf._interface_kind = kind
2195 celf._interface_name = name
2196 celf._interface_property_change_notification = property_change_notification
2197 celf._interface_deprecated = deprecated
2198 celf._interface_methods = \
2199 dict \
2200 (
2201 (f._method_info["name"], f)
2202 for fname in dir(celf)
2203 for f in (getattr(celf, fname),)
2204 if hasattr(f, "_method_info")
2205 )
2206 celf._interface_signals = \
2207 dict \
2208 (
2209 (f._signal_info["name"], f)
2210 for fname in dir(celf)
2211 for f in (getattr(celf, fname),)
2212 if hasattr(f, "_signal_info")
2213 )
2214 props = {}
2215 for info_type, meth_type in \
2216 (
2217 ("_propgetter_info", "getter"), # do first so setter can check change_notification
2218 ("_propsetter_info", "setter"),
2219 ) \
2220 :
2221 for fname in dir(celf) :
2222 func = getattr(celf, fname)
2223 if hasattr(func, info_type) :
2224 propinfo = getattr(func, info_type)
2225 propname = propinfo["name"]
2226 if propname not in props :
2227 props[propname] = {"type" : None}
2228 #end if
2229 propentry = props[propname]
2230 if propinfo["type"] != None :
2231 if propentry["type"] != None :
2232 if propentry["type"] != propinfo["type"] :
2233 raise ValueError \
2234 (
2235 "disagreement on type for property “%s” between"
2236 " getter and setter: “%s” versus “%s”"
2237 %
2238 (
2239 propname,
2240 dbus.unparse_signature(propentry["type"]),
2241 dbus.unparse_signature(propinfo["type"]),
2242 )
2243 )
2244 #end if
2245 else :
2246 propentry["type"] = propinfo["type"]
2247 #end if
2248 #end if
2249 if (
2250 meth_type == "setter"
2251 and
2252 "getter" in propentry
2253 and
2254 propentry["change_notification"]
2255 ==
2256 Introspection.PROP_CHANGE_NOTIFICATION.CONST
2257 ) :
2258 raise ValueError \
2259 (
2260 "mustn’t specify @propsetter() for a"
2261 " PROP_CHANGE_NOTIFICATION.CONST property"
2262 )
2263 #end if
2264 if meth_type == "getter" :
2265 if propinfo["change_notification"] != None :
2266 propentry["change_notification"] = propinfo["change_notification"]
2267 else :
2268 propentry["change_notification"] = property_change_notification
2269 #end if
2270 #end if
2271 propentry[meth_type] = func
2272 #end if
2273 #end for
2274 #end for
2275 celf._interface_props = props
2276 return \
2277 celf
2278 #end decorate
2279
2280 #begin interface
2281 return \
2282 decorate
2283 #end interface
2284
2285 def is_interface(cłass) :
2286 "is cłass defined as an interface class."
2287 return \
2288 isinstance(cłass, type) and hasattr(cłass, "_interface_name")
2289 #end is_interface
2290
2291 def is_interface_instance(obj) :
2292 "is obj an instance of an interface class."
2293 return \
2294 is_interface(type(obj))
2295 #end is_interface_instance
2296
2297 def method \
2298 (*,
2299 name = None,
2300 in_signature,
2301 out_signature,
2302 args_keyword = None,
2303 arg_keys = None,
2304 arg_attrs = None,
2305 result_keyword = None,
2306 result_keys = None,
2307 result_attrs = None,
2308 connection_keyword = None,
2309 message_keyword = None,
2310 path_keyword = None,
2311 bus_keyword = None,
2312 set_result_keyword = None,
2313 reply = True,
2314 deprecated = False
2315 ) :
2316 "Put a call to this function as a decorator for each method of an @interface()" \
2317 " class that is to be registered as a method of the interface." \
2318 " “name” is the name of the method as specified in the D-Bus message; if omitted," \
2319 " it defaults to the name of the function.\n" \
2320 "\n" \
2321 "This is really only useful on the server side. On the client side, omit the" \
2322 " method definition, and even leave out the interface definition and registration" \
2323 " altogether, unless you want to receive signals from the server; instead, use" \
2324 " Connection.get_proxy_object() to send method calls to the server."
2325
2326 in_signature = dbus.parse_signature(in_signature)
2327 out_signature = dbus.parse_signature(out_signature)
2328 for cond, msg in \
2329 (
2330 (
2331 (result_keyword != None or result_keys != None or result_attrs != None)
2332 and
2333 not reply,
2334 "result_keyword, result_keys and result_attrs are"
2335 " meaningless if method does not reply",
2336 ),
2337 (arg_keys != None and arg_attrs != None, "specify arg_keys or arg_attrs, not both"),
2338 (arg_attrs != None and args_keyword == None, "need args_keyword with arg_attrs"),
2339 (
2340 arg_keys != None and len(arg_keys) != len(in_signature),
2341 "number of arg_keys should match number of items in in_signature",
2342 ),
2343 (
2344 arg_attrs != None and len(arg_attrs) != len(in_signature),
2345 "number of arg_attrs should match number of items in in_signature",
2346 ),
2347 (
2348 set_result_keyword != None and result_keyword != None,
2349 "specify set_result_keyword or result_keyword, not both",
2350 ),
2351 (
2352 result_keys != None and result_attrs != None,
2353 "specify result_keys or result_attrs, not both",
2354 ),
2355 (
2356 result_attrs != None and result_keyword == None,
2357 "need result_keyword with result_attrs",
2358 ),
2359 (
2360 result_keys != None and len(result_keys) != len(out_signature),
2361 "number of result_keys should match number of items in out_signature",
2362 ),
2363 (
2364 result_attrs != None and len(result_attrs) != len(out_signature),
2365 "number of result_attrs should match number of items in out_signature",
2366 ),
2367 ) \
2368 :
2369 if cond :
2370 raise ValueError(msg)
2371 #end if
2372 #end for
2373 if arg_keys == None :
2374 args_keys = arg_attrs
2375 #end if
2376 if result_keys == None :
2377 result_keys = result_attrs
2378 #end if
2379
2380 def decorate(func) :
2381 if not callable(func) :
2382 raise TypeError("only apply decorator to callables.")
2383 #end if
2384 if name != None :
2385 func_name = name
2386 else :
2387 func_name = func.__name__
2388 #end if
2389 dbus.validate_member(func_name)
2390 func._method_info = \
2391 {
2392 "name" : func_name,
2393 "in_signature" : in_signature,
2394 "out_signature" : out_signature,
2395 "args_keyword" : args_keyword,
2396 "arg_keys" : arg_keys,
2397 "result_keyword" : result_keyword,
2398 "result_keys" : result_keys,
2399 "connection_keyword" : connection_keyword,
2400 "message_keyword" : message_keyword,
2401 "path_keyword" : path_keyword,
2402 "bus_keyword" : bus_keyword,
2403 "set_result_keyword" : set_result_keyword,
2404 "reply" : reply,
2405 "deprecated" : deprecated,
2406 }
2407 if arg_attrs != None :
2408 func._method_info["args_constructor"] = def_attr_class("%s_args" % func_name, arg_attrs)
2409 #end if
2410 if result_attrs != None :
2411 func._method_info["result_constructor"] = \
2412 def_attr_class("%s_result" % func_name, result_attrs)
2413 #end if
2414 return \
2415 func
2416 #end decorate
2417
2418 #begin method
2419 return \
2420 decorate
2421 #end method
2422
2423 def signal \
2424 (*,
2425 name = None,
2426 in_signature,
2427 args_keyword = None,
2428 arg_keys = None,
2429 arg_attrs = None,
2430 stub = False,
2431 connection_keyword = None,
2432 message_keyword = None,
2433 path_keyword = None,
2434 bus_keyword = None,
2435 deprecated = False # can signals be deprecated?
2436 ) :
2437 "Put a call to this function as a decorator for each method of an @interface()" \
2438 " class that is to be registered as a signal of the interface." \
2439 " “name” is the name of the signal as specified in the D-Bus message; if omitted," \
2440 " it defaults to the name of the function.\n" \
2441 "\n" \
2442 "On the server side, the actual function need only be a dummy, since it is just" \
2443 " a placeholder for storing the information used by Connection.send_signal()."
2444
2445 in_signature = dbus.parse_signature(in_signature)
2446 if arg_attrs != None and args_keyword == None :
2447 raise ValueError("need args_keyword with arg_attrs")
2448 #end if
2449 if arg_keys != None and len(arg_keys) != len(in_signature) :
2450 raise ValueError("number of arg_keys should match number of items in in_signature")
2451 #end if
2452 if arg_attrs != None and len(arg_attrs) != len(in_signature) :
2453 raise ValueError("number of arg_attrs should match number of items in in_signature")
2454 #end if
2455 if arg_keys == None :
2456 args_keys = arg_attrs
2457 #end if
2458
2459 def decorate(func) :
2460 if not callable(func) :
2461 raise TypeError("only apply decorator to callables.")
2462 #end if
2463 if name != None :
2464 func_name = name
2465 else :
2466 func_name = func.__name__
2467 #end if
2468 dbus.validate_member(func_name)
2469 func._signal_info = \
2470 {
2471 "name" : func_name,
2472 "in_signature" : in_signature,
2473 "args_keyword" : args_keyword,
2474 "arg_keys" : arg_keys,
2475 "stub" : stub,
2476 "connection_keyword" : connection_keyword,
2477 "message_keyword" : message_keyword,
2478 "path_keyword" : path_keyword,
2479 "bus_keyword" : bus_keyword,
2480 "deprecated" : deprecated,
2481 }
2482 if arg_attrs != None :
2483 func._signal_info["args_constructor"] = def_attr_class("%s_args" % func_name, arg_attrs)
2484 #end if
2485 return \
2486 func
2487 #end decorate
2488
2489 #begin signal
2490 return \
2491 decorate
2492 #end signal
2493
2494 def def_signal_stub(**kwargs) :
2495 "convenience routine for defining a signal stub function. Instead of\n" \
2496 "\n" \
2497 " @signal(«args»)\n" \
2498 " def stubfunc() : pass\n" \
2499 "\n" \
2500 "you can do\n" \
2501 "\n" \
2502 " stubfunc = def_signal_stub(«args»)\n" \
2503 "\n" \
2504 "passing the same «args» as you would to the @signal() decorator. But note" \
2505 " that the name arg is no longer optional."
2506
2507 def stub() :
2508 "This is just a stub, standing in for a signal definition in a" \
2509 " proxy interface class. It is not meant to be called."
2510 # Lack of formal args should also stymie attempts to invoke as a method.
2511 raise \
2512 NotImplementedError("attempted call on signal stub")
2513 #end stub
2514
2515 #begin def_signal_stub
2516 if "name" not in kwargs :
2517 raise KeyError("name arg is mandatory")
2518 #end if
2519 stub.__name__ = kwargs["name"]
2520 return \
2521 signal(**kwargs)(stub)
2522 #end def_signal_stub
2523
2524 def propgetter \
2525 (*,
2526 name,
2527 type,
2528 name_keyword = None,
2529 connection_keyword = None,
2530 message_keyword = None,
2531 path_keyword = None,
2532 bus_keyword = None,
2533 change_notification = None
2534 ) :
2535 "Put a call to this function as a decorator for a method of an @interface()" \
2536 " class that is to be the getter of the named property."
2537
2538 def decorate(func) :
2539 if not callable(func) :
2540 raise TypeError("only apply decorator to callables.")
2541 #end if
2542 assert isinstance(name, str), "property name is mandatory"
2543 if (
2544 change_notification != None
2545 and
2546 not isinstance(change_notification, Introspection.PROP_CHANGE_NOTIFICATION)
2547 ) :
2548 raise TypeError \
2549 (
2550 "change_notification must be None or an Introspection."
2551 "PROP_CHANGE_NOTIFICATION value"
2552 )
2553 #end if
2554 func._propgetter_info = \
2555 {
2556 "name" : name,
2557 "type" : dbus.parse_single_signature(type),
2558 "name_keyword" : name_keyword,
2559 "connection_keyword" : connection_keyword,
2560 "message_keyword" : message_keyword,
2561 "path_keyword" : path_keyword,
2562 "bus_keyword" : bus_keyword,
2563 "change_notification" : change_notification,
2564 }
2565 return \
2566 func
2567 #end decorate
2568
2569 #begin propgetter
2570 return \
2571 decorate
2572 #end propgetter
2573
2574 def propsetter \
2575 (*,
2576 name,
2577 type,
2578 name_keyword = None,
2579 type_keyword = None,
2580 value_keyword,
2581 connection_keyword = None,
2582 message_keyword = None,
2583 path_keyword = None,
2584 bus_keyword = None
2585 ) :
2586 "Put a call to this function as a decorator for a method of an @interface()" \
2587 " class that is to be the setter of the named property."
2588
2589 def decorate(func) :
2590 if not callable(func) :
2591 raise TypeError("only apply decorator to callables.")
2592 #end if
2593 assert isinstance(name, str), "property name is mandatory"
2594 func._propsetter_info = \
2595 {
2596 "name" : name,
2597 "type" : dbus.parse_single_signature(type),
2598 "name_keyword" : name_keyword,
2599 "type_keyword" : type_keyword,
2600 "value_keyword" : value_keyword,
2601 "connection_keyword" : connection_keyword,
2602 "message_keyword" : message_keyword,
2603 "path_keyword" : path_keyword,
2604 "bus_keyword" : bus_keyword,
2605 }
2606 return \
2607 func
2608 #end decorate
2609
2610 #begin propsetter
2611 return \
2612 decorate
2613 #end propsetter
2614
2615 #+
2616 # Introspection
2617 #-
2618
2619 def introspect(interface) :
2620 "returns an Introspection.Interface object that describes the specified" \
2621 " @interface() class."
2622 if not is_interface(interface) :
2623 raise TypeError("interface must be an @interface()-type class")
2624 #end if
2625
2626 def add_deprecated(annots, deprecated) :
2627 # common routine for generating “deprecated” annotations.
2628 if deprecated :
2629 annots.append \
2630 (
2631 Introspection.Annotation(name = "org.freedesktop.DBus.Deprecated", value = "true")
2632 )
2633 #end if
2634 #end add_deprecated
2635
2636 #begin introspect
2637 methods = []
2638 for name in interface._interface_methods :
2639 method = interface._interface_methods[name]
2640 annots = []
2641 add_deprecated(annots, method._method_info["deprecated"])
2642 if not method._method_info["reply"] :
2643 annots.append \
2644 (
2645 Introspection.Annotation
2646 (
2647 name = "org.freedesktop.DBus.Method.NoReply",
2648 value = "true"
2649 )
2650 )
2651 #end if
2652 args = []
2653 for keys_keyword, sig_keyword, direction in \
2654 (
2655 ("arg_keys", "in_signature", Introspection.DIRECTION.IN),
2656 ("result_keys", "out_signature", Introspection.DIRECTION.OUT),
2657 ) \
2658 :
2659 arg_sigs = dbus.parse_signature(method._method_info[sig_keyword])
2660 arg_names = method._method_info[keys_keyword]
2661 if arg_names == None :
2662 arg_names = [None] * len(arg_sigs)
2663 #end if
2664 for arg_name, arg_sig in zip(arg_names, arg_sigs) :
2665 args.append \
2666 (
2667 Introspection.Interface.Method.Arg
2668 (
2669 name = arg_name,
2670 type = arg_sig,
2671 direction = direction
2672 )
2673 )
2674 #end for
2675 #end for
2676 methods.append \
2677 (
2678 Introspection.Interface.Method
2679 (
2680 name = name,
2681 args = args,
2682 annotations = annots
2683 )
2684 )
2685 #end for
2686 signals = []
2687 for name in interface._interface_signals :
2688 signal = interface._interface_signals[name]
2689 annots = []
2690 add_deprecated(annots, signal._signal_info["deprecated"])
2691 args = []
2692 arg_sigs = dbus.parse_signature(signal._signal_info["in_signature"])
2693 arg_names = signal._signal_info["arg_keys"]
2694 if arg_names == None :
2695 arg_names = [None] * len(arg_sigs)
2696 #end if
2697 for arg_name, arg_sig in zip(arg_names, arg_sigs) :
2698 args.append \
2699 (
2700 Introspection.Interface.Signal.Arg(name = arg_name, type = arg_sig)
2701 )
2702 #end for
2703 signals.append \
2704 (
2705 Introspection.Interface.Signal
2706 (
2707 name = name,
2708 args = args,
2709 annotations = annots
2710 )
2711 )
2712 #end for
2713 properties = []
2714 for name in interface._interface_props :
2715 prop = interface._interface_props[name]
2716 annots = []
2717 if (
2718 "getter" in prop
2719 and
2720 prop["change_notification"] != interface._interface_property_change_notification
2721 ) :
2722 annots.append \
2723 (
2724 Introspection.Annotation
2725 (
2726 name = "org.freedesktop.DBus.Property.EmitsChangedSignal",
2727 value = prop["change_notification"].value
2728 )
2729 )
2730 #end if
2731 properties.append \
2732 (
2733 Introspection.Interface.Property
2734 (
2735 name = name,
2736 type = dbus.parse_single_signature(prop["type"]),
2737 access =
2738 (
2739 None,
2740 Introspection.ACCESS.READ,
2741 Introspection.ACCESS.WRITE,
2742 Introspection.ACCESS.READWRITE,
2743 )[
2744 int("getter" in prop)
2745 |
2746 int("setter" in prop) << 1
2747 ],
2748 annotations = annots
2749 )
2750 )
2751 #end for
2752 annots = []
2753 if (
2754 interface._interface_property_change_notification
2755 !=
2756 Introspection.PROP_CHANGE_NOTIFICATION.NEW_VALUE
2757 ) :
2758 annots.append \
2759 (
2760 Introspection.Annotation
2761 (
2762 name = "org.freedesktop.DBus.Property.EmitsChangedSignal",
2763 value = interface._interface_property_change_notification.value
2764 )
2765 )
2766 #end if
2767 add_deprecated(annots, interface._interface_deprecated)
2768 return \
2769 Introspection.Interface \
2770 (
2771 name = interface._interface_name,
2772 methods = methods,
2773 signals = signals,
2774 properties = properties,
2775 annotations = annots
2776 )
2777 #end introspect
2778
2779 def _append_args(message, call_info, args, kwargs) :
2780 message_args = [None] * len(call_info.in_signature)
2781 if len(args) != 0 :
2782 if len(args) > len(message_args) :
2783 raise ValueError("too many args")
2784 #end if
2785 message_args[:len(args)] = args
2786 #end if
2787 if len(kwargs) != 0 :
2788 arg_positions = {}
2789 idx = 0
2790 for arg in call_info.args :
2791 if (
2792 isinstance(arg, Introspection.Interface.Signal.Arg)
2793 or
2794 arg.direction == Introspection.DIRECTION.IN
2795 ) :
2796 arg_positions[arg.name] = idx
2797 idx += 1
2798 #end if
2799 #end for
2800 for arg_name in kwargs :
2801 if arg_name not in arg_positions :
2802 raise KeyError("no such arg name “%s”" % arg_name)
2803 #end if
2804 pos = arg_positions[arg_name]
2805 if message_args[pos] != None :
2806 raise ValueError("duplicate value for arg %d" % pos)
2807 #end if
2808 message_args[pos] = kwargs[arg_name]
2809 #end for
2810 #end if
2811 missing = set(pos for pos in range(len(message_args)) if message_args[pos] == None)
2812 if len(missing) != 0 :
2813 raise ValueError \
2814 (
2815 "too few args specified: missing %s"
2816 %
2817 ", ".join("%d" % pos for pos in sorted(missing))
2818 )
2819 #end if
2820 message.append_objects(call_info.in_signature, *message_args)
2821 #end _append_args
2822
2823 def def_proxy_interface(kind, *, name, introspected, is_async) :
2824 "given an Introspection.Interface object, creates a proxy class that can be" \
2825 " instantiated by a client to send method-call messages to a server," \
2826 " or by a server to send signal messages to clients. is_async indicates" \
2827 " whether method calls are done via coroutines as opposed to blocking" \
2828 " the thread. The resulting class can be instantiated by\n" \
2829 "\n" \
2830 " instance = proxy_class(«connection», «dest»)\n" \
2831 "\n" \
2832 " where «connection» is a dbussy.Connection object to use for sending and receiving" \
2833 " the messages, and «dest» is the bus name to which to send the messages. The" \
2834 " resulting instance is a “root proxy”: a proxy for a particular object path" \
2835 " is obtained from this by an indexing call like\n" \
2836 "\n" \
2837 " obj = instance[«object_path»]\n" \
2838 "\n" \
2839 "from which you can make proxy method calls like obj.«method»(«args») and so on."
2840
2841 if not isinstance(kind, INTERFACE) :
2842 raise TypeError("kind must be an INTERFACE enum value")
2843 #end if
2844 if not isinstance(introspected, Introspection.Interface) :
2845 raise TypeError("introspected must be an Introspection.Interface")
2846 #end if
2847
2848 class proxy(BusPeer.Object.ProxyInterface) :
2849 # class that will be constructed, to be instantiated for a given connection,
2850 # destination and path.
2851
2852 # class field _iface_name contains interface name.
2853 __slots__ = ("_parent", "_conn", "_dest", "_path", "_timeout")
2854
2855 def __init__(self, *, parent, connection, dest, path, timeout = DBUS.TIMEOUT_USE_DEFAULT) :
2856 if is_async :
2857 assert connection.loop != None, "no event loop to attach coroutines to"
2858 #end if
2859 self._parent = parent
2860 self._conn = connection
2861 self._dest = dest
2862 self._path = path
2863 self._timeout = timeout
2864 #end __init__
2865
2866 # rest filled in dynamically below.
2867
2868 #end proxy
2869
2870 def def_method(intr_method) :
2871 # constructs a method-call method.
2872
2873 if is_async :
2874
2875 async def call_method(self, *args, **kwargs) :
2876 message = dbus.Message.new_method_call \
2877 (
2878 destination = self._dest,
2879 path = dbus.unsplit_path(self._path),
2880 iface = self._iface_name,
2881 method = intr_method.name
2882 )
2883 _append_args(message, intr_method, args, kwargs)
2884 if intr_method.expect_reply :
2885 reply = await self._conn.send_await_reply(message, self._timeout)
2886 result = reply.expect_return_objects(intr_method.out_signature)
2887 else :
2888 message.no_reply = True
2889 self._conn.send(message)
2890 result = None
2891 #end if
2892 return \
2893 result
2894 #end call_method
2895
2896 else :
2897
2898 def call_method(self, *args, **kwargs) :
2899 message = dbus.Message.new_method_call \
2900 (
2901 destination = self._dest,
2902 path = dbus.unsplit_path(self._path),
2903 iface = self._iface_name,
2904 method = intr_method.name
2905 )
2906 _append_args(message, intr_method, args, kwargs)
2907 if intr_method.expect_reply :
2908 reply = self._conn.send_with_reply_and_block(message, self._timeout)
2909 result = reply.expect_return_objects(intr_method.out_signature)
2910 else :
2911 message.no_reply = True
2912 self._conn.send(message)
2913 result = None
2914 #end if
2915 return \
2916 result
2917 #end call_method
2918
2919 #end if
2920
2921 #begin def_method
2922 call_method.__name__ = intr_method.name
2923 call_method.__doc__ = \
2924 (
2925 "method, %(args)s, %(result)s"
2926 %
2927 {
2928 "args" :
2929 (
2930 lambda : "no args",
2931 lambda : "args %s" % dbus.unparse_signature(intr_method.in_signature),
2932 )[len(intr_method.in_signature) != 0](),
2933 "result" :
2934 (
2935 lambda : "no result",
2936 lambda : "result %s" % dbus.unparse_signature(intr_method.out_signature),
2937 )[len(intr_method.out_signature) != 0](),
2938 }
2939 )
2940 setattr(proxy, intr_method.name, call_method)
2941 #end def_method
2942
2943 def def_signal(intr_signal) :
2944 # constructs a signal method. These are never async, since messages
2945 # are queued and there is no reply.
2946
2947 def send_signal(self, *args, **kwargs) :
2948 message = dbus.Message.new_signal \
2949 (
2950 path = dbus.unsplit_path(self._path),
2951 iface = self._iface_name,
2952 name = intr_signal.name
2953 )
2954 _append_args(message, intr_signal, args, kwargs)
2955 self._conn.send(message)
2956 #end send_signal
2957
2958 #begin def_signal
2959 send_signal.__name__ = intr_signal.name
2960 send_signal.__doc__ = \
2961 (
2962 "signal, %(args)s"
2963 %
2964 {
2965 "args" :
2966 (
2967 lambda : "no args",
2968 lambda : "args %s" % dbus.unparse_signature(intr_signal.in_signature),
2969 )[len(intr_signal.in_signature) != 0](),
2970 }
2971 )
2972 setattr(proxy, signal.name, send_signal)
2973 #end def_signal
2974
2975 def def_prop(intr_prop) :
2976 # defines getter and/or setter methods as appropriate for a property.
2977
2978 if is_async :
2979
2980 async def get_prop(self) :
2981 message = dbus.Message.new_method_call \
2982 (
2983 destination = self._dest,
2984 path = dbus.unsplit_path(self._path),
2985 iface = DBUS.INTERFACE_PROPERTIES,
2986 method = "Get"
2987 )
2988 message.append_objects("ss", self._iface_name, intr_prop.name)
2989 reply = await self._conn.send_await_reply(message, self._timeout)
2990 return \
2991 reply.expect_return_objects("v")[0][1]
2992 #end get_prop
2993
2994 def set_prop(self, value) :
2995 # Unfortunately, Python doesn’t (currently) allow “await”
2996 # on the LHS of an assignment. So to avoid holding up the
2997 # thread, I put a task on the event loop to watch over
2998 # the completion of the send. This means any error is
2999 # going to be reported asynchronously. C’est la vie.
3000 message = dbus.Message.new_method_call \
3001 (
3002 destination = self._dest,
3003 path = dbus.unsplit_path(self._path),
3004 iface = DBUS.INTERFACE_PROPERTIES,
3005 method = "Set"
3006 )
3007 message.append_objects("ssv", self._iface_name, intr_prop.name, (intr_prop.type, value))
3008 set_prop_pending = self._conn.loop.create_future()
3009 self._parent._set_prop_pending.append(set_prop_pending)
3010 pending = self._conn.send_with_reply(message, self._timeout)
3011 async def sendit() :
3012 reply = await pending.await_reply()
3013 self._parent._set_prop_pending.pop \
3014 (
3015 self._parent._set_prop_pending.index(set_prop_pending)
3016 )
3017 if reply.type == DBUS.MESSAGE_TYPE_METHOD_RETURN :
3018 set_prop_pending.set_result(reply)
3019 elif reply.type == DBUS.MESSAGE_TYPE_ERROR :
3020 failed = dbus.DBusError(reply.error_name, reply.expect_objects("s")[0])
3021 if self._parent._set_prop_failed == None :
3022 set_prop_pending.set_exception(failed)
3023 self._parent._set_prop_failed = set_prop_pending
3024 else :
3025 # don’t let failures pile up
3026 raise failed
3027 #end if
3028 else :
3029 raise ValueError("unexpected reply type %d" % reply.type)
3030 #end if
3031 #end sendit
3032
3033 self._conn.create_task(sendit())
3034 #end set_prop
3035
3036 else :
3037
3038 def get_prop(self) :
3039 message = dbus.Message.new_method_call \
3040 (
3041 destination = self._dest,
3042 path = dbus.unsplit_path(self._path),
3043 iface = DBUS.INTERFACE_PROPERTIES,
3044 method = "Get"
3045 )
3046 message.append_objects("ss", self._iface_name, intr_prop.name)
3047 reply = self._conn.send_with_reply_and_block(message, self._timeout)
3048 return \
3049 reply.expect_return_objects("v")[0][1]
3050 #end get_prop
3051
3052 def set_prop(self, value) :
3053 message = dbus.Message.new_method_call \
3054 (
3055 destination = self._dest,
3056 path = dbus.unsplit_path(self._path),
3057 iface = DBUS.INTERFACE_PROPERTIES,
3058 method = "Set"
3059 )
3060 message.append_objects("ssv", self._iface_name, intr_prop.name, (intr_prop.type, value))
3061 reply = self._conn.send_with_reply_and_block(message, self._timeout)
3062 if reply.type == DBUS.MESSAGE_TYPE_METHOD_RETURN :
3063 pass
3064 elif reply.type == DBUS.MESSAGE_TYPE_ERROR :
3065 raise dbus.DBusError(reply.error_name, reply.expect_objects("s")[0])
3066 else :
3067 raise ValueError("unexpected reply type %d" % reply.type)
3068 #end if
3069 #end set_prop
3070
3071 #end if
3072
3073 def get_prop_noaccess(self) :
3074 raise dbus.DbusError \
3075 (
3076 name = DBUS.ERROR_ACCESS_DENIED,
3077 message = "property “%s” cannot be read" % intro_prop.name
3078 )
3079 #end get_prop_noaccess
3080
3081 #begin def_prop
3082 if intr_prop.access == Introspection.ACCESS.WRITE :
3083 get_prop = get_prop_noaccess
3084 #end if
3085 if intr_prop.access == Introspection.ACCESS.READ :
3086 set_prop = None
3087 #end if
3088 prop = property(fget = get_prop, fset = set_prop)
3089 setattr(proxy, intr_prop.name, prop)
3090 #end def_prop
3091
3092 class proxy_factory(BusPeer.RootProxy) :
3093 # class that will be returned.
3094
3095 __slots__ = ("connection", "dest", "timeout", "_set_prop_pending", "_set_prop_failed")
3096 # class variables:
3097 # template -- = proxy class (set up above)
3098 # props -- dict of introspected.properties by name
3099
3100 def __init__(self, *, connection, dest, timeout = DBUS.TIMEOUT_USE_DEFAULT) :
3101 if is_async :
3102 assert connection.loop != None, "no event loop to attach coroutines to"
3103 #end if
3104 self.connection = connection
3105 self.dest = dest
3106 self.timeout = timeout
3107 if is_async :
3108 self._set_prop_pending = []
3109 else :
3110 self._set_prop_pending = None
3111 #end if
3112 self._set_prop_failed = None
3113 #end __init__
3114
3115 def __getitem__(self, path) :
3116 return \
3117 self.template \
3118 (
3119 parent = self,
3120 connection = self.connection,
3121 dest = self.dest,
3122 path = path,
3123 timeout = self.timeout
3124 )
3125 #end __getitem__
3126
3127 if is_async :
3128
3129 async def set_prop_flush(self) :
3130 "workaround for the fact that prop-setter has to queue a separate" \
3131 " asynchronous task; caller can await this coroutine to ensure that" \
3132 " all pending set-property calls have completed."
3133 if not is_async :
3134 raise RuntimeError("not without an event loop")
3135 #end if
3136 if self._set_prop_failed != None :
3137 set_prop_pending = [self._set_prop_failed]
3138 self._set_prop_failed = None
3139 else :
3140 set_prop_pending = self._set_prop_pending
3141 #end if
3142 if len(set_prop_pending) != 0 :
3143 done = (await self.connection.wait(set_prop_pending))[0]
3144 failed = list(e for f in done for e in (f.exception(),) if e != None)
3145 if len(failed) > 1 :
3146 raise RuntimeError \
3147 (
3148 "multiple failures to set properties: %s"
3149 %
3150 ", ".join(str(f) for f in failed)
3151 )
3152 elif len(failed) == 1 :
3153 raise failed[0]
3154 #end if
3155 #end if
3156 #end set_prop_flush
3157
3158 def set_prop(self, path, propname, newvalue) :
3159 "alternative way of asynchronously setting a new property value:" \
3160 " returns a Future that can be explicitly awaited."
3161 if propname not in self.props :
3162 raise dbus.DBusError \
3163 (
3164 DBUS.ERROR_UNKNOWN_PROPERTY,
3165 message = "no such property “%s”" % propname
3166 )
3167 #end if
3168 propdef = self.props[propname]
3169 if propdef.access == Introspection.ACCESS.READ :
3170 raise dbus.DBusError \
3171 (
3172 DBUS.ERROR_PROPERTY_READ_ONLY,
3173 message = "property “%s” cannot be written" % propdef.name
3174 )
3175 #end if
3176 message = dbus.Message.new_method_call \
3177 (
3178 destination = self.dest,
3179 path = dbus.unsplit_path(path),
3180 iface = DBUS.INTERFACE_PROPERTIES,
3181 method = "Set"
3182 )
3183 message.append_objects("ssv", self.template._iface_name, propname, (propdef.type, newvalue))
3184 set_prop_pending = self.connection.loop.create_future()
3185 pending = self.connection.send_with_reply(message, self.timeout)
3186 async def sendit() :
3187 reply = await pending.await_reply()
3188 if reply.type == DBUS.MESSAGE_TYPE_METHOD_RETURN :
3189 set_prop_pending.set_result(None)
3190 elif reply.type == DBUS.MESSAGE_TYPE_ERROR :
3191 set_prop_pending.set_exception \
3192 (
3193 dbus.DBusError(reply.error_name, reply.expect_objects("s")[0])
3194 )
3195 else :
3196 raise ValueError("unexpected reply type %d" % reply.type)
3197 #end if
3198 #end sendit
3199 self.connection.create_task(sendit())
3200 return \
3201 set_prop_pending
3202 #end set_prop
3203
3204 #end if
3205
3206 #end proxy_factory
3207
3208 #begin def_proxy_interface
3209 if name != None :
3210 class_name = name
3211 else :
3212 class_name = introspected.name.replace(".", "_")
3213 #end if
3214 proxy.__name__ = class_name
3215 proxy._iface_name = introspected.name
3216 proxy.__doc__ = "for making method calls on the %s interface." % introspected.name
3217 if kind != INTERFACE.SERVER :
3218 for method in introspected.methods :
3219 def_method(method)
3220 #end for
3221 for prop in introspected.properties :
3222 def_prop(prop)
3223 #end for
3224 #end if
3225 if kind != INTERFACE.CLIENT :
3226 for signal in introspected.signals :
3227 def_signal(signal)
3228 #end for
3229 #end if
3230 proxy_factory.__name__ = "%s_factory" % proxy.__name__
3231 proxy_factory.__doc__ = \
3232 (
3233 "proxy factory for a %(kind)s D-Bus interface named %(iname)s. Instantiate as\n"
3234 "\n"
3235 " %(cname)s(connection = «connection»[, dest = «dest»[, timeout = «timeout»]])\n"
3236 "\n"
3237 "where «connection» is the dbussy.Connection instance to use for sending"
3238 " messages and receiving replies, and «dest» is the destination" \
3239 " bus name for sending method calls (not needed if only sending signals)."
3240 " The resulting «proxy» object can be indexed by object path, as follows:\n"
3241 "\n"
3242 " «proxy»[«path»]\n"
3243 "\n"
3244 "to obtain the actual proxy interface object that can be used to do method"
3245 " calls or signal calls."
3246 %
3247 {
3248 "cname" : class_name,
3249 "iname" : introspected.name,
3250 "kind" :
3251 {
3252 INTERFACE.CLIENT : "client-side",
3253 INTERFACE.SERVER : "server-side",
3254 INTERFACE.CLIENT_AND_SERVER : "client-and-server-side",
3255 }[kind]
3256 }
3257 )
3258 proxy_factory.template = proxy
3259 proxy_factory.props = dict \
3260 (
3261 (prop.name, prop)
3262 for prop in introspected.properties
3263 )
3264 return \
3265 proxy_factory
3266 #end def_proxy_interface
3267
3268 async def set_prop_flush(iface) :
3269 "iface must be either a BusPeer.RootProxy or BusPeer.Object.ProxyInterface" \
3270 " instance; calls the set_prop_flush() method on the correct root proxy in" \
3271 " either case."
3272 if isinstance(iface, BusPeer.RootProxy) :
3273 await iface.set_prop_flush()
3274 elif isinstance(iface, BusPeer.Object.ProxyInterface) :
3275 await iface._parent.set_prop_flush()
3276 else :
3277 raise TypeError("iface type %s is not a RootProxy or a ProxyInterface" % type(iface).__name__)
3278 #end if
3279 #end set_prop_flush
3280
3281 #+
3282 # Predefined interfaces
3283 #-
3284
3285 @interface(INTERFACE.CLIENT_AND_SERVER, name = DBUS.INTERFACE_PEER)
3286 class PeerStub :
3287 "This is registered as a fallback at the root of your object tree to get" \
3288 " automatic introspection of the DBUS.INTERFACE_PEER interface. The" \
3289 " implementation is hard-coded inside libdbus itself, so the methods" \
3290 " here will never be called."
3291
3292 @method \
3293 (
3294 name = "Ping",
3295 in_signature = "",
3296 out_signature = "",
3297 )
3298 def ping(self) :
3299 raise NotImplementedError("How did you get here?")
3300 #end ping
3301
3302 @method \
3303 (
3304 name = "GetMachineId",
3305 in_signature = "",
3306 out_signature = "s",
3307 result_keys = ["machine_uuid"],
3308 )
3309 def get_machine_id(self) :
3310 raise NotImplementedError("How did you get here?")
3311 #end get_machine_id
3312
3313 #end PeerStub
3314
3315 @interface(INTERFACE.CLIENT_AND_SERVER, name = DBUS.INTERFACE_INTROSPECTABLE)
3316 class IntrospectionHandler :
3317 "Register this as a fallback at the root of your object tree to obtain" \
3318 " automatic introspection of any point in the tree."
3319
3320 @method \
3321 (
3322 name = "Introspect",
3323 in_signature = "",
3324 out_signature = "s",
3325 path_keyword = "path",
3326 message_keyword = "message",
3327 bus_keyword = "bus",
3328 )
3329 def introspect(self, message, bus, path) :
3330 interfaces = {}
3331 children = None # actually redundant
3332 level = bus._server_dispatch
3333 levels = iter(dbus.split_path(path))
3334 while True :
3335 component = next(levels, None)
3336 for entry in level.interfaces.values() :
3337 if component == None or entry.fallback :
3338 interface = type(entry.interface)
3339 if interface._interface_kind != INTERFACE.CLIENT :
3340 interfaces[interface._interface_name] = interface
3341 # replace any higher-level entry for same name
3342 #end if
3343 #end if
3344 #end for
3345 if (
3346 component == None
3347 # reached bottom of path
3348 or
3349 component not in level.children
3350 # no handlers to be found further down path
3351 ) :
3352 children = sorted(level.children.keys())
3353 break
3354 #end if
3355 level = level.children[component]
3356 # search another step down the path
3357 #end while
3358 introspection = Introspection \
3359 (
3360 interfaces = list
3361 (
3362 introspect(iface)
3363 for iface in sorted(interfaces.values(), key = lambda iface : iface._interface_name)
3364 ),
3365 nodes = list
3366 (
3367 Introspection.Node(name = child) for child in children
3368 )
3369 )
3370 _send_method_return(bus.connection, message, "s", [introspection.unparse()])
3371 return \
3372 DBUS.HANDLER_RESULT_HANDLED
3373 #end introspect
3374
3375 #end IntrospectionHandler
3376
3377 @interface(INTERFACE.CLIENT_AND_SERVER, name = DBUS.INTERFACE_PROPERTIES)
3378 class PropertyHandler :
3379 "Register this as a fallback at the root of your object tree to provide" \
3380 " automatic dispatching to any @propgetter() and @propsetter() methods" \
3381 " defined for registered interfaces appropriate to an object path."
3382
3383 @method \
3384 (
3385 name = "Get",
3386 in_signature = "ss",
3387 out_signature = "v",
3388 args_keyword = "args",
3389 path_keyword = "path",
3390 message_keyword = "message",
3391 bus_keyword = "bus"
3392 )
3393 def getprop(self, bus, message, path, args) :
3394 interface_name, propname = args
3395 dispatch = bus.get_dispatch_interface(path, interface_name)
3396 props = type(dispatch)._interface_props
3397 if propname in props :
3398 propentry = props[propname]
3399 if "getter" in propentry :
3400 getter = getattr(dispatch, propentry["getter"].__name__)
3401 kwargs = {}
3402 for keyword_keyword, value in \
3403 (
3404 ("name_keyword", lambda : propname),
3405 ("connection_keyword", lambda : bus.connection),
3406 ("message_keyword", lambda : message),
3407 ("path_keyword", lambda : path),
3408 ("bus_keyword", lambda : bus),
3409 ) \
3410 :
3411 if getter._propgetter_info[keyword_keyword] != None :
3412 kwargs[getter._propgetter_info[keyword_keyword]] = value()
3413 #end if
3414 #end for
3415 try :
3416 propvalue = getter(**kwargs)
3417 except ErrorReturn as err :
3418 propvalue = err.as_error()
3419 #end try
3420 if asyncio.iscoroutine(propvalue) :
3421 assert bus.loop != None, "no event loop to attach coroutine to"
3422 async def await_return_value(task) :
3423 try :
3424 propvalue = await task
3425 except ErrorReturn as err :
3426 result = err.as_error()
3427 reply = message.new_error(result.name, result.message)
3428 bus.connection.send(reply)
3429 else :
3430 _send_method_return \
3431 (
3432 connection = bus.connection,
3433 message = message,
3434 sig = [dbus.VariantType()],
3435 args = [(propentry["type"], propvalue)]
3436 )
3437 #end try
3438 #end await_return_value
3439 bus.create_task(await_return_value(propvalue))
3440 reply = None
3441 elif isinstance(propvalue, dbus.Error) :
3442 assert propvalue.is_set, "unset Error object returned from propgetter"
3443 reply = message.new_error(propvalue.name, propvalue.nessage)
3444 else :
3445 _send_method_return \
3446 (
3447 connection = bus.connection,
3448 message = message,
3449 sig = [dbus.VariantType()],
3450 args = [(propentry["type"], propvalue)]
3451 )
3452 reply = None
3453 #end if
3454 else :
3455 reply = message.new_error \
3456 (
3457 name = DBUS.ERROR_ACCESS_DENIED,
3458 message = "property “%s” cannot be read" % propname
3459 )
3460 #end if
3461 else :
3462 reply = message.new_error \
3463 (
3464 name = DBUS.ERROR_UNKNOWN_PROPERTY,
3465 message = "property “%s” cannot be found" % propname
3466 )
3467 #end if
3468 if reply != None :
3469 bus.connection.send(reply)
3470 #end if
3471 return \
3472 DBUS.HANDLER_RESULT_HANDLED
3473 #end getprop
3474
3475 @method \
3476 (
3477 name = "Set",
3478 in_signature = "ssv",
3479 out_signature = "",
3480 args_keyword = "args",
3481 path_keyword = "path",
3482 message_keyword = "message",
3483 bus_keyword = "bus"
3484 )
3485 def setprop(self, bus, message, path, args) :
3486
3487 def notify_changed() :
3488 # sends property-changed signal if appropriate.
3489 if "getter" in propentry :
3490 notify = propentry["change_notification"]
3491 if notify == Introspection.PROP_CHANGE_NOTIFICATION.NEW_VALUE :
3492 bus.prop_changed(path, interface_name, propname, proptype, propvalue)
3493 elif notify == Introspection.PROP_CHANGE_NOTIFICATION.INVALIDATES :
3494 bus.prop_changed(path, interface_name, propname, None, None)
3495 #end if
3496 #end if
3497 #end notify_changed
3498
3499 #begin setprop
3500 interface_name, propname, (proptype, propvalue) = args
3501 dispatch = bus.get_dispatch_interface(path, interface_name)
3502 props = type(dispatch)._interface_props
3503 if propname in props :
3504 propentry = props[propname]
3505 if "setter" in propentry :
3506 setter = getattr(dispatch, propentry["setter"].__name__)
3507 try :
3508 if propentry["type"] != None and propentry["type"] != dbus.parse_single_signature(proptype) :
3509 raise ErrorReturn \
3510 (
3511 name = DBUS.ERROR_INVALID_ARGS,
3512 message =
3513 "new property type %s does not match expected signature %s"
3514 %
3515 (proptype, dbus.unparse_signature(propentry["type"]))
3516 )
3517 #end if
3518 kwargs = {}
3519 for keyword_keyword, value in \
3520 (
3521 ("name_keyword", lambda : propname),
3522 ("type_keyword", lambda : proptype),
3523 ("value_keyword", lambda : propvalue),
3524 ("connection_keyword", lambda : bus.connection),
3525 ("message_keyword", lambda : message),
3526 ("path_keyword", lambda : path),
3527 ("bus_keyword", lambda : bus),
3528 ) \
3529 :
3530 if setter._propsetter_info[keyword_keyword] != None :
3531 kwargs[setter._propsetter_info[keyword_keyword]] = value()
3532 #end if
3533 #end for
3534 setresult = setter(**kwargs)
3535 except ErrorReturn as err :
3536 setresult = err.as_error()
3537 #end try
3538 if asyncio.iscoroutine(setresult) :
3539 assert bus.loop != None, "no event loop to attach coroutine to"
3540 async def wait_set_done() :
3541 await setresult
3542 reply = message.new_method_return()
3543 bus.connection.send(reply)
3544 notify_changed()
3545 #end wait_set_done
3546 bus.create_task(wait_set_done())
3547 reply = None # for now
3548 elif isinstance(setresult, dbus.Error) :
3549 assert setresult.is_set, "unset Error object returned"
3550 reply = message.new_error(setresult.name, setresult.message)
3551 elif setresult == None :
3552 reply = message.new_method_return()
3553 notify_changed()
3554 else :
3555 raise ValueError("invalid propsetter result %s" % repr(setresult))
3556 #end if
3557 else :
3558 reply = message.new_error \
3559 (
3560 name = DBUS.ERROR_PROPERTY_READ_ONLY,
3561 message = "property “%s” cannot be written" % propname
3562 )
3563 #end if
3564 else :
3565 reply = message.new_error \
3566 (
3567 name = DBUS.ERROR_UNKNOWN_PROPERTY,
3568 message = "property “%s” cannot be found" % propname
3569 )
3570 #end if
3571 if reply != None :
3572 bus.connection.send(reply)
3573 #end if
3574 return \
3575 DBUS.HANDLER_RESULT_HANDLED
3576 #end setprop
3577
3578 @method \
3579 (
3580 name = "GetAll",
3581 in_signature = "s",
3582 out_signature = "a{sv}",
3583 args_keyword = "args",
3584 path_keyword = "path",
3585 message_keyword = "message",
3586 bus_keyword = "bus"
3587 )
3588 def get_all_props(self, bus, message, path, args) :
3589
3590 properror = None
3591 propvalues = {}
3592 to_await = []
3593
3594 def return_result() :
3595 if properror != None :
3596 reply = message.new_error(properror.name, properror.message)
3597 bus.connection.send(reply)
3598 else :
3599 _send_method_return(bus.connection, message, "a{sv}", [propvalues])
3600 #end if
3601 #end return_result
3602
3603 async def await_propvalues() :
3604 nonlocal properror
3605 for propname, fute in to_await :
3606 try :
3607 propvalue = await fute
3608 except ErrorReturn as err :
3609 properror = err.as_error()
3610 break
3611 #end try
3612 propvalues[propname] = (propvalues[propname][0], propvalue)
3613 #end for
3614 return_result()
3615 #end await_propvalues
3616
3617 #begin get_all_props
3618 interface_name, = args
3619 try :
3620 propvalues, to_await = bus._get_all_my_props(message, path, interface_name)
3621 except ErrorReturn as err :
3622 properror = err.as_error()
3623 #end try
3624 if len(to_await) != 0 :
3625 bus.create_task(await_propvalues())
3626 else :
3627 return_result()
3628 #end if
3629 return \
3630 DBUS.HANDLER_RESULT_HANDLED
3631 #end get_all_props
3632
3633 @signal(name = "PropertiesChanged", in_signature = "sa{sv}as", stub = True)
3634 def properties_changed(self) :
3635 "for use with Connection.send_signal."
3636 pass
3637 #end properties_changed
3638
3639 #end PropertyHandler
3640
3641 @interface(INTERFACE.CLIENT_AND_SERVER, name = DBUSX.INTERFACE_OBJECT_MANAGER)
3642 class ManagedObjectsHandler :
3643 "Register this as a fallback at the root of your object tree to provide" \
3644 " handling of the ObjectManager interface."
3645
3646 @method \
3647 (
3648 name = "GetManagedObjects",
3649 in_signature = "",
3650 out_signature = "a{oa{sa{sv}}}",
3651 set_result_keyword = "set_result",
3652 bus_keyword = "bus",
3653 message_keyword = "message",
3654 path_keyword = "base_path",
3655 )
3656 def get_managed_objects(self, bus, message, base_path, set_result) :
3657
3658 result = {}
3659 to_await = []
3660
3661 async def await_propvalues() :
3662 for path, interface_name, propname, fute in to_await :
3663 propvalue = await fute
3664 # any ErrorReturn raised will be automatically converted
3665 # to error reply by _message_interface_dispatch (above)
3666 propvalues = result[path][interface_name]
3667 propvalues[propname] = (propvalues[propname][0], propvalue)
3668 #end for
3669 set_result([result])
3670 #end await_propvalues
3671
3672 #begin get_managed_objects
3673 "returns supported interfaces and current property values for all" \
3674 " currently-existent managed objects."
3675 for path, interfaces in bus._managed_objects.items() :
3676 if base_path == "/" and path != "/" or path.startswith(base_path + "/") :
3677 obj_entry = {}
3678 for interface_name in interfaces :
3679 obj_entry[interface_name], await_props = \
3680 bus._get_all_my_props(message, path, interface_name)
3681 for propname, propvalue in await_props :
3682 to_await.append((path, interface_name, propname, propvalue))
3683 #end for
3684 #end for
3685 result[path] = obj_entry
3686 #end if
3687 #end for
3688 if len(to_await) != 0 :
3689 return_result = await_propvalues() # result will be available when this is done
3690 else :
3691 set_result([result])
3692 return_result = None
3693 #end if
3694 return \
3695 return_result
3696 #end get_managed_objects
3697
3698 @signal(name = "InterfacesAdded", in_signature = "oa{sa{sv}}", stub = True)
3699 def interfaces_added(self) :
3700 "for use with Connection.send_signal."
3701 pass
3702 #end interfaces_added
3703
3704 @signal(name = "InterfacesRemoved", in_signature = "oas", stub = True)
3705 def interfaces_removed(self) :
3706 "for use with Connection.send_signal."
3707 pass
3708 #end interfaces_removed
3709
3710 #end ManagedObjectsHandler
3711
3712 #+
3713 # Cleanup
3714 #-
3715
3716 def _atexit() :
3717 # disable all __del__ methods at process termination to avoid unpredictable behaviour
3718 for cls in Connection, Server :
3719 delattr(cls, "__del__")
3720 #end for
3721 #end _atexit
3722 atexit.register(_atexit)
3723 del _atexit