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