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