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