Fix property example in gobject tutorial
[platform/upstream/glib.git] / docs / reference / gobject / tut_howto.xml
1 <?xml version='1.0' encoding="ISO-8859-1"?>
2 <!DOCTYPE part PUBLIC "-//OASIS//DTD DocBook XML V4.5//EN" 
3                "http://www.oasis-open.org/docbook/xml/4.5/docbookx.dtd" [
4 ]>
5 <part label="IV">
6   <title>Tutorial</title>
7   <partintro>
8     <para>
9       This chapter tries to answer the real-life questions of users and presents
10       the most common scenario use cases I could come up with.
11       The use cases are presented from most likely to less likely.
12     </para>
13   </partintro>
14
15 <chapter id="howto-gobject">
16   <title>How to define and implement a new GObject</title>
17   
18   <para>
19     Clearly, this is one of the most common questions people ask: they just
20     want to crank code and implement a subclass of a GObject. Sometimes because
21     they want to create their own class hierarchy, sometimes because they want
22     to subclass one of GTK+'s widget. This chapter will focus on the 
23     implementation of a subtype of GObject.
24   </para>
25
26   <sect1 id="howto-gobject-header">
27     <title>Boilerplate header code</title>
28     
29     <para>
30       The first step before writing the code for your GObject is to write the
31       type's header which contains the needed type, function and macro
32       definitions. Each of these elements is nothing but a convention which
33       is followed not only by GTK+'s code but also by most users of GObject.
34       If you feel the need not to obey the rules stated below, think about it
35       twice:
36       <itemizedlist>
37         <listitem><para>If your users are a bit accustomed to GTK+ code or any
38         GLib code, they will be a bit surprised and getting used to the
39         conventions you decided upon will take time (money) and will make them
40         grumpy (not a good thing)</para></listitem>
41         <listitem><para>You must assess the fact that these conventions might
42         have been designed by both smart and experienced people: maybe they
43         were at least partly right. Try  to put your ego aside.</para></listitem>
44       </itemizedlist>
45     </para>
46
47     <para>
48       Pick a name convention for your headers and source code and stick to it:
49       <itemizedlist>
50         <listitem><para>use a dash to separate the prefix from the typename:
51         <filename>maman-bar.h</filename> and <filename>maman-bar.c</filename>
52         (this is the convention used by Nautilus and most GNOME libraries).</para></listitem>
53         <listitem><para>use an underscore to separate the prefix from the
54         typename: <filename>maman_bar.h</filename> and
55         <filename>maman_bar.c</filename>.</para></listitem>
56         <listitem><para>Do not separate the prefix from the typename:
57         <filename>mamanbar.h</filename> and <filename>mamanbar.c</filename>.
58         (this is the convention used by GTK+)</para></listitem>
59       </itemizedlist>
60       Some people like the first two solutions better: it makes reading file
61       names easier for those with poor eyesight.
62     </para>
63
64     <para>
65       When you need some private (internal) declarations in several
66       (sub)classes, you can define them in a private header file which
67       is often named by appending the <emphasis>private</emphasis> keyword
68       to the public header name. For example, one could use
69       <filename>maman-bar-private.h</filename>,
70       <filename>maman_bar_private.h</filename> or
71       <filename>mamanbarprivate.h</filename>. Typically, such private header
72       files are not installed.
73     </para>
74
75     <para>
76       The basic conventions for any header which exposes a GType are described
77       in <xref linkend="gtype-conventions"/>. Most GObject-based code also
78       obeys one of of the following conventions: pick one and stick to it.
79       <itemizedlist>
80         <listitem><para>
81             If you want to declare a type named bar with prefix maman, name the type instance
82             <function>MamanBar</function> and its class <function>MamanBarClass</function>
83             (name is case-sensitive). It is customary to declare them with code similar to the 
84             following:
85 <programlisting>
86 /*
87  * Copyright/Licensing information.
88  */
89
90 /* inclusion guard */
91 #ifndef __MAMAN_BAR_H__
92 #define __MAMAN_BAR_H__
93
94 #include &lt;glib-object.h&gt;
95 /*
96  * Potentially, include other headers on which this header depends.
97  */
98
99 /*
100  * Type macros.
101  */
102 #define MAMAN_TYPE_BAR                  (maman_bar_get_type ())
103 #define MAMAN_BAR(obj)                  (G_TYPE_CHECK_INSTANCE_CAST ((obj), MAMAN_TYPE_BAR, MamanBar))
104 #define MAMAN_IS_BAR(obj)               (G_TYPE_CHECK_INSTANCE_TYPE ((obj), MAMAN_TYPE_BAR))
105 #define MAMAN_BAR_CLASS(klass)          (G_TYPE_CHECK_CLASS_CAST ((klass), MAMAN_TYPE_BAR, MamanBarClass))
106 #define MAMAN_IS_BAR_CLASS(klass)       (G_TYPE_CHECK_CLASS_TYPE ((klass), MAMAN_TYPE_BAR))
107 #define MAMAN_BAR_GET_CLASS(obj)        (G_TYPE_INSTANCE_GET_CLASS ((obj), MAMAN_TYPE_BAR, MamanBarClass))
108
109 typedef struct _MamanBar        MamanBar;
110 typedef struct _MamanBarClass   MamanBarClass;
111
112 struct _MamanBar
113 {
114   GObject parent_instance;
115
116   /* instance members */
117 };
118
119 struct _MamanBarClass
120 {
121   GObjectClass parent_class;
122
123   /* class members */
124 };
125
126 /* used by MAMAN_TYPE_BAR */
127 GType maman_bar_get_type (void);
128
129 /*
130  * Method definitions.
131  */
132
133 #endif /* __MAMAN_BAR_H__ */
134 </programlisting>
135           </para></listitem>
136         <listitem><para>
137             Most GTK+ types declare their private fields in the public header
138             with a /* private */ comment, relying on their user's intelligence
139             not to try to play with these fields. Fields not marked private
140             are considered public by default. The /* protected */ comment
141             (same semantics as those of C++) is also used, mainly in the GType
142             library, in code written by Tim Janik.
143 <programlisting>
144 struct _MamanBar
145 {
146   GObject parent_instance;
147
148   /*&lt; private &gt;*/
149   int hsize;
150 };
151 </programlisting>
152           </para></listitem>
153         <listitem><para>
154             All of Nautilus code and a lot of GNOME libraries use private
155             indirection members, as described by Herb Sutter in his Pimpl
156             articles(see <ulink url="http://www.gotw.ca/gotw/024.htm">Compilation Firewalls</ulink>
157             and <ulink url="http://www.gotw.ca/gotw/028.htm">The Fast Pimpl Idiom</ulink>:
158             he summarizes the different issues better than I will).
159 <programlisting>
160 typedef struct _MamanBarPrivate MamanBarPrivate;
161
162 struct _MamanBar
163 {
164   GObject parent_instance;
165     
166   /*&lt; private &gt;*/
167   MamanBarPrivate *priv;
168 };
169 </programlisting>
170             <note><simpara>Do not call this <varname>private</varname>, as
171             that is a registered c++ keyword.</simpara></note>
172
173             The private structure is then defined in the .c file, using the
174             g_type_class_add_private() function to notify the presence of
175             a private memory area for each instance and it can either
176             be retrieved using <function>G_TYPE_INSTANCE_GET_PRIVATE()</function>
177             each time is needed, or assigned to the <literal>priv</literal>
178             member of the instance structure inside the object's
179             <function>init</function> function.
180 <programlisting>
181 #define MAMAN_BAR_GET_PRIVATE(obj) (G_TYPE_INSTANCE_GET_PRIVATE ((obj), MAMAN_TYPE_BAR, MamanBarPrivate))
182
183 struct _MamanBarPrivate
184 {
185   int hsize;
186 };
187
188 static void
189 maman_bar_class_init (MamanBarClass *klass)
190 {
191   g_type_class_add_private (klass, sizeof (MamanBarPrivate));
192 }
193
194 static void
195 maman_bar_init (MamanBar *self)
196 {
197   MamanBarPrivate *priv;
198
199   self->priv = priv = MAMAN_BAR_GET_PRIVATE (self);
200
201   priv->hsize = 42;
202 }
203 </programlisting>
204           </para></listitem>
205
206           <listitem><para>
207             You don't need to free or allocate the private structure, only the
208             objects or pointers that it may contain. Another advantage of this
209             to the previous version is that is lessens memory fragmentation,
210             as the public and private parts of the instance memory are
211             allocated at once.
212           </para></listitem>
213       </itemizedlist>
214     </para>
215
216     <para>
217       Finally, there are different header include conventions. Again, pick one
218       and stick to it. I personally use indifferently any of the two, depending
219       on the codebase I work on: the rule, as always, is consistency.
220       <itemizedlist>
221         <listitem><para>
222             Some people add at the top of their headers a number of #include
223             directives to pull in all the headers needed to compile client
224             code. This allows client code to simply #include "maman-bar.h".
225           </para></listitem>
226         <listitem><para>
227             Other do not #include anything and expect the client to #include
228             themselves the headers they need before including your header. This
229             speeds up compilation because it minimizes the amount of
230             pre-processor work. This can be used in conjunction with the
231             re-declaration of certain unused types in the client code to
232             minimize compile-time dependencies and thus speed up compilation.
233           </para></listitem>
234       </itemizedlist>
235     </para>
236       
237   </sect1>
238
239   <sect1 id="howto-gobject-code">
240     <title>Boilerplate code</title>
241
242     <para>
243       In your code, the first step is to #include the needed headers: depending
244       on your header include strategy, this can be as simple as
245       <literal>#include "maman-bar.h"</literal> or as complicated as tens
246       of #include lines ending with <literal>#include "maman-bar.h"</literal>:
247 <programlisting>
248 /*
249  * Copyright information
250  */
251
252 #include "maman-bar.h"
253
254 /* If you use Pimpls, include the private structure 
255  * definition here. Some people create a maman-bar-private.h header
256  * which is included by the maman-bar.c file and which contains the
257  * definition for this private structure.
258  */
259 struct _MamanBarPrivate {
260   int member_1;
261   /* stuff */
262 };
263
264 /* 
265  * forward definitions
266  */
267 </programlisting>
268     </para>
269
270     <para>
271       Call the <function>G_DEFINE_TYPE</function> macro using the name
272       of the type, the prefix of the functions and the parent GType to
273       reduce the amount of boilerplate needed. This macro will:
274
275       <itemizedlist>
276         <listitem><simpara>implement the <function>maman_bar_get_type</function>
277         function</simpara></listitem>
278         <listitem><simpara>define a parent class pointer accessible from
279         the whole .c file</simpara></listitem>
280       </itemizedlist>
281
282 <programlisting>
283 G_DEFINE_TYPE (MamanBar, maman_bar, G_TYPE_OBJECT);
284 </programlisting>
285     </para>
286
287     <para>
288       It is also possible to use the
289       <function>G_DEFINE_TYPE_WITH_CODE</function> macro to control the
290       get_type function implementation - for instance, to add a call to
291       <function>G_IMPLEMENT_INTERFACE</function> macro which will
292       call the <function>g_type_implement_interface</function> function.
293     </para>
294   </sect1>
295
296   <sect1 id="howto-gobject-construction">
297     <title>Object Construction</title>
298
299     <para>
300       People often get confused when trying to construct their GObjects because of the
301       sheer number of different ways to hook into the objects's construction process: it is
302       difficult to figure which is the <emphasis>correct</emphasis>, recommended way.
303     </para>
304
305     <para>
306       <xref linkend="gobject-construction-table"/> shows what user-provided functions
307       are invoked during object instantiation and in which order they are invoked.
308       A user looking for the equivalent of the simple C++ constructor function should use
309       the instance_init method. It will be invoked after all the parent's instance_init
310       functions have been invoked. It cannot take arbitrary construction parameters 
311       (as in C++) but if your object needs arbitrary parameters to complete initialization,
312       you can use construction properties.
313     </para>
314
315     <para>
316       Construction properties will be set only after all instance_init functions have run.
317       No object reference will be returned to the client of <function><link linkend="g-object-new">g_object_new</link></function>
318       until all the construction properties have been set.
319     </para>
320
321     <para>
322       As such, I would recommend writing the following code first:
323 <programlisting>
324 static void
325 maman_bar_init (MamanBar *self)
326 {
327   self->priv = MAMAN_BAR_GET_PRIVATE (self); 
328
329   /* initialize all public and private members to reasonable default values. */
330
331   /* If you need specific construction properties to complete initialization,
332    * delay initialization completion until the property is set. 
333    */
334 }
335 </programlisting>
336     </para>
337
338     <para>
339       Now, if you need special construction properties, install the properties in the class_init function,
340       override the set and get methods and implement the get and set methods as described in 
341       <xref linkend="gobject-properties"/>. Make sure that these properties use a construct only 
342       <link linkend="GParamSpec"><type>GParamSpec</type></link> by setting the param spec's flag field to G_PARAM_CONSTRUCT_ONLY: this helps
343       GType ensure that these properties are not set again later by malicious user code.
344 <informalexample><programlisting>
345 enum {
346   PROP_0,
347
348   PROP_MAMAN,
349
350   N_PROPERTIES
351 };
352
353 static GParamSpec *obj_properties[N_PROPERTIES] = { NULL, };
354
355 static void
356 bar_class_init (MamanBarClass *klass)
357 {
358   GObjectClass *gobject_class = G_OBJECT_CLASS (klass);
359
360   gobject_class->set_property = bar_set_property;
361   gobject_class->get_property = bar_get_property;
362
363   obj_properties[PROP_MAMAN] =
364     g_param_spec_string ("maman",
365                          "Maman construct prop",
366                          "Set maman's name",
367                          "no-name-set" /* default value */,
368                          G_PARAM_CONSTRUCT_ONLY | G_PARAM_READWRITE);
369
370   g_object_class_install_properties (gobject_class,
371                                      N_PROPERTIES,
372                                      obj_properties);
373 }
374 </programlisting></informalexample>
375       If you need this, make sure you can build and run code similar to the code shown above. Make sure
376       your construct properties can set correctly during construction, make sure you cannot set them 
377       afterwards and make sure that if your users do not call <function><link linkend="g-object-new">g_object_new</link></function>
378       with the required construction properties, these will be initialized with the default values.
379     </para>
380
381     <para>
382       I consider good taste to halt program execution if a construction property is set its
383       default value. This allows you to catch client code which does not give a reasonable
384       value to the construction properties. Of course, you are free to disagree but you
385       should have a good reason to do so.
386     </para>
387
388     <para>
389       Some people sometimes need to construct their object but only after
390       the construction properties have been set. This is possible through
391       the use of the constructor class method as described in
392       <xref linkend="gobject-instantiation"/> or, more simply, using
393       the constructed class method available since GLib 2.12.
394     </para>
395   </sect1>
396
397   <sect1 id="howto-gobject-destruction">
398     <title>Object Destruction</title>
399
400     <para>
401       Again, it is often difficult to figure out which mechanism to use to
402       hook into the object's destruction process: when the last
403       <function><link linkend="g-object-unref">g_object_unref</link></function>
404       function call is made, a lot of things happen as described in
405       <xref linkend="gobject-destruction-table"/>.
406     </para>
407
408     <para>
409       The destruction process of your object might be split in two different
410       phases: dispose and the finalize.
411 <programlisting>
412 #define MAMAN_BAR_GET_PRIVATE(obj) (G_TYPE_INSTANCE_GET_PRIVATE ((obj), MAMAN_TYPE_BAR, MamanBarPrivate))
413
414 struct _MamanBarPrivate
415 {
416   GObject *an_object;
417
418   gchar *a_string;
419 };
420
421 G_DEFINE_TYPE (MamanBar, maman_bar, G_TYPE_OBJECT);
422
423 static void
424 maman_bar_dispose (GObject *gobject)
425 {
426   MamanBar *self = MAMAN_BAR (gobject);
427
428   /* 
429    * In dispose, you are supposed to free all types referenced from this
430    * object which might themselves hold a reference to self. Generally,
431    * the most simple solution is to unref all members on which you own a 
432    * reference.
433    */
434
435   /* dispose might be called multiple times, so we must guard against
436    * calling g_object_unref() on an invalid GObject.
437    */
438   if (self->priv->an_object)
439     {
440       g_object_unref (self->priv->an_object);
441
442       self->priv->an_object = NULL;
443     }
444
445   /* Chain up to the parent class */
446   G_OBJECT_CLASS (maman_bar_parent_class)->dispose (gobject);
447 }
448
449 static void
450 maman_bar_finalize (GObject *gobject)
451 {
452   MamanBar *self = MAMAN_BAR (gobject);
453
454   g_free (self->priv->a_string);
455
456   /* Chain up to the parent class */
457   G_OBJECT_CLASS (maman_bar_parent_class)->finalize (gobject);
458 }
459
460 static void
461 maman_bar_class_init (MamanBarClass *klass)
462 {
463   GObjectClass *gobject_class = G_OBJECT_CLASS (klass);
464
465   gobject_class->dispose = maman_bar_dispose;
466   gobject_class->finalize = maman_bar_finalize;
467
468   g_type_class_add_private (klass, sizeof (MamanBarPrivate));
469 }
470
471 static void
472 maman_bar_init (MamanBar *self);
473 {
474   self->priv = MAMAN_BAR_GET_PRIVATE (self);
475
476   self->priv->an_object = g_object_new (MAMAN_TYPE_BAZ, NULL);
477   self->priv->a_string = g_strdup ("Maman");
478 }
479 </programlisting>
480     </para>
481
482     <para>
483       Add similar code to your GObject, make sure the code still builds
484       and runs: dispose and finalize must be called during the last unref.
485     </para>
486
487     <para>
488       It is possible that object methods might be invoked after dispose is
489       run and before finalize runs. GObject does not consider this to be a
490       program error: you must gracefully detect this and neither crash nor
491       warn the user.
492     </para>
493   </sect1>
494
495   <sect1 id="howto-gobject-methods">
496     <title>Object methods</title>
497
498     <para>
499       Just as with C++, there are many different ways to define object
500       methods and extend them: the following list and sections draw on
501       C++ vocabulary. (Readers are expected to know basic C++ buzzwords.
502       Those who have not had to write C++ code recently can refer to e.g.
503       <ulink url="http://www.cplusplus.com/doc/tutorial/"/> to refresh
504       their memories.)
505       <itemizedlist>
506         <listitem><para>
507             non-virtual public methods,
508           </para></listitem>
509         <listitem><para>
510             virtual public methods and
511           </para></listitem>
512         <listitem><para>
513             virtual private methods
514           </para></listitem>
515       </itemizedlist>
516     </para>
517
518     <sect2>
519       <title>Non-virtual public methods</title>
520
521       <para>
522         These are the simplest: you want to provide a simple method which
523         can act on your object. All you need to do is to provide a function
524         prototype in the header and an implementation of that prototype
525         in the source file.
526 <programlisting>
527 /* declaration in the header. */
528 void maman_bar_do_action (MamanBar *self, /* parameters */);
529
530 /* implementation in the source file */
531 void
532 maman_bar_do_action (MamanBar *self, /* parameters */)
533 {
534   g_return_if_fail (MAMAN_IS_BAR (self));
535
536   /* do stuff here. */
537 }
538 </programlisting>
539       </para>
540
541       <para>There is really nothing scary about this.</para>
542     </sect2>
543
544     <sect2>
545       <title>Virtual public methods</title>
546
547       <para>
548         This is the preferred way to create polymorphic GObjects. All you
549         need to do is to define the common method and its class function in
550         the public header, implement the common method in the source file
551         and re-implement the class function in each object which inherits
552         from you.
553 <programlisting>
554 /* declaration in maman-bar.h. */
555 struct _MamanBarClass
556 {
557   GObjectClass parent_class;
558
559   /* stuff */
560   void (*do_action) (MamanBar *self, /* parameters */);
561 };
562
563 void maman_bar_do_action (MamanBar *self, /* parameters */);
564
565 /* implementation in maman-bar.c */
566 void
567 maman_bar_do_action (MamanBar *self, /* parameters */)
568 {
569   g_return_if_fail (MAMAN_IS_BAR (self));
570
571   MAMAN_BAR_GET_CLASS (self)->do_action (self, /* parameters */);
572 }
573 </programlisting>
574         The code above simply redirects the do_action call to the relevant
575         class function. Some users, concerned about performance, do not
576         provide the <function>maman_bar_do_action</function> wrapper function
577         and require users to dereference the class pointer themselves. This
578         is not such a great idea in terms of encapsulation and makes it
579         difficult to change the object's implementation afterwards, should
580         this be needed.
581       </para>
582
583       <para>
584         Other users, also concerned by performance issues, declare
585         the <function>maman_bar_do_action</function> function inline in the
586         header file. This, however, makes it difficult to change the
587         object's implementation later (although easier than requiring users
588         to directly dereference the class function) and is often difficult
589         to write in a portable way (the <emphasis>inline</emphasis> keyword
590         is part of the C99 standard but not every compiler supports it).
591       </para>
592
593       <para>
594         In doubt, unless a user shows you hard numbers about the performance
595         cost of the function call, just implement <function>maman_bar_do_action</function>
596         in the source file.
597       </para>
598
599       <para>
600         Please, note that it is possible for you to provide a default
601         implementation for this class method in the object's
602         <function>class_init</function> function: initialize the
603         klass-&gt;do_action field to a pointer to the actual implementation.
604         You can also make this class method pure virtual by initializing
605         the klass-&gt;do_action field to NULL:
606 <programlisting>
607 static void
608 maman_bar_real_do_action_two (MamanBar *self, /* parameters */)
609 {
610   /* Default implementation for the virtual method. */
611 }
612
613 static void
614 maman_bar_class_init (BarClass *klass)
615 {
616   /* pure virtual method: mandates implementation in children. */
617   klass->do_action_one = NULL;
618
619   /* merely virtual method. */
620   klass->do_action_two = maman_bar_real_do_action_two;
621 }
622
623 void
624 maman_bar_do_action_one (MamanBar *self, /* parameters */)
625 {
626   g_return_if_fail (MAMAN_IS_BAR (self));
627
628   MAMAN_BAR_GET_CLASS (self)->do_action_one (self, /* parameters */);
629 }
630
631 void
632 maman_bar_do_action_two (MamanBar *self, /* parameters */)
633 {
634   g_return_if_fail (MAMAN_IS_BAR (self));
635
636   MAMAN_BAR_GET_CLASS (self)->do_action_two (self, /* parameters */);
637 }
638 </programlisting>
639       </para>
640     </sect2>
641
642     <sect2>
643       <title>Virtual private Methods</title>
644
645       <para>
646         These are very similar to Virtual Public methods. They just don't
647         have a public function to call the function directly. The header
648         file contains only a declaration of the class function:
649 <programlisting>
650 /* declaration in maman-bar.h. */
651 struct _MamanBarClass
652 {
653   GObjectClass parent;
654
655   /* stuff */
656   void (* helper_do_specific_action) (MamanBar *self, /* parameters */);
657 };
658
659 void maman_bar_do_any_action (MamanBar *self, /* parameters */);
660 </programlisting>
661         These class functions are often used to delegate part of the job
662         to child classes:
663 <programlisting>
664 /* this accessor function is static: it is not exported outside of this file. */
665 static void 
666 maman_bar_do_specific_action (MamanBar *self, /* parameters */)
667 {
668   MAMAN_BAR_GET_CLASS (self)->do_specific_action (self, /* parameters */);
669 }
670
671 void
672 maman_bar_do_any_action (MamanBar *self, /* parameters */)
673 {
674   /* random code here */
675
676   /* 
677    * Try to execute the requested action. Maybe the requested action
678    * cannot be implemented here. So, we delegate its implementation
679    * to the child class:
680    */
681   maman_bar_do_specific_action (self, /* parameters */);
682
683   /* other random code here */
684 }
685 </programlisting>
686       </para>
687
688       <para>
689         Again, it is possible to provide a default implementation for this
690         private virtual class function:
691 <programlisting>
692 static void
693 maman_bar_class_init (MamanBarClass *klass)
694 {
695   /* pure virtual method: mandates implementation in children. */
696   klass->do_specific_action_one = NULL;
697
698   /* merely virtual method. */
699   klass->do_specific_action_two = maman_bar_real_do_specific_action_two;
700 }
701 </programlisting>
702       </para>
703
704       <para>
705         Children can then implement the subclass with code such as:
706 <programlisting>
707 static void
708 maman_bar_subtype_class_init (MamanBarSubTypeClass *klass)
709 {
710   MamanBarClass *bar_class = MAMAN_BAR_CLASS (klass);
711
712   /* implement pure virtual class function. */
713   bar_class->do_specific_action_one = maman_bar_subtype_do_specific_action_one;
714 }
715 </programlisting>
716       </para>
717     </sect2>
718   </sect1>
719
720   <sect1 id="howto-gobject-chainup">
721     <title>Chaining up</title>
722     
723     <para>Chaining up is often loosely defined by the following set of
724     conditions:
725       <itemizedlist>
726         <listitem><para>Parent class A defines a public virtual method named <function>foo</function> and 
727         provides a default implementation.</para></listitem>
728         <listitem><para>Child class B re-implements method <function>foo</function>.</para></listitem>
729         <listitem><para>In the method B::foo, the child class B calls its parent class method A::foo.</para></listitem>
730       </itemizedlist>
731       There are many uses to this idiom:
732       <itemizedlist>
733         <listitem><para>You need to change the behaviour of a class without modifying its code. You create
734           a subclass to inherit its implementation, re-implement a public virtual method to modify the behaviour
735           slightly and chain up to ensure that the previous behaviour is not really modified, just extended.
736           </para></listitem>
737         <listitem><para>You are lazy, you have access to the source code of the parent class but you don't want 
738           to modify it to add method calls to new specialized method calls: it is faster to hack the child class
739           to chain up than to modify the parent to call down.</para></listitem>
740         <listitem><para>You need to implement the Chain Of Responsibility pattern: each object of the inheritance
741           tree chains up to its parent (typically, at the beginning or the end of the method) to ensure that
742           they each handler is run in turn.</para></listitem>
743       </itemizedlist>
744       I am personally not really convinced any of the last two uses are really a good idea but since this
745       programming idiom is often used, this section attempts to explain how to implement it.
746     </para>
747
748     <para>
749       To explicitly chain up to the implementation of the virtual method in the parent class, 
750       you first need a handle to the original parent class structure. This pointer can then be used to 
751       access the original class function pointer and invoke it directly.
752       <footnote>
753         <para>
754           The <emphasis>original</emphasis> adjective used in this sentence is not innocuous. To fully 
755           understand its meaning, you need to recall how class structures are initialized: for each object type,
756           the class structure associated to this object is created by first copying the class structure of its 
757           parent type (a simple <function>memcpy</function>) and then by invoking the class_init callback on 
758           the resulting class structure. Since the class_init callback is responsible for overwriting the class structure
759           with the user re-implementations of the class methods, we cannot merely use the modified copy of the parent class
760           structure stored in our derived instance. We want to get a copy of the class structure of an instance of the parent 
761           class.
762         </para>
763       </footnote>
764     </para>
765     
766     <para>The function <function><link linkend="g-type-class-peek-parent">g_type_class_peek_parent</link></function> is used to access the original parent 
767     class structure. Its input is a pointer to the class of the derived object and it returns a pointer
768     to the original parent class structure. The code below shows how you could use it:
769 <programlisting>
770 static void
771 b_method_to_call (B *obj, int a)
772 {
773   BClass *klass;
774   AClass *parent_class;
775
776   klass = B_GET_CLASS (obj);
777   parent_class = g_type_class_peek_parent (klass);
778
779   /* do stuff before chain up */
780
781   parent_class->method_to_call (obj, a);
782
783   /* do stuff after chain up */
784 }
785 </programlisting>
786   </para>
787
788   </sect1>
789
790 </chapter>
791 <!-- End Howto GObject -->
792
793 <chapter id="howto-interface">
794   <title>How to define and implement interfaces</title>
795
796   <sect1 id="howto-interface-define">
797     <title>Defining interfaces</title>
798   
799   <para>
800     The bulk of interface definition has already been shown in <xref linkend="gtype-non-instantiable-classed"/>
801     but I feel it is needed to show exactly how to create an interface.
802   </para>
803
804   <para>
805     As above, the first step is to get the header right. This interface
806     defines two methods:
807 <programlisting>
808 #ifndef __MAMAN_IBAZ_H__
809 #define __MAMAN_IBAZ_H__
810
811 #include &lt;glib-object.h&gt;
812
813 #define MAMAN_TYPE_IBAZ                 (maman_ibaz_get_type ())
814 #define MAMAN_IBAZ(obj)                 (G_TYPE_CHECK_INSTANCE_CAST ((obj), MAMAN_TYPE_IBAZ, MamanIbaz))
815 #define MAMAN_IS_IBAZ(obj)              (G_TYPE_CHECK_INSTANCE_TYPE ((obj), MAMAN_TYPE_IBAZ))
816 #define MAMAN_IBAZ_GET_INTERFACE(inst)  (G_TYPE_INSTANCE_GET_INTERFACE ((inst), MAMAN_TYPE_IBAZ, MamanIbazInterface))
817
818
819 typedef struct _MamanIbaz               MamanIbaz; /* dummy object */
820 typedef struct _MamanIbazInterface      MamanIbazInterface;
821
822 struct _MamanIbazInterface
823 {
824   GTypeInterface parent_iface;
825
826   void (*do_action) (MamanIbaz *self);
827   void (*do_something) (MamanIbaz *self);
828 };
829
830 GType maman_ibaz_get_type (void);
831
832 void maman_ibaz_do_action    (MamanIbaz *self);
833 void maman_ibaz_do_something (MamanIbaz *self);
834
835 #endif /* __MAMAN_IBAZ_H__ */
836 </programlisting>
837     This code is the same as the code for a normal <link linkend="GType"><type>GType</type></link>
838     which derives from a <link linkend="GObject"><type>GObject</type></link> except for a few details:
839     <itemizedlist>
840       <listitem><para>
841         The <function>_GET_CLASS</function> macro is called <function>_GET_INTERFACE</function>
842                   and not implemented with <function><link linkend="G-TYPE-INSTANCE-GET-CLASS:CAPS">G_TYPE_INSTANCE_GET_CLASS</link></function>
843                   but with <function><link linkend="G-TYPE-INSTANCE-GET-INTERFACE:CAPS">G_TYPE_INSTANCE_GET_INTERFACE</link></function>.
844       </para></listitem>
845       <listitem><para>
846         The instance type, <type>MamanIbaz</type> is not fully defined: it is
847         used merely as an abstract type which represents an instance of
848         whatever object which implements the interface.
849       </para></listitem>
850       <listitem><para>
851         The parent of the <type>MamanIbazInterface</type> is not
852         <type>GObjectClass</type> but <type>GTypeInterface</type>.
853       </para></listitem>
854     </itemizedlist>
855   </para>
856
857   <para>
858     The implementation of the <type>MamanIbaz</type> type itself is trivial:
859     <itemizedlist>
860       <listitem><para><function><link linkend="G-DEFINE-INTERFACE:CAPS">G_DEFINE_INTERFACE</link></function>
861        creates a <function>maman_ibaz_get_type</function> function which registers the
862        type in the type system. The third argument is used to define a
863        <link linkend="howto-interface-prerequisite">prerequisite interface</link>
864        (which we'll talk about more later). Just pass <code>0</code> for this
865        argument when an interface has no prerequisite.
866        </para></listitem>
867       <listitem><para><function>maman_ibaz_default_init</function> is expected
868       to register the interface's signals if there are any (we will see a bit
869       later how to use them).</para></listitem>
870       <listitem><para>The interface methods <function>maman_ibaz_do_action</function>
871       and <function>maman_ibaz_do_something</function> dereference the interface
872       structure to access its associated interface function and call it.
873       </para></listitem>
874     </itemizedlist>
875 <programlisting>
876 G_DEFINE_INTERFACE (MamanIbaz, maman_ibaz, 0);
877
878 static void
879 maman_ibaz_default_init (gpointer g_class)
880 {
881     /* add properties and signals to the interface here */
882 }
883
884 void
885 maman_ibaz_do_action (MamanIbaz *self)
886 {
887   g_return_if_fail (MAMAN_IS_IBAZ (self));
888
889   MAMAN_IBAZ_GET_INTERFACE (self)->do_action (self);
890 }
891
892 void
893 maman_ibaz_do_something (MamanIbaz *self)
894 {
895   g_return_if_fail (MAMAN_IS_IBAZ (self));
896
897   MAMAN_IBAZ_GET_INTERFACE (self)->do_something (self);
898 }
899 </programlisting>
900     </para>
901   </sect1>
902   
903   <sect1 id="howto-interface-implement">
904     <title>Implementing interfaces</title>
905   
906     <para>
907       Once the interface is defined, implementing it is rather trivial.
908     </para>
909   
910     <para>
911       The first step is to define a normal GObject class, like:
912 <programlisting>
913 #ifndef __MAMAN_BAZ_H__
914 #define __MAMAN_BAZ_H__
915
916 #include &lt;glib-object.h&gt;
917
918 #define MAMAN_TYPE_BAZ             (maman_baz_get_type ())
919 #define MAMAN_BAZ(obj)             (G_TYPE_CHECK_INSTANCE_CAST ((obj), MAMAN_TYPE_BAZ, Mamanbaz))
920 #define MAMAN_IS_BAZ(obj)          (G_TYPE_CHECK_INSTANCE_TYPE ((obj), MAMAN_TYPE_BAZ))
921 #define MAMAN_BAZ_CLASS(klass)     (G_TYPE_CHECK_CLASS_CAST ((klass), MAMAN_TYPE_BAZ, MamanbazClass))
922 #define MAMAN_IS_BAZ_CLASS(klass)  (G_TYPE_CHECK_CLASS_TYPE ((klass), MAMAN_TYPE_BAZ))
923 #define MAMAN_BAZ_GET_CLASS(obj)   (G_TYPE_INSTANCE_GET_CLASS ((obj), MAMAN_TYPE_BAZ, MamanbazClass))
924
925
926 typedef struct _MamanBaz        MamanBaz;
927 typedef struct _MamanBazClass   MamanBazClass;
928
929 struct _MamanBaz
930 {
931   GObject parent_instance;
932
933   gint instance_member;
934 };
935
936 struct _MamanBazClass
937 {
938   GObjectClass parent_class;
939 };
940
941 GType maman_baz_get_type (void);
942
943 #endif /* __MAMAN_BAZ_H__ */
944 </programlisting>
945       <!-- Ha ha! "nothing weird or scary". I actually laughed out loud. Oh boy.
946            The fact that we're so intimate with GObject that all this doesn't look
947            wierd, that's the scary thing. :) -->
948       There is clearly nothing specifically weird or scary about this header:
949       it does not define any weird API or derive from a weird type.
950     </para>
951   
952     <para>
953       The second step is to implement <type>MamanBaz</type> by defining
954       its GType. Instead of using
955       <function><link linkend="G-DEFINE-TYPE:CAPS">G_DEFINE_TYPE</link></function>
956       we use
957       <function><link linkend="G-DEFINE-TYPE-WITH-CODE:CAPS">G_DEFINE_TYPE_WITH_CODE</link></function>
958       and the
959       <function><link linkend="G-IMPLEMENT-INTERFACE:CAPS">G_IMPLEMENT_INTERFACE</link></function>
960       macros.
961 <programlisting>
962 static void maman_ibaz_interface_init (MamanIbazInterface *iface);
963
964 G_DEFINE_TYPE_WITH_CODE (MamanBar, maman_bar, G_TYPE_OBJECT,
965                          G_IMPLEMENT_INTERFACE (MAMAN_TYPE_IBAZ,
966                                                 maman_ibaz_interface_init));
967 </programlisting>
968       This definition is very much like all the similar functions we looked
969       at previously. The only interface-specific code present here is the call to
970       <function><link linkend="G-IMPLEMENT-INTERFACE:CAPS">G_IMPLEMENT_INTERFACE</link></function>.
971     </para>
972
973     <note><para>Classes can implement multiple interfaces by using multiple calls to
974     <function><link linkend="G-IMPLEMENT-INTERFACE:CAPS">G_IMPLEMENT_INTERFACE</link></function>
975     inside the call to
976     <function><link linkend="G-DEFINE-TYPE-WITH-CODE:CAPS">G_DEFINE_TYPE_WITH_CODE</link></function>
977     </para></note>
978   
979     <para>
980       <function>maman_baz_interface_init</function>, the interface
981       initialization function: inside it every virtual method of the interface
982       must be assigned to its implementation:
983 <programlisting>
984 static void
985 maman_baz_do_action (MamanBaz *self)
986 {
987   g_print ("Baz implementation of Ibaz interface Action: 0x%x.\n",
988            self->instance_member);
989 }
990
991 static void
992 maman_baz_do_something (MamanBaz *self)
993 {
994   g_print ("Baz implementation of Ibaz interface Something: 0x%x.\n",
995            self->instance_member);
996 }
997
998 static void
999 maman_ibaz_interface_init (MamanIbazInterface *iface)
1000 {
1001   iface->do_action = maman_baz_do_action;
1002   iface->do_something = maman_baz_do_something;
1003 }
1004
1005 static void
1006 maman_baz_init (MamanBaz *self)
1007 {
1008   MamanBaz *self = MAMAN_BAZ (instance);
1009   self->instance_member = 0xdeadbeaf;
1010 }
1011 </programlisting>
1012     </para>
1013   </sect1>
1014   
1015   <sect1 id="howto-interface-prerequisite">
1016     <title>Interface definition prerequisites</title>
1017   
1018     <para>
1019       To specify that an interface requires the presence of other interfaces
1020       when implemented, GObject introduces the concept of
1021       <emphasis>prerequisites</emphasis>: it is possible to associate
1022       a list of prerequisite types to an interface. For example, if
1023       object A wishes to implement interface I1, and if interface I1 has a
1024       prerequisite on interface I2, A has to implement both I1 and I2.
1025     </para>
1026   
1027     <para>
1028       The mechanism described above is, in practice, very similar to
1029       Java's interface I1 extends interface I2. The example below shows
1030       the GObject equivalent:
1031 <programlisting>
1032 /* Make the MamanIbar interface require MamanIbaz interface. */
1033 G_DEFINE_INTERFACE (MamanIbar, maman_ibar, MAMAN_TYPE_IBAZ);
1034 </programlisting>
1035       In the <function><link linkend="G-DEFINE-INTERFACE:CAPS">G_DEFINE_INTERFACE</link></function>
1036       call above, the third parameter defines the prerequisite type. This
1037       is the GType of either an interface or a class. In this case
1038       the MamanIbaz interface is a prerequisite of the MamanIbar. The code
1039       below shows how an implementation can implement both interfaces and
1040       register their implementations:
1041 <programlisting>
1042 static void
1043 maman_ibar_do_another_action (MamanIbar *ibar)
1044 {
1045   MamanBar *self = MAMAN_BAR (ibar);
1046
1047   g_print ("Bar implementation of IBar interface Another Action: 0x%x.\n",
1048            self->instance_member);
1049 }
1050
1051 static void
1052 maman_ibar_interface_init (MamanIbarInterface *iface)
1053 {
1054   iface->do_another_action = maman_ibar_do_another_action;
1055 }
1056
1057 static void
1058 maman_ibaz_do_action (MamanIbaz *ibaz)
1059 {
1060   MamanBar *self = MAMAN_BAR (ibaz);
1061
1062   g_print ("Bar implementation of Ibaz interface Action: 0x%x.\n",
1063            self->instance_member);
1064 }
1065
1066 static void
1067 maman_ibaz_do_something (MamanIbaz *ibaz)
1068 {
1069   MamanBar *self = MAMAN_BAR (ibaz);
1070
1071   g_print ("Bar implementation of Ibaz interface Something: 0x%x.\n",
1072            self->instance_member);
1073 }
1074
1075 static void
1076 maman_ibaz_interface_init (MamanIbazInterface *iface)
1077 {
1078   iface->do_action = maman_ibaz_do_action;
1079   iface->do_something = maman_ibaz_do_something;
1080 }
1081
1082 static void
1083 maman_bar_class_init (MamanBarClass *klass)
1084 {
1085
1086 }
1087
1088 static void
1089 maman_bar_init (MamanBar *self)
1090 {
1091   self->instance_member = 0x666;
1092 }
1093
1094 G_DEFINE_TYPE_WITH_CODE (MamanBar, maman_bar, G_TYPE_OBJECT,
1095                          G_IMPLEMENT_INTERFACE (MAMAN_TYPE_IBAZ,
1096                                                 maman_ibaz_interface_init)
1097                          G_IMPLEMENT_INTERFACE (MAMAN_TYPE_IBAR,
1098                                                 maman_ibar_interface_init));
1099 </programlisting>
1100       It is very important to notice that the order in which interface
1101       implementations are added to the main object is not random:
1102       <function><link linkend="g-type-add-interface-static">g_type_add_interface_static</link></function>,
1103       which is called by
1104       <function><link linkend="G-DEFINE-INTERFACE:CAPS">G_IMPLEMENT_INTERFACE</link></function>,
1105       must be invoked first on the interfaces which have no prerequisites and then on
1106       the others.
1107     </para>
1108   </sect1>
1109   
1110   <sect1 id="howto-interface-properties">
1111     <title>Interface properties</title>
1112   
1113     <para>
1114       GObject interfaces can also have
1115       properties. Declaration of the interface properties is similar to
1116       declaring the properties of ordinary GObject types as explained in
1117       <xref linkend="gobject-properties"/>, except that
1118       <function><link linkend="g-object-interface-install-property">g_object_interface_install_property</link></function>
1119       is used to declare the properties instead of
1120       <function><link linkend="g-object-class-install-property">g_object_class_install_property</link></function>.
1121     </para>
1122   
1123     <para>
1124       To include a property named 'name' of type <type>string</type> in the 
1125       <type>maman_ibaz</type> interface example code above, we only need to
1126       add one 
1127       <footnote>
1128         <para>
1129           That really is one line extended to six for the sake of clarity
1130         </para>
1131       </footnote>  
1132       line in the <function>maman_ibaz_default_init</function> as shown below:
1133 <programlisting>
1134 static void
1135 maman_ibaz_default_init (gpointer g_iface)
1136 {
1137   g_object_interface_install_property (g_iface,
1138                                        g_param_spec_string ("name",
1139                                                             "Name",
1140                                                             "Name of the MamanIbaz",
1141                                                             "maman",
1142                                                             G_PARAM_READWRITE));
1143 }
1144 </programlisting>
1145     </para>
1146   
1147     <para>
1148       One point worth noting is that the declared property wasn't assigned an 
1149       integer ID. The reason being that integer IDs of properties are used
1150       only inside the get and set methods and since interfaces do not
1151       implement properties, there is no need to assign integer IDs to
1152       interface properties.
1153     </para>
1154     
1155     <para>
1156       An implementation declares and defines it's properties in the usual
1157       way as explained in <xref linkend="gobject-properties"/>, except for one
1158       small change: it can declare the properties of the interface it
1159       implements using <function><link linkend="g-object-class-override-property">g_object_class_override_property</link></function>
1160       instead of <function><link linkend="g-object-class-install-property">g_object_class_install_property</link></function>.
1161       The following code snippet shows the modifications needed in the
1162       <type>MamanBaz</type> declaration and implementation above:
1163 <programlisting>
1164
1165 struct _MamanBaz
1166 {
1167   GObject parent_instance;
1168
1169   gint instance_member;
1170   gchar *name;
1171 };
1172
1173 enum
1174 {
1175   PROP_0,
1176   PROP_NAME
1177 };
1178
1179 static void
1180 maman_baz_set_property (GObject      *object,
1181                         guint         prop_id,
1182                         const GValue *value,
1183                         GParamSpec   *pspec)
1184 {
1185   MamanBaz *baz = MAMAN_BAZ (object);
1186
1187   switch (prop_id)
1188     {
1189     case PROP_NAME:
1190       g_free (baz->name);
1191       baz->name = g_value_dup_string (value);
1192       break;
1193
1194     default:
1195       G_OBJECT_WARN_INVALID_PROPERTY_ID (object, prop_id, pspec);
1196       break;
1197     }
1198 }
1199
1200 static void
1201 maman_baz_get_property (GObject    *object,
1202                         guint       prop_id,
1203                         GValue     *value,
1204                         GParamSpec *pspec)
1205 {
1206   MamanBaz *baz = MAMAN_BAZ (object);
1207
1208   switch (prop_id)
1209     {
1210     case PROP_NAME:
1211       g_value_set_string (value, baz->name);
1212       break;
1213
1214     default:
1215       G_OBJECT_WARN_INVALID_PROPERTY_ID (object, prop_id, pspec);
1216       break;
1217     }
1218 }
1219
1220 static void
1221 maman_baz_class_init (MamanBazClass *klass)
1222 {
1223   GObjectClass *gobject_class = G_OBJECT_CLASS (klass);
1224
1225   gobject_class->set_property = maman_baz_set_property;
1226   gobject_class->get_property = maman_baz_get_property;
1227
1228   g_object_class_override_property (gobject_class, PROP_NAME, "name");
1229 }
1230
1231 </programlisting>
1232     </para>
1233   
1234   </sect1>
1235
1236   <sect1 id="howto-interface-override">
1237     <title>Overriding interface methods</title>
1238
1239     <para>
1240       If a base class already implements an interface, and in a derived
1241       class you wish to implement the same interface overriding only certain
1242       methods of that interface, you just reimplement the interface and
1243       set only the interface methods you wish to override.
1244     </para>
1245
1246     <para>
1247       In this example MamanDerivedBaz is derived from MamanBaz. Both
1248       implement the MamanIbaz interface. MamanDerivedBaz only implements one
1249       method of the MamanIbaz interface and uses the base class implementation
1250       of the other.
1251 <programlisting>
1252 static void
1253 maman_derived_ibaz_do_action (MamanIbaz *ibaz)
1254 {
1255   MamanDerivedBaz *self = MAMAN_DERIVED_BAZ (ibaz);
1256   g_print ("DerivedBaz implementation of Ibaz interface Action\n");
1257 }
1258
1259 static void
1260 maman_derived_ibaz_interface_init (MamanIbazInterface *iface)
1261 {
1262   /* Override the implementation of do_action */
1263   iface->do_action = maman_derived_ibaz_do_action;
1264
1265   /*
1266    * We simply leave iface->do_something alone, it is already set to the
1267    * base class implementation.
1268    */
1269 }
1270
1271 G_DEFINE_TYPE_WITH_CODE (MamanDerivedBaz, maman_derived_baz, MAMAN_TYPE_BAZ,
1272                          G_IMPLEMENT_INTERFACE (MAMAN_TYPE_IBAZ,
1273                                                 maman_derived_ibaz_interface_init)
1274
1275 static void
1276 maman_derived_baz_class_init (MamanDerivedBazClass *klass)
1277 {
1278
1279 }
1280
1281 static void
1282 maman_derived_baz_init (MamanDerivedBaz *self)
1283 {
1284
1285 }
1286 </programlisting>
1287     </para>
1288
1289     <para>
1290       To access the base class interface implementation use
1291       <function><link linkend="g-type-interface-peek-parent">g_type_interface_peek_parent</link></function>
1292       from within an interface's <function>default_init</function> function.
1293     </para>
1294
1295     <para>
1296       If you wish to call the base class implementation of an interface
1297       method from an derived class where than interface method has been
1298       overridden then you can stash away the pointer returned from
1299       <function><link linkend="g-type-interface-peek-parent">g_type_interface_peek_parent</link></function>
1300       in a global variable.
1301     </para>
1302
1303     <para>
1304       In this example MamanDerivedBaz overides the
1305       <function>do_action</function> interface method. In it's overridden method
1306       it calls the base class implementation of the same interface method.
1307 <programlisting>
1308 static MamanIbazInterface *maman_ibaz_parent_interface = NULL;
1309
1310 static void
1311 maman_derived_ibaz_do_action (MamanIbaz *ibaz)
1312 {
1313   MamanDerivedBaz *self = MAMAN_DERIVED_BAZ (ibaz);
1314   g_print ("DerivedBaz implementation of Ibaz interface Action\n");
1315
1316   /* Now we call the base implementation */
1317   maman_ibaz_parent_interface->do_action (ibaz);
1318 }
1319
1320 static void
1321 maman_derived_ibaz_interface_init (MamanIbazInterface *iface)
1322 {
1323   maman_ibaz_parent_interface = g_type_interface_peek_parent (iface);
1324   iface->do_action = maman_derived_ibaz_do_action;
1325 }
1326
1327 G_DEFINE_TYPE_WITH_CODE (MamanDerivedBaz, maman_derived_baz, MAMAN_TYPE_BAZ,
1328                          G_IMPLEMENT_INTERFACE (MAMAN_TYPE_IBAZ,
1329                                                 maman_derived_ibaz_interface_init)
1330
1331 static void
1332 maman_derived_baz_class_init (MamanDerivedBazClass *klass)
1333 {
1334
1335 }
1336
1337 static void
1338 maman_derived_baz_init (MamanDerivedBaz *self)
1339 {
1340
1341 }
1342 </programlisting>
1343     </para>
1344
1345   </sect1>
1346
1347 </chapter>
1348 <!-- End Howto Interfaces -->
1349
1350 <chapter id="howto-signals">
1351   <title>How to create and use signals</title>
1352
1353   <para>
1354     The signal system which was built in GType is pretty complex and
1355     flexible: it is possible for its users to connect at runtime any
1356     number of callbacks (implemented in any language for which a binding
1357     exists)
1358     <footnote>
1359       <para>A Python callback can be connected to any signal on any
1360       C-based GObject.
1361       </para>
1362     </footnote>
1363     to any signal and to stop the emission of any signal at any 
1364     state of the signal emission process. This flexibility makes it
1365     possible to use GSignal for much more than just emit signals which
1366     can be received by numerous clients. 
1367   </para>
1368
1369   <sect1 id="howto-simple-signals">
1370     <title>Simple use of signals</title>
1371
1372     <para>
1373       The most basic use of signals is to implement simple event
1374       notification: for example, if we have a MamanFile object, and
1375       if this object has a write method, we might wish to be notified
1376       whenever someone has changed something via our MamanFile instance.
1377       The code below shows how the user can connect a callback to the
1378       "changed" signal.
1379 <programlisting>
1380 file = g_object_new (MAMAN_FILE_TYPE, NULL);
1381
1382 g_signal_connect (file, "changed", G_CALLBACK (changed_event), NULL);
1383
1384 maman_file_write (file, buffer, strlen (buffer));
1385 </programlisting>
1386     </para>
1387     
1388     <para>
1389       The <type>MamanFile</type> signal is registered in the class_init
1390       function:
1391 <programlisting>
1392 file_signals[CHANGED] = 
1393   g_signal_newv ("changed",
1394                  G_TYPE_FROM_CLASS (gobject_class),
1395                  G_SIGNAL_RUN_LAST | G_SIGNAL_NO_RECURSE | G_SIGNAL_NO_HOOKS,
1396                  NULL /* closure */,
1397                  NULL /* accumulator */,
1398                  NULL /* accumulator data */,
1399                  g_cclosure_marshal_VOID__VOID,
1400                  G_TYPE_NONE /* return_type */,
1401                  0     /* n_params */,
1402                  NULL  /* param_types */);
1403 </programlisting>
1404       and the signal is emitted in <function>maman_file_write</function>:
1405 <programlisting>
1406 void
1407 maman_file_write (MamanFile    *self,
1408                   const guchar *buffer,
1409                   gssize        size)
1410 {
1411   /* First write data. */
1412
1413   /* Then, notify user of data written. */
1414   g_signal_emit (self, file_signals[CHANGED], 0 /* details */);
1415 }
1416 </programlisting>
1417       As shown above, you can safely set the details parameter to zero if
1418       you do not know what it can be used for. For a discussion of what you
1419       could used it for, see <xref linkend="signal-detail"/>
1420     </para>
1421
1422     <para>
1423       The signature of the signal handler in the above example is defined as
1424       <function>g_cclosure_marshal_VOID__VOID</function>. Its name follows
1425       a simple convention which encodes the function parameter and return value
1426       types in the function name. Specifically, the value in front of the
1427       double underscore is the type of the return value, while the value(s)
1428       after the double underscore denote the parameter types.
1429     </para>
1430
1431     <para>
1432       The header <filename>gobject/gmarshal.h</filename> defines a set of
1433       commonly needed closures that one can use. If you want to have complex
1434       marshallers for your signals you should probably use glib-genmarshal
1435       to autogenerate them from a file containing their return and
1436       parameter types.
1437     </para>
1438   </sect1>
1439
1440 <!-- 
1441   this is utterly wrong and should be completely removed - or rewritten
1442   with a better example than writing a buffer using synchronous signals.
1443
1444   <sect1>
1445     <title>How to provide more flexibility to users?</title>
1446
1447     <para>
1448       The previous implementation does the job but the signal facility of
1449       GObject can be used to provide even more flexibility to this file
1450       change notification mechanism. One of the key ideas is to make the
1451       process of writing data to the file part of the signal emission
1452       process to allow users to be notified either before or after the
1453       data is written to the file.
1454     </para>
1455     
1456     <para>
1457       To integrate the process of writing the data to the file into the
1458       signal emission mechanism, we can register a default class closure
1459       for this signal which will be invoked during the signal emission,
1460       just like any other user-connected signal handler. 
1461     </para>
1462     
1463     <para>
1464       The first step to implement this idea is to change the signature of
1465       the signal: we need to pass around the buffer to write and its size.
1466       To do this, we use our own marshaller which will be generated
1467       through GLib's glib-genmarshal tool. We thus create a file named <filename>marshall.list</filename> which contains
1468       the following single line:
1469 <programlisting>
1470 VOID:POINTER,UINT
1471 </programlisting>
1472       and use the Makefile provided in <filename>sample/signal/Makefile</filename> to generate the file named
1473       <filename>maman-file-complex-marshall.c</filename>. This C file is finally included in 
1474       <filename>maman-file-complex.c</filename>.
1475     </para>
1476
1477     <para>
1478       Once the marshaller is present, we register the signal and its marshaller in the class_init function 
1479       of the object <type>MamanFileComplex</type> (full source for this object is included in 
1480       <filename>sample/signal/maman-file-complex.{h|c}</filename>):
1481 <programlisting>
1482 GClosure *default_closure;
1483 GType param_types[2];
1484
1485 default_closure = g_cclosure_new (G_CALLBACK (default_write_signal_handler),
1486                                   (gpointer)0xdeadbeaf /* user_data */, 
1487                                   NULL /* destroy_data */);
1488
1489 param_types[0] = G_TYPE_POINTER;
1490 param_types[1] = G_TYPE_UINT;
1491 klass->write_signal_id = 
1492   g_signal_newv ("write",
1493                  G_TYPE_FROM_CLASS (g_class),
1494                  G_SIGNAL_RUN_LAST | G_SIGNAL_NO_RECURSE | G_SIGNAL_NO_HOOKS,
1495                  default_closure /* class closure */,
1496                  NULL /* accumulator */,
1497                  NULL /* accu_data */,
1498                  maman_file_complex_VOID__POINTER_UINT,
1499                  G_TYPE_NONE /* return_type */,
1500                  2     /* n_params */,
1501                  param_types /* param_types */);
1502 </programlisting>
1503       The code shown above first creates the closure which contains the code to complete the file write. This
1504       closure is registered as the default class_closure of the newly created signal.
1505     </para>
1506
1507     <para>
1508       Of course, you need to implement completely the code for the default closure since I just provided
1509       a skeleton:
1510 <programlisting>
1511 static void
1512 default_write_signal_handler (GObject *obj, guint8 *buffer, guint size, gpointer user_data)
1513 {
1514   g_assert (user_data == (gpointer)0xdeadbeaf);
1515   /* Here, we trigger the real file write. */
1516   g_print ("default signal handler: 0x%x %u\n", buffer, size);
1517 }
1518 </programlisting>
1519     </para>
1520
1521     <para>
1522       Finally, the client code must invoke the <function>maman_file_complex_write</function> function which 
1523       triggers the signal emission:
1524 <programlisting>
1525 void maman_file_complex_write (MamanFileComplex *self, guint8 *buffer, guint size)
1526 {
1527   /* trigger event */
1528   g_signal_emit (self,
1529                  MAMAN_FILE_COMPLEX_GET_CLASS (self)->write_signal_id,
1530                  0, /* details */
1531                  buffer, size);
1532 }
1533 </programlisting>
1534     </para>
1535     
1536     <para>
1537       The client code (as shown in <filename>sample/signal/test.c</filename> and below) can now connect signal handlers before 
1538       and after the file write is completed: since the default signal handler which does the write itself runs during the 
1539       RUN_LAST phase of the signal emission, it will run after all handlers connected with <function><link linkend="g-signal-connect">g_signal_connect</link></function>
1540       and before all handlers connected with <function><link linkend="g-signal-connect-after">g_signal_connect_after</link></function>. If you intent to write a GObject
1541       which emits signals, I would thus urge you to create all your signals with the G_SIGNAL_RUN_LAST such that your users
1542       have a maximum of flexibility as to when to get the event. Here, we combined it with G_SIGNAL_NO_RECURSE and 
1543       G_SIGNAL_NO_HOOKS to ensure our users will not try to do really weird things with our GObject. I strongly advise you
1544       to do the same unless you really know why (in which case you really know the inner workings of GSignal by heart and
1545       you are not reading this).
1546     </para>
1547     
1548     <para>
1549 <programlisting>
1550 static void complex_write_event_before (GObject *file, guint8 *buffer, guint size, gpointer user_data)
1551 {
1552   g_assert (user_data == NULL);
1553   g_print ("Complex Write event before: 0x%x, %u\n", buffer, size);
1554 }
1555
1556 static void complex_write_event_after (GObject *file, guint8 *buffer, guint size, gpointer user_data)
1557 {
1558   g_assert (user_data == NULL);
1559   g_print ("Complex Write event after: 0x%x, %u\n", buffer, size);
1560 }
1561
1562 static void test_file_complex (void)
1563 {
1564   guint8 buffer[100];
1565   GObject *file;
1566
1567   file = g_object_new (MAMAN_FILE_COMPLEX_TYPE, NULL);
1568
1569   g_signal_connect (G_OBJECT (file), "write",
1570                     (GCallback)complex_write_event_before,
1571                     NULL);
1572
1573   g_signal_connect_after (G_OBJECT (file), "write",
1574                           (GCallback)complex_write_event_after,
1575                           NULL);
1576
1577   maman_file_complex_write (MAMAN_FILE_COMPLEX (file), buffer, 50);
1578
1579   g_object_unref (G_OBJECT (file));
1580 }
1581 </programlisting>
1582       The code above generates the following output on my machine:
1583 <programlisting>
1584 Complex Write event before: 0xbfffe280, 50
1585 default signal handler: 0xbfffe280 50
1586 Complex Write event after: 0xbfffe280, 50
1587 </programlisting>
1588     </para>
1589
1590 -->
1591
1592 <!--
1593   this is also utterly wrong on so many levels that I don't even want
1594   to enumerate them. it's also full of completely irrelevant footnotes
1595   about personal preferences demonstrating a severe lack of whatsoever
1596   clue. the whole idea of storing the signal ids inside the Class
1597   structure is so fundamentally flawed that I'll require a frontal
1598   lobotomy just to forget I've ever seen it.
1599
1600     <sect2>
1601     <title>How most people do the same thing with less code</title>
1602     
1603       <para>For many historic reasons related to how the ancestor of GObject used to work in GTK+ 1.x versions,
1604         there is a much <emphasis>simpler</emphasis> 
1605         <footnote>
1606           <para>I personally think that this method is horribly mind-twisting: it adds a new indirection
1607           which unnecessarily complicates the overall code path. However, because this method is widely used
1608           by all of GTK+ and GObject code, readers need to understand it. The reason why this is done that way
1609           in most of GTK+ is related to the fact that the ancestor of GObject did not provide any other way to
1610           create a signal with a default handler than this one. Some people have tried to justify that it is done
1611           that way because it is better, faster (I am extremely doubtful about the faster bit. As a matter of fact,
1612           the better bit also mystifies me ;-). I have the feeling no one really knows and everyone does it
1613           because they copy/pasted code from code which did the same. It is probably better to leave this 
1614           specific trivia to hacker legends domain...
1615           </para>
1616         </footnote>
1617         way to create a signal with a default handler than to create 
1618         a closure by hand and to use the <function><link linkend="g-signal-newv">g_signal_newv</link></function>.
1619       </para>
1620     
1621       <para>For example, <function><link linkend="g-signal-new">g_signal_new</link></function> can be used to create a signal which uses a default 
1622         handler which is stored in the class structure of the object. More specifically, the class structure 
1623         contains a function pointer which is accessed during signal emission to invoke the default handler and
1624         the user is expected to provide to <function><link linkend="g-signal-new">g_signal_new</link></function> the offset from the start of the
1625         class structure to the function pointer.
1626           <footnote>
1627             <para>I would like to point out here that the reason why the default handler of a signal is named everywhere
1628              a class_closure is probably related to the fact that it used to be really a function pointer stored in
1629              the class structure.
1630             </para>
1631           </footnote>
1632       </para>
1633     
1634       <para>The following code shows the declaration of the <type>MamanFileSimple</type> class structure which contains
1635         the <function>write</function> function pointer.
1636 <programlisting>
1637 struct _MamanFileSimpleClass {
1638   GObjectClass parent;
1639         
1640   guint write_signal_id;
1641
1642   /* signal default handlers */
1643   void (*write) (MamanFileSimple *self, guint8 *buffer, guint size);
1644 };
1645 </programlisting>
1646         The <function>write</function> function pointer is initialized in the class_init function of the object
1647         to <function>default_write_signal_handler</function>:
1648 <programlisting>
1649 static void
1650 maman_file_simple_class_init (gpointer g_class,
1651                                gpointer g_class_data)
1652 {
1653   GObjectClass *gobject_class = G_OBJECT_CLASS (g_class);
1654   MamanFileSimpleClass *klass = MAMAN_FILE_SIMPLE_CLASS (g_class);
1655
1656   klass->write = default_write_signal_handler;
1657 </programlisting>
1658         Finally, the signal is created with <function><link linkend="g-signal-new">g_signal_new</link></function> in the same class_init function:
1659 <programlisting>
1660 klass->write_signal_id = 
1661  g_signal_new ("write",
1662                G_TYPE_FROM_CLASS (g_class),
1663                G_SIGNAL_RUN_LAST | G_SIGNAL_NO_RECURSE | G_SIGNAL_NO_HOOKS,
1664                G_STRUCT_OFFSET (MamanFileSimpleClass, write),
1665                NULL /* accumulator */,
1666                NULL /* accu_data */,
1667                maman_file_complex_VOID__POINTER_UINT,
1668                G_TYPE_NONE /* return_type */,
1669                2     /* n_params */,
1670                G_TYPE_POINTER,
1671                G_TYPE_UINT);
1672 </programlisting>
1673         Of note, here, is the 4th argument to the function: it is an integer calculated by the <function><link linkend="G-STRUCT-OFFSET">G_STRUCT_OFFSET</link></function>
1674         macro which indicates the offset of the member <emphasis>write</emphasis> from the start of the 
1675         <type>MamanFileSimpleClass</type> class structure.
1676         <footnote>
1677           <para>GSignal uses this offset to create a special wrapper closure 
1678            which first retrieves the target function pointer before calling it.
1679           </para>
1680         </footnote>
1681      </para>
1682
1683      <para>
1684        While the complete code for this type of default handler looks less cluttered as shown in 
1685        <filename>sample/signal/maman-file-simple.{h|c}</filename>, it contains numerous subtleties.
1686        The main subtle point which everyone must be aware of is that the signature of the default 
1687        handler created that way does not have a user_data argument: 
1688        <function>default_write_signal_handler</function> is different in 
1689        <filename>sample/signal/maman-file-complex.c</filename> and in 
1690        <filename>sample/signal/maman-file-simple.c</filename>.
1691      </para>
1692
1693      <para>If you have doubts about which method to use, I would advise you to use the second one which
1694        involves <function><link linkend="g-signal-new">g_signal_new</link></function> rather than <function><link linkend="g-signal-newv">g_signal_newv</link></function>: 
1695        it is better to write code which looks like the vast majority of other GTK+/GObject code than to
1696        do it your own way. However, now, you know why.
1697      </para>
1698
1699    </sect2>
1700
1701   </sect1>
1702 -->
1703
1704 <!--
1705   yet another pointless section. if we are scared of possible abuses
1706   from the users then we should not be mentioning it inside a tutorial
1707   for beginners. but, obviously, there's nothing to be afraid of - it's
1708   just that this section must be completely reworded.
1709
1710   <sect1>
1711     <title>How users can abuse signals (and why some think it is good)</title>
1712
1713     <para>Now that you know how to create signals to which the users can connect easily and at any point in
1714       the signal emission process thanks to <function><link linkend="g-signal-connect">g_signal_connect</link></function>, 
1715       <function><link linkend="g-signal-connect-after">g_signal_connect_after</link></function> and G_SIGNAL_RUN_LAST, it is time to look into how your
1716       users can and will screw you. This is also interesting to know how you too, can screw other people.
1717       This will make you feel good and eleet.
1718     </para>
1719     
1720     <para>
1721       The users can:
1722       <itemizedlist>
1723          <listitem><para>stop the emission of the signal at anytime</para></listitem>
1724          <listitem><para>override the default handler of the signal if it is stored as a function
1725            pointer in the class structure (which is the preferred way to create a default signal handler,
1726            as discussed in the previous section).</para></listitem>
1727        </itemizedlist> 
1728     </para>
1729     
1730     <para>
1731       In both cases, the original programmer should be as careful as possible to write code which is
1732       resistant to the fact that the default handler of the signal might not able to run. This is obviously
1733       not the case in the example used in the previous sections since the write to the file depends on whether
1734       or not the default handler runs (however, this might be your goal: to allow the user to prevent the file 
1735       write if he wishes to).
1736     </para>
1737     
1738     <para>
1739       If all you want to do is to stop the signal emission from one of the callbacks you connected yourself,
1740       you can call <function><link linkend="g-signal-stop-by-name">g_signal_stop_by_name</link></function>. Its use is very simple which is why I won't detail 
1741       it further.
1742     </para>
1743     
1744     <para>
1745       If the signal's default handler is just a class function pointer, it is also possible to override 
1746       it yourself from the class_init function of a type which derives from the parent. That way, when the signal
1747       is emitted, the parent class will use the function provided by the child as a signal default handler.
1748       Of course, it is also possible (and recommended) to chain up from the child to the parent's default signal 
1749       handler to ensure the integrity of the parent object.
1750     </para>
1751     
1752     <para>
1753       Overriding a class method and chaining up was demonstrated in <xref linkend="howto-gobject-methods"/> 
1754       which is why I won't bother to show exactly how to do it here again.
1755     </para>
1756
1757   </sect1>
1758
1759 -->
1760
1761 </chapter>
1762
1763 <!--
1764   <sect2>
1765     <title>Warning on signal creation and default closure</title>
1766
1767     <para>
1768       Most of the existing code I have seen up to now (in both GTK+, GNOME libraries and
1769       many GTK+ and GNOME applications) using signals uses a small
1770       variation of the default handler pattern I have shown in the previous section.
1771     </para>
1772
1773     <para>
1774       Usually, the <function><link linkend="g-signal-new">g_signal_new</link></function> function is preferred over
1775       <function><link linkend="g-signal-newv">g_signal_newv</link></function>. When <function><link linkend="g-signal-new">g_signal_new</link></function>
1776       is used, the default closure is exported as a class function. For example,
1777       <filename>gobject.h</filename> contains the declaration of <link linkend="GObjectClass"><type>GObjectClass</type></link>
1778       whose notify class function is the default handler for the <emphasis>notify</emphasis>
1779       signal:
1780 <programlisting>
1781 struct  _GObjectClass
1782 {
1783   GTypeClass   g_type_class;
1784
1785   /* class methods and other stuff. */
1786
1787   /* signals */
1788   void (*notify) (GObject     *object,
1789                   GParamSpec  *pspec);
1790 };
1791 </programlisting>
1792      </para>
1793
1794      <para>
1795        <filename>gobject.c</filename>'s <function><link linkend="g-object-do-class-init">g_object_do_class_init</link></function> function
1796        registers the <emphasis>notify</emphasis> signal and initializes this class function
1797        to NULL:
1798 <programlisting>
1799 static void
1800 g_object_do_class_init (GObjectClass *class)
1801 {
1802
1803   /* Stuff */
1804
1805   class->notify = NULL;
1806
1807   gobject_signals[NOTIFY] =
1808     g_signal_new ("notify",
1809                   G_TYPE_FROM_CLASS (class),
1810                   G_SIGNAL_RUN_FIRST | G_SIGNAL_NO_RECURSE | G_SIGNAL_DETAILED | G_SIGNAL_NO_HOOKS,
1811                   G_STRUCT_OFFSET (GObjectClass, notify),
1812                   NULL, NULL,
1813                   g_cclosure_marshal_VOID__PARAM,
1814                   G_TYPE_NONE,
1815                   1, G_TYPE_PARAM);
1816 }
1817 </programlisting>
1818        <function><link linkend="g-signal-new">g_signal_new</link></function> creates a <link linkend="GClosure"><type>GClosure</type></link> which dereferences the
1819        type's class structure to access the class function pointer and invoke it if it not NULL. The
1820        class function is ignored it is set to NULL.
1821      </para>
1822
1823      <para>
1824        To understand the reason for such a complex scheme to access the signal's default handler, 
1825        you must remember the whole reason for the use of these signals. The goal here is to delegate
1826        a part of the process to the user without requiring the user to subclass the object to override
1827        one of the class functions. The alternative to subclassing, that is, the use of signals
1828        to delegate processing to the user, is, however, a bit less optimal in terms of speed: rather
1829        than just dereferencing a function pointer in a class structure, you must start the whole
1830        process of signal emission which is a bit heavyweight.
1831      </para>
1832
1833      <para>
1834        This is why some people decided to use class functions for some signal's default handlers:
1835        rather than having users connect a handler to the signal and stop the signal emission
1836        from within that handler, you just need to override the default class function which is
1837        supposedly more efficient.
1838      </para>
1839
1840     </sect2>
1841 -->
1842 </part>