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