]> Pileus Git - ~andy/gtk/blob - docs/tutorial/gtk-tut.sgml
rearrange rules to not emit the example start and end markers.
[~andy/gtk] / docs / tutorial / gtk-tut.sgml
1 <!doctype book PUBLIC "-//OASIS//DTD DocBook V3.1//EN" []>
2 <book id="gtk-tut">
3
4 <bookinfo>
5     <date>March 1st 2001</date>
6     <title>GTK+ 1.2 Tutorial</title>
7     <authorgroup>
8       <author>
9         <firstname>Tony</firstname>
10         <surname>Gale</surname>
11       </author>
12       <author>
13         <firstname>Ian</firstname>
14         <surname>Main</surname>
15       </author>
16     </authorgroup>
17     <abstract>
18       <para> This is a tutorial on how to use GTK (the GIMP Toolkit) through its C
19             interface.</para>
20     </abstract>
21   </bookinfo>
22
23 <toc></toc>
24
25 <!-- ***************************************************************** -->
26 <chapter id="ch-Introduction">
27 <title>Introduction</title>
28
29 <para>GTK (GIMP Toolkit) is a library for creating graphical user
30 interfaces. It is licensed using the LGPL license, so you can develop
31 open software, free software, or even commercial non-free software
32 using GTK without having to spend anything for licenses or royalties.</para>
33
34 <para>It's called the GIMP toolkit because it was originally written for
35 developing the GNU Image Manipulation Program (GIMP), but GTK has
36 now been used in a large number of software projects, including the
37 GNU Network Object Model Environment (GNOME) project. GTK is built on
38 top of GDK (GIMP Drawing Kit) which is basically a wrapper around the
39 low-level functions for accessing the underlying windowing functions
40 (Xlib in the case of the X windows system). The primary authors of GTK
41 are:</para>
42
43 <itemizedlist>
44 <listitem><simpara> Peter Mattis <ulink url="mailto:petm@xcf.berkeley.edu">
45 petm@xcf.berkeley.edu</ulink></simpara>
46 </listitem>
47 <listitem><simpara> Spencer Kimball <ulink url="mailto:spencer@xcf.berkeley.edu">
48 spencer@xcf.berkeley.edu</ulink></simpara>
49 </listitem>
50 <listitem><simpara> Josh MacDonald <ulink url="mailto:jmacd@xcf.berkeley.edu">
51 jmacd@xcf.berkeley.edu</ulink></simpara>
52 </listitem>
53 </itemizedlist>
54
55 <para>GTK is essentially an object oriented application programmers
56 interface (API). Although written completely in C, it is implemented
57 using the idea of classes and callback functions (pointers to
58 functions).</para>
59
60 <para>There is also a third component called GLib which contains a few
61 replacements for some standard calls, as well as some additional
62 functions for handling linked lists, etc. The replacement functions
63 are used to increase GTK's portability, as some of the functions
64 implemented here are not available or are nonstandard on other unixes
65 such as g_strerror(). Some also contain enhancements to the libc
66 versions, such as g_malloc that has enhanced debugging utilities.</para>
67
68 <para>This tutorial describes the C interface to GTK. There are GTK
69 bindings for many other languages including C++, Guile, Perl, Python,
70 TOM, Ada95, Objective C, Free Pascal, and Eiffel. If you intend to
71 use another language's bindings to GTK, look at that binding's
72 documentation first. In some cases that documentation may describe
73 some important conventions (which you should know first) and then
74 refer you back to this tutorial. There are also some cross-platform
75 APIs (such as wxWindows and V) which use GTK as one of their target
76 platforms; again, consult their documentation first.</para>
77
78 <para>If you're developing your GTK application in C++, a few extra notes
79 are in order. There's a C++ binding to GTK called GTK--, which
80 provides a more C++-like interface to GTK; you should probably look
81 into this instead. If you don't like that approach for whatever
82 reason, there are two alternatives for using GTK. First, you can use
83 only the C subset of C++ when interfacing with GTK and then use the C
84 interface as described in this tutorial. Second, you can use GTK and
85 C++ together by declaring all callbacks as static functions in C++
86 classes, and again calling GTK using its C interface. If you choose
87 this last approach, you can include as the callback's data value a
88 pointer to the object to be manipulated (the so-called "this" value).
89 Selecting between these options is simply a matter of preference,
90 since in all three approaches you get C++ and GTK. None of these
91 approaches requires the use of a specialized preprocessor, so no
92 matter what you choose you can use standard C++ with GTK.</para>
93
94 <para>This tutorial is an attempt to document as much as possible of GTK,
95 but it is by no means complete. This tutorial assumes a good
96 understanding of C, and how to create C programs. It would be a great
97 benefit for the reader to have previous X programming experience, but
98 it shouldn't be necessary. If you are learning GTK as your first
99 widget set, please comment on how you found this tutorial, and what
100 you had trouble with. There are also C++, Objective C, ADA, Guile and
101 other language bindings available, but I don't follow these.</para>
102
103 <para>This document is a "work in progress". Please look for updates on
104 <ulink url="http://www.gtk.org/">http://www.gtk.org/</ulink>.</para>
105
106 <para>I would very much like to hear of any problems you have learning GTK
107 from this document, and would appreciate input as to how it may be
108 improved. Please see the section on <link linkend="ch-Contributing">Contributing
109 </link> for further information.</para>
110
111 </chapter>
112
113 <!-- ***************************************************************** -->
114 <chapter id="ch-GettingStarted">
115 <title>Getting Started</title>
116
117 <para>The first thing to do, of course, is download the GTK source and
118 install it. You can always get the latest version from ftp.gtk.org in
119 /pub/gtk. You can also view other sources of GTK information on
120 <ulink url="http://www.gtk.org/">http://www.gtk.org/</ulink>. GTK
121 uses GNU autoconf for configuration. Once untar'd, type ./configure
122 --help to see a list of options.</para>
123
124 <para>The GTK source distribution also contains the complete source to all
125 of the examples used in this tutorial, along with Makefiles to aid
126 compilation.</para>
127
128 <para>To begin our introduction to GTK, we'll start with the simplest
129 program possible. This program will create a 200x200 pixel window and
130 has no way of exiting except to be killed by using the shell.</para>
131
132 <programlisting role="C">
133 <!-- example-start base base.c -->
134
135 #include &lt;gtk/gtk.h&gt;
136
137 int main( int   argc,
138           char *argv[] )
139 {
140     GtkWidget *window;
141     
142     gtk_init (&amp;argc, &amp;argv);
143     
144     window = gtk_window_new (GTK_WINDOW_TOPLEVEL);
145     gtk_widget_show  (window);
146     
147     gtk_main ();
148     
149     return(0);
150 }
151 <!-- example-end -->
152 </programlisting>
153
154 <para>You can compile the above program with gcc using:</para>
155 <para><literallayout>
156 <literal>gcc base.c -o base `gtk-config --cflags --libs`</literal>
157 </literallayout></para>
158
159 <para>The meaning of the unusual compilation options is explained below in
160 <link linkend="sec-Compiling">Compiling Hello World</link>.</para>
161
162 <para>All programs will of course include gtk/gtk.h which declares the
163 variables, functions, structures, etc. that will be used in your GTK
164 application.</para>
165
166 <para>The next line:</para>
167
168 <programlisting role="C">
169 gtk_init (&amp;argc, &amp;argv);
170 </programlisting>
171
172 <para>calls the function gtk_init(gint *argc, gchar ***argv) which will be
173 called in all GTK applications. This sets up a few things for us such
174 as the default visual and color map and then proceeds to call
175 gdk_init(gint *argc, gchar ***argv). This function initializes the
176 library for use, sets up default signal handlers, and checks the
177 arguments passed to your application on the command line, looking for
178 one of the following:</para>
179
180 <itemizedlist spacing=Compact>
181 <listitem><simpara> <literal>--gtk-module</literal></simpara>
182 </listitem>
183 <listitem><simpara> <literal>--g-fatal-warnings</literal></simpara>
184 </listitem>
185 <listitem><simpara> <literal>--gtk-debug</literal></simpara>
186 </listitem>
187 <listitem><simpara> <literal>--gtk-no-debug</literal></simpara>
188 </listitem>
189 <listitem><simpara> <literal>--gdk-debug</literal></simpara>
190 </listitem>
191 <listitem><simpara> <literal>--gdk-no-debug</literal></simpara>
192 </listitem>
193 <listitem><simpara> <literal>--display</literal></simpara>
194 </listitem>
195 <listitem><simpara> <literal>--sync</literal></simpara>
196 </listitem>
197 <listitem><simpara> <literal>--no-xshm</literal></simpara>
198 </listitem>
199 <listitem><simpara> <literal>--name</literal></simpara>
200 </listitem>
201 <listitem><simpara> <literal>--class</literal></simpara>
202 </listitem>
203 </itemizedlist>
204
205 <para>It removes these from the argument list, leaving anything it does not
206 recognize for your application to parse or ignore. This creates a set
207 of standard arguments accepted by all GTK applications.</para>
208
209 <para>The next two lines of code create and display a window.</para>
210
211 <programlisting role="C">
212   window = gtk_window_new (GTK_WINDOW_TOPLEVEL);
213   gtk_widget_show (window);
214 </programlisting>
215
216 <para>The <literal>GTK_WINDOW_TOPLEVEL</literal> argument specifies that we want the
217 window to undergo window manager decoration and placement. Rather than
218 create a window of 0x0 size, a window without children is set to
219 200x200 by default so you can still manipulate it.</para>
220
221 <para>The gtk_widget_show() function lets GTK know that we are done setting
222 the attributes of this widget, and that it can display it.</para>
223
224 <para>The last line enters the GTK main processing loop.</para>
225
226 <programlisting role="C">
227   gtk_main ();
228 </programlisting>
229
230 <para>gtk_main() is another call you will see in every GTK application.
231 When control reaches this point, GTK will sleep waiting for X events
232 (such as button or key presses), timeouts, or file IO notifications to
233 occur. In our simple example, however, events are ignored.</para>
234
235 <!-- ----------------------------------------------------------------- -->
236 <sect1 id="sec-HelloWorld">
237 <title>Hello World in GTK</title>
238
239 <para>Now for a program with a widget (a button). It's the classic
240 hello world a la GTK.</para>
241
242 <programlisting role="C">
243 <!-- example-start helloworld helloworld.c -->
244
245 #include &lt;gtk/gtk.h&gt;
246
247 /* This is a callback function. The data arguments are ignored
248  * in this example. More on callbacks below. */
249 void hello( GtkWidget *widget,
250             gpointer   data )
251 {
252     g_print ("Hello World\n");
253 }
254
255 gint delete_event( GtkWidget *widget,
256                    GdkEvent  *event,
257                    gpointer   data )
258 {
259     /* If you return FALSE in the "delete_event" signal handler,
260      * GTK will emit the "destroy" signal. Returning TRUE means
261      * you don't want the window to be destroyed.
262      * This is useful for popping up 'are you sure you want to quit?'
263      * type dialogs. */
264
265     g_print ("delete event occurred\n");
266
267     /* Change TRUE to FALSE and the main window will be destroyed with
268      * a "delete_event". */
269
270     return(TRUE);
271 }
272
273 /* Another callback */
274 void destroy( GtkWidget *widget,
275               gpointer   data )
276 {
277     gtk_main_quit();
278 }
279
280 int main( int   argc,
281           char *argv[] )
282 {
283     /* GtkWidget is the storage type for widgets */
284     GtkWidget *window;
285     GtkWidget *button;
286     
287     /* This is called in all GTK applications. Arguments are parsed
288      * from the command line and are returned to the application. */
289     gtk_init(&amp;argc, &amp;argv);
290     
291     /* create a new window */
292     window = gtk_window_new (GTK_WINDOW_TOPLEVEL);
293     
294     /* When the window is given the "delete_event" signal (this is given
295      * by the window manager, usually by the "close" option, or on the
296      * titlebar), we ask it to call the delete_event () function
297      * as defined above. The data passed to the callback
298      * function is NULL and is ignored in the callback function. */
299     gtk_signal_connect (GTK_OBJECT (window), "delete_event",
300                         GTK_SIGNAL_FUNC (delete_event), NULL);
301     
302     /* Here we connect the "destroy" event to a signal handler.  
303      * This event occurs when we call gtk_widget_destroy() on the window,
304      * or if we return FALSE in the "delete_event" callback. */
305     gtk_signal_connect (GTK_OBJECT (window), "destroy",
306                         GTK_SIGNAL_FUNC (destroy), NULL);
307     
308     /* Sets the border width of the window. */
309     gtk_container_set_border_width (GTK_CONTAINER (window), 10);
310     
311     /* Creates a new button with the label "Hello World". */
312     button = gtk_button_new_with_label ("Hello World");
313     
314     /* When the button receives the "clicked" signal, it will call the
315      * function hello() passing it NULL as its argument.  The hello()
316      * function is defined above. */
317     gtk_signal_connect (GTK_OBJECT (button), "clicked",
318                         GTK_SIGNAL_FUNC (hello), NULL);
319     
320     /* This will cause the window to be destroyed by calling
321      * gtk_widget_destroy(window) when "clicked".  Again, the destroy
322      * signal could come from here, or the window manager. */
323     gtk_signal_connect_object (GTK_OBJECT (button), "clicked",
324                                GTK_SIGNAL_FUNC (gtk_widget_destroy),
325                                GTK_OBJECT (window));
326     
327     /* This packs the button into the window (a gtk container). */
328     gtk_container_add (GTK_CONTAINER (window), button);
329     
330     /* The final step is to display this newly created widget. */
331     gtk_widget_show (button);
332     
333     /* and the window */
334     gtk_widget_show (window);
335     
336     /* All GTK applications must have a gtk_main(). Control ends here
337      * and waits for an event to occur (like a key press or
338      * mouse event). */
339     gtk_main ();
340     
341     return(0);
342 }
343 <!-- example-end -->
344 </programlisting>
345
346 </sect1>
347
348 <!-- ----------------------------------------------------------------- -->
349 <sect1 id="sec-Compiling">
350 <title>Compiling Hello World</title>
351
352 <para>To compile use:</para>
353
354 <para><literallayout>
355 <literal>gcc -Wall -g helloworld.c -o helloworld `gtk-config --cflags` \</literal>
356 <literal>    `gtk-config --libs`</literal>
357 </literallayout></para>
358
359 <para>This uses the program <literal>gtk-config</literal>, which comes with GTK. This
360 program "knows" what compiler switches are needed to compile programs
361 that use GTK. <literal>gtk-config --cflags</literal> will output a list of include
362 directories for the compiler to look in, and <literal>gtk-config --libs</>
363 will output the list of libraries for the compiler to link with and
364 the directories to find them in. In the above example they could have
365 been combined into a single instance, such as
366 <literal>`gtk-config --cflags --libs`</literal>.</para>
367
368 <para>Note that the type of single quote used in the compile command above
369 is significant.</para>
370
371 <para>The libraries that are usually linked in are:</para>
372
373 <itemizedlist>
374 <listitem><simpara>The GTK library (-lgtk), the widget library, based on top of GDK.</simpara>
375 </listitem>
376
377 <listitem><simpara>The GDK library (-lgdk), the Xlib wrapper.</simpara>
378 </listitem>
379
380 <listitem><simpara>The gmodule library (-lgmodule), which is used to load run time
381 extensions.</simpara>
382 </listitem>
383
384 <listitem><simpara>The GLib library (-lglib), containing miscellaneous functions;
385 only g_print() is used in this particular example. GTK is built on top
386 of glib so you will always require this library. See the section on
387 <link linkend="ch-glib">GLib</link> for details.</simpara>
388 </listitem>
389
390 <listitem><simpara>The Xlib library (-lX11) which is used by GDK.</simpara>
391 </listitem>
392
393 <listitem><simpara>The Xext library (-lXext). This contains code for shared memory
394 pixmaps and other X extensions.</simpara>
395 </listitem>
396
397 <listitem><simpara>The math library (-lm). This is used by GTK for various
398 purposes.</simpara>
399 </listitem>
400 </itemizedlist>
401
402 </sect1>
403
404 <!-- ----------------------------------------------------------------- -->
405 <sect1 id="sec-TheoryOfSignalsAndCallbacks">
406 <title>Theory of Signals and Callbacks</title>
407
408 <para>Before we look in detail at <emphasis>helloworld</emphasis>, we'll discuss signals
409 and callbacks. GTK is an event driven toolkit, which means it will
410 sleep in gtk_main until an event occurs and control is passed to the
411 appropriate function.</para>
412
413 <para>This passing of control is done using the idea of "signals". (Note
414 that these signals are not the same as the Unix system signals, and
415 are not implemented using them, although the terminology is almost
416 identical.) When an event occurs, such as the press of a mouse button,
417 the appropriate signal will be "emitted" by the widget that was
418 pressed.  This is how GTK does most of its useful work. There are
419 signals that all widgets inherit, such as "destroy", and there are
420 signals that are widget specific, such as "toggled" on a toggle
421 button.</para>
422
423 <para>To make a button perform an action, we set up a signal handler to
424 catch these signals and call the appropriate function. This is done by
425 using a function such as:</para>
426
427 <programlisting role="C">
428 gint gtk_signal_connect( GtkObject     *object,
429                          gchar         *name,
430                          GtkSignalFunc  func,
431                          gpointer       func_data );
432 </programlisting>
433
434 <para>where the first argument is the widget which will be emitting the
435 signal, and the second the name of the signal you wish to catch. The
436 third is the function you wish to be called when it is caught, and the
437 fourth, the data you wish to have passed to this function.</para>
438
439 <para>The function specified in the third argument is called a "callback
440 function", and should generally be of the form</para>
441
442 <programlisting role="C">
443 void callback_func( GtkWidget *widget,
444                     gpointer   callback_data );
445 </programlisting>
446
447 <para>where the first argument will be a pointer to the widget that emitted
448 the signal, and the second a pointer to the data given as the last
449 argument to the gtk_signal_connect() function as shown above.</para>
450
451 <para>Note that the above form for a signal callback function declaration is
452 only a general guide, as some widget specific signals generate
453 different calling parameters. For example, the CList "select_row"
454 signal provides both row and column parameters.</para>
455
456 <para>Another call used in the <emphasis>helloworld</emphasis> example, is:</para>
457
458 <programlisting role="C">
459 gint gtk_signal_connect_object( GtkObject     *object,
460                                 gchar         *name,
461                                 GtkSignalFunc  func,
462                                 GtkObject     *slot_object );
463 </programlisting>
464
465 <para>gtk_signal_connect_object() is the same as gtk_signal_connect() except
466 that the callback function only uses one argument, a pointer to a GTK
467 object. So when using this function to connect signals, the callback
468 should be of the form</para>
469
470 <programlisting role="C">
471 void callback_func( GtkObject *object );
472 </programlisting>
473
474 <para>where the object is usually a widget. We usually don't setup callbacks
475 for gtk_signal_connect_object however. They are usually used to call a
476 GTK function that accepts a single widget or object as an argument, as
477 is the case in our <emphasis>helloworld</emphasis> example.</para>
478
479 <para>The purpose of having two functions to connect signals is simply to
480 allow the callbacks to have a different number of arguments. Many
481 functions in the GTK library accept only a single GtkWidget pointer as
482 an argument, so you want to use the gtk_signal_connect_object() for
483 these, whereas for your functions, you may need to have additional
484 data supplied to the callbacks.</para>
485
486 </sect1>
487
488 <!-- ----------------------------------------------------------------- -->
489 <sect1 id="sec-Events">
490 <title>Events</title>
491
492 <para>In addition to the signal mechanism described above, there is a set
493 of <emphasis>events</emphasis> that reflect the X event mechanism. Callbacks may
494 also be attached to these events. These events are:</para>
495
496 <itemizedlist spacing=Compact>
497 <listitem><simpara> event</simpara>
498 </listitem>
499 <listitem><simpara> button_press_event</simpara>
500 </listitem>
501 <listitem><simpara> button_release_event</simpara>
502 </listitem>
503 <listitem><simpara> motion_notify_event</simpara>
504 </listitem>
505 <listitem><simpara> delete_event</simpara>
506 </listitem>
507 <listitem><simpara> destroy_event</simpara>
508 </listitem>
509 <listitem><simpara> expose_event</simpara>
510 </listitem>
511 <listitem><simpara> key_press_event</simpara>
512 </listitem>
513 <listitem><simpara> key_release_event</simpara>
514 </listitem>
515 <listitem><simpara> enter_notify_event</simpara>
516 </listitem>
517 <listitem><simpara> leave_notify_event</simpara>
518 </listitem>
519 <listitem><simpara> configure_event</simpara>
520 </listitem>
521 <listitem><simpara> focus_in_event</simpara>
522 </listitem>
523 <listitem><simpara> focus_out_event</simpara>
524 </listitem>
525 <listitem><simpara> map_event</simpara>
526 </listitem>
527 <listitem><simpara> unmap_event</simpara>
528 </listitem>
529 <listitem><simpara> property_notify_event</simpara>
530 </listitem>
531 <listitem><simpara> selection_clear_event</simpara>
532 </listitem>
533 <listitem><simpara> selection_request_event</simpara>
534 </listitem>
535 <listitem><simpara> selection_notify_event</simpara>
536 </listitem>
537 <listitem><simpara> proximity_in_event</simpara>
538 </listitem>
539 <listitem><simpara> proximity_out_event</simpara>
540 </listitem>
541 <listitem><simpara> drag_begin_event</simpara>
542 </listitem>
543 <listitem><simpara> drag_request_event</simpara>
544 </listitem>
545 <listitem><simpara> drag_end_event</simpara>
546 </listitem>
547 <listitem><simpara> drop_enter_event</simpara>
548 </listitem>
549 <listitem><simpara> drop_leave_event</simpara>
550 </listitem>
551 <listitem><simpara> drop_data_available_event</simpara>
552 </listitem>
553 <listitem><simpara> other_event</simpara>
554 </listitem>
555 </itemizedlist>
556
557 <para>In order to connect a callback function to one of these events you
558 use the function gtk_signal_connect, as described above, using one of
559 the above event names as the <literal>name</literal> parameter. The callback
560 function for events has a slightly different form than that for
561 signals:</para>
562
563 <programlisting role="C">
564 gint callback_func( GtkWidget *widget,
565                     GdkEvent  *event,
566                     gpointer   callback_data );
567 </programlisting>
568
569 <para>GdkEvent is a C <literal>union</literal> structure whose type will depend upon which
570 of the above events has occurred. In order for us to tell which event
571 has been issued each of the possible alternatives has a <literal>type</literal>
572 member that reflects the event being issued. The other components
573 of the event structure will depend upon the type of the
574 event. Possible values for the type are:</para>
575
576 <programlisting role="C">
577   GDK_NOTHING
578   GDK_DELETE
579   GDK_DESTROY
580   GDK_EXPOSE
581   GDK_MOTION_NOTIFY
582   GDK_BUTTON_PRESS
583   GDK_2BUTTON_PRESS
584   GDK_3BUTTON_PRESS
585   GDK_BUTTON_RELEASE
586   GDK_KEY_PRESS
587   GDK_KEY_RELEASE
588   GDK_ENTER_NOTIFY
589   GDK_LEAVE_NOTIFY
590   GDK_FOCUS_CHANGE
591   GDK_CONFIGURE
592   GDK_MAP
593   GDK_UNMAP
594   GDK_PROPERTY_NOTIFY
595   GDK_SELECTION_CLEAR
596   GDK_SELECTION_REQUEST
597   GDK_SELECTION_NOTIFY
598   GDK_PROXIMITY_IN
599   GDK_PROXIMITY_OUT
600   GDK_DRAG_BEGIN
601   GDK_DRAG_REQUEST
602   GDK_DROP_ENTER
603   GDK_DROP_LEAVE
604   GDK_DROP_DATA_AVAIL
605   GDK_CLIENT_EVENT
606   GDK_VISIBILITY_NOTIFY
607   GDK_NO_EXPOSE
608   GDK_OTHER_EVENT       /* Deprecated, use filters instead */
609 </programlisting>
610
611 <para>So, to connect a callback function to one of these events we would use
612 something like:</para>
613
614 <programlisting role="C">
615 gtk_signal_connect( GTK_OBJECT(button), "button_press_event",
616                     GTK_SIGNAL_FUNC(button_press_callback), 
617                     NULL);
618 </programlisting>
619
620 <para>This assumes that <literal>button</literal> is a Button widget. Now, when the
621 mouse is over the button and a mouse button is pressed, the function
622 <literal>button_press_callback</literal> will be called. This function may be
623 declared as:</para>
624
625 <programlisting role="C">
626 static gint button_press_callback( GtkWidget      *widget, 
627                                    GdkEventButton *event,
628                                    gpointer        data );
629 </programlisting>
630
631 <para>Note that we can declare the second argument as type
632 <literal>GdkEventButton</literal> as we know what type of event will occur for this
633 function to be called.</para>
634
635 <para>The value returned from this function indicates whether the event
636 should be propagated further by the GTK event handling
637 mechanism. Returning TRUE indicates that the event has been handled,
638 and that it should not propagate further. Returning FALSE continues
639 the normal event handling.  See the section on
640 <link linkend="ch-AdvancedEventsAndSignals">Advanced Event and Signal Handling</link> for more details on this
641 propagation process.</para>
642
643 <para>For details on the GdkEvent data types, see the appendix entitled
644 <link linkend="app-GDKEventTypes">GDK Event Types</link>.</para>
645
646 </sect1>
647
648 <!-- ----------------------------------------------------------------- -->
649 <sect1 id="sec-SteppingThroughHelloWorld">
650 <title>Stepping Through Hello World</title>
651
652 <para>Now that we know the theory behind this, let's clarify by walking
653 through the example <emphasis>helloworld</emphasis> program.</para>
654
655 <para>Here is the callback function that will be called when the button is
656 "clicked". We ignore both the widget and the data in this example, but
657 it is not hard to do things with them. The next example will use the
658 data argument to tell us which button was pressed.</para>
659
660 <programlisting role="C">
661 void hello( GtkWidget *widget,
662             gpointer   data )
663 {
664     g_print ("Hello World\n");
665 }
666 </programlisting>
667
668 <para>The next callback is a bit special. The "delete_event" occurs when the
669 window manager sends this event to the application. We have a choice
670 here as to what to do about these events. We can ignore them, make
671 some sort of response, or simply quit the application.</para>
672
673 <para>The value you return in this callback lets GTK know what action to
674 take.  By returning TRUE, we let it know that we don't want to have
675 the "destroy" signal emitted, keeping our application running. By
676 returning FALSE, we ask that "destroy" be emitted, which in turn will
677 call our "destroy" signal handler.</para>
678
679
680 <programlisting role="C">
681 gint delete_event( GtkWidget *widget,
682                    GdkEvent  *event,
683                    gpointer   data )
684 {
685     g_print ("delete event occurred\n");
686
687     return (TRUE); 
688 }
689 </programlisting>
690
691 <para>Here is another callback function which causes the program to quit by
692 calling gtk_main_quit(). This function tells GTK that it is to exit
693 from gtk_main when control is returned to it.</para>
694
695 <programlisting role="C">
696 void destroy( GtkWidget *widget,
697               gpointer   data )
698 {
699     gtk_main_quit ();
700 }
701 </programlisting>
702
703 <para>I assume you know about the main() function... yes, as with other
704 applications, all GTK applications will also have one of these.</para>
705
706 <programlisting role="C">
707 int main( int   argc,
708           char *argv[] )
709 {
710 </programlisting>
711
712 <para>This next part declares pointers to a structure of type
713 GtkWidget. These are used below to create a window and a button.</para>
714
715 <programlisting role="C">
716     GtkWidget *window;
717     GtkWidget *button;
718 </programlisting>
719
720 <para>Here is our gtk_init again. As before, this initializes the toolkit,
721 and parses the arguments found on the command line. Any argument it
722 recognizes from the command line, it removes from the list, and
723 modifies argc and argv to make it look like they never existed,
724 allowing your application to parse the remaining arguments.</para>
725
726 <programlisting role="C">
727     gtk_init (&amp;argc, &amp;argv);
728 </programlisting>
729
730 <para>Create a new window. This is fairly straightforward. Memory is
731 allocated for the GtkWidget *window structure so it now points to a
732 valid structure. It sets up a new window, but it is not displayed
733 until we call gtk_widget_show(window) near the end of our program.</para>
734
735 <programlisting role="C">
736     window = gtk_window_new (GTK_WINDOW_TOPLEVEL);
737 </programlisting>
738
739 <para>Here are two examples of connecting a signal handler to an object, in
740 this case, the window. Here, the "delete_event" and "destroy" signals
741 are caught. The first is emitted when we use the window manager to
742 kill the window, or when we use the gtk_widget_destroy() call passing
743 in the window widget as the object to destroy. The second is emitted
744 when, in the "delete_event" handler, we return FALSE.
745  
746 The <literal>GTK_OBJECT</literal> and <literal>GTK_SIGNAL_FUNC</literal> are macros that perform
747 type casting and checking for us, as well as aid the readability of
748 the code.</para>
749
750 <programlisting role="C">
751     gtk_signal_connect (GTK_OBJECT (window), "delete_event",
752                         GTK_SIGNAL_FUNC (delete_event), NULL);
753     gtk_signal_connect (GTK_OBJECT (window), "destroy",
754                         GTK_SIGNAL_FUNC (destroy), NULL);
755 </programlisting>
756
757 <para>This next function is used to set an attribute of a container object.
758 This just sets the window so it has a blank area along the inside of
759 it 10 pixels wide where no widgets will go. There are other similar
760 functions which we will look at in the section on
761 <link linkend="ch-SettingWidgetAttributes">Setting Widget Attributes</link></para>
762
763 <para>And again, <literal>GTK_CONTAINER</literal> is a macro to perform type casting.</para>
764
765 <programlisting role="C">
766     gtk_container_set_border_width (GTK_CONTAINER (window), 10);
767 </programlisting>
768
769 <para>This call creates a new button. It allocates space for a new GtkWidget
770 structure in memory, initializes it, and makes the button pointer
771 point to it. It will have the label "Hello World" on it when
772 displayed.</para>
773
774 <programlisting role="C">
775     button = gtk_button_new_with_label ("Hello World");
776 </programlisting>
777
778 <para>Here, we take this button, and make it do something useful. We attach
779 a signal handler to it so when it emits the "clicked" signal, our
780 hello() function is called. The data is ignored, so we simply pass in
781 NULL to the hello() callback function. Obviously, the "clicked" signal
782 is emitted when we click the button with our mouse pointer.</para>
783
784 <programlisting role="C">
785     gtk_signal_connect (GTK_OBJECT (button), "clicked",
786                         GTK_SIGNAL_FUNC (hello), NULL);
787 </programlisting>
788
789 <para>We are also going to use this button to exit our program. This will
790 illustrate how the "destroy" signal may come from either the window
791 manager, or our program. When the button is "clicked", same as above,
792 it calls the first hello() callback function, and then this one in the
793 order they are set up. You may have as many callback functions as you
794 need, and all will be executed in the order you connected
795 them. Because the gtk_widget_destroy() function accepts only a
796 GtkWidget *widget as an argument, we use the
797 gtk_signal_connect_object() function here instead of straight
798 gtk_signal_connect().</para>
799
800 <programlisting role="C">
801     gtk_signal_connect_object (GTK_OBJECT (button), "clicked",
802                                GTK_SIGNAL_FUNC (gtk_widget_destroy),
803                                GTK_OBJECT (window));
804 </programlisting>
805
806 <para>This is a packing call, which will be explained in depth later on in
807 <link linkend="ch-PackingWidgets">Packing Widgets</link>. But it is
808 fairly easy to understand. It simply tells GTK that the button is to
809 be placed in the window where it will be displayed. Note that a GTK
810 container can only contain one widget. There are other widgets, that
811 are described later, which are designed to layout multiple widgets in
812 various ways.
813  </para>
814
815 <programlisting role="C">
816     gtk_container_add (GTK_CONTAINER (window), button);
817 </programlisting>
818
819 <para>Now we have everything set up the way we want it to be. With all the
820 signal handlers in place, and the button placed in the window where it
821 should be, we ask GTK to "show" the widgets on the screen. The window
822 widget is shown last so the whole window will pop up at once rather
823 than seeing the window pop up, and then the button form inside of
824 it. Although with such a simple example, you'd never notice.</para>
825
826 <programlisting role="C">
827     gtk_widget_show (button);
828
829     gtk_widget_show (window);
830 </programlisting>
831
832 <para>And of course, we call gtk_main() which waits for events to come from
833 the X server and will call on the widgets to emit signals when these
834 events come.</para>
835
836 <programlisting role="C">
837     gtk_main ();
838 </programlisting>
839
840 <para>And the final return. Control returns here after gtk_quit() is called.</para>
841
842 <programlisting role="C">
843     return (0);
844 </programlisting>
845
846 <para>Now, when we click the mouse button on a GTK button, the widget emits
847 a "clicked" signal. In order for us to use this information, our
848 program sets up a signal handler to catch that signal, which
849 dispatches the function of our choice. In our example, when the button
850 we created is "clicked", the hello() function is called with a NULL
851 argument, and then the next handler for this signal is called. This
852 calls the gtk_widget_destroy() function, passing it the window widget
853 as its argument, destroying the window widget. This causes the window
854 to emit the "destroy" signal, which is caught, and calls our destroy()
855 callback function, which simply exits GTK.</para>
856
857 <para>Another course of events is to use the window manager to kill the
858 window, which will cause the "delete_event" to be emitted. This will
859 call our "delete_event" handler. If we return TRUE here, the window
860 will be left as is and nothing will happen. Returning FALSE will cause
861 GTK to emit the "destroy" signal which of course calls the "destroy"
862 callback, exiting GTK.</para>
863
864 </sect1>
865 </chapter>
866
867 <!-- ***************************************************************** -->
868 <chapter id="ch-MovingOn">
869 <title>Moving On</title>
870
871 <!-- ----------------------------------------------------------------- -->
872 <sect1 id="sec-DataTypes">
873 <title>Data Types</title>
874
875 <para>There are a few things you probably noticed in the previous examples
876 that need explaining. The gint, gchar, etc. that you see are typedefs
877 to int and char, respectively, that are part of the GLlib system. This
878 is done to get around that nasty dependency on the size of simple data
879 types when doing calculations.</para>
880
881 <para>A good example is "gint32" which will be typedef'd to a 32 bit integer
882 for any given platform, whether it be the 64 bit alpha, or the 32 bit
883 i386. The typedefs are very straightforward and intuitive. They are
884 all defined in glib/glib.h (which gets included from gtk.h).</para>
885
886 <para>You'll also notice GTK's ability to use GtkWidget when the function
887 calls for an Object. GTK is an object oriented design, and a widget
888 is an object.</para>
889
890 </sect1>
891
892 <!-- ----------------------------------------------------------------- -->
893 <sect1 id="sec-MoreOnSignalHandlers">
894 <title>More on Signal Handlers</title>
895
896 <para>Lets take another look at the gtk_signal_connect declaration.</para>
897
898 <programlisting role="C">
899 gint gtk_signal_connect( GtkObject *object,
900                          gchar *name,
901                          GtkSignalFunc func,
902                          gpointer func_data );
903 </programlisting>
904
905 <para>Notice the gint return value? This is a tag that identifies your
906 callback function. As stated above, you may have as many callbacks per
907 signal and per object as you need, and each will be executed in turn,
908 in the order they were attached.</para>
909
910 <para>This tag allows you to remove this callback from the list by using:</para>
911
912 <programlisting role="C">
913 void gtk_signal_disconnect( GtkObject *object,
914                             gint id );
915 </programlisting>
916
917 <para>So, by passing in the widget you wish to remove the handler from, and
918 the tag returned by one of the signal_connect functions, you can
919 disconnect a signal handler.</para>
920
921 <para>You can also temporarily disable signal handlers with the
922 gtk_signal_handler_block() and gtk_signal_handler_unblock() family of
923 functions.</para>
924
925 <programlisting role="C">
926 void gtk_signal_handler_block( GtkObject *object,
927                                guint      handler_id );
928
929 void gtk_signal_handler_block_by_func( GtkObject     *object,
930                                        GtkSignalFunc  func,
931                                        gpointer       data );
932
933 void gtk_signal_handler_block_by_data( GtkObject *object,
934                                        gpointer   data );
935
936 void gtk_signal_handler_unblock( GtkObject *object,
937                                  guint      handler_id );
938
939 void gtk_signal_handler_unblock_by_func( GtkObject     *object,
940                                          GtkSignalFunc  func,
941                                          gpointer       data );
942
943 void gtk_signal_handler_unblock_by_data( GtkObject *object,
944                                          gpointer   data);
945 </programlisting>
946
947 </sect1>
948
949 <!-- ----------------------------------------------------------------- -->
950 <sect1 id="sec-AnUpgradedHelloWorld">
951 <title>An Upgraded Hello World</title>
952
953 <para>Let's take a look at a slightly improved <emphasis>helloworld</emphasis> with
954 better examples of callbacks. This will also introduce us to our next
955 topic, packing widgets.</para>
956
957 <programlisting role="C">
958 <!-- example-start helloworld2 helloworld2.c -->
959
960 #include &lt;gtk/gtk.h&gt;
961
962 /* Our new improved callback.  The data passed to this function
963  * is printed to stdout. */
964 void callback( GtkWidget *widget,
965                gpointer   data )
966 {
967     g_print ("Hello again - %s was pressed\n", (char *) data);
968 }
969
970 /* another callback */
971 gint delete_event( GtkWidget *widget,
972                    GdkEvent  *event,
973                    gpointer   data )
974 {
975     gtk_main_quit();
976     return(FALSE);
977 }
978
979 int main( int   argc,
980           char *argv[] )
981 {
982     /* GtkWidget is the storage type for widgets */
983     GtkWidget *window;
984     GtkWidget *button;
985     GtkWidget *box1;
986
987     /* This is called in all GTK applications. Arguments are parsed
988      * from the command line and are returned to the application. */
989     gtk_init (&amp;argc, &amp;argv);
990
991     /* Create a new window */
992     window = gtk_window_new (GTK_WINDOW_TOPLEVEL);
993
994     /* This is a new call, which just sets the title of our
995      * new window to "Hello Buttons!" */
996     gtk_window_set_title (GTK_WINDOW (window), "Hello Buttons!");
997
998     /* Here we just set a handler for delete_event that immediately
999      * exits GTK. */
1000     gtk_signal_connect (GTK_OBJECT (window), "delete_event",
1001                         GTK_SIGNAL_FUNC (delete_event), NULL);
1002
1003     /* Sets the border width of the window. */
1004     gtk_container_set_border_width (GTK_CONTAINER (window), 10);
1005
1006     /* We create a box to pack widgets into.  This is described in detail
1007      * in the "packing" section. The box is not really visible, it
1008      * is just used as a tool to arrange widgets. */
1009     box1 = gtk_hbox_new(FALSE, 0);
1010
1011     /* Put the box into the main window. */
1012     gtk_container_add (GTK_CONTAINER (window), box1);
1013
1014     /* Creates a new button with the label "Button 1". */
1015     button = gtk_button_new_with_label ("Button 1");
1016     
1017     /* Now when the button is clicked, we call the "callback" function
1018      * with a pointer to "button 1" as its argument */
1019     gtk_signal_connect (GTK_OBJECT (button), "clicked",
1020                         GTK_SIGNAL_FUNC (callback), (gpointer) "button 1");
1021
1022     /* Instead of gtk_container_add, we pack this button into the invisible
1023      * box, which has been packed into the window. */
1024     gtk_box_pack_start(GTK_BOX(box1), button, TRUE, TRUE, 0);
1025
1026     /* Always remember this step, this tells GTK that our preparation for
1027      * this button is complete, and it can now be displayed. */
1028     gtk_widget_show(button);
1029
1030     /* Do these same steps again to create a second button */
1031     button = gtk_button_new_with_label ("Button 2");
1032
1033     /* Call the same callback function with a different argument,
1034      * passing a pointer to "button 2" instead. */
1035     gtk_signal_connect (GTK_OBJECT (button), "clicked",
1036                         GTK_SIGNAL_FUNC (callback), (gpointer) "button 2");
1037
1038     gtk_box_pack_start(GTK_BOX(box1), button, TRUE, TRUE, 0);
1039
1040     /* The order in which we show the buttons is not really important, but I
1041      * recommend showing the window last, so it all pops up at once. */
1042     gtk_widget_show(button);
1043
1044     gtk_widget_show(box1);
1045
1046     gtk_widget_show (window);
1047     
1048     /* Rest in gtk_main and wait for the fun to begin! */
1049     gtk_main ();
1050
1051     return(0);
1052 }
1053 <!-- example-end -->
1054 </programlisting>
1055
1056 <para>Compile this program using the same linking arguments as our first
1057 example.  You'll notice this time there is no easy way to exit the
1058 program, you have to use your window manager or command line to kill
1059 it. A good exercise for the reader would be to insert a third "Quit"
1060 button that will exit the program. You may also wish to play with the
1061 options to gtk_box_pack_start() while reading the next section.  Try
1062 resizing the window, and observe the behavior.</para>
1063
1064 <para>Just as a side note, there is another useful define for
1065 gtk_window_new() - <literal>GTK_WINDOW_DIALOG</literal>. This interacts with the
1066 window manager a little differently and should be used for transient
1067 windows.</para>
1068
1069 </sect1>
1070 </chapter>
1071
1072 <!-- ***************************************************************** -->
1073 <chapter id="ch-PackingWidgets">
1074 <title>Packing Widgets</title>
1075
1076 <para>When creating an application, you'll want to put more than one widget
1077 inside a window. Our first <emphasis>helloworld</emphasis> example only used one
1078 widget so we could simply use a gtk_container_add call to "pack" the
1079 widget into the window. But when you want to put more than one widget
1080 into a window, how do you control where that widget is positioned?
1081 This is where packing comes in.</para>
1082
1083 <!-- ----------------------------------------------------------------- -->
1084 <sect1 id="sec-TheoryOfPackingBoxes">
1085 <title>Theory of Packing Boxes</title>
1086
1087 <para>Most packing is done by creating boxes. These
1088 are invisible widget containers that we can pack our widgets into
1089 which come in two forms, a horizontal box, and a vertical box. When
1090 packing widgets into a horizontal box, the objects are inserted
1091 horizontally from left to right or right to left depending on the call
1092 used. In a vertical box, widgets are packed from top to bottom or vice
1093 versa. You may use any combination of boxes inside or beside other
1094 boxes to create the desired effect.</para>
1095
1096 <para>To create a new horizontal box, we use a call to gtk_hbox_new(), and
1097 for vertical boxes, gtk_vbox_new(). The gtk_box_pack_start() and
1098 gtk_box_pack_end() functions are used to place objects inside of these
1099 containers. The gtk_box_pack_start() function will start at the top
1100 and work its way down in a vbox, and pack left to right in an hbox.
1101 gtk_box_pack_end() will do the opposite, packing from bottom to top in
1102 a vbox, and right to left in an hbox. Using these functions allows us
1103 to right justify or left justify our widgets and may be mixed in any
1104 way to achieve the desired effect. We will use gtk_box_pack_start() in
1105 most of our examples. An object may be another container or a
1106 widget. In fact, many widgets are actually containers themselves,
1107 including the button, but we usually only use a label inside a button.</para>
1108
1109 <para>By using these calls, GTK knows where you want to place your widgets
1110 so it can do automatic resizing and other nifty things. There are also
1111 a number of options as to how your widgets should be packed. As you
1112 can imagine, this method gives us a quite a bit of flexibility when
1113 placing and creating widgets.</para>
1114
1115 </sect1>
1116
1117 <!-- ----------------------------------------------------------------- -->
1118 <sect1 id="sec-DetailsOfBoxes">
1119 <title>Details of Boxes</title>
1120
1121 <para>Because of this flexibility, packing boxes in GTK can be confusing at
1122 first. There are a lot of options, and it's not immediately obvious how
1123 they all fit together. In the end, however, there are basically five
1124 different styles.</para>
1125
1126 <para>
1127 <inlinemediaobject>
1128 <imageobject>
1129 <imagedata fileref="gtk_tut_packbox1.jpg">
1130 </imageobject>
1131 </inlinemediaobject>
1132 </para>
1133
1134 <para>Each line contains one horizontal box (hbox) with several buttons. The
1135 call to gtk_box_pack is shorthand for the call to pack each of the
1136 buttons into the hbox. Each of the buttons is packed into the hbox the
1137 same way (i.e., same arguments to the gtk_box_pack_start() function).</para>
1138
1139 <para>This is the declaration of the gtk_box_pack_start function.</para>
1140
1141 <programlisting role="C">
1142 void gtk_box_pack_start( GtkBox    *box,
1143                          GtkWidget *child,
1144                          gint       expand,
1145                          gint       fill,
1146                          gint       padding );
1147 </programlisting>
1148
1149 <para>The first argument is the box you are packing the object into, the
1150 second is the object. The objects will all be buttons for now, so
1151 we'll be packing buttons into boxes.</para>
1152
1153 <para>The expand argument to gtk_box_pack_start() and gtk_box_pack_end()
1154 controls whether the widgets are laid out in the box to fill in all
1155 the extra space in the box so the box is expanded to fill the area
1156 allotted to it (TRUE); or the box is shrunk to just fit the widgets
1157 (FALSE). Setting expand to FALSE will allow you to do right and left
1158 justification of your widgets.  Otherwise, they will all expand to fit
1159 into the box, and the same effect could be achieved by using only one
1160 of gtk_box_pack_start or gtk_box_pack_end.</para>
1161
1162 <para>The fill argument to the gtk_box_pack functions control whether the
1163 extra space is allocated to the objects themselves (TRUE), or as extra
1164 padding in the box around these objects (FALSE). It only has an effect
1165 if the expand argument is also TRUE.</para>
1166
1167 <para>When creating a new box, the function looks like this:</para>
1168
1169 <programlisting role="C">
1170 GtkWidget *gtk_hbox_new (gint homogeneous,
1171                          gint spacing);
1172 </programlisting>
1173
1174 <para>The homogeneous argument to gtk_hbox_new (and the same for
1175 gtk_vbox_new) controls whether each object in the box has the same
1176 size (i.e., the same width in an hbox, or the same height in a
1177 vbox). If it is set, the gtk_box_pack routines function essentially
1178 as if the <literal>expand</literal> argument was always turned on.</para>
1179
1180 <para>What's the difference between spacing (set when the box is created)
1181 and padding (set when elements are packed)? Spacing is added between
1182 objects, and padding is added on either side of an object. The
1183 following figure should make it clearer:</para>
1184
1185 <para>
1186 <inlinemediaobject>
1187 <imageobject>
1188 <imagedata fileref="gtk_tut_packbox2.jpg">
1189 </imageobject>
1190 </inlinemediaobject>
1191 </para>
1192
1193 <para>Here is the code used to create the above images. I've commented it
1194 fairly heavily so I hope you won't have any problems following
1195 it. Compile it yourself and play with it.</para>
1196
1197 </sect1>
1198
1199 <!-- ----------------------------------------------------------------- -->
1200 <sect1 id="sec-PackingDemonstrationProgram">
1201 <title>Packing Demonstration Program</title>
1202
1203 <programlisting role="C">
1204 <!-- example-start packbox packbox.c -->
1205
1206 #include &lt;stdio.h&gt;
1207 #include &lt;stdlib.h&gt;
1208 #include "gtk/gtk.h"
1209
1210 gint delete_event( GtkWidget *widget,
1211                    GdkEvent  *event,
1212                    gpointer   data )
1213 {
1214     gtk_main_quit();
1215     return(FALSE);
1216 }
1217
1218 /* Make a new hbox filled with button-labels. Arguments for the 
1219  * variables we're interested are passed in to this function. 
1220  * We do not show the box, but do show everything inside. */
1221 GtkWidget *make_box( gint homogeneous,
1222                      gint spacing,
1223                      gint expand,
1224                      gint fill,
1225                      gint padding ) 
1226 {
1227     GtkWidget *box;
1228     GtkWidget *button;
1229     char padstr[80];
1230     
1231     /* Create a new hbox with the appropriate homogeneous
1232      * and spacing settings */
1233     box = gtk_hbox_new (homogeneous, spacing);
1234     
1235     /* Create a series of buttons with the appropriate settings */
1236     button = gtk_button_new_with_label ("gtk_box_pack");
1237     gtk_box_pack_start (GTK_BOX (box), button, expand, fill, padding);
1238     gtk_widget_show (button);
1239     
1240     button = gtk_button_new_with_label ("(box,");
1241     gtk_box_pack_start (GTK_BOX (box), button, expand, fill, padding);
1242     gtk_widget_show (button);
1243     
1244     button = gtk_button_new_with_label ("button,");
1245     gtk_box_pack_start (GTK_BOX (box), button, expand, fill, padding);
1246     gtk_widget_show (button);
1247     
1248     /* Create a button with the label depending on the value of
1249      * expand. */
1250     if (expand == TRUE)
1251             button = gtk_button_new_with_label ("TRUE,");
1252     else
1253             button = gtk_button_new_with_label ("FALSE,");
1254     
1255     gtk_box_pack_start (GTK_BOX (box), button, expand, fill, padding);
1256     gtk_widget_show (button);
1257     
1258     /* This is the same as the button creation for "expand"
1259      * above, but uses the shorthand form. */
1260     button = gtk_button_new_with_label (fill ? "TRUE," : "FALSE,");
1261     gtk_box_pack_start (GTK_BOX (box), button, expand, fill, padding);
1262     gtk_widget_show (button);
1263     
1264     sprintf (padstr, "%d);", padding);
1265     
1266     button = gtk_button_new_with_label (padstr);
1267     gtk_box_pack_start (GTK_BOX (box), button, expand, fill, padding);
1268     gtk_widget_show (button);
1269     
1270     return box;
1271 }
1272
1273 int main( int   argc,
1274           char *argv[]) 
1275 {
1276     GtkWidget *window;
1277     GtkWidget *button;
1278     GtkWidget *box1;
1279     GtkWidget *box2;
1280     GtkWidget *separator;
1281     GtkWidget *label;
1282     GtkWidget *quitbox;
1283     int which;
1284     
1285     /* Our init, don't forget this! :) */
1286     gtk_init (&amp;argc, &amp;argv);
1287     
1288     if (argc != 2) {
1289         fprintf (stderr, "usage: packbox num, where num is 1, 2, or 3.\n");
1290         /* This just does cleanup in GTK and exits with an exit status of 1. */
1291         gtk_exit (1);
1292     }
1293     
1294     which = atoi (argv[1]);
1295
1296     /* Create our window */
1297     window = gtk_window_new (GTK_WINDOW_TOPLEVEL);
1298
1299     /* You should always remember to connect the delete_event signal
1300      * to the main window. This is very important for proper intuitive
1301      * behavior */
1302     gtk_signal_connect (GTK_OBJECT (window), "delete_event",
1303                         GTK_SIGNAL_FUNC (delete_event), NULL);
1304     gtk_container_set_border_width (GTK_CONTAINER (window), 10);
1305     
1306     /* We create a vertical box (vbox) to pack the horizontal boxes into.
1307      * This allows us to stack the horizontal boxes filled with buttons one
1308      * on top of the other in this vbox. */
1309     box1 = gtk_vbox_new (FALSE, 0);
1310     
1311     /* which example to show. These correspond to the pictures above. */
1312     switch (which) {
1313     case 1:
1314         /* create a new label. */
1315         label = gtk_label_new ("gtk_hbox_new (FALSE, 0);");
1316         
1317         /* Align the label to the left side.  We'll discuss this function and 
1318          * others in the section on Widget Attributes. */
1319         gtk_misc_set_alignment (GTK_MISC (label), 0, 0);
1320
1321         /* Pack the label into the vertical box (vbox box1).  Remember that 
1322          * widgets added to a vbox will be packed one on top of the other in
1323          * order. */
1324         gtk_box_pack_start (GTK_BOX (box1), label, FALSE, FALSE, 0);
1325         
1326         /* Show the label */
1327         gtk_widget_show (label);
1328         
1329         /* Call our make box function - homogeneous = FALSE, spacing = 0,
1330          * expand = FALSE, fill = FALSE, padding = 0 */
1331         box2 = make_box (FALSE, 0, FALSE, FALSE, 0);
1332         gtk_box_pack_start (GTK_BOX (box1), box2, FALSE, FALSE, 0);
1333         gtk_widget_show (box2);
1334
1335         /* Call our make box function - homogeneous = FALSE, spacing = 0,
1336          * expand = TRUE, fill = FALSE, padding = 0 */
1337         box2 = make_box (FALSE, 0, TRUE, FALSE, 0);
1338         gtk_box_pack_start (GTK_BOX (box1), box2, FALSE, FALSE, 0);
1339         gtk_widget_show (box2);
1340         
1341         /* Args are: homogeneous, spacing, expand, fill, padding */
1342         box2 = make_box (FALSE, 0, TRUE, TRUE, 0);
1343         gtk_box_pack_start (GTK_BOX (box1), box2, FALSE, FALSE, 0);
1344         gtk_widget_show (box2);
1345         
1346         /* Creates a separator, we'll learn more about these later, 
1347          * but they are quite simple. */
1348         separator = gtk_hseparator_new ();
1349         
1350         /* Pack the separator into the vbox. Remember each of these
1351          * widgets is being packed into a vbox, so they'll be stacked
1352          * vertically. */
1353         gtk_box_pack_start (GTK_BOX (box1), separator, FALSE, TRUE, 5);
1354         gtk_widget_show (separator);
1355         
1356         /* Create another new label, and show it. */
1357         label = gtk_label_new ("gtk_hbox_new (TRUE, 0);");
1358         gtk_misc_set_alignment (GTK_MISC (label), 0, 0);
1359         gtk_box_pack_start (GTK_BOX (box1), label, FALSE, FALSE, 0);
1360         gtk_widget_show (label);
1361         
1362         /* Args are: homogeneous, spacing, expand, fill, padding */
1363         box2 = make_box (TRUE, 0, TRUE, FALSE, 0);
1364         gtk_box_pack_start (GTK_BOX (box1), box2, FALSE, FALSE, 0);
1365         gtk_widget_show (box2);
1366         
1367         /* Args are: homogeneous, spacing, expand, fill, padding */
1368         box2 = make_box (TRUE, 0, TRUE, TRUE, 0);
1369         gtk_box_pack_start (GTK_BOX (box1), box2, FALSE, FALSE, 0);
1370         gtk_widget_show (box2);
1371         
1372         /* Another new separator. */
1373         separator = gtk_hseparator_new ();
1374         /* The last 3 arguments to gtk_box_pack_start are:
1375          * expand, fill, padding. */
1376         gtk_box_pack_start (GTK_BOX (box1), separator, FALSE, TRUE, 5);
1377         gtk_widget_show (separator);
1378         
1379         break;
1380
1381     case 2:
1382
1383         /* Create a new label, remember box1 is a vbox as created 
1384          * near the beginning of main() */
1385         label = gtk_label_new ("gtk_hbox_new (FALSE, 10);");
1386         gtk_misc_set_alignment (GTK_MISC (label), 0, 0);
1387         gtk_box_pack_start (GTK_BOX (box1), label, FALSE, FALSE, 0);
1388         gtk_widget_show (label);
1389         
1390         /* Args are: homogeneous, spacing, expand, fill, padding */
1391         box2 = make_box (FALSE, 10, TRUE, FALSE, 0);
1392         gtk_box_pack_start (GTK_BOX (box1), box2, FALSE, FALSE, 0);
1393         gtk_widget_show (box2);
1394         
1395         /* Args are: homogeneous, spacing, expand, fill, padding */
1396         box2 = make_box (FALSE, 10, TRUE, TRUE, 0);
1397         gtk_box_pack_start (GTK_BOX (box1), box2, FALSE, FALSE, 0);
1398         gtk_widget_show (box2);
1399         
1400         separator = gtk_hseparator_new ();
1401         /* The last 3 arguments to gtk_box_pack_start are:
1402          * expand, fill, padding. */
1403         gtk_box_pack_start (GTK_BOX (box1), separator, FALSE, TRUE, 5);
1404         gtk_widget_show (separator);
1405         
1406         label = gtk_label_new ("gtk_hbox_new (FALSE, 0);");
1407         gtk_misc_set_alignment (GTK_MISC (label), 0, 0);
1408         gtk_box_pack_start (GTK_BOX (box1), label, FALSE, FALSE, 0);
1409         gtk_widget_show (label);
1410         
1411         /* Args are: homogeneous, spacing, expand, fill, padding */
1412         box2 = make_box (FALSE, 0, TRUE, FALSE, 10);
1413         gtk_box_pack_start (GTK_BOX (box1), box2, FALSE, FALSE, 0);
1414         gtk_widget_show (box2);
1415         
1416         /* Args are: homogeneous, spacing, expand, fill, padding */
1417         box2 = make_box (FALSE, 0, TRUE, TRUE, 10);
1418         gtk_box_pack_start (GTK_BOX (box1), box2, FALSE, FALSE, 0);
1419         gtk_widget_show (box2);
1420         
1421         separator = gtk_hseparator_new ();
1422         /* The last 3 arguments to gtk_box_pack_start are: expand, fill, padding. */
1423         gtk_box_pack_start (GTK_BOX (box1), separator, FALSE, TRUE, 5);
1424         gtk_widget_show (separator);
1425         break;
1426     
1427     case 3:
1428
1429         /* This demonstrates the ability to use gtk_box_pack_end() to
1430          * right justify widgets. First, we create a new box as before. */
1431         box2 = make_box (FALSE, 0, FALSE, FALSE, 0);
1432
1433         /* Create the label that will be put at the end. */
1434         label = gtk_label_new ("end");
1435         /* Pack it using gtk_box_pack_end(), so it is put on the right
1436          * side of the hbox created in the make_box() call. */
1437         gtk_box_pack_end (GTK_BOX (box2), label, FALSE, FALSE, 0);
1438         /* Show the label. */
1439         gtk_widget_show (label);
1440         
1441         /* Pack box2 into box1 (the vbox remember ? :) */
1442         gtk_box_pack_start (GTK_BOX (box1), box2, FALSE, FALSE, 0);
1443         gtk_widget_show (box2);
1444         
1445         /* A separator for the bottom. */
1446         separator = gtk_hseparator_new ();
1447         /* This explicitly sets the separator to 400 pixels wide by 5 pixels
1448          * high. This is so the hbox we created will also be 400 pixels wide,
1449          * and the "end" label will be separated from the other labels in the
1450          * hbox. Otherwise, all the widgets in the hbox would be packed as
1451          * close together as possible. */
1452         gtk_widget_set_usize (separator, 400, 5);
1453         /* pack the separator into the vbox (box1) created near the start 
1454          * of main() */
1455         gtk_box_pack_start (GTK_BOX (box1), separator, FALSE, TRUE, 5);
1456         gtk_widget_show (separator);    
1457     }
1458     
1459     /* Create another new hbox.. remember we can use as many as we need! */
1460     quitbox = gtk_hbox_new (FALSE, 0);
1461     
1462     /* Our quit button. */
1463     button = gtk_button_new_with_label ("Quit");
1464     
1465     /* Setup the signal to terminate the program when the button is clicked */
1466     gtk_signal_connect_object (GTK_OBJECT (button), "clicked",
1467                                GTK_SIGNAL_FUNC (gtk_main_quit),
1468                                GTK_OBJECT (window));
1469     /* Pack the button into the quitbox.
1470      * The last 3 arguments to gtk_box_pack_start are:
1471      * expand, fill, padding. */
1472     gtk_box_pack_start (GTK_BOX (quitbox), button, TRUE, FALSE, 0);
1473     /* pack the quitbox into the vbox (box1) */
1474     gtk_box_pack_start (GTK_BOX (box1), quitbox, FALSE, FALSE, 0);
1475     
1476     /* Pack the vbox (box1) which now contains all our widgets, into the
1477      * main window. */
1478     gtk_container_add (GTK_CONTAINER (window), box1);
1479     
1480     /* And show everything left */
1481     gtk_widget_show (button);
1482     gtk_widget_show (quitbox);
1483     
1484     gtk_widget_show (box1);
1485     /* Showing the window last so everything pops up at once. */
1486     gtk_widget_show (window);
1487     
1488     /* And of course, our main function. */
1489     gtk_main ();
1490
1491     /* Control returns here when gtk_main_quit() is called, but not when 
1492      * gtk_exit is used. */
1493     
1494     return(0);
1495 }
1496 <!-- example-end -->
1497 </programlisting>
1498
1499 </sect1>
1500
1501 <!-- ----------------------------------------------------------------- -->
1502 <sect1 id="sec-PackingUsingTables">
1503 <title>Packing Using Tables</title>
1504
1505 <para>Let's take a look at another way of packing - Tables. These can be
1506 extremely useful in certain situations.</para>
1507
1508 <para>Using tables, we create a grid that we can place widgets in. The
1509 widgets may take up as many spaces as we specify.</para>
1510
1511 <para>The first thing to look at, of course, is the gtk_table_new function:</para>
1512
1513 <programlisting role="C">
1514 GtkWidget *gtk_table_new( gint rows,
1515                           gint columns,
1516                           gint homogeneous );
1517 </programlisting>
1518
1519 <para>The first argument is the number of rows to make in the table, while
1520 the second, obviously, is the number of columns.</para>
1521
1522 <para>The homogeneous argument has to do with how the table's boxes are
1523 sized. If homogeneous is TRUE, the table boxes are resized to the size
1524 of the largest widget in the table. If homogeneous is FALSE, the size
1525 of a table boxes is dictated by the tallest widget in its same row,
1526 and the widest widget in its column.</para>
1527
1528 <para>The rows and columns are laid out from 0 to n, where n was the number
1529 specified in the call to gtk_table_new. So, if you specify rows = 2
1530 and columns = 2, the layout would look something like this:</para>
1531
1532 <programlisting role="C">
1533  0          1          2
1534 0+----------+----------+
1535  |          |          |
1536 1+----------+----------+
1537  |          |          |
1538 2+----------+----------+
1539 </programlisting>
1540
1541 <para>Note that the coordinate system starts in the upper left hand corner.
1542 To place a widget into a box, use the following function:</para>
1543
1544 <programlisting role="C">
1545 void gtk_table_attach( GtkTable  *table,
1546                        GtkWidget *child,
1547                        gint       left_attach,
1548                        gint       right_attach,
1549                        gint       top_attach,
1550                        gint       bottom_attach,
1551                        gint       xoptions,
1552                        gint       yoptions,
1553                        gint       xpadding,
1554                        gint       ypadding );
1555 </programlisting>
1556
1557 <para>The first argument ("table") is the table you've created and the
1558 second ("child") the widget you wish to place in the table.</para>
1559
1560 <para>The left and right attach arguments specify where to place the widget,
1561 and how many boxes to use. If you want a button in the lower right
1562 table entry of our 2x2 table, and want it to fill that entry ONLY,
1563 left_attach would be = 1, right_attach = 2, top_attach = 1,
1564 bottom_attach = 2.</para>
1565
1566 <para>Now, if you wanted a widget to take up the whole top row of our 2x2
1567 table, you'd use left_attach = 0, right_attach = 2, top_attach = 0,
1568 bottom_attach = 1.</para>
1569
1570 <para>The xoptions and yoptions are used to specify packing options and may
1571 be bitwise OR'ed together to allow multiple options.</para>
1572
1573 <para>These options are:</para>
1574
1575 <itemizedlist>
1576 <listitem><simpara><literal>GTK_FILL</literal> - If the table box is larger than the widget, and
1577 <literal>GTK_FILL</literal> is specified, the widget will expand to use all the room
1578 available.</simpara>
1579 </listitem>
1580
1581 <listitem><simpara><literal>GTK_SHRINK</literal> - If the table widget was allocated less space
1582 then was requested (usually by the user resizing the window), then the
1583 widgets would normally just be pushed off the bottom of the window and
1584 disappear. If <literal>GTK_SHRINK</literal> is specified, the widgets will shrink
1585 with the table.</simpara>
1586 </listitem>
1587
1588 <listitem><simpara><literal>GTK_EXPAND</literal> - This will cause the table to expand to use up
1589 any remaining space in the window.</simpara>
1590 </listitem>
1591 </itemizedlist>
1592
1593 <para>Padding is just like in boxes, creating a clear area around the widget
1594 specified in pixels.</para>
1595
1596 <para>gtk_table_attach() has a LOT of options.  So, there's a shortcut:</para>
1597
1598 <programlisting role="C">
1599 void gtk_table_attach_defaults( GtkTable  *table,
1600                                 GtkWidget *widget,
1601                                 gint       left_attach,
1602                                 gint       right_attach,
1603                                 gint       top_attach,
1604                                 gint       bottom_attach );
1605 </programlisting>
1606
1607 <para>The X and Y options default to <literal>GTK_FILL | GTK_EXPAND</literal>, and X and Y
1608 padding are set to 0. The rest of the arguments are identical to the
1609 previous function.</para>
1610
1611 <para>We also have gtk_table_set_row_spacing() and
1612 gtk_table_set_col_spacing(). These places spacing between the rows at
1613 the specified row or column.</para>
1614
1615 <programlisting role="C">
1616 void gtk_table_set_row_spacing( GtkTable *table,
1617                                 gint      row,
1618                                 gint      spacing );
1619 </programlisting>
1620
1621 <para>and</para>
1622
1623 <programlisting role="C">
1624 void gtk_table_set_col_spacing ( GtkTable *table,
1625                                  gint      column,
1626                                  gint      spacing );
1627 </programlisting>
1628
1629 <para>Note that for columns, the space goes to the right of the column, and
1630 for rows, the space goes below the row.</para>
1631
1632 <para>You can also set a consistent spacing of all rows and/or columns with:</para>
1633
1634 <programlisting role="C">
1635 void gtk_table_set_row_spacings( GtkTable *table,
1636                                  gint      spacing );
1637 </programlisting>
1638
1639 <para>And,</para>
1640
1641 <programlisting role="C">
1642 void gtk_table_set_col_spacings( GtkTable *table,
1643                                  gint      spacing );
1644 </programlisting>
1645
1646 <para>Note that with these calls, the last row and last column do not get
1647 any spacing.</para>
1648
1649 </sect1>
1650
1651 <!-- ----------------------------------------------------------------- -->
1652 <sect1 id="sec-TablePackingExamples">
1653 <title>Table Packing Example</title>
1654
1655 <para>Here we make a window with three buttons in a 2x2 table.
1656 The first two buttons will be placed in the upper row.
1657 A third, quit button, is placed in the lower row, spanning both columns.
1658 Which means it should look something like this:</para>
1659
1660 <para>
1661 <inlinemediaobject>
1662 <imageobject>
1663 <imagedata fileref="gtk_tut_table.jpg">
1664 </imageobject>
1665 </inlinemediaobject>
1666 </para>
1667
1668 <para>Here's the source code:</para>
1669
1670 <programlisting role="C">
1671 <!-- example-start table table.c -->
1672
1673 #include &lt;gtk/gtk.h&gt;
1674
1675 /* Our callback.
1676  * The data passed to this function is printed to stdout */
1677 void callback( GtkWidget *widget,
1678                gpointer   data )
1679 {
1680     g_print ("Hello again - %s was pressed\n", (char *) data);
1681 }
1682
1683 /* This callback quits the program */
1684 gint delete_event( GtkWidget *widget,
1685                    GdkEvent  *event,
1686                    gpointer   data )
1687 {
1688     gtk_main_quit ();
1689     return(FALSE);
1690 }
1691
1692 int main( int   argc,
1693           char *argv[] )
1694 {
1695     GtkWidget *window;
1696     GtkWidget *button;
1697     GtkWidget *table;
1698
1699     gtk_init (&amp;argc, &amp;argv);
1700
1701     /* Create a new window */
1702     window = gtk_window_new (GTK_WINDOW_TOPLEVEL);
1703
1704     /* Set the window title */
1705     gtk_window_set_title (GTK_WINDOW (window), "Table");
1706
1707     /* Set a handler for delete_event that immediately
1708      * exits GTK. */
1709     gtk_signal_connect (GTK_OBJECT (window), "delete_event",
1710                         GTK_SIGNAL_FUNC (delete_event), NULL);
1711
1712     /* Sets the border width of the window. */
1713     gtk_container_set_border_width (GTK_CONTAINER (window), 20);
1714
1715     /* Create a 2x2 table */
1716     table = gtk_table_new (2, 2, TRUE);
1717
1718     /* Put the table in the main window */
1719     gtk_container_add (GTK_CONTAINER (window), table);
1720
1721     /* Create first button */
1722     button = gtk_button_new_with_label ("button 1");
1723
1724     /* When the button is clicked, we call the "callback" function
1725      * with a pointer to "button 1" as its argument */
1726     gtk_signal_connect (GTK_OBJECT (button), "clicked",
1727               GTK_SIGNAL_FUNC (callback), (gpointer) "button 1");
1728
1729
1730     /* Insert button 1 into the upper left quadrant of the table */
1731     gtk_table_attach_defaults (GTK_TABLE(table), button, 0, 1, 0, 1);
1732
1733     gtk_widget_show (button);
1734
1735     /* Create second button */
1736
1737     button = gtk_button_new_with_label ("button 2");
1738
1739     /* When the button is clicked, we call the "callback" function
1740      * with a pointer to "button 2" as its argument */
1741     gtk_signal_connect (GTK_OBJECT (button), "clicked",
1742               GTK_SIGNAL_FUNC (callback), (gpointer) "button 2");
1743     /* Insert button 2 into the upper right quadrant of the table */
1744     gtk_table_attach_defaults (GTK_TABLE(table), button, 1, 2, 0, 1);
1745
1746     gtk_widget_show (button);
1747
1748     /* Create "Quit" button */
1749     button = gtk_button_new_with_label ("Quit");
1750
1751     /* When the button is clicked, we call the "delete_event" function
1752      * and the program exits */
1753     gtk_signal_connect (GTK_OBJECT (button), "clicked",
1754                         GTK_SIGNAL_FUNC (delete_event), NULL);
1755
1756     /* Insert the quit button into the both 
1757      * lower quadrants of the table */
1758     gtk_table_attach_defaults (GTK_TABLE(table), button, 0, 2, 1, 2);
1759
1760     gtk_widget_show (button);
1761
1762     gtk_widget_show (table);
1763     gtk_widget_show (window);
1764
1765     gtk_main ();
1766
1767     return 0;
1768 }
1769 <!-- example-end -->
1770 </programlisting>
1771
1772 </sect1>
1773 </chapter>
1774
1775 <!-- ***************************************************************** -->
1776 <chapter id="ch-WidgetOverview">
1777 <title>Widget Overview</title>
1778
1779 <para>The general steps to creating a widget in GTK are:</para>
1780 <orderedlist>
1781 <listitem><simpara> gtk_*_new - one of various functions to create a new widget.
1782 These are all detailed in this section.</simpara>
1783 </listitem>
1784
1785 <listitem><simpara> Connect all signals and events we wish to use to the
1786 appropriate handlers.</simpara>
1787 </listitem>
1788
1789 <listitem><simpara> Set the attributes of the widget.</simpara>
1790 </listitem>
1791
1792 <listitem><simpara> Pack the widget into a container using the appropriate call
1793 such as gtk_container_add() or gtk_box_pack_start().</simpara>
1794 </listitem>
1795
1796 <listitem><simpara> gtk_widget_show() the widget.</simpara>
1797 </listitem>
1798 </orderedlist>
1799
1800 <para>gtk_widget_show() lets GTK know that we are done setting the
1801 attributes of the widget, and it is ready to be displayed. You may
1802 also use gtk_widget_hide to make it disappear again. The order in
1803 which you show the widgets is not important, but I suggest showing the
1804 window last so the whole window pops up at once rather than seeing the
1805 individual widgets come up on the screen as they're formed. The
1806 children of a widget (a window is a widget too) will not be displayed
1807 until the window itself is shown using the gtk_widget_show() function.</para>
1808
1809 <!-- ----------------------------------------------------------------- -->
1810 <sect1 id="sec-Casting">
1811 <title>Casting</title>
1812
1813 <para>You'll notice as you go on that GTK uses a type casting system. This
1814 is always done using macros that both test the ability to cast the
1815 given item, and perform the cast. Some common ones you will see are:</para>
1816
1817 <programlisting role="C">
1818   GTK_WIDGET(widget)
1819   GTK_OBJECT(object)
1820   GTK_SIGNAL_FUNC(function)
1821   GTK_CONTAINER(container)
1822   GTK_WINDOW(window)
1823   GTK_BOX(box)
1824 </programlisting>
1825
1826 <para>These are all used to cast arguments in functions. You'll see them in the
1827 examples, and can usually tell when to use them simply by looking at the
1828 function's declaration.</para>
1829
1830 <para>As you can see below in the class hierarchy, all GtkWidgets are
1831 derived from the Object base class. This means you can use a widget
1832 in any place the function asks for an object - simply use the
1833 <literal>GTK_OBJECT()</literal> macro.</para>
1834
1835 <para>For example:</para>
1836
1837 <programlisting role="C">
1838 gtk_signal_connect( GTK_OBJECT(button), "clicked",
1839                     GTK_SIGNAL_FUNC(callback_function), callback_data);
1840 </programlisting>
1841
1842 <para>This casts the button into an object, and provides a cast for the
1843 function pointer to the callback.</para>
1844
1845 <para>Many widgets are also containers. If you look in the class hierarchy
1846 below, you'll notice that many widgets derive from the Container
1847 class. Any one of these widgets may be used with the
1848 <literal>GTK_CONTAINER</literal> macro to pass them to functions that ask for
1849 containers.</para>
1850
1851 <para>Unfortunately, these macros are not extensively covered in the
1852 tutorial, but I recommend taking a look through the GTK header
1853 files. It can be very educational. In fact, it's not difficult to
1854 learn how a widget works just by looking at the function declarations.</para>
1855
1856 </sect1>
1857
1858 <!-- ----------------------------------------------------------------- -->
1859 <sect1 id="sec-WidgetHierarchy">
1860 <title>Widget Hierarchy</title>
1861
1862 <para>For your reference, here is the class hierarchy tree used to implement widgets.</para>
1863
1864 <programlisting role="C">
1865  GtkObject
1866   +GtkWidget
1867   | +GtkMisc
1868   | | +GtkLabel
1869   | | | +GtkAccelLabel
1870   | | | `GtkTipsQuery
1871   | | +GtkArrow
1872   | | +GtkImage
1873   | | `GtkPixmap
1874   | +GtkContainer
1875   | | +GtkBin
1876   | | | +GtkAlignment
1877   | | | +GtkFrame
1878   | | | | `GtkAspectFrame
1879   | | | +GtkButton
1880   | | | | +GtkToggleButton
1881   | | | | | `GtkCheckButton
1882   | | | | |   `GtkRadioButton
1883   | | | | `GtkOptionMenu
1884   | | | +GtkItem
1885   | | | | +GtkMenuItem
1886   | | | | | +GtkCheckMenuItem
1887   | | | | | | `GtkRadioMenuItem
1888   | | | | | `GtkTearoffMenuItem
1889   | | | | +GtkListItem
1890   | | | | `GtkTreeItem
1891   | | | +GtkWindow
1892   | | | | +GtkColorSelectionDialog
1893   | | | | +GtkDialog
1894   | | | | | `GtkInputDialog
1895   | | | | +GtkDrawWindow
1896   | | | | +GtkFileSelection
1897   | | | | +GtkFontSelectionDialog
1898   | | | | `GtkPlug
1899   | | | +GtkEventBox
1900   | | | +GtkHandleBox
1901   | | | +GtkScrolledWindow
1902   | | | `GtkViewport
1903   | | +GtkBox
1904   | | | +GtkButtonBox
1905   | | | | +GtkHButtonBox
1906   | | | | `GtkVButtonBox
1907   | | | +GtkVBox
1908   | | | | +GtkColorSelection
1909   | | | | `GtkGammaCurve
1910   | | | `GtkHBox
1911   | | |   +GtkCombo
1912   | | |   `GtkStatusbar
1913   | | +GtkCList
1914   | | | `GtkCTree
1915   | | +GtkFixed
1916   | | +GtkNotebook
1917   | | | `GtkFontSelection
1918   | | +GtkPaned
1919   | | | +GtkHPaned
1920   | | | `GtkVPaned
1921   | | +GtkLayout
1922   | | +GtkList
1923   | | +GtkMenuShell
1924   | | | +GtkMenuBar
1925   | | | `GtkMenu
1926   | | +GtkSocket
1927   | | +GtkTable
1928   | | +GtkToolbar
1929   | | `GtkTree
1930   | +GtkCalendar
1931   | +GtkDrawingArea
1932   | | `GtkCurve
1933   | +GtkEditable
1934   | | +GtkEntry
1935   | | | `GtkSpinButton
1936   | | `GtkText
1937   | +GtkRuler
1938   | | +GtkHRuler
1939   | | `GtkVRuler
1940   | +GtkRange
1941   | | +GtkScale
1942   | | | +GtkHScale
1943   | | | `GtkVScale
1944   | | `GtkScrollbar
1945   | |   +GtkHScrollbar
1946   | |   `GtkVScrollbar
1947   | +GtkSeparator
1948   | | +GtkHSeparator
1949   | | `GtkVSeparator
1950   | +GtkPreview
1951   | `GtkProgress
1952   |   `GtkProgressBar
1953   +GtkData
1954   | +GtkAdjustment
1955   | `GtkTooltips
1956   `GtkItemFactory
1957 </programlisting>
1958
1959 </sect1>
1960
1961 <!-- ----------------------------------------------------------------- -->
1962 <sect1 id="sec-WidgetsWithoutWindows">
1963 <title>Widgets Without Windows</title>
1964
1965 <para>The following widgets do not have an associated window. If you want to
1966 capture events, you'll have to use the EventBox. See the section on
1967 the <link linkend="sec-EventBox">EventBox</link> widget.</para>
1968
1969 <programlisting role="C">
1970 GtkAlignment
1971 GtkArrow
1972 GtkBin
1973 GtkBox
1974 GtkImage
1975 GtkItem
1976 GtkLabel
1977 GtkPixmap
1978 GtkScrolledWindow
1979 GtkSeparator
1980 GtkTable
1981 GtkAspectFrame
1982 GtkFrame
1983 GtkVBox
1984 GtkHBox
1985 GtkVSeparator
1986 GtkHSeparator
1987 </programlisting>
1988
1989 <para>We'll further our exploration of GTK by examining each widget in turn,
1990 creating a few simple functions to display them. Another good source
1991 is the testgtk.c program that comes with GTK. It can be found in
1992 gtk/testgtk.c.</para>
1993
1994 </sect1>
1995 </chapter>
1996
1997 <!-- ***************************************************************** -->
1998 <chapter id="ch-ButtonWidget">
1999 <title>The Button Widget</title>
2000
2001 <!-- ----------------------------------------------------------------- -->
2002 <sect1 id="sec-NormalButtons">
2003 <title>Normal Buttons</title>
2004
2005 <para>We've almost seen all there is to see of the button widget. It's
2006 pretty simple. There are however two ways to create a button. You can
2007 use the gtk_button_new_with_label() to create a button with a label,
2008 or use gtk_button_new() to create a blank button. It's then up to you
2009 to pack a label or pixmap into this new button. To do this, create a
2010 new box, and then pack your objects into this box using the usual
2011 gtk_box_pack_start, and then use gtk_container_add to pack the box
2012 into the button.</para>
2013
2014 <para>Here's an example of using gtk_button_new to create a button with a
2015 picture and a label in it. I've broken up the code to create a box
2016 from the rest so you can use it in your programs. There are further
2017 examples of using pixmaps later in the tutorial.</para>
2018
2019 <programlisting role="C">
2020 <!-- example-start buttons buttons.c -->
2021
2022 #include &lt;gtk/gtk.h&gt;
2023
2024 /* Create a new hbox with an image and a label packed into it
2025  * and return the box. */
2026
2027 GtkWidget *xpm_label_box( GtkWidget *parent,
2028                           gchar     *xpm_filename,
2029                           gchar     *label_text )
2030 {
2031     GtkWidget *box1;
2032     GtkWidget *label;
2033     GtkWidget *pixmapwid;
2034     GdkPixmap *pixmap;
2035     GdkBitmap *mask;
2036     GtkStyle *style;
2037
2038     /* Create box for xpm and label */
2039     box1 = gtk_hbox_new (FALSE, 0);
2040     gtk_container_set_border_width (GTK_CONTAINER (box1), 2);
2041
2042     /* Get the style of the button to get the
2043      * background color. */
2044     style = gtk_widget_get_style(parent);
2045
2046     /* Now on to the xpm stuff */
2047     pixmap = gdk_pixmap_create_from_xpm (parent->window, &amp;mask,
2048                                          &amp;style->bg[GTK_STATE_NORMAL],
2049                                          xpm_filename);
2050     pixmapwid = gtk_pixmap_new (pixmap, mask);
2051
2052     /* Create a label for the button */
2053     label = gtk_label_new (label_text);
2054
2055     /* Pack the pixmap and label into the box */
2056     gtk_box_pack_start (GTK_BOX (box1),
2057                         pixmapwid, FALSE, FALSE, 3);
2058
2059     gtk_box_pack_start (GTK_BOX (box1), label, FALSE, FALSE, 3);
2060
2061     gtk_widget_show(pixmapwid);
2062     gtk_widget_show(label);
2063
2064     return(box1);
2065 }
2066
2067 /* Our usual callback function */
2068 void callback( GtkWidget *widget,
2069                gpointer   data )
2070 {
2071     g_print ("Hello again - %s was pressed\n", (char *) data);
2072 }
2073
2074 int main( int   argc,
2075           char *argv[] )
2076 {
2077     /* GtkWidget is the storage type for widgets */
2078     GtkWidget *window;
2079     GtkWidget *button;
2080     GtkWidget *box1;
2081
2082     gtk_init (&amp;argc, &amp;argv);
2083
2084     /* Create a new window */
2085     window = gtk_window_new (GTK_WINDOW_TOPLEVEL);
2086
2087     gtk_window_set_title (GTK_WINDOW (window), "Pixmap'd Buttons!");
2088
2089     /* It's a good idea to do this for all windows. */
2090     gtk_signal_connect (GTK_OBJECT (window), "destroy",
2091                         GTK_SIGNAL_FUNC (gtk_exit), NULL);
2092
2093     gtk_signal_connect (GTK_OBJECT (window), "delete_event",
2094                         GTK_SIGNAL_FUNC (gtk_exit), NULL);
2095
2096     /* Sets the border width of the window. */
2097     gtk_container_set_border_width (GTK_CONTAINER (window), 10);
2098     gtk_widget_realize(window);
2099
2100     /* Create a new button */
2101     button = gtk_button_new ();
2102
2103     /* Connect the "clicked" signal of the button to our callback */
2104     gtk_signal_connect (GTK_OBJECT (button), "clicked",
2105                         GTK_SIGNAL_FUNC (callback), (gpointer) "cool button");
2106
2107     /* This calls our box creating function */
2108     box1 = xpm_label_box(window, "info.xpm", "cool button");
2109
2110     /* Pack and show all our widgets */
2111     gtk_widget_show(box1);
2112
2113     gtk_container_add (GTK_CONTAINER (button), box1);
2114
2115     gtk_widget_show(button);
2116
2117     gtk_container_add (GTK_CONTAINER (window), button);
2118
2119     gtk_widget_show (window);
2120
2121     /* Rest in gtk_main and wait for the fun to begin! */
2122     gtk_main ();
2123
2124     return(0);
2125 }
2126 <!-- example-end -->
2127 </programlisting>
2128
2129 <para>The xpm_label_box function could be used to pack xpm's and labels into
2130 any widget that can be a container.</para>
2131
2132 <para>Notice in <literal>xpm_label_box</literal> how there is a call to
2133 <literal>gtk_widget_get_style</literal>. Every widget has a "style", consisting of
2134 foreground and background colors for a variety of situations, font
2135 selection, and other graphics data relevant to a widget. These style
2136 values are defaulted in each widget, and are required by many GDK
2137 function calls, such as <literal>gdk_pixmap_create_from_xpm</literal>, which here is
2138 given the "normal" background color. The style data of widgets may
2139 be customized, using <link linkend="ch-GTKRCFiles">GTK's rc files</link>.</para>
2140
2141 <para>Also notice the call to <literal>gtk_widget_realize</literal> after setting the
2142 window's border width. This function uses GDK to create the X
2143 windows related to the widget. The function is automatically called
2144 when you invoke <literal>gtk_widget_show</literal> for a widget, and so has not been
2145 shown in earlier examples. But the call to
2146 <literal>gdk_pixmap_create_from_xpm</literal> requires that its <literal>window</literal> argument
2147 refer to a real X window, so it is necessary to realize the widget
2148 before this GDK call.</para>
2149
2150 <para>The Button widget has the following signals:</para>
2151
2152 <itemizedlist>
2153 <listitem><simpara><literal>pressed</literal> - emitted when pointer button is pressed within
2154 Button widget</simpara>
2155 </listitem>
2156 <listitem><simpara><literal>released</literal> - emitted when pointer button is released within
2157 Button widget</simpara>
2158 </listitem>
2159 <listitem><simpara><literal>clicked</literal> - emitted when pointer button is pressed and then
2160 released within Button widget</simpara>
2161 </listitem>
2162 <listitem><simpara><literal>enter</literal> - emitted when pointer enters Button widget</simpara>
2163 </listitem>
2164 <listitem><simpara><literal>leave</literal> - emitted when pointer leaves Button widget</simpara>
2165 </listitem>
2166 </itemizedlist>
2167
2168 </sect1>
2169
2170 <!-- ----------------------------------------------------------------- -->
2171 <sect1 id="sec-ToggleButtons">
2172 <title>Toggle Buttons</title>
2173
2174 <para>Toggle buttons are derived from normal buttons and are very similar,
2175 except they will always be in one of two states, alternated by a
2176 click. They may be depressed, and when you click again, they will pop
2177 back up. Click again, and they will pop back down.</para>
2178
2179 <para>Toggle buttons are the basis for check buttons and radio buttons, as
2180 such, many of the calls used for toggle buttons are inherited by radio
2181 and check buttons. I will point these out when we come to them.</para>
2182
2183 <para>Creating a new toggle button:</para>
2184
2185 <programlisting role="C">
2186 GtkWidget *gtk_toggle_button_new( void );
2187
2188 GtkWidget *gtk_toggle_button_new_with_label( gchar *label );
2189 </programlisting>
2190
2191 <para>As you can imagine, these work identically to the normal button widget
2192 calls. The first creates a blank toggle button, and the second, a
2193 button with a label widget already packed into it.</para>
2194
2195 <para>To retrieve the state of the toggle widget, including radio and check
2196 buttons, we use a construct as shown in our example below. This tests
2197 the state of the toggle, by accessing the <literal>active</literal> field of the
2198 toggle widget's structure, after first using the
2199 <literal>GTK_TOGGLE_BUTTON</literal> macro to cast the widget pointer into a toggle
2200 widget pointer. The signal of interest to us emitted by toggle
2201 buttons (the toggle button, check button, and radio button widgets) is
2202 the "toggled" signal. To check the state of these buttons, set up a
2203 signal handler to catch the toggled signal, and access the structure
2204 to determine its state. The callback will look something like:</para>
2205
2206 <programlisting role="C">
2207 void toggle_button_callback (GtkWidget *widget, gpointer data)
2208 {
2209     if (GTK_TOGGLE_BUTTON (widget)->active) 
2210     {
2211         /* If control reaches here, the toggle button is down */
2212     
2213     } else {
2214     
2215         /* If control reaches here, the toggle button is up */
2216     }
2217 }
2218 </programlisting>
2219
2220 <para>To force the state of a toggle button, and its children, the radio and
2221 check buttons, use this function:</para>
2222
2223 <programlisting role="C">
2224 void gtk_toggle_button_set_active( GtkToggleButton *toggle_button,
2225                                   gint             state );
2226 </programlisting>
2227
2228 <para>The above call can be used to set the state of the toggle button, and
2229 its children the radio and check buttons. Passing in your created
2230 button as the first argument, and a TRUE or FALSE for the second state
2231 argument to specify whether it should be down (depressed) or up
2232 (released). Default is up, or FALSE.</para>
2233
2234 <para>Note that when you use the gtk_toggle_button_set_active() function, and
2235 the state is actually changed, it causes the "clicked" and "toggled"
2236 signals to be emitted from the button.</para>
2237
2238 <programlisting role="C">
2239 gboolean gtk_toggle_button_get_active   (GtkToggleButton *toggle_button);
2240 </programlisting>
2241
2242 <para>This returns the current state of the toggle button as a boolean
2243 TRUE/FALSE value.</para>
2244
2245 </sect1>
2246
2247 <!-- ----------------------------------------------------------------- -->
2248 <sect1 id="sec-CheckButtons">
2249 <title>Check Buttons</title>
2250
2251 <para>Check buttons inherit many properties and functions from the the
2252 toggle buttons above, but look a little different. Rather than being
2253 buttons with text inside them, they are small squares with the text to
2254 the right of them. These are often used for toggling options on and
2255 off in applications.</para>
2256
2257 <para>The two creation functions are similar to those of the normal button.</para>
2258
2259 <programlisting role="C">
2260 GtkWidget *gtk_check_button_new( void );
2261
2262 GtkWidget *gtk_check_button_new_with_label ( gchar *label );
2263 </programlisting>
2264
2265 <para>The new_with_label function creates a check button with a label beside
2266 it.</para>
2267
2268 <para>Checking the state of the check button is identical to that of the
2269 toggle button.</para>
2270
2271 </sect1>
2272
2273 <!-- ----------------------------------------------------------------- -->
2274 <sect1 id="sec-RadioButtons">
2275 <title>Radio Buttons</title>
2276
2277 <para>Radio buttons are similar to check buttons except they are grouped so
2278 that only one may be selected/depressed at a time. This is good for
2279 places in your application where you need to select from a short list
2280 of options.</para>
2281
2282 <para>Creating a new radio button is done with one of these calls:</para>
2283
2284 <programlisting role="C">
2285 GtkWidget *gtk_radio_button_new( GSList *group );
2286
2287 GtkWidget *gtk_radio_button_new_with_label( GSList *group,
2288                                             gchar  *label );
2289 </programlisting>
2290
2291 <para>You'll notice the extra argument to these calls. They require a group
2292 to perform their duty properly. The first call to
2293 gtk_radio_button_new or gtk_radio_button_new_with_label
2294 should pass NULL as the first argument. Then create a group using:</para>
2295
2296 <programlisting role="C">
2297 GSList *gtk_radio_button_group( GtkRadioButton *radio_button );
2298 </programlisting>
2299
2300 <para>The important thing to remember is that gtk_radio_button_group must be
2301 called for each new button added to the group, with the previous
2302 button passed in as an argument. The result is then passed into the
2303 next call to gtk_radio_button_new or
2304 gtk_radio_button_new_with_label. This allows a chain of buttons to be
2305 established. The example below should make this clear.</para>
2306
2307 <para>You can shorten this slightly by using the following syntax, which
2308 removes the need for a variable to hold the list of buttons. This form
2309 is used in the example to create the third button:</para>
2310
2311 <programlisting role="C">
2312      button2 = gtk_radio_button_new_with_label(
2313                  gtk_radio_button_group (GTK_RADIO_BUTTON (button1)),
2314                  "button2");
2315 </programlisting>
2316
2317 <para>It is also a good idea to explicitly set which button should be the
2318 default depressed button with:</para>
2319
2320 <programlisting role="C">
2321 void gtk_toggle_button_set_active( GtkToggleButton *toggle_button,
2322                                   gint             state );
2323 </programlisting>
2324
2325 <para>This is described in the section on toggle buttons, and works in
2326 exactly the same way.  Once the radio buttons are grouped together,
2327 only one of the group may be active at a time. If the user clicks on
2328 one radio button, and then on another, the first radio button will
2329 first emit a "toggled" signal (to report becoming inactive), and then
2330 the second will emit its "toggled" signal (to report becoming active).</para>
2331
2332 <para>The following example creates a radio button group with three buttons.</para>
2333
2334 <programlisting role="C">
2335 <!-- example-start radiobuttons radiobuttons.c -->
2336
2337 #include &lt;gtk/gtk.h&gt;
2338 #include &lt;glib.h&gt;
2339
2340 gint close_application( GtkWidget *widget,
2341                         GdkEvent  *event,
2342                         gpointer   data )
2343 {
2344   gtk_main_quit();
2345   return(FALSE);
2346 }
2347
2348 int main( int   argc,
2349           char *argv[] )
2350 {
2351     GtkWidget *window = NULL;
2352     GtkWidget *box1;
2353     GtkWidget *box2;
2354     GtkWidget *button;
2355     GtkWidget *separator;
2356     GSList *group;
2357   
2358     gtk_init(&amp;argc,&amp;argv);    
2359       
2360     window = gtk_window_new (GTK_WINDOW_TOPLEVEL);
2361   
2362     gtk_signal_connect (GTK_OBJECT (window), "delete_event",
2363                         GTK_SIGNAL_FUNC(close_application),
2364                         NULL);
2365
2366     gtk_window_set_title (GTK_WINDOW (window), "radio buttons");
2367     gtk_container_set_border_width (GTK_CONTAINER (window), 0);
2368
2369     box1 = gtk_vbox_new (FALSE, 0);
2370     gtk_container_add (GTK_CONTAINER (window), box1);
2371     gtk_widget_show (box1);
2372
2373     box2 = gtk_vbox_new (FALSE, 10);
2374     gtk_container_set_border_width (GTK_CONTAINER (box2), 10);
2375     gtk_box_pack_start (GTK_BOX (box1), box2, TRUE, TRUE, 0);
2376     gtk_widget_show (box2);
2377
2378     button = gtk_radio_button_new_with_label (NULL, "button1");
2379     gtk_box_pack_start (GTK_BOX (box2), button, TRUE, TRUE, 0);
2380     gtk_widget_show (button);
2381
2382     group = gtk_radio_button_group (GTK_RADIO_BUTTON (button));
2383     button = gtk_radio_button_new_with_label(group, "button2");
2384     gtk_toggle_button_set_active (GTK_TOGGLE_BUTTON (button), TRUE);
2385     gtk_box_pack_start (GTK_BOX (box2), button, TRUE, TRUE, 0);
2386     gtk_widget_show (button);
2387
2388     button = gtk_radio_button_new_with_label(
2389                  gtk_radio_button_group (GTK_RADIO_BUTTON (button)),
2390                  "button3");
2391     gtk_box_pack_start (GTK_BOX (box2), button, TRUE, TRUE, 0);
2392     gtk_widget_show (button);
2393
2394     separator = gtk_hseparator_new ();
2395     gtk_box_pack_start (GTK_BOX (box1), separator, FALSE, TRUE, 0);
2396     gtk_widget_show (separator);
2397
2398     box2 = gtk_vbox_new (FALSE, 10);
2399     gtk_container_set_border_width (GTK_CONTAINER (box2), 10);
2400     gtk_box_pack_start (GTK_BOX (box1), box2, FALSE, TRUE, 0);
2401     gtk_widget_show (box2);
2402
2403     button = gtk_button_new_with_label ("close");
2404     gtk_signal_connect_object (GTK_OBJECT (button), "clicked",
2405                                GTK_SIGNAL_FUNC(close_application),
2406                                GTK_OBJECT (window));
2407     gtk_box_pack_start (GTK_BOX (box2), button, TRUE, TRUE, 0);
2408     GTK_WIDGET_SET_FLAGS (button, GTK_CAN_DEFAULT);
2409     gtk_widget_grab_default (button);
2410     gtk_widget_show (button);
2411     gtk_widget_show (window);
2412      
2413     gtk_main();
2414
2415     return(0);
2416 }
2417 <!-- example-end -->
2418 </programlisting>
2419
2420 <!-- TODO: check out gtk_radio_button_new_from_widget function - TRG -->
2421
2422 </sect1>
2423 </chapter>
2424
2425 <!-- ***************************************************************** -->
2426 <chapter id="ch-Adjustments">
2427 <title>Adjustments</title>
2428
2429 <para>GTK has various widgets that can be visually adjusted by the user
2430 using the mouse or the keyboard, such as the range widgets, described
2431 in the <link linkend="ch-RangeWidgets">Range Widgets</link>
2432 section. There are also a few widgets that display some adjustable
2433 portion of a larger area of data, such as the text widget and the
2434 viewport widget.</para>
2435
2436 <para>Obviously, an application needs to be able to react to changes the
2437 user makes in range widgets. One way to do this would be to have each
2438 widget emit its own type of signal when its adjustment changes, and
2439 either pass the new value to the signal handler, or require it to look
2440 inside the widget's data structure in order to ascertain the value.
2441 But you may also want to connect the adjustments of several widgets
2442 together, so that adjusting one adjusts the others. The most obvious
2443 example of this is connecting a scrollbar to a panning viewport or a
2444 scrolling text area. If each widget has its own way of setting or
2445 getting the adjustment value, then the programmer may have to write
2446 their own signal handlers to translate between the output of one
2447 widget's signal and the "input" of another's adjustment setting
2448 function.</para>
2449
2450 <para>GTK solves this problem using the Adjustment object, which is not a
2451 widget but a way for widgets to store and pass adjustment information
2452 in an abstract and flexible form. The most obvious use of Adjustment
2453 is to store the configuration parameters and values of range widgets,
2454 such as scrollbars and scale controls. However, since Adjustments are
2455 derived from Object, they have some special powers beyond those of
2456 normal data structures. Most importantly, they can emit signals, just
2457 like widgets, and these signals can be used not only to allow your
2458 program to react to user input on adjustable widgets, but also to
2459 propagate adjustment values transparently between adjustable widgets.</para>
2460
2461 <para>You will see how adjustments fit in when you see the other widgets
2462 that incorporate them:
2463 <link linkend="sec-ProgressBars">Progress Bars</link>,
2464 <link linkend="sec-Viewports">Viewports</link>,
2465 <link linkend="sec-ScrolledWindows">Scrolled Windows</link>, and others.</para>
2466
2467 <!-- ----------------------------------------------------------------- -->
2468 <sect1 id="sec-CreatingAnAdjustment">
2469 <title>Creating an Adjustment</title>
2470
2471 <para>Many of the widgets which use adjustment objects do so automatically,
2472 but some cases will be shown in later examples where you may need to
2473 create one yourself. You create an adjustment using:</para>
2474
2475 <programlisting role="C">
2476 GtkObject *gtk_adjustment_new( gfloat value,
2477                                gfloat lower,
2478                                gfloat upper,
2479                                gfloat step_increment,
2480                                gfloat page_increment,
2481                                gfloat page_size );
2482 </programlisting>
2483
2484 <para>The <literal>value</literal> argument is the initial value you want to give to the
2485 adjustment, usually corresponding to the topmost or leftmost position
2486 of an adjustable widget. The <literal>lower</literal> argument specifies the lowest
2487 value which the adjustment can hold. The <literal>step_increment</literal> argument
2488 specifies the "smaller" of the two increments by which the user can
2489 change the value, while the <literal>page_increment</literal> is the "larger" one.
2490 The <literal>page_size</literal> argument usually corresponds somehow to the visible
2491 area of a panning widget. The <literal>upper</literal> argument is used to represent
2492 the bottom most or right most coordinate in a panning widget's
2493 child. Therefore it is <emphasis>not</emphasis> always the largest number that
2494 <literal>value</literal> can take, since the <literal>page_size</literal> of such widgets is
2495 usually non-zero.</para>
2496
2497 </sect1>
2498
2499 <!-- ----------------------------------------------------------------- -->
2500 <sect1 id="sec-UsingAdjustments">
2501 <title>Using Adjustments the Easy Way</title>
2502
2503 <para>The adjustable widgets can be roughly divided into those which use and
2504 require specific units for these values and those which treat them as
2505 arbitrary numbers. The group which treats the values as arbitrary
2506 numbers includes the range widgets (scrollbars and scales, the
2507 progress bar widget, and the spin button widget). These widgets are
2508 all the widgets which are typically "adjusted" directly by the user
2509 with the mouse or keyboard. They will treat the <literal>lower</literal> and
2510 <literal>upper</literal> values of an adjustment as a range within which the user
2511 can manipulate the adjustment's <literal>value</literal>. By default, they will only
2512 modify the <literal>value</literal> of an adjustment.</para>
2513
2514 <para>The other group includes the text widget, the viewport widget, the
2515 compound list widget, and the scrolled window widget. All of these
2516 widgets use pixel values for their adjustments. These are also all
2517 widgets which are typically "adjusted" indirectly using scrollbars.
2518 While all widgets which use adjustments can either create their own
2519 adjustments or use ones you supply, you'll generally want to let this
2520 particular category of widgets create its own adjustments. Usually,
2521 they will eventually override all the values except the <literal>value</literal>
2522 itself in whatever adjustments you give them, but the results are, in
2523 general, undefined (meaning, you'll have to read the source code to
2524 find out, and it may be different from widget to widget).</para>
2525
2526 <para>Now, you're probably thinking, since text widgets and viewports insist
2527 on setting everything except the <literal>value</literal> of their adjustments,
2528 while scrollbars will <emphasis>only</emphasis> touch the adjustment's <literal>value</literal>, if
2529 you <emphasis>share</emphasis> an adjustment object between a scrollbar and a text
2530 widget, manipulating the scrollbar will automagically adjust the text
2531 widget?  Of course it will! Just like this:</para>
2532
2533 <programlisting role="C">
2534   /* creates its own adjustments */
2535   text = gtk_text_new (NULL, NULL);
2536   /* uses the newly-created adjustment for the scrollbar as well */
2537   vscrollbar = gtk_vscrollbar_new (GTK_TEXT(text)->vadj);
2538 </programlisting>
2539
2540 </sect1>
2541
2542 <!-- ----------------------------------------------------------------- -->
2543 <sect1 id="sec-AdjustmentInternals">
2544 <title>Adjustment Internals</title>
2545
2546 <para>Ok, you say, that's nice, but what if I want to create my own handlers
2547 to respond when the user adjusts a range widget or a spin button, and
2548 how do I get at the value of the adjustment in these handlers?  To
2549 answer these questions and more, let's start by taking a look at
2550 <literal>struct _GtkAdjustment</literal> itself:</para>
2551
2552 <programlisting role="C">
2553 struct _GtkAdjustment
2554 {
2555   GtkData data;
2556   
2557   gfloat lower;
2558   gfloat upper;
2559   gfloat value;
2560   gfloat step_increment;
2561   gfloat page_increment;
2562   gfloat page_size;
2563 };
2564 </programlisting>
2565
2566 <para>The first thing you should know is that there aren't any handy-dandy
2567 macros or accessor functions for getting the <literal>value</literal> out of an
2568 Adjustment, so you'll have to (horror of horrors) do it like a
2569 <emphasis>real</emphasis> C programmer.  Don't worry - the <literal>GTK_ADJUSTMENT
2570 (Object)</literal> macro does run-time type checking (as do all the GTK
2571 type-casting macros, actually).</para>
2572
2573 <para>Since, when you set the <literal>value</literal> of an adjustment, you generally
2574 want the change to be reflected by every widget that uses this
2575 adjustment, GTK provides this convenience function to do this:</para>
2576
2577 <programlisting role="C">
2578 void gtk_adjustment_set_value( GtkAdjustment *adjustment,
2579                                gfloat         value );
2580 </programlisting>
2581
2582 <para>As mentioned earlier, Adjustment is a subclass of Object just
2583 like all the various widgets, and thus it is able to emit signals.
2584 This is, of course, why updates happen automagically when you share an
2585 adjustment object between a scrollbar and another adjustable widget;
2586 all adjustable widgets connect signal handlers to their adjustment's
2587 <literal>value_changed</literal> signal, as can your program. Here's the definition
2588 of this signal in <literal>struct _GtkAdjustmentClass</literal>:</para>
2589
2590 <programlisting role="C">
2591   void (* value_changed) (GtkAdjustment *adjustment);
2592 </programlisting>
2593
2594 <para>The various widgets that use the Adjustment object will emit this
2595 signal on an adjustment whenever they change its value. This happens
2596 both when user input causes the slider to move on a range widget, as
2597 well as when the program explicitly changes the value with
2598 <literal>gtk_adjustment_set_value()</literal>. So, for example, if you have a scale
2599 widget, and you want to change the rotation of a picture whenever its
2600 value changes, you would create a callback like this:</para>
2601
2602 <programlisting role="C">
2603 void cb_rotate_picture (GtkAdjustment *adj, GtkWidget *picture)
2604 {
2605   set_picture_rotation (picture, adj->value);
2606 ...
2607 </programlisting>
2608
2609 <para>and connect it to the scale widget's adjustment like this:</para>
2610
2611 <programlisting role="C">
2612 gtk_signal_connect (GTK_OBJECT (adj), "value_changed",
2613                     GTK_SIGNAL_FUNC (cb_rotate_picture), picture);
2614 </programlisting>
2615
2616 <para>What about when a widget reconfigures the <literal>upper</literal> or <literal>lower</literal>
2617 fields of its adjustment, such as when a user adds more text to a text
2618 widget?  In this case, it emits the <literal>changed</literal> signal, which looks
2619 like this:</para>
2620
2621 <programlisting role="C">
2622   void (* changed) (GtkAdjustment *adjustment);
2623 </programlisting>
2624
2625 <para>Range widgets typically connect a handler to this signal, which
2626 changes their appearance to reflect the change - for example, the size
2627 of the slider in a scrollbar will grow or shrink in inverse proportion
2628 to the difference between the <literal>lower</literal> and <literal>upper</literal> values of its
2629 adjustment.</para>
2630
2631 <para>You probably won't ever need to attach a handler to this signal,
2632 unless you're writing a new type of range widget.  However, if you
2633 change any of the values in a Adjustment directly, you should emit
2634 this signal on it to reconfigure whatever widgets are using it, like
2635 this:</para>
2636
2637 <programlisting role="C">
2638 gtk_signal_emit_by_name (GTK_OBJECT (adjustment), "changed");
2639 </programlisting>
2640
2641 <para>Now go forth and adjust!</para>
2642
2643 </sect1>
2644 </chapter>
2645
2646 <!-- ***************************************************************** -->
2647 <chapter id="ch-RangeWidgets">
2648 <title>Range Widgets</title>
2649
2650 <para>The category of range widgets includes the ubiquitous scrollbar widget
2651 and the less common "scale" widget. Though these two types of widgets
2652 are generally used for different purposes, they are quite similar in
2653 function and implementation. All range widgets share a set of common
2654 graphic elements, each of which has its own X window and receives
2655 events. They all contain a "trough" and a "slider" (what is sometimes
2656 called a "thumbwheel" in other GUI environments). Dragging the slider
2657 with the pointer moves it back and forth within the trough, while
2658 clicking in the trough advances the slider towards the location of the
2659 click, either completely, or by a designated amount, depending on
2660 which mouse button is used.</para>
2661
2662 <para>As mentioned in <link linkend="ch-Adjustments">Adjustments</link> above,
2663 all range widgets are associated with an adjustment object, from which
2664 they calculate the length of the slider and its position within the
2665 trough. When the user manipulates the slider, the range widget will
2666 change the value of the adjustment.</para>
2667
2668 <!-- ----------------------------------------------------------------- -->
2669 <sect1 id="sec-ScrollbarWidgets">
2670 <title>Scrollbar Widgets</title>
2671
2672 <para>These are your standard, run-of-the-mill scrollbars. These should be
2673 used only for scrolling some other widget, such as a list, a text box,
2674 or a viewport (and it's generally easier to use the scrolled window
2675 widget in most cases).  For other purposes, you should use scale
2676 widgets, as they are friendlier and more featureful.</para>
2677
2678 <para>There are separate types for horizontal and vertical scrollbars.
2679 There really isn't much to say about these. You create them with the
2680 following functions, defined in <literal>&lt;gtk/gtkhscrollbar.h&gt;</literal>
2681 and <literal>&lt;gtk/gtkvscrollbar.h&gt;</literal>:</para>
2682
2683 <programlisting role="C">
2684 GtkWidget *gtk_hscrollbar_new( GtkAdjustment *adjustment );
2685
2686 GtkWidget *gtk_vscrollbar_new( GtkAdjustment *adjustment );
2687 </programlisting>
2688
2689 <para>and that's about it (if you don't believe me, look in the header
2690 files!).  The <literal>adjustment</literal> argument can either be a pointer to an
2691 existing Adjustment, or NULL, in which case one will be created for
2692 you. Specifying NULL might actually be useful in this case, if you
2693 wish to pass the newly-created adjustment to the constructor function
2694 of some other widget which will configure it for you, such as a text
2695 widget.</para>
2696
2697 </sect1>
2698
2699 <!-- ----------------------------------------------------------------- -->
2700 <sect1 id="sec-ScaleWidgets">
2701 <title>Scale Widgets</title>
2702
2703 <para>Scale widgets are used to allow the user to visually select and
2704 manipulate a value within a specific range. You might want to use a
2705 scale widget, for example, to adjust the magnification level on a
2706 zoomed preview of a picture, or to control the brightness of a color,
2707 or to specify the number of minutes of inactivity before a screensaver
2708 takes over the screen.</para>
2709
2710 <!-- ----------------------------------------------------------------- -->
2711 <sect2>
2712 <title>Creating a Scale Widget</title>
2713
2714 <para>As with scrollbars, there are separate widget types for horizontal and
2715 vertical scale widgets. (Most programmers seem to favour horizontal
2716 scale widgets.) Since they work essentially the same way, there's no
2717 need to treat them separately here. The following functions, defined
2718 in <literal>&lt;gtk/gtkvscale.h&gt;</literal> and
2719 <literal>&lt;gtk/gtkhscale.h&gt;</literal>, create vertical and horizontal scale
2720 widgets, respectively:</para>
2721
2722 <programlisting role="C">
2723 GtkWidget *gtk_vscale_new( GtkAdjustment *adjustment );
2724
2725 GtkWidget *gtk_hscale_new( GtkAdjustment *adjustment );
2726 </programlisting>
2727
2728 <para>The <literal>adjustment</literal> argument can either be an adjustment which has
2729 already been created with <literal>gtk_adjustment_new()</literal>, or <literal>NULL</literal>, in
2730 which case, an anonymous Adjustment is created with all of its
2731 values set to <literal>0.0</literal> (which isn't very useful in this case). In
2732 order to avoid confusing yourself, you probably want to create your
2733 adjustment with a <literal>page_size</literal> of <literal>0.0</literal> so that its <literal>upper</literal>
2734 value actually corresponds to the highest value the user can select.
2735 (If you're <emphasis>already</emphasis> thoroughly confused, read the section on <link
2736 linkend="ch-Adjustments">Adjustments</link> again for an explanation of
2737 what exactly adjustments do and how to create and manipulate them.)</para>
2738
2739 </sect2>
2740
2741 <!-- ----------------------------------------------------------------- -->
2742 <sect2>
2743 <title>Functions and Signals (well, functions, at least)</title>
2744
2745 <para>Scale widgets can display their current value as a number beside the
2746 trough. The default behaviour is to show the value, but you can change
2747 this with this function:</para>
2748
2749 <programlisting role="C">
2750 void gtk_scale_set_draw_value( GtkScale *scale,
2751                                gint      draw_value );
2752 </programlisting>
2753
2754 <para>As you might have guessed, <literal>draw_value</literal> is either <literal>TRUE</literal> or
2755 <literal>FALSE</literal>, with predictable consequences for either one.</para>
2756
2757 <para>The value displayed by a scale widget is rounded to one decimal point
2758 by default, as is the <literal>value</literal> field in its GtkAdjustment. You can
2759 change this with:</para>
2760
2761 <programlisting role="C">
2762 void gtk_scale_set_digits( GtkScale *scale,
2763                             gint     digits );
2764 </programlisting>
2765
2766 <para>where <literal>digits</literal> is the number of decimal places you want. You can
2767 set <literal>digits</literal> to anything you like, but no more than 13 decimal
2768 places will actually be drawn on screen.</para>
2769
2770 <para>Finally, the value can be drawn in different positions
2771 relative to the trough:</para>
2772
2773 <programlisting role="C">
2774 void gtk_scale_set_value_pos( GtkScale        *scale,
2775                               GtkPositionType  pos );
2776 </programlisting>
2777
2778 <para>The argument <literal>pos</literal> is of type <literal>GtkPositionType</literal>, which is
2779 defined in <literal>&lt;gtk/gtkenums.h&gt;</literal>, and can take one of the
2780 following values:</para>
2781
2782 <programlisting role="C">
2783   GTK_POS_LEFT
2784   GTK_POS_RIGHT
2785   GTK_POS_TOP
2786   GTK_POS_BOTTOM
2787 </programlisting>
2788
2789 <para>If you position the value on the "side" of the trough (e.g., on the
2790 top or bottom of a horizontal scale widget), then it will follow the
2791 slider up and down the trough.</para>
2792
2793 <para>All the preceding functions are defined in
2794 <literal>&lt;gtk/gtkscale.h&gt;</literal>. The header files for all GTK widgets
2795 are automatically included when you include
2796 <literal>&lt;gtk/gtk.h&gt;</literal>. But you should look over the header files
2797 of all widgets that interest you,</para>
2798
2799 </sect2>
2800 </sect1>
2801
2802 <!-- ----------------------------------------------------------------- -->
2803 <sect1 id="sec-CommonRangeFunctions">
2804 <title>Common Range Functions</title>
2805
2806 <para>The Range widget class is fairly complicated internally, but, like
2807 all the "base class" widgets, most of its complexity is only
2808 interesting if you want to hack on it. Also, almost all of the
2809 functions and signals it defines are only really used in writing
2810 derived widgets. There are, however, a few useful functions that are
2811 defined in <literal>&lt;gtk/gtkrange.h&gt;</literal> and will work on all range
2812 widgets.</para>
2813
2814 <!-- ----------------------------------------------------------------- -->
2815 <sect2>
2816 <title>Setting the Update Policy</title>
2817
2818 <para>The "update policy" of a range widget defines at what points during
2819 user interaction it will change the <literal>value</literal> field of its
2820 Adjustment and emit the "value_changed" signal on this
2821 Adjustment. The update policies, defined in
2822 <literal>&lt;gtk/gtkenums.h&gt;</literal> as type <literal>enum GtkUpdateType</literal>,
2823 are:</para>
2824
2825 <itemizedlist>
2826 <listitem><simpara>GTK_UPDATE_CONTINUOUS - This is the default. The
2827 "value_changed" signal is emitted continuously, i.e., whenever the
2828 slider is moved by even the tiniest amount.</simpara>
2829 </listitem>
2830
2831 <listitem><simpara>GTK_UPDATE_DISCONTINUOUS - The "value_changed" signal is
2832 only emitted once the slider has stopped moving and the user has
2833 released the mouse button.</simpara>
2834 </listitem>
2835
2836 <listitem><simpara>GTK_UPDATE_DELAYED - The "value_changed" signal is emitted
2837 when the user releases the mouse button, or if the slider stops moving
2838 for a short period of time.</simpara>
2839 </listitem>
2840 </itemizedlist>
2841
2842 <para>The update policy of a range widget can be set by casting it using the
2843 <literal>GTK_RANGE (Widget)</literal> macro and passing it to this function:</para>
2844
2845 <programlisting role="C">
2846 void gtk_range_set_update_policy( GtkRange      *range,
2847                                   GtkUpdateType  policy);
2848 </programlisting>
2849
2850 </sect2>
2851
2852 <!-- ----------------------------------------------------------------- -->
2853 <sect2>
2854 <title>Getting and Setting Adjustments</title>
2855
2856 <para>Getting and setting the adjustment for a range widget "on the fly" is
2857 done, predictably, with:</para>
2858
2859 <programlisting role="C">
2860 GtkAdjustment* gtk_range_get_adjustment( GtkRange *range );
2861
2862 void gtk_range_set_adjustment( GtkRange      *range,
2863                                GtkAdjustment *adjustment );
2864 </programlisting>
2865
2866 <para><literal>gtk_range_get_adjustment()</literal> returns a pointer to the adjustment to
2867 which <literal>range</literal> is connected.</para>
2868
2869 <para><literal>gtk_range_set_adjustment()</literal> does absolutely nothing if you pass it
2870 the adjustment that <literal>range</literal> is already using, regardless of whether
2871 you changed any of its fields or not. If you pass it a new
2872 Adjustment, it will unreference the old one if it exists (possibly
2873 destroying it), connect the appropriate signals to the new one, and
2874 call the private function <literal>gtk_range_adjustment_changed()</literal>, which
2875 will (or at least, is supposed to...) recalculate the size and/or
2876 position of the slider and redraw if necessary. As mentioned in the
2877 section on adjustments, if you wish to reuse the same Adjustment,
2878 when you modify its values directly, you should emit the "changed"
2879 signal on it, like this:</para>
2880
2881 <programlisting role="C">
2882 gtk_signal_emit_by_name (GTK_OBJECT (adjustment), "changed");
2883 </programlisting>
2884
2885 </sect2>
2886 </sect1>
2887
2888 <!-- ----------------------------------------------------------------- -->
2889 <sect1 id="sec-KeyAndMouseBindings">
2890 <title>Key and Mouse bindings</title>
2891
2892 <para>All of the GTK range widgets react to mouse clicks in more or less
2893 the same way. Clicking button-1 in the trough will cause its
2894 adjustment's <literal>page_increment</literal> to be added or subtracted from its
2895 <literal>value</literal>, and the slider to be moved accordingly. Clicking mouse
2896 button-2 in the trough will jump the slider to the point at which the
2897 button was clicked. Clicking any button on a scrollbar's arrows will
2898 cause its adjustment's value to change <literal>step_increment</literal> at a time.</para>
2899
2900 <para>It may take a little while to get used to, but by default, scrollbars
2901 as well as scale widgets can take the keyboard focus in GTK. If you
2902 think your users will find this too confusing, you can always disable
2903 this by unsetting the <literal>GTK_CAN_FOCUS</literal> flag on the scrollbar, like
2904 this:</para>
2905
2906 <programlisting role="C">
2907 GTK_WIDGET_UNSET_FLAGS (scrollbar, GTK_CAN_FOCUS);
2908 </programlisting>
2909
2910 <para>The key bindings (which are, of course, only active when the widget
2911 has focus) are slightly different between horizontal and vertical
2912 range widgets, for obvious reasons. They are also not quite the same
2913 for scale widgets as they are for scrollbars, for somewhat less
2914 obvious reasons (possibly to avoid confusion between the keys for
2915 horizontal and vertical scrollbars in scrolled windows, where both
2916 operate on the same area).</para>
2917
2918 <!-- ----------------------------------------------------------------- -->
2919 <sect2>
2920 <title>Vertical Range Widgets</title>
2921
2922 <para>All vertical range widgets can be operated with the up and down arrow
2923 keys, as well as with the <literal>Page Up</literal> and <literal>Page Down</literal> keys. The
2924 arrows move the slider up and down by <literal>step_increment</literal>, while
2925 <literal>Page Up</literal> and <literal>Page Down</literal> move it by <literal>page_increment</literal>.</para>
2926
2927 <para>The user can also move the slider all the way to one end or the other
2928 of the trough using the keyboard. With the VScale widget, this is
2929 done with the <literal>Home</literal> and <literal>End</literal> keys, whereas with the
2930 VScrollbar widget, this is done by typing <literal>Control-Page Up</literal>
2931 and <literal>Control-Page Down</literal>.</para>
2932
2933 </sect2>
2934
2935 <!-- ----------------------------------------------------------------- -->
2936 <sect2>
2937 <title>Horizontal Range Widgets</title>
2938
2939 <para>The left and right arrow keys work as you might expect in these
2940 widgets, moving the slider back and forth by <literal>step_increment</literal>. The
2941 <literal>Home</literal> and <literal>End</literal> keys move the slider to the ends of the trough.
2942 For the HScale widget, moving the slider by <literal>page_increment</literal> is
2943 accomplished with <literal>Control-Left</literal> and <literal>Control-Right</literal>,
2944 while for HScrollbar, it's done with <literal>Control-Home</literal> and
2945 <literal>Control-End</literal>.</para>
2946
2947 </sect2>
2948 </sect1>
2949
2950 <!-- ----------------------------------------------------------------- -->
2951 <sect1 id="sec-RangeWidgetsExample">
2952 <title>Example</title>
2953
2954 <para>This example is a somewhat modified version of the "range controls"
2955 test from <literal>testgtk.c</literal>. It basically puts up a window with three
2956 range widgets all connected to the same adjustment, and a couple of
2957 controls for adjusting some of the parameters mentioned above and in
2958 the section on adjustments, so you can see how they affect the way
2959 these widgets work for the user.</para>
2960
2961 <programlisting role="C">
2962 <!-- example-start rangewidgets rangewidgets.c -->
2963
2964 #include &lt;gtk/gtk.h&gt;
2965
2966 GtkWidget *hscale, *vscale;
2967
2968 void cb_pos_menu_select( GtkWidget       *item,
2969                          GtkPositionType  pos )
2970 {
2971     /* Set the value position on both scale widgets */
2972     gtk_scale_set_value_pos (GTK_SCALE (hscale), pos);
2973     gtk_scale_set_value_pos (GTK_SCALE (vscale), pos);
2974 }
2975
2976 void cb_update_menu_select( GtkWidget     *item,
2977                             GtkUpdateType  policy )
2978 {
2979     /* Set the update policy for both scale widgets */
2980     gtk_range_set_update_policy (GTK_RANGE (hscale), policy);
2981     gtk_range_set_update_policy (GTK_RANGE (vscale), policy);
2982 }
2983
2984 void cb_digits_scale( GtkAdjustment *adj )
2985 {
2986     /* Set the number of decimal places to which adj->value is rounded */
2987     gtk_scale_set_digits (GTK_SCALE (hscale), (gint) adj->value);
2988     gtk_scale_set_digits (GTK_SCALE (vscale), (gint) adj->value);
2989 }
2990
2991 void cb_page_size( GtkAdjustment *get,
2992                    GtkAdjustment *set )
2993 {
2994     /* Set the page size and page increment size of the sample
2995      * adjustment to the value specified by the "Page Size" scale */
2996     set->page_size = get->value;
2997     set->page_increment = get->value;
2998     /* Now emit the "changed" signal to reconfigure all the widgets that
2999      * are attached to this adjustment */
3000     gtk_signal_emit_by_name (GTK_OBJECT (set), "changed");
3001 }
3002
3003 void cb_draw_value( GtkToggleButton *button )
3004 {
3005     /* Turn the value display on the scale widgets off or on depending
3006      *  on the state of the checkbutton */
3007     gtk_scale_set_draw_value (GTK_SCALE (hscale), button->active);
3008     gtk_scale_set_draw_value (GTK_SCALE (vscale), button->active);  
3009 }
3010
3011 /* Convenience functions */
3012
3013 GtkWidget *make_menu_item( gchar         *name,
3014                            GtkSignalFunc  callback,
3015                            gpointer       data )
3016 {
3017     GtkWidget *item;
3018   
3019     item = gtk_menu_item_new_with_label (name);
3020     gtk_signal_connect (GTK_OBJECT (item), "activate",
3021                         callback, data);
3022     gtk_widget_show (item);
3023
3024     return(item);
3025 }
3026
3027 void scale_set_default_values( GtkScale *scale )
3028 {
3029     gtk_range_set_update_policy (GTK_RANGE (scale),
3030                                  GTK_UPDATE_CONTINUOUS);
3031     gtk_scale_set_digits (scale, 1);
3032     gtk_scale_set_value_pos (scale, GTK_POS_TOP);
3033     gtk_scale_set_draw_value (scale, TRUE);
3034 }
3035
3036 /* makes the sample window */
3037
3038 void create_range_controls( void )
3039 {
3040     GtkWidget *window;
3041     GtkWidget *box1, *box2, *box3;
3042     GtkWidget *button;
3043     GtkWidget *scrollbar;
3044     GtkWidget *separator;
3045     GtkWidget *opt, *menu, *item;
3046     GtkWidget *label;
3047     GtkWidget *scale;
3048     GtkObject *adj1, *adj2;
3049
3050     /* Standard window-creating stuff */
3051     window = gtk_window_new (GTK_WINDOW_TOPLEVEL);
3052     gtk_signal_connect (GTK_OBJECT (window), "destroy",
3053                         GTK_SIGNAL_FUNC(gtk_main_quit),
3054                         NULL);
3055     gtk_window_set_title (GTK_WINDOW (window), "range controls");
3056
3057     box1 = gtk_vbox_new (FALSE, 0);
3058     gtk_container_add (GTK_CONTAINER (window), box1);
3059     gtk_widget_show (box1);
3060
3061     box2 = gtk_hbox_new (FALSE, 10);
3062     gtk_container_set_border_width (GTK_CONTAINER (box2), 10);
3063     gtk_box_pack_start (GTK_BOX (box1), box2, TRUE, TRUE, 0);
3064     gtk_widget_show (box2);
3065
3066     /* value, lower, upper, step_increment, page_increment, page_size */
3067     /* Note that the page_size value only makes a difference for
3068      * scrollbar widgets, and the highest value you'll get is actually
3069      * (upper - page_size). */
3070     adj1 = gtk_adjustment_new (0.0, 0.0, 101.0, 0.1, 1.0, 1.0);
3071   
3072     vscale = gtk_vscale_new (GTK_ADJUSTMENT (adj1));
3073     scale_set_default_values (GTK_SCALE (vscale));
3074     gtk_box_pack_start (GTK_BOX (box2), vscale, TRUE, TRUE, 0);
3075     gtk_widget_show (vscale);
3076
3077     box3 = gtk_vbox_new (FALSE, 10);
3078     gtk_box_pack_start (GTK_BOX (box2), box3, TRUE, TRUE, 0);
3079     gtk_widget_show (box3);
3080
3081     /* Reuse the same adjustment */
3082     hscale = gtk_hscale_new (GTK_ADJUSTMENT (adj1));
3083     gtk_widget_set_usize (GTK_WIDGET (hscale), 200, 30);
3084     scale_set_default_values (GTK_SCALE (hscale));
3085     gtk_box_pack_start (GTK_BOX (box3), hscale, TRUE, TRUE, 0);
3086     gtk_widget_show (hscale);
3087
3088     /* Reuse the same adjustment again */
3089     scrollbar = gtk_hscrollbar_new (GTK_ADJUSTMENT (adj1));
3090     /* Notice how this causes the scales to always be updated
3091      * continuously when the scrollbar is moved */
3092     gtk_range_set_update_policy (GTK_RANGE (scrollbar), 
3093                                  GTK_UPDATE_CONTINUOUS);
3094     gtk_box_pack_start (GTK_BOX (box3), scrollbar, TRUE, TRUE, 0);
3095     gtk_widget_show (scrollbar);
3096
3097     box2 = gtk_hbox_new (FALSE, 10);
3098     gtk_container_set_border_width (GTK_CONTAINER (box2), 10);
3099     gtk_box_pack_start (GTK_BOX (box1), box2, TRUE, TRUE, 0);
3100     gtk_widget_show (box2);
3101
3102     /* A checkbutton to control whether the value is displayed or not */
3103     button = gtk_check_button_new_with_label("Display value on scale widgets");
3104     gtk_toggle_button_set_active (GTK_TOGGLE_BUTTON (button), TRUE);
3105     gtk_signal_connect (GTK_OBJECT (button), "toggled",
3106                         GTK_SIGNAL_FUNC(cb_draw_value), NULL);
3107     gtk_box_pack_start (GTK_BOX (box2), button, TRUE, TRUE, 0);
3108     gtk_widget_show (button);
3109   
3110     box2 = gtk_hbox_new (FALSE, 10);
3111     gtk_container_set_border_width (GTK_CONTAINER (box2), 10);
3112
3113     /* An option menu to change the position of the value */
3114     label = gtk_label_new ("Scale Value Position:");
3115     gtk_box_pack_start (GTK_BOX (box2), label, FALSE, FALSE, 0);
3116     gtk_widget_show (label);
3117   
3118     opt = gtk_option_menu_new();
3119     menu = gtk_menu_new();
3120
3121     item = make_menu_item ("Top",
3122                            GTK_SIGNAL_FUNC(cb_pos_menu_select),
3123                            GINT_TO_POINTER (GTK_POS_TOP));
3124     gtk_menu_append (GTK_MENU (menu), item);
3125   
3126     item = make_menu_item ("Bottom", GTK_SIGNAL_FUNC (cb_pos_menu_select), 
3127                            GINT_TO_POINTER (GTK_POS_BOTTOM));
3128     gtk_menu_append (GTK_MENU (menu), item);
3129   
3130     item = make_menu_item ("Left", GTK_SIGNAL_FUNC (cb_pos_menu_select),
3131                            GINT_TO_POINTER (GTK_POS_LEFT));
3132     gtk_menu_append (GTK_MENU (menu), item);
3133   
3134     item = make_menu_item ("Right", GTK_SIGNAL_FUNC (cb_pos_menu_select),
3135                             GINT_TO_POINTER (GTK_POS_RIGHT));
3136     gtk_menu_append (GTK_MENU (menu), item);
3137   
3138     gtk_option_menu_set_menu (GTK_OPTION_MENU (opt), menu);
3139     gtk_box_pack_start (GTK_BOX (box2), opt, TRUE, TRUE, 0);
3140     gtk_widget_show (opt);
3141
3142     gtk_box_pack_start (GTK_BOX (box1), box2, TRUE, TRUE, 0);
3143     gtk_widget_show (box2);
3144
3145     box2 = gtk_hbox_new (FALSE, 10);
3146     gtk_container_set_border_width (GTK_CONTAINER (box2), 10);
3147
3148     /* Yet another option menu, this time for the update policy of the
3149      * scale widgets */
3150     label = gtk_label_new ("Scale Update Policy:");
3151     gtk_box_pack_start (GTK_BOX (box2), label, FALSE, FALSE, 0);
3152     gtk_widget_show (label);
3153   
3154     opt = gtk_option_menu_new();
3155     menu = gtk_menu_new();
3156   
3157     item = make_menu_item ("Continuous",
3158                            GTK_SIGNAL_FUNC (cb_update_menu_select),
3159                            GINT_TO_POINTER (GTK_UPDATE_CONTINUOUS));
3160     gtk_menu_append (GTK_MENU (menu), item);
3161   
3162     item = make_menu_item ("Discontinuous",
3163                             GTK_SIGNAL_FUNC (cb_update_menu_select),
3164                             GINT_TO_POINTER (GTK_UPDATE_DISCONTINUOUS));
3165     gtk_menu_append (GTK_MENU (menu), item);
3166   
3167     item = make_menu_item ("Delayed",
3168                            GTK_SIGNAL_FUNC (cb_update_menu_select),
3169                            GINT_TO_POINTER (GTK_UPDATE_DELAYED));
3170     gtk_menu_append (GTK_MENU (menu), item);
3171   
3172     gtk_option_menu_set_menu (GTK_OPTION_MENU (opt), menu);
3173     gtk_box_pack_start (GTK_BOX (box2), opt, TRUE, TRUE, 0);
3174     gtk_widget_show (opt);
3175   
3176     gtk_box_pack_start (GTK_BOX (box1), box2, TRUE, TRUE, 0);
3177     gtk_widget_show (box2);
3178
3179     box2 = gtk_hbox_new (FALSE, 10);
3180     gtk_container_set_border_width (GTK_CONTAINER (box2), 10);
3181   
3182     /* An HScale widget for adjusting the number of digits on the
3183      * sample scales. */
3184     label = gtk_label_new ("Scale Digits:");
3185     gtk_box_pack_start (GTK_BOX (box2), label, FALSE, FALSE, 0);
3186     gtk_widget_show (label);
3187
3188     adj2 = gtk_adjustment_new (1.0, 0.0, 5.0, 1.0, 1.0, 0.0);
3189     gtk_signal_connect (GTK_OBJECT (adj2), "value_changed",
3190                         GTK_SIGNAL_FUNC (cb_digits_scale), NULL);
3191     scale = gtk_hscale_new (GTK_ADJUSTMENT (adj2));
3192     gtk_scale_set_digits (GTK_SCALE (scale), 0);
3193     gtk_box_pack_start (GTK_BOX (box2), scale, TRUE, TRUE, 0);
3194     gtk_widget_show (scale);
3195
3196     gtk_box_pack_start (GTK_BOX (box1), box2, TRUE, TRUE, 0);
3197     gtk_widget_show (box2);
3198   
3199     box2 = gtk_hbox_new (FALSE, 10);
3200     gtk_container_set_border_width (GTK_CONTAINER (box2), 10);
3201   
3202     /* And, one last HScale widget for adjusting the page size of the
3203      * scrollbar. */
3204     label = gtk_label_new ("Scrollbar Page Size:");
3205     gtk_box_pack_start (GTK_BOX (box2), label, FALSE, FALSE, 0);
3206     gtk_widget_show (label);
3207
3208     adj2 = gtk_adjustment_new (1.0, 1.0, 101.0, 1.0, 1.0, 0.0);
3209     gtk_signal_connect (GTK_OBJECT (adj2), "value_changed",
3210                         GTK_SIGNAL_FUNC (cb_page_size), adj1);
3211     scale = gtk_hscale_new (GTK_ADJUSTMENT (adj2));
3212     gtk_scale_set_digits (GTK_SCALE (scale), 0);
3213     gtk_box_pack_start (GTK_BOX (box2), scale, TRUE, TRUE, 0);
3214     gtk_widget_show (scale);
3215
3216     gtk_box_pack_start (GTK_BOX (box1), box2, TRUE, TRUE, 0);
3217     gtk_widget_show (box2);
3218
3219     separator = gtk_hseparator_new ();
3220     gtk_box_pack_start (GTK_BOX (box1), separator, FALSE, TRUE, 0);
3221     gtk_widget_show (separator);
3222
3223     box2 = gtk_vbox_new (FALSE, 10);
3224     gtk_container_set_border_width (GTK_CONTAINER (box2), 10);
3225     gtk_box_pack_start (GTK_BOX (box1), box2, FALSE, TRUE, 0);
3226     gtk_widget_show (box2);
3227
3228     button = gtk_button_new_with_label ("Quit");
3229     gtk_signal_connect_object (GTK_OBJECT (button), "clicked",
3230                                GTK_SIGNAL_FUNC(gtk_main_quit),
3231                                NULL);
3232     gtk_box_pack_start (GTK_BOX (box2), button, TRUE, TRUE, 0);
3233     GTK_WIDGET_SET_FLAGS (button, GTK_CAN_DEFAULT);
3234     gtk_widget_grab_default (button);
3235     gtk_widget_show (button);
3236
3237     gtk_widget_show (window);
3238 }
3239
3240 int main( int   argc,
3241           char *argv[] )
3242 {
3243     gtk_init(&amp;argc, &amp;argv);
3244
3245     create_range_controls();
3246
3247     gtk_main();
3248
3249     return(0);
3250 }
3251
3252 <!-- example-end -->
3253 </programlisting>
3254
3255 <para>You will notice that the program does not call <literal>gtk_signal_connect</literal>
3256 for the "delete_event", but only for the "destroy" signal. This will
3257 still perform the desired function, because an unhandled
3258 "delete_event" will result in a "destroy" signal being given to the
3259 window.</para>
3260
3261 </sect1>
3262 </chapter>
3263
3264 <!-- ***************************************************************** -->
3265 <chapter id="ch-MiscWidgets">
3266 <title>Miscellaneous Widgets</title>
3267
3268 <!-- ----------------------------------------------------------------- -->
3269 <sect1 id="sec-Labels">
3270 <title>Labels</title>
3271
3272 <para>Labels are used a lot in GTK, and are relatively simple. Labels emit
3273 no signals as they do not have an associated X window. If you need to
3274 catch signals, or do clipping, place it inside a <link linkend="sec-EventBox">
3275 EventBox</link> widget or a Button widget.</para>
3276
3277 <para>To create a new label, use:</para>
3278
3279 <programlisting role="C">
3280 GtkWidget *gtk_label_new( char *str );
3281 </programlisting>
3282
3283 <para>The sole argument is the string you wish the label to display.</para>
3284
3285 <para>To change the label's text after creation, use the function:</para>
3286
3287 <programlisting role="C">
3288 void gtk_label_set_text( GtkLabel *label,
3289                          char     *str );
3290 </programlisting>
3291
3292 <para>The first argument is the label you created previously (cast
3293 using the <literal>GTK_LABEL()</literal> macro), and the second is the new string.</para>
3294
3295 <para>The space needed for the new string will be automatically adjusted if
3296 needed. You can produce multi-line labels by putting line breaks in
3297 the label string.</para>
3298
3299 <para>To retrieve the current string, use:</para>
3300
3301 <programlisting role="C">
3302 void gtk_label_get( GtkLabel  *label,
3303                     char     **str );
3304 </programlisting>
3305
3306 <para>The first argument is the label you've created, and the second,
3307 the return for the string. Do not free the return string, as it is
3308 used internally by GTK.</para>
3309
3310 <para>The label text can be justified using:</para>
3311
3312 <programlisting role="C">
3313 void gtk_label_set_justify( GtkLabel         *label,
3314                             GtkJustification  jtype );
3315 </programlisting>
3316
3317 <para>Values for <literal>jtype</literal> are:</para>
3318 <programlisting role="C">
3319   GTK_JUSTIFY_LEFT
3320   GTK_JUSTIFY_RIGHT
3321   GTK_JUSTIFY_CENTER (the default)
3322   GTK_JUSTIFY_FILL
3323 </programlisting>
3324
3325 <para>The label widget is also capable of line wrapping the text
3326 automatically. This can be activated using:</para>
3327
3328 <programlisting role="C">
3329 void gtk_label_set_line_wrap (GtkLabel *label,
3330                               gboolean  wrap);
3331 </programlisting>
3332
3333 <para>The <literal>wrap</literal> argument takes a TRUE or FALSE value.</para>
3334
3335 <para>If you want your label underlined, then you can set a pattern on the
3336 label:</para>
3337
3338 <programlisting role="C">
3339 void       gtk_label_set_pattern   (GtkLabel          *label,
3340                                     const gchar       *pattern);
3341 </programlisting>
3342
3343 <para>The pattern argument indicates how the underlining should look. It
3344 consists of a string of underscore and space characters. An underscore
3345 indicates that the corresponding character in the label should be
3346 underlined. For example, the string <literal>"__     __"</literal> would underline the
3347 first two characters and eight and ninth characters.</para>
3348
3349 <para>Below is a short example to illustrate these functions. This example
3350 makes use of the Frame widget to better demonstrate the label
3351 styles. You can ignore this for now as the <link linkend="sec-Frames">Frame</link> widget is explained later on.</para>
3352
3353 <programlisting role="C">
3354 <!-- example-start label label.c -->
3355
3356 #include &lt;gtk/gtk.h&gt;
3357
3358 int main( int   argc,
3359           char *argv[] )
3360 {
3361   static GtkWidget *window = NULL;
3362   GtkWidget *hbox;
3363   GtkWidget *vbox;
3364   GtkWidget *frame;
3365   GtkWidget *label;
3366
3367   /* Initialise GTK */
3368   gtk_init(&amp;argc, &amp;argv);
3369
3370   window = gtk_window_new (GTK_WINDOW_TOPLEVEL);
3371   gtk_signal_connect (GTK_OBJECT (window), "destroy",
3372                       GTK_SIGNAL_FUNC(gtk_main_quit),
3373                       NULL);
3374
3375   gtk_window_set_title (GTK_WINDOW (window), "Label");
3376   vbox = gtk_vbox_new (FALSE, 5);
3377   hbox = gtk_hbox_new (FALSE, 5);
3378   gtk_container_add (GTK_CONTAINER (window), hbox);
3379   gtk_box_pack_start (GTK_BOX (hbox), vbox, FALSE, FALSE, 0);
3380   gtk_container_set_border_width (GTK_CONTAINER (window), 5);
3381   
3382   frame = gtk_frame_new ("Normal Label");
3383   label = gtk_label_new ("This is a Normal label");
3384   gtk_container_add (GTK_CONTAINER (frame), label);
3385   gtk_box_pack_start (GTK_BOX (vbox), frame, FALSE, FALSE, 0);
3386   
3387   frame = gtk_frame_new ("Multi-line Label");
3388   label = gtk_label_new ("This is a Multi-line label.\nSecond line\n" \
3389                          "Third line");
3390   gtk_container_add (GTK_CONTAINER (frame), label);
3391   gtk_box_pack_start (GTK_BOX (vbox), frame, FALSE, FALSE, 0);
3392   
3393   frame = gtk_frame_new ("Left Justified Label");
3394   label = gtk_label_new ("This is a Left-Justified\n" \
3395                          "Multi-line label.\nThird      line");
3396   gtk_label_set_justify (GTK_LABEL (label), GTK_JUSTIFY_LEFT);
3397   gtk_container_add (GTK_CONTAINER (frame), label);
3398   gtk_box_pack_start (GTK_BOX (vbox), frame, FALSE, FALSE, 0);
3399   
3400   frame = gtk_frame_new ("Right Justified Label");
3401   label = gtk_label_new ("This is a Right-Justified\nMulti-line label.\n" \
3402                          "Fourth line, (j/k)");
3403   gtk_label_set_justify (GTK_LABEL (label), GTK_JUSTIFY_RIGHT);
3404   gtk_container_add (GTK_CONTAINER (frame), label);
3405   gtk_box_pack_start (GTK_BOX (vbox), frame, FALSE, FALSE, 0);
3406
3407   vbox = gtk_vbox_new (FALSE, 5);
3408   gtk_box_pack_start (GTK_BOX (hbox), vbox, FALSE, FALSE, 0);
3409   frame = gtk_frame_new ("Line wrapped label");
3410   label = gtk_label_new ("This is an example of a line-wrapped label.  It " \
3411                          "should not be taking up the entire             " /* big space to test spacing */\
3412                          "width allocated to it, but automatically " \
3413                          "wraps the words to fit.  " \
3414                          "The time has come, for all good men, to come to " \
3415                          "the aid of their party.  " \
3416                          "The sixth sheik's six sheep's sick.\n" \
3417                          "     It supports multiple paragraphs correctly, " \
3418                          "and  correctly   adds "\
3419                          "many          extra  spaces. ");
3420   gtk_label_set_line_wrap (GTK_LABEL (label), TRUE);
3421   gtk_container_add (GTK_CONTAINER (frame), label);
3422   gtk_box_pack_start (GTK_BOX (vbox), frame, FALSE, FALSE, 0);
3423   
3424   frame = gtk_frame_new ("Filled, wrapped label");
3425   label = gtk_label_new ("This is an example of a line-wrapped, filled label.  " \
3426                          "It should be taking "\
3427                          "up the entire              width allocated to it.  " \
3428                          "Here is a sentence to prove "\
3429                          "my point.  Here is another sentence. "\
3430                          "Here comes the sun, do de do de do.\n"\
3431                          "    This is a new paragraph.\n"\
3432                          "    This is another newer, longer, better " \
3433                          "paragraph.  It is coming to an end, "\
3434                          "unfortunately.");
3435   gtk_label_set_justify (GTK_LABEL (label), GTK_JUSTIFY_FILL);
3436   gtk_label_set_line_wrap (GTK_LABEL (label), TRUE);
3437   gtk_container_add (GTK_CONTAINER (frame), label);
3438   gtk_box_pack_start (GTK_BOX (vbox), frame, FALSE, FALSE, 0);
3439   
3440   frame = gtk_frame_new ("Underlined label");
3441   label = gtk_label_new ("This label is underlined!\n"
3442                          "This one is underlined in quite a funky fashion");
3443   gtk_label_set_justify (GTK_LABEL (label), GTK_JUSTIFY_LEFT);
3444   gtk_label_set_pattern (GTK_LABEL (label),
3445                          "_________________________ _ _________ _ ______     __ _______ ___");
3446   gtk_container_add (GTK_CONTAINER (frame), label);
3447   gtk_box_pack_start (GTK_BOX (vbox), frame, FALSE, FALSE, 0);
3448   
3449   gtk_widget_show_all (window);
3450
3451   gtk_main ();
3452   
3453   return(0);
3454 }
3455 <!-- example-end -->
3456 </programlisting>
3457
3458 </sect1>
3459
3460 <!-- ----------------------------------------------------------------- -->
3461 <sect1 id="sec-Arrows">
3462 <title>Arrows</title>
3463
3464 <para>The Arrow widget draws an arrowhead, facing in a number of possible
3465 directions and having a number of possible styles. It can be very
3466 useful when placed on a button in many applications. Like the Label
3467 widget, it emits no signals.</para>
3468
3469 <para>There are only two functions for manipulating an Arrow widget:</para>
3470
3471 <programlisting role="C">
3472 GtkWidget *gtk_arrow_new( GtkArrowType   arrow_type,
3473                           GtkShadowType  shadow_type );
3474
3475 void gtk_arrow_set( GtkArrow      *arrow,
3476                     GtkArrowType   arrow_type,
3477                     GtkShadowType  shadow_type );
3478 </programlisting>
3479
3480 <para>The first creates a new arrow widget with the indicated type and
3481 appearance. The second allows these values to be altered
3482 retrospectively. The <literal>arrow_type</literal> argument may take one of the
3483 following values:</para>
3484
3485 <programlisting role="C">
3486   GTK_ARROW_UP
3487   GTK_ARROW_DOWN
3488   GTK_ARROW_LEFT
3489   GTK_ARROW_RIGHT
3490 </programlisting>
3491
3492 <para>These values obviously indicate the direction in which the arrow will
3493 point. The <literal>shadow_type</literal> argument may take one of these values:</para>
3494
3495 <programlisting role="C">
3496   GTK_SHADOW_IN
3497   GTK_SHADOW_OUT (the default)
3498   GTK_SHADOW_ETCHED_IN
3499   GTK_SHADOW_ETCHED_OUT
3500 </programlisting>
3501
3502 <para>Here's a brief example to illustrate their use.</para>
3503
3504 <programlisting role="C">
3505 <!-- example-start arrow arrow.c -->
3506
3507 #include &lt;gtk/gtk.h&gt;
3508
3509 /* Create an Arrow widget with the specified parameters
3510  * and pack it into a button */
3511 GtkWidget *create_arrow_button( GtkArrowType  arrow_type,
3512                                 GtkShadowType shadow_type )
3513 {
3514   GtkWidget *button;
3515   GtkWidget *arrow;
3516
3517   button = gtk_button_new();
3518   arrow = gtk_arrow_new (arrow_type, shadow_type);
3519
3520   gtk_container_add (GTK_CONTAINER (button), arrow);
3521   
3522   gtk_widget_show(button);
3523   gtk_widget_show(arrow);
3524
3525   return(button);
3526 }
3527
3528 int main( int   argc,
3529           char *argv[] )
3530 {
3531   /* GtkWidget is the storage type for widgets */
3532   GtkWidget *window;
3533   GtkWidget *button;
3534   GtkWidget *box;
3535
3536   /* Initialize the toolkit */
3537   gtk_init (&amp;argc, &amp;argv);
3538
3539   /* Create a new window */
3540   window = gtk_window_new (GTK_WINDOW_TOPLEVEL);
3541
3542   gtk_window_set_title (GTK_WINDOW (window), "Arrow Buttons");
3543
3544   /* It's a good idea to do this for all windows. */
3545   gtk_signal_connect (GTK_OBJECT (window), "destroy",
3546                       GTK_SIGNAL_FUNC (gtk_main_quit), NULL);
3547
3548   /* Sets the border width of the window. */
3549   gtk_container_set_border_width (GTK_CONTAINER (window), 10);
3550
3551   /* Create a box to hold the arrows/buttons */
3552   box = gtk_hbox_new (FALSE, 0);
3553   gtk_container_set_border_width (GTK_CONTAINER (box), 2);
3554   gtk_container_add (GTK_CONTAINER (window), box);
3555
3556   /* Pack and show all our widgets */
3557   gtk_widget_show(box);
3558
3559   button = create_arrow_button(GTK_ARROW_UP, GTK_SHADOW_IN);
3560   gtk_box_pack_start (GTK_BOX (box), button, FALSE, FALSE, 3);
3561
3562   button = create_arrow_button(GTK_ARROW_DOWN, GTK_SHADOW_OUT);
3563   gtk_box_pack_start (GTK_BOX (box), button, FALSE, FALSE, 3);
3564   
3565   button = create_arrow_button(GTK_ARROW_LEFT, GTK_SHADOW_ETCHED_IN);
3566   gtk_box_pack_start (GTK_BOX (box), button, FALSE, FALSE, 3);
3567   
3568   button = create_arrow_button(GTK_ARROW_RIGHT, GTK_SHADOW_ETCHED_OUT);
3569   gtk_box_pack_start (GTK_BOX (box), button, FALSE, FALSE, 3);
3570   
3571   gtk_widget_show (window);
3572   
3573   /* Rest in gtk_main and wait for the fun to begin! */
3574   gtk_main ();
3575   
3576   return(0);
3577 }
3578 <!-- example-end -->
3579 </programlisting>
3580
3581 </sect1>
3582
3583 <!-- ----------------------------------------------------------------- -->
3584 <sect1 id="sec-TheTooltipsObject">
3585 <title>The Tooltips Object</title>
3586
3587 <para>These are the little text strings that pop up when you leave your
3588 pointer over a button or other widget for a few seconds. They are easy
3589 to use, so I will just explain them without giving an example. If you
3590 want to see some code, take a look at the testgtk.c program
3591 distributed with GTK.</para>
3592
3593 <para>Widgets that do not receive events (widgets that do not have their
3594 own window) will not work with tooltips.</para>
3595
3596 <para>The first call you will use creates a new tooltip. You only need to do
3597 this once for a set of tooltips as the <literal>GtkTooltips</literal> object this
3598 function returns can be used to create multiple tooltips.</para>
3599
3600 <programlisting role="C">
3601 GtkTooltips *gtk_tooltips_new( void );
3602 </programlisting>
3603
3604 <para>Once you have created a new tooltip, and the widget you wish to use it
3605 on, simply use this call to set it:</para>
3606
3607 <programlisting role="C">
3608 void gtk_tooltips_set_tip( GtkTooltips *tooltips,
3609                            GtkWidget   *widget,
3610                            const gchar *tip_text,
3611                            const gchar *tip_private );
3612 </programlisting>
3613
3614 <para>The first argument is the tooltip you've already created, followed by
3615 the widget you wish to have this tooltip pop up for, and the text you
3616 wish it to say. The last argument is a text string that can be used as
3617 an identifier when using GtkTipsQuery to implement context sensitive
3618 help. For now, you can set it to NULL.</para>
3619
3620 <!-- TODO: sort out what how to do the context sensitive help -->
3621
3622 <para>Here's a short example:</para>
3623
3624 <programlisting role="C">
3625 GtkTooltips *tooltips;
3626 GtkWidget *button;
3627 .
3628 .
3629 .
3630 tooltips = gtk_tooltips_new ();
3631 button = gtk_button_new_with_label ("button 1");
3632 .
3633 .
3634 .
3635 gtk_tooltips_set_tip (tooltips, button, "This is button 1", NULL);
3636 </programlisting>
3637
3638 <para>There are other calls that can be used with tooltips. I will just list
3639 them with a brief description of what they do.</para>
3640
3641 <programlisting role="C">
3642 void gtk_tooltips_enable( GtkTooltips *tooltips );
3643 </programlisting>
3644
3645 <para>Enable a disabled set of tooltips.</para>
3646
3647 <programlisting role="C">
3648 void gtk_tooltips_disable( GtkTooltips *tooltips );
3649 </programlisting>
3650
3651 <para>Disable an enabled set of tooltips.</para>
3652
3653 <programlisting role="C">
3654 void gtk_tooltips_set_delay( GtkTooltips *tooltips,
3655                              gint         delay );
3656 </programlisting>
3657
3658 <para>Sets how many milliseconds you have to hold your pointer over the
3659 widget before the tooltip will pop up. The default is 500
3660 milliseconds (half a second).</para>
3661
3662 <programlisting role="C">
3663 void gtk_tooltips_set_colors( GtkTooltips *tooltips,
3664                               GdkColor    *background,
3665                               GdkColor    *foreground );
3666 </programlisting>
3667
3668 <para>Set the foreground and background color of the tooltips.</para>
3669
3670 <para>And that's all the functions associated with tooltips. More than
3671 you'll ever want to know :-)</para>
3672
3673 </sect1>
3674
3675 <!-- ----------------------------------------------------------------- -->
3676 <sect1 id="sec-ProgressBars">
3677 <title>Progress Bars</title>
3678
3679 <para>Progress bars are used to show the status of an operation. They are
3680 pretty easy to use, as you will see with the code below. But first
3681 lets start out with the calls to create a new progress bar.</para>
3682
3683 <para>There are two ways to create a progress bar, one simple that takes
3684 no arguments, and one that takes an Adjustment object as an
3685 argument. If the former is used, the progress bar creates its own
3686 adjustment object.</para>
3687
3688 <programlisting role="C">
3689 GtkWidget *gtk_progress_bar_new( void );
3690
3691 GtkWidget *gtk_progress_bar_new_with_adjustment( GtkAdjustment *adjustment );
3692 </programlisting>
3693
3694 <para>The second method has the advantage that we can use the adjustment
3695 object to specify our own range parameters for the progress bar.</para>
3696
3697 <para>The adjustment of a progress object can be changed dynamically using:</para>
3698
3699 <programlisting role="C">
3700 void gtk_progress_set_adjustment( GtkProgress   *progress,
3701                                   GtkAdjustment *adjustment );
3702 </programlisting>
3703
3704 <para>Now that the progress bar has been created we can use it.</para>
3705
3706 <programlisting role="C">
3707 void gtk_progress_bar_update( GtkProgressBar *pbar,
3708                               gfloat          percentage );
3709 </programlisting>
3710
3711 <para>The first argument is the progress bar you wish to operate on, and the
3712 second argument is the amount "completed", meaning the amount the
3713 progress bar has been filled from 0-100%. This is passed to the
3714 function as a real number ranging from 0 to 1.</para>
3715
3716 <para>GTK v1.2 has added new functionality to the progress bar that enables
3717 it to display its value in different ways, and to inform the user of
3718 its current value and its range.</para>
3719
3720 <para>A progress bar may be set to one of a number of orientations using the
3721 function</para>
3722
3723 <programlisting role="C">
3724 void gtk_progress_bar_set_orientation( GtkProgressBar *pbar,
3725                                        GtkProgressBarOrientation orientation );
3726 </programlisting>
3727
3728 <para>The <literal>orientation</literal> argument may take one of the following
3729 values to indicate the direction in which the progress bar moves:</para>
3730
3731 <programlisting role="C">
3732   GTK_PROGRESS_LEFT_TO_RIGHT
3733   GTK_PROGRESS_RIGHT_TO_LEFT
3734   GTK_PROGRESS_BOTTOM_TO_TOP
3735   GTK_PROGRESS_TOP_TO_BOTTOM
3736 </programlisting>
3737
3738 <para>When used as a measure of how far a process has progressed, the
3739 ProgressBar can be set to display its value in either a continuous
3740 or discrete mode. In continuous mode, the progress bar is updated for
3741 each value. In discrete mode, the progress bar is updated in a number
3742 of discrete blocks. The number of blocks is also configurable.</para>
3743
3744 <para>The style of a progress bar can be set using the following function.</para>
3745
3746 <programlisting role="C">
3747 void gtk_progress_bar_set_bar_style( GtkProgressBar      *pbar,
3748                                      GtkProgressBarStyle  style );
3749 </programlisting>
3750
3751 <para>The <literal>style</literal> parameter can take one of two values:</para>
3752
3753 <programlisting role="C">
3754   GTK_PROGRESS_CONTINUOUS
3755   GTK_PROGRESS_DISCRETE
3756 </programlisting>
3757
3758 <para>The number of discrete blocks can be set by calling</para>
3759
3760 <programlisting role="C">
3761 void gtk_progress_bar_set_discrete_blocks( GtkProgressBar *pbar,
3762                                            guint           blocks );
3763 </programlisting>
3764
3765 <para>As well as indicating the amount of progress that has occured, the
3766 progress bar may be set to just indicate that there is some
3767 activity. This can be useful in situations where progress cannot be
3768 measured against a value range. Activity mode is not effected by the
3769 bar style that is described above, and overrides it. This mode is
3770 either TRUE or FALSE, and is selected by the following function.</para>
3771
3772 <programlisting role="C">
3773 void gtk_progress_set_activity_mode( GtkProgress *progress,
3774                                      guint        activity_mode );
3775 </programlisting>
3776
3777 <para>The step size of the activity indicator, and the number of blocks are
3778 set using the following functions.</para>
3779
3780 <programlisting role="C">
3781 void gtk_progress_bar_set_activity_step( GtkProgressBar *pbar,
3782                                          guint           step );
3783
3784 void gtk_progress_bar_set_activity_blocks( GtkProgressBar *pbar,
3785                                            guint           blocks );
3786 </programlisting>
3787
3788 <para>When in continuous mode, the progress bar can also display a
3789 configurable text string within its trough, using the following
3790 function.</para>
3791
3792 <programlisting role="C">
3793 void gtk_progress_set_format_string( GtkProgress *progress,
3794                                      gchar       *format);
3795 </programlisting>
3796
3797 <para>The <literal>format</literal> argument is similiar to one that would be used in a C
3798 <literal>printf</literal> statement. The following directives may be used within the
3799 format string:</para>
3800
3801 <itemizedlist>
3802 <listitem><simpara> %p - percentage</simpara>
3803 </listitem>
3804 <listitem><simpara> %v - value</simpara>
3805 </listitem>
3806 <listitem><simpara> %l - lower range value</simpara>
3807 </listitem>
3808 <listitem><simpara> %u - upper range value</simpara>
3809 </listitem>
3810 </itemizedlist>
3811
3812 <para>The displaying of this text string can be toggled using:</para>
3813
3814 <programlisting role="C">
3815 void gtk_progress_set_show_text( GtkProgress *progress,
3816                                  gint         show_text );
3817 </programlisting>
3818
3819 <para>The <literal>show_text</literal> argument is a boolean TRUE/FALSE value. The
3820 appearance of the text can be modified further using:</para>
3821
3822 <programlisting role="C">
3823 void gtk_progress_set_text_alignment( GtkProgress   *progress,
3824                                       gfloat         x_align,
3825                                       gfloat         y_align );
3826 </programlisting>
3827
3828 <para>The <literal>x_align</literal> and <literal>y_align</literal> arguments take values between 0.0
3829 and 1.0. Their values indicate the position of the text string within
3830 the trough. Values of 0.0 for both would place the string in the top
3831 left hand corner; values of 0.5 (the default) centres the text, and
3832 values of 1.0 places the text in the lower right hand corner.</para>
3833
3834 <para>The current text setting of a progress object can be retrieved using
3835 the current or a specified adjustment value using the following two
3836 functions. The character string returned by these functions should be
3837 freed by the application (using the g_free() function). These
3838 functions return the formatted string that would be displayed within
3839 the trough.</para>
3840
3841 <programlisting role="C">
3842 gchar *gtk_progress_get_current_text( GtkProgress   *progress );
3843
3844 gchar *gtk_progress_get_text_from_value( GtkProgress *progress,
3845                                          gfloat       value );
3846 </programlisting>
3847
3848 <para>There is yet another way to change the range and value of a progress
3849 object using the following function:</para>
3850
3851 <programlisting role="C">
3852 void gtk_progress_configure( GtkProgress  *progress,
3853                              gfloat        value,
3854                              gfloat        min,
3855                              gfloat        max );
3856 </programlisting>
3857
3858 <para>This function provides quite a simple interface to the range and value
3859 of a progress object.</para>
3860
3861 <para>The remaining functions can be used to get and set the current value
3862 of a progess object in various types and formats:</para>
3863
3864 <programlisting role="C">
3865 void gtk_progress_set_percentage( GtkProgress *progress,
3866                                   gfloat       percentage );
3867
3868 void gtk_progress_set_value( GtkProgress *progress,
3869                              gfloat       value );
3870
3871 gfloat gtk_progress_get_value( GtkProgress *progress );
3872
3873 gfloat gtk_progress_get_current_percentage( GtkProgress *progress );
3874
3875 gfloat gtk_progress_get_percentage_from_value( GtkProgress *progress,
3876                                                gfloat       value );
3877 </programlisting>
3878
3879 <para>These functions are pretty self explanatory. The last function uses
3880 the the adjustment of the specified progess object to compute the
3881 percentage value of the given range value.</para>
3882
3883 <para>Progress Bars are usually used with timeouts or other such functions
3884 (see section on <link linkend="ch-Timeouts">Timeouts, I/O and Idle Functions</link>) to give
3885 the illusion of multitasking. All will employ the
3886 gtk_progress_bar_update function in the same manner.</para>
3887
3888 <para>Here is an example of the progress bar, updated using timeouts. This
3889 code also shows you how to reset the Progress Bar.</para>
3890
3891 <programlisting role="C">
3892 <!-- example-start progressbar progressbar.c -->
3893
3894 #include &lt;gtk/gtk.h&gt;
3895
3896 typedef struct _ProgressData {
3897     GtkWidget *window;
3898     GtkWidget *pbar;
3899     int timer;
3900 } ProgressData;
3901
3902 /* Update the value of the progress bar so that we get
3903  * some movement */
3904 gint progress_timeout( gpointer data )
3905 {
3906     gfloat new_val;
3907     GtkAdjustment *adj;
3908
3909     /* Calculate the value of the progress bar using the
3910      * value range set in the adjustment object */
3911
3912     new_val = gtk_progress_get_value( GTK_PROGRESS(data) ) + 1;
3913
3914     adj = GTK_PROGRESS (data)->adjustment;
3915     if (new_val > adj->upper)
3916       new_val = adj->lower;
3917
3918     /* Set the new value */
3919     gtk_progress_set_value (GTK_PROGRESS (data), new_val);
3920
3921     /* As this is a timeout function, return TRUE so that it
3922      * continues to get called */
3923     return(TRUE);
3924
3925
3926 /* Callback that toggles the text display within the progress
3927  * bar trough */
3928 void toggle_show_text( GtkWidget    *widget,
3929                        ProgressData *pdata )
3930 {
3931     gtk_progress_set_show_text (GTK_PROGRESS (pdata->pbar),
3932                                 GTK_TOGGLE_BUTTON (widget)->active);
3933 }
3934
3935 /* Callback that toggles the activity mode of the progress
3936  * bar */
3937 void toggle_activity_mode( GtkWidget    *widget,
3938                            ProgressData *pdata )
3939 {
3940     gtk_progress_set_activity_mode (GTK_PROGRESS (pdata->pbar),
3941                                     GTK_TOGGLE_BUTTON (widget)->active);
3942 }
3943
3944 /* Callback that toggles the continuous mode of the progress
3945  * bar */
3946 void set_continuous_mode( GtkWidget    *widget,
3947                           ProgressData *pdata )
3948 {
3949     gtk_progress_bar_set_bar_style (GTK_PROGRESS_BAR (pdata->pbar),
3950                                     GTK_PROGRESS_CONTINUOUS);
3951 }
3952
3953 /* Callback that toggles the discrete mode of the progress
3954  * bar */
3955 void set_discrete_mode( GtkWidget    *widget,
3956                         ProgressData *pdata )
3957 {
3958     gtk_progress_bar_set_bar_style (GTK_PROGRESS_BAR (pdata->pbar),
3959                                     GTK_PROGRESS_DISCRETE);
3960 }
3961  
3962 /* Clean up allocated memory and remove the timer */
3963 void destroy_progress( GtkWidget     *widget,
3964                        ProgressData *pdata)
3965 {
3966     gtk_timeout_remove (pdata->timer);
3967     pdata->timer = 0;
3968     pdata->window = NULL;
3969     g_free(pdata);
3970     gtk_main_quit();
3971 }
3972
3973 int main( int   argc,
3974           char *argv[])
3975 {
3976     ProgressData *pdata;
3977     GtkWidget *align;
3978     GtkWidget *separator;
3979     GtkWidget *table;
3980     GtkAdjustment *adj;
3981     GtkWidget *button;
3982     GtkWidget *check;
3983     GtkWidget *vbox;
3984
3985     gtk_init (&amp;argc, &amp;argv);
3986
3987     /* Allocate memory for the data that is passwd to the callbacks */
3988     pdata = g_malloc( sizeof(ProgressData) );
3989   
3990     pdata->window = gtk_window_new (GTK_WINDOW_TOPLEVEL);
3991     gtk_window_set_policy (GTK_WINDOW (pdata->window), FALSE, FALSE, TRUE);
3992
3993     gtk_signal_connect (GTK_OBJECT (pdata->window), "destroy",
3994                         GTK_SIGNAL_FUNC (destroy_progress),
3995                         pdata);
3996     gtk_window_set_title (GTK_WINDOW (pdata->window), "GtkProgressBar");
3997     gtk_container_set_border_width (GTK_CONTAINER (pdata->window), 0);
3998
3999     vbox = gtk_vbox_new (FALSE, 5);
4000     gtk_container_set_border_width (GTK_CONTAINER (vbox), 10);
4001     gtk_container_add (GTK_CONTAINER (pdata->window), vbox);
4002     gtk_widget_show(vbox);
4003   
4004     /* Create a centering alignment object */
4005     align = gtk_alignment_new (0.5, 0.5, 0, 0);
4006     gtk_box_pack_start (GTK_BOX (vbox), align, FALSE, FALSE, 5);
4007     gtk_widget_show(align);
4008
4009     /* Create a Adjusment object to hold the range of the
4010      * progress bar */
4011     adj = (GtkAdjustment *) gtk_adjustment_new (0, 1, 150, 0, 0, 0);
4012
4013     /* Create the GtkProgressBar using the adjustment */
4014     pdata->pbar = gtk_progress_bar_new_with_adjustment (adj);
4015
4016     /* Set the format of the string that can be displayed in the
4017      * trough of the progress bar:
4018      * %p - percentage
4019      * %v - value
4020      * %l - lower range value
4021      * %u - upper range value */
4022     gtk_progress_set_format_string (GTK_PROGRESS (pdata->pbar),
4023                                     "%v from [%l-%u] (=%p%%)");
4024     gtk_container_add (GTK_CONTAINER (align), pdata->pbar);
4025     gtk_widget_show(pdata->pbar);
4026
4027     /* Add a timer callback to update the value of the progress bar */
4028     pdata->timer = gtk_timeout_add (100, progress_timeout, pdata->pbar);
4029
4030     separator = gtk_hseparator_new ();
4031     gtk_box_pack_start (GTK_BOX (vbox), separator, FALSE, FALSE, 0);
4032     gtk_widget_show(separator);
4033
4034     /* rows, columns, homogeneous */
4035     table = gtk_table_new (2, 3, FALSE);
4036     gtk_box_pack_start (GTK_BOX (vbox), table, FALSE, TRUE, 0);
4037     gtk_widget_show(table);
4038
4039     /* Add a check button to select displaying of the trough text */
4040     check = gtk_check_button_new_with_label ("Show text");
4041     gtk_table_attach (GTK_TABLE (table), check, 0, 1, 0, 1,
4042                       GTK_EXPAND | GTK_FILL, GTK_EXPAND | GTK_FILL,
4043                       5, 5);
4044     gtk_signal_connect (GTK_OBJECT (check), "clicked",
4045                         GTK_SIGNAL_FUNC (toggle_show_text),
4046                         pdata);
4047     gtk_widget_show(check);
4048
4049     /* Add a check button to toggle activity mode */
4050     check = gtk_check_button_new_with_label ("Activity mode");
4051     gtk_table_attach (GTK_TABLE (table), check, 0, 1, 1, 2,
4052                       GTK_EXPAND | GTK_FILL, GTK_EXPAND | GTK_FILL,
4053                       5, 5);
4054     gtk_signal_connect (GTK_OBJECT (check), "clicked",
4055                         GTK_SIGNAL_FUNC (toggle_activity_mode),
4056                         pdata);
4057     gtk_widget_show(check);
4058
4059     separator = gtk_vseparator_new ();
4060     gtk_table_attach (GTK_TABLE (table), separator, 1, 2, 0, 2,
4061                       GTK_EXPAND | GTK_FILL, GTK_EXPAND | GTK_FILL,
4062                       5, 5);
4063     gtk_widget_show(separator);
4064
4065     /* Add a radio button to select continuous display mode */
4066     button = gtk_radio_button_new_with_label (NULL, "Continuous");
4067     gtk_table_attach (GTK_TABLE (table), button, 2, 3, 0, 1,
4068                       GTK_EXPAND | GTK_FILL, GTK_EXPAND | GTK_FILL,
4069                       5, 5);
4070     gtk_signal_connect (GTK_OBJECT (button), "clicked",
4071                         GTK_SIGNAL_FUNC (set_continuous_mode),
4072                         pdata);
4073     gtk_widget_show (button);
4074
4075     /* Add a radio button to select discrete display mode */
4076     button = gtk_radio_button_new_with_label(
4077                gtk_radio_button_group (GTK_RADIO_BUTTON (button)),
4078                "Discrete");
4079     gtk_table_attach (GTK_TABLE (table), button, 2, 3, 1, 2,
4080                       GTK_EXPAND | GTK_FILL, GTK_EXPAND | GTK_FILL,
4081                       5, 5);
4082     gtk_signal_connect (GTK_OBJECT (button), "clicked",
4083                         GTK_SIGNAL_FUNC (set_discrete_mode),
4084                         pdata);
4085     gtk_widget_show (button);
4086
4087     separator = gtk_hseparator_new ();
4088     gtk_box_pack_start (GTK_BOX (vbox), separator, FALSE, FALSE, 0);
4089     gtk_widget_show(separator);
4090
4091     /* Add a button to exit the program */
4092     button = gtk_button_new_with_label ("close");
4093     gtk_signal_connect_object (GTK_OBJECT (button), "clicked",
4094                                (GtkSignalFunc) gtk_widget_destroy,
4095                                GTK_OBJECT (pdata->window));
4096     gtk_box_pack_start (GTK_BOX (vbox), button, FALSE, FALSE, 0);
4097
4098     /* This makes it so the button is the default. */
4099     GTK_WIDGET_SET_FLAGS (button, GTK_CAN_DEFAULT);
4100
4101     /* This grabs this button to be the default button. Simply hitting
4102      * the "Enter" key will cause this button to activate. */
4103     gtk_widget_grab_default (button);
4104     gtk_widget_show(button);
4105
4106     gtk_widget_show (pdata->window);
4107
4108     gtk_main ();
4109     
4110     return(0);
4111 }
4112 <!-- example-end -->
4113 </programlisting>
4114
4115 </sect1>
4116
4117 <!-- ----------------------------------------------------------------- -->
4118 <sect1 id="sec-Dialogs">
4119 <title>Dialogs</title>
4120
4121 <para>The Dialog widget is very simple, and is actually just a window with a
4122 few things pre-packed into it for you. The structure for a Dialog is:</para>
4123
4124 <programlisting role="C">
4125 struct GtkDialog
4126 {
4127       GtkWindow window;
4128     
4129       GtkWidget *vbox;
4130       GtkWidget *action_area;
4131 };
4132 </programlisting>
4133
4134 <para>So you see, it simply creates a window, and then packs a vbox into the
4135 top, which contains a separator and then an hbox called the
4136 "action_area".</para>
4137
4138 <para>The Dialog widget can be used for pop-up messages to the user, and
4139 other similar tasks. It is really basic, and there is only one
4140 function for the dialog box, which is:</para>
4141
4142 <programlisting role="C">
4143 GtkWidget *gtk_dialog_new( void );
4144 </programlisting>
4145
4146 <para>So to create a new dialog box, use,</para>
4147
4148 <programlisting role="C">
4149     GtkWidget *window;
4150     window = gtk_dialog_new ();
4151 </programlisting>
4152
4153 <para>This will create the dialog box, and it is now up to you to use it.
4154 You could pack a button in the action_area by doing something like this:</para>
4155
4156 <programlisting role="C">
4157     button = ...
4158     gtk_box_pack_start (GTK_BOX (GTK_DIALOG (window)->action_area),
4159                         button, TRUE, TRUE, 0);
4160     gtk_widget_show (button);
4161 </programlisting>
4162
4163 <para>And you could add to the vbox area by packing, for instance, a label 
4164 in it, try something like this:</para>
4165
4166 <programlisting role="C">
4167     label = gtk_label_new ("Dialogs are groovy");
4168     gtk_box_pack_start (GTK_BOX (GTK_DIALOG (window)->vbox),
4169                         label, TRUE, TRUE, 0);
4170     gtk_widget_show (label);
4171 </programlisting>
4172
4173 <para>As an example in using the dialog box, you could put two buttons in
4174 the action_area, a Cancel button and an Ok button, and a label in the
4175 vbox area, asking the user a question or giving an error etc. Then
4176 you could attach a different signal to each of the buttons and perform
4177 the operation the user selects.</para>
4178
4179 <para>If the simple functionality provided by the default vertical and
4180 horizontal boxes in the two areas doesn't give you enough control for
4181 your application, then you can simply pack another layout widget into
4182 the boxes provided. For example, you could pack a table into the
4183 vertical box.</para>
4184
4185 </sect1>
4186
4187 <!-- ----------------------------------------------------------------- -->
4188 <sect1 id="sec-Pixmaps">
4189 <title>Pixmaps</title>
4190
4191 <para>Pixmaps are data structures that contain pictures. These pictures can
4192 be used in various places, but most commonly as icons on the X
4193 desktop, or as cursors.</para>
4194
4195 <para>A pixmap which only has 2 colors is called a bitmap, and there are a
4196 few additional routines for handling this common special case.</para>
4197
4198 <para>To understand pixmaps, it would help to understand how X window
4199 system works. Under X, applications do not need to be running on the
4200 same computer that is interacting with the user. Instead, the various
4201 applications, called "clients", all communicate with a program which
4202 displays the graphics and handles the keyboard and mouse. This
4203 program which interacts directly with the user is called a "display
4204 server" or "X server." Since the communication might take place over
4205 a network, it's important to keep some information with the X server.
4206 Pixmaps, for example, are stored in the memory of the X server. This
4207 means that once pixmap values are set, they don't need to keep getting
4208 transmitted over the network; instead a command is sent to "display
4209 pixmap number XYZ here." Even if you aren't using X with GTK
4210 currently, using constructs such as Pixmaps will make your programs
4211 work acceptably under X.</para>
4212
4213 <para>To use pixmaps in GTK, we must first build a GdkPixmap structure using
4214 routines from the GDK layer. Pixmaps can either be created from
4215 in-memory data, or from data read from a file. We'll go through each
4216 of the calls to create a pixmap.</para>
4217
4218 <programlisting role="C">
4219 GdkPixmap *gdk_bitmap_create_from_data( GdkWindow *window,
4220                                         gchar     *data,
4221                                         gint       width,
4222                                         gint       height );
4223 </programlisting>
4224
4225 <para>This routine is used to create a single-plane pixmap (2 colors) from
4226 data in memory. Each bit of the data represents whether that pixel is
4227 off or on. Width and height are in pixels. The GdkWindow pointer is to
4228 the current window, since a pixmap's resources are meaningful only in
4229 the context of the screen where it is to be displayed.</para>
4230
4231 <programlisting role="C">
4232 GdkPixmap *gdk_pixmap_create_from_data( GdkWindow *window,
4233                                         gchar     *data,
4234                                         gint       width,
4235                                         gint       height,
4236                                         gint       depth,
4237                                         GdkColor  *fg,
4238                                         GdkColor  *bg );
4239 </programlisting>
4240
4241 <para>This is used to create a pixmap of the given depth (number of colors) from
4242 the bitmap data specified. <literal>fg</literal> and <literal>bg</literal> are the foreground and
4243 background color to use.</para>
4244
4245 <programlisting role="C">
4246 GdkPixmap *gdk_pixmap_create_from_xpm( GdkWindow   *window,
4247                                        GdkBitmap  **mask,
4248                                        GdkColor    *transparent_color,
4249                                        const gchar *filename );
4250 </programlisting>
4251
4252 <para>XPM format is a readable pixmap representation for the X Window
4253 System. It is widely used and many different utilities are available
4254 for creating image files in this format. The file specified by
4255 filename must contain an image in that format and it is loaded into
4256 the pixmap structure. The mask specifies which bits of the pixmap are
4257 opaque. All other bits are colored using the color specified by
4258 transparent_color. An example using this follows below.</para>
4259
4260 <programlisting role="C">
4261 GdkPixmap *gdk_pixmap_create_from_xpm_d( GdkWindow  *window,
4262                                          GdkBitmap **mask,
4263                                          GdkColor   *transparent_color,
4264                                          gchar     **data );
4265 </programlisting>
4266
4267 <para>Small images can be incorporated into a program as data in the XPM
4268 format. A pixmap is created using this data, instead of reading it
4269 from a file. An example of such data is</para>
4270
4271 <programlisting role="C">
4272 /* XPM */
4273 static const char * xpm_data[] = {
4274 "16 16 3 1",
4275 "       c None",
4276 ".      c #000000000000",
4277 "X      c #FFFFFFFFFFFF",
4278 "                ",
4279 "   ......       ",
4280 "   .XXX.X.      ",
4281 "   .XXX.XX.     ",
4282 "   .XXX.XXX.    ",
4283 "   .XXX.....    ",
4284 "   .XXXXXXX.    ",
4285 "   .XXXXXXX.    ",
4286 "   .XXXXXXX.    ",
4287 "   .XXXXXXX.    ",
4288 "   .XXXXXXX.    ",
4289 "   .XXXXXXX.    ",
4290 "   .XXXXXXX.    ",
4291 "   .........    ",
4292 "                ",
4293 "                "};
4294 </programlisting>
4295
4296 <para>When we're done using a pixmap and not likely to reuse it again soon,
4297 it is a good idea to release the resource using
4298 gdk_pixmap_unref(). Pixmaps should be considered a precious resource,
4299 because they take up memory in the end-user's X server process. Even
4300 though the X client you write may run on a powerful "server" computer,
4301 the user may be running the X server on a small personal computer.</para>
4302
4303 <para>Once we've created a pixmap, we can display it as a GTK widget. We
4304 must create a GTK pixmap widget to contain the GDK pixmap. This is
4305 done using</para>
4306
4307 <programlisting role="C">
4308 GtkWidget *gtk_pixmap_new( GdkPixmap *pixmap,
4309                            GdkBitmap *mask );
4310 </programlisting>
4311
4312 <para>The other pixmap widget calls are</para>
4313
4314 <programlisting role="C">
4315 guint gtk_pixmap_get_type( void );
4316
4317 void  gtk_pixmap_set( GtkPixmap  *pixmap,
4318                       GdkPixmap  *val,
4319                       GdkBitmap  *mask );
4320
4321 void  gtk_pixmap_get( GtkPixmap  *pixmap,
4322                       GdkPixmap **val,
4323                       GdkBitmap **mask);
4324 </programlisting>
4325
4326 <para>gtk_pixmap_set is used to change the pixmap that the widget is currently
4327 managing. Val is the pixmap created using GDK.</para>
4328
4329 <para>The following is an example of using a pixmap in a button.</para>
4330
4331 <programlisting role="C">
4332 <!-- example-start pixmap pixmap.c -->
4333
4334 #include &lt;gtk/gtk.h&gt;
4335
4336
4337 /* XPM data of Open-File icon */
4338 static const char * xpm_data[] = {
4339 "16 16 3 1",
4340 "       c None",
4341 ".      c #000000000000",
4342 "X      c #FFFFFFFFFFFF",
4343 "                ",
4344 "   ......       ",
4345 "   .XXX.X.      ",
4346 "   .XXX.XX.     ",
4347 "   .XXX.XXX.    ",
4348 "   .XXX.....    ",
4349 "   .XXXXXXX.    ",
4350 "   .XXXXXXX.    ",
4351 "   .XXXXXXX.    ",
4352 "   .XXXXXXX.    ",
4353 "   .XXXXXXX.    ",
4354 "   .XXXXXXX.    ",
4355 "   .XXXXXXX.    ",
4356 "   .........    ",
4357 "                ",
4358 "                "};
4359
4360
4361 /* when invoked (via signal delete_event), terminates the application.
4362  */
4363 gint close_application( GtkWidget *widget,
4364                         GdkEvent  *event,
4365                         gpointer   data )
4366 {
4367     gtk_main_quit();
4368     return(FALSE);
4369 }
4370
4371
4372 /* is invoked when the button is clicked.  It just prints a message.
4373  */
4374 void button_clicked( GtkWidget *widget,
4375                      gpointer   data ) {
4376     g_print( "button clicked\n" );
4377 }
4378
4379 int main( int   argc,
4380           char *argv[] )
4381 {
4382     /* GtkWidget is the storage type for widgets */
4383     GtkWidget *window, *pixmapwid, *button;
4384     GdkPixmap *pixmap;
4385     GdkBitmap *mask;
4386     GtkStyle *style;
4387     
4388     /* create the main window, and attach delete_event signal to terminating
4389        the application */
4390     gtk_init( &amp;argc, &amp;argv );
4391     window = gtk_window_new( GTK_WINDOW_TOPLEVEL );
4392     gtk_signal_connect( GTK_OBJECT (window), "delete_event",
4393                         GTK_SIGNAL_FUNC (close_application), NULL );
4394     gtk_container_set_border_width( GTK_CONTAINER (window), 10 );
4395     gtk_widget_show( window );
4396
4397     /* now for the pixmap from gdk */
4398     style = gtk_widget_get_style( window );
4399     pixmap = gdk_pixmap_create_from_xpm_d( window->window,  &amp;mask,
4400                                            &amp;style->bg[GTK_STATE_NORMAL],
4401                                            (gchar **)xpm_data );
4402
4403     /* a pixmap widget to contain the pixmap */
4404     pixmapwid = gtk_pixmap_new( pixmap, mask );
4405     gtk_widget_show( pixmapwid );
4406
4407     /* a button to contain the pixmap widget */
4408     button = gtk_button_new();
4409     gtk_container_add( GTK_CONTAINER(button), pixmapwid );
4410     gtk_container_add( GTK_CONTAINER(window), button );
4411     gtk_widget_show( button );
4412
4413     gtk_signal_connect( GTK_OBJECT(button), "clicked",
4414                         GTK_SIGNAL_FUNC(button_clicked), NULL );
4415
4416     /* show the window */
4417     gtk_main ();
4418           
4419     return 0;
4420 }
4421 <!-- example-end -->
4422 </programlisting>
4423
4424 <para>To load a file from an XPM data file called icon0.xpm in the current
4425 directory, we would have created the pixmap thus</para>
4426
4427 <programlisting role="C">
4428     /* load a pixmap from a file */
4429     pixmap = gdk_pixmap_create_from_xpm( window->window, &amp;mask,
4430                                          &amp;style->bg[GTK_STATE_NORMAL],
4431                                          "./icon0.xpm" );
4432     pixmapwid = gtk_pixmap_new( pixmap, mask );
4433     gtk_widget_show( pixmapwid );
4434     gtk_container_add( GTK_CONTAINER(window), pixmapwid );
4435 </programlisting>
4436
4437 <para>A disadvantage of using pixmaps is that the displayed object is always
4438 rectangular, regardless of the image. We would like to create desktops
4439 and applications with icons that have more natural shapes. For
4440 example, for a game interface, we would like to have round buttons to
4441 push. The way to do this is using shaped windows.</para>
4442
4443 <para>A shaped window is simply a pixmap where the background pixels are
4444 transparent. This way, when the background image is multi-colored, we
4445 don't overwrite it with a rectangular, non-matching border around our
4446 icon. The following example displays a full wheelbarrow image on the
4447 desktop.</para>
4448
4449 <programlisting role="C">
4450 <!-- example-start wheelbarrow wheelbarrow.c -->
4451
4452 #include &lt;gtk/gtk.h&gt;
4453
4454 /* XPM */
4455 static char * WheelbarrowFull_xpm[] = {
4456 "48 48 64 1",
4457 "       c None",
4458 ".      c #DF7DCF3CC71B",
4459 "X      c #965875D669A6",
4460 "o      c #71C671C671C6",
4461 "O      c #A699A289A699",
4462 "+      c #965892489658",
4463 "@      c #8E38410330C2",
4464 "#      c #D75C7DF769A6",
4465 "$      c #F7DECF3CC71B",
4466 "%      c #96588A288E38",
4467 "&amp;      c #A69992489E79",
4468 "*      c #8E3886178E38",
4469 "=      c #104008200820",
4470 "-      c #596510401040",
4471 ";      c #C71B30C230C2",
4472 ":      c #C71B9A699658",
4473 ">      c #618561856185",
4474 ",      c #20811C712081",
4475 "<      c #104000000000",
4476 "1      c #861720812081",
4477 "2      c #DF7D4D344103",
4478 "3      c #79E769A671C6",
4479 "4      c #861782078617",
4480 "5      c #41033CF34103",
4481 "6      c #000000000000",
4482 "7      c #49241C711040",
4483 "8      c #492445144924",
4484 "9      c #082008200820",
4485 "0      c #69A618611861",
4486 "q      c #B6DA71C65144",
4487 "w      c #410330C238E3",
4488 "e      c #CF3CBAEAB6DA",
4489 "r      c #71C6451430C2",
4490 "t      c #EFBEDB6CD75C",
4491 "y      c #28A208200820",
4492 "u      c #186110401040",
4493 "i      c #596528A21861",
4494 "p      c #71C661855965",
4495 "a      c #A69996589658",
4496 "s      c #30C228A230C2",
4497 "d      c #BEFBA289AEBA",
4498 "f      c #596545145144",
4499 "g      c #30C230C230C2",
4500 "h      c #8E3882078617",
4501 "j      c #208118612081",
4502 "k      c #38E30C300820",
4503 "l      c #30C2208128A2",
4504 "z      c #38E328A238E3",
4505 "x      c #514438E34924",
4506 "c      c #618555555965",
4507 "v      c #30C2208130C2",
4508 "b      c #38E328A230C2",
4509 "n      c #28A228A228A2",
4510 "m      c #41032CB228A2",
4511 "M      c #104010401040",
4512 "N      c #492438E34103",
4513 "B      c #28A2208128A2",
4514 "V      c #A699596538E3",
4515 "C      c #30C21C711040",
4516 "Z      c #30C218611040",
4517 "A      c #965865955965",
4518 "S      c #618534D32081",
4519 "D      c #38E31C711040",
4520 "F      c #082000000820",
4521 "                                                ",
4522 "          .XoO                                  ",
4523 "         +@#$%o&amp;                                ",
4524 "         *=-;#::o+                              ",
4525 "           >,&lt;12#:34                            ",
4526 "             45671#:X3                          ",
4527 "               +89&lt;02qwo                        ",
4528 "e*                >,67;ro                       ",
4529 "ty>                 459@>+&amp;&amp;                    ",
4530 "$2u+                  >&lt;ipas8*                  ",
4531 "%$;=*                *3:.Xa.dfg>                ",
4532 "Oh$;ya             *3d.a8j,Xe.d3g8+             ",
4533 " Oh$;ka          *3d$a8lz,,xxc:.e3g54           ",
4534 "  Oh$;kO       *pd$%svbzz,sxxxxfX..&amp;wn>         ",
4535 "   Oh$@mO    *3dthwlsslszjzxxxxxxx3:td8M4       ",
4536 "    Oh$@g&amp; *3d$XNlvvvlllm,mNwxxxxxxxfa.:,B*     ",
4537 "     Oh$@,Od.czlllllzlmmqV@V#V@fxxxxxxxf:%j5&amp;   ",
4538 "      Oh$1hd5lllslllCCZrV#r#:#2AxxxxxxxxxcdwM*  ",
4539 "       OXq6c.%8vvvllZZiqqApA:mq:Xxcpcxxxxxfdc9* ",
4540 "        2r&lt;6gde3bllZZrVi7S@SV77A::qApxxxxxxfdcM ",
4541 "        :,q-6MN.dfmZZrrSS:#riirDSAX@Af5xxxxxfevo",
4542 "         +A26jguXtAZZZC7iDiCCrVVii7Cmmmxxxxxx%3g",
4543 "          *#16jszN..3DZZZZrCVSA2rZrV7Dmmwxxxx&amp;en",
4544 "           p2yFvzssXe:fCZZCiiD7iiZDiDSSZwwxx8e*>",
4545 "           OA1&lt;jzxwwc:$d%NDZZZZCCCZCCZZCmxxfd.B ",
4546 "            3206Bwxxszx%et.eaAp77m77mmmf3&amp;eeeg* ",
4547 "             @26MvzxNzvlbwfpdettttttttttt.c,n&amp;  ",
4548 "             *;16=lsNwwNwgsvslbwwvccc3pcfu&lt;o    ",
4549 "              p;&lt;69BvwwsszslllbBlllllllu&lt;5+     ",
4550 "              OS0y6FBlvvvzvzss,u=Blllj=54       ",
4551 "               c1-699Blvlllllu7k96MMMg4         ",
4552 "               *10y8n6FjvllllB&lt;166668           ",
4553 "                S-kg+>666&lt;M&lt;996-y6n&lt;8*          ",
4554 "                p71=4 m69996kD8Z-66698&amp;&amp;        ",
4555 "                &amp;i0ycm6n4 ogk17,0&lt;6666g         ",
4556 "                 N-k-&lt;>     >=01-kuu666>        ",
4557 "                 ,6ky&amp;      &amp;46-10ul,66,        ",
4558 "                 Ou0&lt;>       o66y&lt;ulw&lt;66&amp;       ",
4559 "                  *kk5       >66By7=xu664       ",
4560 "                   &lt;&lt;M4      466lj&lt;Mxu66o       ",
4561 "                   *>>       +66uv,zN666*       ",
4562 "                              566,xxj669        ",
4563 "                              4666FF666>        ",
4564 "                               >966666M         ",
4565 "                                oM6668+         ",
4566 "                                  *4            ",
4567 "                                                ",
4568 "                                                "};
4569
4570
4571 /* When invoked (via signal delete_event), terminates the application */
4572 gint close_application( GtkWidget *widget,
4573                         GdkEvent  *event,
4574                         gpointer   data )
4575 {
4576     gtk_main_quit();
4577     return(FALSE);
4578 }
4579
4580 int main (int argc,
4581           char *argv[] )
4582 {
4583     /* GtkWidget is the storage type for widgets */
4584     GtkWidget *window, *pixmap, *fixed;
4585     GdkPixmap *gdk_pixmap;
4586     GdkBitmap *mask;
4587     GtkStyle *style;
4588     GdkGC *gc;
4589     
4590     /* Create the main window, and attach delete_event signal to terminate
4591      * the application.  Note that the main window will not have a titlebar
4592      * since we're making it a popup. */
4593     gtk_init (&amp;argc, &amp;argv);
4594     window = gtk_window_new( GTK_WINDOW_POPUP );
4595     gtk_signal_connect (GTK_OBJECT (window), "delete_event",
4596                         GTK_SIGNAL_FUNC (close_application), NULL);
4597     gtk_widget_show (window);
4598
4599     /* Now for the pixmap and the pixmap widget */
4600     style = gtk_widget_get_default_style();
4601     gc = style->black_gc;
4602     gdk_pixmap = gdk_pixmap_create_from_xpm_d( window->window, &amp;mask,
4603                                              &amp;style->bg[GTK_STATE_NORMAL],
4604                                              WheelbarrowFull_xpm );
4605     pixmap = gtk_pixmap_new( gdk_pixmap, mask );
4606     gtk_widget_show( pixmap );
4607
4608     /* To display the pixmap, we use a fixed widget to place the pixmap */
4609     fixed = gtk_fixed_new();
4610     gtk_widget_set_usize( fixed, 200, 200 );
4611     gtk_fixed_put( GTK_FIXED(fixed), pixmap, 0, 0 );
4612     gtk_container_add( GTK_CONTAINER(window), fixed );
4613     gtk_widget_show( fixed );
4614
4615     /* This masks out everything except for the image itself */
4616     gtk_widget_shape_combine_mask( window, mask, 0, 0 );
4617     
4618     /* show the window */
4619     gtk_widget_set_uposition( window, 20, 400 );
4620     gtk_widget_show( window );
4621     gtk_main ();
4622           
4623     return(0);
4624 }
4625 <!-- example-end -->
4626 </programlisting>
4627
4628 <para>To make the wheelbarrow image sensitive, we could attach the button
4629 press event signal to make it do something. The following few lines
4630 would make the picture sensitive to a mouse button being pressed which
4631 makes the application terminate.</para>
4632
4633 <programlisting role="C">
4634     gtk_widget_set_events( window,
4635                           gtk_widget_get_events( window ) |
4636                           GDK_BUTTON_PRESS_MASK );
4637
4638    gtk_signal_connect( GTK_OBJECT(window), "button_press_event",
4639                        GTK_SIGNAL_FUNC(close_application), NULL );
4640 </programlisting>
4641
4642 </sect1>
4643
4644 <!-- ----------------------------------------------------------------- -->
4645 <sect1 id="sec-Rulers">
4646 <title>Rulers</title>
4647
4648 <para>Ruler widgets are used to indicate the location of the mouse pointer
4649 in a given window. A window can have a vertical ruler spanning across
4650 the width and a horizontal ruler spanning down the height. A small
4651 triangular indicator on the ruler shows the exact location of the
4652 pointer relative to the ruler.</para>
4653
4654 <para>A ruler must first be created. Horizontal and vertical rulers are
4655 created using</para>
4656
4657 <programlisting role="C">
4658 GtkWidget *gtk_hruler_new( void );    /* horizontal ruler */
4659
4660 GtkWidget *gtk_vruler_new( void );    /* vertical ruler   */
4661 </programlisting>
4662
4663 <para>Once a ruler is created, we can define the unit of measurement. Units
4664 of measure for rulers can be<literal>GTK_PIXELS</literal>, <literal>GTK_INCHES</literal> or
4665 <literal>GTK_CENTIMETERS</literal>. This is set using</para>
4666
4667 <programlisting role="C">
4668 void gtk_ruler_set_metric( GtkRuler      *ruler,
4669                            GtkMetricType  metric );
4670 </programlisting>
4671
4672 <para>The default measure is <literal>GTK_PIXELS</literal>.</para>
4673
4674 <programlisting role="C">
4675     gtk_ruler_set_metric( GTK_RULER(ruler), GTK_PIXELS );
4676 </programlisting>
4677
4678 <para>Other important characteristics of a ruler are how to mark the units
4679 of scale and where the position indicator is initially placed. These
4680 are set for a ruler using</para>
4681
4682 <programlisting role="C">
4683 void gtk_ruler_set_range( GtkRuler *ruler,
4684                           gfloat    lower,
4685                           gfloat    upper,
4686                           gfloat    position,
4687                           gfloat    max_size );
4688 </programlisting>
4689
4690 <para>The lower and upper arguments define the extent of the ruler, and
4691 max_size is the largest possible number that will be displayed.
4692 Position defines the initial position of the pointer indicator within
4693 the ruler.</para>
4694
4695 <para>A vertical ruler can span an 800 pixel wide window thus</para>
4696
4697 <programlisting role="C">
4698     gtk_ruler_set_range( GTK_RULER(vruler), 0, 800, 0, 800);
4699 </programlisting>
4700
4701 <para>The markings displayed on the ruler will be from 0 to 800, with a
4702 number for every 100 pixels. If instead we wanted the ruler to range
4703 from 7 to 16, we would code</para>
4704
4705 <programlisting role="C">
4706     gtk_ruler_set_range( GTK_RULER(vruler), 7, 16, 0, 20);
4707 </programlisting>
4708
4709 <para>The indicator on the ruler is a small triangular mark that indicates
4710 the position of the pointer relative to the ruler. If the ruler is
4711 used to follow the mouse pointer, the motion_notify_event signal
4712 should be connected to the motion_notify_event method of the ruler.
4713 To follow all mouse movements within a window area, we would use</para>
4714
4715 <programlisting role="C">
4716 #define EVENT_METHOD(i, x) GTK_WIDGET_GET_CLASS(i)->x
4717
4718     gtk_signal_connect_object( GTK_OBJECT(area), "motion_notify_event",
4719            (GtkSignalFunc)EVENT_METHOD(ruler, motion_notify_event),
4720            GTK_OBJECT(ruler) );
4721 </programlisting>
4722
4723 <para>The following example creates a drawing area with a horizontal ruler
4724 above it and a vertical ruler to the left of it. The size of the
4725 drawing area is 600 pixels wide by 400 pixels high. The horizontal
4726 ruler spans from 7 to 13 with a mark every 100 pixels, while the
4727 vertical ruler spans from 0 to 400 with a mark every 100 pixels.
4728 Placement of the drawing area and the rulers is done using a table.</para>
4729
4730 <programlisting role="C">
4731 <!-- example-start rulers rulers.c -->
4732
4733 #include &lt;gtk/gtk.h&gt;
4734
4735 #define EVENT_METHOD(i, x) GTK_WIDGET_GET_CLASS(i)->x
4736
4737 #define XSIZE  600
4738 #define YSIZE  400
4739
4740 /* This routine gets control when the close button is clicked */
4741 gint close_application( GtkWidget *widget,
4742                         GdkEvent  *event,
4743                         gpointer   data )
4744 {
4745     gtk_main_quit();
4746     return(FALSE);
4747 }
4748
4749 /* The main routine */
4750 int main( int   argc,
4751           char *argv[] ) {
4752     GtkWidget *window, *table, *area, *hrule, *vrule;
4753
4754     /* Initialize GTK and create the main window */
4755     gtk_init( &amp;argc, &amp;argv );
4756
4757     window = gtk_window_new( GTK_WINDOW_TOPLEVEL );
4758     gtk_signal_connect (GTK_OBJECT (window), "delete_event",
4759             GTK_SIGNAL_FUNC( close_application ), NULL);
4760     gtk_container_set_border_width (GTK_CONTAINER (window), 10);
4761
4762     /* Create a table for placing the ruler and the drawing area */
4763     table = gtk_table_new( 3, 2, FALSE );
4764     gtk_container_add( GTK_CONTAINER(window), table );
4765
4766     area = gtk_drawing_area_new();
4767     gtk_drawing_area_size( (GtkDrawingArea *)area, XSIZE, YSIZE );
4768     gtk_table_attach( GTK_TABLE(table), area, 1, 2, 1, 2,
4769                       GTK_EXPAND|GTK_FILL, GTK_FILL, 0, 0 );
4770     gtk_widget_set_events( area, GDK_POINTER_MOTION_MASK |
4771                                  GDK_POINTER_MOTION_HINT_MASK );
4772
4773     /* The horizontal ruler goes on top. As the mouse moves across the
4774      * drawing area, a motion_notify_event is passed to the
4775      * appropriate event handler for the ruler. */
4776     hrule = gtk_hruler_new();
4777     gtk_ruler_set_metric( GTK_RULER(hrule), GTK_PIXELS );
4778     gtk_ruler_set_range( GTK_RULER(hrule), 7, 13, 0, 20 );
4779     gtk_signal_connect_object( GTK_OBJECT(area), "motion_notify_event",
4780                                (GtkSignalFunc)EVENT_METHOD(hrule,
4781                                                         motion_notify_event),
4782                                GTK_OBJECT(hrule) );
4783     gtk_table_attach( GTK_TABLE(table), hrule, 1, 2, 0, 1,
4784                       GTK_EXPAND|GTK_SHRINK|GTK_FILL, GTK_FILL, 0, 0 );
4785     
4786     /* The vertical ruler goes on the left. As the mouse moves across
4787      * the drawing area, a motion_notify_event is passed to the
4788      * appropriate event handler for the ruler. */
4789     vrule = gtk_vruler_new();
4790     gtk_ruler_set_metric( GTK_RULER(vrule), GTK_PIXELS );
4791     gtk_ruler_set_range( GTK_RULER(vrule), 0, YSIZE, 10, YSIZE );
4792     gtk_signal_connect_object( GTK_OBJECT(area), "motion_notify_event",
4793                                (GtkSignalFunc)EVENT_METHOD(vrule,
4794                                                 motion_notify_event),
4795                                GTK_OBJECT(vrule) );
4796     gtk_table_attach( GTK_TABLE(table), vrule, 0, 1, 1, 2,
4797                       GTK_FILL, GTK_EXPAND|GTK_SHRINK|GTK_FILL, 0, 0 );
4798
4799     /* Now show everything */
4800     gtk_widget_show( area );
4801     gtk_widget_show( hrule );
4802     gtk_widget_show( vrule );
4803     gtk_widget_show( table );
4804     gtk_widget_show( window );
4805     gtk_main();
4806
4807     return(0);
4808 }
4809 <!-- example-end -->
4810 </programlisting>
4811
4812 </sect1>
4813
4814 <!-- ----------------------------------------------------------------- -->
4815 <sect1 id="sec-Statusbars">
4816 <title>Statusbars</title>
4817
4818 <para>Statusbars are simple widgets used to display a text message. They
4819 keep a stack of the messages pushed onto them, so that popping the
4820 current message will re-display the previous text message.</para>
4821
4822 <para>In order to allow different parts of an application to use the same
4823 statusbar to display messages, the statusbar widget issues Context
4824 Identifiers which are used to identify different "users". The message
4825 on top of the stack is the one displayed, no matter what context it is
4826 in. Messages are stacked in last-in-first-out order, not context
4827 identifier order.</para>
4828
4829 <para>A statusbar is created with a call to:</para>
4830
4831 <programlisting role="C">
4832 GtkWidget *gtk_statusbar_new( void );
4833 </programlisting>
4834
4835 <para>A new Context Identifier is requested using a call to the following 
4836 function with a short textual description of the context:</para>
4837
4838 <programlisting role="C">
4839 guint gtk_statusbar_get_context_id( GtkStatusbar *statusbar,
4840                                     const gchar  *context_description );
4841 </programlisting>
4842
4843 <para>There are three functions that can operate on statusbars:</para>
4844
4845 <programlisting role="C">
4846 guint gtk_statusbar_push( GtkStatusbar *statusbar,
4847                           guint         context_id,
4848                           gchar        *text );
4849
4850 void gtk_statusbar_pop( GtkStatusbar *statusbar)
4851                         guint         context_id );
4852
4853 void gtk_statusbar_remove( GtkStatusbar *statusbar,
4854                            guint         context_id,
4855                            guint         message_id ); 
4856 </programlisting>
4857
4858 <para>The first, gtk_statusbar_push, is used to add a new message to the
4859 statusbar.  It returns a Message Identifier, which can be passed later
4860 to the function gtk_statusbar_remove to remove the message with the
4861 given Message and Context Identifiers from the statusbar's stack.</para>
4862
4863 <para>The function gtk_statusbar_pop removes the message highest in the
4864 stack with the given Context Identifier.</para>
4865
4866 <para>The following example creates a statusbar and two buttons, one for
4867 pushing items onto the statusbar, and one for popping the last item
4868 back off.</para>
4869
4870 <programlisting role="C">
4871 <!-- example-start statusbar statusbar.c -->
4872
4873 #include &lt;gtk/gtk.h&gt;
4874 #include &lt;glib.h&gt;
4875
4876 GtkWidget *status_bar;
4877
4878 void push_item( GtkWidget *widget,
4879                 gpointer   data )
4880 {
4881   static int count = 1;
4882   char buff[20];
4883
4884   g_snprintf(buff, 20, "Item %d", count++);
4885   gtk_statusbar_push( GTK_STATUSBAR(status_bar), GPOINTER_TO_INT(data), buff);
4886
4887   return;
4888 }
4889
4890 void pop_item( GtkWidget *widget,
4891                gpointer   data )
4892 {
4893   gtk_statusbar_pop( GTK_STATUSBAR(status_bar), GPOINTER_TO_INT(data) );
4894   return;
4895 }
4896
4897 int main( int   argc,
4898           char *argv[] )
4899 {
4900
4901     GtkWidget *window;
4902     GtkWidget *vbox;
4903     GtkWidget *button;
4904
4905     gint context_id;
4906
4907     gtk_init (&amp;argc, &amp;argv);
4908
4909     /* create a new window */
4910     window = gtk_window_new(GTK_WINDOW_TOPLEVEL);
4911     gtk_widget_set_usize( GTK_WIDGET (window), 200, 100);
4912     gtk_window_set_title(GTK_WINDOW (window), "GTK Statusbar Example");
4913     gtk_signal_connect(GTK_OBJECT (window), "delete_event",
4914                        (GtkSignalFunc) gtk_exit, NULL);
4915  
4916     vbox = gtk_vbox_new(FALSE, 1);
4917     gtk_container_add(GTK_CONTAINER(window), vbox);
4918     gtk_widget_show(vbox);
4919           
4920     status_bar = gtk_statusbar_new();      
4921     gtk_box_pack_start (GTK_BOX (vbox), status_bar, TRUE, TRUE, 0);
4922     gtk_widget_show (status_bar);
4923
4924     context_id = gtk_statusbar_get_context_id(
4925                           GTK_STATUSBAR(status_bar), "Statusbar example");
4926
4927     button = gtk_button_new_with_label("push item");
4928     gtk_signal_connect(GTK_OBJECT(button), "clicked",
4929         GTK_SIGNAL_FUNC (push_item), GINT_TO_POINTER(context_id) );
4930     gtk_box_pack_start(GTK_BOX(vbox), button, TRUE, TRUE, 2);
4931     gtk_widget_show(button);              
4932
4933     button = gtk_button_new_with_label("pop last item");
4934     gtk_signal_connect(GTK_OBJECT(button), "clicked",
4935         GTK_SIGNAL_FUNC (pop_item), GINT_TO_POINTER(context_id) );
4936     gtk_box_pack_start(GTK_BOX(vbox), button, TRUE, TRUE, 2);
4937     gtk_widget_show(button);
4938
4939     /* always display the window as the last step so it all splashes on
4940      * the screen at once. */
4941     gtk_widget_show(window);
4942
4943     gtk_main ();
4944
4945     return 0;
4946 }
4947 <!-- example-end -->
4948 </programlisting>
4949
4950 </sect1>
4951
4952 <!-- ----------------------------------------------------------------- -->
4953 <sect1 id="sec-TextEntries">
4954 <title>Text Entries</title>
4955
4956 <para>The Entry widget allows text to be typed and displayed in a single line
4957 text box. The text may be set with function calls that allow new text
4958 to replace, prepend or append the current contents of the Entry widget.</para>
4959
4960 <para>There are two functions for creating Entry widgets:</para>
4961
4962 <programlisting role="C">
4963 GtkWidget *gtk_entry_new( void );
4964
4965 GtkWidget *gtk_entry_new_with_max_length( guint16 max );
4966 </programlisting>
4967
4968 <para>The first just creates a new Entry widget, whilst the second creates a
4969 new Entry and sets a limit on the length of the text within the Entry.</para>
4970
4971 <para>There are several functions for altering the text which is currently
4972 within the Entry widget.</para>
4973
4974 <programlisting role="C">
4975 void gtk_entry_set_text( GtkEntry    *entry,
4976                          const gchar *text );
4977
4978 void gtk_entry_append_text( GtkEntry    *entry,
4979                             const gchar *text );
4980
4981 void gtk_entry_prepend_text( GtkEntry    *entry,
4982                              const gchar *text );
4983 </programlisting>
4984
4985 <para>The function gtk_entry_set_text sets the contents of the Entry widget,
4986 replacing the current contents. The functions gtk_entry_append_text
4987 and gtk_entry_prepend_text allow the current contents to be appended
4988 and prepended to.</para>
4989
4990 <para>The next function allows the current insertion point to be set.</para>
4991
4992 <programlisting role="C">
4993 void gtk_entry_set_position( GtkEntry *entry,
4994                              gint      position );
4995 </programlisting>
4996
4997 <para>The contents of the Entry can be retrieved by using a call to the
4998 following function. This is useful in the callback functions described below.</para>
4999
5000 <programlisting role="C">
5001 gchar *gtk_entry_get_text( GtkEntry *entry );
5002 </programlisting>
5003
5004 <para>The value returned by this function is used internally, and must not
5005 be freed using either free() or g_free()</para>
5006
5007 <para>If we don't want the contents of the Entry to be changed by someone typing
5008 into it, we can change its editable state.</para>
5009
5010 <programlisting role="C">
5011 void gtk_entry_set_editable( GtkEntry *entry,
5012                              gboolean  editable );
5013 </programlisting>
5014
5015 <para>The function above allows us to toggle the editable state of the
5016 Entry widget by passing in a TRUE or FALSE value for the <literal>editable</literal>
5017 argument.</para>
5018
5019 <para>If we are using the Entry where we don't want the text entered to be
5020 visible, for example when a password is being entered, we can use the
5021 following function, which also takes a boolean flag.</para>
5022
5023 <programlisting role="C">
5024 void gtk_entry_set_visibility( GtkEntry *entry,
5025                                gboolean  visible );
5026 </programlisting>
5027
5028 <para>A region of the text may be set as selected by using the following
5029 function. This would most often be used after setting some default
5030 text in an Entry, making it easy for the user to remove it.</para>
5031
5032 <programlisting role="C">
5033 void gtk_entry_select_region( GtkEntry *entry,
5034                               gint      start,
5035                               gint      end );
5036 </programlisting>
5037
5038 <para>If we want to catch when the user has entered text, we can connect to
5039 the <literal>activate</literal> or <literal>changed</literal> signal. Activate is raised when the
5040 user hits the enter key within the Entry widget. Changed is raised
5041 when the text changes at all, e.g., for every character entered or
5042 removed.</para>
5043
5044 <para>The following code is an example of using an Entry widget.</para>
5045
5046 <programlisting role="C">
5047 <!-- example-start entry entry.c -->
5048
5049 #include &lt;stdio.h&gt;
5050 #include &lt;gtk/gtk.h&gt;
5051
5052 void enter_callback( GtkWidget *widget,
5053                      GtkWidget *entry )
5054 {
5055   const gchar *entry_text;
5056   entry_text = gtk_entry_get_text(GTK_ENTRY(entry));
5057   printf("Entry contents: %s\n", entry_text);
5058 }
5059
5060 void entry_toggle_editable( GtkWidget *checkbutton,
5061                             GtkWidget *entry )
5062 {
5063   gtk_entry_set_editable(GTK_ENTRY(entry),
5064                          GTK_TOGGLE_BUTTON(checkbutton)->active);
5065 }
5066
5067 void entry_toggle_visibility( GtkWidget *checkbutton,
5068                               GtkWidget *entry )
5069 {
5070   gtk_entry_set_visibility(GTK_ENTRY(entry),
5071                          GTK_TOGGLE_BUTTON(checkbutton)->active);
5072 }
5073
5074 int main( int   argc,
5075           char *argv[] )
5076 {
5077
5078     GtkWidget *window;
5079     GtkWidget *vbox, *hbox;
5080     GtkWidget *entry;
5081     GtkWidget *button;
5082     GtkWidget *check;
5083
5084     gtk_init (&amp;argc, &amp;argv);
5085
5086     /* create a new window */
5087     window = gtk_window_new(GTK_WINDOW_TOPLEVEL);
5088     gtk_widget_set_usize( GTK_WIDGET (window), 200, 100);
5089     gtk_window_set_title(GTK_WINDOW (window), "GTK Entry");
5090     gtk_signal_connect(GTK_OBJECT (window), "delete_event",
5091                        (GtkSignalFunc) gtk_exit, NULL);
5092
5093     vbox = gtk_vbox_new (FALSE, 0);
5094     gtk_container_add (GTK_CONTAINER (window), vbox);
5095     gtk_widget_show (vbox);
5096
5097     entry = gtk_entry_new_with_max_length (50);
5098     gtk_signal_connect(GTK_OBJECT(entry), "activate",
5099                        GTK_SIGNAL_FUNC(enter_callback),
5100                        entry);
5101     gtk_entry_set_text (GTK_ENTRY (entry), "hello");
5102     gtk_entry_append_text (GTK_ENTRY (entry), " world");
5103     gtk_entry_select_region (GTK_ENTRY (entry),
5104                              0, GTK_ENTRY(entry)->text_length);
5105     gtk_box_pack_start (GTK_BOX (vbox), entry, TRUE, TRUE, 0);
5106     gtk_widget_show (entry);
5107
5108     hbox = gtk_hbox_new (FALSE, 0);
5109     gtk_container_add (GTK_CONTAINER (vbox), hbox);
5110     gtk_widget_show (hbox);
5111                                   
5112     check = gtk_check_button_new_with_label("Editable");
5113     gtk_box_pack_start (GTK_BOX (hbox), check, TRUE, TRUE, 0);
5114     gtk_signal_connect (GTK_OBJECT(check), "toggled",
5115                         GTK_SIGNAL_FUNC(entry_toggle_editable), entry);
5116     gtk_toggle_button_set_active(GTK_TOGGLE_BUTTON(check), TRUE);
5117     gtk_widget_show (check);
5118     
5119     check = gtk_check_button_new_with_label("Visible");
5120     gtk_box_pack_start (GTK_BOX (hbox), check, TRUE, TRUE, 0);
5121     gtk_signal_connect (GTK_OBJECT(check), "toggled",
5122                         GTK_SIGNAL_FUNC(entry_toggle_visibility), entry);
5123     gtk_toggle_button_set_active(GTK_TOGGLE_BUTTON(check), TRUE);
5124     gtk_widget_show (check);
5125                                    
5126     button = gtk_button_new_with_label ("Close");
5127     gtk_signal_connect_object (GTK_OBJECT (button), "clicked",
5128                                GTK_SIGNAL_FUNC(gtk_exit),
5129                                GTK_OBJECT (window));
5130     gtk_box_pack_start (GTK_BOX (vbox), button, TRUE, TRUE, 0);
5131     GTK_WIDGET_SET_FLAGS (button, GTK_CAN_DEFAULT);
5132     gtk_widget_grab_default (button);
5133     gtk_widget_show (button);
5134     
5135     gtk_widget_show(window);
5136
5137     gtk_main();
5138     return(0);
5139 }
5140 <!-- example-end -->
5141 </programlisting>
5142
5143 </sect1>
5144
5145 <!-- ----------------------------------------------------------------- -->
5146 <sect1 id="sec-SpinButtons">
5147 <title>Spin Buttons</title>
5148
5149 <para>The Spin Button widget is generally used to allow the user to select a
5150 value from a range of numeric values. It consists of a text
5151 entry box with up and down arrow buttons attached to the
5152 side. Selecting one of the buttons causes the value to "spin" up and
5153 down the range of possible values. The entry box may also be edited
5154 directly to enter a specific value.</para>
5155
5156 <para>The Spin Button allows the value to have zero or a number of decimal
5157 places and to be incremented/decremented in configurable steps. The
5158 action of holding down one of the buttons optionally results in an
5159 acceleration of change in the value according to how long it is
5160 depressed.</para>
5161
5162 <para>The Spin Button uses an <link linkend="ch-Adjustments">Adjustment</link>
5163 object to hold information about the range of values that the spin
5164 button can take. This makes for a powerful Spin Button widget.</para>
5165
5166 <para>Recall that an adjustment widget is created with the following
5167 function, which illustrates the information that it holds:</para>
5168
5169 <programlisting role="C">
5170 GtkObject *gtk_adjustment_new( gfloat value,
5171                                gfloat lower,
5172                                gfloat upper,
5173                                gfloat step_increment,
5174                                gfloat page_increment,
5175                                gfloat page_size );
5176 </programlisting>
5177
5178 <para>These attributes of an Adjustment are used by the Spin Button in the
5179 following way:</para>
5180
5181 <itemizedlist>
5182 <listitem><simpara> <literal>value</literal>: initial value for the Spin Button</simpara>
5183 </listitem>
5184 <listitem><simpara> <literal>lower</literal>: lower range value</simpara>
5185 </listitem>
5186 <listitem><simpara> <literal>upper</literal>: upper range value</simpara>
5187 </listitem>
5188 <listitem><simpara> <literal>step_increment</literal>: value to increment/decrement when pressing
5189 mouse button 1 on a button</simpara>
5190 </listitem>
5191 <listitem><simpara> <literal>page_increment</literal>: value to increment/decrement when pressing
5192 mouse button 2 on a button</simpara>
5193 </listitem>
5194 <listitem><simpara> <literal>page_size</literal>: unused</simpara>
5195 </listitem>
5196 </itemizedlist>
5197
5198 <para>Additionally, mouse button 3 can be used to jump directly to the
5199 <literal>upper</literal> or <literal>lower</literal> values when used to select one of the
5200 buttons. Lets look at how to create a Spin Button:</para>
5201
5202 <programlisting role="C">
5203 GtkWidget *gtk_spin_button_new( GtkAdjustment *adjustment,
5204                                 gfloat         climb_rate,
5205                                 guint          digits );
5206 </programlisting>
5207
5208 <para>The <literal>climb_rate</literal> argument take a value between 0.0 and 1.0 and
5209 indicates the amount of acceleration that the Spin Button has. The
5210 <literal>digits</literal> argument specifies the number of decimal places to which
5211 the value will be displayed.</para>
5212
5213 <para>A Spin Button can be reconfigured after creation using the following
5214 function:</para>
5215
5216 <programlisting role="C">
5217 void gtk_spin_button_configure( GtkSpinButton *spin_button,
5218                                 GtkAdjustment *adjustment,
5219                                 gfloat         climb_rate,
5220                                 guint          digits );
5221 </programlisting>
5222
5223 <para>The <literal>spin_button</literal> argument specifies the Spin Button widget that is
5224 to be reconfigured. The other arguments are as specified above.</para>
5225
5226 <para>The adjustment can be set and retrieved independantly using the
5227 following two functions:</para>
5228
5229 <programlisting role="C">
5230 void gtk_spin_button_set_adjustment( GtkSpinButton  *spin_button,
5231                                      GtkAdjustment  *adjustment );
5232
5233 GtkAdjustment *gtk_spin_button_get_adjustment( GtkSpinButton *spin_button );
5234 </programlisting>
5235
5236 <para>The number of decimal places can also be altered using:</para>
5237
5238 <programlisting role="C">
5239 void gtk_spin_button_set_digits( GtkSpinButton *spin_button,
5240                                  guint          digits) ;
5241 </programlisting>
5242
5243 <para>The value that a Spin Button is currently displaying can be changed
5244 using the following function:</para>
5245
5246 <programlisting role="C">
5247 void gtk_spin_button_set_value( GtkSpinButton *spin_button,
5248                                 gfloat         value );
5249 </programlisting>
5250
5251 <para>The current value of a Spin Button can be retrieved as either a
5252 floating point or integer value with the following functions:</para>
5253
5254 <programlisting role="C">
5255 gfloat gtk_spin_button_get_value_as_float( GtkSpinButton *spin_button );
5256
5257 gint gtk_spin_button_get_value_as_int( GtkSpinButton *spin_button );
5258 </programlisting>
5259
5260 <para>If you want to alter the value of a Spin Value relative to its current
5261 value, then the following function can be used:</para>
5262
5263 <programlisting role="C">
5264 void gtk_spin_button_spin( GtkSpinButton *spin_button,
5265                            GtkSpinType    direction,
5266                            gfloat         increment );
5267 </programlisting>
5268
5269 <para>The <literal>direction</literal> parameter can take one of the following values:</para>
5270
5271 <programlisting role="C">
5272   GTK_SPIN_STEP_FORWARD
5273   GTK_SPIN_STEP_BACKWARD
5274   GTK_SPIN_PAGE_FORWARD
5275   GTK_SPIN_PAGE_BACKWARD
5276   GTK_SPIN_HOME
5277   GTK_SPIN_END
5278   GTK_SPIN_USER_DEFINED
5279 </programlisting>
5280
5281 <para>This function packs in quite a bit of functionality, which I will
5282 attempt to clearly explain. Many of these settings use values from the
5283 Adjustment object that is associated with a Spin Button.</para>
5284
5285 <para><literal>GTK_SPIN_STEP_FORWARD</literal> and <literal>GTK_SPIN_STEP_BACKWARD</literal> change the
5286 value of the Spin Button by the amount specified by <literal>increment</literal>,
5287 unless <literal>increment</literal> is equal to 0, in which case the value is
5288 changed by the value of <literal>step_increment</literal> in theAdjustment.</para>
5289
5290 <para><literal>GTK_SPIN_PAGE_FORWARD</literal> and <literal>GTK_SPIN_PAGE_BACKWARD</literal> simply
5291 alter the value of the Spin Button by <literal>increment</literal>.</para>
5292
5293 <para><literal>GTK_SPIN_HOME</literal> sets the value of the Spin Button to the bottom of
5294 the Adjustments range.</para>
5295
5296 <para><literal>GTK_SPIN_END</literal> sets the value of the Spin Button to the top of the
5297 Adjustments range.</para>
5298
5299 <para><literal>GTK_SPIN_USER_DEFINED</literal> simply alters the value of the Spin Button
5300 by the specified amount.</para>
5301
5302 <para>We move away from functions for setting and retreving the range attributes
5303 of the Spin Button now, and move onto functions that effect the
5304 appearance and behaviour of the Spin Button widget itself.</para>
5305
5306 <para>The first of these functions is used to constrain the text box of the
5307 Spin Button such that it may only contain a numeric value. This
5308 prevents a user from typing anything other than numeric values into
5309 the text box of a Spin Button:</para>
5310
5311 <programlisting role="C">
5312 void gtk_spin_button_set_numeric( GtkSpinButton *spin_button,
5313                                   gboolean       numeric );
5314 </programlisting>
5315
5316 <para>You can set whether a Spin Button will wrap around between the upper
5317 and lower range values with the following function:</para>
5318
5319 <programlisting role="C">
5320 void gtk_spin_button_set_wrap( GtkSpinButton *spin_button,
5321                                gboolean       wrap );
5322 </programlisting>
5323
5324 <para>You can set a Spin Button to round the value to the nearest
5325 <literal>step_increment</literal>, which is set within the Adjustment object used
5326 with the Spin Button. This is accomplished with the following
5327 function:</para>
5328
5329 <programlisting role="C">
5330 void gtk_spin_button_set_snap_to_ticks( GtkSpinButton  *spin_button,
5331                                         gboolean        snap_to_ticks );
5332 </programlisting>
5333
5334 <para>The update policy of a Spin Button can be changed with the following
5335 function:</para>
5336
5337 <programlisting role="C">
5338 void gtk_spin_button_set_update_policy( GtkSpinButton  *spin_button,
5339                                     GtkSpinButtonUpdatePolicy policy );
5340 </programlisting>
5341
5342 <para><!-- TODO: find out what this does - TRG --></para>
5343
5344 <para>The possible values of <literal>policy</literal> are either <literal>GTK_UPDATE_ALWAYS</literal> or
5345 <literal>GTK_UPDATE_IF_VALID</literal>.</para>
5346
5347 <para>These policies affect the behavior of a Spin Button when parsing
5348 inserted text and syncing its value with the values of the
5349 Adjustment.</para>
5350
5351 <para>In the case of <literal>GTK_UPDATE_IF_VALID</literal> the Spin Button only value
5352 gets changed if the text input is a numeric value that is within the
5353 range specified by the Adjustment. Otherwise the text is reset to the
5354 current value.</para>
5355
5356 <para>In case of <literal>GTK_UPDATE_ALWAYS</literal> we ignore errors while converting
5357 text into a numeric value.</para>
5358
5359 <para>The appearance of the buttons used in a Spin Button can be changed
5360 using the following function:</para>
5361
5362 <programlisting role="C">
5363 void gtk_spin_button_set_shadow_type( GtkSpinButton *spin_button,
5364                                       GtkShadowType  shadow_type );
5365 </programlisting>
5366
5367 <para>As usual, the <literal>shadow_type</literal> can be one of:</para>
5368
5369 <programlisting role="C">
5370   GTK_SHADOW_IN
5371   GTK_SHADOW_OUT
5372   GTK_SHADOW_ETCHED_IN
5373   GTK_SHADOW_ETCHED_OUT
5374 </programlisting>
5375
5376 <para>Finally, you can explicitly request that a Spin Button update itself:</para>
5377
5378 <programlisting role="C">
5379 void gtk_spin_button_update( GtkSpinButton  *spin_button );
5380 </programlisting>
5381
5382 <para>It's example time again.</para>
5383
5384 <programlisting role="C">
5385 <!-- example-start spinbutton spinbutton.c -->
5386
5387 #include &lt;stdio.h&gt;
5388 #include &lt;gtk/gtk.h&gt;
5389
5390 static GtkWidget *spinner1;
5391
5392 void toggle_snap( GtkWidget     *widget,
5393                   GtkSpinButton *spin )
5394 {
5395   gtk_spin_button_set_snap_to_ticks (spin, GTK_TOGGLE_BUTTON (widget)->active);
5396 }
5397
5398 void toggle_numeric( GtkWidget *widget,
5399                      GtkSpinButton *spin )
5400 {
5401   gtk_spin_button_set_numeric (spin, GTK_TOGGLE_BUTTON (widget)->active);
5402 }
5403
5404 void change_digits( GtkWidget *widget,
5405                     GtkSpinButton *spin )
5406 {
5407   gtk_spin_button_set_digits (GTK_SPIN_BUTTON (spinner1),
5408                               gtk_spin_button_get_value_as_int (spin));
5409 }
5410
5411 void get_value( GtkWidget *widget,
5412                 gpointer data )
5413 {
5414   gchar buf[32];
5415   GtkLabel *label;
5416   GtkSpinButton *spin;
5417
5418   spin = GTK_SPIN_BUTTON (spinner1);
5419   label = GTK_LABEL (gtk_object_get_user_data (GTK_OBJECT (widget)));
5420   if (GPOINTER_TO_INT (data) == 1)
5421     sprintf (buf, "%d", gtk_spin_button_get_value_as_int (spin));
5422   else
5423     sprintf (buf, "%0.*f", spin->digits,
5424              gtk_spin_button_get_value_as_float (spin));
5425   gtk_label_set_text (label, buf);
5426 }
5427
5428
5429 int main( int   argc,
5430           char *argv[] )
5431 {
5432   GtkWidget *window;
5433   GtkWidget *frame;
5434   GtkWidget *hbox;
5435   GtkWidget *main_vbox;
5436   GtkWidget *vbox;
5437   GtkWidget *vbox2;
5438   GtkWidget *spinner2;
5439   GtkWidget *spinner;
5440   GtkWidget *button;
5441   GtkWidget *label;
5442   GtkWidget *val_label;
5443   GtkAdjustment *adj;
5444
5445   /* Initialise GTK */
5446   gtk_init(&amp;argc, &amp;argv);
5447
5448   window = gtk_window_new (GTK_WINDOW_TOPLEVEL);
5449
5450   gtk_signal_connect (GTK_OBJECT (window), "destroy",
5451                       GTK_SIGNAL_FUNC (gtk_main_quit),
5452                       NULL);
5453
5454   gtk_window_set_title (GTK_WINDOW (window), "Spin Button");
5455
5456   main_vbox = gtk_vbox_new (FALSE, 5);
5457   gtk_container_set_border_width (GTK_CONTAINER (main_vbox), 10);
5458   gtk_container_add (GTK_CONTAINER (window), main_vbox);
5459   
5460   frame = gtk_frame_new ("Not accelerated");
5461   gtk_box_pack_start (GTK_BOX (main_vbox), frame, TRUE, TRUE, 0);
5462   
5463   vbox = gtk_vbox_new (FALSE, 0);
5464   gtk_container_set_border_width (GTK_CONTAINER (vbox), 5);
5465   gtk_container_add (GTK_CONTAINER (frame), vbox);
5466   
5467   /* Day, month, year spinners */
5468   
5469   hbox = gtk_hbox_new (FALSE, 0);
5470   gtk_box_pack_start (GTK_BOX (vbox), hbox, TRUE, TRUE, 5);
5471   
5472   vbox2 = gtk_vbox_new (FALSE, 0);
5473   gtk_box_pack_start (GTK_BOX (hbox), vbox2, TRUE, TRUE, 5);
5474   
5475   label = gtk_label_new ("Day :");
5476   gtk_misc_set_alignment (GTK_MISC (label), 0, 0.5);
5477   gtk_box_pack_start (GTK_BOX (vbox2), label, FALSE, TRUE, 0);
5478   
5479   adj = (GtkAdjustment *) gtk_adjustment_new (1.0, 1.0, 31.0, 1.0,
5480                                               5.0, 0.0);
5481   spinner = gtk_spin_button_new (adj, 0, 0);
5482   gtk_spin_button_set_wrap (GTK_SPIN_BUTTON (spinner), TRUE);
5483   gtk_box_pack_start (GTK_BOX (vbox2), spinner, FALSE, TRUE, 0);
5484   
5485   vbox2 = gtk_vbox_new (FALSE, 0);
5486   gtk_box_pack_start (GTK_BOX (hbox), vbox2, TRUE, TRUE, 5);
5487   
5488   label = gtk_label_new ("Month :");
5489   gtk_misc_set_alignment (GTK_MISC (label), 0, 0.5);
5490   gtk_box_pack_start (GTK_BOX (vbox2), label, FALSE, TRUE, 0);
5491   
5492   adj = (GtkAdjustment *) gtk_adjustment_new (1.0, 1.0, 12.0, 1.0,
5493                                               5.0, 0.0);
5494   spinner = gtk_spin_button_new (adj, 0, 0);
5495   gtk_spin_button_set_wrap (GTK_SPIN_BUTTON (spinner), TRUE);
5496   gtk_box_pack_start (GTK_BOX (vbox2), spinner, FALSE, TRUE, 0);
5497   
5498   vbox2 = gtk_vbox_new (FALSE, 0);
5499   gtk_box_pack_start (GTK_BOX (hbox), vbox2, TRUE, TRUE, 5);
5500   
5501   label = gtk_label_new ("Year :");
5502   gtk_misc_set_alignment (GTK_MISC (label), 0, 0.5);
5503   gtk_box_pack_start (GTK_BOX (vbox2), label, FALSE, TRUE, 0);
5504   
5505   adj = (GtkAdjustment *) gtk_adjustment_new (1998.0, 0.0, 2100.0,
5506                                               1.0, 100.0, 0.0);
5507   spinner = gtk_spin_button_new (adj, 0, 0);
5508   gtk_spin_button_set_wrap (GTK_SPIN_BUTTON (spinner), FALSE);
5509   gtk_widget_set_usize (spinner, 55, 0);
5510   gtk_box_pack_start (GTK_BOX (vbox2), spinner, FALSE, TRUE, 0);
5511   
5512   frame = gtk_frame_new ("Accelerated");
5513   gtk_box_pack_start (GTK_BOX (main_vbox), frame, TRUE, TRUE, 0);
5514   
5515   vbox = gtk_vbox_new (FALSE, 0);
5516   gtk_container_set_border_width (GTK_CONTAINER (vbox), 5);
5517   gtk_container_add (GTK_CONTAINER (frame), vbox);
5518   
5519   hbox = gtk_hbox_new (FALSE, 0);
5520   gtk_box_pack_start (GTK_BOX (vbox), hbox, FALSE, TRUE, 5);
5521   
5522   vbox2 = gtk_vbox_new (FALSE, 0);
5523   gtk_box_pack_start (GTK_BOX (hbox), vbox2, TRUE, TRUE, 5);
5524   
5525   label = gtk_label_new ("Value :");
5526   gtk_misc_set_alignment (GTK_MISC (label), 0, 0.5);
5527   gtk_box_pack_start (GTK_BOX (vbox2), label, FALSE, TRUE, 0);
5528   
5529   adj = (GtkAdjustment *) gtk_adjustment_new (0.0, -10000.0, 10000.0,
5530                                               0.5, 100.0, 0.0);
5531   spinner1 = gtk_spin_button_new (adj, 1.0, 2);
5532   gtk_spin_button_set_wrap (GTK_SPIN_BUTTON (spinner1), TRUE);
5533   gtk_widget_set_usize (spinner1, 100, 0);
5534   gtk_box_pack_start (GTK_BOX (vbox2), spinner1, FALSE, TRUE, 0);
5535   
5536   vbox2 = gtk_vbox_new (FALSE, 0);
5537   gtk_box_pack_start (GTK_BOX (hbox), vbox2, TRUE, TRUE, 5);
5538   
5539   label = gtk_label_new ("Digits :");
5540   gtk_misc_set_alignment (GTK_MISC (label), 0, 0.5);
5541   gtk_box_pack_start (GTK_BOX (vbox2), label, FALSE, TRUE, 0);
5542   
5543   adj = (GtkAdjustment *) gtk_adjustment_new (2, 1, 5, 1, 1, 0);
5544   spinner2 = gtk_spin_button_new (adj, 0.0, 0);
5545   gtk_spin_button_set_wrap (GTK_SPIN_BUTTON (spinner2), TRUE);
5546   gtk_signal_connect (GTK_OBJECT (adj), "value_changed",
5547                       GTK_SIGNAL_FUNC (change_digits),
5548                       (gpointer) spinner2);
5549   gtk_box_pack_start (GTK_BOX (vbox2), spinner2, FALSE, TRUE, 0);
5550   
5551   hbox = gtk_hbox_new (FALSE, 0);
5552   gtk_box_pack_start (GTK_BOX (vbox), hbox, FALSE, TRUE, 5);
5553   
5554   button = gtk_check_button_new_with_label ("Snap to 0.5-ticks");
5555   gtk_signal_connect (GTK_OBJECT (button), "clicked",
5556                       GTK_SIGNAL_FUNC (toggle_snap),
5557                       spinner1);
5558   gtk_box_pack_start (GTK_BOX (vbox), button, TRUE, TRUE, 0);
5559   gtk_toggle_button_set_active (GTK_TOGGLE_BUTTON (button), TRUE);
5560   
5561   button = gtk_check_button_new_with_label ("Numeric only input mode");
5562   gtk_signal_connect (GTK_OBJECT (button), "clicked",
5563                       GTK_SIGNAL_FUNC (toggle_numeric),
5564                       spinner1);
5565   gtk_box_pack_start (GTK_BOX (vbox), button, TRUE, TRUE, 0);
5566   gtk_toggle_button_set_active (GTK_TOGGLE_BUTTON (button), TRUE);
5567   
5568   val_label = gtk_label_new ("");
5569   
5570   hbox = gtk_hbox_new (FALSE, 0);
5571   gtk_box_pack_start (GTK_BOX (vbox), hbox, FALSE, TRUE, 5);
5572   button = gtk_button_new_with_label ("Value as Int");
5573   gtk_object_set_user_data (GTK_OBJECT (button), val_label);
5574   gtk_signal_connect (GTK_OBJECT (button), "clicked",
5575                       GTK_SIGNAL_FUNC (get_value),
5576                       GINT_TO_POINTER (1));
5577   gtk_box_pack_start (GTK_BOX (hbox), button, TRUE, TRUE, 5);
5578   
5579   button = gtk_button_new_with_label ("Value as Float");
5580   gtk_object_set_user_data (GTK_OBJECT (button), val_label);
5581   gtk_signal_connect (GTK_OBJECT (button), "clicked",
5582                       GTK_SIGNAL_FUNC (get_value),
5583                       GINT_TO_POINTER (2));
5584   gtk_box_pack_start (GTK_BOX (hbox), button, TRUE, TRUE, 5);
5585   
5586   gtk_box_pack_start (GTK_BOX (vbox), val_label, TRUE, TRUE, 0);
5587   gtk_label_set_text (GTK_LABEL (val_label), "0");
5588   
5589   hbox = gtk_hbox_new (FALSE, 0);
5590   gtk_box_pack_start (GTK_BOX (main_vbox), hbox, FALSE, TRUE, 0);
5591   
5592   button = gtk_button_new_with_label ("Close");
5593   gtk_signal_connect_object (GTK_OBJECT (button), "clicked",
5594                              GTK_SIGNAL_FUNC (gtk_widget_destroy),
5595                              GTK_OBJECT (window));
5596   gtk_box_pack_start (GTK_BOX (hbox), button, TRUE, TRUE, 5);
5597
5598   gtk_widget_show_all (window);
5599
5600   /* Enter the event loop */
5601   gtk_main ();
5602     
5603   return(0);
5604 }
5605 <!-- example-end -->
5606 </programlisting>
5607
5608 </sect1>
5609
5610 <!-- ----------------------------------------------------------------- -->
5611 <sect1 id="sec-ComboBox">
5612 <title>Combo Box</title>
5613
5614 <para>The combo box is another fairly simple widget that is really just a
5615 collection of other widgets. From the user's point of view, the widget
5616 consists of a text entry box and a pull down menu from which the user
5617 can select one of a set of predefined entries. Alternatively, the user
5618 can type a different option directly into the text box.</para>
5619
5620 <para>The following extract from the structure that defines a Combo Box
5621 identifies several of the components:</para>
5622
5623 <programlisting role="C">
5624 struct _GtkCombo { 
5625         GtkHBox hbox; 
5626         GtkWidget *entry; 
5627         GtkWidget *button;
5628         GtkWidget *popup; 
5629         GtkWidget *popwin; 
5630         GtkWidget *list;
5631         ...  };
5632 </programlisting>
5633
5634 <para>As you can see, the Combo Box has two principal parts that you really
5635 care about: an entry and a list.</para>
5636
5637 <para>First off, to create a combo box, use:</para>
5638
5639 <programlisting role="C">
5640 GtkWidget *gtk_combo_new( void );
5641 </programlisting>
5642
5643 <para>Now, if you want to set the string in the entry section of the combo
5644 box, this is done by manipulating the <literal>entry</literal> widget directly:</para>
5645
5646 <programlisting role="C">
5647     gtk_entry_set_text(GTK_ENTRY(GTK_COMBO(combo)->entry), "My String.");
5648 </programlisting>
5649
5650 <para>To set the values in the popdown list, one uses the function:</para>
5651
5652 <programlisting role="C">
5653 void gtk_combo_set_popdown_strings( GtkCombo *combo,
5654                                     GList    *strings );
5655 </programlisting>
5656
5657 <para>Before you can do this, you have to assemble a GList of the strings
5658 that you want. GList is a linked list implementation that is part of
5659 <link linkend="ch-GLib">GLib</link>, a library supporing GTK. For the
5660 moment, the quick and dirty explanation is that you need to set up a
5661 GList pointer, set it equal to NULL, then append strings to it with</para>
5662
5663 <programlisting role="C">
5664 GList *g_list_append( GList *glist, 
5665                       gpointer data );
5666 </programlisting>
5667
5668 <para>It is important that you set the initial GList pointer to NULL. The
5669 value returned from the g_list_append function must be used as the new
5670 pointer to the GList.</para>
5671
5672 <para>Here's a typical code segment for creating a set of options:</para>
5673
5674 <programlisting role="C">
5675     GList *glist=NULL;
5676
5677     glist = g_list_append(glist, "String 1");
5678     glist = g_list_append(glist, "String 2");
5679     glist = g_list_append(glist, "String 3"); 
5680     glist = g_list_append(glist, "String 4");
5681
5682     gtk_combo_set_popdown_strings( GTK_COMBO(combo), glist) ;
5683     
5684     /* can free glist now, combo takes a copy */
5685 </programlisting>
5686
5687 <para>The combo widget makes a copy of the strings passed to it in the glist
5688 structure. As a result, you need to make sure you free the memory used
5689 by the list if that is appropriate for your application.</para>
5690
5691 <para>At this point you have a working combo box that has been set up.
5692 There are a few aspects of its behavior that you can change. These
5693 are accomplished with the functions: </para>
5694
5695 <programlisting role="C">
5696 void gtk_combo_set_use_arrows( GtkCombo *combo,
5697                                gint      val );
5698
5699 void gtk_combo_set_use_arrows_always( GtkCombo *combo,
5700                                       gint      val );
5701
5702 void gtk_combo_set_case_sensitive( GtkCombo *combo,
5703                                    gint      val );
5704 </programlisting>
5705
5706 <para><literal>gtk_combo_set_use_arrows()</literal> lets the user change the value in the
5707 entry using the up/down arrow keys. This doesn't bring up the list, but
5708 rather replaces the current text in the entry with the next list entry
5709 (up or down, as your key choice indicates). It does this by searching
5710 in the list for the item corresponding to the current value in the
5711 entry and selecting the previous/next item accordingly. Usually in an
5712 entry the arrow keys are used to change focus (you can do that anyway
5713 using TAB). Note that when the current item is the last of the list
5714 and you press arrow-down it changes the focus (the same applies with
5715 the first item and arrow-up).</para>
5716
5717 <para>If the current value in the entry is not in the list, then the
5718 function of <literal>gtk_combo_set_use_arrows()</literal> is disabled.</para>
5719
5720 <para><literal>gtk_combo_set_use_arrows_always()</literal> similarly allows the use the
5721 the up/down arrow keys to cycle through the choices in the dropdown
5722 list, except that it wraps around the values in the list, completely
5723 disabling the use of the up and down arrow keys for changing focus.</para>
5724
5725 <para><literal>gtk_combo_set_case_sensitive()</literal> toggles whether or not GTK
5726 searches for entries in a case sensitive manner. This is used when the
5727 Combo widget is asked to find a value from the list using the current
5728 entry in the text box. This completion can be performed in either a
5729 case sensitive or insensitive manner, depending upon the use of this
5730 function. The Combo widget can also simply complete the current entry
5731 if the user presses the key combination MOD-1 and "Tab". MOD-1 is
5732 often mapped to the "Alt" key, by the <literal>xmodmap</literal> utility. Note,
5733 however that some window managers also use this key combination, which
5734 will override its use within GTK.</para>
5735
5736 <para>Now that we have a combo box, tailored to look and act how we want it,
5737 all that remains is being able to get data from the combo box. This is
5738 relatively straightforward. The majority of the time, all you are
5739 going to care about getting data from is the entry. The entry is
5740 accessed simply by <literal>GTK_ENTRY(GTK_COMBO(combo)->entry)</literal>. The
5741 two principal things that you are going to want to do with it are
5742 attach to the activate signal, which indicates that the user has
5743 pressed the Return or Enter key, and read the text. The first is
5744 accomplished using something like:</para>
5745
5746 <programlisting role="C">
5747     gtk_signal_connect(GTK_OBJECT(GTK_COMB(combo)->entry), "activate",
5748                        GTK_SIGNAL_FUNC (my_callback_function), my_data);
5749 </programlisting>
5750
5751 <para>Getting the text at any arbitrary time is accomplished by simply using
5752 the entry function:</para>
5753
5754 <programlisting role="C">
5755 gchar *gtk_entry_get_text(GtkEntry *entry);
5756 </programlisting>
5757
5758 <para>Such as:</para>
5759
5760 <programlisting role="C">
5761     char *string;
5762
5763     string = gtk_entry_get_text(GTK_ENTRY(GTK_COMBO(combo)->entry));
5764 </programlisting>
5765
5766 <para>That's about all there is to it. There is a function</para>
5767
5768 <programlisting role="C">
5769 void gtk_combo_disable_activate(GtkCombo *combo);
5770 </programlisting>
5771
5772 <para>that will disable the activate signal on the entry widget in the combo
5773 box. Personally, I can't think of why you'd want to use it, but it
5774 does exist.</para>
5775
5776 <!-- There is also a function to set the string on a particular item, void
5777 gtk_combo_set_item_string(GtkCombo *combo, GtkItem *item, const gchar
5778 *item_value), but this requires that you have a pointer to the
5779 appropriate Item. Frankly, I have no idea how to do that.
5780 -->
5781
5782 </sect1>
5783
5784 <!-- ----------------------------------------------------------------- -->
5785 <sect1 id="sec-Calendar">
5786 <title>Calendar</title>
5787
5788 <para>The Calendar widget is an effective way to display and retrieve
5789 monthly date related information. It is a very simple widget to create
5790 and work with.</para>
5791
5792 <para>Creating a GtkCalendar widget is a simple as: </para>
5793
5794 <programlisting role="C">
5795 GtkWidget *gtk_calendar_new();
5796 </programlisting>
5797
5798 <para>There might be times where you need to change a lot of information
5799 within this widget and the following functions allow you to make
5800 multiple change to a Calendar widget without the user seeing multiple
5801 on-screen updates.</para>
5802
5803 <programlisting role="C">
5804 void gtk_calendar_freeze( GtkCalendar *Calendar );
5805
5806 void gtk_calendar_thaw  ( GtkCalendar *Calendar );
5807 </programlisting>
5808
5809 <para>They work just like the freeze/thaw functions of every other
5810 widget.</para>
5811
5812 <para>The Calendar widget has a few options that allow you to change the way
5813 the widget both looks and operates by using the function</para>
5814
5815 <programlisting role="C">
5816 void gtk_calendar_display_options( GtkCalendar               *calendar,
5817                                    GtkCalendarDisplayOptions  flags );
5818 </programlisting>
5819
5820 <para>The <literal>flags</literal> argument can be formed by combining either of the
5821 following five options using the logical bitwise OR (|) operation:</para>
5822
5823 <itemizedlist>
5824 <listitem><simpara> GTK_CALENDAR_SHOW_HEADING - this option specifies that
5825 the month and year should be shown when drawing the calendar.</simpara>
5826 </listitem>
5827
5828 <listitem><simpara> GTK_CALENDAR_SHOW_DAY_NAMES - this option specifies that the
5829 three letter descriptions should be displayed for each day (eg
5830 Mon,Tue, etc.).</simpara>
5831 </listitem>
5832
5833 <listitem><simpara> GTK_CALENDAR_NO_MONTH_CHANGE - this option states that the user
5834 should not and can not change the currently displayed month. This can
5835 be good if you only need to display a particular month such as if you
5836 are displaying 12 calendar widgets for every month in a particular
5837 year.</simpara>
5838 </listitem>
5839
5840 <listitem><simpara> GTK_CALENDAR_SHOW_WEEK_NUMBERS - this option specifies that the
5841 number for each week should be displayed down the left side of the
5842 calendar. (eg. Jan 1 = Week 1,Dec 31 = Week 52).</simpara>
5843 </listitem>
5844
5845 <listitem><simpara> GTK_CALENDAR_WEEK_START_MONDAY - this option states that the
5846 calander week will start on Monday instead of Sunday which is the
5847 default. This only affects the order in which days are displayed from
5848 left to right.</simpara>
5849 </listitem>
5850 </itemizedlist>
5851
5852 <para>The following functions are used to set the the currently displayed
5853 date:</para>
5854
5855 <programlisting role="C">
5856 gint gtk_calendar_select_month( GtkCalendar *calendar, 
5857                                 guint        month,
5858                                 guint        year );
5859
5860 void gtk_calendar_select_day( GtkCalendar *calendar,
5861                               guint        day );
5862 </programlisting>
5863
5864 <para>The return value from <literal>gtk_calendar_select_month()</literal> is a boolean
5865 value indicating whether the selection was successful.</para>
5866
5867 <para>With <literal>gtk_calendar_select_day()</literal> the specified day number is
5868 selected within the current month, if that is possible. A
5869 <literal>day</literal> value of 0 will deselect any current selection.</para>
5870
5871 <para>In addition to having a day selected, any number of days in the month
5872 may be "marked". A marked day is highlighted within the calendar
5873 display. The following functions are provided to manipulate marked
5874 days:</para>
5875
5876 <programlisting role="C">
5877 gint gtk_calendar_mark_day( GtkCalendar *calendar,
5878                             guint        day);
5879
5880 gint gtk_calendar_unmark_day( GtkCalendar *calendar,
5881                               guint        day);
5882
5883 void gtk_calendar_clear_marks( GtkCalendar *calendar);
5884 </programlisting>
5885
5886 <para>The currently marked days are stored within an array within the
5887 GtkCalendar structure. This array is 31 elements long so to test
5888 whether a particular day is currently marked, you need to access the
5889 corresponding element of the array (don't forget in C that array
5890 elements are numbered 0 to n-1). For example:</para>
5891
5892 <programlisting role="C">
5893     GtkCalendar *calendar;
5894     calendar = gtk_calendar_new();
5895
5896     ...
5897
5898     /* Is day 7 marked? */
5899     if (calendar->marked_date[7-1])
5900        /* day is marked */
5901 </programlisting>
5902
5903 <para>Note that marks are persistent across month and year changes.</para>
5904
5905 <para>The final Calendar widget function is used to retrieve the currently
5906 selected date, month and/or year.</para>
5907
5908 <programlisting role="C">
5909 void gtk_calendar_get_date( GtkCalendar *calendar, 
5910                             guint       *year,
5911                             guint       *month,
5912                             guint       *day );
5913 </programlisting>
5914
5915 <para>This function requires you to pass the addresses of <literal>guint</literal>
5916 variables, into which the result will be placed. Passing <literal>NULL</literal> as
5917 a value will result in the corresponding value not being returned.</para>
5918
5919 <para>The Calendar widget can generate a number of signals indicating date
5920 selection and change. The names of these signals are self explanatory,
5921 and are:</para>
5922
5923 <itemizedlist>
5924 <listitem><simpara> <literal>month_changed</literal></simpara>
5925 </listitem>
5926 <listitem><simpara> <literal>day_selected</literal></simpara>
5927 </listitem>
5928 <listitem><simpara> <literal>day_selected_double_click</literal></simpara>
5929 </listitem>
5930 <listitem><simpara> <literal>prev_month</literal></simpara>
5931 </listitem>
5932 <listitem><simpara> <literal>next_month</literal></simpara>
5933 </listitem>
5934 <listitem><simpara> <literal>prev_year</literal></simpara>
5935 </listitem>
5936 <listitem><simpara> <literal>next_year</literal></simpara>
5937 </listitem>
5938 </itemizedlist>
5939
5940 <para>That just leaves us with the need to put all of this together into
5941 example code.</para>
5942
5943 <programlisting role="C">
5944 <!-- example-start calendar calendar.c -->
5945 /*
5946  * Copyright (C) 1998 Cesar Miquel, Shawn T. Amundson, Mattias Grönlund
5947  * Copyright (C) 2000 Tony Gale
5948  *
5949  * This program is free software; you can redistribute it and/or modify
5950  * it under the terms of the GNU General Public License as published by
5951  * the Free Software Foundation; either version 2 of the License, or
5952  * (at your option) any later version.
5953  *
5954  * This program is distributed in the hope that it will be useful,
5955  * but WITHOUT ANY WARRANTY; without even the implied warranty of
5956  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
5957  * GNU General Public License for more details.
5958  *
5959  * You should have received a copy of the GNU General Public License
5960  * along with this program; if not, write to the Free Software
5961  * Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
5962  */
5963
5964 #include &lt;gtk/gtk.h&gt;
5965 #include &lt;stdio.h&gt;
5966 #include &lt;string.h&gt;
5967 #include &lt;time.h&gt;
5968
5969 #define DEF_PAD 10
5970 #define DEF_PAD_SMALL 5
5971
5972 #define TM_YEAR_BASE 1900
5973
5974 typedef struct _CalendarData {
5975   GtkWidget *flag_checkboxes[5];
5976   gboolean  settings[5];
5977   gchar     *font;
5978   GtkWidget *font_dialog;
5979   GtkWidget *window;
5980   GtkWidget *prev2_sig;
5981   GtkWidget *prev_sig;
5982   GtkWidget *last_sig;
5983   GtkWidget *month;
5984 } CalendarData;
5985
5986 enum {
5987   calendar_show_header,
5988   calendar_show_days,
5989   calendar_month_change, 
5990   calendar_show_week,
5991   calendar_monday_first
5992 };
5993
5994 /*
5995  * GtkCalendar
5996  */
5997
5998 void calendar_date_to_string( CalendarData *data,
5999                               char         *buffer,
6000                               gint          buff_len )
6001 {
6002   struct tm tm;
6003   time_t time;
6004
6005   memset (&amp;tm, 0, sizeof (tm));
6006   gtk_calendar_get_date (GTK_CALENDAR(data->window),
6007                          &amp;tm.tm_year, &amp;tm.tm_mon, &amp;tm.tm_mday);
6008   tm.tm_year -= TM_YEAR_BASE;
6009   time = mktime(&amp;tm);
6010   strftime (buffer, buff_len-1, "%x", gmtime(&amp;time));
6011 }
6012
6013 void calendar_set_signal_strings( char         *sig_str,
6014                                   CalendarData *data)
6015 {
6016   gchar *prev_sig;
6017
6018   gtk_label_get (GTK_LABEL (data->prev_sig), &amp;prev_sig);
6019   gtk_label_set (GTK_LABEL (data->prev2_sig), prev_sig);
6020
6021   gtk_label_get (GTK_LABEL (data->last_sig), &amp;prev_sig);
6022   gtk_label_set (GTK_LABEL (data->prev_sig), prev_sig);
6023   gtk_label_set (GTK_LABEL (data->last_sig), sig_str);
6024 }
6025
6026 void calendar_month_changed( GtkWidget    *widget,
6027                              CalendarData *data )
6028 {
6029   char buffer[256] = "month_changed: ";
6030
6031   calendar_date_to_string (data, buffer+15, 256-15);
6032   calendar_set_signal_strings (buffer, data);
6033 }
6034
6035 void calendar_day_selected( GtkWidget    *widget,
6036                             CalendarData *data )
6037 {
6038   char buffer[256] = "day_selected: ";
6039
6040   calendar_date_to_string (data, buffer+14, 256-14);
6041   calendar_set_signal_strings (buffer, data);
6042 }
6043
6044 void calendar_day_selected_double_click( GtkWidget    *widget,
6045                                          CalendarData *data )
6046 {
6047   struct tm tm;
6048   char buffer[256] = "day_selected_double_click: ";
6049
6050   calendar_date_to_string (data, buffer+27, 256-27);
6051   calendar_set_signal_strings (buffer, data);
6052
6053   memset (&amp;tm, 0, sizeof (tm));
6054   gtk_calendar_get_date (GTK_CALENDAR(data->window),
6055                          &amp;tm.tm_year, &amp;tm.tm_mon, &amp;tm.tm_mday);
6056   tm.tm_year -= TM_YEAR_BASE;
6057
6058   if(GTK_CALENDAR(data->window)->marked_date[tm.tm_mday-1] == 0) {
6059     gtk_calendar_mark_day(GTK_CALENDAR(data->window),tm.tm_mday);
6060   } else { 
6061     gtk_calendar_unmark_day(GTK_CALENDAR(data->window),tm.tm_mday);
6062   }
6063 }
6064
6065 void calendar_prev_month( GtkWidget    *widget,
6066                             CalendarData *data )
6067 {
6068   char buffer[256] = "prev_month: ";
6069
6070   calendar_date_to_string (data, buffer+12, 256-12);
6071   calendar_set_signal_strings (buffer, data);
6072 }
6073
6074 void calendar_next_month( GtkWidget    *widget,
6075                             CalendarData *data )
6076 {
6077   char buffer[256] = "next_month: ";
6078
6079   calendar_date_to_string (data, buffer+12, 256-12);
6080   calendar_set_signal_strings (buffer, data);
6081 }
6082
6083 void calendar_prev_year( GtkWidget    *widget,
6084                             CalendarData *data )
6085 {
6086   char buffer[256] = "prev_year: ";
6087
6088   calendar_date_to_string (data, buffer+11, 256-11);
6089   calendar_set_signal_strings (buffer, data);
6090 }
6091
6092 void calendar_next_year( GtkWidget    *widget,
6093                             CalendarData *data )
6094 {
6095   char buffer[256] = "next_year: ";
6096
6097   calendar_date_to_string (data, buffer+11, 256-11);
6098   calendar_set_signal_strings (buffer, data);
6099 }
6100
6101
6102 void calendar_set_flags( CalendarData *calendar )
6103 {
6104   gint i;
6105   gint options=0;
6106   for (i=0;i<5;i++) 
6107     if (calendar-&gt;settings[i])
6108       {
6109         options=options + (1&lt;&lt;i);
6110       }
6111   if (calendar-&gt;window)
6112     gtk_calendar_display_options (GTK_CALENDAR (calendar->window), options);
6113 }
6114
6115 void calendar_toggle_flag( GtkWidget    *toggle,
6116                            CalendarData *calendar )
6117 {
6118   gint i;
6119   gint j;
6120   j=0;
6121   for (i=0; i<5; i++)
6122     if (calendar->flag_checkboxes[i] == toggle)
6123       j = i;
6124
6125   calendar->settings[j]=!calendar->settings[j];
6126   calendar_set_flags(calendar);
6127   
6128 }
6129
6130 void calendar_font_selection_ok( GtkWidget    *button,
6131                                  CalendarData *calendar )
6132 {
6133   GtkStyle *style;
6134   GdkFont  *font;
6135
6136   calendar->font = gtk_font_selection_dialog_get_font_name(
6137                         GTK_FONT_SELECTION_DIALOG (calendar->font_dialog));
6138   if (calendar->window)
6139     {
6140       font = gtk_font_selection_dialog_get_font(GTK_FONT_SELECTION_DIALOG(calendar->font_dialog));
6141       if (font) 
6142         {
6143           style = gtk_style_copy (gtk_widget_get_style (calendar->window));
6144           gtk_style_set_font (style, font);
6145           gtk_widget_set_style (calendar->window, style);
6146         }
6147     }
6148 }
6149
6150 void calendar_select_font( GtkWidget    *button,
6151                            CalendarData *calendar )
6152 {
6153   GtkWidget *window;
6154
6155   if (!calendar->font_dialog) {
6156     window = gtk_font_selection_dialog_new ("Font Selection Dialog");
6157     g_return_if_fail(GTK_IS_FONT_SELECTION_DIALOG(window));
6158     calendar->font_dialog = window;
6159     
6160     gtk_window_position (GTK_WINDOW (window), GTK_WIN_POS_MOUSE);
6161     
6162     gtk_signal_connect (GTK_OBJECT (window), "destroy",
6163                         GTK_SIGNAL_FUNC (gtk_widget_destroyed),
6164                         &amp;calendar->font_dialog);
6165     
6166     gtk_signal_connect (GTK_OBJECT (GTK_FONT_SELECTION_DIALOG (window)->ok_button),
6167                         "clicked", GTK_SIGNAL_FUNC(calendar_font_selection_ok),
6168                         calendar);
6169     gtk_signal_connect_object (GTK_OBJECT (GTK_FONT_SELECTION_DIALOG (window)->cancel_button),
6170                                "clicked",
6171                                GTK_SIGNAL_FUNC (gtk_widget_destroy), 
6172                                GTK_OBJECT (calendar->font_dialog));
6173   }
6174   window=calendar->font_dialog;
6175   if (!GTK_WIDGET_VISIBLE (window))
6176     gtk_widget_show (window);
6177   else
6178     gtk_widget_destroy (window);
6179
6180 }
6181
6182 void create_calendar()
6183 {
6184   GtkWidget *window;
6185   GtkWidget *vbox, *vbox2, *vbox3;
6186   GtkWidget *hbox;
6187   GtkWidget *hbbox;
6188   GtkWidget *calendar;
6189   GtkWidget *toggle;
6190   GtkWidget *button;
6191   GtkWidget *frame;
6192   GtkWidget *separator;
6193   GtkWidget *label;
6194   GtkWidget *bbox;
6195   static CalendarData calendar_data;
6196   gint i;
6197   
6198   struct {
6199     char *label;
6200   } flags[] =
6201     {
6202       { "Show Heading" },
6203       { "Show Day Names" },
6204       { "No Month Change" },
6205       { "Show Week Numbers" },
6206       { "Week Start Monday" }
6207     };
6208
6209   
6210   calendar_data.window = NULL;
6211   calendar_data.font = NULL;
6212   calendar_data.font_dialog = NULL;
6213
6214   for (i=0; i<5; i++) {
6215     calendar_data.settings[i]=0;
6216   }
6217
6218   window = gtk_window_new (GTK_WINDOW_TOPLEVEL);
6219   gtk_window_set_title(GTK_WINDOW(window), "GtkCalendar Example");
6220   gtk_container_border_width (GTK_CONTAINER (window), 5);
6221   gtk_signal_connect(GTK_OBJECT(window), "destroy",
6222                      GTK_SIGNAL_FUNC(gtk_main_quit),
6223                      NULL);
6224   gtk_signal_connect(GTK_OBJECT(window), "delete-event",
6225                      GTK_SIGNAL_FUNC(gtk_false),
6226                      NULL);
6227
6228   gtk_window_set_policy(GTK_WINDOW(window), FALSE, FALSE, TRUE);
6229
6230   vbox = gtk_vbox_new(FALSE, DEF_PAD);
6231   gtk_container_add (GTK_CONTAINER (window), vbox);
6232
6233   /*
6234    * The top part of the window, Calendar, flags and fontsel.
6235    */
6236
6237   hbox = gtk_hbox_new(FALSE, DEF_PAD);
6238   gtk_box_pack_start (GTK_BOX(vbox), hbox, TRUE, TRUE, DEF_PAD);
6239   hbbox = gtk_hbutton_box_new();
6240   gtk_box_pack_start(GTK_BOX(hbox), hbbox, FALSE, FALSE, DEF_PAD);
6241   gtk_button_box_set_layout(GTK_BUTTON_BOX(hbbox), GTK_BUTTONBOX_SPREAD);
6242   gtk_button_box_set_spacing(GTK_BUTTON_BOX(hbbox), 5);
6243
6244   /* Calendar widget */
6245   frame = gtk_frame_new("Calendar");
6246   gtk_box_pack_start(GTK_BOX(hbbox), frame, FALSE, TRUE, DEF_PAD);
6247   calendar=gtk_calendar_new();
6248   calendar_data.window = calendar;
6249   calendar_set_flags(&amp;calendar_data);
6250   gtk_calendar_mark_day ( GTK_CALENDAR(calendar), 19);  
6251   gtk_container_add( GTK_CONTAINER( frame), calendar);
6252   gtk_signal_connect (GTK_OBJECT (calendar), "month_changed", 
6253                       GTK_SIGNAL_FUNC (calendar_month_changed),
6254                       &amp;calendar_data);
6255   gtk_signal_connect (GTK_OBJECT (calendar), "day_selected", 
6256                       GTK_SIGNAL_FUNC (calendar_day_selected),
6257                       &amp;calendar_data);
6258   gtk_signal_connect (GTK_OBJECT (calendar), "day_selected_double_click", 
6259                       GTK_SIGNAL_FUNC (calendar_day_selected_double_click),
6260                       &amp;calendar_data);
6261   gtk_signal_connect (GTK_OBJECT (calendar), "prev_month", 
6262                       GTK_SIGNAL_FUNC (calendar_prev_month),
6263                       &amp;calendar_data);
6264   gtk_signal_connect (GTK_OBJECT (calendar), "next_month", 
6265                       GTK_SIGNAL_FUNC (calendar_next_month),
6266                       &amp;calendar_data);
6267   gtk_signal_connect (GTK_OBJECT (calendar), "prev_year", 
6268                       GTK_SIGNAL_FUNC (calendar_prev_year),
6269                       &amp;calendar_data);
6270   gtk_signal_connect (GTK_OBJECT (calendar), "next_year", 
6271                       GTK_SIGNAL_FUNC (calendar_next_year),
6272                       &amp;calendar_data);
6273
6274
6275   separator = gtk_vseparator_new ();
6276   gtk_box_pack_start (GTK_BOX (hbox), separator, FALSE, TRUE, 0);
6277
6278   vbox2 = gtk_vbox_new(FALSE, DEF_PAD);
6279   gtk_box_pack_start(GTK_BOX(hbox), vbox2, FALSE, FALSE, DEF_PAD);
6280   
6281   /* Build the Right frame with the flags in */ 
6282
6283   frame = gtk_frame_new("Flags");
6284   gtk_box_pack_start(GTK_BOX(vbox2), frame, TRUE, TRUE, DEF_PAD);
6285   vbox3 = gtk_vbox_new(TRUE, DEF_PAD_SMALL);
6286   gtk_container_add(GTK_CONTAINER(frame), vbox3);
6287
6288   for (i = 0; i < 5; i++)
6289     {
6290       toggle = gtk_check_button_new_with_label(flags[i].label);
6291       gtk_signal_connect (GTK_OBJECT (toggle),
6292                             "toggled",
6293                             GTK_SIGNAL_FUNC(calendar_toggle_flag),
6294                             &amp;calendar_data);
6295       gtk_box_pack_start (GTK_BOX (vbox3), toggle, TRUE, TRUE, 0);
6296       calendar_data.flag_checkboxes[i]=toggle;
6297     }
6298   /* Build the right font-button */ 
6299   button = gtk_button_new_with_label("Font...");
6300   gtk_signal_connect (GTK_OBJECT (button),
6301                       "clicked",
6302                       GTK_SIGNAL_FUNC(calendar_select_font),
6303                       &amp;calendar_data);
6304   gtk_box_pack_start (GTK_BOX (vbox2), button, FALSE, FALSE, 0);
6305
6306   /*
6307    *  Build the Signal-event part.
6308    */
6309
6310   frame = gtk_frame_new("Signal events");
6311   gtk_box_pack_start(GTK_BOX(vbox), frame, TRUE, TRUE, DEF_PAD);
6312
6313   vbox2 = gtk_vbox_new(TRUE, DEF_PAD_SMALL);
6314   gtk_container_add(GTK_CONTAINER(frame), vbox2);
6315   
6316   hbox = gtk_hbox_new (FALSE, 3);
6317   gtk_box_pack_start (GTK_BOX (vbox2), hbox, FALSE, TRUE, 0);
6318   label = gtk_label_new ("Signal:");
6319   gtk_box_pack_start (GTK_BOX (hbox), label, FALSE, TRUE, 0);
6320   calendar_data.last_sig = gtk_label_new ("");
6321   gtk_box_pack_start (GTK_BOX (hbox), calendar_data.last_sig, FALSE, TRUE, 0);
6322
6323   hbox = gtk_hbox_new (FALSE, 3);
6324   gtk_box_pack_start (GTK_BOX (vbox2), hbox, FALSE, TRUE, 0);
6325   label = gtk_label_new ("Previous signal:");
6326   gtk_box_pack_start (GTK_BOX (hbox), label, FALSE, TRUE, 0);
6327   calendar_data.prev_sig = gtk_label_new ("");
6328   gtk_box_pack_start (GTK_BOX (hbox), calendar_data.prev_sig, FALSE, TRUE, 0);
6329
6330   hbox = gtk_hbox_new (FALSE, 3);
6331   gtk_box_pack_start (GTK_BOX (vbox2), hbox, FALSE, TRUE, 0);
6332   label = gtk_label_new ("Second previous signal:");
6333   gtk_box_pack_start (GTK_BOX (hbox), label, FALSE, TRUE, 0);
6334   calendar_data.prev2_sig = gtk_label_new ("");
6335   gtk_box_pack_start (GTK_BOX (hbox), calendar_data.prev2_sig, FALSE, TRUE, 0);
6336
6337   bbox = gtk_hbutton_box_new ();
6338   gtk_box_pack_start (GTK_BOX (vbox), bbox, FALSE, FALSE, 0);
6339   gtk_button_box_set_layout(GTK_BUTTON_BOX(bbox), GTK_BUTTONBOX_END);
6340
6341   button = gtk_button_new_with_label ("Close");
6342   gtk_signal_connect (GTK_OBJECT (button), "clicked", 
6343                       GTK_SIGNAL_FUNC (gtk_main_quit), 
6344                       NULL);
6345   gtk_container_add (GTK_CONTAINER (bbox), button);
6346   GTK_WIDGET_SET_FLAGS (button, GTK_CAN_DEFAULT);
6347   gtk_widget_grab_default (button);
6348
6349   gtk_widget_show_all(window);
6350 }
6351
6352
6353 int main(int   argc,
6354          char *argv[] )
6355 {
6356   gtk_set_locale ();
6357   gtk_init (&amp;argc, &amp;argv);
6358
6359   create_calendar();
6360
6361   gtk_main();
6362
6363   return(0);
6364 }
6365 <!-- example-end -->
6366 </programlisting>
6367
6368 </sect1>
6369
6370 <!-- ----------------------------------------------------------------- -->
6371 <sect1 id="sec-ColorSelection">
6372 <title>Color Selection</title>
6373
6374 <para>The color selection widget is, not surprisingly, a widget for
6375 interactive selection of colors. This composite widget lets the user
6376 select a color by manipulating RGB (Red, Green, Blue) and HSV (Hue,
6377 Saturation, Value) triples.  This is done either by adjusting single
6378 values with sliders or entries, or by picking the desired color from a
6379 hue-saturation wheel/value bar.  Optionally, the opacity of the color
6380 can also be set.</para>
6381
6382 <para>The color selection widget currently emits only one signal,
6383 "color_changed", which is emitted whenever the current color in the
6384 widget changes, either when the user changes it or if it's set
6385 explicitly through gtk_color_selection_set_color().</para>
6386
6387 <para>Lets have a look at what the color selection widget has to offer
6388 us. The widget comes in two flavours: gtk_color_selection and
6389 gtk_color_selection_dialog.</para>
6390
6391 <programlisting role="C">
6392 GtkWidget *gtk_color_selection_new( void );
6393 </programlisting>
6394         
6395 <para>You'll probably not be using this constructor directly. It creates an
6396 orphan ColorSelection widget which you'll have to parent
6397 yourself. The ColorSelection widget inherits from the VBox
6398 widget.</para>
6399
6400 <programlisting role="C">
6401 GtkWidget *gtk_color_selection_dialog_new( const gchar *title );
6402 </programlisting>
6403
6404 <para>This is the most common color selection constructor. It creates a
6405 ColorSelectionDialog. It consists of a Frame containing a
6406 ColorSelection widget, an HSeparator and an HBox with three buttons,
6407 "Ok", "Cancel" and "Help". You can reach these buttons by accessing
6408 the "ok_button", "cancel_button" and "help_button" widgets in the
6409 ColorSelectionDialog structure,
6410 (i.e., <literal>GTK_COLOR_SELECTION_DIALOG(colorseldialog)->ok_button</literal>)).</para>
6411
6412 <programlisting role="C">
6413 void gtk_color_selection_set_update_policy( GtkColorSelection *colorsel, 
6414                                             GtkUpdateType      policy );
6415 </programlisting>
6416
6417 <para>This function sets the update policy. The default policy is
6418 <literal>GTK_UPDATE_CONTINUOUS</literal> which means that the current color is
6419 updated continuously when the user drags the sliders or presses the
6420 mouse and drags in the hue-saturation wheel or value bar. If you
6421 experience performance problems, you may want to set the policy to
6422 <literal>GTK_UPDATE_DISCONTINUOUS</literal> or <literal>GTK_UPDATE_DELAYED</literal>.</para>
6423
6424 <programlisting role="C">
6425 void gtk_color_selection_set_opacity( GtkColorSelection *colorsel,
6426                                       gint               use_opacity );
6427 </programlisting>
6428
6429 <para>The color selection widget supports adjusting the opacity of a color
6430 (also known as the alpha channel). This is disabled by
6431 default. Calling this function with use_opacity set to TRUE enables
6432 opacity. Likewise, use_opacity set to FALSE will disable opacity.</para>
6433
6434 <programlisting role="C">
6435 void gtk_color_selection_set_color( GtkColorSelection *colorsel,
6436                                     gdouble           *color );
6437 </programlisting>
6438
6439 <para>You can set the current color explicitly by calling this function with
6440 a pointer to an array of colors (gdouble). The length of the array
6441 depends on whether opacity is enabled or not. Position 0 contains the
6442 red component, 1 is green, 2 is blue and opacity is at position 3
6443 (only if opacity is enabled, see
6444 gtk_color_selection_set_opacity()). All values are between 0.0 and
6445 1.0.</para>
6446
6447 <programlisting role="C">
6448 void gtk_color_selection_get_color( GtkColorSelection *colorsel,
6449                                     gdouble           *color );
6450 </programlisting>
6451
6452 <para>When you need to query the current color, typically when you've
6453 received a "color_changed" signal, you use this function. Color is a
6454 pointer to the array of colors to fill in. See the
6455 gtk_color_selection_set_color() function for the description of this
6456 array.</para>
6457
6458 <para><!-- Need to do a whole section on DnD - TRG
6459 Drag and drop
6460 -------------</para>
6461
6462 <para>The color sample areas (right under the hue-saturation wheel) supports
6463 drag and drop. The type of drag and drop is "application/x-color". The
6464 message data consists of an array of 4 (or 5 if opacity is enabled)
6465 gdouble values, where the value at position 0 is 0.0 (opacity on) or
6466 1.0 (opacity off) followed by the red, green and blue values at
6467 positions 1,2 and 3 respectively.  If opacity is enabled, the opacity
6468 is passed in the value at position 4.
6469 --></para>
6470
6471 <para>Here's a simple example demonstrating the use of the
6472 ColorSelectionDialog. The program displays a window containing a
6473 drawing area. Clicking on it opens a color selection dialog, and
6474 changing the color in the color selection dialog changes the
6475 background color.</para>
6476
6477 <programlisting role="C">
6478 <!-- example-start colorsel colorsel.c -->
6479
6480 #include &lt;glib.h&gt;
6481 #include &lt;gdk/gdk.h&gt;
6482 #include &lt;gtk/gtk.h&gt;
6483
6484 GtkWidget *colorseldlg = NULL;
6485 GtkWidget *drawingarea = NULL;
6486
6487 /* Color changed handler */
6488
6489 void color_changed_cb( GtkWidget         *widget,
6490                        GtkColorSelection *colorsel )
6491 {
6492   gdouble color[3];
6493   GdkColor gdk_color;
6494   GdkColormap *colormap;
6495
6496   /* Get drawingarea colormap */
6497
6498   colormap = gdk_window_get_colormap (drawingarea->window);
6499
6500   /* Get current color */
6501
6502   gtk_color_selection_get_color (colorsel,color);
6503
6504   /* Fit to a unsigned 16 bit integer (0..65535) and
6505    * insert into the GdkColor structure */
6506
6507   gdk_color.red = (guint16)(color[0]*65535.0);
6508   gdk_color.green = (guint16)(color[1]*65535.0);
6509   gdk_color.blue = (guint16)(color[2]*65535.0);
6510
6511   /* Allocate color */
6512
6513   gdk_color_alloc (colormap, &amp;gdk_color);
6514
6515   /* Set window background color */
6516
6517   gdk_window_set_background (drawingarea->window, &amp;gdk_color);
6518
6519   /* Clear window */
6520
6521   gdk_window_clear (drawingarea->window);
6522 }
6523
6524 /* Drawingarea event handler */
6525
6526 gint area_event( GtkWidget *widget,
6527                  GdkEvent  *event,
6528                  gpointer   client_data )
6529 {
6530   gint handled = FALSE;
6531   GtkWidget *colorsel;
6532
6533   /* Check if we've received a button pressed event */
6534
6535   if (event->type == GDK_BUTTON_PRESS &amp;&amp; colorseldlg == NULL)
6536     {
6537       /* Yes, we have an event and there's no colorseldlg yet! */
6538
6539       handled = TRUE;
6540
6541       /* Create color selection dialog */
6542
6543       colorseldlg = gtk_color_selection_dialog_new("Select background color");
6544
6545       /* Get the ColorSelection widget */
6546
6547       colorsel = GTK_COLOR_SELECTION_DIALOG(colorseldlg)->colorsel;
6548
6549       /* Connect to the "color_changed" signal, set the client-data
6550        * to the colorsel widget */
6551
6552       gtk_signal_connect(GTK_OBJECT(colorsel), "color_changed",
6553         (GtkSignalFunc)color_changed_cb, (gpointer)colorsel);
6554
6555       /* Show the dialog */
6556
6557       gtk_widget_show(colorseldlg);
6558     }
6559
6560   return handled;
6561 }
6562
6563 /* Close down and exit handler */
6564
6565 gint destroy_window( GtkWidget *widget,
6566                      GdkEvent  *event,
6567                      gpointer   client_data )
6568 {
6569   gtk_main_quit ();
6570   return(TRUE);
6571 }
6572
6573 /* Main */
6574
6575 gint main( gint   argc,
6576            gchar *argv[] )
6577 {
6578   GtkWidget *window;
6579
6580   /* Initialize the toolkit, remove gtk-related commandline stuff */
6581
6582   gtk_init (&amp;argc,&amp;argv);
6583
6584   /* Create toplevel window, set title and policies */
6585
6586   window = gtk_window_new (GTK_WINDOW_TOPLEVEL);
6587   gtk_window_set_title (GTK_WINDOW(window), "Color selection test");
6588   gtk_window_set_policy (GTK_WINDOW(window), TRUE, TRUE, TRUE);
6589
6590   /* Attach to the "delete" and "destroy" events so we can exit */
6591
6592   gtk_signal_connect (GTK_OBJECT(window), "delete_event",
6593     (GtkSignalFunc)destroy_window, (gpointer)window);
6594   
6595   /* Create drawingarea, set size and catch button events */
6596
6597   drawingarea = gtk_drawing_area_new ();
6598
6599   gtk_drawing_area_size (GTK_DRAWING_AREA(drawingarea), 200, 200);
6600
6601   gtk_widget_set_events (drawingarea, GDK_BUTTON_PRESS_MASK);
6602
6603   gtk_signal_connect (GTK_OBJECT(drawingarea), "event", 
6604     (GtkSignalFunc)area_event, (gpointer)drawingarea);
6605   
6606   /* Add drawingarea to window, then show them both */
6607
6608   gtk_container_add (GTK_CONTAINER(window), drawingarea);
6609
6610   gtk_widget_show (drawingarea);
6611   gtk_widget_show (window);
6612   
6613   /* Enter the gtk main loop (this never returns) */
6614
6615   gtk_main ();
6616
6617   /* Satisfy grumpy compilers */
6618
6619   return(0);
6620 }
6621 <!-- example-end -->
6622 </programlisting>
6623
6624 </sect1>
6625
6626 <!-- ----------------------------------------------------------------- -->
6627 <sect1 id="sec-FileSelections">
6628 <title>File Selections</title>
6629
6630 <para>The file selection widget is a quick and simple way to display a File
6631 dialog box. It comes complete with Ok, Cancel, and Help buttons, a
6632 great way to cut down on programming time.</para>
6633
6634 <para>To create a new file selection box use:</para>
6635
6636 <programlisting role="C">
6637 GtkWidget *gtk_file_selection_new( gchar *title );
6638 </programlisting>
6639
6640 <para>To set the filename, for example to bring up a specific directory, or
6641 give a default filename, use this function:</para>
6642
6643 <programlisting role="C">
6644 void gtk_file_selection_set_filename( GtkFileSelection *filesel,
6645                                       gchar            *filename );
6646 </programlisting>
6647
6648 <para>To grab the text that the user has entered or clicked on, use this 
6649 function:</para>
6650
6651 <programlisting role="C">
6652 gchar *gtk_file_selection_get_filename( GtkFileSelection *filesel );
6653 </programlisting>
6654
6655 <para>There are also pointers to the widgets contained within the file 
6656 selection widget. These are:</para>
6657
6658 <programlisting role="C">
6659   dir_list
6660   file_list
6661   selection_entry
6662   selection_text
6663   main_vbox
6664   ok_button
6665   cancel_button
6666   help_button
6667 </programlisting>
6668  
6669 <para>Most likely you will want to use the ok_button, cancel_button, and
6670 help_button pointers in signaling their use.</para>
6671
6672 <para>Included here is an example stolen from testgtk.c, modified to run on
6673 its own. As you will see, there is nothing much to creating a file
6674 selection widget. While in this example the Help button appears on the
6675 screen, it does nothing as there is not a signal attached to it.</para>
6676
6677 <programlisting role="C">
6678 <!-- example-start filesel filesel.c -->
6679
6680 #include &lt;gtk/gtk.h&gt;
6681
6682 /* Get the selected filename and print it to the console */
6683 void file_ok_sel( GtkWidget        *w,
6684                   GtkFileSelection *fs )
6685 {
6686     g_print ("%s\n", gtk_file_selection_get_filename (GTK_FILE_SELECTION (fs)));
6687 }
6688
6689 void destroy( GtkWidget *widget,
6690               gpointer   data )
6691 {
6692     gtk_main_quit ();
6693 }
6694
6695 int main( int   argc,
6696           char *argv[] )
6697 {
6698     GtkWidget *filew;
6699     
6700     gtk_init (&amp;argc, &amp;argv);
6701     
6702     /* Create a new file selection widget */
6703     filew = gtk_file_selection_new ("File selection");
6704     
6705     gtk_signal_connect (GTK_OBJECT (filew), "destroy",
6706                         (GtkSignalFunc) destroy, &amp;filew);
6707     /* Connect the ok_button to file_ok_sel function */
6708     gtk_signal_connect (GTK_OBJECT (GTK_FILE_SELECTION (filew)->ok_button),
6709                         "clicked", (GtkSignalFunc) file_ok_sel, filew );
6710     
6711     /* Connect the cancel_button to destroy the widget */
6712     gtk_signal_connect_object (GTK_OBJECT (GTK_FILE_SELECTION
6713                                             (filew)->cancel_button),
6714                                "clicked", (GtkSignalFunc) gtk_widget_destroy,
6715                                GTK_OBJECT (filew));
6716     
6717     /* Lets set the filename, as if this were a save dialog, and we are giving
6718      a default filename */
6719     gtk_file_selection_set_filename (GTK_FILE_SELECTION(filew), 
6720                                      "penguin.png");
6721     
6722     gtk_widget_show(filew);
6723     gtk_main ();
6724     return 0;
6725 }
6726 <!-- example-end -->
6727 </programlisting>
6728
6729 </sect1>
6730 </chapter>
6731
6732 <!-- ***************************************************************** -->
6733 <chapter id="ch-ContainerWidgets">
6734 <title>Container Widgets</title>
6735
6736 <!-- ----------------------------------------------------------------- -->   
6737 <sect1 id="sec-EventBox">
6738 <title>The EventBox</title>
6739
6740 <para>Some GTK widgets don't have associated X windows, so they just draw on
6741 their parents. Because of this, they cannot receive events and if they
6742 are incorrectly sized, they don't clip so you can get messy
6743 overwriting, etc. If you require more from these widgets, the EventBox
6744 is for you.</para>
6745
6746 <para>At first glance, the EventBox widget might appear to be totally
6747 useless. It draws nothing on the screen and responds to no
6748 events. However, it does serve a function - it provides an X window
6749 for its child widget. This is important as many GTK widgets do not
6750 have an associated X window. Not having an X window saves memory and
6751 improves performance, but also has some drawbacks. A widget without an
6752 X window cannot receive events, and does not perform any clipping on
6753 its contents. Although the name <emphasis>EventBox</emphasis> emphasizes the
6754 event-handling function, the widget can also be used for clipping.
6755 (and more, see the example below).</para>
6756
6757 <para>To create a new EventBox widget, use:</para>
6758
6759 <programlisting role="C">
6760 GtkWidget *gtk_event_box_new( void );
6761 </programlisting>
6762
6763 <para>A child widget can then be added to this EventBox:</para>
6764
6765 <programlisting role="C">
6766     gtk_container_add( GTK_CONTAINER(event_box), child_widget );
6767 </programlisting>
6768
6769 <para>The following example demonstrates both uses of an EventBox - a label
6770 is created that is clipped to a small box, and set up so that a
6771 mouse-click on the label causes the program to exit. Resizing the
6772 window reveals varying amounts of the label.</para>
6773
6774 <programlisting role="C">
6775 <!-- example-start eventbox eventbox.c -->
6776
6777 #include &lt;gtk/gtk.h&gt;
6778
6779 int main( int argc,
6780           char *argv[] )
6781 {
6782     GtkWidget *window;
6783     GtkWidget *event_box;
6784     GtkWidget *label;
6785     
6786     gtk_init (&amp;argc, &amp;argv);
6787     
6788     window = gtk_window_new (GTK_WINDOW_TOPLEVEL);
6789     
6790     gtk_window_set_title (GTK_WINDOW (window), "Event Box");
6791     
6792     gtk_signal_connect (GTK_OBJECT (window), "destroy",
6793                         GTK_SIGNAL_FUNC (gtk_exit), NULL);
6794     
6795     gtk_container_set_border_width (GTK_CONTAINER (window), 10);
6796     
6797     /* Create an EventBox and add it to our toplevel window */
6798     
6799     event_box = gtk_event_box_new ();
6800     gtk_container_add (GTK_CONTAINER(window), event_box);
6801     gtk_widget_show (event_box);
6802     
6803     /* Create a long label */
6804     
6805     label = gtk_label_new ("Click here to quit, quit, quit, quit, quit");
6806     gtk_container_add (GTK_CONTAINER (event_box), label);
6807     gtk_widget_show (label);
6808     
6809     /* Clip it short. */
6810     gtk_widget_set_usize (label, 110, 20);
6811     
6812     /* And bind an action to it */
6813     gtk_widget_set_events (event_box, GDK_BUTTON_PRESS_MASK);
6814     gtk_signal_connect (GTK_OBJECT(event_box), "button_press_event",
6815                         GTK_SIGNAL_FUNC (gtk_exit), NULL);
6816     
6817     /* Yet one more thing you need an X window for ... */
6818     
6819     gtk_widget_realize (event_box);
6820     gdk_window_set_cursor (event_box->window, gdk_cursor_new (GDK_HAND1));
6821     
6822     gtk_widget_show (window);
6823     
6824     gtk_main ();
6825     
6826     return(0);
6827 }
6828 <!-- example-end -->
6829 </programlisting>
6830
6831 </sect1>
6832
6833 <!-- ----------------------------------------------------------------- -->   
6834 <sect1 id="sec-TheAlignmentWidget">
6835 <title>The Alignment widget</title>
6836
6837 <para>The alignment widget allows you to place a widget within its window at
6838 a position and size relative to the size of the Alignment widget
6839 itself. For example, it can be very useful for centering a widget
6840 within the window.</para>
6841
6842 <para>There are only two functions associated with the Alignment widget:</para>
6843
6844 <programlisting role="C">
6845 GtkWidget* gtk_alignment_new( gfloat xalign,
6846                               gfloat yalign,
6847                               gfloat xscale,
6848                               gfloat yscale );
6849
6850 void gtk_alignment_set( GtkAlignment *alignment,
6851                         gfloat        xalign,
6852                         gfloat        yalign,
6853                         gfloat        xscale,
6854                         gfloat        yscale );
6855 </programlisting>
6856
6857 <para>The first function creates a new Alignment widget with the specified
6858 parameters. The second function allows the alignment paramters of an
6859 exisiting Alignment widget to be altered.</para>
6860
6861 <para>All four alignment parameters are floating point numbers which can
6862 range from 0.0 to 1.0. The <literal>xalign</literal> and <literal>yalign</literal> arguments
6863 affect the position of the widget placed within the Alignment
6864 widget. The <literal>xscale</literal> and <literal>yscale</literal> arguments effect the amount of
6865 space allocated to the widget.</para>
6866
6867 <para>A child widget can be added to this Alignment widget using:</para>
6868
6869 <programlisting role="C">
6870     gtk_container_add( GTK_CONTAINER(alignment), child_widget );
6871 </programlisting>
6872
6873 <para>For an example of using an Alignment widget, refer to the example for
6874 the <link linkend="sec-ProgressBars">Progress Bar</link> widget.</para>
6875
6876 </sect1>
6877
6878 <!-- ----------------------------------------------------------------- -->
6879 <sect1 id="sec-FixedContainer">
6880 <title>Fixed Container</title>
6881
6882 <para>The Fixed container allows you to place widgets at a fixed position
6883 within it's window, relative to it's upper left hand corner. The
6884 position of the widgets can be changed dynamically.</para>
6885
6886 <para>There are only three functions associated with the fixed widget:</para>
6887
6888 <programlisting role="C">
6889 GtkWidget* gtk_fixed_new( void );
6890
6891 void gtk_fixed_put( GtkFixed  *fixed,
6892                     GtkWidget *widget,
6893                     gint16     x,
6894                     gint16     y );
6895
6896 void gtk_fixed_move( GtkFixed  *fixed,
6897                      GtkWidget *widget,
6898                      gint16     x,
6899                      gint16     y );
6900 </programlisting>
6901
6902 <para>The function <literal>gtk_fixed_new</literal> allows you to create a new Fixed
6903 container.</para>
6904
6905 <para><literal>gtk_fixed_put</literal> places <literal>widget</literal> in the container <literal>fixed</literal> at
6906 the position specified by <literal>x</literal> and <literal>y</literal>.</para>
6907
6908 <para><literal>gtk_fixed_move</literal> allows the specified widget to be moved to a new
6909 position.</para>
6910
6911 <para>The following example illustrates how to use the Fixed Container.</para>
6912
6913 <programlisting role="C">
6914 <!-- example-start fixed fixed.c -->
6915
6916 #include &lt;gtk/gtk.h&gt;
6917
6918 /* I'm going to be lazy and use some global variables to
6919  * store the position of the widget within the fixed
6920  * container */
6921 gint x=50;
6922 gint y=50;
6923
6924 /* This callback function moves the button to a new position
6925  * in the Fixed container. */
6926 void move_button( GtkWidget *widget,
6927                   GtkWidget *fixed )
6928 {
6929   x = (x+30)%300;
6930   y = (y+50)%300;
6931   gtk_fixed_move( GTK_FIXED(fixed), widget, x, y); 
6932 }
6933
6934 int main( int   argc,
6935           char *argv[] )
6936 {
6937   /* GtkWidget is the storage type for widgets */
6938   GtkWidget *window;
6939   GtkWidget *fixed;
6940   GtkWidget *button;
6941   gint i;
6942
6943   /* Initialise GTK */
6944   gtk_init(&amp;argc, &amp;argv);
6945     
6946   /* Create a new window */
6947   window = gtk_window_new (GTK_WINDOW_TOPLEVEL);
6948   gtk_window_set_title(GTK_WINDOW(window), "Fixed Container");
6949
6950   /* Here we connect the "destroy" event to a signal handler */ 
6951   gtk_signal_connect (GTK_OBJECT (window), "destroy",
6952                       GTK_SIGNAL_FUNC (gtk_main_quit), NULL);
6953  
6954   /* Sets the border width of the window. */
6955   gtk_container_set_border_width (GTK_CONTAINER (window), 10);
6956
6957   /* Create a Fixed Container */
6958   fixed = gtk_fixed_new();
6959   gtk_container_add(GTK_CONTAINER(window), fixed);
6960   gtk_widget_show(fixed);
6961   
6962   for (i = 1 ; i <= 3 ; i++) {
6963     /* Creates a new button with the label "Press me" */
6964     button = gtk_button_new_with_label ("Press me");
6965   
6966     /* When the button receives the "clicked" signal, it will call the
6967      * function move_button() passing it the Fixed Container as its
6968      * argument. */
6969     gtk_signal_connect (GTK_OBJECT (button), "clicked",
6970                         GTK_SIGNAL_FUNC (move_button), fixed);
6971   
6972     /* This packs the button into the fixed containers window. */
6973     gtk_fixed_put (GTK_FIXED (fixed), button, i*50, i*50);
6974   
6975     /* The final step is to display this newly created widget. */
6976     gtk_widget_show (button);
6977   }
6978
6979   /* Display the window */
6980   gtk_widget_show (window);
6981     
6982   /* Enter the event loop */
6983   gtk_main ();
6984     
6985   return(0);
6986 }
6987 <!-- example-end -->
6988 </programlisting>
6989
6990 </sect1>
6991
6992 <!-- ----------------------------------------------------------------- -->
6993 <sect1 id="sec-LayoutContainer">
6994 <title>Layout Container</title>
6995
6996 <para>The Layout container is similar to the Fixed container except that it
6997 implements an infinite (where infinity is less than 2^32) scrolling
6998 area. The X window system has a limitation where windows can be at
6999 most 32767 pixels wide or tall. The Layout container gets around this
7000 limitation by doing some exotic stuff using window and bit gravities,
7001 so that you can have smooth scrolling even when you have many child
7002 widgets in your scrolling area.</para>
7003
7004 <para>A Layout container is created using:</para>
7005
7006 <programlisting role="C">
7007 GtkWidget *gtk_layout_new( GtkAdjustment *hadjustment,
7008                            GtkAdjustment *vadjustment );
7009 </programlisting>
7010
7011 <para>As you can see, you can optionally specify the Adjustment objects that
7012 the Layout widget will use for its scrolling.</para>
7013
7014 <para>You can add and move widgets in the Layout container using the
7015 following two functions:</para>
7016
7017 <programlisting role="C">
7018 void gtk_layout_put( GtkLayout *layout,
7019                      GtkWidget *widget,
7020                      gint       x,
7021                      gint       y );
7022
7023 void gtk_layout_move( GtkLayout *layout,
7024                       GtkWidget *widget,
7025                       gint       x,
7026                       gint       y );
7027 </programlisting>
7028
7029 <para>The size of the Layout container can be set using the next function:</para>
7030
7031 <programlisting role="C">
7032 void gtk_layout_set_size( GtkLayout *layout,
7033                           guint      width,
7034                           guint      height );
7035 </programlisting>
7036
7037 <para>Layout containers are one of the very few widgets in the GTK widget
7038 set that actively repaint themselves on screen as they are changed
7039 using the above functions (the vast majority of widgets queue
7040 requests which are then processed when control returns to the
7041 <literal>gtk_main()</literal> function).</para>
7042
7043 <para>When you want to make a large number of changes to a Layout container,
7044 you can use the following two functions to disable and re-enable this
7045 repainting functionality:</para>
7046
7047 <programlisting role="C">
7048 void gtk_layout_freeze( GtkLayout *layout );
7049
7050 void gtk_layout_thaw( GtkLayout *layout );
7051 </programlisting>
7052
7053 <para>The final four functions for use with Layout widgets are for
7054 manipulating the horizontal and vertical adjustment widgets:</para>
7055
7056 <programlisting role="C">
7057 GtkAdjustment* gtk_layout_get_hadjustment( GtkLayout *layout );
7058
7059 GtkAdjustment* gtk_layout_get_vadjustment( GtkLayout *layout );
7060
7061 void gtk_layout_set_hadjustment( GtkLayout     *layout,
7062                                  GtkAdjustment *adjustment );
7063
7064 void gtk_layout_set_vadjustment( GtkLayout     *layout,
7065                                  GtkAdjustment *adjustment);
7066 </programlisting>
7067
7068 </sect1>
7069
7070 <!-- ----------------------------------------------------------------- -->
7071 <sect1 id="sec-Frames">
7072 <title>Frames</title>
7073
7074 <para>Frames can be used to enclose one or a group of widgets with a box
7075 which can optionally be labelled. The position of the label and the
7076 style of the box can be altered to suit.</para>
7077
7078 <para>A Frame can be created with the following function:</para>
7079
7080 <programlisting role="C">
7081 GtkWidget *gtk_frame_new( const gchar *label );
7082 </programlisting>
7083
7084 <para>The label is by default placed in the upper left hand corner of the
7085 frame. A value of NULL for the <literal>label</literal> argument will result in no
7086 label being displayed. The text of the label can be changed using the
7087 next function.</para>
7088
7089 <programlisting role="C">
7090 void gtk_frame_set_label( GtkFrame    *frame,
7091                           const gchar *label );
7092 </programlisting>
7093
7094 <para>The position of the label can be changed using this function:</para>
7095
7096 <programlisting role="C">
7097 void gtk_frame_set_label_align( GtkFrame *frame,
7098                                 gfloat    xalign,
7099                                 gfloat    yalign );
7100 </programlisting>
7101
7102 <para><literal>xalign</literal> and <literal>yalign</literal> take values between 0.0 and 1.0. <literal>xalign</literal>
7103 indicates the position of the label along the top horizontal of the
7104 frame. <literal>yalign</literal> is not currently used. The default value of xalign
7105 is 0.0 which places the label at the left hand end of the frame.</para>
7106
7107 <para>The next function alters the style of the box that is used to outline
7108 the frame.</para>
7109
7110 <programlisting role="C">
7111 void gtk_frame_set_shadow_type( GtkFrame      *frame,
7112                                 GtkShadowType  type);
7113 </programlisting>
7114
7115 <para>The <literal>type</literal> argument can take one of the following values:</para>
7116 <programlisting role="C">
7117   GTK_SHADOW_NONE
7118   GTK_SHADOW_IN
7119   GTK_SHADOW_OUT
7120   GTK_SHADOW_ETCHED_IN (the default)
7121   GTK_SHADOW_ETCHED_OUT
7122 </programlisting>
7123
7124 <para>The following code example illustrates the use of the Frame widget.</para>
7125
7126 <programlisting role="C">
7127 <!-- example-start frame frame.c -->
7128
7129 #include &lt;gtk/gtk.h&gt;
7130
7131 int main( int   argc,
7132           char *argv[] )
7133 {
7134   /* GtkWidget is the storage type for widgets */
7135   GtkWidget *window;
7136   GtkWidget *frame;
7137   GtkWidget *button;
7138   gint i;
7139
7140   /* Initialise GTK */
7141   gtk_init(&amp;argc, &amp;argv);
7142     
7143   /* Create a new window */
7144   window = gtk_window_new (GTK_WINDOW_TOPLEVEL);
7145   gtk_window_set_title(GTK_WINDOW(window), "Frame Example");
7146
7147   /* Here we connect the "destroy" event to a signal handler */ 
7148   gtk_signal_connect (GTK_OBJECT (window), "destroy",
7149                       GTK_SIGNAL_FUNC (gtk_main_quit), NULL);
7150
7151   gtk_widget_set_usize(window, 300, 300);
7152   /* Sets the border width of the window. */
7153   gtk_container_set_border_width (GTK_CONTAINER (window), 10);
7154
7155   /* Create a Frame */
7156   frame = gtk_frame_new(NULL);
7157   gtk_container_add(GTK_CONTAINER(window), frame);
7158
7159   /* Set the frame's label */
7160   gtk_frame_set_label( GTK_FRAME(frame), "GTK Frame Widget" );
7161
7162   /* Align the label at the right of the frame */
7163   gtk_frame_set_label_align( GTK_FRAME(frame), 1.0, 0.0);
7164
7165   /* Set the style of the frame */
7166   gtk_frame_set_shadow_type( GTK_FRAME(frame), GTK_SHADOW_ETCHED_OUT);
7167
7168   gtk_widget_show(frame);
7169   
7170   /* Display the window */
7171   gtk_widget_show (window);
7172     
7173   /* Enter the event loop */
7174   gtk_main ();
7175     
7176   return(0);
7177 }
7178 <!-- example-end -->
7179 </programlisting>
7180
7181 </sect1>
7182
7183 <!-- ----------------------------------------------------------------- -->   
7184 <sect1 id="sec-AspectFrames">
7185 <title>Aspect Frames</title>
7186
7187 <para>The aspect frame widget is like a frame widget, except that it also
7188 enforces the aspect ratio (that is, the ratio of the width to the
7189 height) of the child widget to have a certain value, adding extra
7190 space if necessary. This is useful, for instance, if you want to
7191 preview a larger image. The size of the preview should vary when the
7192 user resizes the window, but the aspect ratio needs to always match
7193 the original image.</para>
7194   
7195 <para>To create a new aspect frame use:</para>
7196
7197 <programlisting role="C">
7198 GtkWidget *gtk_aspect_frame_new( const gchar *label,
7199                                  gfloat       xalign,
7200                                  gfloat       yalign,
7201                                  gfloat       ratio,
7202                                  gint         obey_child);
7203 </programlisting>
7204    
7205 <para><literal>xalign</literal> and <literal>yalign</literal> specify alignment as with Alignment
7206 widgets. If <literal>obey_child</literal> is true, the aspect ratio of a child
7207 widget will match the aspect ratio of the ideal size it requests.
7208 Otherwise, it is given by <literal>ratio</literal>.</para>
7209    
7210 <para>To change the options of an existing aspect frame, you can use:</para>
7211
7212 <programlisting role="C">
7213 void gtk_aspect_frame_set( GtkAspectFrame *aspect_frame,
7214                            gfloat          xalign,
7215                            gfloat          yalign,
7216                            gfloat          ratio,
7217                            gint            obey_child);
7218 </programlisting>
7219    
7220 <para>As an example, the following program uses an AspectFrame to present a
7221 drawing area whose aspect ratio will always be 2:1, no matter how the
7222 user resizes the top-level window.</para>
7223
7224 <programlisting role="C">
7225 <!-- example-start aspectframe aspectframe.c -->
7226
7227 #include &lt;gtk/gtk.h&gt;
7228    
7229 int main( int argc,
7230           char *argv[] )
7231 {
7232     GtkWidget *window;
7233     GtkWidget *aspect_frame;
7234     GtkWidget *drawing_area;
7235     gtk_init (&amp;argc, &amp;argv);
7236    
7237     window = gtk_window_new (GTK_WINDOW_TOPLEVEL);
7238     gtk_window_set_title (GTK_WINDOW (window), "Aspect Frame");
7239     gtk_signal_connect (GTK_OBJECT (window), "destroy",
7240                         GTK_SIGNAL_FUNC (gtk_main_quit), NULL);
7241     gtk_container_set_border_width (GTK_CONTAINER (window), 10);
7242    
7243     /* Create an aspect_frame and add it to our toplevel window */
7244    
7245     aspect_frame = gtk_aspect_frame_new ("2x1", /* label */
7246                                          0.5, /* center x */
7247                                          0.5, /* center y */
7248                                          2, /* xsize/ysize = 2 */
7249                                          FALSE /* ignore child's aspect */);
7250    
7251     gtk_container_add (GTK_CONTAINER(window), aspect_frame);
7252     gtk_widget_show (aspect_frame);
7253    
7254     /* Now add a child widget to the aspect frame */
7255    
7256     drawing_area = gtk_drawing_area_new ();
7257    
7258     /* Ask for a 200x200 window, but the AspectFrame will give us a 200x100
7259      * window since we are forcing a 2x1 aspect ratio */
7260     gtk_widget_set_usize (drawing_area, 200, 200);
7261     gtk_container_add (GTK_CONTAINER(aspect_frame), drawing_area);
7262     gtk_widget_show (drawing_area);
7263    
7264     gtk_widget_show (window);
7265     gtk_main ();
7266     return 0;
7267 }
7268 <!-- example-end -->
7269 </programlisting>
7270
7271 </sect1>
7272
7273 <!-- ----------------------------------------------------------------- -->   
7274 <sect1 id="sec-PanedWindowWidgets">
7275 <title>Paned Window Widgets</title>
7276
7277 <para>The paned window widgets are useful when you want to divide an area
7278 into two parts, with the relative size of the two parts controlled by
7279 the user. A groove is drawn between the two portions with a handle
7280 that the user can drag to change the ratio. The division can either be
7281 horizontal (HPaned) or vertical (VPaned).</para>
7282    
7283 <para>To create a new paned window, call one of:</para>
7284
7285 <programlisting role="C">
7286 GtkWidget *gtk_hpaned_new (void);
7287
7288 GtkWidget *gtk_vpaned_new (void);
7289 </programlisting>
7290
7291 <para>After creating the paned window widget, you need to add child widgets
7292 to its two halves. To do this, use the functions:</para>
7293
7294 <programlisting role="C">
7295 void gtk_paned_add1 (GtkPaned *paned, GtkWidget *child);
7296
7297 void gtk_paned_add2 (GtkPaned *paned, GtkWidget *child);
7298 </programlisting>
7299
7300 <para><literal>gtk_paned_add1()</literal> adds the child widget to the left or top half of
7301 the paned window. <literal>gtk_paned_add2()</literal> adds the child widget to the
7302 right or bottom half of the paned window.</para>
7303
7304 <para>As an example, we will create part of the user interface of an
7305 imaginary email program. A window is divided into two portions
7306 vertically, with the top portion being a list of email messages and
7307 the bottom portion the text of the email message. Most of the program
7308 is pretty straightforward. A couple of points to note: text can't be
7309 added to a Text widget until it is realized. This could be done by
7310 calling <literal>gtk_widget_realize()</literal>, but as a demonstration of an
7311 alternate technique, we connect a handler to the "realize" signal to
7312 add the text. Also, we need to add the <literal>GTK_SHRINK</literal> option to some
7313 of the items in the table containing the text window and its
7314 scrollbars, so that when the bottom portion is made smaller, the
7315 correct portions shrink instead of being pushed off the bottom of the
7316 window.</para>
7317
7318 <programlisting role="C">
7319 <!-- example-start paned paned.c -->
7320
7321 #define GTK_ENABLE_BROKEN
7322 #include &lt;stdio.h&gt;
7323 #include &lt;gtk/gtk.h&gt;
7324    
7325 /* Create the list of "messages" */
7326 GtkWidget *create_list( void )
7327 {
7328
7329     GtkWidget *scrolled_window;
7330     GtkWidget *list;
7331     GtkWidget *list_item;
7332    
7333     int i;
7334     char buffer[16];
7335    
7336     /* Create a new scrolled window, with scrollbars only if needed */
7337     scrolled_window = gtk_scrolled_window_new (NULL, NULL);
7338     gtk_scrolled_window_set_policy (GTK_SCROLLED_WINDOW (scrolled_window),
7339                                     GTK_POLICY_AUTOMATIC, 
7340                                     GTK_POLICY_AUTOMATIC);
7341    
7342     /* Create a new list and put it in the scrolled window */
7343     list = gtk_list_new ();
7344     gtk_scrolled_window_add_with_viewport (
7345                GTK_SCROLLED_WINDOW (scrolled_window), list);
7346     gtk_widget_show (list);
7347    
7348     /* Add some messages to the window */
7349     for (i=0; i<10; i++) {
7350
7351         sprintf(buffer,"Message #%d",i);
7352         list_item = gtk_list_item_new_with_label (buffer);
7353         gtk_container_add (GTK_CONTAINER(list), list_item);
7354         gtk_widget_show (list_item);
7355
7356     }
7357    
7358     return scrolled_window;
7359 }
7360    
7361 /* Add some text to our text widget - this is a callback that is invoked
7362 when our window is realized. We could also force our window to be
7363 realized with gtk_widget_realize, but it would have to be part of
7364 a hierarchy first */
7365
7366 void realize_text( GtkWidget *text,
7367                    gpointer data )
7368 {
7369     gtk_text_freeze (GTK_TEXT (text));
7370     gtk_text_insert (GTK_TEXT (text), NULL, &amp;text->style->black, NULL,
7371     "From: pathfinder@nasa.gov\n"
7372     "To: mom@nasa.gov\n"
7373     "Subject: Made it!\n"
7374     "\n"
7375     "We just got in this morning. The weather has been\n"
7376     "great - clear but cold, and there are lots of fun sights.\n"
7377     "Sojourner says hi. See you soon.\n"
7378     " -Path\n", -1);
7379    
7380     gtk_text_thaw (GTK_TEXT (text));
7381 }
7382    
7383 /* Create a scrolled text area that displays a "message" */
7384 GtkWidget *create_text( void )
7385 {
7386     GtkWidget *table;
7387     GtkWidget *text;
7388     GtkWidget *hscrollbar;
7389     GtkWidget *vscrollbar;
7390    
7391     /* Create a table to hold the text widget and scrollbars */
7392     table = gtk_table_new (2, 2, FALSE);
7393    
7394     /* Put a text widget in the upper left hand corner. Note the use of
7395      * GTK_SHRINK in the y direction */
7396     text = gtk_text_new (NULL, NULL);
7397     gtk_table_attach (GTK_TABLE (table), text, 0, 1, 0, 1,
7398                       GTK_FILL | GTK_EXPAND,
7399                       GTK_FILL | GTK_EXPAND | GTK_SHRINK, 0, 0);
7400     gtk_widget_show (text);
7401    
7402     /* Put a HScrollbar in the lower left hand corner */
7403     hscrollbar = gtk_hscrollbar_new (GTK_TEXT (text)->hadj);
7404     gtk_table_attach (GTK_TABLE (table), hscrollbar, 0, 1, 1, 2,
7405                       GTK_EXPAND | GTK_FILL, GTK_FILL, 0, 0);
7406     gtk_widget_show (hscrollbar);
7407    
7408     /* And a VScrollbar in the upper right */
7409     vscrollbar = gtk_vscrollbar_new (GTK_TEXT (text)->vadj);
7410     gtk_table_attach (GTK_TABLE (table), vscrollbar, 1, 2, 0, 1,
7411                       GTK_FILL, GTK_EXPAND | GTK_FILL | GTK_SHRINK, 0, 0);
7412     gtk_widget_show (vscrollbar);
7413    
7414     /* Add a handler to put a message in the text widget when it is realized */
7415     gtk_signal_connect (GTK_OBJECT (text), "realize",
7416                         GTK_SIGNAL_FUNC (realize_text), NULL);
7417    
7418     return table;
7419 }
7420    
7421 int main( int   argc,
7422           char *argv[] )
7423 {
7424     GtkWidget *window;
7425     GtkWidget *vpaned;
7426     GtkWidget *list;
7427     GtkWidget *text;
7428
7429     gtk_init (&amp;argc, &amp;argv);
7430    
7431     window = gtk_window_new (GTK_WINDOW_TOPLEVEL);
7432     gtk_window_set_title (GTK_WINDOW (window), "Paned Windows");
7433     gtk_signal_connect (GTK_OBJECT (window), "destroy",
7434                         GTK_SIGNAL_FUNC (gtk_main_quit), NULL);
7435     gtk_container_set_border_width (GTK_CONTAINER (window), 10);
7436     gtk_widget_set_usize (GTK_WIDGET(window), 450, 400);
7437
7438     /* create a vpaned widget and add it to our toplevel window */
7439    
7440     vpaned = gtk_vpaned_new ();
7441     gtk_container_add (GTK_CONTAINER(window), vpaned);
7442     gtk_widget_show (vpaned);
7443    
7444     /* Now create the contents of the two halves of the window */
7445    
7446     list = create_list ();
7447     gtk_paned_add1 (GTK_PANED(vpaned), list);
7448     gtk_widget_show (list);
7449    
7450     text = create_text ();
7451     gtk_paned_add2 (GTK_PANED(vpaned), text);
7452     gtk_widget_show (text);
7453     gtk_widget_show (window);
7454     gtk_main ();
7455     return 0;
7456 }
7457 <!-- example-end -->
7458 </programlisting>
7459
7460 </sect1>
7461
7462 <!-- ----------------------------------------------------------------- -->
7463 <sect1 id="sec-Viewports">
7464 <title>Viewports</title>
7465
7466 <para>It is unlikely that you will ever need to use the Viewport widget
7467 directly. You are much more likely to use the
7468 <link linkend="sec-ScrolledWindows">Scrolled Window</link> widget which
7469 itself uses the Viewport.</para>
7470
7471 <para>A viewport widget allows you to place a larger widget within it such
7472 that you can view a part of it at a time. It uses
7473 <link linkend="ch-Adjustments">Adjustments</link> to define the area that
7474 is currently in view.</para>
7475
7476 <para>A Viewport is created with the function</para>
7477
7478 <programlisting role="C">
7479 GtkWidget *gtk_viewport_new( GtkAdjustment *hadjustment,
7480                              GtkAdjustment *vadjustment );
7481 </programlisting>
7482
7483 <para>As you can see you can specify the horizontal and vertical Adjustments
7484 that the widget is to use when you create the widget. It will create
7485 its own if you pass NULL as the value of the arguments.</para>
7486
7487 <para>You can get and set the adjustments after the widget has been created
7488 using the following four functions:</para>
7489
7490 <programlisting role="C">
7491 GtkAdjustment *gtk_viewport_get_hadjustment (GtkViewport *viewport );
7492
7493 GtkAdjustment *gtk_viewport_get_vadjustment (GtkViewport *viewport );
7494
7495 void gtk_viewport_set_hadjustment( GtkViewport   *viewport,
7496                                    GtkAdjustment *adjustment );
7497
7498 void gtk_viewport_set_vadjustment( GtkViewport   *viewport,
7499                                    GtkAdjustment *adjustment );
7500 </programlisting>
7501
7502 <para>The only other viewport function is used to alter its appearance:</para>
7503
7504 <programlisting role="C">
7505 void gtk_viewport_set_shadow_type( GtkViewport   *viewport,
7506                                    GtkShadowType  type );
7507 </programlisting>
7508
7509 <para>Possible values for the <literal>type</literal> parameter are:</para>
7510 <programlisting role="C">
7511   GTK_SHADOW_NONE,
7512   GTK_SHADOW_IN,
7513   GTK_SHADOW_OUT,
7514   GTK_SHADOW_ETCHED_IN,
7515   GTK_SHADOW_ETCHED_OUT
7516 </programlisting>
7517  
7518 </sect1>
7519
7520 <!-- ----------------------------------------------------------------- -->
7521 <sect1 id="sec-ScrolledWindows"
7522 <title>Scrolled Windows</title>
7523
7524 <para>Scrolled windows are used to create a scrollable area with another
7525 widget inside it. You may insert any type of widget into a scrolled
7526 window, and it will be accessible regardless of the size by using the
7527 scrollbars.</para>
7528
7529 <para>The following function is used to create a new scrolled window.</para>
7530
7531 <programlisting role="C">
7532 GtkWidget *gtk_scrolled_window_new( GtkAdjustment *hadjustment,
7533                                     GtkAdjustment *vadjustment );
7534 </programlisting>
7535
7536 <para>Where the first argument is the adjustment for the horizontal
7537 direction, and the second, the adjustment for the vertical direction.
7538 These are almost always set to NULL.</para>
7539
7540 <programlisting role="C">
7541 void gtk_scrolled_window_set_policy( GtkScrolledWindow *scrolled_window,
7542                                      GtkPolicyType      hscrollbar_policy,
7543                                      GtkPolicyType      vscrollbar_policy );
7544 </programlisting>
7545
7546 <para>This sets the policy to be used with respect to the scrollbars.
7547 The first argument is the scrolled window you wish to change. The second
7548 sets the policy for the horizontal scrollbar, and the third the policy for 
7549 the vertical scrollbar.</para>
7550
7551 <para>The policy may be one of <literal>GTK_POLICY_AUTOMATIC</literal> or
7552 <literal>GTK_POLICY_ALWAYS</literal>. <literal>GTK_POLICY_AUTOMATIC</literal> will automatically
7553 decide whether you need scrollbars, whereas <literal>GTK_POLICY_ALWAYS</literal>
7554 will always leave the scrollbars there.</para>
7555
7556 <para>You can then place your object into the scrolled window using the
7557 following function.</para>
7558
7559 <programlisting role="C">
7560 void gtk_scrolled_window_add_with_viewport( GtkScrolledWindow *scrolled_window,
7561                                             GtkWidget         *child);
7562 </programlisting>
7563
7564 <para>Here is a simple example that packs a table eith 100 toggle buttons
7565 into a scrolled window. I've only commented on the parts that may be
7566 new to you.</para>
7567
7568 <programlisting role="C">
7569 <!-- example-start scrolledwin scrolledwin.c -->
7570
7571 #include &lt;stdio.h&gt;
7572 #include &lt;gtk/gtk.h&gt;
7573
7574 void destroy( GtkWidget *widget,
7575               gpointer   data )
7576 {
7577     gtk_main_quit();
7578 }
7579
7580 int main( int   argc,
7581           char *argv[] )
7582 {
7583     static GtkWidget *window;
7584     GtkWidget *scrolled_window;
7585     GtkWidget *table;
7586     GtkWidget *button;
7587     char buffer[32];
7588     int i, j;
7589     
7590     gtk_init (&amp;argc, &amp;argv);
7591     
7592     /* Create a new dialog window for the scrolled window to be
7593      * packed into.  */
7594     window = gtk_dialog_new ();
7595     gtk_signal_connect (GTK_OBJECT (window), "destroy",
7596                         (GtkSignalFunc) destroy, NULL);
7597     gtk_window_set_title (GTK_WINDOW (window), "GtkScrolledWindow example");
7598     gtk_container_set_border_width (GTK_CONTAINER (window), 0);
7599     gtk_widget_set_usize(window, 300, 300);
7600     
7601     /* create a new scrolled window. */
7602     scrolled_window = gtk_scrolled_window_new (NULL, NULL);
7603     
7604     gtk_container_set_border_width (GTK_CONTAINER (scrolled_window), 10);
7605     
7606     /* the policy is one of GTK_POLICY AUTOMATIC, or GTK_POLICY_ALWAYS.
7607      * GTK_POLICY_AUTOMATIC will automatically decide whether you need
7608      * scrollbars, whereas GTK_POLICY_ALWAYS will always leave the scrollbars
7609      * there.  The first one is the horizontal scrollbar, the second, 
7610      * the vertical. */
7611     gtk_scrolled_window_set_policy (GTK_SCROLLED_WINDOW (scrolled_window),
7612                                     GTK_POLICY_AUTOMATIC, GTK_POLICY_ALWAYS);
7613     /* The dialog window is created with a vbox packed into it. */                                                              
7614     gtk_box_pack_start (GTK_BOX (GTK_DIALOG(window)->vbox), scrolled_window, 
7615                         TRUE, TRUE, 0);
7616     gtk_widget_show (scrolled_window);
7617     
7618     /* create a table of 10 by 10 squares. */
7619     table = gtk_table_new (10, 10, FALSE);
7620     
7621     /* set the spacing to 10 on x and 10 on y */
7622     gtk_table_set_row_spacings (GTK_TABLE (table), 10);
7623     gtk_table_set_col_spacings (GTK_TABLE (table), 10);
7624     
7625     /* pack the table into the scrolled window */
7626     gtk_scrolled_window_add_with_viewport (
7627                    GTK_SCROLLED_WINDOW (scrolled_window), table);
7628     gtk_widget_show (table);
7629     
7630     /* this simply creates a grid of toggle buttons on the table
7631      * to demonstrate the scrolled window. */
7632     for (i = 0; i < 10; i++)
7633        for (j = 0; j < 10; j++) {
7634           sprintf (buffer, "button (%d,%d)\n", i, j);
7635           button = gtk_toggle_button_new_with_label (buffer);
7636           gtk_table_attach_defaults (GTK_TABLE (table), button,
7637                                      i, i+1, j, j+1);
7638           gtk_widget_show (button);
7639        }
7640     
7641     /* Add a "close" button to the bottom of the dialog */
7642     button = gtk_button_new_with_label ("close");
7643     gtk_signal_connect_object (GTK_OBJECT (button), "clicked",
7644                                (GtkSignalFunc) gtk_widget_destroy,
7645                                GTK_OBJECT (window));
7646     
7647     /* this makes it so the button is the default. */
7648     
7649     GTK_WIDGET_SET_FLAGS (button, GTK_CAN_DEFAULT);
7650     gtk_box_pack_start (GTK_BOX (GTK_DIALOG (window)->action_area), button, TRUE, TRUE, 0);
7651     
7652     /* This grabs this button to be the default button. Simply hitting
7653      * the "Enter" key will cause this button to activate. */
7654     gtk_widget_grab_default (button);
7655     gtk_widget_show (button);
7656     
7657     gtk_widget_show (window);
7658     
7659     gtk_main();
7660     
7661     return(0);
7662 }
7663 <!-- example-end -->
7664 </programlisting>
7665
7666 <para>Try playing with resizing the window. You'll notice how the scrollbars
7667 react. You may also wish to use the gtk_widget_set_usize() call to set
7668 the default size of the window or other widgets.</para>
7669
7670 </sect1>
7671
7672 <!-- ----------------------------------------------------------------- -->   
7673 <sect1 id="sec-ButtonBoxes">
7674 <title>Button Boxes</title>
7675
7676 <para>Button Boxes are a convenient way to quickly layout a group of
7677 buttons. They come in both horizontal and vertical flavours. You
7678 create a new Button Box with one of the following calls, which create
7679 a horizontal or vertical box, respectively:</para>
7680
7681 <programlisting role="C">
7682 GtkWidget *gtk_hbutton_box_new( void );
7683
7684 GtkWidget *gtk_vbutton_box_new( void );
7685 </programlisting>
7686
7687 <para>The only attributes pertaining to button boxes effect how the buttons
7688 are laid out. You can change the spacing between the buttons with:</para>
7689
7690 <programlisting role="C">
7691 void gtk_hbutton_box_set_spacing_default( gint spacing );
7692
7693 void gtk_vbutton_box_set_spacing_default( gint spacing );
7694 </programlisting>
7695
7696 <para>Similarly, the current spacing values can be queried using:</para>
7697
7698 <programlisting role="C">
7699 gint gtk_hbutton_box_get_spacing_default( void );
7700
7701 gint gtk_vbutton_box_get_spacing_default( void );
7702 </programlisting>
7703
7704 <para>The second attribute that we can access effects the layout of the
7705 buttons within the box. It is set using one of:</para>
7706
7707 <programlisting role="C">
7708 void gtk_hbutton_box_set_layout_default( GtkButtonBoxStyle layout );
7709
7710 void gtk_vbutton_box_set_layout_default( GtkButtonBoxStyle layout );
7711 </programlisting>
7712
7713 <para>The <literal>layout</literal> argument can take one of the following values:</para>
7714
7715 <programlisting role="C">
7716   GTK_BUTTONBOX_DEFAULT_STYLE
7717   GTK_BUTTONBOX_SPREAD
7718   GTK_BUTTONBOX_EDGE
7719   GTK_BUTTONBOX_START
7720   GTK_BUTTONBOX_END
7721 </programlisting>
7722
7723 <para>The current layout setting can be retrieved using:</para>
7724
7725 <programlisting role="C">
7726 GtkButtonBoxStyle gtk_hbutton_box_get_layout_default( void );
7727
7728 GtkButtonBoxStyle gtk_vbutton_box_get_layout_default( void );
7729 </programlisting>
7730
7731 <para>Buttons are added to a Button Box using the usual function:</para>
7732
7733 <programlisting role="C">
7734     gtk_container_add( GTK_CONTAINER(button_box), child_widget );
7735 </programlisting>
7736
7737 <para>Here's an example that illustrates all the different layout settings
7738 for Button Boxes.</para>
7739
7740 <programlisting role="C">
7741 <!-- example-start buttonbox buttonbox.c -->
7742
7743 #include &lt;gtk/gtk.h&gt;
7744
7745 /* Create a Button Box with the specified parameters */
7746 GtkWidget *create_bbox( gint  horizontal,
7747                         char *title,
7748                         gint  spacing,
7749                         gint  child_w,
7750                         gint  child_h,
7751                         gint  layout )
7752 {
7753   GtkWidget *frame;
7754   GtkWidget *bbox;
7755   GtkWidget *button;
7756
7757   frame = gtk_frame_new (title);
7758
7759   if (horizontal)
7760     bbox = gtk_hbutton_box_new ();
7761   else
7762     bbox = gtk_vbutton_box_new ();
7763
7764   gtk_container_set_border_width (GTK_CONTAINER (bbox), 5);
7765   gtk_container_add (GTK_CONTAINER (frame), bbox);
7766
7767   /* Set the appearance of the Button Box */
7768   gtk_button_box_set_layout (GTK_BUTTON_BOX (bbox), layout);
7769   gtk_button_box_set_spacing (GTK_BUTTON_BOX (bbox), spacing);
7770   gtk_button_box_set_child_size (GTK_BUTTON_BOX (bbox), child_w, child_h);
7771
7772   button = gtk_button_new_with_label ("OK");
7773   gtk_container_add (GTK_CONTAINER (bbox), button);
7774
7775   button = gtk_button_new_with_label ("Cancel");
7776   gtk_container_add (GTK_CONTAINER (bbox), button);
7777
7778   button = gtk_button_new_with_label ("Help");
7779   gtk_container_add (GTK_CONTAINER (bbox), button);
7780
7781   return(frame);
7782 }
7783
7784 int main( int   argc,
7785           char *argv[] )
7786 {
7787   static GtkWidget* window = NULL;
7788   GtkWidget *main_vbox;
7789   GtkWidget *vbox;
7790   GtkWidget *hbox;
7791   GtkWidget *frame_horz;
7792   GtkWidget *frame_vert;
7793
7794   /* Initialize GTK */
7795   gtk_init( &amp;argc, &amp;argv );
7796
7797   window = gtk_window_new (GTK_WINDOW_TOPLEVEL);
7798   gtk_window_set_title (GTK_WINDOW (window), "Button Boxes");
7799
7800   gtk_signal_connect (GTK_OBJECT (window), "destroy",
7801                       GTK_SIGNAL_FUNC(gtk_main_quit),
7802                       NULL);
7803
7804   gtk_container_set_border_width (GTK_CONTAINER (window), 10);
7805
7806   main_vbox = gtk_vbox_new (FALSE, 0);
7807   gtk_container_add (GTK_CONTAINER (window), main_vbox);
7808
7809   frame_horz = gtk_frame_new ("Horizontal Button Boxes");
7810   gtk_box_pack_start (GTK_BOX (main_vbox), frame_horz, TRUE, TRUE, 10);
7811
7812   vbox = gtk_vbox_new (FALSE, 0);
7813   gtk_container_set_border_width (GTK_CONTAINER (vbox), 10);
7814   gtk_container_add (GTK_CONTAINER (frame_horz), vbox);
7815
7816   gtk_box_pack_start (GTK_BOX (vbox),
7817            create_bbox (TRUE, "Spread (spacing 40)", 40, 85, 20, GTK_BUTTONBOX_SPREAD),
7818                       TRUE, TRUE, 0);
7819
7820   gtk_box_pack_start (GTK_BOX (vbox),
7821            create_bbox (TRUE, "Edge (spacing 30)", 30, 85, 20, GTK_BUTTONBOX_EDGE),
7822                       TRUE, TRUE, 5);
7823
7824   gtk_box_pack_start (GTK_BOX (vbox),
7825            create_bbox (TRUE, "Start (spacing 20)", 20, 85, 20, GTK_BUTTONBOX_START),
7826                       TRUE, TRUE, 5);
7827
7828   gtk_box_pack_start (GTK_BOX (vbox),
7829            create_bbox (TRUE, "End (spacing 10)", 10, 85, 20, GTK_BUTTONBOX_END),
7830                       TRUE, TRUE, 5);
7831
7832   frame_vert = gtk_frame_new ("Vertical Button Boxes");
7833   gtk_box_pack_start (GTK_BOX (main_vbox), frame_vert, TRUE, TRUE, 10);
7834
7835   hbox = gtk_hbox_new (FALSE, 0);
7836   gtk_container_set_border_width (GTK_CONTAINER (hbox), 10);
7837   gtk_container_add (GTK_CONTAINER (frame_vert), hbox);
7838
7839   gtk_box_pack_start (GTK_BOX (hbox),
7840            create_bbox (FALSE, "Spread (spacing 5)", 5, 85, 20, GTK_BUTTONBOX_SPREAD),
7841                       TRUE, TRUE, 0);
7842
7843   gtk_box_pack_start (GTK_BOX (hbox),
7844            create_bbox (FALSE, "Edge (spacing 30)", 30, 85, 20, GTK_BUTTONBOX_EDGE),
7845                       TRUE, TRUE, 5);
7846
7847   gtk_box_pack_start (GTK_BOX (hbox),
7848            create_bbox (FALSE, "Start (spacing 20)", 20, 85, 20, GTK_BUTTONBOX_START),
7849                       TRUE, TRUE, 5);
7850
7851   gtk_box_pack_start (GTK_BOX (hbox),
7852            create_bbox (FALSE, "End (spacing 20)", 20, 85, 20, GTK_BUTTONBOX_END),
7853                       TRUE, TRUE, 5);
7854
7855   gtk_widget_show_all (window);
7856
7857   /* Enter the event loop */
7858   gtk_main ();
7859     
7860   return(0);
7861 }
7862 <!-- example-end -->
7863 </programlisting>
7864
7865 </sect1>
7866
7867 <!-- ----------------------------------------------------------------- -->   
7868 <sect1 id="sec-Toolbar">
7869 <title>Toolbar</title>
7870
7871 <para>Toolbars are usually used to group some number of widgets in order to
7872 simplify customization of their look and layout. Typically a toolbar
7873 consists of buttons with icons, labels and tooltips, but any other
7874 widget can also be put inside a toolbar. Finally, items can be
7875 arranged horizontally or vertically and buttons can be displayed with
7876 icons, labels, or both.</para>
7877
7878 <para>Creating a toolbar is (as one may already suspect) done with the
7879 following function:</para>
7880
7881 <programlisting role="C">
7882 GtkWidget *gtk_toolbar_new( GtkOrientation orientation,
7883                             GtkToolbarStyle  style );
7884 </programlisting>
7885
7886 <para>where orientation may be one of:</para>
7887
7888 <programlisting role="C">
7889   GTK_ORIENTATION_HORIZONTAL    
7890   GTK_ORIENTATION_VERTICAL
7891 </programlisting>
7892
7893 <para>and style one of:</para>
7894
7895 <programlisting role="C">
7896   GTK_TOOLBAR_TEXT
7897   GTK_TOOLBAR_ICONS
7898   GTK_TOOLBAR_BOTH
7899 </programlisting>
7900
7901 <para>The style applies to all the buttons created with the `item' functions
7902 (not to buttons inserted into toolbar as separate widgets).</para>
7903
7904 <para>After creating a toolbar one can append, prepend and insert items
7905 (that means simple text strings) or elements (that means any widget
7906 types) into the toolbar. To describe an item we need a label text, a
7907 tooltip text, a private tooltip text, an icon for the button and a
7908 callback function for it. For example, to append or prepend an item
7909 you may use the following functions:</para>
7910
7911 <programlisting role="C">
7912 GtkWidget *gtk_toolbar_append_item( GtkToolbar    *toolbar,
7913                                     const char    *text,
7914                                     const char    *tooltip_text,
7915                                     const char    *tooltip_private_text,
7916                                     GtkWidget     *icon,
7917                                     GtkSignalFunc  callback,
7918                                     gpointer       user_data );
7919
7920 GtkWidget *gtk_toolbar_prepend_item( GtkToolbar    *toolbar,
7921                                      const char    *text,
7922                                      const char    *tooltip_text,
7923                                      const char    *tooltip_private_text,
7924                                      GtkWidget     *icon,
7925                                      GtkSignalFunc  callback,
7926                                      gpointer       user_data );
7927 </programlisting>
7928
7929 <para>If you want to use gtk_toolbar_insert_item, the only additional
7930 parameter which must be specified is the position in which the item
7931 should be inserted, thus:</para>
7932
7933 <programlisting role="C">
7934 GtkWidget *gtk_toolbar_insert_item( GtkToolbar    *toolbar,
7935                                     const char    *text,
7936                                     const char    *tooltip_text,
7937                                     const char    *tooltip_private_text,
7938                                     GtkWidget     *icon,
7939                                     GtkSignalFunc  callback,
7940                                     gpointer       user_data,
7941                                     gint           position );
7942 </programlisting>
7943
7944 <para>To simplify adding spaces between toolbar items, you may use the
7945 following functions:</para>
7946
7947 <programlisting role="C">
7948 void gtk_toolbar_append_space( GtkToolbar *toolbar );
7949
7950 void gtk_toolbar_prepend_space( GtkToolbar *toolbar );
7951
7952 void gtk_toolbar_insert_space( GtkToolbar *toolbar,
7953                                gint        position );
7954 </programlisting>
7955
7956 <para>While the size of the added space can be set globally for a
7957 whole toolbar with the function:</para>
7958
7959 <programlisting role="C">
7960 void gtk_toolbar_set_space_size( GtkToolbar *toolbar,
7961                                  gint        space_size) ;
7962 </programlisting>
7963
7964 <para>If it's required, the orientation of a toolbar and its style can be
7965 changed "on the fly" using the following functions:</para>
7966
7967 <programlisting role="C">
7968 void gtk_toolbar_set_orientation( GtkToolbar     *toolbar,
7969                                   GtkOrientation  orientation );
7970
7971 void gtk_toolbar_set_style( GtkToolbar      *toolbar,
7972                             GtkToolbarStyle  style );
7973
7974 void gtk_toolbar_set_tooltips( GtkToolbar *toolbar,
7975                                gint        enable );
7976 </programlisting>
7977
7978 <para>Where <literal>orientation</literal> is one of <literal>GTK_ORIENTATION_HORIZONTAL</literal> or
7979 <literal>GTK_ORIENTATION_VERTICAL</literal>. The <literal>style</literal> is used to set
7980 appearance of the toolbar items by using one of
7981 <literal>GTK_TOOLBAR_ICONS</literal>, <literal>GTK_TOOLBAR_TEXT</literal>, or
7982 <literal>GTK_TOOLBAR_BOTH</literal>.</para>
7983
7984 <para>To show some other things that can be done with a toolbar, let's take
7985 the following program (we'll interrupt the listing with some
7986 additional explanations):</para>
7987
7988 <programlisting role="C">
7989 #include &lt;gtk/gtk.h&gt;
7990
7991 #include "gtk.xpm"
7992
7993 /* This function is connected to the Close button or
7994  * closing the window from the WM */
7995 gint delete_event (GtkWidget *widget, GdkEvent *event, gpointer data)
7996 {
7997   gtk_main_quit ();
7998   return(FALSE);
7999 }
8000 </programlisting>
8001
8002 <para>The above beginning seems for sure familiar to you if it's not your first
8003 GTK program. There is one additional thing though, we include a nice XPM
8004 picture to serve as an icon for all of the buttons.</para>
8005
8006 <programlisting role="C">
8007 GtkWidget* close_button; /* This button will emit signal to close
8008                           * application */
8009 GtkWidget* tooltips_button; /* to enable/disable tooltips */
8010 GtkWidget* text_button,
8011          * icon_button,
8012          * both_button; /* radio buttons for toolbar style */
8013 GtkWidget* entry; /* a text entry to show packing any widget into
8014                    * toolbar */
8015 </programlisting>
8016
8017 <para>In fact not all of the above widgets are needed here, but to make things
8018 clearer I put them all together.</para>
8019
8020 <programlisting role="C">
8021 /* that's easy... when one of the buttons is toggled, we just
8022  * check which one is active and set the style of the toolbar
8023  * accordingly
8024  * ATTENTION: our toolbar is passed as data to callback ! */
8025 void radio_event (GtkWidget *widget, gpointer data)
8026 {
8027   if (GTK_TOGGLE_BUTTON (text_button)->active) 
8028     gtk_toolbar_set_style(GTK_TOOLBAR ( data ), GTK_TOOLBAR_TEXT);
8029   else if (GTK_TOGGLE_BUTTON (icon_button)->active)
8030     gtk_toolbar_set_style(GTK_TOOLBAR ( data ), GTK_TOOLBAR_ICONS);
8031   else if (GTK_TOGGLE_BUTTON (both_button)->active)
8032     gtk_toolbar_set_style(GTK_TOOLBAR ( data ), GTK_TOOLBAR_BOTH);
8033 }
8034
8035 /* even easier, just check given toggle button and enable/disable 
8036  * tooltips */
8037 void toggle_event (GtkWidget *widget, gpointer data)
8038 {
8039   gtk_toolbar_set_tooltips (GTK_TOOLBAR ( data ),
8040                             GTK_TOGGLE_BUTTON (widget)->active );
8041 }
8042 </programlisting>
8043
8044 <para>The above are just two callback functions that will be called when
8045 one of the buttons on a toolbar is pressed. You should already be
8046 familiar with things like this if you've already used toggle buttons (and
8047 radio buttons).</para>
8048
8049 <programlisting role="C">
8050 int main (int argc, char *argv[])
8051 {
8052   /* Here is our main window (a dialog) and a handle for the handlebox */
8053   GtkWidget* dialog;
8054   GtkWidget* handlebox;
8055
8056   /* Ok, we need a toolbar, an icon with a mask (one for all of 
8057      the buttons) and an icon widget to put this icon in (but 
8058      we'll create a separate widget for each button) */
8059   GtkWidget * toolbar;
8060   GdkPixmap * icon;
8061   GdkBitmap * mask;
8062   GtkWidget * iconw;
8063
8064   /* this is called in all GTK application. */
8065   gtk_init (&amp;argc, &amp;argv);
8066   
8067   /* create a new window with a given title, and nice size */
8068   dialog = gtk_dialog_new ();
8069   gtk_window_set_title ( GTK_WINDOW ( dialog ) , "GTKToolbar Tutorial");
8070   gtk_widget_set_usize( GTK_WIDGET ( dialog ) , 600 , 300 );
8071   GTK_WINDOW ( dialog ) ->allow_shrink = TRUE;
8072
8073   /* typically we quit if someone tries to close us */
8074   gtk_signal_connect ( GTK_OBJECT ( dialog ), "delete_event",
8075                        GTK_SIGNAL_FUNC ( delete_event ), NULL);
8076
8077   /* we need to realize the window because we use pixmaps for 
8078    * items on the toolbar in the context of it */
8079   gtk_widget_realize ( dialog );
8080
8081   /* to make it nice we'll put the toolbar into the handle box, 
8082    * so that it can be detached from the main window */
8083   handlebox = gtk_handle_box_new ();
8084   gtk_box_pack_start ( GTK_BOX ( GTK_DIALOG(dialog)->vbox ),
8085                        handlebox, FALSE, FALSE, 5 );
8086 </programlisting>
8087
8088 <para>The above should be similar to any other GTK application. Just
8089 initialization of GTK, creating the window, etc. There is only one
8090 thing that probably needs some explanation: a handle box. A handle box
8091 is just another box that can be used to pack widgets in to. The
8092 difference between it and typical boxes is that it can be detached
8093 from a parent window (or, in fact, the handle box remains in the
8094 parent, but it is reduced to a very small rectangle, while all of its
8095 contents are reparented to a new freely floating window). It is
8096 usually nice to have a detachable toolbar, so these two widgets occur
8097 together quite often.</para>
8098
8099 <programlisting role="C">
8100   /* toolbar will be horizontal, with both icons and text, and
8101    * with 5pxl spaces between items and finally, 
8102    * we'll also put it into our handlebox */
8103   toolbar = gtk_toolbar_new ( GTK_ORIENTATION_HORIZONTAL,
8104                               GTK_TOOLBAR_BOTH );
8105   gtk_container_set_border_width ( GTK_CONTAINER ( toolbar ) , 5 );
8106   gtk_toolbar_set_space_size ( GTK_TOOLBAR ( toolbar ), 5 );
8107   gtk_container_add ( GTK_CONTAINER ( handlebox ) , toolbar );
8108
8109   /* now we create icon with mask: we'll reuse it to create
8110    * icon widgets for toolbar items */
8111   icon = gdk_pixmap_create_from_xpm_d ( dialog->window, &amp;mask,
8112       &amp;dialog->style->white, gtk_xpm );
8113 </programlisting>
8114
8115 <para>Well, what we do above is just a straightforward initialization of
8116 the toolbar widget and creation of a GDK pixmap with its mask. If you
8117 want to know something more about using pixmaps, refer to GDK
8118 documentation or to the <link linkend="sec-Pixmaps">Pixmaps</link> section
8119 earlier in this tutorial.</para>
8120
8121 <programlisting role="C">
8122   /* our first item is &lt;close&gt; button */
8123   iconw = gtk_pixmap_new ( icon, mask ); /* icon widget */
8124   close_button = 
8125     gtk_toolbar_append_item ( GTK_TOOLBAR (toolbar), /* our toolbar */
8126                               "Close",               /* button label */
8127                               "Closes this app",     /* this button's tooltip */
8128                               "Private",             /* tooltip private info */
8129                               iconw,                 /* icon widget */
8130                               GTK_SIGNAL_FUNC (delete_event), /* a signal */
8131                                NULL );
8132   gtk_toolbar_append_space ( GTK_TOOLBAR ( toolbar ) ); /* space after item */
8133 </programlisting>
8134
8135 <para>In the above code you see the simplest case: adding a button to
8136 toolbar.  Just before appending a new item, we have to construct a
8137 pixmap widget to serve as an icon for this item; this step will have
8138 to be repeated for each new item. Just after the item we also add a
8139 space, so the following items will not touch each other. As you see
8140 gtk_toolbar_append_item returns a pointer to our newly created button
8141 widget, so that we can work with it in the normal way.</para>
8142
8143 <programlisting role="C">
8144   /* now, let's make our radio buttons group... */
8145   iconw = gtk_pixmap_new ( icon, mask );
8146   icon_button = gtk_toolbar_append_element(
8147                     GTK_TOOLBAR(toolbar),
8148                     GTK_TOOLBAR_CHILD_RADIOBUTTON, /* a type of element */
8149                     NULL,                          /* pointer to widget */
8150                     "Icon",                        /* label */
8151                     "Only icons in toolbar",       /* tooltip */
8152                     "Private",                     /* tooltip private string */
8153                     iconw,                         /* icon */
8154                     GTK_SIGNAL_FUNC (radio_event), /* signal */
8155                     toolbar);                      /* data for signal */
8156   gtk_toolbar_append_space ( GTK_TOOLBAR ( toolbar ) );
8157 </programlisting>
8158
8159 <para>Here we begin creating a radio buttons group. To do this we use
8160 gtk_toolbar_append_element.  In fact, using this function one can also
8161 +add simple items or even spaces (type = <literal>GTK_TOOLBAR_CHILD_SPACE</literal>
8162 or +<literal>GTK_TOOLBAR_CHILD_BUTTON</literal>). In the above case we start
8163 creating a radio group. In creating other radio buttons for this group
8164 a pointer to the previous button in the group is required, so that a
8165 list of buttons can be easily constructed (see the section on <link
8166 linkend="sec-RadioButtons"> Radio Buttons </link> earlier in this
8167 tutorial).</para>
8168
8169 <programlisting role="C">
8170   /* following radio buttons refer to previous ones */
8171   iconw = gtk_pixmap_new ( icon, mask );
8172   text_button = 
8173     gtk_toolbar_append_element(GTK_TOOLBAR(toolbar),
8174                                GTK_TOOLBAR_CHILD_RADIOBUTTON,
8175                                icon_button,
8176                                "Text",
8177                                "Only texts in toolbar",
8178                                "Private",
8179                                iconw,
8180                                GTK_SIGNAL_FUNC (radio_event),
8181                                toolbar);
8182   gtk_toolbar_append_space ( GTK_TOOLBAR ( toolbar ) );
8183                                           
8184   iconw = gtk_pixmap_new ( icon, mask );
8185   both_button = 
8186     gtk_toolbar_append_element(GTK_TOOLBAR(toolbar),
8187                                GTK_TOOLBAR_CHILD_RADIOBUTTON,
8188                                text_button,
8189                                "Both",
8190                                "Icons and text in toolbar",
8191                                "Private",
8192                                iconw,
8193                                GTK_SIGNAL_FUNC (radio_event),
8194                                toolbar);
8195   gtk_toolbar_append_space ( GTK_TOOLBAR ( toolbar ) );
8196   gtk_toggle_button_set_active(GTK_TOGGLE_BUTTON(both_button),TRUE);
8197 </programlisting>
8198
8199 <para>In the end we have to set the state of one of the buttons manually
8200 (otherwise they all stay in active state, preventing us from switching
8201 between them).</para>
8202
8203 <programlisting role="C">
8204   /* here we have just a simple toggle button */
8205   iconw = gtk_pixmap_new ( icon, mask );
8206   tooltips_button = 
8207     gtk_toolbar_append_element(GTK_TOOLBAR(toolbar),
8208                                GTK_TOOLBAR_CHILD_TOGGLEBUTTON,
8209                                NULL,
8210                                "Tooltips",
8211                                "Toolbar with or without tips",
8212                                "Private",
8213                                iconw,
8214                                GTK_SIGNAL_FUNC (toggle_event),
8215                                toolbar);
8216   gtk_toolbar_append_space ( GTK_TOOLBAR ( toolbar ) );
8217   gtk_toggle_button_set_active(GTK_TOGGLE_BUTTON(tooltips_button),TRUE);
8218 </programlisting>
8219
8220 <para>A toggle button can be created in the obvious way (if one knows how to create
8221 radio buttons already).</para>
8222
8223 <programlisting role="C">
8224   /* to pack a widget into toolbar, we only have to 
8225    * create it and append it with an appropriate tooltip */
8226   entry = gtk_entry_new ();
8227   gtk_toolbar_append_widget( GTK_TOOLBAR (toolbar), 
8228                              entry, 
8229                              "This is just an entry", 
8230                              "Private" );
8231
8232   /* well, it isn't created within thetoolbar, so we must still show it */
8233   gtk_widget_show ( entry );
8234 </programlisting>
8235
8236 <para>As you see, adding any kind of widget to a toolbar is simple. The
8237 one thing you have to remember is that this widget must be shown manually
8238 (contrary to other items which will be shown together with the toolbar).</para>
8239
8240 <programlisting role="C">
8241   /* that's it ! let's show everything. */
8242   gtk_widget_show ( toolbar );
8243   gtk_widget_show (handlebox);
8244   gtk_widget_show ( dialog );
8245
8246   /* rest in gtk_main and wait for the fun to begin! */
8247   gtk_main ();
8248   
8249   return 0;
8250 }
8251 </programlisting>
8252
8253 <para>So, here we are at the end of toolbar tutorial. Of course, to appreciate
8254 it in full you need also this nice XPM icon, so here it is:</para>
8255
8256 <programlisting role="C">
8257 /* XPM */
8258 static char * gtk_xpm[] = {
8259 "32 39 5 1",
8260 ".      c none",
8261 "+      c black",
8262 "@      c #3070E0",
8263 "#      c #F05050",
8264 "$      c #35E035",
8265 "................+...............",
8266 "..............+++++.............",
8267 "............+++++@@++...........",
8268 "..........+++++@@@@@@++.........",
8269 "........++++@@@@@@@@@@++........",
8270 "......++++@@++++++++@@@++.......",
8271 ".....+++@@@+++++++++++@@@++.....",
8272 "...+++@@@@+++@@@@@@++++@@@@+....",
8273 "..+++@@@@+++@@@@@@@@+++@@@@@++..",
8274 ".++@@@@@@+++@@@@@@@@@@@@@@@@@@++",
8275 ".+#+@@@@@@++@@@@+++@@@@@@@@@@@@+",
8276 ".+##++@@@@+++@@@+++++@@@@@@@@$@.",
8277 ".+###++@@@@+++@@@+++@@@@@++$$$@.",
8278 ".+####+++@@@+++++++@@@@@+@$$$$@.",
8279 ".+#####+++@@@@+++@@@@++@$$$$$$+.",
8280 ".+######++++@@@@@@@++@$$$$$$$$+.",
8281 ".+#######+##+@@@@+++$$$$$$@@$$+.",
8282 ".+###+++##+##+@@++@$$$$$$++$$$+.",
8283 ".+###++++##+##+@@$$$$$$$@+@$$@+.",
8284 ".+###++++++#+++@$$@+@$$@++$$$@+.",
8285 ".+####+++++++#++$$@+@$$++$$$$+..",
8286 ".++####++++++#++$$@+@$++@$$$$+..",
8287 ".+#####+++++##++$$++@+++$$$$$+..",
8288 ".++####+++##+#++$$+++++@$$$$$+..",
8289 ".++####+++####++$$++++++@$$$@+..",
8290 ".+#####++#####++$$+++@++++@$@+..",
8291 ".+#####++#####++$$++@$$@+++$@@..",
8292 ".++####++#####++$$++$$$$$+@$@++.",
8293 ".++####++#####++$$++$$$$$$$$+++.",
8294 ".+++####+#####++$$++$$$$$$$@+++.",
8295 "..+++#########+@$$+@$$$$$$+++...",
8296 "...+++########+@$$$$$$$$@+++....",
8297 ".....+++######+@$$$$$$$+++......",
8298 "......+++#####+@$$$$$@++........",
8299 ".......+++####+@$$$$+++.........",
8300 ".........++###+$$$@++...........",
8301 "..........++##+$@+++............",
8302 "...........+++++++..............",
8303 ".............++++..............."};
8304 </programlisting>
8305
8306 </sect1>
8307
8308 <!-- ----------------------------------------------------------------- -->
8309 <sect1 id="sec-Notebooks">
8310 <title>Notebooks</title>
8311
8312 <para>The NoteBook Widget is a collection of "pages" that overlap each
8313 other, each page contains different information with only one page
8314 visible at a time. This widget has become more common lately in GUI
8315 programming, and it is a good way to show blocks of similar
8316 information that warrant separation in their display.</para>
8317
8318 <para>The first function call you will need to know, as you can probably
8319 guess by now, is used to create a new notebook widget.</para>
8320
8321 <programlisting role="C">
8322 GtkWidget *gtk_notebook_new( void );
8323 </programlisting>
8324
8325 <para>Once the notebook has been created, there are a number of functions
8326 that operate on the notebook widget. Let's look at them individually.</para>
8327
8328 <para>The first one we will look at is how to position the page indicators.
8329 These page indicators or "tabs" as they are referred to, can be
8330 positioned in four ways: top, bottom, left, or right.</para>
8331
8332 <programlisting role="C">
8333 void gtk_notebook_set_tab_pos( GtkNotebook     *notebook,
8334                                GtkPositionType  pos );
8335 </programlisting>
8336
8337 <para>GtkPositionType will be one of the following, which are pretty self
8338 explanatory:</para>
8339 <programlisting role="C">
8340   GTK_POS_LEFT
8341   GTK_POS_RIGHT
8342   GTK_POS_TOP
8343   GTK_POS_BOTTOM
8344 </programlisting>
8345
8346 <para><literal>GTK_POS_TOP</literal> is the default.</para>
8347
8348 <para>Next we will look at how to add pages to the notebook. There are three
8349 ways to add pages to the NoteBook. Let's look at the first two
8350 together as they are quite similar.</para>
8351
8352 <programlisting role="C">
8353 void gtk_notebook_append_page( GtkNotebook *notebook,
8354                                GtkWidget   *child,
8355                                GtkWidget   *tab_label );
8356
8357 void gtk_notebook_prepend_page( GtkNotebook *notebook,
8358                                 GtkWidget   *child,
8359                                 GtkWidget   *tab_label );
8360 </programlisting>
8361
8362 <para>These functions add pages to the notebook by inserting them from the
8363 back of the notebook (append), or the front of the notebook (prepend).
8364 <literal>child</literal> is the widget that is placed within the notebook page, and
8365 <literal>tab_label</literal> is the label for the page being added. The <literal>child</literal>
8366 widget must be created separately, and is typically a set of options
8367 setup witin one of the other container widgets, such as a table.</para>
8368
8369 <para>The final function for adding a page to the notebook contains all of
8370 the properties of the previous two, but it allows you to specify what
8371 position you want the page to be in the notebook.</para>
8372
8373 <programlisting role="C">
8374 void gtk_notebook_insert_page( GtkNotebook *notebook,
8375                                GtkWidget   *child,
8376                                GtkWidget   *tab_label,
8377                                gint         position );
8378 </programlisting>
8379
8380 <para>The parameters are the same as _append_ and _prepend_ except it
8381 contains an extra parameter, <literal>position</literal>.  This parameter is used to
8382 specify what place this page will be inserted into the first page
8383 having position zero.</para>
8384
8385 <para>Now that we know how to add a page, lets see how we can remove a page
8386 from the notebook.</para>
8387
8388 <programlisting role="C">
8389 void gtk_notebook_remove_page( GtkNotebook *notebook,
8390                                gint         page_num );
8391 </programlisting>
8392
8393 <para>This function takes the page specified by <literal>page_num</literal> and removes it
8394 from the widget pointed to by <literal>notebook</literal>.</para>
8395
8396 <para>To find out what the current page is in a notebook use the function:</para>
8397
8398 <programlisting role="C">
8399 gint gtk_notebook_get_current_page( GtkNotebook *notebook );
8400 </programlisting>
8401
8402 <para>These next two functions are simple calls to move the notebook page
8403 forward or backward. Simply provide the respective function call with
8404 the notebook widget you wish to operate on. Note: When the NoteBook is
8405 currently on the last page, and gtk_notebook_next_page is called, the
8406 notebook will wrap back to the first page. Likewise, if the NoteBook
8407 is on the first page, and gtk_notebook_prev_page is called, the
8408 notebook will wrap to the last page.</para>
8409
8410 <programlisting role="C">
8411 void gtk_notebook_next_page( GtkNoteBook *notebook );
8412
8413 void gtk_notebook_prev_page( GtkNoteBook *notebook );
8414 </programlisting>
8415
8416 <para>This next function sets the "active" page. If you wish the notebook to
8417 be opened to page 5 for example, you would use this function.  Without
8418 using this function, the notebook defaults to the first page.</para>
8419
8420 <programlisting role="C">
8421 void gtk_notebook_set_page( GtkNotebook *notebook,
8422                             gint         page_num );
8423 </programlisting>
8424
8425 <para>The next two functions add or remove the notebook page tabs and the
8426 notebook border respectively.</para>
8427
8428 <programlisting role="C">
8429 void gtk_notebook_set_show_tabs( GtkNotebook *notebook,
8430                                  gboolean     show_tabs);
8431
8432 void gtk_notebook_set_show_border( GtkNotebook *notebook,
8433                                    gboolean     show_border );
8434 </programlisting>
8435
8436 <para>The next function is useful when the you have a large number of pages,
8437 and the tabs don't fit on the page. It allows the tabs to be scrolled
8438 through using two arrow buttons.</para>
8439
8440 <programlisting role="C">
8441 void gtk_notebook_set_scrollable( GtkNotebook *notebook,
8442                                   gboolean     scrollable );
8443 </programlisting>
8444
8445 <para><literal>show_tabs</literal>, <literal>show_border</literal> and <literal>scrollable</literal> can be either
8446 TRUE or FALSE.</para>
8447
8448 <para>Now let's look at an example, it is expanded from the testgtk.c code
8449 that comes with the GTK distribution. This small program creates a
8450 window with a notebook and six buttons. The notebook contains 11
8451 pages, added in three different ways, appended, inserted, and
8452 prepended. The buttons allow you rotate the tab positions, add/remove
8453 the tabs and border, remove a page, change pages in both a forward and
8454 backward manner, and exit the program.</para>
8455
8456 <programlisting role="C">
8457 <!-- example-start notebook notebook.c -->
8458
8459 #include &lt;stdio.h&gt;
8460 #include &lt;gtk/gtk.h&gt;
8461
8462 /* This function rotates the position of the tabs */
8463 void rotate_book( GtkButton   *button,
8464                   GtkNotebook *notebook )
8465 {
8466     gtk_notebook_set_tab_pos (notebook, (notebook->tab_pos +1) %4);
8467 }
8468
8469 /* Add/Remove the page tabs and the borders */
8470 void tabsborder_book( GtkButton   *button,
8471                       GtkNotebook *notebook )
8472 {
8473     gint tval = FALSE;
8474     gint bval = FALSE;
8475     if (notebook->show_tabs == 0)
8476             tval = TRUE; 
8477     if (notebook->show_border == 0)
8478             bval = TRUE;
8479     
8480     gtk_notebook_set_show_tabs (notebook, tval);
8481     gtk_notebook_set_show_border (notebook, bval);
8482 }
8483
8484 /* Remove a page from the notebook */
8485 void remove_book( GtkButton   *button,
8486                   GtkNotebook *notebook )
8487 {
8488     gint page;
8489     
8490     page = gtk_notebook_get_current_page(notebook);
8491     gtk_notebook_remove_page (notebook, page);
8492     /* Need to refresh the widget -- 
8493      This forces the widget to redraw itself. */
8494     gtk_widget_draw(GTK_WIDGET(notebook), NULL);
8495 }
8496
8497 gint delete( GtkWidget *widget,
8498              GtkWidget *event,
8499              gpointer   data )
8500 {
8501     gtk_main_quit();
8502     return(FALSE);
8503 }
8504
8505 int main( int argc,
8506           char *argv[] )
8507 {
8508     GtkWidget *window;
8509     GtkWidget *button;
8510     GtkWidget *table;
8511     GtkWidget *notebook;
8512     GtkWidget *frame;
8513     GtkWidget *label;
8514     GtkWidget *checkbutton;
8515     int i;
8516     char bufferf[32];
8517     char bufferl[32];
8518     
8519     gtk_init (&amp;argc, &amp;argv);
8520     
8521     window = gtk_window_new (GTK_WINDOW_TOPLEVEL);
8522     
8523     gtk_signal_connect (GTK_OBJECT (window), "delete_event",
8524                         GTK_SIGNAL_FUNC (delete), NULL);
8525     
8526     gtk_container_set_border_width (GTK_CONTAINER (window), 10);
8527
8528     table = gtk_table_new(3,6,FALSE);
8529     gtk_container_add (GTK_CONTAINER (window), table);
8530     
8531     /* Create a new notebook, place the position of the tabs */
8532     notebook = gtk_notebook_new ();
8533     gtk_notebook_set_tab_pos (GTK_NOTEBOOK (notebook), GTK_POS_TOP);
8534     gtk_table_attach_defaults(GTK_TABLE(table), notebook, 0,6,0,1);
8535     gtk_widget_show(notebook);
8536     
8537     /* Let's append a bunch of pages to the notebook */
8538     for (i=0; i < 5; i++) {
8539         sprintf(bufferf, "Append Frame %d", i+1);
8540         sprintf(bufferl, "Page %d", i+1);
8541         
8542         frame = gtk_frame_new (bufferf);
8543         gtk_container_set_border_width (GTK_CONTAINER (frame), 10);
8544         gtk_widget_set_usize (frame, 100, 75);
8545         gtk_widget_show (frame);
8546         
8547         label = gtk_label_new (bufferf);
8548         gtk_container_add (GTK_CONTAINER (frame), label);
8549         gtk_widget_show (label);
8550         
8551         label = gtk_label_new (bufferl);
8552         gtk_notebook_append_page (GTK_NOTEBOOK (notebook), frame, label);
8553     }
8554       
8555     /* Now let's add a page to a specific spot */
8556     checkbutton = gtk_check_button_new_with_label ("Check me please!");
8557     gtk_widget_set_usize(checkbutton, 100, 75);
8558     gtk_widget_show (checkbutton);
8559    
8560     label = gtk_label_new ("Add page");
8561     gtk_notebook_insert_page (GTK_NOTEBOOK (notebook), checkbutton, label, 2);
8562     
8563     /* Now finally let's prepend pages to the notebook */
8564     for (i=0; i < 5; i++) {
8565         sprintf(bufferf, "Prepend Frame %d", i+1);
8566         sprintf(bufferl, "PPage %d", i+1);
8567         
8568         frame = gtk_frame_new (bufferf);
8569         gtk_container_set_border_width (GTK_CONTAINER (frame), 10);
8570         gtk_widget_set_usize (frame, 100, 75);
8571         gtk_widget_show (frame);
8572         
8573         label = gtk_label_new (bufferf);
8574         gtk_container_add (GTK_CONTAINER (frame), label);
8575         gtk_widget_show (label);
8576         
8577         label = gtk_label_new (bufferl);
8578         gtk_notebook_prepend_page (GTK_NOTEBOOK(notebook), frame, label);
8579     }
8580     
8581     /* Set what page to start at (page 4) */
8582     gtk_notebook_set_page (GTK_NOTEBOOK(notebook), 3);
8583
8584     /* Create a bunch of buttons */
8585     button = gtk_button_new_with_label ("close");
8586     gtk_signal_connect_object (GTK_OBJECT (button), "clicked",
8587                                GTK_SIGNAL_FUNC (delete), NULL);
8588     gtk_table_attach_defaults(GTK_TABLE(table), button, 0,1,1,2);
8589     gtk_widget_show(button);
8590     
8591     button = gtk_button_new_with_label ("next page");
8592     gtk_signal_connect_object (GTK_OBJECT (button), "clicked",
8593                                (GtkSignalFunc) gtk_notebook_next_page,
8594                                GTK_OBJECT (notebook));
8595     gtk_table_attach_defaults(GTK_TABLE(table), button, 1,2,1,2);
8596     gtk_widget_show(button);
8597     
8598     button = gtk_button_new_with_label ("prev page");
8599     gtk_signal_connect_object (GTK_OBJECT (button), "clicked",
8600                                (GtkSignalFunc) gtk_notebook_prev_page,
8601                                GTK_OBJECT (notebook));
8602     gtk_table_attach_defaults(GTK_TABLE(table), button, 2,3,1,2);
8603     gtk_widget_show(button);
8604     
8605     button = gtk_button_new_with_label ("tab position");
8606     gtk_signal_connect (GTK_OBJECT (button), "clicked",
8607                         (GtkSignalFunc) rotate_book,
8608                         GTK_OBJECT(notebook));
8609     gtk_table_attach_defaults(GTK_TABLE(table), button, 3,4,1,2);
8610     gtk_widget_show(button);
8611     
8612     button = gtk_button_new_with_label ("tabs/border on/off");
8613     gtk_signal_connect (GTK_OBJECT (button), "clicked",
8614                         (GtkSignalFunc) tabsborder_book,
8615                         GTK_OBJECT (notebook));
8616     gtk_table_attach_defaults(GTK_TABLE(table), button, 4,5,1,2);
8617     gtk_widget_show(button);
8618     
8619     button = gtk_button_new_with_label ("remove page");
8620     gtk_signal_connect (GTK_OBJECT (button), "clicked",
8621                         (GtkSignalFunc) remove_book,
8622                         GTK_OBJECT(notebook));
8623     gtk_table_attach_defaults(GTK_TABLE(table), button, 5,6,1,2);
8624     gtk_widget_show(button);
8625     
8626     gtk_widget_show(table);
8627     gtk_widget_show(window);
8628     
8629     gtk_main ();
8630     
8631     return(0);
8632 }
8633 <!-- example-end -->
8634 </programlisting>
8635
8636 <para>I hope this helps you on your way with creating notebooks for your
8637 GTK applications.</para>
8638
8639 </sect1>
8640 </chapter>
8641
8642 <!-- ***************************************************************** -->
8643 <chapter id="ch-CListWidget">
8644 <title>CList Widget</title>
8645
8646 <!-- ----------------------------------------------------------------- -->
8647
8648 <para>The CList widget has replaced the List widget (which is still
8649 available).</para>
8650
8651 <para>The CList widget is a multi-column list widget that is capable of
8652 handling literally thousands of rows of information. Each column can
8653 optionally have a title, which itself is optionally active, allowing
8654 us to bind a function to its selection.</para>
8655
8656 <!-- ----------------------------------------------------------------- -->
8657 <sect1 id="sec-CreatingACListWidget">
8658 <title>Creating a CList widget</title>
8659
8660 <para>Creating a CList is quite straightforward, once you have learned
8661 about widgets in general. It provides the almost standard two ways,
8662 that is the hard way, and the easy way. But before we create it, there
8663 is one thing we should figure out beforehand: how many columns should
8664 it have?</para>
8665
8666 <para>Not all columns have to be visible and can be used to store data that
8667 is related to a certain cell in the list.</para>
8668
8669 <programlisting role="C">
8670 GtkWidget *gtk_clist_new ( gint columns );
8671
8672 GtkWidget *gtk_clist_new_with_titles( gint   columns,
8673                                       gchar *titles[] );
8674 </programlisting>
8675
8676 <para>The first form is very straightforward, the second might require some
8677 explanation. Each column can have a title associated with it, and this
8678 title can be a label or a button that reacts when we click on it. If
8679 we use the second form, we must provide pointers to the title texts,
8680 and the number of pointers should equal the number of columns
8681 specified. Of course we can always use the first form, and manually
8682 add titles later.</para>
8683
8684 <para>Note: The CList widget does not have its own scrollbars and should
8685 be placed within a ScrolledWindow widget if your require this
8686 functionality. This is a change from the GTK 1.0 implementation.</para>
8687
8688 </sect1>
8689
8690 <!-- ----------------------------------------------------------------- -->
8691 <sect1 id="sec-ModesOfOperating">
8692 <title>Modes of operation</title>
8693
8694 <para>There are several attributes that can be used to alter the behaviour of
8695 a CList. First there is</para>
8696
8697 <programlisting role="C">
8698 void gtk_clist_set_selection_mode( GtkCList         *clist,
8699                                    GtkSelectionMode  mode );
8700 </programlisting>
8701
8702 <para>which, as the name implies, sets the selection mode of the
8703 CList. The first argument is the CList widget, and the second
8704 specifies the cell selection mode (they are defined in gtkenums.h). At
8705 the time of this writing, the following modes are available to us:</para>
8706
8707 <itemizedlist>
8708 <listitem><simpara> <literal>GTK_SELECTION_SINGLE</literal> - The selection is either NULL or contains
8709 a GList pointer for a single selected item.</simpara>
8710 </listitem>
8711
8712 <listitem><simpara> <literal>GTK_SELECTION_BROWSE</literal> - The selection is NULL if the list
8713 contains no widgets or insensitive ones only, otherwise it contains a
8714 GList pointer for one GList structure, and therefore exactly one list
8715 item.</simpara>
8716 </listitem>
8717
8718 <listitem><simpara> <literal>GTK_SELECTION_MULTIPLE</literal> - The selection is NULL if no list items
8719 are selected or a GList pointer for the first selected item. That in
8720 turn points to a GList structure for the second selected item and so
8721 on. This is currently the <emphasis>default</emphasis> for the CList widget.</simpara>
8722 </listitem>
8723
8724 <listitem><simpara> <literal>GTK_SELECTION_EXTENDED</literal> - The selection is always NULL.</simpara>
8725 </listitem>
8726 </itemizedlist>
8727
8728 <para>Others might be added in later revisions of GTK.</para>
8729
8730 <para>We can also define what the border of the CList widget should look
8731 like. It is done through</para>
8732
8733 <programlisting role="C">
8734 void gtk_clist_set_shadow_type( GtkCList      *clist,
8735                                 GtkShadowType  border );
8736 </programlisting>
8737
8738 <para>The possible values for the second argument are</para>
8739
8740 <programlisting role="C">
8741   GTK_SHADOW_NONE
8742   GTK_SHADOW_IN
8743   GTK_SHADOW_OUT
8744   GTK_SHADOW_ETCHED_IN
8745   GTK_SHADOW_ETCHED_OUT
8746 </programlisting>
8747
8748 </sect1>
8749
8750 <!-- ----------------------------------------------------------------- -->
8751 <sect1 id="sec-WorkingWithTitles">
8752 <title>Working with titles</title>
8753
8754 <para>When you create a CList widget, you will also get a set of title
8755 buttons automatically. They live in the top of the CList window, and
8756 can act either as normal buttons that respond to being pressed, or
8757 they can be passive, in which case they are nothing more than a
8758 title. There are four different calls that aid us in setting the
8759 status of the title buttons.</para>
8760
8761 <programlisting role="C">
8762 void gtk_clist_column_title_active( GtkCList *clist,
8763                                      gint     column );
8764
8765 void gtk_clist_column_title_passive( GtkCList *clist,
8766                                      gint      column );
8767
8768 void gtk_clist_column_titles_active( GtkCList *clist );
8769
8770 void gtk_clist_column_titles_passive( GtkCList *clist );
8771 </programlisting>
8772
8773 <para>An active title is one which acts as a normal button, a passive one is
8774 just a label. The first two calls above will activate/deactivate the
8775 title button above the specific column, while the last two calls
8776 activate/deactivate all title buttons in the supplied clist widget.</para>
8777
8778 <para>But of course there are those cases when we don't want them at all,
8779 and so they can be hidden and shown at will using the following two
8780 calls.</para>
8781
8782 <programlisting role="C">
8783 void gtk_clist_column_titles_show( GtkCList *clist );
8784
8785 void gtk_clist_column_titles_hide( GtkCList *clist );
8786 </programlisting>
8787
8788 <para>For titles to be really useful we need a mechanism to set and change
8789 them, and this is done using</para>
8790
8791 <programlisting role="C">
8792 void gtk_clist_set_column_title( GtkCList *clist,
8793                                  gint      column,
8794                                  gchar    *title );
8795 </programlisting>
8796
8797 <para>Note that only the title of one column can be set at a time, so if all
8798 the titles are known from the beginning, then I really suggest using
8799 gtk_clist_new_with_titles (as described above) to set them. It saves
8800 you coding time, and makes your program smaller. There are some cases
8801 where getting the job done the manual way is better, and that's when
8802 not all titles will be text. CList provides us with title buttons
8803 that can in fact incorporate whole widgets, for example a pixmap. It's
8804 all done through</para>
8805
8806 <programlisting role="C">
8807 void gtk_clist_set_column_widget( GtkCList  *clist,
8808                                   gint       column,
8809                                   GtkWidget *widget );
8810 </programlisting>
8811
8812 <para>which should require no special explanation.</para>
8813
8814 </sect1>
8815
8816 <!-- ----------------------------------------------------------------- -->
8817 <sect1 id="sec-ManipulatingTheListItself">
8818 <title>Manipulating the list itself</title>
8819
8820 <para>It is possible to change the justification for a column, and it is
8821 done through</para>
8822
8823 <programlisting role="C">
8824 void gtk_clist_set_column_justification( GtkCList         *clist,
8825                                          gint              column,
8826                                          GtkJustification  justification );
8827 </programlisting>
8828
8829 <para>The GtkJustification type can take the following values:</para>
8830
8831 <itemizedlist>
8832 <listitem><simpara><literal>GTK_JUSTIFY_LEFT</literal> - The text in the column will begin from the
8833 left edge.</simpara>
8834 </listitem>
8835
8836 <listitem><simpara><literal>GTK_JUSTIFY_RIGHT</literal> - The text in the column will begin from the
8837 right edge.</simpara>
8838 </listitem>
8839
8840 <listitem><simpara><literal>GTK_JUSTIFY_CENTER</literal> - The text is placed in the center of the
8841 column.</simpara>
8842 </listitem>
8843
8844 <listitem><simpara><literal>GTK_JUSTIFY_FILL</literal> - The text will use up all available space in
8845 the column. It is normally done by inserting extra blank spaces
8846 between words (or between individual letters if it's a single
8847 word). Much in the same way as any ordinary WYSIWYG text editor.</simpara>
8848 </listitem>
8849 </itemizedlist>
8850
8851 <para>The next function is a very important one, and should be standard in
8852 the setup of all CList widgets. When the list is created, the width
8853 of the various columns are chosen to match their titles, and since
8854 this is seldom the right width we have to set it using</para>
8855
8856 <programlisting role="C">
8857 void gtk_clist_set_column_width( GtkCList *clist,
8858                                  gint      column,
8859                                  gint      width );
8860 </programlisting>
8861
8862 <para>Note that the width is given in pixels and not letters. The same goes
8863 for the height of the cells in the columns, but as the default value
8864 is the height of the current font this isn't as critical to the
8865 application. Still, it is done through</para>
8866
8867 <programlisting role="C">
8868 void gtk_clist_set_row_height( GtkCList *clist,
8869                                gint      height );
8870 </programlisting>
8871
8872 <para>Again, note that the height is given in pixels.</para>
8873
8874 <para>We can also move the list around without user interaction, however, it
8875 does require that we know what we are looking for. Or in other words,
8876 we need the row and column of the item we want to scroll to.</para>
8877
8878 <programlisting role="C">
8879 void gtk_clist_moveto( GtkCList *clist,
8880                        gint      row,
8881                        gint      column,
8882                        gfloat    row_align,
8883                        gfloat    col_align );
8884 </programlisting>
8885
8886 <para>The gfloat row_align is pretty important to understand. It's a value
8887 between 0.0 and 1.0, where 0.0 means that we should scroll the list so
8888 the row appears at the top, while if the value of row_align is 1.0,
8889 the row will appear at the bottom instead. All other values between
8890 0.0 and 1.0 are also valid and will place the row between the top and
8891 the bottom. The last argument, gfloat col_align works in the same way,
8892 though 0.0 marks left and 1.0 marks right instead.</para>
8893
8894 <para>Depending on the application's needs, we don't have to scroll to an
8895 item that is already visible to us. So how do we know if it is
8896 visible? As usual, there is a function to find that out as well.</para>
8897
8898 <programlisting role="C">
8899 GtkVisibility gtk_clist_row_is_visible( GtkCList *clist,
8900                                         gint      row );
8901 </programlisting>
8902
8903 <para>The return value is is one of the following:</para>
8904
8905 <programlisting role="C">
8906   GTK_VISIBILITY_NONE
8907   GTK_VISIBILITY_PARTIAL
8908   GTK_VISIBILITY_FULL
8909 </programlisting>
8910
8911 <para>Note that it will only tell us if a row is visible. Currently there is
8912 no way to determine this for a column. We can get partial information
8913 though, because if the return is <literal>GTK_VISIBILITY_PARTIAL</literal>, then
8914 some of it is hidden, but we don't know if it is the row that is being
8915 cut by the lower edge of the listbox, or if the row has columns that
8916 are outside.</para>
8917
8918 <para>We can also change both the foreground and background colors of a
8919 particular row. This is useful for marking the row selected by the
8920 user, and the two functions that is used to do it are</para>
8921
8922 <programlisting role="C">
8923 void gtk_clist_set_foreground( GtkCList *clist,
8924                                gint      row,
8925                                GdkColor *color );
8926
8927 void gtk_clist_set_background( GtkCList *clist,
8928                                gint      row,
8929                                GdkColor *color );
8930 </programlisting>
8931
8932 <para>Please note that the colors must have been previously allocated.</para>
8933
8934 </sect1>
8935
8936 <!-- ----------------------------------------------------------------- -->
8937 <sect1 id="sec-AddingRowsToTheList">
8938 <title>Adding rows to the list</title>
8939
8940 <para>We can add rows in three ways. They can be prepended or appended to
8941 the list using</para>
8942
8943 <programlisting role="C">
8944 gint gtk_clist_prepend( GtkCList *clist,
8945                         gchar    *text[] );
8946
8947 gint gtk_clist_append( GtkCList *clist,
8948                        gchar    *text[] );
8949 </programlisting>
8950
8951 <para>The return value of these two functions indicate the index of the row
8952 that was just added. We can insert a row at a given place using</para>
8953
8954 <programlisting role="C">
8955 void gtk_clist_insert( GtkCList *clist,
8956                        gint      row,
8957                        gchar    *text[] );
8958 </programlisting>
8959
8960 <para>In these calls we have to provide a collection of pointers that are
8961 the texts we want to put in the columns. The number of pointers should
8962 equal the number of columns in the list. If the text[] argument is
8963 NULL, then there will be no text in the columns of the row. This is
8964 useful, for example, if we want to add pixmaps instead (something that
8965 has to be done manually).</para>
8966
8967 <para>Also, please note that the numbering of both rows and columns start at 0.</para>
8968
8969 <para>To remove an individual row we use</para>
8970
8971 <programlisting role="C">
8972 void gtk_clist_remove( GtkCList *clist,
8973                        gint      row );
8974 </programlisting>
8975
8976 <para>There is also a call that removes all rows in the list. This is a lot
8977 faster than calling gtk_clist_remove once for each row, which is the
8978 only alternative.</para>
8979
8980 <programlisting role="C">
8981 void gtk_clist_clear( GtkCList *clist );
8982 </programlisting>
8983
8984 <para>There are also two convenience functions that should be used when a
8985 lot of changes have to be made to the list. This is to prevent the
8986 list flickering while being repeatedly updated, which may be highly
8987 annoying to the user. So instead it is a good idea to freeze the list,
8988 do the updates to it, and finally thaw it which causes the list to be
8989 updated on the screen.</para>
8990
8991 <programlisting role="C">
8992 void gtk_clist_freeze( GtkCList * clist );
8993
8994 void gtk_clist_thaw( GtkCList * clist );
8995 </programlisting>
8996
8997 </sect1>
8998
8999 <!-- ----------------------------------------------------------------- -->
9000 <sect1 id="sec-SettingTextAndPixmapsInTheCells">
9001 <title>Setting text and pixmaps in the cells</title>
9002
9003 <para>A cell can contain a pixmap, text or both. To set them the following
9004 functions are used.</para>
9005
9006 <programlisting role="C">
9007 void gtk_clist_set_text( GtkCList    *clist,
9008                          gint         row,
9009                          gint         column,
9010                          const gchar *text );
9011
9012 void gtk_clist_set_pixmap( GtkCList  *clist,
9013                            gint       row,
9014                            gint       column,
9015                            GdkPixmap *pixmap,
9016                            GdkBitmap *mask );
9017
9018 void gtk_clist_set_pixtext( GtkCList  *clist,
9019                             gint       row,
9020                             gint       column,
9021                             gchar     *text,
9022                             guint8     spacing,
9023                             GdkPixmap *pixmap,
9024                             GdkBitmap *mask );
9025 </programlisting>
9026
9027 <para>It's quite straightforward. All the calls have the CList as the first
9028 argument, followed by the row and column of the cell, followed by the
9029 data to be set. The <literal>spacing</literal> argument in gtk_clist_set_pixtext is
9030 the number of pixels between the pixmap and the beginning of the
9031 text. In all cases the data is copied into the widget.</para>
9032
9033 <para>To read back the data, we instead use</para>
9034
9035 <programlisting role="C">
9036 gint gtk_clist_get_text( GtkCList  *clist,
9037                          gint       row,
9038                          gint       column,
9039                          gchar    **text );
9040
9041 gint gtk_clist_get_pixmap( GtkCList   *clist,
9042                            gint        row,
9043                            gint        column,
9044                            GdkPixmap **pixmap,
9045                            GdkBitmap **mask );
9046
9047 gint gtk_clist_get_pixtext( GtkCList   *clist,
9048                             gint        row,
9049                             gint        column,
9050                             gchar     **text,
9051                             guint8     *spacing,
9052                             GdkPixmap **pixmap,
9053                             GdkBitmap **mask );
9054 </programlisting>
9055
9056 <para>The returned pointers are all pointers to the data stored within the
9057 widget, so the referenced data should not be modified or released. It
9058 isn't necessary to read it all back in case you aren't interested. Any
9059 of the pointers that are meant for return values (all except the
9060 clist) can be NULL. So if we want to read back only the text from a
9061 cell that is of type pixtext, then we would do the following, assuming
9062 that clist, row and column already exist:</para>
9063
9064 <programlisting role="C">
9065 gchar *mytext;
9066
9067 gtk_clist_get_pixtext(clist, row, column, &amp;mytext, NULL, NULL, NULL);
9068 </programlisting>
9069
9070 <para>There is one more call that is related to what's inside a cell in the
9071 clist, and that's</para>
9072
9073 <programlisting role="C">
9074 GtkCellType gtk_clist_get_cell_type( GtkCList *clist,
9075                                      gint      row,
9076                                      gint      column );
9077 </programlisting>
9078
9079 <para>which returns the type of data in a cell. The return value is one of</para>
9080
9081 <programlisting role="C">
9082   GTK_CELL_EMPTY
9083   GTK_CELL_TEXT
9084   GTK_CELL_PIXMAP
9085   GTK_CELL_PIXTEXT
9086   GTK_CELL_WIDGET
9087 </programlisting>
9088
9089 <para>There is also a function that will let us set the indentation, both
9090 vertical and horizontal, of a cell. The indentation value is of type
9091 gint, given in pixels, and can be both positive and negative.</para>
9092
9093 <programlisting role="C">
9094 void gtk_clist_set_shift( GtkCList *clist,
9095                           gint      row,
9096                           gint      column,
9097                           gint      vertical,
9098                           gint      horizontal );
9099 </programlisting>
9100
9101 </sect1>
9102
9103 <!-- ----------------------------------------------------------------- -->
9104 <sect1 id="sec-StoringDataPointers">
9105 <title>Storing data pointers</title>
9106
9107 <para>With a CList it is possible to set a data pointer for a row. This
9108 pointer will not be visible for the user, but is merely a convenience
9109 for the programmer to associate a row with a pointer to some
9110 additional data.</para>
9111
9112 <para>The functions should be fairly self-explanatory by now.</para>
9113
9114 <programlisting role="C">
9115 void gtk_clist_set_row_data( GtkCList *clist,
9116                              gint      row,
9117                              gpointer  data );
9118
9119 oid gtk_clist_set_row_data_full( GtkCList         *clist,
9120                                   gint              row,
9121                                   gpointer          data,
9122                                   GtkDestroyNotify  destroy );
9123
9124 gpointer gtk_clist_get_row_data( GtkCList *clist,
9125                                  gint      row );
9126
9127 gint gtk_clist_find_row_from_data( GtkCList *clist,
9128                                    gpointer  data );
9129 </programlisting>
9130
9131 </sect1>
9132
9133 <!-- ----------------------------------------------------------------- -->
9134 <sect1 id="sec-WorkingWithSelections">
9135 <title>Working with selections</title>
9136
9137 <para>There are also functions available that let us force the (un)selection
9138 of a row. These are</para>
9139
9140 <programlisting role="C">
9141 void gtk_clist_select_row( GtkCList *clist,
9142                            gint      row,
9143                            gint      column );
9144
9145 void gtk_clist_unselect_row( GtkCList *clist,
9146                              gint      row,
9147                              gint      column );
9148 </programlisting>
9149
9150 <para>And also a function that will take x and y coordinates (for example,
9151 read from the mousepointer), and map that onto the list, returning the
9152 corresponding row and column.</para>
9153
9154 <programlisting role="C">
9155 gint gtk_clist_get_selection_info( GtkCList *clist,
9156                                    gint      x,
9157                                    gint      y,
9158                                    gint     *row,
9159                                    gint     *column );
9160 </programlisting>
9161
9162 <para>When we detect something of interest (it might be movement of the
9163 pointer, a click somewhere in the list) we can read the pointer
9164 coordinates and find out where in the list the pointer is. Cumbersome?
9165 Luckily, there is a simpler way...</para>
9166
9167 </sect1>
9168
9169 <!-- ----------------------------------------------------------------- -->
9170 <sect1 id="sec-TheSignalsThatBringItTogether">
9171 <title>The signals that bring it together</title>
9172
9173 <para>As with all other widgets, there are a few signals that can be used. The
9174 CList widget is derived from the Container widget, and so has all the
9175 same signals, but also adds the following:</para>
9176
9177 <itemizedlist>
9178 <listitem><simpara>select_row - This signal will send the following information, in
9179 order: GtkCList *clist, gint row, gint column, GtkEventButton *event</simpara>
9180 </listitem>
9181
9182 <listitem><simpara>unselect_row - When the user unselects a row, this signal is
9183 activated. It sends the same information as select_row<</simpara>
9184 </listitem>
9185
9186 <listitem><simpara>click_column - Send GtkCList *clist, gint column</simpara>
9187 </listitem>
9188 </itemizedlist>
9189
9190 <para>So if we want to connect a callback to select_row, the callback
9191 function would be declared like this</para>
9192
9193 <programlisting role="C">
9194 void select_row_callback(GtkWidget *widget,
9195                          gint row,
9196                          gint column,
9197                          GdkEventButton *event,
9198                          gpointer data);
9199 </programlisting>
9200
9201 <para>The callback is connected as usual with</para>
9202
9203 <programlisting role="C">
9204 gtk_signal_connect(GTK_OBJECT( clist),
9205                    "select_row",
9206                    GTK_SIGNAL_FUNC(select_row_callback),
9207                    NULL);
9208 </programlisting>
9209
9210 </sect1>
9211
9212 <!-- ----------------------------------------------------------------- -->
9213 <sect1 id="sec-ACListExample">
9214 <title>A CList example</title>
9215
9216 <programlisting role="C">
9217 <!-- example-start clist clist.c -->
9218
9219 #include &lt;gtk/gtk.h&gt;
9220
9221 /* User clicked the "Add List" button. */
9222 void button_add_clicked( gpointer data )
9223 {
9224     int indx;
9225  
9226     /* Something silly to add to the list. 4 rows of 2 columns each */
9227     gchar *drink[4][2] = { { "Milk",    "3 Oz" },
9228                            { "Water",   "6 l" },
9229                            { "Carrots", "2" },
9230                            { "Snakes",  "55" } };
9231
9232     /* Here we do the actual adding of the text. It's done once for
9233      * each row.
9234      */
9235     for ( indx=0 ; indx < 4 ; indx++ )
9236         gtk_clist_append( (GtkCList *) data, drink[indx]);
9237
9238     return;
9239 }
9240
9241 /* User clicked the "Clear List" button. */
9242 void button_clear_clicked( gpointer data )
9243 {
9244     /* Clear the list using gtk_clist_clear. This is much faster than
9245      * calling gtk_clist_remove once for each row.
9246      */
9247     gtk_clist_clear( (GtkCList *) data);
9248
9249     return;
9250 }
9251
9252 /* The user clicked the "Hide/Show titles" button. */
9253 void button_hide_show_clicked( gpointer data )
9254 {
9255     /* Just a flag to remember the status. 0 = currently visible */
9256     static short int flag = 0;
9257
9258     if (flag == 0)
9259     {
9260         /* Hide the titles and set the flag to 1 */
9261         gtk_clist_column_titles_hide((GtkCList *) data);
9262         flag++;
9263     }
9264     else
9265     {
9266         /* Show the titles and reset flag to 0 */
9267         gtk_clist_column_titles_show((GtkCList *) data);
9268         flag--;
9269     }
9270
9271     return;
9272 }
9273
9274 /* If we come here, then the user has selected a row in the list. */
9275 void selection_made( GtkWidget      *clist,
9276                      gint            row,
9277                      gint            column,
9278                      GdkEventButton *event,
9279                      gpointer        data )
9280 {
9281     gchar *text;
9282
9283     /* Get the text that is stored in the selected row and column
9284      * which was clicked in. We will receive it as a pointer in the
9285      * argument text.
9286      */
9287     gtk_clist_get_text(GTK_CLIST(clist), row, column, &amp;text);
9288
9289     /* Just prints some information about the selected row */
9290     g_print("You selected row %d. More specifically you clicked in "
9291             "column %d, and the text in this cell is %s\n\n",
9292             row, column, text);
9293
9294     return;
9295 }
9296
9297 int main( int    argc,
9298           gchar *argv[] )
9299 {                                  
9300     GtkWidget *window;
9301     GtkWidget *vbox, *hbox;
9302     GtkWidget *scrolled_window, *clist;
9303     GtkWidget *button_add, *button_clear, *button_hide_show;    
9304     gchar *titles[2] = { "Ingredients", "Amount" };
9305
9306     gtk_init(&amp;argc, &amp;argv);
9307     
9308     window=gtk_window_new(GTK_WINDOW_TOPLEVEL);
9309     gtk_widget_set_usize(GTK_WIDGET(window), 300, 150);
9310
9311     gtk_window_set_title(GTK_WINDOW(window), "GtkCList Example");
9312     gtk_signal_connect(GTK_OBJECT(window),
9313                        "destroy",
9314                        GTK_SIGNAL_FUNC(gtk_main_quit),
9315                        NULL);
9316     
9317     vbox=gtk_vbox_new(FALSE, 5);
9318     gtk_container_set_border_width(GTK_CONTAINER(vbox), 5);
9319     gtk_container_add(GTK_CONTAINER(window), vbox);
9320     gtk_widget_show(vbox);
9321     
9322     /* Create a scrolled window to pack the CList widget into */
9323     scrolled_window = gtk_scrolled_window_new (NULL, NULL);
9324     gtk_scrolled_window_set_policy (GTK_SCROLLED_WINDOW (scrolled_window),
9325                                     GTK_POLICY_AUTOMATIC, GTK_POLICY_ALWAYS);
9326
9327     gtk_box_pack_start(GTK_BOX(vbox), scrolled_window, TRUE, TRUE, 0);
9328     gtk_widget_show (scrolled_window);
9329
9330     /* Create the CList. For this example we use 2 columns */
9331     clist = gtk_clist_new_with_titles( 2, titles);
9332
9333     /* When a selection is made, we want to know about it. The callback
9334      * used is selection_made, and its code can be found further down */
9335     gtk_signal_connect(GTK_OBJECT(clist), "select_row",
9336                        GTK_SIGNAL_FUNC(selection_made),
9337                        NULL);
9338
9339     /* It isn't necessary to shadow the border, but it looks nice :) */
9340     gtk_clist_set_shadow_type (GTK_CLIST(clist), GTK_SHADOW_OUT);
9341
9342     /* What however is important, is that we set the column widths as
9343      * they will never be right otherwise. Note that the columns are
9344      * numbered from 0 and up (to 1 in this case).
9345      */
9346     gtk_clist_set_column_width (GTK_CLIST(clist), 0, 150);
9347
9348     /* Add the CList widget to the vertical box and show it. */
9349     gtk_container_add(GTK_CONTAINER(scrolled_window), clist);
9350     gtk_widget_show(clist);
9351
9352     /* Create the buttons and add them to the window. See the button
9353      * tutorial for more examples and comments on this.
9354      */
9355     hbox = gtk_hbox_new(FALSE, 0);
9356     gtk_box_pack_start(GTK_BOX(vbox), hbox, FALSE, TRUE, 0);
9357     gtk_widget_show(hbox);
9358
9359     button_add = gtk_button_new_with_label("Add List");
9360     button_clear = gtk_button_new_with_label("Clear List");
9361     button_hide_show = gtk_button_new_with_label("Hide/Show titles");
9362
9363     gtk_box_pack_start(GTK_BOX(hbox), button_add, TRUE, TRUE, 0);
9364     gtk_box_pack_start(GTK_BOX(hbox), button_clear, TRUE, TRUE, 0);
9365     gtk_box_pack_start(GTK_BOX(hbox), button_hide_show, TRUE, TRUE, 0);
9366
9367     /* Connect our callbacks to the three buttons */
9368     gtk_signal_connect_object(GTK_OBJECT(button_add), "clicked",
9369                               GTK_SIGNAL_FUNC(button_add_clicked),
9370                               (gpointer) clist);
9371     gtk_signal_connect_object(GTK_OBJECT(button_clear), "clicked",
9372                               GTK_SIGNAL_FUNC(button_clear_clicked),
9373                               (gpointer) clist);
9374     gtk_signal_connect_object(GTK_OBJECT(button_hide_show), "clicked",
9375                               GTK_SIGNAL_FUNC(button_hide_show_clicked),
9376                               (gpointer) clist);
9377
9378     gtk_widget_show(button_add);
9379     gtk_widget_show(button_clear);
9380     gtk_widget_show(button_hide_show);
9381
9382     /* The interface is completely set up so we show the window and
9383      * enter the gtk_main loop.
9384      */
9385     gtk_widget_show(window);
9386     gtk_main();
9387     
9388     return(0);
9389 }
9390 <!-- example-end -->
9391 </programlisting>
9392
9393 </sect1>
9394 </chapter>
9395
9396 <!-- ***************************************************************** -->
9397 <chapter id="ch-CTreeWidget">
9398 <title>CTree Widget</title>
9399
9400 <!-- ----------------------------------------------------------------- -->
9401 <para>The CTree widget is derived from the CList widget. It is designed to
9402 display hierarchically-organised data. The tree is displayed
9403 vertically, and branches of the tree can be clapsed and expanded as
9404 required by the user.</para>
9405
9406 <para>This section of the tutorial is under development.</para>
9407  
9408 <!-- ----------------------------------------------------------------- -->
9409 <sect1 id="sec-CreatingACTree">
9410 <title>Creating a CTree</title>
9411
9412 <para>A CTree, being derived from CList, can have multiple columns. These
9413 columns optionally have titles that are displayed along the top of
9414 the CTree widget. Hence there are two functions for creating a new
9415 CTree widget:</para>
9416
9417 <programlisting role="C">
9418 GtkWidget *gtk_ctree_new_with_titles( gint   columns, 
9419                                       gint   tree_column,
9420                                       gchar *titles[] );
9421
9422 GtkWidget *gtk_ctree_new( gint columns, 
9423                           gint tree_column );
9424 </programlisting>
9425
9426 <para>The <literal>columns</literal> argument specifies the number of columns that the
9427 CTree will contain. The <literal>tree_column</literal> argumnet specifies which of
9428 those columns is to contain the tree. Columns are numbered starting
9429 from 0.</para>
9430
9431 <para>With the first funtion above, the <literal>titles</literal> argument contains an
9432 array of strings that contain the captions for the column headings. A
9433 typical code fragment using the <literal>gtk_ctree_new_with_titles()</literal>
9434 function would be:</para>
9435
9436 <programlisting role="C">
9437     /* CTree column titles /*
9438     char *titles[] = { "Location" , "Description" };
9439     GtkWidget *ctree;
9440
9441     ctree = gtk_ctree_new_with_titles(2, 0, titles);
9442 </programlisting>
9443
9444 <para>This would create a new CTree with two columns entitled "Location"
9445 and "Description", with the first column containing the tree.</para>
9446
9447 </sect1>
9448
9449 <!-- ----------------------------------------------------------------- -->
9450 <sect1 id="sec-AddingAndRemovingNodes">
9451 <title>Adding and Removing nodes</title>
9452
9453 <para>The items in a CTree are termed <emphasis>nodes</emphasis>. Nodes are inserted
9454 into a CTree in such a way as to create a hierarchy (although the
9455 order of insertion is not critical). The following function is used to
9456 insert a node:</para>
9457
9458 <programlisting role="C">
9459 GtkCTreeNode *gtk_ctree_insert_node( GtkCTree     *ctree,
9460                                      GtkCTreeNode *parent, 
9461                                      GtkCTreeNode *sibling,
9462                                      gchar        *text[],
9463                                      guint8        spacing,
9464                                      GdkPixmap    *pixmap_closed,
9465                                      GdkBitmap    *mask_closed,
9466                                      GdkPixmap    *pixmap_opened,
9467                                      GdkBitmap    *mask_opened,
9468                                      gboolean      is_leaf,
9469                                      gboolean      expanded );
9470 </programlisting>
9471
9472 <para>This function looks a little daunting, but that is merely due to the
9473 power of the CTreee widget. Not all of the parameters above are
9474 required.</para>
9475
9476 <para>The CTree widget allows you to specify pixmaps to display in each
9477 node. For branch nodes, you can specify different pixmaps for when the
9478 branch is collapsed or expanded. This gives a nice visual feedback to
9479 the user, but it is optional so you don't have to specify pixmaps.</para>
9480
9481 <para>Lets have a quick look at all of the parameters:</para>
9482
9483 <itemizedlist>
9484 <listitem><simpara> <literal>ctree</literal> - the CTree widget we are manipulating</simpara>
9485 </listitem>
9486
9487 <listitem><simpara> <literal>parent</literal> - the parent node of the one we are inserting. May
9488                      be <literal>NULL</literal> for a root-level (i.e. initial)
9489                      node.</simpara>
9490 </listitem>
9491
9492 <listitem><simpara> <literal>sibling</literal> - a sibling of the node we are inserting. May be
9493                       <literal>NULL</literal> if there are no siblings.</simpara>
9494 </listitem>
9495
9496 <listitem><simpara> <literal>text</literal> - the textual contents of each column in the tree for
9497                    this node. This array <emphasis>must</emphasis> have an entry
9498                    for each column, even if it is an empty string.</simpara>
9499 </listitem>
9500
9501 <listitem><simpara> <literal>spacing</literal> - specifies the padding between the nodes pixmap
9502                       and text elements, if a pixmap is provided</simpara>
9503 </listitem>
9504
9505 <listitem><simpara> <literal>pixmap_closed</literal> - a pixmap to display for a collapsed branch
9506                             node and for a leaf node.</simpara>
9507 </listitem>
9508
9509 <listitem><simpara> <literal>mask_closed</literal> - a bitmap mask for the above pixmap.</simpara>
9510 </listitem>
9511
9512 <listitem><simpara> <literal>pixmap_opened</literal> - a pixmap to display for an expanded
9513                             branch node.</simpara>
9514 </listitem>
9515
9516 <listitem><simpara> <literal>mask_opened</literal> - a bitmap mask for the above pixmap.</simpara>
9517 </listitem>
9518
9519 <listitem><simpara> <literal>is_leaf</literal> - indicates whether this is a leaf or branch node.</simpara>
9520 </listitem>
9521
9522 <listitem><simpara> <literal>expanded</literal> - indicates whether a branch node is initially
9523                        expanded or collapsed.</simpara>
9524 </listitem>
9525 </itemizedlist>
9526
9527 <para>An object pointer of type GtkCTreeNode is returned by the
9528 gtk_ctree_insert_node() function. This object pointer is used to
9529 reference the node when manipulating it. The node pointer is also
9530 supplied by many of the CTree signals to identify which node the
9531 signal pertains to.</para>
9532
9533 <para>To remove a node for a CTree, the following function is provided:</para>
9534
9535 <programlisting role="C">
9536 void gtk_ctree_remove_node( GtkCTree     *ctree, 
9537                             GtkCTreeNode *node );
9538 </programlisting>
9539
9540 <para>As you can see, you merely need to specify a CTree and the node to
9541 remove.</para>
9542
9543 </sect1>
9544
9545 <!-- ----------------------------------------------------------------- -->
9546 <sect1 id="sec-SettingCTreeAttributes">
9547 <title>Setting CTree Attributes</title>
9548
9549 <para>There are a number of functions that set options that pertain to a
9550 CTree instance as a whole (rather than to a particular node). The
9551 first group set padding attributes that effect how the widget is drawn:</para>
9552
9553 <programlisting role="C">
9554 void gtk_ctree_set_indent( GtkCTree *ctree, 
9555                            gint      indent );
9556
9557 void gtk_ctree_set_spacing( GtkCTree *ctree, 
9558                             gint      spacing );
9559 </programlisting>
9560
9561 <para>The function <literal>gtk_ctree_set_indent()</literal> sets how far a new branch is
9562 indented in relation to it's parent. The default is 20.</para>
9563
9564 <para>The function <literal>gtk_ctree_set_spacing()</literal> sets how far a node is
9565 horizontally padded from the vertical line that is drawn linking the
9566 nodes of each branch. The default is 5.</para>
9567
9568 <para>The next two functions affect the style of the lines and expander that
9569 are drawn to represent the tree structure. An expander is a grpahical
9570 component that the user can select to expand and collapse a branch of
9571 the tree.</para>
9572
9573 <programlisting role="C">
9574 void gtk_ctree_set_line_style( GtkCTree          *ctree, 
9575                                GtkCTreeLineStyle  line_style );
9576
9577 void gtk_ctree_set_expander_style( GtkCTree              *ctree, 
9578                                    GtkCTreeExpanderStyle  expander_style );
9579 </programlisting>
9580
9581 <para>The function <literal>gtk_ctree_set_line_style()</literal> is used to select the style
9582 of line that is drawn between nodes of the tree. The parameter
9583 <literal>line_style</literal> can be one of:</para>
9584
9585 <programlisting role="C">
9586  GTK_CTREE_LINES_NONE
9587  GTK_CTREE_LINES_SOLID
9588  GTK_CTREE_LINES_DOTTED
9589  GTK_CTREE_LINES_TABBED
9590 </programlisting>
9591
9592 <para>The function <literal>gtk_ctree_set_expander_style()</literal> is used to select
9593 the style of branch expander, and the parameter <literal>expander_style</literal>
9594 can be one of:</para>
9595
9596 <programlisting role="C">
9597  GTK_CTREE_EXPANDER_NONE
9598  GTK_CTREE_EXPANDER_SQUARE
9599  GTK_CTREE_EXPANDER_TRIANGLE
9600  GTK_CTREE_EXPANDER_CIRCULAR
9601 </programlisting>
9602
9603 </sect1>
9604
9605 <!-- ----------------------------------------------------------------- -->
9606 <sect1 id="sec-UtilizingRowData">
9607 <title>Utilizing row data</title>
9608
9609 <para>The CTree widget allows you to associate data with each node of the
9610 tree. This is most often used in callback functions, such as when a
9611 row is selected.</para>
9612
9613 <para>Although only a single data element can be stored for each row, this
9614 data element can be any variable or data structure, which indirectly
9615 allows a set of data to be referenced.</para>
9616
9617 <para>There are two functions for setting row data:</para>
9618
9619 <programlisting role="C">
9620 void gtk_ctree_node_set_row_data( GtkCTree     *ctree,
9621                                   GtkCTreeNode *node,
9622                                   gpointer      data );
9623
9624 void gtk_ctree_node_set_row_data_full( GtkCTree         *ctree,
9625                                        GtkCTreeNode     *node,
9626                                        gpointer          data,
9627                                        GtkDestroyNotify  destroy );
9628 </programlisting>
9629
9630 <para>The function <literal>gtk_ctree_node_set_row_data()</literal> simply takes as
9631 arguments pointers to the CTree, node and data.</para>
9632
9633 <para>The function <literal>gtk_ctree_node_set_row_data_full()</literal> takes an
9634 additional parameter, <literal>destroy</literal>. This parameter is a pointer to a
9635 function that will be called when the row is destroyed. Typically,
9636 this function would take responsibility for freeing the memory used by
9637 the row data. This function should take the form:</para>
9638
9639 <programlisting role="C">
9640 void destroy_func( gpointer data );
9641 </programlisting>
9642
9643 <para>The paramter passed to this function will be the row data.</para>
9644
9645 </sect1>
9646 </chapter>
9647
9648 <!-- ***************************************************************** -->
9649 <chapter id="ch-TreeWidget">
9650 <title>Tree Widget</title>
9651
9652 <!-- ----------------------------------------------------------------- -->
9653
9654 <para>The purpose of tree widgets is to display hierarchically-organized
9655 data. The Tree widget itself is a vertical container for widgets of
9656 type TreeItem. Tree itself is not terribly different from
9657 CList - both are derived directly from Container, and the
9658 Container methods work in the same way on Tree widgets as on
9659 CList widgets. The difference is that Tree widgets can be nested
9660 within other Tree widgets. We'll see how to do this shortly.</para>
9661
9662 <para>The Tree widget has its own window, and defaults to a white
9663 background, as does CList. Also, most of the Tree methods work in
9664 the same way as the corresponding CList ones. However, Tree is
9665 not derived from CList, so you cannot use them interchangeably.</para>
9666
9667 <!-- ----------------------------------------------------------------- -->
9668 <sect1 id="sec-CreatingATree">
9669 <title>Creating a Tree</title>
9670
9671 <para>A Tree is created in the usual way, using:</para>
9672
9673 <programlisting role="C">
9674 GtkWidget *gtk_tree_new( void );
9675 </programlisting>
9676
9677 <para>Like the CList widget, a Tree will simply keep growing as more
9678 items are added to it, as well as when subtrees are expanded.  For
9679 this reason, they are almost always packed into a
9680 ScrolledWindow. You might want to use gtk_widget_set_usize() on the
9681 scrolled window to ensure that it is big enough to see the tree's
9682 items, as the default size for ScrolledWindow is quite small.</para>
9683
9684 <para>Now that you have a tree, you'll probably want to add some items to
9685 it.  <link linkend="sec-TreeItemWidget">The Tree Item Widget</link> below
9686 explains the gory details of TreeItem. For now, it'll suffice to
9687 create one, using:</para>
9688
9689 <programlisting role="C">
9690 GtkWidget *gtk_tree_item_new_with_label( gchar *label );
9691 </programlisting>
9692
9693 <para>You can then add it to the tree using one of the following (see
9694 <link linkend="sec-TreeFunctionsAndMacros">Functions and Macros</link>
9695 below for more options):</para>
9696
9697 <programlisting role="C">
9698 void gtk_tree_append( GtkTree    *tree,
9699                        GtkWidget *tree_item );
9700
9701 void gtk_tree_prepend( GtkTree   *tree,
9702                        GtkWidget *tree_item );
9703 </programlisting>
9704
9705 <para>Note that you must add items to a Tree one at a time - there is no
9706 equivalent to gtk_list_*_items().</para>
9707
9708 </sect1>
9709
9710 <!-- ----------------------------------------------------------------- -->
9711 <sect1 id="sec-AddingASubtree">
9712 <title>Adding a Subtree</title>
9713
9714 <para>A subtree is created like any other Tree widget. A subtree is added
9715 to another tree beneath a tree item, using:</para>
9716
9717 <programlisting role="C">
9718 void gtk_tree_item_set_subtree( GtkTreeItem *tree_item,
9719                                 GtkWidget   *subtree );
9720 </programlisting>
9721
9722 <para>You do not need to call gtk_widget_show() on a subtree before or after
9723 adding it to a TreeItem. However, you <emphasis>must</emphasis> have added the
9724 TreeItem in question to a parent tree before calling
9725 gtk_tree_item_set_subtree(). This is because, technically, the parent
9726 of the subtree is <emphasis>not</emphasis> the GtkTreeItem which "owns" it, but
9727 rather the GtkTree which holds that GtkTreeItem.</para>
9728
9729 <para>When you add a subtree to a TreeItem, a plus or minus sign appears
9730 beside it, which the user can click on to "expand" or "collapse" it,
9731 meaning, to show or hide its subtree. TreeItems are collapsed by
9732 default. Note that when you collapse a TreeItem, any selected
9733 items in its subtree remain selected, which may not be what the user
9734 expects.</para>
9735
9736 </sect1>
9737
9738 <!-- ----------------------------------------------------------------- -->
9739 <sect1 id="sec-HandlingTheSelectionList">
9740 <title>Handling the Selection List</title>
9741
9742 <para>As with CList, the Tree type has a <literal>selection</literal> field, and
9743 it is possible to control the behaviour of the tree (somewhat) by
9744 setting the selection type using:</para>
9745
9746 <programlisting role="C">
9747 void gtk_tree_set_selection_mode( GtkTree          *tree,
9748                                   GtkSelectionMode  mode );
9749 </programlisting>
9750
9751 <para>The semantics associated with the various selection modes are
9752 described in the section on the CList widget. As with the CList
9753 widget, the "select_child", "unselect_child" (not really - see <link
9754 linkend="sec-TreeSignals">Signals</link> below for an explanation),
9755 and "selection_changed" signals are emitted when list items are
9756 selected or unselected. However, in order to take advantage of these
9757 signals, you need to know <emphasis>which</emphasis> Tree widget they will be
9758 emitted by, and where to find the list of selected items.</para>
9759
9760 <para>This is a source of potential confusion. The best way to explain this
9761 is that though all Tree widgets are created equal, some are more equal
9762 than others. All Tree widgets have their own X window, and can
9763 therefore receive events such as mouse clicks (if their TreeItems or
9764 their children don't catch them first!). However, to make
9765 <literal>GTK_SELECTION_SINGLE</literal> and <literal>GTK_SELECTION_BROWSE</literal> selection
9766 types behave in a sane manner, the list of selected items is specific
9767 to the topmost Tree widget in a hierarchy, known as the "root tree".</para>
9768
9769 <para>Thus, accessing the <literal>selection</literal> field directly in an arbitrary
9770 Tree widget is not a good idea unless you <emphasis>know</emphasis> it's the root
9771 tree. Instead, use the <literal>GTK_TREE_SELECTION_OLD (Tree)</literal> macro, which
9772 gives the root tree's selection list as a GList pointer. Of course,
9773 this list can include items that are not in the subtree in question if
9774 the selection type is <literal>GTK_SELECTION_MULTIPLE</literal>.</para>
9775
9776 <para>Finally, the "select_child" (and "unselect_child", in theory) signals
9777 are emitted by all trees, but the "selection_changed" signal is only
9778 emitted by the root tree. Consequently, if you want to handle the
9779 "select_child" signal for a tree and all its subtrees, you will have
9780 to call gtk_signal_connect() for every subtree.</para>
9781
9782 </sect1>
9783
9784 <!-- ----------------------------------------------------------------- -->
9785 <sect1 id="sec-TreeWidgetInternals">
9786 <title>Tree Widget Internals</title>
9787
9788 <para>The Tree's struct definition looks like this:</para>
9789
9790 <programlisting role="C">
9791 struct _GtkTree
9792 {
9793   GtkContainer container;
9794
9795   GList *children;
9796   
9797   GtkTree* root_tree; /* owner of selection list */
9798   GtkWidget* tree_owner;
9799   GList *selection;
9800   guint level;
9801   guint indent_value;
9802   guint current_indent;
9803   guint selection_mode : 2;
9804   guint view_mode : 1;
9805   guint view_line : 1;
9806 };
9807 </programlisting>
9808
9809 <para>The perils associated with accessing the <literal>selection</literal> field
9810 directly have already been mentioned. The other important fields of
9811 the struct can also be accessed with handy macros or class functions.
9812 <literal>GTK_IS_ROOT_TREE (Tree)</literal> returns a boolean value which
9813 indicates whether a tree is the root tree in a Tree hierarchy, while
9814 <literal>GTK_TREE_ROOT_TREE (Tree)</literal> returns the root tree, an object of
9815 type GtkTree (so, remember to cast it using <literal>GTK_WIDGET (Tree)</literal> if
9816 you want to use one of the gtk_widget_*() functions on it).</para>
9817
9818 <para>Instead of directly accessing the children field of a Tree widget,
9819 it's probably best to cast it using >tt/GTK_CONTAINER (Tree)/, and
9820 pass it to the gtk_container_children() function. This creates a
9821 duplicate of the original list, so it's advisable to free it up using
9822 g_list_free() after you're done with it, or to iterate on it
9823 destructively, like this:</para>
9824
9825 <programlisting role="C">
9826     children = gtk_container_children (GTK_CONTAINER (tree));
9827     while (children) {
9828       do_something_nice (GTK_TREE_ITEM (children->data));
9829       children = g_list_remove_link (children, children);
9830 }
9831 </programlisting>
9832
9833 <para>The <literal>tree_owner</literal> field is defined only in subtrees, where it
9834 points to the TreeItem widget which holds the tree in question.
9835 The <literal>level</literal> field indicates how deeply nested a particular tree
9836 is; root trees have level 0, and each successive level of subtrees has
9837 a level one greater than the parent level. This field is set only
9838 after a Tree widget is actually mapped (i.e. drawn on the screen).</para>
9839
9840 <!-- ----------------------------------------------------------------- -->
9841 <sect2 id="sec-TreeSignals">
9842 <title>Signals</title>
9843
9844 <programlisting role="C">
9845 void selection_changed( GtkTree *tree );
9846 </programlisting>
9847
9848 <para>This signal will be emitted whenever the <literal>selection</literal> field of a
9849 Tree has changed. This happens when a child of the Tree is
9850 selected or deselected.</para>
9851
9852 <programlisting role="C">
9853 void select_child( GtkTree   *tree,
9854                    GtkWidget *child );
9855 </programlisting>
9856
9857 <para>This signal is emitted when a child of the Tree is about to get
9858 selected. This happens on calls to gtk_tree_select_item(),
9859 gtk_tree_select_child(), on <emphasis>all</emphasis> button presses and calls to
9860 gtk_tree_item_toggle() and gtk_item_toggle().  It may sometimes be
9861 indirectly triggered on other occasions where children get added to or
9862 removed from the Tree.</para>
9863
9864 <programlisting role="C">
9865 void unselect_child (GtkTree   *tree,
9866                      GtkWidget *child);
9867 </programlisting>
9868
9869 <para>This signal is emitted when a child of the Tree is about to get
9870 deselected. As of GTK 1.0.4, this seems to only occur on calls to
9871 gtk_tree_unselect_item() or gtk_tree_unselect_child(), and perhaps on
9872 other occasions, but <emphasis>not</emphasis> when a button press deselects a
9873 child, nor on emission of the "toggle" signal by gtk_item_toggle().</para>
9874
9875 </sect2>
9876
9877 <!-- ----------------------------------------------------------------- -->
9878 <sect2 id="sec-TreeFunctionsAndMacros">
9879 <title>Functions and Macros</title>
9880
9881 <programlisting role="C">
9882 guint gtk_tree_get_type( void );
9883 </programlisting>
9884
9885 <para>Returns the "GtkTree" type identifier.</para>
9886
9887 <programlisting role="C">
9888 GtkWidget* gtk_tree_new( void );
9889 </programlisting>
9890
9891 <para>Create a new Tree object. The new widget is returned as a pointer to a
9892 GtkWidget object. NULL is returned on failure.</para>
9893
9894 <programlisting role="C">
9895 void gtk_tree_append( GtkTree   *tree,
9896                       GtkWidget *tree_item );
9897 </programlisting>
9898
9899 <para>Append a tree item to a Tree.</para>
9900
9901 <programlisting role="C">
9902 void gtk_tree_prepend( GtkTree   *tree,
9903                        GtkWidget *tree_item );
9904 </programlisting>
9905
9906 <para>Prepend a tree item to a Tree.</para>
9907
9908 <programlisting role="C">
9909 void gtk_tree_insert( GtkTree   *tree,
9910                       GtkWidget *tree_item,
9911                       gint       position );
9912 </programlisting>
9913
9914 <para>Insert a tree item into a Tree at the position in the list
9915 specified by <literal>position.</literal></para>
9916
9917 <programlisting role="C">
9918 void gtk_tree_remove_items( GtkTree *tree,
9919                             GList   *items );
9920 </programlisting>
9921
9922 <para>Remove a list of items (in the form of a GList *) from a Tree.
9923 Note that removing an item from a tree dereferences (and thus usually)
9924 destroys it <emphasis>and</emphasis> its subtree, if it has one, <emphasis>and</emphasis> all
9925 subtrees in that subtree. If you want to remove only one item, you
9926 can use gtk_container_remove().</para>
9927
9928 <programlisting role="C">
9929 void gtk_tree_clear_items( GtkTree *tree,
9930                            gint     start,
9931                            gint     end );
9932 </programlisting>
9933
9934 <para>Remove the items from position <literal>start</literal> to position <literal>end</literal>
9935 from a Tree. The same warning about dereferencing applies here, as
9936 gtk_tree_clear_items() simply constructs a list and passes it to
9937 gtk_tree_remove_items().</para>
9938
9939 <programlisting role="C">
9940 void gtk_tree_select_item( GtkTree *tree,
9941                            gint     item );
9942 </programlisting>
9943
9944 <para>Emits the "select_item" signal for the child at position
9945 <literal>item</literal>, thus selecting the child (unless you unselect it in a
9946 signal handler).</para>
9947
9948 <programlisting role="C">
9949 void gtk_tree_unselect_item( GtkTree *tree,
9950                              gint     item );
9951 </programlisting>
9952
9953 <para>Emits the "unselect_item" signal for the child at position
9954 <literal>item</literal>, thus unselecting the child.</para>
9955
9956 <programlisting role="C">
9957 void gtk_tree_select_child( GtkTree   *tree,
9958                             GtkWidget *tree_item );
9959 </programlisting>
9960
9961 <para>Emits the "select_item" signal for the child <literal>tree_item</literal>, thus
9962 selecting it.</para>
9963
9964 <programlisting role="C">
9965 void gtk_tree_unselect_child( GtkTree   *tree,
9966                               GtkWidget *tree_item );
9967 </programlisting>
9968
9969 <para>Emits the "unselect_item" signal for the child <literal>tree_item</literal>,
9970 thus unselecting it.</para>
9971
9972 <programlisting role="C">
9973 gint gtk_tree_child_position( GtkTree   *tree,
9974                               GtkWidget *child );
9975 </programlisting>
9976
9977 <para>Returns the position in the tree of <literal>child</literal>, unless
9978 <literal>child</literal> is not in the tree, in which case it returns -1.</para>
9979
9980 <programlisting role="C">
9981 void gtk_tree_set_selection_mode( GtkTree          *tree,
9982                                   GtkSelectionMode  mode );
9983 </programlisting>
9984
9985 <para>Sets the selection mode, which can be one of <literal>GTK_SELECTION_SINGLE</literal> (the
9986 default), <literal>GTK_SELECTION_BROWSE</literal>, <literal>GTK_SELECTION_MULTIPLE</literal>, or
9987 <literal>GTK_SELECTION_EXTENDED</literal>. This is only defined for root trees, which
9988 makes sense, since the root tree "owns" the selection. Setting it for
9989 subtrees has no effect at all; the value is simply ignored.</para>
9990
9991 <programlisting role="C">
9992 void gtk_tree_set_view_mode( GtkTree         *tree,
9993                              GtkTreeViewMode  mode ); 
9994 </programlisting>
9995
9996 <para>Sets the "view mode", which can be either <literal>GTK_TREE_VIEW_LINE</literal> (the
9997 default) or <literal>GTK_TREE_VIEW_ITEM</literal>.  The view mode propagates from a
9998 tree to its subtrees, and can't be set exclusively to a subtree (this
9999 is not exactly true - see the example code comments).</para>
10000
10001 <para>The term "view mode" is rather ambiguous - basically, it controls the
10002 way the highlight is drawn when one of a tree's children is selected.
10003 If it's <literal>GTK_TREE_VIEW_LINE</literal>, the entire TreeItem widget is
10004 highlighted, while for <literal>GTK_TREE_VIEW_ITEM</literal>, only the child widget
10005 (i.e., usually the label) is highlighted.</para>
10006
10007 <programlisting role="C">
10008 void gtk_tree_set_view_lines( GtkTree *tree,
10009                               guint    flag );
10010 </programlisting>
10011
10012 <para>Controls whether connecting lines between tree items are drawn.
10013 <literal>flag</literal> is either TRUE, in which case they are, or FALSE, in
10014 which case they aren't.</para>
10015
10016 <programlisting role="C">
10017 GtkTree *GTK_TREE (gpointer obj);
10018 </programlisting>
10019
10020 <para>Cast a generic pointer to "GtkTree *".</para>
10021
10022 <programlisting role="C">
10023 GtkTreeClass *GTK_TREE_CLASS (gpointer class);
10024 </programlisting>
10025
10026 <para>Cast a generic pointer to "GtkTreeClass *".</para>
10027
10028 <programlisting role="C">
10029 gint GTK_IS_TREE (gpointer obj);
10030 </programlisting>
10031
10032 <para>Determine if a generic pointer refers to a "GtkTree" object.</para>
10033
10034 <programlisting role="C">
10035 gint GTK_IS_ROOT_TREE (gpointer obj)
10036 </programlisting>
10037
10038 <para>Determine if a generic pointer refers to a "GtkTree" object
10039 <emphasis>and</emphasis> is a root tree. Though this will accept any pointer, the
10040 results of passing it a pointer that does not refer to a Tree are
10041 undefined and possibly harmful.</para>
10042
10043 <programlisting role="C">
10044 GtkTree *GTK_TREE_ROOT_TREE (gpointer obj)
10045 </programlisting>
10046
10047 <para>Return the root tree of a pointer to a "GtkTree" object. The above
10048 warning applies.</para>
10049
10050 <programlisting role="C">
10051 GList *GTK_TREE_SELECTION_OLD( gpointer obj)
10052 </programlisting>
10053
10054 <para>Return the selection list of the root tree of a "GtkTree" object. The
10055 above warning applies here, too.</para>
10056
10057 </sect2>
10058 </sect1>
10059
10060 <!-- ----------------------------------------------------------------- -->
10061 <sect1 id="sec-TreeItemWidget">
10062 <title>Tree Item Widget</title>
10063
10064 <para>The TreeItem widget, like CListItem, is derived from Item,
10065 which in turn is derived from Bin.  Therefore, the item itself is a
10066 generic container holding exactly one child widget, which can be of
10067 any type. The TreeItem widget has a number of extra fields, but
10068 the only one we need be concerned with is the <literal>subtree</literal> field.</para>
10069
10070 <para>The definition for the TreeItem struct looks like this:</para>
10071
10072 <programlisting role="C">
10073 struct _GtkTreeItem
10074 {
10075   GtkItem item;
10076
10077   GtkWidget *subtree;
10078   GtkWidget *pixmaps_box;
10079   GtkWidget *plus_pix_widget, *minus_pix_widget;
10080
10081   GList *pixmaps;               /* pixmap node for this items color depth */
10082
10083   guint expanded : 1;
10084 };
10085 </programlisting>
10086
10087 <para>The <literal>pixmaps_box</literal> field is an EventBox which catches clicks on
10088 the plus/minus symbol which controls expansion and collapsing. The
10089 <literal>pixmaps</literal> field points to an internal data structure. Since
10090 you can always obtain the subtree of a TreeItem in a (relatively)
10091 type-safe manner with the <literal>GTK_TREE_ITEM_SUBTREE (Item)</literal> macro,
10092 it's probably advisable never to touch the insides of a TreeItem
10093 unless you <emphasis>really</emphasis> know what you're doing.</para>
10094
10095 <para>Since it is directly derived from an Item it can be treated as such by
10096 using the <literal>GTK_ITEM (TreeItem)</literal> macro. A TreeItem usually holds a
10097 label, so the convenience function gtk_list_item_new_with_label() is
10098 provided. The same effect can be achieved using code like the
10099 following, which is actually copied verbatim from
10100 gtk_tree_item_new_with_label():</para>
10101
10102 <programlisting role="C">
10103 tree_item = gtk_tree_item_new ();
10104 label_widget = gtk_label_new (label);
10105 gtk_misc_set_alignment (GTK_MISC (label_widget), 0.0, 0.5);
10106
10107 gtk_container_add (GTK_CONTAINER (tree_item), label_widget);
10108 gtk_widget_show (label_widget);
10109 </programlisting>
10110
10111 <para>As one is not forced to add a Label to a TreeItem, you could
10112 also add an HBox or an Arrow, or even a Notebook (though your
10113 app will likely be quite unpopular in this case) to the TreeItem.</para>
10114
10115 <para>If you remove all the items from a subtree, it will be destroyed and
10116 unparented, unless you reference it beforehand, and the TreeItem
10117 which owns it will be collapsed. So, if you want it to stick around,
10118 do something like the following:</para>
10119
10120 <programlisting role="C">
10121 gtk_widget_ref (tree);
10122 owner = GTK_TREE(tree)->tree_owner;
10123 gtk_container_remove (GTK_CONTAINER(tree), item);
10124 if (tree->parent == NULL){
10125   gtk_tree_item_expand (GTK_TREE_ITEM(owner));
10126   gtk_tree_item_set_subtree (GTK_TREE_ITEM(owner), tree);
10127 }
10128 else
10129   gtk_widget_unref (tree);
10130 </programlisting>
10131
10132 <para>Finally, drag-n-drop <emphasis>does</emphasis> work with TreeItems. You just
10133 have to make sure that the TreeItem you want to make into a drag
10134 item or a drop site has not only been added to a Tree, but that
10135 each successive parent widget has a parent itself, all the way back to
10136 a toplevel or dialog window, when you call gtk_widget_dnd_drag_set()
10137 or gtk_widget_dnd_drop_set().  Otherwise, strange things will happen.</para>
10138
10139 <!-- ----------------------------------------------------------------- -->
10140 <sect2>
10141 <title>Signals</title>
10142
10143 <para>TreeItem inherits the "select", "deselect", and "toggle" signals
10144 from Item. In addition, it adds two signals of its own, "expand"
10145 and "collapse".</para>
10146
10147 <programlisting role="C">
10148 void select( GtkItem *tree_item );
10149 </programlisting>
10150
10151 <para>This signal is emitted when an item is about to be selected, either
10152 after it has been clicked on by the user, or when the program calls
10153 gtk_tree_item_select(), gtk_item_select(), or gtk_tree_select_child().</para>
10154
10155 <programlisting role="C">
10156 void deselect( GtkItem *tree_item );
10157 </programlisting>
10158
10159 <para>This signal is emitted when an item is about to be unselected, either
10160 after it has been clicked on by the user, or when the program calls
10161 gtk_tree_item_deselect() or gtk_item_deselect(). In the case of
10162 TreeItems, it is also emitted by gtk_tree_unselect_child(), and
10163 sometimes gtk_tree_select_child().</para>
10164
10165 <programlisting role="C">
10166 void toggle( GtkItem *tree_item );
10167 </programlisting>
10168
10169 <para>This signal is emitted when the program calls gtk_item_toggle().  The
10170 effect it has when emitted on a TreeItem is to call
10171 gtk_tree_select_child() (and never gtk_tree_unselect_child()) on the
10172 item's parent tree, if the item has a parent tree.  If it doesn't,
10173 then the highlight is reversed on the item.</para>
10174
10175 <programlisting role="C">
10176 void expand( GtkTreeItem *tree_item );
10177 </programlisting>
10178
10179 <para>This signal is emitted when the tree item's subtree is about to be
10180 expanded, that is, when the user clicks on the plus sign next to the
10181 item, or when the program calls gtk_tree_item_expand().</para>
10182
10183 <programlisting role="C">
10184 void collapse( GtkTreeItem *tree_item );
10185 </programlisting>
10186
10187 <para>This signal is emitted when the tree item's subtree is about to be
10188 collapsed, that is, when the user clicks on the minus sign next to the
10189 item, or when the program calls gtk_tree_item_collapse().</para>
10190
10191 </sect2>
10192
10193 <!-- ----------------------------------------------------------------- -->
10194 <sect2>
10195 <title>Functions and Macros</title>
10196
10197 <programlisting role="C">
10198 guint gtk_tree_item_get_type( void );
10199 </programlisting>
10200
10201 <para>Returns the "GtkTreeItem" type identifier.</para>
10202
10203 <programlisting role="C">
10204 GtkWidget* gtk_tree_item_new( void );
10205 </programlisting>
10206
10207 <para>Create a new TreeItem object. The new widget is returned as a
10208 pointer to a GtkWidget object. NULL is returned on failure.</para>
10209
10210 <programlisting role="C">
10211 GtkWidget* gtk_tree_item_new_with_label (gchar       *label);
10212 </programlisting>
10213
10214 <para>Create a new TreeItem object, having a single GtkLabel as the sole
10215 child. The new widget is returned as a pointer to a GtkWidget
10216 object. NULL is returned on failure.</para>
10217
10218 <programlisting role="C">
10219 void gtk_tree_item_select( GtkTreeItem *tree_item );
10220 </programlisting>
10221
10222 <para>This function is basically a wrapper around a call to
10223 <literal>gtk_item_select (GTK_ITEM (tree_item))</literal> which will emit the
10224 select signal.</para>
10225
10226 <programlisting role="C">
10227 void gtk_tree_item_deselect( GtkTreeItem *tree_item );
10228 </programlisting>
10229
10230 <para>This function is basically a wrapper around a call to
10231 gtk_item_deselect (GTK_ITEM (tree_item)) which will emit the deselect
10232 signal.</para>
10233
10234 <programlisting role="C">
10235 void gtk_tree_item_set_subtree( GtkTreeItem *tree_item,
10236                                 GtkWidget   *subtree );
10237 </programlisting>
10238
10239 <para>This function adds a subtree to tree_item, showing it if tree_item is
10240 expanded, or hiding it if tree_item is collapsed. Again, remember that
10241 the tree_item must have already been added to a tree for this to work.</para>
10242
10243 <programlisting role="C">
10244 void gtk_tree_item_remove_subtree( GtkTreeItem *tree_item );
10245 </programlisting>
10246
10247 <para>This removes all of tree_item's subtree's children (thus unreferencing
10248 and destroying it, any of its children's subtrees, and so on...), then
10249 removes the subtree itself, and hides the plus/minus sign.</para>
10250
10251 <programlisting role="C">
10252 void gtk_tree_item_expand( GtkTreeItem *tree_item );
10253 </programlisting>
10254
10255 <para>This emits the "expand" signal on tree_item, which expands it.</para>
10256
10257 <programlisting role="C">
10258 void gtk_tree_item_collapse( GtkTreeItem *tree_item );
10259 </programlisting>
10260
10261 <para>This emits the "collapse" signal on tree_item, which collapses it.</para>
10262
10263 <programlisting role="C">
10264 GtkTreeItem *GTK_TREE_ITEM (gpointer obj)
10265 </programlisting>
10266
10267 <para>Cast a generic pointer to "GtkTreeItem *".</para>
10268
10269 <programlisting role="C">
10270 GtkTreeItemClass *GTK_TREE_ITEM_CLASS (gpointer obj)
10271 </programlisting>
10272
10273 <para>Cast a generic pointer to "GtkTreeItemClass".</para>
10274
10275 <programlisting role="C">
10276 gint GTK_IS_TREE_ITEM (gpointer obj)
10277 </programlisting>
10278
10279 <para>Determine if a generic pointer refers to a "GtkTreeItem" object.</para>
10280
10281 <programlisting role="C">
10282 GtkWidget GTK_TREE_ITEM_SUBTREE (gpointer obj)
10283 </programlisting>
10284
10285 <para>Returns a tree item's subtree (<literal>obj</literal> should point to a
10286 "GtkTreeItem" object).</para>
10287
10288 </sect2>
10289 </sect1>
10290
10291 <!-- ----------------------------------------------------------------- -->
10292 <sect1 id="sec-TreeExample">
10293 <title>Tree Example</title>
10294
10295 <para>This is somewhat like the tree example in testgtk.c, but a lot less
10296 complete (although much better commented).  It puts up a window with a
10297 tree, and connects all the signals for the relevant objects, so you
10298 can see when they are emitted.</para>
10299
10300 <programlisting role="C">
10301 <!-- example-start tree tree.c -->
10302
10303 #define GTK_ENABLE_BROKEN
10304 #include &lt;gtk/gtk.h&gt;
10305
10306 /* for all the GtkItem:: and GtkTreeItem:: signals */
10307 static void cb_itemsignal( GtkWidget *item,
10308                            gchar     *signame )
10309 {
10310   gchar *name;
10311   GtkLabel *label;
10312
10313   /* It's a Bin, so it has one child, which we know to be a
10314      label, so get that */
10315   label = GTK_LABEL (GTK_BIN (item)->child);
10316   /* Get the text of the label */
10317   gtk_label_get (label, &amp;name);
10318   /* Get the level of the tree which the item is in */
10319   g_print ("%s called for item %s->%p, level %d\n", signame, name,
10320            item, GTK_TREE (item->parent)->level);
10321 }
10322
10323 /* Note that this is never called */
10324 static void cb_unselect_child( GtkWidget *root_tree,
10325                                GtkWidget *child,
10326                                GtkWidget *subtree )
10327 {
10328   g_print ("unselect_child called for root tree %p, subtree %p, child %p\n",
10329            root_tree, subtree, child);
10330 }
10331
10332 /* Note that this is called every time the user clicks on an item,
10333    whether it is already selected or not. */
10334 static void cb_select_child (GtkWidget *root_tree, GtkWidget *child,
10335                              GtkWidget *subtree)
10336 {
10337   g_print ("select_child called for root tree %p, subtree %p, child %p\n",
10338            root_tree, subtree, child);
10339 }
10340
10341 static void cb_selection_changed( GtkWidget *tree )
10342 {
10343   GList *i;
10344   
10345   g_print ("selection_change called for tree %p\n", tree);
10346   g_print ("selected objects are:\n");
10347
10348   i = GTK_TREE_SELECTION_OLD(tree);
10349   while (i){
10350     gchar *name;
10351     GtkLabel *label;
10352     GtkWidget *item;
10353
10354     /* Get a GtkWidget pointer from the list node */
10355     item = GTK_WIDGET (i->data);
10356     label = GTK_LABEL (GTK_BIN (item)->child);
10357     gtk_label_get (label, &amp;name);
10358     g_print ("\t%s on level %d\n", name, GTK_TREE
10359              (item->parent)->level);
10360     i = i->next;
10361   }
10362 }
10363
10364 int main( int   argc,
10365           char *argv[] )
10366 {
10367   GtkWidget *window, *scrolled_win, *tree;
10368   static gchar *itemnames[] = {"Foo", "Bar", "Baz", "Quux",
10369                                "Maurice"};
10370   gint i;
10371
10372   gtk_init (&amp;argc, &amp;argv);
10373
10374   /* a generic toplevel window */
10375   window = gtk_window_new (GTK_WINDOW_TOPLEVEL);
10376   gtk_signal_connect (GTK_OBJECT(window), "delete_event",
10377                       GTK_SIGNAL_FUNC (gtk_main_quit), NULL);
10378   gtk_container_set_border_width (GTK_CONTAINER(window), 5);
10379
10380   /* A generic scrolled window */
10381   scrolled_win = gtk_scrolled_window_new (NULL, NULL);
10382   gtk_scrolled_window_set_policy (GTK_SCROLLED_WINDOW (scrolled_win),
10383                                   GTK_POLICY_AUTOMATIC,
10384                                   GTK_POLICY_AUTOMATIC);
10385   gtk_widget_set_usize (scrolled_win, 150, 200);
10386   gtk_container_add (GTK_CONTAINER(window), scrolled_win);
10387   gtk_widget_show (scrolled_win);
10388   
10389   /* Create the root tree */
10390   tree = gtk_tree_new();
10391   g_print ("root tree is %p\n", tree);
10392   /* connect all GtkTree:: signals */
10393   gtk_signal_connect (GTK_OBJECT(tree), "select_child",
10394                       GTK_SIGNAL_FUNC(cb_select_child), tree);
10395   gtk_signal_connect (GTK_OBJECT(tree), "unselect_child",
10396                       GTK_SIGNAL_FUNC(cb_unselect_child), tree);
10397   gtk_signal_connect (GTK_OBJECT(tree), "selection_changed",
10398                       GTK_SIGNAL_FUNC(cb_selection_changed), tree);
10399   /* Add it to the scrolled window */
10400   gtk_scrolled_window_add_with_viewport (GTK_SCROLLED_WINDOW(scrolled_win),
10401                                          tree);
10402   /* Set the selection mode */
10403   gtk_tree_set_selection_mode (GTK_TREE(tree),
10404                                GTK_SELECTION_MULTIPLE);
10405   /* Show it */
10406   gtk_widget_show (tree);
10407
10408   for (i = 0; i < 5; i++){
10409     GtkWidget *subtree, *item;
10410     gint j;
10411
10412     /* Create a tree item */
10413     item = gtk_tree_item_new_with_label (itemnames[i]);
10414     /* Connect all GtkItem:: and GtkTreeItem:: signals */
10415     gtk_signal_connect (GTK_OBJECT(item), "select",
10416                         GTK_SIGNAL_FUNC(cb_itemsignal), "select");
10417     gtk_signal_connect (GTK_OBJECT(item), "deselect",
10418                         GTK_SIGNAL_FUNC(cb_itemsignal), "deselect");
10419     gtk_signal_connect (GTK_OBJECT(item), "toggle",
10420                         GTK_SIGNAL_FUNC(cb_itemsignal), "toggle");
10421     gtk_signal_connect (GTK_OBJECT(item), "expand",
10422                         GTK_SIGNAL_FUNC(cb_itemsignal), "expand");
10423     gtk_signal_connect (GTK_OBJECT(item), "collapse",
10424                         GTK_SIGNAL_FUNC(cb_itemsignal), "collapse");
10425     /* Add it to the parent tree */
10426     gtk_tree_append (GTK_TREE(tree), item);
10427     /* Show it - this can be done at any time */
10428     gtk_widget_show (item);
10429     /* Create this item's subtree */
10430     subtree = gtk_tree_new();
10431     g_print ("-> item %s->%p, subtree %p\n", itemnames[i], item,
10432              subtree);
10433
10434     /* This is still necessary if you want these signals to be called
10435        for the subtree's children.  Note that selection_change will be 
10436        signalled for the root tree regardless. */
10437     gtk_signal_connect (GTK_OBJECT(subtree), "select_child",
10438                         GTK_SIGNAL_FUNC(cb_select_child), subtree);
10439     gtk_signal_connect (GTK_OBJECT(subtree), "unselect_child",
10440                         GTK_SIGNAL_FUNC(cb_unselect_child), subtree);
10441     /* This has absolutely no effect, because it is completely ignored 
10442        in subtrees */
10443     gtk_tree_set_selection_mode (GTK_TREE(subtree),
10444                                  GTK_SELECTION_SINGLE);
10445     /* Neither does this, but for a rather different reason - the
10446        view_mode and view_line values of a tree are propagated to
10447        subtrees when they are mapped.  So, setting it later on would
10448        actually have a (somewhat unpredictable) effect */
10449     gtk_tree_set_view_mode (GTK_TREE(subtree), GTK_TREE_VIEW_ITEM);
10450     /* Set this item's subtree - note that you cannot do this until
10451        AFTER the item has been added to its parent tree! */
10452     gtk_tree_item_set_subtree (GTK_TREE_ITEM(item), subtree);
10453
10454     for (j = 0; j < 5; j++){
10455       GtkWidget *subitem;
10456
10457       /* Create a subtree item, in much the same way */
10458       subitem = gtk_tree_item_new_with_label (itemnames[j]);
10459       /* Connect all GtkItem:: and GtkTreeItem:: signals */
10460       gtk_signal_connect (GTK_OBJECT(subitem), "select",
10461                           GTK_SIGNAL_FUNC(cb_itemsignal), "select");
10462       gtk_signal_connect (GTK_OBJECT(subitem), "deselect",
10463                           GTK_SIGNAL_FUNC(cb_itemsignal), "deselect");
10464       gtk_signal_connect (GTK_OBJECT(subitem), "toggle",
10465                           GTK_SIGNAL_FUNC(cb_itemsignal), "toggle");
10466       gtk_signal_connect (GTK_OBJECT(subitem), "expand",
10467                           GTK_SIGNAL_FUNC(cb_itemsignal), "expand");
10468       gtk_signal_connect (GTK_OBJECT(subitem), "collapse",
10469                           GTK_SIGNAL_FUNC(cb_itemsignal), "collapse");
10470       g_print ("-> -> item %s->%p\n", itemnames[j], subitem);
10471       /* Add it to its parent tree */
10472       gtk_tree_append (GTK_TREE(subtree), subitem);
10473       /* Show it */
10474       gtk_widget_show (subitem);
10475     }
10476   }
10477
10478   /* Show the window and loop endlessly */
10479   gtk_widget_show (window);
10480   gtk_main();
10481   return 0;
10482 }
10483 <!-- example-end -->
10484 </programlisting>
10485
10486 </sect1>
10487 </chapter>
10488
10489 <!-- ***************************************************************** -->
10490 <chapter id="ch-MenuWidget">
10491 <title>Menu Widget</title>
10492
10493 <para>There are two ways to create menus: there's the easy way, and there's
10494 the hard way. Both have their uses, but you can usually use the
10495 Itemfactory (the easy way). The "hard" way is to create all the menus
10496 using the calls directly. The easy way is to use the gtk_item_factory
10497 calls. This is much simpler, but there are advantages and
10498 disadvantages to each approach.</para>
10499
10500 <para>The Itemfactory is much easier to use, and to add new menus to,
10501 although writing a few wrapper functions to create menus using the
10502 manual method could go a long way towards usability. With the
10503 Itemfactory, it is not possible to add images or the character '/' to
10504 the menus.</para>
10505
10506 <!-- ----------------------------------------------------------------- -->
10507 <sect1 id="sec-ManualMenuCreation">
10508 <title>Manual Menu Creation</title>
10509
10510 <para>In the true tradition of teaching, we'll show you the hard way
10511 first. <literal>:)</></para>
10512
10513 <para>There are three widgets that go into making a menubar and submenus:</para>
10514
10515 <itemizedlist>
10516 <listitem><simpara>a menu item, which is what the user wants to select, e.g.,
10517 "Save"</simpara>
10518 </listitem>
10519 <listitem><simpara>a menu, which acts as a container for the menu items, and</simpara>
10520 </listitem>
10521 <listitem><simpara>a menubar, which is a container for each of the individual
10522 menus.</simpara>
10523 </listitem>
10524 </itemizedlist>
10525
10526 <para>This is slightly complicated by the fact that menu item widgets are
10527 used for two different things. They are both the widgets that are
10528 packed into the menu, and the widget that is packed into the menubar,
10529 which, when selected, activates the menu.</para>
10530
10531 <para>Let's look at the functions that are used to create menus and
10532 menubars.  This first function is used to create a new menubar.</para>
10533
10534 <programlisting role="C">
10535 GtkWidget *gtk_menu_bar_new( void );
10536 </programlisting>
10537
10538 <para>This rather self explanatory function creates a new menubar. You use
10539 gtk_container_add to pack this into a window, or the box_pack
10540 functions to pack it into a box - the same as buttons.</para>
10541
10542 <programlisting role="C">
10543 GtkWidget *gtk_menu_new( void );
10544 </programlisting>
10545
10546 <para>This function returns a pointer to a new menu; it is never actually
10547 shown (with gtk_widget_show), it is just a container for the menu
10548 items. I hope this will become more clear when you look at the
10549 example below.</para>
10550
10551 <para>The next two calls are used to create menu items that are packed into
10552 the menu (and menubar).</para>
10553
10554 <programlisting role="C">
10555 GtkWidget *gtk_menu_item_new( void );
10556 </programlisting>
10557
10558 <para>and</para>
10559
10560 <programlisting role="C">
10561 GtkWidget *gtk_menu_item_new_with_label( const char *label );
10562 </programlisting>
10563
10564 <para>These calls are used to create the menu items that are to be
10565 displayed.  Remember to differentiate between a "menu" as created with
10566 gtk_menu_new and a "menu item" as created by the gtk_menu_item_new
10567 functions. The menu item will be an actual button with an associated
10568 action, whereas a menu will be a container holding menu items.</para>
10569
10570 <para>The gtk_menu_new_with_label and gtk_menu_new functions are just as
10571 you'd expect after reading about the buttons. One creates a new menu
10572 item with a label already packed into it, and the other just creates a
10573 blank menu item.</para>
10574
10575 <para>Once you've created a menu item you have to put it into a menu. This
10576 is done using the function gtk_menu_append. In order to capture when
10577 the item is selected by the user, we need to connect to the
10578 <literal>activate</literal> signal in the usual way. So, if we wanted to create a
10579 standard <literal>File</literal> menu, with the options <literal>Open</literal>, <literal>Save</literal>, and
10580 <literal>Quit</literal>, the code would look something like:</para>
10581
10582 <programlisting role="C">
10583     file_menu = gtk_menu_new ();    /* Don't need to show menus */
10584
10585     /* Create the menu items */
10586     open_item = gtk_menu_item_new_with_label ("Open");
10587     save_item = gtk_menu_item_new_with_label ("Save");
10588     quit_item = gtk_menu_item_new_with_label ("Quit");
10589
10590     /* Add them to the menu */
10591     gtk_menu_append (GTK_MENU (file_menu), open_item);
10592     gtk_menu_append (GTK_MENU (file_menu), save_item);
10593     gtk_menu_append (GTK_MENU (file_menu), quit_item);
10594
10595     /* Attach the callback functions to the activate signal */
10596     gtk_signal_connect_object (GTK_OBJECT (open_item), "activate",
10597                                GTK_SIGNAL_FUNC (menuitem_response),
10598                                (gpointer) "file.open");
10599     gtk_signal_connect_object (GTK_OBJECT (save_item), "activate",
10600                                GTK_SIGNAL_FUNC (menuitem_response),
10601                                (gpointer) "file.save");
10602
10603     /* We can attach the Quit menu item to our exit function */
10604     gtk_signal_connect_object (GTK_OBJECT (quit_item), "activate",
10605                                GTK_SIGNAL_FUNC (destroy),
10606                                (gpointer) "file.quit");
10607
10608     /* We do need to show menu items */
10609     gtk_widget_show (open_item);
10610     gtk_widget_show (save_item);
10611     gtk_widget_show (quit_item);
10612 </programlisting>
10613
10614 <para>At this point we have our menu. Now we need to create a menubar and a
10615 menu item for the <literal>File</literal> entry, to which we add our menu. The code
10616 looks like this:</para>
10617
10618 <programlisting role="C">
10619     menu_bar = gtk_menu_bar_new ();
10620     gtk_container_add (GTK_CONTAINER (window), menu_bar);
10621     gtk_widget_show (menu_bar);
10622
10623     file_item = gtk_menu_item_new_with_label ("File");
10624     gtk_widget_show (file_item);
10625 </programlisting>
10626
10627 <para>Now we need to associate the menu with <literal>file_item</literal>. This is done
10628 with the function</para>
10629
10630 <programlisting role="C">
10631 void gtk_menu_item_set_submenu( GtkMenuItem *menu_item,
10632                                 GtkWidget   *submenu );
10633 </programlisting>
10634
10635 <para>So, our example would continue with</para>
10636
10637 <programlisting role="C">
10638     gtk_menu_item_set_submenu (GTK_MENU_ITEM (file_item), file_menu);
10639 </programlisting>
10640
10641 <para>All that is left to do is to add the menu to the menubar, which is
10642 accomplished using the function</para>
10643
10644 <programlisting role="C">
10645 void gtk_menu_bar_append( GtkMenuBar *menu_bar,
10646                           GtkWidget  *menu_item );
10647 </programlisting>
10648
10649 <para>which in our case looks like this:</para>
10650
10651 <programlisting role="C">
10652     gtk_menu_bar_append (GTK_MENU_BAR (menu_bar), file_item);
10653 </programlisting>
10654
10655 <para>If we wanted the menu right justified on the menubar, such as help
10656 menus often are, we can use the following function (again on
10657 <literal>file_item</literal> in the current example) before attaching it to the
10658 menubar.</para>
10659
10660 <programlisting role="C">
10661 void gtk_menu_item_right_justify( GtkMenuItem *menu_item );
10662 </programlisting>
10663
10664 <para>Here is a summary of the steps needed to create a menu bar with menus
10665 attached:</para>
10666
10667 <itemizedlist>
10668 <listitem><simpara> Create a new menu using gtk_menu_new()</simpara>
10669 </listitem>
10670
10671 <listitem><simpara> Use multiple calls to gtk_menu_item_new() for each item you
10672 wish to have on your menu. And use gtk_menu_append() to put each of
10673 these new items on to the menu.</simpara>
10674 </listitem>
10675
10676 <listitem><simpara> Create a menu item using gtk_menu_item_new(). This will be the
10677 root of the menu, the text appearing here will be on the menubar
10678 itself.</simpara>
10679 </listitem>
10680
10681 <listitem><simpara>Use gtk_menu_item_set_submenu() to attach the menu to the root
10682 menu item (the one created in the above step).</simpara>
10683 </listitem>
10684
10685 <listitem><simpara> Create a new menubar using gtk_menu_bar_new. This step only
10686 needs to be done once when creating a series of menus on one menu bar.</simpara>
10687 </listitem>
10688
10689 <listitem><simpara> Use gtk_menu_bar_append() to put the root menu onto the menubar.</simpara>
10690 </listitem>
10691 </itemizedlist>
10692
10693 <para>Creating a popup menu is nearly the same. The difference is that the
10694 menu is not posted "automatically" by a menubar, but explicitly by
10695 calling the function gtk_menu_popup() from a button-press event, for
10696 example.  Take these steps:</para>
10697
10698 <itemizedlist>
10699 <listitem><simpara>Create an event handling function. It needs to have the
10700 prototype</simpara>
10701 <programlisting role="C">
10702 static gint handler (GtkWidget *widget,
10703                      GdkEvent  *event);
10704 </programlisting>
10705 <simpara>and it will use the event to find out where to pop up the menu.</simpara>
10706 </listitem>
10707
10708 <listitem><simpara>In the event handler, if the event is a mouse button press,
10709 treat <literal>event</literal> as a button event (which it is) and use it as
10710 shown in the sample code to pass information to gtk_menu_popup().</simpara>
10711 </listitem>
10712
10713 <listitem><simpara>Bind that event handler to a widget with</simpara>
10714 <programlisting role="C">
10715     gtk_signal_connect_object (GTK_OBJECT (widget), "event",
10716                                GTK_SIGNAL_FUNC (handler),
10717                                GTK_OBJECT (menu));
10718 </programlisting>
10719 <simpara>where <literal>widget</literal> is the widget you are binding to,
10720 <literal>handler</literal> is the handling function, and <literal>menu</literal> is a menu
10721 created with gtk_menu_new(). This can be a menu which is also posted
10722 by a menu bar, as shown in the sample code.</simpara>
10723 </listitem>
10724 </itemizedlist>
10725
10726 </sect1>
10727
10728 <!-- ----------------------------------------------------------------- -->
10729 <sect1 id="sec-ManualMenuExample">
10730 <title>Manual Menu Example</title>
10731
10732 <para>That should about do it. Let's take a look at an example to help clarify.</para>
10733
10734 <programlisting role="C">
10735 <!-- example-start menu menu.c -->
10736
10737 #include &lt;stdio.h&gt;
10738 #include &lt;gtk/gtk.h&gt;
10739
10740 static gint button_press (GtkWidget *, GdkEvent *);
10741 static void menuitem_response (gchar *);
10742
10743 int main( int   argc,
10744           char *argv[] )
10745 {
10746
10747     GtkWidget *window;
10748     GtkWidget *menu;
10749     GtkWidget *menu_bar;
10750     GtkWidget *root_menu;
10751     GtkWidget *menu_items;
10752     GtkWidget *vbox;
10753     GtkWidget *button;
10754     char buf[128];
10755     int i;
10756
10757     gtk_init (&amp;argc, &amp;argv);
10758
10759     /* create a new window */
10760     window = gtk_window_new (GTK_WINDOW_TOPLEVEL);
10761     gtk_widget_set_usize (GTK_WIDGET (window), 200, 100);
10762     gtk_window_set_title (GTK_WINDOW (window), "GTK Menu Test");
10763     gtk_signal_connect (GTK_OBJECT (window), "delete_event",
10764                         (GtkSignalFunc) gtk_main_quit, NULL);
10765
10766     /* Init the menu-widget, and remember -- never
10767      * gtk_show_widget() the menu widget!! 
10768      * This is the menu that holds the menu items, the one that
10769      * will pop up when you click on the "Root Menu" in the app */
10770     menu = gtk_menu_new ();
10771
10772     /* Next we make a little loop that makes three menu-entries for "test-menu".
10773      * Notice the call to gtk_menu_append.  Here we are adding a list of
10774      * menu items to our menu.  Normally, we'd also catch the "clicked"
10775      * signal on each of the menu items and setup a callback for it,
10776      * but it's omitted here to save space. */
10777
10778     for (i = 0; i < 3; i++)
10779         {
10780             /* Copy the names to the buf. */
10781             sprintf (buf, "Test-undermenu - %d", i);
10782
10783             /* Create a new menu-item with a name... */
10784             menu_items = gtk_menu_item_new_with_label (buf);
10785
10786             /* ...and add it to the menu. */
10787             gtk_menu_append (GTK_MENU (menu), menu_items);
10788
10789             /* Do something interesting when the menuitem is selected */
10790             gtk_signal_connect_object (GTK_OBJECT (menu_items), "activate",
10791                 GTK_SIGNAL_FUNC (menuitem_response), (gpointer) g_strdup (buf));
10792
10793             /* Show the widget */
10794             gtk_widget_show (menu_items);
10795         }
10796
10797     /* This is the root menu, and will be the label
10798      * displayed on the menu bar.  There won't be a signal handler attached,
10799      * as it only pops up the rest of the menu when pressed. */
10800     root_menu = gtk_menu_item_new_with_label ("Root Menu");
10801
10802     gtk_widget_show (root_menu);
10803
10804     /* Now we specify that we want our newly created "menu" to be the menu
10805      * for the "root menu" */
10806     gtk_menu_item_set_submenu (GTK_MENU_ITEM (root_menu), menu);
10807
10808     /* A vbox to put a menu and a button in: */
10809     vbox = gtk_vbox_new (FALSE, 0);
10810     gtk_container_add (GTK_CONTAINER (window), vbox);
10811     gtk_widget_show (vbox);
10812
10813     /* Create a menu-bar to hold the menus and add it to our main window */
10814     menu_bar = gtk_menu_bar_new ();
10815     gtk_box_pack_start (GTK_BOX (vbox), menu_bar, FALSE, FALSE, 2);
10816     gtk_widget_show (menu_bar);
10817
10818     /* Create a button to which to attach menu as a popup */
10819     button = gtk_button_new_with_label ("press me");
10820     gtk_signal_connect_object (GTK_OBJECT (button), "event",
10821         GTK_SIGNAL_FUNC (button_press), GTK_OBJECT (menu));
10822     gtk_box_pack_end (GTK_BOX (vbox), button, TRUE, TRUE, 2);
10823     gtk_widget_show (button);
10824
10825     /* And finally we append the menu-item to the menu-bar -- this is the
10826      * "root" menu-item I have been raving about =) */
10827     gtk_menu_bar_append (GTK_MENU_BAR (menu_bar), root_menu);
10828
10829     /* always display the window as the last step so it all splashes on
10830      * the screen at once. */
10831     gtk_widget_show (window);
10832
10833     gtk_main ();
10834
10835     return(0);
10836 }
10837
10838 /* Respond to a button-press by posting a menu passed in as widget.
10839  *
10840  * Note that the "widget" argument is the menu being posted, NOT
10841  * the button that was pressed.
10842  */
10843
10844 static gint button_press( GtkWidget *widget,
10845                           GdkEvent *event )
10846 {
10847
10848     if (event->type == GDK_BUTTON_PRESS) {
10849         GdkEventButton *bevent = (GdkEventButton *) event; 
10850         gtk_menu_popup (GTK_MENU (widget), NULL, NULL, NULL, NULL,
10851                         bevent->button, bevent->time);
10852         /* Tell calling code that we have handled this event; the buck
10853          * stops here. */
10854         return TRUE;
10855     }
10856
10857     /* Tell calling code that we have not handled this event; pass it on. */
10858     return FALSE;
10859 }
10860
10861
10862 /* Print a string when a menu item is selected */
10863
10864 static void menuitem_response( gchar *string )
10865 {
10866     printf ("%s\n", string);
10867 }
10868 <!-- example-end -->
10869 </programlisting>
10870
10871 <para>You may also set a menu item to be insensitive and, using an accelerator
10872 table, bind keys to menu functions.</para>
10873
10874 </sect1>
10875
10876 <!-- ----------------------------------------------------------------- -->
10877 <sect1 id="sec-UsingItemFactory">
10878 <title>Using ItemFactory</title>
10879
10880 <para>Now that we've shown you the hard way, here's how you do it using the
10881 gtk_item_factory calls.</para>
10882
10883 </sect1>
10884
10885 <!-- ----------------------------------------------------------------- -->
10886 <sect1 id="sec-ItemFactoryExample">
10887 <title>Item Factory Example</title>
10888
10889 <para>Here is an example using the GTK item factory.</para>
10890
10891 <programlisting role="C">
10892 <!-- example-start menu itemfactory.c -->
10893
10894 #include &lt;gtk/gtk.h&gt;
10895 #include &lt;strings.h&gt;
10896
10897 /* Obligatory basic callback */
10898 static void print_hello( GtkWidget *w,
10899                          gpointer   data )
10900 {
10901   g_message ("Hello, World!\n");
10902 }
10903
10904 /* This is the GtkItemFactoryEntry structure used to generate new menus.
10905    Item 1: The menu path. The letter after the underscore indicates an
10906            accelerator key once the menu is open.
10907    Item 2: The accelerator key for the entry
10908    Item 3: The callback function.
10909    Item 4: The callback action.  This changes the parameters with
10910            which the function is called.  The default is 0.
10911    Item 5: The item type, used to define what kind of an item it is.
10912            Here are the possible values:
10913
10914            NULL               -> "&lt;Item>"
10915            ""                 -> "&lt;Item>"
10916            "&lt;Title>"          -> create a title item
10917            "&lt;Item>"           -> create a simple item
10918            "&lt;CheckItem>"      -> create a check item
10919            "&lt;ToggleItem>"     -> create a toggle item
10920            "&lt;RadioItem>"      -> create a radio item
10921            &lt;path>             -> path of a radio item to link against
10922            "&lt;Separator>"      -> create a separator
10923            "&lt;Branch>"         -> create an item to hold sub items (optional)
10924            "&lt;LastBranch>"     -> create a right justified branch 
10925 */
10926
10927 static GtkItemFactoryEntry menu_items[] = {
10928   { "/_File",         NULL,         NULL, 0, "&lt;Branch>" },
10929   { "/File/_New",     "&lt;control>N", print_hello, 0, NULL },
10930   { "/File/_Open",    "&lt;control>O", print_hello, 0, NULL },
10931   { "/File/_Save",    "&lt;control>S", print_hello, 0, NULL },
10932   { "/File/Save _As", NULL,         NULL, 0, NULL },
10933   { "/File/sep1",     NULL,         NULL, 0, "&lt;Separator>" },
10934   { "/File/Quit",     "&lt;control>Q", gtk_main_quit, 0, NULL },
10935   { "/_Options",      NULL,         NULL, 0, "&lt;Branch>" },
10936   { "/Options/Test",  NULL,         NULL, 0, NULL },
10937   { "/_Help",         NULL,         NULL, 0, "&lt;LastBranch>" },
10938   { "/_Help/About",   NULL,         NULL, 0, NULL },
10939 };
10940
10941
10942 void get_main_menu( GtkWidget  *window,
10943                     GtkWidget **menubar )
10944 {
10945   GtkItemFactory *item_factory;
10946   GtkAccelGroup *accel_group;
10947   gint nmenu_items = sizeof (menu_items) / sizeof (menu_items[0]);
10948
10949   accel_group = gtk_accel_group_new ();
10950
10951   /* This function initializes the item factory.
10952      Param 1: The type of menu - can be GTK_TYPE_MENU_BAR, GTK_TYPE_MENU,
10953               or GTK_TYPE_OPTION_MENU.
10954      Param 2: The path of the menu.
10955      Param 3: A pointer to a gtk_accel_group.  The item factory sets up
10956               the accelerator table while generating menus.
10957   */
10958
10959   item_factory = gtk_item_factory_new (GTK_TYPE_MENU_BAR, "&lt;main>", 
10960                                        accel_group);
10961
10962   /* This function generates the menu items. Pass the item factory,
10963      the number of items in the array, the array itself, and any
10964      callback data for the the menu items. */
10965   gtk_item_factory_create_items (item_factory, nmenu_items, menu_items, NULL);
10966
10967   /* Attach the new accelerator group to the window. */
10968   gtk_window_add_accel_group (GTK_WINDOW (window), accel_group);
10969
10970   if (menubar)
10971     /* Finally, return the actual menu bar created by the item factory. */ 
10972     *menubar = gtk_item_factory_get_widget (item_factory, "&lt;main>");
10973 }
10974
10975 int main( int argc,
10976           char *argv[] )
10977 {
10978   GtkWidget *window;
10979   GtkWidget *main_vbox;
10980   GtkWidget *menubar;
10981   
10982   gtk_init (&amp;argc, &amp;argv);
10983   
10984   window = gtk_window_new (GTK_WINDOW_TOPLEVEL);
10985   gtk_signal_connect (GTK_OBJECT (window), "destroy", 
10986                       GTK_SIGNAL_FUNC (gtk_main_quit), 
10987                       "WM destroy");
10988   gtk_window_set_title (GTK_WINDOW(window), "Item Factory");
10989   gtk_widget_set_usize (GTK_WIDGET(window), 300, 200);
10990   
10991   main_vbox = gtk_vbox_new (FALSE, 1);
10992   gtk_container_border_width (GTK_CONTAINER (main_vbox), 1);
10993   gtk_container_add (GTK_CONTAINER (window), main_vbox);
10994   gtk_widget_show (main_vbox);
10995   
10996   get_main_menu (window, &amp;menubar);
10997   gtk_box_pack_start (GTK_BOX (main_vbox), menubar, FALSE, TRUE, 0);
10998   gtk_widget_show (menubar);
10999   
11000   gtk_widget_show (window);
11001   gtk_main ();
11002   
11003   return(0);
11004 }
11005 <!-- example-end -->
11006 </programlisting>
11007
11008 <para>For now, there's only this example. An explanation and lots 'o' comments
11009 will follow later.</para>
11010
11011 </sect1>
11012 </chapter>
11013
11014 <!-- ***************************************************************** -->
11015 <chapter id="ch-TextWidget">
11016 <title>Text Widget</title>
11017
11018 <para>The Text widget allows multiple lines of text to be displayed and
11019 edited. It supports both multi-colored and multi-font text, allowing
11020 them to be mixed in any way we wish. It also has a wide set of key
11021 based text editing commands, which are compatible with Emacs.</para>
11022
11023 <para>The text widget supports full cut-and-paste facilities, including the
11024 use of double- and triple-click to select a word and a whole line,
11025 respectively.</para>
11026
11027 <!-- ----------------------------------------------------------------- -->
11028 <sect1 id="sec-CreatingAndConfiguringATextBox">
11029 <title>Creating and Configuring a Text box</title>
11030
11031 <para>There is only one function for creating a new Text widget.</para>
11032
11033 <programlisting role="C">
11034 GtkWidget *gtk_text_new( GtkAdjustment *hadj,
11035                          GtkAdjustment *vadj );
11036 </programlisting>
11037
11038 <para>The arguments allow us to give the Text widget pointers to Adjustments
11039 that can be used to track the viewing position of the widget. Passing
11040 NULL values to either or both of these arguments will cause the
11041 gtk_text_new function to create its own.</para>
11042
11043 <programlisting role="C">
11044 void gtk_text_set_adjustments( GtkText       *text,
11045                                GtkAdjustment *hadj,
11046                                GtkAdjustment *vadj );
11047 </programlisting>
11048
11049 <para>The above function allows the horizontal and vertical adjustments of a
11050 text widget to be changed at any time.</para>
11051
11052 <para>The text widget will not automatically create its own scrollbars when
11053 the amount of text to be displayed is too long for the display
11054 window. We therefore have to create and add them to the display layout
11055 ourselves.</para>
11056
11057 <programlisting role="C">
11058   vscrollbar = gtk_vscrollbar_new (GTK_TEXT(text)->vadj);
11059   gtk_box_pack_start(GTK_BOX(hbox), vscrollbar, FALSE, FALSE, 0);
11060   gtk_widget_show (vscrollbar);
11061 </programlisting>
11062
11063 <para>The above code snippet creates a new vertical scrollbar, and attaches
11064 it to the vertical adjustment of the text widget, <literal>text</literal>. It then
11065 packs it into a box in the normal way.</para>
11066
11067 <para>Note, currently the Text widget does not support horizontal
11068 scrollbars.</para>
11069
11070 <para>There are two main ways in which a Text widget can be used: to allow
11071 the user to edit a body of text, or to allow us to display multiple
11072 lines of text to the user. In order for us to switch between these
11073 modes of operation, the text widget has the following function:</para>
11074
11075 <programlisting role="C">
11076 void gtk_text_set_editable( GtkText *text,
11077                             gint     editable );
11078 </programlisting>
11079
11080 <para>The <literal>editable</literal> argument is a TRUE or FALSE value that specifies
11081 whether the user is permitted to edit the contents of the Text
11082 widget. When the text widget is editable, it will display a cursor at
11083 the current insertion point.</para>
11084
11085 <para>You are not, however, restricted to just using the text widget in
11086 these two modes. You can toggle the editable state of the text widget
11087 at any time, and can insert text at any time.</para>
11088
11089 <para>The text widget wraps lines of text that are too long to fit onto a
11090 single line of the display window. Its default behaviour is to break
11091 words across line breaks. This can be changed using the next function:</para>
11092
11093 <programlisting role="C">
11094 void gtk_text_set_word_wrap( GtkText *text,
11095                              gint     word_wrap );
11096 </programlisting>
11097
11098 <para>Using this function allows us to specify that the text widget should
11099 wrap long lines on word boundaries. The <literal>word_wrap</literal> argument is a
11100 TRUE or FALSE value.</para>
11101
11102 </sect1>
11103
11104 <!-- ----------------------------------------------------------------- -->
11105 <sect1 id="sec-TextManipulation">
11106 <title>Text Manipulation</title>
11107
11108 <para>The current insertion point of a Text widget can be set using</para>
11109
11110 <programlisting role="C">
11111 void gtk_text_set_point( GtkText *text,
11112                          guint    index );
11113 </programlisting>
11114
11115 <para>where <literal>index</literal> is the position to set the insertion point.</para>
11116
11117 <para>Analogous to this is the function for getting the current insertion
11118 point:</para>
11119
11120 <programlisting role="C">
11121 guint gtk_text_get_point( GtkText *text );
11122 </programlisting>
11123
11124 <para>A function that is useful in combination with the above two functions
11125 is</para>
11126
11127 <programlisting role="C">
11128 guint gtk_text_get_length( GtkText *text );
11129 </programlisting>
11130
11131 <para>which returns the current length of the Text widget. The length is the
11132 number of characters that are within the text block of the widget,
11133 including characters such as newline, which marks the end of
11134 lines.</para>
11135
11136 <para>In order to insert text at the current insertion point of a Text
11137 widget, the function gtk_text_insert is used, which also allows us to
11138 specify background and foreground colors and a font for the text.</para>
11139
11140 <programlisting role="C">
11141 void gtk_text_insert( GtkText    *text,
11142                       GdkFont    *font,
11143                       GdkColor   *fore,
11144                       GdkColor   *back,
11145                       const char *chars,
11146                       gint        length );
11147 </programlisting>
11148
11149 <para>Passing a value of <literal>NULL</literal> in as the value for the foreground color,
11150 background color or font will result in the values set within the
11151 widget style to be used. Using a value of <literal>-1</literal> for the length
11152 parameter will result in the whole of the text string given being
11153 inserted.</para>
11154
11155 <para>The text widget is one of the few within GTK that redraws itself
11156 dynamically, outside of the gtk_main function. This means that all
11157 changes to the contents of the text widget take effect
11158 immediately. This may be undesirable when performing multiple changes
11159 to the text widget. In order to allow us to perform multiple updates
11160 to the text widget without it continuously redrawing, we can freeze
11161 the widget, which temporarily stops it from automatically redrawing
11162 itself every time it is changed. We can then thaw the widget after our
11163 updates are complete.</para>
11164
11165 <para>The following two functions perform this freeze and thaw action:</para>
11166
11167 <programlisting role="C">
11168 void gtk_text_freeze( GtkText *text );
11169
11170 void gtk_text_thaw( GtkText *text );         
11171 </programlisting>
11172
11173 <para>Text is deleted from the text widget relative to the current insertion
11174 point by the following two functions. The return value is a TRUE or
11175 FALSE indicator of whether the operation was successful.</para>
11176
11177 <programlisting role="C">
11178 gint gtk_text_backward_delete( GtkText *text,
11179                                guint    nchars );
11180
11181 gint gtk_text_forward_delete ( GtkText *text,
11182                                guint    nchars );
11183 </programlisting>
11184
11185 <para>If you want to retrieve the contents of the text widget, then the
11186 macro <literal>GTK_TEXT_INDEX(t, index)</literal> allows you to retrieve the
11187 character at position <literal>index</literal> within the text widget <literal>t</literal>.</para>
11188
11189 <para>To retrieve larger blocks of text, we can use the function</para>
11190
11191 <programlisting role="C">
11192 gchar *gtk_editable_get_chars( GtkEditable *editable,
11193                                gint         start_pos,
11194                                gint         end_pos );   
11195 </programlisting>
11196
11197 <para>This is a function of the parent class of the text widget. A value of
11198 -1 as <literal>end_pos</literal> signifies the end of the text. The index of the
11199 text starts at 0.</para>
11200
11201 <para>The function allocates a new chunk of memory for the text block, so
11202 don't forget to free it with a call to g_free when you have finished
11203 with it.</para>
11204  
11205 </sect1>
11206
11207 <!-- ----------------------------------------------------------------- -->
11208 <sect1 id="sec-KeyBoardShortcuts">
11209 <title>Keyboard Shortcuts</title>
11210
11211 <para>The text widget has a number of pre-installed keyboard shortcuts for
11212 common editing, motion and selection functions. These are accessed
11213 using Control and Alt key combinations.</para>
11214
11215 <para>In addition to these, holding down the Control key whilst using cursor
11216 key movement will move the cursor by words rather than
11217 characters. Holding down Shift whilst using cursor movement will
11218 extend the selection.</para>
11219
11220 <!-- ----------------------------------------------------------------- -->
11221 <sect2>
11222 <title>Motion Shortcuts</title>
11223
11224 <itemizedlist spacing=compact>
11225 <listitem><simpara> Ctrl-A   Beginning of line</simpara>
11226 </listitem>
11227 <listitem><simpara> Ctrl-E   End of line</simpara>
11228 </listitem>
11229 <listitem><simpara> Ctrl-N   Next Line</simpara>
11230 </listitem>
11231 <listitem><simpara> Ctrl-P   Previous Line</simpara>
11232 </listitem>
11233 <listitem><simpara> Ctrl-B   Backward one character</simpara>
11234 </listitem>
11235 <listitem><simpara> Ctrl-F   Forward one character</simpara>
11236 </listitem>
11237 <listitem><simpara> Alt-B    Backward one word</simpara>
11238 </listitem>
11239 <listitem><simpara> Alt-F    Forward one word</simpara>
11240 </listitem>
11241 </itemizedlist>
11242
11243 </sect2>
11244
11245 <!-- ----------------------------------------------------------------- -->
11246 <sect2>
11247 <title>Editing Shortcuts</title>
11248
11249 <itemizedlist spacing=compact>
11250 <listitem><simpara> Ctrl-H   Delete Backward Character (Backspace)</simpara>
11251 </listitem>
11252 <listitem><simpara> Ctrl-D   Delete Forward Character (Delete)</simpara>
11253 </listitem>
11254 <listitem><simpara> Ctrl-W   Delete Backward Word</simpara>
11255 </listitem>
11256 <listitem><simpara> Alt-D    Delete Forward Word</simpara>
11257 </listitem>
11258 <listitem><simpara> Ctrl-K   Delete to end of line</simpara>
11259 </listitem>
11260 <listitem><simpara> Ctrl-U   Delete line</simpara>
11261 </listitem>
11262 </itemizedlist>
11263
11264 </sect2>
11265
11266 <!-- ----------------------------------------------------------------- -->
11267 <sect2>
11268 <title>Selection Shortcuts</title>
11269
11270 <itemizedlist spacing=compact>
11271 <listitem><simpara> Ctrl-X   Cut to clipboard</simpara>
11272 </listitem>
11273 <listitem><simpara> Ctrl-C   Copy to clipboard</simpara>
11274 </listitem>
11275 <listitem><simpara> Ctrl-V   Paste from clipboard</simpara>
11276 </listitem>
11277 </itemizedlist>
11278
11279 </sect2>
11280 </sect1>
11281
11282 <!-- ----------------------------------------------------------------- -->
11283 <sect1 id="sec-AGtkTextExample">
11284 <title>A GtkText Example</title>
11285
11286 <programlisting role="C">
11287 <!-- example-start text text.c -->
11288
11289 /* text.c */
11290
11291 #define GTK_ENABLE_BROKEN
11292 #include &lt;stdio.h&gt;
11293 #include &lt;gtk/gtk.h&gt;
11294
11295 void text_toggle_editable (GtkWidget *checkbutton,
11296                            GtkWidget *text)
11297 {
11298   gtk_text_set_editable(GTK_TEXT(text),
11299                         GTK_TOGGLE_BUTTON(checkbutton)->active);
11300 }
11301
11302 void text_toggle_word_wrap (GtkWidget *checkbutton,
11303                             GtkWidget *text)
11304 {
11305   gtk_text_set_word_wrap(GTK_TEXT(text),
11306                          GTK_TOGGLE_BUTTON(checkbutton)->active);
11307 }
11308
11309 void close_application( GtkWidget *widget,
11310                         gpointer   data )
11311 {
11312        gtk_main_quit();
11313 }
11314
11315 int main( int argc,
11316           char *argv[] )
11317 {
11318   GtkWidget *window;
11319   GtkWidget *box1;
11320   GtkWidget *box2;
11321   GtkWidget *hbox;
11322   GtkWidget *button;
11323   GtkWidget *check;
11324   GtkWidget *separator;
11325   GtkWidget *table;
11326   GtkWidget *vscrollbar;
11327   GtkWidget *text;
11328   GdkColormap *cmap;
11329   GdkColor color;
11330   GdkFont *fixed_font;
11331
11332   FILE *infile;
11333
11334   gtk_init (&amp;argc, &amp;argv);
11335  
11336   window = gtk_window_new (GTK_WINDOW_TOPLEVEL);
11337   gtk_widget_set_usize (window, 600, 500);
11338   gtk_window_set_policy (GTK_WINDOW(window), TRUE, TRUE, FALSE);  
11339   gtk_signal_connect (GTK_OBJECT (window), "destroy",
11340                       GTK_SIGNAL_FUNC(close_application),
11341                       NULL);
11342   gtk_window_set_title (GTK_WINDOW (window), "Text Widget Example");
11343   gtk_container_set_border_width (GTK_CONTAINER (window), 0);
11344   
11345   
11346   box1 = gtk_vbox_new (FALSE, 0);
11347   gtk_container_add (GTK_CONTAINER (window), box1);
11348   gtk_widget_show (box1);
11349   
11350   
11351   box2 = gtk_vbox_new (FALSE, 10);
11352   gtk_container_set_border_width (GTK_CONTAINER (box2), 10);
11353   gtk_box_pack_start (GTK_BOX (box1), box2, TRUE, TRUE, 0);
11354   gtk_widget_show (box2);
11355   
11356   
11357   table = gtk_table_new (2, 2, FALSE);
11358   gtk_table_set_row_spacing (GTK_TABLE (table), 0, 2);
11359   gtk_table_set_col_spacing (GTK_TABLE (table), 0, 2);
11360   gtk_box_pack_start (GTK_BOX (box2), table, TRUE, TRUE, 0);
11361   gtk_widget_show (table);
11362   
11363   /* Create the GtkText widget */
11364   text = gtk_text_new (NULL, NULL);
11365   gtk_text_set_editable (GTK_TEXT (text), TRUE);
11366   gtk_table_attach (GTK_TABLE (table), text, 0, 1, 0, 1,
11367                     GTK_EXPAND | GTK_SHRINK | GTK_FILL,
11368                     GTK_EXPAND | GTK_SHRINK | GTK_FILL, 0, 0);
11369   gtk_widget_show (text);
11370
11371   /* Add a vertical scrollbar to the GtkText widget */
11372   vscrollbar = gtk_vscrollbar_new (GTK_TEXT (text)->vadj);
11373   gtk_table_attach (GTK_TABLE (table), vscrollbar, 1, 2, 0, 1,
11374                     GTK_FILL, GTK_EXPAND | GTK_SHRINK | GTK_FILL, 0, 0);
11375   gtk_widget_show (vscrollbar);
11376
11377   /* Get the system color map and allocate the color red */
11378   cmap = gdk_colormap_get_system();
11379   color.red = 0xffff;
11380   color.green = 0;
11381   color.blue = 0;
11382   if (!gdk_color_alloc(cmap, &amp;color)) {
11383     g_error("couldn't allocate color");
11384   }
11385
11386   /* Load a fixed font */
11387   fixed_font = gdk_font_load ("-misc-fixed-medium-r-*-*-*-140-*-*-*-*-*-*");
11388
11389   /* Realizing a widget creates a window for it,
11390    * ready for us to insert some text */
11391   gtk_widget_realize (text);
11392
11393   /* Freeze the text widget, ready for multiple updates */
11394   gtk_text_freeze (GTK_TEXT (text));
11395   
11396   /* Insert some colored text */
11397   gtk_text_insert (GTK_TEXT (text), NULL, &amp;text->style->black, NULL,
11398                    "Supports ", -1);
11399   gtk_text_insert (GTK_TEXT (text), NULL, &amp;color, NULL,
11400                    "colored ", -1);
11401   gtk_text_insert (GTK_TEXT (text), NULL, &amp;text->style->black, NULL,
11402                    "text and different ", -1);
11403   gtk_text_insert (GTK_TEXT (text), fixed_font, &amp;text->style->black, NULL,
11404                    "fonts\n\n", -1);
11405   
11406   /* Load the file text.c into the text window */
11407
11408   infile = fopen("text.c", "r");
11409   
11410   if (infile) {
11411     char buffer[1024];
11412     int nchars;
11413     
11414     while (1)
11415       {
11416         nchars = fread(buffer, 1, 1024, infile);
11417         gtk_text_insert (GTK_TEXT (text), fixed_font, NULL,
11418                          NULL, buffer, nchars);
11419         
11420         if (nchars < 1024)
11421           break;
11422       }
11423     
11424     fclose (infile);
11425   }
11426
11427   /* Thaw the text widget, allowing the updates to become visible */  
11428   gtk_text_thaw (GTK_TEXT (text));
11429   
11430   hbox = gtk_hbutton_box_new ();
11431   gtk_box_pack_start (GTK_BOX (box2), hbox, FALSE, FALSE, 0);
11432   gtk_widget_show (hbox);
11433
11434   check = gtk_check_button_new_with_label("Editable");
11435   gtk_box_pack_start (GTK_BOX (hbox), check, FALSE, FALSE, 0);
11436   gtk_signal_connect (GTK_OBJECT(check), "toggled",
11437                       GTK_SIGNAL_FUNC(text_toggle_editable), text);
11438   gtk_toggle_button_set_active(GTK_TOGGLE_BUTTON(check), TRUE);
11439   gtk_widget_show (check);
11440   check = gtk_check_button_new_with_label("Wrap Words");
11441   gtk_box_pack_start (GTK_BOX (hbox), check, FALSE, TRUE, 0);
11442   gtk_signal_connect (GTK_OBJECT(check), "toggled",
11443                       GTK_SIGNAL_FUNC(text_toggle_word_wrap), text);
11444   gtk_toggle_button_set_active(GTK_TOGGLE_BUTTON(check), FALSE);
11445   gtk_widget_show (check);
11446
11447   separator = gtk_hseparator_new ();
11448   gtk_box_pack_start (GTK_BOX (box1), separator, FALSE, TRUE, 0);
11449   gtk_widget_show (separator);
11450
11451   box2 = gtk_vbox_new (FALSE, 10);
11452   gtk_container_set_border_width (GTK_CONTAINER (box2), 10);
11453   gtk_box_pack_start (GTK_BOX (box1), box2, FALSE, TRUE, 0);
11454   gtk_widget_show (box2);
11455   
11456   button = gtk_button_new_with_label ("close");
11457   gtk_signal_connect (GTK_OBJECT (button), "clicked",
11458                       GTK_SIGNAL_FUNC(close_application),
11459                       NULL);
11460   gtk_box_pack_start (GTK_BOX (box2), button, TRUE, TRUE, 0);
11461   GTK_WIDGET_SET_FLAGS (button, GTK_CAN_DEFAULT);
11462   gtk_widget_grab_default (button);
11463   gtk_widget_show (button);
11464
11465   gtk_widget_show (window);
11466
11467   gtk_main ();
11468   
11469   return(0);       
11470 }
11471 <!-- example-end -->
11472 </programlisting>
11473
11474 </sect1>
11475 </chapter>
11476
11477 <!-- ***************************************************************** -->
11478 <chapter id="ch-UndocWidgets">
11479 <title>Undocumented Widgets</title>
11480
11481 <para>These all require authors! :) Please consider contributing to our
11482 tutorial.</para>
11483
11484 <para>If you must use one of these widgets that are undocumented, I strongly
11485 suggest you take a look at their respective header files in the GTK
11486 distribution. GTK's function names are very descriptive. Once you
11487 have an understanding of how things work, it's not difficult to figure
11488 out how to use a widget simply by looking at its function
11489 declarations. This, along with a few examples from others' code, and
11490 it should be no problem.</para>
11491
11492 <para>When you do come to understand all the functions of a new undocumented
11493 widget, please consider writing a tutorial on it so others may benefit
11494 from your time.</para>
11495
11496 <!-- ----------------------------------------------------------------- -->
11497 <sect1 id="sec-Curves">
11498 <title>Curves</title>
11499
11500 <para></para>
11501
11502 </sect1>
11503
11504 <!-- ----------------------------------------------------------------- -->
11505 <sect1 id="sec-DrawingArea">
11506 <title>Drawing Area</title>
11507
11508 <para></para>
11509
11510 </sect1>
11511
11512 <!-- ----------------------------------------------------------------- -->
11513 <sect1 id="sec-FontSelectionDialog">
11514 <title>Font Selection Dialog</title>
11515
11516 <para></para>
11517
11518 </sect1>
11519
11520 <!-- ----------------------------------------------------------------- -->
11521 <sect1 id="sec-GammaCurve">
11522 <title>Gamma Curve</title>
11523
11524 <para></para>
11525
11526 </sect1>
11527
11528 <!-- ----------------------------------------------------------------- -->
11529 <sect1 id="sec-Image">
11530 <title>Image</title>
11531
11532 <para></para>
11533
11534 </sect1>
11535
11536 <!-- ----------------------------------------------------------------- -->
11537 <sect1 id="sec-PlugsAndSockets">
11538 <title>Plugs and Sockets</title>
11539
11540 <para></para>
11541
11542 </sect1>
11543
11544 <!-- ----------------------------------------------------------------- -->
11545 <sect1 id="sec-Preview">
11546 <title>Preview</title>
11547
11548 <para></para>
11549
11550 <!--
11551
11552 <para>(This may need to be rewritten to follow the style of the rest of the tutorial)</para>
11553
11554 <para><tscreen><verb></para>
11555
11556 <para>Previews serve a number of purposes in GIMP/GTK. The most important one is
11557 this. High quality images may take up to tens of megabytes of memory - easily!
11558 Any operation on an image that big is bound to take a long time. If it takes
11559 you 5-10 trial-and-errors (i.e., 10-20 steps, since you have to revert after
11560 you make an error) to choose the desired modification, it make take you
11561 literally hours to make the right one - if you don't run out of memory
11562 first. People who have spent hours in color darkrooms know the feeling.
11563 Previews to the rescue!</para>
11564
11565 <para>But the annoyance of the delay is not the only issue. Oftentimes it is
11566 helpful to compare the Before and After versions side-by-side or at least
11567 back-to-back. If you're working with big images and 10 second delays,
11568 obtaining the Before and After impressions is, to say the least, difficult.
11569 For 30M images (4"x6", 600dpi, 24 bit) the side-by-side comparison is right
11570 out for most people, while back-to-back is more like back-to-1001, 1002,
11571 ..., 1010-back! Previews to the rescue!</para>
11572
11573 <para>But there's more. Previews allow for side-by-side pre-previews. In other
11574 words, you write a plug-in (e.g., the filterpack simulation) which would have
11575 a number of here's-what-it-would-look-like-if-you-were-to-do-this previews.
11576 An approach like this acts as a sort of a preview palette and is very
11577 effective for subtle changes. Let's go previews!</para>
11578
11579 <para>There's more. For certain plug-ins real-time image-specific human
11580 intervention maybe necessary. In the SuperNova plug-in, for example, the
11581 user is asked to enter the coordinates of the center of the future
11582 supernova. The easiest way to do this, really, is to present the user with a
11583 preview and ask him to interactively select the spot. Let's go previews!</para>
11584
11585 <para>Finally, a couple of misc uses. One can use previews even when not working
11586 with big images. For example, they are useful when rendering complicated
11587 patterns. (Just check out the venerable Diffraction plug-in + many other
11588 ones!) As another example, take a look at the colormap rotation plug-in
11589 (work in progress). You can also use previews for little logos inside you
11590 plug-ins and even for an image of yourself, The Author. Let's go previews!</para>
11591
11592 <para>When Not to Use Previews</para>
11593
11594 <para>Don't use previews for graphs, drawing, etc. GDK is much faster for that. Use
11595 previews only for rendered images!</para>
11596
11597 <para>Let's go previews!</para>
11598
11599 <para>You can stick a preview into just about anything. In a vbox, an hbox, a
11600 table, a button, etc. But they look their best in tight frames around them.
11601 Previews by themselves do not have borders and look flat without them. (Of
11602 course, if the flat look is what you want...) Tight frames provide the
11603 necessary borders.</para>
11604
11605 <para>                               [Image][Image]</para>
11606
11607 <para>Previews in many ways are like any other widgets in GTK (whatever that
11608 means) except they possess an additional feature: they need to be filled with
11609 some sort of an image! First, we will deal exclusively with the GTK aspect
11610 of previews and then we'll discuss how to fill them.</para>
11611
11612 <para>GtkWidget *preview!</para>
11613
11614 <para>Without any ado:</para>
11615
11616 <para>                              /* Create a preview widget,
11617                               set its size, an show it */
11618 GtkWidget *preview;
11619 preview=gtk_preview_new(GTK_PREVIEW_COLOR)
11620                               /*Other option:
11621                               GTK_PREVIEW_GRAYSCALE);*/
11622 gtk_preview_size (GTK_PREVIEW (preview), WIDTH, HEIGHT);
11623 gtk_widget_show(preview);
11624 my_preview_rendering_function(preview);</para>
11625
11626 <para>Oh yeah, like I said, previews look good inside frames, so how about:</para>
11627
11628 <para>GtkWidget *create_a_preview(int        Width,
11629                             int        Height,
11630                             int        Colorfulness)
11631 {
11632   GtkWidget *preview;
11633   GtkWidget *frame;
11634   
11635   frame = gtk_frame_new(NULL);
11636   gtk_frame_set_shadow_type (GTK_FRAME (frame), GTK_SHADOW_IN);
11637   gtk_container_set_border_width (GTK_CONTAINER(frame),0);
11638   gtk_widget_show(frame);</para>
11639
11640 <para>  preview=gtk_preview_new (Colorfulness?GTK_PREVIEW_COLOR
11641                                        :GTK_PREVIEW_GRAYSCALE);
11642   gtk_preview_size (GTK_PREVIEW (preview), Width, Height);
11643   gtk_container_add(GTK_CONTAINER(frame),preview);
11644   gtk_widget_show(preview);</para>
11645
11646 <para>  my_preview_rendering_function(preview);
11647   return frame;
11648 }</para>
11649
11650 <para>That's my basic preview. This routine returns the "parent" frame so you can
11651 place it somewhere else in your interface. Of course, you can pass the
11652 parent frame to this routine as a parameter. In many situations, however,
11653 the contents of the preview are changed continually by your application. In
11654 this case you may want to pass a pointer to the preview to a
11655 "create_a_preview()" and thus have control of it later.</para>
11656
11657 <para>One more important note that may one day save you a lot of time. Sometimes
11658 it is desirable to label you preview. For example, you may label the preview
11659 containing the original image as "Original" and the one containing the
11660 modified image as "Less Original". It might occur to you to pack the
11661 preview along with the appropriate label into a vbox. The unexpected caveat
11662 is that if the label is wider than the preview (which may happen for a
11663 variety of reasons unforseeable to you, from the dynamic decision on the
11664 size of the preview to the size of the font) the frame expands and no longer
11665 fits tightly over the preview. The same problem can probably arise in other
11666 situations as well.</para>
11667
11668 <para>                                   [Image]</para>
11669
11670 <para>The solution is to place the preview and the label into a 2x1 table and by
11671 attaching them with the following parameters (this is one possible variations
11672 of course. The key is no GTK_FILL in the second attachment):</para>
11673
11674 <para>gtk_table_attach(GTK_TABLE(table),label,0,1,0,1,
11675                  0,
11676                  GTK_EXPAND|GTK_FILL,
11677                  0,0);
11678 gtk_table_attach(GTK_TABLE(table),frame,0,1,1,2,
11679                  GTK_EXPAND,
11680                  GTK_EXPAND,
11681                  0,0);</para>
11682
11683 <para>
11684 And here's the result:</para>
11685
11686 <para>                                   [Image]</para>
11687
11688 <para>Misc</para>
11689
11690 <para>Making a preview clickable is achieved most easily by placing it in a
11691 button. It also adds a nice border around the preview and you may not even
11692 need to place it in a frame. See the Filter Pack Simulation plug-in for an
11693 example.</para>
11694
11695 <para>This is pretty much it as far as GTK is concerned.</para>
11696
11697 <para>Filling In a Preview</para>
11698
11699 <para>In order to familiarize ourselves with the basics of filling in previews,
11700 let's create the following pattern (contrived by trial and error):</para>
11701
11702 <para>                                   [Image]</para>
11703
11704 <para>void
11705 my_preview_rendering_function(GtkWidget     *preview)
11706 {
11707 #define SIZE 100
11708 #define HALF (SIZE/2)</para>
11709
11710 <para>  guchar *row=(guchar *) malloc(3*SIZE); /* 3 bits per dot */
11711   gint i, j;                             /* Coordinates    */
11712   double r, alpha, x, y;</para>
11713
11714 <para>  if (preview==NULL) return; /* I usually add this when I want */
11715                              /* to avoid silly crashes. You    */
11716                              /* should probably make sure that */
11717                              /* everything has been nicely     */
11718                              /* initialized!                   */
11719   for (j=0; j < ABS(cos(2*alpha)) ) { /* Are we inside the shape?  */
11720                                          /* glib.h contains ABS(x).   */
11721         row[i*3+0] = sqrt(1-r)*255;      /* Define Red                */
11722         row[i*3+1] = 128;                /* Define Green              */
11723         row[i*3+2] = 224;                /* Define Blue               */
11724       }                                  /* "+0" is for alignment!    */
11725       else {
11726         row[i*3+0] = r*255;
11727         row[i*3+1] = ABS(sin((float)i/SIZE*2*PI))*255;
11728         row[i*3+2] = ABS(sin((float)j/SIZE*2*PI))*255;
11729       }
11730     }
11731     gtk_preview_draw_row( GTK_PREVIEW(preview),row,0,j,SIZE);
11732     /* Insert "row" into "preview" starting at the point with  */
11733     /* coordinates (0,j) first column, j_th row extending SIZE */
11734     /* pixels to the right */
11735   }</para>
11736
11737 <para>  free(row); /* save some space */
11738   gtk_widget_draw(preview,NULL); /* what does this do? */
11739   gdk_flush(); /* or this? */
11740 }</para>
11741
11742 <para>Non-GIMP users can have probably seen enough to do a lot of things already.
11743 For the GIMP users I have a few pointers to add.</para>
11744
11745 <para>Image Preview</para>
11746
11747 <para>It is probably wise to keep a reduced version of the image around with just
11748 enough pixels to fill the preview. This is done by selecting every n'th
11749 pixel where n is the ratio of the size of the image to the size of the
11750 preview. All further operations (including filling in the previews) are then
11751 performed on the reduced number of pixels only. The following is my
11752 implementation of reducing the image. (Keep in mind that I've had only basic
11753 C!)</para>
11754
11755 <para>(UNTESTED CODE ALERT!!!)</para>
11756
11757 <para>typedef struct {
11758   gint      width;
11759   gint      height;
11760   gint      bbp;
11761   guchar    *rgb;
11762   guchar    *mask;
11763 } ReducedImage;</para>
11764
11765 <para>enum {
11766   SELECTION_ONLY,
11767   SELECTION_IN_CONTEXT,
11768   ENTIRE_IMAGE
11769 };</para>
11770
11771 <para>ReducedImage *Reduce_The_Image(GDrawable *drawable,
11772                                GDrawable *mask,
11773                                gint LongerSize,
11774                                gint Selection)
11775 {
11776   /* This function reduced the image down to the the selected preview size */
11777   /* The preview size is determine by LongerSize, i.e., the greater of the  */
11778   /* two dimensions. Works for RGB images only!                            */
11779   gint RH, RW;          /* Reduced height and reduced width                */
11780   gint width, height;   /* Width and Height of the area being reduced      */
11781   gint bytes=drawable->bpp;
11782   ReducedImage *temp=(ReducedImage *)malloc(sizeof(ReducedImage));</para>
11783
11784 <para>  guchar *tempRGB, *src_row, *tempmask, *src_mask_row,R,G,B;
11785   gint i, j, whichcol, whichrow, x1, x2, y1, y2;
11786   GPixelRgn srcPR, srcMask;
11787   gint NoSelectionMade=TRUE; /* Assume that we're dealing with the entire  */
11788                              /* image.                                     */</para>
11789
11790 <para>  gimp_drawable_mask_bounds (drawable->id, &amp;x1, &amp;y1, &amp;x2, &amp;y2);
11791   width  = x2-x1;
11792   height = y2-y1;
11793   /* If there's a SELECTION, we got its bounds!)</para>
11794
11795 <para>  if (width != drawable->width &amp;&amp; height != drawable->height)
11796     NoSelectionMade=FALSE;
11797   /* Become aware of whether the user has made an active selection   */
11798   /* This will become important later, when creating a reduced mask. */</para>
11799
11800 <para>  /* If we want to preview the entire image, overrule the above!  */
11801   /* Of course, if no selection has been made, this does nothing! */
11802   if (Selection==ENTIRE_IMAGE) {
11803     x1=0;
11804     x2=drawable->width;
11805     y1=0;
11806     y2=drawable->height;
11807   }</para>
11808
11809 <para>  /* If we want to preview a selection with some surrounding area we */
11810   /* have to expand it a little bit. Consider it a bit of a riddle. */
11811   if (Selection==SELECTION_IN_CONTEXT) {
11812     x1=MAX(0,                x1-width/2.0);
11813     x2=MIN(drawable->width,  x2+width/2.0);
11814     y1=MAX(0,                y1-height/2.0);
11815     y2=MIN(drawable->height, y2+height/2.0);
11816   }</para>
11817
11818 <para>  /* How we can determine the width and the height of the area being */
11819   /* reduced.                                                        */
11820   width  = x2-x1;
11821   height = y2-y1;</para>
11822
11823 <para>  /* The lines below determine which dimension is to be the longer   */
11824   /* side. The idea borrowed from the supernova plug-in. I suspect I */
11825   /* could've thought of it myself, but the truth must be told.      */
11826   /* Plagiarism stinks!                                               */
11827   if (width>height) {
11828     RW=LongerSize;
11829     RH=(float) height * (float) LongerSize/ (float) width;
11830   }
11831   else {
11832     RH=LongerSize;
11833     RW=(float)width * (float) LongerSize/ (float) height;
11834   }</para>
11835
11836 <para>  /* The entire image is stretched into a string! */
11837   tempRGB   = (guchar *) malloc(RW*RH*bytes);
11838   tempmask  = (guchar *) malloc(RW*RH);</para>
11839
11840 <para>  gimp_pixel_rgn_init (&amp;srcPR, drawable, x1, y1, width, height,
11841                        FALSE, FALSE);
11842   gimp_pixel_rgn_init (&amp;srcMask, mask, x1, y1, width, height,
11843                        FALSE, FALSE);</para>
11844
11845 <para>  /* Grab enough to save a row of image and a row of mask. */
11846   src_row       = (guchar *) malloc (width*bytes);
11847   src_mask_row  = (guchar *) malloc (width);</para>
11848
11849 <para>  for (i=0; i < RH; i++) {
11850     whichrow=(float)i*(float)height/(float)RH;
11851     gimp_pixel_rgn_get_row (&amp;srcPR, src_row, x1, y1+whichrow, width);
11852     gimp_pixel_rgn_get_row (&amp;srcMask, src_mask_row, x1, y1+whichrow, width);</para>
11853
11854 <para>    for (j=0; j < RW; j++) {
11855       whichcol=(float)j*(float)width/(float)RW;</para>
11856
11857 <para>      /* No selection made = each point is completely selected! */
11858       if (NoSelectionMade)
11859         tempmask[i*RW+j]=255;
11860       else
11861         tempmask[i*RW+j]=src_mask_row[whichcol];</para>
11862
11863 <para>      /* Add the row to the one long string which now contains the image! */
11864       tempRGB[i*RW*bytes+j*bytes+0]=src_row[whichcol*bytes+0];
11865       tempRGB[i*RW*bytes+j*bytes+1]=src_row[whichcol*bytes+1];
11866       tempRGB[i*RW*bytes+j*bytes+2]=src_row[whichcol*bytes+2];</para>
11867
11868 <para>      /* Hold on to the alpha as well */
11869       if (bytes==4)
11870         tempRGB[i*RW*bytes+j*bytes+3]=src_row[whichcol*bytes+3];
11871     }
11872   }
11873   temp->bpp=bytes;
11874   temp->width=RW;
11875   temp->height=RH;
11876   temp->rgb=tempRGB;
11877   temp->mask=tempmask;
11878   return temp;
11879 }</para>
11880
11881 <para>The following is a preview function which used the same ReducedImage type!
11882 Note that it uses fakes transparency (if one is present by means of
11883 fake_transparency which is defined as follows:</para>
11884
11885 <para>gint fake_transparency(gint i, gint j)
11886 {
11887   if ( ((i%20)- 10) * ((j%20)- 10)>0   )
11888     return 64;
11889   else
11890     return 196;
11891 }</para>
11892
11893 <para>Now here's the preview function:</para>
11894
11895 <para>void
11896 my_preview_render_function(GtkWidget     *preview,
11897                            gint          changewhat,
11898                            gint          changewhich)
11899 {
11900   gint Inten, bytes=drawable->bpp;
11901   gint i, j, k;
11902   float partial;
11903   gint RW=reduced->width;
11904   gint RH=reduced->height;
11905   guchar *row=malloc(bytes*RW);;</para>
11906
11907 <para>
11908   for (i=0; i < RH; i++) {
11909     for (j=0; j < RW; j++) {</para>
11910
11911 <para>      row[j*3+0] = reduced->rgb[i*RW*bytes + j*bytes + 0];
11912       row[j*3+1] = reduced->rgb[i*RW*bytes + j*bytes + 1];
11913       row[j*3+2] = reduced->rgb[i*RW*bytes + j*bytes + 2];</para>
11914
11915 <para>      if (bytes==4)
11916         for (k=0; k<3; k++) {
11917           float transp=reduced->rgb[i*RW*bytes+j*bytes+3]/255.0;
11918           row[3*j+k]=transp*a[3*j+k]+(1-transp)*fake_transparency(i,j);
11919         }
11920     }
11921     gtk_preview_draw_row( GTK_PREVIEW(preview),row,0,i,RW);
11922   }</para>
11923
11924 <para>  free(a);
11925   gtk_widget_draw(preview,NULL);
11926   gdk_flush();
11927 }</para>
11928
11929 <para>Applicable Routines</para>
11930
11931 <para>guint           gtk_preview_get_type           (void);
11932 /* No idea */
11933 void            gtk_preview_uninit             (void);
11934 /* No idea */
11935 GtkWidget*      gtk_preview_new                (GtkPreviewType   type);
11936 /* Described above */
11937 void            gtk_preview_size               (GtkPreview      *preview,
11938                                                 gint             width,
11939                                                 gint             height);
11940 /* Allows you to resize an existing preview.    */
11941 /* Apparently there's a bug in GTK which makes  */
11942 /* this process messy. A way to clean up a mess */
11943 /* is to manually resize the window containing  */
11944 /* the preview after resizing the preview.      */</para>
11945
11946 <para>void            gtk_preview_put                (GtkPreview      *preview,
11947                                                 GdkWindow       *window,
11948                                                 GdkGC           *gc,
11949                                                 gint             srcx,
11950                                                 gint             srcy,
11951                                                 gint             destx,
11952                                                 gint             desty,
11953                                                 gint             width,
11954                                                 gint             height);
11955 /* No idea */</para>
11956
11957 <para>void            gtk_preview_put_row            (GtkPreview      *preview,
11958                                                 guchar          *src,
11959                                                 guchar          *dest,
11960                                                 gint             x,
11961                                                 gint             y,
11962                                                 gint             w);
11963 /* No idea */</para>
11964
11965 <para>void            gtk_preview_draw_row           (GtkPreview      *preview,
11966                                                 guchar          *data,
11967                                                 gint             x,
11968                                                 gint             y,
11969                                                 gint             w);
11970 /* Described in the text */</para>
11971
11972 <para>void            gtk_preview_set_expand         (GtkPreview      *preview,
11973                                                 gint             expand);
11974 /* No idea */</para>
11975
11976 <para>/* No clue for any of the below but    */
11977 /* should be standard for most widgets */
11978 void            gtk_preview_set_gamma          (double           gamma);
11979 void            gtk_preview_set_color_cube     (guint            nred_shades,
11980                                                 guint            ngreen_shades,
11981                                                 guint            nblue_shades,
11982                                                 guint            ngray_shades);
11983 void            gtk_preview_set_install_cmap   (gint             install_cmap);
11984 void            gtk_preview_set_reserved       (gint             nreserved);
11985 GdkVisual*      gtk_preview_get_visual         (void);
11986 GdkColormap*    gtk_preview_get_cmap           (void);
11987 GtkPreviewInfo* gtk_preview_get_info           (void);</para>
11988
11989 <para>That's all, folks!</para>
11990
11991 <para></verb></tscreen></para>
11992
11993 -->
11994
11995 </sect1>
11996 </chapter>
11997
11998 <!-- ***************************************************************** -->
11999 <chapter id="ch-SettingWidgetAttributes">
12000 <title>Setting Widget Attributes</title>
12001
12002 <para>This describes the functions used to operate on widgets. These can be
12003 used to set style, padding, size, etc.</para>
12004
12005 <para>(Maybe I should make a whole section on accelerators.)</para>
12006
12007 <programlisting role="C">
12008 void gtk_widget_install_accelerator( GtkWidget           *widget,
12009                                      GtkAcceleratorTable *table,
12010                                      gchar               *signal_name,
12011                                      gchar                key,
12012                                      guint8               modifiers );
12013
12014 void gtk_widget_remove_accelerator ( GtkWidget           *widget,
12015                                      GtkAcceleratorTable *table,
12016                                      gchar               *signal_name);
12017
12018 void gtk_widget_activate( GtkWidget *widget );
12019
12020 void gtk_widget_set_name( GtkWidget *widget,
12021                           gchar     *name );
12022
12023 gchar *gtk_widget_get_name( GtkWidget *widget );
12024
12025 void gtk_widget_set_sensitive( GtkWidget *widget,
12026                                gint       sensitive );
12027
12028 void gtk_widget_set_style( GtkWidget *widget,
12029                            GtkStyle  *style );
12030                                            
12031 GtkStyle *gtk_widget_get_style( GtkWidget *widget );
12032
12033 GtkStyle *gtk_widget_get_default_style( void );
12034
12035 void gtk_widget_set_uposition( GtkWidget *widget,
12036                                gint       x,
12037                                gint       y );
12038
12039 void gtk_widget_set_usize( GtkWidget *widget,
12040                            gint       width,
12041                            gint       height );
12042
12043 void gtk_widget_grab_focus( GtkWidget *widget );
12044
12045 void gtk_widget_show( GtkWidget *widget );
12046
12047 void gtk_widget_hide( GtkWidget *widget );
12048 </programlisting>
12049
12050 </chapter>
12051
12052 <!-- ***************************************************************** -->
12053 <chapter id="ch-Timeouts">
12054 <title>Timeouts, IO and Idle Functions</title>
12055
12056 <!-- ----------------------------------------------------------------- -->
12057 <sect1 id="sec-Timeouts">
12058 <title>Timeouts</title>
12059
12060 <para>You may be wondering how you make GTK do useful work when in gtk_main.
12061 Well, you have several options. Using the following function you can
12062 create a timeout function that will be called every "interval"
12063 milliseconds.</para>
12064
12065 <programlisting role="C">
12066 gint gtk_timeout_add( guint32     interval,
12067                       GtkFunction function,
12068                       gpointer    data );
12069 </programlisting>
12070
12071 <para>The first argument is the number of milliseconds between calls to your
12072 function. The second argument is the function you wish to have called,
12073 and the third, the data passed to this callback function. The return
12074 value is an integer "tag" which may be used to stop the timeout by
12075 calling:</para>
12076
12077 <programlisting role="C">
12078 void gtk_timeout_remove( gint tag );
12079 </programlisting>
12080
12081 <para>You may also stop the timeout function by returning zero or FALSE from
12082 your callback function. Obviously this means if you want your function
12083 to continue to be called, it should return a non-zero value,
12084 i.e., TRUE.</para>
12085
12086 <para>The declaration of your callback should look something like this:</para>
12087
12088 <programlisting role="C">
12089 gint timeout_callback( gpointer data );
12090 </programlisting>
12091
12092 </sect1>
12093
12094 <!-- ----------------------------------------------------------------- -->
12095 <sect1 id="sec-MonitoringIO">
12096 <title>Monitoring IO</title>
12097
12098 <para>A nifty feature of GDK (the library that underlies GTK), is the
12099 ability to have it check for data on a file descriptor for you (as
12100 returned by open(2) or socket(2)). This is especially useful for
12101 networking applications. The function:</para>
12102
12103 <programlisting role="C">
12104 gint gdk_input_add( gint              source,
12105                     GdkInputCondition condition,
12106                     GdkInputFunction  function,
12107                     gpointer          data );
12108 </programlisting>
12109
12110 <para>Where the first argument is the file descriptor you wish to have
12111 watched, and the second specifies what you want GDK to look for. This
12112 may be one of:</para>
12113
12114 <itemizedlist>
12115 <listitem><simpara><literal>GDK_INPUT_READ</literal> - Call your function when there is data
12116 ready for reading on your file descriptor.</simpara>
12117 </listitem>
12118
12119 <listitem><simpara>><literal>GDK_INPUT_WRITE</literal> - Call your function when the file
12120 descriptor is ready for writing.</simpara>
12121 </listitem>
12122 </itemizedlist>
12123
12124 <para>As I'm sure you've figured out already, the third argument is the
12125 function you wish to have called when the above conditions are
12126 satisfied, and the fourth is the data to pass to this function.</para>
12127
12128 <para>The return value is a tag that may be used to stop GDK from monitoring
12129 this file descriptor using the following function.</para>
12130
12131 <programlisting role="C">
12132 void gdk_input_remove( gint tag );
12133 </programlisting>
12134
12135 <para>The callback function should be declared as:</para>
12136
12137 <programlisting role="C">
12138 void input_callback( gpointer          data,
12139                      gint              source, 
12140                      GdkInputCondition condition );
12141 </programlisting>
12142
12143 <para>Where <literal>source</literal> and <literal>condition</literal> are as specified above.</para>
12144
12145 </sect1>
12146
12147 <!-- ----------------------------------------------------------------- -->
12148 <sect1 id="sec-IdleFunctions">
12149 <title>Idle Functions</title>
12150
12151 <para><!-- TODO: Need to check on idle priorities - TRG -->
12152 What if you have a function which you want to be called when nothing
12153 else is happening ?</para>
12154
12155 <programlisting role="C">
12156 gint gtk_idle_add( GtkFunction function,
12157                    gpointer    data );
12158 </programlisting>
12159
12160 <para>This causes GTK to call the specified function whenever nothing else
12161 is happening.</para>
12162
12163 <programlisting role="C">
12164 void gtk_idle_remove( gint tag );
12165 </programlisting>
12166
12167 <para>I won't explain the meaning of the arguments as they follow very much
12168 like the ones above. The function pointed to by the first argument to
12169 gtk_idle_add will be called whenever the opportunity arises. As with
12170 the others, returning FALSE will stop the idle function from being
12171 called.</para>
12172
12173 </sect1>
12174 </chapter>
12175
12176 <!-- ***************************************************************** -->
12177 <chapter id="ch-AdvancedEventsAndSignals">
12178 <title>Advanced Event and Signal Handling</title>
12179
12180 <!-- ----------------------------------------------------------------- -->
12181 <sect1 id="sec-SignalFunctions">
12182 <title>Signal Functions</title>
12183
12184 <!-- ----------------------------------------------------------------- -->
12185 <sect2>
12186 <title>Connecting and Disconnecting Signal Handlers</title>
12187
12188 <programlisting role="C">
12189 guint gtk_signal_connect( GtkObject     *object,
12190                           const gchar   *name,
12191                           GtkSignalFunc  func,
12192                           gpointer       func_data );
12193
12194 guint gtk_signal_connect_after( GtkObject     *object,
12195                                 const gchar   *name,
12196                                 GtkSignalFunc  func,
12197                                 gpointer       func_data );
12198
12199 guint gtk_signal_connect_object( GtkObject     *object,
12200                                  const gchar   *name,
12201                                  GtkSignalFunc  func,
12202                                  GtkObject     *slot_object );
12203
12204 guint gtk_signal_connect_object_after( GtkObject     *object,
12205                                        const gchar   *name,
12206                                        GtkSignalFunc  func,
12207                                        GtkObject     *slot_object );
12208
12209 guint gtk_signal_connect_full( GtkObject          *object,
12210                                const gchar        *name,
12211                                GtkSignalFunc       func,
12212                                GtkCallbackMarshal  marshal,
12213                                gpointer            data,
12214                                GtkDestroyNotify    destroy_func,
12215                                gint                object_signal,
12216                                gint                after );
12217
12218 guint gtk_signal_connect_interp( GtkObject          *object,
12219                                  const gchar        *name,
12220                                  GtkCallbackMarshal  func,
12221                                  gpointer            data,
12222                                  GtkDestroyNotify    destroy_func,
12223                                  gint                after );
12224
12225 void gtk_signal_connect_object_while_alive( GtkObject     *object,
12226                                             const gchar   *signal,
12227                                             GtkSignalFunc  func,
12228                                             GtkObject     *alive_object );
12229
12230 void gtk_signal_connect_while_alive( GtkObject     *object,
12231                                      const gchar   *signal,
12232                                      GtkSignalFunc  func,
12233                                      gpointer       func_data,
12234                                      GtkObject     *alive_object );
12235
12236 void gtk_signal_disconnect( GtkObject *object,
12237                             guint      handler_id );
12238
12239 void gtk_signal_disconnect_by_func( GtkObject     *object,
12240                                     GtkSignalFunc  func,
12241                                     gpointer       data );
12242 </programlisting>
12243
12244 </sect2>
12245
12246 <!-- ----------------------------------------------------------------- -->
12247 <sect2>
12248 <title>Blocking and Unblocking Signal Handlers</title>
12249
12250 <programlisting role="C">
12251 void gtk_signal_handler_block( GtkObject *object,
12252                                guint      handler_id);
12253
12254 void gtk_signal_handler_block_by_func( GtkObject     *object,
12255                                        GtkSignalFunc  func,
12256                                        gpointer       data );
12257
12258 void gtk_signal_handler_block_by_data( GtkObject *object,
12259                                        gpointer   data );
12260
12261 void gtk_signal_handler_unblock( GtkObject *object,
12262                                  guint      handler_id );
12263
12264 void gtk_signal_handler_unblock_by_func( GtkObject     *object,
12265                                          GtkSignalFunc  func,
12266                                          gpointer       data );
12267
12268 void gtk_signal_handler_unblock_by_data( GtkObject *object,
12269                                          gpointer   data );
12270 </programlisting>
12271
12272 </sect2>
12273
12274 <!-- ----------------------------------------------------------------- -->
12275 <sect2>
12276 <title>Emitting and Stopping Signals</title>
12277
12278 <programlisting role="C">
12279 void gtk_signal_emit( GtkObject *object,
12280                       guint      signal_id,
12281                       ... );
12282
12283 void gtk_signal_emit_by_name( GtkObject   *object,
12284                               const gchar *name,
12285                               ... );
12286
12287 void gtk_signal_emitv( GtkObject *object,
12288                        guint      signal_id,
12289                        GtkArg    *params );
12290
12291 void gtk_signal_emitv_by_name( GtkObject   *object,
12292                                const gchar *name,
12293                                GtkArg      *params );
12294
12295 guint gtk_signal_n_emissions( GtkObject *object,
12296                               guint      signal_id );
12297
12298 guint gtk_signal_n_emissions_by_name( GtkObject   *object,
12299                                       const gchar *name );
12300
12301 void gtk_signal_emit_stop( GtkObject *object,
12302                            guint      signal_id );
12303
12304 void gtk_signal_emit_stop_by_name( GtkObject   *object,
12305                                    const gchar *name );
12306 </programlisting>
12307
12308 </sect2>
12309 </sect1>
12310
12311 <!-- ----------------------------------------------------------------- -->
12312 <sect1 id="sec-SignalEmissionAndPropagation">
12313 <title>Signal Emission and Propagation</title>
12314
12315 <para>Signal emission is the process whereby GTK runs all handlers for a
12316 specific object and signal.</para>
12317
12318 <para>First, note that the return value from a signal emission is the return
12319 value of the <emphasis>last</emphasis> handler executed. Since event signals are
12320 all of type <literal>GTK_RUN_LAST</literal>, this will be the default (GTK supplied)
12321 handler, unless you connect with gtk_signal_connect_after().</para>
12322
12323 <para>The way an event (say "button_press_event") is handled, is:</para>
12324
12325 <itemizedlist>
12326 <listitem><simpara>Start with the widget where the event occured.</simpara>
12327 </listitem>
12328
12329 <listitem><simpara>Emit the generic "event" signal. If that signal handler returns
12330 a value of TRUE, stop all processing.</simpara>
12331 </listitem>
12332
12333 <listitem><simpara>Otherwise, emit a specific, "button_press_event" signal. If that
12334 returns TRUE, stop all processing.</simpara>
12335 </listitem>
12336
12337 <listitem><simpara>Otherwise, go to the widget's parent, and repeat the above two
12338 steps.</simpara>
12339 </listitem>
12340
12341 <listitem><simpara>Continue until some signal handler returns TRUE, or until the
12342 top-level widget is reached.</simpara>
12343 </listitem>
12344 </itemizedlist>
12345
12346 <para>Some consequences of the above are:</para>
12347
12348 <itemizedlist>
12349 <listitem><simpara>Your handler's return value will have no effect if there is a
12350 default handler, unless you connect with gtk_signal_connect_after().</simpara>
12351 </listitem>
12352
12353 <listitem><simpara>To prevent the default handler from being run, you need to
12354 connect with gtk_signal_connect() and use
12355 gtk_signal_emit_stop_by_name() - the return value only affects whether
12356 the signal is propagated, not the current emission.</simpara>
12357 </listitem>
12358 </itemizedlist>
12359
12360 </sect1>
12361 </chapter>
12362
12363 <!-- ***************************************************************** -->
12364 <chapter id="ch-ManagingSelections">
12365 <title>Managing Selections</title>
12366
12367 <!-- ----------------------------------------------------------------- -->
12368 <sect1 id="sec-SelectionsOverview">
12369 <title>Overview</title>
12370
12371 <para>One type of interprocess communication supported by X and GTK is
12372 <emphasis>selections</emphasis>. A selection identifies a chunk of data, for
12373 instance, a portion of text, selected by the user in some fashion, for
12374 instance, by dragging with the mouse. Only one application on a
12375 display (the <emphasis>owner</emphasis>) can own a particular selection at one
12376 time, so when a selection is claimed by one application, the previous
12377 owner must indicate to the user that selection has been
12378 relinquished. Other applications can request the contents of a
12379 selection in different forms, called <emphasis>targets</emphasis>. There can be
12380 any number of selections, but most X applications only handle one, the
12381 <emphasis>primary selection</emphasis>.</para>
12382
12383 <para>In most cases, it isn't necessary for a GTK application to deal with
12384 selections itself. The standard widgets, such as the Entry widget,
12385 already have the capability to claim the selection when appropriate
12386 (e.g., when the user drags over text), and to retrieve the contents of
12387 the selection owned by another widget or another application (e.g.,
12388 when the user clicks the second mouse button). However, there may be
12389 cases in which you want to give other widgets the ability to supply
12390 the selection, or you wish to retrieve targets not supported by
12391 default.</para>
12392
12393 <para>A fundamental concept needed to understand selection handling is that
12394 of the <emphasis>atom</emphasis>. An atom is an integer that uniquely identifies a
12395 string (on a certain display). Certain atoms are predefined by the X
12396 server, and in some cases there are constants in <literal>gtk.h</literal>
12397 corresponding to these atoms. For instance the constant
12398 <literal>GDK_PRIMARY_SELECTION</literal> corresponds to the string "PRIMARY".
12399 In other cases, you should use the functions
12400 <literal>gdk_atom_intern()</literal>, to get the atom corresponding to a string,
12401 and <literal>gdk_atom_name()</literal>, to get the name of an atom. Both
12402 selections and targets are identified by atoms.</para>
12403
12404 </sect1>
12405 <!-- ----------------------------------------------------------------- -->
12406 <sect1 id="sec-RetrievingTheSelection">
12407 <title>Retrieving the selection</title>
12408
12409 <para>Retrieving the selection is an asynchronous process. To start the
12410 process, you call:</para>
12411
12412 <programlisting role="C">
12413 gint gtk_selection_convert( GtkWidget *widget, 
12414                             GdkAtom    selection, 
12415                             GdkAtom    target,
12416                             guint32    time );
12417 </programlisting>
12418
12419 <para>This <emphasis>converts</emphasis> the selection into the form specified by
12420 <literal>target</literal>. If at all possible, the time field should be the time
12421 from the event that triggered the selection. This helps make sure that
12422 events occur in the order that the user requested them. However, if it
12423 is not available (for instance, if the conversion was triggered by a
12424 "clicked" signal), then you can use the constant
12425 <literal>GDK_CURRENT_TIME</literal>.</para>
12426
12427 <para>When the selection owner responds to the request, a
12428 "selection_received" signal is sent to your application. The handler
12429 for this signal receives a pointer to a <literal>GtkSelectionData</literal>
12430 structure, which is defined as:</para>
12431
12432 <programlisting role="C">
12433 struct _GtkSelectionData
12434 {
12435   GdkAtom selection;
12436   GdkAtom target;
12437   GdkAtom type;
12438   gint    format;
12439   guchar *data;
12440   gint    length;
12441 };
12442 </programlisting>
12443
12444 <para><literal>selection</literal> and <literal>target</literal> are the values you gave in your
12445 <literal>gtk_selection_convert()</literal> call. <literal>type</literal> is an atom that
12446 identifies the type of data returned by the selection owner. Some
12447 possible values are "STRING", a string of latin-1 characters, "ATOM",
12448 a series of atoms, "INTEGER", an integer, etc. Most targets can only
12449 return one type. <literal>format</literal> gives the length of the units (for
12450 instance characters) in bits. Usually, you don't care about this when
12451 receiving data. <literal>data</literal> is a pointer to the returned data, and
12452 <literal>length</literal> gives the length of the returned data, in bytes. If
12453 <literal>length</literal> is negative, then an error occurred and the selection
12454 could not be retrieved. This might happen if no application owned the
12455 selection, or if you requested a target that the application didn't
12456 support. The buffer is actually guaranteed to be one byte longer than
12457 <literal>length</literal>; the extra byte will always be zero, so it isn't
12458 necessary to make a copy of strings just to null terminate them.</para>
12459
12460 <para>In the following example, we retrieve the special target "TARGETS",
12461 which is a list of all targets into which the selection can be
12462 converted.</para>
12463
12464 <programlisting role="C">
12465 <!-- example-start selection gettargets.c -->
12466
12467 #include &lt;gtk/gtk.h&gt;
12468
12469 void selection_received( GtkWidget        *widget, 
12470                          GtkSelectionData *selection_data, 
12471                          gpointer          data );
12472
12473 /* Signal handler invoked when user clicks on the "Get Targets" button */
12474 void get_targets( GtkWidget *widget,
12475                   gpointer data )
12476 {
12477   static GdkAtom targets_atom = GDK_NONE;
12478
12479   /* Get the atom corresponding to the string "TARGETS" */
12480   if (targets_atom == GDK_NONE)
12481     targets_atom = gdk_atom_intern ("TARGETS", FALSE);
12482
12483   /* And request the "TARGETS" target for the primary selection */
12484   gtk_selection_convert (widget, GDK_SELECTION_PRIMARY, targets_atom,
12485                          GDK_CURRENT_TIME);
12486 }
12487
12488 /* Signal handler called when the selections owner returns the data */
12489 void selection_received( GtkWidget        *widget,
12490                          GtkSelectionData *selection_data, 
12491                          gpointer          data )
12492 {
12493   GdkAtom *atoms;
12494   GList *item_list;
12495   int i;
12496
12497   /* **** IMPORTANT **** Check to see if retrieval succeeded  */
12498   if (selection_data->length < 0)
12499     {
12500       g_print ("Selection retrieval failed\n");
12501       return;
12502     }
12503   /* Make sure we got the data in the expected form */
12504   if (selection_data->type != GDK_SELECTION_TYPE_ATOM)
12505     {
12506       g_print ("Selection \"TARGETS\" was not returned as atoms!\n");
12507       return;
12508     }
12509   
12510   /* Print out the atoms we received */
12511   atoms = (GdkAtom *)selection_data->data;
12512
12513   item_list = NULL;
12514   for (i=0; i&lt;selection_data->length/sizeof(GdkAtom); i++)
12515     {
12516       char *name;
12517       name = gdk_atom_name (atoms[i]);
12518       if (name != NULL)
12519         g_print ("%s\n",name);
12520       else
12521         g_print ("(bad atom)\n");
12522     }
12523
12524   return;
12525 }
12526
12527 int main( int   argc,
12528           char *argv[] )
12529 {
12530   GtkWidget *window;
12531   GtkWidget *button;
12532   
12533   gtk_init (&amp;argc, &amp;argv);
12534
12535   /* Create the toplevel window */
12536
12537   window = gtk_window_new (GTK_WINDOW_TOPLEVEL);
12538   gtk_window_set_title (GTK_WINDOW (window), "Event Box");
12539   gtk_container_set_border_width (GTK_CONTAINER (window), 10);
12540
12541   gtk_signal_connect (GTK_OBJECT (window), "destroy",
12542                       GTK_SIGNAL_FUNC (gtk_exit), NULL);
12543
12544   /* Create a button the user can click to get targets */
12545
12546   button = gtk_button_new_with_label ("Get Targets");
12547   gtk_container_add (GTK_CONTAINER (window), button);
12548
12549   gtk_signal_connect (GTK_OBJECT(button), "clicked",
12550                       GTK_SIGNAL_FUNC (get_targets), NULL);
12551   gtk_signal_connect (GTK_OBJECT(button), "selection_received",
12552                       GTK_SIGNAL_FUNC (selection_received), NULL);
12553
12554   gtk_widget_show (button);
12555   gtk_widget_show (window);
12556   
12557   gtk_main ();
12558   
12559   return 0;
12560 }
12561 <!-- example-end -->
12562 </programlisting>
12563
12564 </sect1>
12565 <!-- ----------------------------------------------------------------- -->
12566 <sect1 id="sec-SupplyingTheSelection">
12567 <title>Supplying the selection</title>
12568
12569 <para>Supplying the selection is a bit more complicated. You must register 
12570 handlers that will be called when your selection is requested. For
12571 each selection/target pair you will handle, you make a call to:</para>
12572
12573 <programlisting role="C">
12574 void gtk_selection_add_target (GtkWidget           *widget, 
12575                                GdkAtom              selection,
12576                                GdkAtom              target,
12577                                guint                info);
12578 </programlisting>
12579
12580 <para><literal>widget</literal>, <literal>selection</literal>, and <literal>target</literal> identify the requests
12581 this handler will manage. When a request for a selection is received,
12582 the "selection_get" signal will be called. <literal>info</literal> can be used as an
12583 enumerator to identify the specific target within the callback function.</para>
12584
12585 <para>The callback function has the signature:</para>
12586
12587 <programlisting role="C">
12588 void  "selection_get" (GtkWidget          *widget,
12589                        GtkSelectionData   *selection_data,
12590                        guint               info,
12591                        guint               time);
12592 </programlisting>
12593
12594 <para>The GtkSelectionData is the same as above, but this time, we're
12595 responsible for filling in the fields <literal>type</literal>, <literal>format</literal>,
12596 <literal>data</literal>, and <literal>length</literal>. (The <literal>format</literal> field is actually
12597 important here - the X server uses it to figure out whether the data
12598 needs to be byte-swapped or not. Usually it will be 8 - <emphasis>i.e.</emphasis> a
12599 character - or 32 - <emphasis>i.e.</emphasis> a. integer.) This is done by calling the
12600 function:</para>
12601
12602 <programlisting role="C">
12603 void gtk_selection_data_set( GtkSelectionData *selection_data,
12604                              GdkAtom           type,
12605                              gint              format,
12606                              guchar           *data,
12607                              gint              length );
12608 </programlisting>
12609
12610 <para>This function takes care of properly making a copy of the data so that
12611 you don't have to worry about keeping it around. (You should not fill
12612 in the fields of the GtkSelectionData structure by hand.)</para>
12613
12614 <para>When prompted by the user, you claim ownership of the selection by
12615 calling:</para>
12616
12617 <programlisting role="C">
12618 gint gtk_selection_owner_set( GtkWidget *widget,
12619                               GdkAtom    selection,
12620                               guint32    time );
12621 </programlisting>
12622
12623 <para>If another application claims ownership of the selection, you will
12624 receive a "selection_clear_event".</para>
12625
12626 <para>As an example of supplying the selection, the following program adds
12627 selection functionality to a toggle button. When the toggle button is
12628 depressed, the program claims the primary selection. The only target
12629 supported (aside from certain targets like "TARGETS" supplied by GTK
12630 itself), is the "STRING" target. When this target is requested, a
12631 string representation of the time is returned.</para>
12632
12633 <programlisting role="C">
12634 <!-- example-start selection setselection.c -->
12635
12636 #include &lt;gtk/gtk.h&gt;
12637 #include &lt;time.h&gt;
12638
12639 /* Callback when the user toggles the selection */
12640 void selection_toggled( GtkWidget *widget,
12641                         gint      *have_selection )
12642 {
12643   if (GTK_TOGGLE_BUTTON(widget)->active)
12644     {
12645       *have_selection = gtk_selection_owner_set (widget,
12646                                                  GDK_SELECTION_PRIMARY,
12647                                                  GDK_CURRENT_TIME);
12648       /* if claiming the selection failed, we return the button to
12649          the out state */
12650       if (!*have_selection)
12651         gtk_toggle_button_set_active (GTK_TOGGLE_BUTTON(widget), FALSE);
12652     }
12653   else
12654     {
12655       if (*have_selection)
12656         {
12657           /* Before clearing the selection by setting the owner to NULL,
12658              we check if we are the actual owner */
12659           if (gdk_selection_owner_get (GDK_SELECTION_PRIMARY) == widget->window)
12660             gtk_selection_owner_set (NULL, GDK_SELECTION_PRIMARY,
12661                                      GDK_CURRENT_TIME);
12662           *have_selection = FALSE;
12663         }
12664     }
12665 }
12666
12667 /* Called when another application claims the selection */
12668 gint selection_clear( GtkWidget         *widget,
12669                       GdkEventSelection *event,
12670                       gint              *have_selection )
12671 {
12672   *have_selection = FALSE;
12673   gtk_toggle_button_set_active (GTK_TOGGLE_BUTTON(widget), FALSE);
12674
12675   return TRUE;
12676 }
12677
12678 /* Supplies the current time as the selection. */
12679 void selection_handle( GtkWidget        *widget, 
12680                        GtkSelectionData *selection_data,
12681                        guint             info,
12682                        guint             time_stamp,
12683                        gpointer          data )
12684 {
12685   gchar *timestr;
12686   time_t current_time;
12687
12688   current_time = time(NULL);
12689   timestr = asctime (localtime(&amp;current_time)); 
12690   /* When we return a single string, it should not be null terminated.
12691      That will be done for us */
12692
12693   gtk_selection_data_set (selection_data, GDK_SELECTION_TYPE_STRING,
12694                           8, timestr, strlen(timestr));
12695 }
12696
12697 int main( int   argc,
12698           char *argv[] )
12699 {
12700   GtkWidget *window;
12701   GtkWidget *selection_button;
12702
12703   static int have_selection = FALSE;
12704   
12705   gtk_init (&amp;argc, &amp;argv);
12706
12707   /* Create the toplevel window */
12708
12709   window = gtk_window_new (GTK_WINDOW_TOPLEVEL);
12710   gtk_window_set_title (GTK_WINDOW (window), "Event Box");
12711   gtk_container_set_border_width (GTK_CONTAINER (window), 10);
12712
12713   gtk_signal_connect (GTK_OBJECT (window), "destroy",
12714                       GTK_SIGNAL_FUNC (gtk_exit), NULL);
12715
12716   /* Create a toggle button to act as the selection */
12717
12718   selection_button = gtk_toggle_button_new_with_label ("Claim Selection");
12719   gtk_container_add (GTK_CONTAINER (window), selection_button);
12720   gtk_widget_show (selection_button);
12721
12722   gtk_signal_connect (GTK_OBJECT(selection_button), "toggled",
12723                       GTK_SIGNAL_FUNC (selection_toggled), &amp;have_selection);
12724   gtk_signal_connect (GTK_OBJECT(selection_button), "selection_clear_event",
12725                       GTK_SIGNAL_FUNC (selection_clear), &amp;have_selection);
12726
12727   gtk_selection_add_target (selection_button,
12728                             GDK_SELECTION_PRIMARY,
12729                             GDK_SELECTION_TYPE_STRING,
12730                             1);
12731   gtk_signal_connect (GTK_OBJECT(selection_button), "selection_get",
12732                       GTK_SIGNAL_FUNC (selection_handle), &amp;have_selection);
12733
12734   gtk_widget_show (selection_button);
12735   gtk_widget_show (window);
12736   
12737   gtk_main ();
12738   
12739   return 0;
12740 }
12741 <!-- example-end -->
12742 </programlisting>
12743
12744 </sect1>
12745 </chapter>
12746
12747 <!-- ***************************************************************** -->
12748 <chapter id="ch-DragAngDrop">
12749 <title>Drag-and-drop (DND)</title>
12750
12751 <para>GTK+ has a high level set of functions for doing inter-process
12752 communication via the drag-and-drop system. GTK+ can perform
12753 drag-and-drop on top of the low level Xdnd and Motif drag-and-drop
12754 protocols.</para>
12755
12756 <!-- ----------------------------------------------------------------- -->
12757 <sect1 id="sec-DragAndDropOverview">
12758 <title>Overview</title>
12759
12760 <para>An application capable of GTK+ drag-and-drop first defines and sets up
12761 the GTK+ widget(s) for drag-and-drop. Each widget can be a source
12762 and/or destination for drag-and-drop. Note that these GTK+ widgets must have
12763 an associated X Window, check using GTK_WIDGET_NO_WINDOW(widget)).</para>
12764
12765 <para>Source widgets can send out drag data, thus allowing the user to drag
12766 things off of them, while destination widgets can receive drag data.
12767 Drag-and-drop destinations can limit who they accept drag data from,
12768 e.g. the same application or any application (including itself).</para>
12769
12770 <para>Sending and receiving drop data makes use of GTK+ signals.
12771 Dropping an item to a destination widget requires both a data
12772 request (for the source widget) and data received signal handler (for
12773 the target widget). Additional signal handers can be connected if you
12774 want to know when a drag begins (at the very instant it starts), to
12775 when a drop is made, and when the entire drag-and-drop procedure has
12776 ended (successfully or not).</para>
12777
12778 <para>Your application will need to provide data for source widgets when
12779 requested, that involves having a drag data request signal handler. For
12780 destination widgets they will need a drop data received signal
12781 handler. </para>
12782
12783 <para>So a typical drag-and-drop cycle would look as follows:</para>
12784 <orderedlist>
12785 <listitem><simpara> Drag begins.</simpara>
12786 </listitem>
12787 <listitem><simpara> Drag data request (when a drop occurs).</simpara>
12788 </listitem>
12789 <listitem><simpara> Drop data received (may be on same or different
12790 application).</simpara>
12791 </listitem>
12792 <listitem><simpara> Drag data delete (if the drag was a move).</simpara>
12793 </listitem>
12794 <listitem><simpara> Drag-and-drop procedure done.</simpara>
12795 </listitem>
12796 </orderedlist>
12797
12798 <para>There are a few minor steps that go in between here and there, but we
12799 will get into detail about that later.</para>
12800
12801 </sect1>
12802
12803 <!-- ----------------------------------------------------------------- -->
12804 <sect1 id="sec-DragAndDropProperties">
12805 <title>Properties</title>
12806
12807 <para>Drag data has the following properties:</para>
12808
12809 <itemizedlist>
12810 <listitem><simpara> Drag action type (ie GDK_ACTION_COPY, GDK_ACTION_MOVE).</simpara>
12811 </listitem>
12812
12813 <listitem><simpara> Client specified arbitrary drag-and-drop type (a name and number pair).</simpara>
12814 </listitem>
12815
12816 <listitem><simpara> Sent and received data format type.</simpara>
12817 </listitem>
12818 </itemizedlist>
12819
12820 <para>Drag actions are quite obvious, they specify if the widget can
12821 drag with the specified action(s), e.g. GDK_ACTION_COPY and/or
12822 GDK_ACTION_MOVE. A GDK_ACTION_COPY would be a typical drag-and-drop
12823 without the source data being deleted while GDK_ACTION_MOVE would be
12824 just like GDK_ACTION_COPY but the source data will be 'suggested' to be
12825 deleted after the received signal handler is called. There are
12826 additional drag actions including GDK_ACTION_LINK which you may want to
12827 look into when you get to more advanced levels of drag-and-drop.</para>
12828
12829 <para>The client specified arbitrary drag-and-drop type is much more
12830 flexible, because your application will be defining and checking for
12831 that specifically. You will need to set up your destination widgets to
12832 receive certain drag-and-drop types by specifying a name and/or number.
12833 It would be more reliable to use a name since another application may
12834 just happen to use the same number for an entirely different
12835 meaning.</para>
12836
12837 <para>Sent and received data format types (<emphasis>selection
12838 target</emphasis>) come into play only in your request and received
12839 data handler functions. The term <emphasis>selection target</emphasis>
12840 is somewhat misleading. It is a term adapted from GTK+ selection
12841 (cut/copy and paste). What <emphasis>selection target</emphasis>
12842 actually means is the data's format type (i.e. GdkAtom, integer, or
12843 string) that being sent or received. Your request data handler function
12844 needs to specify the type (<emphasis>selection target</emphasis>) of
12845 data that it sends out and your received data handler needs to handle
12846 the type (<emphasis>selection target</emphasis>) of data
12847 received.</para>
12848
12849 </sect1>
12850
12851 <!-- ----------------------------------------------------------------- -->
12852 <sect1 id="sec-DragAndDropFunctions">
12853 <title>Functions</title>
12854
12855 <!-- ----------------------------------------------------------------- -->
12856 <sect2 id="sec-DNDSourceWidgets">
12857 <title>Setting up the source widget</title>
12858
12859 <para>The function <literal>gtk_drag_source_set()</literal> specifies a
12860 set of target types for a drag operation on a widget.</para>
12861
12862 <programlisting role="C">
12863 void gtk_drag_source_set( GtkWidget            *widget,
12864                           GdkModifierType       start_button_mask,
12865                           const GtkTargetEntry *targets,
12866                           gint                  n_targets,
12867                           GdkDragAction         actions );
12868 </programlisting>
12869
12870 <para>The parameters signify the following:</para>
12871 <itemizedlist>
12872 <listitem><simpara><literal>widget</literal> specifies the drag source
12873 widget</simpara>
12874 </listitem>
12875 <listitem><simpara><literal>start_button_mask</literal> specifies a
12876 bitmask of buttons that can start the drag (e.g. GDK_BUTTON1_MASK)</simpara>
12877 </listitem>
12878 <listitem><simpara><literal>targets</literal> specifies a table of
12879 target data types the drag will support</simpara>
12880 </listitem>
12881 <listitem><simpara><literal>n_targets</literal> specifies the number of
12882 targets above</simpara>
12883 </listitem>
12884 <listitem><simpara><literal>actions</literal> specifies a bitmask of
12885 possible actions for a drag from this window</simpara>
12886 </listitem>
12887 </itemizedlist>
12888
12889 <para>The <literal>targets</literal> parameter is an array of the
12890 following structure:</para>
12891
12892 <programlisting role="C">
12893 struct GtkTargetEntry {
12894    gchar *target;
12895    guint  flags;
12896    guint  info;
12897  };
12898 </programlisting>
12899
12900 <para>The fields specify a string representing the drag type, optional
12901 flags and application assigned integer identifier.</para>
12902
12903 <para>If a widget is no longer required to act as a source for
12904 drag-and-drop operations, the function
12905 <literal>gtk_drag_source_unset()</literal> can be used to remove a set
12906 of drag-and-drop target types.</para>
12907
12908 <programlisting role="C">
12909 void gtk_drag_source_unset( GtkWidget *widget );
12910 </programlisting>
12911
12912 </sect2>
12913
12914 <!-- ----------------------------------------------------------------- -->
12915 <sect2 id="sec-SignalsOnSourceWidgets">
12916 <title>Signals on the source widget:</title>
12917
12918 <para>The source widget is sent the following signals during a
12919 drag-and-drop operation.</para>
12920
12921 <table pgwide="1">
12922 <title>Source widget signals</title>
12923 <tgroup cols="2">
12924 <colspec colname="Name" colwidth="150">
12925 <colspec colname="Prototype">
12926 <tbody>
12927 <row>
12928 <entry align="left" valign="middle">drag_begin</entry>
12929 <entry align="left" valign="middle"><literal>void (*drag_begin)(GtkWidget *widget,
12930 GdkDragContext *dc, gpointer data)</literal></entry>
12931 </row>
12932 <row>
12933 <entry align="left" valign="middle">drag_motion</entry>
12934 <entry align="left" valign="middle"><literal>gboolean (*drag_motion)(GtkWidget *widget,
12935 GdkDragContext *dc, gint x, gint y, guint t, gpointer data)</literal></entry>
12936 </row>
12937 <row>
12938 <entry align="left" valign="middle">drag_data_get</entry>
12939 <entry align="left" valign="middle"><literal>void (*drag_data_get)(GtkWidget *widget,
12940 GdkDragContext *dc, GtkSelectionData *selection_data, guint info, guint t, gpointer data)</literal></entry>
12941 </row>
12942 <row>
12943 <entry align="left" valign="middle">drag_data_delete</entry>
12944 <entry align="left" valign="middle"><literal>void (*drag_data_delete)(GtkWidget *widget,
12945 GdkDragContext *dc, gpointer data)</literal></entry>
12946 </row>
12947 <row>
12948 <entry align="left" valign="middle">drag_drop</entry>
12949 <entry align="left" valign="middle"><literal>gboolean (*drag_drop)(GtkWidget *widget,
12950 GdkDragContext *dc, gint x, gint y, guint t, gpointer data)</literal></entry>
12951 </row>
12952 <row>
12953 <entry align="left" valign="middle">drag_end</entry>
12954 <entry align="left" valign="middle"><literal>void (*drag_end)(GtkWidget *widget,
12955 GdkDragContext *dc, gpointer data)</literal></entry>
12956 </row>
12957 </tbody>
12958 </tgroup>
12959 </table>
12960
12961 </sect2>
12962
12963 <!-- ----------------------------------------------------------------- -->
12964 <sect2 id="sec-DNDDestWidgets">
12965 <title>Setting up a destination widget:</title>
12966
12967 <para> <literal> gtk_drag_dest_set()</literal> specifies
12968 that this widget can receive drops and specifies what types of drops it
12969 can receive.</para>
12970
12971 <para> <literal> gtk_drag_dest_unset()</literal> specifies
12972 that the widget can no longer receive drops.</para>
12973
12974 <programlisting role="C">
12975 void gtk_drag_dest_set( GtkWidget            *widget,
12976                         GtkDestDefaults       flags,
12977                         const GtkTargetEntry *targets,
12978                         gint                  n_targets,
12979                         GdkDragAction         actions );
12980
12981 void gtk_drag_dest_unset( GtkWidget *widget );
12982 </programlisting>
12983
12984 </sect2>
12985
12986 <!-- ----------------------------------------------------------------- -->
12987 <sect2 id="sec-SignalsOnDestWidgets">
12988 <title>Signals on the destination widget:</title>
12989
12990 <para>The destination widget is sent the following signals during a
12991 drag-and-drop operation.</para>
12992
12993 <table pgwide="1">
12994 <title>Destination widget signals</title>
12995 <tgroup cols="2">
12996 <colspec colname="Name" colwidth="150">
12997 <colspec colname="Prototype">
12998 <tbody>
12999 <row>
13000 <entry align="left" valign="middle">drag_data_received</entry>
13001 <entry align="left" valign="middle"><literal>void (*drag_data_received)(GtkWidget *widget,
13002 GdkDragContext *dc, gint x, gint y, GtkSelectionData *selection_data, guint info, guint t,
13003 gpointer data)</literal></entry>
13004 </row>
13005 </tbody>
13006 </tgroup>
13007 </table>
13008
13009 </sect2>
13010 </sect1>
13011 </chapter>
13012
13013 <!-- ***************************************************************** -->
13014 <chapter id="ch-GLib">
13015 <title>GLib</title>
13016
13017 <para>GLib is a lower-level library that provides many useful definitions
13018 and functions available for use when creating GDK and GTK
13019 applications. These include definitions for basic types and their
13020 limits, standard macros, type conversions, byte order, memory
13021 allocation, warnings and assertions, message logging, timers, string
13022 utilities, hook functions, a lexical scanner, dynamic loading of
13023 modules, and automatic string completion. A number of data structures
13024 (and their related operations) are also defined, including memory
13025 chunks, doubly-linked lists, singly-linked lists, hash tables, strings
13026 (which can grow dynamically), string chunks (groups of strings),
13027 arrays (which can grow in size as elements are added), balanced binary
13028 trees, N-ary trees, quarks (a two-way association of a string and a
13029 unique integer identifier), keyed data lists (lists of data elements
13030 accessible by a string or integer id), relations and tuples (tables of
13031 data which can be indexed on any number of fields), and caches.</para>
13032
13033 <para>A summary of some of GLib's capabilities follows; not every function,
13034 data structure, or operation is covered here.  For more complete
13035 information about the GLib routines, see the GLib documentation. One
13036 source of GLib documentation is <ulink url="http://www.gtk.org/">http://www.gtk.org/</ulink>.</para>
13037
13038 <para>If you are using a language other than C, you should consult your
13039 language's binding documentation. In some cases your language may
13040 have equivalent functionality built-in, while in other cases it may
13041 not.</para>
13042
13043 <!-- ----------------------------------------------------------------- -->
13044 <sect1 id="sec-Definitions">
13045 <title>Definitions</title>
13046
13047 <para>Definitions for the extremes of many of the standard types are:</para>
13048
13049 <programlisting role="C">
13050 G_MINFLOAT
13051 G_MAXFLOAT
13052 G_MINDOUBLE
13053 G_MAXDOUBLE
13054 G_MINSHORT
13055 G_MAXSHORT
13056 G_MININT
13057 G_MAXINT
13058 G_MINLONG
13059 G_MAXLONG
13060 </programlisting>
13061
13062 <para>Also, the following typedefs. The ones left unspecified are dynamically set
13063 depending on the architecture. Remember to avoid counting on the size of a
13064 pointer if you want to be portable! E.g., a pointer on an Alpha is 8
13065 bytes, but 4 on Intel 80x86 family CPUs.</para>
13066
13067 <programlisting role="C">
13068 char   gchar;
13069 short  gshort;
13070 long   glong;
13071 int    gint;
13072 char   gboolean;
13073
13074 unsigned char   guchar;
13075 unsigned short  gushort;
13076 unsigned long   gulong;
13077 unsigned int    guint;
13078
13079 float   gfloat;
13080 double  gdouble;
13081 long double gldouble;
13082
13083 void* gpointer;
13084
13085 gint8
13086 guint8
13087 gint16
13088 guint16
13089 gint32
13090 guint32
13091 </programlisting>
13092
13093 </sect1>
13094
13095 <!-- ----------------------------------------------------------------- -->
13096 <sect1 id="sec-DoublyLinkedLists">
13097 <title>Doubly Linked Lists</title>
13098
13099 <para>The following functions are used to create, manage, and destroy
13100 standard doubly linked lists. Each element in the list contains a
13101 piece of data, together with pointers which link to the previous and
13102 next elements in the list. This enables easy movement in either
13103 direction through the list. The data item is of type "gpointer",
13104 which means the data can be a pointer to your real data or (through
13105 casting) a numeric value (but do not assume that int and gpointer have
13106 the same size!). These routines internally allocate list elements in
13107 blocks, which is more efficient than allocating elements individually.</para>
13108
13109 <para>There is no function to specifically create a list. Instead, simply
13110 create a variable of type GList* and set its value to NULL; NULL is
13111 considered to be the empty list.</para>
13112
13113 <para>To add elements to a list, use the g_list_append(), g_list_prepend(),
13114 g_list_insert(), or g_list_insert_sorted() routines. In all cases
13115 they accept a pointer to the beginning of the list, and return the
13116 (possibly changed) pointer to the beginning of the list. Thus, for
13117 all of the operations that add or remove elements, be sure to save the
13118 returned value!</para>
13119
13120 <programlisting role="C">
13121 GList *g_list_append( GList    *list,
13122                       gpointer  data );
13123 </programlisting>
13124
13125 <para>This adds a new element (with value <literal>data</literal>) onto the end of the
13126 list.</para>
13127   
13128 <programlisting role="C">
13129 GList *g_list_prepend( GList    *list,
13130                        gpointer  data );
13131 </programlisting>
13132
13133 <para>This adds a new element (with value <literal>data</literal>) to the beginning of the
13134 list.</para>
13135
13136 <programlisting role="C">
13137 GList *g_list_insert( GList    *list,
13138                       gpointer  data,
13139                       gint      position );
13140 </programlisting>
13141
13142 <para>This inserts a new element (with value data) into the list at the
13143 given position. If position is 0, this is just like g_list_prepend();
13144 if position is less than 0, this is just like g_list_append().</para>
13145
13146 <programlisting role="C">
13147 GList *g_list_remove( GList    *list,
13148                       gpointer  data );
13149 </programlisting>
13150
13151 <para>This removes the element in the list with the value <literal>data</literal>;
13152 if the element isn't there, the list is unchanged.</para>
13153
13154 <programlisting role="C">
13155 void g_list_free( GList *list );
13156 </programlisting>
13157
13158 <para>This frees all of the memory used by a GList. If the list elements
13159 refer to dynamically-allocated memory, then they should be freed
13160 first.</para>
13161
13162 <para>There are many other GLib functions that support doubly linked lists;
13163 see the glib documentation for more information.  Here are a few of
13164 the more useful functions' signatures:</para>
13165
13166 <programlisting role="C">  
13167 GList *g_list_remove_link( GList *list,
13168                            GList *link );
13169
13170 GList *g_list_reverse( GList *list );
13171
13172 GList *g_list_nth( GList *list,
13173                    gint   n );
13174                            
13175 GList *g_list_find( GList    *list,
13176                     gpointer  data );
13177
13178 GList *g_list_last( GList *list );
13179
13180 GList *g_list_first( GList *list );
13181
13182 gint g_list_length( GList *list );
13183
13184 void g_list_foreach( GList    *list,
13185                      GFunc     func,
13186                      gpointer  user_data );
13187 </programlisting>
13188
13189 </sect1>
13190
13191 <!-- ----------------------------------------------------------------- -->
13192 <sect1 id="sec-SinglyLinkedLists">
13193 <title>Singly Linked Lists</title>
13194
13195 <para>Many of the above functions for singly linked lists are identical to the
13196 above. Here is a list of some of their operations:</para>
13197
13198 <programlisting role="C">
13199 GSList *g_slist_append( GSList   *list,
13200                         gpointer  data );
13201                 
13202 GSList *g_slist_prepend( GSList   *list,
13203                          gpointer  data );
13204                              
13205 GSList *g_slist_insert( GSList   *list,
13206                         gpointer  data,
13207                         gint      position );
13208                              
13209 GSList *g_slist_remove( GSList   *list,
13210                         gpointer  data );
13211                              
13212 GSList *g_slist_remove_link( GSList *list,
13213                              GSList *link );
13214                              
13215 GSList *g_slist_reverse( GSList *list );
13216
13217 GSList *g_slist_nth( GSList *list,
13218                      gint    n );
13219                              
13220 GSList *g_slist_find( GSList   *list,
13221                       gpointer  data );
13222                              
13223 GSList *g_slist_last( GSList *list );
13224
13225 gint g_slist_length( GSList *list );
13226
13227 void g_slist_foreach( GSList   *list,
13228                       GFunc     func,
13229                       gpointer  user_data );
13230         
13231 </programlisting>
13232
13233 </sect1>
13234
13235 <!-- ----------------------------------------------------------------- -->
13236 <sect1 id="sec-MemoryManagement">
13237 <title>Memory Management</title>
13238
13239 <programlisting role="C">
13240 gpointer g_malloc( gulong size );
13241 </programlisting>
13242
13243 <para>This is a replacement for malloc(). You do not need to check the return
13244 value as it is done for you in this function. If the memory allocation
13245 fails for whatever reasons, your applications will be terminated.</para>
13246
13247 <programlisting role="C">
13248 gpointer g_malloc0( gulong size );
13249 </programlisting>
13250
13251 <para>Same as above, but zeroes the memory before returning a pointer to it.</para>
13252
13253 <programlisting role="C">
13254 gpointer g_realloc( gpointer mem,
13255                     gulong   size );
13256 </programlisting>
13257
13258 <para>Relocates "size" bytes of memory starting at "mem".  Obviously, the
13259 memory should have been previously allocated.</para>
13260
13261 <programlisting role="C">
13262 void g_free( gpointer mem );
13263 </programlisting>
13264
13265 <para>Frees memory. Easy one. If <literal>mem</literal> is NULL it simply returns.</para>
13266
13267 <programlisting role="C">
13268 void g_mem_profile( void );
13269 </programlisting>
13270
13271 <para>Dumps a profile of used memory, but requires that you add <literal>#define
13272 MEM_PROFILE</literal> to the top of glib/gmem.c and re-make and make install.</para>
13273
13274 <programlisting role="C">
13275 void g_mem_check( gpointer mem );
13276 </programlisting>
13277
13278 <para>Checks that a memory location is valid. Requires you add <literal>#define
13279 MEM_CHECK</literal> to the top of gmem.c and re-make and make install.</para>
13280
13281 </sect1>
13282
13283 <!-- ----------------------------------------------------------------- -->
13284 <sect1 id="sec-Timers">
13285 <title>Timers</title>
13286
13287 <para>Timer functions can be used to time operations (e.g., to see how much
13288 time has elapsed). First, you create a new timer with g_timer_new().
13289 You can then use g_timer_start() to start timing an operation,
13290 g_timer_stop() to stop timing an operation, and g_timer_elapsed() to
13291 determine the elapsed time.</para>
13292
13293 <programlisting role="C">
13294 GTimer *g_timer_new( void );
13295
13296 void g_timer_destroy( GTimer *timer );
13297
13298 void g_timer_start( GTimer  *timer );
13299
13300 void g_timer_stop( GTimer  *timer );
13301
13302 void g_timer_reset( GTimer  *timer );
13303
13304 gdouble g_timer_elapsed( GTimer *timer,
13305                          gulong *microseconds );
13306 </programlisting>
13307
13308 </sect1>
13309
13310 <!-- ----------------------------------------------------------------- -->
13311 <sect1 id="sec-StringHandling">
13312 <title>String Handling</title>
13313
13314 <para>GLib defines a new type called a GString, which is similar to a
13315 standard C string but one that grows automatically. Its string data
13316 is null-terminated. What this gives you is protection from buffer
13317 overflow programming errors within your program. This is a very
13318 important feature, and hence I recommend that you make use of
13319 GStrings. GString itself has a simple public definition:</para>
13320
13321 <programlisting role="C">
13322 struct GString 
13323 {
13324   gchar *str; /* Points to the string's current \0-terminated value. */
13325   gint len; /* Current length */
13326 };
13327 </programlisting>
13328
13329 <para>As you might expect, there are a number of operations you can do with
13330 a GString.</para>
13331
13332 <programlisting role="C">
13333 GString *g_string_new( gchar *init );
13334 </programlisting>
13335
13336 <para>This constructs a GString, copying the string value of <literal>init</literal>
13337 into the GString and returning a pointer to it. NULL may be given as
13338 the argument for an initially empty GString.</para>
13339
13340 <programlisting role="C">
13341 void g_string_free( GString *string,
13342                     gint     free_segment );
13343 </programlisting>
13344
13345 <para>This frees the memory for the given GString. If <literal>free_segment</literal> is
13346 TRUE, then this also frees its character data.</para>
13347
13348 <programlisting role="C">            
13349 GString *g_string_assign( GString     *lval,
13350                           const gchar *rval );
13351 </programlisting>
13352
13353 <para>This copies the characters from rval into lval, destroying the
13354 previous contents of lval. Note that lval will be lengthened as
13355 necessary to hold the string's contents, unlike the standard strcpy()
13356 function.</para>
13357
13358 <para>The rest of these functions should be relatively obvious (the _c
13359 versions accept a character instead of a string):</para>
13360              
13361 <programlisting role="C">            
13362 GString *g_string_truncate( GString *string,
13363                             gint     len );
13364                              
13365 GString *g_string_append( GString *string,
13366                           gchar   *val );
13367                             
13368 GString *g_string_append_c( GString *string,
13369                             gchar    c );
13370         
13371 GString *g_string_prepend( GString *string,
13372                            gchar   *val );
13373                              
13374 GString *g_string_prepend_c( GString *string,
13375                              gchar    c );
13376         
13377 void g_string_sprintf( GString *string,
13378                        gchar   *fmt,
13379                        ...);
13380         
13381 void g_string_sprintfa ( GString *string,
13382                          gchar   *fmt,
13383                          ... );
13384 </programlisting>
13385
13386 </sect1>
13387
13388 <!-- ----------------------------------------------------------------- -->
13389 <sect1 id="sec-UtilityAndErrorFunctions">
13390 <title>Utility and Error Functions</title>
13391
13392 <programlisting role="C">
13393 gchar *g_strdup( const gchar *str );
13394 </programlisting>
13395
13396 <para>Replacement strdup function.  Copies the original strings contents to
13397 newly allocated memory, and returns a pointer to it.</para>
13398
13399 <programlisting role="C">
13400 gchar *g_strerror( gint errnum );
13401 </programlisting>
13402
13403 <para>I recommend using this for all error messages.  It's much nicer, and more
13404 portable than perror() or others.  The output is usually of the form:</para>
13405
13406 <programlisting role="C">
13407 program name:function that failed:file or further description:strerror
13408 </programlisting>
13409
13410 <para>Here's an example of one such call used in our hello_world program:</para>
13411
13412 <programlisting role="C">
13413 g_print("hello_world:open:%s:%s\n", filename, g_strerror(errno));
13414 </programlisting>
13415
13416 <programlisting role="C">
13417 void g_error( gchar *format, ... );
13418 </programlisting>
13419
13420 <para>Prints an error message. The format is just like printf, but it
13421 prepends "** ERROR **: " to your message, and exits the program.  
13422 Use only for fatal errors.</para>
13423
13424 <programlisting role="C">
13425 void g_warning( gchar *format, ... );
13426 </programlisting>
13427
13428 <para>Same as above, but prepends "** WARNING **: ", and does not exit the
13429 program.</para>
13430
13431 <programlisting role="C">
13432 void g_message( gchar *format, ... );
13433 </programlisting>
13434
13435 <para>Prints "message: " prepended to the string you pass in.</para>
13436
13437 <programlisting role="C">
13438 void g_print( gchar *format, ... );
13439 </programlisting>
13440
13441 <para>Replacement for printf().</para>
13442
13443 <para>And our last function:</para>
13444
13445 <programlisting role="C">
13446 gchar *g_strsignal( gint signum );
13447 </programlisting>
13448
13449 <para>Prints out the name of the Unix system signal given the signal number.
13450 Useful in generic signal handling functions.</para>
13451
13452 <para>All of the above are more or less just stolen from glib.h.  If anyone cares
13453 to document any function, just send me an email!</para>
13454
13455 </sect1>
13456 </chapter>
13457
13458 <!-- ***************************************************************** -->
13459 <chapter id="ch-GTKRCFiles">
13460 <title>GTK's rc Files</title>
13461
13462 <para>GTK has its own way of dealing with application defaults, by using rc
13463 files. These can be used to set the colors of just about any widget, and
13464 can also be used to tile pixmaps onto the background of some widgets.  </para>
13465
13466 <!-- ----------------------------------------------------------------- -->
13467 <sect1 id="sec-FunctionsForRCFiles">
13468 <title>Functions For rc Files</title>
13469
13470 <para>When your application starts, you should include a call to:</para>
13471
13472 <programlisting role="C">
13473 void gtk_rc_parse( char *filename );
13474 </programlisting>
13475
13476 <para>Passing in the filename of your rc file. This will cause GTK to parse
13477 this file, and use the style settings for the widget types defined
13478 there.</para>
13479
13480 <para>If you wish to have a special set of widgets that can take on a
13481 different style from others, or any other logical division of widgets,
13482 use a call to:</para>
13483
13484 <programlisting role="C">
13485 void gtk_widget_set_name( GtkWidget *widget,
13486                           gchar     *name );
13487 </programlisting>
13488
13489 <para>Passing your newly created widget as the first argument, and the name
13490 you wish to give it as the second. This will allow you to change the
13491 attributes of this widget by name through the rc file.</para>
13492
13493 <para>If we use a call something like this:</para>
13494
13495 <programlisting role="C">
13496 button = gtk_button_new_with_label ("Special Button");
13497 gtk_widget_set_name (button, "special button");
13498 </programlisting>
13499
13500 <para>Then this button is given the name "special button" and may be addressed by
13501 name in the rc file as "special button.GtkButton".  [<--- Verify ME!]</para>
13502
13503 <para>The example rc file below, sets the properties of the main window, and lets
13504 all children of that main window inherit the style described by the "main
13505 button" style.  The code used in the application is:</para>
13506
13507 <programlisting role="C">
13508 window = gtk_window_new (GTK_WINDOW_TOPLEVEL);
13509 gtk_widget_set_name (window, "main window");
13510 </programlisting>
13511
13512 <para>And then the style is defined in the rc file using:</para>
13513
13514 <programlisting role="C">
13515 widget "main window.*GtkButton*" style "main_button"
13516 </programlisting>
13517
13518 <para>Which sets all the Button widgets in the "main window" to the
13519 "main_buttons" style as defined in the rc file.</para>
13520
13521 <para>As you can see, this is a fairly powerful and flexible system.  Use your
13522 imagination as to how best to take advantage of this.</para>
13523
13524 </sect1>
13525
13526 <!-- ----------------------------------------------------------------- -->
13527 <sect1 id="sec-GTKsRCFileFormat">
13528 <title>GTK's rc File Format</title>
13529
13530 <para>The format of the GTK file is illustrated in the example below. This is
13531 the testgtkrc file from the GTK distribution, but I've added a
13532 few comments and things. You may wish to include this explanation in
13533 your application to allow the user to fine tune his application.</para>
13534
13535 <para>There are several directives to change the attributes of a widget.</para>
13536
13537 <itemizedlist>
13538 <listitem><simpara>fg - Sets the foreground color of a widget.</simpara>
13539 </listitem>
13540 <listitem><simpara>bg - Sets the background color of a widget.</simpara>
13541 </listitem>
13542 <listitem><simpara>bg_pixmap - Sets the background of a widget to a tiled pixmap.</simpara>
13543 </listitem>
13544 <listitem><simpara>font - Sets the font to be used with the given widget.</simpara>
13545 </listitem>
13546 </itemizedlist>
13547
13548 <para>In addition to this, there are several states a widget can be in, and you
13549 can set different colors, pixmaps and fonts for each state. These states are:</para>
13550
13551 <itemizedlist>
13552 <listitem><simpara>NORMAL - The normal state of a widget, without the mouse over top of
13553 it, and not being pressed, etc.</simpara>
13554 </listitem>
13555 <listitem><simpara>PRELIGHT - When the mouse is over top of the widget, colors defined
13556 using this state will be in effect.</simpara>
13557 </listitem>
13558 <listitem><simpara>ACTIVE - When the widget is pressed or clicked it will be active, and
13559 the attributes assigned by this tag will be in effect.</simpara>
13560 </listitem>
13561 <listitem><simpara>INSENSITIVE - When a widget is set insensitive, and cannot be
13562 activated, it will take these attributes.</simpara>
13563 </listitem>
13564 <listitem><simpara>SELECTED - When an object is selected, it takes these attributes.</simpara>
13565 </listitem>
13566 </itemizedlist>
13567
13568 <para>When using the "fg" and "bg" keywords to set the colors of widgets, the
13569 format is:</para>
13570
13571 <programlisting role="C">
13572 fg[&lt;STATE>] = { Red, Green, Blue }
13573 </programlisting>
13574
13575 <para>Where STATE is one of the above states (PRELIGHT, ACTIVE, etc), and the Red,
13576 Green and Blue are values in the range of 0 - 1.0,  { 1.0, 1.0, 1.0 } being
13577 white. They must be in float form, or they will register as 0, so a straight 
13578 "1" will not work, it must be "1.0".  A straight "0" is fine because it 
13579 doesn't matter if it's not recognized.  Unrecognized values are set to 0.</para>
13580
13581 <para>bg_pixmap is very similar to the above, except the colors are replaced by a
13582 filename.</para>
13583
13584 <para>pixmap_path is a list of paths separated by ":"'s.  These paths will be
13585 searched for any pixmap you specify.</para>
13586
13587 <para>The font directive is simply:</para>
13588
13589 <programlisting role="C">
13590 font = "&lt;font name>"
13591 </programlisting>
13592
13593 <para>The only hard part is figuring out the font string. Using xfontsel or
13594 a similar utility should help.</para>
13595
13596 <para>The "widget_class" sets the style of a class of widgets. These classes are
13597 listed in the widget overview on the class hierarchy.</para>
13598
13599 <para>The "widget" directive sets a specifically named set of widgets to a
13600 given style, overriding any style set for the given widget class.
13601 These widgets are registered inside the application using the
13602 gtk_widget_set_name() call. This allows you to specify the attributes of a
13603 widget on a per widget basis, rather than setting the attributes of an
13604 entire widget class. I urge you to document any of these special widgets so
13605 users may customize them.</para>
13606
13607 <para>When the keyword <literal>parent</> is used as an attribute, the widget will take on
13608 the attributes of its parent in the application.</para>
13609
13610 <para>When defining a style, you may assign the attributes of a previously defined
13611 style to this new one.</para>
13612
13613 <programlisting role="C">
13614 style "main_button" = "button"
13615 {
13616   font = "-adobe-helvetica-medium-r-normal--*-100-*-*-*-*-*-*"
13617   bg[PRELIGHT] = { 0.75, 0, 0 }
13618 }
13619 </programlisting>
13620
13621 <para>This example takes the "button" style, and creates a new "main_button" style
13622 simply by changing the font and prelight background color of the "button"
13623 style.</para>
13624
13625 <para>Of course, many of these attributes don't apply to all widgets. It's a
13626 simple matter of common sense really. Anything that could apply, should.</para>
13627
13628 </sect1>
13629
13630 <!-- ----------------------------------------------------------------- -->
13631 <sect1 id="sec-ExampleRCFile">
13632 <title>Example rc file</title>
13633
13634 <programlisting role="C">
13635 # pixmap_path "&lt;dir 1>:&lt;dir 2>:&lt;dir 3>:..."
13636 #
13637 pixmap_path "/usr/include/X11R6/pixmaps:/home/imain/pixmaps"
13638 #
13639 # style &lt;name> [= &lt;name>]
13640 # {
13641 #   &lt;option>
13642 # }
13643 #
13644 # widget &lt;widget_set> style &lt;style_name>
13645 # widget_class &lt;widget_class_set> style &lt;style_name>
13646
13647 # Here is a list of all the possible states.  Note that some do not apply to
13648 # certain widgets.
13649 #
13650 # NORMAL - The normal state of a widget, without the mouse over top of
13651 # it, and not being pressed, etc.
13652 #
13653 # PRELIGHT - When the mouse is over top of the widget, colors defined
13654 # using this state will be in effect.
13655 #
13656 # ACTIVE - When the widget is pressed or clicked it will be active, and
13657 # the attributes assigned by this tag will be in effect.
13658 #
13659 # INSENSITIVE - When a widget is set insensitive, and cannot be
13660 # activated, it will take these attributes.
13661 #
13662 # SELECTED - When an object is selected, it takes these attributes.
13663 #
13664 # Given these states, we can set the attributes of the widgets in each of
13665 # these states using the following directives.
13666 #
13667 # fg - Sets the foreground color of a widget.
13668 # fg - Sets the background color of a widget.
13669 # bg_pixmap - Sets the background of a widget to a tiled pixmap.
13670 # font - Sets the font to be used with the given widget.
13671 #
13672
13673 # This sets a style called "button".  The name is not really important, as
13674 # it is assigned to the actual widgets at the bottom of the file.
13675
13676 style "window"
13677 {
13678   #This sets the padding around the window to the pixmap specified.
13679   #bg_pixmap[&lt;STATE>] = "&lt;pixmap filename>"
13680   bg_pixmap[NORMAL] = "warning.xpm"
13681 }
13682
13683 style "scale"
13684 {
13685   #Sets the foreground color (font color) to red when in the "NORMAL"
13686   #state.
13687   
13688   fg[NORMAL] = { 1.0, 0, 0 }
13689   
13690   #Sets the background pixmap of this widget to that of its parent.
13691   bg_pixmap[NORMAL] = "&lt;parent>"
13692 }
13693
13694 style "button"
13695 {
13696   # This shows all the possible states for a button.  The only one that
13697   # doesn't apply is the SELECTED state.
13698   
13699   fg[PRELIGHT] = { 0, 1.0, 1.0 }
13700   bg[PRELIGHT] = { 0, 0, 1.0 }
13701   bg[ACTIVE] = { 1.0, 0, 0 }
13702   fg[ACTIVE] = { 0, 1.0, 0 }
13703   bg[NORMAL] = { 1.0, 1.0, 0 }
13704   fg[NORMAL] = { .99, 0, .99 }
13705   bg[INSENSITIVE] = { 1.0, 1.0, 1.0 }
13706   fg[INSENSITIVE] = { 1.0, 0, 1.0 }
13707 }
13708
13709 # In this example, we inherit the attributes of the "button" style and then
13710 # override the font and background color when prelit to create a new
13711 # "main_button" style.
13712
13713 style "main_button" = "button"
13714 {
13715   font = "-adobe-helvetica-medium-r-normal--*-100-*-*-*-*-*-*"
13716   bg[PRELIGHT] = { 0.75, 0, 0 }
13717 }
13718
13719 style "toggle_button" = "button"
13720 {
13721   fg[NORMAL] = { 1.0, 0, 0 }
13722   fg[ACTIVE] = { 1.0, 0, 0 }
13723   
13724   # This sets the background pixmap of the toggle_button to that of its
13725   # parent widget (as defined in the application).
13726   bg_pixmap[NORMAL] = "&lt;parent>"
13727 }
13728
13729 style "text"
13730 {
13731   bg_pixmap[NORMAL] = "marble.xpm"
13732   fg[NORMAL] = { 1.0, 1.0, 1.0 }
13733 }
13734
13735 style "ruler"
13736 {
13737   font = "-adobe-helvetica-medium-r-normal--*-80-*-*-*-*-*-*"
13738 }
13739
13740 # pixmap_path "~/.pixmaps"
13741
13742 # These set the widget types to use the styles defined above.
13743 # The widget types are listed in the class hierarchy, but could probably be
13744 # just listed in this document for the users reference.
13745
13746 widget_class "GtkWindow" style "window"
13747 widget_class "GtkDialog" style "window"
13748 widget_class "GtkFileSelection" style "window"
13749 widget_class "*Gtk*Scale" style "scale"
13750 widget_class "*GtkCheckButton*" style "toggle_button"
13751 widget_class "*GtkRadioButton*" style "toggle_button"
13752 widget_class "*GtkButton*" style "button"
13753 widget_class "*Ruler" style "ruler"
13754 widget_class "*GtkText" style "text"
13755
13756 # This sets all the buttons that are children of the "main window" to
13757 # the main_button style.  These must be documented to be taken advantage of.
13758 widget "main window.*GtkButton*" style "main_button"
13759 </programlisting>
13760
13761 </sect1>
13762 </chapter>
13763
13764 <!-- ***************************************************************** -->
13765 <chapter id="ch-WritingYourOwnWidgets">
13766 <title>Writing Your Own Widgets</title>
13767
13768 <!-- ----------------------------------------------------------------- -->
13769 <sect1 id="sec-WidgetsOverview">
13770 <title>Overview</title>
13771
13772 <para>Although the GTK distribution comes with many types of widgets that
13773 should cover most basic needs, there may come a time when you need to
13774 create your own new widget type. Since GTK uses widget inheritance
13775 extensively, and there is already a widget that is close to what you want,
13776 it is often possible to make a useful new widget type in
13777 just a few lines of code. But before starting work on a new widget, check
13778 around first to make sure that someone has not already written
13779 it. This will prevent duplication of effort and keep the number of
13780 GTK widgets out there to a minimum, which will help keep both the code
13781 and the interface of different applications consistent. As a flip side
13782 to this, once you finish your widget, announce it to the world so
13783 other people can benefit. The best place to do this is probably the
13784 <literal>gtk-list</literal>.</para>
13785
13786 <para>Complete sources for the example widgets are available at the place you 
13787 got this tutorial, or from:</para>
13788
13789 <para><ulink url="http://www.gtk.org/~otaylor/gtk/tutorial/">http://www.gtk.org/~otaylor/gtk/tutorial/</ulink></para>
13790
13791
13792 </sect1>
13793
13794 <!-- ----------------------------------------------------------------- -->
13795 <sect1 id="sec-TheAnatomyOfAWidget">
13796 <title>The Anatomy Of A Widget</title>
13797
13798 <para>In order to create a new widget, it is important to have an
13799 understanding of how GTK objects work. This section is just meant as a
13800 brief overview. See the reference documentation for the details. </para>
13801
13802 <para>GTK widgets are implemented in an object oriented fashion. However,
13803 they are implemented in standard C. This greatly improves portability
13804 and stability over using current generation C++ compilers; however,
13805 it does mean that the widget writer has to pay attention to some of
13806 the implementation details. The information common to all instances of
13807 one class of widgets (e.g., to all Button widgets) is stored in the 
13808 <emphasis>class structure</emphasis>. There is only one copy of this in
13809 which is stored information about the class's signals
13810 (which act like virtual functions in C). To support inheritance, the
13811 first field in the class structure must be a copy of the parent's
13812 class structure. The declaration of the class structure of GtkButtton
13813 looks like:</para>
13814
13815 <programlisting role="C">
13816 struct _GtkButtonClass
13817 {
13818   GtkContainerClass parent_class;
13819
13820   void (* pressed)  (GtkButton *button);
13821   void (* released) (GtkButton *button);
13822   void (* clicked)  (GtkButton *button);
13823   void (* enter)    (GtkButton *button);
13824   void (* leave)    (GtkButton *button);
13825 };
13826 </programlisting>
13827
13828 <para>When a button is treated as a container (for instance, when it is
13829 resized), its class structure can be cast to GtkContainerClass, and
13830 the relevant fields used to handle the signals.</para>
13831
13832 <para>There is also a structure for each widget that is created on a
13833 per-instance basis. This structure has fields to store information that
13834 is different for each instance of the widget. We'll call this
13835 structure the <emphasis>object structure</emphasis>. For the Button class, it looks
13836 like:</para>
13837
13838 <programlisting role="C">
13839 struct _GtkButton
13840 {
13841   GtkContainer container;
13842
13843   GtkWidget *child;
13844
13845   guint in_button : 1;
13846   guint button_down : 1;
13847 };
13848 </programlisting>
13849
13850 <para>Note that, similar to the class structure, the first field is the
13851 object structure of the parent class, so that this structure can be
13852 cast to the parent class' object structure as needed.</para>
13853
13854 </sect1>
13855
13856 <!-- ----------------------------------------------------------------- -->
13857 <sect1 id="sec-CreatingACompositeWidget">
13858 <title>Creating a Composite widget</title>
13859
13860 <!-- ----------------------------------------------------------------- -->
13861 <sect2>
13862 <title>Introduction</title>
13863
13864 <para>One type of widget that you may be interested in creating is a
13865 widget that is merely an aggregate of other GTK widgets. This type of
13866 widget does nothing that couldn't be done without creating new
13867 widgets, but provides a convenient way of packaging user interface
13868 elements for reuse. The FileSelection and ColorSelection widgets in
13869 the standard distribution are examples of this type of widget.</para>
13870
13871 <para>The example widget that we'll create in this section is the Tictactoe
13872 widget, a 3x3 array of toggle buttons which triggers a signal when all
13873 three buttons in a row, column, or on one of the diagonals are
13874 depressed. </para>
13875
13876 </sect2>
13877
13878 <!-- ----------------------------------------------------------------- -->
13879 <sect2>
13880 <title>Choosing a parent class</title>
13881
13882 <para>The parent class for a composite widget is typically the container
13883 class that holds all of the elements of the composite widget. For
13884 example, the parent class of the FileSelection widget is the
13885 Dialog class. Since our buttons will be arranged in a table, it
13886 might seem natural to make our parent class the Table
13887 class. Unfortunately, this turns out not to work. The creation of a
13888 widget is divided among two functions - a <literal>WIDGETNAME_new()</literal>
13889 function that the user calls, and a <literal>WIDGETNAME_init()</literal> function
13890 which does the basic work of initializing the widget which is
13891 independent of the arguments passed to the <literal>_new()</literal>
13892 function. Descendant widgets only call the <literal>_init</literal> function of
13893 their parent widget. But this division of labor doesn't work well for
13894 tables, which when created need to know the number of rows and
13895 columns in the table. Unless we want to duplicate most of the
13896 functionality of <literal>gtk_table_new()</literal> in our Tictactoe widget, we had
13897 best avoid deriving it from Table. For that reason, we derive it
13898 from VBox instead, and stick our table inside the VBox.</para>
13899
13900 </sect2>
13901
13902 <!-- ----------------------------------------------------------------- -->
13903 <sect2>
13904 <title>The header file</title>
13905
13906 <para>Each widget class has a header file which declares the object and
13907 class structures for that widget, along with public functions. 
13908 A couple of features are worth pointing out. To prevent duplicate
13909 definitions, we wrap the entire header file in:</para>
13910
13911 <programlisting role="C">
13912 #ifndef __TICTACTOE_H__
13913 #define __TICTACTOE_H__
13914 .
13915 .
13916 .
13917 #endif /* __TICTACTOE_H__ */
13918 </programlisting>
13919
13920 <para>And to keep C++ programs that include the header file happy, in:</para>
13921
13922 <programlisting role="C">
13923 #ifdef __cplusplus
13924 extern "C" {
13925 #endif /* __cplusplus */
13926 .
13927 .
13928 .
13929 #ifdef __cplusplus
13930 }
13931 #endif /* __cplusplus */
13932 </programlisting>
13933
13934 <para>Along with the functions and structures, we declare three standard
13935 macros in our header file, <literal>TICTACTOE(obj)</literal>,
13936 <literal>TICTACTOE_CLASS(klass)</literal>, and <literal>IS_TICTACTOE(obj)</literal>, which cast a
13937 pointer into a pointer to the object or class structure, and check
13938 if an object is a Tictactoe widget respectively.</para>
13939
13940 <para>Here is the complete header file:</para>
13941
13942 <programlisting role="C">
13943 /* tictactoe.h */
13944
13945 #ifndef __TICTACTOE_H__
13946 #define __TICTACTOE_H__
13947
13948 #include &lt;gdk/gdk.h&gt;
13949 #include &lt;gtk/gtkvbox.h&gt;
13950
13951 #ifdef __cplusplus
13952 extern "C" {
13953 #endif /* __cplusplus */
13954
13955 #define TICTACTOE(obj)          GTK_CHECK_CAST (obj, tictactoe_get_type (), Tictactoe)
13956 #define TICTACTOE_CLASS(klass)  GTK_CHECK_CLASS_CAST (klass, tictactoe_get_type (), TictactoeClass)
13957 #define IS_TICTACTOE(obj)       GTK_CHECK_TYPE (obj, tictactoe_get_type ())
13958
13959
13960 typedef struct _Tictactoe       Tictactoe;
13961 typedef struct _TictactoeClass  TictactoeClass;
13962
13963 struct _Tictactoe
13964 {
13965   GtkVBox vbox;
13966   
13967   GtkWidget *buttons[3][3];
13968 };
13969
13970 struct _TictactoeClass
13971 {
13972   GtkVBoxClass parent_class;
13973
13974   void (* tictactoe) (Tictactoe *ttt);
13975 };
13976
13977 GtkType        tictactoe_get_type        (void);
13978 GtkWidget*     tictactoe_new             (void);
13979 void           tictactoe_clear           (Tictactoe *ttt);
13980
13981 #ifdef __cplusplus
13982 }
13983 #endif /* __cplusplus */
13984
13985 #endif /* __TICTACTOE_H__ */
13986 </programlisting>
13987
13988 </sect2>
13989
13990 <!-- ----------------------------------------------------------------- -->
13991 <sect2>
13992 <title>The <literal>_get_type()</literal> function</title>
13993
13994 <para>We now continue on to the implementation of our widget. A core
13995 function for every widget is the function
13996 <literal>WIDGETNAME_get_type()</literal>. This function, when first called, tells
13997 GTK about the widget class, and gets an ID that uniquely identifies
13998 the widget class. Upon subsequent calls, it just returns the ID.</para>
13999
14000 <programlisting role="C">
14001 GtkType
14002 tictactoe_get_type ()
14003 {
14004   static guint ttt_type = 0;
14005
14006   if (!ttt_type)
14007     {
14008       GtkTypeInfo ttt_info =
14009       {
14010         "Tictactoe",
14011         sizeof (Tictactoe),
14012         sizeof (TictactoeClass),
14013         (GtkClassInitFunc) tictactoe_class_init,
14014         (GtkObjectInitFunc) tictactoe_init,
14015         (GtkArgSetFunc) NULL,
14016         (GtkArgGetFunc) NULL
14017       };
14018
14019       ttt_type = gtk_type_unique (gtk_vbox_get_type (), &amp;ttt_info);
14020     }
14021
14022   return ttt_type;
14023 }
14024 </programlisting>
14025
14026 <para>The GtkTypeInfo structure has the following definition:</para>
14027
14028 <programlisting role="C">
14029 struct _GtkTypeInfo
14030 {
14031   gchar *type_name;
14032   guint object_size;
14033   guint class_size;
14034   GtkClassInitFunc class_init_func;
14035   GtkObjectInitFunc object_init_func;
14036   GtkArgSetFunc arg_set_func;
14037   GtkArgGetFunc arg_get_func;
14038 };
14039 </programlisting>
14040
14041 <para>The fields of this structure are pretty self-explanatory. We'll ignore
14042 the <literal>arg_set_func</literal> and <literal>arg_get_func</literal> fields here: they have an important, 
14043 but as yet largely
14044 unimplemented, role in allowing widget options to be conveniently set
14045 from interpreted languages. Once GTK has a correctly filled in copy of
14046 this structure, it knows how to create objects of a particular widget
14047 type. </para>
14048
14049 </sect2>
14050
14051 <!-- ----------------------------------------------------------------- -->
14052 <sect2>
14053 <title>The <literal>_class_init()</literal> function</title>
14054
14055 <para>The <literal>WIDGETNAME_class_init()</literal> function initializes the fields of
14056 the widget's class structure, and sets up any signals for the
14057 class. For our Tictactoe widget it looks like:</para>
14058
14059 <programlisting role="C">
14060 enum {
14061   TICTACTOE_SIGNAL,
14062   LAST_SIGNAL
14063 };
14064
14065
14066 static gint tictactoe_signals[LAST_SIGNAL] = { 0 };
14067
14068 static void
14069 tictactoe_class_init (TictactoeClass *class)
14070 {
14071   GtkObjectClass *object_class;
14072
14073   object_class = (GtkObjectClass*) class;
14074   
14075   tictactoe_signals[TICTACTOE_SIGNAL] = gtk_signal_new ("tictactoe",
14076                                          GTK_RUN_FIRST,
14077                                          object_class->type,
14078                                          GTK_SIGNAL_OFFSET (TictactoeClass, tictactoe),
14079                                          gtk_signal_default_marshaller, GTK_TYPE_NONE, 0);
14080
14081
14082   gtk_object_class_add_signals (object_class, tictactoe_signals, LAST_SIGNAL);
14083
14084   class->tictactoe = NULL;
14085 }
14086 </programlisting>
14087
14088 <para>Our widget has just one signal, the <literal>tictactoe</literal> signal that is
14089 invoked when a row, column, or diagonal is completely filled in. Not
14090 every composite widget needs signals, so if you are reading this for
14091 the first time, you may want to skip to the next section now, as
14092 things are going to get a bit complicated.</para>
14093
14094 <para>The function:</para>
14095
14096 <programlisting role="C">
14097 gint gtk_signal_new( const gchar         *name,
14098                      GtkSignalRunType     run_type,
14099                      GtkType              object_type,
14100                      gint                 function_offset,
14101                      GtkSignalMarshaller  marshaller,
14102                      GtkType              return_val,
14103                      guint                nparams,
14104                      ...);
14105 </programlisting>
14106
14107 <para>Creates a new signal. The parameters are:</para>
14108
14109 <itemizedlist>
14110 <listitem><simpara> <literal>name</literal>: The name of the signal.</simpara>
14111 </listitem>
14112
14113 <listitem><simpara> <literal>run_type</literal>: Whether the default handler runs before or after
14114 user handlers. Usually this will be <literal>GTK_RUN_FIRST</literal>, or <literal>GTK_RUN_LAST</literal>,
14115 although there are other possibilities.</simpara>
14116 </listitem>
14117
14118 <listitem><simpara> <literal>object_type</literal>: The ID of the object that this signal applies
14119 to. (It will also apply to that objects descendants.)</simpara>
14120 </listitem>
14121
14122 <listitem><simpara> <literal>function_offset</literal>: The offset within the class structure of
14123 a pointer to the default handler.</simpara>
14124 </listitem>
14125
14126 <listitem><simpara> <literal>marshaller</literal>: A function that is used to invoke the signal
14127 handler. For signal handlers that have no arguments other than the
14128 object that emitted the signal and user data, we can use the
14129 pre-supplied marshaller function <literal>gtk_signal_default_marshaller</literal>.</simpara>
14130 </listitem>
14131
14132 <listitem><simpara> <literal>return_val</literal>: The type of the return val.</simpara>
14133 </listitem>
14134
14135 <listitem><simpara> <literal>nparams</literal>: The number of parameters of the signal handler
14136 (other than the two default ones mentioned above)</simpara>
14137 </listitem>
14138
14139 <listitem><simpara> <literal>...</literal>: The types of the parameters.</simpara>
14140 </listitem>
14141 </itemizedlist>
14142
14143 <para>When specifying types, the <literal>GtkType</literal> enumeration is used:</para>
14144
14145 <programlisting role="C">
14146 typedef enum
14147 {
14148   GTK_TYPE_INVALID,
14149   GTK_TYPE_NONE,
14150   GTK_TYPE_CHAR,
14151   GTK_TYPE_BOOL,
14152   GTK_TYPE_INT,
14153   GTK_TYPE_UINT,
14154   GTK_TYPE_LONG,
14155   GTK_TYPE_ULONG,
14156   GTK_TYPE_FLOAT,
14157   GTK_TYPE_DOUBLE,
14158   GTK_TYPE_STRING,
14159   GTK_TYPE_ENUM,
14160   GTK_TYPE_FLAGS,
14161   GTK_TYPE_BOXED,
14162   GTK_TYPE_FOREIGN,
14163   GTK_TYPE_CALLBACK,
14164   GTK_TYPE_ARGS,
14165
14166   GTK_TYPE_POINTER,
14167
14168   /* it'd be great if the next two could be removed eventually */
14169   GTK_TYPE_SIGNAL,
14170   GTK_TYPE_C_CALLBACK,
14171
14172   GTK_TYPE_OBJECT
14173
14174 } GtkFundamentalType;
14175 </programlisting>
14176
14177 <para><literal>gtk_signal_new()</literal> returns a unique integer identifier for the
14178 signal, that we store in the <literal>tictactoe_signals</literal> array, which we
14179 index using an enumeration. (Conventionally, the enumeration elements
14180 are the signal name, uppercased, but here there would be a conflict
14181 with the <literal>TICTACTOE()</literal> macro, so we called it <literal>TICTACTOE_SIGNAL</literal>
14182 instead.</para>
14183
14184 <para>After creating our signals, we need to tell GTK to associate our
14185 signals with the Tictactoe class. We do that by calling
14186 <literal>gtk_object_class_add_signals()</literal>. We then set the pointer which
14187 points to the default handler for the "tictactoe" signal to NULL,
14188 indicating that there is no default action.</para>
14189
14190 </sect2>
14191
14192 <!-- ----------------------------------------------------------------- -->
14193 <sect2>
14194 <title>The <literal>_init()</literal> function</title>
14195
14196 <para>Each widget class also needs a function to initialize the object
14197 structure. Usually, this function has the fairly limited role of
14198 setting the fields of the structure to default values. For composite
14199 widgets, however, this function also creates the component widgets.</para>
14200
14201 <programlisting role="C">
14202 static void
14203 tictactoe_init (Tictactoe *ttt)
14204 {
14205   GtkWidget *table;
14206   gint i,j;
14207   
14208   table = gtk_table_new (3, 3, TRUE);
14209   gtk_container_add (GTK_CONTAINER(ttt), table);
14210   gtk_widget_show (table);
14211
14212   for (i=0;i<3; i++)
14213     for (j=0;j<3; j++)
14214       {
14215         ttt->buttons[i][j] = gtk_toggle_button_new ();
14216         gtk_table_attach_defaults (GTK_TABLE(table), ttt->buttons[i][j], 
14217                                    i, i+1, j, j+1);
14218         gtk_signal_connect (GTK_OBJECT (ttt->buttons[i][j]), "toggled",
14219                             GTK_SIGNAL_FUNC (tictactoe_toggle), ttt);
14220         gtk_widget_set_usize (ttt->buttons[i][j], 20, 20);
14221         gtk_widget_show (ttt->buttons[i][j]);
14222       }
14223 }
14224 </programlisting>
14225
14226 </sect2>
14227
14228 <!-- ----------------------------------------------------------------- -->
14229 <sect2>
14230 <title>And the rest...</title>
14231
14232 <para>There is one more function that every widget (except for base widget
14233 types like Bin that cannot be instantiated) needs to have - the
14234 function that the user calls to create an object of that type. This is
14235 conventionally called <literal>WIDGETNAME_new()</literal>. In some
14236 widgets, though not for the Tictactoe widgets, this function takes
14237 arguments, and does some setup based on the arguments. The other two
14238 functions are specific to the Tictactoe widget. </para>
14239
14240 <para><literal>tictactoe_clear()</literal> is a public function that resets all the
14241 buttons in the widget to the up position. Note the use of
14242 <literal>gtk_signal_handler_block_by_data()</literal> to keep our signal handler for
14243 button toggles from being triggered unnecessarily.</para>
14244
14245 <para><literal>tictactoe_toggle()</literal> is the signal handler that is invoked when the
14246 user clicks on a button. It checks to see if there are any winning
14247 combinations that involve the toggled button, and if so, emits
14248 the "tictactoe" signal.</para>
14249
14250 <programlisting role="C">
14251 GtkWidget*
14252 tictactoe_new ()
14253 {
14254   return GTK_WIDGET ( gtk_type_new (tictactoe_get_type ()));
14255 }
14256
14257 void           
14258 tictactoe_clear (Tictactoe *ttt)
14259 {
14260   int i,j;
14261
14262   for (i=0;i<3;i++)
14263     for (j=0;j<3;j++)
14264       {
14265         gtk_signal_handler_block_by_data (GTK_OBJECT(ttt->buttons[i][j]), ttt);
14266         gtk_toggle_button_set_active (GTK_TOGGLE_BUTTON (ttt->buttons[i][j]),
14267                                      FALSE);
14268         gtk_signal_handler_unblock_by_data (GTK_OBJECT(ttt->buttons[i][j]), ttt);
14269       }
14270 }
14271
14272 static void
14273 tictactoe_toggle (GtkWidget *widget, Tictactoe *ttt)
14274 {
14275   int i,k;
14276
14277   static int rwins[8][3] = { { 0, 0, 0 }, { 1, 1, 1 }, { 2, 2, 2 },
14278                              { 0, 1, 2 }, { 0, 1, 2 }, { 0, 1, 2 },
14279                              { 0, 1, 2 }, { 0, 1, 2 } };
14280   static int cwins[8][3] = { { 0, 1, 2 }, { 0, 1, 2 }, { 0, 1, 2 },
14281                              { 0, 0, 0 }, { 1, 1, 1 }, { 2, 2, 2 },
14282                              { 0, 1, 2 }, { 2, 1, 0 } };
14283
14284   int success, found;
14285
14286   for (k=0; k<8; k++)
14287     {
14288       success = TRUE;
14289       found = FALSE;
14290
14291       for (i=0;i<3;i++)
14292         {
14293           success = success &amp;&amp; 
14294             GTK_TOGGLE_BUTTON(ttt->buttons[rwins[k][i]][cwins[k][i]])->active;
14295           found = found ||
14296             ttt->buttons[rwins[k][i]][cwins[k][i]] == widget;
14297         }
14298       
14299       if (success &amp;&amp; found)
14300         {
14301           gtk_signal_emit (GTK_OBJECT (ttt), 
14302                            tictactoe_signals[TICTACTOE_SIGNAL]);
14303           break;
14304         }
14305     }
14306 }
14307 </programlisting>
14308
14309 <para>And finally, an example program using our Tictactoe widget:</para>
14310
14311 <programlisting role="C">
14312 #include &lt;gtk/gtk.h&gt;
14313 #include "tictactoe.h"
14314
14315 /* Invoked when a row, column or diagonal is completed */
14316 void
14317 win (GtkWidget *widget, gpointer data)
14318 {
14319   g_print ("Yay!\n");
14320   tictactoe_clear (TICTACTOE (widget));
14321 }
14322
14323 int 
14324 main (int argc, char *argv[])
14325 {
14326   GtkWidget *window;
14327   GtkWidget *ttt;
14328   
14329   gtk_init (&amp;argc, &amp;argv);
14330
14331   window = gtk_window_new (GTK_WINDOW_TOPLEVEL);
14332   
14333   gtk_window_set_title (GTK_WINDOW (window), "Aspect Frame");
14334   
14335   gtk_signal_connect (GTK_OBJECT (window), "destroy",
14336                       GTK_SIGNAL_FUNC (gtk_exit), NULL);
14337   
14338   gtk_container_set_border_width (GTK_CONTAINER (window), 10);
14339
14340   /* Create a new Tictactoe widget */
14341   ttt = tictactoe_new ();
14342   gtk_container_add (GTK_CONTAINER (window), ttt);
14343   gtk_widget_show (ttt);
14344
14345   /* And attach to its "tictactoe" signal */
14346   gtk_signal_connect (GTK_OBJECT (ttt), "tictactoe",
14347                       GTK_SIGNAL_FUNC (win), NULL);
14348
14349   gtk_widget_show (window);
14350   
14351   gtk_main ();
14352   
14353   return 0;
14354 }
14355 </programlisting>
14356
14357 </sect2>
14358 </sect1>
14359
14360 <!-- ----------------------------------------------------------------- -->
14361 <sect1 id="sec-CreatingAWidgetFromScratch">
14362 <title>Creating a widget from scratch</title>
14363
14364 <!-- ----------------------------------------------------------------- -->
14365 <sect2>
14366 <title>Introduction</title>
14367
14368 <para>In this section, we'll learn more about how widgets display themselves
14369 on the screen and interact with events. As an example of this, we'll
14370 create an analog dial widget with a pointer that the user can drag to
14371 set the value.</para>
14372
14373 </sect2>
14374
14375 <!-- ----------------------------------------------------------------- -->
14376 <sect2>
14377 <title>Displaying a widget on the screen</title>
14378
14379 <para>There are several steps that are involved in displaying on the screen.
14380 After the widget is created with a call to <literal>WIDGETNAME_new()</literal>,
14381 several more functions are needed:</para>
14382
14383 <itemizedlist>
14384 <listitem><simpara> <literal>WIDGETNAME_realize()</literal> is responsible for creating an X
14385 window for the widget if it has one.</simpara>
14386 </listitem>
14387 <listitem><simpara> <literal>WIDGETNAME_map()</literal> is invoked after the user calls
14388 <literal>gtk_widget_show()</literal>. It is responsible for making sure the widget
14389 is actually drawn on the screen (<emphasis>mapped</emphasis>). For a container class,
14390 it must also make calls to <literal>map()</literal>> functions of any child widgets.</simpara>
14391 </listitem>
14392 <listitem><simpara> <literal>WIDGETNAME_draw()</literal> is invoked when <literal>gtk_widget_draw()</literal>
14393 is called for the widget or one of its ancestors. It makes the actual
14394 calls to the drawing functions to draw the widget on the screen. For
14395 container widgets, this function must make calls to
14396 <literal>gtk_widget_draw()</literal> for its child widgets.</simpara>
14397 </listitem>
14398 <listitem><simpara> <literal>WIDGETNAME_expose()</literal> is a handler for expose events for the
14399 widget. It makes the necessary calls to the drawing functions to draw
14400 the exposed portion on the screen. For container widgets, this
14401 function must generate expose events for its child widgets which don't
14402 have their own windows. (If they have their own windows, then X will
14403 generate the necessary expose events.)</simpara>
14404 </listitem>
14405 </itemizedlist>
14406
14407 <para>You might notice that the last two functions are quite similar - each
14408 is responsible for drawing the widget on the screen. In fact many
14409 types of widgets don't really care about the difference between the
14410 two. The default <literal>draw()</literal> function in the widget class simply
14411 generates a synthetic expose event for the redrawn area. However, some
14412 types of widgets can save work by distinguishing between the two
14413 functions. For instance, if a widget has multiple X windows, then
14414 since expose events identify the exposed window, it can redraw only
14415 the affected window, which is not possible for calls to <literal>draw()</literal>.</para>
14416
14417 <para>Container widgets, even if they don't care about the difference for
14418 themselves, can't simply use the default <literal>draw()</literal> function because
14419 their child widgets might care about the difference. However,
14420 it would be wasteful to duplicate the drawing code between the two
14421 functions. The convention is that such widgets have a function called
14422 <literal>WIDGETNAME_paint()</literal> that does the actual work of drawing the
14423 widget, that is then called by the <literal>draw()</literal> and <literal>expose()</literal>
14424 functions.</para>
14425
14426 <para>In our example approach, since the dial widget is not a container
14427 widget, and only has a single window, we can take the simplest
14428 approach and use the default <literal>draw()</literal> function and only implement
14429 an <literal>expose()</literal> function.</para>
14430
14431 </sect2>
14432
14433 <!-- ----------------------------------------------------------------- -->
14434 <sect2>
14435 <title>The origins of the Dial Widget</title>
14436
14437 <para>Just as all land animals are just variants on the first amphibian that
14438 crawled up out of the mud, GTK widgets tend to start off as variants
14439 of some other, previously written widget. Thus, although this section
14440 is entitled "Creating a Widget from Scratch", the Dial widget really
14441 began with the source code for the Range widget. This was picked as a
14442 starting point because it would be nice if our Dial had the same
14443 interface as the Scale widgets which are just specialized descendants
14444 of the Range widget. So, though the source code is presented below in
14445 finished form, it should not be implied that it was written, <emphasis>ab
14446 initio</emphasis> in this fashion. Also, if you aren't yet familiar with
14447 how scale widgets work from the application writer's point of view, it
14448 would be a good idea to look them over before continuing.</para>
14449
14450 </sect2>
14451
14452 <!-- ----------------------------------------------------------------- -->
14453 <sect2>
14454 <title>The Basics</title>
14455
14456 <para>Quite a bit of our widget should look pretty familiar from the
14457 Tictactoe widget. First, we have a header file:</para>
14458
14459 <programlisting role="C">
14460 /* GTK - The GIMP Toolkit
14461  * Copyright (C) 1995-1997 Peter Mattis, Spencer Kimball and Josh MacDonald
14462  *
14463  * This library is free software; you can redistribute it and/or
14464  * modify it under the terms of the GNU Library General Public
14465  * License as published by the Free Software Foundation; either
14466  * version 2 of the License, or (at your option) any later version.
14467  *
14468  * This library is distributed in the hope that it will be useful,
14469  * but WITHOUT ANY WARRANTY; without even the implied warranty of
14470  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
14471  * Library General Public License for more details.
14472  *
14473  * You should have received a copy of the GNU Library General Public
14474  * License along with this library; if not, write to the Free
14475  * Software Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
14476  */
14477
14478 #ifndef __GTK_DIAL_H__
14479 #define __GTK_DIAL_H__
14480
14481 #include &lt;gdk/gdk.h&gt;
14482 #include &lt;gtk/gtkadjustment.h&gt;
14483 #include &lt;gtk/gtkwidget.h&gt;
14484
14485
14486 #ifdef __cplusplus
14487 extern "C" {
14488 #endif /* __cplusplus */
14489
14490
14491 #define GTK_DIAL(obj)          GTK_CHECK_CAST (obj, gtk_dial_get_type (), GtkDial)
14492 #define GTK_DIAL_CLASS(klass)  GTK_CHECK_CLASS_CAST (klass, gtk_dial_get_type (), GtkDialClass)
14493 #define GTK_IS_DIAL(obj)       GTK_CHECK_TYPE (obj, gtk_dial_get_type ())
14494
14495
14496 typedef struct _GtkDial        GtkDial;
14497 typedef struct _GtkDialClass   GtkDialClass;
14498
14499 struct _GtkDial
14500 {
14501   GtkWidget widget;
14502
14503   /* update policy (GTK_UPDATE_[CONTINUOUS/DELAYED/DISCONTINUOUS]) */
14504   guint policy : 2;
14505
14506   /* Button currently pressed or 0 if none */
14507   guint8 button;
14508
14509   /* Dimensions of dial components */
14510   gint radius;
14511   gint pointer_width;
14512
14513   /* ID of update timer, or 0 if none */
14514   guint32 timer;
14515
14516   /* Current angle */
14517   gfloat angle;
14518
14519   /* Old values from adjustment stored so we know when something changes */
14520   gfloat old_value;
14521   gfloat old_lower;
14522   gfloat old_upper;
14523
14524   /* The adjustment object that stores the data for this dial */
14525   GtkAdjustment *adjustment;
14526 };
14527
14528 struct _GtkDialClass
14529 {
14530   GtkWidgetClass parent_class;
14531 };
14532
14533
14534 GtkWidget*     gtk_dial_new                    (GtkAdjustment *adjustment);
14535 GtkType        gtk_dial_get_type               (void);
14536 GtkAdjustment* gtk_dial_get_adjustment         (GtkDial      *dial);
14537 void           gtk_dial_set_update_policy      (GtkDial      *dial,
14538                                                 GtkUpdateType  policy);
14539
14540 void           gtk_dial_set_adjustment         (GtkDial      *dial,
14541                                                 GtkAdjustment *adjustment);
14542 #ifdef __cplusplus
14543 }
14544 #endif /* __cplusplus */
14545
14546
14547 #endif /* __GTK_DIAL_H__ */
14548 </programlisting>
14549
14550 <para>Since there is quite a bit more going on in this widget than the last
14551 one, we have more fields in the data structure, but otherwise things
14552 are pretty similar.</para>
14553
14554 <para>Next, after including header files and declaring a few constants,
14555 we have some functions to provide information about the widget
14556 and initialize it:</para>
14557
14558 <programlisting role="C">
14559 #include &lt;math.h&gt;
14560 #include &lt;stdio.h&gt;
14561 #include &lt;gtk/gtkmain.h&gt;
14562 #include &lt;gtk/gtksignal.h&gt;
14563
14564 #include "gtkdial.h"
14565
14566 #define SCROLL_DELAY_LENGTH  300
14567 #define DIAL_DEFAULT_SIZE 100
14568
14569 /* Forward declarations */
14570
14571 [ omitted to save space ]
14572
14573 /* Local data */
14574
14575 static GtkWidgetClass *parent_class = NULL;
14576
14577 GtkType
14578 gtk_dial_get_type ()
14579 {
14580   static GtkType dial_type = 0;
14581
14582   if (!dial_type)
14583     {
14584       static const GtkTypeInfo dial_info =
14585       {
14586         "GtkDial",
14587         sizeof (GtkDial),
14588         sizeof (GtkDialClass),
14589         (GtkClassInitFunc) gtk_dial_class_init,
14590         (GtkObjectInitFunc) gtk_dial_init,
14591         /* reserved_1 */ NULL,
14592         /* reserved_1 */ NULL,
14593         (GtkClassInitFunc) NULL
14594       };
14595
14596       dial_type = gtk_type_unique (GTK_TYPE_WIDGET, &amp;dial_info);
14597     }
14598
14599   return dial_type;
14600 }
14601
14602 static void
14603 gtk_dial_class_init (GtkDialClass *class)
14604 {
14605   GtkObjectClass *object_class;
14606   GtkWidgetClass *widget_class;
14607
14608   object_class = (GtkObjectClass*) class;
14609   widget_class = (GtkWidgetClass*) class;
14610
14611   parent_class = gtk_type_class (gtk_widget_get_type ());
14612
14613   object_class->destroy = gtk_dial_destroy;
14614
14615   widget_class->realize = gtk_dial_realize;
14616   widget_class->expose_event = gtk_dial_expose;
14617   widget_class->size_request = gtk_dial_size_request;
14618   widget_class->size_allocate = gtk_dial_size_allocate;
14619   widget_class->button_press_event = gtk_dial_button_press;
14620   widget_class->button_release_event = gtk_dial_button_release;
14621   widget_class->motion_notify_event = gtk_dial_motion_notify;
14622 }
14623
14624 static void
14625 gtk_dial_init (GtkDial *dial)
14626 {
14627   dial->button = 0;
14628   dial->policy = GTK_UPDATE_CONTINUOUS;
14629   dial->timer = 0;
14630   dial->radius = 0;
14631   dial->pointer_width = 0;
14632   dial->angle = 0.0;
14633   dial->old_value = 0.0;
14634   dial->old_lower = 0.0;
14635   dial->old_upper = 0.0;
14636   dial->adjustment = NULL;
14637 }
14638
14639 GtkWidget*
14640 gtk_dial_new (GtkAdjustment *adjustment)
14641 {
14642   GtkDial *dial;
14643
14644   dial = gtk_type_new (gtk_dial_get_type ());
14645
14646   if (!adjustment)
14647     adjustment = (GtkAdjustment*) gtk_adjustment_new (0.0, 0.0, 0.0, 0.0, 0.0, 0.0);
14648
14649   gtk_dial_set_adjustment (dial, adjustment);
14650
14651   return GTK_WIDGET (dial);
14652 }
14653
14654 static void
14655 gtk_dial_destroy (GtkObject *object)
14656 {
14657   GtkDial *dial;
14658
14659   g_return_if_fail (object != NULL);
14660   g_return_if_fail (GTK_IS_DIAL (object));
14661
14662   dial = GTK_DIAL (object);
14663
14664   if (dial->adjustment)
14665     gtk_object_unref (GTK_OBJECT (dial->adjustment));
14666
14667   if (GTK_OBJECT_CLASS (parent_class)->destroy)
14668     (* GTK_OBJECT_CLASS (parent_class)->destroy) (object);
14669 }
14670 </programlisting>
14671
14672 <para>Note that this <literal>init()</literal> function does less than for the Tictactoe
14673 widget, since this is not a composite widget, and the <literal>new()</literal>
14674 function does more, since it now has an argument. Also, note that when
14675 we store a pointer to the Adjustment object, we increment its
14676 reference count, (and correspondingly decrement it when we no longer
14677 use it) so that GTK can keep track of when it can be safely destroyed.</para>
14678
14679 <para>Also, there are a few function to manipulate the widget's options:</para>
14680
14681 <programlisting role="C">
14682 GtkAdjustment*
14683 gtk_dial_get_adjustment (GtkDial *dial)
14684 {
14685   g_return_val_if_fail (dial != NULL, NULL);
14686   g_return_val_if_fail (GTK_IS_DIAL (dial), NULL);
14687
14688   return dial->adjustment;
14689 }
14690
14691 void
14692 gtk_dial_set_update_policy (GtkDial      *dial,
14693                              GtkUpdateType  policy)
14694 {
14695   g_return_if_fail (dial != NULL);
14696   g_return_if_fail (GTK_IS_DIAL (dial));
14697
14698   dial->policy = policy;
14699 }
14700
14701 void
14702 gtk_dial_set_adjustment (GtkDial      *dial,
14703                           GtkAdjustment *adjustment)
14704 {
14705   g_return_if_fail (dial != NULL);
14706   g_return_if_fail (GTK_IS_DIAL (dial));
14707
14708   if (dial->adjustment)
14709     {
14710       gtk_signal_disconnect_by_data (GTK_OBJECT (dial->adjustment), (gpointer) dial);
14711       gtk_object_unref (GTK_OBJECT (dial->adjustment));
14712     }
14713
14714   dial->adjustment = adjustment;
14715   gtk_object_ref (GTK_OBJECT (dial->adjustment));
14716
14717   gtk_signal_connect (GTK_OBJECT (adjustment), "changed",
14718                       (GtkSignalFunc) gtk_dial_adjustment_changed,
14719                       (gpointer) dial);
14720   gtk_signal_connect (GTK_OBJECT (adjustment), "value_changed",
14721                       (GtkSignalFunc) gtk_dial_adjustment_value_changed,
14722                       (gpointer) dial);
14723
14724   dial->old_value = adjustment->value;
14725   dial->old_lower = adjustment->lower;
14726   dial->old_upper = adjustment->upper;
14727
14728   gtk_dial_update (dial);
14729 }
14730 </programlisting>
14731
14732 </sect2>
14733
14734 <!-- ----------------------------------------------------------------- -->
14735 <sect2>
14736 <title><literal>gtk_dial_realize()</literal></title>
14737
14738 <para>Now we come to some new types of functions. First, we have a function
14739 that does the work of creating the X window. Notice that a mask is
14740 passed to the function <literal>gdk_window_new()</literal> which specifies which fields of
14741 the GdkWindowAttr structure actually have data in them (the remaining
14742 fields will be given default values). Also worth noting is the way the
14743 event mask of the widget is created. We call
14744 <literal>gtk_widget_get_events()</literal> to retrieve the event mask that the user
14745 has specified for this widget (with <literal>gtk_widget_set_events()</literal>), and
14746 add the events that we are interested in ourselves.</para>
14747
14748 <para>After creating the window, we set its style and background, and put a
14749 pointer to the widget in the user data field of the GdkWindow. This
14750 last step allows GTK to dispatch events for this window to the correct
14751 widget.</para>
14752
14753 <programlisting role="C">
14754 static void
14755 gtk_dial_realize (GtkWidget *widget)
14756 {
14757   GtkDial *dial;
14758   GdkWindowAttr attributes;
14759   gint attributes_mask;
14760
14761   g_return_if_fail (widget != NULL);
14762   g_return_if_fail (GTK_IS_DIAL (widget));
14763
14764   GTK_WIDGET_SET_FLAGS (widget, GTK_REALIZED);
14765   dial = GTK_DIAL (widget);
14766
14767   attributes.x = widget->allocation.x;
14768   attributes.y = widget->allocation.y;
14769   attributes.width = widget->allocation.width;
14770   attributes.height = widget->allocation.height;
14771   attributes.wclass = GDK_INPUT_OUTPUT;
14772   attributes.window_type = GDK_WINDOW_CHILD;
14773   attributes.event_mask = gtk_widget_get_events (widget) | 
14774     GDK_EXPOSURE_MASK | GDK_BUTTON_PRESS_MASK | 
14775     GDK_BUTTON_RELEASE_MASK | GDK_POINTER_MOTION_MASK |
14776     GDK_POINTER_MOTION_HINT_MASK;
14777   attributes.visual = gtk_widget_get_visual (widget);
14778   attributes.colormap = gtk_widget_get_colormap (widget);
14779
14780   attributes_mask = GDK_WA_X | GDK_WA_Y | GDK_WA_VISUAL | GDK_WA_COLORMAP;
14781   widget->window = gdk_window_new (widget->parent->window, &amp;attributes, attributes_mask);
14782
14783   widget->style = gtk_style_attach (widget->style, widget->window);
14784
14785   gdk_window_set_user_data (widget->window, widget);
14786
14787   gtk_style_set_background (widget->style, widget->window, GTK_STATE_ACTIVE);
14788 }
14789 </programlisting>
14790
14791 </sect2>
14792
14793 <!-- ----------------------------------------------------------------- -->
14794 <sect2>
14795 <title>Size negotiation</title>
14796
14797 <para>Before the first time that the window containing a widget is
14798 displayed, and whenever the layout of the window changes, GTK asks
14799 each child widget for its desired size. This request is handled by the
14800 function <literal>gtk_dial_size_request()</literal>. Since our widget isn't a
14801 container widget, and has no real constraints on its size, we just
14802 return a reasonable default value.</para>
14803
14804 <programlisting role="C">
14805 static void 
14806 gtk_dial_size_request (GtkWidget      *widget,
14807                        GtkRequisition *requisition)
14808 {
14809   requisition->width = DIAL_DEFAULT_SIZE;
14810   requisition->height = DIAL_DEFAULT_SIZE;
14811 }
14812 </programlisting>
14813
14814 <para>After all the widgets have requested an ideal size, the layout of the
14815 window is computed and each child widget is notified of its actual
14816 size. Usually, this will be at least as large as the requested size,
14817 but if for instance the user has resized the window, it may
14818 occasionally be smaller than the requested size. The size notification
14819 is handled by the function <literal>gtk_dial_size_allocate()</literal>. Notice that
14820 as well as computing the sizes of some component pieces for future
14821 use, this routine also does the grunt work of moving the widget's X
14822 window into the new position and size.</para>
14823
14824 <programlisting role="C">
14825 static void
14826 gtk_dial_size_allocate (GtkWidget     *widget,
14827                         GtkAllocation *allocation)
14828 {
14829   GtkDial *dial;
14830
14831   g_return_if_fail (widget != NULL);
14832   g_return_if_fail (GTK_IS_DIAL (widget));
14833   g_return_if_fail (allocation != NULL);
14834
14835   widget->allocation = *allocation;
14836   if (GTK_WIDGET_REALIZED (widget))
14837     {
14838       dial = GTK_DIAL (widget);
14839
14840       gdk_window_move_resize (widget->window,
14841                               allocation->x, allocation->y,
14842                               allocation->width, allocation->height);
14843
14844       dial->radius = MAX(allocation->width,allocation->height) * 0.45;
14845       dial->pointer_width = dial->radius / 5;
14846     }
14847 }
14848 </programlisting>
14849
14850 </sect2>
14851
14852 <!-- ----------------------------------------------------------------- -->
14853 <sect2>
14854 <title><literal>gtk_dial_expose()</literal></title>
14855
14856 <para>As mentioned above, all the drawing of this widget is done in the
14857 handler for expose events. There's not much to remark on here except
14858 the use of the function <literal>gtk_draw_polygon</literal> to draw the pointer with
14859 three dimensional shading according to the colors stored in the
14860 widget's style.</para>
14861
14862 <programlisting role="C">
14863 static gint
14864 gtk_dial_expose (GtkWidget      *widget,
14865                  GdkEventExpose *event)
14866 {
14867   GtkDial *dial;
14868   GdkPoint points[3];
14869   gdouble s,c;
14870   gdouble theta;
14871   gint xc, yc;
14872   gint tick_length;
14873   gint i;
14874
14875   g_return_val_if_fail (widget != NULL, FALSE);
14876   g_return_val_if_fail (GTK_IS_DIAL (widget), FALSE);
14877   g_return_val_if_fail (event != NULL, FALSE);
14878
14879   if (event->count > 0)
14880     return FALSE;
14881   
14882   dial = GTK_DIAL (widget);
14883
14884   gdk_window_clear_area (widget->window,
14885                          0, 0,
14886                          widget->allocation.width,
14887                          widget->allocation.height);
14888
14889   xc = widget->allocation.width/2;
14890   yc = widget->allocation.height/2;
14891
14892   /* Draw ticks */
14893
14894   for (i=0; i<25; i++)
14895     {
14896       theta = (i*M_PI/18. - M_PI/6.);
14897       s = sin(theta);
14898       c = cos(theta);
14899
14900       tick_length = (i%6 == 0) ? dial->pointer_width : dial->pointer_width/2;
14901       
14902       gdk_draw_line (widget->window,
14903                      widget->style->fg_gc[widget->state],
14904                      xc + c*(dial->radius - tick_length),
14905                      yc - s*(dial->radius - tick_length),
14906                      xc + c*dial->radius,
14907                      yc - s*dial->radius);
14908     }
14909
14910   /* Draw pointer */
14911
14912   s = sin(dial->angle);
14913   c = cos(dial->angle);
14914
14915
14916   points[0].x = xc + s*dial->pointer_width/2;
14917   points[0].y = yc + c*dial->pointer_width/2;
14918   points[1].x = xc + c*dial->radius;
14919   points[1].y = yc - s*dial->radius;
14920   points[2].x = xc - s*dial->pointer_width/2;
14921   points[2].y = yc - c*dial->pointer_width/2;
14922
14923   gtk_draw_polygon (widget->style,
14924                     widget->window,
14925                     GTK_STATE_NORMAL,
14926                     GTK_SHADOW_OUT,
14927                     points, 3,
14928                     TRUE);
14929   
14930   return FALSE;
14931 }
14932 </programlisting>
14933
14934 </sect2>
14935
14936 <!-- ----------------------------------------------------------------- -->
14937 <sect2>
14938 <title>Event handling</title>
14939
14940 <para>The rest of the widget's code handles various types of events, and
14941 isn't too different from what would be found in many GTK
14942 applications. Two types of events can occur - either the user can
14943 click on the widget with the mouse and drag to move the pointer, or
14944 the value of the Adjustment object can change due to some external
14945 circumstance.</para>
14946
14947 <para>When the user clicks on the widget, we check to see if the click was
14948 appropriately near the pointer, and if so, store the button that the
14949 user clicked with in the <literal>button</literal> field of the widget
14950 structure, and grab all mouse events with a call to
14951 <literal>gtk_grab_add()</literal>. Subsequent motion of the mouse causes the
14952 value of the control to be recomputed (by the function
14953 <literal>gtk_dial_update_mouse</literal>). Depending on the policy that has been
14954 set, "value_changed" events are either generated instantly
14955 (<literal>GTK_UPDATE_CONTINUOUS</literal>), after a delay in a timer added with
14956 <literal>gtk_timeout_add()</literal> (<literal>GTK_UPDATE_DELAYED</literal>), or only when the
14957 button is released (<literal>GTK_UPDATE_DISCONTINUOUS</literal>).</para>
14958
14959 <programlisting role="C">
14960 static gint
14961 gtk_dial_button_press (GtkWidget      *widget,
14962                        GdkEventButton *event)
14963 {
14964   GtkDial *dial;
14965   gint dx, dy;
14966   double s, c;
14967   double d_parallel;
14968   double d_perpendicular;
14969
14970   g_return_val_if_fail (widget != NULL, FALSE);
14971   g_return_val_if_fail (GTK_IS_DIAL (widget), FALSE);
14972   g_return_val_if_fail (event != NULL, FALSE);
14973
14974   dial = GTK_DIAL (widget);
14975
14976   /* Determine if button press was within pointer region - we 
14977      do this by computing the parallel and perpendicular distance of
14978      the point where the mouse was pressed from the line passing through
14979      the pointer */
14980   
14981   dx = event->x - widget->allocation.width / 2;
14982   dy = widget->allocation.height / 2 - event->y;
14983   
14984   s = sin(dial->angle);
14985   c = cos(dial->angle);
14986   
14987   d_parallel = s*dy + c*dx;
14988   d_perpendicular = fabs(s*dx - c*dy);
14989   
14990   if (!dial->button &&
14991       (d_perpendicular < dial->pointer_width/2) &&
14992       (d_parallel > - dial->pointer_width))
14993     {
14994       gtk_grab_add (widget);
14995
14996       dial->button = event->button;
14997
14998       gtk_dial_update_mouse (dial, event->x, event->y);
14999     }
15000
15001   return FALSE;
15002 }
15003
15004 static gint
15005 gtk_dial_button_release (GtkWidget      *widget,
15006                           GdkEventButton *event)
15007 {
15008   GtkDial *dial;
15009
15010   g_return_val_if_fail (widget != NULL, FALSE);
15011   g_return_val_if_fail (GTK_IS_DIAL (widget), FALSE);
15012   g_return_val_if_fail (event != NULL, FALSE);
15013
15014   dial = GTK_DIAL (widget);
15015
15016   if (dial->button == event->button)
15017     {
15018       gtk_grab_remove (widget);
15019
15020       dial->button = 0;
15021
15022       if (dial->policy == GTK_UPDATE_DELAYED)
15023         gtk_timeout_remove (dial->timer);
15024       
15025       if ((dial->policy != GTK_UPDATE_CONTINUOUS) &&
15026           (dial->old_value != dial->adjustment->value))
15027         gtk_signal_emit_by_name (GTK_OBJECT (dial->adjustment), "value_changed");
15028     }
15029
15030   return FALSE;
15031 }
15032
15033 static gint
15034 gtk_dial_motion_notify (GtkWidget      *widget,
15035                          GdkEventMotion *event)
15036 {
15037   GtkDial *dial;
15038   GdkModifierType mods;
15039   gint x, y, mask;
15040
15041   g_return_val_if_fail (widget != NULL, FALSE);
15042   g_return_val_if_fail (GTK_IS_DIAL (widget), FALSE);
15043   g_return_val_if_fail (event != NULL, FALSE);
15044
15045   dial = GTK_DIAL (widget);
15046
15047   if (dial->button != 0)
15048     {
15049       x = event->x;
15050       y = event->y;
15051
15052       if (event->is_hint || (event->window != widget->window))
15053         gdk_window_get_pointer (widget->window, &amp;x, &amp;y, &amp;mods);
15054
15055       switch (dial->button)
15056         {
15057         case 1:
15058           mask = GDK_BUTTON1_MASK;
15059           break;
15060         case 2:
15061           mask = GDK_BUTTON2_MASK;
15062           break;
15063         case 3:
15064           mask = GDK_BUTTON3_MASK;
15065           break;
15066         default:
15067           mask = 0;
15068           break;
15069         }
15070
15071       if (mods & mask)
15072         gtk_dial_update_mouse (dial, x,y);
15073     }
15074
15075   return FALSE;
15076 }
15077
15078 static gint
15079 gtk_dial_timer (GtkDial *dial)
15080 {
15081   g_return_val_if_fail (dial != NULL, FALSE);
15082   g_return_val_if_fail (GTK_IS_DIAL (dial), FALSE);
15083
15084   if (dial->policy == GTK_UPDATE_DELAYED)
15085     gtk_signal_emit_by_name (GTK_OBJECT (dial->adjustment), "value_changed");
15086
15087   return FALSE;
15088 }
15089
15090 static void
15091 gtk_dial_update_mouse (GtkDial *dial, gint x, gint y)
15092 {
15093   gint xc, yc;
15094   gfloat old_value;
15095
15096   g_return_if_fail (dial != NULL);
15097   g_return_if_fail (GTK_IS_DIAL (dial));
15098
15099   xc = GTK_WIDGET(dial)->allocation.width / 2;
15100   yc = GTK_WIDGET(dial)->allocation.height / 2;
15101
15102   old_value = dial->adjustment->value;
15103   dial->angle = atan2(yc-y, x-xc);
15104
15105   if (dial->angle < -M_PI/2.)
15106     dial->angle += 2*M_PI;
15107
15108   if (dial->angle < -M_PI/6)
15109     dial->angle = -M_PI/6;
15110
15111   if (dial->angle > 7.*M_PI/6.)
15112     dial->angle = 7.*M_PI/6.;
15113
15114   dial->adjustment->value = dial->adjustment->lower + (7.*M_PI/6 - dial->angle) *
15115     (dial->adjustment->upper - dial->adjustment->lower) / (4.*M_PI/3.);
15116
15117   if (dial->adjustment->value != old_value)
15118     {
15119       if (dial->policy == GTK_UPDATE_CONTINUOUS)
15120         {
15121           gtk_signal_emit_by_name (GTK_OBJECT (dial->adjustment), "value_changed");
15122         }
15123       else
15124         {
15125           gtk_widget_draw (GTK_WIDGET(dial), NULL);
15126
15127           if (dial->policy == GTK_UPDATE_DELAYED)
15128             {
15129               if (dial->timer)
15130                 gtk_timeout_remove (dial->timer);
15131
15132               dial->timer = gtk_timeout_add (SCROLL_DELAY_LENGTH,
15133                                              (GtkFunction) gtk_dial_timer,
15134                                              (gpointer) dial);
15135             }
15136         }
15137     }
15138 }
15139 </programlisting>
15140
15141 <para>Changes to the Adjustment by external means are communicated to our
15142 widget by the "changed" and "value_changed" signals. The handlers
15143 for these functions call <literal>gtk_dial_update()</literal> to validate the
15144 arguments, compute the new pointer angle, and redraw the widget (by
15145 calling <literal>gtk_widget_draw()</literal>).</para>
15146
15147 <programlisting role="C">
15148 static void
15149 gtk_dial_update (GtkDial *dial)
15150 {
15151   gfloat new_value;
15152   
15153   g_return_if_fail (dial != NULL);
15154   g_return_if_fail (GTK_IS_DIAL (dial));
15155
15156   new_value = dial->adjustment->value;
15157   
15158   if (new_value < dial->adjustment->lower)
15159     new_value = dial->adjustment->lower;
15160
15161   if (new_value > dial->adjustment->upper)
15162     new_value = dial->adjustment->upper;
15163
15164   if (new_value != dial->adjustment->value)
15165     {
15166       dial->adjustment->value = new_value;
15167       gtk_signal_emit_by_name (GTK_OBJECT (dial->adjustment), "value_changed");
15168     }
15169
15170   dial->angle = 7.*M_PI/6. - (new_value - dial->adjustment->lower) * 4.*M_PI/3. /
15171     (dial->adjustment->upper - dial->adjustment->lower);
15172
15173   gtk_widget_draw (GTK_WIDGET(dial), NULL);
15174 }
15175
15176 static void
15177 gtk_dial_adjustment_changed (GtkAdjustment *adjustment,
15178                               gpointer       data)
15179 {
15180   GtkDial *dial;
15181
15182   g_return_if_fail (adjustment != NULL);
15183   g_return_if_fail (data != NULL);
15184
15185   dial = GTK_DIAL (data);
15186
15187   if ((dial->old_value != adjustment->value) ||
15188       (dial->old_lower != adjustment->lower) ||
15189       (dial->old_upper != adjustment->upper))
15190     {
15191       gtk_dial_update (dial);
15192
15193       dial->old_value = adjustment->value;
15194       dial->old_lower = adjustment->lower;
15195       dial->old_upper = adjustment->upper;
15196     }
15197 }
15198
15199 static void
15200 gtk_dial_adjustment_value_changed (GtkAdjustment *adjustment,
15201                                     gpointer       data)
15202 {
15203   GtkDial *dial;
15204
15205   g_return_if_fail (adjustment != NULL);
15206   g_return_if_fail (data != NULL);
15207
15208   dial = GTK_DIAL (data);
15209
15210   if (dial->old_value != adjustment->value)
15211     {
15212       gtk_dial_update (dial);
15213
15214       dial->old_value = adjustment->value;
15215     }
15216 }
15217 </programlisting>
15218
15219 </sect2>
15220
15221 <!-- ----------------------------------------------------------------- -->
15222 <sect2>
15223 <title>Possible Enhancements</title>
15224
15225 <para>The Dial widget as we've described it so far runs about 670 lines of
15226 code. Although that might sound like a fair bit, we've really
15227 accomplished quite a bit with that much code, especially since much of
15228 that length is headers and boilerplate. However, there are quite a few
15229 more enhancements that could be made to this widget:</para>
15230
15231 <itemizedlist>
15232 <listitem><simpara> If you try this widget out, you'll find that there is some
15233 flashing as the pointer is dragged around. This is because the entire
15234 widget is erased every time the pointer is moved before being
15235 redrawn. Often, the best way to handle this problem is to draw to an
15236 offscreen pixmap, then copy the final results onto the screen in one
15237 step. (The ProgressBar widget draws itself in this fashion.)</simpara>
15238 </listitem>
15239
15240 <listitem><simpara> The user should be able to use the up and down arrow keys to
15241 increase and decrease the value.</simpara>
15242 </listitem>
15243
15244 <listitem><simpara> It would be nice if the widget had buttons to increase and
15245 decrease the value in small or large steps. Although it would be
15246 possible to use embedded Button widgets for this, we would also like
15247 the buttons to auto-repeat when held down, as the arrows on a
15248 scrollbar do. Most of the code to implement this type of behavior can
15249 be found in the Range widget.</simpara>
15250 </listitem>
15251
15252 <listitem><simpara> The Dial widget could be made into a container widget with a
15253 single child widget positioned at the bottom between the buttons
15254 mentioned above. The user could then add their choice of a label or
15255 entry widget to display the current value of the dial.</simpara>
15256 </listitem>
15257 </itemizedlist>
15258
15259 </sect2>
15260 </sect1>
15261
15262 <!-- ----------------------------------------------------------------- -->
15263 <sect1 id="sec-LearningMore">
15264 <title>Learning More</title>
15265
15266 <para>Only a small part of the many details involved in creating widgets
15267 could be described above. If you want to write your own widgets, the
15268 best source of examples is the GTK source itself. Ask yourself some
15269 questions about the widget you want to write: IS it a Container
15270 widget? Does it have its own window? Is it a modification of an
15271 existing widget? Then find a similar widget, and start making changes.
15272 Good luck!</para>
15273
15274 </sect1>
15275 </chapter>
15276
15277 <!-- ***************************************************************** -->
15278 <chapter id="ch-Scribble">
15279 <title>Scribble, A Simple Example Drawing Program</title>
15280
15281 <!-- ----------------------------------------------------------------- -->
15282 <sect1 id="sec-ScribbleOverview">
15283 <title>Overview</title>
15284
15285 <para>In this section, we will build a simple drawing program. In the
15286 process, we will examine how to handle mouse events, how to draw in a
15287 window, and how to do drawing better by using a backing pixmap. After
15288 creating the simple drawing program, we will extend it by adding
15289 support for XInput devices, such as drawing tablets. GTK provides
15290 support routines which makes getting extended information, such as
15291 pressure and tilt, from such devices quite easy.</para>
15292
15293 </sect1>
15294
15295 <!-- ----------------------------------------------------------------- -->
15296 <sect1 id="sec-EventHandling">
15297 <title>Event Handling</title>
15298
15299 <para>The GTK signals we have already discussed are for high-level actions,
15300 such as a menu item being selected. However, sometimes it is useful to
15301 learn about lower-level occurrences, such as the mouse being moved, or
15302 a key being pressed. There are also GTK signals corresponding to these
15303 low-level <emphasis>events</emphasis>. The handlers for these signals have an
15304 extra parameter which is a pointer to a structure containing
15305 information about the event. For instance, motion event handlers are
15306 passed a pointer to a GdkEventMotion structure which looks (in part)
15307 like:</para>
15308
15309 <programlisting role="C">
15310 struct _GdkEventMotion
15311 {
15312   GdkEventType type;
15313   GdkWindow *window;
15314   guint32 time;
15315   gdouble x;
15316   gdouble y;
15317   ...
15318   guint state;
15319   ...
15320 };
15321 </programlisting>
15322
15323 <para><literal>type</literal> will be set to the event type, in this case
15324 <literal>GDK_MOTION_NOTIFY</literal>, window is the window in which the event
15325 occurred. <literal>x</literal> and <literal>y</literal> give the coordinates of the event.
15326 <literal>state</literal> specifies the modifier state when the event
15327 occurred (that is, it specifies which modifier keys and mouse buttons
15328 were pressed). It is the bitwise OR of some of the following:</para>
15329
15330 <programlisting role="C">
15331 GDK_SHIFT_MASK  
15332 GDK_LOCK_MASK   
15333 GDK_CONTROL_MASK
15334 GDK_MOD1_MASK   
15335 GDK_MOD2_MASK   
15336 GDK_MOD3_MASK   
15337 GDK_MOD4_MASK   
15338 GDK_MOD5_MASK   
15339 GDK_BUTTON1_MASK
15340 GDK_BUTTON2_MASK
15341 GDK_BUTTON3_MASK
15342 GDK_BUTTON4_MASK
15343 GDK_BUTTON5_MASK
15344 </programlisting>
15345
15346 <para>As for other signals, to determine what happens when an event occurs
15347 we call <literal>gtk_signal_connect()</literal>. But we also need let GTK
15348 know which events we want to be notified about. To do this, we call
15349 the function:</para>
15350
15351 <programlisting role="C">
15352 void gtk_widget_set_events (GtkWidget *widget,
15353                             gint      events);
15354 </programlisting>
15355
15356 <para>The second field specifies the events we are interested in. It
15357 is the bitwise OR of constants that specify different types
15358 of events. For future reference the event types are:</para>
15359
15360 <programlisting role="C">
15361 GDK_EXPOSURE_MASK
15362 GDK_POINTER_MOTION_MASK
15363 GDK_POINTER_MOTION_HINT_MASK
15364 GDK_BUTTON_MOTION_MASK     
15365 GDK_BUTTON1_MOTION_MASK    
15366 GDK_BUTTON2_MOTION_MASK    
15367 GDK_BUTTON3_MOTION_MASK    
15368 GDK_BUTTON_PRESS_MASK      
15369 GDK_BUTTON_RELEASE_MASK    
15370 GDK_KEY_PRESS_MASK         
15371 GDK_KEY_RELEASE_MASK       
15372 GDK_ENTER_NOTIFY_MASK      
15373 GDK_LEAVE_NOTIFY_MASK      
15374 GDK_FOCUS_CHANGE_MASK      
15375 GDK_STRUCTURE_MASK         
15376 GDK_PROPERTY_CHANGE_MASK   
15377 GDK_PROXIMITY_IN_MASK      
15378 GDK_PROXIMITY_OUT_MASK     
15379 </programlisting>
15380
15381 <para>There are a few subtle points that have to be observed when calling
15382 <literal>gtk_widget_set_events()</literal>. First, it must be called before the X window
15383 for a GTK widget is created. In practical terms, this means you
15384 should call it immediately after creating the widget. Second, the
15385 widget must have an associated X window. For efficiency, many widget
15386 types do not have their own window, but draw in their parent's window.
15387 These widgets are:</para>
15388
15389 <programlisting role="C">
15390 GtkAlignment
15391 GtkArrow
15392 GtkBin
15393 GtkBox
15394 GtkImage
15395 GtkItem
15396 GtkLabel
15397 GtkPixmap
15398 GtkScrolledWindow
15399 GtkSeparator
15400 GtkTable
15401 GtkAspectFrame
15402 GtkFrame
15403 GtkVBox
15404 GtkHBox
15405 GtkVSeparator
15406 GtkHSeparator
15407 </programlisting>
15408
15409 <para>To capture events for these widgets, you need to use an EventBox
15410 widget. See the section on the <link linkend="sec-EventBox">EventBox</link> widget for details.</para>
15411
15412 <para>For our drawing program, we want to know when the mouse button is
15413 pressed and when the mouse is moved, so we specify
15414 <literal>GDK_POINTER_MOTION_MASK</literal> and <literal>GDK_BUTTON_PRESS_MASK</literal>. We also
15415 want to know when we need to redraw our window, so we specify
15416 <literal>GDK_EXPOSURE_MASK</literal>. Although we want to be notified via a
15417 Configure event when our window size changes, we don't have to specify
15418 the corresponding <literal>GDK_STRUCTURE_MASK</literal> flag, because it is
15419 automatically specified for all windows.</para>
15420
15421 <para>It turns out, however, that there is a problem with just specifying
15422 <literal>GDK_POINTER_MOTION_MASK</literal>. This will cause the server to add a new
15423 motion event to the event queue every time the user moves the mouse.
15424 Imagine that it takes us 0.1 seconds to handle a motion event, but the
15425 X server queues a new motion event every 0.05 seconds. We will soon
15426 get way behind the users drawing. If the user draws for 5 seconds,
15427 it will take us another 5 seconds to catch up after they release 
15428 the mouse button! What we would like is to only get one motion
15429 event for each event we process. The way to do this is to 
15430 specify <literal>GDK_POINTER_MOTION_HINT_MASK</literal>. </para>
15431
15432 <para>When we specify <literal>GDK_POINTER_MOTION_HINT_MASK</literal>, the server sends
15433 us a motion event the first time the pointer moves after entering
15434 our window, or after a button press or release event. Subsequent 
15435 motion events will be suppressed until we explicitly ask for
15436 the position of the pointer using the function:</para>
15437
15438 <programlisting role="C">
15439 GdkWindow*    gdk_window_get_pointer     (GdkWindow       *window,
15440                                           gint            *x,
15441                                           gint            *y,
15442                                           GdkModifierType *mask);
15443 </programlisting>
15444
15445 <para>(There is another function, <literal>gtk_widget_get_pointer()</literal> which
15446 has a simpler interface, but turns out not to be very useful, since
15447 it only retrieves the position of the mouse, not whether the buttons
15448 are pressed.)</para>
15449
15450 <para>The code to set the events for our window then looks like:</para>
15451
15452 <programlisting role="C">
15453   gtk_signal_connect (GTK_OBJECT (drawing_area), "expose_event",
15454                       (GtkSignalFunc) expose_event, NULL);
15455   gtk_signal_connect (GTK_OBJECT(drawing_area),"configure_event",
15456                       (GtkSignalFunc) configure_event, NULL);
15457   gtk_signal_connect (GTK_OBJECT (drawing_area), "motion_notify_event",
15458                       (GtkSignalFunc) motion_notify_event, NULL);
15459   gtk_signal_connect (GTK_OBJECT (drawing_area), "button_press_event",
15460                       (GtkSignalFunc) button_press_event, NULL);
15461
15462   gtk_widget_set_events (drawing_area, GDK_EXPOSURE_MASK
15463                          | GDK_LEAVE_NOTIFY_MASK
15464                          | GDK_BUTTON_PRESS_MASK
15465                          | GDK_POINTER_MOTION_MASK
15466                          | GDK_POINTER_MOTION_HINT_MASK);
15467 </programlisting>
15468
15469 <para>We'll save the "expose_event" and "configure_event" handlers for
15470 later. The "motion_notify_event" and "button_press_event" handlers
15471 are pretty simple:</para>
15472
15473 <programlisting role="C">
15474 static gint
15475 button_press_event (GtkWidget *widget, GdkEventButton *event)
15476 {
15477   if (event->button == 1 &amp;&amp; pixmap != NULL)
15478       draw_brush (widget, event->x, event->y);
15479
15480   return TRUE;
15481 }
15482
15483 static gint
15484 motion_notify_event (GtkWidget *widget, GdkEventMotion *event)
15485 {
15486   int x, y;
15487   GdkModifierType state;
15488
15489   if (event->is_hint)
15490     gdk_window_get_pointer (event->window, &amp;x, &amp;y, &amp;state);
15491   else
15492     {
15493       x = event->x;
15494       y = event->y;
15495       state = event->state;
15496     }
15497     
15498   if (state &amp; GDK_BUTTON1_MASK &amp;&amp; pixmap != NULL)
15499     draw_brush (widget, x, y);
15500   
15501   return TRUE;
15502 }
15503 </programlisting>
15504
15505 </sect1>
15506
15507 <!-- ----------------------------------------------------------------- -->
15508 <sect1 id="sec-TheDrawingAreaWidget">
15509 <title>The DrawingArea Widget, And Drawing</title>
15510
15511 <para>We now turn to the process of drawing on the screen. The 
15512 widget we use for this is the DrawingArea widget. A drawing area
15513 widget is essentially an X window and nothing more. It is a blank
15514 canvas in which we can draw whatever we like. A drawing area
15515 is created using the call:</para>
15516
15517 <programlisting role="C">
15518 GtkWidget* gtk_drawing_area_new        (void);
15519 </programlisting>
15520
15521 <para>A default size for the widget can be specified by calling:</para>
15522
15523 <programlisting role="C">
15524 void       gtk_drawing_area_size       (GtkDrawingArea      *darea,
15525                                         gint                 width,
15526                                         gint                 height);
15527 </programlisting>
15528
15529 <para>This default size can be overridden, as is true for all widgets,
15530 by calling <literal>gtk_widget_set_usize()</literal>, and that, in turn, can
15531 be overridden if the user manually resizes the the window containing
15532 the drawing area.</para>
15533
15534 <para>It should be noted that when we create a DrawingArea widget, we are
15535 <emphasis>completely</emphasis> responsible for drawing the contents. If our
15536 window is obscured then uncovered, we get an exposure event and must
15537 redraw what was previously hidden.</para>
15538
15539 <para>Having to remember everything that was drawn on the screen so we
15540 can properly redraw it can, to say the least, be a nuisance. In
15541 addition, it can be visually distracting if portions of the
15542 window are cleared, then redrawn step by step. The solution to
15543 this problem is to use an offscreen <emphasis>backing pixmap</emphasis>.
15544 Instead of drawing directly to the screen, we draw to an image
15545 stored in server memory but not displayed, then when the image
15546 changes or new portions of the image are displayed, we copy the
15547 relevant portions onto the screen.</para>
15548
15549 <para>To create an offscreen pixmap, we call the function:</para>
15550
15551 <programlisting role="C">
15552 GdkPixmap* gdk_pixmap_new               (GdkWindow  *window,
15553                                          gint        width,
15554                                          gint        height,
15555                                          gint        depth);
15556 </programlisting>
15557
15558 <para>The <literal>window</literal> parameter specifies a GDK window that this pixmap
15559 takes some of its properties from. <literal>width</literal> and <literal>height</literal>
15560 specify the size of the pixmap. <literal>depth</literal> specifies the <emphasis>color
15561 depth</emphasis>, that is the number of bits per pixel, for the new window.
15562 If the depth is specified as <literal>-1</literal>, it will match the depth
15563 of <literal>window</literal>.</para>
15564
15565 <para>We create the pixmap in our "configure_event" handler. This event
15566 is generated whenever the window changes size, including when it
15567 is originally created.</para>
15568
15569 <programlisting role="C">
15570 /* Backing pixmap for drawing area */
15571 static GdkPixmap *pixmap = NULL;
15572
15573 /* Create a new backing pixmap of the appropriate size */
15574 static gint
15575 configure_event (GtkWidget *widget, GdkEventConfigure *event)
15576 {
15577   if (pixmap)
15578     gdk_pixmap_unref(pixmap);
15579
15580   pixmap = gdk_pixmap_new(widget->window,
15581                           widget->allocation.width,
15582                           widget->allocation.height,
15583                           -1);
15584   gdk_draw_rectangle (pixmap,
15585                       widget->style->white_gc,
15586                       TRUE,
15587                       0, 0,
15588                       widget->allocation.width,
15589                       widget->allocation.height);
15590
15591   return TRUE;
15592 }
15593 </programlisting>
15594
15595 <para>The call to <literal>gdk_draw_rectangle()</literal> clears the pixmap
15596 initially to white. We'll say more about that in a moment.</para>
15597
15598 <para>Our exposure event handler then simply copies the relevant portion
15599 of the pixmap onto the screen (we determine the area we need
15600 to redraw by using the event->area field of the exposure event):</para>
15601
15602 <programlisting role="C">
15603 /* Redraw the screen from the backing pixmap */
15604 static gint
15605 expose_event (GtkWidget *widget, GdkEventExpose *event)
15606 {
15607   gdk_draw_pixmap(widget->window,
15608                   widget->style->fg_gc[GTK_WIDGET_STATE (widget)],
15609                   pixmap,
15610                   event->area.x, event->area.y,
15611                   event->area.x, event->area.y,
15612                   event->area.width, event->area.height);
15613
15614   return FALSE;
15615 }
15616 </programlisting>
15617
15618 <para>We've now seen how to keep the screen up to date with our pixmap, but
15619 how do we actually draw interesting stuff on our pixmap?  There are a
15620 large number of calls in GTK's GDK library for drawing on
15621 <emphasis>drawables</emphasis>. A drawable is simply something that can be drawn
15622 upon. It can be a window, a pixmap, or a bitmap (a black and white
15623 image).  We've already seen two such calls above,
15624 <literal>gdk_draw_rectangle()</literal> and <literal>gdk_draw_pixmap()</literal>. The
15625 complete list is:</para>
15626
15627 <programlisting role="C">
15628 gdk_draw_line ()
15629 gdk_draw_rectangle ()
15630 gdk_draw_arc ()
15631 gdk_draw_polygon ()
15632 gdk_draw_string ()
15633 gdk_draw_text ()
15634 gdk_draw_pixmap ()
15635 gdk_draw_bitmap ()
15636 gdk_draw_image ()
15637 gdk_draw_points ()
15638 gdk_draw_segments ()
15639 </programlisting>
15640
15641 <para>See the reference documentation or the header file
15642 <literal>&lt;gdk/gdk.h&gt;</literal> for further details on these functions.
15643 These functions all share the same first two arguments. The first
15644 argument is the drawable to draw upon, the second argument is a
15645 <emphasis>graphics context</emphasis> (GC). </para>
15646
15647 <para>A graphics context encapsulates information about things such as
15648 foreground and background color and line width. GDK has a full set of
15649 functions for creating and modifying graphics contexts, but to keep
15650 things simple we'll just use predefined graphics contexts. Each widget
15651 has an associated style. (Which can be modified in a gtkrc file, see
15652 the section GTK's rc file.) This, among other things, stores a number
15653 of graphics contexts. Some examples of accessing these graphics
15654 contexts are:</para>
15655
15656 <programlisting role="C">
15657 widget->style->white_gc
15658 widget->style->black_gc
15659 widget->style->fg_gc[GTK_STATE_NORMAL]
15660 widget->style->bg_gc[GTK_WIDGET_STATE(widget)]
15661 </programlisting>
15662
15663 <para>The fields <literal>fg_gc</literal>, <literal>bg_gc</literal>, <literal>dark_gc</literal>, and
15664 <literal>light_gc</literal> are indexed by a parameter of type
15665 <literal>GtkStateType</literal> which can take on the values:</para>
15666
15667 <programlisting role="C">
15668 GTK_STATE_NORMAL,
15669 GTK_STATE_ACTIVE,
15670 GTK_STATE_PRELIGHT,
15671 GTK_STATE_SELECTED,
15672 GTK_STATE_INSENSITIVE
15673 </programlisting>
15674
15675 <para>For instance, for <literal>GTK_STATE_SELECTED</literal> the default foreground
15676 color is white and the default background color, dark blue.</para>
15677
15678 <para>Our function <literal>draw_brush()</literal>, which does the actual drawing
15679 on the screen, is then:</para>
15680
15681 <programlisting role="C">
15682 /* Draw a rectangle on the screen */
15683 static void
15684 draw_brush (GtkWidget *widget, gdouble x, gdouble y)
15685 {
15686   GdkRectangle update_rect;
15687
15688   update_rect.x = x - 5;
15689   update_rect.y = y - 5;
15690   update_rect.width = 10;
15691   update_rect.height = 10;
15692   gdk_draw_rectangle (pixmap,
15693                       widget->style->black_gc,
15694                       TRUE,
15695                       update_rect.x, update_rect.y,
15696                       update_rect.width, update_rect.height);
15697   gtk_widget_draw (widget, &amp;update_rect);
15698 }
15699 </programlisting>
15700
15701 <para>After we draw the rectangle representing the brush onto the pixmap,
15702 we call the function:</para>
15703
15704 <programlisting role="C">
15705 void       gtk_widget_draw                (GtkWidget           *widget,
15706                                            GdkRectangle        *area);
15707 </programlisting>
15708
15709 <para>which notifies X that the area given by the <literal>area</literal> parameter
15710 needs to be updated. X will eventually generate an expose event
15711 (possibly combining the areas passed in several calls to
15712 <literal>gtk_widget_draw()</literal>) which will cause our expose event handler
15713 to copy the relevant portions to the screen.</para>
15714
15715 <para>We have now covered the entire drawing program except for a few
15716 mundane details like creating the main window.</para>
15717
15718 </sect1>
15719
15720 <!-- ----------------------------------------------------------------- -->
15721 <sect1 id="sec-AddingXInputSupport">
15722 <title>Adding XInput support</title>
15723
15724 <para>It is now possible to buy quite inexpensive input devices such 
15725 as drawing tablets, which allow drawing with a much greater
15726 ease of artistic expression than does a mouse. The simplest way
15727 to use such devices is simply as a replacement for the mouse,
15728 but that misses out many of the advantages of these devices,
15729 such as:</para>
15730
15731 <itemizedlist>
15732 <listitem><simpara> Pressure sensitivity</simpara>
15733 </listitem>
15734 <listitem><simpara> Tilt reporting</simpara>
15735 </listitem>
15736 <listitem><simpara> Sub-pixel positioning</simpara>
15737 </listitem>
15738 <listitem><simpara> Multiple inputs (for example, a stylus with a point and eraser)</simpara>
15739 </listitem>
15740 </itemizedlist>
15741
15742 <para>For information about the XInput extension, see the <ulink
15743 url="http://www.gtk.org/~otaylor/xinput/howto/index.html">XInput HOWTO</ulink>.</para>
15744
15745 <para>If we examine the full definition of, for example, the GdkEventMotion
15746 structure, we see that it has fields to support extended device
15747 information.</para>
15748
15749 <programlisting role="C">
15750 struct _GdkEventMotion
15751 {
15752   GdkEventType type;
15753   GdkWindow *window;
15754   guint32 time;
15755   gdouble x;
15756   gdouble y;
15757   gdouble pressure;
15758   gdouble xtilt;
15759   gdouble ytilt;
15760   guint state;
15761   gint16 is_hint;
15762   GdkInputSource source;
15763   guint32 deviceid;
15764 };
15765 </programlisting>
15766
15767 <para><literal>pressure</literal> gives the pressure as a floating point number between
15768 0 and 1. <literal>xtilt</literal> and <literal>ytilt</literal> can take on values between 
15769 -1 and 1, corresponding to the degree of tilt in each direction.
15770 <literal>source</literal> and <literal>deviceid</literal> specify the device for which the
15771 event occurred in two different ways. <literal>source</literal> gives some simple
15772 information about the type of device. It can take the enumeration
15773 values:</para>
15774
15775 <programlisting role="C">
15776 GDK_SOURCE_MOUSE
15777 GDK_SOURCE_PEN
15778 GDK_SOURCE_ERASER
15779 GDK_SOURCE_CURSOR
15780 </programlisting>
15781
15782 <para><literal>deviceid</literal> specifies a unique numeric ID for the device. This can
15783 be used to find out further information about the device using the
15784 <literal>gdk_input_list_devices()</literal> call (see below). The special value
15785 <literal>GDK_CORE_POINTER</literal> is used for the core pointer device. (Usually
15786 the mouse.)</para>
15787
15788 <!-- ----------------------------------------------------------------- -->
15789 <sect2>
15790 <title>Enabling extended device information</title>
15791
15792 <para>To let GTK know about our interest in the extended device information,
15793 we merely have to add a single line to our program:</para>
15794
15795 <programlisting role="C">
15796 gtk_widget_set_extension_events (drawing_area, GDK_EXTENSION_EVENTS_CURSOR);
15797 </programlisting>
15798
15799 <para>By giving the value <literal>GDK_EXTENSION_EVENTS_CURSOR</literal> we say that
15800 we are interested in extension events, but only if we don't have
15801 to draw our own cursor. See the section <link
15802 linkend="sec-FurtherSophistications"> Further Sophistications </link> below
15803 for more information about drawing the cursor. We could also 
15804 give the values <literal>GDK_EXTENSION_EVENTS_ALL</literal> if we were willing 
15805 to draw our own cursor, or <literal>GDK_EXTENSION_EVENTS_NONE</literal> to revert
15806 back to the default condition.</para>
15807
15808 <para>This is not completely the end of the story however. By default,
15809 no extension devices are enabled. We need a mechanism to allow
15810 users to enable and configure their extension devices. GTK provides
15811 the InputDialog widget to automate this process. The following
15812 procedure manages an InputDialog widget. It creates the dialog if
15813 it isn't present, and raises it to the top otherwise.</para>
15814
15815 <programlisting role="C">
15816 void
15817 input_dialog_destroy (GtkWidget *w, gpointer data)
15818 {
15819   *((GtkWidget **)data) = NULL;
15820 }
15821
15822 void
15823 create_input_dialog ()
15824 {
15825   static GtkWidget *inputd = NULL;
15826
15827   if (!inputd)
15828     {
15829       inputd = gtk_input_dialog_new();
15830
15831       gtk_signal_connect (GTK_OBJECT(inputd), "destroy",
15832                           (GtkSignalFunc)input_dialog_destroy, &amp;inputd);
15833       gtk_signal_connect_object (GTK_OBJECT(GTK_INPUT_DIALOG(inputd)->close_button),
15834                                  "clicked",
15835                                  (GtkSignalFunc)gtk_widget_hide,
15836                                  GTK_OBJECT(inputd));
15837       gtk_widget_hide ( GTK_INPUT_DIALOG(inputd)->save_button);
15838
15839       gtk_widget_show (inputd);
15840     }
15841   else
15842     {
15843       if (!GTK_WIDGET_MAPPED(inputd))
15844         gtk_widget_show(inputd);
15845       else
15846         gdk_window_raise(inputd->window);
15847     }
15848 }
15849 </programlisting>
15850
15851 <para>(You might want to take note of the way we handle this dialog.  By
15852 connecting to the "destroy" signal, we make sure that we don't keep a
15853 pointer to dialog around after it is destroyed - that could lead to a
15854 segfault.)</para>
15855
15856 <para>The InputDialog has two buttons "Close" and "Save", which by default
15857 have no actions assigned to them. In the above function we make
15858 "Close" hide the dialog, hide the "Save" button, since we don't
15859 implement saving of XInput options in this program.</para>
15860
15861 </sect2>
15862
15863 <!-- ----------------------------------------------------------------- -->
15864 <sect2>
15865 <title>Using extended device information</title>
15866
15867 <para>Once we've enabled the device, we can just use the extended 
15868 device information in the extra fields of the event structures.
15869 In fact, it is always safe to use this information since these
15870 fields will have reasonable default values even when extended
15871 events are not enabled.</para>
15872
15873 <para>Once change we do have to make is to call
15874 <literal>gdk_input_window_get_pointer()</literal> instead of
15875 <literal>gdk_window_get_pointer</literal>. This is necessary because
15876 <literal>gdk_window_get_pointer</literal> doesn't return the extended device
15877 information.</para>
15878
15879 <programlisting role="C">
15880 void gdk_input_window_get_pointer( GdkWindow       *window,
15881                                    guint32         deviceid,
15882                                    gdouble         *x,
15883                                    gdouble         *y,
15884                                    gdouble         *pressure,
15885                                    gdouble         *xtilt,
15886                                    gdouble         *ytilt,
15887                                    GdkModifierType *mask);
15888 </programlisting>
15889
15890 <para>When calling this function, we need to specify the device ID as
15891 well as the window. Usually, we'll get the device ID from the
15892 <literal>deviceid</literal> field of an event structure. Again, this function
15893 will return reasonable values when extension events are not
15894 enabled. (In this case, <literal>event->deviceid</literal> will have the value
15895 <literal>GDK_CORE_POINTER</literal>).</para>
15896
15897 <para>So the basic structure of our button-press and motion event handlers
15898 doesn't change much - we just need to add code to deal with the
15899 extended information.</para>
15900
15901 <programlisting role="C">
15902 static gint
15903 button_press_event (GtkWidget *widget, GdkEventButton *event)
15904 {
15905   print_button_press (event->deviceid);
15906   
15907   if (event->button == 1 &amp;&amp; pixmap != NULL)
15908     draw_brush (widget, event->source, event->x, event->y, event->pressure);
15909
15910   return TRUE;
15911 }
15912
15913 static gint
15914 motion_notify_event (GtkWidget *widget, GdkEventMotion *event)
15915 {
15916   gdouble x, y;
15917   gdouble pressure;
15918   GdkModifierType state;
15919
15920   if (event->is_hint)
15921     gdk_input_window_get_pointer (event->window, event->deviceid,
15922                                   &amp;x, &amp;y, &amp;pressure, NULL, NULL, &amp;state);
15923   else
15924     {
15925       x = event->x;
15926       y = event->y;
15927       pressure = event->pressure;
15928       state = event->state;
15929     }
15930     
15931   if (state &amp; GDK_BUTTON1_MASK &amp;&amp; pixmap != NULL)
15932     draw_brush (widget, event->source, x, y, pressure);
15933   
15934   return TRUE;
15935 }
15936 </programlisting>
15937
15938 <para>We also need to do something with the new information. Our new
15939 <literal>draw_brush()</literal> function draws with a different color for
15940 each <literal>event->source</literal> and changes the brush size depending
15941 on the pressure.</para>
15942
15943 <programlisting role="C">
15944 /* Draw a rectangle on the screen, size depending on pressure,
15945    and color on the type of device */
15946 static void
15947 draw_brush (GtkWidget *widget, GdkInputSource source,
15948             gdouble x, gdouble y, gdouble pressure)
15949 {
15950   GdkGC *gc;
15951   GdkRectangle update_rect;
15952
15953   switch (source)
15954     {
15955     case GDK_SOURCE_MOUSE:
15956       gc = widget->style->dark_gc[GTK_WIDGET_STATE (widget)];
15957       break;
15958     case GDK_SOURCE_PEN:
15959       gc = widget->style->black_gc;
15960       break;
15961     case GDK_SOURCE_ERASER:
15962       gc = widget->style->white_gc;
15963       break;
15964     default:
15965       gc = widget->style->light_gc[GTK_WIDGET_STATE (widget)];
15966     }
15967
15968   update_rect.x = x - 10 * pressure;
15969   update_rect.y = y - 10 * pressure;
15970   update_rect.width = 20 * pressure;
15971   update_rect.height = 20 * pressure;
15972   gdk_draw_rectangle (pixmap, gc, TRUE,
15973                       update_rect.x, update_rect.y,
15974                       update_rect.width, update_rect.height);
15975   gtk_widget_draw (widget, &amp;update_rect);
15976 }
15977 </programlisting>
15978
15979 </sect2>
15980
15981 <!-- ----------------------------------------------------------------- -->
15982 <sect2>
15983 <title>Finding out more about a device</title>
15984
15985 <para>As an example of how to find out more about a device, our program
15986 will print the name of the device that generates each button
15987 press. To find out the name of a device, we call the function:</para>
15988
15989 <programlisting role="C">
15990 GList *gdk_input_list_devices               (void);
15991 </programlisting>
15992
15993 <para>which returns a GList (a linked list type from the GLib library)
15994 of GdkDeviceInfo structures. The GdkDeviceInfo structure is defined
15995 as:</para>
15996
15997 <programlisting role="C">
15998 struct _GdkDeviceInfo
15999 {
16000   guint32 deviceid;
16001   gchar *name;
16002   GdkInputSource source;
16003   GdkInputMode mode;
16004   gint has_cursor;
16005   gint num_axes;
16006   GdkAxisUse *axes;
16007   gint num_keys;
16008   GdkDeviceKey *keys;
16009 };
16010 </programlisting>
16011
16012 <para>Most of these fields are configuration information that you can ignore
16013 unless you are implementing XInput configuration saving. The fieldwe
16014 are interested in here is <literal>name</literal> which is simply the name that X
16015 assigns to the device. The other field that isn't configuration
16016 information is <literal>has_cursor</literal>. If <literal>has_cursor</literal> is false, then we
16017 we need to draw our own cursor. But since we've specified
16018 <literal>GDK_EXTENSION_EVENTS_CURSOR</literal>, we don't have to worry about this.</para>
16019
16020 <para>Our <literal>print_button_press()</literal> function simply iterates through
16021 the returned list until it finds a match, then prints out
16022 the name of the device.</para>
16023
16024 <programlisting role="C">
16025 static void
16026 print_button_press (guint32 deviceid)
16027 {
16028   GList *tmp_list;
16029
16030   /* gdk_input_list_devices returns an internal list, so we shouldn't
16031      free it afterwards */
16032   tmp_list = gdk_input_list_devices();
16033
16034   while (tmp_list)
16035     {
16036       GdkDeviceInfo *info = (GdkDeviceInfo *)tmp_list->data;
16037
16038       if (info->deviceid == deviceid)
16039         {
16040           printf("Button press on device '%s'\n", info->name);
16041           return;
16042         }
16043
16044       tmp_list = tmp_list->next;
16045     }
16046 }
16047 </programlisting>
16048
16049 <para>That completes the changes to "XInputize" our program.</para>
16050
16051 </sect2>
16052
16053 <!-- ----------------------------------------------------------------- -->
16054 <sect2 id="sec-FurtherSophistications">
16055 <title>Further sophistications</title>
16056
16057 <para>Although our program now supports XInput quite well, it lacks some
16058 features we would want in a full-featured application. First, the user
16059 probably doesn't want to have to configure their device each time they
16060 run the program, so we should allow them to save the device
16061 configuration. This is done by iterating through the return of
16062 <literal>gdk_input_list_devices()</literal> and writing out the configuration to a
16063 file.</para>
16064
16065 <para>To restore the state next time the program is run, GDK provides
16066 functions to change device configuration:</para>
16067
16068 <programlisting role="C">
16069 gdk_input_set_extension_events()
16070 gdk_input_set_source()
16071 gdk_input_set_mode()
16072 gdk_input_set_axes()
16073 gdk_input_set_key()
16074 </programlisting>
16075
16076 <para>(The list returned from <literal>gdk_input_list_devices()</literal> should not be
16077 modified directly.) An example of doing this can be found in the
16078 drawing program gsumi. (Available from <ulink
16079 url="http://www.msc.cornell.edu/~otaylor/gsumi/">http://www.msc.cornell.edu/~otaylor/gsumi/</ulink>) Eventually, it
16080 would be nice to have a standard way of doing this for all
16081 applications. This probably belongs at a slightly higher level than
16082 GTK, perhaps in the GNOME library.</para>
16083
16084 <para>Another major omission that we have mentioned above is the lack of
16085 cursor drawing. Platforms other than XFree86 currently do not allow
16086 simultaneously using a device as both the core pointer and directly by
16087 an application. See the <ulink
16088 url="http://www.msc.cornell.edu/~otaylor/xinput/XInput-HOWTO.html">XInput-HOWTO</ulink> for more information about this. This means that
16089 applications that want to support the widest audience need to draw
16090 their own cursor.</para>
16091
16092 <para>An application that draws its own cursor needs to do two things:
16093 determine if the current device needs a cursor drawn or not, and
16094 determine if the current device is in proximity. (If the current
16095 device is a drawing tablet, it's a nice touch to make the cursor 
16096 disappear when the stylus is lifted from the tablet. When the
16097 device is touching the stylus, that is called "in proximity.")
16098 The first is done by searching the device list, as we did
16099 to find out the device name. The second is achieved by selecting
16100 "proximity_out" events. An example of drawing one's own cursor is
16101 found in the "testinput" program found in the GTK distribution.</para>
16102
16103 </sect2>
16104
16105 </sect1>
16106 </chapter>
16107
16108 <!-- ***************************************************************** -->
16109 <chapter id="ch-Tips">
16110 <title>Tips For Writing GTK Applications</title>
16111
16112 <para>This section is simply a gathering of wisdom, general style guidelines
16113 and hints to creating good GTK applications. Currently this section
16114 is very short, but I hope it will get longer in future editions of
16115 this tutorial.</para>
16116
16117 <para>Use GNU autoconf and automake! They are your friends :) Automake
16118 examines C files, determines how they depend on each other, and
16119 generates a Makefile so the files can be compiled in the correct
16120 order. Autoconf permits automatic configuration of software
16121 installation, handling a large number of system quirks to increase
16122 portability. I am planning to make a quick intro on them here.</para>
16123
16124 <para>When writing C code, use only C comments (beginning with "/*" and
16125 ending with "*/"), and don't use C++-style comments ("//").  Although
16126 many C compilers understand C++ comments, others don't, and the ANSI C
16127 standard does not require that C++-style comments be processed as
16128 comments.</para>
16129
16130 </chapter>
16131
16132 <!-- ***************************************************************** -->
16133 <chapter id="ch-Contributing">
16134 <title>Contributing</title>
16135
16136 <para>This document, like so much other great software out there, was
16137 created for free by volunteers.  If you are at all knowledgeable about
16138 any aspect of GTK that does not already have documentation, please
16139 consider contributing to this document.</para>
16140
16141 <para>If you do decide to contribute, please mail your text to Tony Gale,
16142 <literal><ulink url="mailto:gale@gtk.org">gale@gtk.org</ulink></literal>. Also, be aware that the entirety of this
16143 document is free, and any addition by you provide must also be
16144 free. That is, people may use any portion of your examples in their
16145 programs, and copies of this document may be distributed at will, etc.</para>
16146
16147 <para>Thank you.</para>
16148
16149 </chapter>
16150
16151 <!-- ***************************************************************** -->
16152 <chapter id="ch-Credits">
16153 <title>Credits</title>
16154
16155 <para>We would like to thank the following for their contributions to this text.</para>
16156
16157 <itemizedlist>
16158 <listitem><simpara>Bawer Dagdeviren, <literal><ulink url="mailto:chamele0n@geocities.com">chamele0n@geocities.com</ulink></literal> for the menus tutorial.</simpara>
16159 </listitem>
16160
16161 <listitem><simpara>Raph Levien, <literal><ulink url="mailto:raph@acm.org">raph@acm.org</ulink></literal>
16162 for hello world ala GTK, widget packing, and general all around wisdom.
16163 He's also generously donated a home for this tutorial.</simpara>
16164 </listitem>
16165
16166 <listitem><simpara>Peter Mattis, <literal><ulink url="mailto:petm@xcf.berkeley.edu">petm@xcf.berkeley.edu</ulink></literal> for the simplest GTK program.. 
16167 and the ability to make it :)</simpara>
16168 </listitem>
16169
16170 <listitem><simpara>Werner Koch <literal><ulink url="mailto:werner.koch@guug.de">werner.koch@guug.de</ulink></literal> for converting the original plain text to
16171 SGML, and the widget class hierarchy.</simpara>
16172 </listitem>
16173
16174 <listitem><simpara>Mark Crichton <literal><ulink
16175 url="mailto:crichton@expert.cc.purdue.edu">crichton@expert.cc.purdue.edu</ulink></literal> for the menu factory code,
16176 and the table packing tutorial.</simpara>
16177 </listitem>
16178
16179 <listitem><simpara>Owen Taylor <literal><ulink url="mailto:owt1@cornell.edu">owt1@cornell.edu</ulink></literal> for the EventBox widget section (and the
16180 patch to the distro).  He's also responsible for the selections code
16181 and tutorial, as well as the sections on writing your own GTK widgets,
16182 and the example application. Thanks a lot Owen for all you help!</simpara>
16183 </listitem>
16184
16185 <listitem><simpara>Mark VanderBoom <literal><ulink url="mailto:mvboom42@calvin.edu">mvboom42@calvin.edu</ulink></literal> for his wonderful work on the
16186 Notebook, Progress Bar, Dialogs, and File selection widgets.  Thanks a
16187 lot Mark!  You've been a great help.</simpara>
16188 </listitem>
16189
16190 <listitem><simpara>Tim Janik <literal><ulink url="mailto:timj@gtk.org">timj@gtk.org</ulink></literal> for his great job on the Lists
16191 Widget. His excellent work on automatically extracting the widget tree
16192 and signal information from GTK. Thanks Tim :)</simpara>
16193 </listitem>
16194
16195 <listitem><simpara>Rajat Datta <literal><ulink url="mailto:rajat@ix.netcom.com">rajat@ix.netcom.com</ulink>
16196 </literal> for the excellent job on the Pixmap
16197 tutorial.</simpara>
16198 </listitem>
16199
16200 <listitem><simpara>Michael K. Johnson <literal><ulink url="mailto:johnsonm@redhat.com">johnsonm@redhat.com</ulink></literal> for info and code for popup menus.</simpara>
16201 </listitem>
16202
16203 <listitem><simpara>David Huggins-Daines <literal><ulink
16204 url="mailto:bn711@freenet.carleton.ca">bn711@freenet.carleton.ca</ulink></literal> for the Range Widgets and Tree
16205 Widget sections.</simpara>
16206 </listitem>
16207
16208 <listitem><simpara>Stefan Mars <literal><ulink url="mailto:mars@lysator.liu.se">mars@lysator.liu.se</ulink></literal> for the CList section.</simpara>
16209 </listitem>
16210
16211 <listitem><simpara>David A. Wheeler <literal><ulink url="mailto:dwheeler@ida.org">dwheeler@ida.org</ulink></literal> for portions of the text on GLib
16212 and various tutorial fixups and improvements.
16213 The GLib text was in turn based on material developed by Damon Chaplin
16214 <literal><ulink url="mailto:DAChaplin@msn.com">DAChaplin@msn.com</ulink></literal></simpara>
16215 </listitem>
16216
16217 <listitem><simpara>David King for style checking the entire document.</simpara>
16218 </listitem>
16219 </itemizedlist>
16220
16221 <para>And to all of you who commented on and helped refine this document.</para>
16222
16223 <para>Thanks.</para>
16224
16225 </chapter>
16226
16227 <!-- ***************************************************************** -->
16228 <chapter id="ch-Copyright">
16229 <title>Tutorial Copyright and Permissions Notice</title>
16230
16231 <para>The GTK Tutorial is Copyright (C) 1997 Ian Main. </para>
16232
16233 <para>Copyright (C) 1998-1999 Tony Gale.</para>
16234
16235 <para>Permission is granted to make and distribute verbatim copies of this 
16236 manual provided the copyright notice and this permission notice are 
16237 preserved on all copies.</para>
16238
16239 <para>Permission is granted to copy and distribute modified versions of 
16240 this document under the conditions for verbatim copying, provided that 
16241 this copyright notice is included exactly as in the original,
16242 and that the entire resulting derived work is distributed under 
16243 the terms of a permission notice identical to this one.</para>
16244
16245 <para>Permission is granted to copy and distribute translations of this 
16246 document into another language, under the above conditions for modified 
16247 versions.</para>
16248
16249 <para>If you are intending to incorporate this document into a published 
16250 work, please contact the maintainer, and we will make an effort 
16251 to ensure that you have the most up to date information available.</para>
16252
16253 <para>There is no guarantee that this document lives up to its intended
16254 purpose.  This is simply provided as a free resource.  As such,
16255 the authors and maintainers of the information provided within can
16256 not make any guarantee that the information is even accurate.</para>
16257
16258 </chapter>
16259
16260 <!-- ***************************************************************** -->
16261 <!-- ***************************************************************** -->
16262
16263 <!-- ***************************************************************** -->
16264 <appendix id="app-GTKSignals">
16265 <title>GTK Signals</title>
16266
16267 <para>As GTK is an object oriented widget set, it has a hierarchy of
16268 inheritance. This inheritance mechanism applies for
16269 signals. Therefore, you should refer to the widget hierarchy tree when
16270 using the signals listed in this section.</para>
16271
16272 <!-- ----------------------------------------------------------------- -->
16273 <sect1 id="sec-GtkObject">
16274 <title>GtkObject</title>
16275
16276 <programlisting role="C">
16277 void GtkObject::destroy (GtkObject *,
16278                          gpointer);
16279 </programlisting>
16280
16281 </sect1>
16282
16283 <!-- ----------------------------------------------------------------- -->
16284 <sect1 id="sec-GtkWidget">
16285 <title>GtkWidget</title>
16286
16287 <programlisting role="C">
16288 void GtkWidget::show    (GtkWidget *,
16289                          gpointer);
16290 void GtkWidget::hide    (GtkWidget *,
16291                          gpointer);
16292 void GtkWidget::map     (GtkWidget *,
16293                          gpointer);
16294 void GtkWidget::unmap   (GtkWidget *,
16295                          gpointer);
16296 void GtkWidget::realize (GtkWidget *,
16297                          gpointer);
16298 void GtkWidget::unrealize       (GtkWidget *,
16299                                  gpointer);
16300 void GtkWidget::draw    (GtkWidget *,
16301                          ggpointer,
16302                          gpointer);
16303 void GtkWidget::draw-focus      (GtkWidget *,
16304                                  gpointer);
16305 void GtkWidget::draw-default    (GtkWidget *,
16306                                  gpointer);
16307 void GtkWidget::size-request    (GtkWidget *,
16308                                  ggpointer,
16309                                  gpointer);
16310 void GtkWidget::size-allocate   (GtkWidget *,
16311                                  ggpointer,
16312                                  gpointer);
16313 void GtkWidget::state-changed   (GtkWidget *,
16314                                  GtkStateType,
16315                                  gpointer);
16316 void GtkWidget::parent-set      (GtkWidget *,
16317                                  GtkObject *,
16318                                  gpointer);
16319 void GtkWidget::style-set       (GtkWidget *,
16320                                  GtkStyle *,
16321                                  gpointer);
16322 void GtkWidget::add-accelerator (GtkWidget *,
16323                                  gguint,
16324                                  GtkAccelGroup *,
16325                                  gguint,
16326                                  GdkModifierType,
16327                                  GtkAccelFlags,
16328                                  gpointer);
16329 void GtkWidget::remove-accelerator      (GtkWidget *,
16330                                          GtkAccelGroup *,
16331                                          gguint,
16332                                          GdkModifierType,
16333                                          gpointer);
16334 gboolean GtkWidget::event       (GtkWidget *,
16335                                  GdkEvent *,
16336                                  gpointer);
16337 gboolean GtkWidget::button-press-event  (GtkWidget *,
16338                                          GdkEvent *,
16339                                          gpointer);
16340 gboolean GtkWidget::button-release-event        (GtkWidget *,
16341                                                  GdkEvent *,
16342                                                  gpointer);
16343 gboolean GtkWidget::motion-notify-event (GtkWidget *,
16344                                          GdkEvent *,
16345                                          gpointer);
16346 gboolean GtkWidget::delete-event        (GtkWidget *,
16347                                          GdkEvent *,
16348                                          gpointer);
16349 gboolean GtkWidget::destroy-event       (GtkWidget *,
16350                                          GdkEvent *,
16351                                          gpointer);
16352 gboolean GtkWidget::expose-event        (GtkWidget *,
16353                                          GdkEvent *,
16354                                          gpointer);
16355 gboolean GtkWidget::key-press-event     (GtkWidget *,
16356                                          GdkEvent *,
16357                                          gpointer);
16358 gboolean GtkWidget::key-release-event   (GtkWidget *,
16359                                          GdkEvent *,
16360                                          gpointer);
16361 gboolean GtkWidget::enter-notify-event  (GtkWidget *,
16362                                          GdkEvent *,
16363                                          gpointer);
16364 gboolean GtkWidget::leave-notify-event  (GtkWidget *,
16365                                          GdkEvent *,
16366                                          gpointer);
16367 gboolean GtkWidget::configure-event     (GtkWidget *,
16368                                          GdkEvent *,
16369                                          gpointer);
16370 gboolean GtkWidget::focus-in-event      (GtkWidget *,
16371                                          GdkEvent *,
16372                                          gpointer);
16373 gboolean GtkWidget::focus-out-event     (GtkWidget *,
16374                                          GdkEvent *,
16375                                          gpointer);
16376 gboolean GtkWidget::map-event   (GtkWidget *,
16377                                  GdkEvent *,
16378                                  gpointer);
16379 gboolean GtkWidget::unmap-event (GtkWidget *,
16380                                  GdkEvent *,
16381                                  gpointer);
16382 gboolean GtkWidget::property-notify-event       (GtkWidget *,
16383                                                  GdkEvent *,
16384                                                  gpointer);
16385 gboolean GtkWidget::selection-clear-event       (GtkWidget *,
16386                                                  GdkEvent *,
16387                                                  gpointer);
16388 gboolean GtkWidget::selection-request-event     (GtkWidget *,
16389                                                  GdkEvent *,
16390                                                  gpointer);
16391 gboolean GtkWidget::selection-notify-event      (GtkWidget *,
16392                                                  GdkEvent *,
16393                                                  gpointer);
16394 void GtkWidget::selection-get   (GtkWidget *,
16395                                  GtkSelectionData *,
16396                                  gguint,
16397                                  gpointer);
16398 void GtkWidget::selection-received      (GtkWidget *,
16399                                          GtkSelectionData *,
16400                                          gguint,
16401                                          gpointer);
16402 gboolean GtkWidget::proximity-in-event  (GtkWidget *,
16403                                          GdkEvent *,
16404                                          gpointer);
16405 gboolean GtkWidget::proximity-out-event (GtkWidget *,
16406                                          GdkEvent *,
16407                                          gpointer);
16408 void GtkWidget::drag-begin      (GtkWidget *,
16409                                  GdkDragContext *,
16410                                  gpointer);
16411 void GtkWidget::drag-end        (GtkWidget *,
16412                                  GdkDragContext *,
16413                                  gpointer);
16414 void GtkWidget::drag-data-delete        (GtkWidget *,
16415                                          GdkDragContext *,
16416                                          gpointer);
16417 void GtkWidget::drag-leave      (GtkWidget *,
16418                                  GdkDragContext *,
16419                                  gguint,
16420                                  gpointer);
16421 gboolean GtkWidget::drag-motion (GtkWidget *,
16422                                  GdkDragContext *,
16423                                  ggint,
16424                                  ggint,
16425                                  gguint,
16426                                  gpointer);
16427 gboolean GtkWidget::drag-drop   (GtkWidget *,
16428                                  GdkDragContext *,
16429                                  ggint,
16430                                  ggint,
16431                                  gguint,
16432                                  gpointer);
16433 void GtkWidget::drag-data-get   (GtkWidget *,
16434                                  GdkDragContext *,
16435                                  GtkSelectionData *,
16436                                  gguint,
16437                                  gguint,
16438                                  gpointer);
16439 void GtkWidget::drag-data-received      (GtkWidget *,
16440                                          GdkDragContext *,
16441                                          ggint,
16442                                          ggint,
16443                                          GtkSelectionData *,
16444                                          gguint,
16445                                          gguint,
16446                                          gpointer);
16447 gboolean GtkWidget::client-event        (GtkWidget *,
16448                                          GdkEvent *,
16449                                          gpointer);
16450 gboolean GtkWidget::no-expose-event     (GtkWidget *,
16451                                          GdkEvent *,
16452                                          gpointer);
16453 gboolean GtkWidget::visibility-notify-event     (GtkWidget *,
16454                                                  GdkEvent *,
16455                                                  gpointer);
16456 void GtkWidget::debug-msg       (GtkWidget *,
16457                                  GtkString *,
16458                                  gpointer);
16459 </programlisting>
16460
16461 </sect1>
16462
16463 <!-- ----------------------------------------------------------------- -->
16464 <sect1 id="sec-GtkData">
16465 <title>GtkData</title>
16466
16467 <programlisting role="C">
16468 void GtkData::disconnect        (GtkData *,
16469                                  gpointer);
16470 </programlisting>
16471
16472 </sect1>
16473
16474 <!-- ----------------------------------------------------------------- -->
16475 <sect1 id="sec-GtkContainer">
16476 <title>GtkContainer</title>
16477
16478 <programlisting role="C">
16479 void GtkContainer::add  (GtkContainer *,
16480                          GtkWidget *,
16481                          gpointer);
16482 void GtkContainer::remove       (GtkContainer *,
16483                                  GtkWidget *,
16484                                  gpointer);
16485 void GtkContainer::check-resize (GtkContainer *,
16486                                  gpointer);
16487 GtkDirectionType GtkContainer::focus    (GtkContainer *,
16488                                          GtkDirectionType,
16489                                          gpointer);
16490 void GtkContainer::set-focus-child      (GtkContainer *,
16491                                          GtkWidget *,
16492                                          gpointer);
16493 </programlisting>
16494
16495 </sect1>
16496
16497 <!-- ----------------------------------------------------------------- -->
16498 <sect1 id="sec-GtkCalendar">
16499 <title>GtkCalendar</title>
16500
16501 <programlisting role="C">
16502 void GtkCalendar::month-changed (GtkCalendar *,
16503                                  gpointer);
16504 void GtkCalendar::day-selected  (GtkCalendar *,
16505                                  gpointer);
16506 void GtkCalendar::day-selected-double-click     (GtkCalendar *,
16507                                                  gpointer);
16508 void GtkCalendar::prev-month    (GtkCalendar *,
16509                                  gpointer);
16510 void GtkCalendar::next-month    (GtkCalendar *,
16511                                  gpointer);
16512 void GtkCalendar::prev-year     (GtkCalendar *,
16513                                  gpointer);
16514 void GtkCalendar::next-year     (GtkCalendar *,
16515                                  gpointer);
16516 </programlisting>
16517
16518 </sect1>
16519
16520 <!-- ----------------------------------------------------------------- -->
16521 <sect1 id="sec-GtkEditable">
16522 <title>GtkEditable</title>
16523
16524 <programlisting role="C">
16525 void GtkEditable::changed       (GtkEditable *,
16526                                  gpointer);
16527 void GtkEditable::insert-text   (GtkEditable *,
16528                                  GtkString *,
16529                                  ggint,
16530                                  ggpointer,
16531                                  gpointer);
16532 void GtkEditable::delete-text   (GtkEditable *,
16533                                  ggint,
16534                                  ggint,
16535                                  gpointer);
16536 void GtkEditable::activate      (GtkEditable *,
16537                                  gpointer);
16538 void GtkEditable::set-editable  (GtkEditable *,
16539                                  gboolean,
16540                                  gpointer);
16541 void GtkEditable::move-cursor   (GtkEditable *,
16542                                  ggint,
16543                                  ggint,
16544                                  gpointer);
16545 void GtkEditable::move-word     (GtkEditable *,
16546                                  ggint,
16547                                  gpointer);
16548 void GtkEditable::move-page     (GtkEditable *,
16549                                  ggint,
16550                                  ggint,
16551                                  gpointer);
16552 void GtkEditable::move-to-row   (GtkEditable *,
16553                                  ggint,
16554                                  gpointer);
16555 void GtkEditable::move-to-column        (GtkEditable *,
16556                                          ggint,
16557                                          gpointer);
16558 void GtkEditable::kill-char     (GtkEditable *,
16559                                  ggint,
16560                                  gpointer);
16561 void GtkEditable::kill-word     (GtkEditable *,
16562                                  ggint,
16563                                  gpointer);
16564 void GtkEditable::kill-line     (GtkEditable *,
16565                                  ggint,
16566                                  gpointer);
16567 void GtkEditable::cut-clipboard (GtkEditable *,
16568                                  gpointer);
16569 void GtkEditable::copy-clipboard        (GtkEditable *,
16570                                          gpointer);
16571 void GtkEditable::paste-clipboard       (GtkEditable *,
16572                                          gpointer);
16573 </programlisting>
16574
16575 </sect1>
16576
16577 <!-- ----------------------------------------------------------------- -->
16578 <sect1 id="sec-GtkTipsQuery">
16579 <title>GtkTipsQuery</title>
16580
16581 <programlisting role="C">
16582 void GtkTipsQuery::start-query  (GtkTipsQuery *,
16583                                  gpointer);
16584 void GtkTipsQuery::stop-query   (GtkTipsQuery *,
16585                                  gpointer);
16586 void GtkTipsQuery::widget-entered       (GtkTipsQuery *,
16587                                          GtkWidget *,
16588                                          GtkString *,
16589                                          GtkString *,
16590                                          gpointer);
16591 gboolean GtkTipsQuery::widget-selected  (GtkTipsQuery *,
16592                                          GtkWidget *,
16593                                          GtkString *,
16594                                          GtkString *,
16595                                          GdkEvent *,
16596                                          gpointer);
16597 </programlisting>
16598
16599 </sect1>
16600
16601 <!-- ----------------------------------------------------------------- -->
16602 <sect1 id="sec-GtkCList">
16603 <title>GtkCList</title>
16604
16605 <programlisting role="C">
16606 void GtkCList::select-row       (GtkCList *,
16607                                  ggint,
16608                                  ggint,
16609                                  GdkEvent *,
16610                                  gpointer);
16611 void GtkCList::unselect-row     (GtkCList *,
16612                                  ggint,
16613                                  ggint,
16614                                  GdkEvent *,
16615                                  gpointer);
16616 void GtkCList::row-move (GtkCList *,
16617                          ggint,
16618                          ggint,
16619                          gpointer);
16620 void GtkCList::click-column     (GtkCList *,
16621                                  ggint,
16622                                  gpointer);
16623 void GtkCList::resize-column    (GtkCList *,
16624                                  ggint,
16625                                  ggint,
16626                                  gpointer);
16627 void GtkCList::toggle-focus-row (GtkCList *,
16628                                  gpointer);
16629 void GtkCList::select-all       (GtkCList *,
16630                                  gpointer);
16631 void GtkCList::unselect-all     (GtkCList *,
16632                                  gpointer);
16633 void GtkCList::undo-selection   (GtkCList *,
16634                                  gpointer);
16635 void GtkCList::start-selection  (GtkCList *,
16636                                  gpointer);
16637 void GtkCList::end-selection    (GtkCList *,
16638                                  gpointer);
16639 void GtkCList::toggle-add-mode  (GtkCList *,
16640                                  gpointer);
16641 void GtkCList::extend-selection (GtkCList *,
16642                                  GtkScrollType,
16643                                  ggfloat,
16644                                  gboolean,
16645                                  gpointer);
16646 void GtkCList::scroll-vertical  (GtkCList *,
16647                                  GtkScrollType,
16648                                  ggfloat,
16649                                  gpointer);
16650 void GtkCList::scroll-horizontal        (GtkCList *,
16651                                          GtkScrollType,
16652                                          ggfloat,
16653                                          gpointer);
16654 void GtkCList::abort-column-resize      (GtkCList *,
16655                                          gpointer);
16656 </programlisting>
16657
16658 </sect1>
16659
16660 <!-- ----------------------------------------------------------------- -->
16661 <sect1 id="sec-GtkNotebook">
16662 <title>GtkNotebook</title>
16663
16664 <programlisting role="C">
16665 void GtkNotebook::switch-page   (GtkNotebook *,
16666                                  ggpointer,
16667                                  gguint,
16668                                  gpointer);
16669 </programlisting>
16670
16671 </sect1>
16672
16673 <!-- ----------------------------------------------------------------- -->
16674 <sect1 id="sec-GtkList">
16675 <title>GtkList</title>
16676
16677 <programlisting role="C">
16678 void GtkList::selection-changed (GtkList *,
16679                                  gpointer);
16680 void GtkList::select-child      (GtkList *,
16681                                  GtkWidget *,
16682                                  gpointer);
16683 void GtkList::unselect-child    (GtkList *,
16684                                  GtkWidget *,
16685                                  gpointer);
16686 </programlisting>
16687
16688 </sect1>
16689
16690 <!-- ----------------------------------------------------------------- -->
16691 <sect1 id="sec-GtkMenuShell">
16692 <title>GtkMenuShell</title>
16693
16694 <programlisting role="C">
16695 void GtkMenuShell::deactivate   (GtkMenuShell *,
16696                                  gpointer);
16697 void GtkMenuShell::selection-done       (GtkMenuShell *,
16698                                          gpointer);
16699 void GtkMenuShell::move-current (GtkMenuShell *,
16700                                  GtkMenuDirectionType,
16701                                  gpointer);
16702 void GtkMenuShell::activate-current     (GtkMenuShell *,
16703                                          gboolean,
16704                                          gpointer);
16705 void GtkMenuShell::cancel       (GtkMenuShell *,
16706                                  gpointer);
16707 </programlisting>
16708
16709 </sect1>
16710
16711 <!-- ----------------------------------------------------------------- -->
16712 <sect1 id="sec-GtkToolbar">
16713 <title>GtkToolbar</title>
16714
16715 <programlisting role="C">
16716 void GtkToolbar::orientation-changed    (GtkToolbar *,
16717                                          ggint,
16718                                          gpointer);
16719 void GtkToolbar::style-changed  (GtkToolbar *,
16720                                  ggint,
16721                                  gpointer);
16722 </programlisting>
16723
16724 </sect1>
16725
16726 <!-- ----------------------------------------------------------------- -->
16727 <sect1 id="sec-GtkTree">
16728 <title>GtkTree</title>
16729
16730 <programlisting role="C">
16731 void GtkTree::selection-changed (GtkTree *,
16732                                  gpointer);
16733 void GtkTree::select-child      (GtkTree *,
16734                                  GtkWidget *,
16735                                  gpointer);
16736 void GtkTree::unselect-child    (GtkTree *,
16737                                  GtkWidget *,
16738                                  gpointer);
16739 </programlisting>
16740
16741 </sect1>
16742
16743 <!-- ----------------------------------------------------------------- -->
16744 <sect1 id="sec-GtkButton">
16745 <title>GtkButton</title>
16746
16747 <programlisting role="C">
16748 void GtkButton::pressed (GtkButton *,
16749                          gpointer);
16750 void GtkButton::released        (GtkButton *,
16751                                  gpointer);
16752 void GtkButton::clicked (GtkButton *,
16753                          gpointer);
16754 void GtkButton::enter   (GtkButton *,
16755                          gpointer);
16756 void GtkButton::leave   (GtkButton *,
16757                          gpointer);
16758 </programlisting>
16759
16760 </sect1>
16761
16762 <!-- ----------------------------------------------------------------- -->
16763 <sect1 id="sec-GtkItem">
16764 <title>GtkItem</title>
16765
16766 <programlisting role="C">
16767 void GtkItem::select    (GtkItem *,
16768                          gpointer);
16769 void GtkItem::deselect  (GtkItem *,
16770                          gpointer);
16771 void GtkItem::toggle    (GtkItem *,
16772                          gpointer);
16773 </programlisting>
16774
16775 </sect1>
16776
16777 <!-- ----------------------------------------------------------------- -->
16778 <sect1 id="sec-GtkWindow">
16779 <title>GtkWindow</title>
16780
16781 <programlisting role="C">
16782 void GtkWindow::set-focus       (GtkWindow *,
16783                                  ggpointer,
16784                                  gpointer);
16785 </programlisting>
16786
16787 </sect1>
16788
16789 <!-- ----------------------------------------------------------------- -->
16790 <sect1 id="sec-GtkHandleBox">
16791 <title>GtkHandleBox</title>
16792
16793 <programlisting role="C">
16794 void GtkHandleBox::child-attached       (GtkHandleBox *,
16795                                          GtkWidget *,
16796                                          gpointer);
16797 void GtkHandleBox::child-detached       (GtkHandleBox *,
16798                                          GtkWidget *,
16799                                          gpointer);
16800 </programlisting>
16801
16802 </sect1>
16803
16804 <!-- ----------------------------------------------------------------- -->
16805 <sect1 id="sec-GtkToggleButton">
16806 <title>GtkToggleButton</title>
16807
16808 <programlisting role="C">
16809 void GtkToggleButton::toggled   (GtkToggleButton *,
16810                                  gpointer);
16811 </programlisting>
16812
16813 </sect1>
16814
16815 <!-- ----------------------------------------------------------------- -->
16816 <sect1 id="sec-GtkMenuItem">
16817 <title>GtkMenuItem</title>
16818
16819 <programlisting role="C">
16820 void GtkMenuItem::activate      (GtkMenuItem *,
16821                                  gpointer);
16822 void GtkMenuItem::activate-item (GtkMenuItem *,
16823                                  gpointer);
16824 </programlisting>
16825
16826 </sect1>
16827
16828 <!-- ----------------------------------------------------------------- -->
16829 <sect1 id="sec-GtkListItem">
16830 <title>GtkListItem</title>
16831
16832 <programlisting role="C">
16833 void GtkListItem::toggle-focus-row      (GtkListItem *,
16834                                          gpointer);
16835 void GtkListItem::select-all    (GtkListItem *,
16836                                  gpointer);
16837 void GtkListItem::unselect-all  (GtkListItem *,
16838                                  gpointer);
16839 void GtkListItem::undo-selection        (GtkListItem *,
16840                                          gpointer);
16841 void GtkListItem::start-selection       (GtkListItem *,
16842                                          gpointer);
16843 void GtkListItem::end-selection (GtkListItem *,
16844                                  gpointer);
16845 void GtkListItem::toggle-add-mode       (GtkListItem *,
16846                                          gpointer);
16847 void GtkListItem::extend-selection      (GtkListItem *,
16848                                          GtkEnum,
16849                                          ggfloat,
16850                                          gboolean,
16851                                          gpointer);
16852 void GtkListItem::scroll-vertical       (GtkListItem *,
16853                                          GtkEnum,
16854                                          ggfloat,
16855                                          gpointer);
16856 void GtkListItem::scroll-horizontal     (GtkListItem *,
16857                                          GtkEnum,
16858                                          ggfloat,
16859                                          gpointer);
16860 </programlisting>
16861
16862 </sect1>
16863
16864 <!-- ----------------------------------------------------------------- -->
16865 <sect1 id="sec-GtkTreeItem">
16866 <title>GtkTreeItem</title>
16867
16868 <programlisting role="C">
16869 void GtkTreeItem::collapse      (GtkTreeItem *,
16870                                  gpointer);
16871 void GtkTreeItem::expand        (GtkTreeItem *,
16872                                  gpointer);
16873 </programlisting>
16874
16875 </sect1>
16876
16877 <!-- ----------------------------------------------------------------- -->
16878 <sect1 id="sec-GtkCheckMenuItem">
16879 <title>GtkCheckMenuItem</title>
16880
16881 <programlisting role="C">
16882 void GtkCheckMenuItem::toggled  (GtkCheckMenuItem *,
16883                                  gpointer);
16884 </programlisting>
16885
16886 </sect1>
16887
16888 <!-- ----------------------------------------------------------------- -->
16889 <sect1 id="sec-GtkInputDialog">
16890 <title>GtkInputDialog</title>
16891
16892 <programlisting role="C">
16893 void GtkInputDialog::enable-device      (GtkInputDialog *,
16894                                          ggint,
16895                                          gpointer);
16896 void GtkInputDialog::disable-device     (GtkInputDialog *,
16897                                          ggint,
16898                                          gpointer);
16899 </programlisting>
16900
16901 </sect1>
16902
16903 <!-- ----------------------------------------------------------------- -->
16904 <sect1 id="sec-GtkColorSelection">
16905 <title>GtkColorSelection</title>
16906
16907 <programlisting role="C">
16908 void GtkColorSelection::color-changed   (GtkColorSelection *,
16909                                          gpointer);
16910 </programlisting>
16911
16912 </sect1>
16913
16914 <!-- ----------------------------------------------------------------- -->
16915 <sect1 id="sec-GtkStatusBar">
16916 <title>GtkStatusBar</title>
16917
16918 <programlisting role="C">
16919 void GtkStatusbar::text-pushed  (GtkStatusbar *,
16920                                  gguint,
16921                                  GtkString *,
16922                                  gpointer);
16923 void GtkStatusbar::text-popped  (GtkStatusbar *,
16924                                  gguint,
16925                                  GtkString *,
16926                                  gpointer);
16927 </programlisting>
16928
16929 </sect1>
16930
16931 <!-- ----------------------------------------------------------------- -->
16932 <sect1 id="sec-GtkCTree">
16933 <title>GtkCTree</title>
16934
16935 <programlisting role="C">
16936 void GtkCTree::tree-select-row  (GtkCTree *,
16937                                  GtkCTreeNode *,
16938                                  ggint,
16939                                  gpointer);
16940 void GtkCTree::tree-unselect-row        (GtkCTree *,
16941                                          GtkCTreeNode *,
16942                                          ggint,
16943                                          gpointer);
16944 void GtkCTree::tree-expand      (GtkCTree *,
16945                                  GtkCTreeNode *,
16946                                  gpointer);
16947 void GtkCTree::tree-collapse    (GtkCTree *,
16948                                  ggpointer,
16949                                  gpointer);
16950 void GtkCTree::tree-move        (GtkCTree *,
16951                                  GtkCTreeNode *,
16952                                  GtkCTreeNode *,
16953                                  GtkCTreeNode *,
16954                                  gpointer);
16955 void GtkCTree::change-focus-row-expansion       (GtkCTree *,
16956                                                  GtkCTreeExpansionType,
16957                                                  gpointer);
16958 </programlisting>
16959
16960 </sect1>
16961
16962 <!-- ----------------------------------------------------------------- -->
16963 <sect1 id="sec-GtkCurve">
16964 <title>GtkCurve</title>
16965
16966 <programlisting role="C">
16967 void GtkCurve::curve-type-changed       (GtkCurve *,
16968                                          gpointer);
16969 </programlisting>
16970
16971 </sect1>
16972
16973 <!-- ----------------------------------------------------------------- -->
16974 <sect1 id="sec-GtkAdjustment">
16975 <title>GtkAdjustment</title>
16976
16977 <programlisting role="C">
16978 void GtkAdjustment::changed     (GtkAdjustment *,
16979                                  gpointer);
16980 void GtkAdjustment::value-changed       (GtkAdjustment *,
16981                                          gpointer);
16982 </programlisting>
16983
16984 </sect1>
16985 </appendix>
16986
16987 <!-- ***************************************************************** -->
16988 <appendix id="app-GDKEventTypes">
16989 <title>GDK Event Types</title>
16990
16991 <para>The following data types are passed into event handlers by GTK+. For
16992 each data type listed, the signals that use this data type are listed.</para>
16993
16994 <itemizedlist>
16995 <listitem><simpara>  GdkEvent</simpara>
16996           <itemizedlist>
16997           <listitem><simpara>drag_end_event</simpara>
16998           </listitem>
16999           </itemizedlist>
17000 </listitem>
17001
17002 <listitem><simpara>  GdkEventType<</simpara>
17003 </listitem>
17004
17005 <listitem><simpara>  GdkEventAny</simpara>
17006           <itemizedlist>
17007           <listitem><simpara>delete_event</simpara>
17008           </listitem>
17009           <listitem><simpara>destroy_event</simpara>
17010           </listitem>
17011           <listitem><simpara>map_event</simpara>
17012           </listitem>
17013           <listitem><simpara>unmap_event</simpara>
17014           </listitem>
17015           <listitem><simpara>no_expose_event</simpara>
17016           </listitem>
17017           </itemizedlist>
17018 </listitem>
17019
17020 <listitem><simpara>  GdkEventExpose</simpara>
17021           <itemizedlist>
17022           <listitem><simpara>expose_event</simpara>
17023           </listitem>
17024           </itemizedlist>
17025 </listitem>
17026
17027 <listitem><simpara>  GdkEventNoExpose</simpara>
17028 </listitem>
17029
17030 <listitem><simpara>  GdkEventVisibility</simpara>
17031 </listitem>
17032
17033 <listitem><simpara>  GdkEventMotion</simpara>
17034           <itemizedlist>
17035           <listitem><simpara>motion_notify_event</simpara>
17036           </listitem>
17037           </itemizedlist>
17038 </listitem>
17039 <listitem><simpara>  GdkEventButton</simpara>
17040           <itemizedlist>
17041           <listitem><simpara>button_press_event</simpara>
17042           </listitem>
17043           <listitem><simpara>button_release_event</simpara>
17044           </listitem>
17045           </itemizedlist>
17046 </listitem>
17047
17048 <listitem><simpara>  GdkEventKey</simpara>
17049           <itemizedlist>
17050           <listitem><simpara>key_press_event</simpara>
17051           </listitem>
17052           <listitem><simpara>key_release_event</simpara>
17053           </listitem>
17054           </itemizedlist>
17055 </listitem>
17056
17057 <listitem><simpara>  GdkEventCrossing</simpara>
17058           <itemizedlist>
17059           <listitem><simpara>enter_notify_event</simpara>
17060           </listitem>
17061           <listitem><simpara>leave_notify_event</simpara>
17062           </listitem>
17063           </itemizedlist>
17064 </listitem>
17065
17066 <listitem><simpara>  GdkEventFocus</simpara>
17067           <itemizedlist>
17068           <listitem><simpara>focus_in_event</simpara>
17069           </listitem>
17070           <listitem><simpara>focus_out_event</simpara>
17071           </listitem>
17072           </itemizedlist>
17073 </listitem>
17074
17075 <listitem><simpara>  GdkEventConfigure</simpara>
17076           <itemizedlist>
17077           <listitem><simpara>configure_event</simpara>
17078           </listitem>
17079           </itemizedlist>
17080 </listitem>
17081
17082 <listitem><simpara>  GdkEventProperty</simpara>
17083           <itemizedlist>
17084           <listitem><simpara>property_notify_event</simpara>
17085           </listitem>
17086           </itemizedlist>
17087 </listitem>
17088
17089 <listitem><simpara>  GdkEventSelection</simpara>
17090           <itemizedlist>
17091           <listitem><simpara>selection_clear_event</simpara>
17092           </listitem>
17093           <listitem><simpara>selection_request_event</simpara>
17094           </listitem>
17095           <listitem><simpara>selection_notify_event</simpara>
17096           </listitem>
17097           </itemizedlist>
17098 </listitem>
17099
17100 <listitem><simpara>  GdkEventProximity</simpara>
17101           <itemizedlist>
17102           <listitem><simpara>proximity_in_event</simpara>
17103           </listitem>
17104           <listitem><simpara>proximity_out_event</simpara>
17105           </listitem>
17106           </itemizedlist>
17107 </listitem>
17108
17109 <listitem><simpara>  GdkEventDragBegin</simpara>
17110           <itemizedlist>
17111           <listitem><simpara>drag_begin_event</simpara>
17112           </listitem>
17113           </itemizedlist>
17114 </listitem>
17115
17116 <listitem><simpara>  GdkEventDragRequest</simpara>
17117           <itemizedlist>
17118           <listitem><simpara>drag_request_event</simpara>
17119           </listitem>
17120           </itemizedlist>
17121 </listitem>
17122
17123 <listitem><simpara>  GdkEventDropEnter</simpara>
17124           <itemizedlist>
17125           <listitem><simpara>drop_enter_event</simpara>
17126           </listitem>
17127           </itemizedlist>
17128 </listitem>
17129
17130 <listitem><simpara>  GdkEventDropLeave</simpara>
17131           <itemizedlist>
17132           <listitem><simpara>drop_leave_event</simpara>
17133           </listitem>
17134           </itemizedlist>
17135 </listitem>
17136
17137 <listitem><simpara>  GdkEventDropDataAvailable</simpara>
17138           <itemizedlist>
17139           <listitem><simpara>drop_data_available_event</simpara>
17140           </listitem>
17141           </itemizedlist>
17142 </listitem>
17143
17144 <listitem><simpara>  GdkEventClient</simpara>
17145           <itemizedlist>
17146           <listitem><simpara>client_event</simpara>
17147           </listitem>
17148           </itemizedlist>
17149 </listitem>
17150
17151 <listitem><simpara>  GdkEventOther</simpara>
17152           <itemizedlist>
17153           <listitem><simpara>other_event</simpara>
17154           </listitem>
17155           </itemizedlist>
17156 </listitem>
17157 </itemizedlist>
17158
17159 <para>The data type <literal>GdkEventType</literal> is a special data type that is used by
17160 all the other data types as an indicator of the data type being passed
17161 to the signal handler. As you will see below, each of the event data
17162 structures has a member of this type. It is defined as an enumeration
17163 type as follows:</para>
17164
17165 <programlisting role="C">
17166 typedef enum
17167 {
17168   GDK_NOTHING           = -1,
17169   GDK_DELETE            = 0,
17170   GDK_DESTROY           = 1,
17171   GDK_EXPOSE            = 2,
17172   GDK_MOTION_NOTIFY     = 3,
17173   GDK_BUTTON_PRESS      = 4,
17174   GDK_2BUTTON_PRESS     = 5,
17175   GDK_3BUTTON_PRESS     = 6,
17176   GDK_BUTTON_RELEASE    = 7,
17177   GDK_KEY_PRESS         = 8,
17178   GDK_KEY_RELEASE       = 9,
17179   GDK_ENTER_NOTIFY      = 10,
17180   GDK_LEAVE_NOTIFY      = 11,
17181   GDK_FOCUS_CHANGE      = 12,
17182   GDK_CONFIGURE         = 13,
17183   GDK_MAP               = 14,
17184   GDK_UNMAP             = 15,
17185   GDK_PROPERTY_NOTIFY   = 16,
17186   GDK_SELECTION_CLEAR   = 17,
17187   GDK_SELECTION_REQUEST = 18,
17188   GDK_SELECTION_NOTIFY  = 19,
17189   GDK_PROXIMITY_IN      = 20,
17190   GDK_PROXIMITY_OUT     = 21,
17191   GDK_DRAG_BEGIN        = 22,
17192   GDK_DRAG_REQUEST      = 23,
17193   GDK_DROP_ENTER        = 24,
17194   GDK_DROP_LEAVE        = 25,
17195   GDK_DROP_DATA_AVAIL   = 26,
17196   GDK_CLIENT_EVENT      = 27,
17197   GDK_VISIBILITY_NOTIFY = 28,
17198   GDK_NO_EXPOSE         = 29,
17199   GDK_OTHER_EVENT       = 9999  /* Deprecated, use filters instead */
17200 } GdkEventType;
17201 </programlisting>
17202
17203 <para>The other event type that is different from the others is
17204 <literal>GdkEvent</literal> itself. This is a union of all the other
17205 data types, which allows it to be cast to a specific
17206 event data type within a signal handler.</para>
17207
17208 <!-- Just a big list for now, needs expanding upon - TRG -->
17209 <para>So, the event data types are defined as follows:</para>
17210
17211 <programlisting role="C">
17212 struct _GdkEventAny
17213 {
17214   GdkEventType type;
17215   GdkWindow *window;
17216   gint8 send_event;
17217 };
17218
17219 struct _GdkEventExpose
17220 {
17221   GdkEventType type;
17222   GdkWindow *window;
17223   gint8 send_event;
17224   GdkRectangle area;
17225   gint count; /* If non-zero, how many more events follow. */
17226 };
17227
17228 struct _GdkEventNoExpose
17229 {
17230   GdkEventType type;
17231   GdkWindow *window;
17232   gint8 send_event;
17233   /* XXX: does anyone need the X major_code or minor_code fields? */
17234 };
17235
17236 struct _GdkEventVisibility
17237 {
17238   GdkEventType type;
17239   GdkWindow *window;
17240   gint8 send_event;
17241   GdkVisibilityState state;
17242 };
17243
17244 struct _GdkEventMotion
17245 {
17246   GdkEventType type;
17247   GdkWindow *window;
17248   gint8 send_event;
17249   guint32 time;
17250   gdouble x;
17251   gdouble y;
17252   gdouble pressure;
17253   gdouble xtilt;
17254   gdouble ytilt;
17255   guint state;
17256   gint16 is_hint;
17257   GdkInputSource source;
17258   guint32 deviceid;
17259   gdouble x_root, y_root;
17260 };
17261
17262 struct _GdkEventButton
17263 {
17264   GdkEventType type;
17265   GdkWindow *window;
17266   gint8 send_event;
17267   guint32 time;
17268   gdouble x;
17269   gdouble y;
17270   gdouble pressure;
17271   gdouble xtilt;
17272   gdouble ytilt;
17273   guint state;
17274   guint button;
17275   GdkInputSource source;
17276   guint32 deviceid;
17277   gdouble x_root, y_root;
17278 };
17279
17280 struct _GdkEventKey
17281 {
17282   GdkEventType type;
17283   GdkWindow *window;
17284   gint8 send_event;
17285   guint32 time;
17286   guint state;
17287   guint keyval;
17288   gint length;
17289   gchar *string;
17290 };
17291
17292 struct _GdkEventCrossing
17293 {
17294   GdkEventType type;
17295   GdkWindow *window;
17296   gint8 send_event;
17297   GdkWindow *subwindow;
17298   GdkNotifyType detail;
17299 };
17300
17301 struct _GdkEventFocus
17302 {
17303   GdkEventType type;
17304   GdkWindow *window;
17305   gint8 send_event;
17306   gint16 in;
17307 };
17308
17309 struct _GdkEventConfigure
17310 {
17311   GdkEventType type;
17312   GdkWindow *window;
17313   gint8 send_event;
17314   gint16 x, y;
17315   gint16 width;
17316   gint16 height;
17317 };
17318
17319 struct _GdkEventProperty
17320 {
17321   GdkEventType type;
17322   GdkWindow *window;
17323   gint8 send_event;
17324   GdkAtom atom;
17325   guint32 time;
17326   guint state;
17327 };
17328
17329 struct _GdkEventSelection
17330 {
17331   GdkEventType type;
17332   GdkWindow *window;
17333   gint8 send_event;
17334   GdkAtom selection;
17335   GdkAtom target;
17336   GdkAtom property;
17337   guint32 requestor;
17338   guint32 time;
17339 };
17340
17341 /* This event type will be used pretty rarely. It only is important
17342    for XInput aware programs that are drawing their own cursor */
17343
17344 struct _GdkEventProximity
17345 {
17346   GdkEventType type;
17347   GdkWindow *window;
17348   gint8 send_event;
17349   guint32 time;
17350   GdkInputSource source;
17351   guint32 deviceid;
17352 };
17353
17354 struct _GdkEventDragRequest
17355 {
17356   GdkEventType type;
17357   GdkWindow *window;
17358   gint8 send_event;
17359   guint32 requestor;
17360   union {
17361     struct {
17362       guint protocol_version:4;
17363       guint sendreply:1;
17364       guint willaccept:1;
17365       guint delete_data:1; /* Do *not* delete if link is sent, only
17366                               if data is sent */
17367       guint senddata:1;
17368       guint reserved:22;
17369     } flags;
17370     glong allflags;
17371   } u;
17372   guint8 isdrop; /* This gdk event can be generated by a couple of
17373                     X events - this lets the app know whether the
17374                     drop really occurred or we just set the data */
17375
17376   GdkPoint drop_coords;
17377   gchar *data_type;
17378   guint32 timestamp;
17379 };
17380
17381 struct _GdkEventDragBegin
17382 {
17383   GdkEventType type;
17384   GdkWindow *window;
17385   gint8 send_event;
17386   union {
17387     struct {
17388       guint protocol_version:4;
17389       guint reserved:28;
17390     } flags;
17391     glong allflags;
17392   } u;
17393 };
17394
17395 struct _GdkEventDropEnter
17396 {
17397   GdkEventType type;
17398   GdkWindow *window;
17399   gint8 send_event;
17400   guint32 requestor;
17401   union {
17402     struct {
17403       guint protocol_version:4;
17404       guint sendreply:1;
17405       guint extended_typelist:1;
17406       guint reserved:26;
17407     } flags;
17408     glong allflags;
17409   } u;
17410 };
17411
17412 struct _GdkEventDropLeave
17413 {
17414   GdkEventType type;
17415   GdkWindow *window;
17416   gint8 send_event;
17417   guint32 requestor;
17418   union {
17419     struct {
17420       guint protocol_version:4;
17421       guint reserved:28;
17422     } flags;
17423     glong allflags;
17424   } u;
17425 };
17426
17427 struct _GdkEventDropDataAvailable
17428 {
17429   GdkEventType type;
17430   GdkWindow *window;
17431   gint8 send_event;
17432   guint32 requestor;
17433   union {
17434     struct {
17435       guint protocol_version:4;
17436       guint isdrop:1;
17437       guint reserved:25;
17438     } flags;
17439     glong allflags;
17440   } u;
17441   gchar *data_type; /* MIME type */
17442   gulong data_numbytes;
17443   gpointer data;
17444   guint32 timestamp;
17445   GdkPoint coords;
17446 };
17447
17448 struct _GdkEventClient
17449 {
17450   GdkEventType type;
17451   GdkWindow *window;
17452   gint8 send_event;
17453   GdkAtom message_type;
17454   gushort data_format;
17455   union {
17456     char b[20];
17457     short s[10];
17458     long l[5];
17459   } data;
17460 };
17461
17462 struct _GdkEventOther
17463 {
17464   GdkEventType type;
17465   GdkWindow *window;
17466   gint8 send_event;
17467   GdkXEvent *xevent;
17468 };
17469 </programlisting>
17470
17471 </appendix>
17472
17473 <!-- ***************************************************************** -->
17474 <appendix id="app-CodeExamples">
17475 <title>Code Examples</title>
17476
17477 <para>Below are the code examples that are used in the above text
17478 which are not included in complete form elsewhere.</para>
17479
17480 <!-- ----------------------------------------------------------------- -->
17481 <sect1 id="sec-Tictactoe">
17482 <title>Tictactoe</title>
17483 <!-- ----------------------------------------------------------------- -->
17484 <sect2>
17485 <title>tictactoe.h</title>
17486
17487 <programlisting role="C">
17488 <!-- example-start tictactoe tictactoe.h -->
17489
17490 /* GTK - The GIMP Toolkit
17491  * Copyright (C) 1995-1997 Peter Mattis, Spencer Kimball and Josh MacDonald
17492  *
17493  * This library is free software; you can redistribute it and/or
17494  * modify it under the terms of the GNU Library General Public
17495  * License as published by the Free Software Foundation; either
17496  * version 2 of the License, or (at your option) any later version.
17497  *
17498  * This library is distributed in the hope that it will be useful,
17499  * but WITHOUT ANY WARRANTY; without even the implied warranty of
17500  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
17501  * Library General Public License for more details.
17502  *
17503  * You should have received a copy of the GNU Library General Public
17504  * License along with this library; if not, write to the
17505  * Free Software Foundation, Inc., 59 Temple Place - Suite 330,
17506  * Boston, MA 02111-1307, USA.
17507  */
17508 #ifndef __TICTACTOE_H__
17509 #define __TICTACTOE_H__
17510
17511
17512 #include &lt;gdk/gdk.h&gt;
17513 #include &lt;gtk/gtkvbox.h&gt;
17514
17515
17516 #ifdef __cplusplus
17517 extern "C" {
17518 #endif /* __cplusplus */
17519
17520 #define TICTACTOE(obj)          GTK_CHECK_CAST (obj, tictactoe_get_type (), Tictactoe)
17521 #define TICTACTOE_CLASS(klass)  GTK_CHECK_CLASS_CAST (klass, tictactoe_get_type (), TictactoeClass)
17522 #define IS_TICTACTOE(obj)       GTK_CHECK_TYPE (obj, tictactoe_get_type ())
17523
17524
17525 typedef struct _Tictactoe       Tictactoe;
17526 typedef struct _TictactoeClass  TictactoeClass;
17527
17528 struct _Tictactoe
17529 {
17530   GtkVBox vbox;
17531   
17532   GtkWidget *buttons[3][3];
17533 };
17534
17535 struct _TictactoeClass
17536 {
17537   GtkVBoxClass parent_class;
17538
17539   void (* tictactoe) (Tictactoe *ttt);
17540 };
17541
17542 GtkType        tictactoe_get_type        (void);
17543 GtkWidget*     tictactoe_new             (void);
17544 void           tictactoe_clear           (Tictactoe *ttt);
17545
17546 #ifdef __cplusplus
17547 }
17548 #endif /* __cplusplus */
17549
17550 #endif /* __TICTACTOE_H__ */
17551
17552 <!-- example-end -->
17553 </programlisting>
17554
17555 </sect2>
17556
17557 <!-- ----------------------------------------------------------------- -->
17558 <sect2>
17559 <title>tictactoe.c</title>
17560
17561 <programlisting role="C">
17562 <!-- example-start tictactoe tictactoe.c -->
17563
17564 /* GTK - The GIMP Toolkit
17565  * Copyright (C) 1995-1997 Peter Mattis, Spencer Kimball and Josh MacDonald
17566  *
17567  * This library is free software; you can redistribute it and/or
17568  * modify it under the terms of the GNU Library General Public
17569  * License as published by the Free Software Foundation; either
17570  * version 2 of the License, or (at your option) any later version.
17571  *
17572  * This library is distributed in the hope that it will be useful,
17573  * but WITHOUT ANY WARRANTY; without even the implied warranty of
17574  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
17575  * Library General Public License for more details.
17576  *
17577  * You should have received a copy of the GNU Library General Public
17578  * License along with this library; if not, write to the
17579  * Free Software Foundation, Inc., 59 Temple Place - Suite 330,
17580  * Boston, MA 02111-1307, USA.
17581  */
17582 #include "gtk/gtksignal.h"
17583 #include "gtk/gtktable.h"
17584 #include "gtk/gtktogglebutton.h"
17585 #include "tictactoe.h"
17586
17587 enum {
17588   TICTACTOE_SIGNAL,
17589   LAST_SIGNAL
17590 };
17591
17592 static void tictactoe_class_init          (TictactoeClass *klass);
17593 static void tictactoe_init                (Tictactoe      *ttt);
17594 static void tictactoe_toggle              (GtkWidget *widget, Tictactoe *ttt);
17595
17596 static gint tictactoe_signals[LAST_SIGNAL] = { 0 };
17597
17598 GtkType
17599 tictactoe_get_type ()
17600 {
17601   static GtkType ttt_type = 0;
17602
17603   if (!ttt_type)
17604     {
17605       GtkTypeInfo ttt_info =
17606       {
17607         "Tictactoe",
17608         sizeof (Tictactoe),
17609         sizeof (TictactoeClass),
17610         (GtkClassInitFunc) tictactoe_class_init,
17611         (GtkObjectInitFunc) tictactoe_init,
17612         /* reserved_1 */ NULL,
17613         /* reserved_1 */ NULL,
17614         (GtkClassInitFunc) NULL
17615       };
17616
17617       ttt_type = gtk_type_unique (gtk_vbox_get_type (), &amp;ttt_info);
17618     }
17619
17620   return ttt_type;
17621 }
17622
17623 static void
17624 tictactoe_class_init (TictactoeClass *class)
17625 {
17626   GtkObjectClass *object_class;
17627
17628   object_class = (GtkObjectClass*) class;
17629   
17630   tictactoe_signals[TICTACTOE_SIGNAL] = gtk_signal_new ("tictactoe",
17631                                          GTK_RUN_FIRST,
17632                                          GTK_CLASS_TYPE (object_class),
17633                                          GTK_SIGNAL_OFFSET (TictactoeClass,
17634                                                             tictactoe),
17635                                          gtk_signal_default_marshaller,
17636                                          GTK_TYPE_NONE, 0);
17637
17638
17639   class->tictactoe = NULL;
17640 }
17641
17642 static void
17643 tictactoe_init (Tictactoe *ttt)
17644 {
17645   GtkWidget *table;
17646   gint i,j;
17647   
17648   table = gtk_table_new (3, 3, TRUE);
17649   gtk_container_add (GTK_CONTAINER(ttt), table);
17650   gtk_widget_show (table);
17651
17652   for (i=0;i<3; i++)
17653     for (j=0;j<3; j++)
17654       {
17655         ttt->buttons[i][j] = gtk_toggle_button_new ();
17656         gtk_table_attach_defaults (GTK_TABLE(table), ttt->buttons[i][j], 
17657                                    i, i+1, j, j+1);
17658         gtk_signal_connect (GTK_OBJECT (ttt->buttons[i][j]), "toggled",
17659                             GTK_SIGNAL_FUNC (tictactoe_toggle), ttt);
17660         gtk_widget_set_usize (ttt->buttons[i][j], 20, 20);
17661         gtk_widget_show (ttt->buttons[i][j]);
17662       }
17663 }
17664
17665 GtkWidget*
17666 tictactoe_new ()
17667 {
17668   return GTK_WIDGET ( gtk_type_new (tictactoe_get_type ()));
17669 }
17670
17671 void           
17672 tictactoe_clear (Tictactoe *ttt)
17673 {
17674   int i,j;
17675
17676   for (i=0;i<3;i++)
17677     for (j=0;j<3;j++)
17678       {
17679         gtk_signal_handler_block_by_data (GTK_OBJECT(ttt->buttons[i][j]), ttt);
17680         gtk_toggle_button_set_active (GTK_TOGGLE_BUTTON (ttt->buttons[i][j]),
17681                                      FALSE);
17682         gtk_signal_handler_unblock_by_data (GTK_OBJECT(ttt->buttons[i][j]), ttt);
17683       }
17684 }
17685
17686 static void
17687 tictactoe_toggle (GtkWidget *widget, Tictactoe *ttt)
17688 {
17689   int i,k;
17690
17691   static int rwins[8][3] = { { 0, 0, 0 }, { 1, 1, 1 }, { 2, 2, 2 },
17692                              { 0, 1, 2 }, { 0, 1, 2 }, { 0, 1, 2 },
17693                              { 0, 1, 2 }, { 0, 1, 2 } };
17694   static int cwins[8][3] = { { 0, 1, 2 }, { 0, 1, 2 }, { 0, 1, 2 },
17695                              { 0, 0, 0 }, { 1, 1, 1 }, { 2, 2, 2 },
17696                              { 0, 1, 2 }, { 2, 1, 0 } };
17697
17698   int success, found;
17699
17700   for (k=0; k<8; k++)
17701     {
17702       success = TRUE;
17703       found = FALSE;
17704
17705       for (i=0;i<3;i++)
17706         {
17707           success = success &amp;&amp; 
17708             GTK_TOGGLE_BUTTON(ttt->buttons[rwins[k][i]][cwins[k][i]])->active;
17709           found = found ||
17710             ttt->buttons[rwins[k][i]][cwins[k][i]] == widget;
17711         }
17712       
17713       if (success &amp;&amp; found)
17714         {
17715           gtk_signal_emit (GTK_OBJECT (ttt), 
17716                            tictactoe_signals[TICTACTOE_SIGNAL]);
17717           break;
17718         }
17719     }
17720 }
17721
17722 <!-- example-end -->
17723 </programlisting>
17724
17725 </sect2>
17726
17727 <!-- ----------------------------------------------------------------- -->
17728 <sect2>
17729 <title>ttt_test.c</title>
17730
17731 <programlisting role="C">
17732 <!-- example-start tictactoe ttt_test.c -->
17733
17734 #include &lt;gtk/gtk.h&gt;
17735 #include "tictactoe.h"
17736
17737 void win( GtkWidget *widget,
17738           gpointer   data )
17739 {
17740   g_print ("Yay!\n");
17741   tictactoe_clear (TICTACTOE (widget));
17742 }
17743
17744 int main( int   argc,
17745           char *argv[] )
17746 {
17747   GtkWidget *window;
17748   GtkWidget *ttt;
17749   
17750   gtk_init (&amp;argc, &amp;argv);
17751
17752   window = gtk_window_new (GTK_WINDOW_TOPLEVEL);
17753   
17754   gtk_window_set_title (GTK_WINDOW (window), "Aspect Frame");
17755   
17756   gtk_signal_connect (GTK_OBJECT (window), "destroy",
17757                       GTK_SIGNAL_FUNC (gtk_exit), NULL);
17758   
17759   gtk_container_set_border_width (GTK_CONTAINER (window), 10);
17760
17761   ttt = tictactoe_new ();
17762   
17763   gtk_container_add (GTK_CONTAINER (window), ttt);
17764   gtk_widget_show (ttt);
17765
17766   gtk_signal_connect (GTK_OBJECT (ttt), "tictactoe",
17767                       GTK_SIGNAL_FUNC (win), NULL);
17768
17769   gtk_widget_show (window);
17770   
17771   gtk_main ();
17772   
17773   return 0;
17774 }
17775
17776 <!-- example-end -->
17777 </programlisting>
17778
17779 </sect2>
17780 </sect1>
17781
17782 <!-- ----------------------------------------------------------------- -->
17783 <sect1 id="sec-GtkDial">
17784 <title>GtkDial</title>
17785
17786 <!-- ----------------------------------------------------------------- -->
17787 <sect2>
17788 <title>gtkdial.h</title>
17789
17790 <programlisting role="C">
17791 <!-- example-start gtkdial gtkdial.h -->
17792
17793 /* GTK - The GIMP Toolkit
17794  * Copyright (C) 1995-1997 Peter Mattis, Spencer Kimball and Josh MacDonald
17795  *
17796  * This library is free software; you can redistribute it and/or
17797  * modify it under the terms of the GNU Library General Public
17798  * License as published by the Free Software Foundation; either
17799  * version 2 of the License, or (at your option) any later version.
17800  *
17801  * This library is distributed in the hope that it will be useful,
17802  * but WITHOUT ANY WARRANTY; without even the implied warranty of
17803  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
17804  * Library General Public License for more details.
17805  *
17806  * You should have received a copy of the GNU Library General Public
17807  * License along with this library; if not, write to the
17808  * Free Software Foundation, Inc., 59 Temple Place - Suite 330,
17809  * Boston, MA 02111-1307, USA.
17810  */
17811 #ifndef __GTK_DIAL_H__
17812 #define __GTK_DIAL_H__
17813
17814
17815 #include &lt;gdk/gdk.h&gt;
17816 #include &lt;gtk/gtkadjustment.h&gt;
17817 #include &lt;gtk/gtkwidget.h&gt;
17818
17819
17820 #ifdef __cplusplus
17821 extern "C" {
17822 #endif /* __cplusplus */
17823
17824
17825 #define GTK_DIAL(obj)          GTK_CHECK_CAST (obj, gtk_dial_get_type (), GtkDial)
17826 #define GTK_DIAL_CLASS(klass)  GTK_CHECK_CLASS_CAST (klass, gtk_dial_get_type (), GtkDialClass)
17827 #define GTK_IS_DIAL(obj)       GTK_CHECK_TYPE (obj, gtk_dial_get_type ())
17828
17829
17830 typedef struct _GtkDial        GtkDial;
17831 typedef struct _GtkDialClass   GtkDialClass;
17832
17833 struct _GtkDial
17834 {
17835   GtkWidget widget;
17836
17837   /* update policy (GTK_UPDATE_[CONTINUOUS/DELAYED/DISCONTINUOUS]) */
17838   guint policy : 2;
17839
17840   /* Button currently pressed or 0 if none */
17841   guint8 button;
17842
17843   /* Dimensions of dial components */
17844   gint radius;
17845   gint pointer_width;
17846
17847   /* ID of update timer, or 0 if none */
17848   guint32 timer;
17849
17850   /* Current angle */
17851   gfloat angle;
17852   gfloat last_angle;
17853
17854   /* Old values from adjustment stored so we know when something changes */
17855   gfloat old_value;
17856   gfloat old_lower;
17857   gfloat old_upper;
17858
17859   /* The adjustment object that stores the data for this dial */
17860   GtkAdjustment *adjustment;
17861 };
17862
17863 struct _GtkDialClass
17864 {
17865   GtkWidgetClass parent_class;
17866 };
17867
17868
17869 GtkWidget*     gtk_dial_new                    (GtkAdjustment *adjustment);
17870 GtkType        gtk_dial_get_type               (void);
17871 GtkAdjustment* gtk_dial_get_adjustment         (GtkDial      *dial);
17872 void           gtk_dial_set_update_policy      (GtkDial      *dial,
17873                                                 GtkUpdateType  policy);
17874
17875 void           gtk_dial_set_adjustment         (GtkDial      *dial,
17876                                                 GtkAdjustment *adjustment);
17877 #ifdef __cplusplus
17878 }
17879 #endif /* __cplusplus */
17880
17881
17882 #endif /* __GTK_DIAL_H__ */
17883 <!-- example-end -->
17884 </programlisting>
17885
17886 </sect2>
17887
17888 <!-- ----------------------------------------------------------------- -->
17889 <sect2>
17890 <title>gtkdial.c</title>
17891
17892 <programlisting role="C">
17893 <!-- example-start gtkdial gtkdial.c -->
17894
17895 /* GTK - The GIMP Toolkit
17896  * Copyright (C) 1995-1997 Peter Mattis, Spencer Kimball and Josh MacDonald
17897  *
17898  * This library is free software; you can redistribute it and/or
17899  * modify it under the terms of the GNU Library General Public
17900  * License as published by the Free Software Foundation; either
17901  * version 2 of the License, or (at your option) any later version.
17902  *
17903  * This library is distributed in the hope that it will be useful,
17904  * but WITHOUT ANY WARRANTY; without even the implied warranty of
17905  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
17906  * Library General Public License for more details.
17907  *
17908  * You should have received a copy of the GNU Library General Public
17909  * License along with this library; if not, write to the
17910  * Free Software Foundation, Inc., 59 Temple Place - Suite 330,
17911  * Boston, MA 02111-1307, USA.
17912  */
17913 #include &lt;math.h&gt;
17914 #include &lt;stdio.h&gt;
17915 #include &lt;gtk/gtkmain.h&gt;
17916 #include &lt;gtk/gtksignal.h&gt;
17917
17918 #include "gtkdial.h"
17919
17920 #define SCROLL_DELAY_LENGTH  300
17921 #define DIAL_DEFAULT_SIZE 100
17922
17923 /* Forward declarations */
17924
17925 static void gtk_dial_class_init               (GtkDialClass    *klass);
17926 static void gtk_dial_init                     (GtkDial         *dial);
17927 static void gtk_dial_destroy                  (GtkObject        *object);
17928 static void gtk_dial_realize                  (GtkWidget        *widget);
17929 static void gtk_dial_size_request             (GtkWidget      *widget,
17930                                                GtkRequisition *requisition);
17931 static void gtk_dial_size_allocate            (GtkWidget     *widget,
17932                                                GtkAllocation *allocation);
17933 static gint gtk_dial_expose                   (GtkWidget        *widget,
17934                                                 GdkEventExpose   *event);
17935 static gint gtk_dial_button_press             (GtkWidget        *widget,
17936                                                 GdkEventButton   *event);
17937 static gint gtk_dial_button_release           (GtkWidget        *widget,
17938                                                 GdkEventButton   *event);
17939 static gint gtk_dial_motion_notify            (GtkWidget        *widget,
17940                                                 GdkEventMotion   *event);
17941 static gint gtk_dial_timer                    (GtkDial         *dial);
17942
17943 static void gtk_dial_update_mouse             (GtkDial *dial, gint x, gint y);
17944 static void gtk_dial_update                   (GtkDial *dial);
17945 static void gtk_dial_adjustment_changed       (GtkAdjustment    *adjustment,
17946                                                 gpointer          data);
17947 static void gtk_dial_adjustment_value_changed (GtkAdjustment    *adjustment,
17948                                                 gpointer          data);
17949
17950 /* Local data */
17951
17952 static GtkWidgetClass *parent_class = NULL;
17953
17954 GtkType
17955 gtk_dial_get_type ()
17956 {
17957   static GtkType dial_type = 0;
17958
17959   if (!dial_type)
17960     {
17961       GtkTypeInfo dial_info =
17962       {
17963         "GtkDial",
17964         sizeof (GtkDial),
17965         sizeof (GtkDialClass),
17966         (GtkClassInitFunc) gtk_dial_class_init,
17967         (GtkObjectInitFunc) gtk_dial_init,
17968         /* reserved_1 */ NULL,
17969         /* reserved_1 */ NULL,
17970         (GtkClassInitFunc) NULL
17971       };
17972
17973       dial_type = gtk_type_unique (GTK_TYPE_WIDGET, &amp;dial_info);
17974     }
17975
17976   return dial_type;
17977 }
17978
17979 static void
17980 gtk_dial_class_init (GtkDialClass *class)
17981 {
17982   GtkObjectClass *object_class;
17983   GtkWidgetClass *widget_class;
17984
17985   object_class = (GtkObjectClass*) class;
17986   widget_class = (GtkWidgetClass*) class;
17987
17988   parent_class = gtk_type_class (gtk_widget_get_type ());
17989
17990   object_class->destroy = gtk_dial_destroy;
17991
17992   widget_class->realize = gtk_dial_realize;
17993   widget_class->expose_event = gtk_dial_expose;
17994   widget_class->size_request = gtk_dial_size_request;
17995   widget_class->size_allocate = gtk_dial_size_allocate;
17996   widget_class->button_press_event = gtk_dial_button_press;
17997   widget_class->button_release_event = gtk_dial_button_release;
17998   widget_class->motion_notify_event = gtk_dial_motion_notify;
17999 }
18000
18001 static void
18002 gtk_dial_init (GtkDial *dial)
18003 {
18004   dial->button = 0;
18005   dial->policy = GTK_UPDATE_CONTINUOUS;
18006   dial->timer = 0;
18007   dial->radius = 0;
18008   dial->pointer_width = 0;
18009   dial->angle = 0.0;
18010   dial->old_value = 0.0;
18011   dial->old_lower = 0.0;
18012   dial->old_upper = 0.0;
18013   dial->adjustment = NULL;
18014 }
18015
18016 GtkWidget*
18017 gtk_dial_new (GtkAdjustment *adjustment)
18018 {
18019   GtkDial *dial;
18020
18021   dial = gtk_type_new (gtk_dial_get_type ());
18022
18023   if (!adjustment)
18024     adjustment = (GtkAdjustment*) gtk_adjustment_new (0.0, 0.0, 0.0, 0.0, 0.0, 0.0);
18025
18026   gtk_dial_set_adjustment (dial, adjustment);
18027
18028   return GTK_WIDGET (dial);
18029 }
18030
18031 static void
18032 gtk_dial_destroy (GtkObject *object)
18033 {
18034   GtkDial *dial;
18035
18036   g_return_if_fail (object != NULL);
18037   g_return_if_fail (GTK_IS_DIAL (object));
18038
18039   dial = GTK_DIAL (object);
18040
18041   if (dial->adjustment)
18042     gtk_object_unref (GTK_OBJECT (dial->adjustment));
18043
18044   if (GTK_OBJECT_CLASS (parent_class)->destroy)
18045     (* GTK_OBJECT_CLASS (parent_class)->destroy) (object);
18046 }
18047
18048 GtkAdjustment*
18049 gtk_dial_get_adjustment (GtkDial *dial)
18050 {
18051   g_return_val_if_fail (dial != NULL, NULL);
18052   g_return_val_if_fail (GTK_IS_DIAL (dial), NULL);
18053
18054   return dial->adjustment;
18055 }
18056
18057 void
18058 gtk_dial_set_update_policy (GtkDial      *dial,
18059                              GtkUpdateType  policy)
18060 {
18061   g_return_if_fail (dial != NULL);
18062   g_return_if_fail (GTK_IS_DIAL (dial));
18063
18064   dial->policy = policy;
18065 }
18066
18067 void
18068 gtk_dial_set_adjustment (GtkDial      *dial,
18069                           GtkAdjustment *adjustment)
18070 {
18071   g_return_if_fail (dial != NULL);
18072   g_return_if_fail (GTK_IS_DIAL (dial));
18073
18074   if (dial->adjustment)
18075     {
18076       gtk_signal_disconnect_by_data (GTK_OBJECT (dial->adjustment), (gpointer) dial);
18077       gtk_object_unref (GTK_OBJECT (dial->adjustment));
18078     }
18079
18080   dial->adjustment = adjustment;
18081   gtk_object_ref (GTK_OBJECT (dial->adjustment));
18082
18083   gtk_signal_connect (GTK_OBJECT (adjustment), "changed",
18084                       (GtkSignalFunc) gtk_dial_adjustment_changed,
18085                       (gpointer) dial);
18086   gtk_signal_connect (GTK_OBJECT (adjustment), "value_changed",
18087                       (GtkSignalFunc) gtk_dial_adjustment_value_changed,
18088                       (gpointer) dial);
18089
18090   dial->old_value = adjustment->value;
18091   dial->old_lower = adjustment->lower;
18092   dial->old_upper = adjustment->upper;
18093
18094   gtk_dial_update (dial);
18095 }
18096
18097 static void
18098 gtk_dial_realize (GtkWidget *widget)
18099 {
18100   GtkDial *dial;
18101   GdkWindowAttr attributes;
18102   gint attributes_mask;
18103
18104   g_return_if_fail (widget != NULL);
18105   g_return_if_fail (GTK_IS_DIAL (widget));
18106
18107   GTK_WIDGET_SET_FLAGS (widget, GTK_REALIZED);
18108   dial = GTK_DIAL (widget);
18109
18110   attributes.x = widget->allocation.x;
18111   attributes.y = widget->allocation.y;
18112   attributes.width = widget->allocation.width;
18113   attributes.height = widget->allocation.height;
18114   attributes.wclass = GDK_INPUT_OUTPUT;
18115   attributes.window_type = GDK_WINDOW_CHILD;
18116   attributes.event_mask = gtk_widget_get_events (widget) | 
18117     GDK_EXPOSURE_MASK | GDK_BUTTON_PRESS_MASK | 
18118     GDK_BUTTON_RELEASE_MASK | GDK_POINTER_MOTION_MASK |
18119     GDK_POINTER_MOTION_HINT_MASK;
18120   attributes.visual = gtk_widget_get_visual (widget);
18121   attributes.colormap = gtk_widget_get_colormap (widget);
18122
18123   attributes_mask = GDK_WA_X | GDK_WA_Y | GDK_WA_VISUAL | GDK_WA_COLORMAP;
18124   widget->window = gdk_window_new (widget->parent->window, &amp;attributes, attributes_mask);
18125
18126   widget->style = gtk_style_attach (widget->style, widget->window);
18127
18128   gdk_window_set_user_data (widget->window, widget);
18129
18130   gtk_style_set_background (widget->style, widget->window, GTK_STATE_ACTIVE);
18131 }
18132
18133 static void 
18134 gtk_dial_size_request (GtkWidget      *widget,
18135                        GtkRequisition *requisition)
18136 {
18137   requisition->width = DIAL_DEFAULT_SIZE;
18138   requisition->height = DIAL_DEFAULT_SIZE;
18139 }
18140
18141 static void
18142 gtk_dial_size_allocate (GtkWidget     *widget,
18143                         GtkAllocation *allocation)
18144 {
18145   GtkDial *dial;
18146
18147   g_return_if_fail (widget != NULL);
18148   g_return_if_fail (GTK_IS_DIAL (widget));
18149   g_return_if_fail (allocation != NULL);
18150
18151   widget->allocation = *allocation;
18152   dial = GTK_DIAL (widget);
18153
18154   if (GTK_WIDGET_REALIZED (widget))
18155     {
18156
18157       gdk_window_move_resize (widget->window,
18158                               allocation->x, allocation->y,
18159                               allocation->width, allocation->height);
18160
18161     }
18162   dial->radius = MIN(allocation->width,allocation->height) * 0.45;
18163   dial->pointer_width = dial->radius / 5;
18164 }
18165
18166 static gint
18167 gtk_dial_expose (GtkWidget      *widget,
18168                  GdkEventExpose *event)
18169 {
18170   GtkDial *dial;
18171   GdkPoint points[6];
18172   gdouble s,c;
18173   gdouble theta, last, increment;
18174   GtkStyle      *blankstyle;
18175   gint xc, yc;
18176   gint upper, lower;
18177   gint tick_length;
18178   gint i, inc;
18179
18180   g_return_val_if_fail (widget != NULL, FALSE);
18181   g_return_val_if_fail (GTK_IS_DIAL (widget), FALSE);
18182   g_return_val_if_fail (event != NULL, FALSE);
18183
18184   if (event->count > 0)
18185     return FALSE;
18186   
18187   dial = GTK_DIAL (widget);
18188
18189 /*  gdk_window_clear_area (widget->window,
18190                          0, 0,
18191                          widget->allocation.width,
18192                          widget->allocation.height);
18193 */
18194   xc = widget->allocation.width/2;
18195   yc = widget->allocation.height/2;
18196
18197   upper = dial->adjustment->upper;
18198   lower = dial->adjustment->lower;
18199
18200   /* Erase old pointer */
18201
18202   s = sin(dial->last_angle);
18203   c = cos(dial->last_angle);
18204   dial->last_angle = dial->angle;
18205
18206   points[0].x = xc + s*dial->pointer_width/2;
18207   points[0].y = yc + c*dial->pointer_width/2;
18208   points[1].x = xc + c*dial->radius;
18209   points[1].y = yc - s*dial->radius;
18210   points[2].x = xc - s*dial->pointer_width/2;
18211   points[2].y = yc - c*dial->pointer_width/2;
18212   points[3].x = xc - c*dial->radius/10;
18213   points[3].y = yc + s*dial->radius/10;
18214   points[4].x = points[0].x;
18215   points[4].y = points[0].y;
18216
18217   blankstyle = gtk_style_new ();
18218   blankstyle->bg_gc[GTK_STATE_NORMAL] =
18219                 widget->style->bg_gc[GTK_STATE_NORMAL];
18220   blankstyle->dark_gc[GTK_STATE_NORMAL] =
18221                 widget->style->bg_gc[GTK_STATE_NORMAL];
18222   blankstyle->light_gc[GTK_STATE_NORMAL] =
18223                 widget->style->bg_gc[GTK_STATE_NORMAL];
18224   blankstyle->black_gc =
18225                 widget->style->bg_gc[GTK_STATE_NORMAL];
18226
18227   gtk_draw_polygon (blankstyle,
18228                     widget->window,
18229                     GTK_STATE_NORMAL,
18230                     GTK_SHADOW_OUT,
18231                     points, 5,
18232                     FALSE);
18233
18234   gtk_style_unref(blankstyle);
18235
18236
18237   /* Draw ticks */
18238
18239   if ((upper - lower) == 0)
18240     return;
18241
18242   increment = (100*M_PI)/(dial->radius*dial->radius);
18243
18244   inc = (upper - lower);
18245
18246   while (inc < 100) inc *=10;
18247   while (inc >= 1000) inc /=10;
18248   last = -1;
18249
18250   for (i=0; i<=inc; i++)
18251     {
18252       theta = ((gfloat)i*M_PI/(18*inc/24.) - M_PI/6.);
18253
18254       if ((theta - last) < (increment))
18255         continue;     
18256       last = theta;
18257
18258       s = sin(theta);
18259       c = cos(theta);
18260
18261       tick_length = (i%(inc/10) == 0) ? dial->pointer_width : dial->pointer_width/2;
18262
18263       gdk_draw_line (widget->window,
18264                      widget->style->fg_gc[widget->state],
18265                      xc + c*(dial->radius - tick_length),
18266                      yc - s*(dial->radius - tick_length),
18267                      xc + c*dial->radius,
18268                      yc - s*dial->radius);
18269     }
18270
18271   /* Draw pointer */
18272
18273   s = sin(dial->angle);
18274   c = cos(dial->angle);
18275   dial->last_angle = dial->angle;
18276
18277   points[0].x = xc + s*dial->pointer_width/2;
18278   points[0].y = yc + c*dial->pointer_width/2;
18279   points[1].x = xc + c*dial->radius;
18280   points[1].y = yc - s*dial->radius;
18281   points[2].x = xc - s*dial->pointer_width/2;
18282   points[2].y = yc - c*dial->pointer_width/2;
18283   points[3].x = xc - c*dial->radius/10;
18284   points[3].y = yc + s*dial->radius/10;
18285   points[4].x = points[0].x;
18286   points[4].y = points[0].y;
18287
18288
18289   gtk_draw_polygon (widget->style,
18290                     widget->window,
18291                     GTK_STATE_NORMAL,
18292                     GTK_SHADOW_OUT,
18293                     points, 5,
18294                     TRUE);
18295
18296   return FALSE;
18297 }
18298
18299 static gint
18300 gtk_dial_button_press (GtkWidget      *widget,
18301                        GdkEventButton *event)
18302 {
18303   GtkDial *dial;
18304   gint dx, dy;
18305   double s, c;
18306   double d_parallel;
18307   double d_perpendicular;
18308
18309   g_return_val_if_fail (widget != NULL, FALSE);
18310   g_return_val_if_fail (GTK_IS_DIAL (widget), FALSE);
18311   g_return_val_if_fail (event != NULL, FALSE);
18312
18313   dial = GTK_DIAL (widget);
18314
18315   /* Determine if button press was within pointer region - we 
18316      do this by computing the parallel and perpendicular distance of
18317      the point where the mouse was pressed from the line passing through
18318      the pointer */
18319   
18320   dx = event->x - widget->allocation.width / 2;
18321   dy = widget->allocation.height / 2 - event->y;
18322   
18323   s = sin(dial->angle);
18324   c = cos(dial->angle);
18325   
18326   d_parallel = s*dy + c*dx;
18327   d_perpendicular = fabs(s*dx - c*dy);
18328   
18329   if (!dial->button &amp;&amp;
18330       (d_perpendicular < dial->pointer_width/2) &amp;&amp;
18331       (d_parallel > - dial->pointer_width))
18332     {
18333       gtk_grab_add (widget);
18334
18335       dial->button = event->button;
18336
18337       gtk_dial_update_mouse (dial, event->x, event->y);
18338     }
18339
18340   return FALSE;
18341 }
18342
18343 static gint
18344 gtk_dial_button_release (GtkWidget      *widget,
18345                           GdkEventButton *event)
18346 {
18347   GtkDial *dial;
18348
18349   g_return_val_if_fail (widget != NULL, FALSE);
18350   g_return_val_if_fail (GTK_IS_DIAL (widget), FALSE);
18351   g_return_val_if_fail (event != NULL, FALSE);
18352
18353   dial = GTK_DIAL (widget);
18354
18355   if (dial->button == event->button)
18356     {
18357       gtk_grab_remove (widget);
18358
18359       dial->button = 0;
18360
18361       if (dial->policy == GTK_UPDATE_DELAYED)
18362         gtk_timeout_remove (dial->timer);
18363       
18364       if ((dial->policy != GTK_UPDATE_CONTINUOUS) &amp;&amp;
18365           (dial->old_value != dial->adjustment->value))
18366         gtk_signal_emit_by_name (GTK_OBJECT (dial->adjustment), "value_changed");
18367     }
18368
18369   return FALSE;
18370 }
18371
18372 static gint
18373 gtk_dial_motion_notify (GtkWidget      *widget,
18374                          GdkEventMotion *event)
18375 {
18376   GtkDial *dial;
18377   GdkModifierType mods;
18378   gint x, y, mask;
18379
18380   g_return_val_if_fail (widget != NULL, FALSE);
18381   g_return_val_if_fail (GTK_IS_DIAL (widget), FALSE);
18382   g_return_val_if_fail (event != NULL, FALSE);
18383
18384   dial = GTK_DIAL (widget);
18385
18386   if (dial->button != 0)
18387     {
18388       x = event->x;
18389       y = event->y;
18390
18391       if (event->is_hint || (event->window != widget->window))
18392         gdk_window_get_pointer (widget->window, &amp;x, &amp;y, &amp;mods);
18393
18394       switch (dial->button)
18395         {
18396         case 1:
18397           mask = GDK_BUTTON1_MASK;
18398           break;
18399         case 2:
18400           mask = GDK_BUTTON2_MASK;
18401           break;
18402         case 3:
18403           mask = GDK_BUTTON3_MASK;
18404           break;
18405         default:
18406           mask = 0;
18407           break;
18408         }
18409
18410       if (mods &amp; mask)
18411         gtk_dial_update_mouse (dial, x,y);
18412     }
18413
18414   return FALSE;
18415 }
18416
18417 static gint
18418 gtk_dial_timer (GtkDial *dial)
18419 {
18420   g_return_val_if_fail (dial != NULL, FALSE);
18421   g_return_val_if_fail (GTK_IS_DIAL (dial), FALSE);
18422
18423   if (dial->policy == GTK_UPDATE_DELAYED)
18424     gtk_signal_emit_by_name (GTK_OBJECT (dial->adjustment), "value_changed");
18425
18426   return FALSE;
18427 }
18428
18429 static void
18430 gtk_dial_update_mouse (GtkDial *dial, gint x, gint y)
18431 {
18432   gint xc, yc;
18433   gfloat old_value;
18434
18435   g_return_if_fail (dial != NULL);
18436   g_return_if_fail (GTK_IS_DIAL (dial));
18437
18438   xc = GTK_WIDGET(dial)->allocation.width / 2;
18439   yc = GTK_WIDGET(dial)->allocation.height / 2;
18440
18441   old_value = dial->adjustment->value;
18442   dial->angle = atan2(yc-y, x-xc);
18443
18444   if (dial->angle < -M_PI/2.)
18445     dial->angle += 2*M_PI;
18446
18447   if (dial->angle < -M_PI/6)
18448     dial->angle = -M_PI/6;
18449
18450   if (dial->angle > 7.*M_PI/6.)
18451     dial->angle = 7.*M_PI/6.;
18452
18453   dial->adjustment->value = dial->adjustment->lower + (7.*M_PI/6 - dial->angle) *
18454     (dial->adjustment->upper - dial->adjustment->lower) / (4.*M_PI/3.);
18455
18456   if (dial->adjustment->value != old_value)
18457     {
18458       if (dial->policy == GTK_UPDATE_CONTINUOUS)
18459         {
18460           gtk_signal_emit_by_name (GTK_OBJECT (dial->adjustment), "value_changed");
18461         }
18462       else
18463         {
18464           gtk_widget_draw (GTK_WIDGET(dial), NULL);
18465
18466           if (dial->policy == GTK_UPDATE_DELAYED)
18467             {
18468               if (dial->timer)
18469                 gtk_timeout_remove (dial->timer);
18470
18471               dial->timer = gtk_timeout_add (SCROLL_DELAY_LENGTH,
18472                                              (GtkFunction) gtk_dial_timer,
18473                                              (gpointer) dial);
18474             }
18475         }
18476     }
18477 }
18478
18479 static void
18480 gtk_dial_update (GtkDial *dial)
18481 {
18482   gfloat new_value;
18483   
18484   g_return_if_fail (dial != NULL);
18485   g_return_if_fail (GTK_IS_DIAL (dial));
18486
18487   new_value = dial->adjustment->value;
18488   
18489   if (new_value < dial->adjustment->lower)
18490     new_value = dial->adjustment->lower;
18491
18492   if (new_value > dial->adjustment->upper)
18493     new_value = dial->adjustment->upper;
18494
18495   if (new_value != dial->adjustment->value)
18496     {
18497       dial->adjustment->value = new_value;
18498       gtk_signal_emit_by_name (GTK_OBJECT (dial->adjustment), "value_changed");
18499     }
18500
18501   dial->angle = 7.*M_PI/6. - (new_value - dial->adjustment->lower) * 4.*M_PI/3. /
18502     (dial->adjustment->upper - dial->adjustment->lower);
18503
18504   gtk_widget_draw (GTK_WIDGET(dial), NULL);
18505 }
18506
18507 static void
18508 gtk_dial_adjustment_changed (GtkAdjustment *adjustment,
18509                               gpointer       data)
18510 {
18511   GtkDial *dial;
18512
18513   g_return_if_fail (adjustment != NULL);
18514   g_return_if_fail (data != NULL);
18515
18516   dial = GTK_DIAL (data);
18517
18518   if ((dial->old_value != adjustment->value) ||
18519       (dial->old_lower != adjustment->lower) ||
18520       (dial->old_upper != adjustment->upper))
18521     {
18522       gtk_dial_update (dial);
18523
18524       dial->old_value = adjustment->value;
18525       dial->old_lower = adjustment->lower;
18526       dial->old_upper = adjustment->upper;
18527     }
18528 }
18529
18530 static void
18531 gtk_dial_adjustment_value_changed (GtkAdjustment *adjustment,
18532                                     gpointer       data)
18533 {
18534   GtkDial *dial;
18535
18536   g_return_if_fail (adjustment != NULL);
18537   g_return_if_fail (data != NULL);
18538
18539   dial = GTK_DIAL (data);
18540
18541   if (dial->old_value != adjustment->value)
18542     {
18543       gtk_dial_update (dial);
18544
18545       dial->old_value = adjustment->value;
18546     }
18547 }
18548 <!-- example-end -->
18549 </programlisting>
18550
18551 </sect2>
18552
18553 <!-- ----------------------------------------------------------------- -->
18554 <sect2>
18555 <title>dial_test.c</title>
18556
18557 <programlisting role="C">
18558 #include &lt;stdio.h&gt;
18559 #include &lt;gtk/gtk.h&gt;
18560 #include "gtkdial.h"
18561
18562 void value_changed( GtkAdjustment *adjustment,
18563                     GtkWidget     *label )
18564 {
18565   char buffer[16];
18566
18567   sprintf(buffer,"%4.2f",adjustment->value);
18568   gtk_label_set (GTK_LABEL (label), buffer);
18569 }
18570
18571 int main( int   argc,
18572           char *argv[])
18573 {
18574   GtkWidget *window;
18575   GtkAdjustment *adjustment;
18576   GtkWidget *dial;
18577   GtkWidget *frame;
18578   GtkWidget *vbox;
18579   GtkWidget *label;
18580   
18581   gtk_init (&amp;argc, &amp;argv);
18582
18583   window = gtk_window_new (GTK_WINDOW_TOPLEVEL);
18584   
18585   gtk_window_set_title (GTK_WINDOW (window), "Dial");
18586   
18587   gtk_signal_connect (GTK_OBJECT (window), "destroy",
18588                       GTK_SIGNAL_FUNC (gtk_exit), NULL);
18589   
18590   gtk_container_border_width (GTK_CONTAINER (window), 10);
18591
18592   vbox = gtk_vbox_new (FALSE, 5);
18593   gtk_container_add (GTK_CONTAINER (window), vbox);
18594   gtk_widget_show(vbox);
18595
18596   frame = gtk_frame_new (NULL);
18597   gtk_frame_set_shadow_type (GTK_FRAME(frame), GTK_SHADOW_IN);
18598   gtk_container_add (GTK_CONTAINER (vbox), frame);
18599   gtk_widget_show (frame); 
18600  
18601   adjustment = GTK_ADJUSTMENT(gtk_adjustment_new (0, 0, 100, 0.01, 0.1, 0));
18602   
18603   dial = gtk_dial_new(adjustment);
18604   gtk_dial_set_update_policy (GTK_DIAL(dial), GTK_UPDATE_DELAYED);
18605   /*  gtk_widget_set_usize (dial, 100, 100); */
18606   
18607   gtk_container_add (GTK_CONTAINER (frame), dial);
18608   gtk_widget_show (dial);
18609
18610   label = gtk_label_new("0.00");
18611   gtk_box_pack_end (GTK_BOX(vbox), label, 0, 0, 0);
18612   gtk_widget_show (label);
18613
18614   gtk_signal_connect (GTK_OBJECT(adjustment), "value_changed",
18615                       GTK_SIGNAL_FUNC (value_changed), label);
18616   
18617   gtk_widget_show (window);
18618   
18619   gtk_main ();
18620   
18621   return 0;
18622 }
18623 </programlisting>
18624
18625 </sect2>
18626 </sect1>
18627
18628 <!-- ----------------------------------------------------------------- -->
18629 <sect1 id="sec-Scribble">
18630 <title>Scribble</title>
18631
18632 <!-- ----------------------------------------------------------------- -->
18633 <sect2>
18634 <title>scribble-simple.c</title>
18635
18636 <programlisting role="C">
18637 <!-- example-start scribble-simple scribble-simple.c -->
18638
18639 /* GTK - The GIMP Toolkit
18640  * Copyright (C) 1995-1997 Peter Mattis, Spencer Kimball and Josh MacDonald
18641  *
18642  * This library is free software; you can redistribute it and/or
18643  * modify it under the terms of the GNU Library General Public
18644  * License as published by the Free Software Foundation; either
18645  * version 2 of the License, or (at your option) any later version.
18646  *
18647  * This library is distributed in the hope that it will be useful,
18648  * but WITHOUT ANY WARRANTY; without even the implied warranty of
18649  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
18650  * Library General Public License for more details.
18651  *
18652  * You should have received a copy of the GNU Library General Public
18653  * License along with this library; if not, write to the
18654  * Free Software Foundation, Inc., 59 Temple Place - Suite 330,
18655  * Boston, MA 02111-1307, USA.
18656  */
18657
18658 #include &lt;gtk/gtk.h&gt;
18659
18660 /* Backing pixmap for drawing area */
18661 static GdkPixmap *pixmap = NULL;
18662
18663 /* Create a new backing pixmap of the appropriate size */
18664 static gint configure_event( GtkWidget         *widget,
18665                              GdkEventConfigure *event )
18666 {
18667   if (pixmap)
18668     gdk_pixmap_unref(pixmap);
18669
18670   pixmap = gdk_pixmap_new(widget->window,
18671                           widget->allocation.width,
18672                           widget->allocation.height,
18673                           -1);
18674   gdk_draw_rectangle (pixmap,
18675                       widget->style->white_gc,
18676                       TRUE,
18677                       0, 0,
18678                       widget->allocation.width,
18679                       widget->allocation.height);
18680
18681   return TRUE;
18682 }
18683
18684 /* Redraw the screen from the backing pixmap */
18685 static gint expose_event( GtkWidget      *widget,
18686                           GdkEventExpose *event )
18687 {
18688   gdk_draw_pixmap(widget->window,
18689                   widget->style->fg_gc[GTK_WIDGET_STATE (widget)],
18690                   pixmap,
18691                   event->area.x, event->area.y,
18692                   event->area.x, event->area.y,
18693                   event->area.width, event->area.height);
18694
18695   return FALSE;
18696 }
18697
18698 /* Draw a rectangle on the screen */
18699 static void draw_brush( GtkWidget *widget,
18700                         gdouble    x,
18701                         gdouble    y)
18702 {
18703   GdkRectangle update_rect;
18704
18705   update_rect.x = x - 5;
18706   update_rect.y = y - 5;
18707   update_rect.width = 10;
18708   update_rect.height = 10;
18709   gdk_draw_rectangle (pixmap,
18710                       widget->style->black_gc,
18711                       TRUE,
18712                       update_rect.x, update_rect.y,
18713                       update_rect.width, update_rect.height);
18714   gtk_widget_draw (widget, &amp;update_rect);
18715 }
18716
18717 static gint button_press_event( GtkWidget      *widget,
18718                                 GdkEventButton *event )
18719 {
18720   if (event->button == 1 &amp;&amp; pixmap != NULL)
18721     draw_brush (widget, event->x, event->y);
18722
18723   return TRUE;
18724 }
18725
18726 static gint motion_notify_event( GtkWidget *widget,
18727                                  GdkEventMotion *event )
18728 {
18729   int x, y;
18730   GdkModifierType state;
18731
18732   if (event->is_hint)
18733     gdk_window_get_pointer (event->window, &amp;x, &amp;y, &amp;state);
18734   else
18735     {
18736       x = event->x;
18737       y = event->y;
18738       state = event->state;
18739     }
18740     
18741   if (state &amp; GDK_BUTTON1_MASK &amp;&amp; pixmap != NULL)
18742     draw_brush (widget, x, y);
18743   
18744   return TRUE;
18745 }
18746
18747 void quit ()
18748 {
18749   gtk_exit (0);
18750 }
18751
18752 int main( int   argc, 
18753           char *argv[] )
18754 {
18755   GtkWidget *window;
18756   GtkWidget *drawing_area;
18757   GtkWidget *vbox;
18758
18759   GtkWidget *button;
18760
18761   gtk_init (&amp;argc, &amp;argv);
18762
18763   window = gtk_window_new (GTK_WINDOW_TOPLEVEL);
18764   gtk_widget_set_name (window, "Test Input");
18765
18766   vbox = gtk_vbox_new (FALSE, 0);
18767   gtk_container_add (GTK_CONTAINER (window), vbox);
18768   gtk_widget_show (vbox);
18769
18770   gtk_signal_connect (GTK_OBJECT (window), "destroy",
18771                       GTK_SIGNAL_FUNC (quit), NULL);
18772
18773   /* Create the drawing area */
18774
18775   drawing_area = gtk_drawing_area_new ();
18776   gtk_drawing_area_size (GTK_DRAWING_AREA (drawing_area), 200, 200);
18777   gtk_box_pack_start (GTK_BOX (vbox), drawing_area, TRUE, TRUE, 0);
18778
18779   gtk_widget_show (drawing_area);
18780
18781   /* Signals used to handle backing pixmap */
18782
18783   gtk_signal_connect (GTK_OBJECT (drawing_area), "expose_event",
18784                       (GtkSignalFunc) expose_event, NULL);
18785   gtk_signal_connect (GTK_OBJECT(drawing_area),"configure_event",
18786                       (GtkSignalFunc) configure_event, NULL);
18787
18788   /* Event signals */
18789
18790   gtk_signal_connect (GTK_OBJECT (drawing_area), "motion_notify_event",
18791                       (GtkSignalFunc) motion_notify_event, NULL);
18792   gtk_signal_connect (GTK_OBJECT (drawing_area), "button_press_event",
18793                       (GtkSignalFunc) button_press_event, NULL);
18794
18795   gtk_widget_set_events (drawing_area, GDK_EXPOSURE_MASK
18796                          | GDK_LEAVE_NOTIFY_MASK
18797                          | GDK_BUTTON_PRESS_MASK
18798                          | GDK_POINTER_MOTION_MASK
18799                          | GDK_POINTER_MOTION_HINT_MASK);
18800
18801   /* .. And a quit button */
18802   button = gtk_button_new_with_label ("Quit");
18803   gtk_box_pack_start (GTK_BOX (vbox), button, FALSE, FALSE, 0);
18804
18805   gtk_signal_connect_object (GTK_OBJECT (button), "clicked",
18806                              GTK_SIGNAL_FUNC (gtk_widget_destroy),
18807                              GTK_OBJECT (window));
18808   gtk_widget_show (button);
18809
18810   gtk_widget_show (window);
18811
18812   gtk_main ();
18813
18814   return 0;
18815 }
18816 <!-- example-end -->
18817 </programlisting>
18818
18819 </sect2>
18820
18821 <!-- ----------------------------------------------------------------- -->
18822 <sect2>
18823 <title>scribble-xinput.c</title>
18824
18825 <programlisting role="C">
18826 <!-- example-start scribble-xinput scribble-xinput.c -->
18827
18828 /* GTK - The GIMP Toolkit
18829  * Copyright (C) 1995-1997 Peter Mattis, Spencer Kimball and Josh MacDonald
18830  *
18831  * This library is free software; you can redistribute it and/or
18832  * modify it under the terms of the GNU Library General Public
18833  * License as published by the Free Software Foundation; either
18834  * version 2 of the License, or (at your option) any later version.
18835  *
18836  * This library is distributed in the hope that it will be useful,
18837  * but WITHOUT ANY WARRANTY; without even the implied warranty of
18838  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
18839  * Library General Public License for more details.
18840  *
18841  * You should have received a copy of the GNU Library General Public
18842  * License along with this library; if not, write to the
18843  * Free Software Foundation, Inc., 59 Temple Place - Suite 330,
18844  * Boston, MA 02111-1307, USA.
18845  */
18846
18847 #include &lt;gtk/gtk.h&gt;
18848
18849 /* Backing pixmap for drawing area */
18850 static GdkPixmap *pixmap = NULL;
18851
18852 /* Create a new backing pixmap of the appropriate size */
18853 static gint
18854 configure_event (GtkWidget *widget, GdkEventConfigure *event)
18855 {
18856   if (pixmap)
18857      gdk_pixmap_unref(pixmap);
18858
18859   pixmap = gdk_pixmap_new(widget->window,
18860                           widget->allocation.width,
18861                           widget->allocation.height,
18862                           -1);
18863   gdk_draw_rectangle (pixmap,
18864                       widget->style->white_gc,
18865                       TRUE,
18866                       0, 0,
18867                       widget->allocation.width,
18868                       widget->allocation.height);
18869
18870   return TRUE;
18871 }
18872
18873 /* Redraw the screen from the backing pixmap */
18874 static gint
18875 expose_event (GtkWidget *widget, GdkEventExpose *event)
18876 {
18877   gdk_draw_pixmap(widget->window,
18878                   widget->style->fg_gc[GTK_WIDGET_STATE (widget)],
18879                   pixmap,
18880                   event->area.x, event->area.y,
18881                   event->area.x, event->area.y,
18882                   event->area.width, event->area.height);
18883
18884   return FALSE;
18885 }
18886
18887 /* Draw a rectangle on the screen, size depending on pressure,
18888    and color on the type of device */
18889 static void
18890 draw_brush (GtkWidget *widget, GdkInputSource source,
18891             gdouble x, gdouble y, gdouble pressure)
18892 {
18893   GdkGC *gc;
18894   GdkRectangle update_rect;
18895
18896   switch (source)
18897     {
18898     case GDK_SOURCE_MOUSE:
18899       gc = widget->style->dark_gc[GTK_WIDGET_STATE (widget)];
18900       break;
18901     case GDK_SOURCE_PEN:
18902       gc = widget->style->black_gc;
18903       break;
18904     case GDK_SOURCE_ERASER:
18905       gc = widget->style->white_gc;
18906       break;
18907     default:
18908       gc = widget->style->light_gc[GTK_WIDGET_STATE (widget)];
18909     }
18910
18911   update_rect.x = x - 10 * pressure;
18912   update_rect.y = y - 10 * pressure;
18913   update_rect.width = 20 * pressure;
18914   update_rect.height = 20 * pressure;
18915   gdk_draw_rectangle (pixmap, gc, TRUE,
18916                       update_rect.x, update_rect.y,
18917                       update_rect.width, update_rect.height);
18918   gtk_widget_draw (widget, &amp;update_rect);
18919 }
18920
18921 static void
18922 print_button_press (GdkDevice *device)
18923 {
18924   g_print("Button press on device '%s'\n", device->name);
18925 }
18926
18927 static gint
18928 button_press_event (GtkWidget *widget, GdkEventButton *event)
18929 {
18930   print_button_press (event->device);
18931   
18932   if (event->button == 1 &amp;&amp; pixmap != NULL) {
18933     gdouble pressure;
18934     gdk_event_get_axis ((GdkEvent *)event, GDK_AXIS_PRESSURE, &amp;pressure);
18935     draw_brush (widget, event->device->source, event->x, event->y, pressure);
18936   }
18937
18938   return TRUE;
18939 }
18940
18941 static gint
18942 motion_notify_event (GtkWidget *widget, GdkEventMotion *event)
18943 {
18944   gdouble x, y;
18945   gdouble pressure;
18946   GdkModifierType state;
18947
18948   if (event->is_hint) 
18949     {
18950       gdk_device_get_state (event->device, event->window, NULL, &amp;state);
18951       gdk_event_get_axis ((GdkEvent *)event, GDK_AXIS_X, &amp;x);
18952       gdk_event_get_axis ((GdkEvent *)event, GDK_AXIS_Y, &amp;y);
18953       gdk_event_get_axis ((GdkEvent *)event, GDK_AXIS_PRESSURE, &amp;pressure);
18954     }
18955   else
18956     {
18957       x = event->x;
18958       y = event->y;
18959       gdk_event_get_axis ((GdkEvent *)event, GDK_AXIS_PRESSURE, &amp;pressure);
18960       state = event->state;
18961     }
18962     
18963   if (state &amp; GDK_BUTTON1_MASK &amp;&amp; pixmap != NULL)
18964     draw_brush (widget, event->device->source, x, y, pressure);
18965   
18966   return TRUE;
18967 }
18968
18969 void
18970 input_dialog_destroy (GtkWidget *w, gpointer data)
18971 {
18972   *((GtkWidget **)data) = NULL;
18973 }
18974
18975 void
18976 create_input_dialog ()
18977 {
18978   static GtkWidget *inputd = NULL;
18979
18980   if (!inputd)
18981     {
18982       inputd = gtk_input_dialog_new();
18983
18984       gtk_signal_connect (GTK_OBJECT(inputd), "destroy",
18985                           (GtkSignalFunc)input_dialog_destroy, &amp;inputd);
18986       gtk_signal_connect_object (GTK_OBJECT(GTK_INPUT_DIALOG(inputd)->close_button),
18987                                  "clicked",
18988                                  (GtkSignalFunc)gtk_widget_hide,
18989                                  GTK_OBJECT(inputd));
18990       gtk_widget_hide ( GTK_INPUT_DIALOG(inputd)->save_button);
18991
18992       gtk_widget_show (inputd);
18993     }
18994   else
18995     {
18996       if (!GTK_WIDGET_MAPPED(inputd))
18997         gtk_widget_show(inputd);
18998       else
18999         gdk_window_raise(inputd->window);
19000     }
19001 }
19002
19003 void
19004 quit ()
19005 {
19006   gtk_exit (0);
19007 }
19008
19009 int
19010 main (int argc, char *argv[])
19011 {
19012   GtkWidget *window;
19013   GtkWidget *drawing_area;
19014   GtkWidget *vbox;
19015
19016   GtkWidget *button;
19017
19018   gtk_init (&amp;argc, &amp;argv);
19019
19020   window = gtk_window_new (GTK_WINDOW_TOPLEVEL);
19021   gtk_widget_set_name (window, "Test Input");
19022
19023   vbox = gtk_vbox_new (FALSE, 0);
19024   gtk_container_add (GTK_CONTAINER (window), vbox);
19025   gtk_widget_show (vbox);
19026
19027   gtk_signal_connect (GTK_OBJECT (window), "destroy",
19028                       GTK_SIGNAL_FUNC (quit), NULL);
19029
19030   /* Create the drawing area */
19031
19032   drawing_area = gtk_drawing_area_new ();
19033   gtk_drawing_area_size (GTK_DRAWING_AREA (drawing_area), 200, 200);
19034   gtk_box_pack_start (GTK_BOX (vbox), drawing_area, TRUE, TRUE, 0);
19035
19036   gtk_widget_show (drawing_area);
19037
19038   /* Signals used to handle backing pixmap */
19039
19040   gtk_signal_connect (GTK_OBJECT (drawing_area), "expose_event",
19041                       (GtkSignalFunc) expose_event, NULL);
19042   gtk_signal_connect (GTK_OBJECT(drawing_area),"configure_event",
19043                       (GtkSignalFunc) configure_event, NULL);
19044
19045   /* Event signals */
19046
19047   gtk_signal_connect (GTK_OBJECT (drawing_area), "motion_notify_event",
19048                       (GtkSignalFunc) motion_notify_event, NULL);
19049   gtk_signal_connect (GTK_OBJECT (drawing_area), "button_press_event",
19050                       (GtkSignalFunc) button_press_event, NULL);
19051
19052   gtk_widget_set_events (drawing_area, GDK_EXPOSURE_MASK
19053                          | GDK_LEAVE_NOTIFY_MASK
19054                          | GDK_BUTTON_PRESS_MASK
19055                          | GDK_POINTER_MOTION_MASK
19056                          | GDK_POINTER_MOTION_HINT_MASK);
19057
19058   /* The following call enables tracking and processing of extension
19059      events for the drawing area */
19060   gtk_widget_set_extension_events (drawing_area, GDK_EXTENSION_EVENTS_CURSOR);
19061
19062   /* .. And some buttons */
19063   button = gtk_button_new_with_label ("Input Dialog");
19064   gtk_box_pack_start (GTK_BOX (vbox), button, FALSE, FALSE, 0);
19065
19066   gtk_signal_connect (GTK_OBJECT (button), "clicked",
19067                       GTK_SIGNAL_FUNC (create_input_dialog), NULL);
19068   gtk_widget_show (button);
19069
19070   button = gtk_button_new_with_label ("Quit");
19071   gtk_box_pack_start (GTK_BOX (vbox), button, FALSE, FALSE, 0);
19072
19073   gtk_signal_connect_object (GTK_OBJECT (button), "clicked",
19074                              GTK_SIGNAL_FUNC (gtk_widget_destroy),
19075                              GTK_OBJECT (window));
19076   gtk_widget_show (button);
19077
19078   gtk_widget_show (window);
19079
19080   gtk_main ();
19081
19082   return 0;
19083 }
19084 <!-- example-end -->
19085 </programlisting>
19086
19087 </sect2>
19088 </sect1>
19089
19090 </appendix>
19091
19092 <!-- ***************************************************************** -->
19093 <appendix id="app-ListWidget">
19094 <title>List Widget</title>
19095
19096 <para>NOTE: The List widget has been superseded by the CList widget. It is
19097 detailed here just for completeness.</para>
19098
19099 <para>The List widget is designed to act as a vertical container for
19100 widgets that should be of the type ListItem.</para>
19101
19102 <para>A List widget has its own window to receive events and its own
19103 background color which is usually white. As it is directly derived
19104 from a Container it can be treated as such by using the
19105 GTK_CONTAINER(List) macro, see the Container widget for more on
19106 this. One should already be familiar with the usage of a GList and
19107 its related functions g_list_*() to be able to use the List widget
19108 to it full extent.</para>
19109
19110 <para>There is one field inside the structure definition of the List
19111 widget that will be of greater interest to us, this is:</para>
19112
19113 <programlisting role="C">
19114 struct _GtkList
19115 {
19116   ...
19117   GList *selection;
19118   guint selection_mode;
19119   ...
19120 }; 
19121 </programlisting>
19122
19123 <para>The selection field of a List points to a linked list of all items
19124 that are currently selected, or NULL if the selection is empty.  So to
19125 learn about the current selection we read the GTK_LIST()->selection
19126 field, but do not modify it since the internal fields are maintained
19127 by the gtk_list_*() functions.</para>
19128
19129 <para>The selection_mode of the List determines the selection facilities
19130 of a List and therefore the contents of the GTK_LIST()->selection
19131 field. The selection_mode may be one of the following:</para>
19132
19133 <itemizedlist>
19134 <listitem><simpara> <literal>GTK_SELECTION_SINGLE</literal> - The selection is either NULL
19135                         or contains a GList pointer
19136                         for a single selected item.</simpara>
19137 </listitem>
19138 <listitem><simpara> <literal>GTK_SELECTION_BROWSE</literal> -  The selection is NULL if the list
19139                         contains no widgets or insensitive
19140                         ones only, otherwise it contains
19141                         a GList pointer for one GList
19142                         structure, and therefore exactly
19143                         one list item.</simpara>
19144 </listitem>
19145 <listitem><simpara> <literal>GTK_SELECTION_MULTIPLE</literal> -  The selection is NULL if no list
19146                         items are selected or a GList pointer
19147                         for the first selected item. That
19148                         in turn points to a GList structure
19149                         for the second selected item and so
19150                         on.</simpara>
19151 </listitem>
19152 <listitem><simpara> <literal>GTK_SELECTION_EXTENDED</literal> - The selection is always NULL.</simpara>
19153 </listitem>
19154 </itemizedlist>
19155
19156 <para>The default is <literal>GTK_SELECTION_MULTIPLE</literal>.</para>
19157
19158 <!-- ----------------------------------------------------------------- -->
19159 <sect1 id="sec-SelectionSignals">
19160 <title>Signals</title>
19161
19162 <programlisting role="C">
19163 void selection_changed( GtkList *list );
19164 </programlisting>
19165
19166 <para>This signal will be invoked whenever the selection field of a List
19167 has changed. This happens when a child of thekList got selected or
19168 deselected.</para>
19169
19170 <programlisting role="C">
19171 void select_child( GtkList   *list,
19172                    GtkWidget *child);
19173 </programlisting>
19174
19175 <para>This signal is invoked when a child of the List is about to get
19176 selected. This happens mainly on calls to gtk_list_select_item(),
19177 gtk_list_select_child(), button presses and sometimes indirectly
19178 triggered on some else occasions where children get added to or
19179 removed from the List.</para>
19180
19181 <programlisting role="C">
19182 void unselect_child( GtkList   *list,
19183                      GtkWidget *child );
19184 </programlisting>
19185
19186 <para>This signal is invoked when a child of the List is about to get
19187 deselected. This happens mainly on calls to gtk_list_unselect_item(),
19188 gtk_list_unselect_child(), button presses and sometimes indirectly
19189 triggered on some else occasions where children get added to or
19190 removed from the List.</para>
19191
19192 </sect1>
19193
19194 <!-- ----------------------------------------------------------------- -->
19195 <sect1 id="sec-GtkListFunctions">
19196 <title>Functions</title>
19197
19198 <programlisting role="C">
19199 guint gtk_list_get_type( void );
19200 </programlisting>
19201
19202 <para>Returns the "GtkList" type identifier.</para>
19203
19204 <programlisting role="C">
19205 GtkWidget *gtk_list_new( void );
19206 </programlisting>
19207
19208 <para>Create a new List object. The new widget is returned as a pointer
19209 to a GtkWidget object. NULL is returned on failure.</para>
19210
19211 <programlisting role="C">
19212 void gtk_list_insert_items( GtkList *list,
19213                             GList   *items,
19214                             gint     position );
19215 </programlisting>
19216
19217 <para>Insert list items into the list, starting at <literal>position</literal>.
19218 <literal>items</literal> is a doubly linked list where each nodes data pointer is
19219 expected to point to a newly created ListItem. The GList nodes of
19220 <literal>items</literal> are taken over by the list.</para>
19221
19222 <programlisting role="C">
19223 void gtk_list_append_items( GtkList *list,
19224                             GList   *items);
19225 </programlisting>
19226
19227 <para>Insert list items just like gtk_list_insert_items() at the end of the
19228 list. The GList nodes of <literal>items</literal> are taken over by the list.</para>
19229
19230 <programlisting role="C">
19231 void gtk_list_prepend_items( GtkList *list,
19232                              GList   *items);
19233 </programlisting>
19234
19235 <para>Insert list items just like gtk_list_insert_items() at the very
19236 beginning of the list. The GList nodes of <literal>items</literal> are taken over by
19237 the list.</para>
19238
19239 <programlisting role="C">
19240 void gtk_list_remove_items( GtkList *list,
19241                             GList   *items);
19242 </programlisting>
19243
19244 <para>Remove list items from the list. <literal>items</literal> is a doubly linked list
19245 where each nodes data pointer is expected to point to a direct child
19246 of list. It is the callers responsibility to make a call to
19247 g_list_free(items) afterwards. Also the caller has to destroy the list
19248 items himself.</para>
19249
19250 <programlisting role="C">
19251 void gtk_list_clear_items( GtkList *list,
19252                            gint start,
19253                            gint end );
19254 </programlisting>
19255
19256 <para>Remove and destroy list items from the list. A widget is affected if
19257 its current position within the list is in the range specified by
19258 <literal>start</literal> and <literal>end</literal>.</para>
19259
19260 <programlisting role="C">
19261 void gtk_list_select_item( GtkList *list,
19262                            gint     item );
19263 </programlisting>
19264
19265 <para>Invoke the select_child signal for a list item specified through its
19266 current position within the list.</para>
19267
19268 <programlisting role="C">
19269 void gtk_list_unselect_item( GtkList *list,
19270                              gint     item);
19271 </programlisting>
19272
19273 <para>Invoke the unselect_child signal for a list item specified through its
19274 current position within the list.</para>
19275
19276 <programlisting role="C">
19277 void gtk_list_select_child( GtkList *list,
19278                             GtkWidget *child);
19279 </programlisting>
19280
19281 <para>Invoke the select_child signal for the specified child.</para>
19282
19283 <programlisting role="C">
19284 void gtk_list_unselect_child( GtkList   *list,
19285                               GtkWidget *child);
19286 </programlisting>
19287
19288 <para>Invoke the unselect_child signal for the specified child.</para>
19289
19290 <programlisting role="C">
19291 gint gtk_list_child_position( GtkList *list,
19292                               GtkWidget *child);
19293 </programlisting>
19294
19295 <para>Return the position of <literal>child</literal> within the list. "-1" is returned on
19296 failure.</para>
19297
19298 <programlisting role="C">
19299 void gtk_list_set_selection_mode( GtkList         *list,
19300                                   GtkSelectionMode mode );
19301 </programlisting>
19302
19303 <para>Set the selection mode MODE which can be of GTK_SELECTION_SINGLE,
19304 GTK_SELECTION_BROWSE, GTK_SELECTION_MULTIPLE or
19305 GTK_SELECTION_EXTENDED.</para>
19306
19307 <programlisting role="C">
19308 GtkList *GTK_LIST( gpointer obj );
19309 </programlisting>
19310
19311 <para>Cast a generic pointer to "GtkList *".</para>
19312
19313 <programlisting role="C">
19314 GtkListClass *GTK_LIST_CLASS( gpointer class);
19315 </programlisting>
19316
19317 <para>Cast a generic pointer to "GtkListClass *". </para>
19318
19319 <programlisting role="C">
19320 gint GTK_IS_LIST( gpointer obj);
19321 </programlisting>
19322
19323 <para>Determine if a generic pointer refers to a "GtkList" object.</para>
19324
19325 </sect1>
19326
19327 <!-- ----------------------------------------------------------------- -->
19328 <sect1 id="sec-GtkListExample">
19329 <title>Example</title>
19330
19331 <para>Following is an example program that will print out the changes of the
19332 selection of a List, and lets you "arrest" list items into a prison
19333 by selecting them with the rightmost mouse button.</para>
19334
19335 <programlisting role="C">
19336 <!-- example-start list list.c -->
19337
19338 /* Include the GTK header files
19339  * Include stdio.h, we need that for the printf() function
19340  */
19341 #include &lt;gtk/gtk.h&gt;
19342 #include &lt;stdio.h&gt;
19343
19344 /* This is our data identification string to store
19345  * data in list items
19346  */
19347 const gchar *list_item_data_key="list_item_data";
19348
19349
19350 /* prototypes for signal handler that we are going to connect
19351  * to the List widget
19352  */
19353 static void  sigh_print_selection( GtkWidget *gtklist,
19354                                    gpointer   func_data);
19355
19356 static void  sigh_button_event( GtkWidget      *gtklist,
19357                                 GdkEventButton *event,
19358                                 GtkWidget      *frame );
19359
19360
19361 /* Main function to set up the user interface */
19362
19363 gint main( int    argc,
19364            gchar *argv[] )
19365 {                                  
19366     GtkWidget *separator;
19367     GtkWidget *window;
19368     GtkWidget *vbox;
19369     GtkWidget *scrolled_window;
19370     GtkWidget *frame;
19371     GtkWidget *gtklist;
19372     GtkWidget *button;
19373     GtkWidget *list_item;
19374     GList *dlist;
19375     guint i;
19376     gchar buffer[64];
19377     
19378     
19379     /* Initialize GTK (and subsequently GDK) */
19380
19381     gtk_init(&amp;argc, &amp;argv);
19382     
19383     
19384     /* Create a window to put all the widgets in
19385      * connect gtk_main_quit() to the "destroy" event of
19386      * the window to handle window manager close-window-events
19387      */
19388     window=gtk_window_new(GTK_WINDOW_TOPLEVEL);
19389     gtk_window_set_title(GTK_WINDOW(window), "GtkList Example");
19390     gtk_signal_connect(GTK_OBJECT(window),
19391                        "destroy",
19392                        GTK_SIGNAL_FUNC(gtk_main_quit),
19393                        NULL);
19394     
19395     
19396     /* Inside the window we need a box to arrange the widgets
19397      * vertically */
19398     vbox=gtk_vbox_new(FALSE, 5);
19399     gtk_container_set_border_width(GTK_CONTAINER(vbox), 5);
19400     gtk_container_add(GTK_CONTAINER(window), vbox);
19401     gtk_widget_show(vbox);
19402     
19403     /* This is the scrolled window to put the List widget inside */
19404     scrolled_window=gtk_scrolled_window_new(NULL, NULL);
19405     gtk_widget_set_usize(scrolled_window, 250, 150);
19406     gtk_container_add(GTK_CONTAINER(vbox), scrolled_window);
19407     gtk_widget_show(scrolled_window);
19408     
19409     /* Create thekList widget.
19410      * Connect the sigh_print_selection() signal handler
19411      * function to the "selection_changed" signal of the List
19412      * to print out the selected items each time the selection
19413      * has changed */
19414     gtklist=gtk_list_new();
19415     gtk_scrolled_window_add_with_viewport( GTK_SCROLLED_WINDOW(scrolled_window),
19416                                            gtklist);
19417     gtk_widget_show(gtklist);
19418     gtk_signal_connect(GTK_OBJECT(gtklist),
19419                        "selection_changed",
19420                        GTK_SIGNAL_FUNC(sigh_print_selection),
19421                        NULL);
19422     
19423     /* We create a "Prison" to put a list item in ;) */
19424     frame=gtk_frame_new("Prison");
19425     gtk_widget_set_usize(frame, 200, 50);
19426     gtk_container_set_border_width(GTK_CONTAINER(frame), 5);
19427     gtk_frame_set_shadow_type(GTK_FRAME(frame), GTK_SHADOW_OUT);
19428     gtk_container_add(GTK_CONTAINER(vbox), frame);
19429     gtk_widget_show(frame);
19430     
19431     /* Connect the sigh_button_event() signal handler to the List
19432      * which will handle the "arresting" of list items
19433      */
19434     gtk_signal_connect(GTK_OBJECT(gtklist),
19435                        "button_release_event",
19436                        GTK_SIGNAL_FUNC(sigh_button_event),
19437                        frame);
19438     
19439     /* Create a separator */
19440     separator=gtk_hseparator_new();
19441     gtk_container_add(GTK_CONTAINER(vbox), separator);
19442     gtk_widget_show(separator);
19443     
19444     /* Finally create a button and connect its "clicked" signal
19445      * to the destruction of the window */
19446     button=gtk_button_new_with_label("Close");
19447     gtk_container_add(GTK_CONTAINER(vbox), button);
19448     gtk_widget_show(button);
19449     gtk_signal_connect_object(GTK_OBJECT(button),
19450                               "clicked",
19451                               GTK_SIGNAL_FUNC(gtk_widget_destroy),
19452                               GTK_OBJECT(window));
19453     
19454     
19455     /* Now we create 5 list items, each having its own
19456      * label and add them to the List using gtk_container_add()
19457      * Also we query the text string from the label and
19458      * associate it with the list_item_data_key for each list item
19459      */
19460     for (i=0; i<5; i++) {
19461         GtkWidget       *label;
19462         gchar           *string;
19463         
19464         sprintf(buffer, "ListItemContainer with Label #%d", i);
19465         label=gtk_label_new(buffer);
19466         list_item=gtk_list_item_new();
19467         gtk_container_add(GTK_CONTAINER(list_item), label);
19468         gtk_widget_show(label);
19469         gtk_container_add(GTK_CONTAINER(gtklist), list_item);
19470         gtk_widget_show(list_item);
19471         gtk_label_get(GTK_LABEL(label), &amp;string);
19472         gtk_object_set_data(GTK_OBJECT(list_item),
19473                             list_item_data_key,
19474                             string);
19475     }
19476     /* Here, we are creating another 5 labels, this time
19477      * we use gtk_list_item_new_with_label() for the creation
19478      * we can't query the text string from the label because
19479      * we don't have the labels pointer and therefore
19480      * we just associate the list_item_data_key of each
19481      * list item with the same text string.
19482      * For adding of the list items we put them all into a doubly
19483      * linked list (GList), and then add them by a single call to
19484      * gtk_list_append_items().
19485      * Because we use g_list_prepend() to put the items into the
19486      * doubly linked list, their order will be descending (instead
19487      * of ascending when using g_list_append())
19488      */
19489     dlist=NULL;
19490     for (; i<10; i++) {
19491         sprintf(buffer, "List Item with Label %d", i);
19492         list_item=gtk_list_item_new_with_label(buffer);
19493         dlist=g_list_prepend(dlist, list_item);
19494         gtk_widget_show(list_item);
19495         gtk_object_set_data(GTK_OBJECT(list_item),
19496                             list_item_data_key,
19497                             "ListItem with integrated Label");
19498     }
19499     gtk_list_append_items(GTK_LIST(gtklist), dlist);
19500     
19501     /* Finally we want to see the window, don't we? ;) */
19502     gtk_widget_show(window);
19503     
19504     /* Fire up the main event loop of gtk */
19505     gtk_main();
19506     
19507     /* We get here after gtk_main_quit() has been called which
19508      * happens if the main window gets destroyed
19509      */
19510     return(0);
19511 }
19512
19513 /* This is the signal handler that got connected to button
19514  * press/release events of the List
19515  */
19516 void sigh_button_event( GtkWidget      *gtklist,
19517                         GdkEventButton *event,
19518                         GtkWidget      *frame )
19519 {
19520     /* We only do something if the third (rightmost mouse button
19521      * was released
19522      */
19523     if (event->type==GDK_BUTTON_RELEASE &amp;&amp;
19524         event->button==3) {
19525         GList           *dlist, *free_list;
19526         GtkWidget       *new_prisoner;
19527         
19528         /* Fetch the currently selected list item which
19529          * will be our next prisoner ;)
19530          */
19531         dlist=GTK_LIST(gtklist)->selection;
19532         if (dlist)
19533                 new_prisoner=GTK_WIDGET(dlist->data);
19534         else
19535                 new_prisoner=NULL;
19536         
19537         /* Look for already imprisoned list items, we
19538          * will put them back into the list.
19539          * Remember to free the doubly linked list that
19540          * gtk_container_children() returns
19541          */
19542         dlist=gtk_container_children(GTK_CONTAINER(frame));
19543         free_list=dlist;
19544         while (dlist) {
19545             GtkWidget       *list_item;
19546             
19547             list_item=dlist->data;
19548             
19549             gtk_widget_reparent(list_item, gtklist);
19550             
19551             dlist=dlist->next;
19552         }
19553         g_list_free(free_list);
19554         
19555         /* If we have a new prisoner, remove him from the
19556          * List and put him into the frame "Prison".
19557          * We need to unselect the item first.
19558          */
19559         if (new_prisoner) {
19560             GList   static_dlist;
19561             
19562             static_dlist.data=new_prisoner;
19563             static_dlist.next=NULL;
19564             static_dlist.prev=NULL;
19565             
19566             gtk_list_unselect_child(GTK_LIST(gtklist),
19567                                     new_prisoner);
19568             gtk_widget_reparent(new_prisoner, frame);
19569         }
19570     }
19571 }
19572
19573 /* This is the signal handler that gets called if List
19574  * emits the "selection_changed" signal
19575  */
19576 void sigh_print_selection( GtkWidget *gtklist,
19577                            gpointer   func_data )
19578 {
19579     GList   *dlist;
19580     
19581     /* Fetch the doubly linked list of selected items
19582      * of the List, remember to treat this as read-only!
19583      */
19584     dlist=GTK_LIST(gtklist)->selection;
19585     
19586     /* If there are no selected items there is nothing more
19587      * to do than just telling the user so
19588      */
19589     if (!dlist) {
19590         g_print("Selection cleared\n");
19591         return;
19592     }
19593     /* Ok, we got a selection and so we print it
19594      */
19595     g_print("The selection is a ");
19596     
19597     /* Get the list item from the doubly linked list
19598      * and then query the data associated with list_item_data_key.
19599      * We then just print it */
19600     while (dlist) {
19601         GtkObject       *list_item;
19602         gchar           *item_data_string;
19603         
19604         list_item=GTK_OBJECT(dlist->data);
19605         item_data_string=gtk_object_get_data(list_item,
19606                                              list_item_data_key);
19607         g_print("%s ", item_data_string);
19608         
19609         dlist=dlist->next;
19610     }
19611     g_print("\n");
19612 }
19613 <!-- example-end -->
19614 </programlisting>
19615
19616 </sect1>
19617
19618 <!-- ----------------------------------------------------------------- -->
19619 <sect1 id="sec-ListItemWidget">
19620 <title>List Item Widget</title>
19621
19622 <para>The ListItem widget is designed to act as a container holding up to
19623 one child, providing functions for selection/deselection just like the
19624 List widget requires them for its children.</para>
19625
19626 <para>A ListItem has its own window to receive events and has its own
19627 background color which is usually white.</para>
19628
19629 <para>As it is directly derived from an Item it can be treated as such by
19630 using the GTK_ITEM(ListItem) macro, see the Item widget for more on
19631 this. Usually a ListItem just holds a label to identify, e.g., a
19632 filename within a List -- therefore the convenience function
19633 gtk_list_item_new_with_label() is provided. The same effect can be
19634 achieved by creating a Label on its own, setting its alignment to
19635 xalign=0 and yalign=0.5 with a subsequent container addition to the
19636 ListItem.</para>
19637
19638 <para>As one is not forced to add a GtkLabel to a GtkListItem, you could
19639 also add a GtkVBox or a GtkArrow etc. to the GtkListItem.</para>
19640
19641 </sect1>
19642
19643 <!-- ----------------------------------------------------------------- -->
19644 <sect1 id="sec-GtkListItemSignals">
19645 <title>Signals</title>
19646
19647 <para>A GtkListItem does not create new signals on its own, but inherits
19648 the signals of a Item.</para>
19649
19650 </sect1>
19651
19652 <!-- ----------------------------------------------------------------- -->
19653 <sect1 id="sec-GtkListItemFunctions">
19654 <title>Functions</title>
19655
19656 <programlisting role="C">
19657 guint gtk_list_item_get_type( void );
19658 </programlisting>
19659
19660 <para>Returns the "GtkListItem" type identifier.</para>
19661
19662 <programlisting role="C">
19663 GtkWidget *gtk_list_item_new( void );
19664 </programlisting>
19665
19666 <para>Create a new ListItem object. The new widget is returned as a
19667 pointer to a GtkWidget object. NULL is returned on failure.</para>
19668
19669 <programlisting role="C">
19670 GtkWidget *gtk_list_item_new_with_label( gchar *label );
19671 </programlisting>
19672
19673 <para>Create a new ListItem object, having a single GtkLabel as the sole
19674 child. The new widget is returned as a pointer to a GtkWidget
19675 object. NULL is returned on failure.</para>
19676
19677 <programlisting role="C">
19678 void gtk_list_item_select( GtkListItem *list_item );
19679 </programlisting>
19680
19681 <para>This function is basically a wrapper around a call to gtk_item_select
19682 (GTK_ITEM (list_item)) which will emit the select signal.  *Note
19683 GtkItem::, for more info.</para>
19684
19685 <programlisting role="C">
19686 void gtk_list_item_deselect( GtkListItem *list_item );
19687 </programlisting>
19688
19689 <para>This function is basically a wrapper around a call to
19690 gtk_item_deselect (GTK_ITEM (list_item)) which will emit the deselect
19691 signal.  *Note GtkItem::, for more info.</para>
19692
19693 <programlisting role="C">
19694 GtkListItem *GTK_LIST_ITEM( gpointer obj );
19695 </programlisting>
19696
19697 <para>Cast a generic pointer to "GtkListItem *".</para>
19698
19699 <programlisting role="C">
19700 GtkListItemClass *GTK_LIST_ITEM_CLASS( gpointer class );
19701 </programlisting>
19702
19703 <para>Cast a generic pointer to GtkListItemClass*. *Note Standard Macros::,
19704 for more info.</para>
19705
19706 <programlisting role="C">
19707 gint GTK_IS_LIST_ITEM( gpointer obj );
19708 </programlisting>
19709
19710 <para>Determine if a generic pointer refers to a `GtkListItem' object.
19711 *Note Standard Macros::, for more info.</para>
19712
19713 </sect1>
19714
19715 <!-- ----------------------------------------------------------------- -->
19716 <sect1 id="sec-GtkListItemExample">
19717 <title>Example</title>
19718
19719 <para>Please see the List example on this, which covers the usage of a
19720 ListItem as well.</para>
19721
19722 </sect1>
19723 </appendix>
19724 </book>