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