Tizen 2.1 base
[platform/upstream/glib2.0.git] / docs / reference / gobject / tut_gsignal.xml
1 <?xml version='1.0' encoding="ISO-8859-1"?>
2 <!DOCTYPE chapter PUBLIC "-//OASIS//DTD DocBook XML V4.1.2//EN" 
3                "http://www.oasis-open.org/docbook/xml/4.1.2/docbookx.dtd" [
4 ]>
5 <chapter id="chapter-signal">
6   <title>The GObject messaging system</title>
7
8   <sect1 id="closure">
9     <title>Closures</title>
10
11     <para>
12       Closures are central to the concept of asynchronous signal delivery
13       which is widely used throughout GTK+ and GNOME applications. A closure is an 
14       abstraction, a generic representation of a callback. It is a small structure
15       which contains three objects:
16       <itemizedlist>
17         <listitem><para>a function pointer (the callback itself) whose prototype looks like:
18 <programlisting>
19 return_type function_callback (... , gpointer user_data);
20 </programlisting>
21         </para></listitem>
22         <listitem><para>
23            the user_data pointer which is passed to the callback upon invocation of the closure
24           </para></listitem>
25         <listitem><para>
26            a function pointer which represents the destructor of the closure: whenever the
27            closure's refcount reaches zero, this function will be called before the closure
28            structure is freed.
29           </para></listitem>
30       </itemizedlist>
31     </para>
32
33     <para>
34       The <link linkend="GClosure"><type>GClosure</type></link> structure represents the common functionality of all
35       closure implementations: there exists a different Closure implementation for
36       each separate runtime which wants to use the GObject type system.
37       <footnote><para>
38         In practice, closures sit at the boundary of language runtimes: if you are
39         writing Python code and one of your Python callbacks receives a signal from
40         a GTK+ widget, the C code in GTK+ needs to execute your Python
41         code. The closure invoked by the GTK+ object invokes the Python callback:
42         it behaves as a normal C object for GTK+ and as a normal Python object for
43         Python code.
44       </para></footnote>
45       The GObject library provides a simple <link linkend="GCClosure"><type>GCClosure</type></link> type which
46       is a specific implementation of closures to be used with C/C++ callbacks.
47     </para>
48     <para>
49       A <link linkend="GClosure"><type>GClosure</type></link> provides simple services:
50       <itemizedlist>
51         <listitem><para>
52           Invocation (<function><link linkend="g-closure-invoke">g_closure_invoke</link></function>): this is what closures 
53           were created for: they hide the details of callback invocation from the
54           callback invoker.</para>
55         </listitem>
56         <listitem><para>
57           Notification: the closure notifies listeners of certain events such as
58           closure invocation, closure invalidation and closure finalization. Listeners
59           can be registered with <function><link linkend="g-closure-add-finalize-notifier">g_closure_add_finalize_notifier</link></function>
60           (finalization notification), <function><link linkend="g-closure-add-invalidate-notifier">g_closure_add_invalidate_notifier</link></function> 
61           (invalidation notification) and 
62           <function><link linkend="g-closure-add-marshal-guards">g_closure_add_marshal_guards</link></function> (invocation notification).
63           There exist symmetric deregistration functions for finalization and invalidation
64           events (<function><link linkend="g-closure-remove-finalize-notifier">g_closure_remove_finalize_notifier</link></function> and
65           <function><link linkend="g-closure-remove-invalidate-notifier">g_closure_remove_invalidate_notifier</link></function>) but not for the invocation 
66           process.
67           <footnote><para>
68             Closures are reference counted and notify listeners of their destruction in a two-stage
69             process: the invalidation notifiers are invoked before the finalization notifiers.
70           </para></footnote></para>
71         </listitem>
72       </itemizedlist>
73     </para>
74
75     <sect2>
76       <title>C Closures</title>
77
78       <para>
79         If you are using C or C++
80         to connect a callback to a given event, you will either use simple <link linkend="GCClosure"><type>GCClosure</type></link>s
81         which have a pretty minimal API or the even simpler <function><link linkend="g-signal-connect">g_signal_connect</link></function> 
82         functions (which will be presented a bit later :).
83 <programlisting>
84 GClosure *g_cclosure_new             (GCallback      callback_func,
85                                       gpointer       user_data,
86                                       GClosureNotify destroy_data);
87 GClosure *g_cclosure_new_swap        (GCallback      callback_func,
88                                       gpointer       user_data,
89                                       GClosureNotify destroy_data);
90 GClosure *g_signal_type_cclosure_new (GType          itype,
91                                       guint          struct_offset);
92 </programlisting>
93       </para>
94
95       <para>
96         <function><link linkend="g-cclosure-new">g_cclosure_new</link></function> will create a new closure which can invoke the
97         user-provided callback_func with the user-provided user_data as last parameter. When the closure
98         is finalized (second stage of the destruction process), it will invoke the destroy_data function 
99         if the user has supplied one.
100       </para>
101   
102       <para>
103         <function><link linkend="g-cclosure-new-swap">g_cclosure_new_swap</link></function> will create a new closure which can invoke the
104         user-provided callback_func with the user-provided user_data as first parameter (instead of being the 
105         last parameter as with <function><link linkend="g-cclosure-new">g_cclosure_new</link></function>). When the closure
106         is finalized (second stage of the destruction process), it will invoke the destroy_data 
107         function if the user has supplied one.
108       </para>
109     </sect2>
110
111     <sect2>
112       <title>Non-C closures (for the fearless)</title>
113
114       <para>
115         As was explained above, closures hide the details of callback invocation. In C,
116         callback invocation is just like function invocation: it is a matter of creating
117         the correct stack frame for the called function and executing a <emphasis>call</emphasis>
118         assembly instruction.
119       </para>
120   
121       <para>
122         C closure marshallers transform the array of GValues which represent 
123         the parameters to the target function into a C-style function parameter list, invoke
124         the user-supplied C function with this new parameter list, get the return value of the
125         function, transform it into a GValue and return this GValue to the marshaller caller.
126       </para>
127   
128       <para>
129         The following code implements a simple marshaller in C for a C function which takes an
130         integer as first parameter and returns void.
131 <programlisting>
132 g_cclosure_marshal_VOID__INT (GClosure     *closure,
133                               GValue       *return_value,
134                               guint         n_param_values,
135                               const GValue *param_values,
136                               gpointer      invocation_hint,
137                               gpointer      marshal_data)
138 {
139   typedef void (*GMarshalFunc_VOID__INT) (gpointer     data1,
140                                           gint         arg_1,
141                                           gpointer     data2);
142   register GMarshalFunc_VOID__INT callback;
143   register GCClosure *cc = (GCClosure*) closure;
144   register gpointer data1, data2;
145
146   g_return_if_fail (n_param_values == 2);
147
148   data1 = g_value_peek_pointer (param_values + 0);
149   data2 = closure->data;
150
151   callback = (GMarshalFunc_VOID__INT) (marshal_data ? marshal_data : cc->callback);
152
153   callback (data1,
154             g_marshal_value_peek_int (param_values + 1),
155             data2);
156 }
157 </programlisting>
158       </para>
159   
160       <para>
161         Of course, there exist other kinds of marshallers. For example, James Henstridge 
162         wrote a generic Python marshaller which is used by all Python closures (a Python closure
163         is used to have Python-based callback be invoked by the closure invocation process).
164         This Python marshaller transforms the input GValue list representing the function 
165         parameters into a Python tuple which is the equivalent structure in Python (you can
166         look in <function>pyg_closure_marshal</function> in <filename>pygtype.c</filename>
167         in the <emphasis>pygobject</emphasis> module in the GNOME source code repository).
168       </para>
169
170     </sect2>
171   </sect1>
172
173   <sect1 id="signal">
174     <title>Signals</title>
175
176     <para>
177       GObject's signals have nothing to do with standard UNIX signals: they connect 
178       arbitrary application-specific events with any number of listeners.
179       For example, in GTK+, every user event (keystroke or mouse move) is received
180       from the X server and generates a GTK+ event under the form of a signal emission
181       on a given object instance.
182     </para>
183
184     <para>
185       Each signal is registered in the type system together with the type on which
186       it can be emitted: users of the type are said to <emphasis>connect</emphasis>
187       to the signal on a given type instance when they register a closure to be 
188       invoked upon the signal emission. Users can also emit the signal by themselves 
189       or stop the emission of the signal from within one of the closures connected 
190       to the signal.
191     </para>
192
193     <para>
194       When a signal is emitted on a given type instance, all the closures
195       connected to this signal on this type instance will be invoked. All the closures
196       connected to such a signal represent callbacks whose signature looks like:
197 <programlisting>
198 return_type function_callback (gpointer instance, ... , gpointer user_data);
199 </programlisting>
200     </para>
201
202     <sect2 id="signal-registration">
203       <title>Signal registration</title>
204
205           <para>
206                 To register a new signal on an existing type, we can use any of <function><link linkend="g-signal-newv">g_signal_newv</link></function>,
207                 <function><link linkend="g-signal-new-valist">g_signal_new_valist</link></function> or <function><link linkend="g-signal-new">g_signal_new</link></function> functions:
208 <programlisting>
209 guint g_signal_newv (const gchar        *signal_name,
210                      GType               itype,
211                      GSignalFlags        signal_flags,
212                      GClosure           *class_closure,
213                      GSignalAccumulator  accumulator,
214                      gpointer            accu_data,
215                      GSignalCMarshaller  c_marshaller,
216                      GType               return_type,
217                      guint               n_params,
218                      GType              *param_types);
219 </programlisting>
220                 The number of parameters to these functions is a bit intimidating but they are relatively
221                 simple:
222                 <itemizedlist>
223                   <listitem><para>
224                           signal_name: is a string which can be used to uniquely identify a given signal.
225                         </para></listitem>
226                   <listitem><para>
227                           itype: is the instance type on which this signal can be emitted.
228                         </para></listitem>
229                   <listitem><para>
230                           signal_flags: partly defines the order in which closures which were connected to the
231                           signal are invoked.
232                         </para></listitem>
233                   <listitem><para>
234                           class_closure: this is the default closure for the signal: if it is not NULL upon
235                           the signal emission, it will be invoked upon this emission of the signal. The 
236                           moment where this closure is invoked compared to other closures connected to that 
237                           signal depends partly on the signal_flags.
238                         </para></listitem>
239                         <listitem><para>
240                           accumulator: this is a function pointer which is invoked after each closure
241                           has been invoked. If it returns FALSE, signal emission is stopped. If it returns
242                           TRUE, signal emission proceeds normally. It is also used to compute the return
243                           value of the signal based on the return value of all the invoked closures.
244                         </para></listitem>
245                   <listitem><para>
246                           accumulator_data: this pointer will be passed down to each invocation of the
247                           accumulator during emission.
248                         </para></listitem>
249                   <listitem><para>
250                           c_marshaller: this is the default C marshaller for any closure which is connected to
251                         this signal.
252                         </para></listitem>
253                   <listitem><para>
254                           return_type: this is the type of the return value of the signal.
255                         </para></listitem>
256                   <listitem><para>
257                           n_params: this is the number of parameters this signal takes.
258                         </para></listitem>
259                   <listitem><para>
260                           param_types: this is an array of GTypes which indicate the type of each parameter
261                           of the signal. The length of this array is indicated by n_params.
262                         </para></listitem>
263                 </itemizedlist>
264       </para>
265
266           <para>
267                 As you can see from the above definition, a signal is basically a description
268                 of the closures which can be connected to this signal and a description of the
269                 order in which the closures connected to this signal will be invoked.
270           </para>
271
272         </sect2>
273
274         <sect2 id="signal-connection">
275           <title>Signal connection</title>
276
277           <para>
278                 If you want to connect to a signal with a closure, you have three possibilities:
279                 <itemizedlist>
280                   <listitem><para>
281                   You can register a class closure at signal registration: this is a
282                   system-wide operation. i.e.: the class_closure will be invoked during each emission
283                   of a given signal on all the instances of the type which supports that signal.
284                         </para></listitem>
285                   <listitem><para>
286                   You can use <function><link linkend="g-signal-override-class-closure">g_signal_override_class_closure</link></function> which
287                   overrides the class_closure of a given type. It is possible to call this function
288                   only on a derived type of the type on which the signal was registered.
289                   This function is of use only to language bindings.
290                         </para></listitem>
291                   <listitem><para>
292                   You can register a closure with the <function><link linkend="g-signal-connect">g_signal_connect</link></function>
293                   family of functions. This is an instance-specific operation: the closure
294                   will be invoked only during emission of a given signal on a given instance.
295                         </para></listitem>
296                 </itemizedlist>
297                 It is also possible to connect a different kind of callback on a given signal: 
298                 emission hooks are invoked whenever a given signal is emitted whatever the instance on 
299                 which it is emitted. Emission hooks are used for example to get all mouse_clicked
300                 emissions in an application to be able to emit the small mouse click sound.
301                 Emission hooks are connected with <function><link linkend="g-signal-add-emission-hook">g_signal_add_emission_hook</link></function>
302                 and removed with <function><link linkend="g-signal-remove-emission-hook">g_signal_remove_emission_hook</link></function>.
303           </para>
304
305         </sect2>
306
307         <sect2 id="signal-emission">
308           <title>Signal emission</title>
309
310           <para>
311                 Signal emission is done through the use of the <function><link linkend="g-signal-emit">g_signal_emit</link></function> family 
312                 of functions.
313 <programlisting>
314 void g_signal_emitv (const GValue *instance_and_params,
315                      guint         signal_id,
316                      GQuark        detail,
317                      GValue       *return_value);
318 </programlisting>
319                 <itemizedlist>
320                   <listitem><para>
321                         The instance_and_params array of GValues contains the list of input
322                         parameters to the signal. The first element of the array is the 
323                         instance pointer on which to invoke the signal. The following elements of
324                         the array contain the list of parameters to the signal.
325                         </para></listitem>
326                   <listitem><para>
327                         signal_id identifies the signal to invoke.
328                         </para></listitem>
329                   <listitem><para>
330                         detail identifies the specific detail of the signal to invoke. A detail is a kind of 
331                         magic token/argument which is passed around during signal emission and which is used
332                         by closures connected to the signal to filter out unwanted signal emissions. In most 
333                         cases, you can safely set this value to zero. See <xref linkend="signal-detail"/> for
334                         more details about this parameter.
335                         </para></listitem>
336                   <listitem><para>
337                         return_value holds the return value of the last closure invoked during emission if
338                         no accumulator was specified. If an accumulator was specified during signal creation,
339                         this accumulator is used to calculate the return_value as a function of the return
340                         values of all the closures invoked during emission. 
341                         <footnote><para>
342                           James (again!!) gives a few non-trivial examples of accumulators:
343                           <quote>
344                                 For instance, you may have an accumulator that ignores NULL returns from 
345                                 closures, and only accumulates the non-NULL ones. Another accumulator may try
346                                 to return the list of values returned by the closures.
347                           </quote>
348                         </para></footnote>
349                         If no closure is invoked during
350                         emission, the return_value is nonetheless initialized to zero/null.
351                         </para></listitem>
352                   </itemizedlist>
353                 </para>
354
355           <para>
356                 Internally, the GValue array is passed to the emission function proper, 
357                 <function>signal_emit_unlocked_R</function> (implemented in <filename>gsignal.c</filename>).
358                 Signal emission can be decomposed in 5 steps:
359                 <itemizedlist>
360                   <listitem><para>
361                         <emphasis>RUN_FIRST</emphasis>: if the G_SIGNAL_RUN_FIRST flag was used
362                         during signal registration and if there exist a class_closure for this signal,
363                         the class_closure is invoked. Jump to <emphasis>EMISSION_HOOK</emphasis> state.
364                         </para></listitem>
365                   <listitem><para>
366                         <emphasis>EMISSION_HOOK</emphasis>: if any emission hook was added to
367                         the signal, they are invoked from first to last added. Accumulate return values
368                         and jump to <emphasis>HANDLER_RUN_FIRST</emphasis> state. 
369                         </para></listitem>
370                   <listitem><para>
371                         <emphasis>HANDLER_RUN_FIRST</emphasis>: if any closure were connected
372                         with the <function><link linkend="g-signal-connect">g_signal_connect</link></function> family of 
373                         functions, and if they are not blocked (with the <function><link linkend="g-signal-handler-block">g_signal_handler_block</link></function>
374                         family of functions) they are run here, from first to last connected.
375                         Jump to <emphasis>RUN_LAST</emphasis> state.
376                         </para></listitem>
377                   <listitem><para>
378                         <emphasis>RUN_LAST</emphasis>: if the G_SIGNAL_RUN_LAST
379                         flag was set during registration and if a class_closure
380                         was set, it is invoked here. Jump to 
381                         <emphasis>HANDLER_RUN_LAST</emphasis> state.
382                         </para></listitem>
383                   <listitem><para>
384                         <emphasis>HANDLER_RUN_LAST</emphasis>: if any closure were connected
385                         with the <function>g_signal_connect_after</function> family of 
386                         functions, if they were not invoked during HANDLER_RUN_FIRST and if they 
387                         are not blocked, they are run here, from first to last connected.
388                         Jump to  <emphasis>RUN_CLEANUP</emphasis> state.
389                         </para></listitem>
390                   <listitem><para>
391                         <emphasis>RUN_CLEANUP</emphasis>: if the G_SIGNAL_RUN_CLEANUP flag
392                         was set during registration and if a class_closure was set,
393                         it is invoked here. Signal emission is completed here.
394                         </para></listitem>
395                 </itemizedlist>      
396           </para>
397   
398           <para>
399                 If, at any point during emission (except in RUN_CLEANUP state), one of the
400                 closures or emission hook stops the signal emission with
401                 <function><link linkend="g-signal-stop-emission">g_signal_stop_emission</link></function>,
402                 emission jumps to CLEANUP state.
403           </para>
404   
405           <para>
406                 If, at any point during emission, one of the closures or emission hook 
407                 emits the same signal on the same instance, emission is restarted from
408                 the RUN_FIRST state.
409           </para>
410   
411           <para>
412                 The accumulator function is invoked in all states, after invocation
413                 of each closure (except in EMISSION_HOOK and CLEANUP). It accumulates
414                 the closure return value into the signal return value and returns TRUE or
415                 FALSE. If, at any point, it does not return TRUE, emission jumps to CLEANUP state.
416           </para>
417
418           <para>
419                 If no accumulator function was provided, the value returned by the last handler
420                 run will be returned by <function><link linkend="g-signal-emit">g_signal_emit</link></function>.
421           </para>
422
423         </sect2>
424
425
426         <sect2 id="signal-detail">
427           <title>The <emphasis>detail</emphasis> argument</title>
428
429           <para>All the functions related to signal emission or signal connection have a parameter
430                 named the <emphasis>detail</emphasis>. Sometimes, this parameter is hidden by the API
431                 but it is always there, under one form or another. 
432           </para>
433
434           <para>
435             Of the three main connection functions,
436                 only one has an explicit detail parameter as a <link linkend="GQuark"><type>GQuark</type></link>
437                 <footnote>
438                   <para>A GQuark is an integer which uniquely represents a string. It is possible to transform
439                    back and forth between the integer and string representations with the functions 
440                    <function><link linkend="g-quark-from-string">g_quark_from_string</link></function> and <function><link linkend="g-quark-to-string">g_quark_to_string</link></function>.
441                   </para>
442                 </footnote>:
443 <programlisting>
444 gulong     g_signal_connect_closure_by_id          (gpointer          instance,
445                            guint          signal_id,
446                            GQuark          detail,
447                            GClosure         *closure,
448                            gboolean          after);
449 </programlisting>
450         The two other functions hide the detail parameter in the signal name identification:
451 <programlisting>
452 gulong     g_signal_connect_closure          (gpointer          instance,
453                            const gchar       *detailed_signal,
454                            GClosure         *closure,
455                            gboolean          after);
456 gulong     g_signal_connect_data              (gpointer          instance,
457                            const gchar     *detailed_signal,
458                            GCallback      c_handler,
459                            gpointer          data,
460                            GClosureNotify      destroy_data,
461                            GConnectFlags      connect_flags);
462 </programlisting>
463                 Their detailed_signal parameter is a string which identifies the name of the signal
464                 to connect to. However, the format of this string is structured to look like 
465                 <emphasis>signal_name::detail_name</emphasis>. Connecting to the signal
466                 named <emphasis>notify::cursor_position</emphasis> will actually connect to the signal
467                 named <emphasis>notify</emphasis> with the <emphasis>cursor_position</emphasis> name.
468                 Internally, the detail string is transformed to a GQuark if it is present.
469           </para>
470
471           <para>
472                 Of the four main signal emission functions, three have an explicit detail parameter as a 
473                 <link linkend="GQuark"><type>GQuark</type></link> again:
474 <programlisting>
475 void                  g_signal_emitv        (const GValue       *instance_and_params,
476                          guint               signal_id,
477                          GQuark              detail,
478                          GValue             *return_value);
479 void                  g_signal_emit_valist  (gpointer            instance,
480                          guint               signal_id,
481                          GQuark              detail,
482                          va_list             var_args);
483 void                  g_signal_emit         (gpointer            instance,
484                          guint               signal_id,
485                          GQuark              detail,
486                          ...);
487 </programlisting>
488         The fourth function hides it in its signal name parameter:
489 <programlisting>
490 void                  g_signal_emit_by_name (gpointer            instance,
491                          const gchar        *detailed_signal,
492                          ...);
493 </programlisting>
494         The format of the detailed_signal parameter is exactly the same as the format used by
495         the <function><link linkend="g-signal-connect">g_signal_connect</link></function> functions: <emphasis>signal_name::detail_name</emphasis>.
496           </para>
497
498           <para>
499         If a detail is provided by the user to the emission function, it is used during emission to match
500         against the closures which also provide a detail.
501         If the closures' detail does not match the detail provided by the user, they will not be invoked
502         (even though they are connected to a signal which is being emitted).
503           </para>
504
505           <para>
506                 This completely optional filtering mechanism is mainly used as an optimization for signals
507                 which are often emitted for many different reasons: the clients can filter out which events they are
508                 interested in before the closure's marshalling code runs. For example, this is used extensively
509                 by the <emphasis>notify</emphasis> signal of GObject: whenever a property is modified on a GObject,
510                 instead of just emitting the <emphasis>notify</emphasis> signal, GObject associates as a detail to this
511                 signal emission the name of the property modified. This allows clients who wish to be notified of changes
512                 to only one property to filter most events before receiving them.
513           </para>
514
515           <para>
516                 As a simple rule, users can and should set the detail parameter to zero: this will disable completely
517         this optional filtering.
518           </para>
519
520         </sect2>
521
522   </sect1>
523 </chapter>
524