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