* s/D-BUS/D-Bus/g
[platform/upstream/dbus.git] / doc / dbus-tutorial.xml
1 <?xml version="1.0" standalone="no"?>
2 <!DOCTYPE article PUBLIC "-//OASIS//DTD DocBook XML V4.1.2//EN"
3 "http://www.oasis-open.org/docbook/xml/4.1.2/docbookx.dtd"
4 [
5 ]>
6
7 <article id="index">
8   <articleinfo>
9     <title>D-Bus Tutorial</title>
10     <releaseinfo>Version 0.4.1</releaseinfo>
11     <date>15 July 2005</date>
12     <authorgroup>
13       <author>
14         <firstname>Havoc</firstname>
15         <surname>Pennington</surname>
16         <affiliation>
17           <orgname>Red Hat, Inc.</orgname>
18           <address><email>hp@pobox.com</email></address>
19         </affiliation>
20       </author>
21       <author>
22         <firstname>David</firstname>
23         <surname>Wheeler</surname>
24       </author>
25       <author>
26         <firstname>John</firstname>
27         <surname>Palmieri</surname>
28         <affiliation>
29           <orgname>Red Hat, Inc.</orgname>
30           <address><email>johnp@redhat.com</email></address>
31         </affiliation>
32       </author>
33       <author>
34         <firstname>Colin</firstname>
35         <surname>Walters</surname>
36         <affiliation>
37           <orgname>Red Hat, Inc.</orgname>
38           <address><email>walters@redhat.com</email></address>
39         </affiliation>
40       </author>
41     </authorgroup>
42   </articleinfo>
43
44   <sect1 id="whatis">
45     <title>What is D-Bus?</title>
46     <para>
47       D-Bus is a system for <firstterm>interprocess communication</firstterm>
48       (IPC). Architecturally, it has several layers:
49
50       <itemizedlist>
51         <listitem>
52           <para>
53             A library, <firstterm>libdbus</firstterm>, that allows two
54             applications to connect to each other and exchange messages.
55           </para>
56         </listitem>
57         <listitem>
58           <para>
59             A <firstterm>message bus daemon</firstterm> executable, built on
60             libdbus, that multiple applications can connect to. The daemon can
61             route messages from one application to zero or more other
62             applications.
63           </para>
64         </listitem>
65         <listitem>
66           <para>
67             <firstterm>Wrapper libraries</firstterm> based on particular
68             application frameworks.  For example, libdbus-glib and
69             libdbus-qt. There are also bindings to languages such as
70             Python. These wrapper libraries are the API most people should use,
71             as they simplify the details of D-Bus programming. libdbus is 
72             intended to be a low-level backend for the higher level bindings.
73             Much of the libdbus API is only useful for binding implementation.
74           </para>
75         </listitem>
76       </itemizedlist>
77     </para>
78
79     <para>
80       If you just want to use D-Bus and don't care how it works, jump directly
81       to <xref linkend="concepts"/>.
82       Otherwise, read on.
83     </para>
84
85     <para>
86       libdbus only supports one-to-one connections, just like a raw network
87       socket. However, rather than sending byte streams over the connection, you
88       send <firstterm>messages</firstterm>. Messages have a header identifying
89       the kind of message, and a body containing a data payload. libdbus also
90       abstracts the exact transport used (sockets vs. whatever else), and
91       handles details such as authentication.
92     </para>
93
94     <para>
95       The message bus daemon forms the hub of a wheel. Each spoke of the wheel
96       is a one-to-one connection to an application using libdbus.  An
97       application sends a message to the bus daemon over its spoke, and the bus
98       daemon forwards the message to other connected applications as
99       appropriate. Think of the daemon as a router.
100     </para>
101
102     <para>
103       The bus daemon has multiple instances on a typical computer.  The
104       first instance is a machine-global singleton, that is, a system daemon
105       similar to sendmail or Apache. This instance has heavy security
106       restrictions on what messages it will accept, and is used for systemwide
107       communication. The other instances are created one per user login session.
108       These instances allow applications in the user's session to communicate 
109       with one another.
110     </para>
111
112     <para>
113       The systemwide and per-user daemons are separate.  Normal within-session
114       IPC does not involve the systemwide message bus process and vice versa.
115     </para>
116
117     <sect2 id="uses">
118       <title>D-Bus applications</title>
119       <para>
120         There are many, many technologies in the world that have "Inter-process
121         communication" or "networking" in their stated purpose: <ulink
122         url="http://www.omg.org">CORBA</ulink>, <ulink
123         url="http://www.opengroup.org/dce/">DCE</ulink>, <ulink
124         url="http://www.microsoft.com/com/">DCOM</ulink>, <ulink
125         url="http://developer.kde.org/documentation/library/kdeqt/dcop.html">DCOP</ulink>, <ulink
126         url="http://www.xmlrpc.com">XML-RPC</ulink>, <ulink
127         url="http://www.w3.org/TR/SOAP/">SOAP</ulink>, <ulink
128         url="http://www.mbus.org/">MBUS</ulink>, <ulink
129         url="http://www.zeroc.com/ice.html">Internet Communications Engine (ICE)</ulink>,
130         and probably hundreds more.
131         Each of these is tailored for particular kinds of application.
132         D-Bus is designed for two specific cases:
133         <itemizedlist>
134           <listitem>
135             <para>
136               Communication between desktop applications in the same desktop
137               session; to allow integration of the desktop session as a whole,
138               and address issues of process lifecycle (when do desktop components 
139               start and stop running).
140             </para>
141           </listitem>
142           <listitem>
143             <para>
144               Communication between the desktop session and the operating system, 
145               where the operating system would typically include the kernel 
146               and any system daemons or processes.
147             </para>
148           </listitem>
149         </itemizedlist>
150       </para>
151       <para>
152         For the within-desktop-session use case, the GNOME and KDE desktops 
153         have significant previous experience with different IPC solutions
154         such as CORBA and DCOP. D-Bus is built on that experience and 
155         carefully tailored to meet the needs of these desktop projects 
156         in particular. D-Bus may or may not be appropriate for other 
157         applications; the FAQ has some comparisons to other IPC systems.
158       </para>
159       <para>
160         The problem solved by the systemwide or communication-with-the-OS case 
161         is explained well by the following text from the Linux Hotplug project:
162         <blockquote>
163           <para>
164            A gap in current Linux support is that policies with any sort of
165            dynamic "interact with user" component aren't currently
166            supported. For example, that's often needed the first time a network
167            adapter or printer is connected, and to determine appropriate places
168            to mount disk drives. It would seem that such actions could be
169            supported for any case where a responsible human can be identified:
170            single user workstations, or any system which is remotely
171            administered.
172           </para>
173
174           <para>
175             This is a classic "remote sysadmin" problem, where in this case
176             hotplugging needs to deliver an event from one security domain
177             (operating system kernel, in this case) to another (desktop for
178             logged-in user, or remote sysadmin). Any effective response must go
179             the other way: the remote domain taking some action that lets the
180             kernel expose the desired device capabilities. (The action can often
181             be taken asynchronously, for example letting new hardware be idle
182             until a meeting finishes.) At this writing, Linux doesn't have
183             widely adopted solutions to such problems. However, the new D-Bus
184             work may begin to solve that problem.
185           </para>
186         </blockquote>
187       </para>
188       <para>
189         D-Bus may happen to be useful for purposes other than the one it was
190         designed for. Its general properties that distinguish it from 
191         other forms of IPC are:
192         <itemizedlist>
193           <listitem>
194             <para>
195               Binary protocol designed to be used asynchronously 
196               (similar in spirit to the X Window System protocol).
197             </para>
198           </listitem>
199           <listitem>
200             <para>
201               Stateful, reliable connections held open over time.
202             </para>
203           </listitem>
204           <listitem>
205             <para>
206               The message bus is a daemon, not a "swarm" or 
207               distributed architecture.
208             </para>
209           </listitem>
210           <listitem>
211             <para>
212               Many implementation and deployment issues are specified rather
213               than left ambiguous.
214             </para>
215           </listitem>
216           <listitem>
217             <para>
218               Semantics are similar to the existing DCOP system, allowing 
219               KDE to adopt it more easily.
220             </para>
221           </listitem>
222           <listitem>
223             <para>
224               Security features to support the systemwide mode of the 
225               message bus.
226             </para>
227           </listitem>
228         </itemizedlist>
229       </para>
230     </sect2>
231   </sect1>
232   <sect1 id="concepts">
233     <title>Concepts</title>
234     <para>
235       Some basic concepts apply no matter what application framework you're
236       using to write a D-Bus application. The exact code you write will be
237       different for GLib vs. Qt vs. Python applications, however.
238     </para>
239     
240     <para>
241       Here is a diagram (<ulink url="diagram.png">png</ulink> <ulink
242       url="diagram.svg">svg</ulink>) that may help you visualize the concepts
243       that follow.
244     </para>
245
246     <sect2 id="objects">
247       <title>Objects and Object Paths</title>
248       <para>
249         Each application using D-Bus contains <firstterm>objects</firstterm>,
250         which generally map to GObject, QObject, C++ objects, or Python objects
251         (but need not).  An object is an <emphasis>instance</emphasis> rather
252         than a type.  When messages are received over a D-Bus connection, they
253         are sent to a specific object, not to the application as a whole.
254       </para>
255       <para>
256         To allow messages to specify their destination object, there has to be a
257         way to refer to an object. In your favorite programming language, this
258         is normally called a <firstterm>pointer</firstterm> or
259         <firstterm>reference</firstterm>. However, these references are
260         implemented as memory addresses relative to the address space of your
261         application, and thus can't be passed from one application to another.
262       </para>
263       <para>
264         To solve this, D-Bus introduces a name for each object. The name 
265         looks like a filesystem path, for example an object could be 
266         named <literal>/org/kde/kspread/sheets/3/cells/4/5</literal>. 
267         Human-readable paths are nice, but you are free to create an 
268         object named <literal>/com/mycompany/c5yo817y0c1y1c5b</literal> 
269         if it makes sense for your application.
270       </para>
271       <para>
272         Namespacing object paths is smart, by starting them with the components
273         of a domain name you own (e.g. <literal>/org/kde</literal>). This 
274         keeps different code modules in the same process from stepping 
275         on one another's toes.
276       </para>
277     </sect2>    
278
279     <sect2 id="interfaces">
280       <title>Interfaces</title>
281       <para>
282         Each object supports one or more <firstterm>interfaces</firstterm>.
283         Think of an interface as a named group of methods and signals, 
284         just as it is in GLib or Qt or Java. Interfaces define the 
285         <emphasis>type</emphasis> of an object instance.
286       </para>
287     </sect2>
288       
289     <sect2 id="messages">
290       <title>Message Types</title>
291       <para>
292         Messages are not all the same; in particular, D-Bus has 
293         4 built-in message types:
294         <itemizedlist>
295           <listitem>
296             <para>
297               Method call messages ask to invoke a method 
298               on an object.
299             </para>
300           </listitem>
301           <listitem>
302             <para>
303               Method return messages return the results 
304               of invoking a method.
305             </para>
306           </listitem>
307           <listitem>
308             <para>
309               Error messages return an exception caused by 
310               invoking a method.
311             </para>
312           </listitem>
313           <listitem>
314             <para>
315               Signal messages are notifications that a given signal 
316               has been emitted (that an event has occurred). 
317               You could also think of these as "event" messages.
318             </para>
319           </listitem>
320         </itemizedlist>
321       </para>
322       <para>
323         A method call maps very simply to messages, then: you send a method call
324         message, and receive either a method return message or an error message
325         in reply.
326       </para>
327     </sect2>
328
329     <sect2 id="bus-names">
330       <title>Bus Names</title>
331       
332       <para>
333         Object paths, interfaces, and messages exist on the level of 
334         libdbus and the D-Bus protocol; they are used even in the 
335         1-to-1 case with no message bus involved.
336       </para>
337
338       <para>
339         Bus names, on the other hand, are a property of the message bus daemon.
340         The bus maintains a mapping from names to message bus connections.
341         These names are used to specify the origin and destination
342         of messages passing through the message bus. When a name is mapped 
343         to a particular application's connection, that application is said to 
344         <firstterm>own</firstterm> that name.
345       </para>
346
347       <para>
348         On connecting to the bus daemon, each application immediately owns a
349         special name called the <firstterm>unique connection name</firstterm>.
350         A unique name begins with a ':' (colon) character; no other names are
351         allowed to begin with that character. Unique names are special because
352         they are created dynamically, and are never re-used during the lifetime
353         of the same bus daemon. You know that a given unique name will have the
354         same owner at all times.  An example of a unique name might be
355         <literal>:34-907</literal>. The numbers after the colon have 
356         no meaning other than their uniqueness.
357       </para>
358
359       <para>
360         Applications may ask to own additional <firstterm>well-known
361         names</firstterm>. For example, you could write a specification to
362         define a name called <literal>com.mycompany.TextEditor</literal>.
363         Your definition could specify that to own this name, an application
364         should have an object at the path
365         <literal>/com/mycompany/TextFileManager</literal> supporting the
366         interface <literal>org.freedesktop.FileHandler</literal>.        
367       </para>
368       
369       <para>
370         Applications could then send messages to this bus name, 
371         object, and interface to execute method calls.
372       </para>
373
374       <para>
375         You could think of the unique names as IP addresses, and the
376         well-known names as domain names. So
377         <literal>com.mycompany.TextEditor</literal> might map to something like
378         <literal>:34-907</literal> just as <literal>mycompany.com</literal> maps
379         to something like <literal>192.168.0.5</literal>.
380       </para>
381       
382       <para>
383         Names have a second important use, other than routing messages.  They
384         are used to track lifecycle. When an application exits (or crashes), its
385         connection to the message bus will be closed by the operating system
386         kernel. The message bus then sends out notification messages telling
387         remaining applications that the application's names have lost their
388         owner. By tracking these notifications, your application can reliably
389         monitor the lifetime of other applications.
390       </para>
391
392     </sect2>
393
394     <sect2 id="addresses">
395       <title>Addresses</title>
396
397       <para>
398         Applications using D-Bus are either servers or clients.  A server
399         listens for incoming connections; a client connects to a server. Once
400         the connection is established, it is a symmetric flow of messages; the
401         client-server distinction only matters when setting up the 
402         connection.
403       </para>
404
405       <para>
406         A D-Bus <firstterm>address</firstterm> specifies where a server will
407         listen, and where a client will connect.  For example, the address
408         <literal>unix:path=/tmp/abcdef</literal> specifies that the server will
409         listen on a UNIX domain socket at the path
410         <literal>/tmp/abcdef</literal> and the client will connect to that
411         socket. An address can also specify TCP/IP sockets, or any other
412         transport defined in future iterations of the D-Bus specification.
413       </para>
414
415       <para>
416         When using D-Bus with a message bus, the bus daemon is a server 
417         and all other applications are clients of the bus daemon.
418         libdbus automatically discovers the address of the per-session bus 
419         daemon by reading an environment variable. It discovers the 
420         systemwide bus daemon by checking a well-known UNIX domain socket path
421         (though you can override this address with an environment variable).
422       </para>
423
424       <para>
425         If you're using D-Bus without a bus daemon, it's up to you to 
426         define which application will be the server and which will be 
427         the client, and specify a mechanism for them to agree on 
428         the server's address.
429       </para>
430
431     </sect2>
432
433     <sect2 id="bigpicture">
434       <title>Big Conceptual Picture</title>
435
436       <para>
437         Pulling all these concepts together, to specify a particular 
438         method call on a particular object instance, a number of 
439         nested components have to be named:
440         <programlisting>
441           Address -&gt; [Bus Name] -&gt; Path -&gt; Interface -&gt; Method
442         </programlisting>
443         The bus name is in brackets to indicate that it's optional -- you only
444         provide a name to route the method call to the right application
445         when using the bus daemon. If you have a direct connection to another
446         application, bus names aren't used; there's no bus daemon.
447       </para>
448
449       <para>
450         The interface is also optional, primarily for historical 
451         reasons; DCOP does not require specifying the interface, 
452         instead simply forbidding duplicate method names 
453         on the same object instance. D-Bus will thus let you 
454         omit the interface, but if your method name is ambiguous 
455         it is undefined which method will be invoked.
456       </para>
457       
458     </sect2>
459
460   </sect1>
461
462   <sect1 id="glib-client">
463     <title>GLib API: Using Remote Objects</title>
464
465     <para>
466       The GLib binding is defined in the header file
467       <literal>&lt;dbus/dbus-glib.h&gt;</literal>.
468     </para>
469
470     <sect2 id="glib-typemappings">
471       <title>D-Bus - GLib type mappings</title>
472       <para>
473         The heart of the GLib bindings for D-Bus is the mapping it
474         provides between D-Bus "type signatures" and GLib types
475         (<literal>GType</literal>). The D-Bus type system is composed of
476         a number of "basic" types, along with several "container" types.
477       </para>
478       <sect3 id="glib-basic-typemappings">
479         <title>Basic type mappings</title>
480         <para>
481           Below is a list of the basic types, along with their associated
482           mapping to a <literal>GType</literal>.
483           <informaltable>
484             <tgroup cols="4">
485               <thead>
486                 <row>
487                   <entry>D-Bus basic type</entry>
488                   <entry>GType</entry>
489                   <entry>Free function</entry>
490                   <entry>Notes</entry>
491                 </row>
492               </thead>
493               <tbody>
494                 <row>
495                   <entry><literal>BYTE</literal></entry>
496                   <entry><literal>G_TYPE_UCHAR</literal></entry>
497                   <entry></entry>
498                   <entry></entry>
499                   </row><row>
500                   <entry><literal>BOOLEAN</literal></entry>
501                   <entry><literal>G_TYPE_BOOLEAN</literal></entry>
502                   <entry></entry>
503                   <entry></entry>
504                   </row><row>
505                   <entry><literal>INT16</literal></entry>
506                   <entry><literal>G_TYPE_INT</literal></entry>
507                   <entry></entry>
508                   <entry>Will be changed to a <literal>G_TYPE_INT16</literal> once GLib has it</entry>
509                   </row><row>
510                   <entry><literal>UINT16</literal></entry>
511                   <entry><literal>G_TYPE_UINT</literal></entry>
512                   <entry></entry>
513                   <entry>Will be changed to a <literal>G_TYPE_UINT16</literal> once GLib has it</entry>
514                   </row><row>
515                   <entry><literal>INT32</literal></entry>
516                   <entry><literal>G_TYPE_INT</literal></entry>
517                   <entry></entry>
518                   <entry>Will be changed to a <literal>G_TYPE_INT32</literal> once GLib has it</entry>
519                   </row><row>
520                   <entry><literal>UINT32</literal></entry>
521                   <entry><literal>G_TYPE_UINT</literal></entry>
522                   <entry></entry>
523                   <entry>Will be changed to a <literal>G_TYPE_UINT32</literal> once GLib has it</entry>
524                   </row><row>
525                   <entry><literal>INT64</literal></entry>
526                   <entry><literal>G_TYPE_GINT64</literal></entry>
527                   <entry></entry>
528                   <entry></entry>
529                   </row><row>
530                   <entry><literal>UINT64</literal></entry>
531                   <entry><literal>G_TYPE_GUINT64</literal></entry>
532                   <entry></entry>
533                   <entry></entry>
534                   </row><row>
535                   <entry><literal>DOUBLE</literal></entry>
536                   <entry><literal>G_TYPE_DOUBLE</literal></entry>
537                   <entry></entry>
538                   <entry></entry>
539                   </row><row>
540                   <entry><literal>STRING</literal></entry>
541                   <entry><literal>G_TYPE_STRING</literal></entry>
542                   <entry><literal>g_free</literal></entry>
543                   <entry></entry>
544                   </row><row>
545                   <entry><literal>OBJECT_PATH</literal></entry>
546                   <entry><literal>DBUS_TYPE_G_PROXY</literal></entry>
547                   <entry><literal>g_object_unref</literal></entry>
548                   <entry>The returned proxy does not have an interface set; use <literal>dbus_g_proxy_set_interface</literal> to invoke methods</entry>
549                 </row>
550               </tbody>
551             </tgroup>
552           </informaltable>
553           As you can see, the basic mapping is fairly straightforward.
554         </para>
555       </sect3>
556       <sect3 id="glib-container-typemappings">
557         <title>Container type mappings</title>
558         <para>
559           The D-Bus type system also has a number of "container"
560           types, such as <literal>DBUS_TYPE_ARRAY</literal> and
561           <literal>DBUS_TYPE_STRUCT</literal>.  The D-Bus type system
562           is fully recursive, so one can for example have an array of
563           array of strings (i.e. type signature
564           <literal>aas</literal>).
565         </para>
566         <para>
567           However, not all of these types are in common use; for
568           example, at the time of this writing the author knows of no
569           one using <literal>DBUS_TYPE_STRUCT</literal>, or a
570           <literal>DBUS_TYPE_ARRAY</literal> containing any non-basic
571           type.  The approach the GLib bindings take is pragmatic; try
572           to map the most common types in the most obvious way, and
573           let using less common and more complex types be less
574           "natural".
575         </para>
576         <para>
577           First, D-Bus type signatures which have an "obvious"
578           corresponding built-in GLib type are mapped using that type:
579           <informaltable>
580             <tgroup cols="6">
581               <thead>
582                 <row>
583                   <entry>D-Bus type signature</entry>
584                   <entry>Description</entry>
585                   <entry>GType</entry>
586                   <entry>C typedef</entry>
587                   <entry>Free function</entry>
588                   <entry>Notes</entry>
589                 </row>
590               </thead>
591               <tbody>
592                 <row>
593                   <entry><literal>as</literal></entry>
594                   <entry>Array of strings</entry>
595                   <entry><literal>G_TYPE_STRV</literal></entry>
596                   <entry><literal>char **</literal></entry>
597                   <entry><literal>g_strfreev</literal></entry>
598                   <entry></entry>
599                   </row><row>
600                   <entry><literal>v</literal></entry>
601                   <entry>Generic value container</entry>
602                   <entry><literal>G_TYPE_VALUE</literal></entry>
603                   <entry><literal>GValue *</literal></entry>
604                   <entry><literal>g_value_unset</literal></entry>
605                   <entry>The calling conventions for values expect that method callers have allocated return values; see below.</entry>
606                 </row>
607               </tbody>
608             </tgroup>
609           </informaltable>
610         </para>
611         <para>
612           The next most common recursive type signatures are arrays of
613           basic values.  The most obvious mapping for arrays of basic
614           types is a <literal>GArray</literal>.  Now, GLib does not
615           provide a builtin <literal>GType</literal> for
616           <literal>GArray</literal>.  However, we actually need more than
617           that - we need a "parameterized" type which includes the
618           contained type.  Why we need this we will see below.
619         </para>
620         <para>
621           The approach taken is to create these types in the D-Bus GLib
622           bindings; however, there is nothing D-Bus specific about them.
623           In the future, we hope to include such "fundamental" types in GLib
624           itself.
625           <informaltable>
626             <tgroup cols="6">
627               <thead>
628                 <row>
629                   <entry>D-Bus type signature</entry>
630                   <entry>Description</entry>
631                   <entry>GType</entry>
632                   <entry>C typedef</entry>
633                   <entry>Free function</entry>
634                   <entry>Notes</entry>
635                 </row>
636               </thead>
637               <tbody>
638                 <row>
639                   <entry><literal>ay</literal></entry>
640                   <entry>Array of bytes</entry>
641                   <entry><literal>DBUS_TYPE_G_BYTE_ARRAY</literal></entry>
642                   <entry><literal>GArray *</literal></entry>
643                   <entry>g_array_free</entry>
644                   <entry></entry>
645                 </row>
646                 <row>
647                   <entry><literal>au</literal></entry>
648                   <entry>Array of uint</entry>
649                   <entry><literal>DBUS_TYPE_G_UINT_ARRAY</literal></entry>
650                   <entry><literal>GArray *</literal></entry>
651                   <entry>g_array_free</entry>
652                   <entry></entry>
653                 </row>
654                 <row>
655                   <entry><literal>ai</literal></entry>
656                   <entry>Array of int</entry>
657                   <entry><literal>DBUS_TYPE_G_INT_ARRAY</literal></entry>
658                   <entry><literal>GArray *</literal></entry>
659                   <entry>g_array_free</entry>
660                   <entry></entry>
661                 </row>
662                 <row>
663                   <entry><literal>ax</literal></entry>
664                   <entry>Array of int64</entry>
665                   <entry><literal>DBUS_TYPE_G_INT64_ARRAY</literal></entry>
666                   <entry><literal>GArray *</literal></entry>
667                   <entry>g_array_free</entry>
668                   <entry></entry>
669                 </row>
670                 <row>
671                   <entry><literal>at</literal></entry>
672                   <entry>Array of uint64</entry>
673                   <entry><literal>DBUS_TYPE_G_UINT64_ARRAY</literal></entry>
674                   <entry><literal>GArray *</literal></entry>
675                   <entry>g_array_free</entry>
676                   <entry></entry>
677                 </row>
678                 <row>
679                   <entry><literal>ad</literal></entry>
680                   <entry>Array of double</entry>
681                   <entry><literal>DBUS_TYPE_G_DOUBLE_ARRAY</literal></entry>
682                   <entry><literal>GArray *</literal></entry>
683                   <entry>g_array_free</entry>
684                   <entry></entry>
685                 </row>
686                 <row>
687                   <entry><literal>ab</literal></entry>
688                   <entry>Array of boolean</entry>
689                   <entry><literal>DBUS_TYPE_G_BOOLEAN_ARRAY</literal></entry>
690                   <entry><literal>GArray *</literal></entry>
691                   <entry>g_array_free</entry>
692                   <entry></entry>
693                 </row>
694               </tbody>
695             </tgroup>
696           </informaltable>
697         </para>
698         <para>
699           D-Bus also includes a special type DBUS_TYPE_DICT_ENTRY which
700           is only valid in arrays.  It's intended to be mapped to a "dictionary"
701           type by bindings.  The obvious GLib mapping here is GHashTable.  Again,
702           however, there is no builtin <literal>GType</literal> for a GHashTable.
703           Moreover, just like for arrays, we need a parameterized type so that
704           the bindings can communiate which types are contained in the hash table.
705         </para>
706         <para>
707           At present, only strings are supported.  Work is in progress to
708           include more types.
709           <informaltable>
710             <tgroup cols="6">
711               <thead>
712                 <row>
713                   <entry>D-Bus type signature</entry>
714                   <entry>Description</entry>
715                   <entry>GType</entry>
716                   <entry>C typedef</entry>
717                   <entry>Free function</entry>
718                   <entry>Notes</entry>
719                 </row>
720               </thead>
721               <tbody>
722                 <row>
723                   <entry><literal>a{ss}</literal></entry>
724                   <entry>Dictionary mapping strings to strings</entry>
725                   <entry><literal>DBUS_TYPE_G_STRING_STRING_HASHTABLE</literal></entry>
726                   <entry><literal>GHashTable *</literal></entry>
727                   <entry>g_hash_table_destroy</entry>
728                   <entry></entry>
729                 </row>
730               </tbody>
731             </tgroup>
732           </informaltable>
733         </para>
734       </sect3>
735       <sect3 id="glib-generic-typemappings">
736         <title>Arbitrarily recursive type mappings</title>
737         <para>
738           Finally, it is possible users will want to write or invoke D-Bus
739           methods which have arbitrarily complex type signatures not
740           directly supported by these bindings.  For this case, we have a
741           <literal>DBusGValue</literal> which acts as a kind of special
742           variant value which may be iterated over manually.  The
743           <literal>GType</literal> associated is
744           <literal>DBUS_TYPE_G_VALUE</literal>.
745         </para>
746         <para>
747           TODO insert usage of <literal>DBUS_TYPE_G_VALUE</literal> here.
748         </para>
749       </sect3>
750     </sect2>
751     <sect2 id="sample-program-1">
752       <title>A sample program</title>
753       <para>Here is a D-Bus program using the GLib bindings.
754 <programlisting>      
755 int
756 main (int argc, char **argv)
757 {
758   DBusGConnection *connection;
759   GError *error;
760   DBusGProxy *proxy;
761   char **name_list;
762   char **name_list_ptr;
763   
764   g_type_init ();
765
766   error = NULL;
767   connection = dbus_g_bus_get (DBUS_BUS_SESSION,
768                                &amp;error);
769   if (connection == NULL)
770     {
771       g_printerr ("Failed to open connection to bus: %s\n",
772                   error-&gt;message);
773       g_error_free (error);
774       exit (1);
775     }
776
777   /* Create a proxy object for the "bus driver" (name "org.freedesktop.DBus") */
778   
779   proxy = dbus_g_proxy_new_for_name (connection,
780                                      DBUS_SERVICE_DBUS,
781                                      DBUS_PATH_DBUS,
782                                      DBUS_INTERFACE_DBUS);
783
784   /* Call ListNames method, wait for reply */
785   error = NULL;
786   if (!dbus_g_proxy_call (proxy, "ListNames", &amp;error, G_TYPE_INVALID,
787                           G_TYPE_STRV, &amp;name_list, G_TYPE_INVALID))
788     {
789       /* Just do demonstrate remote exceptions versus regular GError */
790       if (error->domain == DBUS_GERROR &amp;&amp; error->code == DBUS_GERROR_REMOTE_EXCEPTION)
791         g_printerr ("Caught remote method exception %s: %s",
792                     dbus_g_error_get_name (error),
793                     error-&gt;message);
794       else
795         g_printerr ("Error: %s\n", error-&gt;message);
796       g_error_free (error);
797       exit (1);
798     }
799
800   /* Print the results */
801  
802   g_print ("Names on the message bus:\n");
803   
804   for (name_list_ptr = name_list; *name_list_ptr; name_list_ptr++)
805     {
806       g_print ("  %s\n", *name_list_ptr);
807     }
808   g_strfreev (name_list);
809
810   g_object_unref (proxy);
811
812   return 0;
813 }
814 </programlisting>
815     </para>
816     </sect2>
817     <sect2 id="glib-program-setup">
818       <title>Program initalization</title>
819       <para>
820         A connection to the bus is acquired using
821         <literal>dbus_g_bus_get</literal>.  Next, a proxy
822         is created for the object "/org/freedesktop/DBus" with
823         interface <literal>org.freedesktop.DBus</literal>
824         on the service <literal>org.freedesktop.DBus</literal>.
825         This is a proxy for the message bus itself.
826       </para>
827     </sect2>
828     <sect2 id="glib-method-invocation">
829       <title>Understanding method invocation</title>
830       <para>
831         You have a number of choices for method invocation.  First, as
832         used above, <literal>dbus_g_proxy_call</literal> sends a
833         method call to the remote object, and blocks until a reply is
834         recieved.  The outgoing arguments are specified in the varargs
835         array, terminated with <literal>G_TYPE_INVALID</literal>.
836         Next, pointers to return values are specified, followed again
837         by <literal>G_TYPE_INVALID</literal>.
838       </para>
839       <para>
840         To invoke a method asynchronously, use
841         <literal>dbus_g_proxy_begin_call</literal>.  This returns a
842         <literal>DBusGPendingCall</literal> object; you may then set a
843         notification function using
844         <literal>dbus_g_pending_call_set_notify</literal>.
845       </para>
846     </sect2>
847     <sect2 id="glib-signal-connection">
848       <title>Connecting to object signals</title>
849       <para>
850         You may connect to signals using
851         <literal>dbus_g_proxy_add_signal</literal> and
852         <literal>dbus_g_proxy_connect_signal</literal>.  You must
853         invoke <literal>dbus_g_proxy_add_signal</literal> to specify
854         the signature of your signal handlers; you may then invoke
855         <literal>dbus_g_proxy_connect_signal</literal> multiple times.
856       </para>
857       <para>
858         Note that it will often be the case that there is no builtin
859         marshaller for the type signature of a remote signal.  In that
860         case, you must generate a marshaller yourself by using
861         <application>glib-genmarshal</application>, and then register
862         it using <literal>dbus_g_object_register_marshaller</literal>.
863       </para>
864     </sect2>
865     <sect2 id="glib-error-handling">
866       <title>Error handling and remote exceptions</title>
867       <para>
868         All of the GLib binding methods such as
869         <literal>dbus_g_proxy_end_call</literal> return a
870         <literal>GError</literal>.  This <literal>GError</literal> can
871         represent two different things:
872       <itemizedlist>
873         <listitem>
874           <para>
875             An internal D-Bus error, such as an out-of-memory
876             condition, an I/O error, or a network timeout.  Errors
877             generated by the D-Bus library itself have the domain
878             <literal>DBUS_GERROR</literal>, and a corresponding code
879             such as <literal>DBUS_GERROR_NO_MEMORY</literal>.  It will
880             not be typical for applications to handle these errors
881             specifically.
882           </para>
883         </listitem>
884         <listitem>
885           <para>
886             A remote D-Bus exception, thrown by the peer, bus, or
887             service.  D-Bus remote exceptions have both a textual
888             "name" and a "message".  The GLib bindings store this
889             information in the <literal>GError</literal>, but some
890             special rules apply.
891           </para>
892           <para>
893             The set error will have the domain
894             <literal>DBUS_GERROR</literal> as above, and will also
895             have the code
896             <literal>DBUS_GERROR_REMOTE_EXCEPTION</literal>.  In order
897             to access the remote exception name, you must use a
898             special accessor, such as
899             <literal>dbus_g_error_has_name</literal> or
900             <literal>dbus_g_error_get_name</literal>.  The remote
901             exception detailed message is accessible via the regular
902             GError <literal>message</literal> member.
903           </para>
904         </listitem>
905       </itemizedlist>
906       </para>
907     </sect2>
908     <sect2 id="glib-more-examples">
909       <title>More examples of method invocation</title>
910       <sect3 id="glib-sending-stuff">
911         <title>Sending an integer and string, receiving an array of bytes</title>
912         <para>
913 <programlisting>
914   GArray *arr;
915   
916   error = NULL;
917   if (!dbus_g_proxy_call (proxy, "Foobar", &amp;error,
918                           G_TYPE_INT, 42, G_TYPE_STRING, "hello",
919                           G_TYPE_INVALID,
920                           DBUS_TYPE_G_UCHAR_ARRAY, &amp;arr, G_TYPE_INVALID))
921     {
922       /* Handle error */
923     }
924    g_assert (arr != NULL);
925    printf ("got back %u values", arr->len);
926 </programlisting>
927         </para>
928       </sect3>
929       <sect3 id="glib-sending-hash">
930         <title>Sending a GHashTable</title>
931         <para>
932 <programlisting>
933   GHashTable *hash = g_hash_table_new (g_str_hash, g_str_equal);
934   guint32 ret;
935   
936   g_hash_table_insert (hash, "foo", "bar");
937   g_hash_table_insert (hash, "baz", "whee");
938
939   error = NULL;
940   if (!dbus_g_proxy_call (proxy, "HashSize", &amp;error,
941                           DBUS_TYPE_G_STRING_STRING_HASH, hash, G_TYPE_INVALID,
942                           G_TYPE_UINT, &amp;ret, G_TYPE_INVALID))
943     {
944       /* Handle error */
945     }
946   g_assert (ret == 2);
947   g_hash_table_destroy (hash);
948 </programlisting>
949         </para>
950       </sect3>
951       <sect3 id="glib-receiving-bool-int">
952         <title>Receiving a boolean and a string</title>
953         <para>
954 <programlisting>
955   gboolean boolret;
956   char *strret;
957   
958   error = NULL;
959   if (!dbus_g_proxy_call (proxy, "GetStuff", &amp;error,
960                           G_TYPE_INVALID,
961                           G_TYPE_BOOLEAN, &amp;boolret,
962                           G_TYPE_STRING, &amp;strret,
963                           G_TYPE_INVALID))
964     {
965       /* Handle error */
966     }
967   printf ("%s %s", boolret ? "TRUE" : "FALSE", strret);
968   g_free (strret);
969 </programlisting>
970         </para>
971       </sect3>
972       <sect3 id="glib-sending-str-arrays">
973         <title>Sending two arrays of strings</title>
974         <para>
975 <programlisting>
976   /* NULL terminate */
977   char *strs_static[] = {"foo", "bar", "baz", NULL};
978   /* Take pointer to array; cannot pass array directly */
979   char **strs_static_p = strs_static;
980   char **strs_dynamic;
981
982   strs_dynamic = g_new (char *, 4);
983   strs_dynamic[0] = g_strdup ("hello");
984   strs_dynamic[1] = g_strdup ("world");
985   strs_dynamic[2] = g_strdup ("!");
986   /* NULL terminate */
987   strs_dynamic[3] = NULL;
988   
989   error = NULL;
990   if (!dbus_g_proxy_call (proxy, "TwoStrArrays", &amp;error,
991                           G_TYPE_STRV, strs_static_p,
992                           G_TYPE_STRV, strs_dynamic,
993                           G_TYPE_INVALID,
994                           G_TYPE_INVALID))
995     {
996       /* Handle error */
997     }
998    g_strfreev (strs_dynamic);
999 </programlisting>
1000         </para>
1001       </sect3>
1002       <sect3 id="glib-getting-str-array">
1003         <title>Sending a boolean, receiving an array of strings</title>
1004         <para>
1005 <programlisting>
1006   char **strs;
1007   char **strs_p;
1008   gboolean blah;
1009
1010   error = NULL;
1011   blah = TRUE;
1012   if (!dbus_g_proxy_call (proxy, "GetStrs", &amp;error,
1013                           G_TYPE_BOOLEAN, blah,
1014                           G_TYPE_INVALID,
1015                           G_TYPE_STRV, &amp;strs,
1016                           G_TYPE_INVALID))
1017     {
1018       /* Handle error */
1019     }
1020    for (strs_p = strs; *strs_p; strs_p++)
1021      printf ("got string: \"%s\"", *strs_p);
1022    g_strfreev (strs);
1023 </programlisting>
1024         </para>
1025       </sect3>
1026       <sect3 id="glib-sending-variant">
1027         <title>Sending a variant</title>
1028         <para>
1029 <programlisting>
1030   GValue val = {0, };
1031
1032   g_value_init (&amp;val, G_TYPE_STRING);
1033   g_value_set_string (&amp;val, "hello world");
1034   
1035   error = NULL;
1036   if (!dbus_g_proxy_call (proxy, "SendVariant", &amp;error,
1037                           G_TYPE_VALUE, &amp;val, G_TYPE_INVALID,
1038                           G_TYPE_INVALID))
1039     {
1040       /* Handle error */
1041     }
1042   g_assert (ret == 2);
1043   g_value_unset (&amp;val);
1044 </programlisting>
1045         </para>
1046       </sect3>
1047       <sect3 id="glib-receiving-variant">
1048         <title>Receiving a variant</title>
1049         <para>
1050 <programlisting>
1051   GValue val = {0, };
1052
1053   error = NULL;
1054   if (!dbus_g_proxy_call (proxy, "GetVariant", &amp;error, G_TYPE_INVALID,
1055                           G_TYPE_VALUE, &amp;val, G_TYPE_INVALID))
1056     {
1057       /* Handle error */
1058     }
1059   if (G_VALUE_TYPE (&amp;val) == G_TYPE_STRING)
1060     printf ("%s\n", g_value_get_string (&amp;val));
1061   else if (G_VALUE_TYPE (&amp;val) == G_TYPE_INT)
1062     printf ("%d\n", g_value_get_int (&amp;val));
1063   else
1064     ...
1065   g_value_unset (&amp;val);
1066 </programlisting>
1067         </para>
1068       </sect3>
1069     </sect2>
1070
1071     <sect2 id="glib-generated-bindings">
1072       <title>Generated Bindings</title>
1073       <para>
1074         By using the Introspection XML files, convenient client-side bindings
1075         can be automatically created to ease the use of a remote DBus object.
1076       </para>
1077       <para>
1078         Here is a sample XML file which describes an object that exposes
1079         one method, named <literal>ManyArgs</literal>.
1080         <programlisting>
1081 &lt;?xml version="1.0" encoding="UTF-8" ?&gt;
1082 &lt;node name="/com/example/MyObject"&gt;
1083   &lt;interface name="com.example.MyObject"&gt;
1084     &lt;method name="ManyArgs"&gt;
1085       &lt;arg type="u" name="x" direction="in" /&gt;
1086       &lt;arg type="s" name="str" direction="in" /&gt;
1087       &lt;arg type="d" name="trouble" direction="in" /&gt;
1088       &lt;arg type="d" name="d_ret" direction="out" /&gt;
1089       &lt;arg type="s" name="str_ret" direction="out" /&gt;
1090     &lt;/method&gt;
1091   &lt;/interface&gt;
1092 &lt;/node&gt;
1093 </programlisting>
1094       </para>
1095       <para>
1096         Run <literal>dbus-binding-tool --mode=glib-client
1097           <replaceable>FILENAME</replaceable> &gt;
1098           <replaceable>HEADER_NAME</replaceable></literal> to generate the header
1099         file.  For example: <command>dbus-binding-tool --mode=glib-client
1100           my-object.xml &gt; my-object-bindings.h</command>.  This will generate
1101         inline functions with the following prototypes:
1102         <programlisting>
1103 /* This is a blocking call */
1104 gboolean
1105 com_example_MyObject_many_args (DBusGProxy *proxy, const guint IN_x,
1106                                 const char * IN_str, const gdouble IN_trouble,
1107                                 gdouble* OUT_d_ret, char ** OUT_str_ret,
1108                                 GError **error);
1109
1110 /* This is a non-blocking call */
1111 DBusGProxyCall*
1112 com_example_MyObject_many_args_async (DBusGProxy *proxy, const guint IN_x,
1113                                       const char * IN_str, const gdouble IN_trouble,
1114                                       com_example_MyObject_many_args_reply callback,
1115                                       gpointer userdata);
1116
1117 /* This is the typedef for the non-blocking callback */
1118 typedef void
1119 (*com_example_MyObject_many_args_reply)
1120 (DBusGProxy *proxy, gdouble OUT_d_ret, char * OUT_str_ret,
1121  GError *error, gpointer userdata);
1122 </programlisting>
1123         The first argument in all functions is a <literal>DBusGProxy
1124         *</literal>, which you should create with the usual
1125         <literal>dbus_g_proxy_new_*</literal> functions.  Following that are the
1126         "in" arguments, and then either the "out" arguments and a
1127         <literal>GError *</literal> for the synchronous (blocking) function, or
1128         callback and user data arguments for the asynchronous (non-blocking)
1129         function.  The callback in the asynchronous function passes the
1130         <literal>DBusGProxy *</literal>, the returned "out" arguments, an
1131         <literal>GError *</literal> which is set if there was an error otherwise
1132         <literal>NULL</literal>, and the user data.
1133       </para>
1134       <para>
1135         As with the server-side bindings support (see <xref
1136         linkend="glib-server"/>), the exact behaviour of the client-side
1137         bindings can be manipulated using "annotations".  Currently the only
1138         annotation used by the client bindings is
1139         <literal>org.freedesktop.DBus.GLib.NoReply</literal>, which sets the
1140         flag indicating that the client isn't expecting a reply to the method
1141         call, so a reply shouldn't be sent.  This is often used to speed up
1142         rapid method calls where there are no "out" arguments, and not knowing
1143         if the method succeeded is an acceptable compromise to half the traffic
1144         on the bus.
1145       </para>
1146     </sect2>
1147   </sect1>
1148
1149   <sect1 id="glib-server">
1150     <title>GLib API: Implementing Objects</title>
1151     <para>
1152       At the moment, to expose a GObject via D-Bus, you must
1153       write XML by hand which describes the methods exported
1154       by the object.  In the future, this manual step will
1155       be obviated by the upcoming GLib introspection support.
1156     </para>
1157     <para>
1158       Here is a sample XML file which describes an object that exposes
1159       one method, named <literal>ManyArgs</literal>.
1160 <programlisting>
1161 &lt;?xml version="1.0" encoding="UTF-8" ?&gt;
1162
1163 &lt;node name="/com/example/MyObject"&gt;
1164
1165   &lt;interface name="com.example.MyObject"&gt;
1166     &lt;annotation name="org.freedesktop.DBus.GLib.CSymbol" value="my_object"/&gt;
1167     &lt;method name="ManyArgs"&gt;
1168       &lt;!-- This is optional, and in this case is redunundant --&gt;
1169       &lt;annotation name="org.freedesktop.DBus.GLib.CSymbol" value="my_object_many_args"/&gt;
1170       &lt;arg type="u" name="x" direction="in" /&gt;
1171       &lt;arg type="s" name="str" direction="in" /&gt;
1172       &lt;arg type="d" name="trouble" direction="in" /&gt;
1173       &lt;arg type="d" name="d_ret" direction="out" /&gt;
1174       &lt;arg type="s" name="str_ret" direction="out" /&gt;
1175     &lt;/method&gt;
1176   &lt;/interface&gt;
1177 &lt;/node&gt;
1178 </programlisting>
1179     </para>
1180     <para>
1181       This XML is in the same format as the D-Bus introspection XML
1182       format. Except we must include an "annotation" which give the C
1183       symbols corresponding to the object implementation prefix
1184       (<literal>my_object</literal>).  In addition, if particular
1185       methods symbol names deviate from C convention
1186       (i.e. <literal>ManyArgs</literal> -&gt;
1187       <literal>many_args</literal>), you may specify an annotation
1188       giving the C symbol.
1189     </para>
1190     <para>
1191       Once you have written this XML, run <literal>dbus-binding-tool --mode=glib-server <replaceable>FILENAME</replaceable> &gt; <replaceable>HEADER_NAME</replaceable>.</literal> to
1192       generate a header file.  For example: <command>dbus-binding-tool --mode=glib-server my-object.xml &gt; my-object-glue.h</command>.
1193     </para>
1194     <para>
1195       Next, include the generated header in your program, and invoke
1196       <literal>dbus_g_object_class_install_info</literal> in the class
1197       initializer, passing the object class and "object info" included in the
1198       header.  For example:
1199       <programlisting>
1200         dbus_g_object_type_install_info (COM_FOO_TYPE_MY_OBJECT, &amp;com_foo_my_object_info);
1201       </programlisting>
1202       This should be done exactly once per object class.
1203     </para>
1204     <para>
1205       To actually implement the method, just define a C function named e.g.
1206       <literal>my_object_many_args</literal> in the same file as the info
1207       header is included.  At the moment, it is required that this function
1208       conform to the following rules:
1209       <itemizedlist>
1210         <listitem>
1211           <para>
1212             The function must return a value of type <literal>gboolean</literal>;
1213             <literal>TRUE</literal> on success, and <literal>FALSE</literal>
1214             otherwise.
1215           </para>
1216         </listitem>
1217         <listitem>
1218           <para>
1219             The first parameter is a pointer to an instance of the object.
1220           </para>
1221         </listitem>
1222         <listitem>
1223           <para>
1224             Following the object instance pointer are the method
1225             input values.
1226           </para>
1227         </listitem>
1228         <listitem>
1229           <para>
1230             Following the input values are pointers to return values.
1231           </para>
1232         </listitem>
1233         <listitem>
1234           <para>
1235             The final parameter must be a <literal>GError **</literal>.
1236             If the function returns <literal>FALSE</literal> for an
1237             error, the error parameter must be initalized with
1238             <literal>g_set_error</literal>.
1239           </para>
1240         </listitem>
1241       </itemizedlist>
1242     </para>
1243     <para>
1244       Finally, you can export an object using <literal>dbus_g_connection_register_g_object</literal>.  For example:
1245       <programlisting>
1246           dbus_g_connection_register_g_object (connection,
1247                                                "/com/foo/MyObject",
1248                                                obj);
1249       </programlisting>
1250     </para>
1251
1252     <sect2 id="glib-annotations">
1253       <title>Server-side Annotations</title>
1254       <para>
1255         There are several annotations that are used when generating the
1256         server-side bindings.  The most common annotation is
1257         <literal>org.freedesktop.DBus.GLib.CSymbol</literal> but there are other
1258         annotations which are often useful.
1259         <variablelist>
1260           <varlistentry>
1261             <term><literal>org.freedesktop.DBus.GLib.CSymbol</literal></term>
1262             <listitem>
1263               <para>
1264                 This annotation is used to specify the C symbol names for
1265                 the various types (interface, method, etc), if it differs from the
1266                 name DBus generates.
1267               </para>
1268             </listitem>
1269           </varlistentry>
1270           <varlistentry>
1271             <term><literal>org.freedesktop.DBus.GLib.Async</literal></term>
1272             <listitem>
1273               <para>
1274                 This annotation marks the method implementation as an
1275                 asynchronous function, which doesn't return a response straight
1276                 away but will send the response at some later point to complete
1277                 the call.  This is used to implement non-blocking services where
1278                 method calls can take time.
1279               </para>
1280               <para>
1281                 When a method is asynchronous, the function prototype is
1282                 different. It is required that the function conform to the
1283                 following rules:
1284                 <itemizedlist>
1285                   <listitem>
1286                     <para>
1287                       The function must return a value of type <literal>gboolean</literal>;
1288                       <literal>TRUE</literal> on success, and <literal>FALSE</literal>
1289                       otherwise. TODO: the return value is currently ignored.
1290                     </para>
1291                   </listitem>
1292                   <listitem>
1293                     <para>
1294                       The first parameter is a pointer to an instance of the object.
1295                     </para>
1296                   </listitem>
1297                   <listitem>
1298                     <para>
1299                       Following the object instance pointer are the method
1300                       input values.
1301                     </para>
1302                   </listitem>
1303                   <listitem>
1304                     <para>
1305                       The final parameter must be a
1306                       <literal>DBusGMethodInvocation *</literal>.  This is used
1307                       when sending the response message back to the client, by
1308                       calling <literal>dbus_g_method_return</literal> or
1309                       <literal>dbus_g_method_return_error</literal>.
1310                     </para>
1311                   </listitem>
1312                 </itemizedlist>
1313               </para>
1314             </listitem>
1315           </varlistentry>
1316           <varlistentry>
1317             <term><literal>org.freedesktop.DBus.GLib.Const</literal></term>
1318             <listitem>
1319               <para>This attribute can only be applied to "out"
1320               <literal>&lt;arg&gt;</literal> nodes, and specifies that the
1321               parameter isn't being copied when returned.  For example, this
1322               turns a 's' argument from a <literal>char **</literal> to a
1323               <literal>const char **</literal>, and results in the argument not
1324               being freed by DBus after the message is sent.
1325               </para>
1326             </listitem>
1327           </varlistentry>
1328           <varlistentry>
1329             <term><literal>org.freedesktop.DBus.GLib.ReturnVal</literal></term>
1330             <listitem>
1331               <para>
1332                 This attribute can only be applied to "out"
1333                 <literal>&lt;arg&gt;</literal> nodes, and alters the expected
1334                 function signature.  It currently can be set to two values:
1335                 <literal>""</literal> or <literal>"error"</literal>.  The
1336                 argument marked with this attribute is not returned via a
1337                 pointer argument, but by the function's return value.  If the
1338                 attribute's value is the empty string, the <literal>GError
1339                 *</literal> argument is also omitted so there is no standard way
1340                 to return an error value.  This is very useful for interfacing
1341                 with existing code, as it is possible to match existing APIs.
1342                 If the attribute's value is <literal>"error"</literal>, then the
1343                 final argument is a <literal>GError *</literal> as usual.
1344               </para>
1345               <para>
1346                 Some examples to demonstrate the usage. This introspection XML:
1347                 <programlisting>
1348 &lt;method name="Increment"&gt;
1349   &lt;arg type="u" name="x" /&gt;
1350   &lt;arg type="u" direction="out" /&gt;
1351 &lt;/method&gt;
1352                 </programlisting>
1353                 Expects the following function declaration:
1354                 <programlisting>
1355 gboolean
1356 my_object_increment (MyObject *obj, gint32 x, gint32 *ret, GError **error);
1357                 </programlisting>
1358               </para>
1359               <para>
1360                 This introspection XML:
1361                 <programlisting>
1362 &lt;method name="IncrementRetval"&gt;
1363   &lt;arg type="u" name="x" /&gt;
1364   &lt;arg type="u" direction="out" &gt;
1365     &lt;annotation name="org.freedesktop.DBus.GLib.ReturnVal" value=""/&gt;
1366   &lt;/arg&gt;
1367 &lt;/method&gt;
1368                 </programlisting>
1369                 Expects the following function declaration:
1370                 <programlisting>
1371 gint32
1372 my_object_increment_retval (MyObject *obj, gint32 x)
1373                 </programlisting>
1374               </para>
1375               <para>
1376                 This introspection XML:
1377                 <programlisting>
1378 &lt;method name="IncrementRetvalError"&gt;
1379   &lt;arg type="u" name="x" /&gt;
1380   &lt;arg type="u" direction="out" &gt;
1381     &lt;annotation name="org.freedesktop.DBus.GLib.ReturnVal" value="error"/&gt;
1382   &lt;/arg&gt;
1383 &lt;/method&gt;
1384                 </programlisting>
1385                 Expects the following function declaration:
1386                 <programlisting>
1387 gint32
1388 my_object_increment_retval_error (MyObject *obj, gint32 x, GError **error)
1389                 </programlisting>
1390               </para>
1391             </listitem>
1392           </varlistentry>
1393         </variablelist>
1394       </para>
1395     </sect2>
1396   </sect1>
1397
1398   <sect1 id="python-client">
1399     <title>Python API: Using Remote Objects</title>
1400     <para>
1401       The Python bindings provide a simple to use interface for talking over D-Bus.
1402       Where possible much of the inner-workings of D-Bus are hidden behind what looks
1403       like normal Python objects.
1404     </para>
1405     <sect2 id="python-typemappings">
1406       <title>D-Bus - Python type mappings</title>
1407       <para>
1408         While python itself is a largely untyped language D-Bus provides a simple type system
1409         for talking with other languages which may be strongly typed.  Python for the most part
1410         tries automatically map python objects to types on the bus.  It is none the less good to 
1411         know what the type mappings are so one can better utilize services over the bus.
1412       </para>
1413       <sect3 id="python-basic-typemappings">
1414         <title>Basic type mappings</title>
1415         <para>
1416           Below is a list of the basic types, along with their associated
1417           mapping to a Python object.
1418           <informaltable>
1419             <tgroup cols="3">
1420               <thead>
1421                 <row>
1422                   <entry>D-Bus basic type</entry>
1423                   <entry>Python wrapper</entry>
1424                   <entry>Notes</entry>
1425                 </row>
1426               </thead>
1427               <tbody>
1428                 <row>
1429                   <entry><literal>BYTE</literal></entry>
1430                   <entry><literal>dbus.Byte</literal></entry>
1431                   <entry></entry>
1432                   </row><row>
1433                   <entry><literal>BOOLEAN</literal></entry>
1434                   <entry><literal>dbus.Boolean</literal></entry>
1435                   <entry>Any variable assigned a True or False boolean value will automatically be converted into a BOOLEAN over the bus</entry>
1436                   </row><row>
1437                   <entry><literal>INT16</literal></entry>
1438                   <entry><literal>dbus.Int16</literal></entry>
1439                   <entry></entry>
1440                   </row><row>
1441                   <entry><literal>UINT16</literal></entry>
1442                   <entry><literal>dbus.UInt16</literal></entry>
1443                   <entry></entry>
1444                   </row><row>
1445                   <entry><literal>INT32</literal></entry>
1446                   <entry><literal>dbus.Int32</literal></entry>
1447                   <entry>This is the default mapping for Python integers</entry>
1448                   </row><row>
1449                   <entry><literal>UINT32</literal></entry>
1450                   <entry><literal>dbus.UInt32</literal></entry>
1451                   <entry></entry>
1452                   </row><row>
1453                   <entry><literal>INT64</literal></entry>
1454                   <entry><literal>dbus.Int64</literal></entry>
1455                   <entry></entry>
1456                   </row><row>
1457                   <entry><literal>UINT64</literal></entry>
1458                   <entry><literal>dbus.UInt64</literal></entry>
1459                   <entry></entry>
1460                   </row><row>
1461                   <entry><literal>DOUBLE</literal></entry>
1462                   <entry><literal>dbus.Double</literal></entry>
1463                   <entry>Any variable assigned a floating point number will automatically be converted into a DOUBLE over the bus</entry>
1464                   </row><row>
1465                   <entry><literal>STRING</literal></entry>
1466                   <entry><literal>dbus.String</literal></entry>
1467                   <entry>Any variable assigned a quoted string will automatically be converted into a STRING over the bus</entry>
1468                   </row><row>
1469                   <entry><literal>OBJECT_PATH</literal></entry>
1470                   <entry><literal>dbus.ObjectPath</literal></entry>
1471                   <entry></entry>
1472                 </row>
1473               </tbody>
1474             </tgroup>
1475           </informaltable>
1476         </para>
1477       </sect3>
1478       <sect3 id="python-container-typemappings">
1479         <title>Container type mappings</title>
1480         <para>
1481           The D-Bus type system also has a number of "container"
1482           types, such as <literal>DBUS_TYPE_ARRAY</literal> and
1483           <literal>DBUS_TYPE_STRUCT</literal>.  The D-Bus type system
1484           is fully recursive, so one can for example have an array of
1485           array of strings (i.e. type signature
1486           <literal>aas</literal>).
1487         </para>
1488         <para>
1489           D-Bus container types have native corresponding built-in Python types
1490           so it is easy to use them.
1491           <informaltable>
1492             <tgroup cols="3">
1493               <thead>
1494                 <row>
1495                   <entry>D-Bus type</entry>
1496                   <entry>Python type</entry>
1497                   <entry>Python wrapper</entry>
1498                   <entry>Notes</entry>
1499                 </row>
1500               </thead>
1501               <tbody>
1502                 <row>
1503                   <entry><literal>ARRAY</literal></entry>
1504                   <entry><literal>Python lists</literal></entry>
1505                   <entry><literal>dbus.Array</literal></entry>
1506                   <entry>Python lists, denoted by square brackets [], are converted into arrays and visa versa.
1507                   The one restriction is that when sending a Python list each element of the list must be of the same
1508                   type.  This is because D-Bus arrays can contain only one element type.  Use Python tuples for mixed types.
1509                   
1510                   When using the wrapper you may also specify a type or signature of the elements contained in the Array.
1511                   This is manditory when passing an empty Array to a method on the bus because Python can not guess at the 
1512                   contents of an empty array.  For example if a method is expecting an Array of int32's and you need to pass
1513                   it an empty Array you would do it as such:
1514                   
1515                   <programlisting>emptyint32array = dbus.Array([], type=dbus.Int32)</programlisting>
1516
1517                   or
1518
1519                   <programlisting>emptyint32array = dbus.Array([], signature="i")</programlisting>
1520
1521                   Note that dbus.Array derives from list so it acts just like a python list.
1522                   </entry>
1523                   </row>
1524                 <row>
1525                   <entry><literal>STRUCT</literal></entry>
1526                   <entry><literal>Python tuple</literal></entry>
1527                   <entry><literal>dbus.Struct</literal></entry>
1528                   <entry>Python tuples, denoted by parentheses (,), are converted into structs and visa versa.
1529                   Tuples can have mixed types.</entry>
1530                 </row>
1531                 <row>
1532                   <entry><literal>DICTIONARY</literal></entry>
1533                   <entry><literal>Python dictionary</literal></entry>
1534                   <entry><literal>dbus.Dictionary</literal></entry>
1535                   <entry>D-Bus doesn't have an explicit dictionary type.  Instead it uses LISTS of DICT_ENTRIES to
1536                   represent a dictionary.  A DICT_ENTRY is simply a two element struct containing a key/value pair.
1537                   Python dictionaries are automatically converted to a LIST of DICT_ENTRIES and visa versa.
1538                   
1539                   Since dictonaries are described as lists of dict_entries we also need the signature in order
1540                   to pass empty dictionaries.  The wrapper provides a way of specifying this through the key_type/value_type
1541                   type parameters or the signature parameters.  To send an empty Dictionary where the key is a string
1542                   and the value is a string you would do it as such:
1543                   
1544                   <programlisting>emptystringstringdict = dbus.Dictionary({}, key_type=dbus.String, value_type=dbus.Value)</programlisting>
1545
1546                   or
1547
1548                   <programlisting>emptystringstringdict = dbus.Dictionary({}, signature="ss")</programlisting>
1549         
1550                   Note that dbus.Dictionary derives from dict so it acts just like a python dictionary.
1551                   </entry>
1552                 </row>
1553                 <row>
1554                   <entry><literal>VARIANT</literal></entry>
1555                   <entry><literal>any type</literal></entry>
1556                   <entry><literal>dbus.Variant</literal></entry>
1557                   <entry>A variant is a container for any type.  Python exports its methods to accept only variants 
1558                    since we are an untyped language and can demarshal into any Python type.
1559                    
1560                    To send a variant you must first wrap it in a<literal>dbus.Variant</literal>.  If no type or signiture is 
1561                    given to the variant the marshaler will get the type from the contents.</entry>
1562                 </row>
1563
1564               </tbody>
1565             </tgroup>
1566           </informaltable>
1567         </para>
1568       </sect3>
1569     </sect2>
1570     <sect2 id="python-invoking-methods">
1571       <title>Invoking Methods</title>
1572       <para>Here is a D-Bus program using the Python bindings to get a listing of all names on the session bus.
1573 <programlisting>      
1574 import dbus
1575
1576 bus = dbus.SessionBus()
1577 proxy_obj = bus.bus.get_object('org.freedesktop.DBus', '/org/freedesktop/DBus')
1578 dbus_iface = dbus.Interface(proxy_obj, 'org.freedesktop.DBus')
1579
1580 print dbus_iface.ListNames()
1581 </programlisting>
1582       </para>
1583       <para>
1584         Notice I get an interface on the proxy object and use that to make the call.  While the specifications
1585         state that you do not need to specify an interface if the call is unambiguous (i.e. only one method implements
1586         that name) due to a bug on the bus that drops messages which don't have an interface field you need to specify
1587         interfaces at this time.  In any event it is always good practice to specify the interface of the method you 
1588         wish to call to avoid any side effects should a method of the same name be implemented on another interface.
1589       </para>
1590       <para>
1591         You can specify the interface for a single call using the dbus_interface keyword.
1592 <programlisting>
1593 proxy_obj.ListNames(dbus_interface = 'org.freedesktop.DBus')
1594 </programlisting>
1595       </para>
1596       <para>
1597         This is all fine and good if all you want to do is call methods on the bus and then exit.  In order to 
1598         do more complex things such as use a GUI or make asynchronous calls you will need a mainloop.  You would use
1599         asynchronous calls because in GUI applications it is very bad to block for any long period of time.  This cause
1600         the GUI to seem to freeze.  Since replies to D-Bus messages can take an indeterminate amount of time using async 
1601         calls allows you to return control to the GUI while you wait for the reply.  This is exceedingly easy to do in
1602         Python.  Here is an example using the GLib/GTK+ mainloop.
1603 <programlisting>
1604 import gobject 
1605 import dbus
1606 if getattr(dbus, 'version', (0,0,0)) >= (0,41,0):
1607     import dbus.glib
1608
1609 def print_list_names_reply(list):
1610     print str(list) 
1611
1612 def print_error(e):
1613     print str(e)
1614     
1615 bus = dbus.SessionBus()
1616 proxy_obj = bus.bus.get_object('org.freedesktop.DBus', '/org/freedesktop/DBus')
1617 dbus_iface = dbus.Interface(proxy_obj, 'org.freedesktop.DBus')
1618
1619 dbus_iface.ListNames(reply_handler=print_list_names_reply, error_handler=print_error)
1620
1621 mainloop = gobject.MainLoop()
1622 mainloop.run()
1623 </programlisting>
1624       </para>
1625       <para>
1626         In the above listing you will notice the reply_handler and error_handler keywords.  These tell the method that
1627         it should be called async and to call print_list_names_reply or print_error depending if you get a reply or an error.
1628         The signature for replys depends on the number of arguments being sent back.  Error handlers always take one parameter
1629         which is the error object returned.
1630       </para>
1631       <para>
1632         You will also notice that I check the version of the dbus bindings before importing dbus.glib.  In older versions
1633         glib was the only available mainloop.  As of version 0.41.0 we split out the glib dependency to allow for other mainloops
1634         to be implemented.  Notice also the python binding version does not match up with the D-Bus version.  Once we reach 1.0
1635         this should change with Python changes simply tracking the D-Bus changes.
1636         While the glib mainloop is the only mainloop currently implemented, integrating other mainloops should
1637         be very easy to do.  There are plans for creating a a generic mainloop to be the default for non gui programs.
1638       </para>
1639     </sect2>
1640     <sect2 id="python-listening-for-signals">
1641       <title>Listening for Signals</title>
1642       <para>
1643         Signals are emitted by objects on the bus to notify listening programs that an event has occurred.  There are a couple of ways
1644         to register a signal handler on the bus.  One way is to attach to an already created proxy using the connect_to_signal method
1645         which takes a signal name and handler as arguments.  Let us look at an example of connecting to the HAL service to receive
1646         signals when devices are added and removed and when devices register a capability.  This example assumes you have HAL already running.
1647 <programlisting>
1648 import gobject 
1649 import dbus
1650 if getattr(dbus, 'version', (0,0,0)) >= (0,41,0):
1651     import dbus.glib
1652
1653 def device_added_callback(udi):
1654     print 'Device with udi %s was added' % (udi)
1655
1656 def device_removed_callback(udi):
1657     print 'Device with udi %s was added' % (udi)
1658
1659 def device_capability_callback(udi, capability):
1660     print 'Device with udi %s added capability %s' % (udi, capability)
1661
1662 bus = dbus.SystemBus()
1663 hal_manager_obj = bus.get_object('org.freedesktop.Hal', 
1664                                  '/org/freedesktop/Hal/Manager')
1665 hal_manager = dbus.Interface(hal_manager_obj,
1666                              'org.freedesktop.Hal.Manager')
1667
1668 hal_manager.connect_to_signal('DeviceAdded', device_added_callback)
1669 hal_manager.connect_to_signal('DeviceRemoved', device_removed_callback)
1670 hal_manager.connect_to_signal('NewCapability', device_capability_callback)
1671
1672 mainloop = gobject.MainLoop()
1673 mainloop.run()
1674 </programlisting>
1675       </para>
1676       <para>
1677         The drawback of using this method is that the service that you are connecting to has to be around when you register
1678         your signal handler.  While HAL is guaranteed to be around on systems that use it this is not always the case for every
1679         service on the bus.  Say our program started up before HAL, we could connect to the signal by adding a signal receiver
1680         directly to the bus.
1681 <programlisting>
1682 bus.add_signal_receiver(device_added_callback,
1683                         'DeviceAdded',
1684                         'org.freedesktop.Hal.Manager',
1685                         'org.freedesktop.Hal',
1686                         '/org/freedesktop/Hal/Manager')
1687
1688 bus.add_signal_receiver(device_removed_callback,
1689                         'DeviceRemoved',
1690                         'org.freedesktop.Hal.Manager',
1691                         'org.freedesktop.Hal',
1692                         '/org/freedesktop/Hal/Manager')
1693
1694 bus.add_signal_receiver(device_capability_callback,
1695                         'DeviceAdded',
1696                         'org.freedesktop.Hal.Manager',
1697                         'org.freedesktop.Hal',
1698                         '/org/freedesktop/Hal/Manager')
1699 </programlisting>
1700       </para>
1701       <para>
1702         All this can be done without creating the proxy object if one wanted to but in most cases you would want to have 
1703         a reference to the object so once a signal was received operations could be executed on the object.
1704       </para>
1705       <sidebar>
1706         <title>Signal matching on arguments</title>
1707         <para>
1708           Starting with D-Bus 0.36 and the (0, 43, 0) version of the python 
1709           bindings you can now add a match on arguments being sent in a signal.
1710           This is useful for instance for only getting NameOwnerChanged
1711           signals for your service.  Lets say we create a name on the bus called
1712           'org.foo.MyName' we could also add a match to just get 
1713           NameOwnerChanges for that name as such:
1714 <programlisting>
1715 bus.add_signal_receiver(myname_changed,
1716                         'NameOwnerChanged',
1717                         'org.freedesktop.DBus',
1718                         'org.freedesktop.DBus',
1719                         '/org/freedesktop/DBus',
1720                         arg0='org.foo.MyName')
1721 </programlisting>
1722
1723           It is as simple as that.  To match the second arg you would use arg1=,
1724           the third arg2=, etc.
1725         </para>
1726       </sidebar>
1727       <sidebar>
1728         <title>Cost of Creating a Proxy Object</title>
1729         <para>
1730           Note that creating proxy objects can have an associated processing cost.  When introspection is implemented
1731           a proxy may wait for introspection data before processing any requests.  It is generally good practice to
1732           create proxies once and reuse the proxy when calling into the object.  Constantly creating the same proxy 
1733           over and over again can become a bottleneck for your program.
1734         </para>
1735       </sidebar>
1736       <para>
1737         TODO: example of getting information about devices from HAL
1738       </para>
1739     </sect2>
1740   </sect1>
1741
1742   <sect1 id="python-server">
1743     <title>Python API: Implementing Objects</title>
1744     <para>
1745       Implementing object on the bus is just as easy as invoking methods or listening for signals on the bus.
1746     </para>
1747     <sidebar>
1748       <title>Version Alert</title>
1749       <para>
1750         The Python D-Bus bindings require version 2.4 or greater of Python when creating D-Bus objects.
1751       </para>
1752     </sidebar>
1753
1754     <sect2 id="python-inheriting-from-dbus-object">
1755       <title>Inheriting From dbus.service.Object</title>
1756       <para>
1757         In order to export a Python object over the bus one must first get a bus name and then create
1758         a Python object that inherits from dbus.service.Object.  The following is the start of an example
1759         HelloWorld object that we want to export over the session bus.
1760 <programlisting>
1761 import gobject 
1762 import dbus
1763 import dbus.service
1764 if getattr(dbus, 'version', (0,0,0)) >= (0,41,0):
1765     import dbus.glib
1766
1767 class HelloWorldObject(dbus.service.Object):
1768     def __init__(self, bus_name, object_path='/org/freedesktop/HelloWorldObject'):
1769         dbus.service.Object.__init__(self, bus_name, object_path)
1770
1771 session_bus = dbus.SessionBus()
1772 bus_name = dbus.service.BusName('org.freedesktop.HelloWorld', bus=session_bus)
1773 object = HelloWorldObject(bus_name)
1774
1775 mainloop = gobject.MainLoop()
1776 mainloop.run()
1777 </programlisting>
1778       </para>
1779       <para>
1780         Here we got the session bus, then created a BusName object which requests a name on the bus.
1781         We pass that bus name to the HelloWorldObject object which inherits from dbus.service.Object.
1782         We now have an object on the bus but it is pretty useless.
1783       </para>
1784     </sect2>
1785     <sect2 id="python-exporting-methods">
1786       <title>Exporting Methods Over The Bus</title>
1787       <para>
1788         Let's make this object do something and export a method over the bus.
1789 <programlisting>
1790 import gobject
1791 import dbus
1792 import dbus.service
1793 if getattr(dbus, 'version', (0,0,0)) >= (0,41,0):
1794     import dbus.glib
1795
1796 class HelloWorldObject(dbus.service.Object):
1797     def __init__(self, bus_name, object_path='/org/freedesktop/HelloWorldObject'):
1798         dbus.service.Object.__init__(self, bus_name, object_path)
1799
1800     @dbus.service.method('org.freedesktop.HelloWorldIFace')
1801     def hello(self):
1802         return 'Hello from the HelloWorldObject'
1803       
1804 session_bus = dbus.SessionBus()
1805 bus_name = dbus.service.BusName('org.freedesktop.HelloWorld', bus=session_bus)
1806 object = HelloWorldObject(bus_name)
1807
1808 mainloop = gobject.MainLoop()
1809 mainloop.run()
1810 </programlisting>
1811       </para>
1812       <sidebar>
1813         <title>Python Decorators</title>
1814         <para>
1815           Notice the @ symbol on the line before the hello method.  This is a new directive introduced in
1816           Python 2.4.  It is called a decorator and it "decorates" methods.  All you have to know is that
1817           it provides metadata that can then be used to alter the behavior of the method being decorated.
1818           In this case we are telling the bindings that the hello method should be exported as a D-Bus method
1819           over the bus.
1820         </para>
1821       </sidebar>
1822       <para>
1823         As you can see we exported the hello method as part of the org.freedesktop.HelloWorldIFace interface.
1824         It takes no arguments and returns a string to the calling program. Let's create a proxy and invoke this
1825         method.
1826 <programlisting>      
1827 import dbus
1828
1829 bus = dbus.SessionBus()
1830 proxy_obj = bus.bus.get_object('org.freedesktop.HelloWorld', '/org/freedesktop/HelloWorldObject')
1831 iface = dbus.Interface(proxy_obj, 'org.freedesktop.HelloWorldIFace')
1832
1833 print iface.hello()
1834 </programlisting>
1835       </para>
1836       <para>
1837         When invoking methods exported over the bus the bindings automatically know how many parameters
1838         the method exports.  You can even make a method that exports an arbitrary number of parameters.
1839         Also, whatever you return will automatically be transfered as a reply over the bus. Some examples.
1840 <programlisting>
1841     @dbus.service.method('org.freedesktop.HelloWorldIFace')
1842     def one_arg(self, first_arg):
1843         return 'I got arg %s' % first_arg
1844       
1845     @dbus.service.method('org.freedesktop.HelloWorldIFace')
1846     def two_args(self, first_arg, second_arg):
1847         return ('I got 2 args', first_arg, second_arg)
1848
1849     @dbus.service.method('org.freedesktop.HelloWorldIFace')
1850     def return_list(self):
1851         return [1, 2, 3, 4, 5, 6]
1852     
1853     @dbus.service.method('org.freedesktop.HelloWorldIFace')
1854     def return_dict(self):
1855         return {one: '1ne', two: '2wo', three: '3ree'}
1856 </programlisting>
1857       </para>
1858     </sect2>
1859     <sect2 id="python-emitting-signals">
1860       <title>Emitting Signals</title>
1861       <para>
1862         Setting up signals to emit is just as easy as exporting methods.  It uses the same syntax as methods.
1863 <programlisting>
1864 import gobject
1865 import dbus
1866 import dbus.service
1867 if getattr(dbus, 'version', (0,0,0)) >= (0,41,0):
1868     import dbus.glib
1869
1870 class HelloWorldObject(dbus.service.Object):
1871     def __init__(self, bus_name, object_path='/org/freedesktop/HelloWorldObject'):
1872         dbus.service.Object.__init__(self, bus_name, object_path)
1873
1874     @dbus.service.method('org.freedesktop.HelloWorldIFace')
1875     def hello(self):
1876         return 'Hello from the HelloWorldObject'
1877       
1878     @dbus.service.signal('org.freedesktop.HelloWorldIFace')
1879     def hello_signal(self, message):
1880         pass
1881         
1882 session_bus = dbus.SessionBus()
1883 bus_name = dbus.service.BusName('org.freedesktop.HelloWorld', bus=session_bus)
1884 object = HelloWorldObject(bus_name)
1885
1886 object.hello_signal('I sent a hello signal')
1887
1888 mainloop = gobject.MainLoop()
1889 mainloop.run()
1890 </programlisting>
1891       </para>
1892       <para>
1893         Adding a @dbus.service.signal decorator to a method turns it into a signal emitter.  You can put code
1894         in this method to do things like keep track of how many times you call the emitter or to print out debug
1895         messages but for the most part a pass noop will do.  Whenever you call the emitter a signal will be emitted
1896         with the parameters you passed in as arguments.  In the above example we send the message 'I sent a hello signal'
1897         with the signal.
1898       </para>
1899     </sect2>
1900     <sect2 id="python-inheriting-and-overriding">
1901       <title>Inheriting from HelloWorldObject</title>
1902       <para>
1903         One of the cool things you can do in Python is inherit from another D-Bus object.  We use this trick in
1904         the bindings to provide a default implementation for the org.freedesktop.DBus.Introspectable interface.
1905         Let's inherit from the HelloWorldObject example above and overide the hello method to say goodbye.
1906 <programlisting>
1907 class HelloWorldGoodbyeObject(HelloWorldObject):
1908     def __init__(self, bus_name, object_path='/org/freedesktop/HelloWorldGoodbyeObject'):
1909         HelloWorldObject.__init__(self, bus_name, object_path)
1910
1911     @dbus.service.method('org.freedesktop.HelloWorldGoodbyeIFace')
1912     def hello(self):
1913         return 'Goodbye'
1914
1915 goodbye_object = HelloWorldGoodbyeObject(bus_name)
1916 </programlisting>
1917       </para>
1918        <para>
1919        Let's now call both methods with a little help from interfaces.
1920 <programlisting>      
1921 import dbus
1922
1923 bus = dbus.SessionBus()
1924 proxy_obj = bus.bus.get_object('org.freedesktop.HelloWorld', '/org/freedesktop/HelloWorldGoodbyeObject')
1925
1926 print proxy_obj.hello(dbus_interface='org.freedesktop.HelloWorldIFace')
1927 print proxy_obj.hello(dbus_interface='org.freedesktop.HelloWorldGoodbyeIFace')
1928 </programlisting>
1929       </para>
1930       <para>
1931         This should print out 'Hello from the HelloWorldObject' followed by a 'Goodbye'.
1932       </para>
1933     </sect2>
1934     <sect2 id="python-conclusion">
1935       <title>Conclusion</title>
1936       <para>
1937         As you can see, using D-Bus from Python is an extremely easy proposition.  Hopefully
1938         the tutorial has been helpful in getting you started.  If you need anymore help please
1939         feel free to post on the <ulink url="http://lists.freedesktop.org/mailman/listinfo/dbus/">mailing list</ulink>.
1940         The Python bindings are still in a state of flux and there may be API changes in the future.
1941         This tutorial will be updated if such changes occur.
1942       </para>
1943     </sect2>
1944   </sect1>
1945
1946   <sect1 id="qt-client">
1947     <title>Qt API: Using Remote Objects</title>
1948     <para>
1949       
1950       The Qt bindings are not yet documented.
1951
1952     </para>
1953   </sect1>
1954
1955   <sect1 id="qt-server">
1956     <title>Qt API: Implementing Objects</title>
1957     <para>
1958       The Qt bindings are not yet documented.
1959     </para>
1960   </sect1>
1961 </article>