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