* net/dbus.el (dbus-byte-array-to-string): Accept also byte arrays
[bpt/emacs.git] / 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 ...), or a byte
833 array as produced by `dbus-string-to-byte-array'."
834 (apply
835 'string
836 (if (equal byte-array '(:array :signature "y"))
837 nil
838 (let (result)
839 (dolist (elt byte-array result)
840 (when (characterp elt) (setq result (append result `(,elt)))))))))
841
842 (defun dbus-escape-as-identifier (string)
843 "Escape an arbitrary STRING so it follows the rules for a C identifier.
844 The escaped string can be used as object path component, interface element
845 component, bus name component or member name in D-Bus.
846
847 The escaping consists of replacing all non-alphanumerics, and the
848 first character if it's a digit, with an underscore and two
849 lower-case hex digits:
850
851 \"0123abc_xyz\\x01\\xff\" -> \"_30123abc_5fxyz_01_ff\"
852
853 i.e. similar to URI encoding, but with \"_\" taking the role of \"%\",
854 and a smaller allowed set. As a special case, \"\" is escaped to
855 \"_\".
856
857 Returns the escaped string. Algorithm taken from
858 telepathy-glib's `tp-escape-as-identifier'."
859 (if (zerop (length string))
860 "_"
861 (replace-regexp-in-string
862 "^[0-9]\\|[^A-Za-z0-9]"
863 (lambda (x) (format "_%2x" (aref x 0)))
864 string)))
865
866 (defun dbus-unescape-from-identifier (string)
867 "Retrieve the original string from the encoded STRING.
868 STRING must have been coded with `dbus-escape-as-identifier'"
869 (if (string-equal string "_")
870 ""
871 (replace-regexp-in-string
872 "_.."
873 (lambda (x) (byte-to-string (string-to-number (substring x 1) 16)))
874 string)))
875
876 \f
877 ;;; D-Bus events.
878
879 (defun dbus-check-event (event)
880 "Checks whether EVENT is a well formed D-Bus event.
881 EVENT is a list which starts with symbol `dbus-event':
882
883 (dbus-event BUS TYPE SERIAL SERVICE PATH INTERFACE MEMBER HANDLER &rest ARGS)
884
885 BUS identifies the D-Bus the message is coming from. It is
886 either a Lisp symbol, `:system' or `:session', or a string
887 denoting the bus address. TYPE is the D-Bus message type which
888 has caused the event, SERIAL is the serial number of the received
889 D-Bus message. SERVICE and PATH are the unique name and the
890 object path of the D-Bus object emitting the message. INTERFACE
891 and MEMBER denote the message which has been sent. HANDLER is
892 the function which has been registered for this message. ARGS
893 are the arguments passed to HANDLER, when it is called during
894 event handling in `dbus-handle-event'.
895
896 This function raises a `dbus-error' signal in case the event is
897 not well formed."
898 (when dbus-debug (message "DBus-Event %s" event))
899 (unless (and (listp event)
900 (eq (car event) 'dbus-event)
901 ;; Bus symbol.
902 (or (symbolp (nth 1 event))
903 (stringp (nth 1 event)))
904 ;; Type.
905 (and (natnump (nth 2 event))
906 (< dbus-message-type-invalid (nth 2 event)))
907 ;; Serial.
908 (natnump (nth 3 event))
909 ;; Service.
910 (or (= dbus-message-type-method-return (nth 2 event))
911 (= dbus-message-type-error (nth 2 event))
912 (stringp (nth 4 event)))
913 ;; Object path.
914 (or (= dbus-message-type-method-return (nth 2 event))
915 (= dbus-message-type-error (nth 2 event))
916 (stringp (nth 5 event)))
917 ;; Interface.
918 (or (= dbus-message-type-method-return (nth 2 event))
919 (= dbus-message-type-error (nth 2 event))
920 (stringp (nth 6 event)))
921 ;; Member.
922 (or (= dbus-message-type-method-return (nth 2 event))
923 (= dbus-message-type-error (nth 2 event))
924 (stringp (nth 7 event)))
925 ;; Handler.
926 (functionp (nth 8 event)))
927 (signal 'dbus-error (list "Not a valid D-Bus event" event))))
928
929 ;;;###autoload
930 (defun dbus-handle-event (event)
931 "Handle events from the D-Bus.
932 EVENT is a D-Bus event, see `dbus-check-event'. HANDLER, being
933 part of the event, is called with arguments ARGS.
934 If the HANDLER returns a `dbus-error', it is propagated as return message."
935 (interactive "e")
936 (condition-case err
937 (let (result)
938 ;; We ignore not well-formed events.
939 (dbus-check-event event)
940 ;; Error messages must be propagated.
941 (when (= dbus-message-type-error (nth 2 event))
942 (signal 'dbus-error (nthcdr 9 event)))
943 ;; Apply the handler.
944 (setq result (apply (nth 8 event) (nthcdr 9 event)))
945 ;; Return a message when it is a message call.
946 (when (= dbus-message-type-method-call (nth 2 event))
947 (dbus-ignore-errors
948 (if (eq result :ignore)
949 (dbus-method-return-internal
950 (nth 1 event) (nth 4 event) (nth 3 event))
951 (apply 'dbus-method-return-internal
952 (nth 1 event) (nth 4 event) (nth 3 event)
953 (if (consp result) result (list result)))))))
954 ;; Error handling.
955 (dbus-error
956 ;; Return an error message when it is a message call.
957 (when (= dbus-message-type-method-call (nth 2 event))
958 (dbus-ignore-errors
959 (dbus-method-error-internal
960 (nth 1 event) (nth 4 event) (nth 3 event) (cadr err))))
961 ;; Propagate D-Bus error messages.
962 (run-hook-with-args 'dbus-event-error-functions event err)
963 (when (or dbus-debug (= dbus-message-type-error (nth 2 event)))
964 (signal (car err) (cdr err))))))
965
966 (defun dbus-event-bus-name (event)
967 "Return the bus name the event is coming from.
968 The result is either a Lisp symbol, `:system' or `:session', or a
969 string denoting the bus address. EVENT is a D-Bus event, see
970 `dbus-check-event'. This function raises a `dbus-error' signal
971 in case the event is not well formed."
972 (dbus-check-event event)
973 (nth 1 event))
974
975 (defun dbus-event-message-type (event)
976 "Return the message type of the corresponding D-Bus message.
977 The result is a number. EVENT is a D-Bus event, see
978 `dbus-check-event'. This function raises a `dbus-error' signal
979 in case the event is not well formed."
980 (dbus-check-event event)
981 (nth 2 event))
982
983 (defun dbus-event-serial-number (event)
984 "Return the serial number of the corresponding D-Bus message.
985 The result is a number. The serial number is needed for
986 generating a reply message. EVENT is a D-Bus event, see
987 `dbus-check-event'. This function raises a `dbus-error' signal
988 in case the event is not well formed."
989 (dbus-check-event event)
990 (nth 3 event))
991
992 (defun dbus-event-service-name (event)
993 "Return the name of the D-Bus object the event is coming from.
994 The result is a string. EVENT is a D-Bus event, see `dbus-check-event'.
995 This function raises a `dbus-error' signal in case the event is
996 not well formed."
997 (dbus-check-event event)
998 (nth 4 event))
999
1000 (defun dbus-event-path-name (event)
1001 "Return the object path of the D-Bus object the event is coming from.
1002 The result is a string. EVENT is a D-Bus event, see `dbus-check-event'.
1003 This function raises a `dbus-error' signal in case the event is
1004 not well formed."
1005 (dbus-check-event event)
1006 (nth 5 event))
1007
1008 (defun dbus-event-interface-name (event)
1009 "Return the interface name of the D-Bus object the event is coming from.
1010 The result is a string. EVENT is a D-Bus event, see `dbus-check-event'.
1011 This function raises a `dbus-error' signal in case the event is
1012 not well formed."
1013 (dbus-check-event event)
1014 (nth 6 event))
1015
1016 (defun dbus-event-member-name (event)
1017 "Return the member name the event is coming from.
1018 It is either a signal name or a method name. The result is a
1019 string. EVENT is a D-Bus event, see `dbus-check-event'. This
1020 function raises a `dbus-error' signal in case the event is not
1021 well formed."
1022 (dbus-check-event event)
1023 (nth 7 event))
1024
1025 \f
1026 ;;; D-Bus registered names.
1027
1028 (defun dbus-list-activatable-names (&optional bus)
1029 "Return the D-Bus service names which can be activated as list.
1030 If BUS is left nil, `:system' is assumed. The result is a list
1031 of strings, which is `nil' when there are no activatable service
1032 names at all."
1033 (dbus-ignore-errors
1034 (dbus-call-method
1035 (or bus :system) dbus-service-dbus
1036 dbus-path-dbus dbus-interface-dbus "ListActivatableNames")))
1037
1038 (defun dbus-list-names (bus)
1039 "Return the service names registered at D-Bus BUS.
1040 The result is a list of strings, which is `nil' when there are no
1041 registered service names at all. Well known names are strings
1042 like \"org.freedesktop.DBus\". Names starting with \":\" are
1043 unique names for services."
1044 (dbus-ignore-errors
1045 (dbus-call-method
1046 bus dbus-service-dbus dbus-path-dbus dbus-interface-dbus "ListNames")))
1047
1048 (defun dbus-list-known-names (bus)
1049 "Retrieve all services which correspond to a known name in BUS.
1050 A service has a known name if it doesn't start with \":\"."
1051 (let (result)
1052 (dolist (name (dbus-list-names bus) result)
1053 (unless (string-equal ":" (substring name 0 1))
1054 (add-to-list 'result name 'append)))))
1055
1056 (defun dbus-list-queued-owners (bus service)
1057 "Return the unique names registered at D-Bus BUS and queued for SERVICE.
1058 The result is a list of strings, or `nil' when there are no
1059 queued name owners service names at all."
1060 (dbus-ignore-errors
1061 (dbus-call-method
1062 bus dbus-service-dbus dbus-path-dbus
1063 dbus-interface-dbus "ListQueuedOwners" service)))
1064
1065 (defun dbus-get-name-owner (bus service)
1066 "Return the name owner of SERVICE registered at D-Bus BUS.
1067 The result is either a string, or `nil' if there is no name owner."
1068 (dbus-ignore-errors
1069 (dbus-call-method
1070 bus dbus-service-dbus dbus-path-dbus
1071 dbus-interface-dbus "GetNameOwner" service)))
1072
1073 (defun dbus-ping (bus service &optional timeout)
1074 "Check whether SERVICE is registered for D-Bus BUS.
1075 TIMEOUT, a nonnegative integer, specifies the maximum number of
1076 milliseconds `dbus-ping' must return. The default value is 25,000.
1077
1078 Note, that this autoloads SERVICE if it is not running yet. If
1079 it shall be checked whether SERVICE is already running, one shall
1080 apply
1081
1082 \(member service \(dbus-list-known-names bus))"
1083 ;; "Ping" raises a D-Bus error if SERVICE does not exist.
1084 ;; Otherwise, it returns silently with `nil'.
1085 (condition-case nil
1086 (not
1087 (if (natnump timeout)
1088 (dbus-call-method
1089 bus service dbus-path-dbus dbus-interface-peer
1090 "Ping" :timeout timeout)
1091 (dbus-call-method
1092 bus service dbus-path-dbus dbus-interface-peer "Ping")))
1093 (dbus-error nil)))
1094
1095 \f
1096 ;;; D-Bus introspection.
1097
1098 (defun dbus-introspect (bus service path)
1099 "Return all interfaces and sub-nodes of SERVICE,
1100 registered at object path PATH at bus BUS.
1101
1102 BUS is either a Lisp symbol, `:system' or `:session', or a string
1103 denoting the bus address. SERVICE must be a known service name,
1104 and PATH must be a valid object path. The last two parameters
1105 are strings. The result, the introspection data, is a string in
1106 XML format."
1107 ;; We don't want to raise errors.
1108 (dbus-ignore-errors
1109 (dbus-call-method
1110 bus service path dbus-interface-introspectable "Introspect"
1111 :timeout 1000)))
1112
1113 (defun dbus-introspect-xml (bus service path)
1114 "Return the introspection data of SERVICE in D-Bus BUS at object path PATH.
1115 The data are a parsed list. The root object is a \"node\",
1116 representing the object path PATH. The root object can contain
1117 \"interface\" and further \"node\" objects."
1118 ;; We don't want to raise errors.
1119 (xml-node-name
1120 (ignore-errors
1121 (with-temp-buffer
1122 (insert (dbus-introspect bus service path))
1123 (xml-parse-region (point-min) (point-max))))))
1124
1125 (defun dbus-introspect-get-attribute (object attribute)
1126 "Return the ATTRIBUTE value of D-Bus introspection OBJECT.
1127 ATTRIBUTE must be a string according to the attribute names in
1128 the D-Bus specification."
1129 (xml-get-attribute-or-nil object (intern attribute)))
1130
1131 (defun dbus-introspect-get-node-names (bus service path)
1132 "Return all node names of SERVICE in D-Bus BUS at object path PATH.
1133 It returns a list of strings. The node names stand for further
1134 object paths of the D-Bus service."
1135 (let ((object (dbus-introspect-xml bus service path))
1136 result)
1137 (dolist (elt (xml-get-children object 'node) result)
1138 (add-to-list
1139 'result (dbus-introspect-get-attribute elt "name") 'append))))
1140
1141 (defun dbus-introspect-get-all-nodes (bus service path)
1142 "Return all node names of SERVICE in D-Bus BUS at object path PATH.
1143 It returns a list of strings, which are further object paths of SERVICE."
1144 (let ((result (list path)))
1145 (dolist (elt
1146 (dbus-introspect-get-node-names bus service path)
1147 result)
1148 (setq elt (expand-file-name elt path))
1149 (setq result
1150 (append result (dbus-introspect-get-all-nodes bus service elt))))))
1151
1152 (defun dbus-introspect-get-interface-names (bus service path)
1153 "Return all interface names of SERVICE in D-Bus BUS at object path PATH.
1154 It returns a list of strings.
1155
1156 There will be always the default interface
1157 \"org.freedesktop.DBus.Introspectable\". Another default
1158 interface is \"org.freedesktop.DBus.Properties\". If present,
1159 \"interface\" objects can also have \"property\" objects as
1160 children, beside \"method\" and \"signal\" objects."
1161 (let ((object (dbus-introspect-xml bus service path))
1162 result)
1163 (dolist (elt (xml-get-children object 'interface) result)
1164 (add-to-list
1165 'result (dbus-introspect-get-attribute elt "name") 'append))))
1166
1167 (defun dbus-introspect-get-interface (bus service path interface)
1168 "Return the INTERFACE of SERVICE in D-Bus BUS at object path PATH.
1169 The return value is an XML object. INTERFACE must be a string,
1170 element of the list returned by `dbus-introspect-get-interface-names'.
1171 The resulting \"interface\" object can contain \"method\", \"signal\",
1172 \"property\" and \"annotation\" children."
1173 (let ((elt (xml-get-children
1174 (dbus-introspect-xml bus service path) 'interface)))
1175 (while (and elt
1176 (not (string-equal
1177 interface
1178 (dbus-introspect-get-attribute (car elt) "name"))))
1179 (setq elt (cdr elt)))
1180 (car elt)))
1181
1182 (defun dbus-introspect-get-method-names (bus service path interface)
1183 "Return a list of strings of all method names of INTERFACE.
1184 SERVICE is a service of D-Bus BUS at object path PATH."
1185 (let ((object (dbus-introspect-get-interface bus service path interface))
1186 result)
1187 (dolist (elt (xml-get-children object 'method) result)
1188 (add-to-list
1189 'result (dbus-introspect-get-attribute elt "name") 'append))))
1190
1191 (defun dbus-introspect-get-method (bus service path interface method)
1192 "Return method METHOD of interface INTERFACE as XML object.
1193 It must be located at SERVICE in D-Bus BUS at object path PATH.
1194 METHOD must be a string, element of the list returned by
1195 `dbus-introspect-get-method-names'. The resulting \"method\"
1196 object can contain \"arg\" and \"annotation\" children."
1197 (let ((elt (xml-get-children
1198 (dbus-introspect-get-interface bus service path interface)
1199 'method)))
1200 (while (and elt
1201 (not (string-equal
1202 method (dbus-introspect-get-attribute (car elt) "name"))))
1203 (setq elt (cdr elt)))
1204 (car elt)))
1205
1206 (defun dbus-introspect-get-signal-names (bus service path interface)
1207 "Return a list of strings of all signal names of INTERFACE.
1208 SERVICE is a service of D-Bus BUS at object path PATH."
1209 (let ((object (dbus-introspect-get-interface bus service path interface))
1210 result)
1211 (dolist (elt (xml-get-children object 'signal) result)
1212 (add-to-list
1213 'result (dbus-introspect-get-attribute elt "name") 'append))))
1214
1215 (defun dbus-introspect-get-signal (bus service path interface signal)
1216 "Return signal SIGNAL of interface INTERFACE as XML object.
1217 It must be located at SERVICE in D-Bus BUS at object path PATH.
1218 SIGNAL must be a string, element of the list returned by
1219 `dbus-introspect-get-signal-names'. The resulting \"signal\"
1220 object can contain \"arg\" and \"annotation\" children."
1221 (let ((elt (xml-get-children
1222 (dbus-introspect-get-interface bus service path interface)
1223 'signal)))
1224 (while (and elt
1225 (not (string-equal
1226 signal (dbus-introspect-get-attribute (car elt) "name"))))
1227 (setq elt (cdr elt)))
1228 (car elt)))
1229
1230 (defun dbus-introspect-get-property-names (bus service path interface)
1231 "Return a list of strings of all property names of INTERFACE.
1232 SERVICE is a service of D-Bus BUS at object path PATH."
1233 (let ((object (dbus-introspect-get-interface bus service path interface))
1234 result)
1235 (dolist (elt (xml-get-children object 'property) result)
1236 (add-to-list
1237 'result (dbus-introspect-get-attribute elt "name") 'append))))
1238
1239 (defun dbus-introspect-get-property (bus service path interface property)
1240 "This function returns PROPERTY of INTERFACE as XML object.
1241 It must be located at SERVICE in D-Bus BUS at object path PATH.
1242 PROPERTY must be a string, element of the list returned by
1243 `dbus-introspect-get-property-names'. The resulting PROPERTY
1244 object can contain \"annotation\" children."
1245 (let ((elt (xml-get-children
1246 (dbus-introspect-get-interface bus service path interface)
1247 'property)))
1248 (while (and elt
1249 (not (string-equal
1250 property
1251 (dbus-introspect-get-attribute (car elt) "name"))))
1252 (setq elt (cdr elt)))
1253 (car elt)))
1254
1255 (defun dbus-introspect-get-annotation-names
1256 (bus service path interface &optional name)
1257 "Return all annotation names as list of strings.
1258 If NAME is `nil', the annotations are children of INTERFACE,
1259 otherwise NAME must be a \"method\", \"signal\", or \"property\"
1260 object, where the annotations belong to."
1261 (let ((object
1262 (if name
1263 (or (dbus-introspect-get-method bus service path interface name)
1264 (dbus-introspect-get-signal bus service path interface name)
1265 (dbus-introspect-get-property bus service path interface name))
1266 (dbus-introspect-get-interface bus service path interface)))
1267 result)
1268 (dolist (elt (xml-get-children object 'annotation) result)
1269 (add-to-list
1270 'result (dbus-introspect-get-attribute elt "name") 'append))))
1271
1272 (defun dbus-introspect-get-annotation
1273 (bus service path interface name annotation)
1274 "Return ANNOTATION as XML object.
1275 If NAME is `nil', ANNOTATION is a child of INTERFACE, otherwise
1276 NAME must be the name of a \"method\", \"signal\", or
1277 \"property\" object, where the ANNOTATION belongs to."
1278 (let ((elt (xml-get-children
1279 (if name
1280 (or (dbus-introspect-get-method
1281 bus service path interface name)
1282 (dbus-introspect-get-signal
1283 bus service path interface name)
1284 (dbus-introspect-get-property
1285 bus service path interface name))
1286 (dbus-introspect-get-interface bus service path interface))
1287 'annotation)))
1288 (while (and elt
1289 (not (string-equal
1290 annotation
1291 (dbus-introspect-get-attribute (car elt) "name"))))
1292 (setq elt (cdr elt)))
1293 (car elt)))
1294
1295 (defun dbus-introspect-get-argument-names (bus service path interface name)
1296 "Return a list of all argument names as list of strings.
1297 NAME must be a \"method\" or \"signal\" object.
1298
1299 Argument names are optional, the function can return `nil'
1300 therefore, even if the method or signal has arguments."
1301 (let ((object
1302 (or (dbus-introspect-get-method bus service path interface name)
1303 (dbus-introspect-get-signal bus service path interface name)))
1304 result)
1305 (dolist (elt (xml-get-children object 'arg) result)
1306 (add-to-list
1307 'result (dbus-introspect-get-attribute elt "name") 'append))))
1308
1309 (defun dbus-introspect-get-argument (bus service path interface name arg)
1310 "Return argument ARG as XML object.
1311 NAME must be a \"method\" or \"signal\" object. ARG must be a string,
1312 element of the list returned by `dbus-introspect-get-argument-names'."
1313 (let ((elt (xml-get-children
1314 (or (dbus-introspect-get-method bus service path interface name)
1315 (dbus-introspect-get-signal bus service path interface name))
1316 'arg)))
1317 (while (and elt
1318 (not (string-equal
1319 arg (dbus-introspect-get-attribute (car elt) "name"))))
1320 (setq elt (cdr elt)))
1321 (car elt)))
1322
1323 (defun dbus-introspect-get-signature
1324 (bus service path interface name &optional direction)
1325 "Return signature of a `method' or `signal', represented by NAME, as string.
1326 If NAME is a `method', DIRECTION can be either \"in\" or \"out\".
1327 If DIRECTION is `nil', \"in\" is assumed.
1328
1329 If NAME is a `signal', and DIRECTION is non-`nil', DIRECTION must
1330 be \"out\"."
1331 ;; For methods, we use "in" as default direction.
1332 (let ((object (or (dbus-introspect-get-method
1333 bus service path interface name)
1334 (dbus-introspect-get-signal
1335 bus service path interface name))))
1336 (when (and (string-equal
1337 "method" (dbus-introspect-get-attribute object "name"))
1338 (not (stringp direction)))
1339 (setq direction "in"))
1340 ;; In signals, no direction is given.
1341 (when (string-equal "signal" (dbus-introspect-get-attribute object "name"))
1342 (setq direction nil))
1343 ;; Collect the signatures.
1344 (mapconcat
1345 (lambda (x)
1346 (let ((arg (dbus-introspect-get-argument
1347 bus service path interface name x)))
1348 (if (or (not (stringp direction))
1349 (string-equal
1350 direction
1351 (dbus-introspect-get-attribute arg "direction")))
1352 (dbus-introspect-get-attribute arg "type")
1353 "")))
1354 (dbus-introspect-get-argument-names bus service path interface name)
1355 "")))
1356
1357 \f
1358 ;;; D-Bus properties.
1359
1360 (defun dbus-get-property (bus service path interface property)
1361 "Return the value of PROPERTY of INTERFACE.
1362 It will be checked at BUS, SERVICE, PATH. The result can be any
1363 valid D-Bus value, or `nil' if there is no PROPERTY."
1364 (dbus-ignore-errors
1365 ;; "Get" returns a variant, so we must use the `car'.
1366 (car
1367 (dbus-call-method
1368 bus service path dbus-interface-properties
1369 "Get" :timeout 500 interface property))))
1370
1371 (defun dbus-set-property (bus service path interface property value)
1372 "Set value of PROPERTY of INTERFACE to VALUE.
1373 It will be checked at BUS, SERVICE, PATH. When the value has
1374 been set successful, the result is VALUE. Otherwise, `nil' is
1375 returned."
1376 (dbus-ignore-errors
1377 ;; "Set" requires a variant.
1378 (dbus-call-method
1379 bus service path dbus-interface-properties
1380 "Set" :timeout 500 interface property (list :variant value))
1381 ;; Return VALUE.
1382 (dbus-get-property bus service path interface property)))
1383
1384 (defun dbus-get-all-properties (bus service path interface)
1385 "Return all properties of INTERFACE at BUS, SERVICE, PATH.
1386 The result is a list of entries. Every entry is a cons of the
1387 name of the property, and its value. If there are no properties,
1388 `nil' is returned."
1389 (dbus-ignore-errors
1390 ;; "GetAll" returns "a{sv}".
1391 (let (result)
1392 (dolist (dict
1393 (dbus-call-method
1394 bus service path dbus-interface-properties
1395 "GetAll" :timeout 500 interface)
1396 result)
1397 (add-to-list 'result (cons (car dict) (cl-caadr dict)) 'append)))))
1398
1399 (defun dbus-register-property
1400 (bus service path interface property access value
1401 &optional emits-signal dont-register-service)
1402 "Register property PROPERTY on the D-Bus BUS.
1403
1404 BUS is either a Lisp symbol, `:system' or `:session', or a string
1405 denoting the bus address.
1406
1407 SERVICE is the D-Bus service name of the D-Bus. It must be a
1408 known name (See discussion of DONT-REGISTER-SERVICE below).
1409
1410 PATH is the D-Bus object path SERVICE is registered (See
1411 discussion of DONT-REGISTER-SERVICE below). INTERFACE is the
1412 name of the interface used at PATH, PROPERTY is the name of the
1413 property of INTERFACE. ACCESS indicates, whether the property
1414 can be changed by other services via D-Bus. It must be either
1415 the symbol `:read' or `:readwrite'. VALUE is the initial value
1416 of the property, it can be of any valid type (see
1417 `dbus-call-method' for details).
1418
1419 If PROPERTY already exists on PATH, it will be overwritten. For
1420 properties with access type `:read' this is the only way to
1421 change their values. Properties with access type `:readwrite'
1422 can be changed by `dbus-set-property'.
1423
1424 The interface \"org.freedesktop.DBus.Properties\" is added to
1425 PATH, including a default handler for the \"Get\", \"GetAll\" and
1426 \"Set\" methods of this interface. When EMITS-SIGNAL is non-nil,
1427 the signal \"PropertiesChanged\" is sent when the property is
1428 changed by `dbus-set-property'.
1429
1430 When DONT-REGISTER-SERVICE is non-nil, the known name SERVICE is
1431 not registered. This means that other D-Bus clients have no way
1432 of noticing the newly registered property. When interfaces are
1433 constructed incrementally by adding single methods or properties
1434 at a time, DONT-REGISTER-SERVICE can be used to prevent other
1435 clients from discovering the still incomplete interface."
1436 (unless (member access '(:read :readwrite))
1437 (signal 'wrong-type-argument (list "Access type invalid" access)))
1438
1439 ;; Add handlers for the three property-related methods.
1440 (dbus-register-method
1441 bus service path dbus-interface-properties "Get"
1442 'dbus-property-handler 'dont-register)
1443 (dbus-register-method
1444 bus service path dbus-interface-properties "GetAll"
1445 'dbus-property-handler 'dont-register)
1446 (dbus-register-method
1447 bus service path dbus-interface-properties "Set"
1448 'dbus-property-handler 'dont-register)
1449
1450 ;; Register SERVICE.
1451 (unless (or dont-register-service (member service (dbus-list-names bus)))
1452 (dbus-register-service bus service))
1453
1454 ;; Send the PropertiesChanged signal.
1455 (when emits-signal
1456 (dbus-send-signal
1457 bus service path dbus-interface-properties "PropertiesChanged"
1458 `((:dict-entry ,property (:variant ,value)))
1459 '(:array)))
1460
1461 ;; Create a hash table entry. We use nil for the unique name,
1462 ;; because the property might be accessed from anybody.
1463 (let ((key (list :property bus interface property))
1464 (val
1465 (list
1466 (list
1467 nil service path
1468 (cons
1469 (if emits-signal (list access :emits-signal) (list access))
1470 value)))))
1471 (puthash key val dbus-registered-objects-table)
1472
1473 ;; Return the object.
1474 (list key (list service path))))
1475
1476 (defun dbus-property-handler (&rest args)
1477 "Default handler for the \"org.freedesktop.DBus.Properties\" interface.
1478 It will be registered for all objects created by `dbus-register-property'."
1479 (let ((bus (dbus-event-bus-name last-input-event))
1480 (service (dbus-event-service-name last-input-event))
1481 (path (dbus-event-path-name last-input-event))
1482 (method (dbus-event-member-name last-input-event))
1483 (interface (car args))
1484 (property (cadr args)))
1485 (cond
1486 ;; "Get" returns a variant.
1487 ((string-equal method "Get")
1488 (let ((entry (gethash (list :property bus interface property)
1489 dbus-registered-objects-table)))
1490 (when (string-equal path (nth 2 (car entry)))
1491 `((:variant ,(cdar (last (car entry))))))))
1492
1493 ;; "Set" expects a variant.
1494 ((string-equal method "Set")
1495 (let* ((value (caar (cddr args)))
1496 (entry (gethash (list :property bus interface property)
1497 dbus-registered-objects-table))
1498 ;; The value of the hash table is a list; in case of
1499 ;; properties it contains just one element (UNAME SERVICE
1500 ;; PATH OBJECT). OBJECT is a cons cell of a list, which
1501 ;; contains a list of annotations (like :read,
1502 ;; :read-write, :emits-signal), and the value of the
1503 ;; property.
1504 (object (car (last (car entry)))))
1505 (unless (consp object)
1506 (signal 'dbus-error
1507 (list "Property not registered at path" property path)))
1508 (unless (member :readwrite (car object))
1509 (signal 'dbus-error
1510 (list "Property not writable at path" property path)))
1511 (puthash (list :property bus interface property)
1512 (list (append (butlast (car entry))
1513 (list (cons (car object) value))))
1514 dbus-registered-objects-table)
1515 ;; Send the "PropertiesChanged" signal.
1516 (when (member :emits-signal (car object))
1517 (dbus-send-signal
1518 bus service path dbus-interface-properties "PropertiesChanged"
1519 `((:dict-entry ,property (:variant ,value)))
1520 '(:array)))
1521 ;; Return empty reply.
1522 :ignore))
1523
1524 ;; "GetAll" returns "a{sv}".
1525 ((string-equal method "GetAll")
1526 (let (result)
1527 (maphash
1528 (lambda (key val)
1529 (when (and (equal (butlast key) (list :property bus interface))
1530 (string-equal path (nth 2 (car val)))
1531 (not (functionp (car (last (car val))))))
1532 (add-to-list
1533 'result
1534 (list :dict-entry
1535 (car (last key))
1536 (list :variant (cdar (last (car val))))))))
1537 dbus-registered-objects-table)
1538 ;; Return the result, or an empty array.
1539 (list :array (or result '(:signature "{sv}"))))))))
1540
1541 \f
1542 ;;; D-Bus object manager.
1543
1544 (defun dbus-get-all-managed-objects (bus service path)
1545 "Return all objects at BUS, SERVICE, PATH, and the children of PATH.
1546 The result is a list of objects. Every object is a cons of an
1547 existing path name, and the list of available interface objects.
1548 An interface object is another cons, which car is the interface
1549 name, and the cdr is the list of properties as returned by
1550 `dbus-get-all-properties' for that path and interface. Example:
1551
1552 \(dbus-get-all-managed-objects :session \"org.gnome.SettingsDaemon\" \"/\")
1553
1554 => \(\(\"/org/gnome/SettingsDaemon/MediaKeys\"
1555 \(\"org.gnome.SettingsDaemon.MediaKeys\")
1556 \(\"org.freedesktop.DBus.Peer\")
1557 \(\"org.freedesktop.DBus.Introspectable\")
1558 \(\"org.freedesktop.DBus.Properties\")
1559 \(\"org.freedesktop.DBus.ObjectManager\"))
1560 \(\"/org/gnome/SettingsDaemon/Power\"
1561 \(\"org.gnome.SettingsDaemon.Power.Keyboard\")
1562 \(\"org.gnome.SettingsDaemon.Power.Screen\")
1563 \(\"org.gnome.SettingsDaemon.Power\"
1564 \(\"Icon\" . \". GThemedIcon battery-full-charged-symbolic \")
1565 \(\"Tooltip\" . \"Laptop battery is charged\"))
1566 \(\"org.freedesktop.DBus.Peer\")
1567 \(\"org.freedesktop.DBus.Introspectable\")
1568 \(\"org.freedesktop.DBus.Properties\")
1569 \(\"org.freedesktop.DBus.ObjectManager\"))
1570 ...)
1571
1572 If possible, \"org.freedesktop.DBus.ObjectManager.GetManagedObjects\"
1573 is used for retrieving the information. Otherwise, the information
1574 is collected via \"org.freedesktop.DBus.Introspectable.Introspect\"
1575 and \"org.freedesktop.DBus.Properties.GetAll\", which is slow."
1576 (let ((result
1577 ;; Direct call. Fails, if the target does not support the
1578 ;; object manager interface.
1579 (dbus-ignore-errors
1580 (dbus-call-method
1581 bus service path dbus-interface-objectmanager
1582 "GetManagedObjects" :timeout 1000))))
1583
1584 (if result
1585 ;; Massage the returned structure.
1586 (dolist (entry result result)
1587 ;; "a{oa{sa{sv}}}".
1588 (dolist (entry1 (cdr entry))
1589 ;; "a{sa{sv}}".
1590 (dolist (entry2 entry1)
1591 ;; "a{sv}".
1592 (if (cadr entry2)
1593 ;; "sv".
1594 (dolist (entry3 (cadr entry2))
1595 (setcdr entry3 (cl-caadr entry3)))
1596 (setcdr entry2 nil)))))
1597
1598 ;; Fallback: collect the information. Slooow!
1599 (dolist (object
1600 (dbus-introspect-get-all-nodes bus service path)
1601 result)
1602 (let (result1)
1603 (dolist
1604 (interface
1605 (dbus-introspect-get-interface-names bus service object)
1606 result1)
1607 (add-to-list
1608 'result1
1609 (cons interface
1610 (dbus-get-all-properties bus service object interface))))
1611 (when result1
1612 (add-to-list 'result (cons object result1))))))))
1613
1614 (defun dbus-managed-objects-handler ()
1615 "Default handler for the \"org.freedesktop.DBus.ObjectManager\" interface.
1616 It will be registered for all objects created by `dbus-register-method'."
1617 (let* ((last-input-event last-input-event)
1618 (bus (dbus-event-bus-name last-input-event))
1619 (path (dbus-event-path-name last-input-event)))
1620 ;; "GetManagedObjects" returns "a{oa{sa{sv}}}".
1621 (let (interfaces result)
1622
1623 ;; Check for object path wildcard interfaces.
1624 (maphash
1625 (lambda (key val)
1626 (when (and (equal (butlast key 2) (list :method bus))
1627 (null (nth 2 (car-safe val))))
1628 (add-to-list 'interfaces (nth 2 key))))
1629 dbus-registered-objects-table)
1630
1631 ;; Check all registered object paths.
1632 (maphash
1633 (lambda (key val)
1634 (let ((object (or (nth 2 (car-safe val)) "")))
1635 (when (and (equal (butlast key 2) (list :method bus))
1636 (string-prefix-p path object))
1637 (dolist (interface (cons (nth 2 key) interfaces))
1638 (unless (assoc object result)
1639 (add-to-list 'result (list object)))
1640 (unless (assoc interface (cdr (assoc object result)))
1641 (setcdr
1642 (assoc object result)
1643 (append
1644 (list (cons
1645 interface
1646 ;; We simulate "org.freedesktop.DBus.Properties.GetAll"
1647 ;; by using an appropriate D-Bus event.
1648 (let ((last-input-event
1649 (append
1650 (butlast last-input-event 4)
1651 (list object dbus-interface-properties
1652 "GetAll" 'dbus-property-handler))))
1653 (dbus-property-handler interface))))
1654 (cdr (assoc object result)))))))))
1655 dbus-registered-objects-table)
1656
1657 ;; Return the result, or an empty array.
1658 (list
1659 :array
1660 (or
1661 (mapcar
1662 (lambda (x)
1663 (list
1664 :dict-entry :object-path (car x)
1665 (cons :array (mapcar (lambda (y) (cons :dict-entry y)) (cdr x)))))
1666 result)
1667 '(:signature "{oa{sa{sv}}}"))))))
1668
1669 \f
1670 ;; Initialize `:system' and `:session' buses. This adds their file
1671 ;; descriptors to input_wait_mask, in order to detect incoming
1672 ;; messages immediately.
1673 (when (featurep 'dbusbind)
1674 (dbus-ignore-errors
1675 (dbus-init-bus :system))
1676 (dbus-ignore-errors
1677 (dbus-init-bus :session)))
1678
1679 (provide 'dbus)
1680
1681 ;;; TODO:
1682
1683 ;; * Implement org.freedesktop.DBus.ObjectManager.InterfacesAdded and
1684 ;; org.freedesktop.DBus.ObjectManager.InterfacesRemoved.
1685
1686 ;;; dbus.el ends here