]> code.delx.au - gnu-emacs/blob - lisp/net/dbus.el
Merge from emacs-24; up to 2013-01-03T02:31:36Z!rgm@gnu.org
[gnu-emacs] / lisp / net / dbus.el
1 ;;; dbus.el --- Elisp bindings for D-Bus.
2
3 ;; Copyright (C) 2007-2013 Free Software Foundation, Inc.
4
5 ;; Author: Michael Albinus <michael.albinus@gmx.de>
6 ;; Keywords: comm, hardware
7
8 ;; This file is part of GNU Emacs.
9
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.
14
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.
19
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/>.
22
23 ;;; Commentary:
24
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.
28
29 ;; Low-level language bindings are implemented in src/dbusbind.c.
30
31 ;; D-Bus support in the Emacs core can be disabled with configuration
32 ;; option "--without-dbus".
33
34 ;;; Code:
35
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)
46
47 ;; Pacify byte compiler.
48 (eval-when-compile (require 'cl-lib))
49
50 (require 'xml)
51
52 (defconst dbus-service-dbus "org.freedesktop.DBus"
53 "The bus name used to talk to the bus itself.")
54
55 (defconst dbus-path-dbus "/org/freedesktop/DBus"
56 "The object path used to talk to the bus itself.")
57
58 ;; Default D-Bus interfaces.
59
60 (defconst dbus-interface-dbus "org.freedesktop.DBus"
61 "The interface exported by the service `dbus-service-dbus'.")
62
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'.")
66
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>
74
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'.")
79
80 ;; <interface name="org.freedesktop.DBus.Introspectable">
81 ;; <method name="Introspect">
82 ;; <arg name="data" type="s" direction="out"/>
83 ;; </method>
84 ;; </interface>
85
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'.")
89
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>
111
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'.")
116
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>
131
132 ;; Emacs defaults.
133 (defconst dbus-service-emacs "org.gnu.Emacs"
134 "The well known service name of Emacs.")
135
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.")
140
141 (defconst dbus-interface-emacs "org.gnu.Emacs"
142 "The interface namespace used by Emacs.")
143
144 ;; D-Bus constants.
145
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\\>"))
154
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'.")
161
162 \f
163 ;;; Basic D-Bus message functions.
164
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.")
171
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))
181
182 (defun dbus-call-method (bus service path interface method &rest args)
183 "Call METHOD on the D-Bus BUS.
184
185 BUS is either a Lisp symbol, `:system' or `:session', or a string
186 denoting the bus address.
187
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.
191
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.
196
197 All other arguments ARGS are passed to METHOD as arguments. They are
198 converted into D-Bus types via the following rules:
199
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
206
207 All arguments can be preceded by a type symbol. For details about
208 type symbols, see Info node `(dbus)Type Conversion'.
209
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:
213
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
231
232 Example:
233
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\")
238
239 => (t (\"Philip R. Zimmermann\"))
240
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.
243
244 \(dbus-call-method
245 :system \"org.freedesktop.Hal\" \"/org/freedesktop/Hal/devices/computer\"
246 \"org.freedesktop.Hal.Device\" \"GetPropertyString\"
247 \"system.kernel.machine\")
248
249 => \"i686\""
250
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)))
261
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)))
267
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)))))))
280
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))))
285
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")
289
290 (defun dbus-call-method-asynchronously
291 (bus service path interface method handler &rest args)
292 "Call METHOD on the D-Bus BUS asynchronously.
293
294 BUS is either a Lisp symbol, `:system' or `:session', or a string
295 denoting the bus address.
296
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.
300
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.
304
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.
309
310 All other arguments ARGS are passed to METHOD as arguments. They are
311 converted into D-Bus types via the following rules:
312
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
319
320 All arguments can be preceded by a type symbol. For details about
321 type symbols, see Info node `(dbus)Type Conversion'.
322
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.
327
328 Example:
329
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\")
334
335 => \(:serial :system 2)
336
337 -| i686"
338
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)))
351
352 (apply 'dbus-message-internal dbus-message-type-method-call
353 bus service path interface method handler args))
354
355 (defun dbus-send-signal (bus service path interface signal &rest args)
356 "Send signal SIGNAL on the D-Bus BUS.
357
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.
361
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.
367
368 All other arguments ARGS are passed to SIGNAL as arguments. They are
369 converted into D-Bus types via the following rules:
370
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
377
378 All arguments can be preceded by a type symbol. For details about
379 type symbols, see Info node `(dbus)Type Conversion'.
380
381 Example:
382
383 \(dbus-send-signal
384 :session nil \"/org/gnu/Emacs\" \"org.gnu.Emacs.FileManager\"
385 \"FileModified\" \"/home/albinus/.emacs\")"
386
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)))
397
398 (apply 'dbus-message-internal dbus-message-type-signal
399 bus service path interface signal args))
400
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."
404
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)))
411
412 (apply 'dbus-message-internal dbus-message-type-method-return
413 bus service serial args))
414
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."
418
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)))
425
426 (apply 'dbus-message-internal dbus-message-type-error
427 bus service serial args))
428
429 \f
430 ;;; Hash table of registered functions.
431
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))
442
443 (defun dbus-setenv (bus variable value)
444 "Set the value of the BUS environment variable named VARIABLE to VALUE.
445
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.
448
449 Normally, services inherit the environment of the BUS daemon. This
450 function adds to or modifies that environment when activating services.
451
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))))
457
458 (defun dbus-register-service (bus service &rest flags)
459 "Register known name SERVICE on the D-Bus BUS.
460
461 BUS is either a Lisp symbol, `:system' or `:session', or a string
462 denoting the bus address.
463
464 SERVICE is the D-Bus service name that should be registered. It must
465 be a known name.
466
467 FLAGS are keywords, which control how the service name is registered.
468 The following keywords are recognized:
469
470 `:allow-replacement': Allow another service to become the primary
471 owner if requested.
472
473 `:replace-existing': Request to replace the current primary owner.
474
475 `:do-not-queue': If we can not become the primary owner do not place
476 us in the queue.
477
478 The function returns a keyword, indicating the result of the
479 operation. One of the following keywords is returned:
480
481 `:primary-owner': Service has become the primary owner of the
482 requested name.
483
484 `:in-queue': Service could not become the primary owner and has been
485 placed in the queue.
486
487 `:exists': Service is already in the queue.
488
489 `:already-owner': Service is already the primary owner."
490
491 ;; Add ObjectManager handler.
492 (dbus-register-method
493 bus service nil dbus-interface-objectmanager "GetManagedObjects"
494 'dbus-managed-objects-handler 'dont-register)
495
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))))))
515
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.
520
521 The function returns a keyword, indicating the result of the
522 operation. One of the following keywords is returned:
523
524 `:released': Service has become the primary owner of the name.
525
526 `:non-existent': Service name does not exist on this bus.
527
528 `:not-owner': We are neither the primary owner nor waiting in the
529 queue of this service."
530
531 (maphash
532 (lambda (key value)
533 (dolist (elt value)
534 (ignore-errors
535 (when (and (equal bus (cadr key)) (string-equal service (cadr elt)))
536 (unless
537 (puthash key (delete elt value) dbus-registered-objects-table)
538 (remhash key dbus-registered-objects-table))))))
539 dbus-registered-objects-table)
540 (let ((reply (dbus-call-method
541 bus dbus-service-dbus dbus-path-dbus dbus-interface-dbus
542 "ReleaseName" service)))
543 (pcase reply
544 (1 :released)
545 (2 :non-existent)
546 (3 :not-owner)
547 (_ (signal 'dbus-error (list "Could not unregister service" service))))))
548
549 (defun dbus-register-signal
550 (bus service path interface signal handler &rest args)
551 "Register for a signal on the D-Bus BUS.
552
553 BUS is either a Lisp symbol, `:system' or `:session', or a string
554 denoting the bus address.
555
556 SERVICE is the D-Bus service name used by the sending D-Bus object.
557 It can be either a known name or the unique name of the D-Bus object
558 sending the signal.
559
560 PATH is the D-Bus object path SERVICE is registered. INTERFACE
561 is an interface offered by SERVICE. It must provide SIGNAL.
562 HANDLER is a Lisp function to be called when the signal is
563 received. It must accept as arguments the values SIGNAL is
564 sending.
565
566 SERVICE, PATH, INTERFACE and SIGNAL can be nil. This is
567 interpreted as a wildcard for the respective argument.
568
569 The remaining arguments ARGS can be keywords or keyword string pairs.
570 The meaning is as follows:
571
572 `:argN' STRING:
573 `:pathN' STRING: This stands for the Nth argument of the
574 signal. `:pathN' arguments can be used for object path wildcard
575 matches as specified by D-Bus, while an `:argN' argument
576 requires an exact match.
577
578 `:arg-namespace' STRING: Register for the signals, which first
579 argument defines the service or interface namespace STRING.
580
581 `:path-namespace' STRING: Register for the object path namespace
582 STRING. All signals sent from an object path, which has STRING as
583 the preceding string, are matched. This requires PATH to be nil.
584
585 `:eavesdrop': Register for unicast signals which are not directed
586 to the D-Bus object Emacs is registered at D-Bus BUS, if the
587 security policy of BUS allows this.
588
589 Example:
590
591 \(defun my-signal-handler (device)
592 (message \"Device %s added\" device))
593
594 \(dbus-register-signal
595 :system \"org.freedesktop.Hal\" \"/org/freedesktop/Hal/Manager\"
596 \"org.freedesktop.Hal.Manager\" \"DeviceAdded\" 'my-signal-handler)
597
598 => \(\(:signal :system \"org.freedesktop.Hal.Manager\" \"DeviceAdded\")
599 \(\"org.freedesktop.Hal\" \"/org/freedesktop/Hal/Manager\" my-signal-handler))
600
601 `dbus-register-signal' returns an object, which can be used in
602 `dbus-unregister-object' for removing the registration."
603
604 (let ((counter 0)
605 (rule "type='signal'")
606 uname key key1 value)
607
608 ;; Retrieve unique name of service. If service is a known name,
609 ;; we will register for the corresponding unique name, if any.
610 ;; Signals are sent always with the unique name as sender. Note:
611 ;; the unique name of `dbus-service-dbus' is that string itself.
612 (if (and (stringp service)
613 (not (zerop (length service)))
614 (not (string-equal service dbus-service-dbus))
615 (not (string-match "^:" service)))
616 (setq uname (dbus-get-name-owner bus service))
617 (setq uname service))
618
619 (setq rule (concat rule
620 (when uname (format ",sender='%s'" uname))
621 (when interface (format ",interface='%s'" interface))
622 (when signal (format ",member='%s'" signal))
623 (when path (format ",path='%s'" path))))
624
625 ;; Add arguments to the rule.
626 (if (or (stringp (car args)) (null (car args)))
627 ;; As backward compatibility option, we allow just strings.
628 (dolist (arg args)
629 (if (stringp arg)
630 (setq rule (concat rule (format ",arg%d='%s'" counter arg)))
631 (if arg (signal 'wrong-type-argument (list "Wrong argument" arg))))
632 (setq counter (1+ counter)))
633
634 ;; Parse keywords.
635 (while args
636 (setq
637 key (car args)
638 rule (concat
639 rule
640 (cond
641 ;; `:arg0' .. `:arg63', `:path0' .. `:path63'.
642 ((and (keywordp key)
643 (string-match
644 "^:\\(arg\\|path\\)\\([[:digit:]]+\\)$"
645 (symbol-name key)))
646 (setq counter (match-string 2 (symbol-name key))
647 args (cdr args)
648 value (car args))
649 (unless (and (<= counter 63) (stringp value))
650 (signal 'wrong-type-argument
651 (list "Wrong argument" key value)))
652 (format
653 ",arg%s%s='%s'"
654 counter
655 (if (string-equal (match-string 1 (symbol-name key)) "path")
656 "path" "")
657 value))
658 ;; `:arg-namespace', `:path-namespace'.
659 ((and (keywordp key)
660 (string-match
661 "^:\\(arg\\|path\\)-namespace$" (symbol-name key)))
662 (setq args (cdr args)
663 value (car args))
664 (unless (stringp value)
665 (signal 'wrong-type-argument
666 (list "Wrong argument" key value)))
667 (format
668 ",%s='%s'"
669 (if (string-equal (match-string 1 (symbol-name key)) "path")
670 "path_namespace" "arg0namespace")
671 value))
672 ;; `:eavesdrop'.
673 ((eq key :eavesdrop)
674 ",eavesdrop='true'")
675 (t (signal 'wrong-type-argument (list "Wrong argument" key)))))
676 args (cdr args))))
677
678 ;; Add the rule to the bus.
679 (condition-case err
680 (dbus-call-method
681 bus dbus-service-dbus dbus-path-dbus dbus-interface-dbus
682 "AddMatch" rule)
683 (dbus-error
684 (if (not (string-match "eavesdrop" rule))
685 (signal (car err) (cdr err))
686 ;; The D-Bus spec says we shall fall back to a rule without eavesdrop.
687 (when dbus-debug (message "Removing eavesdrop from rule %s" rule))
688 (setq rule (replace-regexp-in-string ",eavesdrop='true'" "" rule))
689 (dbus-call-method
690 bus dbus-service-dbus dbus-path-dbus dbus-interface-dbus
691 "AddMatch" rule))))
692
693 (when dbus-debug (message "Matching rule \"%s\" created" rule))
694
695 ;; Create a hash table entry.
696 (setq key (list :signal bus interface signal)
697 key1 (list uname service path handler rule)
698 value (gethash key dbus-registered-objects-table))
699 (unless (member key1 value)
700 (puthash key (cons key1 value) dbus-registered-objects-table))
701
702 ;; Return the object.
703 (list key (list service path handler))))
704
705 (defun dbus-register-method
706 (bus service path interface method handler &optional dont-register-service)
707 "Register for method METHOD on the D-Bus BUS.
708
709 BUS is either a Lisp symbol, `:system' or `:session', or a string
710 denoting the bus address.
711
712 SERVICE is the D-Bus service name of the D-Bus object METHOD is
713 registered for. It must be a known name (See discussion of
714 DONT-REGISTER-SERVICE below).
715
716 PATH is the D-Bus object path SERVICE is registered (See discussion of
717 DONT-REGISTER-SERVICE below). INTERFACE is the interface offered by
718 SERVICE. It must provide METHOD.
719
720 HANDLER is a Lisp function to be called when a method call is
721 received. It must accept the input arguments of METHOD. The return
722 value of HANDLER is used for composing the returning D-Bus message.
723 In case HANDLER shall return a reply message with an empty argument
724 list, HANDLER must return the symbol `:ignore'.
725
726 When DONT-REGISTER-SERVICE is non-nil, the known name SERVICE is not
727 registered. This means that other D-Bus clients have no way of
728 noticing the newly registered method. When interfaces are constructed
729 incrementally by adding single methods or properties at a time,
730 DONT-REGISTER-SERVICE can be used to prevent other clients from
731 discovering the still incomplete interface."
732
733 ;; Register SERVICE.
734 (unless (or dont-register-service
735 (member service (dbus-list-names bus)))
736 (dbus-register-service bus service))
737
738 ;; Create a hash table entry. We use nil for the unique name,
739 ;; because the method might be called from anybody.
740 (let* ((key (list :method bus interface method))
741 (key1 (list nil service path handler))
742 (value (gethash key dbus-registered-objects-table)))
743
744 (unless (member key1 value)
745 (puthash key (cons key1 value) dbus-registered-objects-table))
746
747 ;; Return the object.
748 (list key (list service path handler))))
749
750 (defun dbus-unregister-object (object)
751 "Unregister OBJECT from D-Bus.
752 OBJECT must be the result of a preceding `dbus-register-method',
753 `dbus-register-property' or `dbus-register-signal' call. It
754 returns `t' if OBJECT has been unregistered, `nil' otherwise.
755
756 When OBJECT identifies the last method or property, which is
757 registered for the respective service, Emacs releases its
758 association to the service from D-Bus."
759 ;; Check parameter.
760 (unless (and (consp object) (not (null (car object))) (consp (cdr object)))
761 (signal 'wrong-type-argument (list 'D-Bus object)))
762
763 ;; Find the corresponding entry in the hash table.
764 (let* ((key (car object))
765 (type (car key))
766 (bus (cadr key))
767 (value (cadr object))
768 (service (car value))
769 (entry (gethash key dbus-registered-objects-table))
770 ret)
771 ;; key has the structure (TYPE BUS INTERFACE MEMBER).
772 ;; value has the structure (SERVICE PATH [HANDLER]).
773 ;; entry has the structure ((UNAME SERVICE PATH MEMBER [RULE]) ...).
774 ;; MEMBER is either a string (the handler), or a cons cell (a
775 ;; property value). UNAME and property values are not taken into
776 ;; account for comparison.
777
778 ;; Loop over the registered functions.
779 (dolist (elt entry)
780 (when (equal
781 value
782 (butlast (cdr elt) (- (length (cdr elt)) (length value))))
783 (setq ret t)
784 ;; Compute new hash value. If it is empty, remove it from the
785 ;; hash table.
786 (unless (puthash key (delete elt entry) dbus-registered-objects-table)
787 (remhash key dbus-registered-objects-table))
788 ;; Remove match rule of signals.
789 (when (eq type :signal)
790 (dbus-call-method
791 bus dbus-service-dbus dbus-path-dbus dbus-interface-dbus
792 "RemoveMatch" (nth 4 elt)))))
793
794 ;; Check, whether there is still a registered function or property
795 ;; for the given service. If not, unregister the service from the
796 ;; bus.
797 (when (and service (memq type '(:method :property))
798 (not (catch :found
799 (progn
800 (maphash
801 (lambda (k v)
802 (dolist (e v)
803 (ignore-errors
804 (and
805 ;; Bus.
806 (equal bus (cadr k))
807 ;; Service.
808 (string-equal service (cadr e))
809 ;; Non-empty object path.
810 (cl-caddr e)
811 (throw :found t)))))
812 dbus-registered-objects-table)
813 nil))))
814 (dbus-unregister-service bus service))
815 ;; Return.
816 ret))
817
818 \f
819 ;;; D-Bus type conversion.
820
821 (defun dbus-string-to-byte-array (string)
822 "Transforms STRING to list (:array :byte c1 :byte c2 ...).
823 STRING shall be UTF8 coded."
824 (if (zerop (length string))
825 '(:array :signature "y")
826 (let (result)
827 (dolist (elt (string-to-list string) (append '(:array) result))
828 (setq result (append result (list :byte elt)))))))
829
830 (defun dbus-byte-array-to-string (byte-array)
831 "Transforms BYTE-ARRAY into UTF8 coded string.
832 BYTE-ARRAY must be a list of structure (c1 c2 ...)."
833 (apply 'string byte-array))
834
835 (defun dbus-escape-as-identifier (string)
836 "Escape an arbitrary STRING so it follows the rules for a C identifier.
837 The escaped string can be used as object path component, interface element
838 component, bus name component or member name in D-Bus.
839
840 The escaping consists of replacing all non-alphanumerics, and the
841 first character if it's a digit, with an underscore and two
842 lower-case hex digits:
843
844 \"0123abc_xyz\\x01\\xff\" -> \"_30123abc_5fxyz_01_ff\"
845
846 i.e. similar to URI encoding, but with \"_\" taking the role of \"%\",
847 and a smaller allowed set. As a special case, \"\" is escaped to
848 \"_\".
849
850 Returns the escaped string. Algorithm taken from
851 telepathy-glib's `tp-escape-as-identifier'."
852 (if (zerop (length string))
853 "_"
854 (replace-regexp-in-string
855 "^[0-9]\\|[^A-Za-z0-9]"
856 (lambda (x) (format "_%2x" (aref x 0)))
857 string)))
858
859 (defun dbus-unescape-from-identifier (string)
860 "Retrieve the original string from the encoded STRING.
861 STRING must have been coded with `dbus-escape-as-identifier'"
862 (if (string-equal string "_")
863 ""
864 (replace-regexp-in-string
865 "_.."
866 (lambda (x) (format "%c" (string-to-number (substring x 1) 16)))
867 string)))
868
869 \f
870 ;;; D-Bus events.
871
872 (defun dbus-check-event (event)
873 "Checks whether EVENT is a well formed D-Bus event.
874 EVENT is a list which starts with symbol `dbus-event':
875
876 (dbus-event BUS TYPE SERIAL SERVICE PATH INTERFACE MEMBER HANDLER &rest ARGS)
877
878 BUS identifies the D-Bus the message is coming from. It is
879 either a Lisp symbol, `:system' or `:session', or a string
880 denoting the bus address. TYPE is the D-Bus message type which
881 has caused the event, SERIAL is the serial number of the received
882 D-Bus message. SERVICE and PATH are the unique name and the
883 object path of the D-Bus object emitting the message. INTERFACE
884 and MEMBER denote the message which has been sent. HANDLER is
885 the function which has been registered for this message. ARGS
886 are the arguments passed to HANDLER, when it is called during
887 event handling in `dbus-handle-event'.
888
889 This function raises a `dbus-error' signal in case the event is
890 not well formed."
891 (when dbus-debug (message "DBus-Event %s" event))
892 (unless (and (listp event)
893 (eq (car event) 'dbus-event)
894 ;; Bus symbol.
895 (or (symbolp (nth 1 event))
896 (stringp (nth 1 event)))
897 ;; Type.
898 (and (natnump (nth 2 event))
899 (< dbus-message-type-invalid (nth 2 event)))
900 ;; Serial.
901 (natnump (nth 3 event))
902 ;; Service.
903 (or (= dbus-message-type-method-return (nth 2 event))
904 (= dbus-message-type-error (nth 2 event))
905 (stringp (nth 4 event)))
906 ;; Object path.
907 (or (= dbus-message-type-method-return (nth 2 event))
908 (= dbus-message-type-error (nth 2 event))
909 (stringp (nth 5 event)))
910 ;; Interface.
911 (or (= dbus-message-type-method-return (nth 2 event))
912 (= dbus-message-type-error (nth 2 event))
913 (stringp (nth 6 event)))
914 ;; Member.
915 (or (= dbus-message-type-method-return (nth 2 event))
916 (= dbus-message-type-error (nth 2 event))
917 (stringp (nth 7 event)))
918 ;; Handler.
919 (functionp (nth 8 event)))
920 (signal 'dbus-error (list "Not a valid D-Bus event" event))))
921
922 ;;;###autoload
923 (defun dbus-handle-event (event)
924 "Handle events from the D-Bus.
925 EVENT is a D-Bus event, see `dbus-check-event'. HANDLER, being
926 part of the event, is called with arguments ARGS.
927 If the HANDLER returns a `dbus-error', it is propagated as return message."
928 (interactive "e")
929 (condition-case err
930 (let (result)
931 ;; We ignore not well-formed events.
932 (dbus-check-event event)
933 ;; Error messages must be propagated.
934 (when (= dbus-message-type-error (nth 2 event))
935 (signal 'dbus-error (nthcdr 9 event)))
936 ;; Apply the handler.
937 (setq result (apply (nth 8 event) (nthcdr 9 event)))
938 ;; Return a message when it is a message call.
939 (when (= dbus-message-type-method-call (nth 2 event))
940 (dbus-ignore-errors
941 (if (eq result :ignore)
942 (dbus-method-return-internal
943 (nth 1 event) (nth 4 event) (nth 3 event))
944 (apply 'dbus-method-return-internal
945 (nth 1 event) (nth 4 event) (nth 3 event)
946 (if (consp result) result (list result)))))))
947 ;; Error handling.
948 (dbus-error
949 ;; Return an error message when it is a message call.
950 (when (= dbus-message-type-method-call (nth 2 event))
951 (dbus-ignore-errors
952 (dbus-method-error-internal
953 (nth 1 event) (nth 4 event) (nth 3 event) (cadr err))))
954 ;; Propagate D-Bus error messages.
955 (run-hook-with-args 'dbus-event-error-functions event err)
956 (when (or dbus-debug (= dbus-message-type-error (nth 2 event)))
957 (signal (car err) (cdr err))))))
958
959 (defun dbus-event-bus-name (event)
960 "Return the bus name the event is coming from.
961 The result is either a Lisp symbol, `:system' or `:session', or a
962 string denoting the bus address. EVENT is a D-Bus event, see
963 `dbus-check-event'. This function raises a `dbus-error' signal
964 in case the event is not well formed."
965 (dbus-check-event event)
966 (nth 1 event))
967
968 (defun dbus-event-message-type (event)
969 "Return the message type of the corresponding D-Bus message.
970 The result is a number. EVENT is a D-Bus event, see
971 `dbus-check-event'. This function raises a `dbus-error' signal
972 in case the event is not well formed."
973 (dbus-check-event event)
974 (nth 2 event))
975
976 (defun dbus-event-serial-number (event)
977 "Return the serial number of the corresponding D-Bus message.
978 The result is a number. The serial number is needed for
979 generating a reply message. 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 3 event))
984
985 (defun dbus-event-service-name (event)
986 "Return the name of the D-Bus object the event is coming from.
987 The result is a string. EVENT is a D-Bus event, see `dbus-check-event'.
988 This function raises a `dbus-error' signal in case the event is
989 not well formed."
990 (dbus-check-event event)
991 (nth 4 event))
992
993 (defun dbus-event-path-name (event)
994 "Return the object path of the D-Bus object the event is coming from.
995 The result is a string. EVENT is a D-Bus event, see `dbus-check-event'.
996 This function raises a `dbus-error' signal in case the event is
997 not well formed."
998 (dbus-check-event event)
999 (nth 5 event))
1000
1001 (defun dbus-event-interface-name (event)
1002 "Return the interface name of the D-Bus object the event is coming from.
1003 The result is a string. EVENT is a D-Bus event, see `dbus-check-event'.
1004 This function raises a `dbus-error' signal in case the event is
1005 not well formed."
1006 (dbus-check-event event)
1007 (nth 6 event))
1008
1009 (defun dbus-event-member-name (event)
1010 "Return the member name the event is coming from.
1011 It is either a signal name or a method name. The result is a
1012 string. EVENT is a D-Bus event, see `dbus-check-event'. This
1013 function raises a `dbus-error' signal in case the event is not
1014 well formed."
1015 (dbus-check-event event)
1016 (nth 7 event))
1017
1018 \f
1019 ;;; D-Bus registered names.
1020
1021 (defun dbus-list-activatable-names (&optional bus)
1022 "Return the D-Bus service names which can be activated as list.
1023 If BUS is left nil, `:system' is assumed. The result is a list
1024 of strings, which is `nil' when there are no activatable service
1025 names at all."
1026 (dbus-ignore-errors
1027 (dbus-call-method
1028 (or bus :system) dbus-service-dbus
1029 dbus-path-dbus dbus-interface-dbus "ListActivatableNames")))
1030
1031 (defun dbus-list-names (bus)
1032 "Return the service names registered at D-Bus BUS.
1033 The result is a list of strings, which is `nil' when there are no
1034 registered service names at all. Well known names are strings
1035 like \"org.freedesktop.DBus\". Names starting with \":\" are
1036 unique names for services."
1037 (dbus-ignore-errors
1038 (dbus-call-method
1039 bus dbus-service-dbus dbus-path-dbus dbus-interface-dbus "ListNames")))
1040
1041 (defun dbus-list-known-names (bus)
1042 "Retrieve all services which correspond to a known name in BUS.
1043 A service has a known name if it doesn't start with \":\"."
1044 (let (result)
1045 (dolist (name (dbus-list-names bus) result)
1046 (unless (string-equal ":" (substring name 0 1))
1047 (add-to-list 'result name 'append)))))
1048
1049 (defun dbus-list-queued-owners (bus service)
1050 "Return the unique names registered at D-Bus BUS and queued for SERVICE.
1051 The result is a list of strings, or `nil' when there are no
1052 queued name owners service names at all."
1053 (dbus-ignore-errors
1054 (dbus-call-method
1055 bus dbus-service-dbus dbus-path-dbus
1056 dbus-interface-dbus "ListQueuedOwners" service)))
1057
1058 (defun dbus-get-name-owner (bus service)
1059 "Return the name owner of SERVICE registered at D-Bus BUS.
1060 The result is either a string, or `nil' if there is no name owner."
1061 (dbus-ignore-errors
1062 (dbus-call-method
1063 bus dbus-service-dbus dbus-path-dbus
1064 dbus-interface-dbus "GetNameOwner" service)))
1065
1066 (defun dbus-ping (bus service &optional timeout)
1067 "Check whether SERVICE is registered for D-Bus BUS.
1068 TIMEOUT, a nonnegative integer, specifies the maximum number of
1069 milliseconds `dbus-ping' must return. The default value is 25,000.
1070
1071 Note, that this autoloads SERVICE if it is not running yet. If
1072 it shall be checked whether SERVICE is already running, one shall
1073 apply
1074
1075 \(member service \(dbus-list-known-names bus))"
1076 ;; "Ping" raises a D-Bus error if SERVICE does not exist.
1077 ;; Otherwise, it returns silently with `nil'.
1078 (condition-case nil
1079 (not
1080 (if (natnump timeout)
1081 (dbus-call-method
1082 bus service dbus-path-dbus dbus-interface-peer
1083 "Ping" :timeout timeout)
1084 (dbus-call-method
1085 bus service dbus-path-dbus dbus-interface-peer "Ping")))
1086 (dbus-error nil)))
1087
1088 \f
1089 ;;; D-Bus introspection.
1090
1091 (defun dbus-introspect (bus service path)
1092 "Return all interfaces and sub-nodes of SERVICE,
1093 registered at object path PATH at bus BUS.
1094
1095 BUS is either a Lisp symbol, `:system' or `:session', or a string
1096 denoting the bus address. SERVICE must be a known service name,
1097 and PATH must be a valid object path. The last two parameters
1098 are strings. The result, the introspection data, is a string in
1099 XML format."
1100 ;; We don't want to raise errors.
1101 (dbus-ignore-errors
1102 (dbus-call-method
1103 bus service path dbus-interface-introspectable "Introspect"
1104 :timeout 1000)))
1105
1106 (defun dbus-introspect-xml (bus service path)
1107 "Return the introspection data of SERVICE in D-Bus BUS at object path PATH.
1108 The data are a parsed list. The root object is a \"node\",
1109 representing the object path PATH. The root object can contain
1110 \"interface\" and further \"node\" objects."
1111 ;; We don't want to raise errors.
1112 (xml-node-name
1113 (ignore-errors
1114 (with-temp-buffer
1115 (insert (dbus-introspect bus service path))
1116 (xml-parse-region (point-min) (point-max))))))
1117
1118 (defun dbus-introspect-get-attribute (object attribute)
1119 "Return the ATTRIBUTE value of D-Bus introspection OBJECT.
1120 ATTRIBUTE must be a string according to the attribute names in
1121 the D-Bus specification."
1122 (xml-get-attribute-or-nil object (intern attribute)))
1123
1124 (defun dbus-introspect-get-node-names (bus service path)
1125 "Return all node names of SERVICE in D-Bus BUS at object path PATH.
1126 It returns a list of strings. The node names stand for further
1127 object paths of the D-Bus service."
1128 (let ((object (dbus-introspect-xml bus service path))
1129 result)
1130 (dolist (elt (xml-get-children object 'node) result)
1131 (add-to-list
1132 'result (dbus-introspect-get-attribute elt "name") 'append))))
1133
1134 (defun dbus-introspect-get-all-nodes (bus service path)
1135 "Return all node names of SERVICE in D-Bus BUS at object path PATH.
1136 It returns a list of strings, which are further object paths of SERVICE."
1137 (let ((result (list path)))
1138 (dolist (elt
1139 (dbus-introspect-get-node-names bus service path)
1140 result)
1141 (setq elt (expand-file-name elt path))
1142 (setq result
1143 (append result (dbus-introspect-get-all-nodes bus service elt))))))
1144
1145 (defun dbus-introspect-get-interface-names (bus service path)
1146 "Return all interface names of SERVICE in D-Bus BUS at object path PATH.
1147 It returns a list of strings.
1148
1149 There will be always the default interface
1150 \"org.freedesktop.DBus.Introspectable\". Another default
1151 interface is \"org.freedesktop.DBus.Properties\". If present,
1152 \"interface\" objects can also have \"property\" objects as
1153 children, beside \"method\" and \"signal\" objects."
1154 (let ((object (dbus-introspect-xml bus service path))
1155 result)
1156 (dolist (elt (xml-get-children object 'interface) result)
1157 (add-to-list
1158 'result (dbus-introspect-get-attribute elt "name") 'append))))
1159
1160 (defun dbus-introspect-get-interface (bus service path interface)
1161 "Return the INTERFACE of SERVICE in D-Bus BUS at object path PATH.
1162 The return value is an XML object. INTERFACE must be a string,
1163 element of the list returned by `dbus-introspect-get-interface-names'.
1164 The resulting \"interface\" object can contain \"method\", \"signal\",
1165 \"property\" and \"annotation\" children."
1166 (let ((elt (xml-get-children
1167 (dbus-introspect-xml bus service path) 'interface)))
1168 (while (and elt
1169 (not (string-equal
1170 interface
1171 (dbus-introspect-get-attribute (car elt) "name"))))
1172 (setq elt (cdr elt)))
1173 (car elt)))
1174
1175 (defun dbus-introspect-get-method-names (bus service path interface)
1176 "Return a list of strings of all method names of INTERFACE.
1177 SERVICE is a service of D-Bus BUS at object path PATH."
1178 (let ((object (dbus-introspect-get-interface bus service path interface))
1179 result)
1180 (dolist (elt (xml-get-children object 'method) result)
1181 (add-to-list
1182 'result (dbus-introspect-get-attribute elt "name") 'append))))
1183
1184 (defun dbus-introspect-get-method (bus service path interface method)
1185 "Return method METHOD of interface INTERFACE as XML object.
1186 It must be located at SERVICE in D-Bus BUS at object path PATH.
1187 METHOD must be a string, element of the list returned by
1188 `dbus-introspect-get-method-names'. The resulting \"method\"
1189 object can contain \"arg\" and \"annotation\" children."
1190 (let ((elt (xml-get-children
1191 (dbus-introspect-get-interface bus service path interface)
1192 'method)))
1193 (while (and elt
1194 (not (string-equal
1195 method (dbus-introspect-get-attribute (car elt) "name"))))
1196 (setq elt (cdr elt)))
1197 (car elt)))
1198
1199 (defun dbus-introspect-get-signal-names (bus service path interface)
1200 "Return a list of strings of all signal names of INTERFACE.
1201 SERVICE is a service of D-Bus BUS at object path PATH."
1202 (let ((object (dbus-introspect-get-interface bus service path interface))
1203 result)
1204 (dolist (elt (xml-get-children object 'signal) result)
1205 (add-to-list
1206 'result (dbus-introspect-get-attribute elt "name") 'append))))
1207
1208 (defun dbus-introspect-get-signal (bus service path interface signal)
1209 "Return signal SIGNAL of interface INTERFACE as XML object.
1210 It must be located at SERVICE in D-Bus BUS at object path PATH.
1211 SIGNAL must be a string, element of the list returned by
1212 `dbus-introspect-get-signal-names'. The resulting \"signal\"
1213 object can contain \"arg\" and \"annotation\" children."
1214 (let ((elt (xml-get-children
1215 (dbus-introspect-get-interface bus service path interface)
1216 'signal)))
1217 (while (and elt
1218 (not (string-equal
1219 signal (dbus-introspect-get-attribute (car elt) "name"))))
1220 (setq elt (cdr elt)))
1221 (car elt)))
1222
1223 (defun dbus-introspect-get-property-names (bus service path interface)
1224 "Return a list of strings of all property names of INTERFACE.
1225 SERVICE is a service of D-Bus BUS at object path PATH."
1226 (let ((object (dbus-introspect-get-interface bus service path interface))
1227 result)
1228 (dolist (elt (xml-get-children object 'property) result)
1229 (add-to-list
1230 'result (dbus-introspect-get-attribute elt "name") 'append))))
1231
1232 (defun dbus-introspect-get-property (bus service path interface property)
1233 "This function returns PROPERTY of INTERFACE as XML object.
1234 It must be located at SERVICE in D-Bus BUS at object path PATH.
1235 PROPERTY must be a string, element of the list returned by
1236 `dbus-introspect-get-property-names'. The resulting PROPERTY
1237 object can contain \"annotation\" children."
1238 (let ((elt (xml-get-children
1239 (dbus-introspect-get-interface bus service path interface)
1240 'property)))
1241 (while (and elt
1242 (not (string-equal
1243 property
1244 (dbus-introspect-get-attribute (car elt) "name"))))
1245 (setq elt (cdr elt)))
1246 (car elt)))
1247
1248 (defun dbus-introspect-get-annotation-names
1249 (bus service path interface &optional name)
1250 "Return all annotation names as list of strings.
1251 If NAME is `nil', the annotations are children of INTERFACE,
1252 otherwise NAME must be a \"method\", \"signal\", or \"property\"
1253 object, where the annotations belong to."
1254 (let ((object
1255 (if name
1256 (or (dbus-introspect-get-method bus service path interface name)
1257 (dbus-introspect-get-signal bus service path interface name)
1258 (dbus-introspect-get-property bus service path interface name))
1259 (dbus-introspect-get-interface bus service path interface)))
1260 result)
1261 (dolist (elt (xml-get-children object 'annotation) result)
1262 (add-to-list
1263 'result (dbus-introspect-get-attribute elt "name") 'append))))
1264
1265 (defun dbus-introspect-get-annotation
1266 (bus service path interface name annotation)
1267 "Return ANNOTATION as XML object.
1268 If NAME is `nil', ANNOTATION is a child of INTERFACE, otherwise
1269 NAME must be the name of a \"method\", \"signal\", or
1270 \"property\" object, where the ANNOTATION belongs to."
1271 (let ((elt (xml-get-children
1272 (if name
1273 (or (dbus-introspect-get-method
1274 bus service path interface name)
1275 (dbus-introspect-get-signal
1276 bus service path interface name)
1277 (dbus-introspect-get-property
1278 bus service path interface name))
1279 (dbus-introspect-get-interface bus service path interface))
1280 'annotation)))
1281 (while (and elt
1282 (not (string-equal
1283 annotation
1284 (dbus-introspect-get-attribute (car elt) "name"))))
1285 (setq elt (cdr elt)))
1286 (car elt)))
1287
1288 (defun dbus-introspect-get-argument-names (bus service path interface name)
1289 "Return a list of all argument names as list of strings.
1290 NAME must be a \"method\" or \"signal\" object.
1291
1292 Argument names are optional, the function can return `nil'
1293 therefore, even if the method or signal has arguments."
1294 (let ((object
1295 (or (dbus-introspect-get-method bus service path interface name)
1296 (dbus-introspect-get-signal bus service path interface name)))
1297 result)
1298 (dolist (elt (xml-get-children object 'arg) result)
1299 (add-to-list
1300 'result (dbus-introspect-get-attribute elt "name") 'append))))
1301
1302 (defun dbus-introspect-get-argument (bus service path interface name arg)
1303 "Return argument ARG as XML object.
1304 NAME must be a \"method\" or \"signal\" object. ARG must be a string,
1305 element of the list returned by `dbus-introspect-get-argument-names'."
1306 (let ((elt (xml-get-children
1307 (or (dbus-introspect-get-method bus service path interface name)
1308 (dbus-introspect-get-signal bus service path interface name))
1309 'arg)))
1310 (while (and elt
1311 (not (string-equal
1312 arg (dbus-introspect-get-attribute (car elt) "name"))))
1313 (setq elt (cdr elt)))
1314 (car elt)))
1315
1316 (defun dbus-introspect-get-signature
1317 (bus service path interface name &optional direction)
1318 "Return signature of a `method' or `signal', represented by NAME, as string.
1319 If NAME is a `method', DIRECTION can be either \"in\" or \"out\".
1320 If DIRECTION is `nil', \"in\" is assumed.
1321
1322 If NAME is a `signal', and DIRECTION is non-`nil', DIRECTION must
1323 be \"out\"."
1324 ;; For methods, we use "in" as default direction.
1325 (let ((object (or (dbus-introspect-get-method
1326 bus service path interface name)
1327 (dbus-introspect-get-signal
1328 bus service path interface name))))
1329 (when (and (string-equal
1330 "method" (dbus-introspect-get-attribute object "name"))
1331 (not (stringp direction)))
1332 (setq direction "in"))
1333 ;; In signals, no direction is given.
1334 (when (string-equal "signal" (dbus-introspect-get-attribute object "name"))
1335 (setq direction nil))
1336 ;; Collect the signatures.
1337 (mapconcat
1338 (lambda (x)
1339 (let ((arg (dbus-introspect-get-argument
1340 bus service path interface name x)))
1341 (if (or (not (stringp direction))
1342 (string-equal
1343 direction
1344 (dbus-introspect-get-attribute arg "direction")))
1345 (dbus-introspect-get-attribute arg "type")
1346 "")))
1347 (dbus-introspect-get-argument-names bus service path interface name)
1348 "")))
1349
1350 \f
1351 ;;; D-Bus properties.
1352
1353 (defun dbus-get-property (bus service path interface property)
1354 "Return the value of PROPERTY of INTERFACE.
1355 It will be checked at BUS, SERVICE, PATH. The result can be any
1356 valid D-Bus value, or `nil' if there is no PROPERTY."
1357 (dbus-ignore-errors
1358 ;; "Get" returns a variant, so we must use the `car'.
1359 (car
1360 (dbus-call-method
1361 bus service path dbus-interface-properties
1362 "Get" :timeout 500 interface property))))
1363
1364 (defun dbus-set-property (bus service path interface property value)
1365 "Set value of PROPERTY of INTERFACE to VALUE.
1366 It will be checked at BUS, SERVICE, PATH. When the value has
1367 been set successful, the result is VALUE. Otherwise, `nil' is
1368 returned."
1369 (dbus-ignore-errors
1370 ;; "Set" requires a variant.
1371 (dbus-call-method
1372 bus service path dbus-interface-properties
1373 "Set" :timeout 500 interface property (list :variant value))
1374 ;; Return VALUE.
1375 (dbus-get-property bus service path interface property)))
1376
1377 (defun dbus-get-all-properties (bus service path interface)
1378 "Return all properties of INTERFACE at BUS, SERVICE, PATH.
1379 The result is a list of entries. Every entry is a cons of the
1380 name of the property, and its value. If there are no properties,
1381 `nil' is returned."
1382 (dbus-ignore-errors
1383 ;; "GetAll" returns "a{sv}".
1384 (let (result)
1385 (dolist (dict
1386 (dbus-call-method
1387 bus service path dbus-interface-properties
1388 "GetAll" :timeout 500 interface)
1389 result)
1390 (add-to-list 'result (cons (car dict) (cl-caadr dict)) 'append)))))
1391
1392 (defun dbus-register-property
1393 (bus service path interface property access value
1394 &optional emits-signal dont-register-service)
1395 "Register property PROPERTY on the D-Bus BUS.
1396
1397 BUS is either a Lisp symbol, `:system' or `:session', or a string
1398 denoting the bus address.
1399
1400 SERVICE is the D-Bus service name of the D-Bus. It must be a
1401 known name (See discussion of DONT-REGISTER-SERVICE below).
1402
1403 PATH is the D-Bus object path SERVICE is registered (See
1404 discussion of DONT-REGISTER-SERVICE below). INTERFACE is the
1405 name of the interface used at PATH, PROPERTY is the name of the
1406 property of INTERFACE. ACCESS indicates, whether the property
1407 can be changed by other services via D-Bus. It must be either
1408 the symbol `:read' or `:readwrite'. VALUE is the initial value
1409 of the property, it can be of any valid type (see
1410 `dbus-call-method' for details).
1411
1412 If PROPERTY already exists on PATH, it will be overwritten. For
1413 properties with access type `:read' this is the only way to
1414 change their values. Properties with access type `:readwrite'
1415 can be changed by `dbus-set-property'.
1416
1417 The interface \"org.freedesktop.DBus.Properties\" is added to
1418 PATH, including a default handler for the \"Get\", \"GetAll\" and
1419 \"Set\" methods of this interface. When EMITS-SIGNAL is non-nil,
1420 the signal \"PropertiesChanged\" is sent when the property is
1421 changed by `dbus-set-property'.
1422
1423 When DONT-REGISTER-SERVICE is non-nil, the known name SERVICE is
1424 not registered. This means that other D-Bus clients have no way
1425 of noticing the newly registered property. When interfaces are
1426 constructed incrementally by adding single methods or properties
1427 at a time, DONT-REGISTER-SERVICE can be used to prevent other
1428 clients from discovering the still incomplete interface."
1429 (unless (member access '(:read :readwrite))
1430 (signal 'wrong-type-argument (list "Access type invalid" access)))
1431
1432 ;; Add handlers for the three property-related methods.
1433 (dbus-register-method
1434 bus service path dbus-interface-properties "Get"
1435 'dbus-property-handler 'dont-register)
1436 (dbus-register-method
1437 bus service path dbus-interface-properties "GetAll"
1438 'dbus-property-handler 'dont-register)
1439 (dbus-register-method
1440 bus service path dbus-interface-properties "Set"
1441 'dbus-property-handler 'dont-register)
1442
1443 ;; Register SERVICE.
1444 (unless (or dont-register-service (member service (dbus-list-names bus)))
1445 (dbus-register-service bus service))
1446
1447 ;; Send the PropertiesChanged signal.
1448 (when emits-signal
1449 (dbus-send-signal
1450 bus service path dbus-interface-properties "PropertiesChanged"
1451 `((:dict-entry ,property (:variant ,value)))
1452 '(:array)))
1453
1454 ;; Create a hash table entry. We use nil for the unique name,
1455 ;; because the property might be accessed from anybody.
1456 (let ((key (list :property bus interface property))
1457 (val
1458 (list
1459 (list
1460 nil service path
1461 (cons
1462 (if emits-signal (list access :emits-signal) (list access))
1463 value)))))
1464 (puthash key val dbus-registered-objects-table)
1465
1466 ;; Return the object.
1467 (list key (list service path))))
1468
1469 (defun dbus-property-handler (&rest args)
1470 "Default handler for the \"org.freedesktop.DBus.Properties\" interface.
1471 It will be registered for all objects created by `dbus-register-property'."
1472 (let ((bus (dbus-event-bus-name last-input-event))
1473 (service (dbus-event-service-name last-input-event))
1474 (path (dbus-event-path-name last-input-event))
1475 (method (dbus-event-member-name last-input-event))
1476 (interface (car args))
1477 (property (cadr args)))
1478 (cond
1479 ;; "Get" returns a variant.
1480 ((string-equal method "Get")
1481 (let ((entry (gethash (list :property bus interface property)
1482 dbus-registered-objects-table)))
1483 (when (string-equal path (nth 2 (car entry)))
1484 `((:variant ,(cdar (last (car entry))))))))
1485
1486 ;; "Set" expects a variant.
1487 ((string-equal method "Set")
1488 (let* ((value (caar (cddr args)))
1489 (entry (gethash (list :property bus interface property)
1490 dbus-registered-objects-table))
1491 ;; The value of the hash table is a list; in case of
1492 ;; properties it contains just one element (UNAME SERVICE
1493 ;; PATH OBJECT). OBJECT is a cons cell of a list, which
1494 ;; contains a list of annotations (like :read,
1495 ;; :read-write, :emits-signal), and the value of the
1496 ;; property.
1497 (object (car (last (car entry)))))
1498 (unless (consp object)
1499 (signal 'dbus-error
1500 (list "Property not registered at path" property path)))
1501 (unless (member :readwrite (car object))
1502 (signal 'dbus-error
1503 (list "Property not writable at path" property path)))
1504 (puthash (list :property bus interface property)
1505 (list (append (butlast (car entry))
1506 (list (cons (car object) value))))
1507 dbus-registered-objects-table)
1508 ;; Send the "PropertiesChanged" signal.
1509 (when (member :emits-signal (car object))
1510 (dbus-send-signal
1511 bus service path dbus-interface-properties "PropertiesChanged"
1512 `((:dict-entry ,property (:variant ,value)))
1513 '(:array)))
1514 ;; Return empty reply.
1515 :ignore))
1516
1517 ;; "GetAll" returns "a{sv}".
1518 ((string-equal method "GetAll")
1519 (let (result)
1520 (maphash
1521 (lambda (key val)
1522 (when (and (equal (butlast key) (list :property bus interface))
1523 (string-equal path (nth 2 (car val)))
1524 (not (functionp (car (last (car val))))))
1525 (add-to-list
1526 'result
1527 (list :dict-entry
1528 (car (last key))
1529 (list :variant (cdar (last (car val))))))))
1530 dbus-registered-objects-table)
1531 ;; Return the result, or an empty array.
1532 (list :array (or result '(:signature "{sv}"))))))))
1533
1534 \f
1535 ;;; D-Bus object manager.
1536
1537 (defun dbus-get-all-managed-objects (bus service path)
1538 "Return all objects at BUS, SERVICE, PATH, and the children of PATH.
1539 The result is a list of objects. Every object is a cons of an
1540 existing path name, and the list of available interface objects.
1541 An interface object is another cons, which car is the interface
1542 name, and the cdr is the list of properties as returned by
1543 `dbus-get-all-properties' for that path and interface. Example:
1544
1545 \(dbus-get-all-managed-objects :session \"org.gnome.SettingsDaemon\" \"/\")
1546
1547 => \(\(\"/org/gnome/SettingsDaemon/MediaKeys\"
1548 \(\"org.gnome.SettingsDaemon.MediaKeys\")
1549 \(\"org.freedesktop.DBus.Peer\")
1550 \(\"org.freedesktop.DBus.Introspectable\")
1551 \(\"org.freedesktop.DBus.Properties\")
1552 \(\"org.freedesktop.DBus.ObjectManager\"))
1553 \(\"/org/gnome/SettingsDaemon/Power\"
1554 \(\"org.gnome.SettingsDaemon.Power.Keyboard\")
1555 \(\"org.gnome.SettingsDaemon.Power.Screen\")
1556 \(\"org.gnome.SettingsDaemon.Power\"
1557 \(\"Icon\" . \". GThemedIcon battery-full-charged-symbolic \")
1558 \(\"Tooltip\" . \"Laptop battery is charged\"))
1559 \(\"org.freedesktop.DBus.Peer\")
1560 \(\"org.freedesktop.DBus.Introspectable\")
1561 \(\"org.freedesktop.DBus.Properties\")
1562 \(\"org.freedesktop.DBus.ObjectManager\"))
1563 ...)
1564
1565 If possible, \"org.freedesktop.DBus.ObjectManager.GetManagedObjects\"
1566 is used for retrieving the information. Otherwise, the information
1567 is collected via \"org.freedesktop.DBus.Introspectable.Introspect\"
1568 and \"org.freedesktop.DBus.Properties.GetAll\", which is slow."
1569 (let ((result
1570 ;; Direct call. Fails, if the target does not support the
1571 ;; object manager interface.
1572 (dbus-ignore-errors
1573 (dbus-call-method
1574 bus service path dbus-interface-objectmanager
1575 "GetManagedObjects" :timeout 1000))))
1576
1577 (if result
1578 ;; Massage the returned structure.
1579 (dolist (entry result result)
1580 ;; "a{oa{sa{sv}}}".
1581 (dolist (entry1 (cdr entry))
1582 ;; "a{sa{sv}}".
1583 (dolist (entry2 entry1)
1584 ;; "a{sv}".
1585 (if (cadr entry2)
1586 ;; "sv".
1587 (dolist (entry3 (cadr entry2))
1588 (setcdr entry3 (cl-caadr entry3)))
1589 (setcdr entry2 nil)))))
1590
1591 ;; Fallback: collect the information. Slooow!
1592 (dolist (object
1593 (dbus-introspect-get-all-nodes bus service path)
1594 result)
1595 (let (result1)
1596 (dolist
1597 (interface
1598 (dbus-introspect-get-interface-names bus service object)
1599 result1)
1600 (add-to-list
1601 'result1
1602 (cons interface
1603 (dbus-get-all-properties bus service object interface))))
1604 (when result1
1605 (add-to-list 'result (cons object result1))))))))
1606
1607 (defun dbus-managed-objects-handler ()
1608 "Default handler for the \"org.freedesktop.DBus.ObjectManager\" interface.
1609 It will be registered for all objects created by `dbus-register-method'."
1610 (let* ((last-input-event last-input-event)
1611 (bus (dbus-event-bus-name last-input-event))
1612 (path (dbus-event-path-name last-input-event)))
1613 ;; "GetManagedObjects" returns "a{oa{sa{sv}}}".
1614 (let (interfaces result)
1615
1616 ;; Check for object path wildcard interfaces.
1617 (maphash
1618 (lambda (key val)
1619 (when (and (equal (butlast key 2) (list :method bus))
1620 (null (nth 2 (car-safe val))))
1621 (add-to-list 'interfaces (nth 2 key))))
1622 dbus-registered-objects-table)
1623
1624 ;; Check all registered object paths.
1625 (maphash
1626 (lambda (key val)
1627 (let ((object (or (nth 2 (car-safe val)) "")))
1628 (when (and (equal (butlast key 2) (list :method bus))
1629 (string-prefix-p path object))
1630 (dolist (interface (cons (nth 2 key) interfaces))
1631 (unless (assoc object result)
1632 (add-to-list 'result (list object)))
1633 (unless (assoc interface (cdr (assoc object result)))
1634 (setcdr
1635 (assoc object result)
1636 (append
1637 (list (cons
1638 interface
1639 ;; We simulate "org.freedesktop.DBus.Properties.GetAll"
1640 ;; by using an appropriate D-Bus event.
1641 (let ((last-input-event
1642 (append
1643 (butlast last-input-event 4)
1644 (list object dbus-interface-properties
1645 "GetAll" 'dbus-property-handler))))
1646 (dbus-property-handler interface))))
1647 (cdr (assoc object result)))))))))
1648 dbus-registered-objects-table)
1649
1650 ;; Return the result, or an empty array.
1651 (list
1652 :array
1653 (or
1654 (mapcar
1655 (lambda (x)
1656 (list
1657 :dict-entry :object-path (car x)
1658 (cons :array (mapcar (lambda (y) (cons :dict-entry y)) (cdr x)))))
1659 result)
1660 '(:signature "{oa{sa{sv}}}"))))))
1661
1662 \f
1663 ;; Initialize `:system' and `:session' buses. This adds their file
1664 ;; descriptors to input_wait_mask, in order to detect incoming
1665 ;; messages immediately.
1666 (when (featurep 'dbusbind)
1667 (dbus-ignore-errors
1668 (dbus-init-bus :system))
1669 (dbus-ignore-errors
1670 (dbus-init-bus :session)))
1671
1672 (provide 'dbus)
1673
1674 ;;; TODO:
1675
1676 ;; * Implement org.freedesktop.DBus.ObjectManager.InterfacesAdded and
1677 ;; org.freedesktop.DBus.ObjectManager.InterfacesRemoved.
1678
1679 ;;; dbus.el ends here