Debian Codegraph @

dbussy.py

raw symbols SCIP
1 """
2 Pure-Python binding for D-Bus <https://www.freedesktop.org/wiki/Software/dbus/>,
3 built around libdbus <https://dbus.freedesktop.org/doc/api/html/index.html>.
4
5 This Python binding supports hooking into event loops via Python’s standard
6 asyncio module.
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 os
14 import builtins
15 import operator
16 import array
17 import enum
18 import ctypes as ct
19 from weakref import \
20 ref as weak_ref, \
21 WeakValueDictionary
22 import threading
23 import io
24 import atexit
25 import asyncio
26 import functools
27 from xml.etree import \
28 ElementTree as XMLElementTree
29 from xml.sax.saxutils import \
30 quoteattr as quote_xml_attr
31
32 dbus = ct.cdll.LoadLibrary("libdbus-1.so.3")
33
34 class DBUS :
35 "useful definitions adapted from the D-Bus includes. You will need to use the" \
36 " constants, but apart from that, see the more Pythonic wrappers defined outside" \
37 " this class in preference to accessing low-level structures directly."
38
39 # General ctypes gotcha: when passing addresses of ctypes-constructed objects
40 # to routine calls, do not construct the objects directly in the call. Otherwise
41 # the refcount goes to 0 before the routine is actually entered, and the object
42 # can get prematurely disposed. Always store the object reference into a local
43 # variable, and pass the value of the variable instead.
44
45 # from dbus-protocol.h:
46
47 # Message byte order
48 LITTLE_ENDIAN = 'l'
49 BIG_ENDIAN = 'B'
50
51 # Protocol version.
52 MAJOR_PROTOCOL_VERSION = 1
53
54 # Type code that is never equal to a legitimate type code
55 TYPE_INVALID = 0
56
57 # Primitive types
58 TYPE_BYTE = ord('y') # 8-bit unsigned integer
59 TYPE_BOOLEAN = ord('b') # boolean
60 TYPE_INT16 = ord('n') # 16-bit signed integer
61 TYPE_UINT16 = ord('q') # 16-bit unsigned integer
62 TYPE_INT32 = ord('i') # 32-bit signed integer
63 TYPE_UINT32 = ord('u') # 32-bit unsigned integer
64 TYPE_INT64 = ord('x') # 64-bit signed integer
65 TYPE_UINT64 = ord('t') # 64-bit unsigned integer
66 TYPE_DOUBLE = ord('d') # 8-byte double in IEEE 754 format
67 TYPE_STRING = ord('s') # UTF-8 encoded, nul-terminated Unicode string
68 TYPE_OBJECT_PATH = ord('o') # D-Bus object path
69 TYPE_SIGNATURE = ord('g') # D-Bus type signature
70 TYPE_UNIX_FD = ord('h') # unix file descriptor
71
72 basic_to_ctypes = \
73 { # ctypes objects suitable for holding values of D-Bus types
74 TYPE_BYTE : ct.c_ubyte,
75 TYPE_BOOLEAN : ct.c_ubyte,
76 TYPE_INT16 : ct.c_short,
77 TYPE_UINT16 : ct.c_ushort,
78 TYPE_INT32 : ct.c_int,
79 TYPE_UINT32 : ct.c_uint,
80 TYPE_INT64 : ct.c_longlong,
81 TYPE_UINT64 : ct.c_ulonglong,
82 TYPE_DOUBLE : ct.c_double,
83 TYPE_STRING : ct.c_char_p,
84 TYPE_OBJECT_PATH : ct.c_char_p,
85 TYPE_SIGNATURE : ct.c_char_p,
86 TYPE_UNIX_FD : ct.c_int,
87 }
88
89 def int_subtype(i, bits, signed) :
90 "returns integer i after checking that it fits in the given number of bits."
91 if not isinstance(i, int) :
92 raise TypeError("value is not int: %s" % repr(i))
93 #end if
94 if signed :
95 lo = - 1 << bits - 1
96 hi = (1 << bits - 1) - 1
97 else :
98 lo = 0
99 hi = (1 << bits) - 1
100 #end if
101 if i < lo or i > hi :
102 raise ValueError \
103 (
104 "%d not in range of %s %d-bit value" % (i, ("unsigned", "signed")[signed], bits)
105 )
106 #end if
107 return \
108 i
109 #end int_subtype
110
111 subtype_boolean = lambda i : DBUS.int_subtype(i, 1, False)
112 subtype_byte = lambda i : DBUS.int_subtype(i, 8, False)
113 subtype_int16 = lambda i : DBUS.int_subtype(i, 16, True)
114 subtype_uint16 = lambda i : DBUS.int_subtype(i, 16, False)
115 subtype_int32 = lambda i : DBUS.int_subtype(i, 32, True)
116 subtype_uint32 = lambda i : DBUS.int_subtype(i, 32, False)
117 subtype_int64 = lambda i : DBUS.int_subtype(i, 64, True)
118 subtype_uint64 = lambda i : DBUS.int_subtype(i, 64, False)
119
120 int_convert = \
121 { # range checks for the various D-Bus integer types
122 TYPE_BOOLEAN : subtype_boolean,
123 TYPE_BYTE : subtype_byte,
124 TYPE_INT16 : subtype_int16,
125 TYPE_UINT16 : subtype_uint16,
126 TYPE_INT32 : subtype_int32,
127 TYPE_UINT32 : subtype_uint32,
128 TYPE_INT64 : subtype_int64,
129 TYPE_UINT64 : subtype_uint64,
130 }
131
132 # subclasses for distinguishing various special kinds of D-Bus values:
133
134 class ObjectPath(str) :
135 "an object path string."
136
137 def __repr__(self) :
138 return \
139 "%s(%s)" % (self.__class__.__name__, super().__repr__())
140 #end __repr__
141
142 #end ObjectPath
143
144 class Signature(str) :
145 "a type-signature string."
146
147 def __repr__(self) :
148 return \
149 "%s(%s)" % (self.__class__.__name__, super().__repr__())
150 #end __repr__
151
152 #end Signature
153
154 class UnixFD(int) :
155 "a file-descriptor integer."
156
157 def __repr__(self) :
158 return \
159 "%s(%s)" % (self.__class__.__name__, super().__repr__())
160 #end __repr__
161
162 #end UnixFD
163
164 basic_subclasses = \
165 {
166 TYPE_BOOLEAN : bool,
167 TYPE_OBJECT_PATH : ObjectPath,
168 TYPE_SIGNATURE : Signature,
169 TYPE_UNIX_FD : UnixFD,
170 }
171
172 # Compound types
173 TYPE_ARRAY = ord('a') # D-Bus array type
174 TYPE_VARIANT = ord('v') # D-Bus variant type
175
176 TYPE_STRUCT = ord('r') # a struct; however, type signatures use STRUCT_BEGIN/END_CHAR
177 TYPE_DICT_ENTRY = ord('e') # a dict entry; however, type signatures use DICT_ENTRY_BEGIN/END_CHAR
178 NUMBER_OF_TYPES = 16 # does not include TYPE_INVALID or STRUCT/DICT_ENTRY_BEGIN/END_CHAR
179
180 # characters other than typecodes that appear in type signatures
181 STRUCT_BEGIN_CHAR = ord('(') # start of a struct type in a type signature
182 STRUCT_END_CHAR = ord(')') # end of a struct type in a type signature
183 DICT_ENTRY_BEGIN_CHAR = ord('{') # start of a dict entry type in a type signature
184 DICT_ENTRY_END_CHAR = ord('}') # end of a dict entry type in a type signature
185
186 MAXIMUM_NAME_LENGTH = 255 # max length in bytes of a bus name, interface or member (object paths are unlimited)
187
188 MAXIMUM_SIGNATURE_LENGTH = 255 # fits in a byte
189
190 MAXIMUM_MATCH_RULE_LENGTH = 1024
191
192 MAXIMUM_MATCH_RULE_ARG_NUMBER = 63
193
194 MAXIMUM_ARRAY_LENGTH = 67108864 # 2 * 26
195 MAXIMUM_ARRAY_LENGTH_BITS = 26 # to store the max array size
196
197 MAXIMUM_MESSAGE_LENGTH = MAXIMUM_ARRAY_LENGTH * 2
198 MAXIMUM_MESSAGE_LENGTH_BITS = 27
199
200 MAXIMUM_MESSAGE_UNIX_FDS = MAXIMUM_MESSAGE_LENGTH // 4 # FDs are at least 32 bits
201 MAXIMUM_MESSAGE_UNIX_FDS_BITS = MAXIMUM_MESSAGE_LENGTH_BITS - 2
202
203 MAXIMUM_TYPE_RECURSION_DEPTH = 32
204
205 # Types of message
206
207 MESSAGE_TYPE_INVALID = 0 # never a valid message type
208 MESSAGE_TYPE_METHOD_CALL = 1
209 MESSAGE_TYPE_METHOD_RETURN = 2
210 MESSAGE_TYPE_ERROR = 3
211 MESSAGE_TYPE_SIGNAL = 4
212
213 NUM_MESSAGE_TYPES = 5
214
215 # Header flags
216
217 HEADER_FLAG_NO_REPLY_EXPECTED = 0x1
218 HEADER_FLAG_NO_AUTO_START = 0x2
219 HEADER_FLAG_ALLOW_INTERACTIVE_AUTHORIZATION = 0x4
220
221 # Header fields
222
223 HEADER_FIELD_INVALID = 0
224 HEADER_FIELD_PATH = 1
225 HEADER_FIELD_INTERFACE = 2
226 HEADER_FIELD_MEMBER = 3
227 HEADER_FIELD_ERROR_NAME = 4
228 HEADER_FIELD_REPLY_SERIAL = 5
229 HEADER_FIELD_DESTINATION = 6
230 HEADER_FIELD_SENDER = 7
231 HEADER_FIELD_SIGNATURE = 8
232 HEADER_FIELD_UNIX_FDS = 9
233
234 HEADER_FIELD_LAST = HEADER_FIELD_UNIX_FDS
235
236 HEADER_SIGNATURE = bytes \
237 ((
238 TYPE_BYTE,
239 TYPE_BYTE,
240 TYPE_BYTE,
241 TYPE_BYTE,
242 TYPE_UINT32,
243 TYPE_UINT32,
244 TYPE_ARRAY,
245 STRUCT_BEGIN_CHAR,
246 TYPE_BYTE,
247 TYPE_VARIANT,
248 STRUCT_END_CHAR,
249 ))
250 MINIMUM_HEADER_SIZE = 16 # smallest header size that can occur (missing required fields, though)
251
252 # Errors
253 ERROR_FAILED = "org.freedesktop.DBus.Error.Failed" # generic error
254 ERROR_NO_MEMORY = "org.freedesktop.DBus.Error.NoMemory"
255 ERROR_SERVICE_UNKNOWN = "org.freedesktop.DBus.Error.ServiceUnknown"
256 ERROR_NAME_HAS_NO_OWNER = "org.freedesktop.DBus.Error.NameHasNoOwner"
257 ERROR_NO_REPLY = "org.freedesktop.DBus.Error.NoReply"
258 ERROR_IO_ERROR = "org.freedesktop.DBus.Error.IOError"
259 ERROR_BAD_ADDRESS = "org.freedesktop.DBus.Error.BadAddress"
260 ERROR_NOT_SUPPORTED = "org.freedesktop.DBus.Error.NotSupported"
261 ERROR_LIMITS_EXCEEDED = "org.freedesktop.DBus.Error.LimitsExceeded"
262 ERROR_ACCESS_DENIED = "org.freedesktop.DBus.Error.AccessDenied"
263 ERROR_AUTH_FAILED = "org.freedesktop.DBus.Error.AuthFailed"
264 ERROR_NO_SERVER = "org.freedesktop.DBus.Error.NoServer"
265 ERROR_TIMEOUT = "org.freedesktop.DBus.Error.Timeout"
266 ERROR_NO_NETWORK = "org.freedesktop.DBus.Error.NoNetwork"
267 ERROR_ADDRESS_IN_USE = "org.freedesktop.DBus.Error.AddressInUse"
268 ERROR_DISCONNECTED = "org.freedesktop.DBus.Error.Disconnected"
269 ERROR_INVALID_ARGS = "org.freedesktop.DBus.Error.InvalidArgs"
270 ERROR_FILE_NOT_FOUND = "org.freedesktop.DBus.Error.FileNotFound"
271 ERROR_FILE_EXISTS = "org.freedesktop.DBus.Error.FileExists"
272 ERROR_UNKNOWN_METHOD = "org.freedesktop.DBus.Error.UnknownMethod"
273 ERROR_UNKNOWN_OBJECT = "org.freedesktop.DBus.Error.UnknownObject"
274 ERROR_UNKNOWN_INTERFACE = "org.freedesktop.DBus.Error.UnknownInterface"
275 ERROR_UNKNOWN_PROPERTY = "org.freedesktop.DBus.Error.UnknownProperty"
276 ERROR_PROPERTY_READ_ONLY = "org.freedesktop.DBus.Error.PropertyReadOnly"
277 ERROR_TIMED_OUT = "org.freedesktop.DBus.Error.TimedOut"
278 ERROR_MATCH_RULE_NOT_FOUND = "org.freedesktop.DBus.Error.MatchRuleNotFound"
279 ERROR_MATCH_RULE_INVALID = "org.freedesktop.DBus.Error.MatchRuleInvalid"
280 ERROR_SPAWN_EXEC_FAILED = "org.freedesktop.DBus.Error.Spawn.ExecFailed"
281 ERROR_SPAWN_FORK_FAILED = "org.freedesktop.DBus.Error.Spawn.ForkFailed"
282 ERROR_SPAWN_CHILD_EXITED = "org.freedesktop.DBus.Error.Spawn.ChildExited"
283 ERROR_SPAWN_CHILD_SIGNALED = "org.freedesktop.DBus.Error.Spawn.ChildSignaled"
284 ERROR_SPAWN_FAILED = "org.freedesktop.DBus.Error.Spawn.Failed"
285 ERROR_SPAWN_SETUP_FAILED = "org.freedesktop.DBus.Error.Spawn.FailedToSetup"
286 ERROR_SPAWN_CONFIG_INVALID = "org.freedesktop.DBus.Error.Spawn.ConfigInvalid"
287 ERROR_SPAWN_SERVICE_INVALID = "org.freedesktop.DBus.Error.Spawn.ServiceNotValid"
288 ERROR_SPAWN_SERVICE_NOT_FOUND = "org.freedesktop.DBus.Error.Spawn.ServiceNotFound"
289 ERROR_SPAWN_PERMISSIONS_INVALID = "org.freedesktop.DBus.Error.Spawn.PermissionsInvalid"
290 ERROR_SPAWN_FILE_INVALID = "org.freedesktop.DBus.Error.Spawn.FileInvalid"
291 ERROR_SPAWN_NO_MEMORY = "org.freedesktop.DBus.Error.Spawn.NoMemory"
292 ERROR_UNIX_PROCESS_ID_UNKNOWN = "org.freedesktop.DBus.Error.UnixProcessIdUnknown"
293 ERROR_INVALID_SIGNATURE = "org.freedesktop.DBus.Error.InvalidSignature"
294 ERROR_INVALID_FILE_CONTENT = "org.freedesktop.DBus.Error.InvalidFileContent"
295 ERROR_SELINUX_SECURITY_CONTEXT_UNKNOWN = "org.freedesktop.DBus.Error.SELinuxSecurityContextUnknown"
296 ERROR_ADT_AUDIT_DATA_UNKNOWN = "org.freedesktop.DBus.Error.AdtAuditDataUnknown"
297 ERROR_OBJECT_PATH_IN_USE = "org.freedesktop.DBus.Error.ObjectPathInUse"
298 ERROR_INCONSISTENT_MESSAGE = "org.freedesktop.DBus.Error.InconsistentMessage"
299 ERROR_INTERACTIVE_AUTHORIZATION_REQUIRED = "org.freedesktop.DBus.Error.InteractiveAuthorizationRequired"
300
301 # XML introspection format
302 INTROSPECT_1_0_XML_NAMESPACE = "http://www.freedesktop.org/standards/dbus"
303 INTROSPECT_1_0_XML_PUBLIC_IDENTIFIER = "-//freedesktop//DTD D-BUS Object Introspection 1.0//EN"
304 INTROSPECT_1_0_XML_SYSTEM_IDENTIFIER = "http://www.freedesktop.org/standards/dbus/1.0/introspect.dtd"
305 INTROSPECT_1_0_XML_DOCTYPE_DECL_NODE = \
306 (
307 "<!DOCTYPE node PUBLIC \""
308 +
309 INTROSPECT_1_0_XML_PUBLIC_IDENTIFIER
310 +
311 "\"\n\"" + INTROSPECT_1_0_XML_SYSTEM_IDENTIFIER
312 +
313 "\">\n"
314 )
315
316 # from dbus-shared.h:
317
318 # well-known bus types
319 BusType = ct.c_uint
320 BUS_SESSION = 0
321 BUS_SYSTEM = 1
322 BUS_STARTER = 2
323
324 # results that a message handler can return
325 BusHandlerResult = ct.c_uint
326 HANDLER_RESULT_HANDLED = 0 # no need to try more handlers
327 HANDLER_RESULT_NOT_YET_HANDLED = 1 # see if other handlers want it
328 HANDLER_RESULT_NEED_MEMORY = 2 # try again later with more memory
329
330 # Bus names
331 SERVICE_DBUS = "org.freedesktop.DBus" # used to talk to the bus itself
332
333 # Paths
334 PATH_DBUS = "/org/freedesktop/DBus" # object path used to talk to the bus itself
335 PATH_LOCAL = "/org/freedesktop/DBus/Local" # path used in local/in-process-generated messages
336
337 # Interfaces
338 INTERFACE_DBUS = "org.freedesktop.DBus" # interface exported by the object with SERVICE_DBUS and PATH_DBUS
339 INTERFACE_MONITORING = "org.freedesktop.DBus.Monitoring" # monitoring interface exported by the dbus-daemon
340 INTERFACE_VERBOSE = "org.freedesktop.DBus.Verbose" # verbose interface exported by the dbus-daemon
341 INTERFACE_INTROSPECTABLE = "org.freedesktop.DBus.Introspectable" # interface supported by introspectable objects
342 INTERFACE_PROPERTIES = "org.freedesktop.DBus.Properties" # interface supported by objects with properties
343 INTERFACE_PEER = "org.freedesktop.DBus.Peer" # interface supported by most dbus peers
344 INTERFACE_LOCAL = "org.freedesktop.DBus.Local" # methods can only be invoked locally
345
346 # Owner flags for request_name
347 NAME_FLAG_ALLOW_REPLACEMENT = 0x1
348 NAME_FLAG_REPLACE_EXISTING = 0x2
349 NAME_FLAG_DO_NOT_QUEUE = 0x4
350
351 # Replies to request for a name
352 REQUEST_NAME_REPLY_PRIMARY_OWNER = 1
353 REQUEST_NAME_REPLY_IN_QUEUE = 2
354 REQUEST_NAME_REPLY_EXISTS = 3
355 REQUEST_NAME_REPLY_ALREADY_OWNER = 4
356
357 # Replies to releasing a name
358 RELEASE_NAME_REPLY_RELEASED = 1
359 RELEASE_NAME_REPLY_NON_EXISTENT = 2
360 RELEASE_NAME_REPLY_NOT_OWNER = 3
361
362 # Replies to service starts
363 START_REPLY_SUCCESS = 1
364 START_REPLY_ALREADY_RUNNING = 2
365
366 # from dbus-types.h:
367
368 bool_t = ct.c_uint
369
370 # from dbus-memory.h:
371
372 FreeFunction = ct.CFUNCTYPE(None, ct.c_void_p)
373
374 # from dbus-connection.h:
375
376 HandlerResult = ct.c_uint
377
378 class Error(ct.Structure) :
379 _fields_ = \
380 [
381 ("name", ct.c_char_p),
382 ("message", ct.c_char_p),
383 ("padding", 2 * ct.c_void_p),
384 ]
385 #end Error
386 ErrorPtr = ct.POINTER(Error)
387
388 WatchFlags = ct.c_uint
389 WATCH_READABLE = 1 << 0
390 WATCH_WRITABLE = 1 << 1
391 WATCH_ERROR = 1 << 2
392 WATCH_HANGUP = 1 << 3
393
394 DispatchStatus = ct.c_uint
395 DISPATCH_DATA_REMAINS = 0 # more data available
396 DISPATCH_COMPLETE = 1 # all available data has been processed
397 DISPATCH_NEED_MEMORY = 2 # not enough memory to continue
398
399 AddWatchFunction = ct.CFUNCTYPE(bool_t, ct.c_void_p, ct.c_void_p)
400 # add_watch(DBusWatch, user_data) returns success/failure
401 WatchToggledFunction = ct.CFUNCTYPE(None, ct.c_void_p, ct.c_void_p)
402 # watch_toggled(DBusWatch, user_data)
403 RemoveWatchFunction = ct.CFUNCTYPE(None, ct.c_void_p, ct.c_void_p)
404 # remove_watch(DBusWatch, user_data)
405
406 AddTimeoutFunction = ct.CFUNCTYPE(bool_t, ct.c_void_p, ct.c_void_p)
407 # add_timeout(DBusTimeout, user_data) returns success/failure
408 TimeoutToggledFunction = ct.CFUNCTYPE(None, ct.c_void_p, ct.c_void_p)
409 # timeout_toggled(DBusTimeout, user_data)
410 RemoveTimeoutFunction = ct.CFUNCTYPE(None, ct.c_void_p, ct.c_void_p)
411 # remove_timeout(DBusTimeout, user_data)
412
413 DispatchStatusFunction = ct.CFUNCTYPE(None, ct.c_void_p, ct.POINTER(DispatchStatus), ct.c_void_p)
414 # dispatch_status(DBusConnection, DBusDispatchStatus, user_data)
415 WakeupMainFunction = ct.CFUNCTYPE(None, ct.c_void_p)
416 # wakeup_main(user_data)
417
418 AllowUnixUserFunction = ct.CFUNCTYPE(bool_t, ct.c_void_p, ct.c_ulong, ct.c_void_p)
419 # allow_unix_user(DBusConnection, uid, user_data) returns success/failure
420 AllowWindowsUserFunction = ct.CFUNCTYPE(bool_t, ct.c_void_p, ct.c_void_p, ct.c_void_p)
421 # allow_windows_user(DBusConnection, user_sid, user_data)returns success/failure
422
423 PendingCallNotifyFunction = ct.CFUNCTYPE(None, ct.c_void_p, ct.c_void_p)
424 # notify(DBusPendingCall, user_data)
425
426 HandleMessageFunction = ct.CFUNCTYPE(HandlerResult, ct.c_void_p, ct.c_void_p, ct.c_void_p)
427 # handle_message(DBusConnection, DBusMessage, user_data)
428
429 ObjectPathUnregisterFunction = ct.CFUNCTYPE(None, ct.c_void_p, ct.c_void_p)
430 # unregister(DBusConnection, user_data)
431 ObjectPathMessageFunction = ct.CFUNCTYPE(HandlerResult, ct.c_void_p, ct.c_void_p, ct.c_void_p)
432 # handle_message(DBusConnection, DBusMessage, user_data)
433
434 class ObjectPathVTable(ct.Structure) :
435 pass
436 #end ObjectPathVTable
437 ObjectPathVTable._fields_ = \
438 [
439 ("unregister_function", ObjectPathUnregisterFunction),
440 ("message_function", ObjectPathMessageFunction),
441 ("internal_pad1", ct.CFUNCTYPE(None, ct.c_void_p)),
442 ("internal_pad2", ct.CFUNCTYPE(None, ct.c_void_p)),
443 ("internal_pad3", ct.CFUNCTYPE(None, ct.c_void_p)),
444 ("internal_pad4", ct.CFUNCTYPE(None, ct.c_void_p)),
445 ]
446 ObjectPathVTablePtr = ct.POINTER(ObjectPathVTable)
447
448 # from dbus-pending-call.h:
449 TIMEOUT_INFINITE = 0x7fffffff
450 TIMEOUT_USE_DEFAULT = -1
451
452 # from dbus-message.h:
453 class MessageIter(ct.Structure) :
454 "contains no public fields."
455 _fields_ = \
456 [
457 ("dummy1", ct.c_void_p),
458 ("dummy2", ct.c_void_p),
459 ("dummy3", ct.c_uint),
460 ("dummy4", ct.c_int),
461 ("dummy5", ct.c_int),
462 ("dummy6", ct.c_int),
463 ("dummy7", ct.c_int),
464 ("dummy8", ct.c_int),
465 ("dummy9", ct.c_int),
466 ("dummy10", ct.c_int),
467 ("dummy11", ct.c_int),
468 ("pad1", ct.c_int),
469 ("pad2", ct.c_void_p),
470 ("pad3", ct.c_void_p),
471 ]
472 #end MessageIter
473 MessageIterPtr = ct.POINTER(MessageIter)
474
475 # from dbus-server.h:
476 NewConnectionFunction = ct.CFUNCTYPE(None, ct.c_void_p, ct.c_void_p, ct.c_void_p)
477 # new_connection(DBusServer, DBusConnection, user_data)
478
479 # from dbus-signature.h:
480 class SignatureIter(ct.Structure) :
481 "contains no public fields."
482 _fields_ = \
483 [
484 ("dummy1", ct.c_void_p),
485 ("dummy2", ct.c_void_p),
486 ("dummy8", ct.c_uint),
487 ("dummy12", ct.c_int),
488 ("dummy17", ct.c_int),
489 ]
490 #end SignatureIter
491 SignatureIterPtr = ct.POINTER(SignatureIter)
492
493 #end DBUS
494
495 class DBUSX:
496 "additional definitions not part of the official interfaces"
497
498 DEFAULT_TIMEOUT = 25 # seconds, from dbus-connection-internal.h in libdbus source
499
500 # For reference implementation for how to connect to daemon,
501 # see libdbus sources, dbus/dbus-bus.c (internal_bus_get routine
502 # and stuff that it calls)
503
504 # environment variables used to find addresses of bus daemons
505 SESSION_BUS_ADDRESS_VAR = "DBUS_SESSION_BUS_ADDRESS"
506 SYSTEM_BUS_ADDRESS_VAR = "DBUS_SYSTEM_BUS_ADDRESS"
507 STARTER_BUS_ADDRESS_VAR = "DBUS_STARTER_ADDRESS"
508 STARTER_BUS_ADDRESS_TYPE = "DBUS_STARTER_BUS_TYPE"
509
510 # values for value of STARTER_BUS_ADDRESS_TYPE
511 # If cannot determine type, then default to session bus
512 BUS_TYPE_SESSION = "session"
513 BUS_TYPE_SYSTEM = "system"
514
515 SYSTEM_BUS_ADDRESS = "unix:path=/var/run/dbus/system_bus_socket"
516 # default system bus daemon address if value of SYSTEM_BUS_ADDRESS_VAR is not defined
517 SESSION_BUS_ADDRESS = "autolaunch:"
518 # default session bus daemon address if value of SESSION_BUS_ADDRESS_VAR is not defined
519
520 INTERFACE_OBJECT_MANAGER = "org.freedesktop.DBus.ObjectManager"
521 # no symbolic name for this in standard headers as yet
522
523 #end DBUSX
524
525 #+
526 # Useful stuff
527 #-
528
529 if hasattr(asyncio, "get_running_loop") :
530 # new in Python 3.7
531 get_running_loop = asyncio.get_running_loop
532 else :
533 # as long as I want to support pre-3.7...
534 get_running_loop = asyncio.get_event_loop
535 #end if
536
537 def get_event_loop() :
538 "Python docs indicate that asyncio.get_event_loop() is going away" \
539 " in its current form. But I still need to be able to attach objects" \
540 " to the default event loop from a non-coroutine context. So I" \
541 " reimplement its original semantics here."
542 return \
543 asyncio.get_event_loop_policy().get_event_loop()
544 #end get_event_loop
545
546 def _wderef(w_self, parent) :
547 self = w_self()
548 assert self != None, "%s has gone away" % parent
549 return \
550 self
551 #end _wderef
552
553 def call_async(func, funcargs = (), timeout = None, abort = None, loop = None) :
554 "invokes func on a separate temporary thread and returns a Future that" \
555 " can be used to wait for its completion and obtain its result. If timeout" \
556 " is not None, then waiters on the Future will get a TimeoutError exception" \
557 " if the function has not completed execution after that number of seconds." \
558 " This allows easy invocation of blocking I/O functions in an asyncio-" \
559 "compatible fashion. But note that the operation cannot be cancelled" \
560 " if the timeout elapses; instead, you can specify an abort callback" \
561 " which will be invoked with whatever result is eventually returned from" \
562 " func."
563
564 if loop == None :
565 loop = get_running_loop()
566 #end if
567
568 timeout_task = None
569
570 def func_done(ref_awaiting, result) :
571 awaiting = ref_awaiting()
572 if awaiting != None :
573 if not awaiting.done() :
574 awaiting.set_result(result)
575 if timeout_task != None :
576 timeout_task.cancel()
577 #end if
578 else :
579 if abort != None :
580 abort(result)
581 #end if
582 #end if
583 #end if
584 #end func_done
585
586 def do_func_timedout(ref_awaiting) :
587 awaiting = ref_awaiting()
588 if awaiting != None :
589 if not awaiting.done() :
590 awaiting.set_exception(TimeoutError())
591 # Python doesn’t give me any (easy) way to cancel the thread running the
592 # do_func() call, so just let it run to completion, whereupon func_done()
593 # will get rid of the result. Even if I could delete the thread, can I be sure
594 # that would clean up memory and OS/library resources properly?
595 #end if
596 #end if
597 #end do_func_timedout
598
599 def do_func(ref_awaiting) :
600 # makes the blocking call on a separate thread.
601 result = func(*funcargs)
602 # A Future is not itself threadsafe, but I can thread-safely
603 # run a callback on the main thread to set it.
604 loop.call_soon_threadsafe(func_done, ref_awaiting, result)
605 #end do_func
606
607 #begin call_async
608 awaiting = loop.create_future()
609 ref_awaiting = weak_ref(awaiting)
610 # weak ref to avoid circular refs with loop
611 subthread = threading.Thread(target = do_func, args = (ref_awaiting,), daemon = True)
612 subthread.start()
613 if timeout != None :
614 timeout_task = loop.call_later(timeout, do_func_timedout, ref_awaiting)
615 #end if
616 return \
617 awaiting
618 #end call_async
619
620 #+
621 # Higher-level interface to type system
622 #-
623
624 class TYPE(enum.Enum) :
625 "D-Bus type codes wrapped up in an enumeration."
626
627 BYTE = ord('y') # 8-bit unsigned integer
628 BOOLEAN = ord('b') # boolean
629 INT16 = ord('n') # 16-bit signed integer
630 UINT16 = ord('q') # 16-bit unsigned integer
631 INT32 = ord('i') # 32-bit signed integer
632 UINT32 = ord('u') # 32-bit unsigned integer
633 INT64 = ord('x') # 64-bit signed integer
634 UINT64 = ord('t') # 64-bit unsigned integer
635 DOUBLE = ord('d') # 8-byte double in IEEE 754 format
636 STRING = ord('s') # UTF-8 encoded, nul-terminated Unicode string
637 OBJECT_PATH = ord('o') # D-Bus object path
638 SIGNATURE = ord('g') # D-Bus type signature
639 UNIX_FD = ord('h') # unix file descriptor
640
641 ARRAY = ord('a') # array of elements all of same type, or possibly dict
642 STRUCT = ord('r') # sequence of elements of arbitrary types
643 VARIANT = ord('v') # a single element of dynamic type
644
645 @property
646 def is_basic(self) :
647 "does this code represent a basic (non-container) type."
648 return \
649 self.value in DBUS.basic_to_ctypes
650 #end is_basic
651
652 #end TYPE
653
654 class Type :
655 "base class for all Types. The “signature” property returns the fully-encoded" \
656 " signature string for the entire Type."
657
658 __slots__ = ("code",)
659
660 def __init__(self, code) :
661 if not isinstance(code, TYPE) :
662 raise TypeError("only TYPE.xxx values allowed")
663 #end if
664 self.code = code
665 #end __init__
666
667 @property
668 def signature(self) :
669 raise NotImplementedError("subclass forgot to override signature property")
670 #end signature
671
672 def __eq__(t1, t2) :
673 raise NotImplementedError("subclass forgot to override __eq__ method")
674 #end __eq__
675
676 def validate(self, val) :
677 "returns val if it is an acceptable value of this Type, else raises" \
678 " TypeError or ValueError."
679 raise NotImplementedError("subclass forgot to override validate method")
680 #end validate
681
682 def __repr__(self) :
683 return \
684 "%s(sig = %s)" % (type(self).__name__, repr(self.signature))
685 #end __repr__
686
687 #end Type
688
689 class BasicType(Type) :
690 "a basic (non-container) type."
691
692 __slots__ = ()
693
694 def __init__(self, code) :
695 if not isinstance(code, TYPE) or not code.is_basic :
696 raise TypeError("only basic TYPE.xxx values allowed")
697 #end if
698 super().__init__(code)
699 #end __init__
700
701 def __repr__(self) :
702 return \
703 "%s(%s)" % (type(self).__name__, repr(self.code))
704 #end __repr__
705
706 @property
707 def signature(self) :
708 return \
709 chr(self.code.value)
710 #end signature
711
712 def __eq__(t1, t2) :
713 return \
714 isinstance(t2, BasicType) and t1.code == t2.code
715 #end __eq__
716
717 def validate(self, val) :
718 if self.code.value in DBUS.int_convert :
719 val = DBUS.int_convert[self.code.value](val)
720 elif self.code == TYPE.DOUBLE :
721 if not isinstance(val, float) :
722 raise TypeError("expecting a float, not %s: %s" % (type(val).__name__, repr(val)))
723 #end if
724 elif self.code == TYPE.UNIX_FD :
725 val = DBUS.subtype_uint32(val)
726 elif DBUS.basic_to_ctypes[self.code.value] == ct.c_char_p :
727 if not isinstance(val, str) :
728 raise TypeError("expecting a string, not %s: %s" % (type(val).__name__, repr(val)))
729 #end if
730 else :
731 raise RuntimeError("unknown basic type %s" % repr(self.code))
732 #end if
733 return \
734 val
735 #end validate
736
737 #end BasicType
738
739 class VariantType(Type) :
740 "the variant type--a single element of a type determined at run-time."
741
742 def __init__(self) :
743 super().__init__(TYPE.VARIANT)
744 #end __init__
745
746 @property
747 def signature(self) :
748 return \
749 chr(TYPE.VARIANT.value)
750 #end signature
751
752 def __repr__(self) :
753 return \
754 "%s()" % type(self).__name__
755 #end __repr__
756
757 def __eq__(t1, t2) :
758 return \
759 isinstance(t2, VariantType)
760 #end __eq__
761
762 def validate(self, val) :
763 if not isinstance(val, (tuple, list)) or len(val) != 2 :
764 raise ValueError("expecting a (type, value) pair")
765 #end if
766 valtype, val = val
767 valtype = parse_single_signature(valtype)
768 return \
769 (valtype, valtype.validate(val))
770 #end validate
771
772 #end VariantType
773
774 class StructType(Type) :
775 "a sequence of one or more arbitrary types (empty structs are not allowed)."
776
777 __slots__ = ("elttypes",)
778
779 def __init__(self, *types) :
780 if len(types) == 0 :
781 raise TypeError("must have at least one element type")
782 #end if
783 if not all(isinstance(t, Type) for t in types) :
784 raise TypeError("struct elements must be Types")
785 #end if
786 super().__init__(TYPE.STRUCT)
787 self.elttypes = tuple(types)
788 #end __init__
789
790 def __repr__(self) :
791 return \
792 "%s(%s)" % (type(self).__name__, repr(self.elttypes))
793 #end __repr__
794
795 @property
796 def signature(self) :
797 return \
798 "(%s)" % "".join(t.signature for t in self.elttypes)
799 #end signature
800
801 def __eq__(t1, t2) :
802 return \
803 (
804 isinstance(t2, StructType)
805 and
806 len(t1.elttypes) == len(t2.elttypes)
807 and
808 all(e1 == e2 for e1, e2 in zip(t1.elttypes, t2.elttypes))
809 )
810 #end __eq__
811
812 def validate(self, val) :
813 if not isinstance(val, (tuple, list)) or len(val) != len(self.elttypes) :
814 raise TypeError \
815 (
816 "need a list or tuple of %d elements, not %s" % (len(self.elttypes), repr(val))
817 )
818 #end if
819 return \
820 type(val)(elttype.validate(elt) for elttype, elt in zip(self.elttypes, val))
821 #end validate
822
823 #end StructType
824
825 class ArrayType(Type) :
826 "an array of zero or more elements all of the same type."
827
828 __slots__ = ("elttype",)
829
830 def __init__(self, elttype) :
831 if not isinstance(elttype, Type) :
832 raise TypeError("invalid array element type")
833 #end if
834 super().__init__(TYPE.ARRAY)
835 self.elttype = elttype
836 #end __init__
837
838 def __repr__(self) :
839 return \
840 "%s[%s]" % (type(self).__name__, repr(self.elttype))
841 #end __repr__
842
843 @property
844 def signature(self) :
845 return \
846 chr(TYPE.ARRAY.value) + self.elttype.signature
847 #end signature
848
849 def __eq__(t1, t2) :
850 return \
851 isinstance(t2, ArrayType) and t1.elttype == t2.elttype
852 #end __eq__
853
854 def validate(self, val) :
855 if not isinstance(val, (tuple, list)) :
856 raise TypeError("need a tuple or list, not %s: %s" % (type(val).__name__, repr(val)))
857 #end if
858 return \
859 type(val)(self.elttype.validate(elt) for elt in val)
860 #end validate
861
862 #end ArrayType
863
864 class DictType(Type) :
865 "a dictionary mapping zero or more keys to values."
866
867 __slots__ = ("keytype", "valuetype")
868
869 def __init__(self, keytype, valuetype) :
870 if not isinstance(keytype, BasicType) or not isinstance(valuetype, Type) :
871 raise TypeError("invalid dict key/value type")
872 #end if
873 super().__init__(TYPE.ARRAY)
874 self.keytype = keytype
875 self.valuetype = valuetype
876 #end keytype
877
878 def __repr__(self) :
879 return \
880 "%s[%s : %s]" % (type(self).__name__, repr(self.keytype), repr(self.valuetype))
881 #end __repr__
882
883 @property
884 def signature(self) :
885 return \
886 "%s{%s%s}" % (chr(TYPE.ARRAY.value), self.keytype.signature, self.valuetype.signature)
887 #end signature
888
889 @property
890 def entry_signature(self) :
891 "signature for a dict entry."
892 return \
893 "{%s%s}" % (self.keytype.signature, self.valuetype.signature)
894 #end entry_signature
895
896 def __eq__(t1, t2) :
897 return \
898 isinstance(t2, DictType) and t1.keytype == t2.keytype and t1.valuetype == t2.valuetype
899 #end __eq__
900
901 def validate(self, val) :
902 if not isinstance(val, dict) :
903 raise TypeError("need a dict, not %s: %s" % (type(val).__name__, repr(val)))
904 #end if
905 return \
906 type(val) \
907 (
908 (self.keytype.validate(key), self.valuetype.validate(val[key]))
909 for key in val
910 )
911 #end validate
912
913 #end DictType
914
915 def data_key(data) :
916 "returns a unique value that allows data to be used as a dict/set key."
917 if isinstance(data, (bytes, float, frozenset, int, str, tuple)) :
918 result = data
919 else :
920 # data itself is non-hashable
921 result = id(data)
922 #end if
923 return \
924 result
925 #end data_key
926
927 #+
928 # Library prototypes
929 #-
930
931 # from dbus-connection.h:
932 dbus.dbus_connection_open.restype = ct.c_void_p
933 dbus.dbus_connection_open.argtypes = (ct.c_char_p, DBUS.ErrorPtr)
934 dbus.dbus_connection_open_private.restype = ct.c_void_p
935 dbus.dbus_connection_open_private.argtypes = (ct.c_char_p, DBUS.ErrorPtr)
936 dbus.dbus_connection_ref.restype = ct.c_void_p
937 dbus.dbus_connection_ref.argtypes = (ct.c_void_p,)
938 dbus.dbus_connection_unref.restype = None
939 dbus.dbus_connection_unref.argtypes = (ct.c_void_p,)
940 dbus.dbus_connection_close.restype = None
941 dbus.dbus_connection_close.argtypes = (ct.c_void_p,)
942 dbus.dbus_connection_get_is_connected.restype = DBUS.bool_t
943 dbus.dbus_connection_get_is_connected.argtypes = (ct.c_void_p,)
944 dbus.dbus_connection_get_is_authenticated.restype = DBUS.bool_t
945 dbus.dbus_connection_get_is_authenticated.argtypes = (ct.c_void_p,)
946 dbus.dbus_connection_get_is_anonymous.restype = DBUS.bool_t
947 dbus.dbus_connection_get_is_anonymous.argtypes = (ct.c_void_p,)
948 dbus.dbus_connection_get_server_id.restype = ct.c_void_p
949 dbus.dbus_connection_get_server_id.argtypes = (ct.c_void_p,)
950 dbus.dbus_connection_can_send_type.restype = DBUS.bool_t
951 dbus.dbus_connection_can_send_type.argtypes = (ct.c_void_p, ct.c_int)
952 dbus.dbus_connection_set_exit_on_disconnect.restype = None
953 dbus.dbus_connection_set_exit_on_disconnect.argtypes = (ct.c_void_p, DBUS.bool_t)
954 dbus.dbus_connection_preallocate_send.restype = ct.c_void_p
955 dbus.dbus_connection_preallocate_send.argtypes = (ct.c_void_p,)
956 dbus.dbus_connection_free_preallocated_send.restype = None
957 dbus.dbus_connection_free_preallocated_send.argtypes = (ct.c_void_p, ct.c_void_p)
958 dbus.dbus_connection_send_preallocated.restype = None
959 dbus.dbus_connection_send_preallocated.argtypes = (ct.c_void_p, ct.c_void_p, ct.c_void_p, ct.POINTER(ct.c_uint))
960 dbus.dbus_connection_has_messages_to_send.restype = DBUS.bool_t
961 dbus.dbus_connection_has_messages_to_send.argtypes = (ct.c_void_p,)
962 dbus.dbus_connection_send.restype = DBUS.bool_t
963 dbus.dbus_connection_send.argtypes = (ct.c_void_p, ct.c_void_p, ct.POINTER(ct.c_uint))
964 dbus.dbus_connection_send_with_reply.restype = DBUS.bool_t
965 dbus.dbus_connection_send_with_reply.argtypes = (ct.c_void_p, ct.c_void_p, ct.c_void_p, ct.c_int)
966 dbus.dbus_connection_send_with_reply_and_block.restype = ct.c_void_p
967 dbus.dbus_connection_send_with_reply_and_block.argtypes = (ct.c_void_p, ct.c_void_p, ct.c_int, DBUS.ErrorPtr)
968 dbus.dbus_connection_flush.restype = None
969 dbus.dbus_connection_flush.argtypes = (ct.c_void_p,)
970 dbus.dbus_connection_read_write_dispatch.restype = DBUS.bool_t
971 dbus.dbus_connection_read_write_dispatch.argtypes = (ct.c_void_p, ct.c_int)
972 dbus.dbus_connection_read_write.restype = DBUS.bool_t
973 dbus.dbus_connection_read_write.argtypes = (ct.c_void_p, ct.c_int)
974 dbus.dbus_connection_borrow_message.restype = ct.c_void_p
975 dbus.dbus_connection_borrow_message.argtypes = (ct.c_void_p,)
976 dbus.dbus_connection_return_message.restype = None
977 dbus.dbus_connection_return_message.argtypes = (ct.c_void_p, ct.c_void_p)
978 dbus.dbus_connection_steal_borrowed_message.restype = None
979 dbus.dbus_connection_steal_borrowed_message.argtypes = (ct.c_void_p, ct.c_void_p)
980 dbus.dbus_connection_pop_message.restype = ct.c_void_p
981 dbus.dbus_connection_pop_message.argtypes = (ct.c_void_p,)
982 dbus.dbus_connection_get_dispatch_status.restype = ct.c_uint
983 dbus.dbus_connection_get_dispatch_status.argtypes = (ct.c_void_p,)
984 dbus.dbus_connection_dispatch.restype = ct.c_uint
985 dbus.dbus_connection_dispatch.argtypes = (ct.c_void_p,)
986 dbus.dbus_connection_set_watch_functions.restype = DBUS.bool_t
987 dbus.dbus_connection_set_watch_functions.argtypes = (ct.c_void_p, ct.c_void_p, ct.c_void_p, ct.c_void_p, ct.c_void_p, ct.c_void_p)
988 dbus.dbus_connection_set_timeout_functions.restype = DBUS.bool_t
989 dbus.dbus_connection_set_timeout_functions.argtypes = (ct.c_void_p, ct.c_void_p, ct.c_void_p, ct.c_void_p, ct.c_void_p, ct.c_void_p)
990 dbus.dbus_connection_set_wakeup_main_function.restype = None
991 dbus.dbus_connection_set_wakeup_main_function.argtypes = (ct.c_void_p, ct.c_void_p, ct.c_void_p, ct.c_void_p)
992 dbus.dbus_connection_set_dispatch_status_function.restype = None
993 dbus.dbus_connection_set_dispatch_status_function.argtypes = (ct.c_void_p, ct.c_void_p, ct.c_void_p, ct.c_void_p)
994 dbus.dbus_connection_get_unix_user.restype = DBUS.bool_t
995 dbus.dbus_connection_get_unix_user.argtypes = (ct.c_void_p, ct.POINTER(ct.c_ulong))
996 dbus.dbus_connection_get_unix_process_id.restype = DBUS.bool_t
997 dbus.dbus_connection_get_unix_process_id.argtypes = (ct.c_void_p, ct.POINTER(ct.c_ulong))
998 dbus.dbus_connection_get_adt_audit_session_data.restype = DBUS.bool_t
999 dbus.dbus_connection_get_adt_audit_session_data.argtypes = (ct.c_void_p, ct.c_void_p, ct.POINTER(ct.c_uint))
1000 dbus.dbus_connection_set_unix_user_function.restype = None
1001 dbus.dbus_connection_set_unix_user_function.argtypes = (ct.c_void_p, ct.c_void_p, ct.c_void_p, ct.c_void_p)
1002 dbus.dbus_connection_get_windows_user.restype = DBUS.bool_t
1003 dbus.dbus_connection_get_windows_user.argtypes = (ct.c_void_p, ct.c_void_p)
1004 dbus.dbus_connection_set_windows_user_function.restype = None
1005 dbus.dbus_connection_set_windows_user_function.argtypes = (ct.c_void_p, ct.c_void_p, ct.c_void_p, ct.c_void_p)
1006 dbus.dbus_connection_set_allow_anonymous.restype = None
1007 dbus.dbus_connection_set_allow_anonymous.argtypes = (ct.c_void_p, DBUS.bool_t)
1008 dbus.dbus_connection_set_route_peer_messages.restype = None
1009 dbus.dbus_connection_set_route_peer_messages.argtypes = (ct.c_void_p, DBUS.bool_t)
1010
1011 dbus.dbus_connection_add_filter.restype = DBUS.bool_t
1012 dbus.dbus_connection_add_filter.argtypes = (ct.c_void_p, ct.c_void_p, ct.c_void_p, ct.c_void_p)
1013 dbus.dbus_connection_remove_filter.restype = None
1014 dbus.dbus_connection_remove_filter.argtypes = (ct.c_void_p, ct.c_void_p, ct.c_void_p)
1015
1016 dbus.dbus_connection_allocate_data_slot.restype = DBUS.bool_t
1017 dbus.dbus_connection_allocate_data_slot.argtypes = (ct.POINTER(ct.c_uint),)
1018 dbus.dbus_connection_free_data_slot.restype = None
1019 dbus.dbus_connection_free_data_slot.argtypes = (ct.c_uint,)
1020 dbus.dbus_connection_set_data.restype = DBUS.bool_t
1021 dbus.dbus_connection_set_data.argtypes = (ct.c_void_p, ct.c_uint, ct.c_void_p, ct.c_void_p)
1022 dbus.dbus_connection_get_data.restype = ct.c_void_p
1023 dbus.dbus_connection_get_data.argtypes = (ct.c_void_p, ct.c_uint)
1024 dbus.dbus_connection_set_change_sigpipe.restype = None
1025 dbus.dbus_connection_set_change_sigpipe.argtypes = (DBUS.bool_t,)
1026 dbus.dbus_connection_set_max_message_size.restype = None
1027 dbus.dbus_connection_set_max_message_size.argtypes = (ct.c_void_p, ct.c_long)
1028 dbus.dbus_connection_get_max_message_size.restype = ct.c_long
1029 dbus.dbus_connection_get_max_message_size.argtypes = (ct.c_void_p,)
1030 dbus.dbus_connection_set_max_received_size.restype = None
1031 dbus.dbus_connection_set_max_received_size.argtypes = (ct.c_void_p, ct.c_long)
1032 dbus.dbus_connection_get_max_received_size.restype = ct.c_long
1033 dbus.dbus_connection_get_max_received_size.argtypes = (ct.c_void_p,)
1034 dbus.dbus_connection_set_max_message_unix_fds.restype = None
1035 dbus.dbus_connection_set_max_message_unix_fds.argtypes = (ct.c_void_p, ct.c_long)
1036 dbus.dbus_connection_get_max_message_unix_fds.restype = ct.c_long
1037 dbus.dbus_connection_get_max_message_unix_fds.argtypes = (ct.c_void_p,)
1038 dbus.dbus_connection_set_max_received_unix_fds.restype = None
1039 dbus.dbus_connection_set_max_received_unix_fds.argtypes = (ct.c_void_p, ct.c_long)
1040 dbus.dbus_connection_get_max_received_unix_fds.restype = ct.c_long
1041 dbus.dbus_connection_get_max_received_unix_fds.argtypes = (ct.c_void_p,)
1042
1043 dbus.dbus_connection_get_outgoing_size.restype = ct.c_long
1044 dbus.dbus_connection_get_outgoing_size.argtypes = (ct.c_void_p,)
1045 dbus.dbus_connection_get_outgoing_unix_fds.restype = ct.c_long
1046 dbus.dbus_connection_get_outgoing_unix_fds.argtypes = (ct.c_void_p,)
1047
1048 dbus.dbus_connection_register_object_path.restype = DBUS.bool_t
1049 dbus.dbus_connection_register_object_path.argtypes = (ct.c_void_p, ct.c_char_p, DBUS.ObjectPathVTablePtr, ct.c_void_p)
1050 dbus.dbus_connection_try_register_object_path.restype = DBUS.bool_t
1051 dbus.dbus_connection_try_register_object_path.argtypes = (ct.c_void_p, ct.c_char_p, DBUS.ObjectPathVTablePtr, ct.c_void_p, DBUS.ErrorPtr)
1052 dbus.dbus_connection_register_fallback.restype = DBUS.bool_t
1053 dbus.dbus_connection_register_fallback.argtypes = (ct.c_void_p, ct.c_char_p, DBUS.ObjectPathVTablePtr, ct.c_void_p)
1054 dbus.dbus_connection_try_register_fallback.restype = DBUS.bool_t
1055 dbus.dbus_connection_try_register_fallback.argtypes = (ct.c_void_p, ct.c_char_p, DBUS.ObjectPathVTablePtr, ct.c_void_p, DBUS.ErrorPtr)
1056 dbus.dbus_connection_get_object_path_data.restype = DBUS.bool_t
1057 dbus.dbus_connection_get_object_path_data.argtypes = (ct.c_void_p, ct.c_char_p, ct.c_void_p)
1058 dbus.dbus_connection_list_registered.restype = DBUS.bool_t
1059 dbus.dbus_connection_list_registered.argtypes = (ct.c_void_p, ct.c_char_p, ct.c_void_p)
1060 dbus.dbus_connection_get_unix_fd.restype = DBUS.bool_t
1061 dbus.dbus_connection_get_unix_fd.argtypes = (ct.c_void_p, ct.POINTER(ct.c_int))
1062 dbus.dbus_connection_get_socket.restype = DBUS.bool_t
1063 dbus.dbus_connection_get_socket.argtypes = (ct.c_void_p, ct.POINTER(ct.c_int))
1064 dbus.dbus_connection_unregister_object_path.restype = DBUS.bool_t
1065 dbus.dbus_connection_unregister_object_path.argtypes = (ct.c_void_p, ct.c_char_p)
1066
1067 dbus.dbus_watch_get_unix_fd.restype = ct.c_int
1068 dbus.dbus_watch_get_unix_fd.argtypes = (ct.c_void_p,)
1069 dbus.dbus_watch_get_socket.restype = ct.c_int
1070 dbus.dbus_watch_get_socket.argtypes = (ct.c_void_p,)
1071 dbus.dbus_watch_get_flags.restype = ct.c_uint
1072 dbus.dbus_watch_get_flags.argtypes = (ct.c_void_p,)
1073 dbus.dbus_watch_get_data.restype = ct.c_void_p
1074 dbus.dbus_watch_get_data.argtypes = (ct.c_void_p,)
1075 dbus.dbus_watch_set_data.restype = None
1076 dbus.dbus_watch_set_data.argtypes = (ct.c_void_p, ct.c_void_p, ct.c_void_p)
1077 dbus.dbus_watch_handle.restype = DBUS.bool_t
1078 dbus.dbus_watch_handle.argtypes = (ct.c_void_p, ct.c_uint)
1079 dbus.dbus_watch_get_enabled.restype = DBUS.bool_t
1080 dbus.dbus_watch_get_enabled.argtypes = (ct.c_void_p,)
1081
1082 dbus.dbus_timeout_get_interval.restype = ct.c_int
1083 dbus.dbus_timeout_get_interval.argtypes = (ct.c_void_p,)
1084 dbus.dbus_timeout_get_data.restype = ct.c_void_p
1085 dbus.dbus_timeout_get_data.argtypes = (ct.c_void_p,)
1086 dbus.dbus_timeout_set_data.restype = None
1087 dbus.dbus_timeout_set_data.argtypes = (ct.c_void_p, ct.c_void_p, ct.c_void_p)
1088 dbus.dbus_timeout_handle.restype = DBUS.bool_t
1089 dbus.dbus_timeout_handle.argtypes = (ct.c_void_p,)
1090 dbus.dbus_timeout_get_enabled.restype = DBUS.bool_t
1091 dbus.dbus_timeout_get_enabled.argtypes = (ct.c_void_p,)
1092
1093 # from dbus-bus.h:
1094 dbus.dbus_bus_get.restype = ct.c_void_p
1095 dbus.dbus_bus_get.argtypes = (ct.c_uint, DBUS.ErrorPtr)
1096 dbus.dbus_bus_get_private.restype = ct.c_void_p
1097 dbus.dbus_bus_get_private.argtypes = (ct.c_uint, DBUS.ErrorPtr)
1098 dbus.dbus_bus_register.restype = DBUS.bool_t
1099 dbus.dbus_bus_register.argtypes = (ct.c_void_p, DBUS.ErrorPtr)
1100 dbus.dbus_bus_set_unique_name.restype = DBUS.bool_t
1101 dbus.dbus_bus_set_unique_name.argtypes = (ct.c_void_p, ct.c_char_p)
1102 dbus.dbus_bus_get_unique_name.restype = ct.c_char_p
1103 dbus.dbus_bus_get_unique_name.argtypes = (ct.c_void_p,)
1104 dbus.dbus_bus_get_unix_user.restype = ct.c_ulong
1105 dbus.dbus_bus_get_unix_user.argtypes = (ct.c_void_p, ct.c_char_p, DBUS.ErrorPtr)
1106 dbus.dbus_bus_get_id.restype = ct.c_void_p
1107 dbus.dbus_bus_get_id.argtypes = (ct.c_void_p, DBUS.ErrorPtr)
1108 dbus.dbus_bus_request_name.restype = ct.c_int
1109 dbus.dbus_bus_request_name.argtypes = (ct.c_void_p, ct.c_char_p, ct.c_uint, DBUS.ErrorPtr)
1110 dbus.dbus_bus_release_name.restype = ct.c_int
1111 dbus.dbus_bus_release_name.argtypes = (ct.c_void_p, ct.c_char_p, DBUS.ErrorPtr)
1112 dbus.dbus_bus_name_has_owner.restype = DBUS.bool_t
1113 dbus.dbus_bus_name_has_owner.argtypes = (ct.c_void_p, ct.c_char_p, DBUS.ErrorPtr)
1114 dbus.dbus_bus_start_service_by_name.restype = DBUS.bool_t
1115 dbus.dbus_bus_start_service_by_name.argtypes = (ct.c_void_p, ct.c_char_p, ct.c_uint, ct.POINTER(ct.c_uint), DBUS.ErrorPtr)
1116 dbus.dbus_bus_add_match.restype = None
1117 dbus.dbus_bus_add_match.argtypes = (ct.c_void_p, ct.c_char_p, DBUS.ErrorPtr)
1118 dbus.dbus_bus_remove_match.restype = None
1119 dbus.dbus_bus_remove_match.argtypes = (ct.c_void_p, ct.c_char_p, DBUS.ErrorPtr)
1120
1121 dbus.dbus_error_init.restype = None
1122 dbus.dbus_error_init.argtypes = (DBUS.ErrorPtr,)
1123 dbus.dbus_error_free.restype = None
1124 dbus.dbus_error_free.argtypes = (DBUS.ErrorPtr,)
1125 dbus.dbus_move_error.restype = None
1126 dbus.dbus_move_error.argtypes = (DBUS.ErrorPtr, DBUS.ErrorPtr)
1127 dbus.dbus_error_has_name.restype = DBUS.bool_t
1128 dbus.dbus_error_has_name.argtypes = (DBUS.ErrorPtr, ct.c_char_p)
1129 dbus.dbus_error_is_set.restype = DBUS.bool_t
1130 dbus.dbus_error_is_set.argtypes = (DBUS.ErrorPtr,)
1131 dbus.dbus_set_error.restype = None
1132 dbus.dbus_set_error.argtypes = (DBUS.ErrorPtr, ct.c_char_p, ct.c_char_p, ct.c_char_p)
1133 # note I can’t handle varargs
1134
1135 # from dbus-pending-call.h:
1136 dbus.dbus_pending_call_ref.restype = ct.c_void_p
1137 dbus.dbus_pending_call_ref.argtypes = (ct.c_void_p,)
1138 dbus.dbus_pending_call_unref.restype = None
1139 dbus.dbus_pending_call_unref.argtypes = (ct.c_void_p,)
1140 dbus.dbus_pending_call_set_notify.restype = DBUS.bool_t
1141 dbus.dbus_pending_call_set_notify.argtypes = (ct.c_void_p, ct.c_void_p, ct.c_void_p, ct.c_void_p)
1142 dbus.dbus_pending_call_cancel.restype = None
1143 dbus.dbus_pending_call_cancel.argtypes = (ct.c_void_p,)
1144 dbus.dbus_pending_call_get_completed.restype = DBUS.bool_t
1145 dbus.dbus_pending_call_get_completed.argtypes = (ct.c_void_p,)
1146 dbus.dbus_pending_call_steal_reply.restype = ct.c_void_p
1147 dbus.dbus_pending_call_steal_reply.argtypes = (ct.c_void_p,)
1148 dbus.dbus_pending_call_block.restype = None
1149 dbus.dbus_pending_call_block.argtypes = (ct.c_void_p,)
1150 dbus.dbus_pending_call_allocate_data_slot.restype = DBUS.bool_t
1151 dbus.dbus_pending_call_allocate_data_slot.argtypes = (ct.POINTER(ct.c_int),)
1152 dbus.dbus_pending_call_free_data_slot.restype = None
1153 dbus.dbus_pending_call_free_data_slot.argtypes = (ct.c_int,)
1154 dbus.dbus_pending_call_set_data.restype = DBUS.bool_t
1155 dbus.dbus_pending_call_set_data.argtypes = (ct.c_void_p, ct.c_int, ct.c_void_p, ct.c_void_p)
1156 dbus.dbus_pending_call_get_data.restype = ct.c_void_p
1157 dbus.dbus_pending_call_get_data.argtypes = (ct.c_void_p, ct.c_int)
1158
1159 # from dbus-message.h:
1160 dbus.dbus_message_new.restype = ct.c_void_p
1161 dbus.dbus_message_new.argtypes = (ct.c_int,)
1162 dbus.dbus_message_new_method_call.restype = ct.c_void_p
1163 dbus.dbus_message_new_method_call.argtypes = (ct.c_char_p, ct.c_char_p, ct.c_char_p, ct.c_char_p)
1164 dbus.dbus_message_new_method_return.restype = ct.c_void_p
1165 dbus.dbus_message_new_method_return.argtypes = (ct.c_void_p,)
1166 dbus.dbus_message_new_signal.restype = ct.c_void_p
1167 dbus.dbus_message_new_signal.argtypes = (ct.c_char_p, ct.c_char_p, ct.c_char_p)
1168 dbus.dbus_message_new_error.restype = ct.c_void_p
1169 dbus.dbus_message_new_error.argtypes = (ct.c_void_p, ct.c_char_p, ct.c_char_p)
1170 dbus.dbus_message_new_error_printf.restype = ct.c_void_p
1171 dbus.dbus_message_new_error_printf.argtypes = (ct.c_void_p, ct.c_char_p, ct.c_char_p, ct.c_char_p)
1172 # note I can’t handle varargs
1173 dbus.dbus_message_copy.restype = ct.c_void_p
1174 dbus.dbus_message_copy.argtypes = (ct.c_void_p,)
1175 dbus.dbus_message_ref.restype = ct.c_void_p
1176 dbus.dbus_message_ref.argtypes = (ct.c_void_p,)
1177 dbus.dbus_message_unref.restype = None
1178 dbus.dbus_message_unref.argtypes = (ct.c_void_p,)
1179 dbus.dbus_message_get_type.restype = ct.c_int
1180 dbus.dbus_message_get_type.argtypes = (ct.c_void_p,)
1181 dbus.dbus_message_set_path.restype = DBUS.bool_t
1182 dbus.dbus_message_set_path.argtypes = (ct.c_void_p, ct.c_char_p)
1183 dbus.dbus_message_get_path.restype = ct.c_char_p
1184 dbus.dbus_message_get_path.argtypes = (ct.c_void_p,)
1185 dbus.dbus_message_has_path.restype = DBUS.bool_t
1186 dbus.dbus_message_has_path.argtypes = (ct.c_void_p, ct.c_char_p)
1187 dbus.dbus_message_set_interface.restype = DBUS.bool_t
1188 dbus.dbus_message_set_interface.argtypes = (ct.c_void_p, ct.c_char_p)
1189 dbus.dbus_message_get_interface.restype = ct.c_char_p
1190 dbus.dbus_message_get_interface.argtypes = (ct.c_void_p,)
1191 dbus.dbus_message_has_interface.restype = DBUS.bool_t
1192 dbus.dbus_message_has_interface.argtypes = (ct.c_void_p, ct.c_char_p)
1193 dbus.dbus_message_set_member.restype = DBUS.bool_t
1194 dbus.dbus_message_set_member.argtypes = (ct.c_void_p, ct.c_char_p)
1195 dbus.dbus_message_get_member.restype = ct.c_char_p
1196 dbus.dbus_message_get_member.argtypes = (ct.c_void_p,)
1197 dbus.dbus_message_has_member.restype = DBUS.bool_t
1198 dbus.dbus_message_has_member.argtypes = (ct.c_void_p, ct.c_char_p)
1199 dbus.dbus_message_set_error_name.restype = DBUS.bool_t
1200 dbus.dbus_message_set_error_name.argtypes = (ct.c_void_p, ct.c_char_p)
1201 dbus.dbus_message_get_error_name.restype = ct.c_char_p
1202 dbus.dbus_message_get_error_name.argtypes = (ct.c_void_p,)
1203 dbus.dbus_message_set_destination.restype = DBUS.bool_t
1204 dbus.dbus_message_set_destination.argtypes = (ct.c_void_p, ct.c_char_p)
1205 dbus.dbus_message_get_destination.restype = ct.c_char_p
1206 dbus.dbus_message_get_destination.argtypes = (ct.c_void_p,)
1207 dbus.dbus_message_set_sender.restype = DBUS.bool_t
1208 dbus.dbus_message_set_sender.argtypes = (ct.c_void_p, ct.c_char_p)
1209 dbus.dbus_message_get_sender.restype = ct.c_char_p
1210 dbus.dbus_message_get_sender.argtypes = (ct.c_void_p,)
1211 dbus.dbus_message_get_signature.restype = ct.c_char_p
1212 dbus.dbus_message_get_signature.argtypes = (ct.c_void_p,)
1213 dbus.dbus_message_set_no_reply.restype = None
1214 dbus.dbus_message_set_no_reply.argtypes = (ct.c_void_p, DBUS.bool_t)
1215 dbus.dbus_message_get_no_reply.restype = DBUS.bool_t
1216 dbus.dbus_message_get_no_reply.argtypes = (ct.c_void_p,)
1217 dbus.dbus_message_is_method_call.restype = DBUS.bool_t
1218 dbus.dbus_message_is_method_call.argtypes = (ct.c_void_p, ct.c_char_p, ct.c_char_p)
1219 dbus.dbus_message_is_signal.restype = DBUS.bool_t
1220 dbus.dbus_message_is_signal.argtypes = (ct.c_void_p, ct.c_char_p, ct.c_char_p)
1221 dbus.dbus_message_is_error.restype = DBUS.bool_t
1222 dbus.dbus_message_is_error.argtypes = (ct.c_void_p, ct.c_char_p)
1223 dbus.dbus_message_has_destination.restype = DBUS.bool_t
1224 dbus.dbus_message_has_destination.argtypes = (ct.c_void_p, ct.c_char_p)
1225 dbus.dbus_message_has_sender.restype = DBUS.bool_t
1226 dbus.dbus_message_has_sender.argtypes = (ct.c_void_p, ct.c_char_p)
1227 dbus.dbus_message_has_signature.restype = DBUS.bool_t
1228 dbus.dbus_message_has_signature.argtypes = (ct.c_void_p, ct.c_char_p)
1229 dbus.dbus_message_get_serial.restype = ct.c_uint
1230 dbus.dbus_message_get_serial.argtypes = (ct.c_void_p,)
1231 dbus.dbus_message_set_serial.restype = None
1232 dbus.dbus_message_set_serial.argtypes = (ct.c_void_p, ct.c_uint)
1233 dbus.dbus_message_set_reply_serial.restype = DBUS.bool_t
1234 dbus.dbus_message_set_reply_serial.argtypes = (ct.c_void_p, ct.c_uint)
1235 dbus.dbus_message_get_reply_serial.restype = ct.c_uint
1236 dbus.dbus_message_get_reply_serial.argtypes = (ct.c_void_p,)
1237 dbus.dbus_message_set_auto_start.restype = None
1238 dbus.dbus_message_set_auto_start.argtypes = (ct.c_void_p, DBUS.bool_t)
1239 dbus.dbus_message_get_auto_start.restype = DBUS.bool_t
1240 dbus.dbus_message_get_auto_start.argtypes = (ct.c_void_p,)
1241 dbus.dbus_message_get_path_decomposed.restype = DBUS.bool_t
1242 dbus.dbus_message_get_path_decomposed.argtypes = (ct.c_void_p, ct.c_void_p)
1243 dbus.dbus_message_append_args.restype = DBUS.bool_t
1244 dbus.dbus_message_append_args.argtypes = (ct.c_void_p, ct.c_int, ct.c_void_p, ct.c_int)
1245 # note I can’t handle varargs
1246 # probably cannot make use of dbus.dbus_message_append_args_valist
1247 dbus.dbus_message_get_args.restype = DBUS.bool_t
1248 dbus.dbus_message_get_args.argtypes = (ct.c_void_p, DBUS.ErrorPtr, ct.c_int, ct.c_void_p, ct.c_int)
1249 # note I can’t handle varargs
1250 # probably cannot make use of dbus.dbus_message_get_args_valist
1251 dbus.dbus_message_contains_unix_fds.restype = DBUS.bool_t
1252 dbus.dbus_message_contains_unix_fds.argtypes = (ct.c_void_p,)
1253 dbus.dbus_message_iter_init.restype = DBUS.bool_t
1254 dbus.dbus_message_iter_init.argtypes = (ct.c_void_p, DBUS.MessageIterPtr)
1255 dbus.dbus_message_iter_has_next.restype = DBUS.bool_t
1256 dbus.dbus_message_iter_has_next.argtypes = (DBUS.MessageIterPtr,)
1257 dbus.dbus_message_iter_next.restype = DBUS.bool_t
1258 dbus.dbus_message_iter_next.argtypes = (DBUS.MessageIterPtr,)
1259 dbus.dbus_message_iter_get_signature.restype = ct.c_void_p
1260 dbus.dbus_message_iter_next.argtypes = (DBUS.MessageIterPtr,)
1261 dbus.dbus_message_iter_get_signature.restype = ct.c_void_p
1262 dbus.dbus_message_iter_get_signature.argtypes = (DBUS.MessageIterPtr,)
1263 dbus.dbus_message_iter_get_arg_type.restype = ct.c_int
1264 dbus.dbus_message_iter_get_arg_type.argtypes = (DBUS.MessageIterPtr,)
1265 dbus.dbus_message_iter_get_element_type.restype = ct.c_int
1266 dbus.dbus_message_iter_get_element_type.argtypes = (DBUS.MessageIterPtr,)
1267 dbus.dbus_message_iter_recurse.restype = None
1268 dbus.dbus_message_iter_recurse.argtypes = (DBUS.MessageIterPtr, DBUS.MessageIterPtr)
1269 dbus.dbus_message_iter_get_basic.restype = None
1270 dbus.dbus_message_iter_get_basic.argtypes = (DBUS.MessageIterPtr, ct.c_void_p)
1271 if hasattr(dbus, "dbus_message_iter_get_element_count") :
1272 dbus.dbus_message_iter_get_element_count.restype = ct.c_int
1273 dbus.dbus_message_iter_get_element_count.argtypes = (DBUS.MessageIterPtr,)
1274 #end if
1275 # dbus_message_iter_get_array_len deprecated
1276 dbus.dbus_message_iter_get_fixed_array.restype = None
1277 dbus.dbus_message_iter_get_fixed_array.argtypes = (DBUS.MessageIterPtr, ct.c_void_p, ct.POINTER(ct.c_int))
1278 dbus.dbus_message_iter_init_append.restype = None
1279 dbus.dbus_message_iter_init_append.argtypes = (ct.c_void_p, DBUS.MessageIterPtr)
1280 dbus.dbus_message_iter_append_basic.restype = DBUS.bool_t
1281 dbus.dbus_message_iter_append_basic.argtypes = (DBUS.MessageIterPtr, ct.c_int, ct.c_void_p)
1282 dbus.dbus_message_iter_append_fixed_array.restype = DBUS.bool_t
1283 dbus.dbus_message_iter_append_fixed_array.argtypes = (DBUS.MessageIterPtr, ct.c_int, ct.c_void_p, ct.c_int)
1284 dbus.dbus_message_iter_open_container.restype = DBUS.bool_t
1285 dbus.dbus_message_iter_open_container.argtypes = (DBUS.MessageIterPtr, ct.c_int, ct.c_char_p, DBUS.MessageIterPtr)
1286 dbus.dbus_message_iter_close_container.restype = DBUS.bool_t
1287 dbus.dbus_message_iter_close_container.argtypes = (DBUS.MessageIterPtr, DBUS.MessageIterPtr)
1288 dbus.dbus_message_iter_abandon_container.restype = None
1289 dbus.dbus_message_iter_abandon_container.argtypes = (DBUS.MessageIterPtr, DBUS.MessageIterPtr)
1290 dbus.dbus_message_lock.restype = None
1291 dbus.dbus_message_lock.argtypes = (DBUS.MessageIterPtr,)
1292 dbus.dbus_set_error_from_message.restype = DBUS.bool_t
1293 dbus.dbus_set_error_from_message.argtypes = (DBUS.ErrorPtr, ct.c_void_p)
1294 dbus.dbus_message_allocate_data_slot.restype = DBUS.bool_t
1295 dbus.dbus_message_allocate_data_slot.argtypes = (ct.POINTER(ct.c_int),)
1296 dbus.dbus_message_free_data_slot.restype = None
1297 dbus.dbus_message_free_data_slot.argtypes = (ct.POINTER(ct.c_int),)
1298 dbus.dbus_message_set_data.restype = DBUS.bool_t
1299 dbus.dbus_message_set_data.argtypes = (ct.c_void_p, ct.c_int, ct.c_void_p, ct.c_void_p)
1300 dbus.dbus_message_get_data.restype = ct.c_void_p
1301 dbus.dbus_message_get_data.argtypes = (ct.c_void_p, ct.c_int)
1302 dbus.dbus_message_type_from_string.restype = ct.c_int
1303 dbus.dbus_message_type_from_string.argtypes = (ct.c_char_p,)
1304 dbus.dbus_message_type_to_string.restype = ct.c_char_p
1305 dbus.dbus_message_type_to_string.argtypes = (ct.c_int,)
1306 dbus.dbus_message_marshal.restype = DBUS.bool_t
1307 dbus.dbus_message_marshal.argtypes = (ct.c_void_p, ct.c_void_p, ct.POINTER(ct.c_int))
1308 dbus.dbus_message_demarshal.restype = ct.c_void_p
1309 dbus.dbus_message_demarshal.argtypes = (ct.c_void_p, ct.c_int, DBUS.ErrorPtr)
1310 dbus.dbus_message_demarshal_bytes_needed.restype = ct.c_int
1311 dbus.dbus_message_demarshal_bytes_needed.argtypes = (ct.c_void_p, ct.c_int)
1312 if hasattr(dbus, "dbus_message_set_allow_interactive_authorization") :
1313 dbus.dbus_message_set_allow_interactive_authorization.restype = None
1314 dbus.dbus_message_set_allow_interactive_authorization.argtypes = (ct.c_void_p, DBUS.bool_t)
1315 #end if
1316 if hasattr(dbus, "dbus_message_get_allow_interactive_authorization") :
1317 dbus.dbus_message_get_allow_interactive_authorization.restype = DBUS.bool_t
1318 dbus.dbus_message_get_allow_interactive_authorization.argtypes = (ct.c_void_p,)
1319 #end if
1320
1321 # from dbus-memory.h:
1322 dbus.dbus_malloc.restype = ct.c_void_p
1323 dbus.dbus_malloc.argtypes = (ct.c_size_t,)
1324 dbus.dbus_malloc0.restype = ct.c_void_p
1325 dbus.dbus_malloc0.argtypes = (ct.c_size_t,)
1326 dbus.dbus_realloc.restype = ct.c_void_p
1327 dbus.dbus_realloc.argtypes = (ct.c_void_p, ct.c_size_t)
1328 dbus.dbus_free.restype = None
1329 dbus.dbus_free.argtypes = (ct.c_void_p,)
1330 dbus.dbus_free_string_array.restype = None
1331 dbus.dbus_free_string_array.argtypes = (ct.c_void_p,)
1332
1333 # from dbus-misc.h:
1334 dbus.dbus_get_local_machine_id.restype = ct.c_void_p
1335 dbus.dbus_get_local_machine_id.argtypes = ()
1336 dbus.dbus_get_version.restype = None
1337 dbus.dbus_get_version.argtypes = (ct.POINTER(ct.c_int), ct.POINTER(ct.c_int), ct.POINTER(ct.c_int))
1338 dbus.dbus_setenv.restype = DBUS.bool_t
1339 dbus.dbus_setenv.argtypes = (ct.c_char_p, ct.c_char_p)
1340
1341 # from dbus-address.h:
1342 dbus.dbus_parse_address.restype = DBUS.bool_t
1343 dbus.dbus_parse_address.argtypes = (ct.c_char_p, ct.c_void_p, ct.POINTER(ct.c_int), DBUS.ErrorPtr)
1344 dbus.dbus_address_entry_get_value.restype = ct.c_char_p
1345 dbus.dbus_address_entry_get_value.argtypes = (ct.c_void_p, ct.c_char_p)
1346 dbus.dbus_address_entry_get_method.restype = ct.c_char_p
1347 dbus.dbus_address_entry_get_method.argtypes = (ct.c_void_p,)
1348 dbus.dbus_address_entries_free.restype = None
1349 dbus.dbus_address_entries_free.argtypes = (ct.c_void_p,)
1350 dbus.dbus_address_escape_value.restype = ct.c_void_p
1351 dbus.dbus_address_escape_value.argtypes = (ct.c_char_p,)
1352 dbus.dbus_address_unescape_value.restype = ct.c_void_p
1353 dbus.dbus_address_unescape_value.argtypes = (ct.c_char_p, DBUS.ErrorPtr)
1354
1355 # from dbus-signature.h:
1356 dbus.dbus_signature_iter_init.restype = None
1357 dbus.dbus_signature_iter_init.argtypes = (DBUS.SignatureIterPtr, ct.c_char_p)
1358 dbus.dbus_signature_iter_get_current_type.restype = ct.c_int
1359 dbus.dbus_signature_iter_get_current_type.argtypes = (DBUS.SignatureIterPtr,)
1360 dbus.dbus_signature_iter_get_signature.restype = ct.c_void_p
1361 dbus.dbus_signature_iter_get_signature.argtypes = (DBUS.SignatureIterPtr,)
1362 dbus.dbus_signature_iter_get_element_type.restype = ct.c_int
1363 dbus.dbus_signature_iter_get_element_type.argtypes = (DBUS.SignatureIterPtr,)
1364 dbus.dbus_signature_iter_next.restype = DBUS.bool_t
1365 dbus.dbus_signature_iter_next.argtypes = (DBUS.SignatureIterPtr,)
1366 dbus.dbus_signature_iter_recurse.restype = None
1367 dbus.dbus_signature_iter_recurse.argtypes = (DBUS.SignatureIterPtr, DBUS.SignatureIterPtr)
1368 dbus.dbus_signature_validate.restype = DBUS.bool_t
1369 dbus.dbus_signature_validate.argtypes = (ct.c_char_p, DBUS.ErrorPtr)
1370 dbus.dbus_signature_validate_single.restype = DBUS.bool_t
1371 dbus.dbus_signature_validate_single.argtypes = (ct.c_char_p, DBUS.ErrorPtr)
1372 dbus.dbus_type_is_valid.restype = DBUS.bool_t
1373 dbus.dbus_type_is_valid.argtypes = (ct.c_int,)
1374 dbus.dbus_type_is_basic.restype = DBUS.bool_t
1375 dbus.dbus_type_is_basic.argtypes = (ct.c_int,)
1376 dbus.dbus_type_is_container.restype = DBUS.bool_t
1377 dbus.dbus_type_is_container.argtypes = (ct.c_int,)
1378 dbus.dbus_type_is_fixed.restype = DBUS.bool_t
1379 dbus.dbus_type_is_fixed.argtypes = (ct.c_int,)
1380
1381 # from dbus-syntax.h:
1382 dbus.dbus_validate_path.restype = DBUS.bool_t
1383 dbus.dbus_validate_path.argtypes = (ct.c_char_p, DBUS.ErrorPtr)
1384 dbus.dbus_validate_interface.restype = DBUS.bool_t
1385 dbus.dbus_validate_interface.argtypes = (ct.c_char_p, DBUS.ErrorPtr)
1386 dbus.dbus_validate_member.restype = DBUS.bool_t
1387 dbus.dbus_validate_member.argtypes = (ct.c_char_p, DBUS.ErrorPtr)
1388 dbus.dbus_validate_error_name.restype = DBUS.bool_t
1389 dbus.dbus_validate_error_name.argtypes = (ct.c_char_p, DBUS.ErrorPtr)
1390 dbus.dbus_validate_bus_name.restype = DBUS.bool_t
1391 dbus.dbus_validate_bus_name.argtypes = (ct.c_char_p, DBUS.ErrorPtr)
1392 dbus.dbus_validate_utf8.restype = DBUS.bool_t
1393 dbus.dbus_validate_utf8.argtypes = (ct.c_char_p, DBUS.ErrorPtr)
1394
1395 # from dbus-server.h:
1396 dbus.dbus_server_listen.restype = ct.c_void_p
1397 dbus.dbus_server_listen.argtypes = (ct.c_char_p, DBUS.ErrorPtr)
1398 dbus.dbus_server_ref.restype = ct.c_void_p
1399 dbus.dbus_server_ref.argtypes = (ct.c_void_p,)
1400 dbus.dbus_server_unref.restype = ct.c_void_p
1401 dbus.dbus_server_unref.argtypes = (ct.c_void_p,)
1402 dbus.dbus_server_disconnect.restype = None
1403 dbus.dbus_server_disconnect.argtypes = (ct.c_void_p,)
1404 dbus.dbus_server_get_is_connected.restype = DBUS.bool_t
1405 dbus.dbus_server_get_is_connected.argtypes = (ct.c_void_p,)
1406 dbus.dbus_server_get_address.restype = ct.c_void_p
1407 dbus.dbus_server_get_address.argtypes = (ct.c_void_p,)
1408 dbus.dbus_server_get_id.restype = ct.c_void_p
1409 dbus.dbus_server_get_id.argtypes = (ct.c_void_p,)
1410 dbus.dbus_server_set_new_connection_function.restype = None
1411 dbus.dbus_server_set_new_connection_function.argtypes = (ct.c_void_p, ct.c_void_p, ct.c_void_p, ct.c_void_p)
1412 dbus.dbus_server_set_watch_functions.restype = DBUS.bool_t
1413 dbus.dbus_server_set_watch_functions.argtypes = (ct.c_void_p, ct.c_void_p, ct.c_void_p, ct.c_void_p, ct.c_void_p, ct.c_void_p)
1414 dbus.dbus_server_set_timeout_functions.restype = DBUS.bool_t
1415 dbus.dbus_server_set_timeout_functions.argtypes = (ct.c_void_p, ct.c_void_p, ct.c_void_p, ct.c_void_p, ct.c_void_p, ct.c_void_p)
1416 dbus.dbus_server_set_auth_mechanisms.restype = DBUS.bool_t
1417 dbus.dbus_server_set_auth_mechanisms.argtypes = (ct.c_void_p, ct.c_void_p)
1418 dbus.dbus_server_allocate_data_slot.restype = DBUS.bool_t
1419 dbus.dbus_server_allocate_data_slot.argtypes = (ct.POINTER(ct.c_int),)
1420 dbus.dbus_server_free_data_slot.restype = DBUS.bool_t
1421 dbus.dbus_server_free_data_slot.argtypes = (ct.POINTER(ct.c_int),)
1422 dbus.dbus_server_set_data.restype = DBUS.bool_t
1423 dbus.dbus_server_set_data.argtypes = (ct.c_void_p, ct.c_int, ct.c_void_p, ct.c_void_p)
1424 dbus.dbus_server_set_data.restype = ct.c_void_p
1425 dbus.dbus_server_set_data.argtypes = (ct.c_void_p, ct.c_int)
1426
1427 # TODO dbus-threads.h <https://dbus.freedesktop.org/doc/api/html/group__DBusThreads.html>
1428 # Seems like the only call worth making is dbus_threads_init_default.
1429
1430 #+
1431 # High-level stuff follows
1432 #-
1433
1434 class DBusError(Exception) :
1435 "for raising an exception that reports a D-Bus error name and accompanying message."
1436
1437 __slots__ = ("name", "message")
1438
1439 def __init__(self, name, message) :
1440 self.args = ("%s -- %s" % (name, message),)
1441 self.name = name
1442 self.message = message
1443 #end __init__
1444
1445 #end DBusError
1446
1447 class CallFailed(Exception) :
1448 "used internally for reporting general failure from calling a libdbus routine."
1449
1450 __slots__ = ("funcname",)
1451
1452 def __init__(self, funcname) :
1453 self.args = ("%s failed" % funcname,)
1454 self.funcname = funcname
1455 #end __init__
1456
1457 #end CallFailed
1458
1459 class _Abort(Exception) :
1460 pass
1461 #end _Abort
1462
1463 class TaskKeeper :
1464 "Base class for classes that need to call EventLoop.create_task() to" \
1465 " schedule caller-created coroutines for execution. asyncio only keeps" \
1466 " weak references to Task objects when they are not being scheduled," \
1467 " so to keep them from disappearing unexpectedly, I maintain a list of" \
1468 " strong references here, and clean them out as they end execution."
1469
1470 __slots__ = ("__weakref__", "loop", "_cur_tasks")
1471
1472 def _init(self) :
1473 # avoid __init__ so I don't get passed spurious args
1474 self.loop = None
1475 self._cur_tasks = set()
1476 #end _init
1477
1478 def create_task(self, coro) :
1479 assert self.loop != None, "no event loop to attach coroutine to"
1480 task = self.loop.create_task(coro)
1481 task.add_done_callback(functools.partial(self._reaper, weak_ref(self)))
1482 self._cur_tasks.add(task)
1483 #end create_task
1484
1485 @staticmethod
1486 def _reaper(self, task) :
1487 self = self() # avoid reference circularity
1488 self._cur_tasks.remove(task)
1489 #end _reaper
1490
1491 if "loop" in asyncio.wait.__kwdefaults__ :
1492
1493 def wait(self, futures, *, timeout = None, return_when = asyncio.ALL_COMPLETED) :
1494 "wrapper around asyncio.wait for compatibility with pre-Python-3.7."
1495 return \
1496 asyncio.wait(futures, loop = self.loop, timeout = timeout, return_when = return_when)
1497 # No default loop in pre-3.7.
1498 #end wait
1499
1500 else :
1501
1502 wait = staticmethod(asyncio.wait)
1503 # no need to pass loop arg in ≥ 3.7, removed in ≥ 3.10.
1504
1505 #end if
1506
1507 #end TaskKeeper
1508
1509 # Misc: <https://dbus.freedesktop.org/doc/api/html/group__DBusMisc.html>
1510
1511 def get_local_machine_id() :
1512 "returns a systemwide unique ID that is supposed to remain constant at least" \
1513 " until the next reboot. Two processes seeing the same value for this can assume" \
1514 " they are on the same machine."
1515 c_result = dbus.dbus_get_local_machine_id()
1516 if c_result == None :
1517 raise CallFailed("dbus_get_local_machine_id")
1518 #end if
1519 result = ct.cast(c_result, ct.c_char_p).value.decode()
1520 dbus.dbus_free(c_result)
1521 return \
1522 result
1523 #end get_local_machine_id
1524
1525 def get_version() :
1526 "returns the libdbus library version as a tuple of integers (major, minor, micro)."
1527 major = ct.c_int()
1528 minor = ct.c_int()
1529 micro = ct.c_int()
1530 dbus.dbus_get_version(ct.byref(major), ct.byref(minor), ct.byref(micro))
1531 return \
1532 (major.value, minor.value, micro.value)
1533 #end get_version
1534
1535 def setenv(key, value) :
1536 key = key.encode()
1537 if value != None :
1538 value = value.encode()
1539 #end if
1540 if not dbus.dbus_setenv(key, value) :
1541 raise CallFailed("dbus_setenv")
1542 #end if
1543 #end setenv
1544
1545 def unsetenv(key) :
1546 setenv(key, None)
1547 #end unsetenv
1548
1549 class Watch :
1550 "wrapper around a DBusWatch object. Do not instantiate directly; they" \
1551 " are created and destroyed by libdbus.\n" \
1552 "\n" \
1553 "A Watch is the basic mechanism for plugging libdbus-created file descriptors" \
1554 " into your event loop. When created, they are passed to your add-watch callback" \
1555 " to manage; and conversely, when deleted, your remove-watch callback is notified." \
1556 " (These callbacks are ones you attach to Server and Connection objects.)\n" \
1557 "\n" \
1558 "Check the enabled property to decide if you need to pay attention to this Watch, and" \
1559 " look at the flags to see if you need to check for pending reads, or writes, or both." \
1560 " Call the handle() method with the appropriate flags when you see that reads or writes" \
1561 " are pending."
1562 # <https://dbus.freedesktop.org/doc/api/html/group__DBusWatch.html>
1563
1564 __slots__ = ("__weakref__", "_dbobj",) # to forestall typos
1565
1566 _instances = WeakValueDictionary()
1567
1568 def __new__(celf, _dbobj) :
1569 self = celf._instances.get(_dbobj)
1570 if self == None :
1571 self = super().__new__(celf)
1572 self._dbobj = _dbobj
1573 celf._instances[_dbobj] = self
1574 #end if
1575 return \
1576 self
1577 #end __new__
1578
1579 # no __del__ method -- no underlying dispose API call
1580
1581 @property
1582 def unix_fd(self) :
1583 "the underlying file descriptor for this Watch."
1584 return \
1585 dbus.dbus_watch_get_unix_fd(self._dbobj)
1586 #end unix_fd
1587
1588 def fileno(self) :
1589 "for use with Python’s “select” functions."
1590 return \
1591 self.unix_fd
1592 #end fileno
1593
1594 @property
1595 def socket(self) :
1596 return \
1597 dbus.dbus_watch_get_socket(self._dbobj)
1598 #end socket
1599
1600 @property
1601 def flags(self) :
1602 "returns WATCH_READABLE and/or WATCH_WRITABLE, indicating what to watch for."
1603 return \
1604 dbus.dbus_watch_get_flags(self._dbobj)
1605 #end flags
1606
1607 # TODO: get/set data
1608
1609 def handle(self, flags) :
1610 "tells libdbus that there is something to be read or written." \
1611 " flags are a combination of WATCH_xxx values."
1612 return \
1613 dbus.dbus_watch_handle(self._dbobj, flags) != 0
1614 #end handle
1615
1616 @property
1617 def enabled(self) :
1618 "does libdbus want you to actually watch this Watch."
1619 return \
1620 dbus.dbus_watch_get_enabled(self._dbobj) != 0
1621 #end enabled
1622
1623 #end Watch
1624
1625 class Timeout :
1626 "wrapper around a DBusTimeout object. Do not instantiate directly; they" \
1627 " are created and destroyed by libdbus.\n" \
1628 "\n" \
1629 " A Timeout is the basic mechanism for plugging libdbus-created timeouts" \
1630 " into your event loop. When created, they are passed to your add-timeout" \
1631 " callback to manage; and conversely, when deleted, your remove-timeout" \
1632 " callback is notified. (These callbacks are ones you attach to Server and" \
1633 " Connection objects.)\n" \
1634 "\n" \
1635 "Check the enabled property to decide if you need to pay attention to this" \
1636 " Timeout. Call the handle() method when the timeout becomes due, as measured" \
1637 " from when it was initially created or most recently enabled, whichever" \
1638 " happened last."
1639 # <https://dbus.freedesktop.org/doc/api/html/group__DBusTimeout.html>
1640
1641 __slots__ = ("__weakref__", "_dbobj",) # to forestall typos
1642
1643 _instances = WeakValueDictionary()
1644
1645 def __new__(celf, _dbobj) :
1646 self = celf._instances.get(_dbobj)
1647 if self == None :
1648 self = super().__new__(celf)
1649 self._dbobj = _dbobj
1650 celf._instances[_dbobj] = self
1651 #end if
1652 return \
1653 self
1654 #end __new__
1655
1656 # no __del__ method -- no underlying dispose API call
1657
1658 @property
1659 def interval(self) :
1660 "how long in float seconds until the timeout should fire."
1661 return \
1662 dbus.dbus_timeout_get_interval(self._dbobj) / 1000
1663 #end interval
1664
1665 # TODO: get/set data
1666
1667 def handle(self) :
1668 "tells libdbus the timeout has fired."
1669 return \
1670 dbus.dbus_timeout_handle(self._dbobj)
1671 #end handle
1672
1673 @property
1674 def enabled(self) :
1675 "does libdbus want you to actually schedule this Timeout."
1676 return \
1677 dbus.dbus_timeout_get_enabled(self._dbobj) != 0
1678 #end enabled
1679
1680 #end Timeout
1681
1682 class ObjectPathVTable(TaskKeeper) :
1683 "wrapper around an ObjectPathVTable struct. You can instantiate directly, or call" \
1684 " the init method. An additional feature beyond the underlying libdbus capabilities" \
1685 " is the option to specify an asyncio event loop. If the message handler returns" \
1686 " a coroutine, then an asyncio task is created to run it, and a result of" \
1687 " DBUS.HANDLER_RESULT_HANDLED is returned on behalf of the message handler;" \
1688 " that way, the message function can do the minimum beyond some initial filtering of" \
1689 " the message, leaving the time-consuming part of the work to the coroutine."
1690
1691 __slots__ = \
1692 (
1693 "_dbobj",
1694 # need to keep references to ctypes-wrapped functions
1695 # so they don't disappear prematurely:
1696 "_wrap_unregister_func",
1697 "_wrap_message_func",
1698 ) # to forestall typos
1699
1700 def __init__(self, *, loop = None, unregister = None, message = None) :
1701 super().__init__()
1702 super()._init()
1703 self._dbobj = DBUS.ObjectPathVTable()
1704 self.loop = loop
1705 self._wrap_unregister_func = None
1706 self._wrap_message_func = None
1707 if unregister != None :
1708 self.set_unregister(unregister)
1709 #end if
1710 if message != None :
1711 self.set_message(message)
1712 #end if
1713 #end __init__
1714
1715 @classmethod
1716 def init(celf, *, loop = None, unregister = None, message = None) :
1717 "for consistency with other classes that don’t want caller to instantiate directly."
1718 return \
1719 celf \
1720 (
1721 loop = loop,
1722 unregister = unregister,
1723 message = message,
1724 )
1725 #end init
1726
1727 def set_unregister(self, unregister) :
1728
1729 def wrap_unregister(c_conn, c_user_data) :
1730 conn = Connection(dbus.dbus_connection_ref(c_conn))
1731 unregister(conn, conn._user_data.get(c_user_data))
1732 #end wrap_unregister
1733
1734 #begin set_unregister
1735 if unregister != None :
1736 self._wrap_unregister_func = DBUS.ObjectPathUnregisterFunction(wrap_unregister)
1737 else :
1738 self._wrap_unregister_func = None
1739 #end if
1740 self._dbobj.unregister_function = self._wrap_unregister_func
1741 return \
1742 self
1743 #end set_unregister
1744
1745 def set_message(self, message) :
1746
1747 w_self = weak_ref(self)
1748
1749 def wrap_message(c_conn, c_message, c_user_data) :
1750 self = _wderef(w_self, "vtable")
1751 conn = Connection(dbus.dbus_connection_ref(c_conn))
1752 msg = Message(dbus.dbus_message_ref(c_message))
1753 user_data = conn._user_data.get(c_user_data)
1754 result = message(conn, msg, user_data)
1755 if asyncio.iscoroutine(result) :
1756 self.create_task(result)
1757 result = DBUS.HANDLER_RESULT_HANDLED
1758 #end if
1759 return \
1760 result
1761 #end wrap_message
1762
1763 #begin set_message
1764 if message != None :
1765 self._wrap_message_func = DBUS.ObjectPathMessageFunction(wrap_message)
1766 else :
1767 self._wrap_message_func = None
1768 #end if
1769 self._dbobj.message_function = self._wrap_message_func
1770 return \
1771 self
1772 #end set_message
1773
1774 #end ObjectPathVTable
1775
1776 class _DummyError :
1777 # like an Error, but is never set and so will never raise.
1778
1779 @property
1780 def is_set(self) :
1781 return \
1782 False
1783 #end is_set
1784
1785 def raise_if_set(self) :
1786 pass
1787 #end raise_if_set
1788
1789 #end _DummyError
1790
1791 def _get_error(error) :
1792 # Common routine which processes an optional user-supplied Error
1793 # argument, and returns 2 Error-like objects: the first a real
1794 # Error object to be passed to the libdbus call, the second is
1795 # either the same Error object or a separate _DummyError object
1796 # on which to call raise_if_set() afterwards. The procedure for
1797 # using this is
1798 #
1799 # error, my_error = _get_error(error)
1800 # ... call libdbus routine, passing error._dbobj ...
1801 # my_error.raise_if_set()
1802 #
1803 # If the user passes None for error, then an internal Error object
1804 # is created, and returned as both results. That way, if it is
1805 # filled in by the libdbus call, calling raise_if_set() will
1806 # automatically raise the exception.
1807 # But if the user passed their own Error object, then it is
1808 # returned as the first result, and a _DummyError as the second
1809 # result. This means the raise_if_set() call becomes a noop, and
1810 # it is up to the caller to check if their Error object was filled
1811 # in or not.
1812 if error != None and not isinstance(error, Error) :
1813 raise TypeError("error must be an Error")
1814 #end if
1815 if error != None :
1816 my_error = _DummyError()
1817 else :
1818 my_error = Error()
1819 error = my_error
1820 #end if
1821 return \
1822 error, my_error
1823 #end _get_error
1824
1825 def _get_timeout(timeout) :
1826 # accepts a timeout in float seconds and converts it to integer milliseconds
1827 # as expected by libdbus. Special-cases DBUS.TIMEOUT_INFINITE and DBUS.TIMEOUT_USE_DEFAULT,
1828 # allowing these to be passed through unchanged.
1829 if not isinstance(timeout, int) or timeout not in (DBUS.TIMEOUT_INFINITE, DBUS.TIMEOUT_USE_DEFAULT) :
1830 timeout = round(timeout * 1000)
1831 #end if
1832 return \
1833 timeout
1834 #end _get_timeout
1835
1836 def _loop_attach(self, loop, dispatch) :
1837 # attaches a Server or Connection object to a given asyncio event loop.
1838 # If loop is None, then the default asyncio loop is used. The actual loop
1839 # value is also stored as the loop attribute of the object.
1840
1841 if loop == None :
1842 try :
1843 # if running within a task, current loop takes priority
1844 loop = get_running_loop()
1845 except RuntimeError :
1846 # not running within a task, use default loop
1847 loop = get_event_loop()
1848 #end try
1849 #end if
1850
1851 watches = [] # do I need to keep track of Watch objects?
1852 timeouts = []
1853
1854 def call_dispatch() :
1855 status = dispatch()
1856 if status == DBUS.DISPATCH_NEED_MEMORY :
1857 raise DBusError(DBUS.ERROR_NO_MEMORY, "not enough memory for connection dispatch")
1858 #end if
1859 if status == DBUS.DISPATCH_DATA_REMAINS :
1860 loop.call_soon(call_dispatch)
1861 #end if
1862 #end call_dispatch
1863
1864 def add_remove_watch(watch, add) :
1865
1866 def handle_watch_event(flags) :
1867 # seems I need to remove the watch and add it again to
1868 # avoid an endless stream of notifications that cause
1869 # excessive CPU usage -- asyncio bug?
1870 add_remove_watch(watch, False)
1871 watch.handle(flags)
1872 if watch.enabled :
1873 add_remove_watch(watch, True)
1874 #end if
1875 if dispatch != None :
1876 call_dispatch()
1877 #end if
1878 #end handle_watch_event
1879
1880 #end add_remove_watch
1881 if DBUS.WATCH_READABLE & watch.flags != 0 :
1882 if add :
1883 loop.add_reader(watch, handle_watch_event, DBUS.WATCH_READABLE)
1884 else :
1885 loop.remove_reader(watch)
1886 #end if
1887 #end if
1888 if DBUS.WATCH_WRITABLE & watch.flags != 0 :
1889 if add :
1890 loop.add_writer(watch, handle_watch_event, DBUS.WATCH_WRITABLE)
1891 else :
1892 loop.remove_writer(watch)
1893 #end if
1894 #end if
1895 #end add_remove_watch
1896
1897 def handle_add_watch(watch, data) :
1898 if watch not in watches :
1899 watches.append(watch)
1900 add_remove_watch(watch, True)
1901 #end if
1902 return \
1903 True
1904 #end handle_add_watch
1905
1906 def handle_watch_toggled(watch, data) :
1907 add_remove_watch(watch, watch.enabled)
1908 #end handle_watch_toggled
1909
1910 def handle_remove_watch(watch, data) :
1911 try :
1912 pos = watches.index(watch)
1913 except ValueError :
1914 pos = None
1915 #end try
1916 if pos != None :
1917 watches[pos : pos + 1] = []
1918 add_remove_watch(watch, False)
1919 #end if
1920 #end handle_remove_watch
1921
1922 def handle_timeout(timeout) :
1923 if timeout["due"] != None and timeout["due"] <= loop.time() and timeout["timeout"].enabled :
1924 timeout["timeout"].handle()
1925 #end if
1926 #end handle_timeout
1927
1928 def handle_add_timeout(timeout, data) :
1929 if not any(timeout == t["timeout"] for t in timeouts) :
1930 entry = \
1931 {
1932 "timeout" : timeout,
1933 "due" : (lambda : None, lambda : loop.time() + timeout.interval)[timeout.enabled](),
1934 }
1935 timeouts.append(entry)
1936 if timeout.enabled :
1937 loop.call_later(timeout.interval, handle_timeout, entry)
1938 #end if
1939 #end if
1940 return \
1941 True
1942 #end handle_add_timeout
1943
1944 def handle_timeout_toggled(timeout, data) :
1945 # not sure what to do if a Timeout gets toggled from enabled to disabled
1946 # and then to enabled again; effectively I update the due time from
1947 # the time of re-enabling.
1948 search = iter(timeouts)
1949 while True :
1950 entry = next(search, None)
1951 if entry == None :
1952 break
1953 #end if
1954 if entry["timeout"] == timeout :
1955 if timeout.enabled :
1956 entry["due"] = loop.time() + timeout.enterval
1957 loop.call_later(timeout.interval, handle_timeout, entry)
1958 else :
1959 entry["due"] = None
1960 #end if
1961 break
1962 #end if
1963 #end while
1964 #end handle_timeout_toggled
1965
1966 def handle_remove_timeout(timeout, data) :
1967 new_timeouts = []
1968 for entry in timeouts :
1969 if entry["timeout"] == timeout :
1970 entry["due"] = None # in case already queued, avoid segfault in handle_timeout
1971 else :
1972 new_timeouts.append(entry)
1973 #end if
1974 #end for
1975 timeouts[:] = new_timeouts
1976 #end handle_remove_timeout
1977
1978 #begin _loop_attach
1979 self.set_watch_functions \
1980 (
1981 add_function = handle_add_watch,
1982 remove_function = handle_remove_watch,
1983 toggled_function = handle_watch_toggled,
1984 data = None
1985 )
1986 self.set_timeout_functions \
1987 (
1988 add_function = handle_add_timeout,
1989 remove_function = handle_remove_timeout,
1990 toggled_function = handle_timeout_toggled,
1991 data = None
1992 )
1993 self.loop = loop
1994 self = None # avoid circularity
1995 #end _loop_attach
1996
1997 class _MatchActionEntry :
1998 __slots__ = ("rule", "actions")
1999
2000 class _Action :
2001 __slots__ = ("func", "user_data")
2002
2003 def __init__(self, func, user_data) :
2004 self.func = func
2005 self.user_data = user_data
2006 #end __init__
2007
2008 def __eq__(a, b) :
2009 # needed to allow equality comparison of set entries
2010 return \
2011 (
2012 a.func == b.func
2013 and
2014 data_key(a.user_data) == data_key(b.user_data)
2015 )
2016 #end __eq__
2017
2018 def __hash__(self) :
2019 return \
2020 hash((self.func, data_key(self.user_data)))
2021 #end __hash__
2022
2023 #end _Action
2024
2025 def __init__(self, rule) :
2026 self.rule = rule
2027 self.actions = set()
2028 #end __init__
2029
2030 #end _MatchActionEntry
2031
2032 @enum.unique
2033 class STOP_ON(enum.Enum) :
2034 "set of conditions on which to raise StopAsyncIteration:\n" \
2035 "\n" \
2036 " TIMEOUT - timeout has elapsed\n" \
2037 " CLOSED - server/connection has closed.\n" \
2038 "\n" \
2039 "Otherwise None will be returned on timeout, and the usual BrokenPipeError" \
2040 " exception will be raised when the connection is closed."
2041 TIMEOUT = 1
2042 CLOSED = 2
2043 #end STOP_ON
2044
2045 class Connection(TaskKeeper) :
2046 "wrapper around a DBusConnection object. Do not instantiate directly; use the open" \
2047 " or bus_get methods."
2048 # <https://dbus.freedesktop.org/doc/api/html/group__DBusConnection.html>
2049
2050 __slots__ = \
2051 (
2052 "_dbobj",
2053 "_filters",
2054 "_match_actions",
2055 "_receive_queue",
2056 "_receive_queue_enabled",
2057 "_awaiting_receive",
2058 "_user_data",
2059 # need to keep references to ctypes-wrapped functions
2060 # so they don't disappear prematurely:
2061 "_object_paths",
2062 "_add_watch_function",
2063 "_remove_watch_function",
2064 "_toggled_watch_function",
2065 "_free_watch_data",
2066 "_add_timeout_function",
2067 "_remove_timeout_function",
2068 "_toggled_timeout_function",
2069 "_free_timeout_data",
2070 "_wakeup_main",
2071 "_free_wakeup_main_data",
2072 "_dispatch_status",
2073 "_free_dispatch_status_data",
2074 "_allow_unix_user",
2075 "_free_unix_user_data",
2076 ) # to forestall typos
2077
2078 _instances = WeakValueDictionary()
2079 _shared_connections = [None, None]
2080
2081 def __new__(celf, _dbobj) :
2082 self = celf._instances.get(_dbobj)
2083 if self == None :
2084 self = super().__new__(celf)
2085 super()._init(self)
2086 self._dbobj = _dbobj
2087 self._user_data = {}
2088 self._filters = {}
2089 self._match_actions = {}
2090 self._receive_queue = None
2091 self._receive_queue_enabled = set()
2092 self._awaiting_receive = []
2093 self._object_paths = {}
2094 celf._instances[_dbobj] = self
2095 else :
2096 dbus.dbus_connection_unref(self._dbobj)
2097 # lose extra reference created by caller
2098 #end if
2099 return \
2100 self
2101 #end __new__
2102
2103 def __del__(self) :
2104 if self._dbobj != None :
2105 if self.loop != None :
2106 # remove via direct low-level libdbus calls
2107 dbus.dbus_connection_set_watch_functions(self._dbobj, None, None, None, None, None)
2108 dbus.dbus_connection_set_timeout_functions(self._dbobj, None, None, None, None, None)
2109 self.loop = None
2110 #end if
2111 # Any entries still in super(TaskKeeper, self)._cur_tasks will be lost
2112 # at this point. I leave it to asyncio to report them as destroyed
2113 # while still pending, and the caller to notice this as a program bug.
2114 dbus.dbus_connection_unref(self._dbobj)
2115 self._dbobj = None
2116 #end if
2117 #end __del__
2118
2119 @classmethod
2120 def open(celf, address, private, error = None) :
2121 "opens a Connection to a specified address, separate from the" \
2122 " system or session buses."
2123 error, my_error = _get_error(error)
2124 result = (dbus.dbus_connection_open, dbus.dbus_connection_open_private)[private](address.encode(), error._dbobj)
2125 my_error.raise_if_set()
2126 if result != None :
2127 result = celf(result)
2128 #end if
2129 return \
2130 result
2131 #end open
2132
2133 @classmethod
2134 async def open_async(celf, address, private, error = None, loop = None, timeout = DBUS.TIMEOUT_INFINITE) :
2135 "opens a Connection to a specified address, separate from the" \
2136 " system or session buses."
2137 # There is no nonblocking version of dbus_connection_open/dbus_connection_open_private,
2138 # so I invoke it in a separate thread.
2139
2140 if loop == None :
2141 loop = get_running_loop()
2142 #end if
2143 error, my_error = _get_error(error)
2144 if timeout == DBUS.TIMEOUT_USE_DEFAULT :
2145 timeout = DBUSX.DEFAULT_TIMEOUT
2146 elif timeout == DBUS.TIMEOUT_INFINITE :
2147 timeout = None
2148 #end if
2149 try :
2150 result = await call_async \
2151 (
2152 func = (dbus.dbus_connection_open, dbus.dbus_connection_open_private)[private],
2153 funcargs = (address.encode(), error._dbobj),
2154 timeout = timeout,
2155 abort = dbus.dbus_connection_unref,
2156 loop = loop
2157 )
2158 except TimeoutError :
2159 result = None
2160 error.set(DBUS.ERROR_TIMEOUT, "connection did not open in time")
2161 #end try
2162 my_error.raise_if_set()
2163 if result != None :
2164 result = celf(result)
2165 result.attach_asyncio(loop)
2166 #end if
2167 return \
2168 result
2169 #end open_async
2170
2171 def _flush_awaiting_receive(self) :
2172 if self._receive_queue != None :
2173 while len(self._awaiting_receive) != 0 :
2174 waiting = self._awaiting_receive.pop(0)
2175 waiting.set_exception(BrokenPipeError("async receives have been disabled"))
2176 #end while
2177 #end if
2178 #end _flush_awaiting_receive
2179
2180 def close(self) :
2181 self._flush_awaiting_receive()
2182 dbus.dbus_connection_close(self._dbobj)
2183 #end close
2184
2185 @property
2186 def is_connected(self) :
2187 return \
2188 dbus.dbus_connection_get_is_connected(self._dbobj) != 0
2189 #end is_connected
2190
2191 @property
2192 def is_authenticated(self) :
2193 return \
2194 dbus.dbus_connection_get_is_authenticated(self._dbobj) != 0
2195 #end is_authenticated
2196
2197 @property
2198 def is_anonymous(self) :
2199 return \
2200 dbus.dbus_connection_get_is_anonymous(self._dbobj) != 0
2201 #end is_anonymous
2202
2203 @property
2204 def server_id(self) :
2205 "asks the server at the other end for its unique id."
2206 c_result = dbus.dbus_connection_get_server_id(self._dbobj)
2207 result = ct.cast(c_result, ct.c_char_p).value.decode()
2208 dbus.dbus_free(c_result)
2209 return \
2210 result
2211 #end server_id
2212
2213 def can_send_type(self, type_code) :
2214 "can this Connection send values of the specified TYPE_XXX code." \
2215 " Mainly useful for checking if we can send TYPE_UNIX_FD values."
2216 return \
2217 dbus.dbus_connection_can_send_type(self._dbobj, type_code) != 0
2218 #end can_send_type
2219
2220 def set_exit_on_disconnect(self, exit_on_disconnect) :
2221 dbus.dbus_connection_set_exit_on_disconnect(self._dbobj, exit_on_disconnect)
2222 #end set_exit_on_disconnect
2223
2224 def preallocate_send(self) :
2225 result = dbus.dbus_connection_preallocate_send(self._dbobj)
2226 if result == None :
2227 raise CallFailed("dbus_connection_preallocate_send")
2228 #end if
2229 return \
2230 PreallocatedSend(result, self)
2231 #end preallocate_send
2232
2233 def send_preallocated(self, preallocated, message) :
2234 if not isinstance(preallocated, PreallocatedSend) or not isinstance(message, Message) :
2235 raise TypeError("preallocated must be a PreallocatedSend and message must be a Message")
2236 #end if
2237 assert not preallocated._sent, "preallocated has already been sent"
2238 serial = ct.c_uint()
2239 dbus.dbus_connection_send_preallocated(self._dbobj, preallocated._dbobj, message._dbobj, ct.byref(serial))
2240 preallocated._sent = True
2241 return \
2242 serial.value
2243 #end send_preallocated
2244
2245 def send(self, message) :
2246 "puts a message in the outgoing queue."
2247 if not isinstance(message, Message) :
2248 raise TypeError("message must be a Message")
2249 #end if
2250 serial = ct.c_uint()
2251 if not dbus.dbus_connection_send(self._dbobj, message._dbobj, ct.byref(serial)) :
2252 raise CallFailed("dbus_connection_send")
2253 #end if
2254 return \
2255 serial.value
2256 #end send
2257
2258 def send_with_reply(self, message, timeout = DBUS.TIMEOUT_USE_DEFAULT) :
2259 "puts a message in the outgoing queue and returns a PendingCall" \
2260 " that you can use to obtain the reply."
2261 if not isinstance(message, Message) :
2262 raise TypeError("message must be a Message")
2263 #end if
2264 pending_call = ct.c_void_p()
2265 if not dbus.dbus_connection_send_with_reply(self._dbobj, message._dbobj, ct.byref(pending_call), _get_timeout(timeout)) :
2266 raise CallFailed("dbus_connection_send_with_reply")
2267 #end if
2268 if pending_call.value != None :
2269 result = PendingCall(pending_call.value, self)
2270 else :
2271 result = None
2272 #end if
2273 return \
2274 result
2275 #end send_with_reply
2276
2277 def send_with_reply_and_block(self, message, timeout = DBUS.TIMEOUT_USE_DEFAULT, error = None) :
2278 "sends a message, blocks the thread until the reply is available, and returns it."
2279 if not isinstance(message, Message) :
2280 raise TypeError("message must be a Message")
2281 #end if
2282 error, my_error = _get_error(error)
2283 reply = dbus.dbus_connection_send_with_reply_and_block(self._dbobj, message._dbobj, _get_timeout(timeout), error._dbobj)
2284 my_error.raise_if_set()
2285 if reply != None :
2286 result = Message(reply)
2287 else :
2288 result = None
2289 #end if
2290 return \
2291 result
2292 #end send_with_reply_and_block
2293
2294 async def send_await_reply(self, message, timeout = DBUS.TIMEOUT_USE_DEFAULT) :
2295 "queues a message, suspends the coroutine (letting the event loop do" \
2296 " other things) until the reply is available, and returns it."
2297 if not isinstance(message, Message) :
2298 raise TypeError("message must be a Message")
2299 #end if
2300 assert self.loop != None, "no event loop to attach coroutine to"
2301 pending_call = ct.c_void_p()
2302 if not dbus.dbus_connection_send_with_reply(self._dbobj, message._dbobj, ct.byref(pending_call), _get_timeout(timeout)) :
2303 raise CallFailed("dbus_connection_send_with_reply")
2304 #end if
2305 if pending_call.value != None :
2306 pending = PendingCall(pending_call.value, self)
2307 else :
2308 pending = None
2309 #end if
2310 reply = None # to begin with
2311 if pending != None :
2312 reply = await pending.await_reply()
2313 #end if
2314 return \
2315 reply
2316 #end send_await_reply
2317
2318 def flush(self) :
2319 "makes sure all queued messages have been sent, blocking" \
2320 " the thread until this is done."
2321 dbus.dbus_connection_flush(self._dbobj)
2322 #end flush
2323
2324 def read_write_dispatch(self, timeout = DBUS.TIMEOUT_USE_DEFAULT) :
2325 "dispatches the first available message, if any. Otherwise blocks the" \
2326 " thread until it can read or write, and does so before returning. Returns" \
2327 " True as long as the Connection remains connected."
2328 return \
2329 dbus.dbus_connection_read_write_dispatch(self._dbobj, _get_timeout(timeout)) != 0
2330 #end read_write_dispatch
2331
2332 def read_write(self, timeout = DBUS.TIMEOUT_USE_DEFAULT) :
2333 "blocks the thread until something can be read or written on the Connection," \
2334 " and does so, returning True. If the Connection has been disconnected," \
2335 " immediately returns False."
2336 return \
2337 dbus.dbus_connection_read_write(self._dbobj, _get_timeout(timeout)) != 0
2338 #end read_write
2339
2340 def borrow_message(self) :
2341 "tries to peek at the next available message waiting to be read, returning" \
2342 " None if these isn’t one. Call the Message’s return_borrowed() method" \
2343 " to return it to the queue, or steal_borrowed() to confirm that you have" \
2344 " read the message."
2345 msg = dbus.dbus_connection_borrow_message(self._dbobj)
2346 if msg != None :
2347 msg = Message(msg)
2348 msg._conn = self
2349 msg._borrowed = True
2350 #end if
2351 return \
2352 msg
2353 #end borrow_message
2354
2355 # returning/stealing borrowed messages done with
2356 # Message.return_borrowed and Message.steal_borrowed
2357
2358 def pop_message(self) :
2359 "returns the next available incoming Message, if any, otherwise returns None." \
2360 " Note this bypasses all message filtering/dispatching on this Connection."
2361 message = dbus.dbus_connection_pop_message(self._dbobj)
2362 if message != None :
2363 message = Message(message)
2364 #end if
2365 return \
2366 message
2367 #end pop_message
2368
2369 @property
2370 def dispatch_status(self) :
2371 "checks the state of the incoming message queue; returns a DISPATCH_XXX code."
2372 return \
2373 dbus.dbus_connection_get_dispatch_status(self._dbobj)
2374 #end dispatch_status
2375
2376 def dispatch(self) :
2377 "processes any available data, adding messages into the incoming" \
2378 " queue as appropriate. returns a DISPATCH_XXX code."
2379 return \
2380 dbus.dbus_connection_dispatch(self._dbobj)
2381 #end dispatch
2382
2383 def set_watch_functions(self, add_function, remove_function, toggled_function, data, free_data = None) :
2384 "sets the callbacks for libdbus to use to notify you of Watch objects it wants" \
2385 " you to manage."
2386
2387 def wrap_add_function(c_watch, _data) :
2388 return \
2389 add_function(Watch(c_watch), data)
2390 #end wrap_add_function
2391
2392 def wrap_remove_function(c_watch, _data) :
2393 return \
2394 remove_function(Watch(c_watch), data)
2395 #end wrap_remove_function
2396
2397 def wrap_toggled_function(c_watch, _data) :
2398 return \
2399 toggled_function(Watch(c_watch), data)
2400 #end wrap_toggled_function
2401
2402 def wrap_free_data(_data) :
2403 free_data(data)
2404 #end wrap_free_data
2405
2406 #begin set_watch_functions
2407 self._add_watch_function = DBUS.AddWatchFunction(wrap_add_function)
2408 self._remove_watch_function = DBUS.RemoveWatchFunction(wrap_remove_function)
2409 if toggled_function != None :
2410 self._toggled_watch_function = DBUS.WatchToggledFunction(wrap_toggled_function)
2411 else :
2412 self._toggled_watch_function = None
2413 #end if
2414 if free_data != None :
2415 self._free_watch_data = DBUS.FreeFunction(wrap_free_data)
2416 else :
2417 self._free_watch_data = None
2418 #end if
2419 if not dbus.dbus_connection_set_watch_functions(self._dbobj, self._add_watch_function, self._remove_watch_function, self._toggled_watch_function, None, self._free_watch_data) :
2420 raise CallFailed("dbus_connection_set_watch_functions")
2421 #end if
2422 #end set_watch_functions
2423
2424 def set_timeout_functions(self, add_function, remove_function, toggled_function, data, free_data = None) :
2425 "sets the callbacks for libdbus to use to notify you of Timeout objects it wants" \
2426 " you to manage."
2427
2428 def wrap_add_function(c_timeout, _data) :
2429 return \
2430 add_function(Timeout(c_timeout), data)
2431 #end wrap_add_function
2432
2433 def wrap_remove_function(c_timeout, _data) :
2434 return \
2435 remove_function(Timeout(c_timeout), data)
2436 #end wrap_remove_function
2437
2438 def wrap_toggled_function(c_timeout, _data) :
2439 return \
2440 toggled_function(Timeout(c_timeout), data)
2441 #end wrap_toggled_function
2442
2443 def wrap_free_data(_data) :
2444 free_data(data)
2445 #end wrap_free_data
2446
2447 #begin set_timeout_functions
2448 self._add_timeout_function = DBUS.AddTimeoutFunction(wrap_add_function)
2449 self._remove_timeout_function = DBUS.RemoveTimeoutFunction(wrap_remove_function)
2450 if toggled_function != None :
2451 self._toggled_timeout_function = DBUS.TimeoutToggledFunction(wrap_toggled_function)
2452 else :
2453 self._toggled_timeout_function = None
2454 #end if
2455 if free_data != None :
2456 self._free_timeout_data = DBUS.FreeFunction(wrap_free_data)
2457 else :
2458 self._free_timeout_data = None
2459 #end if
2460 if not dbus.dbus_connection_set_timeout_functions(self._dbobj, self._add_timeout_function, self._remove_timeout_function, self._toggled_timeout_function, None, self._free_timeout_data) :
2461 raise CallFailed("dbus_connection_set_timeout_functions")
2462 #end if
2463 #end set_timeout_functions
2464
2465 def set_wakeup_main_function(self, wakeup_main, data, free_data = None) :
2466 "sets the callback to use for libdbus to notify you that something has" \
2467 " happened requiring processing on the Connection."
2468
2469 def wrap_wakeup_main(_data) :
2470 wakeup_main(data)
2471 #end wrap_wakeup_main
2472
2473 def wrap_free_data(_data) :
2474 free_data(data)
2475 #end wrap_free_data
2476
2477 #begin set_wakeup_main_function
2478 if wakeup_main != None :
2479 self._wakeup_main = DBUS.WakeupMainFunction(wrap_wakeup_main)
2480 else :
2481 self._wakeup_main = None
2482 #end if
2483 if free_data != None :
2484 self._free_wakeup_main_data = DBUS.FreeFunction(wrap_free_data)
2485 else :
2486 self._free_wakeup_main_data = None
2487 #end if
2488 dbus.dbus_connection_set_wakeup_main_function(self._dbobj, self._wakeup_main, None, self._free_wakeup_main_data)
2489 #end set_wakeup_main_function
2490
2491 def set_dispatch_status_function(self, function, data, free_data = None) :
2492 "sets the callback to use for libdbus to notify you of a change in the" \
2493 " dispatch status of the Connection."
2494
2495 w_self = weak_ref(self)
2496
2497 def wrap_dispatch_status(_conn, status, _data) :
2498 function(_wderef(w_self, "connection"), status, data)
2499 #end wrap_dispatch_status
2500
2501 def wrap_free_data(_data) :
2502 free_data(data)
2503 #end wrap_free_data
2504
2505 #begin set_dispatch_status_function
2506 self._dispatch_status = DBUS.DispatchStatusFunction(wrap_dispatch_status)
2507 if free_data != None :
2508 self._free_wakeup_main_data = DBUS.FreeFunction(wrap_free_data)
2509 else :
2510 self._free_wakeup_main_data = None
2511 #end if
2512 dbus.dbus_connection_set_dispatch_status_function(self._dbobj, self._dispatch_status, None, self._free_wakeup_main_data)
2513 #end set_dispatch_status_function
2514
2515 @property
2516 def unix_fd(self) :
2517 c_fd = ct.c_int()
2518 if dbus.dbus_connection_get_unix_fd(self._dbobj, ct.byref(c_fd)) :
2519 result = c_fd.value
2520 else :
2521 result = None
2522 #end if
2523 return \
2524 result
2525 #end unix_fd
2526
2527 def fileno(self) :
2528 "for use with Python’s “select” functions."
2529 return \
2530 self.unix_fd
2531 #end fileno
2532
2533 @property
2534 def socket(self) :
2535 c_fd = ct.c_int()
2536 if dbus.dbus_connection_get_socket(self._dbobj, ct.byref(c_fd)) :
2537 result = c_fd.value
2538 else :
2539 result = None
2540 #end if
2541 return \
2542 result
2543 #end socket
2544
2545 @property
2546 def unix_process_id(self) :
2547 c_pid = ct.c_ulong()
2548 if dbus.dbus_connection_get_unix_process_id(self._dbobj, ct.byref(c_pid)) :
2549 result = c_pid.value
2550 else :
2551 result = None
2552 #end if
2553 return \
2554 result
2555 #end unix_process_id
2556
2557 @property
2558 def unix_user(self) :
2559 c_uid = ct.c_ulong()
2560 if dbus.dbus_connection_get_unix_user(self._dbobj, ct.byref(c_uid)) :
2561 result = c_uid.value
2562 else :
2563 result = None
2564 #end if
2565 return \
2566 result
2567 #end unix_user
2568
2569 # TODO: get_adt
2570
2571 def set_unix_user_function(self, allow_unix_user, data, free_data = None) :
2572
2573 w_self = weak_ref(self)
2574
2575 def wrap_allow_unix_user(c_conn, uid, c_data) :
2576 return \
2577 allow_unix_user(_wderef(w_self, "connection"), uid, data)
2578 #end wrap_allow_unix_user
2579
2580 def wrap_free_data(_data) :
2581 free_data(data)
2582 #end wrap_free_data
2583
2584 #begin set_unix_user_function
2585 if allow_unix_user != None :
2586 self._allow_unix_user = DBUS.AllowUnixUserFunction(wrap_allow_unix_user)
2587 else :
2588 self._allow_unix_user = None
2589 #end if
2590 if free_data != None :
2591 self._free_unix_user_data = DBUS.FreeFunction(wrap_free_data)
2592 else :
2593 self._free_unix_user_data = None
2594 #end if
2595 dbus.dbus_connection_set_unix_user_function(self._dbobj, self._allow_unix_user, None, self._free_unix_user_data)
2596 #end set_unix_user_function
2597
2598 def set_allow_anonymous(self, allow) :
2599 dbus.dbus_connection_set_allow_anonymous(self._dbobj, allow)
2600 #end set_allow_anonymous
2601
2602 def set_route_peer_messages(self, enable) :
2603 dbus.dbus_connection_set_route_peer_messages(self._dbobj, enable)
2604 #end set_route_peer_messages
2605
2606 def add_filter(self, function, user_data, free_data = None) :
2607 "adds a filter callback that gets to look at all incoming messages" \
2608 " before they get to the dispatch system. The same function can be added" \
2609 " multiple times as long as the user_data is different."
2610
2611 w_self = weak_ref(self)
2612
2613 def wrap_function(c_conn, c_message, _data) :
2614 self = _wderef(w_self, "connection")
2615 message = Message(dbus.dbus_message_ref(c_message))
2616 result = function(self, message, user_data)
2617 if asyncio.iscoroutine(result) :
2618 self.create_task(result)
2619 result = DBUS.HANDLER_RESULT_HANDLED
2620 #end if
2621 return \
2622 result
2623 #end wrap_function
2624
2625 def wrap_free_data(_data) :
2626 free_data(user_data)
2627 #end wrap_free_data
2628
2629 #begin add_filter
2630 filter_key = (function, data_key(user_data))
2631 filter_value = \
2632 {
2633 "function" : DBUS.HandleMessageFunction(wrap_function),
2634 "free_data" : (lambda : None, lambda : DBUS.FreeFunction(wrap_free_data))[free_data != None](),
2635 }
2636 # pass user_data id because libdbus identifies filter entry by both function address and user data address
2637 if not dbus.dbus_connection_add_filter(self._dbobj, filter_value["function"], filter_key[1], filter_value["free_data"]) :
2638 raise CallFailed("dbus_connection_add_filter")
2639 #end if
2640 self._filters[filter_key] = filter_value
2641 # need to ensure wrapped functions don’t disappear prematurely
2642 #end add_filter
2643
2644 def remove_filter(self, function, user_data) :
2645 "removes a message filter added by add_filter. The filter is identified" \
2646 " by both the function object and the user_data that was passed."
2647 filter_key = (function, data_key(user_data))
2648 if filter_key not in self._filters :
2649 raise KeyError("removing nonexistent Connection filter")
2650 #end if
2651 filter_value = self._filters[filter_key]
2652 # pass user_data id because libdbus identifies filter entry by both function address and user data address
2653 dbus.dbus_connection_remove_filter(self._dbobj, filter_value["function"], filter_key[1])
2654 del self._filters[filter_key]
2655 #end remove_filter
2656
2657 def register_object_path(self, path, vtable, user_data, error = None) :
2658 "registers an ObjectPathVTable as a dispatch handler for a specified" \
2659 " path within your object hierarchy."
2660 if not isinstance(vtable, ObjectPathVTable) :
2661 raise TypeError("vtable must be an ObjectPathVTable")
2662 #end if
2663 self._object_paths[path] = {"vtable" : vtable, "user_data" : user_data} # ensure it doesn’t disappear prematurely
2664 error, my_error = _get_error(error)
2665 if user_data != None :
2666 c_user_data = id(user_data)
2667 self._user_data[c_user_data] = user_data
2668 else :
2669 c_user_data = None
2670 #end if
2671 dbus.dbus_connection_try_register_object_path(self._dbobj, path.encode(), vtable._dbobj, c_user_data, error._dbobj)
2672 my_error.raise_if_set()
2673 #end register_object_path
2674
2675 def register_fallback(self, path, vtable, user_data, error = None) :
2676 "registers an ObjectPathVTable as a dispatch handler for an entire specified" \
2677 " subtree within your object hierarchy."
2678 if not isinstance(vtable, ObjectPathVTable) :
2679 raise TypeError("vtable must be an ObjectPathVTable")
2680 #end if
2681 self._object_paths[path] = {"vtable" : vtable, "user_data" : user_data} # ensure it doesn’t disappear prematurely
2682 error, my_error = _get_error(error)
2683 if user_data != None :
2684 c_user_data = id(user_data)
2685 self._user_data[c_user_data] = user_data
2686 else :
2687 c_user_data = None
2688 #end if
2689 dbus.dbus_connection_try_register_fallback(self._dbobj, path.encode(), vtable._dbobj, c_user_data, error._dbobj)
2690 my_error.raise_if_set()
2691 #end register_fallback
2692
2693 def unregister_object_path(self, path) :
2694 "removes a previously-registered ObjectPathVTable handler at a specified" \
2695 " point (single object or entire subtree) within your object hierarchy."
2696 if path not in self._object_paths :
2697 raise KeyError("unregistering unregistered path")
2698 #end if
2699 if not dbus.dbus_connection_unregister_object_path(self._dbobj, path.encode()) :
2700 raise CallFailed("dbus_connection_unregister_object_path")
2701 #end if
2702 user_data = self._object_paths[path]["user_data"]
2703 c_user_data = id(user_data)
2704 nr_remaining_refs = sum(int(self._object_paths[p]["user_data"] == user_data) for p in self._object_paths if p != path)
2705 if nr_remaining_refs == 0 :
2706 try :
2707 del self._user_data[c_user_data]
2708 except KeyError :
2709 pass
2710 #end try
2711 #end if
2712 del self._object_paths[path]
2713 #end unregister_object_path
2714
2715 def get_object_path_data(self, path) :
2716 "returns the user_data you passed when previously registering an ObjectPathVTable" \
2717 " that covers this path in your object hierarchy, or None if no suitable match" \
2718 " could be found."
2719 c_data_p = ct.c_void_p()
2720 if not dbus.dbus_connection_get_object_path_data(self._dbobj, path.encode(), ct.byref(c_data_p)) :
2721 raise CallFailed("dbus_connection_get_object_path_data")
2722 #end if
2723 return \
2724 self._user_data.get(c_data_p.value)
2725 #end get_object_path_data
2726
2727 def list_registered(self, parent_path) :
2728 "lists all the object paths for which you have ObjectPathVTable handlers registered."
2729 child_entries = ct.POINTER(ct.c_char_p)()
2730 if not dbus.dbus_connection_list_registered(self._dbobj, parent_path.encode(), ct.byref(child_entries)) :
2731 raise CallFailed("dbus_connection_list_registered")
2732 #end if
2733 result = []
2734 i = 0
2735 while True :
2736 entry = child_entries[i]
2737 if entry == None :
2738 break
2739 result.append(entry.decode())
2740 i += 1
2741 #end while
2742 dbus.dbus_free_string_array(child_entries)
2743 return \
2744 result
2745 #end list_registered
2746
2747 @staticmethod
2748 def _queue_received_message(self, message, _) :
2749 # message filter which queues messages as appropriate for receive_message_async.
2750 # Must be static so same function object can be passed to all add_filter/remove_filter
2751 # calls.
2752 queueit = message.type in self._receive_queue_enabled
2753 if queueit :
2754 self._receive_queue.append(message)
2755 while len(self._awaiting_receive) != 0 :
2756 # wake them all up, because I don’t know what message types
2757 # each might be waiting for
2758 waiting = self._awaiting_receive.pop(0)
2759 waiting.set_result(True) # result actually ignored
2760 #end while
2761 #end if
2762 return \
2763 (DBUS.HANDLER_RESULT_NOT_YET_HANDLED, DBUS.HANDLER_RESULT_HANDLED)[queueit]
2764 #end _queue_received_message
2765
2766 def enable_receive_message(self, queue_types) :
2767 "enables/disables message types for reception via receive_message_async." \
2768 " queue_types is a set or sequence of DBUS.MESSAGE_TYPE_XXX values for" \
2769 " the types of messages to be put into the receive queue, or None to" \
2770 " disable all message types; this replaces queue_types passed to" \
2771 " any prior enable_receive_message_async call on this Connection."
2772 assert self.loop != None, "no event loop to attach coroutines to"
2773 enable = queue_types != None and len(queue_types) != 0
2774 if (
2775 enable
2776 and
2777 not all
2778 (
2779 m
2780 in
2781 (
2782 DBUS.MESSAGE_TYPE_METHOD_CALL,
2783 DBUS.MESSAGE_TYPE_METHOD_RETURN,
2784 DBUS.MESSAGE_TYPE_ERROR,
2785 DBUS.MESSAGE_TYPE_SIGNAL,
2786 )
2787 for m in queue_types
2788 )
2789 ) :
2790 raise TypeError("invalid message type in queue_types: %s" % repr(queue_types))
2791 #end if
2792 if enable :
2793 if self._receive_queue == None :
2794 self.add_filter(self._queue_received_message, None)
2795 self._receive_queue = []
2796 #end if
2797 self._receive_queue_enabled.clear()
2798 self._receive_queue_enabled.update(queue_types)
2799 else :
2800 if self._receive_queue != None :
2801 self._flush_awaiting_receive()
2802 self.remove_filter(self._queue_received_message, None)
2803 self._receive_queue = None
2804 #end if
2805 #end if
2806 #end enable_receive_message
2807
2808 async def receive_message_async(self, want_types = None, timeout = DBUS.TIMEOUT_INFINITE) :
2809 "receives the first available queued message of an appropriate type, blocking" \
2810 " if none is available and timeout is nonzero. Returns None if the timeout" \
2811 " elapses without a suitable message becoming available. want_types can be" \
2812 " None to receive any of the previously-enabled message types, or a set or" \
2813 " sequence of DBUS.MESSAGE_TYPE_XXX values to look only for messages of those" \
2814 " types.\n" \
2815 "\n" \
2816 "You must have previously made a call to enable_receive_message to enable" \
2817 " queueing of one or more message types on this Connection."
2818 assert self._receive_queue != None, "receive_message_async not enabled"
2819 # should I check if want_types contains anything not in self._receive_queue_enabled?
2820 if timeout == DBUS.TIMEOUT_USE_DEFAULT :
2821 timeout = DBUSX.DEFAULT_TIMEOUT
2822 #end if
2823 if timeout != DBUS.TIMEOUT_INFINITE :
2824 finish_time = self.loop.time() + timeout
2825 else :
2826 finish_time = None
2827 #end if
2828 result = ... # indicates “watch this space”
2829 while True :
2830 # keep rescanning queue until got something or timeout
2831 index = 0 # start next queue scan
2832 while True :
2833 if index == len(self._receive_queue) :
2834 # nothing currently suitable on queue
2835 if (
2836 timeout == 0
2837 or
2838 finish_time != None
2839 and
2840 self.loop.time() > finish_time
2841 ) :
2842 # waited too long, give up
2843 result = None
2844 break
2845 #end if
2846 if not self.is_connected :
2847 raise BrokenPipeError("Connection has been disconnected")
2848 #end if
2849 # wait and see if something turns up
2850 awaiting = self.loop.create_future()
2851 self._awaiting_receive.append(awaiting)
2852 if finish_time != None :
2853 wait_timeout = finish_time - self.loop.time()
2854 else :
2855 wait_timeout = None
2856 #end if
2857 await self.wait \
2858 (
2859 (awaiting,),
2860 timeout = wait_timeout
2861 )
2862 # ignore done & pending results because they
2863 # don’t match up with future I’m waiting for
2864 try :
2865 self._awaiting_receive.remove(awaiting)
2866 except ValueError :
2867 pass
2868 #end try
2869 awaiting.cancel()
2870 # just to avoid “Future exception was never retrieved” message
2871 break # start new queue scan
2872 #end if
2873 # check next queue item
2874 msg = self._receive_queue[index]
2875 if want_types == None or msg.type in want_types :
2876 # caller wants this one
2877 result = msg
2878 self._receive_queue.pop(index) # remove msg from queue
2879 break
2880 #end if
2881 index += 1
2882 #end while
2883 if result != ... :
2884 # either got something or given up
2885 break
2886 #end while
2887 return \
2888 result
2889 #end receive_message_async
2890
2891 def iter_messages_async(self, want_types = None, stop_on = None, timeout = DBUS.TIMEOUT_INFINITE) :
2892 "wrapper around receive_message_async() to allow use with an async-for statement." \
2893 " Lets you write\n" \
2894 "\n" \
2895 " async for message in «conn».iter_messages_async(«want_types», «stop_on», «timeout») :" \
2896 " «process message»\n" \
2897 " #end for\n" \
2898 "\n" \
2899 "to receive and process messages in a loop. stop_on is an optional set of" \
2900 " STOP_ON.xxx values indicating the conditions under which the iterator will" \
2901 " raise StopAsyncIteration to terminate the loop."
2902 if stop_on == None :
2903 stop_on = frozenset()
2904 elif (
2905 not isinstance(stop_on, (set, frozenset))
2906 or
2907 not all(isinstance(elt, STOP_ON) for elt in stop_on)
2908 ) :
2909 raise TypeError("stop_on must be None or set of STOP_ON")
2910 #end if
2911 assert self._receive_queue != None, "receive_message_async not enabled"
2912 return \
2913 _MsgAiter(self, want_types, stop_on, timeout)
2914 #end iter_messages_async
2915
2916 # TODO: allocate/free data slot -- staticmethods
2917 # TODO: get/set data
2918
2919 def set_change_sigpipe(self, will_modify_sigpipe) :
2920 dbus.dbus_connection_set_change_sigpipe(self._dbobj, will_modify_sigpipe)
2921 #end set_change_sigpipe
2922
2923 @property
2924 def max_message_size(self) :
2925 return \
2926 dbus.dbus_connection_get_max_message_size(self._dbobj)
2927 #end max_message_size
2928
2929 @max_message_size.setter
2930 def max_message_size(self, size) :
2931 dbus.dbus_connection_set_max_message_size(self._dbobj, size)
2932 #end max_message_size
2933
2934 @property
2935 def max_received_size(self) :
2936 return \
2937 dbus.dbus_connection_get_max_received_size(self._dbobj)
2938 #end max_received_size
2939
2940 @max_received_size.setter
2941 def max_received_size(self, size) :
2942 dbus.dbus_connection_set_max_received_size(self._dbobj, size)
2943 #end max_received_size
2944
2945 @property
2946 def max_message_unix_fds(self) :
2947 return \
2948 dbus.dbus_connection_get_max_message_unix_fds(self._dbobj)
2949 #end max_message_unix_fds
2950
2951 @max_message_unix_fds.setter
2952 def max_message_unix_fds(self, size) :
2953 dbus.dbus_connection_set_max_message_unix_fds(self._dbobj, size)
2954 #end max_message_unix_fds
2955
2956 @property
2957 def max_received_unix_fds(self) :
2958 return \
2959 dbus.dbus_connection_get_max_received_unix_fds(self._dbobj)
2960 #end max_received_unix_fds
2961
2962 @max_received_unix_fds.setter
2963 def max_received_unix_fds(self, size) :
2964 dbus.dbus_connection_set_max_received_unix_fds(self._dbobj, size)
2965 #end max_received_unix_fds
2966
2967 @property
2968 def outgoing_size(self) :
2969 return \
2970 dbus.dbus_connection_get_outgoing_size(self._dbobj)
2971 #end outgoing_size
2972
2973 @property
2974 def outgoing_unix_fds(self) :
2975 return \
2976 dbus.dbus_connection_get_outgoing_unix_fds(self._dbobj)
2977 #end outgoing_unix_fds
2978
2979 @property
2980 def has_messages_to_send(self) :
2981 return \
2982 dbus.dbus_connection_has_messages_to_send(self._dbobj) != 0
2983 #end has_messages_to_send
2984
2985 # message bus APIs
2986 # <https://dbus.freedesktop.org/doc/api/html/group__DBusBus.html>
2987
2988 @classmethod
2989 def bus_get(celf, type, private, error = None) :
2990 "returns a Connection to one of the predefined D-Bus buses; type is a BUS_xxx value."
2991 error, my_error = _get_error(error)
2992 result = (dbus.dbus_bus_get, dbus.dbus_bus_get_private)[private](type, error._dbobj)
2993 my_error.raise_if_set()
2994 if result != None :
2995 result = celf(result)
2996 #end if
2997 return \
2998 result
2999 #end bus_get
3000
3001 @classmethod
3002 async def bus_get_async(celf, type, private, error = None, loop = None, timeout = DBUS.TIMEOUT_USE_DEFAULT) :
3003 if loop == None :
3004 loop = get_running_loop()
3005 #end if
3006 assert type in (DBUS.BUS_SESSION, DBUS.BUS_SYSTEM, DBUS.BUS_STARTER), \
3007 "bus type must be BUS_SESSION, BUS_SYSTEM or BUS_STARTER"
3008 if type == DBUS.BUS_STARTER :
3009 starter_type = os.environ.get(DBUSX.STARTER_BUS_ADDRESS_TYPE)
3010 is_system_bus = starter_type != None and starter_type == DBUSX.BUS_TYPE_SYSTEM
3011 addr = os.environ.get(DBUSX.STARTER_BUS_ADDRESS_VAR)
3012 else :
3013 is_system_bus = type == DBUS.BUS_SYSTEM
3014 addr = os.environ.get \
3015 (
3016 (DBUSX.SESSION_BUS_ADDRESS_VAR, DBUSX.SYSTEM_BUS_ADDRESS_VAR)[is_system_bus]
3017 )
3018 #end if
3019 if not private and celf._shared_connections[is_system_bus] != None :
3020 result = celf._shared_connections[is_system_bus]
3021 else :
3022 if addr == None :
3023 addr = (DBUSX.SESSION_BUS_ADDRESS, DBUSX.SYSTEM_BUS_ADDRESS)[is_system_bus]
3024 #end if
3025 try :
3026 result = await celf.open_async(addr, private, error, loop, timeout)
3027 if error != None and error.is_set :
3028 raise _Abort
3029 #end if
3030 await result.bus_register_async(error = error, timeout = timeout)
3031 if error != None and error.is_set :
3032 raise _Abort
3033 #end if
3034 if not private :
3035 celf._shared_connections[is_system_bus] = result
3036 #end if
3037 except _Abort :
3038 result = None
3039 #end try
3040 #end if
3041 return \
3042 result
3043 #end bus_get_async
3044
3045 def bus_register(self, error = None) :
3046 "Only to be used if you created the Connection with open() instead of bus_get();" \
3047 " sends a “Hello” message to the D-Bus daemon to get a unique name assigned." \
3048 " Can only be called once."
3049 error, my_error = _get_error(error)
3050 dbus.dbus_bus_register(self._dbobj, error._dbobj)
3051 my_error.raise_if_set()
3052 #end bus_register
3053
3054 async def bus_register_async(self, error = None, timeout = DBUS.TIMEOUT_USE_DEFAULT) :
3055 "Only to be used if you created the Connection with open() instead of bus_get();" \
3056 " sends a “Hello” message to the D-Bus daemon to get a unique name assigned." \
3057 " Can only be called once."
3058 assert self.loop != None, "no event loop to attach coroutine to"
3059 assert self.bus_unique_name == None, "bus already registered"
3060 message = Message.new_method_call \
3061 (
3062 destination = DBUS.SERVICE_DBUS,
3063 path = DBUS.PATH_DBUS,
3064 iface = DBUS.INTERFACE_DBUS,
3065 method = "Hello"
3066 )
3067 reply = await self.send_await_reply(message, timeout = timeout)
3068 if error != None and reply.type == DBUS.MESSAGE_TYPE_ERROR :
3069 reply.set_error(error)
3070 else :
3071 self.bus_unique_name = reply.expect_return_objects("s")[0]
3072 #end if
3073 #end bus_register_async
3074
3075 @property
3076 def bus_unique_name(self) :
3077 "returns None if the bus connection has not been registered. Note that the" \
3078 " unique_name can only be set once."
3079 result = dbus.dbus_bus_get_unique_name(self._dbobj)
3080 if result != None :
3081 result = result.decode()
3082 #end if
3083 return \
3084 result
3085 #end bus_unique_name
3086
3087 @bus_unique_name.setter
3088 def bus_unique_name(self, unique_name) :
3089 if not dbus.dbus_bus_set_unique_name(self._dbobj, unique_name.encode()) :
3090 raise CallFailed("dbus_bus_set_unique_name")
3091 #end if
3092 #end bus_unique_name
3093
3094 #+
3095 # Calls to D-Bus Daemon
3096 #-
3097
3098 @property
3099 def bus_id(self) :
3100 my_error = Error()
3101 c_result = dbus.dbus_bus_get_id(self._dbobj, my_error._dbobj)
3102 my_error.raise_if_set()
3103 result = ct.cast(c_result, ct.c_char_p).value.decode()
3104 dbus.dbus_free(c_result)
3105 return \
3106 result
3107 #end bus_id
3108
3109 @property
3110 async def bus_id_async(self) :
3111 message = Message.new_method_call \
3112 (
3113 destination = DBUS.SERVICE_DBUS,
3114 path = DBUS.PATH_DBUS,
3115 iface = DBUS.INTERFACE_DBUS,
3116 method = "GetId"
3117 )
3118 reply = await self.send_await_reply(message)
3119 return \
3120 reply.expect_return_objects("s")[0]
3121 #end bus_id_async
3122
3123 def bus_get_unix_user(self, name, error = None) :
3124 error, my_error = _get_error(error)
3125 result = dbus.dbus_bus_get_unix_user(self._dbobj, name.encode(), error._dbobj)
3126 my_error.raise_if_set()
3127 return \
3128 result
3129 #end bus_get_unix_user
3130
3131 async def bus_get_unix_user_async(self, name, error = None, timeout = DBUS.TIMEOUT_USE_DEFAULT) :
3132 message = Message.new_method_call \
3133 (
3134 destination = DBUS.SERVICE_DBUS,
3135 path = DBUS.PATH_DBUS,
3136 iface = DBUS.INTERFACE_DBUS,
3137 method = "GetConnectionUnixUser"
3138 )
3139 message.append_objects("s", name)
3140 reply = await self.send_await_reply(message, timeout = timeout)
3141 if error != None and reply.type == DBUS.MESSAGE_TYPE_ERROR :
3142 reply.set_error(error)
3143 result = None
3144 else :
3145 result = reply.expect_return_objects("u")[0]
3146 #end if
3147 return \
3148 result
3149 #end bus_get_unix_user_async
3150
3151 def bus_request_name(self, name, flags, error = None) :
3152 "asks the D-Bus daemon to register the specified bus name on your behalf," \
3153 " blocking the thread until the reply is received. flags is a combination of" \
3154 " NAME_FLAG_xxx bits. Result will be a REQUEST_NAME_REPLY_xxx value or -1 on error."
3155 error, my_error = _get_error(error)
3156 result = dbus.dbus_bus_request_name(self._dbobj, name.encode(), flags, error._dbobj)
3157 my_error.raise_if_set()
3158 return \
3159 result
3160 #end bus_request_name
3161
3162 async def bus_request_name_async(self, name, flags, error = None, timeout = DBUS.TIMEOUT_USE_DEFAULT) :
3163 "asks the D-Bus daemon to register the specified bus name on your behalf. flags is" \
3164 " a combination of NAME_FLAG_xxx bits. Result will be a REQUEST_NAME_REPLY_xxx value" \
3165 " or None on error."
3166 message = Message.new_method_call \
3167 (
3168 destination = DBUS.SERVICE_DBUS,
3169 path = DBUS.PATH_DBUS,
3170 iface = DBUS.INTERFACE_DBUS,
3171 method = "RequestName"
3172 )
3173 message.append_objects("su", name, flags)
3174 reply = await self.send_await_reply(message, timeout = timeout)
3175 if error != None and reply.type == DBUS.MESSAGE_TYPE_ERROR :
3176 reply.set_error(error)
3177 result = None
3178 else :
3179 result = reply.expect_return_objects("u")[0]
3180 #end if
3181 return \
3182 result
3183 #end bus_request_name_async
3184
3185 def bus_release_name(self, name, error = None) :
3186 "asks the D-Bus daemon to release your registration of the specified bus name," \
3187 " blocking the thread until the reply is received."
3188 error, my_error = _get_error(error)
3189 result = dbus.dbus_bus_release_name(self._dbobj, name.encode(), error._dbobj)
3190 my_error.raise_if_set()
3191 return \
3192 result
3193 #end bus_release_name
3194
3195 async def bus_release_name_async(self, name, error = None, timeout = DBUS.TIMEOUT_USE_DEFAULT) :
3196 "asks the D-Bus daemon to release your registration of the specified bus name."
3197 message = Message.new_method_call \
3198 (
3199 destination = DBUS.SERVICE_DBUS,
3200 path = DBUS.PATH_DBUS,
3201 iface = DBUS.INTERFACE_DBUS,
3202 method = "ReleaseName"
3203 )
3204 message.append_objects("s", name)
3205 reply = await self.send_await_reply(message, timeout = timeout)
3206 if error != None and reply.type == DBUS.MESSAGE_TYPE_ERROR :
3207 reply.set_error(error)
3208 result = None
3209 else :
3210 result = reply.expect_return_objects("u")[0]
3211 #end if
3212 return \
3213 result
3214 #end bus_release_name_async
3215
3216 def bus_name_has_owner(self, name, error = None) :
3217 "asks the D-Bus daemon if anybody has claimed the specified bus name, blocking" \
3218 " the thread until the reply is received."
3219 error, my_error = _get_error(error)
3220 result = dbus.dbus_bus_name_has_owner(self._dbobj, name.encode(), error._dbobj)
3221 my_error.raise_if_set()
3222 return \
3223 result
3224 #end bus_name_has_owner
3225
3226 async def bus_name_has_owner_async(self, name, error = None, timeout = DBUS.TIMEOUT_USE_DEFAULT) :
3227 "asks the D-Bus daemon if anybody has claimed the specified bus name."
3228 message = Message.new_method_call \
3229 (
3230 destination = DBUS.SERVICE_DBUS,
3231 path = DBUS.PATH_DBUS,
3232 iface = DBUS.INTERFACE_DBUS,
3233 method = "NameHasOwner"
3234 )
3235 message.append_objects("s", name)
3236 reply = await self.send_await_reply(message, timeout = timeout)
3237 if error != None and reply.type == DBUS.MESSAGE_TYPE_ERROR :
3238 reply.set_error(error)
3239 result = None
3240 else :
3241 result = reply.expect_return_objects("b")[0]
3242 #end if
3243 return \
3244 result
3245 #end bus_name_has_owner_async
3246
3247 def bus_start_service_by_name(self, name, flags = 0, error = None) :
3248 error, my_error = _get_error(error)
3249 outflags = ct.c_uint()
3250 success = dbus.dbus_bus_start_service_by_name(self._dbobj, name.encode(), flags, ct.byref(outflags), error._dbobj)
3251 my_error.raise_if_set()
3252 return \
3253 outflags.value
3254 #end bus_start_service_by_name
3255
3256 async def bus_start_service_by_name_async(self, name, flags = 0, error = None, timeout = DBUS.TIMEOUT_USE_DEFAULT) :
3257 message = Message.new_method_call \
3258 (
3259 destination = DBUS.SERVICE_DBUS,
3260 path = DBUS.PATH_DBUS,
3261 iface = DBUS.INTERFACE_DBUS,
3262 method = "StartServiceByName"
3263 )
3264 message.append_objects("su", name, flags)
3265 reply = await self.send_await_reply(message, timeout = timeout)
3266 if error != None and reply.type == DBUS.MESSAGE_TYPE_ERROR :
3267 reply.set_error(error)
3268 result = None
3269 else :
3270 result = reply.expect_return_objects("u")[0]
3271 #end if
3272 return \
3273 result
3274 #end bus_start_service_by_name
3275
3276 def bus_add_match(self, rule, error = None) :
3277 "adds a match rule for messages you want to receive. By default you get all" \
3278 " messages addressed to your bus name(s); but you can use this, for example," \
3279 " to request notification of signals indicating useful events on the system."
3280 error, my_error = _get_error(error)
3281 dbus.dbus_bus_add_match(self._dbobj, format_rule(rule).encode(), error._dbobj)
3282 my_error.raise_if_set()
3283 #end bus_add_match
3284
3285 async def bus_add_match_async(self, rule, error = None, timeout = DBUS.TIMEOUT_USE_DEFAULT) :
3286 "adds a match rule for messages you want to receive. By default you get all" \
3287 " messages addressed to your bus name(s); but you can use this, for example," \
3288 " to request notification of signals indicating useful events on the system."
3289 message = Message.new_method_call \
3290 (
3291 destination = DBUS.SERVICE_DBUS,
3292 path = DBUS.PATH_DBUS,
3293 iface = DBUS.INTERFACE_DBUS,
3294 method = "AddMatch"
3295 )
3296 message.append_objects("s", format_rule(rule))
3297 reply = await self.send_await_reply(message, timeout = timeout)
3298 if error != None and reply.type == DBUS.MESSAGE_TYPE_ERROR :
3299 reply.set_error(error)
3300 else :
3301 reply.expect_return_objects("")
3302 #end if
3303 #end bus_add_match_async
3304
3305 def bus_remove_match(self, rule, error = None) :
3306 "removes a previously-added match rule for messages you previously wanted" \
3307 " to receive."
3308 error, my_error = _get_error(error)
3309 dbus.dbus_bus_remove_match(self._dbobj, format_rule(rule).encode(), error._dbobj)
3310 my_error.raise_if_set()
3311 #end bus_remove_match
3312
3313 async def bus_remove_match_async(self, rule, error = None, timeout = DBUS.TIMEOUT_USE_DEFAULT) :
3314 "removes a previously-added match rule for messages you previously wanted" \
3315 " to receive."
3316 message = Message.new_method_call \
3317 (
3318 destination = DBUS.SERVICE_DBUS,
3319 path = DBUS.PATH_DBUS,
3320 iface = DBUS.INTERFACE_DBUS,
3321 method = "RemoveMatch"
3322 )
3323 message.append_objects("s", format_rule(rule))
3324 reply = await self.send_await_reply(message, timeout = timeout)
3325 if error != None and reply.type == DBUS.MESSAGE_TYPE_ERROR :
3326 reply.set_error(error)
3327 else :
3328 reply.expect_return_objects("")
3329 #end if
3330 #end bus_remove_match_async
3331
3332 @staticmethod
3333 def _rule_action_match(self, message, _) :
3334 # installed as a message filter to invoke actions corresponding to rules
3335 # that the message matches. To avoid spurious method-not-handled errors
3336 # from eavesdropping on method calls not addressed to me, this routine
3337 # always returns a “handled” status. That means this same Connection
3338 # object should not be used for both eavesdropping and for normal
3339 # method calls.
3340 handled = False
3341 for entry in self._match_actions.values() :
3342 if matches_rule(message, entry.rule) :
3343 for action in entry.actions :
3344 result = action.func(self, message, action.user_data)
3345 if asyncio.iscoroutine(result) :
3346 self.create_task(result)
3347 #end if
3348 #end for
3349 handled = True # passed to at least one handler
3350 #end if
3351 #end for
3352 return \
3353 (DBUS.HANDLER_RESULT_NOT_YET_HANDLED, DBUS.HANDLER_RESULT_HANDLED)[handled]
3354 #end _rule_action_match
3355
3356 def bus_add_match_action(self, rule, func, user_data, error = None) :
3357 "adds a message filter that invokes func(conn, message, user_data)" \
3358 " for each incoming message that matches the specified rule. Unlike" \
3359 " the underlying add_filter and bus_add_match calls, this allows you" \
3360 " to associate the action with the particular matching rule.\n" \
3361 "\n" \
3362 "Note that the message filter installed to process these rules always" \
3363 " returns a DBUS.HANDLER_RESULT_HANDLED status; so either only use this" \
3364 " to listen for signals, or do not use the same Connection object to" \
3365 " handle normal method calls."
3366 rulekey = format_rule(rule)
3367 rule = unformat_rule(rule)
3368 if rulekey not in self._match_actions :
3369 self.bus_add_match(rulekey, error) # could fail here with bad rule
3370 if error == None or not error.is_set :
3371 if len(self._match_actions) == 0 :
3372 self.add_filter(self._rule_action_match, None)
3373 #end if
3374 self._match_actions[rulekey] = _MatchActionEntry(rule)
3375 #end if
3376 #end if
3377 if error == None or not error.is_set :
3378 self._match_actions[rulekey].actions.add(_MatchActionEntry._Action(func, user_data))
3379 #end if
3380 #end bus_add_match_action
3381
3382 def bus_remove_match_action(self, rule, func, user_data, error = None) :
3383 "removes a message filter previously installed with bus_add_match_action."
3384 rulekey = format_rule(rule)
3385 rule = unformat_rule(rule)
3386 self._match_actions[rulekey].actions.remove(_MatchActionEntry._Action(func, user_data))
3387 if len(self._match_actions[rulekey].actions) == 0 :
3388 self.bus_remove_match(rulekey, error) # shouldn’t fail!
3389 del self._match_actions[rulekey]
3390 if len(self._match_actions) == 0 :
3391 self.remove_filter(self._rule_action_match, None)
3392 #end if
3393 #end if
3394 #end bus_remove_match_action
3395
3396 async def bus_add_match_action_async(self, rule, func, user_data, error = None, timeout = DBUS.TIMEOUT_USE_DEFAULT) :
3397 "adds a message filter that invokes func(conn, message, user_data)" \
3398 " for each incoming message that matches the specified rule. Unlike" \
3399 " the underlying add_filter and bus_add_match calls, this allows you" \
3400 " to associate the action with the particular matching rule.\n" \
3401 "\n" \
3402 "Note that the message filter installed to process these rules always" \
3403 " returns a DBUS.HANDLER_RESULT_HANDLED status; so either only use this" \
3404 " to listen for signals, or do not use the same Connection object to" \
3405 " handle normal method calls."
3406 rulekey = format_rule(rule)
3407 rule = unformat_rule(rule)
3408 if rulekey not in self._match_actions :
3409 await self.bus_add_match_async(rulekey, error, timeout) # could fail here with bad rule
3410 if error == None or not error.is_set :
3411 if len(self._match_actions) == 0 :
3412 self.add_filter(self._rule_action_match, None)
3413 #end if
3414 self._match_actions[rulekey] = _MatchActionEntry(rule)
3415 #end if
3416 #end if
3417 if error == None or not error.is_set :
3418 self._match_actions[rulekey].actions.add(_MatchActionEntry._Action(func, user_data))
3419 #end if
3420 #end bus_add_match_action_async
3421
3422 async def bus_remove_match_action_async(self, rule, func, user_data, error = None, timeout = DBUS.TIMEOUT_USE_DEFAULT) :
3423 "removes a message filter previously installed with bus_add_match_action."
3424 rulekey = format_rule(rule)
3425 rule = unformat_rule(rule)
3426 self._match_actions[rulekey].actions.remove(_MatchActionEntry._Action(func, user_data))
3427 if len(self._match_actions[rulekey].actions) == 0 :
3428 await self.bus_remove_match_async(rulekey, error, timeout) # shouldn’t fail!
3429 del self._match_actions[rulekey]
3430 if len(self._match_actions) == 0 :
3431 self.remove_filter(self._rule_action_match, None)
3432 #end if
3433 #end if
3434 #end bus_remove_match_action_async
3435
3436 def become_monitor(self, rules) :
3437 "turns the connection into one that can only receive monitoring messages."
3438 message = Message.new_method_call \
3439 (
3440 destination = DBUS.SERVICE_DBUS,
3441 path = DBUS.PATH_DBUS,
3442 iface = DBUS.INTERFACE_MONITORING,
3443 method = "BecomeMonitor"
3444 )
3445 message.append_objects("asu", (list(format_rule(rule) for rule in rules)), 0)
3446 self.send(message)
3447 #end become_monitor
3448
3449 #+
3450 # End calls to D-Bus Daemon
3451 #-
3452
3453 def attach_asyncio(self, loop = None) :
3454 "attaches this Connection object to an asyncio event loop. If none is" \
3455 " specified, the default event loop (as returned from asyncio.get_event_loop()" \
3456 " is used."
3457
3458 w_self = weak_ref(self)
3459 # to avoid a reference cycle
3460
3461 def dispatch() :
3462 return \
3463 _wderef(w_self, "connection").dispatch()
3464 #end dispatch
3465
3466 #begin attach_asyncio
3467 assert self.loop == None, "already attached to an event loop"
3468 _loop_attach(self, loop, dispatch)
3469 #end attach_asyncio
3470
3471 #end Connection
3472
3473 class _MsgAiter :
3474 # internal class for use by Connection.iter_messages_async (above).
3475
3476 def __init__(self, conn, want_types, stop_on, timeout) :
3477 self.conn = conn
3478 self.want_types = want_types
3479 self.stop_on = stop_on
3480 self.timeout = timeout
3481 #end __init__
3482
3483 def __aiter__(self) :
3484 # I’m my own iterator.
3485 return \
3486 self
3487 #end __aiter__
3488
3489 async def __anext__(self) :
3490 stop_iter = False
3491 try :
3492 result = await self.conn.receive_message_async(self.want_types, self.timeout)
3493 if result == None and STOP_ON.TIMEOUT in self.stop_on :
3494 stop_iter = True
3495 #end if
3496 except BrokenPipeError :
3497 if STOP_ON.CLOSED not in self.stop_on :
3498 raise
3499 #end if
3500 stop_iter = True
3501 #end try
3502 if stop_iter :
3503 raise StopAsyncIteration("Connection.receive_message_async terminating")
3504 #end if
3505 return \
3506 result
3507 #end __anext__
3508
3509 #end _MsgAiter
3510
3511 class Server(TaskKeeper) :
3512 "wrapper around a DBusServer object. Do not instantiate directly; use" \
3513 " the listen method.\n" \
3514 "\n" \
3515 "You only need this if you want to use D-Bus as a communication mechanism" \
3516 " separate from the system/session buses provided by the D-Bus daemon: you" \
3517 " create a Server object listening on a specified address, and clients can" \
3518 " use Connection.open() to connect to you on that address."
3519 # <https://dbus.freedesktop.org/doc/api/html/group__DBusServer.html>
3520
3521 # Doesn’t really need services of TaskKeeper for now, but might be
3522 # useful in future
3523
3524 __slots__ = \
3525 (
3526 "_dbobj",
3527 "_new_connections",
3528 "_await_new_connections",
3529 "max_new_connections",
3530 "autoattach_new_connections",
3531 # need to keep references to ctypes-wrapped functions
3532 # so they don't disappear prematurely:
3533 "_new_connection_function",
3534 "_free_new_connection_data",
3535 "_add_watch_function",
3536 "_remove_watch_function",
3537 "_toggled_watch_function",
3538 "_free_watch_data",
3539 "_add_timeout_function",
3540 "_remove_timeout_function",
3541 "_toggled_timeout_function",
3542 "_free_timeout_data",
3543 ) # to forestall typos
3544
3545 _instances = WeakValueDictionary()
3546
3547 def __new__(celf, _dbobj) :
3548 self = celf._instances.get(_dbobj)
3549 if self == None :
3550 self = super().__new__(celf)
3551 super()._init(self)
3552 self._dbobj = _dbobj
3553 self._new_connections = None
3554 self._await_new_connections = None
3555 self.max_new_connections = None
3556 self.autoattach_new_connections = True
3557 self._new_connection_function = None
3558 self._free_new_connection_data = None
3559 self._add_watch_function = None
3560 self._remove_watch_function = None
3561 self._toggled_watch_function = None
3562 self._free_watch_data = None
3563 self._add_timeout_function = None
3564 self._remove_timeout_function = None
3565 self._toggled_timeout_function = None
3566 self._free_timeout_data = None
3567 celf._instances[_dbobj] = self
3568 else :
3569 dbus.dbus_server_unref(self._dbobj)
3570 # lose extra reference created by caller
3571 #end if
3572 return \
3573 self
3574 #end __new__
3575
3576 def __del__(self) :
3577 if self._dbobj != None :
3578 if self.loop != None :
3579 # remove via direct low-level libdbus calls
3580 dbus.dbus_server_set_watch_functions(self._dbobj, None, None, None, None, None)
3581 dbus.dbus_server_set_timeout_functions(self._dbobj, None, None, None, None, None)
3582 self.loop = None
3583 #end if
3584 dbus.dbus_server_unref(self._dbobj)
3585 self._dbobj = None
3586 #end if
3587 #end __del__
3588
3589 @classmethod
3590 def listen(celf, address, error = None) :
3591 error, my_error = _get_error(error)
3592 result = dbus.dbus_server_listen(address.encode(), error._dbobj)
3593 my_error.raise_if_set()
3594 if result != None :
3595 result = celf(result)
3596 #end if
3597 return \
3598 result
3599 #end listen
3600
3601 def _flush_awaiting_connect(self) :
3602 if self._await_new_connections != None :
3603 while len(self._await_new_connections) != 0 :
3604 waiting = self._await_new_connections.pop(0)
3605 waiting.set_exception(BrokenPipeError("async listens have been disabled"))
3606 #end while
3607 #end if
3608 #end _flush_awaiting_connect
3609
3610 def disconnect(self) :
3611 self._flush_awaiting_connect()
3612 dbus.dbus_server_disconnect(self._dbobj)
3613 #end disconnect
3614
3615 @property
3616 def is_connected(self) :
3617 return \
3618 dbus.dbus_server_get_is_connected(self._dbobj) != 0
3619 #end is_connected
3620
3621 @property
3622 def address(self) :
3623 c_result = dbus.dbus_server_get_address(self._dbobj)
3624 if c_result == None :
3625 raise CallFailed("dbus_server_get_address")
3626 #end if
3627 result = ct.cast(c_result, ct.c_char_p).value.decode()
3628 dbus.dbus_free(c_result)
3629 return \
3630 result
3631 #end address
3632
3633 @property
3634 def id(self) :
3635 c_result = dbus.dbus_server_get_id(self._dbobj)
3636 if c_result == None :
3637 raise CallFailed("dbus_server_get_id")
3638 #end if
3639 result = ct.cast(c_result, ct.c_char_p).value.decode()
3640 dbus.dbus_free(c_result)
3641 return \
3642 result
3643 #end id
3644
3645 def set_new_connection_function(self, function, data, free_data = None) :
3646 "sets the callback for libdbus to notify you of a new incoming connection." \
3647 " It is up to you to save the Connection object for later processing of" \
3648 " messages, or close it to reject the connection attempt."
3649
3650 w_self = weak_ref(self)
3651
3652 def wrap_function(c_self, c_conn, _data) :
3653 function(_wderef(w_self, "server"), Connection(dbus.dbus_connection_ref(c_conn)), data)
3654 # even though this is a new connection, I still have to reference it
3655 #end wrap_function
3656
3657 def wrap_free_data(_data) :
3658 free_data(data)
3659 #end wrap_free_data
3660
3661 #begin set_new_connection_function
3662 assert self.loop == None, "new connections are being managed by an event loop"
3663 self._new_connection_function = DBUS.NewConnectionFunction(wrap_function)
3664 if free_data != None :
3665 self._free_new_connection_data = DBUS.FreeFunction(wrap_free_data)
3666 else :
3667 self._free_new_connection_data = None
3668 #end if
3669 dbus.dbus_server_set_new_connection_function(self._dbobj, self._new_connection_function, None, self._free_new_connection_data)
3670 #end set_new_connection_function
3671
3672 def set_watch_functions(self, add_function, remove_function, toggled_function, data, free_data = None) :
3673 "sets the callbacks for libdbus to use to notify you of Watch objects it wants" \
3674 " you to manage."
3675
3676 def wrap_add_function(c_watch, _data) :
3677 return \
3678 add_function(Watch(c_watch), data)
3679 #end wrap_add_function
3680
3681 def wrap_remove_function(c_watch, _data) :
3682 return \
3683 remove_function(Watch(c_watch), data)
3684 #end wrap_remove_function
3685
3686 def wrap_toggled_function(c_watch, _data) :
3687 return \
3688 toggled_function(Watch(c_watch), data)
3689 #end wrap_toggled_function
3690
3691 def wrap_free_data(_data) :
3692 free_data(data)
3693 #end wrap_free_data
3694
3695 #begin set_watch_functions
3696 self._add_watch_function = DBUS.AddWatchFunction(wrap_add_function)
3697 self._remove_watch_function = DBUS.RemoveWatchFunction(wrap_remove_function)
3698 if toggled_function != None :
3699 self._toggled_watch_function = DBUS.WatchToggledFunction(wrap_toggled_function)
3700 else :
3701 self._toggled_watch_function = None
3702 #end if
3703 if free_data != None :
3704 self._free_watch_data = DBUS.FreeFunction(wrap_free_data)
3705 else :
3706 self._free_watch_data = None
3707 #end if
3708 if not dbus.dbus_server_set_watch_functions(self._dbobj, self._add_watch_function, self._remove_watch_function, self._toggled_watch_function, None, self._free_watch_data) :
3709 raise CallFailed("dbus_server_set_watch_functions")
3710 #end if
3711 #end set_watch_functions
3712
3713 def set_timeout_functions(self, add_function, remove_function, toggled_function, data, free_data = None) :
3714 "sets the callbacks for libdbus to use to notify you of Timeout objects it wants" \
3715 " you to manage."
3716
3717 def wrap_add_function(c_timeout, _data) :
3718 return \
3719 add_function(Timeout(c_timeout), data)
3720 #end wrap_add_function
3721
3722 def wrap_remove_function(c_timeout, _data) :
3723 return \
3724 remove_function(Timeout(c_timeout), data)
3725 #end wrap_remove_function
3726
3727 def wrap_toggled_function(c_timeout, _data) :
3728 return \
3729 toggled_function(Timeout(c_timeout), data)
3730 #end wrap_toggled_function
3731
3732 def wrap_free_data(_data) :
3733 free_data(data)
3734 #end wrap_free_data
3735
3736 #begin set_timeout_functions
3737 self._add_timeout_function = DBUS.AddTimeoutFunction(wrap_add_function)
3738 self._remove_timeout_function = DBUS.RemoveTimeoutFunction(wrap_remove_function)
3739 if toggled_function != None :
3740 self._toggled_timeout_function = DBUS.TimeoutToggledFunction(wrap_toggled_function)
3741 else :
3742 self._toggled_timeout_function = None
3743 #end if
3744 if free_data != None :
3745 self._free_timeout_data = DBUS.FreeFunction(wrap_free_data)
3746 else :
3747 self._free_timeout_data = None
3748 #end if
3749 if not dbus.dbus_server_set_timeout_functions(self._dbobj, self._add_timeout_function, self._remove_timeout_function, self._toggled_timeout_function, None, self._free_timeout_data) :
3750 raise CallFailed("dbus_server_set_timeout_functions")
3751 #end if
3752 #end set_timeout_functions
3753
3754 def set_auth_mechanisms(self, mechanisms) :
3755 nr_mechanisms = len(mechanisms)
3756 c_mechanisms = (ct.c_char_p * (nr_mechanisms + 1))()
3757 for i in range(nr_mechanisms) :
3758 c_mechanisms[i] = mechanisms[i].encode()
3759 #end if
3760 c_mechanisms[nr_mechanisms] = None # marks end of array
3761 if not dbus.dbus_server_set_auth_mechanisms(self._dbobj, c_mechanisms) :
3762 raise CallFailed("dbus_server_set_auth_mechanisms")
3763 #end if
3764 #end set_auth_mechanisms
3765
3766 # TODO: allocate/free slot (static methods)
3767 # TODO: get/set/data
3768
3769 def attach_asyncio(self, loop = None) :
3770 "attaches this Server object to an asyncio event loop. If none is" \
3771 " specified, the default event loop (as returned from asyncio.get_event_loop()" \
3772 " is used.\n" \
3773 "\n" \
3774 "This call will also automatically attach a new_connection callback. You then use" \
3775 " the await_new_connection coroutine to obtain new connections. If" \
3776 " self.autoattach_new_connections, then Connection.attach_asyncio() will" \
3777 " automatically be called to handle events for the new connection."
3778
3779 def new_connection(self, conn, user_data) :
3780 if len(self._await_new_connections) != 0 :
3781 awaiting = self._await_new_connections.pop(0)
3782 awaiting.set_result(conn)
3783 else :
3784 # put it in _new_connections queue
3785 if (
3786 self.max_new_connections != None
3787 and
3788 len(self._new_connections) >= self.max_new_connections
3789 ) :
3790 # too many connections pending, reject
3791 conn.close()
3792 else :
3793 self._new_connections.append(conn)
3794 #end if
3795 #end if
3796 #end new_connection
3797
3798 #begin attach_asyncio
3799 assert self.loop == None, "already attached to an event loop"
3800 assert self._new_connection_function == None, "already set a new-connection function"
3801 self._new_connections = []
3802 self._await_new_connections = []
3803 self.set_new_connection_function(new_connection, None)
3804 _loop_attach(self, loop, None)
3805 #end attach_asyncio
3806
3807 async def await_new_connection(self, timeout = DBUS.TIMEOUT_INFINITE) :
3808 "retrieves the next new Connection, if there is one available, otherwise" \
3809 " suspends the current coroutine for up to the specified timeout duration" \
3810 " while waiting for one to appear. Returns None if there is no new connection" \
3811 " within that time."
3812 assert self.loop != None, "no event loop to attach coroutine to"
3813 if len(self._new_connections) != 0 :
3814 result = self._new_connections.pop(0)
3815 else :
3816 if not self.is_connected :
3817 raise BrokenPipeError("Server has been disconnected")
3818 #end if
3819 if timeout == 0 :
3820 # might as well short-circuit the whole waiting process
3821 result = None
3822 else :
3823 awaiting = self.loop.create_future()
3824 self._await_new_connections.append(awaiting)
3825 if timeout == DBUS.TIMEOUT_INFINITE :
3826 timeout = None
3827 else :
3828 if timeout == DBUS.TIMEOUT_USE_DEFAULT :
3829 timeout = DBUSX.DEFAULT_TIMEOUT
3830 #end if
3831 #end if
3832 await self.wait \
3833 (
3834 (awaiting,),
3835 timeout = timeout
3836 )
3837 # ignore done & pending results because they
3838 # don’t match up with future I’m waiting for
3839 if awaiting.done() :
3840 result = awaiting.result()
3841 else :
3842 self._await_new_connections.pop(self._await_new_connections.index(awaiting))
3843 result = None
3844 #end if
3845 #end if
3846 #end if
3847 if result != None and self.autoattach_new_connections :
3848 result.attach_asyncio(self.loop)
3849 #end if
3850 return \
3851 result
3852 #end await_new_connection
3853
3854 def iter_connections_async(self, stop_on = None, timeout = DBUS.TIMEOUT_INFINITE) :
3855 "wrapper around await_new_connection() to allow use with an async-for" \
3856 " statement. Lets you write\n" \
3857 "\n" \
3858 " async for conn in «server».iter_connections_async(«timeout») :" \
3859 " «accept conn»\n" \
3860 " #end for\n" \
3861 "\n" \
3862 "to receive and process incoming connections in a loop. stop_on is an optional set of" \
3863 " STOP_ON.xxx values indicating the conditions under which the iterator will" \
3864 " raise StopAsyncIteration to terminate the loop."
3865 assert self.loop != None, "no event loop to attach coroutine to"
3866 if stop_on == None :
3867 stop_on = frozenset()
3868 elif (
3869 not isinstance(stop_on, (set, frozenset))
3870 or
3871 not all(isinstance(elt, STOP_ON) for elt in stop_on)
3872 ) :
3873 raise TypeError("stop_on must be None or set of STOP_ON")
3874 #end if
3875 return \
3876 _SrvAiter(self, stop_on, timeout)
3877 #end iter_connections_async
3878
3879 #end Server
3880
3881 class _SrvAiter :
3882 # internal class for use by Server.iter_connections_async (above).
3883
3884 def __init__(self, srv, stop_on, timeout) :
3885 self.srv = srv
3886 self.stop_on = stop_on
3887 self.timeout = timeout
3888 #end __init__
3889
3890 def __aiter__(self) :
3891 # I’m my own iterator.
3892 return \
3893 self
3894 #end __aiter__
3895
3896 async def __anext__(self) :
3897 stop_iter = False
3898 try :
3899 result = await self.srv.await_new_connection(self.timeout)
3900 if result == None and STOP_ON.TIMEOUT in self.stop_on :
3901 stop_iter = True
3902 #end if
3903 except BrokenPipeError :
3904 if STOP_ON.CLOSED not in self.stop_on :
3905 raise
3906 #end if
3907 stop_iter = True
3908 #end try
3909 if stop_iter :
3910 raise StopAsyncIteration("Server.iter_connections_async terminating")
3911 #end if
3912 return \
3913 result
3914 #end __anext__
3915
3916 #end _SrvAiter
3917
3918 class PreallocatedSend :
3919 "wrapper around a DBusPreallocatedSend object. Do not instantiate directly;" \
3920 " get from Connection.preallocate_send method."
3921 # <https://dbus.freedesktop.org/doc/api/html/group__DBusConnection.html>
3922
3923 __slots__ = ("__weakref__", "_dbobj", "_w_parent", "_sent") # to forestall typos
3924
3925 _instances = WeakValueDictionary()
3926
3927 def __new__(celf, _dbobj, _parent) :
3928 self = celf._instances.get(_dbobj)
3929 if self == None :
3930 self = super().__new__(celf)
3931 self._dbobj = _dbobj
3932 self._w_parent = weak_ref(_parent)
3933 self._sent = False
3934 celf._instances[_dbobj] = self
3935 else :
3936 assert self._w_parent() == _parent
3937 #end if
3938 return \
3939 self
3940 #end __new__
3941
3942 def __del__(self) :
3943 if self._dbobj != None :
3944 parent = self._w_parent()
3945 if parent != None and not self._sent :
3946 dbus.dbus_connection_free_preallocated_send(parent._dbobj, self._dbobj)
3947 #end if
3948 self._dbobj = None
3949 #end if
3950 #end __del__
3951
3952 def send(self, message) :
3953 "alternative to Connection.send_preallocated."
3954 if not isinstance(message, Message) :
3955 raise TypeError("message must be a Message")
3956 #end if
3957 assert not self._sent, "preallocated has already been sent"
3958 parent = self._w_parent()
3959 assert parent != None, "parent Connection has gone away"
3960 serial = ct.c_uint()
3961 dbus.dbus_connection_send_preallocated(parent._dbobj, self._dbobj, message._dbobj, ct.byref(serial))
3962 self._sent = True
3963 return \
3964 serial.value
3965 #end send
3966
3967 #end PreallocatedSend
3968
3969 class Message :
3970 "wrapper around a DBusMessage object. Do not instantiate directly; use one of the" \
3971 " new_xxx or copy methods, or Connection.pop_message or Connection.borrow_message."
3972 # <https://dbus.freedesktop.org/doc/api/html/group__DBusMessage.html>
3973
3974 __slots__ = ("__weakref__", "_dbobj", "_conn", "_borrowed") # to forestall typos
3975
3976 _instances = WeakValueDictionary()
3977
3978 def __new__(celf, _dbobj) :
3979 self = celf._instances.get(_dbobj)
3980 if self == None :
3981 self = super().__new__(celf)
3982 self._dbobj = _dbobj
3983 self._conn = None
3984 self._borrowed = False
3985 celf._instances[_dbobj] = self
3986 else :
3987 dbus.dbus_message_unref(self._dbobj)
3988 # lose extra reference created by caller
3989 #end if
3990 return \
3991 self
3992 #end __new__
3993
3994 def __del__(self) :
3995 if self._dbobj != None :
3996 assert not self._borrowed, "trying to dispose of borrowed message"
3997 dbus.dbus_message_unref(self._dbobj)
3998 self._dbobj = None
3999 #end if
4000 #end __del__
4001
4002 @classmethod
4003 def new(celf, type) :
4004 "type is one of the DBUS.MESSAGE_TYPE_xxx codes. Using one of the type-specific" \
4005 " calls--new_error, new_method_call, new_method_return, new_signal--is probably" \
4006 " more convenient."
4007 result = dbus.dbus_message_new(type)
4008 if result == None :
4009 raise CallFailed("dbus_message_new")
4010 #end if
4011 return \
4012 celf(result)
4013 #end new
4014
4015 def new_error(self, name, message) :
4016 "creates a new DBUS.MESSAGE_TYPE_ERROR message that is a reply to this Message."
4017 result = dbus.dbus_message_new_error(self._dbobj, name.encode(), (lambda : None, lambda : message.encode())[message != None]())
4018 if result == None :
4019 raise CallFailed("dbus_message_new_error")
4020 #end if
4021 return \
4022 type(self)(result)
4023 #end new_error
4024
4025 # probably not much point trying to use new_error_printf
4026
4027 @classmethod
4028 def new_method_call(celf, destination, path, iface, method) :
4029 "creates a new DBUS.MESSAGE_TYPE_METHOD_CALL message."
4030 result = dbus.dbus_message_new_method_call \
4031 (
4032 (lambda : None, lambda : destination.encode())[destination != None](),
4033 path.encode(),
4034 (lambda : None, lambda : iface.encode())[iface != None](),
4035 method.encode(),
4036 )
4037 if result == None :
4038 raise CallFailed("dbus_message_new_method_call")
4039 #end if
4040 return \
4041 celf(result)
4042 #end new_method_call
4043
4044 def new_method_return(self) :
4045 "creates a new DBUS.MESSAGE_TYPE_METHOD_RETURN that is a reply to this Message."
4046 result = dbus.dbus_message_new_method_return(self._dbobj)
4047 if result == None :
4048 raise CallFailed("dbus_message_new_method_return")
4049 #end if
4050 return \
4051 type(self)(result)
4052 #end new_method_return
4053
4054 @classmethod
4055 def new_signal(celf, path, iface, name) :
4056 "creates a new DBUS.MESSAGE_TYPE_SIGNAL message."
4057 result = dbus.dbus_message_new_signal(path.encode(), iface.encode(), name.encode())
4058 if result == None :
4059 raise CallFailed("dbus_message_new_signal")
4060 #end if
4061 return \
4062 celf(result)
4063 #end new_signal
4064
4065 def copy(self) :
4066 "creates a copy of this Message."
4067 result = dbus.dbus_message_copy(self._dbobj)
4068 if result == None :
4069 raise CallFailed("dbus_message_copy")
4070 #end if
4071 return \
4072 type(self)(result)
4073 #end copy
4074
4075 @property
4076 def type(self) :
4077 "returns the DBUS.MESSAGE_TYPE_XXX code for this Message."
4078 return \
4079 dbus.dbus_message_get_type(self._dbobj)
4080 #end type
4081
4082 # NYI append_args, get_args -- probably not useful, use my
4083 # objects and append_objects convenience methods (below) instead
4084
4085 class ExtractIter :
4086 "for iterating over the arguments in a Message for reading. Do not" \
4087 " instantiate directly; get from Message.iter_init or ExtractIter.recurse.\n" \
4088 "\n" \
4089 "You can use this as a Python iterator, in a for-loop, passing" \
4090 " it to the next() built-in function etc. Do not mix such usage with calls to" \
4091 " the has_next() and next() methods."
4092
4093 __slots__ = ("_dbobj", "_parent", "_nulliter", "_startiter") # to forestall typos
4094
4095 def __init__(self, _parent) :
4096 self._dbobj = DBUS.MessageIter()
4097 self._parent = _parent
4098 self._nulliter = False
4099 self._startiter = True
4100 #end __init__
4101
4102 @property
4103 def has_next(self) :
4104 return \
4105 dbus.dbus_message_iter_has_next(self._dbobj)
4106 #end has_next
4107
4108 def next(self) :
4109 if self._nulliter or not dbus.dbus_message_iter_next(self._dbobj) :
4110 raise StopIteration("end of message iterator")
4111 #end if
4112 self._startiter = False
4113 return \
4114 self
4115 #end next
4116
4117 def __iter__(self) :
4118 return \
4119 self
4120 #end __iter__
4121
4122 def __next__(self) :
4123 if self._nulliter :
4124 raise StopIteration("empty message iterator")
4125 else :
4126 if self._startiter :
4127 self._startiter = False
4128 else :
4129 self.next()
4130 #end if
4131 #end if
4132 return \
4133 self
4134 #end __next__
4135
4136 @property
4137 def arg_type(self) :
4138 "the type code for this argument."
4139 return \
4140 dbus.dbus_message_iter_get_arg_type(self._dbobj)
4141 #end arg_type
4142
4143 @property
4144 def element_type(self) :
4145 "the contained element type of this argument, assuming it is of a container type."
4146 return \
4147 dbus.dbus_message_iter_get_element_type(self._dbobj)
4148 #end element_type
4149
4150 def recurse(self) :
4151 "creates a sub-iterator for recursing into a container argument."
4152 subiter = type(self)(self)
4153 dbus.dbus_message_iter_recurse(self._dbobj, subiter._dbobj)
4154 return \
4155 subiter
4156 #end recurse
4157
4158 @property
4159 def signature(self) :
4160 c_result = dbus.dbus_message_iter_get_signature(self._dbobj)
4161 if c_result == None :
4162 raise CallFailed("dbus_message_iter_get_signature")
4163 #end if
4164 result = ct.cast(c_result, ct.c_char_p).value.decode()
4165 dbus.dbus_free(c_result)
4166 return \
4167 result
4168 #end signature
4169
4170 @property
4171 def basic(self) :
4172 "returns the argument value, assuming it is of a non-container type."
4173 argtype = self.arg_type
4174 c_result_type = DBUS.basic_to_ctypes[argtype]
4175 c_result = c_result_type()
4176 dbus.dbus_message_iter_get_basic(self._dbobj, ct.byref(c_result))
4177 if c_result_type == ct.c_char_p :
4178 result = c_result.value.decode()
4179 else :
4180 result = c_result.value
4181 #end if
4182 if argtype in DBUS.basic_subclasses :
4183 result = DBUS.basic_subclasses[argtype](result)
4184 #end if
4185 return \
4186 result
4187 #end basic
4188
4189 @property
4190 def object(self) :
4191 "returns the current iterator item as a Python object. Will recursively" \
4192 " process container objects."
4193 argtype = self.arg_type
4194 if argtype in DBUS.basic_to_ctypes :
4195 result = self.basic
4196 elif argtype == DBUS.TYPE_ARRAY :
4197 if self.element_type == DBUS.TYPE_DICT_ENTRY :
4198 result = {}
4199 subiter = self.recurse()
4200 while True :
4201 entry = next(subiter, None)
4202 if entry == None or entry.arg_type == DBUS.TYPE_INVALID :
4203 # TYPE_INVALID can be returned for an empty dict
4204 break
4205 if entry.arg_type != DBUS.TYPE_DICT_ENTRY :
4206 raise RuntimeError("invalid dict entry type %d" % entry.arg_type)
4207 #end if
4208 key, value = tuple(x.object for x in entry.recurse())
4209 result[key] = value
4210 #end while
4211 elif type_is_fixed_array_elttype(self.element_type) :
4212 result = self.fixed_array
4213 else :
4214 result = list(x.object for x in self.recurse())
4215 if len(result) != 0 and result[-1] == None :
4216 # fudge for iterating into an empty array
4217 result = result[:-1]
4218 #end if
4219 #end if
4220 elif argtype == DBUS.TYPE_STRUCT :
4221 result = list(x.object for x in self.recurse())
4222 elif argtype == DBUS.TYPE_VARIANT :
4223 subiter = self.recurse()
4224 subiter = next(subiter)
4225 result = (DBUS.Signature(subiter.signature), subiter.object)
4226 elif argtype == DBUS.TYPE_INVALID :
4227 # fudge for iterating into an empty array
4228 result = None
4229 else :
4230 raise RuntimeError("unrecognized argtype %d" % argtype)
4231 #end if
4232 return \
4233 result
4234 #end object
4235
4236 if hasattr(dbus, "dbus_message_iter_get_element_count") :
4237
4238 @property
4239 def element_count(self) :
4240 "returns the count of contained elements, assuming the current argument" \
4241 " is of a container type."
4242 return \
4243 dbus.dbus_message_iter_get_element_count(self._dbobj)
4244 #end element_count
4245
4246 #end if
4247
4248 @property
4249 def fixed_array(self) :
4250 "returns the array elements, assuming the current argument is an array" \
4251 " with a non-container element type."
4252 c_element_type = DBUS.basic_to_ctypes[self.element_type]
4253 c_result = ct.POINTER(c_element_type)()
4254 c_nr_elts = ct.c_int()
4255 subiter = self.recurse()
4256 dbus.dbus_message_iter_get_fixed_array(subiter._dbobj, ct.byref(c_result), ct.byref(c_nr_elts))
4257 result = []
4258 for i in range(c_nr_elts.value) :
4259 elt = c_result[i]
4260 if c_element_type == ct.c_char_p :
4261 elt = elt.value.decode()
4262 #end if
4263 result.append(elt)
4264 #end for
4265 return \
4266 result
4267 #end fixed_array
4268
4269 #end ExtractIter
4270
4271 class AppendIter :
4272 "for iterating over the arguments in a Message for appending." \
4273 " Do not instantiate directly; get from Message.iter_init_append or" \
4274 " AppendIter.open_container."
4275
4276 __slots__ = ("_dbobj", "_parent") # to forestall typos
4277
4278 def __init__(self, _parent) :
4279 self._dbobj = DBUS.MessageIter()
4280 self._parent = _parent
4281 #end __init__
4282
4283 def append_basic(self, type, value) :
4284 "appends a single value of a non-container type."
4285 if type in DBUS.int_convert :
4286 value = DBUS.int_convert[type](value)
4287 #end if
4288 c_type = DBUS.basic_to_ctypes[type]
4289 if c_type == ct.c_char_p :
4290 if not isinstance(value, str) :
4291 raise TypeError \
4292 (
4293 "expecting type %s, got %s" % (TYPE(type), builtins.type(value).__name__)
4294 )
4295 #end if
4296 value = value.encode()
4297 #end if
4298 c_value = c_type(value)
4299 if not dbus.dbus_message_iter_append_basic(self._dbobj, type, ct.byref(c_value)) :
4300 raise CallFailed("dbus_message_iter_append_basic")
4301 #end if
4302 return \
4303 self
4304 #end append_basic
4305
4306 def append_fixed_array(self, element_type, values) :
4307 "appends an array of elements of a non-container type."
4308 c_elt_type = DBUS.basic_to_ctypes[element_type]
4309 nr_elts = len(values)
4310 c_arr = (nr_elts * c_elt_type)()
4311 for i in range(nr_elts) :
4312 if c_elt_type == ct.c_char_p :
4313 c_arr[i] = values[i].encode()
4314 else :
4315 c_arr[i] = values[i]
4316 #end if
4317 #end for
4318 c_arr_ptr = ct.pointer(c_arr)
4319 if not dbus.dbus_message_iter_append_fixed_array(self._dbobj, element_type, ct.byref(c_arr_ptr), nr_elts) :
4320 raise CallFailed("dbus_message_iter_append_fixed_array")
4321 #end if
4322 return \
4323 self
4324 #end append_fixed_array
4325
4326 def open_container(self, type, contained_signature) :
4327 "starts appending an argument of a container type, returning a sub-iterator" \
4328 " for appending the contents of the argument. Can be called recursively for" \
4329 " containers of containers etc."
4330 if contained_signature != None :
4331 c_sig = contained_signature.encode()
4332 else :
4333 c_sig = None
4334 #end if
4335 subiter = builtins.type(self)(self)
4336 if not dbus.dbus_message_iter_open_container(self._dbobj, type, c_sig, subiter._dbobj) :
4337 raise CallFailed("dbus_message_iter_open_container")
4338 #end if
4339 return \
4340 subiter
4341 #end open_container
4342
4343 def close(self) :
4344 "closes a sub-iterator, indicating the completion of construction" \
4345 " of a container value."
4346 assert self._parent != None, "cannot close top-level iterator"
4347 if not dbus.dbus_message_iter_close_container(self._parent._dbobj, self._dbobj) :
4348 raise CallFailed("dbus_message_iter_close_container")
4349 #end if
4350 return \
4351 self._parent
4352 #end close
4353
4354 def abandon(self) :
4355 "closes a sub-iterator, indicating the abandonment of construction" \
4356 " of a container value. The Message object is effectively unusable" \
4357 " after this point and should be discarded."
4358 assert self._parent != None, "cannot abandon top-level iterator"
4359 dbus.dbus_message_iter_abandon_container(self._parent._dbobj, self._dbobj)
4360 return \
4361 self._parent
4362 #end abandon
4363
4364 #end AppendIter
4365
4366 def iter_init(self) :
4367 "creates an iterator for extracting the arguments of the Message."
4368 iter = self.ExtractIter(None)
4369 if dbus.dbus_message_iter_init(self._dbobj, iter._dbobj) == 0 :
4370 iter._nulliter = True
4371 #end if
4372 return \
4373 iter
4374 #end iter_init
4375
4376 @property
4377 def objects(self) :
4378 "yields the arguments of the Message as Python objects."
4379 for iter in self.iter_init() :
4380 yield iter.object
4381 #end for
4382 #end objects
4383
4384 @property
4385 def all_objects(self) :
4386 "all the arguments of the Message as a list of Python objects."
4387 return \
4388 list(self.objects)
4389 #end all_objects
4390
4391 def expect_objects(self, signature) :
4392 "expects the arguments of the Message to conform to the given signature," \
4393 " raising a TypeError if not. If they match, returns them as a list."
4394 signature = unparse_signature(signature)
4395 if self.signature != signature :
4396 raise TypeError("message args don’t match: expected “%s”, got “%s”" % (signature, self.signature))
4397 #end if
4398 return \
4399 self.all_objects
4400 #end expect_objects
4401
4402 def expect_return_objects(self, signature) :
4403 "expects the Message to be of type DBUS.MESSAGE_TYPE_METHOD_RETURN and its" \
4404 " arguments to conform to the given signature. Raises the appropriate DBusError" \
4405 " if the Message is of type DBUS.MESSAGE_TYPE_ERROR."
4406 if self.type == DBUS.MESSAGE_TYPE_METHOD_RETURN :
4407 result = self.expect_objects(signature)
4408 elif self.type == DBUS.MESSAGE_TYPE_ERROR :
4409 raise DBusError(self.error_name, self.expect_objects("s")[0])
4410 else :
4411 raise ValueError("unexpected message type %d" % self.type)
4412 #end if
4413 return \
4414 result
4415 #end expect_return_objects
4416
4417 def iter_init_append(self) :
4418 "creates a Message.AppendIter for appending arguments to the Message."
4419 iter = self.AppendIter(None)
4420 dbus.dbus_message_iter_init_append(self._dbobj, iter._dbobj)
4421 return \
4422 iter
4423 #end iter_init_append
4424
4425 def append_objects(self, signature, *args) :
4426 "interprets Python values args according to signature and appends" \
4427 " converted item(s) to the message args."
4428
4429 def append_sub(siglist, eltlist, appenditer) :
4430 if len(siglist) != len(eltlist) :
4431 raise ValueError \
4432 (
4433 "mismatch between signature entries %s and number of sequence elements %s"
4434 %
4435 (repr(siglist), repr(eltlist))
4436 )
4437 #end if
4438 for elttype, elt in zip(siglist, eltlist) :
4439 if isinstance(elttype, BasicType) :
4440 appenditer.append_basic(elttype.code.value, elt)
4441 elif isinstance(elttype, DictType) :
4442 if not isinstance(elt, dict) :
4443 raise TypeError("dict expected for %s" % repr(elttype))
4444 #end if
4445 subiter = appenditer.open_container(DBUS.TYPE_ARRAY, elttype.entry_signature)
4446 for key in sorted(elt) : # might as well insert in some kind of predictable order
4447 value = elt[key]
4448 subsubiter = subiter.open_container(DBUS.TYPE_DICT_ENTRY, None)
4449 append_sub([elttype.keytype, elttype.valuetype], [key, value], subsubiter)
4450 subsubiter.close()
4451 #end for
4452 subiter.close()
4453 elif isinstance(elttype, ArrayType) :
4454 # append 0 or more elements matching elttype.elttype
4455 arrelttype = elttype.elttype
4456 if type_is_fixed_array_elttype(arrelttype.code.value) :
4457 subiter = appenditer.open_container(DBUS.TYPE_ARRAY, arrelttype.signature)
4458 subiter.append_fixed_array(arrelttype.code.value, elt)
4459 subiter.close()
4460 else :
4461 subiter = appenditer.open_container(DBUS.TYPE_ARRAY, arrelttype.signature)
4462 if not isinstance(elt, (tuple, list)) :
4463 raise TypeError("expecting sequence of values for array")
4464 #end if
4465 for subval in elt :
4466 append_sub([arrelttype], [subval], subiter)
4467 #end for
4468 subiter.close()
4469 #end if
4470 elif isinstance(elttype, StructType) :
4471 if not isinstance(elt, (tuple, list)) :
4472 raise TypeError("expecting sequence of values for struct")
4473 #end if
4474 subiter = appenditer.open_container(DBUS.TYPE_STRUCT, None)
4475 append_sub(elttype.elttypes, elt, subiter)
4476 subiter.close()
4477 elif isinstance(elttype, VariantType) :
4478 if not isinstance(elt, (list, tuple)) or len(elt) != 2 :
4479 raise TypeError("sequence of 2 elements expected for variant: %s" % repr(elt))
4480 #end if
4481 actual_type = parse_single_signature(elt[0])
4482 subiter = appenditer.open_container(DBUS.TYPE_VARIANT, actual_type.signature)
4483 append_sub([actual_type], [elt[1]], subiter)
4484 subiter.close()
4485 else :
4486 raise RuntimeError("unrecognized type %s" % repr(elttype))
4487 #end if
4488 #end for
4489 #end append_sub
4490
4491 #begin append_objects
4492 append_sub(parse_signature(signature), args, self.iter_init_append())
4493 return \
4494 self
4495 #end append_objects
4496
4497 @property
4498 def no_reply(self) :
4499 "whether the Message is not expecting a reply."
4500 return \
4501 dbus.dbus_message_get_no_reply(self._dbobj) != 0
4502 #end no_reply
4503
4504 @no_reply.setter
4505 def no_reply(self, no_reply) :
4506 dbus.dbus_message_set_no_reply(self._dbobj, no_reply)
4507 #end no_reply
4508
4509 @property
4510 def auto_start(self) :
4511 return \
4512 dbus.dbus_message_get_auto_start(self._dbobj) != 0
4513 #end auto_start
4514
4515 @auto_start.setter
4516 def auto_start(self, auto_start) :
4517 dbus.dbus_message_set_auto_start(self._dbobj, auto_start)
4518 #end auto_start
4519
4520 @property
4521 def path(self) :
4522 "the object path for a DBUS.MESSAGE_TYPE_METHOD_CALL or DBUS.DBUS.MESSAGE_TYPE_SIGNAL" \
4523 " message."
4524 result = dbus.dbus_message_get_path(self._dbobj)
4525 if result != None :
4526 result = DBUS.ObjectPath(result.decode())
4527 #end if
4528 return \
4529 result
4530 #end path
4531
4532 @path.setter
4533 def path(self, object_path) :
4534 if not dbus.dbus_message_set_path(self._dbobj, (lambda : None, lambda : object_path.encode())[object_path != None]()) :
4535 raise CallFailed("dbus_message_set_path")
4536 #end if
4537 #end path
4538
4539 @property
4540 def path_decomposed(self) :
4541 "the object path for a DBUS.MESSAGE_TYPE_METHOD_CALL or DBUS.DBUS.MESSAGE_TYPE_SIGNAL" \
4542 " message, decomposed into a list of the slash-separated components without the slashes."
4543 path = ct.POINTER(ct.c_char_p)()
4544 if not dbus.dbus_message_get_path_decomposed(self._dbobj, ct.byref(path)) :
4545 raise CallFailed("dbus_message_get_path_decomposed")
4546 #end if
4547 if bool(path) :
4548 result = []
4549 i = 0
4550 while True :
4551 entry = path[i]
4552 if entry == None :
4553 break
4554 result.append(entry.decode())
4555 i += 1
4556 #end while
4557 dbus.dbus_free_string_array(path)
4558 else :
4559 result = None
4560 #end if
4561 return \
4562 result
4563 #end path_decomposed
4564
4565 @property
4566 def interface(self) :
4567 "the interface name for a DBUS.MESSAGE_TYPE_METHOD_CALL or DBUS.MESSAGE_TYPE_SIGNAL" \
4568 " message."
4569 result = dbus.dbus_message_get_interface(self._dbobj)
4570 if result != None :
4571 result = result.decode()
4572 #end if
4573 return \
4574 result
4575 #end interface
4576
4577 @interface.setter
4578 def interface(self, iface) :
4579 if not dbus.dbus_message_set_interface(self._dbobj, (lambda : None, lambda : iface.encode())[iface != None]()) :
4580 raise CallFailed("dbus_message_set_interface")
4581 #end if
4582 #end interface
4583
4584 def has_interface(self, iface) :
4585 return \
4586 dbus.dbus_message_has_interface(self._dbobj, iface.encode()) != 0
4587 #end has_interface
4588
4589 @property
4590 def member(self) :
4591 "the method name for a DBUS.MESSAGE_TYPE_METHOD_CALL message or the signal" \
4592 " name for DBUS.MESSAGE_TYPE_SIGNAL."
4593 result = dbus.dbus_message_get_member(self._dbobj)
4594 if result != None :
4595 result = result.decode()
4596 #end if
4597 return \
4598 result
4599 #end member
4600
4601 @member.setter
4602 def member(self, member) :
4603 if not dbus.dbus_message_set_member(self._dbobj, (lambda : None, lambda : member.encode())[member != None]()) :
4604 raise CallFailed("dbus_message_set_member")
4605 #end if
4606 #end member
4607
4608 def has_member(self, member) :
4609 return \
4610 dbus.dbus_message_has_member(self._dbobj, member.encode()) != 0
4611 #end has_member
4612
4613 @property
4614 def error_name(self) :
4615 "the error name for a DBUS.MESSAGE_TYPE_ERROR message."
4616 result = dbus.dbus_message_get_error_name(self._dbobj)
4617 if result != None :
4618 result = result.decode()
4619 #end if
4620 return \
4621 result
4622 #end error_name
4623
4624 @error_name.setter
4625 def error_name(self, error_name) :
4626 if not dbus.dbus_message_set_error_name(self._dbobj, (lambda : None, lambda : error_name.encode())[error_name != None]()) :
4627 raise CallFailed("dbus_message_set_error_name")
4628 #end if
4629 #end error_name
4630
4631 @property
4632 def destination(self) :
4633 "the bus name that the message is to be sent to."
4634 result = dbus.dbus_message_get_destination(self._dbobj)
4635 if result != None :
4636 result = result.decode()
4637 #end if
4638 return \
4639 result
4640 #end destination
4641
4642 @destination.setter
4643 def destination(self, destination) :
4644 if not dbus.dbus_message_set_destination(self._dbobj, (lambda : None, lambda : destination.encode())[destination != None]()) :
4645 raise CallFailed("dbus_message_set_destination")
4646 #end if
4647 #end destination
4648
4649 @property
4650 def sender(self) :
4651 result = dbus.dbus_message_get_sender(self._dbobj)
4652 if result != None :
4653 result = result.decode()
4654 #end if
4655 return \
4656 result
4657 #end sender
4658
4659 @sender.setter
4660 def sender(self, sender) :
4661 if not dbus.dbus_message_set_sender(self._dbobj, (lambda : None, lambda : sender.encode())[sender != None]()) :
4662 raise CallFailed("dbus_message_set_sender")
4663 #end if
4664 #end sender
4665
4666 @property
4667 def signature(self) :
4668 result = dbus.dbus_message_get_signature(self._dbobj)
4669 if result != None :
4670 result = DBUS.Signature(result.decode())
4671 #end if
4672 return \
4673 result
4674 #end signature
4675
4676 def is_method_call(self, iface, method) :
4677 return \
4678 dbus.dbus_message_is_method_call(self._dbobj, iface.encode(), method.encode()) != 0
4679 #end is_method_call
4680
4681 def is_signal(self, iface, signal_name) :
4682 return \
4683 dbus.dbus_message_is_signal(self._dbobj, iface.encode(), signal_name.encode()) != 0
4684 #end is_signal
4685
4686 def is_error(self, iface, error_name) :
4687 return \
4688 dbus.dbus_message_is_error(self._dbobj, error_name.encode()) != 0
4689 #end is_error
4690
4691 def has_destination(self, iface, destination) :
4692 return \
4693 dbus.dbus_message_has_destination(self._dbobj, destination.encode()) != 0
4694 #end has_destination
4695
4696 def has_sender(self, iface, sender) :
4697 return \
4698 dbus.dbus_message_has_sender(self._dbobj, sender.encode()) != 0
4699 #end has_sender
4700
4701 def has_signature(self, iface, signature) :
4702 return \
4703 dbus.dbus_message_has_signature(self._dbobj, signature.encode()) != 0
4704 #end has_signature
4705
4706 def set_error(self, error) :
4707 "fills in error if this is an error message, else does nothing. Returns" \
4708 " whether it was an error message or not."
4709 if not isinstance(error, Error) :
4710 raise TypeError("error must be an Error")
4711 #end if
4712 return \
4713 dbus.dbus_set_error_from_message(error._dbobj, self._dbobj) != 0
4714 #end set_error
4715
4716 @property
4717 def contains_unix_fds(self) :
4718 return \
4719 dbus.dbus_message_contains_unix_fds(self._dbobj) != 0
4720 #end contains_unix_fds
4721
4722 @property
4723 def serial(self) :
4724 "the serial number of the Message, to be referenced in replies."
4725 return \
4726 dbus.dbus_message_get_serial(self._dbobj)
4727 #end serial
4728
4729 @serial.setter
4730 def serial(self, serial) :
4731 dbus.dbus_message_set_serial(self._dbobj, serial)
4732 #end serial
4733
4734 @property
4735 def reply_serial(self) :
4736 "the serial number of the original Message that that this" \
4737 " DBUS.MESSAGE_TYPE_METHOD_RETURN message is a reply to."
4738 return \
4739 dbus.dbus_message_get_reply_serial(self._dbobj)
4740 #end reply_serial
4741
4742 @reply_serial.setter
4743 def reply_serial(self, serial) :
4744 if not dbus.dbus_message_set_reply_serial(self._dbobj, serial) :
4745 raise CallFailed("dbus_message_set_reply_serial")
4746 #end if
4747 #end serial
4748
4749 def lock(self) :
4750 dbus.dbus_message_lock(self._dbobj)
4751 #end lock
4752
4753 def return_borrowed(self) :
4754 assert self._borrowed and self._conn != None
4755 dbus.dbus_connection_return_message(self._conn._dbobj, self._dbobj)
4756 self._borrowed = False
4757 #end return_borrowed
4758
4759 def steal_borrowed(self) :
4760 assert self._borrowed and self._conn != None
4761 dbus.dbus_connection_steal_borrowed_message(self._conn._dbobj, self._dbobj)
4762 self._borrowed = False
4763 return \
4764 self
4765 #end steal_borrowed
4766
4767 # TODO: allocate/free data slot -- static methods
4768 # (freeing slot can set passed-in var to -1 on actual free; do I care?)
4769 # TODO: set/get data
4770
4771 @staticmethod
4772 def type_from_string(type_str) :
4773 "returns a MESSAGE_TYPE_xxx value."
4774 return \
4775 dbus.dbus_message_type_from_string(type_str.encode())
4776 #end type_from_string
4777
4778 @staticmethod
4779 def type_to_string(type) :
4780 "type is a MESSAGE_TYPE_xxx value."
4781 return \
4782 dbus.dbus_message_type_to_string(type).decode()
4783 #end type_to_string
4784
4785 def marshal(self) :
4786 "serializes this Message into the wire protocol format and returns a bytes object."
4787 buf = ct.POINTER(ct.c_ubyte)()
4788 nr_bytes = ct.c_int()
4789 if not dbus.dbus_message_marshal(self._dbobj, ct.byref(buf), ct.byref(nr_bytes)) :
4790 raise CallFailed("dbus_message_marshal")
4791 #end if
4792 result = bytearray(nr_bytes.value)
4793 ct.memmove \
4794 (
4795 ct.addressof((ct.c_ubyte * nr_bytes.value).from_buffer(result)),
4796 buf,
4797 nr_bytes.value
4798 )
4799 dbus.dbus_free(buf)
4800 return \
4801 result
4802 #end marshal
4803
4804 @classmethod
4805 def demarshal(celf, buf, error = None) :
4806 "deserializes a bytes or array-of-bytes object from the wire protocol" \
4807 " format into a Message object."
4808 error, my_error = _get_error(error)
4809 if isinstance(buf, bytes) :
4810 baseadr = ct.cast(buf, ct.c_void_p).value
4811 elif isinstance(buf, bytearray) :
4812 baseadr = ct.addressof((ct.c_ubyte * len(buf)).from_buffer(buf))
4813 elif isinstance(buf, array.array) and buf.typecode == "B" :
4814 baseadr = buf.buffer_info()[0]
4815 else :
4816 raise TypeError("buf is not bytes, bytearray or array.array of bytes")
4817 #end if
4818 msg = dbus.dbus_message_demarshal(baseadr, len(buf), error._dbobj)
4819 my_error.raise_if_set()
4820 if msg != None :
4821 msg = celf(msg)
4822 #end if
4823 return \
4824 msg
4825 #end demarshal
4826
4827 @classmethod
4828 def demarshal_bytes_needed(celf, buf) :
4829 "the number of bytes needed to deserialize a bytes or array-of-bytes" \
4830 " object from the wire protocol format."
4831 if isinstance(buf, bytes) :
4832 baseadr = ct.cast(buf, ct.c_void_p).value
4833 elif isinstance(buf, bytearray) :
4834 baseadr = ct.addressof((ct.c_ubyte * len(buf)).from_buffer(buf))
4835 elif isinstance(buf, array.array) and buf.typecode == "B" :
4836 baseadr = buf.buffer_info()[0]
4837 else :
4838 raise TypeError("buf is not bytes, bytearray or array.array of bytes")
4839 #end if
4840 return \
4841 dbus.dbus_message_demarshal_bytes_needed(baseadr, len(buf))
4842 #end demarshal_bytes_needed
4843
4844 @property
4845 def interactive_authorization(self) :
4846 return \
4847 dbus.dbus_message_get_interactive_authorization(self._dbobj)
4848 #end interactive_authorization
4849
4850 @interactive_authorization.setter
4851 def interactive_authorization(self, allow) :
4852 dbus.dbus_message_set_interactive_authorization(self._dbobj, allow)
4853 #end interactive_authorization
4854
4855 #end Message
4856
4857 class PendingCall :
4858 "wrapper around a DBusPendingCall object. This represents a pending reply" \
4859 " message that hasn’t been received yet. Do not instantiate directly; libdbus" \
4860 " creates these as the result from calling send_with_reply() on a Message."
4861 # <https://dbus.freedesktop.org/doc/api/html/group__DBusPendingCall.html>
4862
4863 __slots__ = \
4864 (
4865 "__weakref__",
4866 "_dbobj",
4867 "_w_conn",
4868 "_wrap_notify",
4869 "_wrap_free",
4870 "_awaiting",
4871 ) # to forestall typos
4872
4873 _instances = WeakValueDictionary()
4874
4875 def __new__(celf, _dbobj, _conn) :
4876 self = celf._instances.get(_dbobj)
4877 if self == None :
4878 self = super().__new__(celf)
4879 self._dbobj = _dbobj
4880 self._w_conn = weak_ref(_conn)
4881 self._wrap_notify = None
4882 self._wrap_free = None
4883 self._awaiting = None
4884 celf._instances[_dbobj] = self
4885 else :
4886 dbus.dbus_pending_call_unref(self._dbobj)
4887 # lose extra reference created by caller
4888 #end if
4889 return \
4890 self
4891 #end __new__
4892
4893 def __del__(self) :
4894 if self._dbobj != None :
4895 dbus.dbus_pending_call_unref(self._dbobj)
4896 self._dbobj = None
4897 #end if
4898 #end __del__
4899
4900 def set_notify(self, function, user_data, free_user_data = None) :
4901 "sets the callback for libdbus to notify you that the pending message" \
4902 " has become available. Note: it appears to be possible for your notifier" \
4903 " to be called spuriously before the message is actually available."
4904
4905 w_self = weak_ref(self)
4906
4907 def wrap_notify(c_pending, c_user_data) :
4908 function(_wderef(w_self, "pending call"), user_data)
4909 #end _wrap_notify
4910
4911 def wrap_free(c_user_data) :
4912 free_user_data(user_data)
4913 #end _wrap_free
4914
4915 #begin set_notify
4916 if function != None :
4917 self._wrap_notify = DBUS.PendingCallNotifyFunction(wrap_notify)
4918 else :
4919 self._wrap_notify = None
4920 #end if
4921 if free_user_data != None :
4922 self._wrap_free = DBUS.FreeFunction(wrap_free)
4923 else :
4924 self._wrap_free = None
4925 #end if
4926 if not dbus.dbus_pending_call_set_notify(self._dbobj, self._wrap_notify, None, self._wrap_free) :
4927 raise CallFailed("dbus_pending_call_set_notify")
4928 #end if
4929 #end set_notify
4930
4931 def cancel(self) :
4932 "tells libdbus you no longer care about the pending incoming message."
4933 dbus.dbus_pending_call_cancel(self._dbobj)
4934 if self._awaiting != None :
4935 # This probably shouldn’t occur. Looking at the source of libdbus,
4936 # it doesn’t keep track of any “cancelled” state for the PendingCall,
4937 # it just detaches it from any notifications about an incoming reply.
4938 self._awaiting.cancel()
4939 #end if
4940 #end cancel
4941
4942 @property
4943 def completed(self) :
4944 "checks whether the pending message is available."
4945 return \
4946 dbus.dbus_pending_call_get_completed(self._dbobj) != 0
4947 #end completed
4948
4949 def steal_reply(self) :
4950 "retrieves the Message, assuming it is actually available." \
4951 " You should check PendingCall.completed returns True first."
4952 result = dbus.dbus_pending_call_steal_reply(self._dbobj)
4953 if result != None :
4954 result = Message(result)
4955 #end if
4956 return \
4957 result
4958 #end steal_reply
4959
4960 async def await_reply(self) :
4961 "retrieves the Message. If it is not yet available, suspends the" \
4962 " coroutine (letting the event loop do other things) until it becomes" \
4963 " available. On a timeout, libdbus will construct and return an error" \
4964 " return message."
4965 conn = self._w_conn()
4966 assert conn != None, "parent Connection has gone away"
4967 assert conn.loop != None, "no event loop on parent Connection to attach coroutine to"
4968 if self._wrap_notify != None or self._awaiting != None :
4969 raise asyncio.InvalidStateError("there is already a notify set on this PendingCall")
4970 #end if
4971 done = conn.loop.create_future()
4972 self._awaiting = done
4973
4974 def pending_done(pending, wself) :
4975 if not done.done() : # just in case of self.cancel() being called
4976 self = wself()
4977 # Note it seems to be possible for callback to be triggered spuriously
4978 if self != None and self.completed :
4979 done.set_result(self.steal_reply())
4980 #end if
4981 #end if
4982 #end pending_done
4983
4984 self.set_notify(pending_done, weak_ref(self))
4985 # avoid reference circularity self → pending_done → self
4986 reply = await done
4987 return \
4988 reply
4989 #end await_reply
4990
4991 def block(self) :
4992 "blocks the current thread until the pending message has become available."
4993 dbus.dbus_pending_call_block(self._dbobj)
4994 #end block
4995
4996 # TODO: data slots (static methods), get/set data
4997
4998 #end PendingCall
4999
5000 class Error :
5001 "wrapper around a DBusError object. You can create one by calling the init method."
5002 # <https://dbus.freedesktop.org/doc/api/html/group__DBusErrors.html>
5003
5004 __slots__ = ("_dbobj",) # to forestall typos
5005
5006 def __init__(self) :
5007 dbobj = DBUS.Error()
5008 dbus.dbus_error_init(dbobj)
5009 self._dbobj = dbobj
5010 #end __init__
5011
5012 def __del__(self) :
5013 if self._dbobj != None :
5014 dbus.dbus_error_free(self._dbobj)
5015 self._dbobj = None
5016 #end if
5017 #end __del__
5018
5019 @classmethod
5020 def init(celf) :
5021 "for consistency with other classes that don’t want caller to instantiate directly."
5022 return \
5023 celf()
5024 #end init
5025
5026 def set(self, name, msg) :
5027 "fills in the error name and message."
5028 dbus.dbus_set_error(self._dbobj, name.encode(), b"%s", msg.encode())
5029 #end set
5030
5031 @property
5032 def is_set(self) :
5033 "has the Error been filled in."
5034 return \
5035 dbus.dbus_error_is_set(self._dbobj) != 0
5036 #end is_set
5037
5038 def has_name(self, name) :
5039 "has the Error got the specified name."
5040 return \
5041 dbus.dbus_error_has_name(self._dbobj, name.encode()) != 0
5042 #end has_name
5043
5044 @property
5045 def name(self) :
5046 "the name of the Error, if it has been filled in."
5047 return \
5048 (lambda : None, lambda : self._dbobj.name.decode())[self._dbobj.name != None]()
5049 #end name
5050
5051 @property
5052 def message(self) :
5053 "the message string for the Error, if it has been filled in."
5054 return \
5055 (lambda : None, lambda : self._dbobj.message.decode())[self._dbobj.message != None]()
5056 #end message
5057
5058 def raise_if_set(self) :
5059 "raises a DBusError exception if this Error has been filled in."
5060 if self.is_set :
5061 raise DBusError(self.name, self.message)
5062 #end if
5063 #end raise_if_set
5064
5065 def set_from_message(self, message) :
5066 "fills in this Error object from message if it is an error message." \
5067 " Returns whether it was or not."
5068 if not isinstance(message, Message) :
5069 raise TypeError("message must be a Message")
5070 #end if
5071 return \
5072 dbus.dbus_set_error_from_message(self._dbobj, message._dbobj) != 0
5073 #end set_from_message
5074
5075 #end Error
5076
5077 class AddressEntries :
5078 "wrapper for arrays of DBusAddressEntry values. Do not instantiate directly;" \
5079 " get from AddressEntries.parse. This object behaves like an array; you can obtain" \
5080 " the number of elements with len(), and use array subscripting to access the elements."
5081 # <https://dbus.freedesktop.org/doc/api/html/group__DBusAddress.html>
5082
5083 __slots__ = ("__weakref__", "_dbobj", "_nrelts") # to forestall typos
5084
5085 def __init__(self, _dbobj, _nrelts) :
5086 self._dbobj = _dbobj
5087 self._nrelts = _nrelts
5088 #end __init__
5089
5090 def __del__(self) :
5091 if self._dbobj != None :
5092 dbus.dbus_address_entries_free(self._dbobj)
5093 self._dbobj = None
5094 #end if
5095 #end __del__
5096
5097 class Entry :
5098 "a single AddressEntry. Do not instantiate directly; get from AddressEntries[]." \
5099 " This object behaves like a dictionary in that you can use keys to get values;" \
5100 " however, there is no libdbus API to check what keys are present; unrecognized" \
5101 " keys return a value of None."
5102
5103 __slots__ = ("_dbobj", "_parent", "_index") # to forestall typos
5104
5105 def __init__(self, _parent, _index) :
5106 self._dbobj = _parent._dbobj
5107 self._parent = weak_ref(_parent)
5108 self._index = _index
5109 #end __init__
5110
5111 @property
5112 def method(self) :
5113 assert self._parent() != None, "AddressEntries object has gone"
5114 result = dbus.dbus_address_entry_get_method(self._dbobj[self._index])
5115 if result != None :
5116 result = result.decode()
5117 #end if
5118 return \
5119 result
5120 #end method
5121
5122 def get_value(self, key) :
5123 assert self._parent() != None, "AddressEntries object has gone"
5124 c_result = dbus.dbus_address_entry_get_value(self._dbobj[self._index], key.encode())
5125 if c_result != None :
5126 result = c_result.decode()
5127 else :
5128 result = None
5129 #end if
5130 return \
5131 result
5132 #end get_value
5133 __getitem__ = get_value
5134
5135 #end Entry
5136
5137 @classmethod
5138 def parse(celf, address, error = None) :
5139 error, my_error = _get_error(error)
5140 c_result = ct.POINTER(ct.c_void_p)()
5141 nr_elts = ct.c_int()
5142 if not dbus.dbus_parse_address(address.encode(), ct.byref(c_result), ct.byref(nr_elts), error._dbobj) :
5143 c_result.contents = None
5144 nr_elts.value = 0
5145 #end if
5146 my_error.raise_if_set()
5147 if c_result.contents != None :
5148 result = celf(c_result, nr_elts.value)
5149 else :
5150 result = None
5151 #end if
5152 return \
5153 result
5154 #end parse
5155
5156 def __len__(self) :
5157 return \
5158 self._nrelts
5159 #end __len__
5160
5161 def __getitem__(self, index) :
5162 if not isinstance(index, int) or index < 0 or index >= self._nrelts :
5163 raise IndexError("AddressEntries[%d] out of range" % index)
5164 #end if
5165 return \
5166 type(self).Entry(self, index)
5167 #end __getitem__
5168
5169 #end AddressEntries
5170
5171 def address_escape_value(value) :
5172 c_result = dbus.dbus_address_escape_value(value.encode())
5173 if c_result == None :
5174 raise CallFailed("dbus_address_escape_value")
5175 #end if
5176 result = ct.cast(c_result, ct.c_char_p).value.decode()
5177 dbus.dbus_free(c_result)
5178 return \
5179 result
5180 #end address_escape_value
5181
5182 def address_unescape_value(value, error = None) :
5183 error, my_error = _get_error(error)
5184 c_result = dbus.dbus_address_unescape_value(value.encode(), error._dbobj)
5185 my_error.raise_if_set()
5186 if c_result != None :
5187 result = ct.cast(c_result, ct.c_char_p).value.decode()
5188 dbus.dbus_free(c_result)
5189 elif not error.is_set :
5190 raise CallFailed("dbus_address_unescape_value")
5191 else :
5192 result = None
5193 #end if
5194 return \
5195 result
5196 #end address_unescape_value
5197
5198 def format_rule(rule) :
5199 "convenience routine to allow a match rule to be expressed as either" \
5200 " a dict of {key : value} or the usual string \"key='value'\", automatically" \
5201 " converting the former to the latter."
5202
5203 def escape_val(val) :
5204 if "," in val :
5205 if "'" in val :
5206 out = "'"
5207 in_quotes = True
5208 for ch in val :
5209 if ch == "'" :
5210 if in_quotes :
5211 out += "'"
5212 in_quotes = False
5213 #end if
5214 out += "\\'"
5215 else :
5216 if not in_quotes :
5217 out += "'"
5218 in_quotes = True
5219 #end if
5220 out += ch
5221 #end if
5222 #end for
5223 if in_quotes :
5224 out += "'"
5225 #end if
5226 else :
5227 out = "'" + val + "'"
5228 #end if
5229 else :
5230 out = ""
5231 for ch in val :
5232 if ch in ("\\", "'") :
5233 out += "\\"
5234 #end if
5235 out += ch
5236 #end for
5237 #end if
5238 return \
5239 out
5240 #end escape_val
5241
5242 #begin format_rule
5243 if isinstance(rule, str) :
5244 pass
5245 elif isinstance(rule, dict) :
5246 rule = ",".join("%s=%s" % (k, escape_val(rule[k])) for k in sorted(rule))
5247 # sort to ensure some kind of consistent ordering, just for
5248 # appearance’s sake
5249 else :
5250 raise TypeError("rule “%s” must be a dict or string" % repr(rule))
5251 #end if
5252 return \
5253 rule
5254 #end format_rule
5255
5256 class _RuleParser :
5257 # internal definitions for rule parsing.
5258
5259 class PARSE(enum.Enum) :
5260 EXPECT_NAME = 1
5261 EXPECT_UNQUOTED_VALUE = 2
5262 EXPECT_ESCAPED = 3
5263 EXPECT_QUOTED_VALUE = 4
5264 #end PARSE
5265
5266 @classmethod
5267 def unformat_rule(celf, rule) :
5268 "converts a match rule string from the standard syntax to a dict of {key : value} entries."
5269 if isinstance(rule, dict) :
5270 pass
5271 elif isinstance(rule, str) :
5272 PARSE = celf.PARSE
5273 parsed = {}
5274 chars = iter(rule)
5275 state = PARSE.EXPECT_NAME
5276 curname = None
5277 curval = None
5278 while True :
5279 ch = next(chars, None)
5280 if ch == None :
5281 if state == PARSE.EXPECT_ESCAPED :
5282 raise SyntaxError("missing character after backslash")
5283 elif state == PARSE.EXPECT_QUOTED_VALUE :
5284 raise SyntaxError("missing closing apostrophe")
5285 else : # state in (PARSE.EXPECT_NAME, PARSE.EXPECT_UNQUOTED_VALUE)
5286 if curname != None :
5287 if curval != None :
5288 if curname in parsed :
5289 raise SyntaxError("duplicated attribute “%s”" % curname)
5290 #end if
5291 parsed[curname] = curval
5292 else :
5293 raise SyntaxError("missing value for attribute “%s”" % curname)
5294 #end if
5295 #end if
5296 #end if
5297 break
5298 #end if
5299 if state == PARSE.EXPECT_ESCAPED :
5300 if ch == "'" :
5301 usech = ch
5302 nextch = None
5303 else :
5304 usech = "\\"
5305 nextch = ch
5306 #end if
5307 ch = usech
5308 if curval == None :
5309 curval = ch
5310 else :
5311 curval += ch
5312 #end if
5313 ch = nextch # None indicates already processed
5314 state = PARSE.EXPECT_UNQUOTED_VALUE
5315 #end if
5316 if ch != None :
5317 if ch == "," and state != PARSE.EXPECT_QUOTED_VALUE :
5318 if state == PARSE.EXPECT_UNQUOTED_VALUE :
5319 if curname in parsed :
5320 raise SyntaxError("duplicated attribute “%s”" % curname)
5321 #end if
5322 if curval == None :
5323 curval = ""
5324 #end if
5325 parsed[curname] = curval
5326 curname = None
5327 curval = None
5328 state = PARSE.EXPECT_NAME
5329 else :
5330 raise SyntaxError("unexpected comma")
5331 #end if
5332 elif ch == "\\" and state != PARSE.EXPECT_QUOTED_VALUE :
5333 if state == PARSE.EXPECT_UNQUOTED_VALUE :
5334 state = PARSE.EXPECT_ESCAPED
5335 else :
5336 raise SyntaxError("unexpected backslash")
5337 #end if
5338 elif ch == "=" and state != PARSE.EXPECT_QUOTED_VALUE :
5339 if curname == None :
5340 raise SyntaxError("empty attribute name")
5341 #end if
5342 if state == PARSE.EXPECT_NAME :
5343 state = PARSE.EXPECT_UNQUOTED_VALUE
5344 else :
5345 raise SyntaxError("unexpected equals sign")
5346 #end if
5347 elif ch == "'" :
5348 if state == PARSE.EXPECT_UNQUOTED_VALUE :
5349 state = PARSE.EXPECT_QUOTED_VALUE
5350 elif state == PARSE.EXPECT_QUOTED_VALUE :
5351 state = PARSE.EXPECT_UNQUOTED_VALUE
5352 else :
5353 raise SyntaxError("unexpected apostrophe")
5354 #end if
5355 else :
5356 if state == PARSE.EXPECT_NAME :
5357 if curname == None :
5358 curname = ch
5359 else :
5360 curname += ch
5361 #end if
5362 elif state in (PARSE.EXPECT_QUOTED_VALUE, PARSE.EXPECT_UNQUOTED_VALUE) :
5363 if curval == None :
5364 curval = ch
5365 else :
5366 curval += ch
5367 #end if
5368 else :
5369 raise AssertionError("shouldn’t occur: parse state %s" % repr(state))
5370 #end if
5371 #end if
5372 #end if
5373 #end while
5374 rule = parsed
5375 else :
5376 raise TypeError("rule “%s” must be a dict or string" % repr(rule))
5377 #end if
5378 return \
5379 rule
5380 #end unformat_rule
5381
5382 #end _RuleParser
5383
5384 unformat_rule = _RuleParser.unformat_rule
5385 del _RuleParser
5386
5387 def matches_rule(message, rule, destinations = None) :
5388 "does Message message match against the specified rule."
5389 if not isinstance(message, Message) :
5390 raise TypeError("message must be a Message")
5391 #end if
5392 rule = unformat_rule(rule)
5393 eavesdrop = rule.get("eavesdrop", "false") == "true"
5394
5395 def match_message_type(expect, actual) :
5396 return \
5397 actual == Message.type_from_string(expect)
5398 #end match_message_type
5399
5400 def match_path_namespace(expect, actual) :
5401 return \
5402 (
5403 actual != None
5404 and
5405 (
5406 expect == actual
5407 or
5408 actual.startswith(expect) and (expect == "/" or actual[len(expect)] == "/")
5409 )
5410 )
5411 #end match_path_namespace
5412
5413 def match_dotted_namespace(expect, actual) :
5414 return \
5415 (
5416 actual != None
5417 and
5418 (
5419 expect == actual
5420 or
5421 actual.startswith(expect) and actual[len(expect)] == "."
5422 )
5423 )
5424 #end match_dotted_namespace
5425
5426 def get_nth_arg(msg, n, expect_types) :
5427 msg_signature = parse_signature(msg.signature)
5428 if n >= len(msg_signature) :
5429 raise IndexError("arg nr %d beyond nr args %d" % (n, len(msg_signature)))
5430 #end if
5431 val = msg.all_objects[n]
5432 valtype = msg_signature[n]
5433 if valtype not in expect_types :
5434 if False :
5435 raise TypeError \
5436 (
5437 "expecting one of types %s, not %s for arg %d val %s"
5438 %
5439 ((repr(expect_types), repr(valtype), n, repr(val)))
5440 )
5441 #end if
5442 val = None # never match
5443 #end if
5444 return \
5445 val
5446 #end get_nth_arg
5447
5448 def get_arg_0_str(message) :
5449 return \
5450 get_nth_arg(message, 0, [BasicType(TYPE.STRING)])
5451 #end get_arg_0_str
5452
5453 def match_arg_paths(expect, actual) :
5454 return \
5455 (
5456 actual != None
5457 and
5458 (
5459 expect == actual
5460 or
5461 expect.endswith("/") and actual.startswith(expect)
5462 or
5463 actual.endswith("/") and expect.startswith(actual)
5464 )
5465 )
5466 #end match_arg_paths
5467
5468 match_types = \
5469 ( # note that message attribute value of None will fail to match
5470 # any expected string value, which is exactly what we want
5471 ("type", None, match_message_type, None),
5472 ("sender", None, operator.eq, None),
5473 ("interface", None, operator.eq, None),
5474 ("member", None, operator.eq, None),
5475 ("path", None, operator.eq, None),
5476 ("destination", None, operator.eq, None),
5477 ("path_namespace", "path", match_path_namespace, None),
5478 ("arg0namespace", None, match_dotted_namespace, get_arg_0_str),
5479 # “arg«n»path” handled specially below
5480 )
5481
5482 #begin matches_rule
5483 keys_used = set(rule.keys()) - {"eavesdrop"}
5484 matches = \
5485 (
5486 eavesdrop
5487 or
5488 destinations == None
5489 or
5490 message.destination == None
5491 or
5492 message.destination in destinations
5493 )
5494 if matches :
5495 try_matching = iter(match_types)
5496 while True :
5497 try_rule = next(try_matching, None)
5498 if try_rule == None :
5499 break
5500 rulekey, attrname, action, accessor = try_rule
5501 if attrname == None :
5502 attrname = rulekey
5503 #end if
5504 if rulekey in rule :
5505 if accessor != None :
5506 val = accessor(message)
5507 else :
5508 val = getattr(message, attrname)
5509 #end if
5510 keys_used.remove(rulekey)
5511 if not action(rule[rulekey], val) :
5512 matches = False
5513 break
5514 #end if
5515 #end if
5516 #end while
5517 #end if
5518 if matches :
5519 try_matching = iter(rule.keys())
5520 while True :
5521 try_key = next(try_matching, None)
5522 if try_key == None :
5523 break
5524 if try_key.startswith("arg") and not try_key.endswith("namespace") :
5525 argnr = try_key[3:]
5526 is_path = argnr.endswith("path")
5527 if is_path :
5528 argnr = argnr[:-4]
5529 #end if
5530 argnr = int(argnr)
5531 if not (0 <= argnr < 64) :
5532 raise ValueError("argnr %d out of range" % argnr)
5533 #end if
5534 argval = get_nth_arg \
5535 (
5536 message,
5537 argnr,
5538 [BasicType(TYPE.STRING)] + ([], [BasicType(TYPE.OBJECT_PATH)])[is_path]
5539 )
5540 keys_used.remove(try_key)
5541 if not (operator.eq, match_arg_paths)[is_path](rule[try_key], argval) :
5542 matches = False
5543 break
5544 #end if
5545 #end if
5546 #end while
5547 #end if
5548 if matches and len(keys_used) != 0 :
5549 # fixme: not checking for unrecognized rule keys if I didn’t try matching them all
5550 raise KeyError("unrecognized rule keywords: %s" % ", ".join(sorted(keys_used)))
5551 #end if
5552 return \
5553 matches
5554 #end matches_rule
5555
5556 class SignatureIter :
5557 "wraps a DBusSignatureIter object. Do not instantiate directly; use the init" \
5558 " and recurse methods."
5559 # <https://dbus.freedesktop.org/doc/api/html/group__DBusSignature.html>
5560
5561 __slots__ = ("_dbobj", "_signature", "_startiter") # to forestall typos
5562
5563 @classmethod
5564 def init(celf, signature) :
5565 self = celf()
5566 self._signature = ct.c_char_p(signature.encode()) # need to ensure storage stays valid
5567 dbus.dbus_signature_iter_init(self._dbobj, self._signature)
5568 return \
5569 self
5570 #end init
5571
5572 def __init__(self) :
5573 self._dbobj = DBUS.SignatureIter()
5574 self._signature = None # caller will set as necessary
5575 self._startiter = True
5576 #end __init__
5577
5578 def __iter__(self) :
5579 return \
5580 self
5581 #end __iter__
5582
5583 def __next__(self) :
5584 if self._startiter :
5585 self._startiter = False
5586 else :
5587 self.next()
5588 #end if
5589 return \
5590 self
5591 #end __next__
5592
5593 def next(self) :
5594 if dbus.dbus_signature_iter_next(self._dbobj) == 0 :
5595 raise StopIteration("end of signature iterator")
5596 #end if
5597 self._startiter = False
5598 return \
5599 self
5600 #end next
5601
5602 def recurse(self) :
5603 subiter = type(self)()
5604 dbus.dbus_signature_iter_recurse(self._dbobj, subiter._dbobj)
5605 return \
5606 subiter
5607 #end recurse
5608
5609 @property
5610 def current_type(self) :
5611 return \
5612 dbus.dbus_signature_iter_get_current_type(self._dbobj)
5613 #end current_type
5614
5615 @property
5616 def signature(self) :
5617 c_result = dbus.dbus_signature_iter_get_signature(self._dbobj)
5618 result = ct.cast(c_result, ct.c_char_p).value.decode()
5619 dbus.dbus_free(c_result)
5620 return \
5621 result
5622 #end signature
5623
5624 @property
5625 def parsed_signature(self) :
5626 return \
5627 parse_single_signature(self.signature)
5628 #end parsed_signature
5629
5630 @property
5631 def element_type(self) :
5632 return \
5633 dbus.dbus_signature_iter_get_element_type(self._dbobj)
5634 #end element_type
5635
5636 #end SignatureIter
5637
5638 def signature_validate(signature, error = None) :
5639 "is signature a valid sequence of zero or more complete types."
5640 error, my_error = _get_error(error)
5641 result = dbus.dbus_signature_validate(signature.encode(), error._dbobj) != 0
5642 my_error.raise_if_set()
5643 return \
5644 result
5645 #end signature_validate
5646
5647 def parse_signature(signature) :
5648 "convenience routine for parsing a signature string into a list of Type()" \
5649 " instances."
5650
5651 def process_subsig(sigelt) :
5652 elttype = sigelt.current_type
5653 if elttype in DBUS.basic_to_ctypes :
5654 result = BasicType(TYPE(elttype))
5655 elif elttype == DBUS.TYPE_ARRAY :
5656 if sigelt.element_type == DBUS.TYPE_DICT_ENTRY :
5657 subsig = sigelt.recurse()
5658 subsubsig = subsig.recurse()
5659 keytype = process_subsig(next(subsubsig))
5660 valuetype = process_subsig(next(subsubsig))
5661 result = DictType(keytype, valuetype)
5662 else :
5663 subsig = sigelt.recurse()
5664 result = ArrayType(process_subsig(next(subsig)))
5665 #end if
5666 elif elttype == DBUS.TYPE_STRUCT :
5667 result = []
5668 subsig = sigelt.recurse()
5669 for subelt in subsig :
5670 result.append(process_subsig(subelt))
5671 #end for
5672 result = StructType(*result)
5673 elif elttype == DBUS.TYPE_VARIANT :
5674 result = VariantType()
5675 else :
5676 raise RuntimeError("unrecognized type %s" % bytes((elttype,)))
5677 #end if
5678 return \
5679 result
5680 #end process_subsig
5681
5682 #begin parse_signature
5683 if isinstance(signature, (tuple, list)) :
5684 if not all(isinstance(t, Type) for t in signature) :
5685 raise TypeError("signature is list containing non-Type objects")
5686 #end if
5687 result = signature
5688 elif isinstance(signature, Type) :
5689 result = [signature]
5690 elif isinstance(signature, str) :
5691 signature_validate(signature)
5692 result = []
5693 if len(signature) != 0 :
5694 sigiter = SignatureIter.init(signature)
5695 for elt in sigiter :
5696 result.append(process_subsig(elt))
5697 #end for
5698 #end if
5699 else :
5700 raise TypeError("signature must be list or str")
5701 #end if
5702 return \
5703 result
5704 #end parse_signature
5705
5706 def parse_single_signature(signature) :
5707 result = parse_signature(signature)
5708 if len(result) != 1 :
5709 raise ValueError("only single type expected")
5710 #end if
5711 return \
5712 result[0]
5713 #end parse_single_signature
5714
5715 def unparse_signature(signature) :
5716 "converts a signature from parsed form to string form."
5717 signature = parse_signature(signature)
5718 if not isinstance(signature, (tuple, list)) :
5719 signature = [signature]
5720 #end if
5721 return \
5722 DBUS.Signature("".join(t.signature for t in signature))
5723 #end unparse_signature
5724
5725 def signature_validate_single(signature, error = None) :
5726 "is signature a single valid type."
5727 error, my_error = _get_error(error)
5728 result = dbus.dbus_signature_validate_single(signature.encode(), error._dbobj) != 0
5729 my_error.raise_if_set()
5730 return \
5731 result
5732 #end signature_validate_single
5733
5734 def type_is_valid(typecode) :
5735 return \
5736 dbus.dbus_type_is_valid(typecode) != 0
5737 #end type_is_valid
5738
5739 def type_is_basic(typecode) :
5740 return \
5741 dbus.dbus_type_is_basic(typecode) != 0
5742 #end type_is_basic
5743
5744 def type_is_container(typecode) :
5745 return \
5746 dbus.dbus_type_is_container(typecode) != 0
5747 #end type_is_container
5748
5749 def type_is_fixed(typecode) :
5750 return \
5751 dbus.dbus_type_is_fixed(typecode) != 0
5752 #end type_is_fixed
5753
5754 def type_is_fixed_array_elttype(typecode) :
5755 "is typecode suitable as the element type of a fixed_array."
5756 return \
5757 type_is_fixed(typecode) and typecode != DBUS.TYPE_UNIX_FD
5758 #end type_is_fixed_array_elttype
5759
5760 # syntax validation <https://dbus.freedesktop.org/doc/api/html/group__DBusSyntax.html>
5761
5762 def validate_path(path, error = None) :
5763 error, my_error = _get_error(error)
5764 result = dbus.dbus_validate_path(path.encode(), error._dbobj) != 0
5765 my_error.raise_if_set()
5766 return \
5767 result
5768 #end validate_path
5769
5770 def valid_path(path) :
5771 "returns path if valid, raising appropriate exception if not."
5772 validate_path(path)
5773 return \
5774 path
5775 #end valid_path
5776
5777 def split_path(path) :
5778 "convenience routine for splitting a path into a list of components."
5779 if isinstance(path, (tuple, list)) :
5780 result = path # assume already split
5781 elif path == "/" :
5782 result = []
5783 else :
5784 if not path.startswith("/") or path.endswith("/") :
5785 raise DBusError(DBUS.ERROR_INVALID_ARGS, "invalid path %s" % repr(path))
5786 #end if
5787 result = path.split("/")[1:]
5788 #end if
5789 return \
5790 result
5791 #end split_path
5792
5793 def unsplit_path(path) :
5794 path = split_path(path)
5795 if len(path) != 0 :
5796 result = DBUS.ObjectPath("".join("/" + component for component in path))
5797 else :
5798 result = "/"
5799 #end if
5800 return \
5801 result
5802 #end unsplit_path
5803
5804 def validate_interface(name, error = None) :
5805 error, my_error = _get_error(error)
5806 result = dbus.dbus_validate_interface(name.encode(), error._dbobj) != 0
5807 my_error.raise_if_set()
5808 return \
5809 result
5810 #end validate_interface
5811
5812 def valid_interface(name) :
5813 "returns name if it is a valid interface name, raising appropriate exception if not."
5814 validate_interface(name)
5815 return \
5816 name
5817 #end valid_interface
5818
5819 def validate_member(name, error = None) :
5820 error, my_error = _get_error(error)
5821 result = dbus.dbus_validate_member(name.encode(), error._dbobj) != 0
5822 my_error.raise_if_set()
5823 return \
5824 result
5825 #end validate_member
5826
5827 def valid_member(name) :
5828 "returns name if it is a valid member name, raising appropriate exception if not."
5829 validate_member(name)
5830 return \
5831 name
5832 #end valid_member
5833
5834 def validate_error_name(name, error = None) :
5835 error, my_error = _get_error(error)
5836 result = dbus.dbus_validate_error_name(name.encode(), error._dbobj) != 0
5837 my_error.raise_if_set()
5838 return \
5839 result
5840 #end validate_error_name
5841
5842 def valid_error_name(name) :
5843 "returns name if it is a valid error name, raising appropriate exception if not."
5844 validate_error_name(name)
5845 return \
5846 name
5847 #end valid_error_name
5848
5849 def validate_bus_name(name, error = None) :
5850 error, my_error = _get_error(error)
5851 result = dbus.dbus_validate_bus_name(name.encode(), error._dbobj) != 0
5852 my_error.raise_if_set()
5853 return \
5854 result
5855 #end validate_bus_name
5856
5857 def valid_bus_name(name) :
5858 "returns name if it is a valid bus name, raising appropriate exception if not."
5859 validate_bus_name(name)
5860 return \
5861 name
5862 #end valid_bus_name
5863
5864 def validate_utf8(alleged_utf8, error = None) :
5865 "alleged_utf8 must be null-terminated bytes."
5866 error, my_error = _get_error(error)
5867 result = dbus.dbus_validate_utf8(alleged_utf8, error._dbobj) != 0
5868 my_error.raise_if_set()
5869 return \
5870 result
5871 #end validate_utf8
5872
5873 def valid_utf8(alleged_utf8) :
5874 "returns alleged_utf8 if it is a valid utf-8 bytes value, raising" \
5875 " appropriate exception if not."
5876 validate_utf8(alleged_utf8)
5877 return \
5878 alleged_utf8
5879 #end valid_utf8
5880
5881 #+
5882 # Introspection representation
5883 #-
5884
5885 class _TagCommon :
5886
5887 def get_annotation(self, name) :
5888 "returns the value of the annotation with the specified name, or None" \
5889 " if none could be found"
5890 annots = iter(self.annotations)
5891 while True :
5892 annot = next(annots, None)
5893 if annot == None :
5894 result = None
5895 break
5896 #end if
5897 if annot.name == name :
5898 result = annot.value
5899 break
5900 #end if
5901 #end while
5902 return \
5903 result
5904 #end get_annotation
5905
5906 @property
5907 def is_deprecated(self) :
5908 "is this interface/method/signal etc deprecated."
5909 return \
5910 self.get_annotation("org.freedesktop.DBus.Deprecated") == "true"
5911 #end is_deprecated
5912
5913 def __repr__(self) :
5914 celf = type(self)
5915 return \
5916 (
5917 "%s(%s)"
5918 %
5919 (
5920 celf.__name__,
5921 ", ".join
5922 (
5923 "%s = %s"
5924 %
5925 (name, repr(getattr(self, name)))
5926 for name in celf.__slots__
5927 ),
5928 )
5929 )
5930 #end __repr__
5931
5932 #end _TagCommon
5933
5934 class Introspection(_TagCommon) :
5935 "high-level wrapper for the DBUS.INTERFACE_INTROSPECTABLE interface."
5936
5937 __slots__ = ("name", "interfaces", "nodes", "annotations")
5938
5939 tag_name = "node"
5940 tag_attrs = ("name",)
5941 tag_attrs_optional = {"name"}
5942
5943 class DIRECTION(enum.Enum) :
5944 "argument direction."
5945 IN = "in" # client to server
5946 OUT = "out" # server to client
5947 #end DIRECTION
5948
5949 class ACCESS(enum.Enum) :
5950 "property access."
5951 READ = "read"
5952 WRITE = "write"
5953 READWRITE = "readwrite"
5954 #end ACCESS
5955
5956 class PROP_CHANGE_NOTIFICATION(enum.Enum) :
5957 "how/if a changed property emits a notification signal."
5958 NEW_VALUE = "true" # notification includes new value
5959 INVALIDATES = "invalidates" # notification does not include new value
5960 CONST = "const" # property shouldn’t change
5961 NONE = "false" # does not notify changes
5962 #end PROP_CHANGE_NOTIFICATION
5963
5964 class Annotation(_TagCommon) :
5965
5966 __slots__ = ("name", "value")
5967 tag_name = "annotation"
5968 tag_attrs = ("name", "value")
5969 tag_elts = {}
5970
5971 def __init__(self, name, value) :
5972 self.name = name
5973 self.value = value
5974 #end __init__
5975
5976 #end Annotation
5977
5978 def _get_annotations(annotations) :
5979 # common validation of annotations arguments.
5980 if not all(isinstance(a, Introspection.Annotation) for a in annotations) :
5981 raise TypeError("annotations must be Annotation instances")
5982 #end if
5983 return \
5984 annotations
5985 #end _get_annotations
5986
5987 class Interface(_TagCommon) :
5988
5989 __slots__ = ("name", "methods", "signals", "properties", "annotations")
5990 tag_name = "interface"
5991 tag_attrs = ("name",)
5992
5993 class Method(_TagCommon) :
5994
5995 __slots__ = ("name", "args", "annotations")
5996 tag_name = "method"
5997 tag_attrs = ("name",)
5998
5999 class Arg(_TagCommon) :
6000
6001 __slots__ = ("name", "type", "direction", "annotations")
6002 tag_name = "arg"
6003 tag_attrs = ("name", "type", "direction")
6004 tag_attrs_optional = {"name"}
6005 tag_elts = {}
6006 attr_convert = {} # {"direction" : Introspection.DIRECTION} assigned below
6007
6008 def __init__(self, *, name = None, type, direction, annotations = ()) :
6009 if not isinstance(direction, Introspection.DIRECTION) :
6010 raise TypeError("direction must be an Introspection.DIRECTION.xxx enum")
6011 #end if
6012 self.name = name
6013 self.type = parse_single_signature(type)
6014 self.direction = direction
6015 self.annotations = Introspection._get_annotations(annotations)
6016 #end __init__
6017
6018 #end Arg
6019
6020 tag_elts = {"args" : Arg}
6021
6022 def __init__(self, name, args = (), annotations = ()) :
6023 if not all(isinstance(a, self.Arg) for a in args) :
6024 raise TypeError("args must be Arg instances")
6025 #end if
6026 self.name = name
6027 self.args = list(args)
6028 self.annotations = Introspection._get_annotations(annotations)
6029 #end __init__
6030
6031 @property
6032 def in_signature(self) :
6033 return \
6034 list(a.type for a in self.args if a.direction == Introspection.DIRECTION.IN)
6035 #end in_signature
6036
6037 @property
6038 def out_signature(self) :
6039 return \
6040 list \
6041 (a.type for a in self.args if a.direction == Introspection.DIRECTION.OUT)
6042 #end out_signature
6043
6044 @property
6045 def expect_reply(self) :
6046 "will there be replies to this request method."
6047 return \
6048 self.get_annotation("org.freedesktop.DBus.Method.NoReply") != "true"
6049 #end expect_reply
6050
6051 #end Method
6052
6053 class Signal(_TagCommon) :
6054
6055 __slots__ = ("name", "args", "annotations")
6056 tag_name = "signal"
6057 tag_attrs = ("name",)
6058
6059 class Arg(_TagCommon) :
6060
6061 __slots__ = ("name", "type", "direction", "annotations")
6062 tag_name = "arg"
6063 tag_attrs = ("name", "type", "direction")
6064 tag_attrs_optional = {"name", "direction"}
6065 tag_elts = {}
6066 attr_convert = {} # {"direction" : Introspection.DIRECTION} assigned below
6067
6068 def __init__(self, *, name = None, type, direction = None, annotations = ()) :
6069 if direction != None and direction != Introspection.DIRECTION.OUT :
6070 raise ValueError("direction can only be Introspection.DIRECTION.OUT")
6071 #end if
6072 self.name = name
6073 self.type = parse_single_signature(type)
6074 self.direction = direction
6075 self.annotations = Introspection._get_annotations(annotations)
6076 #end __init__
6077
6078 #end Arg
6079
6080 tag_elts = {"args" : Arg}
6081
6082 def __init__(self, name, args = (), annotations = ()) :
6083 if not all(isinstance(a, self.Arg) for a in args) :
6084 raise TypeError("args must be Arg instances")
6085 #end if
6086 self.name = name
6087 self.args = list(args)
6088 self.annotations = Introspection._get_annotations(annotations)
6089 #end __init__
6090
6091 @property
6092 def in_signature(self) :
6093 return \
6094 list(a.type for a in self.args)
6095 #end in_signature
6096
6097 #end Signal
6098
6099 class Property(_TagCommon) :
6100
6101 __slots__ = ("name", "type", "access", "annotations")
6102 tag_name = "property"
6103 tag_attrs = ("name", "type", "access")
6104 tag_elts = {}
6105 attr_convert = {} # {"access" : Introspection.ACCESS} assigned below
6106
6107 def __init__(self, name, type, access, annotations = ()) :
6108 if not isinstance(access, Introspection.ACCESS) :
6109 raise TypeError("access must be an Introspection.ACCESS.xxx enum")
6110 #end if
6111 self.name = name
6112 self.type = parse_single_signature(type)
6113 self.access = access
6114 self.annotations = Introspection._get_annotations(annotations)
6115 #end __init__
6116
6117 #end Property
6118
6119 tag_elts = {"methods" : Method, "signals" : Signal, "properties" : Property}
6120
6121 def __init__(self, name, methods = (), signals = (), properties = (), annotations = ()) :
6122 if not all(isinstance(m, self.Method) for m in methods) :
6123 raise TypeError("methods must be Method instances")
6124 #end if
6125 if not all(isinstance(s, self.Signal) for s in signals) :
6126 raise TypeError("signals must be Signal instances")
6127 #end if
6128 if not all(isinstance(p, self.Property) for p in properties) :
6129 raise TypeError("properties must be Property instances")
6130 #end if
6131 self.name = name
6132 self.methods = list(methods)
6133 self.signals = list(signals)
6134 self.properties = list(properties)
6135 self.annotations = Introspection._get_annotations(annotations)
6136 #end __init__
6137
6138 @property
6139 def methods_by_name(self) :
6140 "returns a dict associating all the methods with their names."
6141 return \
6142 dict((method.name, method) for method in self.methods)
6143 #end methods_by_name
6144
6145 @property
6146 def signals_by_name(self) :
6147 "returns a dict associating all the signals with their names."
6148 return \
6149 dict((signal.name, signal) for signal in self.signals)
6150 #end signals_by_name
6151
6152 @property
6153 def properties_by_name(self) :
6154 "returns a dict associating all the properties with their names."
6155 return \
6156 dict((prop.name, prop) for prop in self.properties)
6157 #end properties_by_name
6158
6159 #end Interface
6160 Interface.Method.Arg.attr_convert["direction"] = DIRECTION
6161 Interface.Signal.Arg.attr_convert["direction"] = lambda x : (lambda : None, lambda : Introspection.DIRECTION(x))[x != None]()
6162 Interface.Property.attr_convert["access"] = ACCESS
6163
6164 class StubInterface(_TagCommon) :
6165 "use this as a replacement for an Interface that you don’t want" \
6166 " to see expanded, e.g. if it has already been seen."
6167
6168 __slots__ = ("name", "annotations")
6169 tag_name = "interface"
6170 tag_attrs = ("name",)
6171 tag_elts = {}
6172
6173 def __init__(self, name) :
6174 self.name = name
6175 self.annotations = ()
6176 #end __init__
6177
6178 #end StubInterface
6179
6180 class Node(_TagCommon) :
6181
6182 __slots__ = ("name", "interfaces", "nodes", "annotations")
6183 tag_name = "node"
6184 tag_attrs = ("name",)
6185
6186 def __init__(self, name, interfaces = (), nodes = (), annotations = ()) :
6187 if not all(isinstance(i, (Introspection.Interface, Introspection.StubInterface)) for i in interfaces) :
6188 raise TypeError("interfaces must be Interface or StubInterface instances")
6189 #end if
6190 if not all(isinstance(n, Introspection.Node) for n in nodes) :
6191 raise TypeError("nodes must be Node instances")
6192 #end if
6193 self.name = name
6194 self.interfaces = interfaces
6195 self.nodes = nodes
6196 self.annotations = Introspection._get_annotations(annotations)
6197 #end __init__
6198
6199 @property
6200 def interfaces_by_name(self) :
6201 "returns a dict associating all the interfaces with their names."
6202 return \
6203 dict((iface.name, iface) for iface in self.interfaces)
6204 #end interfaces_by_name
6205
6206 @property
6207 def nodes_by_name(self) :
6208 "returns a dict associating all the child nodes with their names."
6209 return \
6210 dict((node.name, node) for node in self.nodes)
6211 #end nodes_by_name
6212
6213 #end Node
6214 Node.tag_elts = {"interfaces" : Interface, "nodes" : Node}
6215
6216 tag_elts = {"interfaces" : Interface, "nodes" : Node}
6217
6218 def __init__(self, name = None, interfaces = (), nodes = (), annotations = ()) :
6219 if not all(isinstance(i, self.Interface) for i in interfaces) :
6220 raise TypeError("interfaces must be Interface instances")
6221 #end if
6222 if not all(isinstance(n, self.Node) for n in nodes) :
6223 raise TypeError("nodes must be Node instances")
6224 #end if
6225 self.name = name
6226 self.interfaces = list(interfaces)
6227 self.nodes = list(nodes)
6228 self.annotations = Introspection._get_annotations(annotations)
6229 #end __init__
6230
6231 @property
6232 def interfaces_by_name(self) :
6233 "returns a dict associating all the interfaces with their names."
6234 return \
6235 dict((iface.name, iface) for iface in self.interfaces)
6236 #end interfaces_by_name
6237
6238 @property
6239 def nodes_by_name(self) :
6240 "returns a dict associating all the nodes with their names."
6241 return \
6242 dict((node.name, node) for node in self.nodes)
6243 #end nodes_by_name
6244
6245 @classmethod
6246 def parse(celf, s) :
6247 "generates an Introspection tree from the given XML string description."
6248
6249 def from_string_elts(celf, attrs, tree) :
6250 elts = dict((k, attrs[k]) for k in attrs)
6251 child_tags = dict \
6252 (
6253 (childclass.tag_name, childclass)
6254 for childclass in tuple(celf.tag_elts.values()) + (Introspection.Annotation,)
6255 )
6256 children = []
6257 for child in tree :
6258 if child.tag not in child_tags :
6259 raise KeyError("unrecognized tag %s" % child.tag)
6260 #end if
6261 childclass = child_tags[child.tag]
6262 childattrs = {}
6263 for attrname in childclass.tag_attrs :
6264 if hasattr(childclass, "tag_attrs_optional") and attrname in childclass.tag_attrs_optional :
6265 childattrs[attrname] = child.attrib.get(attrname, None)
6266 else :
6267 if attrname not in child.attrib :
6268 raise ValueError("missing %s attribute for %s tag" % (attrname, child.tag))
6269 #end if
6270 childattrs[attrname] = child.attrib[attrname]
6271 #end if
6272 #end for
6273 if hasattr(childclass, "attr_convert") :
6274 for attr in childclass.attr_convert :
6275 if attr in childattrs :
6276 childattrs[attr] = childclass.attr_convert[attr](childattrs[attr])
6277 #end if
6278 #end for
6279 #end if
6280 children.append(from_string_elts(childclass, childattrs, child))
6281 #end for
6282 for child_tag, childclass in tuple(celf.tag_elts.items()) + ((), (("annotations", Introspection.Annotation),))[tree.tag != "annotation"] :
6283 for child in children :
6284 if isinstance(child, childclass) :
6285 if child_tag not in elts :
6286 elts[child_tag] = []
6287 #end if
6288 elts[child_tag].append(child)
6289 #end if
6290 #end for
6291 #end for
6292 return \
6293 celf(**elts)
6294 #end from_string_elts
6295
6296 #begin parse
6297 tree = XMLElementTree.fromstring(s)
6298 assert tree.tag == "node", "root of introspection tree must be <node> tag"
6299 return \
6300 from_string_elts(Introspection, {}, tree)
6301 #end parse
6302
6303 def unparse(self, indent_step = 4, max_linelen = 72) :
6304 "returns an XML string description of this Introspection tree."
6305
6306 out = io.StringIO()
6307
6308 def to_string(obj, indent) :
6309 tag_name = obj.tag_name
6310 attrs = []
6311 for attrname in obj.tag_attrs :
6312 attr = getattr(obj, attrname)
6313 if attr != None :
6314 if isinstance(attr, enum.Enum) :
6315 attr = attr.value
6316 elif isinstance(attr, Type) :
6317 attr = unparse_signature(attr)
6318 elif not isinstance(attr, str) :
6319 raise TypeError("unexpected attribute type %s for %s" % (type(attr).__name__, repr(attr)))
6320 #end if
6321 attrs.append("%s=%s" % (attrname, quote_xml_attr(attr)))
6322 #end if
6323 #end for
6324 has_elts = \
6325 (
6326 sum
6327 (
6328 len(getattr(obj, attrname))
6329 for attrname in
6330 tuple(obj.tag_elts.keys())
6331 +
6332 ((), ("annotations",))
6333 [not isinstance(obj, Introspection.Annotation)]
6334 )
6335 !=
6336 0
6337 )
6338 out.write(" " * indent + "<" + tag_name)
6339 if (
6340 max_linelen != None
6341 and
6342 indent
6343 +
6344 len(tag_name)
6345 +
6346 sum((len(s) + 1) for s in attrs)
6347 +
6348 2
6349 +
6350 int(has_elts)
6351 >
6352 max_linelen
6353 ) :
6354 out.write("\n")
6355 for attr in attrs :
6356 out.write(" " * (indent + indent_step))
6357 out.write(attr)
6358 out.write("\n")
6359 #end for
6360 out.write(" " * indent)
6361 else :
6362 for attr in attrs :
6363 out.write(" ")
6364 out.write(attr)
6365 #end for
6366 #end if
6367 if not has_elts :
6368 out.write("/")
6369 #end if
6370 out.write(">\n")
6371 if has_elts :
6372 for attrname in sorted(obj.tag_elts.keys()) + ["annotations"] :
6373 for elt in getattr(obj, attrname) :
6374 to_string(elt, indent + indent_step)
6375 #end for
6376 #end for
6377 out.write(" " * indent + "</" + tag_name + ">\n")
6378 #end if
6379 #end to_string
6380
6381 #begin unparse
6382 out.write(DBUS.INTROSPECT_1_0_XML_DOCTYPE_DECL_NODE)
6383 out.write("<node")
6384 if self.name != None :
6385 out.write(" name=%s" % quote_xml_attr(self.name))
6386 #end if
6387 out.write(">\n")
6388 for elt in self.interfaces :
6389 to_string(elt, indent_step)
6390 #end for
6391 for elt in self.nodes :
6392 to_string(elt, indent_step)
6393 #end for
6394 out.write("</node>\n")
6395 return \
6396 out.getvalue()
6397 #end unparse
6398
6399 #end Introspection
6400
6401 del _TagCommon
6402
6403 #+
6404 # Standard interfaces
6405 #-
6406
6407 standard_interfaces = \
6408 {
6409 DBUS.INTERFACE_PEER :
6410 # note implementation of this is hard-coded inside libdbus
6411 Introspection.Interface
6412 (
6413 name = DBUS.INTERFACE_PEER,
6414 methods =
6415 [
6416 Introspection.Interface.Method(name = "Ping"),
6417 Introspection.Interface.Method
6418 (
6419 name = "GetMachineId",
6420 args =
6421 [
6422 Introspection.Interface.Method.Arg
6423 (
6424 name = "machine_uuid",
6425 type = BasicType(TYPE.STRING),
6426 direction = Introspection.DIRECTION.OUT,
6427 ),
6428 ]
6429 ),
6430 ],
6431 ),
6432 DBUS.INTERFACE_LOCAL :
6433 # note implementation of this is hard-coded inside, and specific to, libdbus
6434 Introspection.Interface
6435 (
6436 name = DBUS.INTERFACE_LOCAL,
6437 signals =
6438 [
6439 Introspection.Interface.Signal(name = "Disconnected"),
6440 # auto-generated by libdbus with path = DBUS.PATH_LOCAL
6441 # when connection is closed; cannot be explicitly sent by
6442 # clients. Documented here:
6443 # <https://lists.freedesktop.org/archives/dbus/2018-October/017587.html>
6444 ],
6445 ),
6446 DBUS.INTERFACE_DBUS :
6447 Introspection.Interface
6448 (
6449 name = DBUS.INTERFACE_DBUS,
6450 methods =
6451 [
6452 Introspection.Interface.Method
6453 (
6454 name = "Hello",
6455 args =
6456 [
6457 Introspection.Interface.Method.Arg
6458 (
6459 type = BasicType(TYPE.STRING),
6460 direction = Introspection.DIRECTION.OUT,
6461 ), # returned unique name
6462 ]
6463 ),
6464 Introspection.Interface.Method
6465 (
6466 name = "RequestName",
6467 args =
6468 [
6469 Introspection.Interface.Method.Arg
6470 (
6471 type = BasicType(TYPE.STRING),
6472 direction = Introspection.DIRECTION.IN,
6473 ), # name
6474 Introspection.Interface.Method.Arg
6475 (
6476 type = BasicType(TYPE.UINT32),
6477 direction = Introspection.DIRECTION.IN,
6478 ), # flags DBUS.NAME_FLAG_xxx
6479 Introspection.Interface.Method.Arg
6480 (
6481 type = BasicType(TYPE.UINT32),
6482 direction = Introspection.DIRECTION.OUT,
6483 ), # result DBUS.REQUEST_NAME_REPLY_xxx
6484 ]
6485 ),
6486 Introspection.Interface.Method
6487 (
6488 name = "ReleaseName",
6489 args =
6490 [
6491 Introspection.Interface.Method.Arg
6492 (
6493 type = BasicType(TYPE.STRING),
6494 direction = Introspection.DIRECTION.IN,
6495 ),
6496 Introspection.Interface.Method.Arg
6497 (
6498 type = BasicType(TYPE.UINT32),
6499 direction = Introspection.DIRECTION.OUT,
6500 ), # result DBUS.RELEASE_NAME_REPLY_xxx
6501 ]
6502 ),
6503 Introspection.Interface.Method
6504 (
6505 name = "StartServiceByName",
6506 args =
6507 [
6508 Introspection.Interface.Method.Arg
6509 (
6510 type = BasicType(TYPE.STRING),
6511 direction = Introspection.DIRECTION.IN,
6512 ), # name
6513 Introspection.Interface.Method.Arg
6514 (
6515 type = BasicType(TYPE.UINT32),
6516 direction = Introspection.DIRECTION.IN,
6517 ), # flags (currently unused)
6518 Introspection.Interface.Method.Arg
6519 (
6520 type = BasicType(TYPE.UINT32),
6521 direction = Introspection.DIRECTION.OUT,
6522 ), # result DBUS.START_REPLY_xxx
6523 ]
6524 ),
6525 Introspection.Interface.Method
6526 (
6527 name = "UpdateActivationEnvironment",
6528 args =
6529 [
6530 Introspection.Interface.Method.Arg
6531 (
6532 type = DictType
6533 (
6534 keytype = BasicType(TYPE.STRING),
6535 valuetype = BasicType(TYPE.STRING)
6536 ),
6537 direction = Introspection.DIRECTION.IN,
6538 ), # environment
6539 ]
6540 ),
6541 Introspection.Interface.Method
6542 (
6543 name = "NameHasOwner",
6544 args =
6545 [
6546 Introspection.Interface.Method.Arg
6547 (
6548 type = BasicType(TYPE.STRING),
6549 direction = Introspection.DIRECTION.IN,
6550 ), # name
6551 Introspection.Interface.Method.Arg
6552 (
6553 type = BasicType(TYPE.BOOLEAN),
6554 direction = Introspection.DIRECTION.OUT,
6555 ),
6556 ]
6557 ),
6558 Introspection.Interface.Method
6559 (
6560 name = "ListNames",
6561 args =
6562 [
6563 Introspection.Interface.Method.Arg
6564 (
6565 type = ArrayType(BasicType(TYPE.STRING)),
6566 direction = Introspection.DIRECTION.OUT,
6567 ),
6568 ]
6569 ),
6570 Introspection.Interface.Method
6571 (
6572 name = "ListActivatableNames",
6573 args =
6574 [
6575 Introspection.Interface.Method.Arg
6576 (
6577 type = ArrayType(BasicType(TYPE.STRING)),
6578 direction = Introspection.DIRECTION.OUT,
6579 ),
6580 ]
6581 ),
6582 Introspection.Interface.Method
6583 (
6584 name = "AddMatch",
6585 args =
6586 [
6587 Introspection.Interface.Method.Arg
6588 (
6589 type = BasicType(TYPE.STRING),
6590 direction = Introspection.DIRECTION.IN,
6591 ),
6592 ]
6593 ),
6594 Introspection.Interface.Method
6595 (
6596 name = "RemoveMatch",
6597 args =
6598 [
6599 Introspection.Interface.Method.Arg
6600 (
6601 type = BasicType(TYPE.STRING),
6602 direction = Introspection.DIRECTION.IN,
6603 ),
6604 ]
6605 ),
6606 Introspection.Interface.Method
6607 (
6608 name = "GetNameOwner",
6609 args =
6610 [
6611 Introspection.Interface.Method.Arg
6612 (
6613 type = BasicType(TYPE.STRING),
6614 direction = Introspection.DIRECTION.IN,
6615 ),
6616 Introspection.Interface.Method.Arg
6617 (
6618 type = BasicType(TYPE.STRING),
6619 direction = Introspection.DIRECTION.OUT,
6620 ),
6621 ]
6622 ),
6623 Introspection.Interface.Method
6624 (
6625 name = "ListQueuedOwners",
6626 args =
6627 [
6628 Introspection.Interface.Method.Arg
6629 (
6630 type = BasicType(TYPE.STRING),
6631 direction = Introspection.DIRECTION.IN,
6632 ),
6633 Introspection.Interface.Method.Arg
6634 (
6635 type = ArrayType(BasicType(TYPE.STRING)),
6636 direction = Introspection.DIRECTION.OUT,
6637 ),
6638 ]
6639 ),
6640 Introspection.Interface.Method
6641 (
6642 name = "GetConnectionUnixUser",
6643 args =
6644 [
6645 Introspection.Interface.Method.Arg
6646 (
6647 type = BasicType(TYPE.STRING),
6648 direction = Introspection.DIRECTION.IN,
6649 ),
6650 Introspection.Interface.Method.Arg
6651 (
6652 type = BasicType(TYPE.UINT32),
6653 direction = Introspection.DIRECTION.OUT,
6654 ),
6655 ]
6656 ),
6657 Introspection.Interface.Method
6658 (
6659 name = "GetConnectionUnixProcessID",
6660 args =
6661 [
6662 Introspection.Interface.Method.Arg
6663 (
6664 type = BasicType(TYPE.STRING),
6665 direction = Introspection.DIRECTION.IN,
6666 ),
6667 Introspection.Interface.Method.Arg
6668 (
6669 type = BasicType(TYPE.UINT32),
6670 direction = Introspection.DIRECTION.OUT,
6671 ),
6672 ]
6673 ),
6674 Introspection.Interface.Method
6675 (
6676 name = "GetAdtAuditSessionData",
6677 args =
6678 [
6679 Introspection.Interface.Method.Arg
6680 (
6681 type = BasicType(TYPE.STRING),
6682 direction = Introspection.DIRECTION.IN,
6683 ),
6684 Introspection.Interface.Method.Arg
6685 (
6686 type = ArrayType(BasicType(TYPE.BYTE)),
6687 direction = Introspection.DIRECTION.OUT,
6688 ),
6689 ]
6690 ),
6691 Introspection.Interface.Method
6692 (
6693 name = "GetConnectionSELinuxSecurityContext",
6694 args =
6695 [
6696 Introspection.Interface.Method.Arg
6697 (
6698 type = BasicType(TYPE.STRING),
6699 direction = Introspection.DIRECTION.IN,
6700 ),
6701 Introspection.Interface.Method.Arg
6702 (
6703 type = ArrayType(BasicType(TYPE.BYTE)),
6704 direction = Introspection.DIRECTION.OUT,
6705 ),
6706 ]
6707 ),
6708 Introspection.Interface.Method
6709 (
6710 name = "ReloadConfig",
6711 ),
6712 Introspection.Interface.Method
6713 (
6714 name = "GetId",
6715 args =
6716 [
6717 Introspection.Interface.Method.Arg
6718 (
6719 type = BasicType(TYPE.STRING),
6720 direction = Introspection.DIRECTION.OUT,
6721 ),
6722 ]
6723 ),
6724 Introspection.Interface.Method
6725 (
6726 name = "GetConnectionCredentials",
6727 args =
6728 [
6729 Introspection.Interface.Method.Arg
6730 (
6731 type = BasicType(TYPE.STRING),
6732 direction = Introspection.DIRECTION.IN,
6733 ),
6734 Introspection.Interface.Method.Arg
6735 (
6736 type = DictType(BasicType(TYPE.STRING), VariantType()),
6737 direction = Introspection.DIRECTION.OUT,
6738 ),
6739 ]
6740 ),
6741 ],
6742 signals =
6743 [
6744 Introspection.Interface.Signal
6745 (
6746 name = "NameOwnerChanged",
6747 args =
6748 [
6749 Introspection.Interface.Signal.Arg
6750 (
6751 type = BasicType(TYPE.STRING),
6752 ), # bus name
6753 Introspection.Interface.Signal.Arg
6754 (
6755 type = BasicType(TYPE.STRING),
6756 ), # old owner, empty if none
6757 Introspection.Interface.Signal.Arg
6758 (
6759 type = BasicType(TYPE.STRING),
6760 ), # new owner, empty if none
6761 ]
6762 ),
6763 Introspection.Interface.Signal
6764 (
6765 name = "NameLost", # sent to previous owner of name
6766 args =
6767 [
6768 Introspection.Interface.Signal.Arg
6769 (
6770 type = BasicType(TYPE.STRING),
6771 ),
6772 ]
6773 ),
6774 Introspection.Interface.Signal
6775 (
6776 name = "NameAcquired", # sent to new owner of name
6777 args =
6778 [
6779 Introspection.Interface.Signal.Arg
6780 (
6781 type = BasicType(TYPE.STRING),
6782 ),
6783 ]
6784 ),
6785 ],
6786 ),
6787 DBUS.INTERFACE_INTROSPECTABLE :
6788 Introspection.Interface
6789 (
6790 name = DBUS.INTERFACE_INTROSPECTABLE,
6791 methods =
6792 [
6793 Introspection.Interface.Method
6794 (
6795 name = "Introspect",
6796 args =
6797 [
6798 Introspection.Interface.Method.Arg
6799 (
6800 name = "data",
6801 type = BasicType(TYPE.STRING),
6802 direction = Introspection.DIRECTION.OUT,
6803 ),
6804 ]
6805 ),
6806 ],
6807 ),
6808 DBUS.INTERFACE_PROPERTIES :
6809 Introspection.Interface
6810 (
6811 name = DBUS.INTERFACE_PROPERTIES,
6812 methods =
6813 [
6814 Introspection.Interface.Method
6815 (
6816 name = "Get",
6817 args =
6818 [
6819 Introspection.Interface.Method.Arg
6820 (
6821 name = "interface_name",
6822 type = BasicType(TYPE.STRING),
6823 direction = Introspection.DIRECTION.IN,
6824 ),
6825 Introspection.Interface.Method.Arg
6826 (
6827 name = "property_name",
6828 type = BasicType(TYPE.STRING),
6829 direction = Introspection.DIRECTION.IN,
6830 ),
6831 Introspection.Interface.Method.Arg
6832 (
6833 name = "value",
6834 type = VariantType(),
6835 direction = Introspection.DIRECTION.OUT,
6836 ),
6837 ],
6838 ),
6839 Introspection.Interface.Method
6840 (
6841 name = "Set",
6842 args =
6843 [
6844 Introspection.Interface.Method.Arg
6845 (
6846 name = "interface_name",
6847 type = BasicType(TYPE.STRING),
6848 direction = Introspection.DIRECTION.IN,
6849 ),
6850 Introspection.Interface.Method.Arg
6851 (
6852 name = "property_name",
6853 type = BasicType(TYPE.STRING),
6854 direction = Introspection.DIRECTION.IN,
6855 ),
6856 Introspection.Interface.Method.Arg
6857 (
6858 name = "value",
6859 type = VariantType(),
6860 direction = Introspection.DIRECTION.IN,
6861 ),
6862 ],
6863 ),
6864 Introspection.Interface.Method
6865 (
6866 name = "GetAll",
6867 args =
6868 [
6869 Introspection.Interface.Method.Arg
6870 (
6871 name = "interface_name",
6872 type = BasicType(TYPE.STRING),
6873 direction = Introspection.DIRECTION.IN,
6874 ),
6875 Introspection.Interface.Method.Arg
6876 (
6877 name = "values",
6878 type = DictType(BasicType(TYPE.STRING), VariantType()),
6879 direction = Introspection.DIRECTION.OUT,
6880 ),
6881 ],
6882 ),
6883 ],
6884 signals =
6885 [
6886 Introspection.Interface.Signal
6887 (
6888 name = "PropertiesChanged",
6889 args =
6890 [
6891 Introspection.Interface.Signal.Arg
6892 (
6893 name = "interface_name",
6894 type = BasicType(TYPE.STRING),
6895 ),
6896 Introspection.Interface.Signal.Arg
6897 (
6898 name = "changed_properties",
6899 type = DictType(BasicType(TYPE.STRING), VariantType()),
6900 ),
6901 Introspection.Interface.Signal.Arg
6902 (
6903 name = "invalidated_properties",
6904 type = ArrayType(BasicType(TYPE.STRING)),
6905 ),
6906 ],
6907 ),
6908 ],
6909 ),
6910 DBUS.INTERFACE_MONITORING :
6911 Introspection.Interface
6912 (
6913 name = DBUS.INTERFACE_MONITORING,
6914 methods =
6915 [
6916 Introspection.Interface.Method
6917 (
6918 name = "BecomeMonitor",
6919 args =
6920 [
6921 Introspection.Interface.Method.Arg
6922 (
6923 type = ArrayType(BasicType(TYPE.STRING)),
6924 direction = Introspection.DIRECTION.IN,
6925 ), # match rules to add to the connection
6926 Introspection.Interface.Method.Arg
6927 (
6928 type = BasicType(TYPE.UINT32),
6929 direction = Introspection.DIRECTION.IN,
6930 ), # flags (currently unused)
6931 ],
6932 ),
6933 ],
6934 ),
6935 DBUSX.INTERFACE_OBJECT_MANAGER :
6936 Introspection.Interface
6937 (
6938 name = DBUSX.INTERFACE_OBJECT_MANAGER,
6939 methods =
6940 [
6941 Introspection.Interface.Method
6942 (
6943 name = "GetManagedObjects",
6944 args =
6945 [
6946 Introspection.Interface.Method.Arg
6947 (
6948 name = "objpath_interfaces_and_properties",
6949 type = DictType
6950 (
6951 BasicType(TYPE.OBJECT_PATH),
6952 DictType
6953 (
6954 BasicType(TYPE.STRING), # interface
6955 DictType(BasicType(TYPE.STRING), VariantType())
6956 # properties and values
6957 )
6958 ),
6959 direction = Introspection.DIRECTION.OUT,
6960 ),
6961 ],
6962 ),
6963 ],
6964 signals =
6965 [
6966 Introspection.Interface.Signal
6967 (
6968 name = "InterfacesAdded",
6969 args =
6970 [
6971 Introspection.Interface.Signal.Arg
6972 (
6973 name = "object_path",
6974 type = BasicType(TYPE.OBJECT_PATH),
6975 ),
6976 Introspection.Interface.Signal.Arg
6977 (
6978 name = "interfaces_and_properties",
6979 type = DictType
6980 (
6981 BasicType(TYPE.STRING), # interface added/changed
6982 DictType(BasicType(TYPE.STRING), VariantType())
6983 # properties and values added
6984 ),
6985 ),
6986 ],
6987 ),
6988 Introspection.Interface.Signal
6989 (
6990 name = "InterfacesRemoved",
6991 args =
6992 [
6993 Introspection.Interface.Signal.Arg
6994 (
6995 name = "object_path",
6996 type = BasicType(TYPE.OBJECT_PATH),
6997 ),
6998 Introspection.Interface.Signal.Arg
6999 (
7000 name = "interfaces",
7001 type = ArrayType(BasicType(TYPE.STRING)),
7002 # interfaces removed
7003 ),
7004 ],
7005 ),
7006 ],
7007 ),
7008 }
7009
7010 #+
7011 # Cleanup
7012 #-
7013
7014 def _atexit() :
7015 # disable all __del__ methods at process termination to avoid segfaults
7016 for cls in Connection, Server, PreallocatedSend, Message, PendingCall, Error, AddressEntries :
7017 delattr(cls, "__del__")
7018 #end for
7019 #end _atexit
7020 atexit.register(_atexit)
7021 del _atexit