D-Bus integration in Emacs
**************************

This manual documents an API for usage of D-Bus in Emacs. (D-Bus is not enabled by default.  You must run ./configure --with-dbus in Emacs' top level directory, before you compile Emacs.)  D-Bus is a message bus system, a simple way for applications to talk to one another.  An overview of D-Bus can be found at http://dbus.freedesktop.org/.

Copyright © 2007 Free Software Foundation, Inc.

     Permission is granted to copy, distribute and/or modify this document under the terms of the GNU Free Documentation License, Version 1.2 or any later version published by the Free Software Foundation; with no Invariant Sections, with the Front-Cover texts being ``A GNU Manual'', and with the Back-Cover Texts as in (a) below.  A copy of the license is included in the section entitled ``GNU Free Documentation License'' in the Emacs manual.

     (a) The FSF's Back-Cover Text is: ``You have freedom to copy and modify this GNU Manual, like GNU software.  Copies published by the Free Software Foundation raise funds for GNU development.''

     This document is part of a collection distributed under the GNU Free Documentation License.  If you want to distribute this document separately from the collection, you can do so by adding a copy of the license to the document, as described in section 6 of the license.

An overview of D-Bus
********************

D-Bus is an inter-process communication mechanism for applications residing on the same host.  The communication is based on messages.  Data in the messages is carried in a structured way, it is not just a byte stream.

The communication is connection oriented to two kinds of message buses: a so called system bus, and a session bus.  On a given machine, there is always one single system bus for miscellaneous system-wide communication, like changing of hardware configuration. On the other hand, the session bus is always related to a single user's session.

Every client application, which is connected to a bus, registers under a unique name at the bus.  This name is used for identifying the client application.  Such a unique name starts always with a colon, and looks like :1.42.

Additionally, a client application can register itself to a so called known name, which is a series of identifiers separated by dots, as in org.gnu.Emacs.  If several applications register to the same known name, these registrations are queued, and only the first application which has registered for the known name is reachable via this name.  If this application disconnects from the bus, the next queued unique name becomes the owner of this known name.

An application can install one or several objects under its name. Such objects are identified by an object path, which looks similar to paths in a filesystem.  An example of such an object path could be /org/gnu/Emacs/.

Applications might send a request to an object, that means sending a message with some data as input parameters, and receiving a message from that object with the result of this message, the output parameters.  Such a request is called method in D-Bus.

The other form of communication are signals.  The underlying message is emitted from an object and will be received by all other applications which have registered for such a signal.

All methods and signals an object supports are called interface of the object.  Interfaces are specified under a hierarchical name in D-Bus; an object can support several interfaces.  Such an interface name could be org.gnu.Emacs.TextEditor or org.gnu.Emacs.FileManager.

Inspection of the bus names.
****************************

There are several basic functions which inspect the buses for registered names.  Internally they use the basic interface org.freedesktop.DBus, which is supported by all objects of a bus.

 -- Function: dbus-list-activatable-names
     This function returns the D-Bus service names, which can be activated. An activatable service is described in a service registration file. Under GNU/Linux, such files are located at /usr/share/dbus-1/services/.

     The result is a list of strings, which is nil when there are no activatable service names at all.

 -- Function: dbus-list-names bus
     All service names, which are registered at D-Bus BUS, are returned.  The result is a list of strings, which is nil when there are no registered service names at all.  Well known names are strings like org.freedesktop.DBus.  Names starting with : are unique names for services.

     BUS must be either the symbol :system or the symbol :session.

 -- Function: dbus-list-known-names bus
     Retrieves all services which correspond to a known name in BUS. A service has a known name if it doesn't start with :.  The result is a list of strings, which is nil when there are no known names at all.

     BUS must be either the symbol :system or the symbol :session.

 -- Function: dbus-list-queued-owners bus service
     For a given service, registered at D-Bus BUS under the name SERVICE, all queued unique names are returned.  The result is a list of strings, or nil when there are no queued names for SERVICE at all.

     BUS must be either the symbol :system or the symbol :session.  SERVICE must be a known service name as string.

 -- Function: dbus-get-name-owner bus service
     For a given service, registered at D-Bus BUS under the name SERVICE, the unique name of the name owner is returned.  The result is a string, or nil when there exist no name owner of SERVICE.

     BUS must be either the symbol :system or the symbol :session.  SERVICE must be a known service name as string.

 -- Function: dbus-get-unique-name bus
     The unique name, under which Emacs is registered at D-Bus BUS, is returned as string.

     BUS must be either the symbol :system or the symbol :session.

 -- Function: dbus-introspect bus service path
     Objects can publish there interfaces to the D-Bus.  This function returns all interfaces of SERVICE, registered at object path PATH at bus BUS.

     BUS must be either the symbol :system or the symbol :session.  SERVICE must be a known service name, and PATH must be a valid object path.  The last two parameters are strings.  The result, the introspection data, is a string in XML format. Example:

          (dbus-introspect
            :system "org.freedesktop.Hal"
            "/org/freedesktop/Hal/devices/computer")

          => "<!DOCTYPE node PUBLIC
              \"-//freedesktop//DTD D-BUS Object Introspection 1.0//EN\"
              \"http://www.freedesktop.org/standards/dbus/1.0/introspect.dtd\">
              <node>
                <interface name=\"org.freedesktop.Hal.Device\">
                  <method name=\"GetAllProperties\">
                    <arg name=\"properties\" direction=\"out\" type=\"a{sv}\"/>
                  </method>
                  ...
                  <signal name=\"PropertyModified\">
                    <arg name=\"num_updates\" type=\"i\"/>
                    <arg name=\"updates\" type=\"a(sbb)\"/>
                  </signal>
                </interface>
                ...
              </node>"

     This example informs us, that the service org.freedesktop.Hal at object path /org/freedesktop/Hal/devices/computer offers the interface org.freedesktop.Hal.Device (and 2 other interfaces not documented here).  This interface contains the method GetAllProperties, which needs no input parameters, but returns as output parameter an array of dictionary entries (key-value pairs). Every dictionary entry has a string as key, and a variant as value.

     The interface offers also a signal, which returns 2 parameters: an integer, and an array consisting of elements which are a struct of a string and 2 boolean values.

     Such type descriptions are called signature in D-Bus.  For a discussion of D-Bus types and their Lisp representation see Type Conversion. (D-Bus signatures are explained in the D-Bus specification http://dbus.freedesktop.org/doc/dbus-specification.html#message-protocol-signatures. The interfaces of the service org.freedesktop.Hal are described at http://people.freedesktop.org/~david/hal-spec/hal-spec.html#interfaces.)

Mapping Lisp types and D-Bus types.
***********************************

D-Bus method calls and signals accept usually several arguments as parameters, either as input parameter, or as output parameter.  Every argument belongs to a D-Bus type.

Such arguments must be mapped between the value encoded as a D-Bus type, and the corresponding type of Lisp objects.  The mapping is applied Lisp object ==> D-Bus type for input parameters, and D-Bus type ==> Lisp object for output parameters.

Input parameters.
=================

Input parameters for D-Bus methods and signals occur as arguments of a Lisp function call.  The following mapping to D-Bus types is applied, when the corresponding D-Bus message is created:

     Lisp type                                D-Bus type

     t and nil   ==>   DBUS_TYPE_BOOLEAN
     number                    ==>   DBUS_TYPE_UINT32
     integer                   ==>   DBUS_TYPE_INT32
     float                     ==>   DBUS_TYPE_DOUBLE
     string                    ==>   DBUS_TYPE_STRING
     list                      ==>   DBUS_TYPE_ARRAY

Other Lisp objects, like symbols or hash tables, are not accepted as input parameter.

If it is necessary to use another D-Bus type, a corresponding type symbol can be preceeded to the corresponding Lisp object. Basic D-Bus types are represented by the type symbols :byte, :boolean, :int16, :uint16, :int32, :uint32, :int64, :uint64, :double, :string, :object-path and :signature.

Example:

     (dbus-call-method ... NUMBER STRING)

is equivalent to

     (dbus-call-method ... :uint32 NUMBER :string STRING)

but different to

     (dbus-call-method ... :int32 NUMBER :signature STRING)

A D-Bus compound type is always represented as list.  The car of this list can be the type symbol :array, :variant, :struct or :dict-entry, which would result in a corresponding D-Bus container.  :array is optional, because this is the default compoud type for a list.

The objects being elements of the list are checked according to the D-Bus compound type rules.

  * An array must contain only elements of the same D-Bus type.

  * A variant must contain only one single element.

  * A dictionary entry must be element of an array, and it must contain only a key-value pair of two element, with a basic type key.

  * There is no restriction for structs.

Example:

     (dbus-send-signal ...
       :object-path STRING '(:variant :boolean BOOL)
       '(:array NUMBER NUMBER) '(:array BOOL :boolean BOOL)
       '(:struct BOOL :boolean BOOL BOOL
         (:array NUMBER NUMBER) (:array BOOL BOOL))
       '(:struct NUMBER NUMBER) '((:dict-entry NUMBER (NUMBER)))
       '(:array (:dict-entry NUMBER :int32 NUMBER)))

Output parameters.
==================

Output parameters of D-Bus methods and signals are mapped to Lisp objects.

     D-Bus type                             Lisp type

     DBUS_TYPE_BOOLEAN       ==>   t or nil
     DBUS_TYPE_BYTE          ==>   number
     DBUS_TYPE_UINT16        ==>   number
     DBUS_TYPE_INT16         ==>   number
     DBUS_TYPE_UINT32        ==>   number or float
     DBUS_TYPE_INT32         ==>   number or float
     DBUS_TYPE_UINT64        ==>   number or float
     DBUS_TYPE_INT64         ==>   number or float
     DBUS_TYPE_DOUBLE        ==>   float
     DBUS_TYPE_STRING        ==>   string
     DBUS_TYPE_OBJECT_PATH   ==>   string
     DBUS_TYPE_SIGNATURE     ==>   string
     DBUS_TYPE_ARRAY         ==>   list
     DBUS_TYPE_VARIANT       ==>   list
     DBUS_TYPE_STRUCT        ==>   list
     DBUS_TYPE_DICT_ENTRY    ==>   list

A float object in case of DBUS_TYPE_UINT32, DBUS_TYPE_INT32, DBUS_TYPE_UINT64 and DBUS_TYPE_INT6432 is returned, when the C value exceeds the Emacs number size range.

The resulting list of the last 4 D-Bus compound types contains as elements the elements of the D-Bus container, mapped according to the same rules.

The signal PropertyModified, discussed as example in Inspection, would offer as Lisp data the following object (BOOL stands here for either nil or t):

     (NUMBER ((STRING BOOL BOOL) (STRING BOOL BOOL) ...))

Calling methods in a blocking way.
**********************************

Methods can be called synchronously (blocking) or asynchronously (non-blocking).  Currently, just synchronous methods are implemented.

At D-Bus level, a method call consist of two messages: one message which carries the input parameters to the object owning the method to be called, and a reply message returning the resulting output parameters from the object.

 -- Function: dbus-call-method bus service path interface method &rest args
     This function calls METHOD on the D-Bus BUS.  BUS is either the symbol :system or the symbol :session.

     SERVICE is the D-Bus service name to be used.  PATH is the D-Bus object path, SERVICE is registered at.  INTERFACE is an interface offered by SERVICE.  It must provide METHOD.

     All other arguments args are passed to METHOD as arguments. They are converted into D-Bus types as described in Type Conversion.

     The function returns the resulting values of METHOD as a list of Lisp objects, according to the type conversion rules described in Type Conversion.  Example:

          (dbus-call-method
            :session "org.gnome.seahorse" "/org/gnome/seahorse/keys/openpgp"
            "org.gnome.seahorse.Keys" "GetKeyField"
            "openpgp:657984B8C7A966DD" "simple-name")

          => (t ("Philip R. Zimmermann"))

     If the result of the method call is just one value, the converted Lisp object is returned instead of a list containing this single Lisp object.  Example:

          (dbus-call-method
            :system "org.freedesktop.Hal"
            "/org/freedesktop/Hal/devices/computer"
            "org.freedesktop.Hal.Device" "GetPropertyString"
            "system.kernel.machine")

          => "i686"

     With the dbus-introspect function it is possible to explore the interfaces of org.freedesktop.Hal service. It offers the interfaces org.freedesktop.Hal.Manager for the object at the path /org/freedesktop/Hal/Manager as well as the interface org.freedesktop.Hal.Device for all objects prefixed with the path /org/freedesktop/Hal/devices.  With the methods GetAllDevices and GetAllProperties, it is simple to emulate the lshal command on GNU/Linux systems:

          (dolist (device
                    (dbus-call-method
                      :system "org.freedesktop.Hal"
                      "/org/freedesktop/Hal/Manager"
                      "org.freedesktop.Hal.Manager" "GetAllDevices"))
            (message "\nudi = %s" device)
            (dolist (properties
                      (dbus-call-method
                        :system "org.freedesktop.Hal" device
                        "org.freedesktop.Hal.Device" "GetAllProperties"))
              (message "  %s = %S"
                       (car properties) (or (caar (cdr properties)) ""))))

          -| "udi = /org/freedesktop/Hal/devices/computer
                info.addons = (\"hald-addon-acpi\")
                info.bus = \"unknown\"
                info.product = \"Computer\"
                info.subsystem = \"unknown\"
                info.udi = \"/org/freedesktop/Hal/devices/computer\"
                linux.sysfs_path_device = \"(none)\"
                power_management.acpi.linux.version = \"20051216\"
                power_management.can_suspend_to_disk = t
                power_management.can_suspend_to_ram = \"\"
                power_management.type = \"acpi\"
                smbios.bios.release_date = \"11/07/2001\"
                system.chassis.manufacturer = \"COMPAL\"
                system.chassis.type = \"Notebook\"
                system.firmware.release_date = \"03/19/2005\"
                ..."

Sending and receiving signals.
******************************

Signals are broadcast messages.  They carry input parameters, which are received by all objects which have registered for such a signal.

 -- Function: dbus-send-signal bus service path interface signal &rest args
     This function is similar to dbus-call-method.  The difference is, that there are no returning output parameters.

     The function emits SIGNAL on the D-Bus BUS.  BUS is either the symbol :system or the symbol :session.  It doesn't matter whether another object has registered for SIGNAL.

     SERVICE is the D-Bus service name of the object the signal is emitted from.  PATH is the corresponding D-Bus object path, SERVICE is registered at.  INTERFACE is an interface offered by SERVICE.  It must provide SIGNAL.

     All other arguments args are passed to SIGNAL as arguments. They are converted into D-Bus types as described in Type Conversion.  Example:

          (dbus-send-signal
            :session "org.gnu.Emacs" "/org/gnu/Emacs"
            "org.gnu.Emacs.FileManager" "FileModified" "/home/albinus/.emacs")

 -- Function: dbus-register-signal bus service path interface signal handler
     With this function, an application registers for SIGNAL on the D-Bus BUS.

     BUS is either the symbol :system or the symbol :session.

     SERVICE is the D-Bus service name used by the sending D-Bus object.  It can be either a known name or the unique name of the D-Bus object sending the signal.  In case of a unique name, signals won't be received any longer once the object owning this unique name has disappeared, and a new queued object has replaced it.

     When SERVICE is nil, related signals from all D-Bus objects shall be accepted.

     PATH is the corresponding D-Bus object path, SERVICE is registered at.  It can also be nil if the path name of incoming signals shall not be checked.

     INTERFACE is an interface offered by SERVICE.  It must provide SIGNAL.

     HANDLER is a Lisp function to be called when the SIGNAL is received.  It must accept as arguments the output parameters SIGNAL is sending.  Example:

          (defun my-dbus-signal-handler (device)
            (message "Device %s added" device))

          => my-dbus-signal-handler

          (dbus-register-signal
            :system "org.freedesktop.Hal" "/org/freedesktop/Hal/Manager"
            "org.freedesktop.Hal.Manager" "DeviceAdded"
            'my-dbus-signal-handler)

          => ((:system "org.freedesktop.Hal.Manager" "DeviceAdded")
              ("org.freedesktop.Hal" "/org/freedesktop/Hal/Manager"
               my-signal-handler))

     As we know from the inspection data of interface org.freedesktop.Hal.Manager, the signal DeviceAdded provides one single parameter, which is mapped into a Lisp string. The callback function my-dbus-signal-handler must define one single string argument therefore.  Plugging an USB device to your machine, when registered for signal DeviceAdded, will show you which objects the GNU/Linux hal daemon adds.

     dbus-register-signal returns a Lisp symbol, which can be used as argument in dbus-unregister-signal for removing the registration for SIGNAL.

 -- Function: dbus-unregister-signal object
     Unregister OBJECT from the the D-Bus.  OBJECT must be the result of a preceding dbus-register-signal call.

Errors and events.
******************

Input parameters of dbus-call-method and dbus-register-signal are checked for correct D-Bus types. If there is a type mismatch, the Lisp error wrong-type-argument D-Bus ARG is raised.

All errors raised by D-Bus are signaled with the error symbol dbus-error.  As usual, such an error can be trapped with a condition-case form.  If possible, error messages from D-Bus are appended to the dbus-error.

Incoming D-Bus messages are handled as Emacs events (see Misc Events (elisp)).  The generated event has this form:

     (dbus-event BUS SERVICE PATH INTERFACE MEMBER HANDLER &rest ARGS)

BUS identifies the D-Bus the signal is coming from.  It is either the symbol :system or the symbol :session.

SERVICE and PATH are the unique name and the object path of the D-Bus object emitting the signal.  INTERFACE and MEMBER denote the signal which has been sent.

HANDLER is the callback function which has been registered for this signal (see Signals).  When a dbus-event event arrives, HANDLER is called with ARGS as arguments.

In order to inspect the dbus-event data, you could extend the definition of the callback function in Signals:

     (defun my-dbus-signal-handler (&rest args)
       (message "my-dbus-signal-handler: %S" last-input-event))

There exist convenience functions which could be called inside a callback function in order to retrieve the information from the event.

 -- Function: dbus-event-bus-name event
     Returns the bus name EVENT is coming from. The result is either the symbol :system or the symbol :session.

 -- Function: dbus-event-service-name event
     Returns the unique name of the D-Bus object EVENT is coming from.

 -- Function: dbus-event-path-name event
     Returns the object path of the D-Bus object EVENT is coming from.

 -- Function: dbus-event-interface-name event
     Returns the interface name of of the D-Bus object EVENT is coming from.

 -- Function: dbus-event-member-name event
     Returns the member name of of the D-Bus object EVENT is coming from.  It is either a signal name or a method name.

GNU Free Documentation License
******************************

     [file doclicense.texi not included]