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