Unify spelling of GObject and GType. Improve some wording. Update the
[platform/upstream/glib.git] / docs / reference / gobject / tut_gobject.xml
1 <?xml version='1.0' encoding="ISO-8859-1"?>
2
3   <chapter id="chapter-gobject">
4     <title>The GObject base class</title>
5
6     <para>
7       The two previous chapters discussed the details of Glib's Dynamic Type System
8       and its signal control system. The GObject library also contains an implementation
9       for a base fundamental type named <type><link linkend="GObject">GObject</link></type>.
10     </para>
11
12     <para>
13       <type><link linkend="GObject">GObject</link></type> is a fundamental classed instantiable type. It implements:
14       <itemizedlist>
15         <listitem><para>Memory management with reference counting</para></listitem>
16         <listitem><para>Construction/Destruction of instances</para></listitem>
17         <listitem><para>Generic per-object properties with set/get function pairs</para></listitem>
18         <listitem><para>Easy use of signals</para></listitem>
19       </itemizedlist>
20       All the GNOME libraries which use the GLib type system (like Gtk+ and GStreamer)
21       inherit from <type><link linkend="GObject">GObject</link></type> which is why it is important to understand
22       the details of how it works.
23     </para>
24
25     <sect1 id="gobject-instanciation">
26       <title>Object instanciation</title>
27
28       <para>
29         The <function><link linkend="g-object-new">g_object_new</link></function> family of functions can be used to instantiate any
30         GType which inherits from the GObject base type. All these functions make sure the class
31         and instance structures have been correctly initialized by glib's type system and
32         then invoke at one point or another the constructor class method which is used to:
33         <itemizedlist>
34           <listitem><para>
35               Allocate and clear memory through <function><link linkend="g-type-create-instance">g_type_create_instance</link></function>,
36             </para></listitem>
37           <listitem><para>
38               Initialize the object' instance with the construction properties.
39             </para></listitem>
40         </itemizedlist>
41        Although one can expect all class and instance members (except the fields
42        pointing to the parents) to be set to zero, some consider it good practice to explicitly set them.
43       </para>
44
45       <para>
46         Objects which inherit from GObject are allowed to override this constructor class method:
47         they should however chain to their parent constructor method before doing so:
48 <programlisting>
49   GObject*   (*constructor)     (GType                  type,
50                                  guint                  n_construct_properties,
51                                  GObjectConstructParam *construct_properties);
52 </programlisting>
53       </para>
54
55       <para>
56         The example below shows how <type>MamanBar</type> overrides the parent's constructor:
57 <programlisting>
58 #define MAMAN_TYPE_BAR            (maman_bar_get_type ())
59 #define MAMAN_BAR(obj)            (G_TYPE_CHECK_INSTANCE_CAST ((obj), MAMAN_TYPE_BAR, MamanBar))
60 #define MAMAN_BAR_CLASS(klass)    (G_TYPE_CHECK_CLASS_CAST ((klass), MAMAN_TYPE_BAR, MamanBarClass))
61 #define MAMAN_IS_BAR(obj)         (G_TYPE_CHECK_INSTANCE_TYPE ((obj), MAMAN_TYPE_BAR))
62 #define MAMAN_IS_BAR_CLASS(klass) (G_TYPE_CHECK_CLASS_TYPE ((klass), MAMAN_TYPE_BAR))
63 #define MAMAN_BAR_GET_CLASS(obj)  (G_TYPE_INSTANCE_GET_CLASS ((obj), MAMAN_TYPE_BAR, MamanBarClass))
64
65 typedef struct _MamanBar MamanBar;
66 typedef struct _MamanBarClass MamanBarClass;
67
68 struct _MamanBar {
69   GObject parent;
70   /* instance members */
71 };
72
73 struct _MamanBarClass {
74   GObjectClass parent;
75
76   /* class members */
77 };
78
79 /* used by MAMAN_TYPE_BAR */
80 GType maman_bar_get_type (void);
81
82 static GObject *
83 maman_bar_constructor (GType                  type,
84                        guint                  n_construct_properties,
85                        GObjectConstructParam *construct_properties)
86 {
87   GObject *obj;
88
89   {
90     /* Invoke parent constructor. */
91     MamanBarClass *klass;
92     GObjectClass *parent_class;  
93     klass = MAMAN_BAR_CLASS (g_type_class_peek (MAMAN_TYPE_BAR));
94     parent_class = G_OBJECT_CLASS (g_type_class_peek_parent (klass));
95     obj = parent_class->constructor (type,
96                                      n_construct_properties,
97                                      construct_properties);
98   }
99   
100   /* do stuff. */
101
102   return obj;
103 }
104
105 static void
106 maman_bar_instance_init (GTypeInstance   *instance,
107                          gpointer         g_class)
108 {
109   MamanBar *self = (MamanBar *)instance;
110   /* do stuff */
111 }
112
113 static void
114 maman_bar_class_init (gpointer g_class,
115                       gpointer g_class_data)
116 {
117   GObjectClass *gobject_class = G_OBJECT_CLASS (g_class);
118   MamanBarClass *klass = MAMAN_BAR_CLASS (g_class);
119
120   gobject_class->constructor = maman_bar_constructor;
121 }
122
123 GType maman_bar_get_type (void)
124 {
125   static GType type = 0;
126   if (type == 0) {
127     static const GTypeInfo info = {
128       sizeof (MamanBarClass),
129       NULL,   /* base_init */
130       NULL,   /* base_finalize */
131       maman_bar_class_init,   /* class_init */
132       NULL,   /* class_finalize */
133       NULL,   /* class_data */
134       sizeof (MamanBar),
135       0,      /* n_preallocs */
136       maman_bar_instance_init    /* instance_init */
137     };
138     type = g_type_register_static (G_TYPE_OBJECT,
139                                    "MamanBarType",
140                                    &amp;info, 0);
141   }
142   return type;
143 }
144 </programlisting>
145         If the user instantiates an object <type>MamanBar</type> with:
146 <programlisting>
147 MamanBar *bar = g_object_new (MAMAN_TYPE_BAR, NULL);
148 </programlisting>       
149         If this is the first instantiation of such an object, the <function>maman_b_class_init</function>
150         function will be invoked after any <function>maman_b_base_class_init</function> function. 
151         This will make sure the class structure of this new object is correctly initialized. Here, 
152         <function>maman_bar_class_init</function> is expected to override the object's class methods
153         and setup the class' own methods. In the example above, the constructor method is the only 
154         overridden method: it is set to <function>maman_bar_constructor</function>.
155       </para>
156
157       <para>
158         Once <function><link linkend="g-object-new">g_object_new</link></function> has obtained a reference to an initialized
159         class structure, it invokes its constructor method to create an instance of the new 
160         object. Since it has just been overridden by <function>maman_bar_class_init</function> 
161         to <function>maman_bar_constructor</function>, the latter is called and, because it
162         was implemented correctly, it chains up to its parent's constructor. The problem here
163         is how we can find the parent constructor. An approach (used in GTK+ source code) would be
164         to save the original constructor in a static variable from <function>maman_bar_class_init</function>
165         and then to re-use it from <function>maman_bar_constructor</function>. This is clearly possible
166         and very simple but I was told it was not nice and the prefered way is to use the 
167         <function><link linkend="g-type-class-peek">g_type_class_peek</link></function> and <function><link linkend="g-type-class-peek-parent">g_type_class_peek_parent</link></function> functions.
168       </para>
169
170       <para>
171         Finally, at one point or another, <function>g_object_constructor</function> is invoked
172         by the last constructor in the chain. This function allocates the object's instance' buffer 
173         through <function><link linkend="g-type-create-instance">g_type_create_instance</link></function>
174         which means that the instance_init function is invoked at this point if one
175         was registered. After instance_init returns, the object is fully initialized and should be 
176         ready to answer any user-request. When <function><link linkend="g-type-create-instance">g_type_create_instance</link></function>
177         returns, <function>g_object_constructor</function> sets the construction properties
178         (ie: the properties which were given to <function><link linkend="g-object-new">g_object_new</link></function>) and returns
179         to the user's constructor which is then allowed to do useful instance initialization...
180       </para>
181
182       <para>
183         The process described above might seem a bit complicated (it <emphasis>is</emphasis> actually
184         overly complicated in my opinion..) but it can be summarized easily by the table below which
185         lists the functions invoked by <function><link linkend="g-object-new">g_object_new</link></function> and their order of
186         invocation.
187       </para>
188
189       <para>
190         The array below lists the functions invoked by <function><link linkend="g-object-new">g_object_new</link></function> and 
191         their order of invocation:
192
193         <table id="gobject-construction-table">
194           <title><function><link linkend="g-object-new">g_object_new</link></function></title>
195           <tgroup cols="3">
196             <colspec colwidth="*" colnum="1" align="left"/>
197             <colspec colwidth="*" colnum="2" align="left"/>
198             <colspec colwidth="8*" colnum="3" align="left"/>
199
200             <thead>
201               <row>
202                 <entry>Invocation time</entry>
203                 <entry>Function Invoked</entry>
204                 <entry>Function's parameters</entry>
205                 <entry>Remark</entry>
206               </row>
207             </thead>
208             <tbody>
209               <row>
210                 <entry morerows="3">First call to <function><link linkend="g-object-new">g_object_new</link></function> for target type</entry>
211                 <entry>target type's base_init function</entry>
212                 <entry>On the inheritance tree of classes from fundamental type to target type. 
213                   base_init is invoked once for each class structure.</entry>
214                 <entry>
215                   I have no real idea on how this can be used. If you have a good real-life
216                   example of how a class' base_init can be used, please, let me know.
217                 </entry>
218               </row>
219               <row>
220                 <!--entry>First call to <function><link linkend="g-object-new">g_object_new</link></function> for target type</entry-->
221                 <entry>target type's class_init function</entry>
222                 <entry>On target type's class structure</entry>
223                 <entry>
224                   Here, you should make sure to initialize or override class methods (that is,
225                   assign to each class' method its function pointer) and create the signals and
226                   the properties associated to your object.
227                 </entry>
228               </row>
229               <row>
230                 <!--entry>First call to <function><link linkend="g-object-new">g_object_new</link></function> for target type</entry-->
231                 <entry>interface' base_init function</entry>
232                 <entry>On interface' vtable</entry>
233                 <entry></entry>
234               </row>
235               <row>
236                 <!--entry>First call to <function><link linkend="g-object-new">g_object_new</link></function> for target type</entry-->
237                 <entry>interface' interface_init function</entry>
238                 <entry>On interface' vtable</entry>
239                 <entry></entry>
240               </row>
241               <row>
242                 <entry morerows="1">Each call to <function><link linkend="g-object-new">g_object_new</link></function> for target type</entry>
243                 <entry>target type's class constructor method: GObjectClass->constructor</entry>
244                 <entry>On object's instance</entry>
245                 <entry>
246                   If you need to complete the object initialization after all the construction properties
247                   are set, override the constructor method and make sure to chain up to the object's
248                   parent class before doing your own initialization.
249                   In doubt, do not override the constructor method.
250                 </entry>
251               </row>
252               <row>
253                 <!--entry>Each call to <function><link linkend="g-object-new">g_object_new</link></function> for target type</entry-->
254                 <entry>type's instance_init function</entry>
255                 <entry>On the inheritance tree of classes from fundamental type to target type. 
256                 the instance_init provided for each type is invoked once for each instance 
257                 structure.</entry>
258                 <entry>
259                   Provide an instance_init function to initialize your object before its construction
260                   properties are set. This is the preferred way to initialize a GObject instance.
261                   This function is equivalent to C++ constructors.
262                 </entry>
263               </row>
264             </tbody>
265           </tgroup>
266         </table>
267       </para>
268
269       <para>
270         Readers should feel concerned about one little twist in the order in which functions 
271         are invoked: while, technically, the class' constructor method is called
272         <emphasis>before</emphasis> the GType's instance_init function (since 
273         <function><link linkend="g-type-create-instance">g_type_create_instance</link></function> which calls instance_init is called by
274         <function>g_object_constructor</function> which is the top-level class 
275         constructor method and to which users are expected to chain to), the user's code
276         which runs in a user-provided constructor will always run <emphasis>after</emphasis>
277         GType's instance_init function since the user-provided constructor 
278         <emphasis>must</emphasis> (you've been warned) chain up <emphasis>before</emphasis>
279         doing anything useful.
280       </para>
281     </sect1>
282
283     <sect1 id="gobject-memory">
284       <title>Object memory management</title>
285
286       <para>
287         The memory-management API for GObjects is a bit complicated but the idea behind it
288         is pretty simple: the goal is to provide a flexible model based on reference counting
289         which can be integrated in applications which use or require different memory management
290         models (such as garbage collection, aso...). The methods which are used to
291         manipulate this reference count are described below.
292 <programlisting>
293 /*
294   Refcounting
295 */
296 gpointer    g_object_ref                      (gpointer        object);
297 void        g_object_unref                    (gpointer        object);
298
299 /*
300   Weak References
301 */
302 typedef void (*GWeakNotify)             (gpointer      data,
303                                          GObject      *where_the_object_was);
304 void        g_object_weak_ref                 (GObject        *object,
305                                                GWeakNotify     notify,
306                                                gpointer        data);
307 void        g_object_weak_unref               (GObject        *object,
308                                                GWeakNotify     notify,
309                                                gpointer        data);
310 void        g_object_add_weak_pointer         (GObject        *object, 
311                                                gpointer       *weak_pointer_location);
312 void        g_object_remove_weak_pointer      (GObject        *object, 
313                                                gpointer       *weak_pointer_location);
314 /*
315   Cycle handling
316 */
317 void        g_object_run_dispose              (GObject        *object);
318 </programlisting>
319       </para>
320
321       <sect2 id="gobject-memory-refcount">
322         <title>Reference count</title>
323
324         <para>
325           The functions <function><link linkend="g-object-ref">g_object_ref</link></function>/<function><link linkend="g-object-unref">g_object_unref</link></function> respectively 
326           increase and decrease the reference count.These functions are thread-safe as of GLib 2.8.
327           The reference count is, unsurprisingly, initialized to one by 
328           <function><link linkend="g-object-new">g_object_new</link></function> which means that the caller
329           is currenly the sole owner of the newly-created reference.
330           When the reference count reaches zero, that is, 
331           when <function><link linkend="g-object-unref">g_object_unref</link></function> is called by the last client holding
332           a reference to the object, the <emphasis>dispose</emphasis> and the 
333           <emphasis>finalize</emphasis> class methods are invoked.
334         </para>
335         <para>
336           Finally, after <emphasis>finalize</emphasis> is invoked, 
337           <function><link linkend="g-type-free-instance">g_type_free_instance</link></function> is called to free the object instance.
338           Depending on the memory allocation policy decided when the type was registered (through
339           one of the <function>g_type_register_*</function> functions), the object's instance 
340           memory will be freed or returned to the object pool for this type.
341           Once the object has been freed, if it was the last instance of the type, the type's class
342           will be destroyed as described in <xref linkend="gtype-instantiable-classed"/> and 
343             <xref linkend="gtype-non-instantiable-classed"/>.
344         </para>
345
346         <para>
347           The table below summarizes the destruction process of a GObject:
348           <table id="gobject-destruction-table">
349             <title><function><link linkend="g-object-unref">g_object_unref</link></function></title>
350             <tgroup cols="3">
351               <colspec colwidth="*" colnum="1" align="left"/>
352               <colspec colwidth="*" colnum="2" align="left"/>
353               <colspec colwidth="8*" colnum="3" align="left"/>
354
355               <thead>
356                 <row>
357                   <entry>Invocation time</entry>
358                   <entry>Function Invoked</entry>
359                   <entry>Function's parameters</entry>
360                   <entry>Remark</entry>
361                 </row>
362               </thead>
363               <tbody>
364                 <row>
365                   <entry morerows="1">Last call to <function><link linkend="g-object-unref">g_object_unref</link></function> for an instance
366                     of target type
367                    </entry>
368                   <entry>target type's dispose class function</entry>
369                   <entry>GObject instance</entry>
370                   <entry>
371                     When dispose ends, the object should not hold any reference to any other
372                     member object. The object is also expected to be able to answer client
373                     method invocations (with possibly an error code but no memory violation)
374                     until finalize is executed. dispose can be executed more than once.
375                   dispose should chain up to its parent implementation just before returning
376                   to the caller.
377                   </entry>
378                 </row>
379                 <row>
380                   <!--entry>Last call to <function><link linkend="g-object-unref">g_object_unref</link></function> for an instance
381                     of target type
382                   </entry-->
383                   <entry>target type's finalize class function</entry>
384                   <entry>GObject instance</entry>
385                   <entry>
386                     Finalize is expected to complete the destruction process initiated by
387                     dispose. It should complete the object's destruction. finalize will be
388                     executed only once.
389                   finalize should chain up to its parent implementation just before returning
390                   to the caller.
391                     The reason why the destruction process is split is two different phases is
392                     explained in <xref linkend="gobject-memory-cycles"/>.
393                   </entry>
394                 </row>
395                 <row>
396                   <entry morerows="3">Last call to <function><link linkend="g-object-unref">g_object_unref</link></function> for the last
397                     instance of target type
398                    </entry>
399                   <entry>interface' interface_finalize function</entry>
400                   <entry>On interface' vtable</entry>
401                   <entry>Never used in practice. Unlikely you will need it.</entry>
402                 </row>
403                 <row>
404                   <!--entry>Last call to <function><link linkend="g-object-unref">g_object_unref</link></function>for the last
405                     instance of target type
406                    </entry-->
407                   <entry>interface' base_finalize function</entry>
408                   <entry>On interface' vtable</entry>
409                   <entry>Never used in practice. Unlikely you will need it.</entry>
410                 </row>
411                 <row>
412                   <!--entry>Last call to <function><link linkend="g-object-unref">g_object_unref</link></function> for the last
413                     instance of target type
414                    </entry-->
415                   <entry>target type's class_finalize function</entry>
416                   <entry>On target type's class structure</entry>
417                   <entry>Never used in practice. Unlikely you will need it.</entry>
418                 </row>
419                 <row>
420                   <!--entry>Last call to <function><link linkend="g-object-unref">g_object_unref</link></function> for the last
421                     instance of target type
422                    </entry-->
423                   <entry>type's base_finalize function</entry>
424                   <entry>On the inheritance tree of classes from fundamental type to target type.
425                     base_init is invoked once for each class structure.</entry>
426                   <entry>Never used in practice. Unlikely you will need it.</entry>
427                 </row>
428               </tbody>
429             </tgroup>
430           </table>              
431         </para>
432
433       </sect2>
434
435       <sect2 id="gobject-memory-weakref">
436         <title>Weak References</title>
437       
438         <para>
439         Weak References are used to monitor object finalization: 
440         <function><link linkend="g-object-weak-ref">g_object_weak_ref</link></function> adds a monitoring callback which does
441         not hold a reference to the object but which is invoked when the object runs 
442         its dispose method. As such, each weak ref can be invoked more than once upon
443         object finalization (since dispose can run more than once during object 
444         finalization).
445         </para>
446
447       <para>
448         <function><link linkend="g-object-weak-unref">g_object_weak_unref</link></function> can be used to remove a monitoring
449         callback from the object. 
450       </para>
451
452       <para>
453         Weak References are also used to implement <function><link linkend="g-object-add-weak-pointer">g_object_add_weak_pointer</link></function>
454         and <function><link linkend="g-object-remove-weak-pointer">g_object_remove_weak_pointer</link></function>. These functions add a weak reference
455         to the object they are applied to which makes sure to nullify the pointer given by the user
456         when object is finalized.
457       </para>
458
459     </sect2>
460
461     <sect2 id="gobject-memory-cycles">
462       <title>Reference counts and cycles</title>
463       
464       <para>
465         Note: the following section was inspired by James Henstridge. I guess this means that 
466         all praise and all curses will be directly forwarded to him.
467       </para>
468
469       <para>
470         GObject's memory management model was designed to be easily integrated in existing code
471         using garbage collection. This is why the destruction process is split in two phases:
472         the first phase, executed in the dispose handler is supposed to release all references
473         to other member objects. The second phase, executed by the finalize handler is supposed
474         to complete the object's destruction process. Object methods should be able to run
475         without program error (that is, without segfault :) in-between the two phases.
476       </para>
477
478       <para>
479         This two-step destruction process is very useful to break reference counting cycles.
480         While the detection of the cycles is up to the external code, once the cycles have been
481         detected, the external code can invoke <function><link linkend="g-object-dispose">g_object_dispose</link></function> which 
482         will indeed break any existing cycles since it will run the dispose handler associated
483         to the object and thus release all references to other objects.
484       </para>
485
486       <para>
487         Attentive readers might now have understood one of the rules about the dispose handler
488         we stated a bit sooner: the dispose handler can be invoked multiple times. Let's say we
489         have a reference count cycle: object A references B which itself references object A.
490         Let's say we have detected the cycle and we want to destroy the two objects. One way to 
491         do this would be to invoke <function><link linkend="g-object-dispose">g_object_dispose</link></function> on one of the 
492         objects.
493       </para>
494
495       <para>
496         If object A releases all its references to all objects, this means it releases its
497         reference to object B. If object B was not owned by anyone else, this is its last
498         reference count which means this last unref runs B's dispose handler which, in turn,
499         releases B's reference on object A. If this is A's last reference count, this last 
500         unref runs A's dispose handler which is running for the second time before
501         A's finalize handler is invoked !
502       </para>
503
504       <para>
505         The above example, which might seem a bit contrived can really happen if your
506         GObject's are being handled by language bindings. I would thus suggest the rules stated above
507         for object destruction are closely followed. Otherwise, <emphasis>Bad Bad Things</emphasis> 
508         will happen.
509       </para>
510     </sect2>
511     </sect1>
512
513   <sect1 id="gobject-properties">
514     <title>Object properties</title>
515
516     <para>
517       One of GObject's nice features is its generic get/set mechanism for object
518       properties. When an object
519       is instanciated, the object's class_init handler should be used to register
520       the object's properties with <function><link linkend="g-object-class-install-property">g_object_class_install_property</link></function>
521       (implemented in <filename>gobject.c</filename>).
522     </para>
523
524     <para>
525       The best way to understand how object properties work is by looking at a real example
526       on how it is used:
527 <programlisting>
528 /************************************************/
529 /* Implementation                               */
530 /************************************************/
531
532 enum {
533   MAMAN_BAR_CONSTRUCT_NAME = 1,
534   MAMAN_BAR_PAPA_NUMBER,
535 };
536
537 static void
538 maman_bar_instance_init (GTypeInstance   *instance,
539                          gpointer         g_class)
540 {
541   MamanBar *self = (MamanBar *)instance;
542 }
543
544
545 static void
546 maman_bar_set_property (GObject      *object,
547                         guint         property_id,
548                         const GValue *value,
549                         GParamSpec   *pspec)
550 {
551   MamanBar *self = (MamanBar *) object;
552
553   switch (property_id) {
554   case MAMAN_BAR_CONSTRUCT_NAME: {
555     g_free (self->priv->name);
556     self->priv->name = g_value_dup_string (value);
557     g_print ("maman: %s\n",self->priv->name);
558   }
559     break;
560   case MAMAN_BAR_PAPA_NUMBER: {
561     self->priv->papa_number = g_value_get_uchar (value);
562     g_print ("papa: %u\n",self->priv->papa_number);
563   }
564     break;
565   default:
566     /* We don't have any other property... */
567     G_OBJECT_WARN_INVALID_PROPERTY_ID(object,property_id,pspec);
568     break;
569   }
570 }
571
572 static void
573 maman_bar_get_property (GObject      *object,
574                         guint         property_id,
575                         GValue       *value,
576                         GParamSpec   *pspec)
577 {
578   MamanBar *self = (MamanBar *) object;
579
580   switch (property_id) {
581   case MAMAN_BAR_CONSTRUCT_NAME: {
582     g_value_set_string (value, self->priv->name);
583   }
584     break;
585   case MAMAN_BAR_PAPA_NUMBER: {
586     g_value_set_uchar (value, self->priv->papa_number);
587   }
588     break;
589   default:
590     /* We don't have any other property... */
591     G_OBJECT_WARN_INVALID_PROPERTY_ID(object,property_id,pspec);
592     break;
593   }
594 }
595
596 static void
597 maman_bar_class_init (gpointer g_class,
598                       gpointer g_class_data)
599 {
600   GObjectClass *gobject_class = G_OBJECT_CLASS (g_class);
601   MamanBarClass *klass = MAMAN_BAR_CLASS (g_class);
602   GParamSpec *pspec;
603
604   gobject_class->set_property = maman_bar_set_property;
605   gobject_class->get_property = maman_bar_get_property;
606
607   pspec = g_param_spec_string ("maman-name",
608                                "Maman construct prop",
609                                "Set maman's name",
610                                "no-name-set" /* default value */,
611                                G_PARAM_CONSTRUCT_ONLY | G_PARAM_READWRITE);
612   g_object_class_install_property (gobject_class,
613                                    MAMAN_BAR_CONSTRUCT_NAME,
614                                    pspec);
615
616   pspec = g_param_spec_uchar ("papa-number",
617                               "Number of current Papa",
618                               "Set/Get papa's number",
619                               0  /* minimum value */,
620                               10 /* maximum value */,
621                               2  /* default value */,
622                               G_PARAM_READWRITE);
623   g_object_class_install_property (gobject_class,
624                                    MAMAN_BAR_PAPA_NUMBER,
625                                    pspec);
626 }
627
628 /************************************************/
629 /* Use                                          */
630 /************************************************/
631
632 GObject *bar;
633 GValue val = {0,};
634 bar = g_object_new (MAMAN_TYPE_SUBBAR, NULL);
635 g_value_init (&amp;val, G_TYPE_CHAR);
636 g_value_set_char (&amp;val, 11);
637 g_object_set_property (G_OBJECT (bar), "papa-number", &amp;val);
638 </programlisting>
639       The client code just above looks simple but a lot of things happen under the hood:
640     </para>
641
642     <para>
643       <function><link linkend="g-object-set-property">g_object_set_property</link></function> first ensures a property
644       with this name was registered in bar's class_init handler. If so, it calls
645       <function><link linkend="object-set-property">object_set_property</link></function> which first walks the class hierarchy,
646       from bottom, most derived type, to top, fundamental type to find the class
647       which registered that property. It then tries to convert the user-provided GValue
648       into a GValue whose type if that of the associated property.
649     </para>
650
651     <para>
652       If the user provides a signed char GValue, as is shown
653       here, and if the object's property was registered as an unsigned int, 
654       <function><link linkend="g-value-transform">g_value_transform</link></function> will try to transform the input signed char into
655       an unsigned int. Of course, the success of the transformation depends on the availability
656       of the required transform function. In practice, there will almost always be a transformation
657       <footnote>
658         <para>Its behaviour might not be what you expect but it is up to you to actually avoid
659           relying on these transformations.
660         </para>
661       </footnote>
662       which matches and conversion will be caried out if needed.
663     </para>
664
665     <para>
666       After transformation, the <type><link linkend="GValue">GValue</link></type> is validated by 
667       <function><link linkend="g-param-value-validate">g_param_value_validate</link></function> which makes sure the user's
668       data stored in the <type><link linkend="GValue">GValue</link></type> matches the characteristics specified by
669       the property's <type><link linkend="GParamSpec">GParamSpec</link></type>.  Here, the <type><link linkend="GParamSpec">GParamSpec</link></type> we 
670       provided in class_init has a validation function which makes sure that the GValue
671       contains a value which respects the minimum and maximum bounds of the 
672       <type><link linkend="GParamSpec">GParamSpec</link></type>. In the example above, the client's GValue does not
673       respect these constraints (it is set to 11, while the maximum is 10). As such, the
674       <function><link linkend="g-object-set-property">g_object_set_property</link></function> function will return with an error.
675     </para>
676
677     <para>
678       If the user's GValue had been set to a valid value, <function><link linkend="g-object-set-property">g_object_set_property</link></function>
679       would have proceeded with calling the object's set_property class method. Here, since our
680       implementation of Foo did override this method, the code path would jump to
681       <function>foo_set_property</function> after having retrieved from the 
682       <type><link linkend="GParamSpec">GParamSpec</link></type> the <emphasis>param_id</emphasis>
683       <footnote>
684         <para>
685           It should be noted that the param_id used here need only to uniquely identify each 
686           <type><link linkend="GParamSpec">GParamSpec</link></type> within the <type><link linkend="FooClass">FooClass</link></type> such that the switch
687           used in the set and get methods actually works. Of course, this locally-unique 
688           integer is purely an optimization: it would have been possible to use a set of 
689           <emphasis>if (strcmp (a, b) == 0) {} else if (strcmp (a, b) == 0) {}</emphasis> statements.
690         </para>
691       </footnote>
692       which had been stored by
693       <function><link linkend="g-object-class-install-property">g_object_class_install_property</link></function>.
694     </para>
695
696     <para>
697       Once the property has been set by the object's set_property class method, the code path
698       returns to <function><link linkend="g-object-set-property">g_object_set_property</link></function> which calls 
699       <function><link linkend="g-object-notify-queue-thaw">g_object_notify_queue_thaw</link></function>. This function makes sure that
700       the "notify" signal is emitted on the object's instance with the changed property as
701       parameter unless notifications were frozen by <function><link linkend="g-object-freeze-notify">g_object_freeze_notify</link></function>.
702     </para>
703
704     <para>
705       <function><link linkend="g-object-thaw-notify">g_object_thaw_notify</link></function> can be used to re-enable notification of 
706       property modifications through the "notify" signal. It is important to remember that
707       even if properties are changed while property change notification is frozen, the "notify"
708       signal will be emitted once for each of these changed properties as soon as the property
709       change notification is thawn: no property change is lost for the "notify" signal. Signal
710       can only be delayed by the notification freezing mechanism.
711     </para>
712     
713     <para>
714       It sounds like a tedious task to set up GValues everytime when one wants to modify a property.
715       In practice one will rarely do this. The functions <function><link linkend="g-object-set-property">g_object_set_property</link></function>
716       and <function><link linkend="g-object-get-property">g_object_get_property</link></function>
717       are meant to be used by language bindings. For application there is an easier way and
718       that is described next.
719     </para>
720
721     <sect2 id="gobject-multi-properties">
722         <title>Accessing multiple properties at once</title>
723
724
725     <para>
726       It is interesting to note that the <function><link linkend="g-object-set">g_object_set</link></function> and 
727       <function><link linkend="g-object-set-valist">g_object_set_valist</link></function> (vararg version) functions can be used to set
728       multiple properties at once. The client code shown above can then be re-written as:
729 <programlisting>
730 MamanBar *foo;
731 foo = /* */;
732 g_object_set (G_OBJECT (foo),
733               "papa-number", 2, 
734               "maman-name", "test", 
735               NULL);
736 </programlisting>
737       This saves us from managing the GValues that we were needing to handle when using
738       <function><link linkend="g-object-set-property">g_object_set_property</link></function>.
739       The code above will trigger one notify signal emission for each property modified.
740     </para>
741
742     <para>
743       Of course, the _get versions are also available: <function><link linkend="g-object-get">g_object_get</link></function>
744       and <function><link linkend="g-object-get-valist">g_object_get_valist</link></function> (vararg version) can be used to get numerous
745       properties at once.
746     </para>
747     
748     <para>
749       These high level functions have one drawback - they don't provide a return result.
750       One should pay attention to the argument types and ranges when using them.
751       A know source of errors is to e.g. pass a gfloat instead of a gdouble and thus
752       shifting all subsequent parameters by four bytes. Also forgetting the terminating
753       NULL will lead to unexpected behaviour.
754     </para>
755
756     <para>
757       Really attentive readers now understand how <function><link linkend="g-object-new">g_object_new</link></function>,
758       <function><link linkend="g-object-newv">g_object_newv</link></function> and <function><link linkend="g-object-new-valist">g_object_new_valist</link></function> 
759       work: they parse the user-provided variable number of parameters and invoke
760       <function><link linkend="g-object-set">g_object_set</link></function> on the parameters only after the object has been successfully constructed.
761       Of course, the "notify" signal will be emitted for each property set.
762     </para>
763
764     </sect2>
765
766 <!-- @todo tell here about how to pass use handle properties in derived classe -->
767
768
769   </sect1>
770
771   </chapter>
772
773
774
775