Update copyright year to 2014 by running admin/update-copyright.
[emacs.git] / lisp / net / dbus.el
blob032315c363cedf7835b3c7b7eb3ef97c3b6389ed
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 ;; Default D-Bus interfaces.
60 (defconst dbus-interface-dbus "org.freedesktop.DBus"
61 "The interface exported by the service `dbus-service-dbus'.")
63 (defconst dbus-interface-peer (concat dbus-interface-dbus ".Peer")
64 "The interface for peer objects.
65 See URL `http://dbus.freedesktop.org/doc/dbus-specification.html#standard-interfaces-peer'.")
67 ;; <interface name="org.freedesktop.DBus.Peer">
68 ;; <method name="Ping">
69 ;; </method>
70 ;; <method name="GetMachineId">
71 ;; <arg name="machine_uuid" type="s" direction="out"/>
72 ;; </method>
73 ;; </interface>
75 (defconst dbus-interface-introspectable
76 (concat dbus-interface-dbus ".Introspectable")
77 "The interface supported by introspectable objects.
78 See URL `http://dbus.freedesktop.org/doc/dbus-specification.html#standard-interfaces-introspectable'.")
80 ;; <interface name="org.freedesktop.DBus.Introspectable">
81 ;; <method name="Introspect">
82 ;; <arg name="data" type="s" direction="out"/>
83 ;; </method>
84 ;; </interface>
86 (defconst dbus-interface-properties (concat dbus-interface-dbus ".Properties")
87 "The interface for property objects.
88 See URL `http://dbus.freedesktop.org/doc/dbus-specification.html#standard-interfaces-properties'.")
90 ;; <interface name="org.freedesktop.DBus.Properties">
91 ;; <method name="Get">
92 ;; <arg name="interface" type="s" direction="in"/>
93 ;; <arg name="propname" type="s" direction="in"/>
94 ;; <arg name="value" type="v" direction="out"/>
95 ;; </method>
96 ;; <method name="Set">
97 ;; <arg name="interface" type="s" direction="in"/>
98 ;; <arg name="propname" type="s" direction="in"/>
99 ;; <arg name="value" type="v" direction="in"/>
100 ;; </method>
101 ;; <method name="GetAll">
102 ;; <arg name="interface" type="s" direction="in"/>
103 ;; <arg name="props" type="a{sv}" direction="out"/>
104 ;; </method>
105 ;; <signal name="PropertiesChanged">
106 ;; <arg name="interface" type="s"/>
107 ;; <arg name="changed_properties" type="a{sv}"/>
108 ;; <arg name="invalidated_properties" type="as"/>
109 ;; </signal>
110 ;; </interface>
112 (defconst dbus-interface-objectmanager
113 (concat dbus-interface-dbus ".ObjectManager")
114 "The object manager interface.
115 See URL `http://dbus.freedesktop.org/doc/dbus-specification.html#standard-interfaces-objectmanager'.")
117 ;; <interface name="org.freedesktop.DBus.ObjectManager">
118 ;; <method name="GetManagedObjects">
119 ;; <arg name="object_paths_interfaces_and_properties"
120 ;; type="a{oa{sa{sv}}}" direction="out"/>
121 ;; </method>
122 ;; <signal name="InterfacesAdded">
123 ;; <arg name="object_path" type="o"/>
124 ;; <arg name="interfaces_and_properties" type="a{sa{sv}}"/>
125 ;; </signal>
126 ;; <signal name="InterfacesRemoved">
127 ;; <arg name="object_path" type="o"/>
128 ;; <arg name="interfaces" type="as"/>
129 ;; </signal>
130 ;; </interface>
132 ;; Emacs defaults.
133 (defconst dbus-service-emacs "org.gnu.Emacs"
134 "The well known service name of Emacs.")
136 (defconst dbus-path-emacs "/org/gnu/Emacs"
137 "The object path namespace used by Emacs.
138 All object paths provided by the service `dbus-service-emacs'
139 shall be subdirectories of this path.")
141 (defconst dbus-interface-emacs "org.gnu.Emacs"
142 "The interface namespace used by Emacs.")
144 ;; D-Bus constants.
146 (defmacro dbus-ignore-errors (&rest body)
147 "Execute BODY; signal D-Bus error when `dbus-debug' is non-nil.
148 Otherwise, return result of last form in BODY, or all other errors."
149 (declare (indent 0) (debug t))
150 `(condition-case err
151 (progn ,@body)
152 (dbus-error (when dbus-debug (signal (car err) (cdr err))))))
153 (font-lock-add-keywords 'emacs-lisp-mode '("\\<dbus-ignore-errors\\>"))
155 (define-obsolete-variable-alias 'dbus-event-error-hooks
156 'dbus-event-error-functions "24.3")
157 (defvar dbus-event-error-functions nil
158 "Functions to be called when a D-Bus error happens in the event handler.
159 Every function must accept two arguments, the event and the error variable
160 caught in `condition-case' by `dbus-error'.")
163 ;;; Basic D-Bus message functions.
165 (defvar dbus-return-values-table (make-hash-table :test 'equal)
166 "Hash table for temporary storing arguments of reply messages.
167 A key in this hash table is a list (:serial BUS SERIAL), like in
168 `dbus-registered-objects-table'. BUS is either a Lisp symbol,
169 `:system' or `:session', or a string denoting the bus address.
170 SERIAL is the serial number of the reply message.")
172 (defun dbus-call-method-handler (&rest args)
173 "Handler for reply messages of asynchronous D-Bus message calls.
174 It calls the function stored in `dbus-registered-objects-table'.
175 The result will be made available in `dbus-return-values-table'."
176 (puthash (list :serial
177 (dbus-event-bus-name last-input-event)
178 (dbus-event-serial-number last-input-event))
179 (if (= (length args) 1) (car args) args)
180 dbus-return-values-table))
182 (defun dbus-call-method (bus service path interface method &rest args)
183 "Call METHOD on the D-Bus BUS.
185 BUS is either a Lisp symbol, `:system' or `:session', or a string
186 denoting the bus address.
188 SERVICE is the D-Bus service name to be used. PATH is the D-Bus
189 object path SERVICE is registered at. INTERFACE is an interface
190 offered by SERVICE. It must provide METHOD.
192 If the parameter `:timeout' is given, the following integer TIMEOUT
193 specifies the maximum number of milliseconds the method call must
194 return. The default value is 25,000. If the method call doesn't
195 return in time, a D-Bus error is raised.
197 All other arguments ARGS are passed to METHOD as arguments. They are
198 converted into D-Bus types via the following rules:
200 t and nil => DBUS_TYPE_BOOLEAN
201 number => DBUS_TYPE_UINT32
202 integer => DBUS_TYPE_INT32
203 float => DBUS_TYPE_DOUBLE
204 string => DBUS_TYPE_STRING
205 list => DBUS_TYPE_ARRAY
207 All arguments can be preceded by a type symbol. For details about
208 type symbols, see Info node `(dbus)Type Conversion'.
210 `dbus-call-method' returns the resulting values of METHOD as a list of
211 Lisp objects. The type conversion happens the other direction as for
212 input arguments. It follows the mapping rules:
214 DBUS_TYPE_BOOLEAN => t or nil
215 DBUS_TYPE_BYTE => number
216 DBUS_TYPE_UINT16 => number
217 DBUS_TYPE_INT16 => integer
218 DBUS_TYPE_UINT32 => number or float
219 DBUS_TYPE_UNIX_FD => number or float
220 DBUS_TYPE_INT32 => integer or float
221 DBUS_TYPE_UINT64 => number or float
222 DBUS_TYPE_INT64 => integer or float
223 DBUS_TYPE_DOUBLE => float
224 DBUS_TYPE_STRING => string
225 DBUS_TYPE_OBJECT_PATH => string
226 DBUS_TYPE_SIGNATURE => string
227 DBUS_TYPE_ARRAY => list
228 DBUS_TYPE_VARIANT => list
229 DBUS_TYPE_STRUCT => list
230 DBUS_TYPE_DICT_ENTRY => list
232 Example:
234 \(dbus-call-method
235 :session \"org.gnome.seahorse\" \"/org/gnome/seahorse/keys/openpgp\"
236 \"org.gnome.seahorse.Keys\" \"GetKeyField\"
237 \"openpgp:657984B8C7A966DD\" \"simple-name\")
239 => (t (\"Philip R. Zimmermann\"))
241 If the result of the METHOD call is just one value, the converted Lisp
242 object is returned instead of a list containing this single Lisp object.
244 \(dbus-call-method
245 :system \"org.freedesktop.Hal\" \"/org/freedesktop/Hal/devices/computer\"
246 \"org.freedesktop.Hal.Device\" \"GetPropertyString\"
247 \"system.kernel.machine\")
249 => \"i686\""
251 (or (memq bus '(:system :session)) (stringp bus)
252 (signal 'wrong-type-argument (list 'keywordp bus)))
253 (or (stringp service)
254 (signal 'wrong-type-argument (list 'stringp service)))
255 (or (stringp path)
256 (signal 'wrong-type-argument (list 'stringp path)))
257 (or (stringp interface)
258 (signal 'wrong-type-argument (list 'stringp interface)))
259 (or (stringp method)
260 (signal 'wrong-type-argument (list 'stringp method)))
262 (let ((timeout (plist-get args :timeout))
263 (key
264 (apply
265 'dbus-message-internal dbus-message-type-method-call
266 bus service path interface method 'dbus-call-method-handler args)))
268 ;; Wait until `dbus-call-method-handler' has put the result into
269 ;; `dbus-return-values-table'. If no timeout is given, use the
270 ;; default 25". Events which are not from D-Bus must be restored.
271 ;; `read-event' performs a redisplay. This must be suppressed; it
272 ;; hurts when reading D-Bus events asynchronously.
273 (with-timeout ((if timeout (/ timeout 1000.0) 25))
274 (while (eq (gethash key dbus-return-values-table :ignore) :ignore)
275 (let ((event (let ((inhibit-redisplay t) unread-command-events)
276 (read-event nil nil 0.1))))
277 (when (and event (not (ignore-errors (dbus-check-event event))))
278 (setq unread-command-events
279 (append unread-command-events (list event)))))))
281 ;; Cleanup `dbus-return-values-table'. Return the result.
282 (prog1
283 (gethash key dbus-return-values-table)
284 (remhash key dbus-return-values-table))))
286 ;; `dbus-call-method' works non-blocking now.
287 (defalias 'dbus-call-method-non-blocking 'dbus-call-method)
288 (make-obsolete 'dbus-call-method-non-blocking 'dbus-call-method "24.3")
290 (defun dbus-call-method-asynchronously
291 (bus service path interface method handler &rest args)
292 "Call METHOD on the D-Bus BUS asynchronously.
294 BUS is either a Lisp symbol, `:system' or `:session', or a string
295 denoting the bus address.
297 SERVICE is the D-Bus service name to be used. PATH is the D-Bus
298 object path SERVICE is registered at. INTERFACE is an interface
299 offered by SERVICE. It must provide METHOD.
301 HANDLER is a Lisp function, which is called when the corresponding
302 return message has arrived. If HANDLER is nil, no return message
303 will be expected.
305 If the parameter `:timeout' is given, the following integer TIMEOUT
306 specifies the maximum number of milliseconds the method call must
307 return. The default value is 25,000. If the method call doesn't
308 return in time, a D-Bus error is raised.
310 All other arguments ARGS are passed to METHOD as arguments. They are
311 converted into D-Bus types via the following rules:
313 t and nil => DBUS_TYPE_BOOLEAN
314 number => DBUS_TYPE_UINT32
315 integer => DBUS_TYPE_INT32
316 float => DBUS_TYPE_DOUBLE
317 string => DBUS_TYPE_STRING
318 list => DBUS_TYPE_ARRAY
320 All arguments can be preceded by a type symbol. For details about
321 type symbols, see Info node `(dbus)Type Conversion'.
323 If HANDLER is a Lisp function, the function returns a key into the
324 hash table `dbus-registered-objects-table'. The corresponding entry
325 in the hash table is removed, when the return message has been arrived,
326 and HANDLER is called.
328 Example:
330 \(dbus-call-method-asynchronously
331 :system \"org.freedesktop.Hal\" \"/org/freedesktop/Hal/devices/computer\"
332 \"org.freedesktop.Hal.Device\" \"GetPropertyString\" 'message
333 \"system.kernel.machine\")
335 => \(:serial :system 2)
337 -| i686"
339 (or (memq bus '(:system :session)) (stringp bus)
340 (signal 'wrong-type-argument (list 'keywordp bus)))
341 (or (stringp service)
342 (signal 'wrong-type-argument (list 'stringp service)))
343 (or (stringp path)
344 (signal 'wrong-type-argument (list 'stringp path)))
345 (or (stringp interface)
346 (signal 'wrong-type-argument (list 'stringp interface)))
347 (or (stringp method)
348 (signal 'wrong-type-argument (list 'stringp method)))
349 (or (null handler) (functionp handler)
350 (signal 'wrong-type-argument (list 'functionp handler)))
352 (apply 'dbus-message-internal dbus-message-type-method-call
353 bus service path interface method handler args))
355 (defun dbus-send-signal (bus service path interface signal &rest args)
356 "Send signal SIGNAL on the D-Bus BUS.
358 BUS is either a Lisp symbol, `:system' or `:session', or a string
359 denoting the bus address. The signal is sent from the D-Bus object
360 Emacs is registered at BUS.
362 SERVICE is the D-Bus name SIGNAL is sent to. It can be either a known
363 name or a unique name. If SERVICE is nil, the signal is sent as
364 broadcast message. PATH is the D-Bus object path SIGNAL is sent from.
365 INTERFACE is an interface available at PATH. It must provide signal
366 SIGNAL.
368 All other arguments ARGS are passed to SIGNAL as arguments. They are
369 converted into D-Bus types via the following rules:
371 t and nil => DBUS_TYPE_BOOLEAN
372 number => DBUS_TYPE_UINT32
373 integer => DBUS_TYPE_INT32
374 float => DBUS_TYPE_DOUBLE
375 string => DBUS_TYPE_STRING
376 list => DBUS_TYPE_ARRAY
378 All arguments can be preceded by a type symbol. For details about
379 type symbols, see Info node `(dbus)Type Conversion'.
381 Example:
383 \(dbus-send-signal
384 :session nil \"/org/gnu/Emacs\" \"org.gnu.Emacs.FileManager\"
385 \"FileModified\" \"/home/albinus/.emacs\")"
387 (or (memq bus '(:system :session)) (stringp bus)
388 (signal 'wrong-type-argument (list 'keywordp bus)))
389 (or (null service) (stringp service)
390 (signal 'wrong-type-argument (list 'stringp service)))
391 (or (stringp path)
392 (signal 'wrong-type-argument (list 'stringp path)))
393 (or (stringp interface)
394 (signal 'wrong-type-argument (list 'stringp interface)))
395 (or (stringp signal)
396 (signal 'wrong-type-argument (list 'stringp signal)))
398 (apply 'dbus-message-internal dbus-message-type-signal
399 bus service path interface signal args))
401 (defun dbus-method-return-internal (bus service serial &rest args)
402 "Return for message SERIAL on the D-Bus BUS.
403 This is an internal function, it shall not be used outside dbus.el."
405 (or (memq bus '(:system :session)) (stringp bus)
406 (signal 'wrong-type-argument (list 'keywordp bus)))
407 (or (stringp service)
408 (signal 'wrong-type-argument (list 'stringp service)))
409 (or (natnump serial)
410 (signal 'wrong-type-argument (list 'natnump serial)))
412 (apply 'dbus-message-internal dbus-message-type-method-return
413 bus service serial args))
415 (defun dbus-method-error-internal (bus service serial &rest args)
416 "Return error message for message SERIAL on the D-Bus BUS.
417 This is an internal function, it shall not be used outside dbus.el."
419 (or (memq bus '(:system :session)) (stringp bus)
420 (signal 'wrong-type-argument (list 'keywordp bus)))
421 (or (stringp service)
422 (signal 'wrong-type-argument (list 'stringp service)))
423 (or (natnump serial)
424 (signal 'wrong-type-argument (list 'natnump serial)))
426 (apply 'dbus-message-internal dbus-message-type-error
427 bus service serial args))
430 ;;; Hash table of registered functions.
432 (defun dbus-list-hash-table ()
433 "Returns all registered member registrations to D-Bus.
434 The return value is a list, with elements of kind (KEY . VALUE).
435 See `dbus-registered-objects-table' for a description of the
436 hash table."
437 (let (result)
438 (maphash
439 (lambda (key value) (add-to-list 'result (cons key value) 'append))
440 dbus-registered-objects-table)
441 result))
443 (defun dbus-setenv (bus variable value)
444 "Set the value of the BUS environment variable named VARIABLE to VALUE.
446 BUS is either a Lisp symbol, `:system' or `:session', or a string
447 denoting the bus address. Both VARIABLE and VALUE should be strings.
449 Normally, services inherit the environment of the BUS daemon. This
450 function adds to or modifies that environment when activating services.
452 Some bus instances, such as `:system', may disable setting the environment."
453 (dbus-call-method
454 bus dbus-service-dbus dbus-path-dbus
455 dbus-interface-dbus "UpdateActivationEnvironment"
456 `(:array (:dict-entry ,variable ,value))))
458 (defun dbus-register-service (bus service &rest flags)
459 "Register known name SERVICE on the D-Bus BUS.
461 BUS is either a Lisp symbol, `:system' or `:session', or a string
462 denoting the bus address.
464 SERVICE is the D-Bus service name that should be registered. It must
465 be a known name.
467 FLAGS are keywords, which control how the service name is registered.
468 The following keywords are recognized:
470 `:allow-replacement': Allow another service to become the primary
471 owner if requested.
473 `:replace-existing': Request to replace the current primary owner.
475 `:do-not-queue': If we can not become the primary owner do not place
476 us in the queue.
478 The function returns a keyword, indicating the result of the
479 operation. One of the following keywords is returned:
481 `:primary-owner': Service has become the primary owner of the
482 requested name.
484 `:in-queue': Service could not become the primary owner and has been
485 placed in the queue.
487 `:exists': Service is already in the queue.
489 `:already-owner': Service is already the primary owner."
491 ;; Add ObjectManager handler.
492 (dbus-register-method
493 bus service nil dbus-interface-objectmanager "GetManagedObjects"
494 'dbus-managed-objects-handler 'dont-register)
496 (let ((arg 0)
497 reply)
498 (dolist (flag flags)
499 (setq arg
500 (+ arg
501 (pcase flag
502 (:allow-replacement 1)
503 (:replace-existing 2)
504 (:do-not-queue 4)
505 (_ (signal 'wrong-type-argument (list flag)))))))
506 (setq reply (dbus-call-method
507 bus dbus-service-dbus dbus-path-dbus dbus-interface-dbus
508 "RequestName" service arg))
509 (pcase reply
510 (1 :primary-owner)
511 (2 :in-queue)
512 (3 :exists)
513 (4 :already-owner)
514 (_ (signal 'dbus-error (list "Could not register service" service))))))
516 (defun dbus-unregister-service (bus service)
517 "Unregister all objects related to SERVICE from D-Bus BUS.
518 BUS is either a Lisp symbol, `:system' or `:session', or a string
519 denoting the bus address. SERVICE must be a known service name.
521 The function returns a keyword, indicating the result of the
522 operation. One of the following keywords is returned:
524 `:released': We successfully released the service.
526 `:non-existent': Service name does not exist on this bus.
528 `:not-owner': We are neither the primary owner nor waiting in the
529 queue of this service."
531 (maphash
532 (lambda (key value)
533 (unless (equal :serial (car key))
534 (dolist (elt value)
535 (ignore-errors
536 (when (and (equal bus (cadr key)) (string-equal service (cadr elt)))
537 (unless
538 (puthash key (delete elt value) dbus-registered-objects-table)
539 (remhash key dbus-registered-objects-table)))))))
540 dbus-registered-objects-table)
541 (let ((reply (dbus-call-method
542 bus dbus-service-dbus dbus-path-dbus dbus-interface-dbus
543 "ReleaseName" service)))
544 (pcase reply
545 (1 :released)
546 (2 :non-existent)
547 (3 :not-owner)
548 (_ (signal 'dbus-error (list "Could not unregister service" service))))))
550 (defun dbus-register-signal
551 (bus service path interface signal handler &rest args)
552 "Register for a signal on the D-Bus BUS.
554 BUS is either a Lisp symbol, `:system' or `:session', or a string
555 denoting the bus address.
557 SERVICE is the D-Bus service name used by the sending D-Bus object.
558 It can be either a known name or the unique name of the D-Bus object
559 sending the signal.
561 PATH is the D-Bus object path SERVICE is registered. INTERFACE
562 is an interface offered by SERVICE. It must provide SIGNAL.
563 HANDLER is a Lisp function to be called when the signal is
564 received. It must accept as arguments the values SIGNAL is
565 sending.
567 SERVICE, PATH, INTERFACE and SIGNAL can be nil. This is
568 interpreted as a wildcard for the respective argument.
570 The remaining arguments ARGS can be keywords or keyword string pairs.
571 The meaning is as follows:
573 `:argN' STRING:
574 `:pathN' STRING: This stands for the Nth argument of the
575 signal. `:pathN' arguments can be used for object path wildcard
576 matches as specified by D-Bus, while an `:argN' argument
577 requires an exact match.
579 `:arg-namespace' STRING: Register for the signals, which first
580 argument defines the service or interface namespace STRING.
582 `:path-namespace' STRING: Register for the object path namespace
583 STRING. All signals sent from an object path, which has STRING as
584 the preceding string, are matched. This requires PATH to be nil.
586 `:eavesdrop': Register for unicast signals which are not directed
587 to the D-Bus object Emacs is registered at D-Bus BUS, if the
588 security policy of BUS allows this.
590 Example:
592 \(defun my-signal-handler (device)
593 (message \"Device %s added\" device))
595 \(dbus-register-signal
596 :system \"org.freedesktop.Hal\" \"/org/freedesktop/Hal/Manager\"
597 \"org.freedesktop.Hal.Manager\" \"DeviceAdded\" 'my-signal-handler)
599 => \(\(:signal :system \"org.freedesktop.Hal.Manager\" \"DeviceAdded\")
600 \(\"org.freedesktop.Hal\" \"/org/freedesktop/Hal/Manager\" my-signal-handler))
602 `dbus-register-signal' returns an object, which can be used in
603 `dbus-unregister-object' for removing the registration."
605 (let ((counter 0)
606 (rule "type='signal'")
607 uname key key1 value)
609 ;; Retrieve unique name of service. If service is a known name,
610 ;; we will register for the corresponding unique name, if any.
611 ;; Signals are sent always with the unique name as sender. Note:
612 ;; the unique name of `dbus-service-dbus' is that string itself.
613 (if (and (stringp service)
614 (not (zerop (length service)))
615 (not (string-equal service dbus-service-dbus))
616 (not (string-match "^:" service)))
617 (setq uname (dbus-get-name-owner bus service))
618 (setq uname service))
620 (setq rule (concat rule
621 (when uname (format ",sender='%s'" uname))
622 (when interface (format ",interface='%s'" interface))
623 (when signal (format ",member='%s'" signal))
624 (when path (format ",path='%s'" path))))
626 ;; Add arguments to the rule.
627 (if (or (stringp (car args)) (null (car args)))
628 ;; As backward compatibility option, we allow just strings.
629 (dolist (arg args)
630 (if (stringp arg)
631 (setq rule (concat rule (format ",arg%d='%s'" counter arg)))
632 (if arg (signal 'wrong-type-argument (list "Wrong argument" arg))))
633 (setq counter (1+ counter)))
635 ;; Parse keywords.
636 (while args
637 (setq
638 key (car args)
639 rule (concat
640 rule
641 (cond
642 ;; `:arg0' .. `:arg63', `:path0' .. `:path63'.
643 ((and (keywordp key)
644 (string-match
645 "^:\\(arg\\|path\\)\\([[:digit:]]+\\)$"
646 (symbol-name key)))
647 (setq counter (match-string 2 (symbol-name key))
648 args (cdr args)
649 value (car args))
650 (unless (and (<= counter 63) (stringp value))
651 (signal 'wrong-type-argument
652 (list "Wrong argument" key value)))
653 (format
654 ",arg%s%s='%s'"
655 counter
656 (if (string-equal (match-string 1 (symbol-name key)) "path")
657 "path" "")
658 value))
659 ;; `:arg-namespace', `:path-namespace'.
660 ((and (keywordp key)
661 (string-match
662 "^:\\(arg\\|path\\)-namespace$" (symbol-name key)))
663 (setq args (cdr args)
664 value (car args))
665 (unless (stringp value)
666 (signal 'wrong-type-argument
667 (list "Wrong argument" key value)))
668 (format
669 ",%s='%s'"
670 (if (string-equal (match-string 1 (symbol-name key)) "path")
671 "path_namespace" "arg0namespace")
672 value))
673 ;; `:eavesdrop'.
674 ((eq key :eavesdrop)
675 ",eavesdrop='true'")
676 (t (signal 'wrong-type-argument (list "Wrong argument" key)))))
677 args (cdr args))))
679 ;; Add the rule to the bus.
680 (condition-case err
681 (dbus-call-method
682 bus dbus-service-dbus dbus-path-dbus dbus-interface-dbus
683 "AddMatch" rule)
684 (dbus-error
685 (if (not (string-match "eavesdrop" rule))
686 (signal (car err) (cdr err))
687 ;; The D-Bus spec says we shall fall back to a rule without eavesdrop.
688 (when dbus-debug (message "Removing eavesdrop from rule %s" rule))
689 (setq rule (replace-regexp-in-string ",eavesdrop='true'" "" rule))
690 (dbus-call-method
691 bus dbus-service-dbus dbus-path-dbus dbus-interface-dbus
692 "AddMatch" rule))))
694 (when dbus-debug (message "Matching rule \"%s\" created" rule))
696 ;; Create a hash table entry.
697 (setq key (list :signal bus interface signal)
698 key1 (list uname service path handler rule)
699 value (gethash key dbus-registered-objects-table))
700 (unless (member key1 value)
701 (puthash key (cons key1 value) dbus-registered-objects-table))
703 ;; Return the object.
704 (list key (list service path handler))))
706 (defun dbus-register-method
707 (bus service path interface method handler &optional dont-register-service)
708 "Register for method METHOD on the D-Bus BUS.
710 BUS is either a Lisp symbol, `:system' or `:session', or a string
711 denoting the bus address.
713 SERVICE is the D-Bus service name of the D-Bus object METHOD is
714 registered for. It must be a known name (See discussion of
715 DONT-REGISTER-SERVICE below).
717 PATH is the D-Bus object path SERVICE is registered (See discussion of
718 DONT-REGISTER-SERVICE below). INTERFACE is the interface offered by
719 SERVICE. It must provide METHOD.
721 HANDLER is a Lisp function to be called when a method call is
722 received. It must accept the input arguments of METHOD. The return
723 value of HANDLER is used for composing the returning D-Bus message.
724 In case HANDLER shall return a reply message with an empty argument
725 list, HANDLER must return the symbol `:ignore'.
727 When DONT-REGISTER-SERVICE is non-nil, the known name SERVICE is not
728 registered. This means that other D-Bus clients have no way of
729 noticing the newly registered method. When interfaces are constructed
730 incrementally by adding single methods or properties at a time,
731 DONT-REGISTER-SERVICE can be used to prevent other clients from
732 discovering the still incomplete interface."
734 ;; Register SERVICE.
735 (unless (or dont-register-service
736 (member service (dbus-list-names bus)))
737 (dbus-register-service bus service))
739 ;; Create a hash table entry. We use nil for the unique name,
740 ;; because the method might be called from anybody.
741 (let* ((key (list :method bus interface method))
742 (key1 (list nil service path handler))
743 (value (gethash key dbus-registered-objects-table)))
745 (unless (member key1 value)
746 (puthash key (cons key1 value) dbus-registered-objects-table))
748 ;; Return the object.
749 (list key (list service path handler))))
751 (defun dbus-unregister-object (object)
752 "Unregister OBJECT from D-Bus.
753 OBJECT must be the result of a preceding `dbus-register-method',
754 `dbus-register-property' or `dbus-register-signal' call. It
755 returns `t' if OBJECT has been unregistered, `nil' otherwise.
757 When OBJECT identifies the last method or property, which is
758 registered for the respective service, Emacs releases its
759 association to the service from D-Bus."
760 ;; Check parameter.
761 (unless (and (consp object) (not (null (car object))) (consp (cdr object)))
762 (signal 'wrong-type-argument (list 'D-Bus object)))
764 ;; Find the corresponding entry in the hash table.
765 (let* ((key (car object))
766 (type (car key))
767 (bus (cadr key))
768 (value (cadr object))
769 (service (car value))
770 (entry (gethash key dbus-registered-objects-table))
771 ret)
772 ;; key has the structure (TYPE BUS INTERFACE MEMBER).
773 ;; value has the structure (SERVICE PATH [HANDLER]).
774 ;; entry has the structure ((UNAME SERVICE PATH MEMBER [RULE]) ...).
775 ;; MEMBER is either a string (the handler), or a cons cell (a
776 ;; property value). UNAME and property values are not taken into
777 ;; account for comparison.
779 ;; Loop over the registered functions.
780 (dolist (elt entry)
781 (when (equal
782 value
783 (butlast (cdr elt) (- (length (cdr elt)) (length value))))
784 (setq ret t)
785 ;; Compute new hash value. If it is empty, remove it from the
786 ;; hash table.
787 (unless (puthash key (delete elt entry) dbus-registered-objects-table)
788 (remhash key dbus-registered-objects-table))
789 ;; Remove match rule of signals.
790 (when (eq type :signal)
791 (dbus-call-method
792 bus dbus-service-dbus dbus-path-dbus dbus-interface-dbus
793 "RemoveMatch" (nth 4 elt)))))
795 ;; Check, whether there is still a registered function or property
796 ;; for the given service. If not, unregister the service from the
797 ;; bus.
798 (when (and service (memq type '(:method :property))
799 (not (catch :found
800 (progn
801 (maphash
802 (lambda (k v)
803 (dolist (e v)
804 (ignore-errors
805 (and
806 ;; Bus.
807 (equal bus (cadr k))
808 ;; Service.
809 (string-equal service (cadr e))
810 ;; Non-empty object path.
811 (cl-caddr e)
812 (throw :found t)))))
813 dbus-registered-objects-table)
814 nil))))
815 (dbus-unregister-service bus service))
816 ;; Return.
817 ret))
820 ;;; D-Bus type conversion.
822 (defun dbus-string-to-byte-array (string)
823 "Transforms STRING to list (:array :byte c1 :byte c2 ...).
824 STRING shall be UTF8 coded."
825 (if (zerop (length string))
826 '(:array :signature "y")
827 (let (result)
828 (dolist (elt (string-to-list string) (append '(:array) result))
829 (setq result (append result (list :byte elt)))))))
831 (defun dbus-byte-array-to-string (byte-array &optional multibyte)
832 "Transforms BYTE-ARRAY into UTF8 coded string.
833 BYTE-ARRAY must be a list of structure (c1 c2 ...), or a byte
834 array as produced by `dbus-string-to-byte-array'. The resulting
835 string is unibyte encoded, unless MULTIBYTE is non-nil."
836 (apply
837 (if multibyte 'string 'unibyte-string)
838 (if (equal byte-array '(:array :signature "y"))
840 (let (result)
841 (dolist (elt byte-array result)
842 (when (characterp elt) (setq result (append result `(,elt)))))))))
844 (defun dbus-escape-as-identifier (string)
845 "Escape an arbitrary STRING so it follows the rules for a C identifier.
846 The escaped string can be used as object path component, interface element
847 component, bus name component or member name in D-Bus.
849 The escaping consists of replacing all non-alphanumerics, and the
850 first character if it's a digit, with an underscore and two
851 lower-case hex digits:
853 \"0123abc_xyz\\x01\\xff\" -> \"_30123abc_5fxyz_01_ff\"
855 i.e. similar to URI encoding, but with \"_\" taking the role of \"%\",
856 and a smaller allowed set. As a special case, \"\" is escaped to
857 \"_\".
859 Returns the escaped string. Algorithm taken from
860 telepathy-glib's `tp_escape_as_identifier'."
861 (if (zerop (length string))
863 (replace-regexp-in-string
864 "^[0-9]\\|[^A-Za-z0-9]"
865 (lambda (x) (format "_%2x" (aref x 0)))
866 string)))
868 (defun dbus-unescape-from-identifier (string)
869 "Retrieve the original string from the encoded STRING as unibyte string.
870 STRING must have been encoded with `dbus-escape-as-identifier'."
871 (if (string-equal string "_")
873 (replace-regexp-in-string
874 "_.."
875 (lambda (x) (byte-to-string (string-to-number (substring x 1) 16)))
876 string)))
879 ;;; D-Bus events.
881 (defun dbus-check-event (event)
882 "Checks whether EVENT is a well formed D-Bus event.
883 EVENT is a list which starts with symbol `dbus-event':
885 (dbus-event BUS TYPE SERIAL SERVICE PATH INTERFACE MEMBER HANDLER &rest ARGS)
887 BUS identifies the D-Bus the message is coming from. It is
888 either a Lisp symbol, `:system' or `:session', or a string
889 denoting the bus address. TYPE is the D-Bus message type which
890 has caused the event, SERIAL is the serial number of the received
891 D-Bus message. SERVICE and PATH are the unique name and the
892 object path of the D-Bus object emitting the message. INTERFACE
893 and MEMBER denote the message which has been sent. HANDLER is
894 the function which has been registered for this message. ARGS
895 are the arguments passed to HANDLER, when it is called during
896 event handling in `dbus-handle-event'.
898 This function raises a `dbus-error' signal in case the event is
899 not well formed."
900 (when dbus-debug (message "DBus-Event %s" event))
901 (unless (and (listp event)
902 (eq (car event) 'dbus-event)
903 ;; Bus symbol.
904 (or (symbolp (nth 1 event))
905 (stringp (nth 1 event)))
906 ;; Type.
907 (and (natnump (nth 2 event))
908 (< dbus-message-type-invalid (nth 2 event)))
909 ;; Serial.
910 (natnump (nth 3 event))
911 ;; Service.
912 (or (= dbus-message-type-method-return (nth 2 event))
913 (= dbus-message-type-error (nth 2 event))
914 (stringp (nth 4 event)))
915 ;; Object path.
916 (or (= dbus-message-type-method-return (nth 2 event))
917 (= dbus-message-type-error (nth 2 event))
918 (stringp (nth 5 event)))
919 ;; Interface.
920 (or (= dbus-message-type-method-return (nth 2 event))
921 (= dbus-message-type-error (nth 2 event))
922 (stringp (nth 6 event)))
923 ;; Member.
924 (or (= dbus-message-type-method-return (nth 2 event))
925 (= dbus-message-type-error (nth 2 event))
926 (stringp (nth 7 event)))
927 ;; Handler.
928 (functionp (nth 8 event)))
929 (signal 'dbus-error (list "Not a valid D-Bus event" event))))
931 ;;;###autoload
932 (defun dbus-handle-event (event)
933 "Handle events from the D-Bus.
934 EVENT is a D-Bus event, see `dbus-check-event'. HANDLER, being
935 part of the event, is called with arguments ARGS.
936 If the HANDLER returns a `dbus-error', it is propagated as return message."
937 (interactive "e")
938 (condition-case err
939 (let (result)
940 ;; We ignore not well-formed events.
941 (dbus-check-event event)
942 ;; Error messages must be propagated.
943 (when (= dbus-message-type-error (nth 2 event))
944 (signal 'dbus-error (nthcdr 9 event)))
945 ;; Apply the handler.
946 (setq result (apply (nth 8 event) (nthcdr 9 event)))
947 ;; Return a message when it is a message call.
948 (when (= dbus-message-type-method-call (nth 2 event))
949 (dbus-ignore-errors
950 (if (eq result :ignore)
951 (dbus-method-return-internal
952 (nth 1 event) (nth 4 event) (nth 3 event))
953 (apply 'dbus-method-return-internal
954 (nth 1 event) (nth 4 event) (nth 3 event)
955 (if (consp result) result (list result)))))))
956 ;; Error handling.
957 (dbus-error
958 ;; Return an error message when it is a message call.
959 (when (= dbus-message-type-method-call (nth 2 event))
960 (dbus-ignore-errors
961 (dbus-method-error-internal
962 (nth 1 event) (nth 4 event) (nth 3 event) (cadr err))))
963 ;; Propagate D-Bus error messages.
964 (run-hook-with-args 'dbus-event-error-functions event err)
965 (when (or dbus-debug (= dbus-message-type-error (nth 2 event)))
966 (signal (car err) (cdr err))))))
968 (defun dbus-event-bus-name (event)
969 "Return the bus name the event is coming from.
970 The result is either a Lisp symbol, `:system' or `:session', or a
971 string denoting the bus address. EVENT is a D-Bus event, see
972 `dbus-check-event'. This function raises a `dbus-error' signal
973 in case the event is not well formed."
974 (dbus-check-event event)
975 (nth 1 event))
977 (defun dbus-event-message-type (event)
978 "Return the message type of the corresponding D-Bus message.
979 The result is a number. EVENT is a D-Bus event, see
980 `dbus-check-event'. This function raises a `dbus-error' signal
981 in case the event is not well formed."
982 (dbus-check-event event)
983 (nth 2 event))
985 (defun dbus-event-serial-number (event)
986 "Return the serial number of the corresponding D-Bus message.
987 The result is a number. The serial number is needed for
988 generating a reply message. EVENT is a D-Bus event, see
989 `dbus-check-event'. This function raises a `dbus-error' signal
990 in case the event is not well formed."
991 (dbus-check-event event)
992 (nth 3 event))
994 (defun dbus-event-service-name (event)
995 "Return the name of the D-Bus object the event is coming from.
996 The result is a string. EVENT is a D-Bus event, see `dbus-check-event'.
997 This function raises a `dbus-error' signal in case the event is
998 not well formed."
999 (dbus-check-event event)
1000 (nth 4 event))
1002 (defun dbus-event-path-name (event)
1003 "Return the object path of the D-Bus object the event is coming from.
1004 The result is a string. EVENT is a D-Bus event, see `dbus-check-event'.
1005 This function raises a `dbus-error' signal in case the event is
1006 not well formed."
1007 (dbus-check-event event)
1008 (nth 5 event))
1010 (defun dbus-event-interface-name (event)
1011 "Return the interface name of the D-Bus object the event is coming from.
1012 The result is a string. EVENT is a D-Bus event, see `dbus-check-event'.
1013 This function raises a `dbus-error' signal in case the event is
1014 not well formed."
1015 (dbus-check-event event)
1016 (nth 6 event))
1018 (defun dbus-event-member-name (event)
1019 "Return the member name the event is coming from.
1020 It is either a signal name or a method name. The result is a
1021 string. EVENT is a D-Bus event, see `dbus-check-event'. This
1022 function raises a `dbus-error' signal in case the event is not
1023 well formed."
1024 (dbus-check-event event)
1025 (nth 7 event))
1028 ;;; D-Bus registered names.
1030 (defun dbus-list-activatable-names (&optional bus)
1031 "Return the D-Bus service names which can be activated as list.
1032 If BUS is left nil, `:system' is assumed. The result is a list
1033 of strings, which is `nil' when there are no activatable service
1034 names at all."
1035 (dbus-ignore-errors
1036 (dbus-call-method
1037 (or bus :system) dbus-service-dbus
1038 dbus-path-dbus dbus-interface-dbus "ListActivatableNames")))
1040 (defun dbus-list-names (bus)
1041 "Return the service names registered at D-Bus BUS.
1042 The result is a list of strings, which is `nil' when there are no
1043 registered service names at all. Well known names are strings
1044 like \"org.freedesktop.DBus\". Names starting with \":\" are
1045 unique names for services."
1046 (dbus-ignore-errors
1047 (dbus-call-method
1048 bus dbus-service-dbus dbus-path-dbus dbus-interface-dbus "ListNames")))
1050 (defun dbus-list-known-names (bus)
1051 "Retrieve all services which correspond to a known name in BUS.
1052 A service has a known name if it doesn't start with \":\"."
1053 (let (result)
1054 (dolist (name (dbus-list-names bus) result)
1055 (unless (string-equal ":" (substring name 0 1))
1056 (add-to-list 'result name 'append)))))
1058 (defun dbus-list-queued-owners (bus service)
1059 "Return the unique names registered at D-Bus BUS and queued for SERVICE.
1060 The result is a list of strings, or `nil' when there are no
1061 queued name owners service names at all."
1062 (dbus-ignore-errors
1063 (dbus-call-method
1064 bus dbus-service-dbus dbus-path-dbus
1065 dbus-interface-dbus "ListQueuedOwners" service)))
1067 (defun dbus-get-name-owner (bus service)
1068 "Return the name owner of SERVICE registered at D-Bus BUS.
1069 The result is either a string, or `nil' if there is no name owner."
1070 (dbus-ignore-errors
1071 (dbus-call-method
1072 bus dbus-service-dbus dbus-path-dbus
1073 dbus-interface-dbus "GetNameOwner" service)))
1075 (defun dbus-ping (bus service &optional timeout)
1076 "Check whether SERVICE is registered for D-Bus BUS.
1077 TIMEOUT, a nonnegative integer, specifies the maximum number of
1078 milliseconds `dbus-ping' must return. The default value is 25,000.
1080 Note, that this autoloads SERVICE if it is not running yet. If
1081 it shall be checked whether SERVICE is already running, one shall
1082 apply
1084 \(member service \(dbus-list-known-names bus))"
1085 ;; "Ping" raises a D-Bus error if SERVICE does not exist.
1086 ;; Otherwise, it returns silently with `nil'.
1087 (condition-case nil
1088 (not
1089 (if (natnump timeout)
1090 (dbus-call-method
1091 bus service dbus-path-dbus dbus-interface-peer
1092 "Ping" :timeout timeout)
1093 (dbus-call-method
1094 bus service dbus-path-dbus dbus-interface-peer "Ping")))
1095 (dbus-error nil)))
1098 ;;; D-Bus introspection.
1100 (defun dbus-introspect (bus service path)
1101 "Return all interfaces and sub-nodes of SERVICE,
1102 registered at object path PATH at bus BUS.
1104 BUS is either a Lisp symbol, `:system' or `:session', or a string
1105 denoting the bus address. SERVICE must be a known service name,
1106 and PATH must be a valid object path. The last two parameters
1107 are strings. The result, the introspection data, is a string in
1108 XML format."
1109 ;; We don't want to raise errors.
1110 (dbus-ignore-errors
1111 (dbus-call-method
1112 bus service path dbus-interface-introspectable "Introspect"
1113 :timeout 1000)))
1115 (defun dbus-introspect-xml (bus service path)
1116 "Return the introspection data of SERVICE in D-Bus BUS at object path PATH.
1117 The data are a parsed list. The root object is a \"node\",
1118 representing the object path PATH. The root object can contain
1119 \"interface\" and further \"node\" objects."
1120 ;; We don't want to raise errors.
1121 (xml-node-name
1122 (ignore-errors
1123 (with-temp-buffer
1124 (insert (dbus-introspect bus service path))
1125 (xml-parse-region (point-min) (point-max))))))
1127 (defun dbus-introspect-get-attribute (object attribute)
1128 "Return the ATTRIBUTE value of D-Bus introspection OBJECT.
1129 ATTRIBUTE must be a string according to the attribute names in
1130 the D-Bus specification."
1131 (xml-get-attribute-or-nil object (intern attribute)))
1133 (defun dbus-introspect-get-node-names (bus service path)
1134 "Return all node names of SERVICE in D-Bus BUS at object path PATH.
1135 It returns a list of strings. The node names stand for further
1136 object paths of the D-Bus service."
1137 (let ((object (dbus-introspect-xml bus service path))
1138 result)
1139 (dolist (elt (xml-get-children object 'node) result)
1140 (add-to-list
1141 'result (dbus-introspect-get-attribute elt "name") 'append))))
1143 (defun dbus-introspect-get-all-nodes (bus service path)
1144 "Return all node names of SERVICE in D-Bus BUS at object path PATH.
1145 It returns a list of strings, which are further object paths of SERVICE."
1146 (let ((result (list path)))
1147 (dolist (elt
1148 (dbus-introspect-get-node-names bus service path)
1149 result)
1150 (setq elt (expand-file-name elt path))
1151 (setq result
1152 (append result (dbus-introspect-get-all-nodes bus service elt))))))
1154 (defun dbus-introspect-get-interface-names (bus service path)
1155 "Return all interface names of SERVICE in D-Bus BUS at object path PATH.
1156 It returns a list of strings.
1158 There will be always the default interface
1159 \"org.freedesktop.DBus.Introspectable\". Another default
1160 interface is \"org.freedesktop.DBus.Properties\". If present,
1161 \"interface\" objects can also have \"property\" objects as
1162 children, beside \"method\" and \"signal\" objects."
1163 (let ((object (dbus-introspect-xml bus service path))
1164 result)
1165 (dolist (elt (xml-get-children object 'interface) result)
1166 (add-to-list
1167 'result (dbus-introspect-get-attribute elt "name") 'append))))
1169 (defun dbus-introspect-get-interface (bus service path interface)
1170 "Return the INTERFACE of SERVICE in D-Bus BUS at object path PATH.
1171 The return value is an XML object. INTERFACE must be a string,
1172 element of the list returned by `dbus-introspect-get-interface-names'.
1173 The resulting \"interface\" object can contain \"method\", \"signal\",
1174 \"property\" and \"annotation\" children."
1175 (let ((elt (xml-get-children
1176 (dbus-introspect-xml bus service path) 'interface)))
1177 (while (and elt
1178 (not (string-equal
1179 interface
1180 (dbus-introspect-get-attribute (car elt) "name"))))
1181 (setq elt (cdr elt)))
1182 (car elt)))
1184 (defun dbus-introspect-get-method-names (bus service path interface)
1185 "Return a list of strings of all method names of INTERFACE.
1186 SERVICE is a service of D-Bus BUS at object path PATH."
1187 (let ((object (dbus-introspect-get-interface bus service path interface))
1188 result)
1189 (dolist (elt (xml-get-children object 'method) result)
1190 (add-to-list
1191 'result (dbus-introspect-get-attribute elt "name") 'append))))
1193 (defun dbus-introspect-get-method (bus service path interface method)
1194 "Return method METHOD of interface INTERFACE as XML object.
1195 It must be located at SERVICE in D-Bus BUS at object path PATH.
1196 METHOD must be a string, element of the list returned by
1197 `dbus-introspect-get-method-names'. The resulting \"method\"
1198 object can contain \"arg\" and \"annotation\" children."
1199 (let ((elt (xml-get-children
1200 (dbus-introspect-get-interface bus service path interface)
1201 'method)))
1202 (while (and elt
1203 (not (string-equal
1204 method (dbus-introspect-get-attribute (car elt) "name"))))
1205 (setq elt (cdr elt)))
1206 (car elt)))
1208 (defun dbus-introspect-get-signal-names (bus service path interface)
1209 "Return a list of strings of all signal names of INTERFACE.
1210 SERVICE is a service of D-Bus BUS at object path PATH."
1211 (let ((object (dbus-introspect-get-interface bus service path interface))
1212 result)
1213 (dolist (elt (xml-get-children object 'signal) result)
1214 (add-to-list
1215 'result (dbus-introspect-get-attribute elt "name") 'append))))
1217 (defun dbus-introspect-get-signal (bus service path interface signal)
1218 "Return signal SIGNAL of interface INTERFACE as XML object.
1219 It must be located at SERVICE in D-Bus BUS at object path PATH.
1220 SIGNAL must be a string, element of the list returned by
1221 `dbus-introspect-get-signal-names'. The resulting \"signal\"
1222 object can contain \"arg\" and \"annotation\" children."
1223 (let ((elt (xml-get-children
1224 (dbus-introspect-get-interface bus service path interface)
1225 'signal)))
1226 (while (and elt
1227 (not (string-equal
1228 signal (dbus-introspect-get-attribute (car elt) "name"))))
1229 (setq elt (cdr elt)))
1230 (car elt)))
1232 (defun dbus-introspect-get-property-names (bus service path interface)
1233 "Return a list of strings of all property names of INTERFACE.
1234 SERVICE is a service of D-Bus BUS at object path PATH."
1235 (let ((object (dbus-introspect-get-interface bus service path interface))
1236 result)
1237 (dolist (elt (xml-get-children object 'property) result)
1238 (add-to-list
1239 'result (dbus-introspect-get-attribute elt "name") 'append))))
1241 (defun dbus-introspect-get-property (bus service path interface property)
1242 "This function returns PROPERTY of INTERFACE as XML object.
1243 It must be located at SERVICE in D-Bus BUS at object path PATH.
1244 PROPERTY must be a string, element of the list returned by
1245 `dbus-introspect-get-property-names'. The resulting PROPERTY
1246 object can contain \"annotation\" children."
1247 (let ((elt (xml-get-children
1248 (dbus-introspect-get-interface bus service path interface)
1249 'property)))
1250 (while (and elt
1251 (not (string-equal
1252 property
1253 (dbus-introspect-get-attribute (car elt) "name"))))
1254 (setq elt (cdr elt)))
1255 (car elt)))
1257 (defun dbus-introspect-get-annotation-names
1258 (bus service path interface &optional name)
1259 "Return all annotation names as list of strings.
1260 If NAME is `nil', the annotations are children of INTERFACE,
1261 otherwise NAME must be a \"method\", \"signal\", or \"property\"
1262 object, where the annotations belong to."
1263 (let ((object
1264 (if name
1265 (or (dbus-introspect-get-method bus service path interface name)
1266 (dbus-introspect-get-signal bus service path interface name)
1267 (dbus-introspect-get-property bus service path interface name))
1268 (dbus-introspect-get-interface bus service path interface)))
1269 result)
1270 (dolist (elt (xml-get-children object 'annotation) result)
1271 (add-to-list
1272 'result (dbus-introspect-get-attribute elt "name") 'append))))
1274 (defun dbus-introspect-get-annotation
1275 (bus service path interface name annotation)
1276 "Return ANNOTATION as XML object.
1277 If NAME is `nil', ANNOTATION is a child of INTERFACE, otherwise
1278 NAME must be the name of a \"method\", \"signal\", or
1279 \"property\" object, where the ANNOTATION belongs to."
1280 (let ((elt (xml-get-children
1281 (if name
1282 (or (dbus-introspect-get-method
1283 bus service path interface name)
1284 (dbus-introspect-get-signal
1285 bus service path interface name)
1286 (dbus-introspect-get-property
1287 bus service path interface name))
1288 (dbus-introspect-get-interface bus service path interface))
1289 'annotation)))
1290 (while (and elt
1291 (not (string-equal
1292 annotation
1293 (dbus-introspect-get-attribute (car elt) "name"))))
1294 (setq elt (cdr elt)))
1295 (car elt)))
1297 (defun dbus-introspect-get-argument-names (bus service path interface name)
1298 "Return a list of all argument names as list of strings.
1299 NAME must be a \"method\" or \"signal\" object.
1301 Argument names are optional, the function can return `nil'
1302 therefore, even if the method or signal has arguments."
1303 (let ((object
1304 (or (dbus-introspect-get-method bus service path interface name)
1305 (dbus-introspect-get-signal bus service path interface name)))
1306 result)
1307 (dolist (elt (xml-get-children object 'arg) result)
1308 (add-to-list
1309 'result (dbus-introspect-get-attribute elt "name") 'append))))
1311 (defun dbus-introspect-get-argument (bus service path interface name arg)
1312 "Return argument ARG as XML object.
1313 NAME must be a \"method\" or \"signal\" object. ARG must be a string,
1314 element of the list returned by `dbus-introspect-get-argument-names'."
1315 (let ((elt (xml-get-children
1316 (or (dbus-introspect-get-method bus service path interface name)
1317 (dbus-introspect-get-signal bus service path interface name))
1318 'arg)))
1319 (while (and elt
1320 (not (string-equal
1321 arg (dbus-introspect-get-attribute (car elt) "name"))))
1322 (setq elt (cdr elt)))
1323 (car elt)))
1325 (defun dbus-introspect-get-signature
1326 (bus service path interface name &optional direction)
1327 "Return signature of a `method' or `signal', represented by NAME, as string.
1328 If NAME is a `method', DIRECTION can be either \"in\" or \"out\".
1329 If DIRECTION is `nil', \"in\" is assumed.
1331 If NAME is a `signal', and DIRECTION is non-`nil', DIRECTION must
1332 be \"out\"."
1333 ;; For methods, we use "in" as default direction.
1334 (let ((object (or (dbus-introspect-get-method
1335 bus service path interface name)
1336 (dbus-introspect-get-signal
1337 bus service path interface name))))
1338 (when (and (string-equal
1339 "method" (dbus-introspect-get-attribute object "name"))
1340 (not (stringp direction)))
1341 (setq direction "in"))
1342 ;; In signals, no direction is given.
1343 (when (string-equal "signal" (dbus-introspect-get-attribute object "name"))
1344 (setq direction nil))
1345 ;; Collect the signatures.
1346 (mapconcat
1347 (lambda (x)
1348 (let ((arg (dbus-introspect-get-argument
1349 bus service path interface name x)))
1350 (if (or (not (stringp direction))
1351 (string-equal
1352 direction
1353 (dbus-introspect-get-attribute arg "direction")))
1354 (dbus-introspect-get-attribute arg "type")
1355 "")))
1356 (dbus-introspect-get-argument-names bus service path interface name)
1357 "")))
1360 ;;; D-Bus properties.
1362 (defun dbus-get-property (bus service path interface property)
1363 "Return the value of PROPERTY of INTERFACE.
1364 It will be checked at BUS, SERVICE, PATH. The result can be any
1365 valid D-Bus value, or `nil' if there is no PROPERTY."
1366 (dbus-ignore-errors
1367 ;; "Get" returns a variant, so we must use the `car'.
1368 (car
1369 (dbus-call-method
1370 bus service path dbus-interface-properties
1371 "Get" :timeout 500 interface property))))
1373 (defun dbus-set-property (bus service path interface property value)
1374 "Set value of PROPERTY of INTERFACE to VALUE.
1375 It will be checked at BUS, SERVICE, PATH. When the value has
1376 been set successful, the result is VALUE. Otherwise, `nil' is
1377 returned."
1378 (dbus-ignore-errors
1379 ;; "Set" requires a variant.
1380 (dbus-call-method
1381 bus service path dbus-interface-properties
1382 "Set" :timeout 500 interface property (list :variant value))
1383 ;; Return VALUE.
1384 (dbus-get-property bus service path interface property)))
1386 (defun dbus-get-all-properties (bus service path interface)
1387 "Return all properties of INTERFACE at BUS, SERVICE, PATH.
1388 The result is a list of entries. Every entry is a cons of the
1389 name of the property, and its value. If there are no properties,
1390 `nil' is returned."
1391 (dbus-ignore-errors
1392 ;; "GetAll" returns "a{sv}".
1393 (let (result)
1394 (dolist (dict
1395 (dbus-call-method
1396 bus service path dbus-interface-properties
1397 "GetAll" :timeout 500 interface)
1398 result)
1399 (add-to-list 'result (cons (car dict) (cl-caadr dict)) 'append)))))
1401 (defun dbus-register-property
1402 (bus service path interface property access value
1403 &optional emits-signal dont-register-service)
1404 "Register property PROPERTY on the D-Bus BUS.
1406 BUS is either a Lisp symbol, `:system' or `:session', or a string
1407 denoting the bus address.
1409 SERVICE is the D-Bus service name of the D-Bus. It must be a
1410 known name (See discussion of DONT-REGISTER-SERVICE below).
1412 PATH is the D-Bus object path SERVICE is registered (See
1413 discussion of DONT-REGISTER-SERVICE below). INTERFACE is the
1414 name of the interface used at PATH, PROPERTY is the name of the
1415 property of INTERFACE. ACCESS indicates, whether the property
1416 can be changed by other services via D-Bus. It must be either
1417 the symbol `:read' or `:readwrite'. VALUE is the initial value
1418 of the property, it can be of any valid type (see
1419 `dbus-call-method' for details).
1421 If PROPERTY already exists on PATH, it will be overwritten. For
1422 properties with access type `:read' this is the only way to
1423 change their values. Properties with access type `:readwrite'
1424 can be changed by `dbus-set-property'.
1426 The interface \"org.freedesktop.DBus.Properties\" is added to
1427 PATH, including a default handler for the \"Get\", \"GetAll\" and
1428 \"Set\" methods of this interface. When EMITS-SIGNAL is non-nil,
1429 the signal \"PropertiesChanged\" is sent when the property is
1430 changed by `dbus-set-property'.
1432 When DONT-REGISTER-SERVICE is non-nil, the known name SERVICE is
1433 not registered. This means that other D-Bus clients have no way
1434 of noticing the newly registered property. When interfaces are
1435 constructed incrementally by adding single methods or properties
1436 at a time, DONT-REGISTER-SERVICE can be used to prevent other
1437 clients from discovering the still incomplete interface."
1438 (unless (member access '(:read :readwrite))
1439 (signal 'wrong-type-argument (list "Access type invalid" access)))
1441 ;; Add handlers for the three property-related methods.
1442 (dbus-register-method
1443 bus service path dbus-interface-properties "Get"
1444 'dbus-property-handler 'dont-register)
1445 (dbus-register-method
1446 bus service path dbus-interface-properties "GetAll"
1447 'dbus-property-handler 'dont-register)
1448 (dbus-register-method
1449 bus service path dbus-interface-properties "Set"
1450 'dbus-property-handler 'dont-register)
1452 ;; Register SERVICE.
1453 (unless (or dont-register-service (member service (dbus-list-names bus)))
1454 (dbus-register-service bus service))
1456 ;; Send the PropertiesChanged signal.
1457 (when emits-signal
1458 (dbus-send-signal
1459 bus service path dbus-interface-properties "PropertiesChanged"
1460 `((:dict-entry ,property (:variant ,value)))
1461 '(:array)))
1463 ;; Create a hash table entry. We use nil for the unique name,
1464 ;; because the property might be accessed from anybody.
1465 (let ((key (list :property bus interface property))
1466 (val
1467 (list
1468 (list
1469 nil service path
1470 (cons
1471 (if emits-signal (list access :emits-signal) (list access))
1472 value)))))
1473 (puthash key val dbus-registered-objects-table)
1475 ;; Return the object.
1476 (list key (list service path))))
1478 (defun dbus-property-handler (&rest args)
1479 "Default handler for the \"org.freedesktop.DBus.Properties\" interface.
1480 It will be registered for all objects created by `dbus-register-property'."
1481 (let ((bus (dbus-event-bus-name last-input-event))
1482 (service (dbus-event-service-name last-input-event))
1483 (path (dbus-event-path-name last-input-event))
1484 (method (dbus-event-member-name last-input-event))
1485 (interface (car args))
1486 (property (cadr args)))
1487 (cond
1488 ;; "Get" returns a variant.
1489 ((string-equal method "Get")
1490 (let ((entry (gethash (list :property bus interface property)
1491 dbus-registered-objects-table)))
1492 (when (string-equal path (nth 2 (car entry)))
1493 `((:variant ,(cdar (last (car entry))))))))
1495 ;; "Set" expects a variant.
1496 ((string-equal method "Set")
1497 (let* ((value (caar (cddr args)))
1498 (entry (gethash (list :property bus interface property)
1499 dbus-registered-objects-table))
1500 ;; The value of the hash table is a list; in case of
1501 ;; properties it contains just one element (UNAME SERVICE
1502 ;; PATH OBJECT). OBJECT is a cons cell of a list, which
1503 ;; contains a list of annotations (like :read,
1504 ;; :read-write, :emits-signal), and the value of the
1505 ;; property.
1506 (object (car (last (car entry)))))
1507 (unless (consp object)
1508 (signal 'dbus-error
1509 (list "Property not registered at path" property path)))
1510 (unless (member :readwrite (car object))
1511 (signal 'dbus-error
1512 (list "Property not writable at path" property path)))
1513 (puthash (list :property bus interface property)
1514 (list (append (butlast (car entry))
1515 (list (cons (car object) value))))
1516 dbus-registered-objects-table)
1517 ;; Send the "PropertiesChanged" signal.
1518 (when (member :emits-signal (car object))
1519 (dbus-send-signal
1520 bus service path dbus-interface-properties "PropertiesChanged"
1521 `((:dict-entry ,property (:variant ,value)))
1522 '(:array)))
1523 ;; Return empty reply.
1524 :ignore))
1526 ;; "GetAll" returns "a{sv}".
1527 ((string-equal method "GetAll")
1528 (let (result)
1529 (maphash
1530 (lambda (key val)
1531 (when (and (equal (butlast key) (list :property bus interface))
1532 (string-equal path (nth 2 (car val)))
1533 (not (functionp (car (last (car val))))))
1534 (add-to-list
1535 'result
1536 (list :dict-entry
1537 (car (last key))
1538 (list :variant (cdar (last (car val))))))))
1539 dbus-registered-objects-table)
1540 ;; Return the result, or an empty array.
1541 (list :array (or result '(:signature "{sv}"))))))))
1544 ;;; D-Bus object manager.
1546 (defun dbus-get-all-managed-objects (bus service path)
1547 "Return all objects at BUS, SERVICE, PATH, and the children of PATH.
1548 The result is a list of objects. Every object is a cons of an
1549 existing path name, and the list of available interface objects.
1550 An interface object is another cons, which car is the interface
1551 name, and the cdr is the list of properties as returned by
1552 `dbus-get-all-properties' for that path and interface. Example:
1554 \(dbus-get-all-managed-objects :session \"org.gnome.SettingsDaemon\" \"/\")
1556 => \(\(\"/org/gnome/SettingsDaemon/MediaKeys\"
1557 \(\"org.gnome.SettingsDaemon.MediaKeys\")
1558 \(\"org.freedesktop.DBus.Peer\")
1559 \(\"org.freedesktop.DBus.Introspectable\")
1560 \(\"org.freedesktop.DBus.Properties\")
1561 \(\"org.freedesktop.DBus.ObjectManager\"))
1562 \(\"/org/gnome/SettingsDaemon/Power\"
1563 \(\"org.gnome.SettingsDaemon.Power.Keyboard\")
1564 \(\"org.gnome.SettingsDaemon.Power.Screen\")
1565 \(\"org.gnome.SettingsDaemon.Power\"
1566 \(\"Icon\" . \". GThemedIcon battery-full-charged-symbolic \")
1567 \(\"Tooltip\" . \"Laptop battery is charged\"))
1568 \(\"org.freedesktop.DBus.Peer\")
1569 \(\"org.freedesktop.DBus.Introspectable\")
1570 \(\"org.freedesktop.DBus.Properties\")
1571 \(\"org.freedesktop.DBus.ObjectManager\"))
1572 ...)
1574 If possible, \"org.freedesktop.DBus.ObjectManager.GetManagedObjects\"
1575 is used for retrieving the information. Otherwise, the information
1576 is collected via \"org.freedesktop.DBus.Introspectable.Introspect\"
1577 and \"org.freedesktop.DBus.Properties.GetAll\", which is slow."
1578 (let ((result
1579 ;; Direct call. Fails, if the target does not support the
1580 ;; object manager interface.
1581 (dbus-ignore-errors
1582 (dbus-call-method
1583 bus service path dbus-interface-objectmanager
1584 "GetManagedObjects" :timeout 1000))))
1586 (if result
1587 ;; Massage the returned structure.
1588 (dolist (entry result result)
1589 ;; "a{oa{sa{sv}}}".
1590 (dolist (entry1 (cdr entry))
1591 ;; "a{sa{sv}}".
1592 (dolist (entry2 entry1)
1593 ;; "a{sv}".
1594 (if (cadr entry2)
1595 ;; "sv".
1596 (dolist (entry3 (cadr entry2))
1597 (setcdr entry3 (cl-caadr entry3)))
1598 (setcdr entry2 nil)))))
1600 ;; Fallback: collect the information. Slooow!
1601 (dolist (object
1602 (dbus-introspect-get-all-nodes bus service path)
1603 result)
1604 (let (result1)
1605 (dolist
1606 (interface
1607 (dbus-introspect-get-interface-names bus service object)
1608 result1)
1609 (add-to-list
1610 'result1
1611 (cons interface
1612 (dbus-get-all-properties bus service object interface))))
1613 (when result1
1614 (add-to-list 'result (cons object result1))))))))
1616 (defun dbus-managed-objects-handler ()
1617 "Default handler for the \"org.freedesktop.DBus.ObjectManager\" interface.
1618 It will be registered for all objects created by `dbus-register-method'."
1619 (let* ((last-input-event last-input-event)
1620 (bus (dbus-event-bus-name last-input-event))
1621 (path (dbus-event-path-name last-input-event)))
1622 ;; "GetManagedObjects" returns "a{oa{sa{sv}}}".
1623 (let (interfaces result)
1625 ;; Check for object path wildcard interfaces.
1626 (maphash
1627 (lambda (key val)
1628 (when (and (equal (butlast key 2) (list :method bus))
1629 (null (nth 2 (car-safe val))))
1630 (add-to-list 'interfaces (nth 2 key))))
1631 dbus-registered-objects-table)
1633 ;; Check all registered object paths.
1634 (maphash
1635 (lambda (key val)
1636 (let ((object (or (nth 2 (car-safe val)) "")))
1637 (when (and (equal (butlast key 2) (list :method bus))
1638 (string-prefix-p path object))
1639 (dolist (interface (cons (nth 2 key) interfaces))
1640 (unless (assoc object result)
1641 (add-to-list 'result (list object)))
1642 (unless (assoc interface (cdr (assoc object result)))
1643 (setcdr
1644 (assoc object result)
1645 (append
1646 (list (cons
1647 interface
1648 ;; We simulate "org.freedesktop.DBus.Properties.GetAll"
1649 ;; by using an appropriate D-Bus event.
1650 (let ((last-input-event
1651 (append
1652 (butlast last-input-event 4)
1653 (list object dbus-interface-properties
1654 "GetAll" 'dbus-property-handler))))
1655 (dbus-property-handler interface))))
1656 (cdr (assoc object result)))))))))
1657 dbus-registered-objects-table)
1659 ;; Return the result, or an empty array.
1660 (list
1661 :array
1663 (mapcar
1664 (lambda (x)
1665 (list
1666 :dict-entry :object-path (car x)
1667 (cons :array (mapcar (lambda (y) (cons :dict-entry y)) (cdr x)))))
1668 result)
1669 '(:signature "{oa{sa{sv}}}"))))))
1672 ;; Initialize `:system' and `:session' buses. This adds their file
1673 ;; descriptors to input_wait_mask, in order to detect incoming
1674 ;; messages immediately.
1675 (when (featurep 'dbusbind)
1676 (dbus-ignore-errors
1677 (dbus-init-bus :system))
1678 (dbus-ignore-errors
1679 (dbus-init-bus :session)))
1681 (provide 'dbus)
1683 ;;; TODO:
1685 ;; * Implement org.freedesktop.DBus.ObjectManager.InterfacesAdded and
1686 ;; org.freedesktop.DBus.ObjectManager.InterfacesRemoved.
1688 ;;; dbus.el ends here