1 <?xml version='1.0' encoding="UTF-8"?>
2 <!DOCTYPE part PUBLIC "-//OASIS//DTD DocBook XML V4.5//EN"
3 "http://www.oasis-open.org/docbook/xml/4.5/docbookx.dtd" [
6 <title>Tutorial</title>
9 This chapter tries to answer the real-life questions of users and presents
10 the most common use cases in order from most likely to least
15 <chapter id="howto-gobject">
16 <title>How to define and implement a new GObject</title>
19 This chapter focuses on the implementation of a subtype of GObject, for
20 example to create a custom class hierarchy, or to subclass a GTK+ widget.
24 Throughout the chapter, a running example of a file viewer program is used,
25 which has a <type>ViewerFile</type> class to represent a single file being
26 viewed, and various derived classes for different types of files with
27 special functionality, such as audio files. The example application also
28 supports editing files (for example, to tweak a photo being viewed), using
29 a <type>ViewerEditable</type> interface.
32 <sect1 id="howto-gobject-header">
33 <title>Boilerplate header code</title>
36 The first step before writing the code for your GObject is to write the
37 type's header which contains the needed type, function and macro
38 definitions. Each of these elements is nothing but a convention which
39 is followed by almost all users of GObject, and has been refined over
40 multiple years of experience developing GObject-based code. If you are
41 writing a library, it is particularly important for you to adhere closely
42 to these conventions; users of your library will assume that you have.
43 Even if not writing a library, it will help other people who want to work
48 Pick a name convention for your headers and source code and stick to it:
50 <listitem><para>use a dash to separate the prefix from the typename:
51 <filename>viewer-file.h</filename> and <filename>viewer-file.c</filename>
52 (this is the convention used by Nautilus and most GNOME libraries).</para></listitem>
53 <listitem><para>use an underscore to separate the prefix from the
54 typename: <filename>viewer_file.h</filename> and
55 <filename>viewer_file.c</filename>.</para></listitem>
56 <listitem><para>Do not separate the prefix from the typename:
57 <filename>viewerfile.h</filename> and <filename>viewerfile.c</filename>.
58 (this is the convention used by GTK+)</para></listitem>
60 Some people like the first two solutions better: it makes reading file
61 names easier for those with poor eyesight.
65 The basic conventions for any header which exposes a GType are described
66 in <xref linkend="gtype-conventions"/>.
70 If you want to declare a type named ‘file’ in namespace ‘viewer’, name the
71 type instance <function>ViewerFile</function> and its class
72 <function>ViewerFileClass</function> (names are case sensitive). The
73 recommended method of declaring a type differs based on whether the type
74 is final or derivable.
78 Final types cannot be subclassed further, and should be the default choice
79 for new types — changing a final type to be derivable is always a change
80 that will be compatible with existing uses of the code, but the converse
81 will often cause problems. Final types are declared using
82 <link linkend="G-DECLARE-FINAL-TYPE:CAPS"><function>G_DECLARE_FINAL_TYPE</function></link>,
83 and require a structure to hold the instance data to be declared in the
84 source code (not the header file).
86 <informalexample><programlisting>
88 * Copyright/Licensing information.
92 #ifndef __VIEWER_FILE_H__
93 #define __VIEWER_FILE_H__
95 #include <glib-object.h>
97 * Potentially, include other headers on which this header depends.
105 #define VIEWER_TYPE_FILE viewer_file_get_type ()
106 G_DECLARE_FINAL_TYPE (ViewerFile, viewer_file, VIEWER, FILE, GObject)
109 * Method definitions.
111 ViewerFile *viewer_file_new (void);
115 #endif /* __VIEWER_FILE_H__ */
116 </programlisting></informalexample>
120 Derivable types <emphasis>can</emphasis> be subclassed further, and their class and
121 instance structures form part of the public API which must not be changed
122 if API stability is cared about. They are declared using
123 <link linkend="G-DECLARE-DERIVABLE-TYPE:CAPS"><function>G_DECLARE_DERIVABLE_TYPE</function></link>:
124 <informalexample><programlisting>
126 * Copyright/Licensing information.
129 /* inclusion guard */
130 #ifndef __VIEWER_FILE_H__
131 #define __VIEWER_FILE_H__
133 #include <glib-object.h>
135 * Potentially, include other headers on which this header depends.
143 #define VIEWER_TYPE_FILE viewer_file_get_type ()
144 G_DECLARE_DERIVABLE_TYPE (ViewerFile, viewer_file, VIEWER, FILE, GObject)
146 struct _ViewerFileClass
148 GObjectClass parent_class;
150 /* Class virtual function fields. */
151 void (* open) (ViewerFile *file,
154 /* Padding to allow adding up to 12 new virtual functions without
156 gpointer padding[12];
160 * Method definitions.
162 ViewerFile *viewer_file_new (void);
166 #endif /* __VIEWER_FILE_H__ */
167 </programlisting></informalexample>
171 The convention for header includes is to add the minimum number of
172 <function>#include</function> directives to the top of your headers needed
173 to compile that header. This
174 allows client code to simply <function>#include "viewer-file.h"</function>,
175 without needing to know the prerequisites for
176 <filename>viewer-file.h</filename>.
180 <sect1 id="howto-gobject-code">
181 <title>Boilerplate code</title>
184 In your code, the first step is to <function>#include</function> the
186 <informalexample><programlisting>
188 * Copyright information
191 #include "viewer-file.h"
193 /* Private structure definition. */
200 * forward definitions
202 </programlisting></informalexample>
206 If the class is being declared as final using
207 <function>G_DECLARE_FINAL_TYPE</function>, its instance structure should
208 be defined in the C file:
209 <informalexample><programlisting>
212 GObject parent_instance;
214 /* Other members, including private data. */
216 </programlisting></informalexample>
220 Call the <function>G_DEFINE_TYPE</function> macro (or
221 <function>G_DEFINE_TYPE_WITH_PRIVATE</function> if your class needs
222 private data — final types do <emphasis>not</emphasis> need private data)
224 of the type, the prefix of the functions and the parent GType to
225 reduce the amount of boilerplate needed. This macro will:
228 <listitem><simpara>implement the <function>viewer_file_get_type</function>
229 function</simpara></listitem>
230 <listitem><simpara>define a parent class pointer accessible from
231 the whole .c file</simpara></listitem>
232 <listitem><simpara>add private instance data to the type (if using
233 <function>G_DEFINE_TYPE_WITH_PRIVATE</function>)</simpara></listitem>
238 If the class has been declared as final using
239 <function>G_DECLARE_FINAL_TYPE</function> (see
240 <xref linkend="howto-gobject-header"/>), private data should be placed in
241 the instance structure, <type>ViewerFile</type>, and
242 <function>G_DEFINE_TYPE</function> should be used instead of
243 <function>G_DEFINE_TYPE_WITH_PRIVATE</function>. The instance structure
244 for a final class is not exposed publicly, and is not embedded in the
245 instance structures of any derived classes (because the class is final);
246 so its size can vary without causing incompatibilities for code which uses
247 the class. Conversely, private data for derivable classes
248 <emphasis>must</emphasis> be included in a private structure, and
249 <function>G_DEFINE_TYPE_WITH_PRIVATE</function> must be used.
251 <informalexample><programlisting>
252 G_DEFINE_TYPE (ViewerFile, viewer_file, G_TYPE_OBJECT)
253 </programlisting></informalexample>
255 <informalexample><programlisting>
256 G_DEFINE_TYPE_WITH_PRIVATE (ViewerFile, viewer_file, G_TYPE_OBJECT)
257 </programlisting></informalexample>
261 It is also possible to use the
262 <function>G_DEFINE_TYPE_WITH_CODE</function> macro to control the
263 <function>get_type</function> function implementation — for instance, to
264 add a call to the <function>G_IMPLEMENT_INTERFACE</function> macro to
265 implement an interface.
269 <sect1 id="howto-gobject-construction">
270 <title>Object construction</title>
273 People often get confused when trying to construct their GObjects because of the
274 sheer number of different ways to hook into the objects's construction process: it is
275 difficult to figure which is the <emphasis>correct</emphasis>, recommended way.
279 <xref linkend="gobject-construction-table"/> shows what user-provided functions
280 are invoked during object instantiation and in which order they are invoked.
281 A user looking for the equivalent of the simple C++ constructor function should use
282 the <function>instance_init</function> method. It will be invoked after
283 all the parents’ <function>instance_init</function>
284 functions have been invoked. It cannot take arbitrary construction parameters
285 (as in C++) but if your object needs arbitrary parameters to complete initialization,
286 you can use construction properties.
290 Construction properties will be set only after all
291 <function>instance_init</function> functions have run.
292 No object reference will be returned to the client of <function><link linkend="g-object-new">g_object_new</link></function>
293 until all the construction properties have been set.
297 It is important to note that object construction cannot <emphasis>ever</emphasis>
298 fail. If you require a fallible GObject construction, you can use the
299 <link linkend="GInitable"><type>GInitable</type></link> and
300 <link linkend="GAsyncInitable"><type>GAsyncInitable</type></link>
301 interfaces provided by the GIO library.
305 You should write the following code first:
306 <informalexample><programlisting>
307 G_DEFINE_TYPE_WITH_PRIVATE (ViewerFile, viewer_file, G_TYPE_OBJECT)
310 viewer_file_class_init (ViewerFileClass *klass)
315 viewer_file_init (ViewerFile *self)
317 ViewerFilePrivate *priv = viewer_file_get_instance_private (self);
319 /* initialize all public and private members to reasonable default values.
320 * They are all automatically initialized to 0 to begin with. */
322 </programlisting></informalexample>
326 If you need special construction properties (with
327 <link linkend="G-PARAM-CONSTRUCT-ONLY:CAPS"><function>G_PARAM_CONSTRUCT_ONLY</function></link>
328 set), install the properties in
329 the <function>class_init()</function> function, override the <function>set_property()</function>
330 and <function>get_property()</function> methods of the GObject class,
331 and implement them as described by <xref linkend="gobject-properties"/>.
335 Property IDs must start from 1, as 0 is reserved for internal use by
337 <informalexample><programlisting>
345 static GParamSpec *obj_properties[N_PROPERTIES] = { NULL, };
348 viewer_file_class_init (ViewerFileClass *klass)
350 GObjectClass *object_class = G_OBJECT_CLASS (klass);
352 object_class->set_property = viewer_file_set_property;
353 object_class->get_property = viewer_file_get_property;
355 obj_properties[PROP_FILENAME] =
356 g_param_spec_string ("filename",
358 "Name of the file to load and display from.",
359 NULL /* default value */,
360 G_PARAM_CONSTRUCT_ONLY | G_PARAM_READWRITE);
362 obj_properties[PROP_ZOOM_LEVEL] =
363 g_param_spec_uint ("zoom-level",
365 "Zoom level to view the file at.",
366 0 /* minimum value */,
367 10 /* maximum value */,
368 2 /* default value */,
371 g_object_class_install_properties (object_class,
375 </programlisting></informalexample>
376 If you need this, make sure you can build and run code similar to the
377 code shown above. Also, make sure your construct properties can be set
378 without side effects during construction.
382 Some people sometimes need to complete the initialization of a instance
383 of a type only after the properties passed to the constructors have been
384 set. This is possible through the use of the <function>constructor()</function>
385 class method as described in <xref linkend="gobject-instantiation"/> or,
386 more simply, using the <function>constructed()</function> class method.
387 Note that the <function>constructed()</function>
388 virtual function will only be invoked after the properties marked as
389 <function>G_PARAM_CONSTRUCT_ONLY</function> or
390 <function>G_PARAM_CONSTRUCT</function> have been consumed, but
391 before the regular properties passed to <function>g_object_new()</function>
396 <sect1 id="howto-gobject-destruction">
397 <title>Object destruction</title>
400 Again, it is often difficult to figure out which mechanism to use to
401 hook into the object's destruction process: when the last
402 <function><link linkend="g-object-unref">g_object_unref</link></function>
403 function call is made, a lot of things happen as described in
404 <xref linkend="gobject-destruction-table"/>.
408 The destruction process of your object is in two phases: dispose and
409 finalize. This split is necessary to handle
410 potential cycles due to the nature of the reference counting mechanism
411 used by GObject, as well as dealing with temporary revival of
412 instances in case of signal emission during the destruction sequence.
413 See <xref linkend="gobject-memory-cycles"/> for more information.
414 <informalexample><programlisting>
415 struct _ViewerFilePrivate
420 GInputStream *input_stream;
423 G_DEFINE_TYPE_WITH_PRIVATE (ViewerFile, viewer_file, G_TYPE_OBJECT)
426 viewer_file_dispose (GObject *gobject)
428 ViewerFilePrivate *priv = viewer_file_get_instance_private (VIEWER_FILE (gobject));
430 /* In dispose(), you are supposed to free all types referenced from this
431 * object which might themselves hold a reference to self. Generally,
432 * the most simple solution is to unref all members on which you own a
436 /* dispose() might be called multiple times, so we must guard against
437 * calling g_object_unref() on an invalid GObject by setting the member
438 * NULL; g_clear_object() does this for us.
440 g_clear_object (&priv->input_stream);
442 /* Always chain up to the parent class; there is no need to check if
443 * the parent class implements the dispose() virtual function: it is
444 * always guaranteed to do so
446 G_OBJECT_CLASS (viewer_file_parent_class)->dispose (gobject);
450 viewer_file_finalize (GObject *gobject)
452 ViewerFilePrivate *priv = viewer_file_get_instance_private (VIEWER_FILE (gobject));
454 g_free (priv->filename);
456 /* Always chain up to the parent class; as with dispose(), finalize()
457 * is guaranteed to exist on the parent's class virtual function table
459 G_OBJECT_CLASS (viewer_file_parent_class)->finalize (gobject);
463 viewer_file_class_init (ViewerFileClass *klass)
465 GObjectClass *object_class = G_OBJECT_CLASS (klass);
467 object_class->dispose = viewer_file_dispose;
468 object_class->finalize = viewer_file_finalize;
472 viewer_file_init (ViewerFile *self);
474 ViewerFilePrivate *priv = viewer_file_get_instance_private (self);
476 priv->input_stream = g_object_new (VIEWER_TYPE_INPUT_STREAM, NULL);
477 priv->filename = /* would be set as a property */;
479 </programlisting></informalexample>
483 It is possible that object methods might be invoked after dispose is
484 run and before finalize runs. GObject does not consider this to be a
485 program error: you must gracefully detect this and neither crash nor
486 warn the user, by having a disposed instance revert to an inert state.
490 <sect1 id="howto-gobject-methods">
491 <title>Object methods</title>
494 Just as with C++, there are many different ways to define object
495 methods and extend them: the following list and sections draw on
496 C++ vocabulary. (Readers are expected to know basic C++ concepts.
497 Those who have not had to write C++ code recently can refer to e.g.
498 <ulink url="http://www.cplusplus.com/doc/tutorial/"/> to refresh
502 non-virtual public methods,
505 virtual public methods and
508 virtual private methods
513 <sect2 id="non-virtual-public-methods">
514 <title>Non-virtual public methods</title>
517 These are the simplest, providing a simple method which
518 acts on the object. Provide a function
519 prototype in the header and an implementation of that prototype
521 <informalexample><programlisting>
522 /* declaration in the header. */
523 void viewer_file_open (ViewerFile *self,
526 /* implementation in the source file */
528 viewer_file_open (ViewerFile *self,
531 g_return_if_fail (VIEWER_IS_FILE (self));
532 g_return_if_fail (error == NULL || *error == NULL);
536 </programlisting></informalexample>
540 <sect2 id="virtual-public-methods">
541 <title>Virtual public methods</title>
544 This is the preferred way to create GObjects with overridable methods:
547 Define the common method and its virtual function in the
548 class structure in the public header
551 Define the common method in the header file and implement it in the
555 Implement a base version of the virtual function in the source
556 file and initialize the virtual function pointer to this
557 implementation in the object’s <function>class_init</function>
558 function; or leave it as <constant>NULL</constant> for a ‘pure
559 virtual’ method which must be overridden by derived classes
562 Re-implement the virtual function in each derived class which needs
568 Note that virtual functions can only be defined if the class is
569 derivable, declared using
570 <link linkend="G-DECLARE-DERIVABLE-TYPE:CAPS"><function>G_DECLARE_DERIVABLE_TYPE</function></link>
571 so the class structure can be defined.
572 <informalexample><programlisting>
573 /* declaration in viewer-file.h. */
574 #define VIEWER_TYPE_FILE viewer_file_get_type ()
575 G_DECLARE_DERIVABLE_TYPE (ViewerFile, viewer_file, VIEWER, FILE, GObject)
577 struct _ViewerFileClass
579 GObjectClass parent_class;
582 void (*open) (ViewerFile *self,
585 /* Padding to allow adding up to 12 new virtual functions without
587 gpointer padding[12];
590 void viewer_file_open (ViewerFile *self,
593 /* implementation in viewer-file.c */
595 viewer_file_open (ViewerFile *self,
598 ViewerFileClass *klass;
600 g_return_if_fail (VIEWER_IS_FILE (self));
601 g_return_if_fail (error == NULL || *error == NULL);
603 klass = VIEWER_FILE_GET_CLASS (self);
604 g_return_if_fail (klass->open != NULL);
606 klass->open (self, error);
608 </programlisting></informalexample>
609 The code above simply redirects the <function>open</function> call
610 to the relevant virtual function.
614 It is possible to provide a default
615 implementation for this class method in the object's
616 <function>class_init</function> function: initialize the
617 <function>klass->open</function> field to a pointer to the
618 actual implementation.
619 By default, class methods that are not inherited are initialized to
620 <function>NULL</function>, and thus are to be considered "pure virtual".
621 <informalexample><programlisting>
623 viewer_file_real_close (ViewerFile *self,
626 /* Default implementation for the virtual method. */
630 viewer_file_class_init (ViewerFileClass *klass)
632 /* this is not necessary, except for demonstration purposes.
634 * pure virtual method: mandates implementation in children.
638 /* merely virtual method. */
639 klass->close = viewer_file_real_close;
643 viewer_file_open (ViewerFile *self,
646 ViewerFileClass *klass;
648 g_return_if_fail (VIEWER_IS_FILE (self));
649 g_return_if_fail (error == NULL || *error == NULL);
651 klass = VIEWER_FILE_GET_CLASS (self);
653 /* if the method is purely virtual, then it is a good idea to
654 * check that it has been overridden before calling it, and,
655 * depending on the intent of the class, either ignore it silently
658 g_return_if_fail (klass->open != NULL);
659 klass->open (self, error);
663 viewer_file_close (ViewerFile *self,
666 ViewerFileClass *klass;
668 g_return_if_fail (VIEWER_IS_FILE (self));
669 g_return_if_fail (error == NULL || *error == NULL);
671 klass = VIEWER_FILE_GET_CLASS (self);
672 if (klass->close != NULL)
673 klass->close (self, error);
675 </programlisting></informalexample>
679 <sect2 id="virtual-private-methods">
680 <title>Virtual private Methods</title>
683 These are very similar to <link linkend="virtual-public-methods">virtual
684 public methods</link>. They just don't
685 have a public function to call directly. The header
686 file contains only a declaration of the virtual function:
687 <informalexample><programlisting>
688 /* declaration in viewer-file.h. */
689 struct _ViewerFileClass
693 /* Public virtual method as before. */
694 void (*open) (ViewerFile *self,
697 /* Private helper function to work out whether the file can be loaded via
698 * memory mapped I/O, or whether it has to be read as a stream. */
699 gboolean (*can_memory_map) (ViewerFile *self);
701 /* Padding to allow adding up to 12 new virtual functions without
703 gpointer padding[12];
706 void viewer_file_open (ViewerFile *self, GError **error);
707 </programlisting></informalexample>
708 These virtual functions are often used to delegate part of the job
710 <informalexample><programlisting>
711 /* this accessor function is static: it is not exported outside of this file. */
713 viewer_file_can_memory_map (ViewerFile *self)
715 return VIEWER_FILE_GET_CLASS (self)->can_memory_map (self);
719 viewer_file_open (ViewerFile *self,
722 g_return_if_fail (VIEWER_IS_FILE (self));
723 g_return_if_fail (error == NULL || *error == NULL);
726 * Try to load the file using memory mapped I/O, if the implementation of the
727 * class determines that is possible using its private virtual method.
729 if (viewer_file_can_memory_map (self))
731 /* Load the file using memory mapped I/O. */
735 /* Fall back to trying to load the file using streaming I/O… */
738 </programlisting></informalexample>
742 Again, it is possible to provide a default implementation for this
743 private virtual function:
744 <informalexample><programlisting>
746 viewer_file_real_can_memory_map (ViewerFile *self)
748 /* As an example, always return false. Or, potentially return true if the
754 viewer_file_class_init (ViewerFileClass *klass)
756 /* non-pure virtual method; does not have to be implemented in children. */
757 klass->can_memory_map = viewer_file_real_can_memory_map;
759 </programlisting></informalexample>
763 Derived classes can then override the method with code such as:
764 <informalexample><programlisting>
766 viewer_audio_file_class_init (ViewerAudioFileClass *klass)
768 ViewerFileClass *file_class = VIEWER_FILE_CLASS (klass);
770 /* implement pure virtual function. */
771 file_class->can_memory_map = viewer_audio_file_can_memory_map;
773 </programlisting></informalexample>
778 <sect1 id="howto-gobject-chainup">
779 <title>Chaining up</title>
781 <para>Chaining up is often loosely defined by the following set of
784 <listitem><para>Parent class A defines a public virtual method named <function>foo</function> and
785 provides a default implementation.</para></listitem>
786 <listitem><para>Child class B re-implements method <function>foo</function>.</para></listitem>
787 <listitem><para>B’s implementation of <function>foo</function> calls (‘chains up to’) its parent class A’s implementation of <function>foo</function>.</para></listitem>
789 There are various uses of this idiom:
791 <listitem><para>You need to extend the behaviour of a class without modifying its code. You create
792 a subclass to inherit its implementation, re-implement a public virtual method to modify the behaviour
793 and chain up to ensure that the previous behaviour is not really modified, just extended.
795 <listitem><para>You need to implement the
796 <ulink url="http://en.wikipedia.org/wiki/Chain-of-responsibility_pattern">Chain
797 Of Responsibility pattern</ulink>: each object of the inheritance
798 tree chains up to its parent (typically, at the beginning or the end of the method) to ensure that
799 each handler is run in turn.</para></listitem>
804 To explicitly chain up to the implementation of the virtual method in the parent class,
805 you first need a handle to the original parent class structure. This pointer can then be used to
806 access the original virtual function pointer and invoke it directly.
809 The <emphasis>original</emphasis> adjective used in this sentence is not innocuous. To fully
810 understand its meaning, recall how class structures are initialized: for each object type,
811 the class structure associated with this object is created by first copying the class structure of its
812 parent type (a simple <function>memcpy</function>) and then by invoking the <function>class_init</function> callback on
813 the resulting class structure. Since the <function>class_init</function> callback is responsible for overwriting the class structure
814 with the user re-implementations of the class methods, the modified copy of the parent class
815 structure stored in the derived instance cannot be used. A copy of the class structure of an instance of the parent
822 Use the <function>parent_class</function> pointer created and initialized
824 <link linkend="G-DEFINE-TYPE:CAPS"><function>G_DEFINE_TYPE</function></link>
825 family of macros, for instance:
826 <informalexample><programlisting>
828 b_method_to_call (B *obj, gint some_param)
830 /* do stuff before chain up */
832 /* call the method_to_call() virtual function on the
833 * parent of BClass, AClass.
835 * remember the explicit cast to AClass*
837 A_CLASS (b_parent_class)->method_to_call (obj, some_param);
839 /* do stuff after chain up */
841 </programlisting></informalexample>
847 <!-- End Howto GObject -->
849 <chapter id="howto-interface">
850 <title>How to define and implement interfaces</title>
852 <sect1 id="howto-interface-define">
853 <title>Defining interfaces</title>
856 The theory behind how GObject interfaces work is given in
857 <xref linkend="gtype-non-instantiable-classed"/>; this section covers how to
858 define and implement an interface.
862 The first step is to get the header right. This interface
863 defines three methods:
864 <informalexample><programlisting>
866 * Copyright/Licensing information.
869 #ifndef __VIEWER_EDITABLE_H__
870 #define __VIEWER_EDITABLE_H__
872 #include <glib-object.h>
876 #define VIEWER_TYPE_EDITABLE viewer_editable_get_type ()
877 G_DECLARE_INTERFACE (ViewerEditable, viewer_editable, VIEWER, EDITABLE, GObject)
879 struct _ViewerEditableInterface
881 GTypeInterface parent_iface;
883 void (*save) (ViewerEditable *self,
885 void (*undo) (ViewerEditable *self,
887 void (*redo) (ViewerEditable *self,
891 void viewer_editable_save (ViewerEditable *self,
893 void viewer_editable_undo (ViewerEditable *self,
895 void viewer_editable_redo (ViewerEditable *self,
900 #endif /* __VIEWER_EDITABLE_H__ */
901 </programlisting></informalexample>
902 This code is the same as the code for a normal <link linkend="GType"><type>GType</type></link>
903 which derives from a <link linkend="GObject"><type>GObject</type></link> except for a few details:
906 The <function>_GET_CLASS</function> function is called
907 <function>_GET_IFACE</function> (and is defined by
908 <link linkend="G-DECLARE-INTERFACE:CAPS"><function>G_DECLARE_INTERFACE</function></link>).
911 The instance type, <type>ViewerEditable</type>, is not fully defined: it is
912 used merely as an abstract type which represents an instance of
913 whatever object which implements the interface.
916 The parent of the <type>ViewerEditableInterface</type> is
917 <type>GTypeInterface</type>, not <type>GObjectClass</type>.
923 The implementation of the <type>ViewerEditable</type> type itself is trivial:
925 <listitem><para><function><link linkend="G-DEFINE-INTERFACE:CAPS">G_DEFINE_INTERFACE</link></function>
926 creates a <function>viewer_editable_get_type</function> function which registers the
927 type in the type system. The third argument is used to define a
928 <link linkend="howto-interface-prerequisite">prerequisite interface</link>
929 (which we'll talk about more later). Just pass <code>0</code> for this
930 argument when an interface has no prerequisite.
932 <listitem><para><function>viewer_editable_default_init</function> is expected
933 to register the interface's signals if there are any (we will see a bit
934 later how to use them).</para></listitem>
935 <listitem><para>The interface methods <function>viewer_editable_save</function>,
936 <function>viewer_editable_undo</function> and <function>viewer_editable_redo</function> dereference the interface
937 structure to access its associated interface function and call it.
940 <informalexample><programlisting>
941 G_DEFINE_INTERFACE (ViewerEditable, viewer_editable, G_TYPE_OBJECT)
944 viewer_editable_default_init (ViewerEditableInterface *iface)
946 /* add properties and signals to the interface here */
950 viewer_editable_save (ViewerEditable *self,
953 ViewerEditableInterface *iface;
955 g_return_if_fail (VIEWER_IS_EDITABLE (self));
956 g_return_if_fail (error == NULL || *error == NULL);
958 iface = VIEWER_EDITABLE_GET_IFACE (self);
959 g_return_if_fail (iface->save != NULL);
960 iface->save (self, error);
964 viewer_editable_undo (ViewerEditable *self,
967 ViewerEditableInterface *iface;
969 g_return_if_fail (VIEWER_IS_EDITABLE (self));
971 iface = VIEWER_EDITABLE_GET_IFACE (self);
972 g_return_if_fail (iface->undo != NULL);
973 iface->undo (self, n_steps);
977 viewer_editable_redo (ViewerEditable *self,
980 ViewerEditableInterface *iface;
982 g_return_if_fail (VIEWER_IS_EDITABLE (self));
984 iface = VIEWER_EDITABLE_GET_IFACE (self);
985 g_return_if_fail (iface->redo != NULL);
986 iface->redo (self, n_steps);
988 </programlisting></informalexample>
992 <sect1 id="howto-interface-implement">
993 <title>Implementing interfaces</title>
996 Once the interface is defined, implementing it is rather trivial.
1000 The first step is to define a normal final GObject class exactly as in
1001 <xref linkend="howto-gobject-header"/>.
1005 The second step is to implement <type>ViewerFile</type> by defining
1007 <function><link linkend="G-DEFINE-TYPE-WITH-CODE:CAPS">G_DEFINE_TYPE_WITH_CODE</link></function>
1009 <function><link linkend="G-IMPLEMENT-INTERFACE:CAPS">G_IMPLEMENT_INTERFACE</link></function>
1011 <function><link linkend="G-DEFINE-TYPE:CAPS">G_DEFINE_TYPE</link></function>:
1012 <informalexample><programlisting>
1013 static void viewer_file_editable_interface_init (ViewerEditableInterface *iface);
1015 G_DEFINE_TYPE_WITH_CODE (ViewerFile, viewer_file, G_TYPE_OBJECT,
1016 G_IMPLEMENT_INTERFACE (VIEWER_TYPE_EDITABLE,
1017 viewer_file_editable_interface_init))
1018 </programlisting></informalexample>
1019 This definition is very much like all the similar functions seen
1020 previously. The only interface-specific code present here is the use of
1021 <function><link linkend="G-IMPLEMENT-INTERFACE:CAPS">G_IMPLEMENT_INTERFACE</link></function>.
1024 <note><para>Classes can implement multiple interfaces by using multiple calls to
1025 <function><link linkend="G-IMPLEMENT-INTERFACE:CAPS">G_IMPLEMENT_INTERFACE</link></function>
1027 <function><link linkend="G-DEFINE-TYPE-WITH-CODE:CAPS">G_DEFINE_TYPE_WITH_CODE</link></function>
1031 <function>viewer_file_editable_interface_init</function>, the interface
1032 initialization function: inside it every virtual method of the interface
1033 must be assigned to its implementation:
1034 <informalexample><programlisting>
1036 viewer_file_editable_save (ViewerFile *self,
1039 g_print ("File implementation of editable interface save method: %s.\n",
1044 viewer_file_editable_undo (ViewerFile *self,
1047 g_print ("File implementation of editable interface undo method: %s.\n",
1052 viewer_file_editable_redo (ViewerFile *self,
1055 g_print ("File implementation of editable interface redo method: %s.\n",
1060 viewer_file_editable_interface_init (ViewerEditableInterface *iface)
1062 iface->save = viewer_file_editable_save;
1063 iface->undo = viewer_file_editable_undo;
1064 iface->redo = viewer_file_editable_redo;
1068 viewer_file_init (ViewerFile *self)
1070 /* Instance variable initialisation code. */
1072 </programlisting></informalexample>
1075 If the object is not of final type, e.g. was declared using
1076 <function><link linkend="G-DECLARE-DERIVABLE-TYPE:CAPS">G_DECLARE_DERIVABLE_TYPE</link></function>
1078 <function><link linkend="G-ADD-PRIVATE:CAPS">G_ADD_PRIVATE</link></function>
1079 macro should be added. The private structure should be declared exactly
1080 as for a normal derivable object, see <xref linkend="howto-gobject-code"/>.
1081 <informalexample><programlisting>
1082 G_DEFINE_TYPE_WITH_CODE (ViewerFile, viewer_file, G_TYPE_OBJECT,
1083 G_ADD_PRIVATE (ViewerFile)
1084 G_IMPLEMENT_INTERFACE (VIEWER_TYPE_EDITABLE,
1085 viewer_file_editable_interface_init))
1086 </programlisting></informalexample>
1090 <sect1 id="howto-interface-prerequisite">
1091 <title>Interface definition prerequisites</title>
1094 To specify that an interface requires the presence of other interfaces
1095 when implemented, GObject introduces the concept of
1096 <emphasis>prerequisites</emphasis>: it is possible to associate
1097 a list of prerequisite types to an interface. For example, if
1098 object A wishes to implement interface I1, and if interface I1 has a
1099 prerequisite on interface I2, A has to implement both I1 and I2.
1103 The mechanism described above is, in practice, very similar to
1104 Java's interface I1 extends interface I2. The example below shows
1105 the GObject equivalent:
1106 <informalexample><programlisting>
1107 /* Make the ViewerEditableLossy interface require ViewerEditable interface. */
1108 G_DEFINE_INTERFACE (ViewerEditableLossy, viewer_editable_lossy, VIEWER_TYPE_EDITABLE)
1109 </programlisting></informalexample>
1110 In the <function><link linkend="G-DEFINE-INTERFACE:CAPS">G_DEFINE_INTERFACE</link></function>
1111 call above, the third parameter defines the prerequisite type. This
1112 is the GType of either an interface or a class. In this case
1113 the <type>ViewerEditable</type> interface is a prerequisite of
1114 <type>ViewerEditableLossy</type>. The code
1115 below shows how an implementation can implement both interfaces and
1116 register their implementations:
1117 <informalexample><programlisting>
1119 viewer_file_editable_lossy_compress (ViewerEditableLossy *editable)
1121 ViewerFile *self = VIEWER_FILE (editable);
1123 g_print ("File implementation of lossy editable interface compress method: %s.\n",
1128 viewer_file_editable_lossy_interface_init (ViewerEditableLossyInterface *iface)
1130 iface->compress = viewer_file_editable_lossy_compress;
1134 viewer_file_editable_save (ViewerEditable *editable,
1137 ViewerFile *self = VIEWER_FILE (editable);
1139 g_print ("File implementation of editable interface save method: %s.\n",
1144 viewer_file_editable_undo (ViewerEditable *editable,
1147 ViewerFile *self = VIEWER_FILE (editable);
1149 g_print ("File implementation of editable interface undo method: %s.\n",
1154 viewer_file_editable_redo (ViewerEditable *editable,
1157 ViewerFile *self = VIEWER_FILE (editable);
1159 g_print ("File implementation of editable interface redo method: %s.\n",
1164 viewer_file_editable_interface_init (ViewerEditableInterface *iface)
1166 iface->save = viewer_file_editable_save;
1167 iface->undo = viewer_file_editable_undo;
1168 iface->redo = viewer_file_editable_redo;
1172 viewer_file_class_init (ViewerFileClass *klass)
1178 viewer_file_init (ViewerFile *self)
1180 /* Instance variable initialisation code. */
1183 G_DEFINE_TYPE_WITH_CODE (ViewerFile, viewer_file, G_TYPE_OBJECT,
1184 G_IMPLEMENT_INTERFACE (VIEWER_TYPE_EDITABLE,
1185 viewer_file_editable_interface_init)
1186 G_IMPLEMENT_INTERFACE (VIEWER_TYPE_EDITABLE_LOSSY,
1187 viewer_file_editable_lossy_interface_init))
1188 </programlisting></informalexample>
1189 It is very important to notice that the order in which interface
1190 implementations are added to the main object is not random:
1191 <function><link linkend="g-type-add-interface-static">g_type_add_interface_static</link></function>,
1193 <function><link linkend="G-DEFINE-INTERFACE:CAPS">G_IMPLEMENT_INTERFACE</link></function>,
1194 must be invoked first on the interfaces which have no prerequisites and then on
1199 <sect1 id="howto-interface-properties">
1200 <title>Interface properties</title>
1203 GObject interfaces can also have
1204 properties. Declaration of the interface properties is similar to
1205 declaring the properties of ordinary GObject types as explained in
1206 <xref linkend="gobject-properties"/>, except that
1207 <function><link linkend="g-object-interface-install-property">g_object_interface_install_property</link></function>
1208 is used to declare the properties instead of
1209 <function><link linkend="g-object-class-install-property">g_object_class_install_property</link></function>.
1213 To include a property named 'autosave-frequency' of type <type>gdouble</type> in the
1214 <type>ViewerEditable</type> interface example code above, we only need to
1215 add one call in <function>viewer_editable_default_init</function> as shown
1217 <informalexample><programlisting>
1219 viewer_editable_default_init (ViewerEditableInterface *iface)
1221 g_object_interface_install_property (iface,
1222 g_param_spec_double ("autosave-frequency",
1223 "Autosave frequency",
1224 "Frequency (in per-seconds) to autosave backups of the editable content at. "
1225 "Or zero to disable autosaves.",
1227 G_MAXDOUBLE, /* maximum */
1229 G_PARAM_READWRITE));
1231 </programlisting></informalexample>
1235 One point worth noting is that the declared property wasn't assigned an
1236 integer ID. The reason being that integer IDs of properties are used
1237 only inside the <function>get_property</function> and
1238 <function>set_property</function> virtual methods. Since interfaces
1239 declare but do not <emphasis>implement</emphasis> properties, there is no
1240 need to assign integer IDs to them.
1244 An implementation declares and defines its properties in the usual
1245 way as explained in <xref linkend="gobject-properties"/>, except for one
1246 small change: it can declare the properties of the interface it
1247 implements using <function><link linkend="g-object-class-override-property">g_object_class_override_property</link></function>
1248 instead of <function><link linkend="g-object-class-install-property">g_object_class_install_property</link></function>.
1249 The following code snippet shows the modifications needed in the
1250 <type>ViewerFile</type> declaration and implementation above:
1251 <informalexample><programlisting>
1254 GObject parent_instance;
1256 gdouble autosave_frequency;
1261 PROP_AUTOSAVE_FREQUENCY = 1,
1266 viewer_file_set_property (GObject *object,
1268 const GValue *value,
1271 ViewerFile *file = VIEWER_FILE (object);
1275 case PROP_AUTOSAVE_FREQUENCY:
1276 file->autosave_frequency = g_value_get_double (value);
1280 G_OBJECT_WARN_INVALID_PROPERTY_ID (object, prop_id, pspec);
1286 viewer_file_get_property (GObject *object,
1291 ViewerFile *file = VIEWER_FILE (object);
1295 case PROP_AUTOSAVE_FREQUENCY:
1296 g_value_set_double (value, file->autosave_frequency);
1300 G_OBJECT_WARN_INVALID_PROPERTY_ID (object, prop_id, pspec);
1306 viewer_file_class_init (ViewerFileClass *klass)
1308 GObjectClass *object_class = G_OBJECT_CLASS (klass);
1310 object_class->set_property = viewer_file_set_property;
1311 object_class->get_property = viewer_file_get_property;
1313 g_object_class_override_property (object_class, PROP_AUTOSAVE_FREQUENCY, "autosave-frequency");
1315 </programlisting></informalexample>
1320 <sect1 id="howto-interface-override">
1321 <title>Overriding interface methods</title>
1324 If a base class already implements an interface and a derived
1325 class needs to implement the same interface but needs to override certain
1326 methods, you must reimplement the interface and set only the interface
1327 methods which need overriding.
1331 In this example, <type>ViewerAudioFile</type> is derived from
1332 <type>ViewerFile</type>. Both implement the <type>ViewerEditable</type>
1333 interface. <type>ViewerAudioFile</type> only implements one method of the
1334 <type>ViewerEditable</type> interface and uses the base class implementation of
1336 <informalexample><programlisting>
1338 viewer_audio_file_editable_save (ViewerEditable *editable,
1341 ViewerAudioFile *self = VIEWER_AUDIO_FILE (editable);
1343 g_print ("Audio file implementation of editable interface save method.\n");
1347 viewer_audio_file_editable_interface_init (ViewerEditableInterface *iface)
1349 /* Override the implementation of save(). */
1350 iface->save = viewer_audio_file_editable_save;
1353 * Leave iface->undo and ->redo alone, they are already set to the
1354 * base class implementation.
1358 G_DEFINE_TYPE_WITH_CODE (ViewerAudioFile, viewer_audio_file, VIEWER_TYPE_FILE,
1359 G_IMPLEMENT_INTERFACE (VIEWER_TYPE_EDITABLE,
1360 viewer_audio_file_editable_interface_init))
1363 viewer_audio_file_class_init (ViewerAudioFileClass *klass)
1369 viewer_audio_file_init (ViewerAudioFile *self)
1373 </programlisting></informalexample>
1377 To access the base class interface implementation use
1378 <function><link linkend="g-type-interface-peek-parent">g_type_interface_peek_parent</link></function>
1379 from within an interface's <function>default_init</function> function.
1383 To call the base class implementation of an interface
1384 method from an derived class where than interface method has been
1385 overridden, stash away the pointer returned from
1386 <function><link linkend="g-type-interface-peek-parent">g_type_interface_peek_parent</link></function>
1387 in a global variable.
1391 In this example <type>ViewerAudioFile</type> overrides the
1392 <function>save</function> interface method. In its overridden method
1393 it calls the base class implementation of the same interface method.
1394 <informalexample><programlisting>
1395 static ViewerEditableInterface *viewer_editable_parent_interface = NULL;
1398 viewer_audio_file_editable_save (ViewerEditable *editable,
1401 ViewerAudioFile *self = VIEWER_AUDIO_FILE (editable);
1403 g_print ("Audio file implementation of editable interface save method.\n");
1405 /* Now call the base implementation */
1406 viewer_editable_parent_interface->save (editable, error);
1410 viewer_audio_file_editable_interface_init (ViewerEditableInterface *iface)
1412 viewer_editable_parent_interface = g_type_interface_peek_parent (iface);
1414 iface->save = viewer_audio_file_editable_save;
1417 G_DEFINE_TYPE_WITH_CODE (ViewerAudioFile, viewer_audio_file, VIEWER_TYPE_FILE,
1418 G_IMPLEMENT_INTERFACE (VIEWER_TYPE_EDITABLE,
1419 viewer_audio_file_editable_interface_init))
1422 viewer_audio_file_class_init (ViewerAudioFileClass *klass)
1428 viewer_audio_file_init (ViewerAudioFile *self)
1432 </programlisting></informalexample>
1438 <!-- End Howto Interfaces -->
1440 <chapter id="howto-signals">
1441 <title>How to create and use signals</title>
1444 The signal system in GType is pretty complex and
1445 flexible: it is possible for its users to connect at runtime any
1446 number of callbacks (implemented in any language for which a binding
1449 <para>A Python callback can be connected to any signal on any
1450 C-based GObject, and vice versa, assuming that the Python object
1451 inherits from GObject.</para>
1453 to any signal and to stop the emission of any signal at any
1454 state of the signal emission process. This flexibility makes it
1455 possible to use GSignal for much more than just emitting signals to
1459 <sect1 id="howto-simple-signals">
1460 <title>Simple use of signals</title>
1463 The most basic use of signals is to implement event
1464 notification. For example, given a <type>ViewerFile</type> object with
1465 a <function>write</function> method, a signal could be emitted whenever
1466 the file is changed using that method.
1467 The code below shows how the user can connect a callback to the
1469 <informalexample><programlisting>
1470 file = g_object_new (VIEWER_FILE_TYPE, NULL);
1472 g_signal_connect (file, "changed", (GCallback) changed_event, NULL);
1474 viewer_file_write (file, buffer, strlen (buffer));
1475 </programlisting></informalexample>
1479 The <type>ViewerFile</type> signal is registered in the
1480 <function>class_init</function> function:
1481 <informalexample><programlisting>
1482 file_signals[CHANGED] =
1483 g_signal_newv ("changed",
1484 G_TYPE_FROM_CLASS (object_class),
1485 G_SIGNAL_RUN_LAST | G_SIGNAL_NO_RECURSE | G_SIGNAL_NO_HOOKS,
1487 NULL /* accumulator */,
1488 NULL /* accumulator data */,
1489 NULL /* C marshaller */,
1490 G_TYPE_NONE /* return_type */,
1492 NULL /* param_types */);
1493 </programlisting></informalexample>
1494 and the signal is emitted in <function>viewer_file_write</function>:
1495 <informalexample><programlisting>
1497 viewer_file_write (ViewerFile *self,
1498 const guint8 *buffer,
1501 g_return_if_fail (VIEWER_IS_FILE (self));
1502 g_return_if_fail (buffer != NULL || size == 0);
1504 /* First write data. */
1506 /* Then, notify user of data written. */
1507 g_signal_emit (self, file_signals[CHANGED], 0 /* details */);
1509 </programlisting></informalexample>
1510 As shown above, the details parameter can safely be set to zero if no
1511 detail needs to be conveyed. For a discussion of what it can be used for,
1512 see <xref linkend="signal-detail"/>
1516 The C signal marshaller should always be <literal>NULL</literal>, in which
1517 case the best marshaller for the given closure type will be chosen by
1518 GLib. This may be an internal marshaller specific to the closure type, or
1519 <function>g_cclosure_marshal_generic</function>, which implements generic
1520 conversion of arrays of parameters to C callback invocations. GLib used to
1521 require the user to write or generate a type-specific marshaller and pass
1522 that, but that has been deprecated in favour of automatic selection of
1527 Note that <function>g_cclosure_marshal_generic</function> is slower than
1528 non-generic marshallers, so should be avoided for performance critical
1529 code. However, performance critical code should rarely be using signals
1530 anyway, as emitting a signal blocks on emitting it to all listeners, which
1531 has potentially unbounded cost.