]> code.delx.au - gnu-emacs/blob - lisp/net/dbus.el
Merge from trunk
[gnu-emacs] / lisp / net / dbus.el
1 ;;; dbus.el --- Elisp bindings for D-Bus.
2
3 ;; Copyright (C) 2007, 2008, 2009, 2010 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 ;;; Code:
32
33 ;; D-Bus support in the Emacs core can be disabled with configuration
34 ;; option "--without-dbus". Declare used subroutines and variables.
35 (declare-function dbus-call-method "dbusbind.c")
36 (declare-function dbus-call-method-asynchronously "dbusbind.c")
37 (declare-function dbus-init-bus "dbusbind.c")
38 (declare-function dbus-method-return-internal "dbusbind.c")
39 (declare-function dbus-method-error-internal "dbusbind.c")
40 (declare-function dbus-register-signal "dbusbind.c")
41 (declare-function dbus-register-method "dbusbind.c")
42 (declare-function dbus-send-signal "dbusbind.c")
43 (defvar dbus-debug)
44 (defvar dbus-registered-objects-table)
45
46 ;; Pacify byte compiler.
47 (eval-when-compile
48 (require 'cl))
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 (defconst dbus-interface-dbus "org.freedesktop.DBus"
59 "The interface exported by the object with `dbus-service-dbus' and `dbus-path-dbus'.")
60
61 (defconst dbus-interface-peer (concat dbus-interface-dbus ".Peer")
62 "The interface for peer objects.")
63
64 (defconst dbus-interface-introspectable
65 (concat dbus-interface-dbus ".Introspectable")
66 "The interface supported by introspectable objects.")
67
68 (defconst dbus-interface-properties (concat dbus-interface-dbus ".Properties")
69 "The interface for property objects.")
70
71 (defconst dbus-service-emacs "org.gnu.Emacs"
72 "The well known service name of Emacs.")
73
74 (defconst dbus-path-emacs "/org/gnu/Emacs"
75 "The object path head used by Emacs.")
76
77 (defconst dbus-message-type-invalid 0
78 "This value is never a valid message type.")
79
80 (defconst dbus-message-type-method-call 1
81 "Message type of a method call message.")
82
83 (defconst dbus-message-type-method-return 2
84 "Message type of a method return message.")
85
86 (defconst dbus-message-type-error 3
87 "Message type of an error reply message.")
88
89 (defconst dbus-message-type-signal 4
90 "Message type of a signal message.")
91
92 (defmacro dbus-ignore-errors (&rest body)
93 "Execute BODY; signal D-Bus error when `dbus-debug' is non-nil.
94 Otherwise, return result of last form in BODY, or all other errors."
95 `(condition-case err
96 (progn ,@body)
97 (dbus-error (when dbus-debug (signal (car err) (cdr err))))))
98
99 (put 'dbus-ignore-errors 'lisp-indent-function 0)
100 (put 'dbus-ignore-errors 'edebug-form-spec '(form body))
101 (font-lock-add-keywords 'emacs-lisp-mode '("\\<dbus-ignore-errors\\>"))
102
103 (defvar dbus-event-error-hooks nil
104 "Functions to be called when a D-Bus error happens in the event handler.
105 Every function must accept two arguments, the event and the error variable
106 catched in `condition-case' by `dbus-error'.")
107
108 \f
109 ;;; Hash table of registered functions.
110
111 ;; We create it here. So we have a simple test in dbusbind.c, whether
112 ;; the Lisp code has been loaded.
113 (setq dbus-registered-objects-table (make-hash-table :test 'equal))
114
115 (defvar dbus-return-values-table (make-hash-table :test 'equal)
116 "Hash table for temporary storing arguments of reply messages.
117 A key in this hash table is a list (BUS SERIAL). BUS is either the
118 symbol `:system' or the symbol `:session'. SERIAL is the serial number
119 of the reply message. See `dbus-call-method-non-blocking-handler' and
120 `dbus-call-method-non-blocking'.")
121
122 (defun dbus-list-hash-table ()
123 "Returns all registered member registrations to D-Bus.
124 The return value is a list, with elements of kind (KEY . VALUE).
125 See `dbus-registered-objects-table' for a description of the
126 hash table."
127 (let (result)
128 (maphash
129 '(lambda (key value) (add-to-list 'result (cons key value) 'append))
130 dbus-registered-objects-table)
131 result))
132
133 (defun dbus-unregister-object (object)
134 "Unregister OBJECT from D-Bus.
135 OBJECT must be the result of a preceding `dbus-register-method',
136 `dbus-register-property' or `dbus-register-signal' call. It
137 returns `t' if OBJECT has been unregistered, `nil' otherwise.
138
139 When OBJECT identifies the last method or property, which is
140 registered for the respective service, Emacs releases its
141 association to the service from D-Bus."
142 ;; Check parameter.
143 (unless (and (consp object) (not (null (car object))) (consp (cdr object)))
144 (signal 'wrong-type-argument (list 'D-Bus object)))
145
146 ;; Find the corresponding entry in the hash table.
147 (let* ((key (car object))
148 (value (cdr object))
149 (entry (gethash key dbus-registered-objects-table))
150 ret)
151 ;; entry has the structure ((UNAME SERVICE PATH MEMBER) ...).
152 ;; value has the structure ((SERVICE PATH [HANDLER]) ...).
153 ;; MEMBER is either a string (the handler), or a cons cell (a
154 ;; property value). UNAME and property values are not taken into
155 ;; account for comparision.
156
157 ;; Loop over the registered functions.
158 (dolist (elt entry)
159 (when (equal
160 (car value)
161 (butlast (cdr elt) (- (length (cdr elt)) (length (car value)))))
162 ;; Compute new hash value. If it is empty, remove it from the
163 ;; hash table.
164 (unless (puthash key (delete elt entry) dbus-registered-objects-table)
165 (remhash key dbus-registered-objects-table))
166 (setq ret t)))
167 ;; Check, whether there is still a registered function or property
168 ;; for the given service. If not, unregister the service from the
169 ;; bus.
170 (dolist (elt entry)
171 (let ((service (cadr elt))
172 (bus (car key))
173 found)
174 (maphash
175 (lambda (k v)
176 (dolist (e v)
177 (ignore-errors
178 (when (and (equal bus (car k)) (string-equal service (cadr e)))
179 (setq found t)))))
180 dbus-registered-objects-table)
181 (unless found
182 (dbus-call-method
183 bus dbus-service-dbus dbus-path-dbus dbus-interface-dbus
184 "ReleaseName" service))))
185 ;; Return.
186 ret))
187
188 (defun dbus-unregister-service (bus service)
189 "Unregister all objects related to SERVICE from D-Bus BUS.
190 BUS must be either the symbol `:system' or the symbol `:session'.
191 SERVICE must be a known service name."
192 (maphash
193 (lambda (key value)
194 (dolist (elt value)
195 (ignore-errors
196 (when (and (equal bus (car key)) (string-equal service (cadr elt)))
197 (unless
198 (puthash key (delete elt value) dbus-registered-objects-table)
199 (remhash key dbus-registered-objects-table))))))
200 dbus-registered-objects-table)
201 (dbus-call-method
202 bus dbus-service-dbus dbus-path-dbus dbus-interface-dbus
203 "ReleaseName" service))
204
205 (defun dbus-call-method-non-blocking-handler (&rest args)
206 "Handler for reply messages of asynchronous D-Bus message calls.
207 It calls the function stored in `dbus-registered-objects-table'.
208 The result will be made available in `dbus-return-values-table'."
209 (puthash (list (dbus-event-bus-name last-input-event)
210 (dbus-event-serial-number last-input-event))
211 (if (= (length args) 1) (car args) args)
212 dbus-return-values-table))
213
214 (defun dbus-call-method-non-blocking
215 (bus service path interface method &rest args)
216 "Call METHOD on the D-Bus BUS, but don't block the event queue.
217 This is necessary for communicating to registered D-Bus methods,
218 which are running in the same Emacs process.
219
220 The arguments are the same as in `dbus-call-method'.
221
222 usage: (dbus-call-method-non-blocking
223 BUS SERVICE PATH INTERFACE METHOD
224 &optional :timeout TIMEOUT &rest ARGS)"
225
226 (let ((key
227 (apply
228 'dbus-call-method-asynchronously
229 bus service path interface method
230 'dbus-call-method-non-blocking-handler args)))
231 ;; Wait until `dbus-call-method-non-blocking-handler' has put the
232 ;; result into `dbus-return-values-table'.
233 (while (eq (gethash key dbus-return-values-table :ignore) :ignore)
234 (read-event nil nil 0.1))
235
236 ;; Cleanup `dbus-return-values-table'. Return the result.
237 (prog1
238 (gethash key dbus-return-values-table nil)
239 (remhash key dbus-return-values-table))))
240
241 (defun dbus-name-owner-changed-handler (&rest args)
242 "Reapplies all member registrations to D-Bus.
243 This handler is applied when a \"NameOwnerChanged\" signal has
244 arrived. SERVICE is the object name for which the name owner has
245 been changed. OLD-OWNER is the previous owner of SERVICE, or the
246 empty string if SERVICE was not owned yet. NEW-OWNER is the new
247 owner of SERVICE, or the empty string if SERVICE looses any name owner.
248
249 usage: (dbus-name-owner-changed-handler service old-owner new-owner)"
250 (save-match-data
251 ;; Check the arguments. We should silently ignore it when they
252 ;; are wrong.
253 (if (and (= (length args) 3)
254 (stringp (car args))
255 (stringp (cadr args))
256 (stringp (caddr args)))
257 (let ((service (car args))
258 (old-owner (cadr args))
259 (new-owner (caddr args)))
260 ;; Check whether SERVICE is a known name.
261 (when (not (string-match "^:" service))
262 (maphash
263 '(lambda (key value)
264 (dolist (elt value)
265 ;; key has the structure (BUS INTERFACE MEMBER).
266 ;; elt has the structure (UNAME SERVICE PATH HANDLER).
267 (when (string-equal old-owner (car elt))
268 ;; Remove old key, and add new entry with changed name.
269 (dbus-unregister-object (list key (cdr elt)))
270 ;; Maybe we could arrange the lists a little bit better
271 ;; that we don't need to extract every single element?
272 (dbus-register-signal
273 ;; BUS SERVICE PATH
274 (nth 0 key) (nth 1 elt) (nth 2 elt)
275 ;; INTERFACE MEMBER HANDLER
276 (nth 1 key) (nth 2 key) (nth 3 elt)))))
277 (copy-hash-table dbus-registered-objects-table))))
278 ;; The error is reported only in debug mode.
279 (when dbus-debug
280 (signal
281 'dbus-error
282 (cons
283 (format "Wrong arguments of %s.NameOwnerChanged" dbus-interface-dbus)
284 args))))))
285
286 ;; Register the handler.
287 (when nil ;ignore-errors
288 (dbus-register-signal
289 :system dbus-service-dbus dbus-path-dbus dbus-interface-dbus
290 "NameOwnerChanged" 'dbus-name-owner-changed-handler)
291 (dbus-register-signal
292 :session dbus-service-dbus dbus-path-dbus dbus-interface-dbus
293 "NameOwnerChanged" 'dbus-name-owner-changed-handler))
294
295 \f
296 ;;; D-Bus type conversion.
297
298 (defun dbus-string-to-byte-array (string)
299 "Transforms STRING to list (:array :byte c1 :byte c2 ...).
300 STRING shall be UTF8 coded."
301 (if (zerop (length string))
302 '(:array :signature "y")
303 (let (result)
304 (dolist (elt (string-to-list string) (append '(:array) result))
305 (setq result (append result (list :byte elt)))))))
306
307 (defun dbus-byte-array-to-string (byte-array)
308 "Transforms BYTE-ARRAY into UTF8 coded string.
309 BYTE-ARRAY must be a list of structure (c1 c2 ...)."
310 (apply 'string byte-array))
311
312 (defun dbus-escape-as-identifier (string)
313 "Escape an arbitrary STRING so it follows the rules for a C identifier.
314 The escaped string can be used as object path component, interface element
315 component, bus name component or member name in D-Bus.
316
317 The escaping consists of replacing all non-alphanumerics, and the
318 first character if it's a digit, with an underscore and two
319 lower-case hex digits:
320
321 \"0123abc_xyz\\x01\\xff\" -> \"_30123abc_5fxyz_01_ff\"
322
323 i.e. similar to URI encoding, but with \"_\" taking the role of \"%\",
324 and a smaller allowed set. As a special case, \"\" is escaped to
325 \"_\".
326
327 Returns the escaped string. Algorithm taken from
328 telepathy-glib's `tp-escape-as-identifier'."
329 (if (zerop (length string))
330 "_"
331 (replace-regexp-in-string
332 "^[0-9]\\|[^A-Za-z0-9]"
333 (lambda (x) (format "_%2x" (aref x 0)))
334 string)))
335
336 (defun dbus-unescape-from-identifier (string)
337 "Retrieve the original string from the encoded STRING.
338 STRING must have been coded with `dbus-escape-as-identifier'"
339 (if (string-equal string "_")
340 ""
341 (replace-regexp-in-string
342 "_.."
343 (lambda (x) (format "%c" (string-to-number (substring x 1) 16)))
344 string)))
345
346 \f
347 ;;; D-Bus events.
348
349 (defun dbus-check-event (event)
350 "Checks whether EVENT is a well formed D-Bus event.
351 EVENT is a list which starts with symbol `dbus-event':
352
353 (dbus-event BUS TYPE SERIAL SERVICE PATH INTERFACE MEMBER HANDLER &rest ARGS)
354
355 BUS identifies the D-Bus the message is coming from. It is
356 either the symbol `:system' or the symbol `:session'. TYPE is
357 the D-Bus message type which has caused the event, SERIAL is the
358 serial number of the received D-Bus message. SERVICE and PATH
359 are the unique name and the object path of the D-Bus object
360 emitting the message. INTERFACE and MEMBER denote the message
361 which has been sent. HANDLER is the function which has been
362 registered for this message. ARGS are the arguments passed to
363 HANDLER, when it is called during event handling in
364 `dbus-handle-event'.
365
366 This function raises a `dbus-error' signal in case the event is
367 not well formed."
368 (when dbus-debug (message "DBus-Event %s" event))
369 (unless (and (listp event)
370 (eq (car event) 'dbus-event)
371 ;; Bus symbol.
372 (symbolp (nth 1 event))
373 ;; Type.
374 (and (natnump (nth 2 event))
375 (< dbus-message-type-invalid (nth 2 event)))
376 ;; Serial.
377 (natnump (nth 3 event))
378 ;; Service.
379 (or (= dbus-message-type-method-return (nth 2 event))
380 (= dbus-message-type-error (nth 2 event))
381 (stringp (nth 4 event)))
382 ;; Object path.
383 (or (= dbus-message-type-method-return (nth 2 event))
384 (= dbus-message-type-error (nth 2 event))
385 (stringp (nth 5 event)))
386 ;; Interface.
387 (or (= dbus-message-type-method-return (nth 2 event))
388 (= dbus-message-type-error (nth 2 event))
389 (stringp (nth 6 event)))
390 ;; Member.
391 (or (= dbus-message-type-method-return (nth 2 event))
392 (= dbus-message-type-error (nth 2 event))
393 (stringp (nth 7 event)))
394 ;; Handler.
395 (functionp (nth 8 event)))
396 (signal 'dbus-error (list "Not a valid D-Bus event" event))))
397
398 ;;;###autoload
399 (defun dbus-handle-event (event)
400 "Handle events from the D-Bus.
401 EVENT is a D-Bus event, see `dbus-check-event'. HANDLER, being
402 part of the event, is called with arguments ARGS.
403 If the HANDLER returns a `dbus-error', it is propagated as return message."
404 (interactive "e")
405 (condition-case err
406 (let (result)
407 ;; We ignore not well-formed events.
408 (dbus-check-event event)
409 ;; Error messages must be propagated.
410 (when (= dbus-message-type-error (nth 2 event))
411 (signal 'dbus-error (nthcdr 9 event)))
412 ;; Apply the handler.
413 (setq result (apply (nth 8 event) (nthcdr 9 event)))
414 ;; Return a message when it is a message call.
415 (when (= dbus-message-type-method-call (nth 2 event))
416 (dbus-ignore-errors
417 (if (eq result :ignore)
418 (dbus-method-return-internal
419 (nth 1 event) (nth 3 event) (nth 4 event))
420 (apply 'dbus-method-return-internal
421 (nth 1 event) (nth 3 event) (nth 4 event)
422 (if (consp result) result (list result)))))))
423 ;; Error handling.
424 (dbus-error
425 ;; Return an error message when it is a message call.
426 (when (= dbus-message-type-method-call (nth 2 event))
427 (dbus-ignore-errors
428 (dbus-method-error-internal
429 (nth 1 event) (nth 3 event) (nth 4 event) (cadr err))))
430 ;; Propagate D-Bus error messages.
431 (run-hook-with-args 'dbus-event-error-hooks event err)
432 (when (or dbus-debug (= dbus-message-type-error (nth 2 event)))
433 (signal (car err) (cdr err))))))
434
435 (defun dbus-event-bus-name (event)
436 "Return the bus name the event is coming from.
437 The result is either the symbol `:system' or the symbol `:session'.
438 EVENT is a D-Bus event, see `dbus-check-event'. This function
439 raises a `dbus-error' signal in case the event is not well formed."
440 (dbus-check-event event)
441 (nth 1 event))
442
443 (defun dbus-event-message-type (event)
444 "Return the message type of the corresponding D-Bus message.
445 The result is a number. EVENT is a D-Bus event, see
446 `dbus-check-event'. This function raises a `dbus-error' signal
447 in case the event is not well formed."
448 (dbus-check-event event)
449 (nth 2 event))
450
451 (defun dbus-event-serial-number (event)
452 "Return the serial number of the corresponding D-Bus message.
453 The result is a number. The serial number is needed for
454 generating a reply message. EVENT is a D-Bus event, see
455 `dbus-check-event'. This function raises a `dbus-error' signal
456 in case the event is not well formed."
457 (dbus-check-event event)
458 (nth 3 event))
459
460 (defun dbus-event-service-name (event)
461 "Return the name of the D-Bus object the event is coming from.
462 The result is a string. EVENT is a D-Bus event, see `dbus-check-event'.
463 This function raises a `dbus-error' signal in case the event is
464 not well formed."
465 (dbus-check-event event)
466 (nth 4 event))
467
468 (defun dbus-event-path-name (event)
469 "Return the object path of the D-Bus object the event is coming from.
470 The result is a string. EVENT is a D-Bus event, see `dbus-check-event'.
471 This function raises a `dbus-error' signal in case the event is
472 not well formed."
473 (dbus-check-event event)
474 (nth 5 event))
475
476 (defun dbus-event-interface-name (event)
477 "Return the interface name of the D-Bus object the event is coming from.
478 The result is a string. EVENT is a D-Bus event, see `dbus-check-event'.
479 This function raises a `dbus-error' signal in case the event is
480 not well formed."
481 (dbus-check-event event)
482 (nth 6 event))
483
484 (defun dbus-event-member-name (event)
485 "Return the member name the event is coming from.
486 It is either a signal name or a method name. The result is is a
487 string. EVENT is a D-Bus event, see `dbus-check-event'. This
488 function raises a `dbus-error' signal in case the event is not
489 well formed."
490 (dbus-check-event event)
491 (nth 7 event))
492
493 \f
494 ;;; D-Bus registered names.
495
496 (defun dbus-list-activatable-names ()
497 "Return the D-Bus service names which can be activated as list.
498 The result is a list of strings, which is `nil' when there are no
499 activatable service names at all."
500 (dbus-ignore-errors
501 (dbus-call-method
502 :system dbus-service-dbus
503 dbus-path-dbus dbus-interface-dbus "ListActivatableNames")))
504
505 (defun dbus-list-names (bus)
506 "Return the service names registered at D-Bus BUS.
507 The result is a list of strings, which is `nil' when there are no
508 registered service names at all. Well known names are strings
509 like \"org.freedesktop.DBus\". Names starting with \":\" are
510 unique names for services."
511 (dbus-ignore-errors
512 (dbus-call-method
513 bus dbus-service-dbus dbus-path-dbus dbus-interface-dbus "ListNames")))
514
515 (defun dbus-list-known-names (bus)
516 "Retrieve all services which correspond to a known name in BUS.
517 A service has a known name if it doesn't start with \":\"."
518 (let (result)
519 (dolist (name (dbus-list-names bus) result)
520 (unless (string-equal ":" (substring name 0 1))
521 (add-to-list 'result name 'append)))))
522
523 (defun dbus-list-queued-owners (bus service)
524 "Return the unique names registered at D-Bus BUS and queued for SERVICE.
525 The result is a list of strings, or `nil' when there are no
526 queued name owners service names at all."
527 (dbus-ignore-errors
528 (dbus-call-method
529 bus dbus-service-dbus dbus-path-dbus
530 dbus-interface-dbus "ListQueuedOwners" service)))
531
532 (defun dbus-get-name-owner (bus service)
533 "Return the name owner of SERVICE registered at D-Bus BUS.
534 The result is either a string, or `nil' if there is no name owner."
535 (dbus-ignore-errors
536 (dbus-call-method
537 bus dbus-service-dbus dbus-path-dbus
538 dbus-interface-dbus "GetNameOwner" service)))
539
540 (defun dbus-ping (bus service &optional timeout)
541 "Check whether SERVICE is registered for D-Bus BUS.
542 TIMEOUT, a nonnegative integer, specifies the maximum number of
543 milliseconds `dbus-ping' must return. The default value is 25,000.
544
545 Note, that this autoloads SERVICE if it is not running yet. If
546 it shall be checked whether SERVICE is already running, one shall
547 apply
548
549 \(member service \(dbus-list-known-names bus))"
550 ;; "Ping" raises a D-Bus error if SERVICE does not exist.
551 ;; Otherwise, it returns silently with `nil'.
552 (condition-case nil
553 (not
554 (if (natnump timeout)
555 (dbus-call-method
556 bus service dbus-path-dbus dbus-interface-peer
557 "Ping" :timeout timeout)
558 (dbus-call-method
559 bus service dbus-path-dbus dbus-interface-peer "Ping")))
560 (dbus-error nil)))
561
562 \f
563 ;;; D-Bus introspection.
564
565 (defun dbus-introspect (bus service path)
566 "Return all interfaces and sub-nodes of SERVICE,
567 registered at object path PATH at bus BUS.
568
569 BUS must be either the symbol `:system' or the symbol `:session'.
570 SERVICE must be a known service name, and PATH must be a valid
571 object path. The last two parameters are strings. The result,
572 the introspection data, is a string in XML format."
573 ;; We don't want to raise errors. `dbus-call-method-non-blocking'
574 ;; is used, because the handler can be registered in our Emacs
575 ;; instance; caller an callee would block each other.
576 (dbus-ignore-errors
577 (funcall
578 (if noninteractive 'dbus-call-method 'dbus-call-method-non-blocking)
579 bus service path dbus-interface-introspectable "Introspect")))
580
581 (defun dbus-introspect-xml (bus service path)
582 "Return the introspection data of SERVICE in D-Bus BUS at object path PATH.
583 The data are a parsed list. The root object is a \"node\",
584 representing the object path PATH. The root object can contain
585 \"interface\" and further \"node\" objects."
586 ;; We don't want to raise errors.
587 (xml-node-name
588 (ignore-errors
589 (with-temp-buffer
590 (insert (dbus-introspect bus service path))
591 (xml-parse-region (point-min) (point-max))))))
592
593 (defun dbus-introspect-get-attribute (object attribute)
594 "Return the ATTRIBUTE value of D-Bus introspection OBJECT.
595 ATTRIBUTE must be a string according to the attribute names in
596 the D-Bus specification."
597 (xml-get-attribute-or-nil object (intern attribute)))
598
599 (defun dbus-introspect-get-node-names (bus service path)
600 "Return all node names of SERVICE in D-Bus BUS at object path PATH.
601 It returns a list of strings. The node names stand for further
602 object paths of the D-Bus service."
603 (let ((object (dbus-introspect-xml bus service path))
604 result)
605 (dolist (elt (xml-get-children object 'node) result)
606 (add-to-list
607 'result (dbus-introspect-get-attribute elt "name") 'append))))
608
609 (defun dbus-introspect-get-all-nodes (bus service path)
610 "Return all node names of SERVICE in D-Bus BUS at object path PATH.
611 It returns a list of strings, which are further object paths of SERVICE."
612 (let ((result (list path)))
613 (dolist (elt
614 (dbus-introspect-get-node-names bus service path)
615 result)
616 (setq elt (expand-file-name elt path))
617 (setq result
618 (append result (dbus-introspect-get-all-nodes bus service elt))))))
619
620 (defun dbus-introspect-get-interface-names (bus service path)
621 "Return all interface names of SERVICE in D-Bus BUS at object path PATH.
622 It returns a list of strings.
623
624 There will be always the default interface
625 \"org.freedesktop.DBus.Introspectable\". Another default
626 interface is \"org.freedesktop.DBus.Properties\". If present,
627 \"interface\" objects can also have \"property\" objects as
628 children, beside \"method\" and \"signal\" objects."
629 (let ((object (dbus-introspect-xml bus service path))
630 result)
631 (dolist (elt (xml-get-children object 'interface) result)
632 (add-to-list
633 'result (dbus-introspect-get-attribute elt "name") 'append))))
634
635 (defun dbus-introspect-get-interface (bus service path interface)
636 "Return the INTERFACE of SERVICE in D-Bus BUS at object path PATH.
637 The return value is an XML object. INTERFACE must be a string,
638 element of the list returned by `dbus-introspect-get-interface-names'.
639 The resulting \"interface\" object can contain \"method\", \"signal\",
640 \"property\" and \"annotation\" children."
641 (let ((elt (xml-get-children
642 (dbus-introspect-xml bus service path) 'interface)))
643 (while (and elt
644 (not (string-equal
645 interface
646 (dbus-introspect-get-attribute (car elt) "name"))))
647 (setq elt (cdr elt)))
648 (car elt)))
649
650 (defun dbus-introspect-get-method-names (bus service path interface)
651 "Return a list of strings of all method names of INTERFACE.
652 SERVICE is a service of D-Bus BUS at object path PATH."
653 (let ((object (dbus-introspect-get-interface bus service path interface))
654 result)
655 (dolist (elt (xml-get-children object 'method) result)
656 (add-to-list
657 'result (dbus-introspect-get-attribute elt "name") 'append))))
658
659 (defun dbus-introspect-get-method (bus service path interface method)
660 "Return method METHOD of interface INTERFACE as XML object.
661 It must be located at SERVICE in D-Bus BUS at object path PATH.
662 METHOD must be a string, element of the list returned by
663 `dbus-introspect-get-method-names'. The resulting \"method\"
664 object can contain \"arg\" and \"annotation\" children."
665 (let ((elt (xml-get-children
666 (dbus-introspect-get-interface bus service path interface)
667 'method)))
668 (while (and elt
669 (not (string-equal
670 method (dbus-introspect-get-attribute (car elt) "name"))))
671 (setq elt (cdr elt)))
672 (car elt)))
673
674 (defun dbus-introspect-get-signal-names (bus service path interface)
675 "Return a list of strings of all signal names of INTERFACE.
676 SERVICE is a service of D-Bus BUS at object path PATH."
677 (let ((object (dbus-introspect-get-interface bus service path interface))
678 result)
679 (dolist (elt (xml-get-children object 'signal) result)
680 (add-to-list
681 'result (dbus-introspect-get-attribute elt "name") 'append))))
682
683 (defun dbus-introspect-get-signal (bus service path interface signal)
684 "Return signal SIGNAL of interface INTERFACE as XML object.
685 It must be located at SERVICE in D-Bus BUS at object path PATH.
686 SIGNAL must be a string, element of the list returned by
687 `dbus-introspect-get-signal-names'. The resulting \"signal\"
688 object can contain \"arg\" and \"annotation\" children."
689 (let ((elt (xml-get-children
690 (dbus-introspect-get-interface bus service path interface)
691 'signal)))
692 (while (and elt
693 (not (string-equal
694 signal (dbus-introspect-get-attribute (car elt) "name"))))
695 (setq elt (cdr elt)))
696 (car elt)))
697
698 (defun dbus-introspect-get-property-names (bus service path interface)
699 "Return a list of strings of all property names of INTERFACE.
700 SERVICE is a service of D-Bus BUS at object path PATH."
701 (let ((object (dbus-introspect-get-interface bus service path interface))
702 result)
703 (dolist (elt (xml-get-children object 'property) result)
704 (add-to-list
705 'result (dbus-introspect-get-attribute elt "name") 'append))))
706
707 (defun dbus-introspect-get-property (bus service path interface property)
708 "This function returns PROPERTY of INTERFACE as XML object.
709 It must be located at SERVICE in D-Bus BUS at object path PATH.
710 PROPERTY must be a string, element of the list returned by
711 `dbus-introspect-get-property-names'. The resulting PROPERTY
712 object can contain \"annotation\" children."
713 (let ((elt (xml-get-children
714 (dbus-introspect-get-interface bus service path interface)
715 'property)))
716 (while (and elt
717 (not (string-equal
718 property
719 (dbus-introspect-get-attribute (car elt) "name"))))
720 (setq elt (cdr elt)))
721 (car elt)))
722
723 (defun dbus-introspect-get-annotation-names
724 (bus service path interface &optional name)
725 "Return all annotation names as list of strings.
726 If NAME is `nil', the annotations are children of INTERFACE,
727 otherwise NAME must be a \"method\", \"signal\", or \"property\"
728 object, where the annotations belong to."
729 (let ((object
730 (if name
731 (or (dbus-introspect-get-method bus service path interface name)
732 (dbus-introspect-get-signal bus service path interface name)
733 (dbus-introspect-get-property bus service path interface name))
734 (dbus-introspect-get-interface bus service path interface)))
735 result)
736 (dolist (elt (xml-get-children object 'annotation) result)
737 (add-to-list
738 'result (dbus-introspect-get-attribute elt "name") 'append))))
739
740 (defun dbus-introspect-get-annotation
741 (bus service path interface name annotation)
742 "Return ANNOTATION as XML object.
743 If NAME is `nil', ANNOTATION is a child of INTERFACE, otherwise
744 NAME must be the name of a \"method\", \"signal\", or
745 \"property\" object, where the ANNOTATION belongs to."
746 (let ((elt (xml-get-children
747 (if name
748 (or (dbus-introspect-get-method
749 bus service path interface name)
750 (dbus-introspect-get-signal
751 bus service path interface name)
752 (dbus-introspect-get-property
753 bus service path interface name))
754 (dbus-introspect-get-interface bus service path interface))
755 'annotation)))
756 (while (and elt
757 (not (string-equal
758 annotation
759 (dbus-introspect-get-attribute (car elt) "name"))))
760 (setq elt (cdr elt)))
761 (car elt)))
762
763 (defun dbus-introspect-get-argument-names (bus service path interface name)
764 "Return a list of all argument names as list of strings.
765 NAME must be a \"method\" or \"signal\" object.
766
767 Argument names are optional, the function can return `nil'
768 therefore, even if the method or signal has arguments."
769 (let ((object
770 (or (dbus-introspect-get-method bus service path interface name)
771 (dbus-introspect-get-signal bus service path interface name)))
772 result)
773 (dolist (elt (xml-get-children object 'arg) result)
774 (add-to-list
775 'result (dbus-introspect-get-attribute elt "name") 'append))))
776
777 (defun dbus-introspect-get-argument (bus service path interface name arg)
778 "Return argument ARG as XML object.
779 NAME must be a \"method\" or \"signal\" object. ARG must be a string,
780 element of the list returned by `dbus-introspect-get-argument-names'."
781 (let ((elt (xml-get-children
782 (or (dbus-introspect-get-method bus service path interface name)
783 (dbus-introspect-get-signal bus service path interface name))
784 'arg)))
785 (while (and elt
786 (not (string-equal
787 arg (dbus-introspect-get-attribute (car elt) "name"))))
788 (setq elt (cdr elt)))
789 (car elt)))
790
791 (defun dbus-introspect-get-signature
792 (bus service path interface name &optional direction)
793 "Return signature of a `method' or `signal', represented by NAME, as string.
794 If NAME is a `method', DIRECTION can be either \"in\" or \"out\".
795 If DIRECTION is `nil', \"in\" is assumed.
796
797 If NAME is a `signal', and DIRECTION is non-`nil', DIRECTION must
798 be \"out\"."
799 ;; For methods, we use "in" as default direction.
800 (let ((object (or (dbus-introspect-get-method
801 bus service path interface name)
802 (dbus-introspect-get-signal
803 bus service path interface name))))
804 (when (and (string-equal
805 "method" (dbus-introspect-get-attribute object "name"))
806 (not (stringp direction)))
807 (setq direction "in"))
808 ;; In signals, no direction is given.
809 (when (string-equal "signal" (dbus-introspect-get-attribute object "name"))
810 (setq direction nil))
811 ;; Collect the signatures.
812 (mapconcat
813 '(lambda (x)
814 (let ((arg (dbus-introspect-get-argument
815 bus service path interface name x)))
816 (if (or (not (stringp direction))
817 (string-equal
818 direction
819 (dbus-introspect-get-attribute arg "direction")))
820 (dbus-introspect-get-attribute arg "type")
821 "")))
822 (dbus-introspect-get-argument-names bus service path interface name)
823 "")))
824
825 \f
826 ;;; D-Bus properties.
827
828 (defun dbus-get-property (bus service path interface property)
829 "Return the value of PROPERTY of INTERFACE.
830 It will be checked at BUS, SERVICE, PATH. The result can be any
831 valid D-Bus value, or `nil' if there is no PROPERTY."
832 (dbus-ignore-errors
833 ;; "Get" returns a variant, so we must use the `car'.
834 (car
835 (funcall
836 (if noninteractive 'dbus-call-method 'dbus-call-method-non-blocking)
837 bus service path dbus-interface-properties
838 "Get" :timeout 500 interface property))))
839
840 (defun dbus-set-property (bus service path interface property value)
841 "Set value of PROPERTY of INTERFACE to VALUE.
842 It will be checked at BUS, SERVICE, PATH. When the value has
843 been set successful, the result is VALUE. Otherwise, `nil' is
844 returned."
845 (dbus-ignore-errors
846 ;; "Set" requires a variant.
847 (funcall
848 (if noninteractive 'dbus-call-method 'dbus-call-method-non-blocking)
849 bus service path dbus-interface-properties
850 "Set" :timeout 500 interface property (list :variant value))
851 ;; Return VALUE.
852 (dbus-get-property bus service path interface property)))
853
854 (defun dbus-get-all-properties (bus service path interface)
855 "Return all properties of INTERFACE at BUS, SERVICE, PATH.
856 The result is a list of entries. Every entry is a cons of the
857 name of the property, and its value. If there are no properties,
858 `nil' is returned."
859 (dbus-ignore-errors
860 ;; "GetAll" returns "a{sv}".
861 (let (result)
862 (dolist (dict
863 (funcall
864 (if noninteractive
865 'dbus-call-method
866 'dbus-call-method-non-blocking)
867 bus service path dbus-interface-properties
868 "GetAll" :timeout 500 interface)
869 result)
870 (add-to-list 'result (cons (car dict) (caadr dict)) 'append)))))
871
872 (defun dbus-register-property
873 (bus service path interface property access value &optional emits-signal)
874 "Register property PROPERTY on the D-Bus BUS.
875
876 BUS is either the symbol `:system' or the symbol `:session'.
877
878 SERVICE is the D-Bus service name of the D-Bus. It must be a
879 known name.
880
881 PATH is the D-Bus object path SERVICE is registered. INTERFACE
882 is the name of the interface used at PATH, PROPERTY is the name
883 of the property of INTERFACE. ACCESS indicates, whether the
884 property can be changed by other services via D-Bus. It must be
885 either the symbol `:read' or `:readwrite'. VALUE is the initial
886 value of the property, it can be of any valid type (see
887 `dbus-call-method' for details).
888
889 If PROPERTY already exists on PATH, it will be overwritten. For
890 properties with access type `:read' this is the only way to
891 change their values. Properties with access type `:readwrite'
892 can be changed by `dbus-set-property'.
893
894 The interface \"org.freedesktop.DBus.Properties\" is added to
895 PATH, including a default handler for the \"Get\", \"GetAll\" and
896 \"Set\" methods of this interface. When EMITS-SIGNAL is non-nil,
897 the signal \"PropertiesChanged\" is sent when the property is
898 changed by `dbus-set-property'."
899 (unless (member access '(:read :readwrite))
900 (signal 'dbus-error (list "Access type invalid" access)))
901
902 ;; Register SERVICE.
903 (unless (member service (dbus-list-names bus))
904 (dbus-call-method
905 bus dbus-service-dbus dbus-path-dbus dbus-interface-dbus
906 "RequestName" service 0))
907
908 ;; Add the handler. We use `dbus-service-emacs' as service name, in
909 ;; order to let unregister SERVICE despite of this default handler.
910 (dbus-register-method
911 bus service path dbus-interface-properties "Get" 'dbus-property-handler)
912 (dbus-register-method
913 bus service path dbus-interface-properties "GetAll" 'dbus-property-handler)
914 (dbus-register-method
915 bus service path dbus-interface-properties "Set" 'dbus-property-handler)
916
917 ;; Send the PropertiesChanged signal.
918 (when emits-signal
919 (dbus-send-signal
920 bus service path dbus-interface-properties "PropertiesChanged"
921 (list (list :dict-entry property (list :variant value)))
922 '(:array)))
923
924 ;; Create a hash table entry. We use nil for the unique name,
925 ;; because the property might be accessed from anybody.
926 (let ((key (list bus interface property))
927 (val
928 (list
929 (list
930 nil service path
931 (cons
932 (if emits-signal (list access :emits-signal) (list access))
933 value)))))
934 (puthash key val dbus-registered-objects-table)
935
936 ;; Return the object.
937 (list key (list service path))))
938
939 (defun dbus-property-handler (&rest args)
940 "Default handler for the \"org.freedesktop.DBus.Properties\" interface.
941 It will be registered for all objects created by `dbus-register-object'."
942 (let ((bus (dbus-event-bus-name last-input-event))
943 (service (dbus-event-service-name last-input-event))
944 (path (dbus-event-path-name last-input-event))
945 (method (dbus-event-member-name last-input-event))
946 (interface (car args))
947 (property (cadr args)))
948 (cond
949 ;; "Get" returns a variant.
950 ((string-equal method "Get")
951 (let ((entry (gethash (list bus interface property)
952 dbus-registered-objects-table)))
953 (when (string-equal path (nth 2 (car entry)))
954 (list (list :variant (cdar (last (car entry))))))))
955
956 ;; "Set" expects a variant.
957 ((string-equal method "Set")
958 (let* ((value (caar (cddr args)))
959 (entry (gethash (list bus interface property)
960 dbus-registered-objects-table))
961 ;; The value of the hash table is a list; in case of
962 ;; properties it contains just one element (UNAME SERVICE
963 ;; PATH OBJECT). OBJECT is a cons cell of a list, which
964 ;; contains a list of annotations (like :read,
965 ;; :read-write, :emits-signal), and the value of the
966 ;; property.
967 (object (car (last (car entry)))))
968 (unless (consp object)
969 (signal 'dbus-error
970 (list "Property not registered at path" property path)))
971 (unless (member :readwrite (car object))
972 (signal 'dbus-error
973 (list "Property not writable at path" property path)))
974 (puthash (list bus interface property)
975 (list (append (butlast (car entry))
976 (list (cons (car object) value))))
977 dbus-registered-objects-table)
978 ;; Send the "PropertiesChanged" signal.
979 (when (member :emits-signal (car object))
980 (dbus-send-signal
981 bus service path dbus-interface-properties "PropertiesChanged"
982 (list (list :dict-entry property (list :variant value)))
983 '(:array)))
984 ;; Return empty reply.
985 :ignore))
986
987 ;; "GetAll" returns "a{sv}".
988 ((string-equal method "GetAll")
989 (let (result)
990 (maphash
991 (lambda (key val)
992 (when (and (equal (butlast key) (list bus interface))
993 (string-equal path (nth 2 (car val)))
994 (not (functionp (car (last (car val))))))
995 (add-to-list
996 'result
997 (list :dict-entry
998 (car (last key))
999 (list :variant (cdar (last (car val))))))))
1000 dbus-registered-objects-table)
1001 (list result))))))
1002
1003 \f
1004 ;; Initialize :system and :session buses. This adds their file
1005 ;; descriptors to input_wait_mask, in order to detect incoming
1006 ;; messages immediately.
1007 (when (featurep 'dbusbind)
1008 (dbus-ignore-errors
1009 (dbus-init-bus :system)
1010 (dbus-init-bus :session)))
1011
1012 (provide 'dbus)
1013
1014 ;; arch-tag: a47caf84-9162-4811-90cc-5d388e37b9bd
1015 ;;; dbus.el ends here