Initial commit
[platform/upstream/glib2.0.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.1.2//EN" 
3                "http://www.oasis-open.org/docbook/xml/4.1.2/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       I personally like the first solution better: it makes reading file names
61       easier for those with poor eyesight like me.
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       <type><link linkend="GParamSpec">GParamSpec</link></type> 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 <programlisting>
345 static void
346 bar_class_init (MamanBarClass *klass)
347 {
348   GObjectClass *gobject_class = G_OBJECT_CLASS (klass);
349   GParamSpec *maman_param_spec;
350
351   gobject_class->set_property = bar_set_property;
352   gobject_class->get_property = bar_get_property;
353
354   maman_param_spec = g_param_spec_string ("maman",
355                                           "Maman construct prop",
356                                           "Set maman's name",
357                                           "no-name-set" /* default value */,
358                                           G_PARAM_CONSTRUCT_ONLY | G_PARAM_READWRITE);
359   g_object_class_install_property (gobject_class,
360                                    PROP_MAMAN,
361                                    maman_param_spec);
362 }
363 </programlisting>
364       If you need this, make sure you can build and run code similar to the code shown above. Make sure
365       your construct properties can set correctly during construction, make sure you cannot set them 
366       afterwards and make sure that if your users do not call <function><link linkend="g-object-new">g_object_new</link></function>
367       with the required construction properties, these will be initialized with the default values.
368     </para>
369
370     <para>
371       I consider good taste to halt program execution if a construction property is set its
372       default value. This allows you to catch client code which does not give a reasonable
373       value to the construction properties. Of course, you are free to disagree but you
374       should have a good reason to do so.
375     </para>
376
377     <para>
378       Some people sometimes need to construct their object but only after
379       the construction properties have been set. This is possible through
380       the use of the constructor class method as described in
381       <xref linkend="gobject-instantiation"/> or, more simply, using
382       the constructed class method available since GLib 2.12.
383     </para>
384   </sect1>
385
386   <sect1 id="howto-gobject-destruction">
387     <title>Object Destruction</title>
388
389     <para>
390       Again, it is often difficult to figure out which mechanism to use to
391       hook into the object's destruction process: when the last
392       <function><link linkend="g-object-unref">g_object_unref</link></function>
393       function call is made, a lot of things happen as described in
394       <xref linkend="gobject-destruction-table"/>.
395     </para>
396
397     <para>
398       The destruction process of your object might be split in two different
399       phases: dispose and the finalize.
400 <programlisting>
401 #define MAMAN_BAR_GET_PRIVATE(obj) (G_TYPE_INSTANCE_GET_PRIVATE ((obj), MAMAN_TYPE_BAR, MamanBarPrivate))
402
403 struct _MamanBarPrivate
404 {
405   GObject *an_object;
406
407   gchar *a_string;
408 };
409
410 G_DEFINE_TYPE (MamanBar, maman_bar, G_TYPE_OBJECT);
411
412 static void
413 maman_bar_dispose (GObject *gobject)
414 {
415   MamanBar *self = MAMAN_BAR (gobject);
416
417   /* 
418    * In dispose, you are supposed to free all types referenced from this
419    * object which might themselves hold a reference to self. Generally,
420    * the most simple solution is to unref all members on which you own a 
421    * reference.
422    */
423
424   /* dispose might be called multiple times, so we must guard against
425    * calling g_object_unref() on an invalid GObject.
426    */
427   if (self->priv->an_object)
428     {
429       g_object_unref (self->priv->an_object);
430
431       self->priv->an_object = NULL;
432     }
433
434   /* Chain up to the parent class */
435   G_OBJECT_CLASS (maman_bar_parent_class)->dispose (gobject);
436 }
437
438 static void
439 maman_bar_finalize (GObject *gobject)
440 {
441   MamanBar *self = MAMAN_BAR (gobject);
442
443   g_free (self->priv->a_string);
444
445   /* Chain up to the parent class */
446   G_OBJECT_CLASS (maman_bar_parent_class)->finalize (gobject);
447 }
448
449 static void
450 maman_bar_class_init (MamanBarClass *klass)
451 {
452   GObjectClass *gobject_class = G_OBJECT_CLASS (klass);
453
454   gobject_class->dispose = maman_bar_dispose;
455   gobject_class->finalize = maman_bar_finalize;
456
457   g_type_class_add_private (klass, sizeof (MamanBarPrivate));
458 }
459
460 static void
461 maman_bar_init (MamanBar *self);
462 {
463   self->priv = MAMAN_BAR_GET_PRIVATE (self);
464
465   self->priv->an_object = g_object_new (MAMAN_TYPE_BAZ, NULL);
466   self->priv->a_string = g_strdup ("Maman");
467 }
468 </programlisting>
469     </para>
470
471     <para>
472       Add similar code to your GObject, make sure the code still builds
473       and runs: dispose and finalize must be called during the last unref.
474     </para>
475
476     <para>
477       It is possible that object methods might be invoked after dispose is
478       run and before finalize runs. GObject does not consider this to be a
479       program error: you must gracefully detect this and neither crash nor
480       warn the user.
481     </para>
482   </sect1>
483
484   <sect1 id="howto-gobject-methods">
485     <title>Object methods</title>
486
487     <para>
488       Just as with C++, there are many different ways to define object
489       methods and extend them: the following list and sections draw on
490       C++ vocabulary. (Readers are expected to know basic C++ buzzwords.
491       Those who have not had to write C++ code recently can refer to e.g.
492       <ulink url="http://www.cplusplus.com/doc/tutorial/"/> to refresh
493       their memories.)
494       <itemizedlist>
495         <listitem><para>
496             non-virtual public methods,
497           </para></listitem>
498         <listitem><para>
499             virtual public methods and
500           </para></listitem>
501         <listitem><para>
502             virtual private methods
503           </para></listitem>
504       </itemizedlist>
505     </para>
506
507     <sect2>
508       <title>Non-virtual public methods</title>
509
510       <para>
511         These are the simplest: you want to provide a simple method which
512         can act on your object. All you need to do is to provide a function
513         prototype in the header and an implementation of that prototype
514         in the source file.
515 <programlisting>
516 /* declaration in the header. */
517 void maman_bar_do_action (MamanBar *self, /* parameters */);
518
519 /* implementation in the source file */
520 void
521 maman_bar_do_action (MamanBar *self, /* parameters */)
522 {
523   g_return_if_fail (MAMAN_IS_BAR (self));
524
525   /* do stuff here. */
526 }
527 </programlisting>
528       </para>
529
530       <para>There is really nothing scary about this.</para>
531     </sect2>
532
533     <sect2>
534       <title>Virtual public methods</title>
535
536       <para>
537         This is the preferred way to create polymorphic GObjects. All you
538         need to do is to define the common method and its class function in
539         the public header, implement the common method in the source file
540         and re-implement the class function in each object which inherits
541         from you.
542 <programlisting>
543 /* declaration in maman-bar.h. */
544 struct _MamanBarClass
545 {
546   GObjectClass parent_class;
547
548   /* stuff */
549   void (*do_action) (MamanBar *self, /* parameters */);
550 };
551
552 void maman_bar_do_action (MamanBar *self, /* parameters */);
553
554 /* implementation in maman-bar.c */
555 void
556 maman_bar_do_action (MamanBar *self, /* parameters */)
557 {
558   g_return_if_fail (MAMAN_IS_BAR (self));
559
560   MAMAN_BAR_GET_CLASS (self)->do_action (self, /* parameters */);
561 }
562 </programlisting>
563         The code above simply redirects the do_action call to the relevant
564         class function. Some users, concerned about performance, do not
565         provide the <function>maman_bar_do_action</function> wrapper function
566         and require users to dereference the class pointer themselves. This
567         is not such a great idea in terms of encapsulation and makes it
568         difficult to change the object's implementation afterwards, should
569         this be needed.
570       </para>
571
572       <para>
573         Other users, also concerned by performance issues, declare
574         the <function>maman_bar_do_action</function> function inline in the
575         header file. This, however, makes it difficult to change the
576         object's implementation later (although easier than requiring users
577         to directly dereference the class function) and is often difficult
578         to write in a portable way (the <emphasis>inline</emphasis> keyword
579         is part of the C99 standard but not every compiler supports it).
580       </para>
581
582       <para>
583         In doubt, unless a user shows you hard numbers about the performance
584         cost of the function call, just implement <function>maman_bar_do_action</function>
585         in the source file.
586       </para>
587
588       <para>
589         Please, note that it is possible for you to provide a default
590         implementation for this class method in the object's
591         <function>class_init</function> function: initialize the
592         klass-&gt;do_action field to a pointer to the actual implementation.
593         You can also make this class method pure virtual by initializing
594         the klass-&gt;do_action field to NULL:
595 <programlisting>
596 static void
597 maman_bar_real_do_action_two (MamanBar *self, /* parameters */)
598 {
599   /* Default implementation for the virtual method. */
600 }
601
602 static void
603 maman_bar_class_init (BarClass *klass)
604 {
605   /* pure virtual method: mandates implementation in children. */
606   klass->do_action_one = NULL;
607
608   /* merely virtual method. */
609   klass->do_action_two = maman_bar_real_do_action_two;
610 }
611
612 void
613 maman_bar_do_action_one (MamanBar *self, /* parameters */)
614 {
615   g_return_if_fail (MAMAN_IS_BAR (self));
616
617   MAMAN_BAR_GET_CLASS (self)->do_action_one (self, /* parameters */);
618 }
619
620 void
621 maman_bar_do_action_two (MamanBar *self, /* parameters */)
622 {
623   g_return_if_fail (MAMAN_IS_BAR (self));
624
625   MAMAN_BAR_GET_CLASS (self)->do_action_two (self, /* parameters */);
626 }
627 </programlisting>
628       </para>
629     </sect2>
630
631     <sect2>
632       <title>Virtual private Methods</title>
633
634       <para>
635         These are very similar to Virtual Public methods. They just don't
636         have a public function to call the function directly. The header
637         file contains only a declaration of the class function:
638 <programlisting>
639 /* declaration in maman-bar.h. */
640 struct _MamanBarClass
641 {
642   GObjectClass parent;
643
644   /* stuff */
645   void (* helper_do_specific_action) (MamanBar *self, /* parameters */);
646 };
647
648 void maman_bar_do_any_action (MamanBar *self, /* parameters */);
649 </programlisting>
650         These class functions are often used to delegate part of the job
651         to child classes:
652 <programlisting>
653 /* this accessor function is static: it is not exported outside of this file. */
654 static void 
655 maman_bar_do_specific_action (MamanBar *self, /* parameters */)
656 {
657   MAMAN_BAR_GET_CLASS (self)->do_specific_action (self, /* parameters */);
658 }
659
660 void
661 maman_bar_do_any_action (MamanBar *self, /* parameters */)
662 {
663   /* random code here */
664
665   /* 
666    * Try to execute the requested action. Maybe the requested action
667    * cannot be implemented here. So, we delegate its implementation
668    * to the child class:
669    */
670   maman_bar_do_specific_action (self, /* parameters */);
671
672   /* other random code here */
673 }
674 </programlisting>
675       </para>
676
677       <para>
678         Again, it is possible to provide a default implementation for this
679         private virtual class function:
680 <programlisting>
681 static void
682 maman_bar_class_init (MamanBarClass *klass)
683 {
684   /* pure virtual method: mandates implementation in children. */
685   klass->do_specific_action_one = NULL;
686
687   /* merely virtual method. */
688   klass->do_specific_action_two = maman_bar_real_do_specific_action_two;
689 }
690 </programlisting>
691       </para>
692
693       <para>
694         Children can then implement the subclass with code such as:
695 <programlisting>
696 static void
697 maman_bar_subtype_class_init (MamanBarSubTypeClass *klass)
698 {
699   MamanBarClass *bar_class = MAMAN_BAR_CLASS (klass);
700
701   /* implement pure virtual class function. */
702   bar_class->do_specific_action_one = maman_bar_subtype_do_specific_action_one;
703 }
704 </programlisting>
705       </para>
706     </sect2>
707   </sect1>
708
709   <sect1 id="howto-gobject-chainup">
710     <title>Chaining up</title>
711     
712     <para>Chaining up is often loosely defined by the following set of
713     conditions:
714       <itemizedlist>
715         <listitem><para>Parent class A defines a public virtual method named <function>foo</function> and 
716         provides a default implementation.</para></listitem>
717         <listitem><para>Child class B re-implements method <function>foo</function>.</para></listitem>
718         <listitem><para>In the method B::foo, the child class B calls its parent class method A::foo.</para></listitem>
719       </itemizedlist>
720       There are many uses to this idiom:
721       <itemizedlist>
722         <listitem><para>You need to change the behaviour of a class without modifying its code. You create
723           a subclass to inherit its implementation, re-implement a public virtual method to modify the behaviour
724           slightly and chain up to ensure that the previous behaviour is not really modified, just extended.
725           </para></listitem>
726         <listitem><para>You are lazy, you have access to the source code of the parent class but you don't want 
727           to modify it to add method calls to new specialized method calls: it is faster to hack the child class
728           to chain up than to modify the parent to call down.</para></listitem>
729         <listitem><para>You need to implement the Chain Of Responsibility pattern: each object of the inheritance
730           tree chains up to its parent (typically, at the beginning or the end of the method) to ensure that
731           they each handler is run in turn.</para></listitem>
732       </itemizedlist>
733       I am personally not really convinced any of the last two uses are really a good idea but since this
734       programming idiom is often used, this section attempts to explain how to implement it.
735     </para>
736
737     <para>
738       To explicitly chain up to the implementation of the virtual method in the parent class, 
739       you first need a handle to the original parent class structure. This pointer can then be used to 
740       access the original class function pointer and invoke it directly.
741       <footnote>
742         <para>
743           The <emphasis>original</emphasis> adjective used in this sentence is not innocuous. To fully 
744           understand its meaning, you need to recall how class structures are initialized: for each object type,
745           the class structure associated to this object is created by first copying the class structure of its 
746           parent type (a simple <function>memcpy</function>) and then by invoking the class_init callback on 
747           the resulting class structure. Since the class_init callback is responsible for overwriting the class structure
748           with the user re-implementations of the class methods, we cannot merely use the modified copy of the parent class
749           structure stored in our derived instance. We want to get a copy of the class structure of an instance of the parent 
750           class.
751         </para>
752       </footnote>
753     </para>
754     
755     <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 
756     class structure. Its input is a pointer to the class of the derived object and it returns a pointer
757     to the original parent class structure. The code below shows how you could use it:
758 <programlisting>
759 static void
760 b_method_to_call (B *obj, int a)
761 {
762   BClass *klass;
763   AClass *parent_class;
764
765   klass = B_GET_CLASS (obj);
766   parent_class = g_type_class_peek_parent (klass);
767
768   /* do stuff before chain up */
769
770   parent_class->method_to_call (obj, a);
771
772   /* do stuff after chain up */
773 }
774 </programlisting>
775   </para>
776
777   </sect1>
778
779 </chapter>
780 <!-- End Howto GObject -->
781
782 <chapter id="howto-interface">
783   <title>How to define and implement interfaces</title>
784
785   <sect1 id="howto-interface-define">
786     <title>How to define interfaces</title>
787   
788   <para>
789     The bulk of interface definition has already been shown in <xref linkend="gtype-non-instantiable-classed"/>
790     but I feel it is needed to show exactly how to create an interface.
791   </para>
792
793   <para>
794     As above, the first step is to get the header right:
795 <programlisting>
796 #ifndef __MAMAN_IBAZ_H__
797 #define __MAMAN_IBAZ_H__
798
799 #include &lt;glib-object.h&gt;
800
801 #define MAMAN_TYPE_IBAZ                 (maman_ibaz_get_type ())
802 #define MAMAN_IBAZ(obj)                 (G_TYPE_CHECK_INSTANCE_CAST ((obj), MAMAN_TYPE_IBAZ, MamanIbaz))
803 #define MAMAN_IS_IBAZ(obj)              (G_TYPE_CHECK_INSTANCE_TYPE ((obj), MAMAN_TYPE_IBAZ))
804 #define MAMAN_IBAZ_GET_INTERFACE(inst)  (G_TYPE_INSTANCE_GET_INTERFACE ((inst), MAMAN_TYPE_IBAZ, MamanIbazInterface))
805
806
807 typedef struct _MamanIbaz               MamanIbaz; /* dummy object */
808 typedef struct _MamanIbazInterface      MamanIbazInterface;
809
810 struct _MamanIbazInterface
811 {
812   GTypeInterface parent_iface;
813
814   void (*do_action) (MamanIbaz *self);
815 };
816
817 GType maman_ibaz_get_type (void);
818
819 void maman_ibaz_do_action (MamanIbaz *self);
820
821 #endif /* __MAMAN_IBAZ_H__ */
822 </programlisting>
823     This code is the same as the code for a normal <type><link linkend="GType">GType</link></type>
824     which derives from a <type><link linkend="GObject">GObject</link></type> except for a few details:
825     <itemizedlist>
826       <listitem><para>
827         The <function>_GET_CLASS</function> macro is called <function>_GET_INTERFACE</function>
828                   and not implemented with <function><link linkend="G_TYPE_INSTANCE_GET_CLASS">G_TYPE_INSTANCE_GET_CLASS</link></function>
829                   but with <function><link linkend="G_TYPE_INSTANCE_GET_INTERFACE">G_TYPE_INSTANCE_GET_INTERFACE</link></function>.
830       </para></listitem>
831       <listitem><para>
832         The instance type, <type>MamanIbaz</type> is not fully defined: it is
833         used merely as an abstract type which represents an instance of
834         whatever object which implements the interface.
835       </para></listitem>
836       <listitem><para>
837         The parent of the <type>MamanIbazInterface</type> is not
838         <type>GObjectClass</type> but <type>GTypeInterface</type>.
839       </para></listitem>
840     </itemizedlist>
841   </para>
842
843   <para>
844     The implementation of the <type>MamanIbaz</type> type itself is trivial:
845     <itemizedlist>
846       <listitem><para><function>maman_ibaz_get_type</function> registers the
847        type in the type system.
848        </para></listitem>
849       <listitem><para><function>maman_ibaz_base_init</function> is expected 
850       to register the interface's signals if there are any (we will see a bit
851       (later how to use them). Make sure to use a static local boolean variable
852       to make sure not to run the initialization code twice (as described in
853       <xref linkend="gtype-non-instantiable-classed-init"/>, 
854       <function>base_init</function> is run once for each interface implementation 
855       instantiation)</para></listitem>
856       <listitem><para><function>maman_ibaz_do_action</function> dereferences
857       the class structure to access its associated class function and calls it.
858       </para></listitem>
859     </itemizedlist>
860 <programlisting>
861 static void
862 maman_ibaz_base_init (gpointer g_class)
863 {
864   static gboolean is_initialized = FALSE;
865
866   if (!is_initialized)
867     {
868       /* add properties and signals to the interface here */
869
870       is_initialized = TRUE;
871     }
872 }
873
874 GType
875 maman_ibaz_get_type (void)
876 {
877   static GType iface_type = 0;
878   if (iface_type == 0)
879     {
880       static const GTypeInfo info = {
881         sizeof (MamanIbazInterface),
882         maman_ibaz_base_init,   /* base_init */
883         NULL,   /* base_finalize */
884       };
885
886       iface_type = g_type_register_static (G_TYPE_INTERFACE, "MamanIbaz",
887                                            &amp;info, 0);
888     }
889
890   return iface_type;
891 }
892
893 void
894 maman_ibaz_do_action (MamanIbaz *self)
895 {
896   g_return_if_fail (MAMAN_IS_IBAZ (self));
897
898   MAMAN_IBAZ_GET_INTERFACE (self)->do_action (self);
899 }
900 </programlisting>
901     </para>
902   </sect1>
903   
904   <sect1 id="howto-interface-implement">
905     <title>How To define implement an Interface?</title>
906   
907     <para>
908       Once the interface is defined, implementing it is rather trivial.
909     </para>
910   
911     <para>
912       The first step is to define a normal GObject class, like:
913 <programlisting>
914 #ifndef __MAMAN_BAZ_H__
915 #define __MAMAN_BAZ_H__
916
917 #include &lt;glib-object.h&gt;
918
919 #define MAMAN_TYPE_BAZ             (maman_baz_get_type ())
920 #define MAMAN_BAZ(obj)             (G_TYPE_CHECK_INSTANCE_CAST ((obj), MAMAN_TYPE_BAZ, Mamanbaz))
921 #define MAMAN_IS_BAZ(obj)          (G_TYPE_CHECK_INSTANCE_TYPE ((obj), MAMAN_TYPE_BAZ))
922 #define MAMAN_BAZ_CLASS(klass)     (G_TYPE_CHECK_CLASS_CAST ((klass), MAMAN_TYPE_BAZ, MamanbazClass))
923 #define MAMAN_IS_BAZ_CLASS(klass)  (G_TYPE_CHECK_CLASS_TYPE ((klass), MAMAN_TYPE_BAZ))
924 #define MAMAN_BAZ_GET_CLASS(obj)   (G_TYPE_INSTANCE_GET_CLASS ((obj), MAMAN_TYPE_BAZ, MamanbazClass))
925
926
927 typedef struct _MamanBaz        MamanBaz;
928 typedef struct _MamanBazClass   MamanBazClass;
929
930 struct _MamanBaz
931 {
932   GObject parent_instance;
933
934   int instance_member;
935 };
936
937 struct _MamanBazClass
938 {
939   GObjectClass parent_class;
940 };
941
942 GType maman_baz_get_type (void);
943
944 #endif /* __MAMAN_BAZ_H__ */
945 </programlisting>
946       There is clearly nothing specifically weird or scary about this header:
947       it does not define any weird API or derives from a weird type.
948     </para>
949   
950     <para>
951       The second step is to implement <type>MamanBaz</type> by defining
952       its GType. Instead of using <function>G_DEFINE_TYPE</function> we
953       use <function>G_DEFINE_TYPE_WITH_CODE</function> and the
954       <function>G_IMPLEMENT_INTERFACE</function> macros.
955 <programlisting>
956 static void maman_ibaz_interface_init (MamanIbazInterface *iface);
957
958 G_DEFINE_TYPE_WITH_CODE (MamanBar, maman_bar, G_TYPE_OBJECT,
959                          G_IMPLEMENT_INTERFACE (MAMAN_TYPE_IBAZ,
960                                                 maman_ibaz_interface_init));
961 </programlisting>
962       This definition is very much like all the similar functions we looked
963       at previously. The only interface-specific code present here is the call
964       to <function>G_IMPLEMENT_INTERFACE</function>. 
965     </para>
966
967     <note><para>Classes can implement multiple interfaces by using multiple
968     calls to <function>G_IMPLEMENT_INTERFACE</function> inside the call
969     to <function>G_DEFINE_TYPE_WITH_CODE</function>.</para></note>
970   
971     <para>
972       <function>maman_baz_interface_init</function>, the interface
973       initialization function: inside it every virtual method of the interface
974       must be assigned to its implementation:
975 <programlisting>
976 static void
977 maman_baz_do_action (MamanBaz *self)
978 {
979   g_print ("Baz implementation of IBaz interface Action: 0x%x.\n",
980            self->instance_member);
981 }
982
983 static void
984 maman_ibaz_interface_init (MamanIbazInterface *iface)
985 {
986   iface->do_action = baz_do_action;
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   
998   </sect1>
999   
1000   <sect1>
1001     <title>Interface definition prerequisites</title>
1002   
1003     <para>
1004       To specify that an interface requires the presence of other interfaces
1005       when implemented, GObject introduces the concept of
1006       <emphasis>prerequisites</emphasis>: it is possible to associate
1007       a list of prerequisite interfaces to an interface. For example, if
1008       object A wishes to implement interface I1, and if interface I1 has a
1009       prerequisite on interface I2, A has to implement both I1 and I2.
1010     </para>
1011   
1012     <para>
1013       The mechanism described above is, in practice, very similar to
1014       Java's interface I1 extends interface I2. The example below shows
1015       the GObject equivalent:
1016 <programlisting>
1017   /* inside the GType function of the MamanIbar interface */
1018   type = g_type_register_static (G_TYPE_INTERFACE, "MamanIbar", &amp;info, 0);
1019
1020   /* Make the MamanIbar interface require MamanIbaz interface. */
1021   g_type_interface_add_prerequisite (type, MAMAN_TYPE_IBAZ);
1022 </programlisting>
1023       The code shown above adds the MamanIbaz interface to the list of
1024       prerequisites of MamanIbar while the code below shows how an
1025       implementation can implement both interfaces and register their
1026       implementations:
1027 <programlisting>
1028 static void
1029 maman_ibar_do_another_action (MamanIbar *ibar)
1030 {
1031   MamanBar *self = MAMAN_BAR (ibar);
1032
1033   g_print ("Bar implementation of IBar interface Another Action: 0x%x.\n",
1034            self->instance_member);
1035 }
1036
1037 static void
1038 maman_ibar_interface_init (MamanIbarInterface *iface)
1039 {
1040   iface->do_another_action = maman_ibar_do_another_action;
1041 }
1042
1043 static void
1044 maman_ibaz_do_action (MamanIbaz *ibaz)
1045 {
1046   MamanBar *self = MAMAN_BAR (ibaz);
1047
1048   g_print ("Bar implementation of IBaz interface Action: 0x%x.\n",
1049            self->instance_member);
1050 }
1051
1052 static void
1053 maman_ibaz_interface_init (MamanIbazInterface *iface)
1054 {
1055   iface->do_action = maman_ibaz_do_action;
1056 }
1057
1058 static void
1059 maman_bar_class_init (MamanBarClass *klass)
1060 {
1061
1062 }
1063
1064 static void
1065 maman_bar_init (MamanBar *self)
1066 {
1067   self->instance_member = 0x666;
1068 }
1069
1070 G_DEFINE_TYPE_WITH_CODE (MamanBar, maman_bar, G_TYPE_OBJECT,
1071                          G_IMPLEMENT_INTERFACE (MAMAN_TYPE_IBAZ,
1072                                                 maman_ibaz_interface_init)
1073                          G_IMPLEMENT_INTERFACE (MAMAN_TYPE_IBAR,
1074                                                 maman_ibar_interface_init));
1075 </programlisting>
1076       It is very important to notice that the order in which interface
1077       implementations are added to the main object is not random:
1078       <function><link linkend="g-type-add-interface-static">g_type_add_interface_static</link></function>,
1079       which is called by <function>G_IMPLEMENT_INTERFACE</function>, must be
1080       invoked first on the interfaces which have no prerequisites and then on
1081       the others.
1082     </para>
1083   </sect1>
1084   
1085   <sect1 id="howto-interface-properties">
1086     <title>Interface Properties</title>
1087   
1088     <para>
1089       Starting from version 2.4 of GLib, GObject interfaces can also have
1090       properties. Declaration of the interface properties is similar to
1091       declaring the properties of ordinary GObject types as explained in
1092       <xref linkend="gobject-properties"/>, 
1093       except that <function><link linkend="g-object-interface-install-property">g_object_interface_install_property</link></function> is used to 
1094       declare the properties instead of <function><link linkend="g-object-class-install-property">g_object_class_install_property</link></function>.
1095     </para>
1096   
1097     <para>
1098       To include a property named 'name' of type <type>string</type> in the 
1099       <type>maman_ibaz</type> interface example code above, we only need to
1100       add one 
1101       <footnote>
1102         <para>
1103           That really is one line extended to six for the sake of clarity
1104         </para>
1105       </footnote>  
1106       line in the <function>maman_ibaz_base_init</function>
1107       <footnote>
1108         <para>
1109           The <function><link linkend="g-object-interface-install-property">g_object_interface_install_property</link></function>
1110           can also be called from <function>class_init</function> but it must
1111           not be called after that point.
1112         </para>
1113       </footnote>
1114       as shown below:
1115 <programlisting>
1116 static void
1117 maman_ibaz_base_init (gpointer g_iface)
1118 {
1119   static gboolean is_initialized = FALSE;
1120
1121   if (!is_initialized)
1122     {
1123       g_object_interface_install_property (g_iface,
1124                                            g_param_spec_string ("name",
1125                                                                 "Name",
1126                                                                 "Name of the MamanIbaz",
1127                                                                 "maman",
1128                                                                 G_PARAM_READWRITE));
1129       is_initialized = TRUE;
1130     }
1131 }
1132 </programlisting>
1133     </para>
1134   
1135     <para>
1136       One point worth noting is that the declared property wasn't assigned an 
1137       integer ID. The reason being that integer IDs of properties are used
1138       only inside the get and set methods and since interfaces do not
1139       implement properties, there is no need to assign integer IDs to
1140       interface properties.
1141     </para>
1142     
1143     <para>
1144       An implementation shall declare and define it's properties in the usual
1145       way as explained in <xref linkend="gobject-properties"/>, except for one
1146       small change: it must declare the properties of the interface it
1147       implements using <function><link linkend="g-object-class-override-property">g_object_class_override_property</link></function>
1148       instead of <function><link linkend="g-object-class-install-property">g_object_class_install_property</link></function>.
1149       The following code snippet shows the modifications needed in the
1150       <type>MamanBaz</type> declaration and implementation above:
1151 <programlisting>
1152
1153 struct _MamanBaz
1154 {
1155   GObject parent_instance;
1156
1157   gint instance_member;
1158   gchar *name;
1159 };
1160
1161 enum
1162 {
1163   PROP_0,
1164
1165   PROP_NAME
1166 };
1167
1168 static void
1169 maman_baz_set_property (GObject      *object,
1170                         guint         property_id,
1171                         const GValue *value,
1172                         GParamSpec   *pspec)
1173 {
1174   MamanBaz *baz = MAMAN_BAZ (object);
1175   GObject *obj;
1176
1177   switch (prop_id)
1178     {
1179     case ARG_NAME:
1180       g_free (baz->name);
1181       baz->name = g_value_dup_string (value);
1182       break;
1183
1184     default:
1185       G_OBJECT_WARN_INVALID_PROPERTY_ID (object, prop_id, pspec);
1186       break;
1187     }
1188 }
1189
1190 static void
1191 maman_baz_get_property (GObject    *object,
1192                         guint       prop_id,
1193                         GValue     *value,
1194                         GParamSpec *pspec)
1195 {
1196   MamanBaz *baz = MAMAN_BAZ (object);
1197
1198   switch (prop_id)
1199     {
1200     case ARG_NAME:
1201       g_value_set_string (value, baz->name);
1202       break;
1203
1204     default:
1205       G_OBJECT_WARN_INVALID_PROPERTY_ID (object, prop_id, pspec);
1206       break;
1207     }
1208 }
1209
1210 static void
1211 maman_baz_class_init (MamanBazClass *klass)
1212 {
1213   GObjectClass *gobject_class = G_OBJECT_CLASS (klass);
1214
1215   gobject_class->set_property = maman_baz_set_property;
1216   gobject_class->get_property = maman_baz_get_property;
1217
1218   g_object_class_override_property (gobject_class, PROP_NAME, "name");
1219 }
1220
1221 </programlisting>
1222     </para>
1223   
1224   </sect1>
1225 </chapter>
1226 <!-- End Howto Interfaces -->
1227
1228 <chapter id="howto-signals">
1229   <title>How to create and use signals</title>
1230
1231   <para>
1232     The signal system which was built in GType is pretty complex and
1233     flexible: it is possible for its users to connect at runtime any
1234     number of callbacks (implemented in any language for which a binding
1235     exists)
1236     <footnote>
1237       <para>A Python callback can be connected to any signal on any
1238       C-based GObject.
1239       </para>
1240     </footnote>
1241     to any signal and to stop the emission of any signal at any 
1242     state of the signal emission process. This flexibility makes it
1243     possible to use GSignal for much more than just emit signals which
1244     can be received by numerous clients. 
1245   </para>
1246
1247   <sect1 id="howto-simple-signals">
1248     <title>Simple use of signals</title>
1249
1250     <para>
1251       The most basic use of signals is to implement simple event
1252       notification: for example, if we have a MamanFile object, and
1253       if this object has a write method, we might wish to be notified
1254       whenever someone has changed something via our MamanFile instance.
1255       The code below shows how the user can connect a callback to the
1256       "changed" signal.
1257 <programlisting>
1258 file = g_object_new (MAMAN_FILE_TYPE, NULL);
1259
1260 g_signal_connect (file, "changed", G_CALLBACK (changed_event), NULL);
1261
1262 maman_file_write (file, buffer, strlen (buffer));
1263 </programlisting>
1264     </para>
1265     
1266     <para>
1267       The <type>MamanFile</type> signal is registered in the class_init
1268       function:
1269 <programlisting>
1270 file_signals[CHANGED] = 
1271   g_signal_newv ("changed",
1272                  G_TYPE_FROM_CLASS (gobject_class),
1273                  G_SIGNAL_RUN_LAST | G_SIGNAL_NO_RECURSE | G_SIGNAL_NO_HOOKS,
1274                  NULL /* closure */,
1275                  NULL /* accumulator */,
1276                  NULL /* accumulator data */,
1277                  g_cclosure_marshal_VOID__VOID,
1278                  G_TYPE_NONE /* return_type */,
1279                  0     /* n_params */,
1280                  NULL  /* param_types */);
1281 </programlisting>
1282       and the signal is emitted in <function>maman_file_write</function>:
1283 <programlisting>
1284 void
1285 maman_file_write (MamanFile    *self,
1286                   const guchar *buffer,
1287                   gssize        size)
1288 {
1289   /* First write data. */
1290
1291   /* Then, notify user of data written. */
1292   g_signal_emit (self, file_signals[CHANGED], 0 /* details */);
1293 }
1294 </programlisting>
1295       As shown above, you can safely set the details parameter to zero if
1296       you do not know what it can be used for. For a discussion of what you
1297       could used it for, see <xref linkend="signal-detail"/>
1298     </para>
1299
1300     <para>
1301       The signature of the signal handler in the above example is defined as
1302       <function>g_cclosure_marshal_VOID__VOID</function>. Its name follows
1303       a simple convention which encodes the function parameter and return value
1304       types in the function name. Specifically, the value in front of the
1305       double underscore is the type of the return value, while the value(s)
1306       after the double underscore denote the parameter types.
1307     </para>
1308
1309     <para>
1310       The header <filename>gobject/gmarshal.h</filename> defines a set of
1311       commonly needed closures that one can use. If you want to have complex
1312       marshallers for your signals you should probably use glib-genmarshal
1313       to autogenerate them from a file containing their return and
1314       parameter types.
1315     </para>
1316   </sect1>
1317
1318 <!-- 
1319   this is utterly wrong and should be completely removed - or rewritten
1320   with a better example than writing a buffer using synchronous signals.
1321
1322   <sect1>
1323     <title>How to provide more flexibility to users?</title>
1324
1325     <para>
1326       The previous implementation does the job but the signal facility of
1327       GObject can be used to provide even more flexibility to this file
1328       change notification mechanism. One of the key ideas is to make the
1329       process of writing data to the file part of the signal emission
1330       process to allow users to be notified either before or after the
1331       data is written to the file.
1332     </para>
1333     
1334     <para>
1335       To integrate the process of writing the data to the file into the
1336       signal emission mechanism, we can register a default class closure
1337       for this signal which will be invoked during the signal emission,
1338       just like any other user-connected signal handler. 
1339     </para>
1340     
1341     <para>
1342       The first step to implement this idea is to change the signature of
1343       the signal: we need to pass around the buffer to write and its size.
1344       To do this, we use our own marshaller which will be generated
1345       through GLib's glib-genmarshal tool. We thus create a file named <filename>marshall.list</filename> which contains
1346       the following single line:
1347 <programlisting>
1348 VOID:POINTER,UINT
1349 </programlisting>
1350       and use the Makefile provided in <filename>sample/signal/Makefile</filename> to generate the file named
1351       <filename>maman-file-complex-marshall.c</filename>. This C file is finally included in 
1352       <filename>maman-file-complex.c</filename>.
1353     </para>
1354
1355     <para>
1356       Once the marshaller is present, we register the signal and its marshaller in the class_init function 
1357       of the object <type>MamanFileComplex</type> (full source for this object is included in 
1358       <filename>sample/signal/maman-file-complex.{h|c}</filename>):
1359 <programlisting>
1360 GClosure *default_closure;
1361 GType param_types[2];
1362
1363 default_closure = g_cclosure_new (G_CALLBACK (default_write_signal_handler),
1364                                   (gpointer)0xdeadbeaf /* user_data */, 
1365                                   NULL /* destroy_data */);
1366
1367 param_types[0] = G_TYPE_POINTER;
1368 param_types[1] = G_TYPE_UINT;
1369 klass->write_signal_id = 
1370   g_signal_newv ("write",
1371                  G_TYPE_FROM_CLASS (g_class),
1372                  G_SIGNAL_RUN_LAST | G_SIGNAL_NO_RECURSE | G_SIGNAL_NO_HOOKS,
1373                  default_closure /* class closure */,
1374                  NULL /* accumulator */,
1375                  NULL /* accu_data */,
1376                  maman_file_complex_VOID__POINTER_UINT,
1377                  G_TYPE_NONE /* return_type */,
1378                  2     /* n_params */,
1379                  param_types /* param_types */);
1380 </programlisting>
1381       The code shown above first creates the closure which contains the code to complete the file write. This
1382       closure is registered as the default class_closure of the newly created signal.
1383     </para>
1384
1385     <para>
1386       Of course, you need to implement completely the code for the default closure since I just provided
1387       a skeleton:
1388 <programlisting>
1389 static void
1390 default_write_signal_handler (GObject *obj, guint8 *buffer, guint size, gpointer user_data)
1391 {
1392   g_assert (user_data == (gpointer)0xdeadbeaf);
1393   /* Here, we trigger the real file write. */
1394   g_print ("default signal handler: 0x%x %u\n", buffer, size);
1395 }
1396 </programlisting>
1397     </para>
1398
1399     <para>
1400       Finally, the client code must invoke the <function>maman_file_complex_write</function> function which 
1401       triggers the signal emission:
1402 <programlisting>
1403 void maman_file_complex_write (MamanFileComplex *self, guint8 *buffer, guint size)
1404 {
1405   /* trigger event */
1406   g_signal_emit (self,
1407                  MAMAN_FILE_COMPLEX_GET_CLASS (self)->write_signal_id,
1408                  0, /* details */
1409                  buffer, size);
1410 }
1411 </programlisting>
1412     </para>
1413     
1414     <para>
1415       The client code (as shown in <filename>sample/signal/test.c</filename> and below) can now connect signal handlers before 
1416       and after the file write is completed: since the default signal handler which does the write itself runs during the 
1417       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>
1418       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
1419       which emits signals, I would thus urge you to create all your signals with the G_SIGNAL_RUN_LAST such that your users
1420       have a maximum of flexibility as to when to get the event. Here, we combined it with G_SIGNAL_NO_RECURSE and 
1421       G_SIGNAL_NO_HOOKS to ensure our users will not try to do really weird things with our GObject. I strongly advise you
1422       to do the same unless you really know why (in which case you really know the inner workings of GSignal by heart and
1423       you are not reading this).
1424     </para>
1425     
1426     <para>
1427 <programlisting>
1428 static void complex_write_event_before (GObject *file, guint8 *buffer, guint size, gpointer user_data)
1429 {
1430   g_assert (user_data == NULL);
1431   g_print ("Complex Write event before: 0x%x, %u\n", buffer, size);
1432 }
1433
1434 static void complex_write_event_after (GObject *file, guint8 *buffer, guint size, gpointer user_data)
1435 {
1436   g_assert (user_data == NULL);
1437   g_print ("Complex Write event after: 0x%x, %u\n", buffer, size);
1438 }
1439
1440 static void test_file_complex (void)
1441 {
1442   guint8 buffer[100];
1443   GObject *file;
1444
1445   file = g_object_new (MAMAN_FILE_COMPLEX_TYPE, NULL);
1446
1447   g_signal_connect (G_OBJECT (file), "write",
1448                     (GCallback)complex_write_event_before,
1449                     NULL);
1450
1451   g_signal_connect_after (G_OBJECT (file), "write",
1452                           (GCallback)complex_write_event_after,
1453                           NULL);
1454
1455   maman_file_complex_write (MAMAN_FILE_COMPLEX (file), buffer, 50);
1456
1457   g_object_unref (G_OBJECT (file));
1458 }
1459 </programlisting>
1460       The code above generates the following output on my machine:
1461 <programlisting>
1462 Complex Write event before: 0xbfffe280, 50
1463 default signal handler: 0xbfffe280 50
1464 Complex Write event after: 0xbfffe280, 50
1465 </programlisting>
1466     </para>
1467
1468 -->
1469
1470 <!--
1471   this is also utterly wrong on so many levels that I don't even want
1472   to enumerate them. it's also full of completely irrelevant footnotes
1473   about personal preferences demonstrating a severe lack of whatsoever
1474   clue. the whole idea of storing the signal ids inside the Class
1475   structure is so fundamentally flawed that I'll require a frontal
1476   lobotomy just to forget I've ever seen it.
1477
1478     <sect2>
1479     <title>How most people do the same thing with less code</title>
1480     
1481       <para>For many historic reasons related to how the ancestor of GObject used to work in GTK+ 1.x versions,
1482         there is a much <emphasis>simpler</emphasis> 
1483         <footnote>
1484           <para>I personally think that this method is horribly mind-twisting: it adds a new indirection
1485           which unnecessarily complicates the overall code path. However, because this method is widely used
1486           by all of GTK+ and GObject code, readers need to understand it. The reason why this is done that way
1487           in most of GTK+ is related to the fact that the ancestor of GObject did not provide any other way to
1488           create a signal with a default handler than this one. Some people have tried to justify that it is done
1489           that way because it is better, faster (I am extremely doubtful about the faster bit. As a matter of fact,
1490           the better bit also mystifies me ;-). I have the feeling no one really knows and everyone does it
1491           because they copy/pasted code from code which did the same. It is probably better to leave this 
1492           specific trivia to hacker legends domain...
1493           </para>
1494         </footnote>
1495         way to create a signal with a default handler than to create 
1496         a closure by hand and to use the <function><link linkend="g-signal-newv">g_signal_newv</link></function>.
1497       </para>
1498     
1499       <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 
1500         handler which is stored in the class structure of the object. More specifically, the class structure 
1501         contains a function pointer which is accessed during signal emission to invoke the default handler and
1502         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
1503         class structure to the function pointer.
1504           <footnote>
1505             <para>I would like to point out here that the reason why the default handler of a signal is named everywhere
1506              a class_closure is probably related to the fact that it used to be really a function pointer stored in
1507              the class structure.
1508             </para>
1509           </footnote>
1510       </para>
1511     
1512       <para>The following code shows the declaration of the <type>MamanFileSimple</type> class structure which contains
1513         the <function>write</function> function pointer.
1514 <programlisting>
1515 struct _MamanFileSimpleClass {
1516   GObjectClass parent;
1517         
1518   guint write_signal_id;
1519
1520   /* signal default handlers */
1521   void (*write) (MamanFileSimple *self, guint8 *buffer, guint size);
1522 };
1523 </programlisting>
1524         The <function>write</function> function pointer is initialized in the class_init function of the object
1525         to <function>default_write_signal_handler</function>:
1526 <programlisting>
1527 static void
1528 maman_file_simple_class_init (gpointer g_class,
1529                                gpointer g_class_data)
1530 {
1531   GObjectClass *gobject_class = G_OBJECT_CLASS (g_class);
1532   MamanFileSimpleClass *klass = MAMAN_FILE_SIMPLE_CLASS (g_class);
1533
1534   klass->write = default_write_signal_handler;
1535 </programlisting>
1536         Finally, the signal is created with <function><link linkend="g-signal-new">g_signal_new</link></function> in the same class_init function:
1537 <programlisting>
1538 klass->write_signal_id = 
1539  g_signal_new ("write",
1540                G_TYPE_FROM_CLASS (g_class),
1541                G_SIGNAL_RUN_LAST | G_SIGNAL_NO_RECURSE | G_SIGNAL_NO_HOOKS,
1542                G_STRUCT_OFFSET (MamanFileSimpleClass, write),
1543                NULL /* accumulator */,
1544                NULL /* accu_data */,
1545                maman_file_complex_VOID__POINTER_UINT,
1546                G_TYPE_NONE /* return_type */,
1547                2     /* n_params */,
1548                G_TYPE_POINTER,
1549                G_TYPE_UINT);
1550 </programlisting>
1551         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>
1552         macro which indicates the offset of the member <emphasis>write</emphasis> from the start of the 
1553         <type>MamanFileSimpleClass</type> class structure.
1554         <footnote>
1555           <para>GSignal uses this offset to create a special wrapper closure 
1556            which first retrieves the target function pointer before calling it.
1557           </para>
1558         </footnote>
1559      </para>
1560
1561      <para>
1562        While the complete code for this type of default handler looks less cluttered as shown in 
1563        <filename>sample/signal/maman-file-simple.{h|c}</filename>, it contains numerous subtleties.
1564        The main subtle point which everyone must be aware of is that the signature of the default 
1565        handler created that way does not have a user_data argument: 
1566        <function>default_write_signal_handler</function> is different in 
1567        <filename>sample/signal/maman-file-complex.c</filename> and in 
1568        <filename>sample/signal/maman-file-simple.c</filename>.
1569      </para>
1570
1571      <para>If you have doubts about which method to use, I would advise you to use the second one which
1572        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>: 
1573        it is better to write code which looks like the vast majority of other GTK+/GObject code than to
1574        do it your own way. However, now, you know why.
1575      </para>
1576
1577    </sect2>
1578
1579   </sect1>
1580 -->
1581
1582 <!--
1583   yet another pointless section. if we are scared of possible abuses
1584   from the users then we should not be mentioning it inside a tutorial
1585   for beginners. but, obviously, there's nothing to be afraid of - it's
1586   just that this section must be completely reworded.
1587
1588   <sect1>
1589     <title>How users can abuse signals (and why some think it is good)</title>
1590
1591     <para>Now that you know how to create signals to which the users can connect easily and at any point in
1592       the signal emission process thanks to <function><link linkend="g-signal-connect">g_signal_connect</link></function>, 
1593       <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
1594       users can and will screw you. This is also interesting to know how you too, can screw other people.
1595       This will make you feel good and eleet.
1596     </para>
1597     
1598     <para>
1599       The users can:
1600       <itemizedlist>
1601          <listitem><para>stop the emission of the signal at anytime</para></listitem>
1602          <listitem><para>override the default handler of the signal if it is stored as a function
1603            pointer in the class structure (which is the preferred way to create a default signal handler,
1604            as discussed in the previous section).</para></listitem>
1605        </itemizedlist> 
1606     </para>
1607     
1608     <para>
1609       In both cases, the original programmer should be as careful as possible to write code which is
1610       resistant to the fact that the default handler of the signal might not able to run. This is obviously
1611       not the case in the example used in the previous sections since the write to the file depends on whether
1612       or not the default handler runs (however, this might be your goal: to allow the user to prevent the file 
1613       write if he wishes to).
1614     </para>
1615     
1616     <para>
1617       If all you want to do is to stop the signal emission from one of the callbacks you connected yourself,
1618       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 
1619       it further.
1620     </para>
1621     
1622     <para>
1623       If the signal's default handler is just a class function pointer, it is also possible to override 
1624       it yourself from the class_init function of a type which derives from the parent. That way, when the signal
1625       is emitted, the parent class will use the function provided by the child as a signal default handler.
1626       Of course, it is also possible (and recommended) to chain up from the child to the parent's default signal 
1627       handler to ensure the integrity of the parent object.
1628     </para>
1629     
1630     <para>
1631       Overriding a class method and chaining up was demonstrated in <xref linkend="howto-gobject-methods"/> 
1632       which is why I won't bother to show exactly how to do it here again.
1633     </para>
1634
1635   </sect1>
1636
1637 -->
1638
1639 </chapter>
1640
1641 <!--
1642   <sect2>
1643     <title>Warning on signal creation and default closure</title>
1644
1645     <para>
1646       Most of the existing code I have seen up to now (in both GTK+, GNOME libraries and
1647       many GTK+ and GNOME applications) using signals uses a small
1648       variation of the default handler pattern I have shown in the previous section.
1649     </para>
1650
1651     <para>
1652       Usually, the <function><link linkend="g-signal-new">g_signal_new</link></function> function is preferred over
1653       <function><link linkend="g-signal-newv">g_signal_newv</link></function>. When <function><link linkend="g-signal-new">g_signal_new</link></function>
1654       is used, the default closure is exported as a class function. For example,
1655       <filename>gobject.h</filename> contains the declaration of <type><link linkend="GObjectClass">GObjectClass</link></type>
1656       whose notify class function is the default handler for the <emphasis>notify</emphasis>
1657       signal:
1658 <programlisting>
1659 struct  _GObjectClass
1660 {
1661   GTypeClass   g_type_class;
1662
1663   /* class methods and other stuff. */
1664
1665   /* signals */
1666   void (*notify) (GObject     *object,
1667                   GParamSpec  *pspec);
1668 };
1669 </programlisting>
1670      </para>
1671
1672      <para>
1673        <filename>gobject.c</filename>'s <function><link linkend="g-object-do-class-init">g_object_do_class_init</link></function> function
1674        registers the <emphasis>notify</emphasis> signal and initializes this class function
1675        to NULL:
1676 <programlisting>
1677 static void
1678 g_object_do_class_init (GObjectClass *class)
1679 {
1680
1681   /* Stuff */
1682
1683   class->notify = NULL;
1684
1685   gobject_signals[NOTIFY] =
1686     g_signal_new ("notify",
1687                   G_TYPE_FROM_CLASS (class),
1688                   G_SIGNAL_RUN_FIRST | G_SIGNAL_NO_RECURSE | G_SIGNAL_DETAILED | G_SIGNAL_NO_HOOKS,
1689                   G_STRUCT_OFFSET (GObjectClass, notify),
1690                   NULL, NULL,
1691                   g_cclosure_marshal_VOID__PARAM,
1692                   G_TYPE_NONE,
1693                   1, G_TYPE_PARAM);
1694 }
1695 </programlisting>
1696        <function><link linkend="g-signal-new">g_signal_new</link></function> creates a <type><link linkend="GClosure">GClosure</link></type> which dereferences the
1697        type's class structure to access the class function pointer and invoke it if it not NULL. The
1698        class function is ignored it is set to NULL.
1699      </para>
1700
1701      <para>
1702        To understand the reason for such a complex scheme to access the signal's default handler, 
1703        you must remember the whole reason for the use of these signals. The goal here is to delegate
1704        a part of the process to the user without requiring the user to subclass the object to override
1705        one of the class functions. The alternative to subclassing, that is, the use of signals
1706        to delegate processing to the user, is, however, a bit less optimal in terms of speed: rather
1707        than just dereferencing a function pointer in a class structure, you must start the whole
1708        process of signal emission which is a bit heavyweight.
1709      </para>
1710
1711      <para>
1712        This is why some people decided to use class functions for some signal's default handlers:
1713        rather than having users connect a handler to the signal and stop the signal emission
1714        from within that handler, you just need to override the default class function which is
1715        supposedly more efficient.
1716      </para>
1717
1718     </sect2>
1719 -->
1720 </part>