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