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