* net/tramp.el (tramp-file-name-handler)
[emacs.git] / lisp / net / dbus.el
blob4d146a33248a99cad098cab09ca26cbb363776dc
1 ;;; dbus.el --- Elisp bindings for D-Bus.
3 ;; Copyright (C) 2007-2014 Free Software Foundation, Inc.
5 ;; Author: Michael Albinus <michael.albinus@gmx.de>
6 ;; Keywords: comm, hardware
8 ;; This file is part of GNU Emacs.
10 ;; GNU Emacs is free software: you can redistribute it and/or modify
11 ;; it under the terms of the GNU General Public License as published by
12 ;; the Free Software Foundation, either version 3 of the License, or
13 ;; (at your option) any later version.
15 ;; GNU Emacs is distributed in the hope that it will be useful,
16 ;; but WITHOUT ANY WARRANTY; without even the implied warranty of
17 ;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
18 ;; GNU General Public License for more details.
20 ;; You should have received a copy of the GNU General Public License
21 ;; along with GNU Emacs. If not, see <http://www.gnu.org/licenses/>.
23 ;;; Commentary:
25 ;; This package provides language bindings for the D-Bus API. D-Bus
26 ;; is a message bus system, a simple way for applications to talk to
27 ;; one another. See <http://dbus.freedesktop.org/> for details.
29 ;; Low-level language bindings are implemented in src/dbusbind.c.
31 ;; D-Bus support in the Emacs core can be disabled with configuration
32 ;; option "--without-dbus".
34 ;;; Code:
36 ;; Declare used subroutines and variables.
37 (declare-function dbus-message-internal "dbusbind.c")
38 (declare-function dbus--init-bus "dbusbind.c")
39 (defvar dbus-message-type-invalid)
40 (defvar dbus-message-type-method-call)
41 (defvar dbus-message-type-method-return)
42 (defvar dbus-message-type-error)
43 (defvar dbus-message-type-signal)
44 (defvar dbus-debug)
45 (defvar dbus-registered-objects-table)
47 ;; Pacify byte compiler.
48 (eval-when-compile (require 'cl-lib))
50 (require 'xml)
52 (defconst dbus-service-dbus "org.freedesktop.DBus"
53 "The bus name used to talk to the bus itself.")
55 (defconst dbus-path-dbus "/org/freedesktop/DBus"
56 "The object path used to talk to the bus itself.")
58 (defconst dbus-path-local (concat dbus-path-dbus "/Local")
59 "The object path used in local/in-process-generated messages.")
61 ;; Default D-Bus interfaces.
63 (defconst dbus-interface-dbus "org.freedesktop.DBus"
64 "The interface exported by the service `dbus-service-dbus'.")
66 (defconst dbus-interface-peer (concat dbus-interface-dbus ".Peer")
67 "The interface for peer objects.
68 See URL `http://dbus.freedesktop.org/doc/dbus-specification.html#standard-interfaces-peer'.")
70 ;; <interface name="org.freedesktop.DBus.Peer">
71 ;; <method name="Ping">
72 ;; </method>
73 ;; <method name="GetMachineId">
74 ;; <arg name="machine_uuid" type="s" direction="out"/>
75 ;; </method>
76 ;; </interface>
78 (defconst dbus-interface-introspectable
79 (concat dbus-interface-dbus ".Introspectable")
80 "The interface supported by introspectable objects.
81 See URL `http://dbus.freedesktop.org/doc/dbus-specification.html#standard-interfaces-introspectable'.")
83 ;; <interface name="org.freedesktop.DBus.Introspectable">
84 ;; <method name="Introspect">
85 ;; <arg name="data" type="s" direction="out"/>
86 ;; </method>
87 ;; </interface>
89 (defconst dbus-interface-properties (concat dbus-interface-dbus ".Properties")
90 "The interface for property objects.
91 See URL `http://dbus.freedesktop.org/doc/dbus-specification.html#standard-interfaces-properties'.")
93 ;; <interface name="org.freedesktop.DBus.Properties">
94 ;; <method name="Get">
95 ;; <arg name="interface" type="s" direction="in"/>
96 ;; <arg name="propname" type="s" direction="in"/>
97 ;; <arg name="value" type="v" direction="out"/>
98 ;; </method>
99 ;; <method name="Set">
100 ;; <arg name="interface" type="s" direction="in"/>
101 ;; <arg name="propname" type="s" direction="in"/>
102 ;; <arg name="value" type="v" direction="in"/>
103 ;; </method>
104 ;; <method name="GetAll">
105 ;; <arg name="interface" type="s" direction="in"/>
106 ;; <arg name="props" type="a{sv}" direction="out"/>
107 ;; </method>
108 ;; <signal name="PropertiesChanged">
109 ;; <arg name="interface" type="s"/>
110 ;; <arg name="changed_properties" type="a{sv}"/>
111 ;; <arg name="invalidated_properties" type="as"/>
112 ;; </signal>
113 ;; </interface>
115 (defconst dbus-interface-objectmanager
116 (concat dbus-interface-dbus ".ObjectManager")
117 "The object manager interface.
118 See URL `http://dbus.freedesktop.org/doc/dbus-specification.html#standard-interfaces-objectmanager'.")
120 ;; <interface name="org.freedesktop.DBus.ObjectManager">
121 ;; <method name="GetManagedObjects">
122 ;; <arg name="object_paths_interfaces_and_properties"
123 ;; type="a{oa{sa{sv}}}" direction="out"/>
124 ;; </method>
125 ;; <signal name="InterfacesAdded">
126 ;; <arg name="object_path" type="o"/>
127 ;; <arg name="interfaces_and_properties" type="a{sa{sv}}"/>
128 ;; </signal>
129 ;; <signal name="InterfacesRemoved">
130 ;; <arg name="object_path" type="o"/>
131 ;; <arg name="interfaces" type="as"/>
132 ;; </signal>
133 ;; </interface>
135 (defconst dbus-interface-local (concat dbus-interface-dbus ".Local")
136 "An interface whose methods can only be invoked by the local implementation.")
138 ;; <interface name="org.freedesktop.DBus.Local">
139 ;; <signal name="Disconnected">
140 ;; <arg name="object_path" type="o"/>
141 ;; </signal>
142 ;; </interface>
144 ;; Emacs defaults.
145 (defconst dbus-service-emacs "org.gnu.Emacs"
146 "The well known service name of Emacs.")
148 (defconst dbus-path-emacs "/org/gnu/Emacs"
149 "The object path namespace used by Emacs.
150 All object paths provided by the service `dbus-service-emacs'
151 shall be subdirectories of this path.")
153 (defconst dbus-interface-emacs "org.gnu.Emacs"
154 "The interface namespace used by Emacs.")
156 ;; D-Bus constants.
158 (defmacro dbus-ignore-errors (&rest body)
159 "Execute BODY; signal D-Bus error when `dbus-debug' is non-nil.
160 Otherwise, return result of last form in BODY, or all other errors."
161 (declare (indent 0) (debug t))
162 `(condition-case err
163 (progn ,@body)
164 (dbus-error (when dbus-debug (signal (car err) (cdr err))))))
165 (font-lock-add-keywords 'emacs-lisp-mode '("\\<dbus-ignore-errors\\>"))
167 (define-obsolete-variable-alias 'dbus-event-error-hooks
168 'dbus-event-error-functions "24.3")
169 (defvar dbus-event-error-functions '(dbus-notice-synchronous-call-errors)
170 "Functions to be called when a D-Bus error happens in the event handler.
171 Every function must accept two arguments, the event and the error variable
172 caught in `condition-case' by `dbus-error'.")
175 ;;; Basic D-Bus message functions.
177 (defvar dbus-return-values-table (make-hash-table :test 'equal)
178 "Hash table for temporary storing arguments of reply messages.
179 A key in this hash table is a list (:serial BUS SERIAL), like in
180 `dbus-registered-objects-table'. BUS is either a Lisp symbol,
181 `:system' or `:session', or a string denoting the bus address.
182 SERIAL is the serial number of the reply message.
184 The value of an entry is a cons (STATE . RESULT). STATE can be
185 either `:pending' (we are still waiting for the result),
186 `:complete' (the result is available) or `:error' (the reply
187 message was an error message).")
189 (defun dbus-call-method-handler (&rest args)
190 "Handler for reply messages of asynchronous D-Bus message calls.
191 It calls the function stored in `dbus-registered-objects-table'.
192 The result will be made available in `dbus-return-values-table'."
193 (let* ((key (list :serial
194 (dbus-event-bus-name last-input-event)
195 (dbus-event-serial-number last-input-event)))
196 (result (gethash key dbus-return-values-table)))
197 (when (consp result)
198 (setcar result :complete)
199 (setcdr result (if (= (length args) 1) (car args) args)))))
201 (defun dbus-notice-synchronous-call-errors (ev er)
202 "Detect errors resulting from pending synchronous calls."
203 (let* ((key (list :serial
204 (dbus-event-bus-name ev)
205 (dbus-event-serial-number ev)))
206 (result (gethash key dbus-return-values-table)))
207 (when (consp result)
208 (setcar result :error)
209 (setcdr result er))))
211 (defun dbus-call-method (bus service path interface method &rest args)
212 "Call METHOD on the D-Bus BUS.
214 BUS is either a Lisp symbol, `:system' or `:session', or a string
215 denoting the bus address.
217 SERVICE is the D-Bus service name to be used. PATH is the D-Bus
218 object path SERVICE is registered at. INTERFACE is an interface
219 offered by SERVICE. It must provide METHOD.
221 If the parameter `:timeout' is given, the following integer TIMEOUT
222 specifies the maximum number of milliseconds the method call must
223 return. The default value is 25,000. If the method call doesn't
224 return in time, a D-Bus error is raised.
226 All other arguments ARGS are passed to METHOD as arguments. They are
227 converted into D-Bus types via the following rules:
229 t and nil => DBUS_TYPE_BOOLEAN
230 number => DBUS_TYPE_UINT32
231 integer => DBUS_TYPE_INT32
232 float => DBUS_TYPE_DOUBLE
233 string => DBUS_TYPE_STRING
234 list => DBUS_TYPE_ARRAY
236 All arguments can be preceded by a type symbol. For details about
237 type symbols, see Info node `(dbus)Type Conversion'.
239 `dbus-call-method' returns the resulting values of METHOD as a list of
240 Lisp objects. The type conversion happens the other direction as for
241 input arguments. It follows the mapping rules:
243 DBUS_TYPE_BOOLEAN => t or nil
244 DBUS_TYPE_BYTE => number
245 DBUS_TYPE_UINT16 => number
246 DBUS_TYPE_INT16 => integer
247 DBUS_TYPE_UINT32 => number or float
248 DBUS_TYPE_UNIX_FD => number or float
249 DBUS_TYPE_INT32 => integer or float
250 DBUS_TYPE_UINT64 => number or float
251 DBUS_TYPE_INT64 => integer or float
252 DBUS_TYPE_DOUBLE => float
253 DBUS_TYPE_STRING => string
254 DBUS_TYPE_OBJECT_PATH => string
255 DBUS_TYPE_SIGNATURE => string
256 DBUS_TYPE_ARRAY => list
257 DBUS_TYPE_VARIANT => list
258 DBUS_TYPE_STRUCT => list
259 DBUS_TYPE_DICT_ENTRY => list
261 Example:
263 \(dbus-call-method
264 :session \"org.gnome.seahorse\" \"/org/gnome/seahorse/keys/openpgp\"
265 \"org.gnome.seahorse.Keys\" \"GetKeyField\"
266 \"openpgp:657984B8C7A966DD\" \"simple-name\")
268 => (t (\"Philip R. Zimmermann\"))
270 If the result of the METHOD call is just one value, the converted Lisp
271 object is returned instead of a list containing this single Lisp object.
273 \(dbus-call-method
274 :system \"org.freedesktop.Hal\" \"/org/freedesktop/Hal/devices/computer\"
275 \"org.freedesktop.Hal.Device\" \"GetPropertyString\"
276 \"system.kernel.machine\")
278 => \"i686\""
280 (or (memq bus '(:system :session)) (stringp bus)
281 (signal 'wrong-type-argument (list 'keywordp bus)))
282 (or (stringp service)
283 (signal 'wrong-type-argument (list 'stringp service)))
284 (or (stringp path)
285 (signal 'wrong-type-argument (list 'stringp path)))
286 (or (stringp interface)
287 (signal 'wrong-type-argument (list 'stringp interface)))
288 (or (stringp method)
289 (signal 'wrong-type-argument (list 'stringp method)))
291 (let ((timeout (plist-get args :timeout))
292 (check-interval 0.001)
293 (key
294 (apply
295 'dbus-message-internal dbus-message-type-method-call
296 bus service path interface method 'dbus-call-method-handler args))
297 (result (cons :pending nil)))
299 ;; Wait until `dbus-call-method-handler' has put the result into
300 ;; `dbus-return-values-table'. If no timeout is given, use the
301 ;; default 25". Events which are not from D-Bus must be restored.
302 ;; `read-event' performs a redisplay. This must be suppressed; it
303 ;; hurts when reading D-Bus events asynchronously.
305 ;; Work around bug#16775 by busy-waiting with gradual backoff for
306 ;; dbus calls to complete. A better approach would involve either
307 ;; adding arbitrary wait condition support to read-event or
308 ;; restructuring dbus as a kind of process object. Poll at most
309 ;; about once per second for completion.
311 (puthash key result dbus-return-values-table)
312 (unwind-protect
313 (progn
314 (with-timeout ((if timeout (/ timeout 1000.0) 25)
315 (signal 'dbus-error (list "call timed out")))
316 (while (eq (car result) :pending)
317 (let ((event (let ((inhibit-redisplay t) unread-command-events)
318 (read-event nil nil check-interval))))
319 (when event
320 (setf unread-command-events
321 (nconc unread-command-events
322 (cons event nil))))
323 (when (< check-interval 1)
324 (setf check-interval (* check-interval 1.05))))))
325 (when (eq (car result) :error)
326 (signal (cadr result) (cddr result)))
327 (cdr result))
328 (remhash key dbus-return-values-table))))
330 ;; `dbus-call-method' works non-blocking now.
331 (defalias 'dbus-call-method-non-blocking 'dbus-call-method)
332 (make-obsolete 'dbus-call-method-non-blocking 'dbus-call-method "24.3")
334 (defun dbus-call-method-asynchronously
335 (bus service path interface method handler &rest args)
336 "Call METHOD on the D-Bus BUS asynchronously.
338 BUS is either a Lisp symbol, `:system' or `:session', or a string
339 denoting the bus address.
341 SERVICE is the D-Bus service name to be used. PATH is the D-Bus
342 object path SERVICE is registered at. INTERFACE is an interface
343 offered by SERVICE. It must provide METHOD.
345 HANDLER is a Lisp function, which is called when the corresponding
346 return message has arrived. If HANDLER is nil, no return message
347 will be expected.
349 If the parameter `:timeout' is given, the following integer TIMEOUT
350 specifies the maximum number of milliseconds the method call must
351 return. The default value is 25,000. If the method call doesn't
352 return in time, a D-Bus error is raised.
354 All other arguments ARGS are passed to METHOD as arguments. They are
355 converted into D-Bus types via the following rules:
357 t and nil => DBUS_TYPE_BOOLEAN
358 number => DBUS_TYPE_UINT32
359 integer => DBUS_TYPE_INT32
360 float => DBUS_TYPE_DOUBLE
361 string => DBUS_TYPE_STRING
362 list => DBUS_TYPE_ARRAY
364 All arguments can be preceded by a type symbol. For details about
365 type symbols, see Info node `(dbus)Type Conversion'.
367 If HANDLER is a Lisp function, the function returns a key into the
368 hash table `dbus-registered-objects-table'. The corresponding entry
369 in the hash table is removed, when the return message has been arrived,
370 and HANDLER is called.
372 Example:
374 \(dbus-call-method-asynchronously
375 :system \"org.freedesktop.Hal\" \"/org/freedesktop/Hal/devices/computer\"
376 \"org.freedesktop.Hal.Device\" \"GetPropertyString\" 'message
377 \"system.kernel.machine\")
379 => \(:serial :system 2)
381 -| i686"
383 (or (memq bus '(:system :session)) (stringp bus)
384 (signal 'wrong-type-argument (list 'keywordp bus)))
385 (or (stringp service)
386 (signal 'wrong-type-argument (list 'stringp service)))
387 (or (stringp path)
388 (signal 'wrong-type-argument (list 'stringp path)))
389 (or (stringp interface)
390 (signal 'wrong-type-argument (list 'stringp interface)))
391 (or (stringp method)
392 (signal 'wrong-type-argument (list 'stringp method)))
393 (or (null handler) (functionp handler)
394 (signal 'wrong-type-argument (list 'functionp handler)))
396 (apply 'dbus-message-internal dbus-message-type-method-call
397 bus service path interface method handler args))
399 (defun dbus-send-signal (bus service path interface signal &rest args)
400 "Send signal SIGNAL on the D-Bus BUS.
402 BUS is either a Lisp symbol, `:system' or `:session', or a string
403 denoting the bus address. The signal is sent from the D-Bus object
404 Emacs is registered at BUS.
406 SERVICE is the D-Bus name SIGNAL is sent to. It can be either a known
407 name or a unique name. If SERVICE is nil, the signal is sent as
408 broadcast message. PATH is the D-Bus object path SIGNAL is sent from.
409 INTERFACE is an interface available at PATH. It must provide signal
410 SIGNAL.
412 All other arguments ARGS are passed to SIGNAL as arguments. They are
413 converted into D-Bus types via the following rules:
415 t and nil => DBUS_TYPE_BOOLEAN
416 number => DBUS_TYPE_UINT32
417 integer => DBUS_TYPE_INT32
418 float => DBUS_TYPE_DOUBLE
419 string => DBUS_TYPE_STRING
420 list => DBUS_TYPE_ARRAY
422 All arguments can be preceded by a type symbol. For details about
423 type symbols, see Info node `(dbus)Type Conversion'.
425 Example:
427 \(dbus-send-signal
428 :session nil \"/org/gnu/Emacs\" \"org.gnu.Emacs.FileManager\"
429 \"FileModified\" \"/home/albinus/.emacs\")"
431 (or (memq bus '(:system :session)) (stringp bus)
432 (signal 'wrong-type-argument (list 'keywordp bus)))
433 (or (null service) (stringp service)
434 (signal 'wrong-type-argument (list 'stringp service)))
435 (or (stringp path)
436 (signal 'wrong-type-argument (list 'stringp path)))
437 (or (stringp interface)
438 (signal 'wrong-type-argument (list 'stringp interface)))
439 (or (stringp signal)
440 (signal 'wrong-type-argument (list 'stringp signal)))
442 (apply 'dbus-message-internal dbus-message-type-signal
443 bus service path interface signal args))
445 (defun dbus-method-return-internal (bus service serial &rest args)
446 "Return for message SERIAL on the D-Bus BUS.
447 This is an internal function, it shall not be used outside dbus.el."
449 (or (memq bus '(:system :session)) (stringp bus)
450 (signal 'wrong-type-argument (list 'keywordp bus)))
451 (or (stringp service)
452 (signal 'wrong-type-argument (list 'stringp service)))
453 (or (natnump serial)
454 (signal 'wrong-type-argument (list 'natnump serial)))
456 (apply 'dbus-message-internal dbus-message-type-method-return
457 bus service serial args))
459 (defun dbus-method-error-internal (bus service serial &rest args)
460 "Return error message for message SERIAL on the D-Bus BUS.
461 This is an internal function, it shall not be used outside dbus.el."
463 (or (memq bus '(:system :session)) (stringp bus)
464 (signal 'wrong-type-argument (list 'keywordp bus)))
465 (or (stringp service)
466 (signal 'wrong-type-argument (list 'stringp service)))
467 (or (natnump serial)
468 (signal 'wrong-type-argument (list 'natnump serial)))
470 (apply 'dbus-message-internal dbus-message-type-error
471 bus service serial args))
474 ;;; Hash table of registered functions.
476 (defun dbus-list-hash-table ()
477 "Returns all registered member registrations to D-Bus.
478 The return value is a list, with elements of kind (KEY . VALUE).
479 See `dbus-registered-objects-table' for a description of the
480 hash table."
481 (let (result)
482 (maphash
483 (lambda (key value) (add-to-list 'result (cons key value) 'append))
484 dbus-registered-objects-table)
485 result))
487 (defun dbus-setenv (bus variable value)
488 "Set the value of the BUS environment variable named VARIABLE to VALUE.
490 BUS is either a Lisp symbol, `:system' or `:session', or a string
491 denoting the bus address. Both VARIABLE and VALUE should be strings.
493 Normally, services inherit the environment of the BUS daemon. This
494 function adds to or modifies that environment when activating services.
496 Some bus instances, such as `:system', may disable setting the environment."
497 (dbus-call-method
498 bus dbus-service-dbus dbus-path-dbus
499 dbus-interface-dbus "UpdateActivationEnvironment"
500 `(:array (:dict-entry ,variable ,value))))
502 (defun dbus-register-service (bus service &rest flags)
503 "Register known name SERVICE on the D-Bus BUS.
505 BUS is either a Lisp symbol, `:system' or `:session', or a string
506 denoting the bus address.
508 SERVICE is the D-Bus service name that should be registered. It must
509 be a known name.
511 FLAGS are keywords, which control how the service name is registered.
512 The following keywords are recognized:
514 `:allow-replacement': Allow another service to become the primary
515 owner if requested.
517 `:replace-existing': Request to replace the current primary owner.
519 `:do-not-queue': If we can not become the primary owner do not place
520 us in the queue.
522 The function returns a keyword, indicating the result of the
523 operation. One of the following keywords is returned:
525 `:primary-owner': Service has become the primary owner of the
526 requested name.
528 `:in-queue': Service could not become the primary owner and has been
529 placed in the queue.
531 `:exists': Service is already in the queue.
533 `:already-owner': Service is already the primary owner."
535 ;; Add ObjectManager handler.
536 (dbus-register-method
537 bus service nil dbus-interface-objectmanager "GetManagedObjects"
538 'dbus-managed-objects-handler 'dont-register)
540 (let ((arg 0)
541 reply)
542 (dolist (flag flags)
543 (setq arg
544 (+ arg
545 (pcase flag
546 (:allow-replacement 1)
547 (:replace-existing 2)
548 (:do-not-queue 4)
549 (_ (signal 'wrong-type-argument (list flag)))))))
550 (setq reply (dbus-call-method
551 bus dbus-service-dbus dbus-path-dbus dbus-interface-dbus
552 "RequestName" service arg))
553 (pcase reply
554 (1 :primary-owner)
555 (2 :in-queue)
556 (3 :exists)
557 (4 :already-owner)
558 (_ (signal 'dbus-error (list "Could not register service" service))))))
560 (defun dbus-unregister-service (bus service)
561 "Unregister all objects related to SERVICE from D-Bus BUS.
562 BUS is either a Lisp symbol, `:system' or `:session', or a string
563 denoting the bus address. SERVICE must be a known service name.
565 The function returns a keyword, indicating the result of the
566 operation. One of the following keywords is returned:
568 `:released': We successfully released the service.
570 `:non-existent': Service name does not exist on this bus.
572 `:not-owner': We are neither the primary owner nor waiting in the
573 queue of this service."
575 (maphash
576 (lambda (key value)
577 (unless (equal :serial (car key))
578 (dolist (elt value)
579 (ignore-errors
580 (when (and (equal bus (cadr key)) (string-equal service (cadr elt)))
581 (unless
582 (puthash key (delete elt value) dbus-registered-objects-table)
583 (remhash key dbus-registered-objects-table)))))))
584 dbus-registered-objects-table)
585 (let ((reply (dbus-call-method
586 bus dbus-service-dbus dbus-path-dbus dbus-interface-dbus
587 "ReleaseName" service)))
588 (pcase reply
589 (1 :released)
590 (2 :non-existent)
591 (3 :not-owner)
592 (_ (signal 'dbus-error (list "Could not unregister service" service))))))
594 (defun dbus-register-signal
595 (bus service path interface signal handler &rest args)
596 "Register for a signal on the D-Bus BUS.
598 BUS is either a Lisp symbol, `:system' or `:session', or a string
599 denoting the bus address.
601 SERVICE is the D-Bus service name used by the sending D-Bus object.
602 It can be either a known name or the unique name of the D-Bus object
603 sending the signal.
605 PATH is the D-Bus object path SERVICE is registered. INTERFACE
606 is an interface offered by SERVICE. It must provide SIGNAL.
607 HANDLER is a Lisp function to be called when the signal is
608 received. It must accept as arguments the values SIGNAL is
609 sending.
611 SERVICE, PATH, INTERFACE and SIGNAL can be nil. This is
612 interpreted as a wildcard for the respective argument.
614 The remaining arguments ARGS can be keywords or keyword string pairs.
615 The meaning is as follows:
617 `:argN' STRING:
618 `:pathN' STRING: This stands for the Nth argument of the
619 signal. `:pathN' arguments can be used for object path wildcard
620 matches as specified by D-Bus, while an `:argN' argument
621 requires an exact match.
623 `:arg-namespace' STRING: Register for the signals, which first
624 argument defines the service or interface namespace STRING.
626 `:path-namespace' STRING: Register for the object path namespace
627 STRING. All signals sent from an object path, which has STRING as
628 the preceding string, are matched. This requires PATH to be nil.
630 `:eavesdrop': Register for unicast signals which are not directed
631 to the D-Bus object Emacs is registered at D-Bus BUS, if the
632 security policy of BUS allows this.
634 Example:
636 \(defun my-signal-handler (device)
637 (message \"Device %s added\" device))
639 \(dbus-register-signal
640 :system \"org.freedesktop.Hal\" \"/org/freedesktop/Hal/Manager\"
641 \"org.freedesktop.Hal.Manager\" \"DeviceAdded\" 'my-signal-handler)
643 => \(\(:signal :system \"org.freedesktop.Hal.Manager\" \"DeviceAdded\")
644 \(\"org.freedesktop.Hal\" \"/org/freedesktop/Hal/Manager\" my-signal-handler))
646 `dbus-register-signal' returns an object, which can be used in
647 `dbus-unregister-object' for removing the registration."
649 (let ((counter 0)
650 (rule "type='signal'")
651 uname key key1 value)
653 ;; Retrieve unique name of service. If service is a known name,
654 ;; we will register for the corresponding unique name, if any.
655 ;; Signals are sent always with the unique name as sender. Note:
656 ;; the unique name of `dbus-service-dbus' is that string itself.
657 (if (and (stringp service)
658 (not (zerop (length service)))
659 (not (string-equal service dbus-service-dbus))
660 (not (string-match "^:" service)))
661 (setq uname (dbus-get-name-owner bus service))
662 (setq uname service))
664 (setq rule (concat rule
665 (when uname (format ",sender='%s'" uname))
666 (when interface (format ",interface='%s'" interface))
667 (when signal (format ",member='%s'" signal))
668 (when path (format ",path='%s'" path))))
670 ;; Add arguments to the rule.
671 (if (or (stringp (car args)) (null (car args)))
672 ;; As backward compatibility option, we allow just strings.
673 (dolist (arg args)
674 (if (stringp arg)
675 (setq rule (concat rule (format ",arg%d='%s'" counter arg)))
676 (if arg (signal 'wrong-type-argument (list "Wrong argument" arg))))
677 (setq counter (1+ counter)))
679 ;; Parse keywords.
680 (while args
681 (setq
682 key (car args)
683 rule (concat
684 rule
685 (cond
686 ;; `:arg0' .. `:arg63', `:path0' .. `:path63'.
687 ((and (keywordp key)
688 (string-match
689 "^:\\(arg\\|path\\)\\([[:digit:]]+\\)$"
690 (symbol-name key)))
691 (setq counter (match-string 2 (symbol-name key))
692 args (cdr args)
693 value (car args))
694 (unless (and (<= counter 63) (stringp value))
695 (signal 'wrong-type-argument
696 (list "Wrong argument" key value)))
697 (format
698 ",arg%s%s='%s'"
699 counter
700 (if (string-equal (match-string 1 (symbol-name key)) "path")
701 "path" "")
702 value))
703 ;; `:arg-namespace', `:path-namespace'.
704 ((and (keywordp key)
705 (string-match
706 "^:\\(arg\\|path\\)-namespace$" (symbol-name key)))
707 (setq args (cdr args)
708 value (car args))
709 (unless (stringp value)
710 (signal 'wrong-type-argument
711 (list "Wrong argument" key value)))
712 (format
713 ",%s='%s'"
714 (if (string-equal (match-string 1 (symbol-name key)) "path")
715 "path_namespace" "arg0namespace")
716 value))
717 ;; `:eavesdrop'.
718 ((eq key :eavesdrop)
719 ",eavesdrop='true'")
720 (t (signal 'wrong-type-argument (list "Wrong argument" key)))))
721 args (cdr args))))
723 ;; Add the rule to the bus.
724 (condition-case err
725 (dbus-call-method
726 bus dbus-service-dbus dbus-path-dbus dbus-interface-dbus
727 "AddMatch" rule)
728 (dbus-error
729 (if (not (string-match "eavesdrop" rule))
730 (signal (car err) (cdr err))
731 ;; The D-Bus spec says we shall fall back to a rule without eavesdrop.
732 (when dbus-debug (message "Removing eavesdrop from rule %s" rule))
733 (setq rule (replace-regexp-in-string ",eavesdrop='true'" "" rule))
734 (dbus-call-method
735 bus dbus-service-dbus dbus-path-dbus dbus-interface-dbus
736 "AddMatch" rule))))
738 (when dbus-debug (message "Matching rule \"%s\" created" rule))
740 ;; Create a hash table entry.
741 (setq key (list :signal bus interface signal)
742 key1 (list uname service path handler rule)
743 value (gethash key dbus-registered-objects-table))
744 (unless (member key1 value)
745 (puthash key (cons key1 value) dbus-registered-objects-table))
747 ;; Return the object.
748 (list key (list service path handler))))
750 (defun dbus-register-method
751 (bus service path interface method handler &optional dont-register-service)
752 "Register for method METHOD on the D-Bus BUS.
754 BUS is either a Lisp symbol, `:system' or `:session', or a string
755 denoting the bus address.
757 SERVICE is the D-Bus service name of the D-Bus object METHOD is
758 registered for. It must be a known name (See discussion of
759 DONT-REGISTER-SERVICE below).
761 PATH is the D-Bus object path SERVICE is registered (See discussion of
762 DONT-REGISTER-SERVICE below). INTERFACE is the interface offered by
763 SERVICE. It must provide METHOD.
765 HANDLER is a Lisp function to be called when a method call is
766 received. It must accept the input arguments of METHOD. The return
767 value of HANDLER is used for composing the returning D-Bus message.
768 In case HANDLER shall return a reply message with an empty argument
769 list, HANDLER must return the symbol `:ignore'.
771 When DONT-REGISTER-SERVICE is non-nil, the known name SERVICE is not
772 registered. This means that other D-Bus clients have no way of
773 noticing the newly registered method. When interfaces are constructed
774 incrementally by adding single methods or properties at a time,
775 DONT-REGISTER-SERVICE can be used to prevent other clients from
776 discovering the still incomplete interface."
778 ;; Register SERVICE.
779 (unless (or dont-register-service
780 (member service (dbus-list-names bus)))
781 (dbus-register-service bus service))
783 ;; Create a hash table entry. We use nil for the unique name,
784 ;; because the method might be called from anybody.
785 (let* ((key (list :method bus interface method))
786 (key1 (list nil service path handler))
787 (value (gethash key dbus-registered-objects-table)))
789 (unless (member key1 value)
790 (puthash key (cons key1 value) dbus-registered-objects-table))
792 ;; Return the object.
793 (list key (list service path handler))))
795 (defun dbus-unregister-object (object)
796 "Unregister OBJECT from D-Bus.
797 OBJECT must be the result of a preceding `dbus-register-method',
798 `dbus-register-property' or `dbus-register-signal' call. It
799 returns `t' if OBJECT has been unregistered, `nil' otherwise.
801 When OBJECT identifies the last method or property, which is
802 registered for the respective service, Emacs releases its
803 association to the service from D-Bus."
804 ;; Check parameter.
805 (unless (and (consp object) (not (null (car object))) (consp (cdr object)))
806 (signal 'wrong-type-argument (list 'D-Bus object)))
808 ;; Find the corresponding entry in the hash table.
809 (let* ((key (car object))
810 (type (car key))
811 (bus (cadr key))
812 (value (cadr object))
813 (service (car value))
814 (entry (gethash key dbus-registered-objects-table))
815 ret)
816 ;; key has the structure (TYPE BUS INTERFACE MEMBER).
817 ;; value has the structure (SERVICE PATH [HANDLER]).
818 ;; entry has the structure ((UNAME SERVICE PATH MEMBER [RULE]) ...).
819 ;; MEMBER is either a string (the handler), or a cons cell (a
820 ;; property value). UNAME and property values are not taken into
821 ;; account for comparison.
823 ;; Loop over the registered functions.
824 (dolist (elt entry)
825 (when (equal
826 value
827 (butlast (cdr elt) (- (length (cdr elt)) (length value))))
828 (setq ret t)
829 ;; Compute new hash value. If it is empty, remove it from the
830 ;; hash table.
831 (unless (puthash key (delete elt entry) dbus-registered-objects-table)
832 (remhash key dbus-registered-objects-table))
833 ;; Remove match rule of signals.
834 (when (eq type :signal)
835 (dbus-call-method
836 bus dbus-service-dbus dbus-path-dbus dbus-interface-dbus
837 "RemoveMatch" (nth 4 elt)))))
839 ;; Check, whether there is still a registered function or property
840 ;; for the given service. If not, unregister the service from the
841 ;; bus.
842 (when (and service (memq type '(:method :property))
843 (not (catch :found
844 (progn
845 (maphash
846 (lambda (k v)
847 (dolist (e v)
848 (ignore-errors
849 (and
850 ;; Bus.
851 (equal bus (cadr k))
852 ;; Service.
853 (string-equal service (cadr e))
854 ;; Non-empty object path.
855 (cl-caddr e)
856 (throw :found t)))))
857 dbus-registered-objects-table)
858 nil))))
859 (dbus-unregister-service bus service))
860 ;; Return.
861 ret))
864 ;;; D-Bus type conversion.
866 (defun dbus-string-to-byte-array (string)
867 "Transforms STRING to list (:array :byte c1 :byte c2 ...).
868 STRING shall be UTF8 coded."
869 (if (zerop (length string))
870 '(:array :signature "y")
871 (let (result)
872 (dolist (elt (string-to-list string) (append '(:array) result))
873 (setq result (append result (list :byte elt)))))))
875 (defun dbus-byte-array-to-string (byte-array &optional multibyte)
876 "Transforms BYTE-ARRAY into UTF8 coded string.
877 BYTE-ARRAY must be a list of structure (c1 c2 ...), or a byte
878 array as produced by `dbus-string-to-byte-array'. The resulting
879 string is unibyte encoded, unless MULTIBYTE is non-nil."
880 (apply
881 (if multibyte 'string 'unibyte-string)
882 (if (equal byte-array '(:array :signature "y"))
884 (let (result)
885 (dolist (elt byte-array result)
886 (when (characterp elt) (setq result (append result `(,elt)))))))))
888 (defun dbus-escape-as-identifier (string)
889 "Escape an arbitrary STRING so it follows the rules for a C identifier.
890 The escaped string can be used as object path component, interface element
891 component, bus name component or member name in D-Bus.
893 The escaping consists of replacing all non-alphanumerics, and the
894 first character if it's a digit, with an underscore and two
895 lower-case hex digits:
897 \"0123abc_xyz\\x01\\xff\" -> \"_30123abc_5fxyz_01_ff\"
899 i.e. similar to URI encoding, but with \"_\" taking the role of \"%\",
900 and a smaller allowed set. As a special case, \"\" is escaped to
901 \"_\".
903 Returns the escaped string. Algorithm taken from
904 telepathy-glib's `tp_escape_as_identifier'."
905 (if (zerop (length string))
907 (replace-regexp-in-string
908 "^[0-9]\\|[^A-Za-z0-9]"
909 (lambda (x) (format "_%2x" (aref x 0)))
910 string)))
912 (defun dbus-unescape-from-identifier (string)
913 "Retrieve the original string from the encoded STRING as unibyte string.
914 STRING must have been encoded with `dbus-escape-as-identifier'."
915 (if (string-equal string "_")
917 (replace-regexp-in-string
918 "_.."
919 (lambda (x) (byte-to-string (string-to-number (substring x 1) 16)))
920 string)))
923 ;;; D-Bus events.
925 (defun dbus-check-event (event)
926 "Checks whether EVENT is a well formed D-Bus event.
927 EVENT is a list which starts with symbol `dbus-event':
929 (dbus-event BUS TYPE SERIAL SERVICE PATH INTERFACE MEMBER HANDLER &rest ARGS)
931 BUS identifies the D-Bus the message is coming from. It is
932 either a Lisp symbol, `:system' or `:session', or a string
933 denoting the bus address. TYPE is the D-Bus message type which
934 has caused the event, SERIAL is the serial number of the received
935 D-Bus message. SERVICE and PATH are the unique name and the
936 object path of the D-Bus object emitting the message. INTERFACE
937 and MEMBER denote the message which has been sent. HANDLER is
938 the function which has been registered for this message. ARGS
939 are the arguments passed to HANDLER, when it is called during
940 event handling in `dbus-handle-event'.
942 This function raises a `dbus-error' signal in case the event is
943 not well formed."
944 (when dbus-debug (message "DBus-Event %s" event))
945 (unless (and (listp event)
946 (eq (car event) 'dbus-event)
947 ;; Bus symbol.
948 (or (symbolp (nth 1 event))
949 (stringp (nth 1 event)))
950 ;; Type.
951 (and (natnump (nth 2 event))
952 (< dbus-message-type-invalid (nth 2 event)))
953 ;; Serial.
954 (natnump (nth 3 event))
955 ;; Service.
956 (or (= dbus-message-type-method-return (nth 2 event))
957 (= dbus-message-type-error (nth 2 event))
958 (or (stringp (nth 4 event))
959 (null (nth 4 event))))
960 ;; Object path.
961 (or (= dbus-message-type-method-return (nth 2 event))
962 (= dbus-message-type-error (nth 2 event))
963 (stringp (nth 5 event)))
964 ;; Interface.
965 (or (= dbus-message-type-method-return (nth 2 event))
966 (= dbus-message-type-error (nth 2 event))
967 (stringp (nth 6 event)))
968 ;; Member.
969 (or (= dbus-message-type-method-return (nth 2 event))
970 (= dbus-message-type-error (nth 2 event))
971 (stringp (nth 7 event)))
972 ;; Handler.
973 (functionp (nth 8 event)))
974 (signal 'dbus-error (list "Not a valid D-Bus event" event))))
976 ;;;###autoload
977 (defun dbus-handle-event (event)
978 "Handle events from the D-Bus.
979 EVENT is a D-Bus event, see `dbus-check-event'. HANDLER, being
980 part of the event, is called with arguments ARGS.
981 If the HANDLER returns a `dbus-error', it is propagated as return message."
982 (interactive "e")
983 (condition-case err
984 (let (result)
985 ;; We ignore not well-formed events.
986 (dbus-check-event event)
987 ;; Error messages must be propagated.
988 (when (= dbus-message-type-error (nth 2 event))
989 (signal 'dbus-error (nthcdr 9 event)))
990 ;; Apply the handler.
991 (setq result (apply (nth 8 event) (nthcdr 9 event)))
992 ;; Return a message when it is a message call.
993 (when (= dbus-message-type-method-call (nth 2 event))
994 (dbus-ignore-errors
995 (if (eq result :ignore)
996 (dbus-method-return-internal
997 (nth 1 event) (nth 4 event) (nth 3 event))
998 (apply 'dbus-method-return-internal
999 (nth 1 event) (nth 4 event) (nth 3 event)
1000 (if (consp result) result (list result)))))))
1001 ;; Error handling.
1002 (dbus-error
1003 ;; Return an error message when it is a message call.
1004 (when (= dbus-message-type-method-call (nth 2 event))
1005 (dbus-ignore-errors
1006 (dbus-method-error-internal
1007 (nth 1 event) (nth 4 event) (nth 3 event) (cadr err))))
1008 ;; Propagate D-Bus error messages.
1009 (run-hook-with-args 'dbus-event-error-functions event err)
1010 (when dbus-debug
1011 (signal (car err) (cdr err))))))
1013 (defun dbus-event-bus-name (event)
1014 "Return the bus name the event is coming from.
1015 The result is either a Lisp symbol, `:system' or `:session', or a
1016 string denoting the bus address. EVENT is a D-Bus event, see
1017 `dbus-check-event'. This function raises a `dbus-error' signal
1018 in case the event is not well formed."
1019 (dbus-check-event event)
1020 (nth 1 event))
1022 (defun dbus-event-message-type (event)
1023 "Return the message type of the corresponding D-Bus message.
1024 The result is a number. EVENT is a D-Bus event, see
1025 `dbus-check-event'. This function raises a `dbus-error' signal
1026 in case the event is not well formed."
1027 (dbus-check-event event)
1028 (nth 2 event))
1030 (defun dbus-event-serial-number (event)
1031 "Return the serial number of the corresponding D-Bus message.
1032 The result is a number. The serial number is needed for
1033 generating a reply message. EVENT is a D-Bus event, see
1034 `dbus-check-event'. This function raises a `dbus-error' signal
1035 in case the event is not well formed."
1036 (dbus-check-event event)
1037 (nth 3 event))
1039 (defun dbus-event-service-name (event)
1040 "Return the name of the D-Bus object the event is coming from.
1041 The result is a string. EVENT is a D-Bus event, see `dbus-check-event'.
1042 This function raises a `dbus-error' signal in case the event is
1043 not well formed."
1044 (dbus-check-event event)
1045 (nth 4 event))
1047 (defun dbus-event-path-name (event)
1048 "Return the object path of the D-Bus object the event is coming from.
1049 The result is a string. EVENT is a D-Bus event, see `dbus-check-event'.
1050 This function raises a `dbus-error' signal in case the event is
1051 not well formed."
1052 (dbus-check-event event)
1053 (nth 5 event))
1055 (defun dbus-event-interface-name (event)
1056 "Return the interface name of the D-Bus object the event is coming from.
1057 The result is a string. EVENT is a D-Bus event, see `dbus-check-event'.
1058 This function raises a `dbus-error' signal in case the event is
1059 not well formed."
1060 (dbus-check-event event)
1061 (nth 6 event))
1063 (defun dbus-event-member-name (event)
1064 "Return the member name the event is coming from.
1065 It is either a signal name or a method name. The result is a
1066 string. EVENT is a D-Bus event, see `dbus-check-event'. This
1067 function raises a `dbus-error' signal in case the event is not
1068 well formed."
1069 (dbus-check-event event)
1070 (nth 7 event))
1073 ;;; D-Bus registered names.
1075 (defun dbus-list-activatable-names (&optional bus)
1076 "Return the D-Bus service names which can be activated as list.
1077 If BUS is left nil, `:system' is assumed. The result is a list
1078 of strings, which is `nil' when there are no activatable service
1079 names at all."
1080 (dbus-ignore-errors
1081 (dbus-call-method
1082 (or bus :system) dbus-service-dbus
1083 dbus-path-dbus dbus-interface-dbus "ListActivatableNames")))
1085 (defun dbus-list-names (bus)
1086 "Return the service names registered at D-Bus BUS.
1087 The result is a list of strings, which is `nil' when there are no
1088 registered service names at all. Well known names are strings
1089 like \"org.freedesktop.DBus\". Names starting with \":\" are
1090 unique names for services."
1091 (dbus-ignore-errors
1092 (dbus-call-method
1093 bus dbus-service-dbus dbus-path-dbus dbus-interface-dbus "ListNames")))
1095 (defun dbus-list-known-names (bus)
1096 "Retrieve all services which correspond to a known name in BUS.
1097 A service has a known name if it doesn't start with \":\"."
1098 (let (result)
1099 (dolist (name (dbus-list-names bus) result)
1100 (unless (string-equal ":" (substring name 0 1))
1101 (add-to-list 'result name 'append)))))
1103 (defun dbus-list-queued-owners (bus service)
1104 "Return the unique names registered at D-Bus BUS and queued for SERVICE.
1105 The result is a list of strings, or `nil' when there are no
1106 queued name owners service names at all."
1107 (dbus-ignore-errors
1108 (dbus-call-method
1109 bus dbus-service-dbus dbus-path-dbus
1110 dbus-interface-dbus "ListQueuedOwners" service)))
1112 (defun dbus-get-name-owner (bus service)
1113 "Return the name owner of SERVICE registered at D-Bus BUS.
1114 The result is either a string, or `nil' if there is no name owner."
1115 (dbus-ignore-errors
1116 (dbus-call-method
1117 bus dbus-service-dbus dbus-path-dbus
1118 dbus-interface-dbus "GetNameOwner" service)))
1120 (defun dbus-ping (bus service &optional timeout)
1121 "Check whether SERVICE is registered for D-Bus BUS.
1122 TIMEOUT, a nonnegative integer, specifies the maximum number of
1123 milliseconds `dbus-ping' must return. The default value is 25,000.
1125 Note, that this autoloads SERVICE if it is not running yet. If
1126 it shall be checked whether SERVICE is already running, one shall
1127 apply
1129 \(member service \(dbus-list-known-names bus))"
1130 ;; "Ping" raises a D-Bus error if SERVICE does not exist.
1131 ;; Otherwise, it returns silently with `nil'.
1132 (condition-case nil
1133 (not
1134 (if (natnump timeout)
1135 (dbus-call-method
1136 bus service dbus-path-dbus dbus-interface-peer
1137 "Ping" :timeout timeout)
1138 (dbus-call-method
1139 bus service dbus-path-dbus dbus-interface-peer "Ping")))
1140 (dbus-error nil)))
1143 ;;; D-Bus introspection.
1145 (defun dbus-introspect (bus service path)
1146 "Return all interfaces and sub-nodes of SERVICE,
1147 registered at object path PATH at bus BUS.
1149 BUS is either a Lisp symbol, `:system' or `:session', or a string
1150 denoting the bus address. SERVICE must be a known service name,
1151 and PATH must be a valid object path. The last two parameters
1152 are strings. The result, the introspection data, is a string in
1153 XML format."
1154 ;; We don't want to raise errors.
1155 (dbus-ignore-errors
1156 (dbus-call-method
1157 bus service path dbus-interface-introspectable "Introspect"
1158 :timeout 1000)))
1160 (defun dbus-introspect-xml (bus service path)
1161 "Return the introspection data of SERVICE in D-Bus BUS at object path PATH.
1162 The data are a parsed list. The root object is a \"node\",
1163 representing the object path PATH. The root object can contain
1164 \"interface\" and further \"node\" objects."
1165 ;; We don't want to raise errors.
1166 (xml-node-name
1167 (ignore-errors
1168 (with-temp-buffer
1169 (insert (dbus-introspect bus service path))
1170 (xml-parse-region (point-min) (point-max))))))
1172 (defun dbus-introspect-get-attribute (object attribute)
1173 "Return the ATTRIBUTE value of D-Bus introspection OBJECT.
1174 ATTRIBUTE must be a string according to the attribute names in
1175 the D-Bus specification."
1176 (xml-get-attribute-or-nil object (intern attribute)))
1178 (defun dbus-introspect-get-node-names (bus service path)
1179 "Return all node names of SERVICE in D-Bus BUS at object path PATH.
1180 It returns a list of strings. The node names stand for further
1181 object paths of the D-Bus service."
1182 (let ((object (dbus-introspect-xml bus service path))
1183 result)
1184 (dolist (elt (xml-get-children object 'node) result)
1185 (add-to-list
1186 'result (dbus-introspect-get-attribute elt "name") 'append))))
1188 (defun dbus-introspect-get-all-nodes (bus service path)
1189 "Return all node names of SERVICE in D-Bus BUS at object path PATH.
1190 It returns a list of strings, which are further object paths of SERVICE."
1191 (let ((result (list path)))
1192 (dolist (elt
1193 (dbus-introspect-get-node-names bus service path)
1194 result)
1195 (setq elt (expand-file-name elt path))
1196 (setq result
1197 (append result (dbus-introspect-get-all-nodes bus service elt))))))
1199 (defun dbus-introspect-get-interface-names (bus service path)
1200 "Return all interface names of SERVICE in D-Bus BUS at object path PATH.
1201 It returns a list of strings.
1203 There will be always the default interface
1204 \"org.freedesktop.DBus.Introspectable\". Another default
1205 interface is \"org.freedesktop.DBus.Properties\". If present,
1206 \"interface\" objects can also have \"property\" objects as
1207 children, beside \"method\" and \"signal\" objects."
1208 (let ((object (dbus-introspect-xml bus service path))
1209 result)
1210 (dolist (elt (xml-get-children object 'interface) result)
1211 (add-to-list
1212 'result (dbus-introspect-get-attribute elt "name") 'append))))
1214 (defun dbus-introspect-get-interface (bus service path interface)
1215 "Return the INTERFACE of SERVICE in D-Bus BUS at object path PATH.
1216 The return value is an XML object. INTERFACE must be a string,
1217 element of the list returned by `dbus-introspect-get-interface-names'.
1218 The resulting \"interface\" object can contain \"method\", \"signal\",
1219 \"property\" and \"annotation\" children."
1220 (let ((elt (xml-get-children
1221 (dbus-introspect-xml bus service path) 'interface)))
1222 (while (and elt
1223 (not (string-equal
1224 interface
1225 (dbus-introspect-get-attribute (car elt) "name"))))
1226 (setq elt (cdr elt)))
1227 (car elt)))
1229 (defun dbus-introspect-get-method-names (bus service path interface)
1230 "Return a list of strings of all method names of INTERFACE.
1231 SERVICE is a service of D-Bus BUS at object path PATH."
1232 (let ((object (dbus-introspect-get-interface bus service path interface))
1233 result)
1234 (dolist (elt (xml-get-children object 'method) result)
1235 (add-to-list
1236 'result (dbus-introspect-get-attribute elt "name") 'append))))
1238 (defun dbus-introspect-get-method (bus service path interface method)
1239 "Return method METHOD of interface INTERFACE as XML object.
1240 It must be located at SERVICE in D-Bus BUS at object path PATH.
1241 METHOD must be a string, element of the list returned by
1242 `dbus-introspect-get-method-names'. The resulting \"method\"
1243 object can contain \"arg\" and \"annotation\" children."
1244 (let ((elt (xml-get-children
1245 (dbus-introspect-get-interface bus service path interface)
1246 'method)))
1247 (while (and elt
1248 (not (string-equal
1249 method (dbus-introspect-get-attribute (car elt) "name"))))
1250 (setq elt (cdr elt)))
1251 (car elt)))
1253 (defun dbus-introspect-get-signal-names (bus service path interface)
1254 "Return a list of strings of all signal names of INTERFACE.
1255 SERVICE is a service of D-Bus BUS at object path PATH."
1256 (let ((object (dbus-introspect-get-interface bus service path interface))
1257 result)
1258 (dolist (elt (xml-get-children object 'signal) result)
1259 (add-to-list
1260 'result (dbus-introspect-get-attribute elt "name") 'append))))
1262 (defun dbus-introspect-get-signal (bus service path interface signal)
1263 "Return signal SIGNAL of interface INTERFACE as XML object.
1264 It must be located at SERVICE in D-Bus BUS at object path PATH.
1265 SIGNAL must be a string, element of the list returned by
1266 `dbus-introspect-get-signal-names'. The resulting \"signal\"
1267 object can contain \"arg\" and \"annotation\" children."
1268 (let ((elt (xml-get-children
1269 (dbus-introspect-get-interface bus service path interface)
1270 'signal)))
1271 (while (and elt
1272 (not (string-equal
1273 signal (dbus-introspect-get-attribute (car elt) "name"))))
1274 (setq elt (cdr elt)))
1275 (car elt)))
1277 (defun dbus-introspect-get-property-names (bus service path interface)
1278 "Return a list of strings of all property names of INTERFACE.
1279 SERVICE is a service of D-Bus BUS at object path PATH."
1280 (let ((object (dbus-introspect-get-interface bus service path interface))
1281 result)
1282 (dolist (elt (xml-get-children object 'property) result)
1283 (add-to-list
1284 'result (dbus-introspect-get-attribute elt "name") 'append))))
1286 (defun dbus-introspect-get-property (bus service path interface property)
1287 "This function returns PROPERTY of INTERFACE as XML object.
1288 It must be located at SERVICE in D-Bus BUS at object path PATH.
1289 PROPERTY must be a string, element of the list returned by
1290 `dbus-introspect-get-property-names'. The resulting PROPERTY
1291 object can contain \"annotation\" children."
1292 (let ((elt (xml-get-children
1293 (dbus-introspect-get-interface bus service path interface)
1294 'property)))
1295 (while (and elt
1296 (not (string-equal
1297 property
1298 (dbus-introspect-get-attribute (car elt) "name"))))
1299 (setq elt (cdr elt)))
1300 (car elt)))
1302 (defun dbus-introspect-get-annotation-names
1303 (bus service path interface &optional name)
1304 "Return all annotation names as list of strings.
1305 If NAME is `nil', the annotations are children of INTERFACE,
1306 otherwise NAME must be a \"method\", \"signal\", or \"property\"
1307 object, where the annotations belong to."
1308 (let ((object
1309 (if name
1310 (or (dbus-introspect-get-method bus service path interface name)
1311 (dbus-introspect-get-signal bus service path interface name)
1312 (dbus-introspect-get-property bus service path interface name))
1313 (dbus-introspect-get-interface bus service path interface)))
1314 result)
1315 (dolist (elt (xml-get-children object 'annotation) result)
1316 (add-to-list
1317 'result (dbus-introspect-get-attribute elt "name") 'append))))
1319 (defun dbus-introspect-get-annotation
1320 (bus service path interface name annotation)
1321 "Return ANNOTATION as XML object.
1322 If NAME is `nil', ANNOTATION is a child of INTERFACE, otherwise
1323 NAME must be the name of a \"method\", \"signal\", or
1324 \"property\" object, where the ANNOTATION belongs to."
1325 (let ((elt (xml-get-children
1326 (if name
1327 (or (dbus-introspect-get-method
1328 bus service path interface name)
1329 (dbus-introspect-get-signal
1330 bus service path interface name)
1331 (dbus-introspect-get-property
1332 bus service path interface name))
1333 (dbus-introspect-get-interface bus service path interface))
1334 'annotation)))
1335 (while (and elt
1336 (not (string-equal
1337 annotation
1338 (dbus-introspect-get-attribute (car elt) "name"))))
1339 (setq elt (cdr elt)))
1340 (car elt)))
1342 (defun dbus-introspect-get-argument-names (bus service path interface name)
1343 "Return a list of all argument names as list of strings.
1344 NAME must be a \"method\" or \"signal\" object.
1346 Argument names are optional, the function can return `nil'
1347 therefore, even if the method or signal has arguments."
1348 (let ((object
1349 (or (dbus-introspect-get-method bus service path interface name)
1350 (dbus-introspect-get-signal bus service path interface name)))
1351 result)
1352 (dolist (elt (xml-get-children object 'arg) result)
1353 (add-to-list
1354 'result (dbus-introspect-get-attribute elt "name") 'append))))
1356 (defun dbus-introspect-get-argument (bus service path interface name arg)
1357 "Return argument ARG as XML object.
1358 NAME must be a \"method\" or \"signal\" object. ARG must be a string,
1359 element of the list returned by `dbus-introspect-get-argument-names'."
1360 (let ((elt (xml-get-children
1361 (or (dbus-introspect-get-method bus service path interface name)
1362 (dbus-introspect-get-signal bus service path interface name))
1363 'arg)))
1364 (while (and elt
1365 (not (string-equal
1366 arg (dbus-introspect-get-attribute (car elt) "name"))))
1367 (setq elt (cdr elt)))
1368 (car elt)))
1370 (defun dbus-introspect-get-signature
1371 (bus service path interface name &optional direction)
1372 "Return signature of a `method' or `signal', represented by NAME, as string.
1373 If NAME is a `method', DIRECTION can be either \"in\" or \"out\".
1374 If DIRECTION is `nil', \"in\" is assumed.
1376 If NAME is a `signal', and DIRECTION is non-`nil', DIRECTION must
1377 be \"out\"."
1378 ;; For methods, we use "in" as default direction.
1379 (let ((object (or (dbus-introspect-get-method
1380 bus service path interface name)
1381 (dbus-introspect-get-signal
1382 bus service path interface name))))
1383 (when (and (string-equal
1384 "method" (dbus-introspect-get-attribute object "name"))
1385 (not (stringp direction)))
1386 (setq direction "in"))
1387 ;; In signals, no direction is given.
1388 (when (string-equal "signal" (dbus-introspect-get-attribute object "name"))
1389 (setq direction nil))
1390 ;; Collect the signatures.
1391 (mapconcat
1392 (lambda (x)
1393 (let ((arg (dbus-introspect-get-argument
1394 bus service path interface name x)))
1395 (if (or (not (stringp direction))
1396 (string-equal
1397 direction
1398 (dbus-introspect-get-attribute arg "direction")))
1399 (dbus-introspect-get-attribute arg "type")
1400 "")))
1401 (dbus-introspect-get-argument-names bus service path interface name)
1402 "")))
1405 ;;; D-Bus properties.
1407 (defun dbus-get-property (bus service path interface property)
1408 "Return the value of PROPERTY of INTERFACE.
1409 It will be checked at BUS, SERVICE, PATH. The result can be any
1410 valid D-Bus value, or `nil' if there is no PROPERTY."
1411 (dbus-ignore-errors
1412 ;; "Get" returns a variant, so we must use the `car'.
1413 (car
1414 (dbus-call-method
1415 bus service path dbus-interface-properties
1416 "Get" :timeout 500 interface property))))
1418 (defun dbus-set-property (bus service path interface property value)
1419 "Set value of PROPERTY of INTERFACE to VALUE.
1420 It will be checked at BUS, SERVICE, PATH. When the value has
1421 been set successful, the result is VALUE. Otherwise, `nil' is
1422 returned."
1423 (dbus-ignore-errors
1424 ;; "Set" requires a variant.
1425 (dbus-call-method
1426 bus service path dbus-interface-properties
1427 "Set" :timeout 500 interface property (list :variant value))
1428 ;; Return VALUE.
1429 (dbus-get-property bus service path interface property)))
1431 (defun dbus-get-all-properties (bus service path interface)
1432 "Return all properties of INTERFACE at BUS, SERVICE, PATH.
1433 The result is a list of entries. Every entry is a cons of the
1434 name of the property, and its value. If there are no properties,
1435 `nil' is returned."
1436 (dbus-ignore-errors
1437 ;; "GetAll" returns "a{sv}".
1438 (let (result)
1439 (dolist (dict
1440 (dbus-call-method
1441 bus service path dbus-interface-properties
1442 "GetAll" :timeout 500 interface)
1443 result)
1444 (add-to-list 'result (cons (car dict) (cl-caadr dict)) 'append)))))
1446 (defun dbus-register-property
1447 (bus service path interface property access value
1448 &optional emits-signal dont-register-service)
1449 "Register property PROPERTY on the D-Bus BUS.
1451 BUS is either a Lisp symbol, `:system' or `:session', or a string
1452 denoting the bus address.
1454 SERVICE is the D-Bus service name of the D-Bus. It must be a
1455 known name (See discussion of DONT-REGISTER-SERVICE below).
1457 PATH is the D-Bus object path SERVICE is registered (See
1458 discussion of DONT-REGISTER-SERVICE below). INTERFACE is the
1459 name of the interface used at PATH, PROPERTY is the name of the
1460 property of INTERFACE. ACCESS indicates, whether the property
1461 can be changed by other services via D-Bus. It must be either
1462 the symbol `:read' or `:readwrite'. VALUE is the initial value
1463 of the property, it can be of any valid type (see
1464 `dbus-call-method' for details).
1466 If PROPERTY already exists on PATH, it will be overwritten. For
1467 properties with access type `:read' this is the only way to
1468 change their values. Properties with access type `:readwrite'
1469 can be changed by `dbus-set-property'.
1471 The interface \"org.freedesktop.DBus.Properties\" is added to
1472 PATH, including a default handler for the \"Get\", \"GetAll\" and
1473 \"Set\" methods of this interface. When EMITS-SIGNAL is non-nil,
1474 the signal \"PropertiesChanged\" is sent when the property is
1475 changed by `dbus-set-property'.
1477 When DONT-REGISTER-SERVICE is non-nil, the known name SERVICE is
1478 not registered. This means that other D-Bus clients have no way
1479 of noticing the newly registered property. When interfaces are
1480 constructed incrementally by adding single methods or properties
1481 at a time, DONT-REGISTER-SERVICE can be used to prevent other
1482 clients from discovering the still incomplete interface."
1483 (unless (member access '(:read :readwrite))
1484 (signal 'wrong-type-argument (list "Access type invalid" access)))
1486 ;; Add handlers for the three property-related methods.
1487 (dbus-register-method
1488 bus service path dbus-interface-properties "Get"
1489 'dbus-property-handler 'dont-register)
1490 (dbus-register-method
1491 bus service path dbus-interface-properties "GetAll"
1492 'dbus-property-handler 'dont-register)
1493 (dbus-register-method
1494 bus service path dbus-interface-properties "Set"
1495 'dbus-property-handler 'dont-register)
1497 ;; Register SERVICE.
1498 (unless (or dont-register-service (member service (dbus-list-names bus)))
1499 (dbus-register-service bus service))
1501 ;; Send the PropertiesChanged signal.
1502 (when emits-signal
1503 (dbus-send-signal
1504 bus service path dbus-interface-properties "PropertiesChanged"
1505 `((:dict-entry ,property (:variant ,value)))
1506 '(:array)))
1508 ;; Create a hash table entry. We use nil for the unique name,
1509 ;; because the property might be accessed from anybody.
1510 (let ((key (list :property bus interface property))
1511 (val
1512 (list
1513 (list
1514 nil service path
1515 (cons
1516 (if emits-signal (list access :emits-signal) (list access))
1517 value)))))
1518 (puthash key val dbus-registered-objects-table)
1520 ;; Return the object.
1521 (list key (list service path))))
1523 (defun dbus-property-handler (&rest args)
1524 "Default handler for the \"org.freedesktop.DBus.Properties\" interface.
1525 It will be registered for all objects created by `dbus-register-property'."
1526 (let ((bus (dbus-event-bus-name last-input-event))
1527 (service (dbus-event-service-name last-input-event))
1528 (path (dbus-event-path-name last-input-event))
1529 (method (dbus-event-member-name last-input-event))
1530 (interface (car args))
1531 (property (cadr args)))
1532 (cond
1533 ;; "Get" returns a variant.
1534 ((string-equal method "Get")
1535 (let ((entry (gethash (list :property bus interface property)
1536 dbus-registered-objects-table)))
1537 (when (string-equal path (nth 2 (car entry)))
1538 `((:variant ,(cdar (last (car entry))))))))
1540 ;; "Set" expects a variant.
1541 ((string-equal method "Set")
1542 (let* ((value (caar (cddr args)))
1543 (entry (gethash (list :property bus interface property)
1544 dbus-registered-objects-table))
1545 ;; The value of the hash table is a list; in case of
1546 ;; properties it contains just one element (UNAME SERVICE
1547 ;; PATH OBJECT). OBJECT is a cons cell of a list, which
1548 ;; contains a list of annotations (like :read,
1549 ;; :read-write, :emits-signal), and the value of the
1550 ;; property.
1551 (object (car (last (car entry)))))
1552 (unless (consp object)
1553 (signal 'dbus-error
1554 (list "Property not registered at path" property path)))
1555 (unless (member :readwrite (car object))
1556 (signal 'dbus-error
1557 (list "Property not writable at path" property path)))
1558 (puthash (list :property bus interface property)
1559 (list (append (butlast (car entry))
1560 (list (cons (car object) value))))
1561 dbus-registered-objects-table)
1562 ;; Send the "PropertiesChanged" signal.
1563 (when (member :emits-signal (car object))
1564 (dbus-send-signal
1565 bus service path dbus-interface-properties "PropertiesChanged"
1566 `((:dict-entry ,property (:variant ,value)))
1567 '(:array)))
1568 ;; Return empty reply.
1569 :ignore))
1571 ;; "GetAll" returns "a{sv}".
1572 ((string-equal method "GetAll")
1573 (let (result)
1574 (maphash
1575 (lambda (key val)
1576 (when (and (equal (butlast key) (list :property bus interface))
1577 (string-equal path (nth 2 (car val)))
1578 (not (functionp (car (last (car val))))))
1579 (add-to-list
1580 'result
1581 (list :dict-entry
1582 (car (last key))
1583 (list :variant (cdar (last (car val))))))))
1584 dbus-registered-objects-table)
1585 ;; Return the result, or an empty array.
1586 (list :array (or result '(:signature "{sv}"))))))))
1589 ;;; D-Bus object manager.
1591 (defun dbus-get-all-managed-objects (bus service path)
1592 "Return all objects at BUS, SERVICE, PATH, and the children of PATH.
1593 The result is a list of objects. Every object is a cons of an
1594 existing path name, and the list of available interface objects.
1595 An interface object is another cons, which car is the interface
1596 name, and the cdr is the list of properties as returned by
1597 `dbus-get-all-properties' for that path and interface. Example:
1599 \(dbus-get-all-managed-objects :session \"org.gnome.SettingsDaemon\" \"/\")
1601 => \(\(\"/org/gnome/SettingsDaemon/MediaKeys\"
1602 \(\"org.gnome.SettingsDaemon.MediaKeys\")
1603 \(\"org.freedesktop.DBus.Peer\")
1604 \(\"org.freedesktop.DBus.Introspectable\")
1605 \(\"org.freedesktop.DBus.Properties\")
1606 \(\"org.freedesktop.DBus.ObjectManager\"))
1607 \(\"/org/gnome/SettingsDaemon/Power\"
1608 \(\"org.gnome.SettingsDaemon.Power.Keyboard\")
1609 \(\"org.gnome.SettingsDaemon.Power.Screen\")
1610 \(\"org.gnome.SettingsDaemon.Power\"
1611 \(\"Icon\" . \". GThemedIcon battery-full-charged-symbolic \")
1612 \(\"Tooltip\" . \"Laptop battery is charged\"))
1613 \(\"org.freedesktop.DBus.Peer\")
1614 \(\"org.freedesktop.DBus.Introspectable\")
1615 \(\"org.freedesktop.DBus.Properties\")
1616 \(\"org.freedesktop.DBus.ObjectManager\"))
1617 ...)
1619 If possible, \"org.freedesktop.DBus.ObjectManager.GetManagedObjects\"
1620 is used for retrieving the information. Otherwise, the information
1621 is collected via \"org.freedesktop.DBus.Introspectable.Introspect\"
1622 and \"org.freedesktop.DBus.Properties.GetAll\", which is slow."
1623 (let ((result
1624 ;; Direct call. Fails, if the target does not support the
1625 ;; object manager interface.
1626 (dbus-ignore-errors
1627 (dbus-call-method
1628 bus service path dbus-interface-objectmanager
1629 "GetManagedObjects" :timeout 1000))))
1631 (if result
1632 ;; Massage the returned structure.
1633 (dolist (entry result result)
1634 ;; "a{oa{sa{sv}}}".
1635 (dolist (entry1 (cdr entry))
1636 ;; "a{sa{sv}}".
1637 (dolist (entry2 entry1)
1638 ;; "a{sv}".
1639 (if (cadr entry2)
1640 ;; "sv".
1641 (dolist (entry3 (cadr entry2))
1642 (setcdr entry3 (cl-caadr entry3)))
1643 (setcdr entry2 nil)))))
1645 ;; Fallback: collect the information. Slooow!
1646 (dolist (object
1647 (dbus-introspect-get-all-nodes bus service path)
1648 result)
1649 (let (result1)
1650 (dolist
1651 (interface
1652 (dbus-introspect-get-interface-names bus service object)
1653 result1)
1654 (add-to-list
1655 'result1
1656 (cons interface
1657 (dbus-get-all-properties bus service object interface))))
1658 (when result1
1659 (add-to-list 'result (cons object result1))))))))
1661 (defun dbus-managed-objects-handler ()
1662 "Default handler for the \"org.freedesktop.DBus.ObjectManager\" interface.
1663 It will be registered for all objects created by `dbus-register-method'."
1664 (let* ((last-input-event last-input-event)
1665 (bus (dbus-event-bus-name last-input-event))
1666 (path (dbus-event-path-name last-input-event)))
1667 ;; "GetManagedObjects" returns "a{oa{sa{sv}}}".
1668 (let (interfaces result)
1670 ;; Check for object path wildcard interfaces.
1671 (maphash
1672 (lambda (key val)
1673 (when (and (equal (butlast key 2) (list :method bus))
1674 (null (nth 2 (car-safe val))))
1675 (add-to-list 'interfaces (nth 2 key))))
1676 dbus-registered-objects-table)
1678 ;; Check all registered object paths.
1679 (maphash
1680 (lambda (key val)
1681 (let ((object (or (nth 2 (car-safe val)) "")))
1682 (when (and (equal (butlast key 2) (list :method bus))
1683 (string-prefix-p path object))
1684 (dolist (interface (cons (nth 2 key) interfaces))
1685 (unless (assoc object result)
1686 (add-to-list 'result (list object)))
1687 (unless (assoc interface (cdr (assoc object result)))
1688 (setcdr
1689 (assoc object result)
1690 (append
1691 (list (cons
1692 interface
1693 ;; We simulate "org.freedesktop.DBus.Properties.GetAll"
1694 ;; by using an appropriate D-Bus event.
1695 (let ((last-input-event
1696 (append
1697 (butlast last-input-event 4)
1698 (list object dbus-interface-properties
1699 "GetAll" 'dbus-property-handler))))
1700 (dbus-property-handler interface))))
1701 (cdr (assoc object result)))))))))
1702 dbus-registered-objects-table)
1704 ;; Return the result, or an empty array.
1705 (list
1706 :array
1708 (mapcar
1709 (lambda (x)
1710 (list
1711 :dict-entry :object-path (car x)
1712 (cons :array (mapcar (lambda (y) (cons :dict-entry y)) (cdr x)))))
1713 result)
1714 '(:signature "{oa{sa{sv}}}"))))))
1716 (defun dbus-handle-bus-disconnect ()
1717 "React to a bus disconnection.
1718 BUS is the bus that disconnected. This routine unregisters all
1719 handlers on the given bus and causes all synchronous calls
1720 pending at the time of disconnect to fail."
1721 (let ((bus (dbus-event-bus-name last-input-event))
1722 (keys-to-remove))
1723 (maphash
1724 (lambda (key value)
1725 (when (and (eq (nth 0 key) :serial)
1726 (eq (nth 1 key) bus))
1727 (run-hook-with-args
1728 'dbus-event-error-functions
1729 (list 'dbus-event
1731 dbus-message-type-error
1732 (nth 2 key)
1737 value)
1738 (list 'dbus-error "Bus disconnected" bus))
1739 (push key keys-to-remove)))
1740 dbus-registered-objects-table)
1741 (dolist (key keys-to-remove)
1742 (remhash key dbus-registered-objects-table))))
1744 (defun dbus-init-bus (bus &optional private)
1745 "Establish the connection to D-Bus BUS.
1747 BUS can be either the symbol `:system' or the symbol `:session', or it
1748 can be a string denoting the address of the corresponding bus. For
1749 the system and session buses, this function is called when loading
1750 `dbus.el', there is no need to call it again.
1752 The function returns a number, which counts the connections this Emacs
1753 session has established to the BUS under the same unique name (see
1754 `dbus-get-unique-name'). It depends on the libraries Emacs is linked
1755 with, and on the environment Emacs is running. For example, if Emacs
1756 is linked with the gtk toolkit, and it runs in a GTK-aware environment
1757 like Gnome, another connection might already be established.
1759 When PRIVATE is non-nil, a new connection is established instead of
1760 reusing an existing one. It results in a new unique name at the bus.
1761 This can be used, if it is necessary to distinguish from another
1762 connection used in the same Emacs process, like the one established by
1763 GTK+. It should be used with care for at least the `:system' and
1764 `:session' buses, because other Emacs Lisp packages might already use
1765 this connection to those buses."
1766 (dbus--init-bus bus private)
1767 (dbus-register-signal
1768 bus nil dbus-path-local dbus-interface-local
1769 "Disconnected" #'dbus-handle-bus-disconnect))
1772 ;; Initialize `:system' and `:session' buses. This adds their file
1773 ;; descriptors to input_wait_mask, in order to detect incoming
1774 ;; messages immediately.
1775 (when (featurep 'dbusbind)
1776 (dbus-ignore-errors
1777 (dbus-init-bus :system))
1778 (dbus-ignore-errors
1779 (dbus-init-bus :session)))
1781 (provide 'dbus)
1783 ;;; TODO:
1785 ;; * Implement org.freedesktop.DBus.ObjectManager.InterfacesAdded and
1786 ;; org.freedesktop.DBus.ObjectManager.InterfacesRemoved.
1788 ;;; dbus.el ends here