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