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