## How to provide more flexibility to users?

The previous implementation does the job but the signal facility of GObject can be used to provide even more flexibility to this file change notification mechanism. One of the key ideas is to make the process of writing data to the file part of the signal emission process to allow users to be notified either before or after the data is written to the file.

To integrate the process of writing the data to the file into the signal emission mechanism, we can register a default class closure for this signal which will be invoked during the signal emission, just like any other user-connected signal handler.

The first step to implement this idea is to change the signature of the signal: we need to pass around the buffer to write and its size. To do this, we use our own marshaller which will be generated through glib's genmarshall tool. We thus create a file named `marshall.list` which contains the following single line:

    VOID:POINTER,UINT

and use the Makefile provided in `sample/signal/Makefile` to generate the file named `maman-file-complex-marshall.c`. This C file is finally included in `maman-file-complex.c`.

Once the marshaller is present, we register the signal and its marshaller in the class_init function of the object MamanFileComplex (full source for this object is included in `sample/signal/maman-file-complex.{h|c}`):

    GClosure *default_closure;
    GType param_types[2];

    default_closure = g_cclosure_new (G_CALLBACK (default_write_signal_handler),
                                      (gpointer)0xdeadbeaf /* user_data */,
                                      NULL /* destroy_data */);

    param_types[0] = G_TYPE_POINTER;
    param_types[1] = G_TYPE_UINT;
    klass->write_signal_id =
      g_signal_newv ("write",
                     G_TYPE_FROM_CLASS (g_class),
                     G_SIGNAL_RUN_LAST | G_SIGNAL_NO_RECURSE | G_SIGNAL_NO_HOOKS,
                     default_closure /* class closure */,
                     NULL /* accumulator */,
                     NULL /* accu_data */,
                     maman_file_complex_VOID__POINTER_UINT,
                     G_TYPE_NONE /* return_type */,
                     2     /* n_params */,
                     param_types /* param_types */);

The code shown above first creates the closure which contains the code to complete the file write. This closure is registered as the default class_closure of the newly created signal.

Of course, you need to implement completely the code for the default closure since I just provided a skeleton:

    static void
    default_write_signal_handler (GObject *obj, guint8 *buffer, guint size, gpointer user_data)
    {
      g_assert (user_data == (gpointer)0xdeadbeaf);
      /* Here, we trigger the real file write. */
      g_print ("default signal handler: 0x%x %u\n", buffer, size);
    }

Finally, the client code must invoke the `maman_file_complex_write` function which triggers the signal emission:

    void maman_file_complex_write (MamanFileComplex *self, guint8 *buffer, guint size)
    {
      /* trigger event */
      g_signal_emit (self,
                     MAMAN_FILE_COMPLEX_GET_CLASS (self)->write_signal_id,
                     0, /* details */
                     buffer, size);
    }

The client code (as shown in `sample/signal/test.c` and below) can now connect signal handlers before and after the file write is completed: since the default signal handler which does the write itself runs during the RUN_LAST phase of the signal emission, it will run after all handlers connected with `g_signal_connect` and before all handlers connected with `g_signal_connect_after`. If you intent to write a GObject which emits signals, I would thus urge you to create all your signals with the G_SIGNAL_RUN_LAST such that your users have a maximum of flexibility as to when to get the event. Here, we combined it with G_SIGNAL_NO_RECURSE and G_SIGNAL_NO_HOOKS to ensure our users will not try to do really weird things with our GObject. I strongly advise you to do the same unless you really know why (in which case you really know the inner workings of GSignal by heart and you are not reading this).

    static void complex_write_event_before (GObject *file, guint8 *buffer, guint size, gpointer user_data)
    {
      g_assert (user_data == NULL);
      g_print ("Complex Write event before: 0x%x, %u\n", buffer, size);
    }

    static void complex_write_event_after (GObject *file, guint8 *buffer, guint size, gpointer user_data)
    {
      g_assert (user_data == NULL);
      g_print ("Complex Write event after: 0x%x, %u\n", buffer, size);
    }

    static void test_file_complex (void)
    {
      guint8 buffer[100];
      GObject *file;

      file = g_object_new (MAMAN_FILE_COMPLEX_TYPE, NULL);

      g_signal_connect (G_OBJECT (file), "write",
                        (GCallback)complex_write_event_before,
                        NULL);

      g_signal_connect_after (G_OBJECT (file), "write",
                              (GCallback)complex_write_event_after,
                              NULL);

      maman_file_complex_write (MAMAN_FILE_COMPLEX (file), buffer, 50);

      g_object_unref (G_OBJECT (file));
    }

The code above generates the following output on my machine:

    Complex Write event before: 0xbfffe280, 50
    default signal handler: 0xbfffe280 50
    Complex Write event after: 0xbfffe280, 50

### How most people do the same thing with less code

For many historic reasons related to how the ancestor of GObject used to work in GTK+ 1.x versions, there is a much simpler [16] way to create a signal with a default handler than to create a closure by hand and to use the `g_signal_newv`.

For example, `g_signal_new` can be used to create a signal which uses a default handler which is stored in the class structure of the object. More specifically, the class structure contains a function pointer which is accessed during signal emission to invoke the default handler and the user is expected to provide to `g_signal_new` the offset from the start of the class structure to the function pointer. [17]

The following code shows the declaration of the MamanFileSimple class structure which contains the `write` function pointer.

    struct _MamanFileSimpleClass {
      GObjectClass parent;

      guint write_signal_id;

      /* signal default handlers */
      void (*write) (MamanFileSimple *self, guint8 *buffer, guint size);
    };

The `write` function pointer is initialied in the class_init function of the object to `default_write_signal_handler`:

    static void
    maman_file_simple_class_init (gpointer g_class,
                                   gpointer g_class_data)
    {
      GObjectClass *gobject_class = G_OBJECT_CLASS (g_class);
      MamanFileSimpleClass *klass = MAMAN_FILE_SIMPLE_CLASS (g_class);

      klass->write = default_write_signal_handler;

Finally, the signal is created with `g_signal_new` in the same class_init function:

    klass->write_signal_id =
     g_signal_new ("write",
                   G_TYPE_FROM_CLASS (g_class),
                   G_SIGNAL_RUN_LAST | G_SIGNAL_NO_RECURSE | G_SIGNAL_NO_HOOKS,
                   G_STRUCT_OFFSET (MamanFileSimpleClass, write),
                   NULL /* accumulator */,
                   NULL /* accu_data */,
                   maman_file_complex_VOID__POINTER_UINT,
                   G_TYPE_NONE /* return_type */,
                   2     /* n_params */,
                   G_TYPE_POINTER,
                   G_TYPE_UINT);

Of note, here, is the 4th argument to the function: it is an integer calculated by the `G_STRUCT_OFFSET` macro which indicates the offset of the member write from the start of the MamanFileSimpleClass class structure. [18]

While the complete code for this type of default handler looks less clutered as shown in `sample/signal/maman-file-simple.{h|c}`, it contains numerous subtleties. The main subtle point which everyone must be aware of is that the signature of the default handler created that way does not have a user_data argument: `default_write_signal_handler` is different in `sample/signal/maman-file-complex.c` and in `sample/signal/maman-file-simple.c`.

If you have doubts about which method to use, I would advise you to use the second one which involves `g_signal_new` rather than `g_signal_newv`: it is better to write code which looks like the vast majority of other GTK+/Gobject code than to do it your own way. However, now, you know why.

[16] I personally think that this method is horribly mind-twisting: it adds a new indirection which unecessarily complicates the overall code path. However, because this method is widely used by all of GTK+ and GObject code, readers need to understand it. The reason why this is done that way in most of GTK+ is related to the fact that the ancestor of GObject did not provide any other way to create a signal with a default handler than this one. Some people have tried to justify that it is done that way because it is better, faster (I am extremly doubtfull about the faster bit. As a matter of fact, the better bit also mystifies me ;-). I have the feeling no one really knows and everyone does it because they copy/pasted code from code which did the same. It is probably better to leave this specific trivia to hacker legends domain...

[17] I would like to point out here that the reason why the default handler of a signal is named everywhere a class_closure is probably related to the fact that it used to be really a function pointer stored in the class structure.

[18] GSignal uses this offset to create a special wrapper closure which first retrieves the target function pointer before calling it.