1 <!doctype book PUBLIC "-//OASIS//DTD DocBook V3.1//EN" []>
5 <date>March 1st 2001</date>
6 <title>GTK+ 1.2 Tutorial</title>
9 <firstname>Tony</firstname>
10 <surname>Gale</surname>
13 <firstname>Ian</firstname>
14 <surname>Main</surname>
18 <para> This is a tutorial on how to use GTK (the GIMP Toolkit) through its C
25 <!-- ***************************************************************** -->
26 <chapter id="ch-Introduction">
27 <title>Introduction</title>
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>
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
44 <listitem><simpara> Peter Mattis <ulink url="mailto:petm@xcf.berkeley.edu">
45 petm@xcf.berkeley.edu</ulink></simpara>
47 <listitem><simpara> Spencer Kimball <ulink url="mailto:spencer@xcf.berkeley.edu">
48 spencer@xcf.berkeley.edu</ulink></simpara>
50 <listitem><simpara> Josh MacDonald <ulink url="mailto:jmacd@xcf.berkeley.edu">
51 jmacd@xcf.berkeley.edu</ulink></simpara>
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
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>
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>
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>
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>
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>
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>
113 <!-- ***************************************************************** -->
114 <chapter id="ch-GettingStarted">
115 <title>Getting Started</title>
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>
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
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>
132 <programlisting role="C">
133 <!-- example-start base base.c -->
135 #include <gtk/gtk.h>
142 gtk_init (&argc, &argv);
144 window = gtk_window_new (GTK_WINDOW_TOPLEVEL);
145 gtk_widget_show (window);
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>
159 <para>The meaning of the unusual compilation options is explained below in
160 <link linkend="sec-Compiling">Compiling Hello World</link>.</para>
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
166 <para>The next line:</para>
168 <programlisting role="C">
169 gtk_init (&argc, &argv);
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>
180 <itemizedlist spacing=Compact>
181 <listitem><simpara> <literal>--gtk-module</literal></simpara>
183 <listitem><simpara> <literal>--g-fatal-warnings</literal></simpara>
185 <listitem><simpara> <literal>--gtk-debug</literal></simpara>
187 <listitem><simpara> <literal>--gtk-no-debug</literal></simpara>
189 <listitem><simpara> <literal>--gdk-debug</literal></simpara>
191 <listitem><simpara> <literal>--gdk-no-debug</literal></simpara>
193 <listitem><simpara> <literal>--display</literal></simpara>
195 <listitem><simpara> <literal>--sync</literal></simpara>
197 <listitem><simpara> <literal>--no-xshm</literal></simpara>
199 <listitem><simpara> <literal>--name</literal></simpara>
201 <listitem><simpara> <literal>--class</literal></simpara>
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>
209 <para>The next two lines of code create and display a window.</para>
211 <programlisting role="C">
212 window = gtk_window_new (GTK_WINDOW_TOPLEVEL);
213 gtk_widget_show (window);
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>
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>
224 <para>The last line enters the GTK main processing loop.</para>
226 <programlisting role="C">
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>
235 <!-- ----------------------------------------------------------------- -->
236 <sect1 id="sec-HelloWorld">
237 <title>Hello World in GTK</title>
239 <para>Now for a program with a widget (a button). It's the classic
240 hello world a la GTK.</para>
242 <programlisting role="C">
243 <!-- example-start helloworld helloworld.c -->
245 #include <gtk/gtk.h>
247 /* This is a callback function. The data arguments are ignored
248 * in this example. More on callbacks below. */
249 void hello( GtkWidget *widget,
252 g_print ("Hello World\n");
255 gint delete_event( GtkWidget *widget,
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?'
265 g_print ("delete event occurred\n");
267 /* Change TRUE to FALSE and the main window will be destroyed with
268 * a "delete_event". */
273 /* Another callback */
274 void destroy( GtkWidget *widget,
283 /* GtkWidget is the storage type for widgets */
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(&argc, &argv);
291 /* create a new window */
292 window = gtk_window_new (GTK_WINDOW_TOPLEVEL);
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);
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);
308 /* Sets the border width of the window. */
309 gtk_container_set_border_width (GTK_CONTAINER (window), 10);
311 /* Creates a new button with the label "Hello World". */
312 button = gtk_button_new_with_label ("Hello World");
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);
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));
327 /* This packs the button into the window (a gtk container). */
328 gtk_container_add (GTK_CONTAINER (window), button);
330 /* The final step is to display this newly created widget. */
331 gtk_widget_show (button);
334 gtk_widget_show (window);
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
348 <!-- ----------------------------------------------------------------- -->
349 <sect1 id="sec-Compiling">
350 <title>Compiling Hello World</title>
352 <para>To compile use:</para>
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>
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>
368 <para>Note that the type of single quote used in the compile command above
369 is significant.</para>
371 <para>The libraries that are usually linked in are:</para>
374 <listitem><simpara>The GTK library (-lgtk), the widget library, based on top of GDK.</simpara>
377 <listitem><simpara>The GDK library (-lgdk), the Xlib wrapper.</simpara>
380 <listitem><simpara>The gmodule library (-lgmodule), which is used to load run time
381 extensions.</simpara>
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>
390 <listitem><simpara>The Xlib library (-lX11) which is used by GDK.</simpara>
393 <listitem><simpara>The Xext library (-lXext). This contains code for shared memory
394 pixmaps and other X extensions.</simpara>
397 <listitem><simpara>The math library (-lm). This is used by GTK for various
404 <!-- ----------------------------------------------------------------- -->
405 <sect1 id="sec-TheoryOfSignalsAndCallbacks">
406 <title>Theory of Signals and Callbacks</title>
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>
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
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>
427 <programlisting role="C">
428 gint gtk_signal_connect( GtkObject *object,
431 gpointer func_data );
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>
439 <para>The function specified in the third argument is called a "callback
440 function", and should generally be of the form</para>
442 <programlisting role="C">
443 void callback_func( GtkWidget *widget,
444 gpointer callback_data );
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>
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>
456 <para>Another call used in the <emphasis>helloworld</emphasis> example, is:</para>
458 <programlisting role="C">
459 gint gtk_signal_connect_object( GtkObject *object,
462 GtkObject *slot_object );
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>
470 <programlisting role="C">
471 void callback_func( GtkObject *object );
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>
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>
488 <!-- ----------------------------------------------------------------- -->
489 <sect1 id="sec-Events">
490 <title>Events</title>
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>
496 <itemizedlist spacing=Compact>
497 <listitem><simpara> event</simpara>
499 <listitem><simpara> button_press_event</simpara>
501 <listitem><simpara> button_release_event</simpara>
503 <listitem><simpara> motion_notify_event</simpara>
505 <listitem><simpara> delete_event</simpara>
507 <listitem><simpara> destroy_event</simpara>
509 <listitem><simpara> expose_event</simpara>
511 <listitem><simpara> key_press_event</simpara>
513 <listitem><simpara> key_release_event</simpara>
515 <listitem><simpara> enter_notify_event</simpara>
517 <listitem><simpara> leave_notify_event</simpara>
519 <listitem><simpara> configure_event</simpara>
521 <listitem><simpara> focus_in_event</simpara>
523 <listitem><simpara> focus_out_event</simpara>
525 <listitem><simpara> map_event</simpara>
527 <listitem><simpara> unmap_event</simpara>
529 <listitem><simpara> property_notify_event</simpara>
531 <listitem><simpara> selection_clear_event</simpara>
533 <listitem><simpara> selection_request_event</simpara>
535 <listitem><simpara> selection_notify_event</simpara>
537 <listitem><simpara> proximity_in_event</simpara>
539 <listitem><simpara> proximity_out_event</simpara>
541 <listitem><simpara> drag_begin_event</simpara>
543 <listitem><simpara> drag_request_event</simpara>
545 <listitem><simpara> drag_end_event</simpara>
547 <listitem><simpara> drop_enter_event</simpara>
549 <listitem><simpara> drop_leave_event</simpara>
551 <listitem><simpara> drop_data_available_event</simpara>
553 <listitem><simpara> other_event</simpara>
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
563 <programlisting role="C">
564 gint callback_func( GtkWidget *widget,
566 gpointer callback_data );
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>
576 <programlisting role="C">
596 GDK_SELECTION_REQUEST
606 GDK_VISIBILITY_NOTIFY
608 GDK_OTHER_EVENT /* Deprecated, use filters instead */
611 <para>So, to connect a callback function to one of these events we would use
612 something like:</para>
614 <programlisting role="C">
615 gtk_signal_connect( GTK_OBJECT(button), "button_press_event",
616 GTK_SIGNAL_FUNC(button_press_callback),
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
625 <programlisting role="C">
626 static gint button_press_callback( GtkWidget *widget,
627 GdkEventButton *event,
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>
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>
643 <para>For details on the GdkEvent data types, see the appendix entitled
644 <link linkend="app-GDKEventTypes">GDK Event Types</link>.</para>
648 <!-- ----------------------------------------------------------------- -->
649 <sect1 id="sec-SteppingThroughHelloWorld">
650 <title>Stepping Through Hello World</title>
652 <para>Now that we know the theory behind this, let's clarify by walking
653 through the example <emphasis>helloworld</emphasis> program.</para>
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>
660 <programlisting role="C">
661 void hello( GtkWidget *widget,
664 g_print ("Hello World\n");
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>
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>
680 <programlisting role="C">
681 gint delete_event( GtkWidget *widget,
685 g_print ("delete event occurred\n");
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>
695 <programlisting role="C">
696 void destroy( GtkWidget *widget,
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>
706 <programlisting role="C">
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>
715 <programlisting role="C">
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>
726 <programlisting role="C">
727 gtk_init (&argc, &argv);
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>
735 <programlisting role="C">
736 window = gtk_window_new (GTK_WINDOW_TOPLEVEL);
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.
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
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);
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>
763 <para>And again, <literal>GTK_CONTAINER</literal> is a macro to perform type casting.</para>
765 <programlisting role="C">
766 gtk_container_set_border_width (GTK_CONTAINER (window), 10);
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
774 <programlisting role="C">
775 button = gtk_button_new_with_label ("Hello World");
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>
784 <programlisting role="C">
785 gtk_signal_connect (GTK_OBJECT (button), "clicked",
786 GTK_SIGNAL_FUNC (hello), NULL);
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>
800 <programlisting role="C">
801 gtk_signal_connect_object (GTK_OBJECT (button), "clicked",
802 GTK_SIGNAL_FUNC (gtk_widget_destroy),
803 GTK_OBJECT (window));
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
815 <programlisting role="C">
816 gtk_container_add (GTK_CONTAINER (window), button);
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>
826 <programlisting role="C">
827 gtk_widget_show (button);
829 gtk_widget_show (window);
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
836 <programlisting role="C">
840 <para>And the final return. Control returns here after gtk_quit() is called.</para>
842 <programlisting role="C">
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>
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>
867 <!-- ***************************************************************** -->
868 <chapter id="ch-MovingOn">
869 <title>Moving On</title>
871 <!-- ----------------------------------------------------------------- -->
872 <sect1 id="sec-DataTypes">
873 <title>Data Types</title>
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>
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>
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
892 <!-- ----------------------------------------------------------------- -->
893 <sect1 id="sec-MoreOnSignalHandlers">
894 <title>More on Signal Handlers</title>
896 <para>Lets take another look at the gtk_signal_connect declaration.</para>
898 <programlisting role="C">
899 gint gtk_signal_connect( GtkObject *object,
902 gpointer func_data );
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>
910 <para>This tag allows you to remove this callback from the list by using:</para>
912 <programlisting role="C">
913 void gtk_signal_disconnect( GtkObject *object,
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>
921 <para>You can also temporarily disable signal handlers with the
922 gtk_signal_handler_block() and gtk_signal_handler_unblock() family of
925 <programlisting role="C">
926 void gtk_signal_handler_block( GtkObject *object,
929 void gtk_signal_handler_block_by_func( GtkObject *object,
933 void gtk_signal_handler_block_by_data( GtkObject *object,
936 void gtk_signal_handler_unblock( GtkObject *object,
939 void gtk_signal_handler_unblock_by_func( GtkObject *object,
943 void gtk_signal_handler_unblock_by_data( GtkObject *object,
949 <!-- ----------------------------------------------------------------- -->
950 <sect1 id="sec-AnUpgradedHelloWorld">
951 <title>An Upgraded Hello World</title>
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>
957 <programlisting role="C">
958 <!-- example-start helloworld2 helloworld2.c -->
960 #include <gtk/gtk.h>
962 /* Our new improved callback. The data passed to this function
963 * is printed to stdout. */
964 void callback( GtkWidget *widget,
967 g_print ("Hello again - %s was pressed\n", (char *) data);
970 /* another callback */
971 gint delete_event( GtkWidget *widget,
982 /* GtkWidget is the storage type for widgets */
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 (&argc, &argv);
991 /* Create a new window */
992 window = gtk_window_new (GTK_WINDOW_TOPLEVEL);
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!");
998 /* Here we just set a handler for delete_event that immediately
1000 gtk_signal_connect (GTK_OBJECT (window), "delete_event",
1001 GTK_SIGNAL_FUNC (delete_event), NULL);
1003 /* Sets the border width of the window. */
1004 gtk_container_set_border_width (GTK_CONTAINER (window), 10);
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);
1011 /* Put the box into the main window. */
1012 gtk_container_add (GTK_CONTAINER (window), box1);
1014 /* Creates a new button with the label "Button 1". */
1015 button = gtk_button_new_with_label ("Button 1");
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");
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);
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);
1030 /* Do these same steps again to create a second button */
1031 button = gtk_button_new_with_label ("Button 2");
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");
1038 gtk_box_pack_start(GTK_BOX(box1), button, TRUE, TRUE, 0);
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);
1044 gtk_widget_show(box1);
1046 gtk_widget_show (window);
1048 /* Rest in gtk_main and wait for the fun to begin! */
1053 <!-- example-end -->
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>
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
1072 <!-- ***************************************************************** -->
1073 <chapter id="ch-PackingWidgets">
1074 <title>Packing Widgets</title>
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>
1083 <!-- ----------------------------------------------------------------- -->
1084 <sect1 id="sec-TheoryOfPackingBoxes">
1085 <title>Theory of Packing Boxes</title>
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>
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>
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>
1117 <!-- ----------------------------------------------------------------- -->
1118 <sect1 id="sec-DetailsOfBoxes">
1119 <title>Details of Boxes</title>
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>
1129 <imagedata fileref="gtk_tut_packbox1.jpg">
1131 </inlinemediaobject>
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>
1139 <para>This is the declaration of the gtk_box_pack_start function.</para>
1141 <programlisting role="C">
1142 void gtk_box_pack_start( GtkBox *box,
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>
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>
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>
1167 <para>When creating a new box, the function looks like this:</para>
1169 <programlisting role="C">
1170 GtkWidget *gtk_hbox_new (gint homogeneous,
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>
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>
1188 <imagedata fileref="gtk_tut_packbox2.jpg">
1190 </inlinemediaobject>
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>
1199 <!-- ----------------------------------------------------------------- -->
1200 <sect1 id="sec-PackingDemonstrationProgram">
1201 <title>Packing Demonstration Program</title>
1203 <programlisting role="C">
1204 <!-- example-start packbox packbox.c -->
1206 #include <stdio.h>
1207 #include <stdlib.h>
1208 #include "gtk/gtk.h"
1210 gint delete_event( GtkWidget *widget,
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,
1231 /* Create a new hbox with the appropriate homogeneous
1232 * and spacing settings */
1233 box = gtk_hbox_new (homogeneous, spacing);
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);
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);
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);
1248 /* Create a button with the label depending on the value of
1251 button = gtk_button_new_with_label ("TRUE,");
1253 button = gtk_button_new_with_label ("FALSE,");
1255 gtk_box_pack_start (GTK_BOX (box), button, expand, fill, padding);
1256 gtk_widget_show (button);
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);
1264 sprintf (padstr, "%d);", padding);
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);
1280 GtkWidget *separator;
1285 /* Our init, don't forget this! :) */
1286 gtk_init (&argc, &argv);
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. */
1294 which = atoi (argv[1]);
1296 /* Create our window */
1297 window = gtk_window_new (GTK_WINDOW_TOPLEVEL);
1299 /* You should always remember to connect the delete_event signal
1300 * to the main window. This is very important for proper intuitive
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);
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);
1311 /* which example to show. These correspond to the pictures above. */
1314 /* create a new label. */
1315 label = gtk_label_new ("gtk_hbox_new (FALSE, 0);");
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);
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
1324 gtk_box_pack_start (GTK_BOX (box1), label, FALSE, FALSE, 0);
1326 /* Show the label */
1327 gtk_widget_show (label);
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);
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);
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);
1346 /* Creates a separator, we'll learn more about these later,
1347 * but they are quite simple. */
1348 separator = gtk_hseparator_new ();
1350 /* Pack the separator into the vbox. Remember each of these
1351 * widgets is being packed into a vbox, so they'll be stacked
1353 gtk_box_pack_start (GTK_BOX (box1), separator, FALSE, TRUE, 5);
1354 gtk_widget_show (separator);
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);
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);
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);
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);
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);
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);
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);
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);
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);
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);
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);
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);
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);
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);
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);
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
1455 gtk_box_pack_start (GTK_BOX (box1), separator, FALSE, TRUE, 5);
1456 gtk_widget_show (separator);
1459 /* Create another new hbox.. remember we can use as many as we need! */
1460 quitbox = gtk_hbox_new (FALSE, 0);
1462 /* Our quit button. */
1463 button = gtk_button_new_with_label ("Quit");
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);
1476 /* Pack the vbox (box1) which now contains all our widgets, into the
1478 gtk_container_add (GTK_CONTAINER (window), box1);
1480 /* And show everything left */
1481 gtk_widget_show (button);
1482 gtk_widget_show (quitbox);
1484 gtk_widget_show (box1);
1485 /* Showing the window last so everything pops up at once. */
1486 gtk_widget_show (window);
1488 /* And of course, our main function. */
1491 /* Control returns here when gtk_main_quit() is called, but not when
1492 * gtk_exit is used. */
1496 <!-- example-end -->
1501 <!-- ----------------------------------------------------------------- -->
1502 <sect1 id="sec-PackingUsingTables">
1503 <title>Packing Using Tables</title>
1505 <para>Let's take a look at another way of packing - Tables. These can be
1506 extremely useful in certain situations.</para>
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>
1511 <para>The first thing to look at, of course, is the gtk_table_new function:</para>
1513 <programlisting role="C">
1514 GtkWidget *gtk_table_new( gint rows,
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>
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>
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>
1532 <programlisting role="C">
1534 0+----------+----------+
1536 1+----------+----------+
1538 2+----------+----------+
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>
1544 <programlisting role="C">
1545 void gtk_table_attach( GtkTable *table,
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>
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>
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>
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>
1573 <para>These options are:</para>
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>
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>
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>
1593 <para>Padding is just like in boxes, creating a clear area around the widget
1594 specified in pixels.</para>
1596 <para>gtk_table_attach() has a LOT of options. So, there's a shortcut:</para>
1598 <programlisting role="C">
1599 void gtk_table_attach_defaults( GtkTable *table,
1604 gint bottom_attach );
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>
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>
1615 <programlisting role="C">
1616 void gtk_table_set_row_spacing( GtkTable *table,
1623 <programlisting role="C">
1624 void gtk_table_set_col_spacing ( GtkTable *table,
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>
1632 <para>You can also set a consistent spacing of all rows and/or columns with:</para>
1634 <programlisting role="C">
1635 void gtk_table_set_row_spacings( GtkTable *table,
1641 <programlisting role="C">
1642 void gtk_table_set_col_spacings( GtkTable *table,
1646 <para>Note that with these calls, the last row and last column do not get
1651 <!-- ----------------------------------------------------------------- -->
1652 <sect1 id="sec-TablePackingExamples">
1653 <title>Table Packing Example</title>
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>
1663 <imagedata fileref="gtk_tut_table.jpg">
1665 </inlinemediaobject>
1668 <para>Here's the source code:</para>
1670 <programlisting role="C">
1671 <!-- example-start table table.c -->
1673 #include <gtk/gtk.h>
1676 * The data passed to this function is printed to stdout */
1677 void callback( GtkWidget *widget,
1680 g_print ("Hello again - %s was pressed\n", (char *) data);
1683 /* This callback quits the program */
1684 gint delete_event( GtkWidget *widget,
1699 gtk_init (&argc, &argv);
1701 /* Create a new window */
1702 window = gtk_window_new (GTK_WINDOW_TOPLEVEL);
1704 /* Set the window title */
1705 gtk_window_set_title (GTK_WINDOW (window), "Table");
1707 /* Set a handler for delete_event that immediately
1709 gtk_signal_connect (GTK_OBJECT (window), "delete_event",
1710 GTK_SIGNAL_FUNC (delete_event), NULL);
1712 /* Sets the border width of the window. */
1713 gtk_container_set_border_width (GTK_CONTAINER (window), 20);
1715 /* Create a 2x2 table */
1716 table = gtk_table_new (2, 2, TRUE);
1718 /* Put the table in the main window */
1719 gtk_container_add (GTK_CONTAINER (window), table);
1721 /* Create first button */
1722 button = gtk_button_new_with_label ("button 1");
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");
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);
1733 gtk_widget_show (button);
1735 /* Create second button */
1737 button = gtk_button_new_with_label ("button 2");
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);
1746 gtk_widget_show (button);
1748 /* Create "Quit" button */
1749 button = gtk_button_new_with_label ("Quit");
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);
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);
1760 gtk_widget_show (button);
1762 gtk_widget_show (table);
1763 gtk_widget_show (window);
1769 <!-- example-end -->
1775 <!-- ***************************************************************** -->
1776 <chapter id="ch-WidgetOverview">
1777 <title>Widget Overview</title>
1779 <para>The general steps to creating a widget in GTK are:</para>
1781 <listitem><simpara> gtk_*_new - one of various functions to create a new widget.
1782 These are all detailed in this section.</simpara>
1785 <listitem><simpara> Connect all signals and events we wish to use to the
1786 appropriate handlers.</simpara>
1789 <listitem><simpara> Set the attributes of the widget.</simpara>
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>
1796 <listitem><simpara> gtk_widget_show() the widget.</simpara>
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>
1809 <!-- ----------------------------------------------------------------- -->
1810 <sect1 id="sec-Casting">
1811 <title>Casting</title>
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>
1817 <programlisting role="C">
1820 GTK_SIGNAL_FUNC(function)
1821 GTK_CONTAINER(container)
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>
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>
1835 <para>For example:</para>
1837 <programlisting role="C">
1838 gtk_signal_connect( GTK_OBJECT(button), "clicked",
1839 GTK_SIGNAL_FUNC(callback_function), callback_data);
1842 <para>This casts the button into an object, and provides a cast for the
1843 function pointer to the callback.</para>
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
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>
1858 <!-- ----------------------------------------------------------------- -->
1859 <sect1 id="sec-WidgetHierarchy">
1860 <title>Widget Hierarchy</title>
1862 <para>For your reference, here is the class hierarchy tree used to implement widgets.</para>
1864 <programlisting role="C">
1869 | | | +GtkAccelLabel
1878 | | | | `GtkAspectFrame
1880 | | | | +GtkToggleButton
1881 | | | | | `GtkCheckButton
1882 | | | | | `GtkRadioButton
1883 | | | | `GtkOptionMenu
1885 | | | | +GtkMenuItem
1886 | | | | | +GtkCheckMenuItem
1887 | | | | | | `GtkRadioMenuItem
1888 | | | | | `GtkTearoffMenuItem
1889 | | | | +GtkListItem
1890 | | | | `GtkTreeItem
1892 | | | | +GtkColorSelectionDialog
1894 | | | | | `GtkInputDialog
1895 | | | | +GtkDrawWindow
1896 | | | | +GtkFileSelection
1897 | | | | +GtkFontSelectionDialog
1901 | | | +GtkScrolledWindow
1905 | | | | +GtkHButtonBox
1906 | | | | `GtkVButtonBox
1908 | | | | +GtkColorSelection
1909 | | | | `GtkGammaCurve
1917 | | | `GtkFontSelection
1935 | | | `GtkSpinButton
1961 <!-- ----------------------------------------------------------------- -->
1962 <sect1 id="sec-WidgetsWithoutWindows">
1963 <title>Widgets Without Windows</title>
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>
1969 <programlisting role="C">
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>
1997 <!-- ***************************************************************** -->
1998 <chapter id="ch-ButtonWidget">
1999 <title>The Button Widget</title>
2001 <!-- ----------------------------------------------------------------- -->
2002 <sect1 id="sec-NormalButtons">
2003 <title>Normal Buttons</title>
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>
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>
2019 <programlisting role="C">
2020 <!-- example-start buttons buttons.c -->
2022 #include <gtk/gtk.h>
2024 /* Create a new hbox with an image and a label packed into it
2025 * and return the box. */
2027 GtkWidget *xpm_label_box( GtkWidget *parent,
2028 gchar *xpm_filename,
2033 GtkWidget *pixmapwid;
2038 /* Create box for xpm and label */
2039 box1 = gtk_hbox_new (FALSE, 0);
2040 gtk_container_set_border_width (GTK_CONTAINER (box1), 2);
2042 /* Get the style of the button to get the
2043 * background color. */
2044 style = gtk_widget_get_style(parent);
2046 /* Now on to the xpm stuff */
2047 pixmap = gdk_pixmap_create_from_xpm (parent->window, &mask,
2048 &style->bg[GTK_STATE_NORMAL],
2050 pixmapwid = gtk_pixmap_new (pixmap, mask);
2052 /* Create a label for the button */
2053 label = gtk_label_new (label_text);
2055 /* Pack the pixmap and label into the box */
2056 gtk_box_pack_start (GTK_BOX (box1),
2057 pixmapwid, FALSE, FALSE, 3);
2059 gtk_box_pack_start (GTK_BOX (box1), label, FALSE, FALSE, 3);
2061 gtk_widget_show(pixmapwid);
2062 gtk_widget_show(label);
2067 /* Our usual callback function */
2068 void callback( GtkWidget *widget,
2071 g_print ("Hello again - %s was pressed\n", (char *) data);
2077 /* GtkWidget is the storage type for widgets */
2082 gtk_init (&argc, &argv);
2084 /* Create a new window */
2085 window = gtk_window_new (GTK_WINDOW_TOPLEVEL);
2087 gtk_window_set_title (GTK_WINDOW (window), "Pixmap'd Buttons!");
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);
2093 gtk_signal_connect (GTK_OBJECT (window), "delete_event",
2094 GTK_SIGNAL_FUNC (gtk_exit), NULL);
2096 /* Sets the border width of the window. */
2097 gtk_container_set_border_width (GTK_CONTAINER (window), 10);
2098 gtk_widget_realize(window);
2100 /* Create a new button */
2101 button = gtk_button_new ();
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");
2107 /* This calls our box creating function */
2108 box1 = xpm_label_box(window, "info.xpm", "cool button");
2110 /* Pack and show all our widgets */
2111 gtk_widget_show(box1);
2113 gtk_container_add (GTK_CONTAINER (button), box1);
2115 gtk_widget_show(button);
2117 gtk_container_add (GTK_CONTAINER (window), button);
2119 gtk_widget_show (window);
2121 /* Rest in gtk_main and wait for the fun to begin! */
2126 <!-- example-end -->
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>
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>
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>
2150 <para>The Button widget has the following signals:</para>
2153 <listitem><simpara><literal>pressed</literal> - emitted when pointer button is pressed within
2154 Button widget</simpara>
2156 <listitem><simpara><literal>released</literal> - emitted when pointer button is released within
2157 Button widget</simpara>
2159 <listitem><simpara><literal>clicked</literal> - emitted when pointer button is pressed and then
2160 released within Button widget</simpara>
2162 <listitem><simpara><literal>enter</literal> - emitted when pointer enters Button widget</simpara>
2164 <listitem><simpara><literal>leave</literal> - emitted when pointer leaves Button widget</simpara>
2170 <!-- ----------------------------------------------------------------- -->
2171 <sect1 id="sec-ToggleButtons">
2172 <title>Toggle Buttons</title>
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>
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>
2183 <para>Creating a new toggle button:</para>
2185 <programlisting role="C">
2186 GtkWidget *gtk_toggle_button_new( void );
2188 GtkWidget *gtk_toggle_button_new_with_label( gchar *label );
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>
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>
2206 <programlisting role="C">
2207 void toggle_button_callback (GtkWidget *widget, gpointer data)
2209 if (GTK_TOGGLE_BUTTON (widget)->active)
2211 /* If control reaches here, the toggle button is down */
2215 /* If control reaches here, the toggle button is up */
2220 <para>To force the state of a toggle button, and its children, the radio and
2221 check buttons, use this function:</para>
2223 <programlisting role="C">
2224 void gtk_toggle_button_set_active( GtkToggleButton *toggle_button,
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>
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>
2238 <programlisting role="C">
2239 gboolean gtk_toggle_button_get_active (GtkToggleButton *toggle_button);
2242 <para>This returns the current state of the toggle button as a boolean
2243 TRUE/FALSE value.</para>
2247 <!-- ----------------------------------------------------------------- -->
2248 <sect1 id="sec-CheckButtons">
2249 <title>Check Buttons</title>
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>
2257 <para>The two creation functions are similar to those of the normal button.</para>
2259 <programlisting role="C">
2260 GtkWidget *gtk_check_button_new( void );
2262 GtkWidget *gtk_check_button_new_with_label ( gchar *label );
2265 <para>The new_with_label function creates a check button with a label beside
2268 <para>Checking the state of the check button is identical to that of the
2269 toggle button.</para>
2273 <!-- ----------------------------------------------------------------- -->
2274 <sect1 id="sec-RadioButtons">
2275 <title>Radio Buttons</title>
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
2282 <para>Creating a new radio button is done with one of these calls:</para>
2284 <programlisting role="C">
2285 GtkWidget *gtk_radio_button_new( GSList *group );
2287 GtkWidget *gtk_radio_button_new_with_label( GSList *group,
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>
2296 <programlisting role="C">
2297 GSList *gtk_radio_button_group( GtkRadioButton *radio_button );
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>
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>
2311 <programlisting role="C">
2312 button2 = gtk_radio_button_new_with_label(
2313 gtk_radio_button_group (GTK_RADIO_BUTTON (button1)),
2317 <para>It is also a good idea to explicitly set which button should be the
2318 default depressed button with:</para>
2320 <programlisting role="C">
2321 void gtk_toggle_button_set_active( GtkToggleButton *toggle_button,
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>
2332 <para>The following example creates a radio button group with three buttons.</para>
2334 <programlisting role="C">
2335 <!-- example-start radiobuttons radiobuttons.c -->
2337 #include <gtk/gtk.h>
2338 #include <glib.h>
2340 gint close_application( GtkWidget *widget,
2351 GtkWidget *window = NULL;
2355 GtkWidget *separator;
2358 gtk_init(&argc,&argv);
2360 window = gtk_window_new (GTK_WINDOW_TOPLEVEL);
2362 gtk_signal_connect (GTK_OBJECT (window), "delete_event",
2363 GTK_SIGNAL_FUNC(close_application),
2366 gtk_window_set_title (GTK_WINDOW (window), "radio buttons");
2367 gtk_container_set_border_width (GTK_CONTAINER (window), 0);
2369 box1 = gtk_vbox_new (FALSE, 0);
2370 gtk_container_add (GTK_CONTAINER (window), box1);
2371 gtk_widget_show (box1);
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);
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);
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);
2388 button = gtk_radio_button_new_with_label(
2389 gtk_radio_button_group (GTK_RADIO_BUTTON (button)),
2391 gtk_box_pack_start (GTK_BOX (box2), button, TRUE, TRUE, 0);
2392 gtk_widget_show (button);
2394 separator = gtk_hseparator_new ();
2395 gtk_box_pack_start (GTK_BOX (box1), separator, FALSE, TRUE, 0);
2396 gtk_widget_show (separator);
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);
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);
2417 <!-- example-end -->
2420 <!-- TODO: check out gtk_radio_button_new_from_widget function - TRG -->
2425 <!-- ***************************************************************** -->
2426 <chapter id="ch-Adjustments">
2427 <title>Adjustments</title>
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>
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
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>
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>
2467 <!-- ----------------------------------------------------------------- -->
2468 <sect1 id="sec-CreatingAnAdjustment">
2469 <title>Creating an Adjustment</title>
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>
2475 <programlisting role="C">
2476 GtkObject *gtk_adjustment_new( gfloat value,
2479 gfloat step_increment,
2480 gfloat page_increment,
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>
2499 <!-- ----------------------------------------------------------------- -->
2500 <sect1 id="sec-UsingAdjustments">
2501 <title>Using Adjustments the Easy Way</title>
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>
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>
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>
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);
2542 <!-- ----------------------------------------------------------------- -->
2543 <sect1 id="sec-AdjustmentInternals">
2544 <title>Adjustment Internals</title>
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>
2552 <programlisting role="C">
2553 struct _GtkAdjustment
2560 gfloat step_increment;
2561 gfloat page_increment;
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>
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>
2577 <programlisting role="C">
2578 void gtk_adjustment_set_value( GtkAdjustment *adjustment,
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>
2590 <programlisting role="C">
2591 void (* value_changed) (GtkAdjustment *adjustment);
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>
2602 <programlisting role="C">
2603 void cb_rotate_picture (GtkAdjustment *adj, GtkWidget *picture)
2605 set_picture_rotation (picture, adj->value);
2609 <para>and connect it to the scale widget's adjustment like this:</para>
2611 <programlisting role="C">
2612 gtk_signal_connect (GTK_OBJECT (adj), "value_changed",
2613 GTK_SIGNAL_FUNC (cb_rotate_picture), picture);
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
2621 <programlisting role="C">
2622 void (* changed) (GtkAdjustment *adjustment);
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
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
2637 <programlisting role="C">
2638 gtk_signal_emit_by_name (GTK_OBJECT (adjustment), "changed");
2641 <para>Now go forth and adjust!</para>
2646 <!-- ***************************************************************** -->
2647 <chapter id="ch-RangeWidgets">
2648 <title>Range Widgets</title>
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>
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>
2668 <!-- ----------------------------------------------------------------- -->
2669 <sect1 id="sec-ScrollbarWidgets">
2670 <title>Scrollbar Widgets</title>
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>
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><gtk/gtkhscrollbar.h></literal>
2681 and <literal><gtk/gtkvscrollbar.h></literal>:</para>
2683 <programlisting role="C">
2684 GtkWidget *gtk_hscrollbar_new( GtkAdjustment *adjustment );
2686 GtkWidget *gtk_vscrollbar_new( GtkAdjustment *adjustment );
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
2699 <!-- ----------------------------------------------------------------- -->
2700 <sect1 id="sec-ScaleWidgets">
2701 <title>Scale Widgets</title>
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>
2710 <!-- ----------------------------------------------------------------- -->
2712 <title>Creating a Scale Widget</title>
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><gtk/gtkvscale.h></literal> and
2719 <literal><gtk/gtkhscale.h></literal>, create vertical and horizontal scale
2720 widgets, respectively:</para>
2722 <programlisting role="C">
2723 GtkWidget *gtk_vscale_new( GtkAdjustment *adjustment );
2725 GtkWidget *gtk_hscale_new( GtkAdjustment *adjustment );
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>
2741 <!-- ----------------------------------------------------------------- -->
2743 <title>Functions and Signals (well, functions, at least)</title>
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>
2749 <programlisting role="C">
2750 void gtk_scale_set_draw_value( GtkScale *scale,
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>
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>
2761 <programlisting role="C">
2762 void gtk_scale_set_digits( GtkScale *scale,
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>
2770 <para>Finally, the value can be drawn in different positions
2771 relative to the trough:</para>
2773 <programlisting role="C">
2774 void gtk_scale_set_value_pos( GtkScale *scale,
2775 GtkPositionType pos );
2778 <para>The argument <literal>pos</literal> is of type <literal>GtkPositionType</literal>, which is
2779 defined in <literal><gtk/gtkenums.h></literal>, and can take one of the
2780 following values:</para>
2782 <programlisting role="C">
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>
2793 <para>All the preceding functions are defined in
2794 <literal><gtk/gtkscale.h></literal>. The header files for all GTK widgets
2795 are automatically included when you include
2796 <literal><gtk/gtk.h></literal>. But you should look over the header files
2797 of all widgets that interest you,</para>
2802 <!-- ----------------------------------------------------------------- -->
2803 <sect1 id="sec-CommonRangeFunctions">
2804 <title>Common Range Functions</title>
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><gtk/gtkrange.h></literal> and will work on all range
2814 <!-- ----------------------------------------------------------------- -->
2816 <title>Setting the Update Policy</title>
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><gtk/gtkenums.h></literal> as type <literal>enum GtkUpdateType</literal>,
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>
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>
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>
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>
2845 <programlisting role="C">
2846 void gtk_range_set_update_policy( GtkRange *range,
2847 GtkUpdateType policy);
2852 <!-- ----------------------------------------------------------------- -->
2854 <title>Getting and Setting Adjustments</title>
2856 <para>Getting and setting the adjustment for a range widget "on the fly" is
2857 done, predictably, with:</para>
2859 <programlisting role="C">
2860 GtkAdjustment* gtk_range_get_adjustment( GtkRange *range );
2862 void gtk_range_set_adjustment( GtkRange *range,
2863 GtkAdjustment *adjustment );
2866 <para><literal>gtk_range_get_adjustment()</literal> returns a pointer to the adjustment to
2867 which <literal>range</literal> is connected.</para>
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>
2881 <programlisting role="C">
2882 gtk_signal_emit_by_name (GTK_OBJECT (adjustment), "changed");
2888 <!-- ----------------------------------------------------------------- -->
2889 <sect1 id="sec-KeyAndMouseBindings">
2890 <title>Key and Mouse bindings</title>
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>
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
2906 <programlisting role="C">
2907 GTK_WIDGET_UNSET_FLAGS (scrollbar, GTK_CAN_FOCUS);
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>
2918 <!-- ----------------------------------------------------------------- -->
2920 <title>Vertical Range Widgets</title>
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>
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>
2935 <!-- ----------------------------------------------------------------- -->
2937 <title>Horizontal Range Widgets</title>
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>
2950 <!-- ----------------------------------------------------------------- -->
2951 <sect1 id="sec-RangeWidgetsExample">
2952 <title>Example</title>
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>
2961 <programlisting role="C">
2962 <!-- example-start rangewidgets rangewidgets.c -->
2964 #include <gtk/gtk.h>
2966 GtkWidget *hscale, *vscale;
2968 void cb_pos_menu_select( GtkWidget *item,
2969 GtkPositionType pos )
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);
2976 void cb_update_menu_select( GtkWidget *item,
2977 GtkUpdateType policy )
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);
2984 void cb_digits_scale( GtkAdjustment *adj )
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);
2991 void cb_page_size( GtkAdjustment *get,
2992 GtkAdjustment *set )
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");
3003 void cb_draw_value( GtkToggleButton *button )
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);
3011 /* Convenience functions */
3013 GtkWidget *make_menu_item( gchar *name,
3014 GtkSignalFunc callback,
3019 item = gtk_menu_item_new_with_label (name);
3020 gtk_signal_connect (GTK_OBJECT (item), "activate",
3022 gtk_widget_show (item);
3027 void scale_set_default_values( GtkScale *scale )
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);
3036 /* makes the sample window */
3038 void create_range_controls( void )
3041 GtkWidget *box1, *box2, *box3;
3043 GtkWidget *scrollbar;
3044 GtkWidget *separator;
3045 GtkWidget *opt, *menu, *item;
3048 GtkObject *adj1, *adj2;
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),
3055 gtk_window_set_title (GTK_WINDOW (window), "range controls");
3057 box1 = gtk_vbox_new (FALSE, 0);
3058 gtk_container_add (GTK_CONTAINER (window), box1);
3059 gtk_widget_show (box1);
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);
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);
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);
3077 box3 = gtk_vbox_new (FALSE, 10);
3078 gtk_box_pack_start (GTK_BOX (box2), box3, TRUE, TRUE, 0);
3079 gtk_widget_show (box3);
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);
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);
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);
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);
3110 box2 = gtk_hbox_new (FALSE, 10);
3111 gtk_container_set_border_width (GTK_CONTAINER (box2), 10);
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);
3118 opt = gtk_option_menu_new();
3119 menu = gtk_menu_new();
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);
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);
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);
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);
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);
3142 gtk_box_pack_start (GTK_BOX (box1), box2, TRUE, TRUE, 0);
3143 gtk_widget_show (box2);
3145 box2 = gtk_hbox_new (FALSE, 10);
3146 gtk_container_set_border_width (GTK_CONTAINER (box2), 10);
3148 /* Yet another option menu, this time for the update policy of the
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);
3154 opt = gtk_option_menu_new();
3155 menu = gtk_menu_new();
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);
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);
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);
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);
3176 gtk_box_pack_start (GTK_BOX (box1), box2, TRUE, TRUE, 0);
3177 gtk_widget_show (box2);
3179 box2 = gtk_hbox_new (FALSE, 10);
3180 gtk_container_set_border_width (GTK_CONTAINER (box2), 10);
3182 /* An HScale widget for adjusting the number of digits on the
3184 label = gtk_label_new ("Scale Digits:");
3185 gtk_box_pack_start (GTK_BOX (box2), label, FALSE, FALSE, 0);
3186 gtk_widget_show (label);
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);
3196 gtk_box_pack_start (GTK_BOX (box1), box2, TRUE, TRUE, 0);
3197 gtk_widget_show (box2);
3199 box2 = gtk_hbox_new (FALSE, 10);
3200 gtk_container_set_border_width (GTK_CONTAINER (box2), 10);
3202 /* And, one last HScale widget for adjusting the page size of the
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);
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);
3216 gtk_box_pack_start (GTK_BOX (box1), box2, TRUE, TRUE, 0);
3217 gtk_widget_show (box2);
3219 separator = gtk_hseparator_new ();
3220 gtk_box_pack_start (GTK_BOX (box1), separator, FALSE, TRUE, 0);
3221 gtk_widget_show (separator);
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);
3228 button = gtk_button_new_with_label ("Quit");
3229 gtk_signal_connect_object (GTK_OBJECT (button), "clicked",
3230 GTK_SIGNAL_FUNC(gtk_main_quit),
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);
3237 gtk_widget_show (window);
3243 gtk_init(&argc, &argv);
3245 create_range_controls();
3252 <!-- example-end -->
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
3264 <!-- ***************************************************************** -->
3265 <chapter id="ch-MiscWidgets">
3266 <title>Miscellaneous Widgets</title>
3268 <!-- ----------------------------------------------------------------- -->
3269 <sect1 id="sec-Labels">
3270 <title>Labels</title>
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>
3277 <para>To create a new label, use:</para>
3279 <programlisting role="C">
3280 GtkWidget *gtk_label_new( char *str );
3283 <para>The sole argument is the string you wish the label to display.</para>
3285 <para>To change the label's text after creation, use the function:</para>
3287 <programlisting role="C">
3288 void gtk_label_set_text( GtkLabel *label,
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>
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>
3299 <para>To retrieve the current string, use:</para>
3301 <programlisting role="C">
3302 void gtk_label_get( GtkLabel *label,
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>
3310 <para>The label text can be justified using:</para>
3312 <programlisting role="C">
3313 void gtk_label_set_justify( GtkLabel *label,
3314 GtkJustification jtype );
3317 <para>Values for <literal>jtype</literal> are:</para>
3318 <programlisting role="C">
3321 GTK_JUSTIFY_CENTER (the default)
3325 <para>The label widget is also capable of line wrapping the text
3326 automatically. This can be activated using:</para>
3328 <programlisting role="C">
3329 void gtk_label_set_line_wrap (GtkLabel *label,
3333 <para>The <literal>wrap</literal> argument takes a TRUE or FALSE value.</para>
3335 <para>If you want your label underlined, then you can set a pattern on the
3338 <programlisting role="C">
3339 void gtk_label_set_pattern (GtkLabel *label,
3340 const gchar *pattern);
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>
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>
3353 <programlisting role="C">
3354 <!-- example-start label label.c -->
3356 #include <gtk/gtk.h>
3361 static GtkWidget *window = NULL;
3367 /* Initialise GTK */
3368 gtk_init(&argc, &argv);
3370 window = gtk_window_new (GTK_WINDOW_TOPLEVEL);
3371 gtk_signal_connect (GTK_OBJECT (window), "destroy",
3372 GTK_SIGNAL_FUNC(gtk_main_quit),
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);
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);
3387 frame = gtk_frame_new ("Multi-line Label");
3388 label = gtk_label_new ("This is a Multi-line label.\nSecond line\n" \
3390 gtk_container_add (GTK_CONTAINER (frame), label);
3391 gtk_box_pack_start (GTK_BOX (vbox), frame, FALSE, FALSE, 0);
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);
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);
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);
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, "\
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);
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);
3449 gtk_widget_show_all (window);
3455 <!-- example-end -->
3460 <!-- ----------------------------------------------------------------- -->
3461 <sect1 id="sec-Arrows">
3462 <title>Arrows</title>
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>
3469 <para>There are only two functions for manipulating an Arrow widget:</para>
3471 <programlisting role="C">
3472 GtkWidget *gtk_arrow_new( GtkArrowType arrow_type,
3473 GtkShadowType shadow_type );
3475 void gtk_arrow_set( GtkArrow *arrow,
3476 GtkArrowType arrow_type,
3477 GtkShadowType shadow_type );
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>
3485 <programlisting role="C">
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>
3495 <programlisting role="C">
3497 GTK_SHADOW_OUT (the default)
3498 GTK_SHADOW_ETCHED_IN
3499 GTK_SHADOW_ETCHED_OUT
3502 <para>Here's a brief example to illustrate their use.</para>
3504 <programlisting role="C">
3505 <!-- example-start arrow arrow.c -->
3507 #include <gtk/gtk.h>
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 )
3517 button = gtk_button_new();
3518 arrow = gtk_arrow_new (arrow_type, shadow_type);
3520 gtk_container_add (GTK_CONTAINER (button), arrow);
3522 gtk_widget_show(button);
3523 gtk_widget_show(arrow);
3531 /* GtkWidget is the storage type for widgets */
3536 /* Initialize the toolkit */
3537 gtk_init (&argc, &argv);
3539 /* Create a new window */
3540 window = gtk_window_new (GTK_WINDOW_TOPLEVEL);
3542 gtk_window_set_title (GTK_WINDOW (window), "Arrow Buttons");
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);
3548 /* Sets the border width of the window. */
3549 gtk_container_set_border_width (GTK_CONTAINER (window), 10);
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);
3556 /* Pack and show all our widgets */
3557 gtk_widget_show(box);
3559 button = create_arrow_button(GTK_ARROW_UP, GTK_SHADOW_IN);
3560 gtk_box_pack_start (GTK_BOX (box), button, FALSE, FALSE, 3);
3562 button = create_arrow_button(GTK_ARROW_DOWN, GTK_SHADOW_OUT);
3563 gtk_box_pack_start (GTK_BOX (box), button, FALSE, FALSE, 3);
3565 button = create_arrow_button(GTK_ARROW_LEFT, GTK_SHADOW_ETCHED_IN);
3566 gtk_box_pack_start (GTK_BOX (box), button, FALSE, FALSE, 3);
3568 button = create_arrow_button(GTK_ARROW_RIGHT, GTK_SHADOW_ETCHED_OUT);
3569 gtk_box_pack_start (GTK_BOX (box), button, FALSE, FALSE, 3);
3571 gtk_widget_show (window);
3573 /* Rest in gtk_main and wait for the fun to begin! */
3578 <!-- example-end -->
3583 <!-- ----------------------------------------------------------------- -->
3584 <sect1 id="sec-TheTooltipsObject">
3585 <title>The Tooltips Object</title>
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>
3593 <para>Widgets that do not receive events (widgets that do not have their
3594 own window) will not work with tooltips.</para>
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>
3600 <programlisting role="C">
3601 GtkTooltips *gtk_tooltips_new( void );
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>
3607 <programlisting role="C">
3608 void gtk_tooltips_set_tip( GtkTooltips *tooltips,
3610 const gchar *tip_text,
3611 const gchar *tip_private );
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>
3620 <!-- TODO: sort out what how to do the context sensitive help -->
3622 <para>Here's a short example:</para>
3624 <programlisting role="C">
3625 GtkTooltips *tooltips;
3630 tooltips = gtk_tooltips_new ();
3631 button = gtk_button_new_with_label ("button 1");
3635 gtk_tooltips_set_tip (tooltips, button, "This is button 1", NULL);
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>
3641 <programlisting role="C">
3642 void gtk_tooltips_enable( GtkTooltips *tooltips );
3645 <para>Enable a disabled set of tooltips.</para>
3647 <programlisting role="C">
3648 void gtk_tooltips_disable( GtkTooltips *tooltips );
3651 <para>Disable an enabled set of tooltips.</para>
3653 <programlisting role="C">
3654 void gtk_tooltips_set_delay( GtkTooltips *tooltips,
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>
3662 <programlisting role="C">
3663 void gtk_tooltips_set_colors( GtkTooltips *tooltips,
3664 GdkColor *background,
3665 GdkColor *foreground );
3668 <para>Set the foreground and background color of the tooltips.</para>
3670 <para>And that's all the functions associated with tooltips. More than
3671 you'll ever want to know :-)</para>
3675 <!-- ----------------------------------------------------------------- -->
3676 <sect1 id="sec-ProgressBars">
3677 <title>Progress Bars</title>
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>
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>
3688 <programlisting role="C">
3689 GtkWidget *gtk_progress_bar_new( void );
3691 GtkWidget *gtk_progress_bar_new_with_adjustment( GtkAdjustment *adjustment );
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>
3697 <para>The adjustment of a progress object can be changed dynamically using:</para>
3699 <programlisting role="C">
3700 void gtk_progress_set_adjustment( GtkProgress *progress,
3701 GtkAdjustment *adjustment );
3704 <para>Now that the progress bar has been created we can use it.</para>
3706 <programlisting role="C">
3707 void gtk_progress_bar_update( GtkProgressBar *pbar,
3708 gfloat percentage );
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>
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>
3720 <para>A progress bar may be set to one of a number of orientations using the
3723 <programlisting role="C">
3724 void gtk_progress_bar_set_orientation( GtkProgressBar *pbar,
3725 GtkProgressBarOrientation orientation );
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>
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
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>
3744 <para>The style of a progress bar can be set using the following function.</para>
3746 <programlisting role="C">
3747 void gtk_progress_bar_set_bar_style( GtkProgressBar *pbar,
3748 GtkProgressBarStyle style );
3751 <para>The <literal>style</literal> parameter can take one of two values:</para>
3753 <programlisting role="C">
3754 GTK_PROGRESS_CONTINUOUS
3755 GTK_PROGRESS_DISCRETE
3758 <para>The number of discrete blocks can be set by calling</para>
3760 <programlisting role="C">
3761 void gtk_progress_bar_set_discrete_blocks( GtkProgressBar *pbar,
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>
3772 <programlisting role="C">
3773 void gtk_progress_set_activity_mode( GtkProgress *progress,
3774 guint activity_mode );
3777 <para>The step size of the activity indicator, and the number of blocks are
3778 set using the following functions.</para>
3780 <programlisting role="C">
3781 void gtk_progress_bar_set_activity_step( GtkProgressBar *pbar,
3784 void gtk_progress_bar_set_activity_blocks( GtkProgressBar *pbar,
3788 <para>When in continuous mode, the progress bar can also display a
3789 configurable text string within its trough, using the following
3792 <programlisting role="C">
3793 void gtk_progress_set_format_string( GtkProgress *progress,
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>
3802 <listitem><simpara> %p - percentage</simpara>
3804 <listitem><simpara> %v - value</simpara>
3806 <listitem><simpara> %l - lower range value</simpara>
3808 <listitem><simpara> %u - upper range value</simpara>
3812 <para>The displaying of this text string can be toggled using:</para>
3814 <programlisting role="C">
3815 void gtk_progress_set_show_text( GtkProgress *progress,
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>
3822 <programlisting role="C">
3823 void gtk_progress_set_text_alignment( GtkProgress *progress,
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>
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
3841 <programlisting role="C">
3842 gchar *gtk_progress_get_current_text( GtkProgress *progress );
3844 gchar *gtk_progress_get_text_from_value( GtkProgress *progress,
3848 <para>There is yet another way to change the range and value of a progress
3849 object using the following function:</para>
3851 <programlisting role="C">
3852 void gtk_progress_configure( GtkProgress *progress,
3858 <para>This function provides quite a simple interface to the range and value
3859 of a progress object.</para>
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>
3864 <programlisting role="C">
3865 void gtk_progress_set_percentage( GtkProgress *progress,
3866 gfloat percentage );
3868 void gtk_progress_set_value( GtkProgress *progress,
3871 gfloat gtk_progress_get_value( GtkProgress *progress );
3873 gfloat gtk_progress_get_current_percentage( GtkProgress *progress );
3875 gfloat gtk_progress_get_percentage_from_value( GtkProgress *progress,
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>
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>
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>
3891 <programlisting role="C">
3892 <!-- example-start progressbar progressbar.c -->
3894 #include <gtk/gtk.h>
3896 typedef struct _ProgressData {
3902 /* Update the value of the progress bar so that we get
3904 gint progress_timeout( gpointer data )
3909 /* Calculate the value of the progress bar using the
3910 * value range set in the adjustment object */
3912 new_val = gtk_progress_get_value( GTK_PROGRESS(data) ) + 1;
3914 adj = GTK_PROGRESS (data)->adjustment;
3915 if (new_val > adj->upper)
3916 new_val = adj->lower;
3918 /* Set the new value */
3919 gtk_progress_set_value (GTK_PROGRESS (data), new_val);
3921 /* As this is a timeout function, return TRUE so that it
3922 * continues to get called */
3926 /* Callback that toggles the text display within the progress
3928 void toggle_show_text( GtkWidget *widget,
3929 ProgressData *pdata )
3931 gtk_progress_set_show_text (GTK_PROGRESS (pdata->pbar),
3932 GTK_TOGGLE_BUTTON (widget)->active);
3935 /* Callback that toggles the activity mode of the progress
3937 void toggle_activity_mode( GtkWidget *widget,
3938 ProgressData *pdata )
3940 gtk_progress_set_activity_mode (GTK_PROGRESS (pdata->pbar),
3941 GTK_TOGGLE_BUTTON (widget)->active);
3944 /* Callback that toggles the continuous mode of the progress
3946 void set_continuous_mode( GtkWidget *widget,
3947 ProgressData *pdata )
3949 gtk_progress_bar_set_bar_style (GTK_PROGRESS_BAR (pdata->pbar),
3950 GTK_PROGRESS_CONTINUOUS);
3953 /* Callback that toggles the discrete mode of the progress
3955 void set_discrete_mode( GtkWidget *widget,
3956 ProgressData *pdata )
3958 gtk_progress_bar_set_bar_style (GTK_PROGRESS_BAR (pdata->pbar),
3959 GTK_PROGRESS_DISCRETE);
3962 /* Clean up allocated memory and remove the timer */
3963 void destroy_progress( GtkWidget *widget,
3964 ProgressData *pdata)
3966 gtk_timeout_remove (pdata->timer);
3968 pdata->window = NULL;
3976 ProgressData *pdata;
3978 GtkWidget *separator;
3985 gtk_init (&argc, &argv);
3987 /* Allocate memory for the data that is passwd to the callbacks */
3988 pdata = g_malloc( sizeof(ProgressData) );
3990 pdata->window = gtk_window_new (GTK_WINDOW_TOPLEVEL);
3991 gtk_window_set_policy (GTK_WINDOW (pdata->window), FALSE, FALSE, TRUE);
3993 gtk_signal_connect (GTK_OBJECT (pdata->window), "destroy",
3994 GTK_SIGNAL_FUNC (destroy_progress),
3996 gtk_window_set_title (GTK_WINDOW (pdata->window), "GtkProgressBar");
3997 gtk_container_set_border_width (GTK_CONTAINER (pdata->window), 0);
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);
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);
4009 /* Create a Adjusment object to hold the range of the
4011 adj = (GtkAdjustment *) gtk_adjustment_new (0, 1, 150, 0, 0, 0);
4013 /* Create the GtkProgressBar using the adjustment */
4014 pdata->pbar = gtk_progress_bar_new_with_adjustment (adj);
4016 /* Set the format of the string that can be displayed in the
4017 * trough of the progress bar:
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);
4027 /* Add a timer callback to update the value of the progress bar */
4028 pdata->timer = gtk_timeout_add (100, progress_timeout, pdata->pbar);
4030 separator = gtk_hseparator_new ();
4031 gtk_box_pack_start (GTK_BOX (vbox), separator, FALSE, FALSE, 0);
4032 gtk_widget_show(separator);
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);
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,
4044 gtk_signal_connect (GTK_OBJECT (check), "clicked",
4045 GTK_SIGNAL_FUNC (toggle_show_text),
4047 gtk_widget_show(check);
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,
4054 gtk_signal_connect (GTK_OBJECT (check), "clicked",
4055 GTK_SIGNAL_FUNC (toggle_activity_mode),
4057 gtk_widget_show(check);
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,
4063 gtk_widget_show(separator);
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,
4070 gtk_signal_connect (GTK_OBJECT (button), "clicked",
4071 GTK_SIGNAL_FUNC (set_continuous_mode),
4073 gtk_widget_show (button);
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)),
4079 gtk_table_attach (GTK_TABLE (table), button, 2, 3, 1, 2,
4080 GTK_EXPAND | GTK_FILL, GTK_EXPAND | GTK_FILL,
4082 gtk_signal_connect (GTK_OBJECT (button), "clicked",
4083 GTK_SIGNAL_FUNC (set_discrete_mode),
4085 gtk_widget_show (button);
4087 separator = gtk_hseparator_new ();
4088 gtk_box_pack_start (GTK_BOX (vbox), separator, FALSE, FALSE, 0);
4089 gtk_widget_show(separator);
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);
4098 /* This makes it so the button is the default. */
4099 GTK_WIDGET_SET_FLAGS (button, GTK_CAN_DEFAULT);
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);
4106 gtk_widget_show (pdata->window);
4112 <!-- example-end -->
4117 <!-- ----------------------------------------------------------------- -->
4118 <sect1 id="sec-Dialogs">
4119 <title>Dialogs</title>
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>
4124 <programlisting role="C">
4130 GtkWidget *action_area;
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>
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>
4142 <programlisting role="C">
4143 GtkWidget *gtk_dialog_new( void );
4146 <para>So to create a new dialog box, use,</para>
4148 <programlisting role="C">
4150 window = gtk_dialog_new ();
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>
4156 <programlisting role="C">
4158 gtk_box_pack_start (GTK_BOX (GTK_DIALOG (window)->action_area),
4159 button, TRUE, TRUE, 0);
4160 gtk_widget_show (button);
4163 <para>And you could add to the vbox area by packing, for instance, a label
4164 in it, try something like this:</para>
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);
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>
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>
4187 <!-- ----------------------------------------------------------------- -->
4188 <sect1 id="sec-Pixmaps">
4189 <title>Pixmaps</title>
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>
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>
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>
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>
4218 <programlisting role="C">
4219 GdkPixmap *gdk_bitmap_create_from_data( GdkWindow *window,
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>
4231 <programlisting role="C">
4232 GdkPixmap *gdk_pixmap_create_from_data( GdkWindow *window,
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>
4245 <programlisting role="C">
4246 GdkPixmap *gdk_pixmap_create_from_xpm( GdkWindow *window,
4248 GdkColor *transparent_color,
4249 const gchar *filename );
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>
4260 <programlisting role="C">
4261 GdkPixmap *gdk_pixmap_create_from_xpm_d( GdkWindow *window,
4263 GdkColor *transparent_color,
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>
4271 <programlisting role="C">
4273 static const char * xpm_data[] = {
4276 ". c #000000000000",
4277 "X c #FFFFFFFFFFFF",
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>
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
4307 <programlisting role="C">
4308 GtkWidget *gtk_pixmap_new( GdkPixmap *pixmap,
4312 <para>The other pixmap widget calls are</para>
4314 <programlisting role="C">
4315 guint gtk_pixmap_get_type( void );
4317 void gtk_pixmap_set( GtkPixmap *pixmap,
4321 void gtk_pixmap_get( GtkPixmap *pixmap,
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>
4329 <para>The following is an example of using a pixmap in a button.</para>
4331 <programlisting role="C">
4332 <!-- example-start pixmap pixmap.c -->
4334 #include <gtk/gtk.h>
4337 /* XPM data of Open-File icon */
4338 static const char * xpm_data[] = {
4341 ". c #000000000000",
4342 "X c #FFFFFFFFFFFF",
4361 /* when invoked (via signal delete_event), terminates the application.
4363 gint close_application( GtkWidget *widget,
4372 /* is invoked when the button is clicked. It just prints a message.
4374 void button_clicked( GtkWidget *widget,
4376 g_print( "button clicked\n" );
4382 /* GtkWidget is the storage type for widgets */
4383 GtkWidget *window, *pixmapwid, *button;
4388 /* create the main window, and attach delete_event signal to terminating
4390 gtk_init( &argc, &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 );
4397 /* now for the pixmap from gdk */
4398 style = gtk_widget_get_style( window );
4399 pixmap = gdk_pixmap_create_from_xpm_d( window->window, &mask,
4400 &style->bg[GTK_STATE_NORMAL],
4401 (gchar **)xpm_data );
4403 /* a pixmap widget to contain the pixmap */
4404 pixmapwid = gtk_pixmap_new( pixmap, mask );
4405 gtk_widget_show( pixmapwid );
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 );
4413 gtk_signal_connect( GTK_OBJECT(button), "clicked",
4414 GTK_SIGNAL_FUNC(button_clicked), NULL );
4416 /* show the window */
4421 <!-- example-end -->
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>
4427 <programlisting role="C">
4428 /* load a pixmap from a file */
4429 pixmap = gdk_pixmap_create_from_xpm( window->window, &mask,
4430 &style->bg[GTK_STATE_NORMAL],
4432 pixmapwid = gtk_pixmap_new( pixmap, mask );
4433 gtk_widget_show( pixmapwid );
4434 gtk_container_add( GTK_CONTAINER(window), pixmapwid );
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>
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
4449 <programlisting role="C">
4450 <!-- example-start wheelbarrow wheelbarrow.c -->
4452 #include <gtk/gtk.h>
4455 static char * WheelbarrowFull_xpm[] = {
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 "& 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",
4529 "ty> 459@>+&& ",
4530 "$2u+ ><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..&wn> ",
4535 " Oh$@mO *3dthwlsslszjzxxxxxxx3:td8M4 ",
4536 " Oh$@g& *3d$XNlvvvlllm,mNwxxxxxxxfa.:,B* ",
4537 " Oh$@,Od.czlllllzlmmqV@V#V@fxxxxxxxf:%j5& ",
4538 " Oh$1hd5lllslllCCZrV#r#:#2AxxxxxxxxxcdwM* ",
4539 " OXq6c.%8vvvllZZiqqApA:mq:Xxcpcxxxxxfdc9* ",
4540 " 2r<6gde3bllZZrVi7S@SV77A::qApxxxxxxfdcM ",
4541 " :,q-6MN.dfmZZrrSS:#riirDSAX@Af5xxxxxfevo",
4542 " +A26jguXtAZZZC7iDiCCrVVii7Cmmmxxxxxx%3g",
4543 " *#16jszN..3DZZZZrCVSA2rZrV7Dmmwxxxx&en",
4544 " p2yFvzssXe:fCZZCiiD7iiZDiDSSZwwxx8e*>",
4545 " OA1<jzxwwc:$d%NDZZZZCCCZCCZZCmxxfd.B ",
4546 " 3206Bwxxszx%et.eaAp77m77mmmf3&eeeg* ",
4547 " @26MvzxNzvlbwfpdettttttttttt.c,n& ",
4548 " *;16=lsNwwNwgsvslbwwvccc3pcfu<o ",
4549 " p;<69BvwwsszslllbBlllllllu<5+ ",
4550 " OS0y6FBlvvvzvzss,u=Blllj=54 ",
4551 " c1-699Blvlllllu7k96MMMg4 ",
4552 " *10y8n6FjvllllB<166668 ",
4553 " S-kg+>666<M<996-y6n<8* ",
4554 " p71=4 m69996kD8Z-66698&& ",
4555 " &i0ycm6n4 ogk17,0<6666g ",
4556 " N-k-<> >=01-kuu666> ",
4557 " ,6ky& &46-10ul,66, ",
4558 " Ou0<> o66y<ulw<66& ",
4559 " *kk5 >66By7=xu664 ",
4560 " <<M4 466lj<Mxu66o ",
4561 " *>> +66uv,zN666* ",
4571 /* When invoked (via signal delete_event), terminates the application */
4572 gint close_application( GtkWidget *widget,
4583 /* GtkWidget is the storage type for widgets */
4584 GtkWidget *window, *pixmap, *fixed;
4585 GdkPixmap *gdk_pixmap;
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 (&argc, &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);
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, &mask,
4603 &style->bg[GTK_STATE_NORMAL],
4604 WheelbarrowFull_xpm );
4605 pixmap = gtk_pixmap_new( gdk_pixmap, mask );
4606 gtk_widget_show( pixmap );
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 );
4615 /* This masks out everything except for the image itself */
4616 gtk_widget_shape_combine_mask( window, mask, 0, 0 );
4618 /* show the window */
4619 gtk_widget_set_uposition( window, 20, 400 );
4620 gtk_widget_show( window );
4625 <!-- example-end -->
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>
4633 <programlisting role="C">
4634 gtk_widget_set_events( window,
4635 gtk_widget_get_events( window ) |
4636 GDK_BUTTON_PRESS_MASK );
4638 gtk_signal_connect( GTK_OBJECT(window), "button_press_event",
4639 GTK_SIGNAL_FUNC(close_application), NULL );
4644 <!-- ----------------------------------------------------------------- -->
4645 <sect1 id="sec-Rulers">
4646 <title>Rulers</title>
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>
4654 <para>A ruler must first be created. Horizontal and vertical rulers are
4655 created using</para>
4657 <programlisting role="C">
4658 GtkWidget *gtk_hruler_new( void ); /* horizontal ruler */
4660 GtkWidget *gtk_vruler_new( void ); /* vertical ruler */
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>
4667 <programlisting role="C">
4668 void gtk_ruler_set_metric( GtkRuler *ruler,
4669 GtkMetricType metric );
4672 <para>The default measure is <literal>GTK_PIXELS</literal>.</para>
4674 <programlisting role="C">
4675 gtk_ruler_set_metric( GTK_RULER(ruler), GTK_PIXELS );
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>
4682 <programlisting role="C">
4683 void gtk_ruler_set_range( GtkRuler *ruler,
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
4695 <para>A vertical ruler can span an 800 pixel wide window thus</para>
4697 <programlisting role="C">
4698 gtk_ruler_set_range( GTK_RULER(vruler), 0, 800, 0, 800);
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>
4705 <programlisting role="C">
4706 gtk_ruler_set_range( GTK_RULER(vruler), 7, 16, 0, 20);
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>
4715 <programlisting role="C">
4716 #define EVENT_METHOD(i, x) GTK_WIDGET_GET_CLASS(i)->x
4718 gtk_signal_connect_object( GTK_OBJECT(area), "motion_notify_event",
4719 (GtkSignalFunc)EVENT_METHOD(ruler, motion_notify_event),
4720 GTK_OBJECT(ruler) );
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>
4730 <programlisting role="C">
4731 <!-- example-start rulers rulers.c -->
4733 #include <gtk/gtk.h>
4735 #define EVENT_METHOD(i, x) GTK_WIDGET_GET_CLASS(i)->x
4740 /* This routine gets control when the close button is clicked */
4741 gint close_application( GtkWidget *widget,
4749 /* The main routine */
4752 GtkWidget *window, *table, *area, *hrule, *vrule;
4754 /* Initialize GTK and create the main window */
4755 gtk_init( &argc, &argv );
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);
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 );
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 );
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 );
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 );
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 );
4809 <!-- example-end -->
4814 <!-- ----------------------------------------------------------------- -->
4815 <sect1 id="sec-Statusbars">
4816 <title>Statusbars</title>
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>
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>
4829 <para>A statusbar is created with a call to:</para>
4831 <programlisting role="C">
4832 GtkWidget *gtk_statusbar_new( void );
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>
4838 <programlisting role="C">
4839 guint gtk_statusbar_get_context_id( GtkStatusbar *statusbar,
4840 const gchar *context_description );
4843 <para>There are three functions that can operate on statusbars:</para>
4845 <programlisting role="C">
4846 guint gtk_statusbar_push( GtkStatusbar *statusbar,
4850 void gtk_statusbar_pop( GtkStatusbar *statusbar)
4853 void gtk_statusbar_remove( GtkStatusbar *statusbar,
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>
4863 <para>The function gtk_statusbar_pop removes the message highest in the
4864 stack with the given Context Identifier.</para>
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
4870 <programlisting role="C">
4871 <!-- example-start statusbar statusbar.c -->
4873 #include <gtk/gtk.h>
4874 #include <glib.h>
4876 GtkWidget *status_bar;
4878 void push_item( GtkWidget *widget,
4881 static int count = 1;
4884 g_snprintf(buff, 20, "Item %d", count++);
4885 gtk_statusbar_push( GTK_STATUSBAR(status_bar), GPOINTER_TO_INT(data), buff);
4890 void pop_item( GtkWidget *widget,
4893 gtk_statusbar_pop( GTK_STATUSBAR(status_bar), GPOINTER_TO_INT(data) );
4907 gtk_init (&argc, &argv);
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);
4916 vbox = gtk_vbox_new(FALSE, 1);
4917 gtk_container_add(GTK_CONTAINER(window), vbox);
4918 gtk_widget_show(vbox);
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);
4924 context_id = gtk_statusbar_get_context_id(
4925 GTK_STATUSBAR(status_bar), "Statusbar example");
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);
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);
4939 /* always display the window as the last step so it all splashes on
4940 * the screen at once. */
4941 gtk_widget_show(window);
4947 <!-- example-end -->
4952 <!-- ----------------------------------------------------------------- -->
4953 <sect1 id="sec-TextEntries">
4954 <title>Text Entries</title>
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>
4960 <para>There are two functions for creating Entry widgets:</para>
4962 <programlisting role="C">
4963 GtkWidget *gtk_entry_new( void );
4965 GtkWidget *gtk_entry_new_with_max_length( guint16 max );
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>
4971 <para>There are several functions for altering the text which is currently
4972 within the Entry widget.</para>
4974 <programlisting role="C">
4975 void gtk_entry_set_text( GtkEntry *entry,
4976 const gchar *text );
4978 void gtk_entry_append_text( GtkEntry *entry,
4979 const gchar *text );
4981 void gtk_entry_prepend_text( GtkEntry *entry,
4982 const gchar *text );
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>
4990 <para>The next function allows the current insertion point to be set.</para>
4992 <programlisting role="C">
4993 void gtk_entry_set_position( GtkEntry *entry,
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>
5000 <programlisting role="C">
5001 gchar *gtk_entry_get_text( GtkEntry *entry );
5004 <para>The value returned by this function is used internally, and must not
5005 be freed using either free() or g_free()</para>
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>
5010 <programlisting role="C">
5011 void gtk_entry_set_editable( GtkEntry *entry,
5012 gboolean editable );
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>
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>
5023 <programlisting role="C">
5024 void gtk_entry_set_visibility( GtkEntry *entry,
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>
5032 <programlisting role="C">
5033 void gtk_entry_select_region( GtkEntry *entry,
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
5044 <para>The following code is an example of using an Entry widget.</para>
5046 <programlisting role="C">
5047 <!-- example-start entry entry.c -->
5049 #include <stdio.h>
5050 #include <gtk/gtk.h>
5052 void enter_callback( GtkWidget *widget,
5055 const gchar *entry_text;
5056 entry_text = gtk_entry_get_text(GTK_ENTRY(entry));
5057 printf("Entry contents: %s\n", entry_text);
5060 void entry_toggle_editable( GtkWidget *checkbutton,
5063 gtk_entry_set_editable(GTK_ENTRY(entry),
5064 GTK_TOGGLE_BUTTON(checkbutton)->active);
5067 void entry_toggle_visibility( GtkWidget *checkbutton,
5070 gtk_entry_set_visibility(GTK_ENTRY(entry),
5071 GTK_TOGGLE_BUTTON(checkbutton)->active);
5079 GtkWidget *vbox, *hbox;
5084 gtk_init (&argc, &argv);
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);
5093 vbox = gtk_vbox_new (FALSE, 0);
5094 gtk_container_add (GTK_CONTAINER (window), vbox);
5095 gtk_widget_show (vbox);
5097 entry = gtk_entry_new_with_max_length (50);
5098 gtk_signal_connect(GTK_OBJECT(entry), "activate",
5099 GTK_SIGNAL_FUNC(enter_callback),
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);
5108 hbox = gtk_hbox_new (FALSE, 0);
5109 gtk_container_add (GTK_CONTAINER (vbox), hbox);
5110 gtk_widget_show (hbox);
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);
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);
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);
5135 gtk_widget_show(window);
5140 <!-- example-end -->
5145 <!-- ----------------------------------------------------------------- -->
5146 <sect1 id="sec-SpinButtons">
5147 <title>Spin Buttons</title>
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>
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
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>
5166 <para>Recall that an adjustment widget is created with the following
5167 function, which illustrates the information that it holds:</para>
5169 <programlisting role="C">
5170 GtkObject *gtk_adjustment_new( gfloat value,
5173 gfloat step_increment,
5174 gfloat page_increment,
5178 <para>These attributes of an Adjustment are used by the Spin Button in the
5179 following way:</para>
5182 <listitem><simpara> <literal>value</literal>: initial value for the Spin Button</simpara>
5184 <listitem><simpara> <literal>lower</literal>: lower range value</simpara>
5186 <listitem><simpara> <literal>upper</literal>: upper range value</simpara>
5188 <listitem><simpara> <literal>step_increment</literal>: value to increment/decrement when pressing
5189 mouse button 1 on a button</simpara>
5191 <listitem><simpara> <literal>page_increment</literal>: value to increment/decrement when pressing
5192 mouse button 2 on a button</simpara>
5194 <listitem><simpara> <literal>page_size</literal>: unused</simpara>
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>
5202 <programlisting role="C">
5203 GtkWidget *gtk_spin_button_new( GtkAdjustment *adjustment,
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>
5213 <para>A Spin Button can be reconfigured after creation using the following
5216 <programlisting role="C">
5217 void gtk_spin_button_configure( GtkSpinButton *spin_button,
5218 GtkAdjustment *adjustment,
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>
5226 <para>The adjustment can be set and retrieved independantly using the
5227 following two functions:</para>
5229 <programlisting role="C">
5230 void gtk_spin_button_set_adjustment( GtkSpinButton *spin_button,
5231 GtkAdjustment *adjustment );
5233 GtkAdjustment *gtk_spin_button_get_adjustment( GtkSpinButton *spin_button );
5236 <para>The number of decimal places can also be altered using:</para>
5238 <programlisting role="C">
5239 void gtk_spin_button_set_digits( GtkSpinButton *spin_button,
5243 <para>The value that a Spin Button is currently displaying can be changed
5244 using the following function:</para>
5246 <programlisting role="C">
5247 void gtk_spin_button_set_value( GtkSpinButton *spin_button,
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>
5254 <programlisting role="C">
5255 gfloat gtk_spin_button_get_value_as_float( GtkSpinButton *spin_button );
5257 gint gtk_spin_button_get_value_as_int( GtkSpinButton *spin_button );
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>
5263 <programlisting role="C">
5264 void gtk_spin_button_spin( GtkSpinButton *spin_button,
5265 GtkSpinType direction,
5269 <para>The <literal>direction</literal> parameter can take one of the following values:</para>
5271 <programlisting role="C">
5272 GTK_SPIN_STEP_FORWARD
5273 GTK_SPIN_STEP_BACKWARD
5274 GTK_SPIN_PAGE_FORWARD
5275 GTK_SPIN_PAGE_BACKWARD
5278 GTK_SPIN_USER_DEFINED
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>
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>
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>
5293 <para><literal>GTK_SPIN_HOME</literal> sets the value of the Spin Button to the bottom of
5294 the Adjustments range.</para>
5296 <para><literal>GTK_SPIN_END</literal> sets the value of the Spin Button to the top of the
5297 Adjustments range.</para>
5299 <para><literal>GTK_SPIN_USER_DEFINED</literal> simply alters the value of the Spin Button
5300 by the specified amount.</para>
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>
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>
5311 <programlisting role="C">
5312 void gtk_spin_button_set_numeric( GtkSpinButton *spin_button,
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>
5319 <programlisting role="C">
5320 void gtk_spin_button_set_wrap( GtkSpinButton *spin_button,
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
5329 <programlisting role="C">
5330 void gtk_spin_button_set_snap_to_ticks( GtkSpinButton *spin_button,
5331 gboolean snap_to_ticks );
5334 <para>The update policy of a Spin Button can be changed with the following
5337 <programlisting role="C">
5338 void gtk_spin_button_set_update_policy( GtkSpinButton *spin_button,
5339 GtkSpinButtonUpdatePolicy policy );
5342 <para><!-- TODO: find out what this does - TRG --></para>
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>
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
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>
5356 <para>In case of <literal>GTK_UPDATE_ALWAYS</literal> we ignore errors while converting
5357 text into a numeric value.</para>
5359 <para>The appearance of the buttons used in a Spin Button can be changed
5360 using the following function:</para>
5362 <programlisting role="C">
5363 void gtk_spin_button_set_shadow_type( GtkSpinButton *spin_button,
5364 GtkShadowType shadow_type );
5367 <para>As usual, the <literal>shadow_type</literal> can be one of:</para>
5369 <programlisting role="C">
5372 GTK_SHADOW_ETCHED_IN
5373 GTK_SHADOW_ETCHED_OUT
5376 <para>Finally, you can explicitly request that a Spin Button update itself:</para>
5378 <programlisting role="C">
5379 void gtk_spin_button_update( GtkSpinButton *spin_button );
5382 <para>It's example time again.</para>
5384 <programlisting role="C">
5385 <!-- example-start spinbutton spinbutton.c -->
5387 #include <stdio.h>
5388 #include <gtk/gtk.h>
5390 static GtkWidget *spinner1;
5392 void toggle_snap( GtkWidget *widget,
5393 GtkSpinButton *spin )
5395 gtk_spin_button_set_snap_to_ticks (spin, GTK_TOGGLE_BUTTON (widget)->active);
5398 void toggle_numeric( GtkWidget *widget,
5399 GtkSpinButton *spin )
5401 gtk_spin_button_set_numeric (spin, GTK_TOGGLE_BUTTON (widget)->active);
5404 void change_digits( GtkWidget *widget,
5405 GtkSpinButton *spin )
5407 gtk_spin_button_set_digits (GTK_SPIN_BUTTON (spinner1),
5408 gtk_spin_button_get_value_as_int (spin));
5411 void get_value( GtkWidget *widget,
5416 GtkSpinButton *spin;
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));
5423 sprintf (buf, "%0.*f", spin->digits,
5424 gtk_spin_button_get_value_as_float (spin));
5425 gtk_label_set_text (label, buf);
5435 GtkWidget *main_vbox;
5438 GtkWidget *spinner2;
5442 GtkWidget *val_label;
5445 /* Initialise GTK */
5446 gtk_init(&argc, &argv);
5448 window = gtk_window_new (GTK_WINDOW_TOPLEVEL);
5450 gtk_signal_connect (GTK_OBJECT (window), "destroy",
5451 GTK_SIGNAL_FUNC (gtk_main_quit),
5454 gtk_window_set_title (GTK_WINDOW (window), "Spin Button");
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);
5460 frame = gtk_frame_new ("Not accelerated");
5461 gtk_box_pack_start (GTK_BOX (main_vbox), frame, TRUE, TRUE, 0);
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);
5467 /* Day, month, year spinners */
5469 hbox = gtk_hbox_new (FALSE, 0);
5470 gtk_box_pack_start (GTK_BOX (vbox), hbox, TRUE, TRUE, 5);
5472 vbox2 = gtk_vbox_new (FALSE, 0);
5473 gtk_box_pack_start (GTK_BOX (hbox), vbox2, TRUE, TRUE, 5);
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);
5479 adj = (GtkAdjustment *) gtk_adjustment_new (1.0, 1.0, 31.0, 1.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);
5485 vbox2 = gtk_vbox_new (FALSE, 0);
5486 gtk_box_pack_start (GTK_BOX (hbox), vbox2, TRUE, TRUE, 5);
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);
5492 adj = (GtkAdjustment *) gtk_adjustment_new (1.0, 1.0, 12.0, 1.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);
5498 vbox2 = gtk_vbox_new (FALSE, 0);
5499 gtk_box_pack_start (GTK_BOX (hbox), vbox2, TRUE, TRUE, 5);
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);
5505 adj = (GtkAdjustment *) gtk_adjustment_new (1998.0, 0.0, 2100.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);
5512 frame = gtk_frame_new ("Accelerated");
5513 gtk_box_pack_start (GTK_BOX (main_vbox), frame, TRUE, TRUE, 0);
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);
5519 hbox = gtk_hbox_new (FALSE, 0);
5520 gtk_box_pack_start (GTK_BOX (vbox), hbox, FALSE, TRUE, 5);
5522 vbox2 = gtk_vbox_new (FALSE, 0);
5523 gtk_box_pack_start (GTK_BOX (hbox), vbox2, TRUE, TRUE, 5);
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);
5529 adj = (GtkAdjustment *) gtk_adjustment_new (0.0, -10000.0, 10000.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);
5536 vbox2 = gtk_vbox_new (FALSE, 0);
5537 gtk_box_pack_start (GTK_BOX (hbox), vbox2, TRUE, TRUE, 5);
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);
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);
5551 hbox = gtk_hbox_new (FALSE, 0);
5552 gtk_box_pack_start (GTK_BOX (vbox), hbox, FALSE, TRUE, 5);
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),
5558 gtk_box_pack_start (GTK_BOX (vbox), button, TRUE, TRUE, 0);
5559 gtk_toggle_button_set_active (GTK_TOGGLE_BUTTON (button), TRUE);
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),
5565 gtk_box_pack_start (GTK_BOX (vbox), button, TRUE, TRUE, 0);
5566 gtk_toggle_button_set_active (GTK_TOGGLE_BUTTON (button), TRUE);
5568 val_label = gtk_label_new ("");
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);
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);
5586 gtk_box_pack_start (GTK_BOX (vbox), val_label, TRUE, TRUE, 0);
5587 gtk_label_set_text (GTK_LABEL (val_label), "0");
5589 hbox = gtk_hbox_new (FALSE, 0);
5590 gtk_box_pack_start (GTK_BOX (main_vbox), hbox, FALSE, TRUE, 0);
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);
5598 gtk_widget_show_all (window);
5600 /* Enter the event loop */
5605 <!-- example-end -->
5610 <!-- ----------------------------------------------------------------- -->
5611 <sect1 id="sec-ComboBox">
5612 <title>Combo Box</title>
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>
5620 <para>The following extract from the structure that defines a Combo Box
5621 identifies several of the components:</para>
5623 <programlisting role="C">
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>
5637 <para>First off, to create a combo box, use:</para>
5639 <programlisting role="C">
5640 GtkWidget *gtk_combo_new( void );
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>
5646 <programlisting role="C">
5647 gtk_entry_set_text(GTK_ENTRY(GTK_COMBO(combo)->entry), "My String.");
5650 <para>To set the values in the popdown list, one uses the function:</para>
5652 <programlisting role="C">
5653 void gtk_combo_set_popdown_strings( GtkCombo *combo,
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>
5663 <programlisting role="C">
5664 GList *g_list_append( GList *glist,
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>
5672 <para>Here's a typical code segment for creating a set of options:</para>
5674 <programlisting role="C">
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");
5682 gtk_combo_set_popdown_strings( GTK_COMBO(combo), glist) ;
5684 /* can free glist now, combo takes a copy */
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>
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>
5695 <programlisting role="C">
5696 void gtk_combo_set_use_arrows( GtkCombo *combo,
5699 void gtk_combo_set_use_arrows_always( GtkCombo *combo,
5702 void gtk_combo_set_case_sensitive( GtkCombo *combo,
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>
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>
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>
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>
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>
5746 <programlisting role="C">
5747 gtk_signal_connect(GTK_OBJECT(GTK_COMB(combo)->entry), "activate",
5748 GTK_SIGNAL_FUNC (my_callback_function), my_data);
5751 <para>Getting the text at any arbitrary time is accomplished by simply using
5752 the entry function:</para>
5754 <programlisting role="C">
5755 gchar *gtk_entry_get_text(GtkEntry *entry);
5758 <para>Such as:</para>
5760 <programlisting role="C">
5763 string = gtk_entry_get_text(GTK_ENTRY(GTK_COMBO(combo)->entry));
5766 <para>That's about all there is to it. There is a function</para>
5768 <programlisting role="C">
5769 void gtk_combo_disable_activate(GtkCombo *combo);
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
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.
5784 <!-- ----------------------------------------------------------------- -->
5785 <sect1 id="sec-Calendar">
5786 <title>Calendar</title>
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>
5792 <para>Creating a GtkCalendar widget is a simple as: </para>
5794 <programlisting role="C">
5795 GtkWidget *gtk_calendar_new();
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>
5803 <programlisting role="C">
5804 void gtk_calendar_freeze( GtkCalendar *Calendar );
5806 void gtk_calendar_thaw ( GtkCalendar *Calendar );
5809 <para>They work just like the freeze/thaw functions of every other
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>
5815 <programlisting role="C">
5816 void gtk_calendar_display_options( GtkCalendar *calendar,
5817 GtkCalendarDisplayOptions flags );
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>
5824 <listitem><simpara> GTK_CALENDAR_SHOW_HEADING - this option specifies that
5825 the month and year should be shown when drawing the calendar.</simpara>
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>
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
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>
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>
5852 <para>The following functions are used to set the the currently displayed
5855 <programlisting role="C">
5856 gint gtk_calendar_select_month( GtkCalendar *calendar,
5860 void gtk_calendar_select_day( GtkCalendar *calendar,
5864 <para>The return value from <literal>gtk_calendar_select_month()</literal> is a boolean
5865 value indicating whether the selection was successful.</para>
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>
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
5876 <programlisting role="C">
5877 gint gtk_calendar_mark_day( GtkCalendar *calendar,
5880 gint gtk_calendar_unmark_day( GtkCalendar *calendar,
5883 void gtk_calendar_clear_marks( GtkCalendar *calendar);
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>
5892 <programlisting role="C">
5893 GtkCalendar *calendar;
5894 calendar = gtk_calendar_new();
5898 /* Is day 7 marked? */
5899 if (calendar->marked_date[7-1])
5903 <para>Note that marks are persistent across month and year changes.</para>
5905 <para>The final Calendar widget function is used to retrieve the currently
5906 selected date, month and/or year.</para>
5908 <programlisting role="C">
5909 void gtk_calendar_get_date( GtkCalendar *calendar,
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>
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,
5924 <listitem><simpara> <literal>month_changed</literal></simpara>
5926 <listitem><simpara> <literal>day_selected</literal></simpara>
5928 <listitem><simpara> <literal>day_selected_double_click</literal></simpara>
5930 <listitem><simpara> <literal>prev_month</literal></simpara>
5932 <listitem><simpara> <literal>next_month</literal></simpara>
5934 <listitem><simpara> <literal>prev_year</literal></simpara>
5936 <listitem><simpara> <literal>next_year</literal></simpara>
5940 <para>That just leaves us with the need to put all of this together into
5941 example code.</para>
5943 <programlisting role="C">
5944 <!-- example-start calendar calendar.c -->
5946 * Copyright (C) 1998 Cesar Miquel, Shawn T. Amundson, Mattias Grönlund
5947 * Copyright (C) 2000 Tony Gale
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.
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.
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.
5964 #include <gtk/gtk.h>
5965 #include <stdio.h>
5966 #include <string.h>
5967 #include <time.h>
5970 #define DEF_PAD_SMALL 5
5972 #define TM_YEAR_BASE 1900
5974 typedef struct _CalendarData {
5975 GtkWidget *flag_checkboxes[5];
5976 gboolean settings[5];
5978 GtkWidget *font_dialog;
5980 GtkWidget *prev2_sig;
5981 GtkWidget *prev_sig;
5982 GtkWidget *last_sig;
5987 calendar_show_header,
5989 calendar_month_change,
5991 calendar_monday_first
5998 void calendar_date_to_string( CalendarData *data,
6005 memset (&tm, 0, sizeof (tm));
6006 gtk_calendar_get_date (GTK_CALENDAR(data->window),
6007 &tm.tm_year, &tm.tm_mon, &tm.tm_mday);
6008 tm.tm_year -= TM_YEAR_BASE;
6009 time = mktime(&tm);
6010 strftime (buffer, buff_len-1, "%x", gmtime(&time));
6013 void calendar_set_signal_strings( char *sig_str,
6018 gtk_label_get (GTK_LABEL (data->prev_sig), &prev_sig);
6019 gtk_label_set (GTK_LABEL (data->prev2_sig), prev_sig);
6021 gtk_label_get (GTK_LABEL (data->last_sig), &prev_sig);
6022 gtk_label_set (GTK_LABEL (data->prev_sig), prev_sig);
6023 gtk_label_set (GTK_LABEL (data->last_sig), sig_str);
6026 void calendar_month_changed( GtkWidget *widget,
6027 CalendarData *data )
6029 char buffer[256] = "month_changed: ";
6031 calendar_date_to_string (data, buffer+15, 256-15);
6032 calendar_set_signal_strings (buffer, data);
6035 void calendar_day_selected( GtkWidget *widget,
6036 CalendarData *data )
6038 char buffer[256] = "day_selected: ";
6040 calendar_date_to_string (data, buffer+14, 256-14);
6041 calendar_set_signal_strings (buffer, data);
6044 void calendar_day_selected_double_click( GtkWidget *widget,
6045 CalendarData *data )
6048 char buffer[256] = "day_selected_double_click: ";
6050 calendar_date_to_string (data, buffer+27, 256-27);
6051 calendar_set_signal_strings (buffer, data);
6053 memset (&tm, 0, sizeof (tm));
6054 gtk_calendar_get_date (GTK_CALENDAR(data->window),
6055 &tm.tm_year, &tm.tm_mon, &tm.tm_mday);
6056 tm.tm_year -= TM_YEAR_BASE;
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);
6061 gtk_calendar_unmark_day(GTK_CALENDAR(data->window),tm.tm_mday);
6065 void calendar_prev_month( GtkWidget *widget,
6066 CalendarData *data )
6068 char buffer[256] = "prev_month: ";
6070 calendar_date_to_string (data, buffer+12, 256-12);
6071 calendar_set_signal_strings (buffer, data);
6074 void calendar_next_month( GtkWidget *widget,
6075 CalendarData *data )
6077 char buffer[256] = "next_month: ";
6079 calendar_date_to_string (data, buffer+12, 256-12);
6080 calendar_set_signal_strings (buffer, data);
6083 void calendar_prev_year( GtkWidget *widget,
6084 CalendarData *data )
6086 char buffer[256] = "prev_year: ";
6088 calendar_date_to_string (data, buffer+11, 256-11);
6089 calendar_set_signal_strings (buffer, data);
6092 void calendar_next_year( GtkWidget *widget,
6093 CalendarData *data )
6095 char buffer[256] = "next_year: ";
6097 calendar_date_to_string (data, buffer+11, 256-11);
6098 calendar_set_signal_strings (buffer, data);
6102 void calendar_set_flags( CalendarData *calendar )
6107 if (calendar->settings[i])
6109 options=options + (1<<i);
6111 if (calendar->window)
6112 gtk_calendar_display_options (GTK_CALENDAR (calendar->window), options);
6115 void calendar_toggle_flag( GtkWidget *toggle,
6116 CalendarData *calendar )
6122 if (calendar->flag_checkboxes[i] == toggle)
6125 calendar->settings[j]=!calendar->settings[j];
6126 calendar_set_flags(calendar);
6130 void calendar_font_selection_ok( GtkWidget *button,
6131 CalendarData *calendar )
6136 calendar->font = gtk_font_selection_dialog_get_font_name(
6137 GTK_FONT_SELECTION_DIALOG (calendar->font_dialog));
6138 if (calendar->window)
6140 font = gtk_font_selection_dialog_get_font(GTK_FONT_SELECTION_DIALOG(calendar->font_dialog));
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);
6150 void calendar_select_font( GtkWidget *button,
6151 CalendarData *calendar )
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;
6160 gtk_window_position (GTK_WINDOW (window), GTK_WIN_POS_MOUSE);
6162 gtk_signal_connect (GTK_OBJECT (window), "destroy",
6163 GTK_SIGNAL_FUNC (gtk_widget_destroyed),
6164 &calendar->font_dialog);
6166 gtk_signal_connect (GTK_OBJECT (GTK_FONT_SELECTION_DIALOG (window)->ok_button),
6167 "clicked", GTK_SIGNAL_FUNC(calendar_font_selection_ok),
6169 gtk_signal_connect_object (GTK_OBJECT (GTK_FONT_SELECTION_DIALOG (window)->cancel_button),
6171 GTK_SIGNAL_FUNC (gtk_widget_destroy),
6172 GTK_OBJECT (calendar->font_dialog));
6174 window=calendar->font_dialog;
6175 if (!GTK_WIDGET_VISIBLE (window))
6176 gtk_widget_show (window);
6178 gtk_widget_destroy (window);
6182 void create_calendar()
6185 GtkWidget *vbox, *vbox2, *vbox3;
6188 GtkWidget *calendar;
6192 GtkWidget *separator;
6195 static CalendarData calendar_data;
6203 { "Show Day Names" },
6204 { "No Month Change" },
6205 { "Show Week Numbers" },
6206 { "Week Start Monday" }
6210 calendar_data.window = NULL;
6211 calendar_data.font = NULL;
6212 calendar_data.font_dialog = NULL;
6214 for (i=0; i<5; i++) {
6215 calendar_data.settings[i]=0;
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),
6224 gtk_signal_connect(GTK_OBJECT(window), "delete-event",
6225 GTK_SIGNAL_FUNC(gtk_false),
6228 gtk_window_set_policy(GTK_WINDOW(window), FALSE, FALSE, TRUE);
6230 vbox = gtk_vbox_new(FALSE, DEF_PAD);
6231 gtk_container_add (GTK_CONTAINER (window), vbox);
6234 * The top part of the window, Calendar, flags and fontsel.
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);
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(&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 &calendar_data);
6255 gtk_signal_connect (GTK_OBJECT (calendar), "day_selected",
6256 GTK_SIGNAL_FUNC (calendar_day_selected),
6257 &calendar_data);
6258 gtk_signal_connect (GTK_OBJECT (calendar), "day_selected_double_click",
6259 GTK_SIGNAL_FUNC (calendar_day_selected_double_click),
6260 &calendar_data);
6261 gtk_signal_connect (GTK_OBJECT (calendar), "prev_month",
6262 GTK_SIGNAL_FUNC (calendar_prev_month),
6263 &calendar_data);
6264 gtk_signal_connect (GTK_OBJECT (calendar), "next_month",
6265 GTK_SIGNAL_FUNC (calendar_next_month),
6266 &calendar_data);
6267 gtk_signal_connect (GTK_OBJECT (calendar), "prev_year",
6268 GTK_SIGNAL_FUNC (calendar_prev_year),
6269 &calendar_data);
6270 gtk_signal_connect (GTK_OBJECT (calendar), "next_year",
6271 GTK_SIGNAL_FUNC (calendar_next_year),
6272 &calendar_data);
6275 separator = gtk_vseparator_new ();
6276 gtk_box_pack_start (GTK_BOX (hbox), separator, FALSE, TRUE, 0);
6278 vbox2 = gtk_vbox_new(FALSE, DEF_PAD);
6279 gtk_box_pack_start(GTK_BOX(hbox), vbox2, FALSE, FALSE, DEF_PAD);
6281 /* Build the Right frame with the flags in */
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);
6288 for (i = 0; i < 5; i++)
6290 toggle = gtk_check_button_new_with_label(flags[i].label);
6291 gtk_signal_connect (GTK_OBJECT (toggle),
6293 GTK_SIGNAL_FUNC(calendar_toggle_flag),
6294 &calendar_data);
6295 gtk_box_pack_start (GTK_BOX (vbox3), toggle, TRUE, TRUE, 0);
6296 calendar_data.flag_checkboxes[i]=toggle;
6298 /* Build the right font-button */
6299 button = gtk_button_new_with_label("Font...");
6300 gtk_signal_connect (GTK_OBJECT (button),
6302 GTK_SIGNAL_FUNC(calendar_select_font),
6303 &calendar_data);
6304 gtk_box_pack_start (GTK_BOX (vbox2), button, FALSE, FALSE, 0);
6307 * Build the Signal-event part.
6310 frame = gtk_frame_new("Signal events");
6311 gtk_box_pack_start(GTK_BOX(vbox), frame, TRUE, TRUE, DEF_PAD);
6313 vbox2 = gtk_vbox_new(TRUE, DEF_PAD_SMALL);
6314 gtk_container_add(GTK_CONTAINER(frame), vbox2);
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);
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);
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);
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);
6341 button = gtk_button_new_with_label ("Close");
6342 gtk_signal_connect (GTK_OBJECT (button), "clicked",
6343 GTK_SIGNAL_FUNC (gtk_main_quit),
6345 gtk_container_add (GTK_CONTAINER (bbox), button);
6346 GTK_WIDGET_SET_FLAGS (button, GTK_CAN_DEFAULT);
6347 gtk_widget_grab_default (button);
6349 gtk_widget_show_all(window);
6357 gtk_init (&argc, &argv);
6365 <!-- example-end -->
6370 <!-- ----------------------------------------------------------------- -->
6371 <sect1 id="sec-ColorSelection">
6372 <title>Color Selection</title>
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>
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>
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>
6391 <programlisting role="C">
6392 GtkWidget *gtk_color_selection_new( void );
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
6400 <programlisting role="C">
6401 GtkWidget *gtk_color_selection_dialog_new( const gchar *title );
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>
6412 <programlisting role="C">
6413 void gtk_color_selection_set_update_policy( GtkColorSelection *colorsel,
6414 GtkUpdateType policy );
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>
6424 <programlisting role="C">
6425 void gtk_color_selection_set_opacity( GtkColorSelection *colorsel,
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>
6434 <programlisting role="C">
6435 void gtk_color_selection_set_color( GtkColorSelection *colorsel,
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
6447 <programlisting role="C">
6448 void gtk_color_selection_get_color( GtkColorSelection *colorsel,
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
6458 <para><!-- Need to do a whole section on DnD - TRG
6460 -------------</para>
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.
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>
6477 <programlisting role="C">
6478 <!-- example-start colorsel colorsel.c -->
6480 #include <glib.h>
6481 #include <gdk/gdk.h>
6482 #include <gtk/gtk.h>
6484 GtkWidget *colorseldlg = NULL;
6485 GtkWidget *drawingarea = NULL;
6487 /* Color changed handler */
6489 void color_changed_cb( GtkWidget *widget,
6490 GtkColorSelection *colorsel )
6494 GdkColormap *colormap;
6496 /* Get drawingarea colormap */
6498 colormap = gdk_window_get_colormap (drawingarea->window);
6500 /* Get current color */
6502 gtk_color_selection_get_color (colorsel,color);
6504 /* Fit to a unsigned 16 bit integer (0..65535) and
6505 * insert into the GdkColor structure */
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);
6511 /* Allocate color */
6513 gdk_color_alloc (colormap, &gdk_color);
6515 /* Set window background color */
6517 gdk_window_set_background (drawingarea->window, &gdk_color);
6521 gdk_window_clear (drawingarea->window);
6524 /* Drawingarea event handler */
6526 gint area_event( GtkWidget *widget,
6528 gpointer client_data )
6530 gint handled = FALSE;
6531 GtkWidget *colorsel;
6533 /* Check if we've received a button pressed event */
6535 if (event->type == GDK_BUTTON_PRESS && colorseldlg == NULL)
6537 /* Yes, we have an event and there's no colorseldlg yet! */
6541 /* Create color selection dialog */
6543 colorseldlg = gtk_color_selection_dialog_new("Select background color");
6545 /* Get the ColorSelection widget */
6547 colorsel = GTK_COLOR_SELECTION_DIALOG(colorseldlg)->colorsel;
6549 /* Connect to the "color_changed" signal, set the client-data
6550 * to the colorsel widget */
6552 gtk_signal_connect(GTK_OBJECT(colorsel), "color_changed",
6553 (GtkSignalFunc)color_changed_cb, (gpointer)colorsel);
6555 /* Show the dialog */
6557 gtk_widget_show(colorseldlg);
6563 /* Close down and exit handler */
6565 gint destroy_window( GtkWidget *widget,
6567 gpointer client_data )
6575 gint main( gint argc,
6580 /* Initialize the toolkit, remove gtk-related commandline stuff */
6582 gtk_init (&argc,&argv);
6584 /* Create toplevel window, set title and policies */
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);
6590 /* Attach to the "delete" and "destroy" events so we can exit */
6592 gtk_signal_connect (GTK_OBJECT(window), "delete_event",
6593 (GtkSignalFunc)destroy_window, (gpointer)window);
6595 /* Create drawingarea, set size and catch button events */
6597 drawingarea = gtk_drawing_area_new ();
6599 gtk_drawing_area_size (GTK_DRAWING_AREA(drawingarea), 200, 200);
6601 gtk_widget_set_events (drawingarea, GDK_BUTTON_PRESS_MASK);
6603 gtk_signal_connect (GTK_OBJECT(drawingarea), "event",
6604 (GtkSignalFunc)area_event, (gpointer)drawingarea);
6606 /* Add drawingarea to window, then show them both */
6608 gtk_container_add (GTK_CONTAINER(window), drawingarea);
6610 gtk_widget_show (drawingarea);
6611 gtk_widget_show (window);
6613 /* Enter the gtk main loop (this never returns) */
6617 /* Satisfy grumpy compilers */
6621 <!-- example-end -->
6626 <!-- ----------------------------------------------------------------- -->
6627 <sect1 id="sec-FileSelections">
6628 <title>File Selections</title>
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>
6634 <para>To create a new file selection box use:</para>
6636 <programlisting role="C">
6637 GtkWidget *gtk_file_selection_new( gchar *title );
6640 <para>To set the filename, for example to bring up a specific directory, or
6641 give a default filename, use this function:</para>
6643 <programlisting role="C">
6644 void gtk_file_selection_set_filename( GtkFileSelection *filesel,
6648 <para>To grab the text that the user has entered or clicked on, use this
6651 <programlisting role="C">
6652 gchar *gtk_file_selection_get_filename( GtkFileSelection *filesel );
6655 <para>There are also pointers to the widgets contained within the file
6656 selection widget. These are:</para>
6658 <programlisting role="C">
6669 <para>Most likely you will want to use the ok_button, cancel_button, and
6670 help_button pointers in signaling their use.</para>
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>
6677 <programlisting role="C">
6678 <!-- example-start filesel filesel.c -->
6680 #include <gtk/gtk.h>
6682 /* Get the selected filename and print it to the console */
6683 void file_ok_sel( GtkWidget *w,
6684 GtkFileSelection *fs )
6686 g_print ("%s\n", gtk_file_selection_get_filename (GTK_FILE_SELECTION (fs)));
6689 void destroy( GtkWidget *widget,
6700 gtk_init (&argc, &argv);
6702 /* Create a new file selection widget */
6703 filew = gtk_file_selection_new ("File selection");
6705 gtk_signal_connect (GTK_OBJECT (filew), "destroy",
6706 (GtkSignalFunc) destroy, &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 );
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));
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),
6722 gtk_widget_show(filew);
6726 <!-- example-end -->
6732 <!-- ***************************************************************** -->
6733 <chapter id="ch-ContainerWidgets">
6734 <title>Container Widgets</title>
6736 <!-- ----------------------------------------------------------------- -->
6737 <sect1 id="sec-EventBox">
6738 <title>The EventBox</title>
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
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>
6757 <para>To create a new EventBox widget, use:</para>
6759 <programlisting role="C">
6760 GtkWidget *gtk_event_box_new( void );
6763 <para>A child widget can then be added to this EventBox:</para>
6765 <programlisting role="C">
6766 gtk_container_add( GTK_CONTAINER(event_box), child_widget );
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>
6774 <programlisting role="C">
6775 <!-- example-start eventbox eventbox.c -->
6777 #include <gtk/gtk.h>
6783 GtkWidget *event_box;
6786 gtk_init (&argc, &argv);
6788 window = gtk_window_new (GTK_WINDOW_TOPLEVEL);
6790 gtk_window_set_title (GTK_WINDOW (window), "Event Box");
6792 gtk_signal_connect (GTK_OBJECT (window), "destroy",
6793 GTK_SIGNAL_FUNC (gtk_exit), NULL);
6795 gtk_container_set_border_width (GTK_CONTAINER (window), 10);
6797 /* Create an EventBox and add it to our toplevel window */
6799 event_box = gtk_event_box_new ();
6800 gtk_container_add (GTK_CONTAINER(window), event_box);
6801 gtk_widget_show (event_box);
6803 /* Create a long label */
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);
6809 /* Clip it short. */
6810 gtk_widget_set_usize (label, 110, 20);
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);
6817 /* Yet one more thing you need an X window for ... */
6819 gtk_widget_realize (event_box);
6820 gdk_window_set_cursor (event_box->window, gdk_cursor_new (GDK_HAND1));
6822 gtk_widget_show (window);
6828 <!-- example-end -->
6833 <!-- ----------------------------------------------------------------- -->
6834 <sect1 id="sec-TheAlignmentWidget">
6835 <title>The Alignment widget</title>
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>
6842 <para>There are only two functions associated with the Alignment widget:</para>
6844 <programlisting role="C">
6845 GtkWidget* gtk_alignment_new( gfloat xalign,
6850 void gtk_alignment_set( GtkAlignment *alignment,
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>
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>
6867 <para>A child widget can be added to this Alignment widget using:</para>
6869 <programlisting role="C">
6870 gtk_container_add( GTK_CONTAINER(alignment), child_widget );
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>
6878 <!-- ----------------------------------------------------------------- -->
6879 <sect1 id="sec-FixedContainer">
6880 <title>Fixed Container</title>
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>
6886 <para>There are only three functions associated with the fixed widget:</para>
6888 <programlisting role="C">
6889 GtkWidget* gtk_fixed_new( void );
6891 void gtk_fixed_put( GtkFixed *fixed,
6896 void gtk_fixed_move( GtkFixed *fixed,
6902 <para>The function <literal>gtk_fixed_new</literal> allows you to create a new Fixed
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>
6908 <para><literal>gtk_fixed_move</literal> allows the specified widget to be moved to a new
6911 <para>The following example illustrates how to use the Fixed Container.</para>
6913 <programlisting role="C">
6914 <!-- example-start fixed fixed.c -->
6916 #include <gtk/gtk.h>
6918 /* I'm going to be lazy and use some global variables to
6919 * store the position of the widget within the fixed
6924 /* This callback function moves the button to a new position
6925 * in the Fixed container. */
6926 void move_button( GtkWidget *widget,
6931 gtk_fixed_move( GTK_FIXED(fixed), widget, x, y);
6937 /* GtkWidget is the storage type for widgets */
6943 /* Initialise GTK */
6944 gtk_init(&argc, &argv);
6946 /* Create a new window */
6947 window = gtk_window_new (GTK_WINDOW_TOPLEVEL);
6948 gtk_window_set_title(GTK_WINDOW(window), "Fixed Container");
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);
6954 /* Sets the border width of the window. */
6955 gtk_container_set_border_width (GTK_CONTAINER (window), 10);
6957 /* Create a Fixed Container */
6958 fixed = gtk_fixed_new();
6959 gtk_container_add(GTK_CONTAINER(window), fixed);
6960 gtk_widget_show(fixed);
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");
6966 /* When the button receives the "clicked" signal, it will call the
6967 * function move_button() passing it the Fixed Container as its
6969 gtk_signal_connect (GTK_OBJECT (button), "clicked",
6970 GTK_SIGNAL_FUNC (move_button), fixed);
6972 /* This packs the button into the fixed containers window. */
6973 gtk_fixed_put (GTK_FIXED (fixed), button, i*50, i*50);
6975 /* The final step is to display this newly created widget. */
6976 gtk_widget_show (button);
6979 /* Display the window */
6980 gtk_widget_show (window);
6982 /* Enter the event loop */
6987 <!-- example-end -->
6992 <!-- ----------------------------------------------------------------- -->
6993 <sect1 id="sec-LayoutContainer">
6994 <title>Layout Container</title>
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>
7004 <para>A Layout container is created using:</para>
7006 <programlisting role="C">
7007 GtkWidget *gtk_layout_new( GtkAdjustment *hadjustment,
7008 GtkAdjustment *vadjustment );
7011 <para>As you can see, you can optionally specify the Adjustment objects that
7012 the Layout widget will use for its scrolling.</para>
7014 <para>You can add and move widgets in the Layout container using the
7015 following two functions:</para>
7017 <programlisting role="C">
7018 void gtk_layout_put( GtkLayout *layout,
7023 void gtk_layout_move( GtkLayout *layout,
7029 <para>The size of the Layout container can be set using the next function:</para>
7031 <programlisting role="C">
7032 void gtk_layout_set_size( GtkLayout *layout,
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>
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>
7047 <programlisting role="C">
7048 void gtk_layout_freeze( GtkLayout *layout );
7050 void gtk_layout_thaw( GtkLayout *layout );
7053 <para>The final four functions for use with Layout widgets are for
7054 manipulating the horizontal and vertical adjustment widgets:</para>
7056 <programlisting role="C">
7057 GtkAdjustment* gtk_layout_get_hadjustment( GtkLayout *layout );
7059 GtkAdjustment* gtk_layout_get_vadjustment( GtkLayout *layout );
7061 void gtk_layout_set_hadjustment( GtkLayout *layout,
7062 GtkAdjustment *adjustment );
7064 void gtk_layout_set_vadjustment( GtkLayout *layout,
7065 GtkAdjustment *adjustment);
7070 <!-- ----------------------------------------------------------------- -->
7071 <sect1 id="sec-Frames">
7072 <title>Frames</title>
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>
7078 <para>A Frame can be created with the following function:</para>
7080 <programlisting role="C">
7081 GtkWidget *gtk_frame_new( const gchar *label );
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>
7089 <programlisting role="C">
7090 void gtk_frame_set_label( GtkFrame *frame,
7091 const gchar *label );
7094 <para>The position of the label can be changed using this function:</para>
7096 <programlisting role="C">
7097 void gtk_frame_set_label_align( GtkFrame *frame,
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>
7107 <para>The next function alters the style of the box that is used to outline
7110 <programlisting role="C">
7111 void gtk_frame_set_shadow_type( GtkFrame *frame,
7112 GtkShadowType type);
7115 <para>The <literal>type</literal> argument can take one of the following values:</para>
7116 <programlisting role="C">
7120 GTK_SHADOW_ETCHED_IN (the default)
7121 GTK_SHADOW_ETCHED_OUT
7124 <para>The following code example illustrates the use of the Frame widget.</para>
7126 <programlisting role="C">
7127 <!-- example-start frame frame.c -->
7129 #include <gtk/gtk.h>
7134 /* GtkWidget is the storage type for widgets */
7140 /* Initialise GTK */
7141 gtk_init(&argc, &argv);
7143 /* Create a new window */
7144 window = gtk_window_new (GTK_WINDOW_TOPLEVEL);
7145 gtk_window_set_title(GTK_WINDOW(window), "Frame Example");
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);
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);
7155 /* Create a Frame */
7156 frame = gtk_frame_new(NULL);
7157 gtk_container_add(GTK_CONTAINER(window), frame);
7159 /* Set the frame's label */
7160 gtk_frame_set_label( GTK_FRAME(frame), "GTK Frame Widget" );
7162 /* Align the label at the right of the frame */
7163 gtk_frame_set_label_align( GTK_FRAME(frame), 1.0, 0.0);
7165 /* Set the style of the frame */
7166 gtk_frame_set_shadow_type( GTK_FRAME(frame), GTK_SHADOW_ETCHED_OUT);
7168 gtk_widget_show(frame);
7170 /* Display the window */
7171 gtk_widget_show (window);
7173 /* Enter the event loop */
7178 <!-- example-end -->
7183 <!-- ----------------------------------------------------------------- -->
7184 <sect1 id="sec-AspectFrames">
7185 <title>Aspect Frames</title>
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>
7195 <para>To create a new aspect frame use:</para>
7197 <programlisting role="C">
7198 GtkWidget *gtk_aspect_frame_new( const gchar *label,
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>
7210 <para>To change the options of an existing aspect frame, you can use:</para>
7212 <programlisting role="C">
7213 void gtk_aspect_frame_set( GtkAspectFrame *aspect_frame,
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>
7224 <programlisting role="C">
7225 <!-- example-start aspectframe aspectframe.c -->
7227 #include <gtk/gtk.h>
7233 GtkWidget *aspect_frame;
7234 GtkWidget *drawing_area;
7235 gtk_init (&argc, &argv);
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);
7243 /* Create an aspect_frame and add it to our toplevel window */
7245 aspect_frame = gtk_aspect_frame_new ("2x1", /* label */
7248 2, /* xsize/ysize = 2 */
7249 FALSE /* ignore child's aspect */);
7251 gtk_container_add (GTK_CONTAINER(window), aspect_frame);
7252 gtk_widget_show (aspect_frame);
7254 /* Now add a child widget to the aspect frame */
7256 drawing_area = gtk_drawing_area_new ();
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);
7264 gtk_widget_show (window);
7268 <!-- example-end -->
7273 <!-- ----------------------------------------------------------------- -->
7274 <sect1 id="sec-PanedWindowWidgets">
7275 <title>Paned Window Widgets</title>
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>
7283 <para>To create a new paned window, call one of:</para>
7285 <programlisting role="C">
7286 GtkWidget *gtk_hpaned_new (void);
7288 GtkWidget *gtk_vpaned_new (void);
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>
7294 <programlisting role="C">
7295 void gtk_paned_add1 (GtkPaned *paned, GtkWidget *child);
7297 void gtk_paned_add2 (GtkPaned *paned, GtkWidget *child);
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>
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
7318 <programlisting role="C">
7319 <!-- example-start paned paned.c -->
7321 #define GTK_ENABLE_BROKEN
7322 #include <stdio.h>
7323 #include <gtk/gtk.h>
7325 /* Create the list of "messages" */
7326 GtkWidget *create_list( void )
7329 GtkWidget *scrolled_window;
7331 GtkWidget *list_item;
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);
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);
7348 /* Add some messages to the window */
7349 for (i=0; i<10; i++) {
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);
7358 return scrolled_window;
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 */
7366 void realize_text( GtkWidget *text,
7369 gtk_text_freeze (GTK_TEXT (text));
7370 gtk_text_insert (GTK_TEXT (text), NULL, &text->style->black, NULL,
7371 "From: pathfinder@nasa.gov\n"
7372 "To: mom@nasa.gov\n"
7373 "Subject: Made it!\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"
7380 gtk_text_thaw (GTK_TEXT (text));
7383 /* Create a scrolled text area that displays a "message" */
7384 GtkWidget *create_text( void )
7388 GtkWidget *hscrollbar;
7389 GtkWidget *vscrollbar;
7391 /* Create a table to hold the text widget and scrollbars */
7392 table = gtk_table_new (2, 2, FALSE);
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);
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);
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);
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);
7429 gtk_init (&argc, &argv);
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);
7438 /* create a vpaned widget and add it to our toplevel window */
7440 vpaned = gtk_vpaned_new ();
7441 gtk_container_add (GTK_CONTAINER(window), vpaned);
7442 gtk_widget_show (vpaned);
7444 /* Now create the contents of the two halves of the window */
7446 list = create_list ();
7447 gtk_paned_add1 (GTK_PANED(vpaned), list);
7448 gtk_widget_show (list);
7450 text = create_text ();
7451 gtk_paned_add2 (GTK_PANED(vpaned), text);
7452 gtk_widget_show (text);
7453 gtk_widget_show (window);
7457 <!-- example-end -->
7462 <!-- ----------------------------------------------------------------- -->
7463 <sect1 id="sec-Viewports">
7464 <title>Viewports</title>
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>
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>
7476 <para>A Viewport is created with the function</para>
7478 <programlisting role="C">
7479 GtkWidget *gtk_viewport_new( GtkAdjustment *hadjustment,
7480 GtkAdjustment *vadjustment );
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>
7487 <para>You can get and set the adjustments after the widget has been created
7488 using the following four functions:</para>
7490 <programlisting role="C">
7491 GtkAdjustment *gtk_viewport_get_hadjustment (GtkViewport *viewport );
7493 GtkAdjustment *gtk_viewport_get_vadjustment (GtkViewport *viewport );
7495 void gtk_viewport_set_hadjustment( GtkViewport *viewport,
7496 GtkAdjustment *adjustment );
7498 void gtk_viewport_set_vadjustment( GtkViewport *viewport,
7499 GtkAdjustment *adjustment );
7502 <para>The only other viewport function is used to alter its appearance:</para>
7504 <programlisting role="C">
7505 void gtk_viewport_set_shadow_type( GtkViewport *viewport,
7506 GtkShadowType type );
7509 <para>Possible values for the <literal>type</literal> parameter are:</para>
7510 <programlisting role="C">
7514 GTK_SHADOW_ETCHED_IN,
7515 GTK_SHADOW_ETCHED_OUT
7520 <!-- ----------------------------------------------------------------- -->
7521 <sect1 id="sec-ScrolledWindows"
7522 <title>Scrolled Windows</title>
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
7529 <para>The following function is used to create a new scrolled window.</para>
7531 <programlisting role="C">
7532 GtkWidget *gtk_scrolled_window_new( GtkAdjustment *hadjustment,
7533 GtkAdjustment *vadjustment );
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>
7540 <programlisting role="C">
7541 void gtk_scrolled_window_set_policy( GtkScrolledWindow *scrolled_window,
7542 GtkPolicyType hscrollbar_policy,
7543 GtkPolicyType vscrollbar_policy );
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>
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>
7556 <para>You can then place your object into the scrolled window using the
7557 following function.</para>
7559 <programlisting role="C">
7560 void gtk_scrolled_window_add_with_viewport( GtkScrolledWindow *scrolled_window,
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
7568 <programlisting role="C">
7569 <!-- example-start scrolledwin scrolledwin.c -->
7571 #include <stdio.h>
7572 #include <gtk/gtk.h>
7574 void destroy( GtkWidget *widget,
7583 static GtkWidget *window;
7584 GtkWidget *scrolled_window;
7590 gtk_init (&argc, &argv);
7592 /* Create a new dialog window for the scrolled window to be
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);
7601 /* create a new scrolled window. */
7602 scrolled_window = gtk_scrolled_window_new (NULL, NULL);
7604 gtk_container_set_border_width (GTK_CONTAINER (scrolled_window), 10);
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,
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,
7616 gtk_widget_show (scrolled_window);
7618 /* create a table of 10 by 10 squares. */
7619 table = gtk_table_new (10, 10, FALSE);
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);
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);
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,
7638 gtk_widget_show (button);
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));
7647 /* this makes it so the button is the default. */
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);
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);
7657 gtk_widget_show (window);
7663 <!-- example-end -->
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>
7672 <!-- ----------------------------------------------------------------- -->
7673 <sect1 id="sec-ButtonBoxes">
7674 <title>Button Boxes</title>
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>
7681 <programlisting role="C">
7682 GtkWidget *gtk_hbutton_box_new( void );
7684 GtkWidget *gtk_vbutton_box_new( void );
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>
7690 <programlisting role="C">
7691 void gtk_hbutton_box_set_spacing_default( gint spacing );
7693 void gtk_vbutton_box_set_spacing_default( gint spacing );
7696 <para>Similarly, the current spacing values can be queried using:</para>
7698 <programlisting role="C">
7699 gint gtk_hbutton_box_get_spacing_default( void );
7701 gint gtk_vbutton_box_get_spacing_default( void );
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>
7707 <programlisting role="C">
7708 void gtk_hbutton_box_set_layout_default( GtkButtonBoxStyle layout );
7710 void gtk_vbutton_box_set_layout_default( GtkButtonBoxStyle layout );
7713 <para>The <literal>layout</literal> argument can take one of the following values:</para>
7715 <programlisting role="C">
7716 GTK_BUTTONBOX_DEFAULT_STYLE
7717 GTK_BUTTONBOX_SPREAD
7723 <para>The current layout setting can be retrieved using:</para>
7725 <programlisting role="C">
7726 GtkButtonBoxStyle gtk_hbutton_box_get_layout_default( void );
7728 GtkButtonBoxStyle gtk_vbutton_box_get_layout_default( void );
7731 <para>Buttons are added to a Button Box using the usual function:</para>
7733 <programlisting role="C">
7734 gtk_container_add( GTK_CONTAINER(button_box), child_widget );
7737 <para>Here's an example that illustrates all the different layout settings
7738 for Button Boxes.</para>
7740 <programlisting role="C">
7741 <!-- example-start buttonbox buttonbox.c -->
7743 #include <gtk/gtk.h>
7745 /* Create a Button Box with the specified parameters */
7746 GtkWidget *create_bbox( gint horizontal,
7757 frame = gtk_frame_new (title);
7760 bbox = gtk_hbutton_box_new ();
7762 bbox = gtk_vbutton_box_new ();
7764 gtk_container_set_border_width (GTK_CONTAINER (bbox), 5);
7765 gtk_container_add (GTK_CONTAINER (frame), bbox);
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);
7772 button = gtk_button_new_with_label ("OK");
7773 gtk_container_add (GTK_CONTAINER (bbox), button);
7775 button = gtk_button_new_with_label ("Cancel");
7776 gtk_container_add (GTK_CONTAINER (bbox), button);
7778 button = gtk_button_new_with_label ("Help");
7779 gtk_container_add (GTK_CONTAINER (bbox), button);
7787 static GtkWidget* window = NULL;
7788 GtkWidget *main_vbox;
7791 GtkWidget *frame_horz;
7792 GtkWidget *frame_vert;
7794 /* Initialize GTK */
7795 gtk_init( &argc, &argv );
7797 window = gtk_window_new (GTK_WINDOW_TOPLEVEL);
7798 gtk_window_set_title (GTK_WINDOW (window), "Button Boxes");
7800 gtk_signal_connect (GTK_OBJECT (window), "destroy",
7801 GTK_SIGNAL_FUNC(gtk_main_quit),
7804 gtk_container_set_border_width (GTK_CONTAINER (window), 10);
7806 main_vbox = gtk_vbox_new (FALSE, 0);
7807 gtk_container_add (GTK_CONTAINER (window), main_vbox);
7809 frame_horz = gtk_frame_new ("Horizontal Button Boxes");
7810 gtk_box_pack_start (GTK_BOX (main_vbox), frame_horz, TRUE, TRUE, 10);
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);
7816 gtk_box_pack_start (GTK_BOX (vbox),
7817 create_bbox (TRUE, "Spread (spacing 40)", 40, 85, 20, GTK_BUTTONBOX_SPREAD),
7820 gtk_box_pack_start (GTK_BOX (vbox),
7821 create_bbox (TRUE, "Edge (spacing 30)", 30, 85, 20, GTK_BUTTONBOX_EDGE),
7824 gtk_box_pack_start (GTK_BOX (vbox),
7825 create_bbox (TRUE, "Start (spacing 20)", 20, 85, 20, GTK_BUTTONBOX_START),
7828 gtk_box_pack_start (GTK_BOX (vbox),
7829 create_bbox (TRUE, "End (spacing 10)", 10, 85, 20, GTK_BUTTONBOX_END),
7832 frame_vert = gtk_frame_new ("Vertical Button Boxes");
7833 gtk_box_pack_start (GTK_BOX (main_vbox), frame_vert, TRUE, TRUE, 10);
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);
7839 gtk_box_pack_start (GTK_BOX (hbox),
7840 create_bbox (FALSE, "Spread (spacing 5)", 5, 85, 20, GTK_BUTTONBOX_SPREAD),
7843 gtk_box_pack_start (GTK_BOX (hbox),
7844 create_bbox (FALSE, "Edge (spacing 30)", 30, 85, 20, GTK_BUTTONBOX_EDGE),
7847 gtk_box_pack_start (GTK_BOX (hbox),
7848 create_bbox (FALSE, "Start (spacing 20)", 20, 85, 20, GTK_BUTTONBOX_START),
7851 gtk_box_pack_start (GTK_BOX (hbox),
7852 create_bbox (FALSE, "End (spacing 20)", 20, 85, 20, GTK_BUTTONBOX_END),
7855 gtk_widget_show_all (window);
7857 /* Enter the event loop */
7862 <!-- example-end -->
7867 <!-- ----------------------------------------------------------------- -->
7868 <sect1 id="sec-Toolbar">
7869 <title>Toolbar</title>
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>
7878 <para>Creating a toolbar is (as one may already suspect) done with the
7879 following function:</para>
7881 <programlisting role="C">
7882 GtkWidget *gtk_toolbar_new( GtkOrientation orientation,
7883 GtkToolbarStyle style );
7886 <para>where orientation may be one of:</para>
7888 <programlisting role="C">
7889 GTK_ORIENTATION_HORIZONTAL
7890 GTK_ORIENTATION_VERTICAL
7893 <para>and style one of:</para>
7895 <programlisting role="C">
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>
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>
7911 <programlisting role="C">
7912 GtkWidget *gtk_toolbar_append_item( GtkToolbar *toolbar,
7914 const char *tooltip_text,
7915 const char *tooltip_private_text,
7917 GtkSignalFunc callback,
7918 gpointer user_data );
7920 GtkWidget *gtk_toolbar_prepend_item( GtkToolbar *toolbar,
7922 const char *tooltip_text,
7923 const char *tooltip_private_text,
7925 GtkSignalFunc callback,
7926 gpointer user_data );
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>
7933 <programlisting role="C">
7934 GtkWidget *gtk_toolbar_insert_item( GtkToolbar *toolbar,
7936 const char *tooltip_text,
7937 const char *tooltip_private_text,
7939 GtkSignalFunc callback,
7944 <para>To simplify adding spaces between toolbar items, you may use the
7945 following functions:</para>
7947 <programlisting role="C">
7948 void gtk_toolbar_append_space( GtkToolbar *toolbar );
7950 void gtk_toolbar_prepend_space( GtkToolbar *toolbar );
7952 void gtk_toolbar_insert_space( GtkToolbar *toolbar,
7956 <para>While the size of the added space can be set globally for a
7957 whole toolbar with the function:</para>
7959 <programlisting role="C">
7960 void gtk_toolbar_set_space_size( GtkToolbar *toolbar,
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>
7967 <programlisting role="C">
7968 void gtk_toolbar_set_orientation( GtkToolbar *toolbar,
7969 GtkOrientation orientation );
7971 void gtk_toolbar_set_style( GtkToolbar *toolbar,
7972 GtkToolbarStyle style );
7974 void gtk_toolbar_set_tooltips( GtkToolbar *toolbar,
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>
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>
7988 <programlisting role="C">
7989 #include <gtk/gtk.h>
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)
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>
8006 <programlisting role="C">
8007 GtkWidget* close_button; /* This button will emit signal to close
8009 GtkWidget* tooltips_button; /* to enable/disable tooltips */
8010 GtkWidget* text_button,
8012 * both_button; /* radio buttons for toolbar style */
8013 GtkWidget* entry; /* a text entry to show packing any widget into
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>
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
8024 * ATTENTION: our toolbar is passed as data to callback ! */
8025 void radio_event (GtkWidget *widget, gpointer data)
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);
8035 /* even easier, just check given toggle button and enable/disable
8037 void toggle_event (GtkWidget *widget, gpointer data)
8039 gtk_toolbar_set_tooltips (GTK_TOOLBAR ( data ),
8040 GTK_TOGGLE_BUTTON (widget)->active );
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>
8049 <programlisting role="C">
8050 int main (int argc, char *argv[])
8052 /* Here is our main window (a dialog) and a handle for the handlebox */
8054 GtkWidget* handlebox;
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;
8064 /* this is called in all GTK application. */
8065 gtk_init (&argc, &argv);
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;
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);
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 );
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 );
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>
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,
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 );
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, &mask,
8112 &dialog->style->white, gtk_xpm );
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>
8121 <programlisting role="C">
8122 /* our first item is <close> button */
8123 iconw = gtk_pixmap_new ( icon, mask ); /* icon widget */
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 */
8132 gtk_toolbar_append_space ( GTK_TOOLBAR ( toolbar ) ); /* space after item */
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>
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 */
8151 "Only icons in toolbar", /* tooltip */
8152 "Private", /* tooltip private string */
8154 GTK_SIGNAL_FUNC (radio_event), /* signal */
8155 toolbar); /* data for signal */
8156 gtk_toolbar_append_space ( GTK_TOOLBAR ( toolbar ) );
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
8169 <programlisting role="C">
8170 /* following radio buttons refer to previous ones */
8171 iconw = gtk_pixmap_new ( icon, mask );
8173 gtk_toolbar_append_element(GTK_TOOLBAR(toolbar),
8174 GTK_TOOLBAR_CHILD_RADIOBUTTON,
8177 "Only texts in toolbar",
8180 GTK_SIGNAL_FUNC (radio_event),
8182 gtk_toolbar_append_space ( GTK_TOOLBAR ( toolbar ) );
8184 iconw = gtk_pixmap_new ( icon, mask );
8186 gtk_toolbar_append_element(GTK_TOOLBAR(toolbar),
8187 GTK_TOOLBAR_CHILD_RADIOBUTTON,
8190 "Icons and text in toolbar",
8193 GTK_SIGNAL_FUNC (radio_event),
8195 gtk_toolbar_append_space ( GTK_TOOLBAR ( toolbar ) );
8196 gtk_toggle_button_set_active(GTK_TOGGLE_BUTTON(both_button),TRUE);
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>
8203 <programlisting role="C">
8204 /* here we have just a simple toggle button */
8205 iconw = gtk_pixmap_new ( icon, mask );
8207 gtk_toolbar_append_element(GTK_TOOLBAR(toolbar),
8208 GTK_TOOLBAR_CHILD_TOGGLEBUTTON,
8211 "Toolbar with or without tips",
8214 GTK_SIGNAL_FUNC (toggle_event),
8216 gtk_toolbar_append_space ( GTK_TOOLBAR ( toolbar ) );
8217 gtk_toggle_button_set_active(GTK_TOGGLE_BUTTON(tooltips_button),TRUE);
8220 <para>A toggle button can be created in the obvious way (if one knows how to create
8221 radio buttons already).</para>
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),
8229 "This is just an entry",
8232 /* well, it isn't created within thetoolbar, so we must still show it */
8233 gtk_widget_show ( entry );
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>
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 );
8246 /* rest in gtk_main and wait for the fun to begin! */
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>
8256 <programlisting role="C">
8258 static char * gtk_xpm[] = {
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 ".............++++..............."};
8308 <!-- ----------------------------------------------------------------- -->
8309 <sect1 id="sec-Notebooks">
8310 <title>Notebooks</title>
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>
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>
8321 <programlisting role="C">
8322 GtkWidget *gtk_notebook_new( void );
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>
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>
8332 <programlisting role="C">
8333 void gtk_notebook_set_tab_pos( GtkNotebook *notebook,
8334 GtkPositionType pos );
8337 <para>GtkPositionType will be one of the following, which are pretty self
8339 <programlisting role="C">
8346 <para><literal>GTK_POS_TOP</literal> is the default.</para>
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>
8352 <programlisting role="C">
8353 void gtk_notebook_append_page( GtkNotebook *notebook,
8355 GtkWidget *tab_label );
8357 void gtk_notebook_prepend_page( GtkNotebook *notebook,
8359 GtkWidget *tab_label );
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>
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>
8373 <programlisting role="C">
8374 void gtk_notebook_insert_page( GtkNotebook *notebook,
8376 GtkWidget *tab_label,
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>
8385 <para>Now that we know how to add a page, lets see how we can remove a page
8386 from the notebook.</para>
8388 <programlisting role="C">
8389 void gtk_notebook_remove_page( GtkNotebook *notebook,
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>
8396 <para>To find out what the current page is in a notebook use the function:</para>
8398 <programlisting role="C">
8399 gint gtk_notebook_get_current_page( GtkNotebook *notebook );
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>
8410 <programlisting role="C">
8411 void gtk_notebook_next_page( GtkNoteBook *notebook );
8413 void gtk_notebook_prev_page( GtkNoteBook *notebook );
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>
8420 <programlisting role="C">
8421 void gtk_notebook_set_page( GtkNotebook *notebook,
8425 <para>The next two functions add or remove the notebook page tabs and the
8426 notebook border respectively.</para>
8428 <programlisting role="C">
8429 void gtk_notebook_set_show_tabs( GtkNotebook *notebook,
8430 gboolean show_tabs);
8432 void gtk_notebook_set_show_border( GtkNotebook *notebook,
8433 gboolean show_border );
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>
8440 <programlisting role="C">
8441 void gtk_notebook_set_scrollable( GtkNotebook *notebook,
8442 gboolean scrollable );
8445 <para><literal>show_tabs</literal>, <literal>show_border</literal> and <literal>scrollable</literal> can be either
8446 TRUE or FALSE.</para>
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>
8456 <programlisting role="C">
8457 <!-- example-start notebook notebook.c -->
8459 #include <stdio.h>
8460 #include <gtk/gtk.h>
8462 /* This function rotates the position of the tabs */
8463 void rotate_book( GtkButton *button,
8464 GtkNotebook *notebook )
8466 gtk_notebook_set_tab_pos (notebook, (notebook->tab_pos +1) %4);
8469 /* Add/Remove the page tabs and the borders */
8470 void tabsborder_book( GtkButton *button,
8471 GtkNotebook *notebook )
8475 if (notebook->show_tabs == 0)
8477 if (notebook->show_border == 0)
8480 gtk_notebook_set_show_tabs (notebook, tval);
8481 gtk_notebook_set_show_border (notebook, bval);
8484 /* Remove a page from the notebook */
8485 void remove_book( GtkButton *button,
8486 GtkNotebook *notebook )
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);
8497 gint delete( GtkWidget *widget,
8511 GtkWidget *notebook;
8514 GtkWidget *checkbutton;
8519 gtk_init (&argc, &argv);
8521 window = gtk_window_new (GTK_WINDOW_TOPLEVEL);
8523 gtk_signal_connect (GTK_OBJECT (window), "delete_event",
8524 GTK_SIGNAL_FUNC (delete), NULL);
8526 gtk_container_set_border_width (GTK_CONTAINER (window), 10);
8528 table = gtk_table_new(3,6,FALSE);
8529 gtk_container_add (GTK_CONTAINER (window), table);
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);
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);
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);
8547 label = gtk_label_new (bufferf);
8548 gtk_container_add (GTK_CONTAINER (frame), label);
8549 gtk_widget_show (label);
8551 label = gtk_label_new (bufferl);
8552 gtk_notebook_append_page (GTK_NOTEBOOK (notebook), frame, label);
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);
8560 label = gtk_label_new ("Add page");
8561 gtk_notebook_insert_page (GTK_NOTEBOOK (notebook), checkbutton, label, 2);
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);
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);
8573 label = gtk_label_new (bufferf);
8574 gtk_container_add (GTK_CONTAINER (frame), label);
8575 gtk_widget_show (label);
8577 label = gtk_label_new (bufferl);
8578 gtk_notebook_prepend_page (GTK_NOTEBOOK(notebook), frame, label);
8581 /* Set what page to start at (page 4) */
8582 gtk_notebook_set_page (GTK_NOTEBOOK(notebook), 3);
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);
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);
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);
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);
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);
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);
8626 gtk_widget_show(table);
8627 gtk_widget_show(window);
8633 <!-- example-end -->
8636 <para>I hope this helps you on your way with creating notebooks for your
8637 GTK applications.</para>
8642 <!-- ***************************************************************** -->
8643 <chapter id="ch-CListWidget">
8644 <title>CList Widget</title>
8646 <!-- ----------------------------------------------------------------- -->
8648 <para>The CList widget has replaced the List widget (which is still
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>
8656 <!-- ----------------------------------------------------------------- -->
8657 <sect1 id="sec-CreatingACListWidget">
8658 <title>Creating a CList widget</title>
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
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>
8669 <programlisting role="C">
8670 GtkWidget *gtk_clist_new ( gint columns );
8672 GtkWidget *gtk_clist_new_with_titles( gint columns,
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>
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>
8690 <!-- ----------------------------------------------------------------- -->
8691 <sect1 id="sec-ModesOfOperating">
8692 <title>Modes of operation</title>
8694 <para>There are several attributes that can be used to alter the behaviour of
8695 a CList. First there is</para>
8697 <programlisting role="C">
8698 void gtk_clist_set_selection_mode( GtkCList *clist,
8699 GtkSelectionMode mode );
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>
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>
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
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>
8724 <listitem><simpara> <literal>GTK_SELECTION_EXTENDED</literal> - The selection is always NULL.</simpara>
8728 <para>Others might be added in later revisions of GTK.</para>
8730 <para>We can also define what the border of the CList widget should look
8731 like. It is done through</para>
8733 <programlisting role="C">
8734 void gtk_clist_set_shadow_type( GtkCList *clist,
8735 GtkShadowType border );
8738 <para>The possible values for the second argument are</para>
8740 <programlisting role="C">
8744 GTK_SHADOW_ETCHED_IN
8745 GTK_SHADOW_ETCHED_OUT
8750 <!-- ----------------------------------------------------------------- -->
8751 <sect1 id="sec-WorkingWithTitles">
8752 <title>Working with titles</title>
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>
8761 <programlisting role="C">
8762 void gtk_clist_column_title_active( GtkCList *clist,
8765 void gtk_clist_column_title_passive( GtkCList *clist,
8768 void gtk_clist_column_titles_active( GtkCList *clist );
8770 void gtk_clist_column_titles_passive( GtkCList *clist );
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>
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
8782 <programlisting role="C">
8783 void gtk_clist_column_titles_show( GtkCList *clist );
8785 void gtk_clist_column_titles_hide( GtkCList *clist );
8788 <para>For titles to be really useful we need a mechanism to set and change
8789 them, and this is done using</para>
8791 <programlisting role="C">
8792 void gtk_clist_set_column_title( GtkCList *clist,
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>
8806 <programlisting role="C">
8807 void gtk_clist_set_column_widget( GtkCList *clist,
8809 GtkWidget *widget );
8812 <para>which should require no special explanation.</para>
8816 <!-- ----------------------------------------------------------------- -->
8817 <sect1 id="sec-ManipulatingTheListItself">
8818 <title>Manipulating the list itself</title>
8820 <para>It is possible to change the justification for a column, and it is
8823 <programlisting role="C">
8824 void gtk_clist_set_column_justification( GtkCList *clist,
8826 GtkJustification justification );
8829 <para>The GtkJustification type can take the following values:</para>
8832 <listitem><simpara><literal>GTK_JUSTIFY_LEFT</literal> - The text in the column will begin from the
8833 left edge.</simpara>
8836 <listitem><simpara><literal>GTK_JUSTIFY_RIGHT</literal> - The text in the column will begin from the
8837 right edge.</simpara>
8840 <listitem><simpara><literal>GTK_JUSTIFY_CENTER</literal> - The text is placed in the center of the
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>
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>
8856 <programlisting role="C">
8857 void gtk_clist_set_column_width( GtkCList *clist,
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>
8867 <programlisting role="C">
8868 void gtk_clist_set_row_height( GtkCList *clist,
8872 <para>Again, note that the height is given in pixels.</para>
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>
8878 <programlisting role="C">
8879 void gtk_clist_moveto( GtkCList *clist,
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>
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>
8898 <programlisting role="C">
8899 GtkVisibility gtk_clist_row_is_visible( GtkCList *clist,
8903 <para>The return value is is one of the following:</para>
8905 <programlisting role="C">
8907 GTK_VISIBILITY_PARTIAL
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
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>
8922 <programlisting role="C">
8923 void gtk_clist_set_foreground( GtkCList *clist,
8927 void gtk_clist_set_background( GtkCList *clist,
8932 <para>Please note that the colors must have been previously allocated.</para>
8936 <!-- ----------------------------------------------------------------- -->
8937 <sect1 id="sec-AddingRowsToTheList">
8938 <title>Adding rows to the list</title>
8940 <para>We can add rows in three ways. They can be prepended or appended to
8941 the list using</para>
8943 <programlisting role="C">
8944 gint gtk_clist_prepend( GtkCList *clist,
8947 gint gtk_clist_append( GtkCList *clist,
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>
8954 <programlisting role="C">
8955 void gtk_clist_insert( GtkCList *clist,
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>
8967 <para>Also, please note that the numbering of both rows and columns start at 0.</para>
8969 <para>To remove an individual row we use</para>
8971 <programlisting role="C">
8972 void gtk_clist_remove( GtkCList *clist,
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>
8980 <programlisting role="C">
8981 void gtk_clist_clear( GtkCList *clist );
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>
8991 <programlisting role="C">
8992 void gtk_clist_freeze( GtkCList * clist );
8994 void gtk_clist_thaw( GtkCList * clist );
8999 <!-- ----------------------------------------------------------------- -->
9000 <sect1 id="sec-SettingTextAndPixmapsInTheCells">
9001 <title>Setting text and pixmaps in the cells</title>
9003 <para>A cell can contain a pixmap, text or both. To set them the following
9004 functions are used.</para>
9006 <programlisting role="C">
9007 void gtk_clist_set_text( GtkCList *clist,
9010 const gchar *text );
9012 void gtk_clist_set_pixmap( GtkCList *clist,
9018 void gtk_clist_set_pixtext( GtkCList *clist,
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>
9033 <para>To read back the data, we instead use</para>
9035 <programlisting role="C">
9036 gint gtk_clist_get_text( GtkCList *clist,
9041 gint gtk_clist_get_pixmap( GtkCList *clist,
9047 gint gtk_clist_get_pixtext( GtkCList *clist,
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>
9064 <programlisting role="C">
9067 gtk_clist_get_pixtext(clist, row, column, &mytext, NULL, NULL, NULL);
9070 <para>There is one more call that is related to what's inside a cell in the
9071 clist, and that's</para>
9073 <programlisting role="C">
9074 GtkCellType gtk_clist_get_cell_type( GtkCList *clist,
9079 <para>which returns the type of data in a cell. The return value is one of</para>
9081 <programlisting role="C">
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>
9093 <programlisting role="C">
9094 void gtk_clist_set_shift( GtkCList *clist,
9103 <!-- ----------------------------------------------------------------- -->
9104 <sect1 id="sec-StoringDataPointers">
9105 <title>Storing data pointers</title>
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>
9112 <para>The functions should be fairly self-explanatory by now.</para>
9114 <programlisting role="C">
9115 void gtk_clist_set_row_data( GtkCList *clist,
9119 oid gtk_clist_set_row_data_full( GtkCList *clist,
9122 GtkDestroyNotify destroy );
9124 gpointer gtk_clist_get_row_data( GtkCList *clist,
9127 gint gtk_clist_find_row_from_data( GtkCList *clist,
9133 <!-- ----------------------------------------------------------------- -->
9134 <sect1 id="sec-WorkingWithSelections">
9135 <title>Working with selections</title>
9137 <para>There are also functions available that let us force the (un)selection
9138 of a row. These are</para>
9140 <programlisting role="C">
9141 void gtk_clist_select_row( GtkCList *clist,
9145 void gtk_clist_unselect_row( GtkCList *clist,
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>
9154 <programlisting role="C">
9155 gint gtk_clist_get_selection_info( GtkCList *clist,
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>
9169 <!-- ----------------------------------------------------------------- -->
9170 <sect1 id="sec-TheSignalsThatBringItTogether">
9171 <title>The signals that bring it together</title>
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>
9178 <listitem><simpara>select_row - This signal will send the following information, in
9179 order: GtkCList *clist, gint row, gint column, GtkEventButton *event</simpara>
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>
9186 <listitem><simpara>click_column - Send GtkCList *clist, gint column</simpara>
9190 <para>So if we want to connect a callback to select_row, the callback
9191 function would be declared like this</para>
9193 <programlisting role="C">
9194 void select_row_callback(GtkWidget *widget,
9197 GdkEventButton *event,
9201 <para>The callback is connected as usual with</para>
9203 <programlisting role="C">
9204 gtk_signal_connect(GTK_OBJECT( clist),
9206 GTK_SIGNAL_FUNC(select_row_callback),
9212 <!-- ----------------------------------------------------------------- -->
9213 <sect1 id="sec-ACListExample">
9214 <title>A CList example</title>
9216 <programlisting role="C">
9217 <!-- example-start clist clist.c -->
9219 #include <gtk/gtk.h>
9221 /* User clicked the "Add List" button. */
9222 void button_add_clicked( gpointer data )
9226 /* Something silly to add to the list. 4 rows of 2 columns each */
9227 gchar *drink[4][2] = { { "Milk", "3 Oz" },
9230 { "Snakes", "55" } };
9232 /* Here we do the actual adding of the text. It's done once for
9235 for ( indx=0 ; indx < 4 ; indx++ )
9236 gtk_clist_append( (GtkCList *) data, drink[indx]);
9241 /* User clicked the "Clear List" button. */
9242 void button_clear_clicked( gpointer data )
9244 /* Clear the list using gtk_clist_clear. This is much faster than
9245 * calling gtk_clist_remove once for each row.
9247 gtk_clist_clear( (GtkCList *) data);
9252 /* The user clicked the "Hide/Show titles" button. */
9253 void button_hide_show_clicked( gpointer data )
9255 /* Just a flag to remember the status. 0 = currently visible */
9256 static short int flag = 0;
9260 /* Hide the titles and set the flag to 1 */
9261 gtk_clist_column_titles_hide((GtkCList *) data);
9266 /* Show the titles and reset flag to 0 */
9267 gtk_clist_column_titles_show((GtkCList *) data);
9274 /* If we come here, then the user has selected a row in the list. */
9275 void selection_made( GtkWidget *clist,
9278 GdkEventButton *event,
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
9287 gtk_clist_get_text(GTK_CLIST(clist), row, column, &text);
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",
9301 GtkWidget *vbox, *hbox;
9302 GtkWidget *scrolled_window, *clist;
9303 GtkWidget *button_add, *button_clear, *button_hide_show;
9304 gchar *titles[2] = { "Ingredients", "Amount" };
9306 gtk_init(&argc, &argv);
9308 window=gtk_window_new(GTK_WINDOW_TOPLEVEL);
9309 gtk_widget_set_usize(GTK_WIDGET(window), 300, 150);
9311 gtk_window_set_title(GTK_WINDOW(window), "GtkCList Example");
9312 gtk_signal_connect(GTK_OBJECT(window),
9314 GTK_SIGNAL_FUNC(gtk_main_quit),
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);
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);
9327 gtk_box_pack_start(GTK_BOX(vbox), scrolled_window, TRUE, TRUE, 0);
9328 gtk_widget_show (scrolled_window);
9330 /* Create the CList. For this example we use 2 columns */
9331 clist = gtk_clist_new_with_titles( 2, titles);
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),
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);
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).
9346 gtk_clist_set_column_width (GTK_CLIST(clist), 0, 150);
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);
9352 /* Create the buttons and add them to the window. See the button
9353 * tutorial for more examples and comments on this.
9355 hbox = gtk_hbox_new(FALSE, 0);
9356 gtk_box_pack_start(GTK_BOX(vbox), hbox, FALSE, TRUE, 0);
9357 gtk_widget_show(hbox);
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");
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);
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),
9371 gtk_signal_connect_object(GTK_OBJECT(button_clear), "clicked",
9372 GTK_SIGNAL_FUNC(button_clear_clicked),
9374 gtk_signal_connect_object(GTK_OBJECT(button_hide_show), "clicked",
9375 GTK_SIGNAL_FUNC(button_hide_show_clicked),
9378 gtk_widget_show(button_add);
9379 gtk_widget_show(button_clear);
9380 gtk_widget_show(button_hide_show);
9382 /* The interface is completely set up so we show the window and
9383 * enter the gtk_main loop.
9385 gtk_widget_show(window);
9390 <!-- example-end -->
9396 <!-- ***************************************************************** -->
9397 <chapter id="ch-CTreeWidget">
9398 <title>CTree Widget</title>
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>
9406 <para>This section of the tutorial is under development.</para>
9408 <!-- ----------------------------------------------------------------- -->
9409 <sect1 id="sec-CreatingACTree">
9410 <title>Creating a CTree</title>
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>
9417 <programlisting role="C">
9418 GtkWidget *gtk_ctree_new_with_titles( gint columns,
9422 GtkWidget *gtk_ctree_new( gint columns,
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
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>
9436 <programlisting role="C">
9437 /* CTree column titles /*
9438 char *titles[] = { "Location" , "Description" };
9441 ctree = gtk_ctree_new_with_titles(2, 0, titles);
9444 <para>This would create a new CTree with two columns entitled "Location"
9445 and "Description", with the first column containing the tree.</para>
9449 <!-- ----------------------------------------------------------------- -->
9450 <sect1 id="sec-AddingAndRemovingNodes">
9451 <title>Adding and Removing nodes</title>
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>
9458 <programlisting role="C">
9459 GtkCTreeNode *gtk_ctree_insert_node( GtkCTree *ctree,
9460 GtkCTreeNode *parent,
9461 GtkCTreeNode *sibling,
9464 GdkPixmap *pixmap_closed,
9465 GdkBitmap *mask_closed,
9466 GdkPixmap *pixmap_opened,
9467 GdkBitmap *mask_opened,
9469 gboolean expanded );
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
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>
9481 <para>Lets have a quick look at all of the parameters:</para>
9484 <listitem><simpara> <literal>ctree</literal> - the CTree widget we are manipulating</simpara>
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)
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>
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>
9501 <listitem><simpara> <literal>spacing</literal> - specifies the padding between the nodes pixmap
9502 and text elements, if a pixmap is provided</simpara>
9505 <listitem><simpara> <literal>pixmap_closed</literal> - a pixmap to display for a collapsed branch
9506 node and for a leaf node.</simpara>
9509 <listitem><simpara> <literal>mask_closed</literal> - a bitmap mask for the above pixmap.</simpara>
9512 <listitem><simpara> <literal>pixmap_opened</literal> - a pixmap to display for an expanded
9513 branch node.</simpara>
9516 <listitem><simpara> <literal>mask_opened</literal> - a bitmap mask for the above pixmap.</simpara>
9519 <listitem><simpara> <literal>is_leaf</literal> - indicates whether this is a leaf or branch node.</simpara>
9522 <listitem><simpara> <literal>expanded</literal> - indicates whether a branch node is initially
9523 expanded or collapsed.</simpara>
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>
9533 <para>To remove a node for a CTree, the following function is provided:</para>
9535 <programlisting role="C">
9536 void gtk_ctree_remove_node( GtkCTree *ctree,
9537 GtkCTreeNode *node );
9540 <para>As you can see, you merely need to specify a CTree and the node to
9545 <!-- ----------------------------------------------------------------- -->
9546 <sect1 id="sec-SettingCTreeAttributes">
9547 <title>Setting CTree Attributes</title>
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>
9553 <programlisting role="C">
9554 void gtk_ctree_set_indent( GtkCTree *ctree,
9557 void gtk_ctree_set_spacing( GtkCTree *ctree,
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>
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>
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
9573 <programlisting role="C">
9574 void gtk_ctree_set_line_style( GtkCTree *ctree,
9575 GtkCTreeLineStyle line_style );
9577 void gtk_ctree_set_expander_style( GtkCTree *ctree,
9578 GtkCTreeExpanderStyle expander_style );
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>
9585 <programlisting role="C">
9586 GTK_CTREE_LINES_NONE
9587 GTK_CTREE_LINES_SOLID
9588 GTK_CTREE_LINES_DOTTED
9589 GTK_CTREE_LINES_TABBED
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>
9596 <programlisting role="C">
9597 GTK_CTREE_EXPANDER_NONE
9598 GTK_CTREE_EXPANDER_SQUARE
9599 GTK_CTREE_EXPANDER_TRIANGLE
9600 GTK_CTREE_EXPANDER_CIRCULAR
9605 <!-- ----------------------------------------------------------------- -->
9606 <sect1 id="sec-UtilizingRowData">
9607 <title>Utilizing row data</title>
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>
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>
9617 <para>There are two functions for setting row data:</para>
9619 <programlisting role="C">
9620 void gtk_ctree_node_set_row_data( GtkCTree *ctree,
9624 void gtk_ctree_node_set_row_data_full( GtkCTree *ctree,
9627 GtkDestroyNotify destroy );
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>
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>
9639 <programlisting role="C">
9640 void destroy_func( gpointer data );
9643 <para>The paramter passed to this function will be the row data.</para>
9648 <!-- ***************************************************************** -->
9649 <chapter id="ch-TreeWidget">
9650 <title>Tree Widget</title>
9652 <!-- ----------------------------------------------------------------- -->
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>
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>
9667 <!-- ----------------------------------------------------------------- -->
9668 <sect1 id="sec-CreatingATree">
9669 <title>Creating a Tree</title>
9671 <para>A Tree is created in the usual way, using:</para>
9673 <programlisting role="C">
9674 GtkWidget *gtk_tree_new( void );
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>
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>
9689 <programlisting role="C">
9690 GtkWidget *gtk_tree_item_new_with_label( gchar *label );
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>
9697 <programlisting role="C">
9698 void gtk_tree_append( GtkTree *tree,
9699 GtkWidget *tree_item );
9701 void gtk_tree_prepend( GtkTree *tree,
9702 GtkWidget *tree_item );
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>
9710 <!-- ----------------------------------------------------------------- -->
9711 <sect1 id="sec-AddingASubtree">
9712 <title>Adding a Subtree</title>
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>
9717 <programlisting role="C">
9718 void gtk_tree_item_set_subtree( GtkTreeItem *tree_item,
9719 GtkWidget *subtree );
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>
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
9738 <!-- ----------------------------------------------------------------- -->
9739 <sect1 id="sec-HandlingTheSelectionList">
9740 <title>Handling the Selection List</title>
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>
9746 <programlisting role="C">
9747 void gtk_tree_set_selection_mode( GtkTree *tree,
9748 GtkSelectionMode mode );
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>
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>
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>
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>
9784 <!-- ----------------------------------------------------------------- -->
9785 <sect1 id="sec-TreeWidgetInternals">
9786 <title>Tree Widget Internals</title>
9788 <para>The Tree's struct definition looks like this:</para>
9790 <programlisting role="C">
9793 GtkContainer container;
9797 GtkTree* root_tree; /* owner of selection list */
9798 GtkWidget* tree_owner;
9802 guint current_indent;
9803 guint selection_mode : 2;
9804 guint view_mode : 1;
9805 guint view_line : 1;
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>
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>
9825 <programlisting role="C">
9826 children = gtk_container_children (GTK_CONTAINER (tree));
9828 do_something_nice (GTK_TREE_ITEM (children->data));
9829 children = g_list_remove_link (children, children);
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>
9840 <!-- ----------------------------------------------------------------- -->
9841 <sect2 id="sec-TreeSignals">
9842 <title>Signals</title>
9844 <programlisting role="C">
9845 void selection_changed( GtkTree *tree );
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>
9852 <programlisting role="C">
9853 void select_child( GtkTree *tree,
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>
9864 <programlisting role="C">
9865 void unselect_child (GtkTree *tree,
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>
9877 <!-- ----------------------------------------------------------------- -->
9878 <sect2 id="sec-TreeFunctionsAndMacros">
9879 <title>Functions and Macros</title>
9881 <programlisting role="C">
9882 guint gtk_tree_get_type( void );
9885 <para>Returns the "GtkTree" type identifier.</para>
9887 <programlisting role="C">
9888 GtkWidget* gtk_tree_new( void );
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>
9894 <programlisting role="C">
9895 void gtk_tree_append( GtkTree *tree,
9896 GtkWidget *tree_item );
9899 <para>Append a tree item to a Tree.</para>
9901 <programlisting role="C">
9902 void gtk_tree_prepend( GtkTree *tree,
9903 GtkWidget *tree_item );
9906 <para>Prepend a tree item to a Tree.</para>
9908 <programlisting role="C">
9909 void gtk_tree_insert( GtkTree *tree,
9910 GtkWidget *tree_item,
9914 <para>Insert a tree item into a Tree at the position in the list
9915 specified by <literal>position.</literal></para>
9917 <programlisting role="C">
9918 void gtk_tree_remove_items( GtkTree *tree,
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>
9928 <programlisting role="C">
9929 void gtk_tree_clear_items( GtkTree *tree,
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>
9939 <programlisting role="C">
9940 void gtk_tree_select_item( GtkTree *tree,
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>
9948 <programlisting role="C">
9949 void gtk_tree_unselect_item( GtkTree *tree,
9953 <para>Emits the "unselect_item" signal for the child at position
9954 <literal>item</literal>, thus unselecting the child.</para>
9956 <programlisting role="C">
9957 void gtk_tree_select_child( GtkTree *tree,
9958 GtkWidget *tree_item );
9961 <para>Emits the "select_item" signal for the child <literal>tree_item</literal>, thus
9962 selecting it.</para>
9964 <programlisting role="C">
9965 void gtk_tree_unselect_child( GtkTree *tree,
9966 GtkWidget *tree_item );
9969 <para>Emits the "unselect_item" signal for the child <literal>tree_item</literal>,
9970 thus unselecting it.</para>
9972 <programlisting role="C">
9973 gint gtk_tree_child_position( GtkTree *tree,
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>
9980 <programlisting role="C">
9981 void gtk_tree_set_selection_mode( GtkTree *tree,
9982 GtkSelectionMode mode );
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>
9991 <programlisting role="C">
9992 void gtk_tree_set_view_mode( GtkTree *tree,
9993 GtkTreeViewMode mode );
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>
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>
10007 <programlisting role="C">
10008 void gtk_tree_set_view_lines( GtkTree *tree,
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>
10016 <programlisting role="C">
10017 GtkTree *GTK_TREE (gpointer obj);
10020 <para>Cast a generic pointer to "GtkTree *".</para>
10022 <programlisting role="C">
10023 GtkTreeClass *GTK_TREE_CLASS (gpointer class);
10026 <para>Cast a generic pointer to "GtkTreeClass *".</para>
10028 <programlisting role="C">
10029 gint GTK_IS_TREE (gpointer obj);
10032 <para>Determine if a generic pointer refers to a "GtkTree" object.</para>
10034 <programlisting role="C">
10035 gint GTK_IS_ROOT_TREE (gpointer obj)
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>
10043 <programlisting role="C">
10044 GtkTree *GTK_TREE_ROOT_TREE (gpointer obj)
10047 <para>Return the root tree of a pointer to a "GtkTree" object. The above
10048 warning applies.</para>
10050 <programlisting role="C">
10051 GList *GTK_TREE_SELECTION_OLD( gpointer obj)
10054 <para>Return the selection list of the root tree of a "GtkTree" object. The
10055 above warning applies here, too.</para>
10060 <!-- ----------------------------------------------------------------- -->
10061 <sect1 id="sec-TreeItemWidget">
10062 <title>Tree Item Widget</title>
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>
10070 <para>The definition for the TreeItem struct looks like this:</para>
10072 <programlisting role="C">
10073 struct _GtkTreeItem
10077 GtkWidget *subtree;
10078 GtkWidget *pixmaps_box;
10079 GtkWidget *plus_pix_widget, *minus_pix_widget;
10081 GList *pixmaps; /* pixmap node for this items color depth */
10083 guint expanded : 1;
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>
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>
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);
10107 gtk_container_add (GTK_CONTAINER (tree_item), label_widget);
10108 gtk_widget_show (label_widget);
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>
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>
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);
10129 gtk_widget_unref (tree);
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>
10139 <!-- ----------------------------------------------------------------- -->
10141 <title>Signals</title>
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>
10147 <programlisting role="C">
10148 void select( GtkItem *tree_item );
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>
10155 <programlisting role="C">
10156 void deselect( GtkItem *tree_item );
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>
10165 <programlisting role="C">
10166 void toggle( GtkItem *tree_item );
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>
10175 <programlisting role="C">
10176 void expand( GtkTreeItem *tree_item );
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>
10183 <programlisting role="C">
10184 void collapse( GtkTreeItem *tree_item );
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>
10193 <!-- ----------------------------------------------------------------- -->
10195 <title>Functions and Macros</title>
10197 <programlisting role="C">
10198 guint gtk_tree_item_get_type( void );
10201 <para>Returns the "GtkTreeItem" type identifier.</para>
10203 <programlisting role="C">
10204 GtkWidget* gtk_tree_item_new( void );
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>
10210 <programlisting role="C">
10211 GtkWidget* gtk_tree_item_new_with_label (gchar *label);
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>
10218 <programlisting role="C">
10219 void gtk_tree_item_select( GtkTreeItem *tree_item );
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>
10226 <programlisting role="C">
10227 void gtk_tree_item_deselect( GtkTreeItem *tree_item );
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
10234 <programlisting role="C">
10235 void gtk_tree_item_set_subtree( GtkTreeItem *tree_item,
10236 GtkWidget *subtree );
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>
10243 <programlisting role="C">
10244 void gtk_tree_item_remove_subtree( GtkTreeItem *tree_item );
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>
10251 <programlisting role="C">
10252 void gtk_tree_item_expand( GtkTreeItem *tree_item );
10255 <para>This emits the "expand" signal on tree_item, which expands it.</para>
10257 <programlisting role="C">
10258 void gtk_tree_item_collapse( GtkTreeItem *tree_item );
10261 <para>This emits the "collapse" signal on tree_item, which collapses it.</para>
10263 <programlisting role="C">
10264 GtkTreeItem *GTK_TREE_ITEM (gpointer obj)
10267 <para>Cast a generic pointer to "GtkTreeItem *".</para>
10269 <programlisting role="C">
10270 GtkTreeItemClass *GTK_TREE_ITEM_CLASS (gpointer obj)
10273 <para>Cast a generic pointer to "GtkTreeItemClass".</para>
10275 <programlisting role="C">
10276 gint GTK_IS_TREE_ITEM (gpointer obj)
10279 <para>Determine if a generic pointer refers to a "GtkTreeItem" object.</para>
10281 <programlisting role="C">
10282 GtkWidget GTK_TREE_ITEM_SUBTREE (gpointer obj)
10285 <para>Returns a tree item's subtree (<literal>obj</literal> should point to a
10286 "GtkTreeItem" object).</para>
10291 <!-- ----------------------------------------------------------------- -->
10292 <sect1 id="sec-TreeExample">
10293 <title>Tree Example</title>
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>
10300 <programlisting role="C">
10301 <!-- example-start tree tree.c -->
10303 #define GTK_ENABLE_BROKEN
10304 #include <gtk/gtk.h>
10306 /* for all the GtkItem:: and GtkTreeItem:: signals */
10307 static void cb_itemsignal( GtkWidget *item,
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, &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);
10323 /* Note that this is never called */
10324 static void cb_unselect_child( GtkWidget *root_tree,
10326 GtkWidget *subtree )
10328 g_print ("unselect_child called for root tree %p, subtree %p, child %p\n",
10329 root_tree, subtree, child);
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)
10337 g_print ("select_child called for root tree %p, subtree %p, child %p\n",
10338 root_tree, subtree, child);
10341 static void cb_selection_changed( GtkWidget *tree )
10345 g_print ("selection_change called for tree %p\n", tree);
10346 g_print ("selected objects are:\n");
10348 i = GTK_TREE_SELECTION_OLD(tree);
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, &name);
10358 g_print ("\t%s on level %d\n", name, GTK_TREE
10359 (item->parent)->level);
10364 int main( int argc,
10367 GtkWidget *window, *scrolled_win, *tree;
10368 static gchar *itemnames[] = {"Foo", "Bar", "Baz", "Quux",
10372 gtk_init (&argc, &argv);
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);
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);
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),
10402 /* Set the selection mode */
10403 gtk_tree_set_selection_mode (GTK_TREE(tree),
10404 GTK_SELECTION_MULTIPLE);
10406 gtk_widget_show (tree);
10408 for (i = 0; i < 5; i++){
10409 GtkWidget *subtree, *item;
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,
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
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);
10454 for (j = 0; j < 5; j++){
10455 GtkWidget *subitem;
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);
10474 gtk_widget_show (subitem);
10478 /* Show the window and loop endlessly */
10479 gtk_widget_show (window);
10483 <!-- example-end -->
10489 <!-- ***************************************************************** -->
10490 <chapter id="ch-MenuWidget">
10491 <title>Menu Widget</title>
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>
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
10506 <!-- ----------------------------------------------------------------- -->
10507 <sect1 id="sec-ManualMenuCreation">
10508 <title>Manual Menu Creation</title>
10510 <para>In the true tradition of teaching, we'll show you the hard way
10511 first. <literal>:)</></para>
10513 <para>There are three widgets that go into making a menubar and submenus:</para>
10516 <listitem><simpara>a menu item, which is what the user wants to select, e.g.,
10519 <listitem><simpara>a menu, which acts as a container for the menu items, and</simpara>
10521 <listitem><simpara>a menubar, which is a container for each of the individual
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>
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>
10534 <programlisting role="C">
10535 GtkWidget *gtk_menu_bar_new( void );
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>
10542 <programlisting role="C">
10543 GtkWidget *gtk_menu_new( void );
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>
10551 <para>The next two calls are used to create menu items that are packed into
10552 the menu (and menubar).</para>
10554 <programlisting role="C">
10555 GtkWidget *gtk_menu_item_new( void );
10560 <programlisting role="C">
10561 GtkWidget *gtk_menu_item_new_with_label( const char *label );
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>
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>
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>
10582 <programlisting role="C">
10583 file_menu = gtk_menu_new (); /* Don't need to show menus */
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");
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);
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");
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");
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);
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>
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);
10623 file_item = gtk_menu_item_new_with_label ("File");
10624 gtk_widget_show (file_item);
10627 <para>Now we need to associate the menu with <literal>file_item</literal>. This is done
10628 with the function</para>
10630 <programlisting role="C">
10631 void gtk_menu_item_set_submenu( GtkMenuItem *menu_item,
10632 GtkWidget *submenu );
10635 <para>So, our example would continue with</para>
10637 <programlisting role="C">
10638 gtk_menu_item_set_submenu (GTK_MENU_ITEM (file_item), file_menu);
10641 <para>All that is left to do is to add the menu to the menubar, which is
10642 accomplished using the function</para>
10644 <programlisting role="C">
10645 void gtk_menu_bar_append( GtkMenuBar *menu_bar,
10646 GtkWidget *menu_item );
10649 <para>which in our case looks like this:</para>
10651 <programlisting role="C">
10652 gtk_menu_bar_append (GTK_MENU_BAR (menu_bar), file_item);
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
10660 <programlisting role="C">
10661 void gtk_menu_item_right_justify( GtkMenuItem *menu_item );
10664 <para>Here is a summary of the steps needed to create a menu bar with menus
10668 <listitem><simpara> Create a new menu using gtk_menu_new()</simpara>
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>
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
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>
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>
10689 <listitem><simpara> Use gtk_menu_bar_append() to put the root menu onto the menubar.</simpara>
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>
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,
10705 <simpara>and it will use the event to find out where to pop up the menu.</simpara>
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>
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));
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>
10728 <!-- ----------------------------------------------------------------- -->
10729 <sect1 id="sec-ManualMenuExample">
10730 <title>Manual Menu Example</title>
10732 <para>That should about do it. Let's take a look at an example to help clarify.</para>
10734 <programlisting role="C">
10735 <!-- example-start menu menu.c -->
10737 #include <stdio.h>
10738 #include <gtk/gtk.h>
10740 static gint button_press (GtkWidget *, GdkEvent *);
10741 static void menuitem_response (gchar *);
10743 int main( int argc,
10749 GtkWidget *menu_bar;
10750 GtkWidget *root_menu;
10751 GtkWidget *menu_items;
10757 gtk_init (&argc, &argv);
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);
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 ();
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. */
10778 for (i = 0; i < 3; i++)
10780 /* Copy the names to the buf. */
10781 sprintf (buf, "Test-undermenu - %d", i);
10783 /* Create a new menu-item with a name... */
10784 menu_items = gtk_menu_item_new_with_label (buf);
10786 /* ...and add it to the menu. */
10787 gtk_menu_append (GTK_MENU (menu), menu_items);
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));
10793 /* Show the widget */
10794 gtk_widget_show (menu_items);
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");
10802 gtk_widget_show (root_menu);
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);
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);
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);
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);
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);
10829 /* always display the window as the last step so it all splashes on
10830 * the screen at once. */
10831 gtk_widget_show (window);
10838 /* Respond to a button-press by posting a menu passed in as widget.
10840 * Note that the "widget" argument is the menu being posted, NOT
10841 * the button that was pressed.
10844 static gint button_press( GtkWidget *widget,
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
10857 /* Tell calling code that we have not handled this event; pass it on. */
10862 /* Print a string when a menu item is selected */
10864 static void menuitem_response( gchar *string )
10866 printf ("%s\n", string);
10868 <!-- example-end -->
10871 <para>You may also set a menu item to be insensitive and, using an accelerator
10872 table, bind keys to menu functions.</para>
10876 <!-- ----------------------------------------------------------------- -->
10877 <sect1 id="sec-UsingItemFactory">
10878 <title>Using ItemFactory</title>
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>
10885 <!-- ----------------------------------------------------------------- -->
10886 <sect1 id="sec-ItemFactoryExample">
10887 <title>Item Factory Example</title>
10889 <para>Here is an example using the GTK item factory.</para>
10891 <programlisting role="C">
10892 <!-- example-start menu itemfactory.c -->
10894 #include <gtk/gtk.h>
10895 #include <strings.h>
10897 /* Obligatory basic callback */
10898 static void print_hello( GtkWidget *w,
10901 g_message ("Hello, World!\n");
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:
10914 NULL -> "<Item>"
10916 "<Title>" -> create a title item
10917 "<Item>" -> create a simple item
10918 "<CheckItem>" -> create a check item
10919 "<ToggleItem>" -> create a toggle item
10920 "<RadioItem>" -> create a radio item
10921 <path> -> path of a radio item to link against
10922 "<Separator>" -> create a separator
10923 "<Branch>" -> create an item to hold sub items (optional)
10924 "<LastBranch>" -> create a right justified branch
10927 static GtkItemFactoryEntry menu_items[] = {
10928 { "/_File", NULL, NULL, 0, "<Branch>" },
10929 { "/File/_New", "<control>N", print_hello, 0, NULL },
10930 { "/File/_Open", "<control>O", print_hello, 0, NULL },
10931 { "/File/_Save", "<control>S", print_hello, 0, NULL },
10932 { "/File/Save _As", NULL, NULL, 0, NULL },
10933 { "/File/sep1", NULL, NULL, 0, "<Separator>" },
10934 { "/File/Quit", "<control>Q", gtk_main_quit, 0, NULL },
10935 { "/_Options", NULL, NULL, 0, "<Branch>" },
10936 { "/Options/Test", NULL, NULL, 0, NULL },
10937 { "/_Help", NULL, NULL, 0, "<LastBranch>" },
10938 { "/_Help/About", NULL, NULL, 0, NULL },
10942 void get_main_menu( GtkWidget *window,
10943 GtkWidget **menubar )
10945 GtkItemFactory *item_factory;
10946 GtkAccelGroup *accel_group;
10947 gint nmenu_items = sizeof (menu_items) / sizeof (menu_items[0]);
10949 accel_group = gtk_accel_group_new ();
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.
10959 item_factory = gtk_item_factory_new (GTK_TYPE_MENU_BAR, "<main>",
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);
10967 /* Attach the new accelerator group to the window. */
10968 gtk_window_add_accel_group (GTK_WINDOW (window), accel_group);
10971 /* Finally, return the actual menu bar created by the item factory. */
10972 *menubar = gtk_item_factory_get_widget (item_factory, "<main>");
10975 int main( int argc,
10979 GtkWidget *main_vbox;
10980 GtkWidget *menubar;
10982 gtk_init (&argc, &argv);
10984 window = gtk_window_new (GTK_WINDOW_TOPLEVEL);
10985 gtk_signal_connect (GTK_OBJECT (window), "destroy",
10986 GTK_SIGNAL_FUNC (gtk_main_quit),
10988 gtk_window_set_title (GTK_WINDOW(window), "Item Factory");
10989 gtk_widget_set_usize (GTK_WIDGET(window), 300, 200);
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);
10996 get_main_menu (window, &menubar);
10997 gtk_box_pack_start (GTK_BOX (main_vbox), menubar, FALSE, TRUE, 0);
10998 gtk_widget_show (menubar);
11000 gtk_widget_show (window);
11005 <!-- example-end -->
11008 <para>For now, there's only this example. An explanation and lots 'o' comments
11009 will follow later.</para>
11014 <!-- ***************************************************************** -->
11015 <chapter id="ch-TextWidget">
11016 <title>Text Widget</title>
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>
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>
11027 <!-- ----------------------------------------------------------------- -->
11028 <sect1 id="sec-CreatingAndConfiguringATextBox">
11029 <title>Creating and Configuring a Text box</title>
11031 <para>There is only one function for creating a new Text widget.</para>
11033 <programlisting role="C">
11034 GtkWidget *gtk_text_new( GtkAdjustment *hadj,
11035 GtkAdjustment *vadj );
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>
11043 <programlisting role="C">
11044 void gtk_text_set_adjustments( GtkText *text,
11045 GtkAdjustment *hadj,
11046 GtkAdjustment *vadj );
11049 <para>The above function allows the horizontal and vertical adjustments of a
11050 text widget to be changed at any time.</para>
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
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);
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>
11067 <para>Note, currently the Text widget does not support horizontal
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>
11075 <programlisting role="C">
11076 void gtk_text_set_editable( GtkText *text,
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>
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>
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>
11093 <programlisting role="C">
11094 void gtk_text_set_word_wrap( GtkText *text,
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>
11104 <!-- ----------------------------------------------------------------- -->
11105 <sect1 id="sec-TextManipulation">
11106 <title>Text Manipulation</title>
11108 <para>The current insertion point of a Text widget can be set using</para>
11110 <programlisting role="C">
11111 void gtk_text_set_point( GtkText *text,
11115 <para>where <literal>index</literal> is the position to set the insertion point.</para>
11117 <para>Analogous to this is the function for getting the current insertion
11120 <programlisting role="C">
11121 guint gtk_text_get_point( GtkText *text );
11124 <para>A function that is useful in combination with the above two functions
11127 <programlisting role="C">
11128 guint gtk_text_get_length( GtkText *text );
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
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>
11140 <programlisting role="C">
11141 void gtk_text_insert( GtkText *text,
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
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>
11165 <para>The following two functions perform this freeze and thaw action:</para>
11167 <programlisting role="C">
11168 void gtk_text_freeze( GtkText *text );
11170 void gtk_text_thaw( GtkText *text );
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>
11177 <programlisting role="C">
11178 gint gtk_text_backward_delete( GtkText *text,
11181 gint gtk_text_forward_delete ( GtkText *text,
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>
11189 <para>To retrieve larger blocks of text, we can use the function</para>
11191 <programlisting role="C">
11192 gchar *gtk_editable_get_chars( GtkEditable *editable,
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>
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
11207 <!-- ----------------------------------------------------------------- -->
11208 <sect1 id="sec-KeyBoardShortcuts">
11209 <title>Keyboard Shortcuts</title>
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>
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>
11220 <!-- ----------------------------------------------------------------- -->
11222 <title>Motion Shortcuts</title>
11224 <itemizedlist spacing=compact>
11225 <listitem><simpara> Ctrl-A Beginning of line</simpara>
11227 <listitem><simpara> Ctrl-E End of line</simpara>
11229 <listitem><simpara> Ctrl-N Next Line</simpara>
11231 <listitem><simpara> Ctrl-P Previous Line</simpara>
11233 <listitem><simpara> Ctrl-B Backward one character</simpara>
11235 <listitem><simpara> Ctrl-F Forward one character</simpara>
11237 <listitem><simpara> Alt-B Backward one word</simpara>
11239 <listitem><simpara> Alt-F Forward one word</simpara>
11245 <!-- ----------------------------------------------------------------- -->
11247 <title>Editing Shortcuts</title>
11249 <itemizedlist spacing=compact>
11250 <listitem><simpara> Ctrl-H Delete Backward Character (Backspace)</simpara>
11252 <listitem><simpara> Ctrl-D Delete Forward Character (Delete)</simpara>
11254 <listitem><simpara> Ctrl-W Delete Backward Word</simpara>
11256 <listitem><simpara> Alt-D Delete Forward Word</simpara>
11258 <listitem><simpara> Ctrl-K Delete to end of line</simpara>
11260 <listitem><simpara> Ctrl-U Delete line</simpara>
11266 <!-- ----------------------------------------------------------------- -->
11268 <title>Selection Shortcuts</title>
11270 <itemizedlist spacing=compact>
11271 <listitem><simpara> Ctrl-X Cut to clipboard</simpara>
11273 <listitem><simpara> Ctrl-C Copy to clipboard</simpara>
11275 <listitem><simpara> Ctrl-V Paste from clipboard</simpara>
11282 <!-- ----------------------------------------------------------------- -->
11283 <sect1 id="sec-AGtkTextExample">
11284 <title>A GtkText Example</title>
11286 <programlisting role="C">
11287 <!-- example-start text text.c -->
11291 #define GTK_ENABLE_BROKEN
11292 #include <stdio.h>
11293 #include <gtk/gtk.h>
11295 void text_toggle_editable (GtkWidget *checkbutton,
11298 gtk_text_set_editable(GTK_TEXT(text),
11299 GTK_TOGGLE_BUTTON(checkbutton)->active);
11302 void text_toggle_word_wrap (GtkWidget *checkbutton,
11305 gtk_text_set_word_wrap(GTK_TEXT(text),
11306 GTK_TOGGLE_BUTTON(checkbutton)->active);
11309 void close_application( GtkWidget *widget,
11315 int main( int argc,
11324 GtkWidget *separator;
11326 GtkWidget *vscrollbar;
11330 GdkFont *fixed_font;
11334 gtk_init (&argc, &argv);
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),
11342 gtk_window_set_title (GTK_WINDOW (window), "Text Widget Example");
11343 gtk_container_set_border_width (GTK_CONTAINER (window), 0);
11346 box1 = gtk_vbox_new (FALSE, 0);
11347 gtk_container_add (GTK_CONTAINER (window), box1);
11348 gtk_widget_show (box1);
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);
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);
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);
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);
11377 /* Get the system color map and allocate the color red */
11378 cmap = gdk_colormap_get_system();
11379 color.red = 0xffff;
11382 if (!gdk_color_alloc(cmap, &color)) {
11383 g_error("couldn't allocate color");
11386 /* Load a fixed font */
11387 fixed_font = gdk_font_load ("-misc-fixed-medium-r-*-*-*-140-*-*-*-*-*-*");
11389 /* Realizing a widget creates a window for it,
11390 * ready for us to insert some text */
11391 gtk_widget_realize (text);
11393 /* Freeze the text widget, ready for multiple updates */
11394 gtk_text_freeze (GTK_TEXT (text));
11396 /* Insert some colored text */
11397 gtk_text_insert (GTK_TEXT (text), NULL, &text->style->black, NULL,
11399 gtk_text_insert (GTK_TEXT (text), NULL, &color, NULL,
11401 gtk_text_insert (GTK_TEXT (text), NULL, &text->style->black, NULL,
11402 "text and different ", -1);
11403 gtk_text_insert (GTK_TEXT (text), fixed_font, &text->style->black, NULL,
11406 /* Load the file text.c into the text window */
11408 infile = fopen("text.c", "r");
11416 nchars = fread(buffer, 1, 1024, infile);
11417 gtk_text_insert (GTK_TEXT (text), fixed_font, NULL,
11418 NULL, buffer, nchars);
11427 /* Thaw the text widget, allowing the updates to become visible */
11428 gtk_text_thaw (GTK_TEXT (text));
11430 hbox = gtk_hbutton_box_new ();
11431 gtk_box_pack_start (GTK_BOX (box2), hbox, FALSE, FALSE, 0);
11432 gtk_widget_show (hbox);
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);
11447 separator = gtk_hseparator_new ();
11448 gtk_box_pack_start (GTK_BOX (box1), separator, FALSE, TRUE, 0);
11449 gtk_widget_show (separator);
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);
11456 button = gtk_button_new_with_label ("close");
11457 gtk_signal_connect (GTK_OBJECT (button), "clicked",
11458 GTK_SIGNAL_FUNC(close_application),
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);
11465 gtk_widget_show (window);
11471 <!-- example-end -->
11477 <!-- ***************************************************************** -->
11478 <chapter id="ch-UndocWidgets">
11479 <title>Undocumented Widgets</title>
11481 <para>These all require authors! :) Please consider contributing to our
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>
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>
11496 <!-- ----------------------------------------------------------------- -->
11497 <sect1 id="sec-Curves">
11498 <title>Curves</title>
11504 <!-- ----------------------------------------------------------------- -->
11505 <sect1 id="sec-DrawingArea">
11506 <title>Drawing Area</title>
11512 <!-- ----------------------------------------------------------------- -->
11513 <sect1 id="sec-FontSelectionDialog">
11514 <title>Font Selection Dialog</title>
11520 <!-- ----------------------------------------------------------------- -->
11521 <sect1 id="sec-GammaCurve">
11522 <title>Gamma Curve</title>
11528 <!-- ----------------------------------------------------------------- -->
11529 <sect1 id="sec-Image">
11530 <title>Image</title>
11536 <!-- ----------------------------------------------------------------- -->
11537 <sect1 id="sec-PlugsAndSockets">
11538 <title>Plugs and Sockets</title>
11544 <!-- ----------------------------------------------------------------- -->
11545 <sect1 id="sec-Preview">
11546 <title>Preview</title>
11552 <para>(This may need to be rewritten to follow the style of the rest of the tutorial)</para>
11554 <para><tscreen><verb></para>
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>
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>
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>
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>
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>
11592 <para>When Not to Use Previews</para>
11594 <para>Don't use previews for graphs, drawing, etc. GDK is much faster for that. Use
11595 previews only for rendered images!</para>
11597 <para>Let's go previews!</para>
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>
11605 <para> [Image][Image]</para>
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>
11612 <para>GtkWidget *preview!</para>
11614 <para>Without any ado:</para>
11616 <para> /* Create a preview widget,
11617 set its size, an show it */
11618 GtkWidget *preview;
11619 preview=gtk_preview_new(GTK_PREVIEW_COLOR)
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>
11626 <para>Oh yeah, like I said, previews look good inside frames, so how about:</para>
11628 <para>GtkWidget *create_a_preview(int Width,
11632 GtkWidget *preview;
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>
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>
11646 <para> my_preview_rendering_function(preview);
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>
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>
11668 <para> [Image]</para>
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>
11674 <para>gtk_table_attach(GTK_TABLE(table),label,0,1,0,1,
11676 GTK_EXPAND|GTK_FILL,
11678 gtk_table_attach(GTK_TABLE(table),frame,0,1,1,2,
11684 And here's the result:</para>
11686 <para> [Image]</para>
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
11695 <para>This is pretty much it as far as GTK is concerned.</para>
11697 <para>Filling In a Preview</para>
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>
11702 <para> [Image]</para>
11705 my_preview_rendering_function(GtkWidget *preview)
11708 #define HALF (SIZE/2)</para>
11710 <para> guchar *row=(guchar *) malloc(3*SIZE); /* 3 bits per dot */
11711 gint i, j; /* Coordinates */
11712 double r, alpha, x, y;</para>
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 */
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! */
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;
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 */
11737 <para> free(row); /* save some space */
11738 gtk_widget_draw(preview,NULL); /* what does this do? */
11739 gdk_flush(); /* or this? */
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>
11745 <para>Image Preview</para>
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
11755 <para>(UNTESTED CODE ALERT!!!)</para>
11757 <para>typedef struct {
11763 } ReducedImage;</para>
11767 SELECTION_IN_CONTEXT,
11771 <para>ReducedImage *Reduce_The_Image(GDrawable *drawable,
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>
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>
11790 <para> gimp_drawable_mask_bounds (drawable->id, &x1, &y1, &x2, &y2);
11793 /* If there's a SELECTION, we got its bounds!)</para>
11795 <para> if (width != drawable->width && 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>
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) {
11804 x2=drawable->width;
11806 y2=drawable->height;
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);
11818 <para> /* How we can determine the width and the height of the area being */
11821 height = y2-y1;</para>
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) {
11829 RH=(float) height * (float) LongerSize/ (float) width;
11833 RW=(float)width * (float) LongerSize/ (float) height;
11836 <para> /* The entire image is stretched into a string! */
11837 tempRGB = (guchar *) malloc(RW*RH*bytes);
11838 tempmask = (guchar *) malloc(RW*RH);</para>
11840 <para> gimp_pixel_rgn_init (&srcPR, drawable, x1, y1, width, height,
11842 gimp_pixel_rgn_init (&srcMask, mask, x1, y1, width, height,
11843 FALSE, FALSE);</para>
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>
11849 <para> for (i=0; i < RH; i++) {
11850 whichrow=(float)i*(float)height/(float)RH;
11851 gimp_pixel_rgn_get_row (&srcPR, src_row, x1, y1+whichrow, width);
11852 gimp_pixel_rgn_get_row (&srcMask, src_mask_row, x1, y1+whichrow, width);</para>
11854 <para> for (j=0; j < RW; j++) {
11855 whichcol=(float)j*(float)width/(float)RW;</para>
11857 <para> /* No selection made = each point is completely selected! */
11858 if (NoSelectionMade)
11859 tempmask[i*RW+j]=255;
11861 tempmask[i*RW+j]=src_mask_row[whichcol];</para>
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>
11868 <para> /* Hold on to the alpha as well */
11870 tempRGB[i*RW*bytes+j*bytes+3]=src_row[whichcol*bytes+3];
11877 temp->mask=tempmask;
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>
11885 <para>gint fake_transparency(gint i, gint j)
11887 if ( ((i%20)- 10) * ((j%20)- 10)>0 )
11893 <para>Now here's the preview function:</para>
11896 my_preview_render_function(GtkWidget *preview,
11900 gint Inten, bytes=drawable->bpp;
11903 gint RW=reduced->width;
11904 gint RH=reduced->height;
11905 guchar *row=malloc(bytes*RW);;</para>
11908 for (i=0; i < RH; i++) {
11909 for (j=0; j < RW; j++) {</para>
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>
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);
11921 gtk_preview_draw_row( GTK_PREVIEW(preview),row,0,i,RW);
11925 gtk_widget_draw(preview,NULL);
11929 <para>Applicable Routines</para>
11931 <para>guint gtk_preview_get_type (void);
11933 void gtk_preview_uninit (void);
11935 GtkWidget* gtk_preview_new (GtkPreviewType type);
11936 /* Described above */
11937 void gtk_preview_size (GtkPreview *preview,
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>
11946 <para>void gtk_preview_put (GtkPreview *preview,
11955 /* No idea */</para>
11957 <para>void gtk_preview_put_row (GtkPreview *preview,
11963 /* No idea */</para>
11965 <para>void gtk_preview_draw_row (GtkPreview *preview,
11970 /* Described in the text */</para>
11972 <para>void gtk_preview_set_expand (GtkPreview *preview,
11974 /* No idea */</para>
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>
11989 <para>That's all, folks!</para>
11991 <para></verb></tscreen></para>
11998 <!-- ***************************************************************** -->
11999 <chapter id="ch-SettingWidgetAttributes">
12000 <title>Setting Widget Attributes</title>
12002 <para>This describes the functions used to operate on widgets. These can be
12003 used to set style, padding, size, etc.</para>
12005 <para>(Maybe I should make a whole section on accelerators.)</para>
12007 <programlisting role="C">
12008 void gtk_widget_install_accelerator( GtkWidget *widget,
12009 GtkAcceleratorTable *table,
12010 gchar *signal_name,
12012 guint8 modifiers );
12014 void gtk_widget_remove_accelerator ( GtkWidget *widget,
12015 GtkAcceleratorTable *table,
12016 gchar *signal_name);
12018 void gtk_widget_activate( GtkWidget *widget );
12020 void gtk_widget_set_name( GtkWidget *widget,
12023 gchar *gtk_widget_get_name( GtkWidget *widget );
12025 void gtk_widget_set_sensitive( GtkWidget *widget,
12028 void gtk_widget_set_style( GtkWidget *widget,
12031 GtkStyle *gtk_widget_get_style( GtkWidget *widget );
12033 GtkStyle *gtk_widget_get_default_style( void );
12035 void gtk_widget_set_uposition( GtkWidget *widget,
12039 void gtk_widget_set_usize( GtkWidget *widget,
12043 void gtk_widget_grab_focus( GtkWidget *widget );
12045 void gtk_widget_show( GtkWidget *widget );
12047 void gtk_widget_hide( GtkWidget *widget );
12052 <!-- ***************************************************************** -->
12053 <chapter id="ch-Timeouts">
12054 <title>Timeouts, IO and Idle Functions</title>
12056 <!-- ----------------------------------------------------------------- -->
12057 <sect1 id="sec-Timeouts">
12058 <title>Timeouts</title>
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>
12065 <programlisting role="C">
12066 gint gtk_timeout_add( guint32 interval,
12067 GtkFunction function,
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
12077 <programlisting role="C">
12078 void gtk_timeout_remove( gint tag );
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,
12086 <para>The declaration of your callback should look something like this:</para>
12088 <programlisting role="C">
12089 gint timeout_callback( gpointer data );
12094 <!-- ----------------------------------------------------------------- -->
12095 <sect1 id="sec-MonitoringIO">
12096 <title>Monitoring IO</title>
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>
12103 <programlisting role="C">
12104 gint gdk_input_add( gint source,
12105 GdkInputCondition condition,
12106 GdkInputFunction function,
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>
12115 <listitem><simpara><literal>GDK_INPUT_READ</literal> - Call your function when there is data
12116 ready for reading on your file descriptor.</simpara>
12119 <listitem><simpara>><literal>GDK_INPUT_WRITE</literal> - Call your function when the file
12120 descriptor is ready for writing.</simpara>
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>
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>
12131 <programlisting role="C">
12132 void gdk_input_remove( gint tag );
12135 <para>The callback function should be declared as:</para>
12137 <programlisting role="C">
12138 void input_callback( gpointer data,
12140 GdkInputCondition condition );
12143 <para>Where <literal>source</literal> and <literal>condition</literal> are as specified above.</para>
12147 <!-- ----------------------------------------------------------------- -->
12148 <sect1 id="sec-IdleFunctions">
12149 <title>Idle Functions</title>
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>
12155 <programlisting role="C">
12156 gint gtk_idle_add( GtkFunction function,
12160 <para>This causes GTK to call the specified function whenever nothing else
12161 is happening.</para>
12163 <programlisting role="C">
12164 void gtk_idle_remove( gint tag );
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
12176 <!-- ***************************************************************** -->
12177 <chapter id="ch-AdvancedEventsAndSignals">
12178 <title>Advanced Event and Signal Handling</title>
12180 <!-- ----------------------------------------------------------------- -->
12181 <sect1 id="sec-SignalFunctions">
12182 <title>Signal Functions</title>
12184 <!-- ----------------------------------------------------------------- -->
12186 <title>Connecting and Disconnecting Signal Handlers</title>
12188 <programlisting role="C">
12189 guint gtk_signal_connect( GtkObject *object,
12191 GtkSignalFunc func,
12192 gpointer func_data );
12194 guint gtk_signal_connect_after( GtkObject *object,
12196 GtkSignalFunc func,
12197 gpointer func_data );
12199 guint gtk_signal_connect_object( GtkObject *object,
12201 GtkSignalFunc func,
12202 GtkObject *slot_object );
12204 guint gtk_signal_connect_object_after( GtkObject *object,
12206 GtkSignalFunc func,
12207 GtkObject *slot_object );
12209 guint gtk_signal_connect_full( GtkObject *object,
12211 GtkSignalFunc func,
12212 GtkCallbackMarshal marshal,
12214 GtkDestroyNotify destroy_func,
12215 gint object_signal,
12218 guint gtk_signal_connect_interp( GtkObject *object,
12220 GtkCallbackMarshal func,
12222 GtkDestroyNotify destroy_func,
12225 void gtk_signal_connect_object_while_alive( GtkObject *object,
12226 const gchar *signal,
12227 GtkSignalFunc func,
12228 GtkObject *alive_object );
12230 void gtk_signal_connect_while_alive( GtkObject *object,
12231 const gchar *signal,
12232 GtkSignalFunc func,
12233 gpointer func_data,
12234 GtkObject *alive_object );
12236 void gtk_signal_disconnect( GtkObject *object,
12237 guint handler_id );
12239 void gtk_signal_disconnect_by_func( GtkObject *object,
12240 GtkSignalFunc func,
12246 <!-- ----------------------------------------------------------------- -->
12248 <title>Blocking and Unblocking Signal Handlers</title>
12250 <programlisting role="C">
12251 void gtk_signal_handler_block( GtkObject *object,
12254 void gtk_signal_handler_block_by_func( GtkObject *object,
12255 GtkSignalFunc func,
12258 void gtk_signal_handler_block_by_data( GtkObject *object,
12261 void gtk_signal_handler_unblock( GtkObject *object,
12262 guint handler_id );
12264 void gtk_signal_handler_unblock_by_func( GtkObject *object,
12265 GtkSignalFunc func,
12268 void gtk_signal_handler_unblock_by_data( GtkObject *object,
12274 <!-- ----------------------------------------------------------------- -->
12276 <title>Emitting and Stopping Signals</title>
12278 <programlisting role="C">
12279 void gtk_signal_emit( GtkObject *object,
12283 void gtk_signal_emit_by_name( GtkObject *object,
12287 void gtk_signal_emitv( GtkObject *object,
12291 void gtk_signal_emitv_by_name( GtkObject *object,
12295 guint gtk_signal_n_emissions( GtkObject *object,
12298 guint gtk_signal_n_emissions_by_name( GtkObject *object,
12299 const gchar *name );
12301 void gtk_signal_emit_stop( GtkObject *object,
12304 void gtk_signal_emit_stop_by_name( GtkObject *object,
12305 const gchar *name );
12311 <!-- ----------------------------------------------------------------- -->
12312 <sect1 id="sec-SignalEmissionAndPropagation">
12313 <title>Signal Emission and Propagation</title>
12315 <para>Signal emission is the process whereby GTK runs all handlers for a
12316 specific object and signal.</para>
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>
12323 <para>The way an event (say "button_press_event") is handled, is:</para>
12326 <listitem><simpara>Start with the widget where the event occured.</simpara>
12329 <listitem><simpara>Emit the generic "event" signal. If that signal handler returns
12330 a value of TRUE, stop all processing.</simpara>
12333 <listitem><simpara>Otherwise, emit a specific, "button_press_event" signal. If that
12334 returns TRUE, stop all processing.</simpara>
12337 <listitem><simpara>Otherwise, go to the widget's parent, and repeat the above two
12341 <listitem><simpara>Continue until some signal handler returns TRUE, or until the
12342 top-level widget is reached.</simpara>
12346 <para>Some consequences of the above are:</para>
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>
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>
12363 <!-- ***************************************************************** -->
12364 <chapter id="ch-ManagingSelections">
12365 <title>Managing Selections</title>
12367 <!-- ----------------------------------------------------------------- -->
12368 <sect1 id="sec-SelectionsOverview">
12369 <title>Overview</title>
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>
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
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>
12405 <!-- ----------------------------------------------------------------- -->
12406 <sect1 id="sec-RetrievingTheSelection">
12407 <title>Retrieving the selection</title>
12409 <para>Retrieving the selection is an asynchronous process. To start the
12410 process, you call:</para>
12412 <programlisting role="C">
12413 gint gtk_selection_convert( GtkWidget *widget,
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>
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>
12432 <programlisting role="C">
12433 struct _GtkSelectionData
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>
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
12464 <programlisting role="C">
12465 <!-- example-start selection gettargets.c -->
12467 #include <gtk/gtk.h>
12469 void selection_received( GtkWidget *widget,
12470 GtkSelectionData *selection_data,
12473 /* Signal handler invoked when user clicks on the "Get Targets" button */
12474 void get_targets( GtkWidget *widget,
12477 static GdkAtom targets_atom = GDK_NONE;
12479 /* Get the atom corresponding to the string "TARGETS" */
12480 if (targets_atom == GDK_NONE)
12481 targets_atom = gdk_atom_intern ("TARGETS", FALSE);
12483 /* And request the "TARGETS" target for the primary selection */
12484 gtk_selection_convert (widget, GDK_SELECTION_PRIMARY, targets_atom,
12488 /* Signal handler called when the selections owner returns the data */
12489 void selection_received( GtkWidget *widget,
12490 GtkSelectionData *selection_data,
12497 /* **** IMPORTANT **** Check to see if retrieval succeeded */
12498 if (selection_data->length < 0)
12500 g_print ("Selection retrieval failed\n");
12503 /* Make sure we got the data in the expected form */
12504 if (selection_data->type != GDK_SELECTION_TYPE_ATOM)
12506 g_print ("Selection \"TARGETS\" was not returned as atoms!\n");
12510 /* Print out the atoms we received */
12511 atoms = (GdkAtom *)selection_data->data;
12514 for (i=0; i<selection_data->length/sizeof(GdkAtom); i++)
12517 name = gdk_atom_name (atoms[i]);
12519 g_print ("%s\n",name);
12521 g_print ("(bad atom)\n");
12527 int main( int argc,
12533 gtk_init (&argc, &argv);
12535 /* Create the toplevel window */
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);
12541 gtk_signal_connect (GTK_OBJECT (window), "destroy",
12542 GTK_SIGNAL_FUNC (gtk_exit), NULL);
12544 /* Create a button the user can click to get targets */
12546 button = gtk_button_new_with_label ("Get Targets");
12547 gtk_container_add (GTK_CONTAINER (window), button);
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);
12554 gtk_widget_show (button);
12555 gtk_widget_show (window);
12561 <!-- example-end -->
12565 <!-- ----------------------------------------------------------------- -->
12566 <sect1 id="sec-SupplyingTheSelection">
12567 <title>Supplying the selection</title>
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>
12573 <programlisting role="C">
12574 void gtk_selection_add_target (GtkWidget *widget,
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>
12585 <para>The callback function has the signature:</para>
12587 <programlisting role="C">
12588 void "selection_get" (GtkWidget *widget,
12589 GtkSelectionData *selection_data,
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
12602 <programlisting role="C">
12603 void gtk_selection_data_set( GtkSelectionData *selection_data,
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>
12614 <para>When prompted by the user, you claim ownership of the selection by
12617 <programlisting role="C">
12618 gint gtk_selection_owner_set( GtkWidget *widget,
12623 <para>If another application claims ownership of the selection, you will
12624 receive a "selection_clear_event".</para>
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>
12633 <programlisting role="C">
12634 <!-- example-start selection setselection.c -->
12636 #include <gtk/gtk.h>
12637 #include <time.h>
12639 /* Callback when the user toggles the selection */
12640 void selection_toggled( GtkWidget *widget,
12641 gint *have_selection )
12643 if (GTK_TOGGLE_BUTTON(widget)->active)
12645 *have_selection = gtk_selection_owner_set (widget,
12646 GDK_SELECTION_PRIMARY,
12648 /* if claiming the selection failed, we return the button to
12650 if (!*have_selection)
12651 gtk_toggle_button_set_active (GTK_TOGGLE_BUTTON(widget), FALSE);
12655 if (*have_selection)
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,
12662 *have_selection = FALSE;
12667 /* Called when another application claims the selection */
12668 gint selection_clear( GtkWidget *widget,
12669 GdkEventSelection *event,
12670 gint *have_selection )
12672 *have_selection = FALSE;
12673 gtk_toggle_button_set_active (GTK_TOGGLE_BUTTON(widget), FALSE);
12678 /* Supplies the current time as the selection. */
12679 void selection_handle( GtkWidget *widget,
12680 GtkSelectionData *selection_data,
12686 time_t current_time;
12688 current_time = time(NULL);
12689 timestr = asctime (localtime(&current_time));
12690 /* When we return a single string, it should not be null terminated.
12691 That will be done for us */
12693 gtk_selection_data_set (selection_data, GDK_SELECTION_TYPE_STRING,
12694 8, timestr, strlen(timestr));
12697 int main( int argc,
12701 GtkWidget *selection_button;
12703 static int have_selection = FALSE;
12705 gtk_init (&argc, &argv);
12707 /* Create the toplevel window */
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);
12713 gtk_signal_connect (GTK_OBJECT (window), "destroy",
12714 GTK_SIGNAL_FUNC (gtk_exit), NULL);
12716 /* Create a toggle button to act as the selection */
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);
12722 gtk_signal_connect (GTK_OBJECT(selection_button), "toggled",
12723 GTK_SIGNAL_FUNC (selection_toggled), &have_selection);
12724 gtk_signal_connect (GTK_OBJECT(selection_button), "selection_clear_event",
12725 GTK_SIGNAL_FUNC (selection_clear), &have_selection);
12727 gtk_selection_add_target (selection_button,
12728 GDK_SELECTION_PRIMARY,
12729 GDK_SELECTION_TYPE_STRING,
12731 gtk_signal_connect (GTK_OBJECT(selection_button), "selection_get",
12732 GTK_SIGNAL_FUNC (selection_handle), &have_selection);
12734 gtk_widget_show (selection_button);
12735 gtk_widget_show (window);
12741 <!-- example-end -->
12747 <!-- ***************************************************************** -->
12748 <chapter id="ch-DragAngDrop">
12749 <title>Drag-and-drop (DND)</title>
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
12756 <!-- ----------------------------------------------------------------- -->
12757 <sect1 id="sec-DragAndDropOverview">
12758 <title>Overview</title>
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>
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>
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>
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
12783 <para>So a typical drag-and-drop cycle would look as follows:</para>
12785 <listitem><simpara> Drag begins.</simpara>
12787 <listitem><simpara> Drag data request (when a drop occurs).</simpara>
12789 <listitem><simpara> Drop data received (may be on same or different
12790 application).</simpara>
12792 <listitem><simpara> Drag data delete (if the drag was a move).</simpara>
12794 <listitem><simpara> Drag-and-drop procedure done.</simpara>
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>
12803 <!-- ----------------------------------------------------------------- -->
12804 <sect1 id="sec-DragAndDropProperties">
12805 <title>Properties</title>
12807 <para>Drag data has the following properties:</para>
12810 <listitem><simpara> Drag action type (ie GDK_ACTION_COPY, GDK_ACTION_MOVE).</simpara>
12813 <listitem><simpara> Client specified arbitrary drag-and-drop type (a name and number pair).</simpara>
12816 <listitem><simpara> Sent and received data format type.</simpara>
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>
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
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
12851 <!-- ----------------------------------------------------------------- -->
12852 <sect1 id="sec-DragAndDropFunctions">
12853 <title>Functions</title>
12855 <!-- ----------------------------------------------------------------- -->
12856 <sect2 id="sec-DNDSourceWidgets">
12857 <title>Setting up the source widget</title>
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>
12862 <programlisting role="C">
12863 void gtk_drag_source_set( GtkWidget *widget,
12864 GdkModifierType start_button_mask,
12865 const GtkTargetEntry *targets,
12867 GdkDragAction actions );
12870 <para>The parameters signify the following:</para>
12872 <listitem><simpara><literal>widget</literal> specifies the drag source
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>
12878 <listitem><simpara><literal>targets</literal> specifies a table of
12879 target data types the drag will support</simpara>
12881 <listitem><simpara><literal>n_targets</literal> specifies the number of
12882 targets above</simpara>
12884 <listitem><simpara><literal>actions</literal> specifies a bitmask of
12885 possible actions for a drag from this window</simpara>
12889 <para>The <literal>targets</literal> parameter is an array of the
12890 following structure:</para>
12892 <programlisting role="C">
12893 struct GtkTargetEntry {
12900 <para>The fields specify a string representing the drag type, optional
12901 flags and application assigned integer identifier.</para>
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>
12908 <programlisting role="C">
12909 void gtk_drag_source_unset( GtkWidget *widget );
12914 <!-- ----------------------------------------------------------------- -->
12915 <sect2 id="sec-SignalsOnSourceWidgets">
12916 <title>Signals on the source widget:</title>
12918 <para>The source widget is sent the following signals during a
12919 drag-and-drop operation.</para>
12922 <title>Source widget signals</title>
12924 <colspec colname="Name" colwidth="150">
12925 <colspec colname="Prototype">
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>
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>
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>
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>
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>
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>
12963 <!-- ----------------------------------------------------------------- -->
12964 <sect2 id="sec-DNDDestWidgets">
12965 <title>Setting up a destination widget:</title>
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>
12971 <para> <literal> gtk_drag_dest_unset()</literal> specifies
12972 that the widget can no longer receive drops.</para>
12974 <programlisting role="C">
12975 void gtk_drag_dest_set( GtkWidget *widget,
12976 GtkDestDefaults flags,
12977 const GtkTargetEntry *targets,
12979 GdkDragAction actions );
12981 void gtk_drag_dest_unset( GtkWidget *widget );
12986 <!-- ----------------------------------------------------------------- -->
12987 <sect2 id="sec-SignalsOnDestWidgets">
12988 <title>Signals on the destination widget:</title>
12990 <para>The destination widget is sent the following signals during a
12991 drag-and-drop operation.</para>
12994 <title>Destination widget signals</title>
12996 <colspec colname="Name" colwidth="150">
12997 <colspec colname="Prototype">
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>
13013 <!-- ***************************************************************** -->
13014 <chapter id="ch-GLib">
13015 <title>GLib</title>
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>
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>
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
13043 <!-- ----------------------------------------------------------------- -->
13044 <sect1 id="sec-Definitions">
13045 <title>Definitions</title>
13047 <para>Definitions for the extremes of many of the standard types are:</para>
13049 <programlisting role="C">
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>
13067 <programlisting role="C">
13074 unsigned char guchar;
13075 unsigned short gushort;
13076 unsigned long gulong;
13077 unsigned int guint;
13081 long double gldouble;
13095 <!-- ----------------------------------------------------------------- -->
13096 <sect1 id="sec-DoublyLinkedLists">
13097 <title>Doubly Linked Lists</title>
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>
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>
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>
13120 <programlisting role="C">
13121 GList *g_list_append( GList *list,
13125 <para>This adds a new element (with value <literal>data</literal>) onto the end of the
13128 <programlisting role="C">
13129 GList *g_list_prepend( GList *list,
13133 <para>This adds a new element (with value <literal>data</literal>) to the beginning of the
13136 <programlisting role="C">
13137 GList *g_list_insert( GList *list,
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>
13146 <programlisting role="C">
13147 GList *g_list_remove( GList *list,
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>
13154 <programlisting role="C">
13155 void g_list_free( GList *list );
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
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>
13166 <programlisting role="C">
13167 GList *g_list_remove_link( GList *list,
13170 GList *g_list_reverse( GList *list );
13172 GList *g_list_nth( GList *list,
13175 GList *g_list_find( GList *list,
13178 GList *g_list_last( GList *list );
13180 GList *g_list_first( GList *list );
13182 gint g_list_length( GList *list );
13184 void g_list_foreach( GList *list,
13186 gpointer user_data );
13191 <!-- ----------------------------------------------------------------- -->
13192 <sect1 id="sec-SinglyLinkedLists">
13193 <title>Singly Linked Lists</title>
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>
13198 <programlisting role="C">
13199 GSList *g_slist_append( GSList *list,
13202 GSList *g_slist_prepend( GSList *list,
13205 GSList *g_slist_insert( GSList *list,
13209 GSList *g_slist_remove( GSList *list,
13212 GSList *g_slist_remove_link( GSList *list,
13215 GSList *g_slist_reverse( GSList *list );
13217 GSList *g_slist_nth( GSList *list,
13220 GSList *g_slist_find( GSList *list,
13223 GSList *g_slist_last( GSList *list );
13225 gint g_slist_length( GSList *list );
13227 void g_slist_foreach( GSList *list,
13229 gpointer user_data );
13235 <!-- ----------------------------------------------------------------- -->
13236 <sect1 id="sec-MemoryManagement">
13237 <title>Memory Management</title>
13239 <programlisting role="C">
13240 gpointer g_malloc( gulong size );
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>
13247 <programlisting role="C">
13248 gpointer g_malloc0( gulong size );
13251 <para>Same as above, but zeroes the memory before returning a pointer to it.</para>
13253 <programlisting role="C">
13254 gpointer g_realloc( gpointer mem,
13258 <para>Relocates "size" bytes of memory starting at "mem". Obviously, the
13259 memory should have been previously allocated.</para>
13261 <programlisting role="C">
13262 void g_free( gpointer mem );
13265 <para>Frees memory. Easy one. If <literal>mem</literal> is NULL it simply returns.</para>
13267 <programlisting role="C">
13268 void g_mem_profile( void );
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>
13274 <programlisting role="C">
13275 void g_mem_check( gpointer mem );
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>
13283 <!-- ----------------------------------------------------------------- -->
13284 <sect1 id="sec-Timers">
13285 <title>Timers</title>
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>
13293 <programlisting role="C">
13294 GTimer *g_timer_new( void );
13296 void g_timer_destroy( GTimer *timer );
13298 void g_timer_start( GTimer *timer );
13300 void g_timer_stop( GTimer *timer );
13302 void g_timer_reset( GTimer *timer );
13304 gdouble g_timer_elapsed( GTimer *timer,
13305 gulong *microseconds );
13310 <!-- ----------------------------------------------------------------- -->
13311 <sect1 id="sec-StringHandling">
13312 <title>String Handling</title>
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>
13321 <programlisting role="C">
13324 gchar *str; /* Points to the string's current \0-terminated value. */
13325 gint len; /* Current length */
13329 <para>As you might expect, there are a number of operations you can do with
13332 <programlisting role="C">
13333 GString *g_string_new( gchar *init );
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>
13340 <programlisting role="C">
13341 void g_string_free( GString *string,
13342 gint free_segment );
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>
13348 <programlisting role="C">
13349 GString *g_string_assign( GString *lval,
13350 const gchar *rval );
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()
13358 <para>The rest of these functions should be relatively obvious (the _c
13359 versions accept a character instead of a string):</para>
13361 <programlisting role="C">
13362 GString *g_string_truncate( GString *string,
13365 GString *g_string_append( GString *string,
13368 GString *g_string_append_c( GString *string,
13371 GString *g_string_prepend( GString *string,
13374 GString *g_string_prepend_c( GString *string,
13377 void g_string_sprintf( GString *string,
13381 void g_string_sprintfa ( GString *string,
13388 <!-- ----------------------------------------------------------------- -->
13389 <sect1 id="sec-UtilityAndErrorFunctions">
13390 <title>Utility and Error Functions</title>
13392 <programlisting role="C">
13393 gchar *g_strdup( const gchar *str );
13396 <para>Replacement strdup function. Copies the original strings contents to
13397 newly allocated memory, and returns a pointer to it.</para>
13399 <programlisting role="C">
13400 gchar *g_strerror( gint errnum );
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>
13406 <programlisting role="C">
13407 program name:function that failed:file or further description:strerror
13410 <para>Here's an example of one such call used in our hello_world program:</para>
13412 <programlisting role="C">
13413 g_print("hello_world:open:%s:%s\n", filename, g_strerror(errno));
13416 <programlisting role="C">
13417 void g_error( gchar *format, ... );
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>
13424 <programlisting role="C">
13425 void g_warning( gchar *format, ... );
13428 <para>Same as above, but prepends "** WARNING **: ", and does not exit the
13431 <programlisting role="C">
13432 void g_message( gchar *format, ... );
13435 <para>Prints "message: " prepended to the string you pass in.</para>
13437 <programlisting role="C">
13438 void g_print( gchar *format, ... );
13441 <para>Replacement for printf().</para>
13443 <para>And our last function:</para>
13445 <programlisting role="C">
13446 gchar *g_strsignal( gint signum );
13449 <para>Prints out the name of the Unix system signal given the signal number.
13450 Useful in generic signal handling functions.</para>
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>
13458 <!-- ***************************************************************** -->
13459 <chapter id="ch-GTKRCFiles">
13460 <title>GTK's rc Files</title>
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>
13466 <!-- ----------------------------------------------------------------- -->
13467 <sect1 id="sec-FunctionsForRCFiles">
13468 <title>Functions For rc Files</title>
13470 <para>When your application starts, you should include a call to:</para>
13472 <programlisting role="C">
13473 void gtk_rc_parse( char *filename );
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
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>
13484 <programlisting role="C">
13485 void gtk_widget_set_name( GtkWidget *widget,
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>
13493 <para>If we use a call something like this:</para>
13495 <programlisting role="C">
13496 button = gtk_button_new_with_label ("Special Button");
13497 gtk_widget_set_name (button, "special button");
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>
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>
13507 <programlisting role="C">
13508 window = gtk_window_new (GTK_WINDOW_TOPLEVEL);
13509 gtk_widget_set_name (window, "main window");
13512 <para>And then the style is defined in the rc file using:</para>
13514 <programlisting role="C">
13515 widget "main window.*GtkButton*" style "main_button"
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>
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>
13526 <!-- ----------------------------------------------------------------- -->
13527 <sect1 id="sec-GTKsRCFileFormat">
13528 <title>GTK's rc File Format</title>
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>
13535 <para>There are several directives to change the attributes of a widget.</para>
13538 <listitem><simpara>fg - Sets the foreground color of a widget.</simpara>
13540 <listitem><simpara>bg - Sets the background color of a widget.</simpara>
13542 <listitem><simpara>bg_pixmap - Sets the background of a widget to a tiled pixmap.</simpara>
13544 <listitem><simpara>font - Sets the font to be used with the given widget.</simpara>
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>
13552 <listitem><simpara>NORMAL - The normal state of a widget, without the mouse over top of
13553 it, and not being pressed, etc.</simpara>
13555 <listitem><simpara>PRELIGHT - When the mouse is over top of the widget, colors defined
13556 using this state will be in effect.</simpara>
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>
13561 <listitem><simpara>INSENSITIVE - When a widget is set insensitive, and cannot be
13562 activated, it will take these attributes.</simpara>
13564 <listitem><simpara>SELECTED - When an object is selected, it takes these attributes.</simpara>
13568 <para>When using the "fg" and "bg" keywords to set the colors of widgets, the
13571 <programlisting role="C">
13572 fg[<STATE>] = { Red, Green, Blue }
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>
13581 <para>bg_pixmap is very similar to the above, except the colors are replaced by a
13584 <para>pixmap_path is a list of paths separated by ":"'s. These paths will be
13585 searched for any pixmap you specify.</para>
13587 <para>The font directive is simply:</para>
13589 <programlisting role="C">
13590 font = "<font name>"
13593 <para>The only hard part is figuring out the font string. Using xfontsel or
13594 a similar utility should help.</para>
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>
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>
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>
13610 <para>When defining a style, you may assign the attributes of a previously defined
13611 style to this new one.</para>
13613 <programlisting role="C">
13614 style "main_button" = "button"
13616 font = "-adobe-helvetica-medium-r-normal--*-100-*-*-*-*-*-*"
13617 bg[PRELIGHT] = { 0.75, 0, 0 }
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"
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>
13630 <!-- ----------------------------------------------------------------- -->
13631 <sect1 id="sec-ExampleRCFile">
13632 <title>Example rc file</title>
13634 <programlisting role="C">
13635 # pixmap_path "<dir 1>:<dir 2>:<dir 3>:..."
13637 pixmap_path "/usr/include/X11R6/pixmaps:/home/imain/pixmaps"
13639 # style <name> [= <name>]
13644 # widget <widget_set> style <style_name>
13645 # widget_class <widget_class_set> style <style_name>
13647 # Here is a list of all the possible states. Note that some do not apply to
13650 # NORMAL - The normal state of a widget, without the mouse over top of
13651 # it, and not being pressed, etc.
13653 # PRELIGHT - When the mouse is over top of the widget, colors defined
13654 # using this state will be in effect.
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.
13659 # INSENSITIVE - When a widget is set insensitive, and cannot be
13660 # activated, it will take these attributes.
13662 # SELECTED - When an object is selected, it takes these attributes.
13664 # Given these states, we can set the attributes of the widgets in each of
13665 # these states using the following directives.
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.
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.
13678 #This sets the padding around the window to the pixmap specified.
13679 #bg_pixmap[<STATE>] = "<pixmap filename>"
13680 bg_pixmap[NORMAL] = "warning.xpm"
13685 #Sets the foreground color (font color) to red when in the "NORMAL"
13688 fg[NORMAL] = { 1.0, 0, 0 }
13690 #Sets the background pixmap of this widget to that of its parent.
13691 bg_pixmap[NORMAL] = "<parent>"
13696 # This shows all the possible states for a button. The only one that
13697 # doesn't apply is the SELECTED state.
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 }
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.
13713 style "main_button" = "button"
13715 font = "-adobe-helvetica-medium-r-normal--*-100-*-*-*-*-*-*"
13716 bg[PRELIGHT] = { 0.75, 0, 0 }
13719 style "toggle_button" = "button"
13721 fg[NORMAL] = { 1.0, 0, 0 }
13722 fg[ACTIVE] = { 1.0, 0, 0 }
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] = "<parent>"
13731 bg_pixmap[NORMAL] = "marble.xpm"
13732 fg[NORMAL] = { 1.0, 1.0, 1.0 }
13737 font = "-adobe-helvetica-medium-r-normal--*-80-*-*-*-*-*-*"
13740 # pixmap_path "~/.pixmaps"
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.
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"
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"
13764 <!-- ***************************************************************** -->
13765 <chapter id="ch-WritingYourOwnWidgets">
13766 <title>Writing Your Own Widgets</title>
13768 <!-- ----------------------------------------------------------------- -->
13769 <sect1 id="sec-WidgetsOverview">
13770 <title>Overview</title>
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>
13786 <para>Complete sources for the example widgets are available at the place you
13787 got this tutorial, or from:</para>
13789 <para><ulink url="http://www.gtk.org/~otaylor/gtk/tutorial/">http://www.gtk.org/~otaylor/gtk/tutorial/</ulink></para>
13794 <!-- ----------------------------------------------------------------- -->
13795 <sect1 id="sec-TheAnatomyOfAWidget">
13796 <title>The Anatomy Of A Widget</title>
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>
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
13815 <programlisting role="C">
13816 struct _GtkButtonClass
13818 GtkContainerClass parent_class;
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);
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>
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
13838 <programlisting role="C">
13841 GtkContainer container;
13845 guint in_button : 1;
13846 guint button_down : 1;
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>
13856 <!-- ----------------------------------------------------------------- -->
13857 <sect1 id="sec-CreatingACompositeWidget">
13858 <title>Creating a Composite widget</title>
13860 <!-- ----------------------------------------------------------------- -->
13862 <title>Introduction</title>
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>
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
13878 <!-- ----------------------------------------------------------------- -->
13880 <title>Choosing a parent class</title>
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>
13902 <!-- ----------------------------------------------------------------- -->
13904 <title>The header file</title>
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>
13911 <programlisting role="C">
13912 #ifndef __TICTACTOE_H__
13913 #define __TICTACTOE_H__
13917 #endif /* __TICTACTOE_H__ */
13920 <para>And to keep C++ programs that include the header file happy, in:</para>
13922 <programlisting role="C">
13925 #endif /* __cplusplus */
13931 #endif /* __cplusplus */
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>
13940 <para>Here is the complete header file:</para>
13942 <programlisting role="C">
13945 #ifndef __TICTACTOE_H__
13946 #define __TICTACTOE_H__
13948 #include <gdk/gdk.h>
13949 #include <gtk/gtkvbox.h>
13953 #endif /* __cplusplus */
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 ())
13960 typedef struct _Tictactoe Tictactoe;
13961 typedef struct _TictactoeClass TictactoeClass;
13967 GtkWidget *buttons[3][3];
13970 struct _TictactoeClass
13972 GtkVBoxClass parent_class;
13974 void (* tictactoe) (Tictactoe *ttt);
13977 GtkType tictactoe_get_type (void);
13978 GtkWidget* tictactoe_new (void);
13979 void tictactoe_clear (Tictactoe *ttt);
13983 #endif /* __cplusplus */
13985 #endif /* __TICTACTOE_H__ */
13990 <!-- ----------------------------------------------------------------- -->
13992 <title>The <literal>_get_type()</literal> function</title>
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>
14000 <programlisting role="C">
14002 tictactoe_get_type ()
14004 static guint ttt_type = 0;
14008 GtkTypeInfo ttt_info =
14011 sizeof (Tictactoe),
14012 sizeof (TictactoeClass),
14013 (GtkClassInitFunc) tictactoe_class_init,
14014 (GtkObjectInitFunc) tictactoe_init,
14015 (GtkArgSetFunc) NULL,
14016 (GtkArgGetFunc) NULL
14019 ttt_type = gtk_type_unique (gtk_vbox_get_type (), &ttt_info);
14026 <para>The GtkTypeInfo structure has the following definition:</para>
14028 <programlisting role="C">
14029 struct _GtkTypeInfo
14034 GtkClassInitFunc class_init_func;
14035 GtkObjectInitFunc object_init_func;
14036 GtkArgSetFunc arg_set_func;
14037 GtkArgGetFunc arg_get_func;
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,
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
14051 <!-- ----------------------------------------------------------------- -->
14053 <title>The <literal>_class_init()</literal> function</title>
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>
14059 <programlisting role="C">
14066 static gint tictactoe_signals[LAST_SIGNAL] = { 0 };
14069 tictactoe_class_init (TictactoeClass *class)
14071 GtkObjectClass *object_class;
14073 object_class = (GtkObjectClass*) class;
14075 tictactoe_signals[TICTACTOE_SIGNAL] = gtk_signal_new ("tictactoe",
14077 object_class->type,
14078 GTK_SIGNAL_OFFSET (TictactoeClass, tictactoe),
14079 gtk_signal_default_marshaller, GTK_TYPE_NONE, 0);
14082 gtk_object_class_add_signals (object_class, tictactoe_signals, LAST_SIGNAL);
14084 class->tictactoe = NULL;
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>
14094 <para>The function:</para>
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,
14107 <para>Creates a new signal. The parameters are:</para>
14110 <listitem><simpara> <literal>name</literal>: The name of the signal.</simpara>
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>
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>
14122 <listitem><simpara> <literal>function_offset</literal>: The offset within the class structure of
14123 a pointer to the default handler.</simpara>
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>
14132 <listitem><simpara> <literal>return_val</literal>: The type of the return val.</simpara>
14135 <listitem><simpara> <literal>nparams</literal>: The number of parameters of the signal handler
14136 (other than the two default ones mentioned above)</simpara>
14139 <listitem><simpara> <literal>...</literal>: The types of the parameters.</simpara>
14143 <para>When specifying types, the <literal>GtkType</literal> enumeration is used:</para>
14145 <programlisting role="C">
14168 /* it'd be great if the next two could be removed eventually */
14170 GTK_TYPE_C_CALLBACK,
14174 } GtkFundamentalType;
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>
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>
14192 <!-- ----------------------------------------------------------------- -->
14194 <title>The <literal>_init()</literal> function</title>
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>
14201 <programlisting role="C">
14203 tictactoe_init (Tictactoe *ttt)
14208 table = gtk_table_new (3, 3, TRUE);
14209 gtk_container_add (GTK_CONTAINER(ttt), table);
14210 gtk_widget_show (table);
14215 ttt->buttons[i][j] = gtk_toggle_button_new ();
14216 gtk_table_attach_defaults (GTK_TABLE(table), ttt->buttons[i][j],
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]);
14228 <!-- ----------------------------------------------------------------- -->
14230 <title>And the rest...</title>
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>
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>
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>
14250 <programlisting role="C">
14254 return GTK_WIDGET ( gtk_type_new (tictactoe_get_type ()));
14258 tictactoe_clear (Tictactoe *ttt)
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]),
14268 gtk_signal_handler_unblock_by_data (GTK_OBJECT(ttt->buttons[i][j]), ttt);
14273 tictactoe_toggle (GtkWidget *widget, Tictactoe *ttt)
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 } };
14284 int success, found;
14286 for (k=0; k<8; k++)
14293 success = success &&
14294 GTK_TOGGLE_BUTTON(ttt->buttons[rwins[k][i]][cwins[k][i]])->active;
14296 ttt->buttons[rwins[k][i]][cwins[k][i]] == widget;
14299 if (success && found)
14301 gtk_signal_emit (GTK_OBJECT (ttt),
14302 tictactoe_signals[TICTACTOE_SIGNAL]);
14309 <para>And finally, an example program using our Tictactoe widget:</para>
14311 <programlisting role="C">
14312 #include <gtk/gtk.h>
14313 #include "tictactoe.h"
14315 /* Invoked when a row, column or diagonal is completed */
14317 win (GtkWidget *widget, gpointer data)
14319 g_print ("Yay!\n");
14320 tictactoe_clear (TICTACTOE (widget));
14324 main (int argc, char *argv[])
14329 gtk_init (&argc, &argv);
14331 window = gtk_window_new (GTK_WINDOW_TOPLEVEL);
14333 gtk_window_set_title (GTK_WINDOW (window), "Aspect Frame");
14335 gtk_signal_connect (GTK_OBJECT (window), "destroy",
14336 GTK_SIGNAL_FUNC (gtk_exit), NULL);
14338 gtk_container_set_border_width (GTK_CONTAINER (window), 10);
14340 /* Create a new Tictactoe widget */
14341 ttt = tictactoe_new ();
14342 gtk_container_add (GTK_CONTAINER (window), ttt);
14343 gtk_widget_show (ttt);
14345 /* And attach to its "tictactoe" signal */
14346 gtk_signal_connect (GTK_OBJECT (ttt), "tictactoe",
14347 GTK_SIGNAL_FUNC (win), NULL);
14349 gtk_widget_show (window);
14360 <!-- ----------------------------------------------------------------- -->
14361 <sect1 id="sec-CreatingAWidgetFromScratch">
14362 <title>Creating a widget from scratch</title>
14364 <!-- ----------------------------------------------------------------- -->
14366 <title>Introduction</title>
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>
14375 <!-- ----------------------------------------------------------------- -->
14377 <title>Displaying a widget on the screen</title>
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>
14384 <listitem><simpara> <literal>WIDGETNAME_realize()</literal> is responsible for creating an X
14385 window for the widget if it has one.</simpara>
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>
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>
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>
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>
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>
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>
14433 <!-- ----------------------------------------------------------------- -->
14435 <title>The origins of the Dial Widget</title>
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>
14452 <!-- ----------------------------------------------------------------- -->
14454 <title>The Basics</title>
14456 <para>Quite a bit of our widget should look pretty familiar from the
14457 Tictactoe widget. First, we have a header file:</para>
14459 <programlisting role="C">
14460 /* GTK - The GIMP Toolkit
14461 * Copyright (C) 1995-1997 Peter Mattis, Spencer Kimball and Josh MacDonald
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.
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.
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.
14478 #ifndef __GTK_DIAL_H__
14479 #define __GTK_DIAL_H__
14481 #include <gdk/gdk.h>
14482 #include <gtk/gtkadjustment.h>
14483 #include <gtk/gtkwidget.h>
14488 #endif /* __cplusplus */
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 ())
14496 typedef struct _GtkDial GtkDial;
14497 typedef struct _GtkDialClass GtkDialClass;
14503 /* update policy (GTK_UPDATE_[CONTINUOUS/DELAYED/DISCONTINUOUS]) */
14506 /* Button currently pressed or 0 if none */
14509 /* Dimensions of dial components */
14511 gint pointer_width;
14513 /* ID of update timer, or 0 if none */
14516 /* Current angle */
14519 /* Old values from adjustment stored so we know when something changes */
14524 /* The adjustment object that stores the data for this dial */
14525 GtkAdjustment *adjustment;
14528 struct _GtkDialClass
14530 GtkWidgetClass parent_class;
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);
14540 void gtk_dial_set_adjustment (GtkDial *dial,
14541 GtkAdjustment *adjustment);
14544 #endif /* __cplusplus */
14547 #endif /* __GTK_DIAL_H__ */
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>
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>
14558 <programlisting role="C">
14559 #include <math.h>
14560 #include <stdio.h>
14561 #include <gtk/gtkmain.h>
14562 #include <gtk/gtksignal.h>
14564 #include "gtkdial.h"
14566 #define SCROLL_DELAY_LENGTH 300
14567 #define DIAL_DEFAULT_SIZE 100
14569 /* Forward declarations */
14571 [ omitted to save space ]
14575 static GtkWidgetClass *parent_class = NULL;
14578 gtk_dial_get_type ()
14580 static GtkType dial_type = 0;
14584 static const GtkTypeInfo dial_info =
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
14596 dial_type = gtk_type_unique (GTK_TYPE_WIDGET, &dial_info);
14603 gtk_dial_class_init (GtkDialClass *class)
14605 GtkObjectClass *object_class;
14606 GtkWidgetClass *widget_class;
14608 object_class = (GtkObjectClass*) class;
14609 widget_class = (GtkWidgetClass*) class;
14611 parent_class = gtk_type_class (gtk_widget_get_type ());
14613 object_class->destroy = gtk_dial_destroy;
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;
14625 gtk_dial_init (GtkDial *dial)
14628 dial->policy = GTK_UPDATE_CONTINUOUS;
14631 dial->pointer_width = 0;
14633 dial->old_value = 0.0;
14634 dial->old_lower = 0.0;
14635 dial->old_upper = 0.0;
14636 dial->adjustment = NULL;
14640 gtk_dial_new (GtkAdjustment *adjustment)
14644 dial = gtk_type_new (gtk_dial_get_type ());
14647 adjustment = (GtkAdjustment*) gtk_adjustment_new (0.0, 0.0, 0.0, 0.0, 0.0, 0.0);
14649 gtk_dial_set_adjustment (dial, adjustment);
14651 return GTK_WIDGET (dial);
14655 gtk_dial_destroy (GtkObject *object)
14659 g_return_if_fail (object != NULL);
14660 g_return_if_fail (GTK_IS_DIAL (object));
14662 dial = GTK_DIAL (object);
14664 if (dial->adjustment)
14665 gtk_object_unref (GTK_OBJECT (dial->adjustment));
14667 if (GTK_OBJECT_CLASS (parent_class)->destroy)
14668 (* GTK_OBJECT_CLASS (parent_class)->destroy) (object);
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>
14679 <para>Also, there are a few function to manipulate the widget's options:</para>
14681 <programlisting role="C">
14683 gtk_dial_get_adjustment (GtkDial *dial)
14685 g_return_val_if_fail (dial != NULL, NULL);
14686 g_return_val_if_fail (GTK_IS_DIAL (dial), NULL);
14688 return dial->adjustment;
14692 gtk_dial_set_update_policy (GtkDial *dial,
14693 GtkUpdateType policy)
14695 g_return_if_fail (dial != NULL);
14696 g_return_if_fail (GTK_IS_DIAL (dial));
14698 dial->policy = policy;
14702 gtk_dial_set_adjustment (GtkDial *dial,
14703 GtkAdjustment *adjustment)
14705 g_return_if_fail (dial != NULL);
14706 g_return_if_fail (GTK_IS_DIAL (dial));
14708 if (dial->adjustment)
14710 gtk_signal_disconnect_by_data (GTK_OBJECT (dial->adjustment), (gpointer) dial);
14711 gtk_object_unref (GTK_OBJECT (dial->adjustment));
14714 dial->adjustment = adjustment;
14715 gtk_object_ref (GTK_OBJECT (dial->adjustment));
14717 gtk_signal_connect (GTK_OBJECT (adjustment), "changed",
14718 (GtkSignalFunc) gtk_dial_adjustment_changed,
14720 gtk_signal_connect (GTK_OBJECT (adjustment), "value_changed",
14721 (GtkSignalFunc) gtk_dial_adjustment_value_changed,
14724 dial->old_value = adjustment->value;
14725 dial->old_lower = adjustment->lower;
14726 dial->old_upper = adjustment->upper;
14728 gtk_dial_update (dial);
14734 <!-- ----------------------------------------------------------------- -->
14736 <title><literal>gtk_dial_realize()</literal></title>
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>
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
14753 <programlisting role="C">
14755 gtk_dial_realize (GtkWidget *widget)
14758 GdkWindowAttr attributes;
14759 gint attributes_mask;
14761 g_return_if_fail (widget != NULL);
14762 g_return_if_fail (GTK_IS_DIAL (widget));
14764 GTK_WIDGET_SET_FLAGS (widget, GTK_REALIZED);
14765 dial = GTK_DIAL (widget);
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);
14780 attributes_mask = GDK_WA_X | GDK_WA_Y | GDK_WA_VISUAL | GDK_WA_COLORMAP;
14781 widget->window = gdk_window_new (widget->parent->window, &attributes, attributes_mask);
14783 widget->style = gtk_style_attach (widget->style, widget->window);
14785 gdk_window_set_user_data (widget->window, widget);
14787 gtk_style_set_background (widget->style, widget->window, GTK_STATE_ACTIVE);
14793 <!-- ----------------------------------------------------------------- -->
14795 <title>Size negotiation</title>
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>
14804 <programlisting role="C">
14806 gtk_dial_size_request (GtkWidget *widget,
14807 GtkRequisition *requisition)
14809 requisition->width = DIAL_DEFAULT_SIZE;
14810 requisition->height = DIAL_DEFAULT_SIZE;
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>
14824 <programlisting role="C">
14826 gtk_dial_size_allocate (GtkWidget *widget,
14827 GtkAllocation *allocation)
14831 g_return_if_fail (widget != NULL);
14832 g_return_if_fail (GTK_IS_DIAL (widget));
14833 g_return_if_fail (allocation != NULL);
14835 widget->allocation = *allocation;
14836 if (GTK_WIDGET_REALIZED (widget))
14838 dial = GTK_DIAL (widget);
14840 gdk_window_move_resize (widget->window,
14841 allocation->x, allocation->y,
14842 allocation->width, allocation->height);
14844 dial->radius = MAX(allocation->width,allocation->height) * 0.45;
14845 dial->pointer_width = dial->radius / 5;
14852 <!-- ----------------------------------------------------------------- -->
14854 <title><literal>gtk_dial_expose()</literal></title>
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>
14862 <programlisting role="C">
14864 gtk_dial_expose (GtkWidget *widget,
14865 GdkEventExpose *event)
14868 GdkPoint points[3];
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);
14879 if (event->count > 0)
14882 dial = GTK_DIAL (widget);
14884 gdk_window_clear_area (widget->window,
14886 widget->allocation.width,
14887 widget->allocation.height);
14889 xc = widget->allocation.width/2;
14890 yc = widget->allocation.height/2;
14894 for (i=0; i<25; i++)
14896 theta = (i*M_PI/18. - M_PI/6.);
14900 tick_length = (i%6 == 0) ? dial->pointer_width : dial->pointer_width/2;
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);
14912 s = sin(dial->angle);
14913 c = cos(dial->angle);
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;
14923 gtk_draw_polygon (widget->style,
14936 <!-- ----------------------------------------------------------------- -->
14938 <title>Event handling</title>
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>
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>
14959 <programlisting role="C">
14961 gtk_dial_button_press (GtkWidget *widget,
14962 GdkEventButton *event)
14968 double d_perpendicular;
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);
14974 dial = GTK_DIAL (widget);
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
14981 dx = event->x - widget->allocation.width / 2;
14982 dy = widget->allocation.height / 2 - event->y;
14984 s = sin(dial->angle);
14985 c = cos(dial->angle);
14987 d_parallel = s*dy + c*dx;
14988 d_perpendicular = fabs(s*dx - c*dy);
14990 if (!dial->button &&
14991 (d_perpendicular < dial->pointer_width/2) &&
14992 (d_parallel > - dial->pointer_width))
14994 gtk_grab_add (widget);
14996 dial->button = event->button;
14998 gtk_dial_update_mouse (dial, event->x, event->y);
15005 gtk_dial_button_release (GtkWidget *widget,
15006 GdkEventButton *event)
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);
15014 dial = GTK_DIAL (widget);
15016 if (dial->button == event->button)
15018 gtk_grab_remove (widget);
15022 if (dial->policy == GTK_UPDATE_DELAYED)
15023 gtk_timeout_remove (dial->timer);
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");
15034 gtk_dial_motion_notify (GtkWidget *widget,
15035 GdkEventMotion *event)
15038 GdkModifierType mods;
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);
15045 dial = GTK_DIAL (widget);
15047 if (dial->button != 0)
15052 if (event->is_hint || (event->window != widget->window))
15053 gdk_window_get_pointer (widget->window, &x, &y, &mods);
15055 switch (dial->button)
15058 mask = GDK_BUTTON1_MASK;
15061 mask = GDK_BUTTON2_MASK;
15064 mask = GDK_BUTTON3_MASK;
15072 gtk_dial_update_mouse (dial, x,y);
15079 gtk_dial_timer (GtkDial *dial)
15081 g_return_val_if_fail (dial != NULL, FALSE);
15082 g_return_val_if_fail (GTK_IS_DIAL (dial), FALSE);
15084 if (dial->policy == GTK_UPDATE_DELAYED)
15085 gtk_signal_emit_by_name (GTK_OBJECT (dial->adjustment), "value_changed");
15091 gtk_dial_update_mouse (GtkDial *dial, gint x, gint y)
15096 g_return_if_fail (dial != NULL);
15097 g_return_if_fail (GTK_IS_DIAL (dial));
15099 xc = GTK_WIDGET(dial)->allocation.width / 2;
15100 yc = GTK_WIDGET(dial)->allocation.height / 2;
15102 old_value = dial->adjustment->value;
15103 dial->angle = atan2(yc-y, x-xc);
15105 if (dial->angle < -M_PI/2.)
15106 dial->angle += 2*M_PI;
15108 if (dial->angle < -M_PI/6)
15109 dial->angle = -M_PI/6;
15111 if (dial->angle > 7.*M_PI/6.)
15112 dial->angle = 7.*M_PI/6.;
15114 dial->adjustment->value = dial->adjustment->lower + (7.*M_PI/6 - dial->angle) *
15115 (dial->adjustment->upper - dial->adjustment->lower) / (4.*M_PI/3.);
15117 if (dial->adjustment->value != old_value)
15119 if (dial->policy == GTK_UPDATE_CONTINUOUS)
15121 gtk_signal_emit_by_name (GTK_OBJECT (dial->adjustment), "value_changed");
15125 gtk_widget_draw (GTK_WIDGET(dial), NULL);
15127 if (dial->policy == GTK_UPDATE_DELAYED)
15130 gtk_timeout_remove (dial->timer);
15132 dial->timer = gtk_timeout_add (SCROLL_DELAY_LENGTH,
15133 (GtkFunction) gtk_dial_timer,
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>
15147 <programlisting role="C">
15149 gtk_dial_update (GtkDial *dial)
15153 g_return_if_fail (dial != NULL);
15154 g_return_if_fail (GTK_IS_DIAL (dial));
15156 new_value = dial->adjustment->value;
15158 if (new_value < dial->adjustment->lower)
15159 new_value = dial->adjustment->lower;
15161 if (new_value > dial->adjustment->upper)
15162 new_value = dial->adjustment->upper;
15164 if (new_value != dial->adjustment->value)
15166 dial->adjustment->value = new_value;
15167 gtk_signal_emit_by_name (GTK_OBJECT (dial->adjustment), "value_changed");
15170 dial->angle = 7.*M_PI/6. - (new_value - dial->adjustment->lower) * 4.*M_PI/3. /
15171 (dial->adjustment->upper - dial->adjustment->lower);
15173 gtk_widget_draw (GTK_WIDGET(dial), NULL);
15177 gtk_dial_adjustment_changed (GtkAdjustment *adjustment,
15182 g_return_if_fail (adjustment != NULL);
15183 g_return_if_fail (data != NULL);
15185 dial = GTK_DIAL (data);
15187 if ((dial->old_value != adjustment->value) ||
15188 (dial->old_lower != adjustment->lower) ||
15189 (dial->old_upper != adjustment->upper))
15191 gtk_dial_update (dial);
15193 dial->old_value = adjustment->value;
15194 dial->old_lower = adjustment->lower;
15195 dial->old_upper = adjustment->upper;
15200 gtk_dial_adjustment_value_changed (GtkAdjustment *adjustment,
15205 g_return_if_fail (adjustment != NULL);
15206 g_return_if_fail (data != NULL);
15208 dial = GTK_DIAL (data);
15210 if (dial->old_value != adjustment->value)
15212 gtk_dial_update (dial);
15214 dial->old_value = adjustment->value;
15221 <!-- ----------------------------------------------------------------- -->
15223 <title>Possible Enhancements</title>
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>
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>
15240 <listitem><simpara> The user should be able to use the up and down arrow keys to
15241 increase and decrease the value.</simpara>
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>
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>
15262 <!-- ----------------------------------------------------------------- -->
15263 <sect1 id="sec-LearningMore">
15264 <title>Learning More</title>
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.
15277 <!-- ***************************************************************** -->
15278 <chapter id="ch-Scribble">
15279 <title>Scribble, A Simple Example Drawing Program</title>
15281 <!-- ----------------------------------------------------------------- -->
15282 <sect1 id="sec-ScribbleOverview">
15283 <title>Overview</title>
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>
15295 <!-- ----------------------------------------------------------------- -->
15296 <sect1 id="sec-EventHandling">
15297 <title>Event Handling</title>
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)
15309 <programlisting role="C">
15310 struct _GdkEventMotion
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>
15330 <programlisting role="C">
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>
15351 <programlisting role="C">
15352 void gtk_widget_set_events (GtkWidget *widget,
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>
15360 <programlisting role="C">
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
15371 GDK_KEY_RELEASE_MASK
15372 GDK_ENTER_NOTIFY_MASK
15373 GDK_LEAVE_NOTIFY_MASK
15374 GDK_FOCUS_CHANGE_MASK
15376 GDK_PROPERTY_CHANGE_MASK
15377 GDK_PROXIMITY_IN_MASK
15378 GDK_PROXIMITY_OUT_MASK
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>
15389 <programlisting role="C">
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>
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>
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>
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>
15438 <programlisting role="C">
15439 GdkWindow* gdk_window_get_pointer (GdkWindow *window,
15442 GdkModifierType *mask);
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>
15450 <para>The code to set the events for our window then looks like:</para>
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);
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);
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>
15473 <programlisting role="C">
15475 button_press_event (GtkWidget *widget, GdkEventButton *event)
15477 if (event->button == 1 && pixmap != NULL)
15478 draw_brush (widget, event->x, event->y);
15484 motion_notify_event (GtkWidget *widget, GdkEventMotion *event)
15487 GdkModifierType state;
15489 if (event->is_hint)
15490 gdk_window_get_pointer (event->window, &x, &y, &state);
15495 state = event->state;
15498 if (state & GDK_BUTTON1_MASK && pixmap != NULL)
15499 draw_brush (widget, x, y);
15507 <!-- ----------------------------------------------------------------- -->
15508 <sect1 id="sec-TheDrawingAreaWidget">
15509 <title>The DrawingArea Widget, And Drawing</title>
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>
15517 <programlisting role="C">
15518 GtkWidget* gtk_drawing_area_new (void);
15521 <para>A default size for the widget can be specified by calling:</para>
15523 <programlisting role="C">
15524 void gtk_drawing_area_size (GtkDrawingArea *darea,
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>
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>
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>
15549 <para>To create an offscreen pixmap, we call the function:</para>
15551 <programlisting role="C">
15552 GdkPixmap* gdk_pixmap_new (GdkWindow *window,
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>
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>
15569 <programlisting role="C">
15570 /* Backing pixmap for drawing area */
15571 static GdkPixmap *pixmap = NULL;
15573 /* Create a new backing pixmap of the appropriate size */
15575 configure_event (GtkWidget *widget, GdkEventConfigure *event)
15578 gdk_pixmap_unref(pixmap);
15580 pixmap = gdk_pixmap_new(widget->window,
15581 widget->allocation.width,
15582 widget->allocation.height,
15584 gdk_draw_rectangle (pixmap,
15585 widget->style->white_gc,
15588 widget->allocation.width,
15589 widget->allocation.height);
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>
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>
15602 <programlisting role="C">
15603 /* Redraw the screen from the backing pixmap */
15605 expose_event (GtkWidget *widget, GdkEventExpose *event)
15607 gdk_draw_pixmap(widget->window,
15608 widget->style->fg_gc[GTK_WIDGET_STATE (widget)],
15610 event->area.x, event->area.y,
15611 event->area.x, event->area.y,
15612 event->area.width, event->area.height);
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>
15627 <programlisting role="C">
15629 gdk_draw_rectangle ()
15631 gdk_draw_polygon ()
15638 gdk_draw_segments ()
15641 <para>See the reference documentation or the header file
15642 <literal><gdk/gdk.h></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>
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>
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)]
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>
15667 <programlisting role="C">
15670 GTK_STATE_PRELIGHT,
15671 GTK_STATE_SELECTED,
15672 GTK_STATE_INSENSITIVE
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>
15678 <para>Our function <literal>draw_brush()</literal>, which does the actual drawing
15679 on the screen, is then:</para>
15681 <programlisting role="C">
15682 /* Draw a rectangle on the screen */
15684 draw_brush (GtkWidget *widget, gdouble x, gdouble y)
15686 GdkRectangle update_rect;
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,
15695 update_rect.x, update_rect.y,
15696 update_rect.width, update_rect.height);
15697 gtk_widget_draw (widget, &update_rect);
15701 <para>After we draw the rectangle representing the brush onto the pixmap,
15702 we call the function:</para>
15704 <programlisting role="C">
15705 void gtk_widget_draw (GtkWidget *widget,
15706 GdkRectangle *area);
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>
15715 <para>We have now covered the entire drawing program except for a few
15716 mundane details like creating the main window.</para>
15720 <!-- ----------------------------------------------------------------- -->
15721 <sect1 id="sec-AddingXInputSupport">
15722 <title>Adding XInput support</title>
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,
15732 <listitem><simpara> Pressure sensitivity</simpara>
15734 <listitem><simpara> Tilt reporting</simpara>
15736 <listitem><simpara> Sub-pixel positioning</simpara>
15738 <listitem><simpara> Multiple inputs (for example, a stylus with a point and eraser)</simpara>
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>
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>
15749 <programlisting role="C">
15750 struct _GdkEventMotion
15762 GdkInputSource source;
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
15775 <programlisting role="C">
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
15788 <!-- ----------------------------------------------------------------- -->
15790 <title>Enabling extended device information</title>
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>
15795 <programlisting role="C">
15796 gtk_widget_set_extension_events (drawing_area, GDK_EXTENSION_EVENTS_CURSOR);
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>
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>
15815 <programlisting role="C">
15817 input_dialog_destroy (GtkWidget *w, gpointer data)
15819 *((GtkWidget **)data) = NULL;
15823 create_input_dialog ()
15825 static GtkWidget *inputd = NULL;
15829 inputd = gtk_input_dialog_new();
15831 gtk_signal_connect (GTK_OBJECT(inputd), "destroy",
15832 (GtkSignalFunc)input_dialog_destroy, &inputd);
15833 gtk_signal_connect_object (GTK_OBJECT(GTK_INPUT_DIALOG(inputd)->close_button),
15835 (GtkSignalFunc)gtk_widget_hide,
15836 GTK_OBJECT(inputd));
15837 gtk_widget_hide ( GTK_INPUT_DIALOG(inputd)->save_button);
15839 gtk_widget_show (inputd);
15843 if (!GTK_WIDGET_MAPPED(inputd))
15844 gtk_widget_show(inputd);
15846 gdk_window_raise(inputd->window);
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
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>
15863 <!-- ----------------------------------------------------------------- -->
15865 <title>Using extended device information</title>
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>
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>
15879 <programlisting role="C">
15880 void gdk_input_window_get_pointer( GdkWindow *window,
15887 GdkModifierType *mask);
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>
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>
15901 <programlisting role="C">
15903 button_press_event (GtkWidget *widget, GdkEventButton *event)
15905 print_button_press (event->deviceid);
15907 if (event->button == 1 && pixmap != NULL)
15908 draw_brush (widget, event->source, event->x, event->y, event->pressure);
15914 motion_notify_event (GtkWidget *widget, GdkEventMotion *event)
15918 GdkModifierType state;
15920 if (event->is_hint)
15921 gdk_input_window_get_pointer (event->window, event->deviceid,
15922 &x, &y, &pressure, NULL, NULL, &state);
15927 pressure = event->pressure;
15928 state = event->state;
15931 if (state & GDK_BUTTON1_MASK && pixmap != NULL)
15932 draw_brush (widget, event->source, x, y, pressure);
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>
15943 <programlisting role="C">
15944 /* Draw a rectangle on the screen, size depending on pressure,
15945 and color on the type of device */
15947 draw_brush (GtkWidget *widget, GdkInputSource source,
15948 gdouble x, gdouble y, gdouble pressure)
15951 GdkRectangle update_rect;
15955 case GDK_SOURCE_MOUSE:
15956 gc = widget->style->dark_gc[GTK_WIDGET_STATE (widget)];
15958 case GDK_SOURCE_PEN:
15959 gc = widget->style->black_gc;
15961 case GDK_SOURCE_ERASER:
15962 gc = widget->style->white_gc;
15965 gc = widget->style->light_gc[GTK_WIDGET_STATE (widget)];
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, &update_rect);
15981 <!-- ----------------------------------------------------------------- -->
15983 <title>Finding out more about a device</title>
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>
15989 <programlisting role="C">
15990 GList *gdk_input_list_devices (void);
15993 <para>which returns a GList (a linked list type from the GLib library)
15994 of GdkDeviceInfo structures. The GdkDeviceInfo structure is defined
15997 <programlisting role="C">
15998 struct _GdkDeviceInfo
16002 GdkInputSource source;
16008 GdkDeviceKey *keys;
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>
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>
16024 <programlisting role="C">
16026 print_button_press (guint32 deviceid)
16030 /* gdk_input_list_devices returns an internal list, so we shouldn't
16031 free it afterwards */
16032 tmp_list = gdk_input_list_devices();
16036 GdkDeviceInfo *info = (GdkDeviceInfo *)tmp_list->data;
16038 if (info->deviceid == deviceid)
16040 printf("Button press on device '%s'\n", info->name);
16044 tmp_list = tmp_list->next;
16049 <para>That completes the changes to "XInputize" our program.</para>
16053 <!-- ----------------------------------------------------------------- -->
16054 <sect2 id="sec-FurtherSophistications">
16055 <title>Further sophistications</title>
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
16065 <para>To restore the state next time the program is run, GDK provides
16066 functions to change device configuration:</para>
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()
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>
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>
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>
16108 <!-- ***************************************************************** -->
16109 <chapter id="ch-Tips">
16110 <title>Tips For Writing GTK Applications</title>
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>
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>
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
16132 <!-- ***************************************************************** -->
16133 <chapter id="ch-Contributing">
16134 <title>Contributing</title>
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>
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>
16147 <para>Thank you.</para>
16151 <!-- ***************************************************************** -->
16152 <chapter id="ch-Credits">
16153 <title>Credits</title>
16155 <para>We would like to thank the following for their contributions to this text.</para>
16158 <listitem><simpara>Bawer Dagdeviren, <literal><ulink url="mailto:chamele0n@geocities.com">chamele0n@geocities.com</ulink></literal> for the menus tutorial.</simpara>
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>
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>
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>
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>
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>
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>
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>
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>
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>
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>
16208 <listitem><simpara>Stefan Mars <literal><ulink url="mailto:mars@lysator.liu.se">mars@lysator.liu.se</ulink></literal> for the CList section.</simpara>
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>
16217 <listitem><simpara>David King for style checking the entire document.</simpara>
16221 <para>And to all of you who commented on and helped refine this document.</para>
16223 <para>Thanks.</para>
16227 <!-- ***************************************************************** -->
16228 <chapter id="ch-Copyright">
16229 <title>Tutorial Copyright and Permissions Notice</title>
16231 <para>The GTK Tutorial is Copyright (C) 1997 Ian Main. </para>
16233 <para>Copyright (C) 1998-1999 Tony Gale.</para>
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>
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>
16245 <para>Permission is granted to copy and distribute translations of this
16246 document into another language, under the above conditions for modified
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>
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>
16260 <!-- ***************************************************************** -->
16261 <!-- ***************************************************************** -->
16263 <!-- ***************************************************************** -->
16264 <appendix id="app-GTKSignals">
16265 <title>GTK Signals</title>
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>
16272 <!-- ----------------------------------------------------------------- -->
16273 <sect1 id="sec-GtkObject">
16274 <title>GtkObject</title>
16276 <programlisting role="C">
16277 void GtkObject::destroy (GtkObject *,
16283 <!-- ----------------------------------------------------------------- -->
16284 <sect1 id="sec-GtkWidget">
16285 <title>GtkWidget</title>
16287 <programlisting role="C">
16288 void GtkWidget::show (GtkWidget *,
16290 void GtkWidget::hide (GtkWidget *,
16292 void GtkWidget::map (GtkWidget *,
16294 void GtkWidget::unmap (GtkWidget *,
16296 void GtkWidget::realize (GtkWidget *,
16298 void GtkWidget::unrealize (GtkWidget *,
16300 void GtkWidget::draw (GtkWidget *,
16303 void GtkWidget::draw-focus (GtkWidget *,
16305 void GtkWidget::draw-default (GtkWidget *,
16307 void GtkWidget::size-request (GtkWidget *,
16310 void GtkWidget::size-allocate (GtkWidget *,
16313 void GtkWidget::state-changed (GtkWidget *,
16316 void GtkWidget::parent-set (GtkWidget *,
16319 void GtkWidget::style-set (GtkWidget *,
16322 void GtkWidget::add-accelerator (GtkWidget *,
16329 void GtkWidget::remove-accelerator (GtkWidget *,
16334 gboolean GtkWidget::event (GtkWidget *,
16337 gboolean GtkWidget::button-press-event (GtkWidget *,
16340 gboolean GtkWidget::button-release-event (GtkWidget *,
16343 gboolean GtkWidget::motion-notify-event (GtkWidget *,
16346 gboolean GtkWidget::delete-event (GtkWidget *,
16349 gboolean GtkWidget::destroy-event (GtkWidget *,
16352 gboolean GtkWidget::expose-event (GtkWidget *,
16355 gboolean GtkWidget::key-press-event (GtkWidget *,
16358 gboolean GtkWidget::key-release-event (GtkWidget *,
16361 gboolean GtkWidget::enter-notify-event (GtkWidget *,
16364 gboolean GtkWidget::leave-notify-event (GtkWidget *,
16367 gboolean GtkWidget::configure-event (GtkWidget *,
16370 gboolean GtkWidget::focus-in-event (GtkWidget *,
16373 gboolean GtkWidget::focus-out-event (GtkWidget *,
16376 gboolean GtkWidget::map-event (GtkWidget *,
16379 gboolean GtkWidget::unmap-event (GtkWidget *,
16382 gboolean GtkWidget::property-notify-event (GtkWidget *,
16385 gboolean GtkWidget::selection-clear-event (GtkWidget *,
16388 gboolean GtkWidget::selection-request-event (GtkWidget *,
16391 gboolean GtkWidget::selection-notify-event (GtkWidget *,
16394 void GtkWidget::selection-get (GtkWidget *,
16395 GtkSelectionData *,
16398 void GtkWidget::selection-received (GtkWidget *,
16399 GtkSelectionData *,
16402 gboolean GtkWidget::proximity-in-event (GtkWidget *,
16405 gboolean GtkWidget::proximity-out-event (GtkWidget *,
16408 void GtkWidget::drag-begin (GtkWidget *,
16411 void GtkWidget::drag-end (GtkWidget *,
16414 void GtkWidget::drag-data-delete (GtkWidget *,
16417 void GtkWidget::drag-leave (GtkWidget *,
16421 gboolean GtkWidget::drag-motion (GtkWidget *,
16427 gboolean GtkWidget::drag-drop (GtkWidget *,
16433 void GtkWidget::drag-data-get (GtkWidget *,
16435 GtkSelectionData *,
16439 void GtkWidget::drag-data-received (GtkWidget *,
16443 GtkSelectionData *,
16447 gboolean GtkWidget::client-event (GtkWidget *,
16450 gboolean GtkWidget::no-expose-event (GtkWidget *,
16453 gboolean GtkWidget::visibility-notify-event (GtkWidget *,
16456 void GtkWidget::debug-msg (GtkWidget *,
16463 <!-- ----------------------------------------------------------------- -->
16464 <sect1 id="sec-GtkData">
16465 <title>GtkData</title>
16467 <programlisting role="C">
16468 void GtkData::disconnect (GtkData *,
16474 <!-- ----------------------------------------------------------------- -->
16475 <sect1 id="sec-GtkContainer">
16476 <title>GtkContainer</title>
16478 <programlisting role="C">
16479 void GtkContainer::add (GtkContainer *,
16482 void GtkContainer::remove (GtkContainer *,
16485 void GtkContainer::check-resize (GtkContainer *,
16487 GtkDirectionType GtkContainer::focus (GtkContainer *,
16490 void GtkContainer::set-focus-child (GtkContainer *,
16497 <!-- ----------------------------------------------------------------- -->
16498 <sect1 id="sec-GtkCalendar">
16499 <title>GtkCalendar</title>
16501 <programlisting role="C">
16502 void GtkCalendar::month-changed (GtkCalendar *,
16504 void GtkCalendar::day-selected (GtkCalendar *,
16506 void GtkCalendar::day-selected-double-click (GtkCalendar *,
16508 void GtkCalendar::prev-month (GtkCalendar *,
16510 void GtkCalendar::next-month (GtkCalendar *,
16512 void GtkCalendar::prev-year (GtkCalendar *,
16514 void GtkCalendar::next-year (GtkCalendar *,
16520 <!-- ----------------------------------------------------------------- -->
16521 <sect1 id="sec-GtkEditable">
16522 <title>GtkEditable</title>
16524 <programlisting role="C">
16525 void GtkEditable::changed (GtkEditable *,
16527 void GtkEditable::insert-text (GtkEditable *,
16532 void GtkEditable::delete-text (GtkEditable *,
16536 void GtkEditable::activate (GtkEditable *,
16538 void GtkEditable::set-editable (GtkEditable *,
16541 void GtkEditable::move-cursor (GtkEditable *,
16545 void GtkEditable::move-word (GtkEditable *,
16548 void GtkEditable::move-page (GtkEditable *,
16552 void GtkEditable::move-to-row (GtkEditable *,
16555 void GtkEditable::move-to-column (GtkEditable *,
16558 void GtkEditable::kill-char (GtkEditable *,
16561 void GtkEditable::kill-word (GtkEditable *,
16564 void GtkEditable::kill-line (GtkEditable *,
16567 void GtkEditable::cut-clipboard (GtkEditable *,
16569 void GtkEditable::copy-clipboard (GtkEditable *,
16571 void GtkEditable::paste-clipboard (GtkEditable *,
16577 <!-- ----------------------------------------------------------------- -->
16578 <sect1 id="sec-GtkTipsQuery">
16579 <title>GtkTipsQuery</title>
16581 <programlisting role="C">
16582 void GtkTipsQuery::start-query (GtkTipsQuery *,
16584 void GtkTipsQuery::stop-query (GtkTipsQuery *,
16586 void GtkTipsQuery::widget-entered (GtkTipsQuery *,
16591 gboolean GtkTipsQuery::widget-selected (GtkTipsQuery *,
16601 <!-- ----------------------------------------------------------------- -->
16602 <sect1 id="sec-GtkCList">
16603 <title>GtkCList</title>
16605 <programlisting role="C">
16606 void GtkCList::select-row (GtkCList *,
16611 void GtkCList::unselect-row (GtkCList *,
16616 void GtkCList::row-move (GtkCList *,
16620 void GtkCList::click-column (GtkCList *,
16623 void GtkCList::resize-column (GtkCList *,
16627 void GtkCList::toggle-focus-row (GtkCList *,
16629 void GtkCList::select-all (GtkCList *,
16631 void GtkCList::unselect-all (GtkCList *,
16633 void GtkCList::undo-selection (GtkCList *,
16635 void GtkCList::start-selection (GtkCList *,
16637 void GtkCList::end-selection (GtkCList *,
16639 void GtkCList::toggle-add-mode (GtkCList *,
16641 void GtkCList::extend-selection (GtkCList *,
16646 void GtkCList::scroll-vertical (GtkCList *,
16650 void GtkCList::scroll-horizontal (GtkCList *,
16654 void GtkCList::abort-column-resize (GtkCList *,
16660 <!-- ----------------------------------------------------------------- -->
16661 <sect1 id="sec-GtkNotebook">
16662 <title>GtkNotebook</title>
16664 <programlisting role="C">
16665 void GtkNotebook::switch-page (GtkNotebook *,
16673 <!-- ----------------------------------------------------------------- -->
16674 <sect1 id="sec-GtkList">
16675 <title>GtkList</title>
16677 <programlisting role="C">
16678 void GtkList::selection-changed (GtkList *,
16680 void GtkList::select-child (GtkList *,
16683 void GtkList::unselect-child (GtkList *,
16690 <!-- ----------------------------------------------------------------- -->
16691 <sect1 id="sec-GtkMenuShell">
16692 <title>GtkMenuShell</title>
16694 <programlisting role="C">
16695 void GtkMenuShell::deactivate (GtkMenuShell *,
16697 void GtkMenuShell::selection-done (GtkMenuShell *,
16699 void GtkMenuShell::move-current (GtkMenuShell *,
16700 GtkMenuDirectionType,
16702 void GtkMenuShell::activate-current (GtkMenuShell *,
16705 void GtkMenuShell::cancel (GtkMenuShell *,
16711 <!-- ----------------------------------------------------------------- -->
16712 <sect1 id="sec-GtkToolbar">
16713 <title>GtkToolbar</title>
16715 <programlisting role="C">
16716 void GtkToolbar::orientation-changed (GtkToolbar *,
16719 void GtkToolbar::style-changed (GtkToolbar *,
16726 <!-- ----------------------------------------------------------------- -->
16727 <sect1 id="sec-GtkTree">
16728 <title>GtkTree</title>
16730 <programlisting role="C">
16731 void GtkTree::selection-changed (GtkTree *,
16733 void GtkTree::select-child (GtkTree *,
16736 void GtkTree::unselect-child (GtkTree *,
16743 <!-- ----------------------------------------------------------------- -->
16744 <sect1 id="sec-GtkButton">
16745 <title>GtkButton</title>
16747 <programlisting role="C">
16748 void GtkButton::pressed (GtkButton *,
16750 void GtkButton::released (GtkButton *,
16752 void GtkButton::clicked (GtkButton *,
16754 void GtkButton::enter (GtkButton *,
16756 void GtkButton::leave (GtkButton *,
16762 <!-- ----------------------------------------------------------------- -->
16763 <sect1 id="sec-GtkItem">
16764 <title>GtkItem</title>
16766 <programlisting role="C">
16767 void GtkItem::select (GtkItem *,
16769 void GtkItem::deselect (GtkItem *,
16771 void GtkItem::toggle (GtkItem *,
16777 <!-- ----------------------------------------------------------------- -->
16778 <sect1 id="sec-GtkWindow">
16779 <title>GtkWindow</title>
16781 <programlisting role="C">
16782 void GtkWindow::set-focus (GtkWindow *,
16789 <!-- ----------------------------------------------------------------- -->
16790 <sect1 id="sec-GtkHandleBox">
16791 <title>GtkHandleBox</title>
16793 <programlisting role="C">
16794 void GtkHandleBox::child-attached (GtkHandleBox *,
16797 void GtkHandleBox::child-detached (GtkHandleBox *,
16804 <!-- ----------------------------------------------------------------- -->
16805 <sect1 id="sec-GtkToggleButton">
16806 <title>GtkToggleButton</title>
16808 <programlisting role="C">
16809 void GtkToggleButton::toggled (GtkToggleButton *,
16815 <!-- ----------------------------------------------------------------- -->
16816 <sect1 id="sec-GtkMenuItem">
16817 <title>GtkMenuItem</title>
16819 <programlisting role="C">
16820 void GtkMenuItem::activate (GtkMenuItem *,
16822 void GtkMenuItem::activate-item (GtkMenuItem *,
16828 <!-- ----------------------------------------------------------------- -->
16829 <sect1 id="sec-GtkListItem">
16830 <title>GtkListItem</title>
16832 <programlisting role="C">
16833 void GtkListItem::toggle-focus-row (GtkListItem *,
16835 void GtkListItem::select-all (GtkListItem *,
16837 void GtkListItem::unselect-all (GtkListItem *,
16839 void GtkListItem::undo-selection (GtkListItem *,
16841 void GtkListItem::start-selection (GtkListItem *,
16843 void GtkListItem::end-selection (GtkListItem *,
16845 void GtkListItem::toggle-add-mode (GtkListItem *,
16847 void GtkListItem::extend-selection (GtkListItem *,
16852 void GtkListItem::scroll-vertical (GtkListItem *,
16856 void GtkListItem::scroll-horizontal (GtkListItem *,
16864 <!-- ----------------------------------------------------------------- -->
16865 <sect1 id="sec-GtkTreeItem">
16866 <title>GtkTreeItem</title>
16868 <programlisting role="C">
16869 void GtkTreeItem::collapse (GtkTreeItem *,
16871 void GtkTreeItem::expand (GtkTreeItem *,
16877 <!-- ----------------------------------------------------------------- -->
16878 <sect1 id="sec-GtkCheckMenuItem">
16879 <title>GtkCheckMenuItem</title>
16881 <programlisting role="C">
16882 void GtkCheckMenuItem::toggled (GtkCheckMenuItem *,
16888 <!-- ----------------------------------------------------------------- -->
16889 <sect1 id="sec-GtkInputDialog">
16890 <title>GtkInputDialog</title>
16892 <programlisting role="C">
16893 void GtkInputDialog::enable-device (GtkInputDialog *,
16896 void GtkInputDialog::disable-device (GtkInputDialog *,
16903 <!-- ----------------------------------------------------------------- -->
16904 <sect1 id="sec-GtkColorSelection">
16905 <title>GtkColorSelection</title>
16907 <programlisting role="C">
16908 void GtkColorSelection::color-changed (GtkColorSelection *,
16914 <!-- ----------------------------------------------------------------- -->
16915 <sect1 id="sec-GtkStatusBar">
16916 <title>GtkStatusBar</title>
16918 <programlisting role="C">
16919 void GtkStatusbar::text-pushed (GtkStatusbar *,
16923 void GtkStatusbar::text-popped (GtkStatusbar *,
16931 <!-- ----------------------------------------------------------------- -->
16932 <sect1 id="sec-GtkCTree">
16933 <title>GtkCTree</title>
16935 <programlisting role="C">
16936 void GtkCTree::tree-select-row (GtkCTree *,
16940 void GtkCTree::tree-unselect-row (GtkCTree *,
16944 void GtkCTree::tree-expand (GtkCTree *,
16947 void GtkCTree::tree-collapse (GtkCTree *,
16950 void GtkCTree::tree-move (GtkCTree *,
16955 void GtkCTree::change-focus-row-expansion (GtkCTree *,
16956 GtkCTreeExpansionType,
16962 <!-- ----------------------------------------------------------------- -->
16963 <sect1 id="sec-GtkCurve">
16964 <title>GtkCurve</title>
16966 <programlisting role="C">
16967 void GtkCurve::curve-type-changed (GtkCurve *,
16973 <!-- ----------------------------------------------------------------- -->
16974 <sect1 id="sec-GtkAdjustment">
16975 <title>GtkAdjustment</title>
16977 <programlisting role="C">
16978 void GtkAdjustment::changed (GtkAdjustment *,
16980 void GtkAdjustment::value-changed (GtkAdjustment *,
16987 <!-- ***************************************************************** -->
16988 <appendix id="app-GDKEventTypes">
16989 <title>GDK Event Types</title>
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>
16995 <listitem><simpara> GdkEvent</simpara>
16997 <listitem><simpara>drag_end_event</simpara>
17002 <listitem><simpara> GdkEventType<</simpara>
17005 <listitem><simpara> GdkEventAny</simpara>
17007 <listitem><simpara>delete_event</simpara>
17009 <listitem><simpara>destroy_event</simpara>
17011 <listitem><simpara>map_event</simpara>
17013 <listitem><simpara>unmap_event</simpara>
17015 <listitem><simpara>no_expose_event</simpara>
17020 <listitem><simpara> GdkEventExpose</simpara>
17022 <listitem><simpara>expose_event</simpara>
17027 <listitem><simpara> GdkEventNoExpose</simpara>
17030 <listitem><simpara> GdkEventVisibility</simpara>
17033 <listitem><simpara> GdkEventMotion</simpara>
17035 <listitem><simpara>motion_notify_event</simpara>
17039 <listitem><simpara> GdkEventButton</simpara>
17041 <listitem><simpara>button_press_event</simpara>
17043 <listitem><simpara>button_release_event</simpara>
17048 <listitem><simpara> GdkEventKey</simpara>
17050 <listitem><simpara>key_press_event</simpara>
17052 <listitem><simpara>key_release_event</simpara>
17057 <listitem><simpara> GdkEventCrossing</simpara>
17059 <listitem><simpara>enter_notify_event</simpara>
17061 <listitem><simpara>leave_notify_event</simpara>
17066 <listitem><simpara> GdkEventFocus</simpara>
17068 <listitem><simpara>focus_in_event</simpara>
17070 <listitem><simpara>focus_out_event</simpara>
17075 <listitem><simpara> GdkEventConfigure</simpara>
17077 <listitem><simpara>configure_event</simpara>
17082 <listitem><simpara> GdkEventProperty</simpara>
17084 <listitem><simpara>property_notify_event</simpara>
17089 <listitem><simpara> GdkEventSelection</simpara>
17091 <listitem><simpara>selection_clear_event</simpara>
17093 <listitem><simpara>selection_request_event</simpara>
17095 <listitem><simpara>selection_notify_event</simpara>
17100 <listitem><simpara> GdkEventProximity</simpara>
17102 <listitem><simpara>proximity_in_event</simpara>
17104 <listitem><simpara>proximity_out_event</simpara>
17109 <listitem><simpara> GdkEventDragBegin</simpara>
17111 <listitem><simpara>drag_begin_event</simpara>
17116 <listitem><simpara> GdkEventDragRequest</simpara>
17118 <listitem><simpara>drag_request_event</simpara>
17123 <listitem><simpara> GdkEventDropEnter</simpara>
17125 <listitem><simpara>drop_enter_event</simpara>
17130 <listitem><simpara> GdkEventDropLeave</simpara>
17132 <listitem><simpara>drop_leave_event</simpara>
17137 <listitem><simpara> GdkEventDropDataAvailable</simpara>
17139 <listitem><simpara>drop_data_available_event</simpara>
17144 <listitem><simpara> GdkEventClient</simpara>
17146 <listitem><simpara>client_event</simpara>
17151 <listitem><simpara> GdkEventOther</simpara>
17153 <listitem><simpara>other_event</simpara>
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>
17165 <programlisting role="C">
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,
17178 GDK_KEY_RELEASE = 9,
17179 GDK_ENTER_NOTIFY = 10,
17180 GDK_LEAVE_NOTIFY = 11,
17181 GDK_FOCUS_CHANGE = 12,
17182 GDK_CONFIGURE = 13,
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 */
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>
17208 <!-- Just a big list for now, needs expanding upon - TRG -->
17209 <para>So, the event data types are defined as follows:</para>
17211 <programlisting role="C">
17212 struct _GdkEventAny
17219 struct _GdkEventExpose
17225 gint count; /* If non-zero, how many more events follow. */
17228 struct _GdkEventNoExpose
17233 /* XXX: does anyone need the X major_code or minor_code fields? */
17236 struct _GdkEventVisibility
17241 GdkVisibilityState state;
17244 struct _GdkEventMotion
17257 GdkInputSource source;
17259 gdouble x_root, y_root;
17262 struct _GdkEventButton
17275 GdkInputSource source;
17277 gdouble x_root, y_root;
17280 struct _GdkEventKey
17292 struct _GdkEventCrossing
17297 GdkWindow *subwindow;
17298 GdkNotifyType detail;
17301 struct _GdkEventFocus
17309 struct _GdkEventConfigure
17319 struct _GdkEventProperty
17329 struct _GdkEventSelection
17341 /* This event type will be used pretty rarely. It only is important
17342 for XInput aware programs that are drawing their own cursor */
17344 struct _GdkEventProximity
17350 GdkInputSource source;
17354 struct _GdkEventDragRequest
17362 guint protocol_version:4;
17364 guint willaccept:1;
17365 guint delete_data:1; /* Do *not* delete if link is sent, only
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 */
17376 GdkPoint drop_coords;
17381 struct _GdkEventDragBegin
17388 guint protocol_version:4;
17395 struct _GdkEventDropEnter
17403 guint protocol_version:4;
17405 guint extended_typelist:1;
17412 struct _GdkEventDropLeave
17420 guint protocol_version:4;
17427 struct _GdkEventDropDataAvailable
17435 guint protocol_version:4;
17441 gchar *data_type; /* MIME type */
17442 gulong data_numbytes;
17448 struct _GdkEventClient
17453 GdkAtom message_type;
17454 gushort data_format;
17462 struct _GdkEventOther
17473 <!-- ***************************************************************** -->
17474 <appendix id="app-CodeExamples">
17475 <title>Code Examples</title>
17477 <para>Below are the code examples that are used in the above text
17478 which are not included in complete form elsewhere.</para>
17480 <!-- ----------------------------------------------------------------- -->
17481 <sect1 id="sec-Tictactoe">
17482 <title>Tictactoe</title>
17483 <!-- ----------------------------------------------------------------- -->
17485 <title>tictactoe.h</title>
17487 <programlisting role="C">
17488 <!-- example-start tictactoe tictactoe.h -->
17490 /* GTK - The GIMP Toolkit
17491 * Copyright (C) 1995-1997 Peter Mattis, Spencer Kimball and Josh MacDonald
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.
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.
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.
17508 #ifndef __TICTACTOE_H__
17509 #define __TICTACTOE_H__
17512 #include <gdk/gdk.h>
17513 #include <gtk/gtkvbox.h>
17518 #endif /* __cplusplus */
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 ())
17525 typedef struct _Tictactoe Tictactoe;
17526 typedef struct _TictactoeClass TictactoeClass;
17532 GtkWidget *buttons[3][3];
17535 struct _TictactoeClass
17537 GtkVBoxClass parent_class;
17539 void (* tictactoe) (Tictactoe *ttt);
17542 GtkType tictactoe_get_type (void);
17543 GtkWidget* tictactoe_new (void);
17544 void tictactoe_clear (Tictactoe *ttt);
17548 #endif /* __cplusplus */
17550 #endif /* __TICTACTOE_H__ */
17552 <!-- example-end -->
17557 <!-- ----------------------------------------------------------------- -->
17559 <title>tictactoe.c</title>
17561 <programlisting role="C">
17562 <!-- example-start tictactoe tictactoe.c -->
17564 /* GTK - The GIMP Toolkit
17565 * Copyright (C) 1995-1997 Peter Mattis, Spencer Kimball and Josh MacDonald
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.
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.
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.
17582 #include "gtk/gtksignal.h"
17583 #include "gtk/gtktable.h"
17584 #include "gtk/gtktogglebutton.h"
17585 #include "tictactoe.h"
17592 static void tictactoe_class_init (TictactoeClass *klass);
17593 static void tictactoe_init (Tictactoe *ttt);
17594 static void tictactoe_toggle (GtkWidget *widget, Tictactoe *ttt);
17596 static gint tictactoe_signals[LAST_SIGNAL] = { 0 };
17599 tictactoe_get_type ()
17601 static GtkType ttt_type = 0;
17605 GtkTypeInfo ttt_info =
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
17617 ttt_type = gtk_type_unique (gtk_vbox_get_type (), &ttt_info);
17624 tictactoe_class_init (TictactoeClass *class)
17626 GtkObjectClass *object_class;
17628 object_class = (GtkObjectClass*) class;
17630 tictactoe_signals[TICTACTOE_SIGNAL] = gtk_signal_new ("tictactoe",
17632 GTK_CLASS_TYPE (object_class),
17633 GTK_SIGNAL_OFFSET (TictactoeClass,
17635 gtk_signal_default_marshaller,
17639 class->tictactoe = NULL;
17643 tictactoe_init (Tictactoe *ttt)
17648 table = gtk_table_new (3, 3, TRUE);
17649 gtk_container_add (GTK_CONTAINER(ttt), table);
17650 gtk_widget_show (table);
17655 ttt->buttons[i][j] = gtk_toggle_button_new ();
17656 gtk_table_attach_defaults (GTK_TABLE(table), ttt->buttons[i][j],
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]);
17668 return GTK_WIDGET ( gtk_type_new (tictactoe_get_type ()));
17672 tictactoe_clear (Tictactoe *ttt)
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]),
17682 gtk_signal_handler_unblock_by_data (GTK_OBJECT(ttt->buttons[i][j]), ttt);
17687 tictactoe_toggle (GtkWidget *widget, Tictactoe *ttt)
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 } };
17698 int success, found;
17700 for (k=0; k<8; k++)
17707 success = success &&
17708 GTK_TOGGLE_BUTTON(ttt->buttons[rwins[k][i]][cwins[k][i]])->active;
17710 ttt->buttons[rwins[k][i]][cwins[k][i]] == widget;
17713 if (success && found)
17715 gtk_signal_emit (GTK_OBJECT (ttt),
17716 tictactoe_signals[TICTACTOE_SIGNAL]);
17722 <!-- example-end -->
17727 <!-- ----------------------------------------------------------------- -->
17729 <title>ttt_test.c</title>
17731 <programlisting role="C">
17732 <!-- example-start tictactoe ttt_test.c -->
17734 #include <gtk/gtk.h>
17735 #include "tictactoe.h"
17737 void win( GtkWidget *widget,
17740 g_print ("Yay!\n");
17741 tictactoe_clear (TICTACTOE (widget));
17744 int main( int argc,
17750 gtk_init (&argc, &argv);
17752 window = gtk_window_new (GTK_WINDOW_TOPLEVEL);
17754 gtk_window_set_title (GTK_WINDOW (window), "Aspect Frame");
17756 gtk_signal_connect (GTK_OBJECT (window), "destroy",
17757 GTK_SIGNAL_FUNC (gtk_exit), NULL);
17759 gtk_container_set_border_width (GTK_CONTAINER (window), 10);
17761 ttt = tictactoe_new ();
17763 gtk_container_add (GTK_CONTAINER (window), ttt);
17764 gtk_widget_show (ttt);
17766 gtk_signal_connect (GTK_OBJECT (ttt), "tictactoe",
17767 GTK_SIGNAL_FUNC (win), NULL);
17769 gtk_widget_show (window);
17776 <!-- example-end -->
17782 <!-- ----------------------------------------------------------------- -->
17783 <sect1 id="sec-GtkDial">
17784 <title>GtkDial</title>
17786 <!-- ----------------------------------------------------------------- -->
17788 <title>gtkdial.h</title>
17790 <programlisting role="C">
17791 <!-- example-start gtkdial gtkdial.h -->
17793 /* GTK - The GIMP Toolkit
17794 * Copyright (C) 1995-1997 Peter Mattis, Spencer Kimball and Josh MacDonald
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.
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.
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.
17811 #ifndef __GTK_DIAL_H__
17812 #define __GTK_DIAL_H__
17815 #include <gdk/gdk.h>
17816 #include <gtk/gtkadjustment.h>
17817 #include <gtk/gtkwidget.h>
17822 #endif /* __cplusplus */
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 ())
17830 typedef struct _GtkDial GtkDial;
17831 typedef struct _GtkDialClass GtkDialClass;
17837 /* update policy (GTK_UPDATE_[CONTINUOUS/DELAYED/DISCONTINUOUS]) */
17840 /* Button currently pressed or 0 if none */
17843 /* Dimensions of dial components */
17845 gint pointer_width;
17847 /* ID of update timer, or 0 if none */
17850 /* Current angle */
17854 /* Old values from adjustment stored so we know when something changes */
17859 /* The adjustment object that stores the data for this dial */
17860 GtkAdjustment *adjustment;
17863 struct _GtkDialClass
17865 GtkWidgetClass parent_class;
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);
17875 void gtk_dial_set_adjustment (GtkDial *dial,
17876 GtkAdjustment *adjustment);
17879 #endif /* __cplusplus */
17882 #endif /* __GTK_DIAL_H__ */
17883 <!-- example-end -->
17888 <!-- ----------------------------------------------------------------- -->
17890 <title>gtkdial.c</title>
17892 <programlisting role="C">
17893 <!-- example-start gtkdial gtkdial.c -->
17895 /* GTK - The GIMP Toolkit
17896 * Copyright (C) 1995-1997 Peter Mattis, Spencer Kimball and Josh MacDonald
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.
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.
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.
17913 #include <math.h>
17914 #include <stdio.h>
17915 #include <gtk/gtkmain.h>
17916 #include <gtk/gtksignal.h>
17918 #include "gtkdial.h"
17920 #define SCROLL_DELAY_LENGTH 300
17921 #define DIAL_DEFAULT_SIZE 100
17923 /* Forward declarations */
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);
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,
17947 static void gtk_dial_adjustment_value_changed (GtkAdjustment *adjustment,
17952 static GtkWidgetClass *parent_class = NULL;
17955 gtk_dial_get_type ()
17957 static GtkType dial_type = 0;
17961 GtkTypeInfo dial_info =
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
17973 dial_type = gtk_type_unique (GTK_TYPE_WIDGET, &dial_info);
17980 gtk_dial_class_init (GtkDialClass *class)
17982 GtkObjectClass *object_class;
17983 GtkWidgetClass *widget_class;
17985 object_class = (GtkObjectClass*) class;
17986 widget_class = (GtkWidgetClass*) class;
17988 parent_class = gtk_type_class (gtk_widget_get_type ());
17990 object_class->destroy = gtk_dial_destroy;
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;
18002 gtk_dial_init (GtkDial *dial)
18005 dial->policy = GTK_UPDATE_CONTINUOUS;
18008 dial->pointer_width = 0;
18010 dial->old_value = 0.0;
18011 dial->old_lower = 0.0;
18012 dial->old_upper = 0.0;
18013 dial->adjustment = NULL;
18017 gtk_dial_new (GtkAdjustment *adjustment)
18021 dial = gtk_type_new (gtk_dial_get_type ());
18024 adjustment = (GtkAdjustment*) gtk_adjustment_new (0.0, 0.0, 0.0, 0.0, 0.0, 0.0);
18026 gtk_dial_set_adjustment (dial, adjustment);
18028 return GTK_WIDGET (dial);
18032 gtk_dial_destroy (GtkObject *object)
18036 g_return_if_fail (object != NULL);
18037 g_return_if_fail (GTK_IS_DIAL (object));
18039 dial = GTK_DIAL (object);
18041 if (dial->adjustment)
18042 gtk_object_unref (GTK_OBJECT (dial->adjustment));
18044 if (GTK_OBJECT_CLASS (parent_class)->destroy)
18045 (* GTK_OBJECT_CLASS (parent_class)->destroy) (object);
18049 gtk_dial_get_adjustment (GtkDial *dial)
18051 g_return_val_if_fail (dial != NULL, NULL);
18052 g_return_val_if_fail (GTK_IS_DIAL (dial), NULL);
18054 return dial->adjustment;
18058 gtk_dial_set_update_policy (GtkDial *dial,
18059 GtkUpdateType policy)
18061 g_return_if_fail (dial != NULL);
18062 g_return_if_fail (GTK_IS_DIAL (dial));
18064 dial->policy = policy;
18068 gtk_dial_set_adjustment (GtkDial *dial,
18069 GtkAdjustment *adjustment)
18071 g_return_if_fail (dial != NULL);
18072 g_return_if_fail (GTK_IS_DIAL (dial));
18074 if (dial->adjustment)
18076 gtk_signal_disconnect_by_data (GTK_OBJECT (dial->adjustment), (gpointer) dial);
18077 gtk_object_unref (GTK_OBJECT (dial->adjustment));
18080 dial->adjustment = adjustment;
18081 gtk_object_ref (GTK_OBJECT (dial->adjustment));
18083 gtk_signal_connect (GTK_OBJECT (adjustment), "changed",
18084 (GtkSignalFunc) gtk_dial_adjustment_changed,
18086 gtk_signal_connect (GTK_OBJECT (adjustment), "value_changed",
18087 (GtkSignalFunc) gtk_dial_adjustment_value_changed,
18090 dial->old_value = adjustment->value;
18091 dial->old_lower = adjustment->lower;
18092 dial->old_upper = adjustment->upper;
18094 gtk_dial_update (dial);
18098 gtk_dial_realize (GtkWidget *widget)
18101 GdkWindowAttr attributes;
18102 gint attributes_mask;
18104 g_return_if_fail (widget != NULL);
18105 g_return_if_fail (GTK_IS_DIAL (widget));
18107 GTK_WIDGET_SET_FLAGS (widget, GTK_REALIZED);
18108 dial = GTK_DIAL (widget);
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);
18123 attributes_mask = GDK_WA_X | GDK_WA_Y | GDK_WA_VISUAL | GDK_WA_COLORMAP;
18124 widget->window = gdk_window_new (widget->parent->window, &attributes, attributes_mask);
18126 widget->style = gtk_style_attach (widget->style, widget->window);
18128 gdk_window_set_user_data (widget->window, widget);
18130 gtk_style_set_background (widget->style, widget->window, GTK_STATE_ACTIVE);
18134 gtk_dial_size_request (GtkWidget *widget,
18135 GtkRequisition *requisition)
18137 requisition->width = DIAL_DEFAULT_SIZE;
18138 requisition->height = DIAL_DEFAULT_SIZE;
18142 gtk_dial_size_allocate (GtkWidget *widget,
18143 GtkAllocation *allocation)
18147 g_return_if_fail (widget != NULL);
18148 g_return_if_fail (GTK_IS_DIAL (widget));
18149 g_return_if_fail (allocation != NULL);
18151 widget->allocation = *allocation;
18152 dial = GTK_DIAL (widget);
18154 if (GTK_WIDGET_REALIZED (widget))
18157 gdk_window_move_resize (widget->window,
18158 allocation->x, allocation->y,
18159 allocation->width, allocation->height);
18162 dial->radius = MIN(allocation->width,allocation->height) * 0.45;
18163 dial->pointer_width = dial->radius / 5;
18167 gtk_dial_expose (GtkWidget *widget,
18168 GdkEventExpose *event)
18171 GdkPoint points[6];
18173 gdouble theta, last, increment;
18174 GtkStyle *blankstyle;
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);
18184 if (event->count > 0)
18187 dial = GTK_DIAL (widget);
18189 /* gdk_window_clear_area (widget->window,
18191 widget->allocation.width,
18192 widget->allocation.height);
18194 xc = widget->allocation.width/2;
18195 yc = widget->allocation.height/2;
18197 upper = dial->adjustment->upper;
18198 lower = dial->adjustment->lower;
18200 /* Erase old pointer */
18202 s = sin(dial->last_angle);
18203 c = cos(dial->last_angle);
18204 dial->last_angle = dial->angle;
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;
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];
18227 gtk_draw_polygon (blankstyle,
18234 gtk_style_unref(blankstyle);
18239 if ((upper - lower) == 0)
18242 increment = (100*M_PI)/(dial->radius*dial->radius);
18244 inc = (upper - lower);
18246 while (inc < 100) inc *=10;
18247 while (inc >= 1000) inc /=10;
18250 for (i=0; i<=inc; i++)
18252 theta = ((gfloat)i*M_PI/(18*inc/24.) - M_PI/6.);
18254 if ((theta - last) < (increment))
18261 tick_length = (i%(inc/10) == 0) ? dial->pointer_width : dial->pointer_width/2;
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);
18273 s = sin(dial->angle);
18274 c = cos(dial->angle);
18275 dial->last_angle = dial->angle;
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;
18289 gtk_draw_polygon (widget->style,
18300 gtk_dial_button_press (GtkWidget *widget,
18301 GdkEventButton *event)
18307 double d_perpendicular;
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);
18313 dial = GTK_DIAL (widget);
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
18320 dx = event->x - widget->allocation.width / 2;
18321 dy = widget->allocation.height / 2 - event->y;
18323 s = sin(dial->angle);
18324 c = cos(dial->angle);
18326 d_parallel = s*dy + c*dx;
18327 d_perpendicular = fabs(s*dx - c*dy);
18329 if (!dial->button &&
18330 (d_perpendicular < dial->pointer_width/2) &&
18331 (d_parallel > - dial->pointer_width))
18333 gtk_grab_add (widget);
18335 dial->button = event->button;
18337 gtk_dial_update_mouse (dial, event->x, event->y);
18344 gtk_dial_button_release (GtkWidget *widget,
18345 GdkEventButton *event)
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);
18353 dial = GTK_DIAL (widget);
18355 if (dial->button == event->button)
18357 gtk_grab_remove (widget);
18361 if (dial->policy == GTK_UPDATE_DELAYED)
18362 gtk_timeout_remove (dial->timer);
18364 if ((dial->policy != GTK_UPDATE_CONTINUOUS) &&
18365 (dial->old_value != dial->adjustment->value))
18366 gtk_signal_emit_by_name (GTK_OBJECT (dial->adjustment), "value_changed");
18373 gtk_dial_motion_notify (GtkWidget *widget,
18374 GdkEventMotion *event)
18377 GdkModifierType mods;
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);
18384 dial = GTK_DIAL (widget);
18386 if (dial->button != 0)
18391 if (event->is_hint || (event->window != widget->window))
18392 gdk_window_get_pointer (widget->window, &x, &y, &mods);
18394 switch (dial->button)
18397 mask = GDK_BUTTON1_MASK;
18400 mask = GDK_BUTTON2_MASK;
18403 mask = GDK_BUTTON3_MASK;
18410 if (mods & mask)
18411 gtk_dial_update_mouse (dial, x,y);
18418 gtk_dial_timer (GtkDial *dial)
18420 g_return_val_if_fail (dial != NULL, FALSE);
18421 g_return_val_if_fail (GTK_IS_DIAL (dial), FALSE);
18423 if (dial->policy == GTK_UPDATE_DELAYED)
18424 gtk_signal_emit_by_name (GTK_OBJECT (dial->adjustment), "value_changed");
18430 gtk_dial_update_mouse (GtkDial *dial, gint x, gint y)
18435 g_return_if_fail (dial != NULL);
18436 g_return_if_fail (GTK_IS_DIAL (dial));
18438 xc = GTK_WIDGET(dial)->allocation.width / 2;
18439 yc = GTK_WIDGET(dial)->allocation.height / 2;
18441 old_value = dial->adjustment->value;
18442 dial->angle = atan2(yc-y, x-xc);
18444 if (dial->angle < -M_PI/2.)
18445 dial->angle += 2*M_PI;
18447 if (dial->angle < -M_PI/6)
18448 dial->angle = -M_PI/6;
18450 if (dial->angle > 7.*M_PI/6.)
18451 dial->angle = 7.*M_PI/6.;
18453 dial->adjustment->value = dial->adjustment->lower + (7.*M_PI/6 - dial->angle) *
18454 (dial->adjustment->upper - dial->adjustment->lower) / (4.*M_PI/3.);
18456 if (dial->adjustment->value != old_value)
18458 if (dial->policy == GTK_UPDATE_CONTINUOUS)
18460 gtk_signal_emit_by_name (GTK_OBJECT (dial->adjustment), "value_changed");
18464 gtk_widget_draw (GTK_WIDGET(dial), NULL);
18466 if (dial->policy == GTK_UPDATE_DELAYED)
18469 gtk_timeout_remove (dial->timer);
18471 dial->timer = gtk_timeout_add (SCROLL_DELAY_LENGTH,
18472 (GtkFunction) gtk_dial_timer,
18480 gtk_dial_update (GtkDial *dial)
18484 g_return_if_fail (dial != NULL);
18485 g_return_if_fail (GTK_IS_DIAL (dial));
18487 new_value = dial->adjustment->value;
18489 if (new_value < dial->adjustment->lower)
18490 new_value = dial->adjustment->lower;
18492 if (new_value > dial->adjustment->upper)
18493 new_value = dial->adjustment->upper;
18495 if (new_value != dial->adjustment->value)
18497 dial->adjustment->value = new_value;
18498 gtk_signal_emit_by_name (GTK_OBJECT (dial->adjustment), "value_changed");
18501 dial->angle = 7.*M_PI/6. - (new_value - dial->adjustment->lower) * 4.*M_PI/3. /
18502 (dial->adjustment->upper - dial->adjustment->lower);
18504 gtk_widget_draw (GTK_WIDGET(dial), NULL);
18508 gtk_dial_adjustment_changed (GtkAdjustment *adjustment,
18513 g_return_if_fail (adjustment != NULL);
18514 g_return_if_fail (data != NULL);
18516 dial = GTK_DIAL (data);
18518 if ((dial->old_value != adjustment->value) ||
18519 (dial->old_lower != adjustment->lower) ||
18520 (dial->old_upper != adjustment->upper))
18522 gtk_dial_update (dial);
18524 dial->old_value = adjustment->value;
18525 dial->old_lower = adjustment->lower;
18526 dial->old_upper = adjustment->upper;
18531 gtk_dial_adjustment_value_changed (GtkAdjustment *adjustment,
18536 g_return_if_fail (adjustment != NULL);
18537 g_return_if_fail (data != NULL);
18539 dial = GTK_DIAL (data);
18541 if (dial->old_value != adjustment->value)
18543 gtk_dial_update (dial);
18545 dial->old_value = adjustment->value;
18548 <!-- example-end -->
18553 <!-- ----------------------------------------------------------------- -->
18555 <title>dial_test.c</title>
18557 <programlisting role="C">
18558 #include <stdio.h>
18559 #include <gtk/gtk.h>
18560 #include "gtkdial.h"
18562 void value_changed( GtkAdjustment *adjustment,
18567 sprintf(buffer,"%4.2f",adjustment->value);
18568 gtk_label_set (GTK_LABEL (label), buffer);
18571 int main( int argc,
18575 GtkAdjustment *adjustment;
18581 gtk_init (&argc, &argv);
18583 window = gtk_window_new (GTK_WINDOW_TOPLEVEL);
18585 gtk_window_set_title (GTK_WINDOW (window), "Dial");
18587 gtk_signal_connect (GTK_OBJECT (window), "destroy",
18588 GTK_SIGNAL_FUNC (gtk_exit), NULL);
18590 gtk_container_border_width (GTK_CONTAINER (window), 10);
18592 vbox = gtk_vbox_new (FALSE, 5);
18593 gtk_container_add (GTK_CONTAINER (window), vbox);
18594 gtk_widget_show(vbox);
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);
18601 adjustment = GTK_ADJUSTMENT(gtk_adjustment_new (0, 0, 100, 0.01, 0.1, 0));
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); */
18607 gtk_container_add (GTK_CONTAINER (frame), dial);
18608 gtk_widget_show (dial);
18610 label = gtk_label_new("0.00");
18611 gtk_box_pack_end (GTK_BOX(vbox), label, 0, 0, 0);
18612 gtk_widget_show (label);
18614 gtk_signal_connect (GTK_OBJECT(adjustment), "value_changed",
18615 GTK_SIGNAL_FUNC (value_changed), label);
18617 gtk_widget_show (window);
18628 <!-- ----------------------------------------------------------------- -->
18629 <sect1 id="sec-Scribble">
18630 <title>Scribble</title>
18632 <!-- ----------------------------------------------------------------- -->
18634 <title>scribble-simple.c</title>
18636 <programlisting role="C">
18637 <!-- example-start scribble-simple scribble-simple.c -->
18639 /* GTK - The GIMP Toolkit
18640 * Copyright (C) 1995-1997 Peter Mattis, Spencer Kimball and Josh MacDonald
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.
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.
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.
18658 #include <gtk/gtk.h>
18660 /* Backing pixmap for drawing area */
18661 static GdkPixmap *pixmap = NULL;
18663 /* Create a new backing pixmap of the appropriate size */
18664 static gint configure_event( GtkWidget *widget,
18665 GdkEventConfigure *event )
18668 gdk_pixmap_unref(pixmap);
18670 pixmap = gdk_pixmap_new(widget->window,
18671 widget->allocation.width,
18672 widget->allocation.height,
18674 gdk_draw_rectangle (pixmap,
18675 widget->style->white_gc,
18678 widget->allocation.width,
18679 widget->allocation.height);
18684 /* Redraw the screen from the backing pixmap */
18685 static gint expose_event( GtkWidget *widget,
18686 GdkEventExpose *event )
18688 gdk_draw_pixmap(widget->window,
18689 widget->style->fg_gc[GTK_WIDGET_STATE (widget)],
18691 event->area.x, event->area.y,
18692 event->area.x, event->area.y,
18693 event->area.width, event->area.height);
18698 /* Draw a rectangle on the screen */
18699 static void draw_brush( GtkWidget *widget,
18703 GdkRectangle update_rect;
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,
18712 update_rect.x, update_rect.y,
18713 update_rect.width, update_rect.height);
18714 gtk_widget_draw (widget, &update_rect);
18717 static gint button_press_event( GtkWidget *widget,
18718 GdkEventButton *event )
18720 if (event->button == 1 && pixmap != NULL)
18721 draw_brush (widget, event->x, event->y);
18726 static gint motion_notify_event( GtkWidget *widget,
18727 GdkEventMotion *event )
18730 GdkModifierType state;
18732 if (event->is_hint)
18733 gdk_window_get_pointer (event->window, &x, &y, &state);
18738 state = event->state;
18741 if (state & GDK_BUTTON1_MASK && pixmap != NULL)
18742 draw_brush (widget, x, y);
18752 int main( int argc,
18756 GtkWidget *drawing_area;
18761 gtk_init (&argc, &argv);
18763 window = gtk_window_new (GTK_WINDOW_TOPLEVEL);
18764 gtk_widget_set_name (window, "Test Input");
18766 vbox = gtk_vbox_new (FALSE, 0);
18767 gtk_container_add (GTK_CONTAINER (window), vbox);
18768 gtk_widget_show (vbox);
18770 gtk_signal_connect (GTK_OBJECT (window), "destroy",
18771 GTK_SIGNAL_FUNC (quit), NULL);
18773 /* Create the drawing area */
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);
18779 gtk_widget_show (drawing_area);
18781 /* Signals used to handle backing pixmap */
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);
18788 /* Event signals */
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);
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);
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);
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);
18810 gtk_widget_show (window);
18816 <!-- example-end -->
18821 <!-- ----------------------------------------------------------------- -->
18823 <title>scribble-xinput.c</title>
18825 <programlisting role="C">
18826 <!-- example-start scribble-xinput scribble-xinput.c -->
18828 /* GTK - The GIMP Toolkit
18829 * Copyright (C) 1995-1997 Peter Mattis, Spencer Kimball and Josh MacDonald
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.
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.
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.
18847 #include <gtk/gtk.h>
18849 /* Backing pixmap for drawing area */
18850 static GdkPixmap *pixmap = NULL;
18852 /* Create a new backing pixmap of the appropriate size */
18854 configure_event (GtkWidget *widget, GdkEventConfigure *event)
18857 gdk_pixmap_unref(pixmap);
18859 pixmap = gdk_pixmap_new(widget->window,
18860 widget->allocation.width,
18861 widget->allocation.height,
18863 gdk_draw_rectangle (pixmap,
18864 widget->style->white_gc,
18867 widget->allocation.width,
18868 widget->allocation.height);
18873 /* Redraw the screen from the backing pixmap */
18875 expose_event (GtkWidget *widget, GdkEventExpose *event)
18877 gdk_draw_pixmap(widget->window,
18878 widget->style->fg_gc[GTK_WIDGET_STATE (widget)],
18880 event->area.x, event->area.y,
18881 event->area.x, event->area.y,
18882 event->area.width, event->area.height);
18887 /* Draw a rectangle on the screen, size depending on pressure,
18888 and color on the type of device */
18890 draw_brush (GtkWidget *widget, GdkInputSource source,
18891 gdouble x, gdouble y, gdouble pressure)
18894 GdkRectangle update_rect;
18898 case GDK_SOURCE_MOUSE:
18899 gc = widget->style->dark_gc[GTK_WIDGET_STATE (widget)];
18901 case GDK_SOURCE_PEN:
18902 gc = widget->style->black_gc;
18904 case GDK_SOURCE_ERASER:
18905 gc = widget->style->white_gc;
18908 gc = widget->style->light_gc[GTK_WIDGET_STATE (widget)];
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, &update_rect);
18922 print_button_press (GdkDevice *device)
18924 g_print("Button press on device '%s'\n", device->name);
18928 button_press_event (GtkWidget *widget, GdkEventButton *event)
18930 print_button_press (event->device);
18932 if (event->button == 1 && pixmap != NULL) {
18934 gdk_event_get_axis ((GdkEvent *)event, GDK_AXIS_PRESSURE, &pressure);
18935 draw_brush (widget, event->device->source, event->x, event->y, pressure);
18942 motion_notify_event (GtkWidget *widget, GdkEventMotion *event)
18946 GdkModifierType state;
18948 if (event->is_hint)
18950 gdk_device_get_state (event->device, event->window, NULL, &state);
18951 gdk_event_get_axis ((GdkEvent *)event, GDK_AXIS_X, &x);
18952 gdk_event_get_axis ((GdkEvent *)event, GDK_AXIS_Y, &y);
18953 gdk_event_get_axis ((GdkEvent *)event, GDK_AXIS_PRESSURE, &pressure);
18959 gdk_event_get_axis ((GdkEvent *)event, GDK_AXIS_PRESSURE, &pressure);
18960 state = event->state;
18963 if (state & GDK_BUTTON1_MASK && pixmap != NULL)
18964 draw_brush (widget, event->device->source, x, y, pressure);
18970 input_dialog_destroy (GtkWidget *w, gpointer data)
18972 *((GtkWidget **)data) = NULL;
18976 create_input_dialog ()
18978 static GtkWidget *inputd = NULL;
18982 inputd = gtk_input_dialog_new();
18984 gtk_signal_connect (GTK_OBJECT(inputd), "destroy",
18985 (GtkSignalFunc)input_dialog_destroy, &inputd);
18986 gtk_signal_connect_object (GTK_OBJECT(GTK_INPUT_DIALOG(inputd)->close_button),
18988 (GtkSignalFunc)gtk_widget_hide,
18989 GTK_OBJECT(inputd));
18990 gtk_widget_hide ( GTK_INPUT_DIALOG(inputd)->save_button);
18992 gtk_widget_show (inputd);
18996 if (!GTK_WIDGET_MAPPED(inputd))
18997 gtk_widget_show(inputd);
18999 gdk_window_raise(inputd->window);
19010 main (int argc, char *argv[])
19013 GtkWidget *drawing_area;
19018 gtk_init (&argc, &argv);
19020 window = gtk_window_new (GTK_WINDOW_TOPLEVEL);
19021 gtk_widget_set_name (window, "Test Input");
19023 vbox = gtk_vbox_new (FALSE, 0);
19024 gtk_container_add (GTK_CONTAINER (window), vbox);
19025 gtk_widget_show (vbox);
19027 gtk_signal_connect (GTK_OBJECT (window), "destroy",
19028 GTK_SIGNAL_FUNC (quit), NULL);
19030 /* Create the drawing area */
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);
19036 gtk_widget_show (drawing_area);
19038 /* Signals used to handle backing pixmap */
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);
19045 /* Event signals */
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);
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);
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);
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);
19066 gtk_signal_connect (GTK_OBJECT (button), "clicked",
19067 GTK_SIGNAL_FUNC (create_input_dialog), NULL);
19068 gtk_widget_show (button);
19070 button = gtk_button_new_with_label ("Quit");
19071 gtk_box_pack_start (GTK_BOX (vbox), button, FALSE, FALSE, 0);
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);
19078 gtk_widget_show (window);
19084 <!-- example-end -->
19092 <!-- ***************************************************************** -->
19093 <appendix id="app-ListWidget">
19094 <title>List Widget</title>
19096 <para>NOTE: The List widget has been superseded by the CList widget. It is
19097 detailed here just for completeness.</para>
19099 <para>The List widget is designed to act as a vertical container for
19100 widgets that should be of the type ListItem.</para>
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>
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>
19113 <programlisting role="C">
19118 guint selection_mode;
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>
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>
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>
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>
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
19152 <listitem><simpara> <literal>GTK_SELECTION_EXTENDED</literal> - The selection is always NULL.</simpara>
19156 <para>The default is <literal>GTK_SELECTION_MULTIPLE</literal>.</para>
19158 <!-- ----------------------------------------------------------------- -->
19159 <sect1 id="sec-SelectionSignals">
19160 <title>Signals</title>
19162 <programlisting role="C">
19163 void selection_changed( GtkList *list );
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
19170 <programlisting role="C">
19171 void select_child( GtkList *list,
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>
19181 <programlisting role="C">
19182 void unselect_child( GtkList *list,
19183 GtkWidget *child );
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>
19194 <!-- ----------------------------------------------------------------- -->
19195 <sect1 id="sec-GtkListFunctions">
19196 <title>Functions</title>
19198 <programlisting role="C">
19199 guint gtk_list_get_type( void );
19202 <para>Returns the "GtkList" type identifier.</para>
19204 <programlisting role="C">
19205 GtkWidget *gtk_list_new( void );
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>
19211 <programlisting role="C">
19212 void gtk_list_insert_items( GtkList *list,
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>
19222 <programlisting role="C">
19223 void gtk_list_append_items( GtkList *list,
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>
19230 <programlisting role="C">
19231 void gtk_list_prepend_items( GtkList *list,
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
19239 <programlisting role="C">
19240 void gtk_list_remove_items( GtkList *list,
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>
19250 <programlisting role="C">
19251 void gtk_list_clear_items( GtkList *list,
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>
19260 <programlisting role="C">
19261 void gtk_list_select_item( GtkList *list,
19265 <para>Invoke the select_child signal for a list item specified through its
19266 current position within the list.</para>
19268 <programlisting role="C">
19269 void gtk_list_unselect_item( GtkList *list,
19273 <para>Invoke the unselect_child signal for a list item specified through its
19274 current position within the list.</para>
19276 <programlisting role="C">
19277 void gtk_list_select_child( GtkList *list,
19281 <para>Invoke the select_child signal for the specified child.</para>
19283 <programlisting role="C">
19284 void gtk_list_unselect_child( GtkList *list,
19288 <para>Invoke the unselect_child signal for the specified child.</para>
19290 <programlisting role="C">
19291 gint gtk_list_child_position( GtkList *list,
19295 <para>Return the position of <literal>child</literal> within the list. "-1" is returned on
19298 <programlisting role="C">
19299 void gtk_list_set_selection_mode( GtkList *list,
19300 GtkSelectionMode mode );
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>
19307 <programlisting role="C">
19308 GtkList *GTK_LIST( gpointer obj );
19311 <para>Cast a generic pointer to "GtkList *".</para>
19313 <programlisting role="C">
19314 GtkListClass *GTK_LIST_CLASS( gpointer class);
19317 <para>Cast a generic pointer to "GtkListClass *". </para>
19319 <programlisting role="C">
19320 gint GTK_IS_LIST( gpointer obj);
19323 <para>Determine if a generic pointer refers to a "GtkList" object.</para>
19327 <!-- ----------------------------------------------------------------- -->
19328 <sect1 id="sec-GtkListExample">
19329 <title>Example</title>
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>
19335 <programlisting role="C">
19336 <!-- example-start list list.c -->
19338 /* Include the GTK header files
19339 * Include stdio.h, we need that for the printf() function
19341 #include <gtk/gtk.h>
19342 #include <stdio.h>
19344 /* This is our data identification string to store
19345 * data in list items
19347 const gchar *list_item_data_key="list_item_data";
19350 /* prototypes for signal handler that we are going to connect
19351 * to the List widget
19353 static void sigh_print_selection( GtkWidget *gtklist,
19354 gpointer func_data);
19356 static void sigh_button_event( GtkWidget *gtklist,
19357 GdkEventButton *event,
19358 GtkWidget *frame );
19361 /* Main function to set up the user interface */
19363 gint main( int argc,
19366 GtkWidget *separator;
19369 GtkWidget *scrolled_window;
19371 GtkWidget *gtklist;
19373 GtkWidget *list_item;
19379 /* Initialize GTK (and subsequently GDK) */
19381 gtk_init(&argc, &argv);
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
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),
19392 GTK_SIGNAL_FUNC(gtk_main_quit),
19396 /* Inside the window we need a box to arrange the widgets
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);
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);
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
19414 gtklist=gtk_list_new();
19415 gtk_scrolled_window_add_with_viewport( GTK_SCROLLED_WINDOW(scrolled_window),
19417 gtk_widget_show(gtklist);
19418 gtk_signal_connect(GTK_OBJECT(gtklist),
19419 "selection_changed",
19420 GTK_SIGNAL_FUNC(sigh_print_selection),
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);
19431 /* Connect the sigh_button_event() signal handler to the List
19432 * which will handle the "arresting" of list items
19434 gtk_signal_connect(GTK_OBJECT(gtklist),
19435 "button_release_event",
19436 GTK_SIGNAL_FUNC(sigh_button_event),
19439 /* Create a separator */
19440 separator=gtk_hseparator_new();
19441 gtk_container_add(GTK_CONTAINER(vbox), separator);
19442 gtk_widget_show(separator);
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),
19451 GTK_SIGNAL_FUNC(gtk_widget_destroy),
19452 GTK_OBJECT(window));
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
19460 for (i=0; i<5; i++) {
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), &string);
19472 gtk_object_set_data(GTK_OBJECT(list_item),
19473 list_item_data_key,
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())
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");
19499 gtk_list_append_items(GTK_LIST(gtklist), dlist);
19501 /* Finally we want to see the window, don't we? ;) */
19502 gtk_widget_show(window);
19504 /* Fire up the main event loop of gtk */
19507 /* We get here after gtk_main_quit() has been called which
19508 * happens if the main window gets destroyed
19513 /* This is the signal handler that got connected to button
19514 * press/release events of the List
19516 void sigh_button_event( GtkWidget *gtklist,
19517 GdkEventButton *event,
19520 /* We only do something if the third (rightmost mouse button
19523 if (event->type==GDK_BUTTON_RELEASE &&
19524 event->button==3) {
19525 GList *dlist, *free_list;
19526 GtkWidget *new_prisoner;
19528 /* Fetch the currently selected list item which
19529 * will be our next prisoner ;)
19531 dlist=GTK_LIST(gtklist)->selection;
19533 new_prisoner=GTK_WIDGET(dlist->data);
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
19542 dlist=gtk_container_children(GTK_CONTAINER(frame));
19545 GtkWidget *list_item;
19547 list_item=dlist->data;
19549 gtk_widget_reparent(list_item, gtklist);
19553 g_list_free(free_list);
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.
19559 if (new_prisoner) {
19560 GList static_dlist;
19562 static_dlist.data=new_prisoner;
19563 static_dlist.next=NULL;
19564 static_dlist.prev=NULL;
19566 gtk_list_unselect_child(GTK_LIST(gtklist),
19568 gtk_widget_reparent(new_prisoner, frame);
19573 /* This is the signal handler that gets called if List
19574 * emits the "selection_changed" signal
19576 void sigh_print_selection( GtkWidget *gtklist,
19577 gpointer func_data )
19581 /* Fetch the doubly linked list of selected items
19582 * of the List, remember to treat this as read-only!
19584 dlist=GTK_LIST(gtklist)->selection;
19586 /* If there are no selected items there is nothing more
19587 * to do than just telling the user so
19590 g_print("Selection cleared\n");
19593 /* Ok, we got a selection and so we print it
19595 g_print("The selection is a ");
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 */
19601 GtkObject *list_item;
19602 gchar *item_data_string;
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);
19613 <!-- example-end -->
19618 <!-- ----------------------------------------------------------------- -->
19619 <sect1 id="sec-ListItemWidget">
19620 <title>List Item Widget</title>
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>
19626 <para>A ListItem has its own window to receive events and has its own
19627 background color which is usually white.</para>
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
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>
19643 <!-- ----------------------------------------------------------------- -->
19644 <sect1 id="sec-GtkListItemSignals">
19645 <title>Signals</title>
19647 <para>A GtkListItem does not create new signals on its own, but inherits
19648 the signals of a Item.</para>
19652 <!-- ----------------------------------------------------------------- -->
19653 <sect1 id="sec-GtkListItemFunctions">
19654 <title>Functions</title>
19656 <programlisting role="C">
19657 guint gtk_list_item_get_type( void );
19660 <para>Returns the "GtkListItem" type identifier.</para>
19662 <programlisting role="C">
19663 GtkWidget *gtk_list_item_new( void );
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>
19669 <programlisting role="C">
19670 GtkWidget *gtk_list_item_new_with_label( gchar *label );
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>
19677 <programlisting role="C">
19678 void gtk_list_item_select( GtkListItem *list_item );
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>
19685 <programlisting role="C">
19686 void gtk_list_item_deselect( GtkListItem *list_item );
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>
19693 <programlisting role="C">
19694 GtkListItem *GTK_LIST_ITEM( gpointer obj );
19697 <para>Cast a generic pointer to "GtkListItem *".</para>
19699 <programlisting role="C">
19700 GtkListItemClass *GTK_LIST_ITEM_CLASS( gpointer class );
19703 <para>Cast a generic pointer to GtkListItemClass*. *Note Standard Macros::,
19704 for more info.</para>
19706 <programlisting role="C">
19707 gint GTK_IS_LIST_ITEM( gpointer obj );
19710 <para>Determine if a generic pointer refers to a `GtkListItem' object.
19711 *Note Standard Macros::, for more info.</para>
19715 <!-- ----------------------------------------------------------------- -->
19716 <sect1 id="sec-GtkListItemExample">
19717 <title>Example</title>
19719 <para>Please see the List example on this, which covers the usage of a
19720 ListItem as well.</para>