<!doctype book PUBLIC "-//OASIS//DTD DocBook V3.1//EN" [
<!notation PNG system "PNG">
<!entity % local.notation.class "| PNG">
]>
<book id="gtk-tut">

<bookinfo>
    <date>March 8th, 2007</date>
    <title>RGtk2 Tutorial</title>
    <authorgroup>
      <author>
        <firstname>Michael</firstname>
        <surname>Lawrence</surname>
      </author>
    </authorgroup>
    <abstract>
      <para>This is a tutorial on how to use GTK (the GIMP Toolkit) through its 
      R interface RGtk2. It is based on the original C interface tutorial by
      Tony Gale, Ian Main, and the GTK+ team.</para>
    </abstract>
  </bookinfo>

<toc></toc>

<!--**************************************************************** -->
<chapter id="ch-TutorialDownload">
<title>Tutorial Availability</title>

<para>A copy of this tutorial in SGML is distributed with each
source code release of RGtk2.</para>

<para>A copy is available online for <ulink 
url="http://www.ggobi.org/rgtk2/tutorial/">reference</ulink>.</para>

</chapter>

<!--**************************************************************** -->
<chapter id="ch-Introduction">
<title>Introduction</title>

<para>GTK (GIMP Toolkit) is a library for creating graphical user
interfaces. It is licensed using the LGPL license, so you can develop
open software, free software, or even commercial non-free software
using GTK without having to spend anything for licenses or royalties.</para>

<para>It's called the GIMP toolkit because it was originally written for
developing the GNU Image Manipulation Program (GIMP), but GTK has
now been used in a large number of software projects, including the
GNU Network Object Model Environment (GNOME) project. GTK is built on
top of GDK (GIMP Drawing Kit) which is basically a wrapper around the
low-level functions for accessing the underlying windowing functions
(Xlib in the case of the X windows system), and gdk-pixbuf, a library for
client-side image manipulation.</para>

</para>
<para>GTK is essentially an object oriented application programmers
interface (API). Although written completely in C, it is implemented
using the idea of classes and callback functions (pointers to
functions).</para>

<para>There is also a third component called GLib which contains a few
replacements for some standard calls, as well as some additional
functions for handling linked lists, etc. The replacement functions
are used to increase GTK's portability, as some of the functions
implemented here are not available or are nonstandard on other Unixes
such as gStrerror(). Some also contain enhancements to the libc
versions, such as gMalloc() that has enhanced debugging utilities.</para>

<para>In version 2.0, GLib has picked up the type system which forms the
foundation for GTK's class hierarchy, the signal system which is used
throughout GTK, a thread API which abstracts the different native thread APIs 
of the various platforms and a facility for loading modules.
</para>

<para>GTK uses the Pango library for internationalized
text output and is integrated with the Accessibility Tool Kit (ATK) for, you
guessed it, accessibility.
</para>

<para>This tutorial describes the R interface to GTK. There are GTK
bindings for many other languages including C, C++, Guile, Perl, Python,
TOM, Ada95, Objective C, Free Pascal, Eiffel, Java and C#.</para>

<para>This tutorial is an attempt to document as much as possible of GTK,
but it is by no means complete. This tutorial assumes a good
understanding of R. If you are learning GTK as your first
widget set, please comment on how you found this tutorial, and what
you had trouble with.</para>

<para>This document is a "work in progress". Please look for updates on
<ulink url="http://www.gtk.org/">http://www.gtk.org/</ulink>.</para>

<para>I would very much like to hear of any problems you have learning GTK
from this document, and would appreciate input as to how it may be
improved. Please see the section on <link linkend="ch-Contributing">Contributing
</link> for further information.</para>

</chapter>

<!--**************************************************************** -->
<chapter id="ch-GettingStarted">
<title>Getting Started</title>

<para>The first thing to do, of course, is to install the RGtk2 package from CRAN. 
You can also view other sources of GTK information on
<ulink url="http://www.gtk.org/">http://www.gtk.org/</ulink>. 

<para>The RGtk2 source distribution also contains the complete source to all
of the examples used in this tutorial.</para>

<para>To begin our introduction to GTK, we'll start with the simplest
program possible. This program will create a 200x200 pixel window.</para>

<para>
<inlinemediaobject>
<imageobject>
<imagedata fileref="images/base.png" format="png">
</imageobject>
</inlinemediaobject>
</para>

<programlisting role="R">
<!-- example-start base base.R -->

win &lt;- gtkWindow("toplevel")

<!-- example-end -->
</programlisting>

<para>This single line of code creates a GtkWindow object and assigns it to 
the <literal>win</literal> simple. In RGtk2, any GTK+ class may be instantiated
by calling a function with the same name of the class, with the 
first character in lowercase.</para>

<para>The <literal>"toplevel"</literal> argument specifies that we want the
window to undergo window manager decoration and placement. Rather than
create a window of 0x0 size, a window without children is set to
200x200 by default so you can still manipulate it.</para>

<para>The window, like all other widgets, is automatically
shown by RGtk2; this can be avoided by passing <literal>show = FALSE</literal> 
to <literal>gtkWindow()</literal>.</para>

<!-- ----------------------------------------------------------------- -->
<sect1 id="sec-HelloWorld">
<title>Hello World in GTK</title>

<para>Now for a program with a widget (a button). It's the classic
hello world a la GTK.</para>

<para>
<inlinemediaobject>
<imageobject>
<imagedata fileref="images/helloworld.png" format="png">
</imageobject>
</inlinemediaobject>
</para>

<programlisting role="R">
<!-- example-start helloworld helloworld.c -->

# This is a callback function.
hello &lt;- function(widget)
{
    print("Hello World")
}

deleteEvent &lt;- function(widget, event)
{
     # If you return FALSE in the "deleteEvent" signal handler,
     # GTK will emit the "destroy" signal. Returning TRUE means
     # you don't want the window to be destroyed.
     # This is useful for popping up 'are you sure you want to quit?'
     # type dialogs.

    print("delete event occurred")

    # Change TRUE to FALSE and the main window will be destroyed with
    # a "deleteEvent".

    return(TRUE)
}

# create a new window 
window &lt;- gtkWindow("toplevel")

# When the window is given the "deleteEvent" signal (this is given
# by the window manager, usually by the "close" option, or on the
# titlebar), we ask it to call the deleteEvent () function
# as defined above.
gSignalConnect(window, "delete-event", deleteEvent)

# Sets the border width of the window.
window$setBorderWidth(10)

# Creates a new button with the label "Hello World".
button &lt;- gtkButton("Hello World")

# When the button receives the "clicked" signal. The hello()
# function is defined above.
gSignalConnect(button, "clicked", hello)

# After the click, close the window
gSignalConnect(button, "clicked", gtkWidgetDestroy, user.data.first = TRUE)

# This packs the button into the window (a gtk container).
window$add(button)
    
<!-- example-end -->
</programlisting>

</sect1>

<!-- ----------------------------------------------------------------- -->
<sect1 id="sec-TheoryOfSignalsAndCallbacks">
<title>Theory of Signals and Callbacks</title>

<para>Before we look in detail at <emphasis>helloworld</emphasis>, we'll discuss signals
and callbacks. GTK is an event driven toolkit, which means it will
sleep until an event occurs and control is passed to the
appropriate function.</para>

<para>This passing of control is done using the idea of "signals". (Note
that these signals are not the same as R signals). 
When an event occurs, such as the press of a mouse button,
the appropriate signal will be "emitted" by the widget that was
pressed.  This is how GTK does most of its useful work. There are
signals that all widgets inherit, such as "destroy", and there are
signals that are widget specific, such as "toggled" on a toggle
button.</para>

<para>To make a button perform an action, we set up a signal handler to
catch these signals and call the appropriate function. This is done by
using:</para>

<programlisting role="R">
gSignalConnect(obj, signal, f, data = NULL, after = FALSE, user.data.first = FALSE)
</programlisting>

<para>where the first argument is the widget which will be emitting the
signal, and the second the name of the signal you wish to catch. The
third is the function you wish to be called when it is caught, and the
fourth, the data you wish to have passed to this function.</para>

<para>The function specified in the third argument is called a "callback
function", and should generally be of the form</para>

<programlisting role="R">
callbackFunc(widget,
              ... # other signal arguments
              data)
</programlisting>

<para>where the first argument will be a pointer to the widget that emitted
the signal, and the last a pointer to the data given as the last
argument to the gSignalConnect function as shown above.</para>

<para>Note that the above form for a signal callback function declaration is
only a general guide, as some widget specific signals generate
different calling parameters.</para>

<para>When after is <literal>TRUE</literal> the callback is invoked
after the default handler of the signal (the handler within the widget itself),
as long as the signal is defined with the "last" flag. This is not generally
useful.</para>

<para>When user.data.first is <literal>TRUE</literal> the user-provided data
is swapped with the widget parameter when the callback is invoked. This is
useful when passing a method belonging to the class of the user data as
the callback function.</para>

</sect1>

<!-- ----------------------------------------------------------------- -->
<sect1 id="sec-Events">
<title>Events</title>

<para>In addition to the signal mechanism described above, there is a set
of <emphasis>events</emphasis> that reflect the X event mechanism. Callbacks may
also be attached to these events. These events are:</para>

<itemizedlist spacing=Compact>
<listitem><simpara> event</simpara>
</listitem>
<listitem><simpara> buttonPressEvent</simpara>
</listitem>
<listitem><simpara> buttonReleaseEvent</simpara>
</listitem>
<listitem><simpara> scrollEvent</simpara>
</listitem>
<listitem><simpara> motionNotifyEvent</simpara>
</listitem>
<listitem><simpara> deleteEvent</simpara>
</listitem>
<listitem><simpara> destroyEvent</simpara>
</listitem>
<listitem><simpara> exposeEvent</simpara>
</listitem>
<listitem><simpara> keyPressEvent</simpara>
</listitem>
<listitem><simpara> keyReleaseEvent</simpara>
</listitem>
<listitem><simpara> enterNotifyEvent</simpara>
</listitem>
<listitem><simpara> leaveNotifyEvent</simpara>
</listitem>
<listitem><simpara> configureEvent</simpara>
</listitem>
<listitem><simpara> focusInEvent</simpara>
</listitem>
<listitem><simpara> focusOutEvent</simpara>
</listitem>
<listitem><simpara> mapEvent</simpara>
</listitem>
<listitem><simpara> unmapEvent</simpara>
</listitem>
<listitem><simpara> propertyNotifyEvent</simpara>
</listitem>
<listitem><simpara> selectionClearEvent</simpara>
</listitem>
<listitem><simpara> selectionRequestEvent</simpara>
</listitem>
<listitem><simpara> selectionNotifyEvent</simpara>
</listitem>
<listitem><simpara> proximityInEvent</simpara>
</listitem>
<listitem><simpara> proximityOutEvent</simpara>
</listitem>
<listitem><simpara> visibilityNotifyEvent</simpara>
</listitem>
<listitem><simpara> clientEvent</simpara>
</listitem>
<listitem><simpara> noExposeEvent</simpara>
</listitem>
<listitem><simpara> windowStateEvent</simpara>
</listitem>
</itemizedlist>

<para>In order to connect a callback function to one of these events you
use the function gSignalConnect, as described above, using one of
the above event names as the <literal>signal</literal> parameter. The callback
function for events has a slightly different form than that for
signals:</para>

<programlisting role="R">
callbackFunc(widget, event, data)
</programlisting>

<para>The <literal>event</literal> parameter is a GdkEvent structure whose type will depend upon 
which of the above events has occurred. In order for us to tell which event
has been issued each of the possible alternatives has a <literal>type</literal>
member that reflects the event being issued. The other components
of the event structure will depend upon the type of the
event. The type may be obtained from the <literal>class</literal> attribute
of the R object.</para>

<para>So, to connect a callback function to one of these events we would use
something like:</para>

<programlisting role="R">
gSignalConnect(button, "button-press-event", buttonPressCallback)
</programlisting>

<para>This assumes that <literal>button</literal> is a Button widget. Now, when the
mouse is over the button and a mouse button is pressed, the function
buttonPressCallback() will be called. This function may be declared as:</para>

<programlisting role="R">
buttonPressCallback &lt;- function(widget, event)
</programlisting>

<para>The value returned from this function indicates whether the event
should be propagated further by the GTK event handling
mechanism. Returning TRUE indicates that the event has been handled,
and that it should not propagate further. Returning FALSE continues
the normal event handling.  See the section on
<link linkend="ch-AdvancedEventsAndSignals">Advanced Event and Signal Handling</link> 
for more details on this propagation process.</para>

<para>For details on the GdkEvent data types, see the appendix entitled
<link linkend="app-GDKEventTypes">GDK Event Types</link>.</para>

<para>The GDK selection and drag-and-drop APIs also emit a number of events which
are reflected in GTK by the signals. See <link 
linkend="sec-SignalsOnSourceWidgets">Signals on the source widget</link> and <link 
linkend="sec-SignalsOnDestWidgets">Signals on the destination widget</link>
for details on the signatures of the callback functions for these signals:</para>

<itemizedlist spacing=Compact>
<listitem><simpara> selectionReceived</simpara>
</listitem>
<listitem><simpara> selectionGet</simpara>
</listitem>
<listitem><simpara> dragBeginEvent</simpara>
</listitem>
<listitem><simpara> dragEndEvent</simpara>
</listitem>
<listitem><simpara> dragDataDelete</simpara>
</listitem>
<listitem><simpara> dragMotion</simpara>
</listitem>
<listitem><simpara> dragDrop</simpara>
</listitem>
<listitem><simpara> dragDataGet</simpara>
</listitem>
<listitem><simpara> dragDataReceived</simpara>
</listitem>
</itemizedlist>

</sect1>

<!-- ----------------------------------------------------------------- -->
<sect1 id="sec-SteppingThroughHelloWorld">
<title>Stepping Through Hello World</title>

<para>Now that we know the theory behind this, let's clarify by walking
through the example <emphasis>helloworld</emphasis> program.</para>

<para>Here is the callback function that will be called when the button is
"clicked". We ignore both the widget and the data in this example, but
it is not hard to do things with them. The next example will use the
data argument to tell us which button was pressed.</para>

<programlisting role="R">
hello &lt;- function(widget)
{
    print("Hello World")
}
</programlisting>

<para>The next callback is a bit special. The "deleteEvent" occurs when the
window manager sends this event to the application. We have a choice
here as to what to do about these events. We can ignore them, make
some sort of response, or simply quit the application.</para>

<para>The value you return in this callback lets GTK know what action to
take.  By returning TRUE, we let it know that we don't want to have
the "destroy" signal emitted, keeping our application running. By
returning FALSE, we ask that "destroy" be emitted.</para>


<programlisting role="R">
deleteEvent &lt;- function(widget, event)
{
    print("delete event occurred")
    return(TRUE)
}
</programlisting>

<para>Create a new window. This is fairly straightforward.</para>

<programlisting role="R">
    win &lt;- gtkWindow("toplevel")
</programlisting>

<para>Here is an example of connecting a signal handler to an object, in
this case, the window. Here, the "deleteEvent" signal is caught.
The signal is emitted when we use the window manager to
kill the window, or when we use the gtkWidgetDestroy() call passing
in the window widget as the object to destroy. </para>

<programlisting role="R">
    gSignalConnect(window, "delete-event", deleteEvent)
</programlisting>

<para>This next function is used to set an attribute of a container object.
This just sets the window so it has a blank area along the inside of
it 10 pixels wide where no widgets will go. There are other similar
functions which we will look at in the section on
<link linkend="ch-SettingWidgetAttributes">Setting Widget Attributes</link></para>.

<programlisting role="R">
    window$setBorderWidth(10)
</programlisting>

<note>The <literal>$</literal> function is specially defined for GTK+ objects
and serves as a shortcut for method invocation with a syntax similar
to that of Java. The below is the long-form equivalent of the above:</note>

<programlisting role="R">
    gtkContainerSetBorderWidth(window, 10)
</programlisting>

<para>This call creates a new button. It will have the label "Hello World" on it when
displayed.</para>

<programlisting role="R">
    button &lt;- gtkButton("Hello World")
</programlisting>

<para>Here, we take this button, and make it do something useful. We attach
a signal handler to it so when it emits the "clicked" signal, our
hello() function is called. The data is ignored, so we simply pass in
NULL to the hello() callback function. Obviously, the "clicked" signal
is emitted when we click the button with our mouse pointer.</para>

<programlisting role="R">
    gSignalConnect(button, "clicked", hello)
</programlisting>

<para>We are also going to use this button to close the window. This will
illustrate how the "destroy" signal may come from either the window
manager, or our program. When the button is "clicked", same as above,
it calls the first hello() callback function, and then this one in the
order they are set up. You may have as many callback functions as you
need, and all will be executed in the order you connected
them. Because the gtkWidgetDestroy() function accepts only a
widget as an argument, we specify <literal>user.data.first = TRUE</literal> here.
</para>

<programlisting role="R">
    gSignalConnect(button, "clicked", gtkWidgetDestroy, user.data.first = TRUE)
</programlisting>

<para>This is a packing call, which will be explained in depth later on in
<link linkend="ch-PackingWidgets">Packing Widgets</link>. But it is
fairly easy to understand. It simply tells GTK that the button is to
be placed in the window where it will be displayed. Note that a GTK
container can only contain one widget. There are other widgets, that
are described later, which are designed to layout multiple widgets in
various ways.
 </para>

<programlisting role="R">
    window$add(button)
</programlisting>

<para>Now, when we click the mouse button on a GTK button, the widget emits
a "clicked" signal. In order for us to use this information, our
program sets up a signal handler to catch that signal, which
dispatches the function of our choice. In our example, when the button
we created is "clicked", the hello() function is called with a NULL
argument, and then the next handler for this signal is called. This
calls the gtkWidgetDestroy() function, passing it the window widget
as its argument, destroying the window widget.</para>

<para>Another course of events is to use the window manager to kill the
window, which will cause the "delete-event" to be emitted. This will
call our "deleteEvent" handler. If we return TRUE here, the window
will be left as is and nothing will happen. Returning FALSE will cause
GTK to emit the "destroy" signal.</para>

</sect1>
</chapter>

<!--**************************************************************** -->
<chapter id="ch-MovingOn">
<title>Moving On</title>

<!-- ----------------------------------------------------------------- -->
<sect1 id="sec-MoreOnSignalHandlers">
<title>More on Signal Handlers</title>

<para>The gSignalHandler() function returns a tag that identifies your
callback function. As stated above, you may have as many callbacks per
signal and per object as you need, and each will be executed in turn,
in the order they were attached.</para>

<para>This tag allows you to remove this callback from the list by using:</para>

<programlisting role="R">
gSignalHandlerDisconnect(obj, id)
</programlisting>

<para>So, by passing in the widget you wish to remove the handler from, and
the tag returned by gSignalConnect(), you can
disconnect a signal handler.</para>

<para>You can also temporarily disable signal handlers with the
gSignalHandlerBlock() and gSignalHandlerUnblock() functions.</para>

<programlisting role="R">
gSignalHandlerBlock(obj, id)
gSignalHandlerUnblock(obj, id)
</programlisting>

</sect1>

<!-- ----------------------------------------------------------------- -->
<sect1 id="sec-AnUpgradedHelloWorld">
<title>An Upgraded Hello World</title>

<para>Let's take a look at a slightly improved <emphasis>helloworld</emphasis> with
better examples of callbacks. This will also introduce us to our next
topic, packing widgets.</para>

<para>
<inlinemediaobject>
<imageobject>
<imagedata fileref="images/helloworld2.png" format="png">
</imageobject>
</inlinemediaobject>
</para>

<programlisting role="R">
<!-- example-start helloworld2 helloworld2.R -->

hello &lt;- function(wid, data)
{
    cat(sprintf("Hello again - %s was pressed\n", data))
}

# create a new window 
window &lt;- gtkWindow("toplevel")

# This is a new call, which just sets the title of our
# new window to "Hello Buttons!"
window$setTitle("Hello Buttons!")

# Sets the border width of the window.
window$setBorderWidth(10)

# We create a box to pack widgets into.  This is described in detail
# in the "packing" section. The box is not really visible, it
# is just used as a tool to arrange widgets.
box1 &lt;- gtkHBox(FALSE, 0)

# Put the box into the main window.
window$add(box1)

# Creates a new button with the label "Button 1".
button &lt;- gtkButton("Button 1")
    
# Now when the button is clicked, we call the "callback" function
# with "button 1" as its argument
gSignalConnect(button, "clicked", hello, "button 1")

# Instead of gtkContainerAdd(), we pack this button into the invisible
# box, which has been packed into the window.
box1$packStart(button, TRUE, TRUE, 0)

# Do these same steps again to create a second button
button &lt;- gtkButton("Button 2")

# Call the same callback function with a different argument,
# passing a pointer to "button 2" instead.
gSignalConnect(button, "clicked", hello, "button 2")
box1$packStart(button, TRUE, TRUE, 0)

<!-- example-end -->
</programlisting>

<para>Compile this program using the same linking arguments as our first
example. A good exercise for the reader would be to insert a third "Quit"
button that will close the window. You may also wish to play with the
options to gtkBoxPackStart() while reading the next section.  Try
resizing the window, and observe the behavior.</para>

</sect1>
</chapter>

<!--**************************************************************** -->
<chapter id="ch-PackingWidgets">
<title>Packing Widgets</title>

<para>When creating an application, you'll want to put more than one widget
inside a window. Our first <emphasis>helloworld</emphasis> example only used one
widget so we could simply use a gtkContainerAdd() call to "pack" the
widget into the window. But when you want to put more than one widget
into a window, how do you control where that widget is positioned?
This is where packing comes in.</para>

<!-- ----------------------------------------------------------------- -->
<sect1 id="sec-TheoryOfPackingBoxes">
<title>Theory of Packing Boxes</title>

<para>Most packing is done by creating boxes. These
are invisible widget containers that we can pack our widgets into
which come in two forms, a horizontal box, and a vertical box. When
packing widgets into a horizontal box, the objects are inserted
horizontally from left to right or right to left depending on the call
used. In a vertical box, widgets are packed from top to bottom or vice
versa. You may use any combination of boxes inside or beside other
boxes to create the desired effect.</para>

<para>To create a new horizontal box, we use a call to gtkHBox(), and
for vertical boxes, gtkVBox(). The gtkBoxPackStart() and
gtkBoxPackEnd() functions are used to place objects inside of these
containers. The gtkBoxPackStart() function will start at the top
and work its way down in a vbox, and pack left to right in an hbox.
gtkBoxPackEnd() will do the opposite, packing from bottom to top in
a vbox, and right to left in an hbox. Using these functions allows us
to right justify or left justify our widgets and may be mixed in any
way to achieve the desired effect. We will use gtkBoxPackStart() in
most of our examples. An object may be another container or a
widget. In fact, many widgets are actually containers themselves,
including the button, but we usually only use a label inside a button.</para>

<para>By using these calls, GTK knows where you want to place your widgets
so it can do automatic resizing and other nifty things. There are also
a number of options as to how your widgets should be packed. As you
can imagine, this method gives us a quite a bit of flexibility when
placing and creating widgets.</para>

</sect1>

<!-- ----------------------------------------------------------------- -->
<sect1 id="sec-DetailsOfBoxes">
<title>Details of Boxes</title>

<para>Because of this flexibility, packing boxes in GTK can be confusing at
first. There are a lot of options, and it's not immediately obvious how
they all fit together. In the end, however, there are basically five
different styles.</para>

<para>
<inlinemediaobject>
<imageobject>
<imagedata fileref="images/packbox1.png" format="png">
</imageobject>
</inlinemediaobject>
</para>

<para>Each line contains one horizontal box (hbox) with several buttons. The
call to gtkBoxPack is shorthand for the call to pack each of the
buttons into the hbox. Each of the buttons is packed into the hbox the
same way (i.e., same arguments to the gtkBoxPackStart() function).</para>

<para>This is the declaration of the gtkBoxPackStart() function.</para>

<programlisting role="R">
gtkBoxPackStart(box, child, expand, fill, padding)
</programlisting>

<para>The first argument is the box you are packing the object into, the
second is the object. The objects will all be buttons for now, so
we'll be packing buttons into boxes.</para>

<para>The expand argument to gtkBoxPackStart() and gtkBoxPackEnd()
controls whether the widgets are laid out in the box to fill in all
the extra space in the box so the box is expanded to fill the area
allotted to it (TRUE); or the box is shrunk to just fit the widgets
(FALSE). Setting expand to FALSE will allow you to do right and left
justification of your widgets.  Otherwise, they will all expand to fit
into the box, and the same effect could be achieved by using only one
of gtkBoxPackStart() or gtkBoxPackEnd().</para>

<para>The fill argument to the gtkBoxPack functions control whether the
extra space is allocated to the objects themselves (TRUE), or as extra
padding in the box around these objects (FALSE). It only has an effect
if the expand argument is also TRUE.</para>

<para>When creating a new box, the function looks like this:</para>

<programlisting role="R">
gtkHBox(homogeneous = NULL, spacing = NULL)
</programlisting>

<para>The homogeneous argument to gtkHBox() (and the same for
gtkVBox()) controls whether each object in the box has the same
size (i.e., the same width in an hbox, or the same height in a
vbox). If it is set, the gtkBoxPack() routines function essentially
as if the <literal>expand</literal> argument was always turned on.</para>

<para>What's the difference between spacing (set when the box is created)
and padding (set when elements are packed)? Spacing is added between
objects, and padding is added on either side of an object. The
following figure should make it clearer:</para>

<para>
<inlinemediaobject>
<imageobject>
<imagedata fileref="images/packbox2.png" format="png">
</imageobject>
</inlinemediaobject>
</para>

<para>Here is the code used to create the above images. I've commented it
fairly heavily so I hope you won't have any problems following
it.</para>

</sect1>

<!-- ----------------------------------------------------------------- -->
<sect1 id="sec-PackingDemonstrationProgram">
<title>Packing Demonstration Program</title>

<programlisting role="R">
# Make a new hbox filled with button-labels. Arguments for the 
# variables we're interested are passed in to this function. 
# We do not show the box, but do show everything inside.
makeBox &lt;- function(homogeneous, spacing, expand, fill, padding) 
{
    # Create a new hbox with the appropriate homogeneous
    # and spacing settings
    box &lt;- gtkHBox(homogeneous, spacing)
    
    # Create a series of buttons with the appropriate settings 
    button &lt;- gtkButton("gtkBoxPack")
    box$packStart(button, expand, fill, padding)
        
    button &lt;- gtkButton("(box,")
    box$packStart(button, expand, fill, padding)
        
    button &lt;- gtkButton("button,")
    box$packStart(button, expand, fill, padding)
        
    # Create a button with the label depending on the value of
    # expand. 
    if(expand)
	    button &lt;- gtkButton("TRUE,")
    else
	    button &lt;- gtkButton("FALSE,")
    
    box$packStart(button, expand, fill, padding)
        
    # This is the same as the button creation for "expand"
    # above, but uses the shorthand form. 
    button &lt;- gtkButton(ifelse(fill, "TRUE,", "FALSE,"))
    box$packStart(button, expand, fill, padding)
        
    button &lt;- gtkButton(padding)
    box$packStart(button, expand, fill, padding)
        
    return box
}

# Create our window 
window &lt;- gtkWindow("toplevel")
window$setBorderWidth(10)

# We create a vertical vbox to pack the horizontal boxes into.
# This allows us to stack the horizontal boxes filled with buttons one
# on top of the other in this vbox. 
box1 &lt;- gtkVBox(FALSE, 0)

example1 &lt;- function() {
  # create a new label. 
  label &lt;- gtkLabel("gtkHHbox(FALSE, 0)")
  
  # Align the label to the left side.  We'll discuss this function and 
  # others in the section on Widget Attributes. 
  label$setAlignment(0, 0)
  
  # Pack the label into the vertical box(vbox box1).  Remember that 
  # widgets added to a vbox will be packed one on top of the other in
  # order. 
  box1$packStart(label, FALSE, FALSE, 0)
  
  # Call our make box function - homogeneous = FALSE, spacing = 0,
  # expand = FALSE, fill = FALSE, padding = 0 
  box2 &lt;- makeBox(FALSE, 0, FALSE, FALSE, 0)
  box1$packStart(box2, FALSE, FALSE, 0)
  
  # Call our make box function - homogeneous = FALSE, spacing = 0,
  # expand = TRUE, fill = FALSE, padding = 0 
  box2 &lt;- makeBox(FALSE, 0, TRUE, FALSE, 0)
  box1$packStart(box2, FALSE, FALSE, 0)
  
  # Args are: homogeneous, spacing, expand, fill, padding 
  box2 &lt;- makeBox(FALSE, 0, TRUE, TRUE, 0)
  box1$packStart(box2, FALSE, FALSE, 0)
  
  # Creates a separator, we'll learn more about these later, 
  # but they are quite simple. 
  separator &lt;- gtkHSeparator()
  
  # Pack the separator into the vbox. Remember each of these
  # widgets is being packed into a vbox, so they'll be stacked
  # vertically. 
  box1$packStart(separator, FALSE, TRUE, 5)
  
  # Create another new label, and show it. 
  label &lt;- gtkLabel("gtkHBox(TRUE, 0)")
  label$setAlignment(0, 0)
  box1$packStart(label, FALSE, FALSE, 0)
  
  # Args are: homogeneous, spacing, expand, fill, padding 
  box2 &lt;- makeBox(TRUE, 0, TRUE, FALSE, 0)
  box1$packStart(box2, FALSE, FALSE, 0)
  
  # Args are: homogeneous, spacing, expand, fill, padding 
  box2 &lt;- makeBox(TRUE, 0, TRUE, TRUE, 0)
  box1$packStart(box2, FALSE, FALSE, 0)
  
  # Another new separator. 
  separator &lt;- gtkHSeparator()
  # The last 3 arguments to box$packStartare:
  # expand, fill, padding. 
  box1$packStart(separator, FALSE, TRUE, 5)
} 

example2 &lt;- function() {

  # Create a new label, remember box1 is a vbox as created 
  # near the beginning of main() 
  label &lt;- gtkLabelNew("gtkHBox(FALSE, 10)")
  label$setAlignment(0, 0)
  box1$packStart(label, FALSE, FALSE, 0)
  
  # Args are: homogeneous, spacing, expand, fill, padding 
  box2 &lt;- makeBox(FALSE, 10, TRUE, FALSE, 0)
  box1$packStart(box2, FALSE, FALSE, 0)
  
  # Args are: homogeneous, spacing, expand, fill, padding 
  box2 &lt;- makeBox(FALSE, 10, TRUE, TRUE, 0)
  box1$packStart(box2, FALSE, FALSE, 0)
  
  separator &lt;- gtkHSeparator()
  # The last 3 arguments to box$packStartare:
  # expand, fill, padding. 
  box1$packStart(separator, FALSE, TRUE, 5)
  
  label &lt;- gtkLabel("gtkHBox(FALSE, 0)")
  label$setAlignment(0, 0)
  box1$packStart(label, FALSE, FALSE, 0)
  
  # Args are: homogeneous, spacing, expand, fill, padding 
  box2 &lt;- makeBox(FALSE, 0, TRUE, FALSE, 10)
  box1$packStart(box2, FALSE, FALSE, 0)
  
  # Args are: homogeneous, spacing, expand, fill, padding 
  box2 &lt;- makeBox(FALSE, 0, TRUE, TRUE, 10)
  box1$packStart(box2, FALSE, FALSE, 0)
  
  separator &lt;- gtkHSeparator()
  # The last 3 arguments to box$packStartare: expand, fill, padding. 
  box1$packStart(separator, FALSE, TRUE, 5)
} 

example3 &lt;- function() {

  # This demonstrates the ability to use gtkBoxPackEnd() to
  # right justify widgets. First, we create a new box as before. 
  box2 &lt;- makeBox(FALSE, 0, FALSE, FALSE, 0)
  
  # Create the label that will be put at the end. 
  label &lt;- gtkLabel("end")
  # Pack it using gtkBoxPackEnd(), so it is put on the right
  # side of the hbox created in the makeBox() call. 
  box2$packEnd(label, FALSE, FALSE, 0)
  
  # Pack box2 into box1(the vbox remember ? :) 
  box1$packStart(box2, FALSE, FALSE, 0)
  
  # A separator for the bottom. 
  separator &lt;- gtkHSeparator()
  # This explicitly sets the separator to 400 pixels wide by 5 pixels
  # high. This is so the hbox we created will also be 400 pixels wide,
  # and the "end" label will be separated from the other labels in the
  # hbox. Otherwise, all the widgets in the hbox would be packed as
  # close together as possible. 
  separator$setSizeRequest(400, 5)
  # pack the separator into the vbox(box1) created near the start 
  # of main() 
  box1$packStart(separator, FALSE, TRUE, 5)   
}
  
# Create another new hbox.. remember we can use as many as we need! 
quitbox &lt;- gtkHBox(FALSE, 0)

# Our quit button. 
button &lt;- gtkButton("Quit")

# Setup the signal to close the window when clicked
gSignalConnect(button, "clicked", gtkWidgetDestroy, window, user.data.first = TRUE)

# Pack the button into the quitbox.
# The last 3 arguments to box$packStartare:
# expand, fill, padding. 
quitbox$packStart(button, TRUE, FALSE, 0)
# pack the quitbox into the vbox(box1) 
box1$packStart(quitbox, FALSE, FALSE, 0)

# Pack the vbox(box1) which now contains all our widgets, into the
# main window. 
window$add(box1)
<!-- example-end -->
</programlisting>

</sect1>

<!-- ----------------------------------------------------------------- -->
<sect1 id="sec-PackingUsingTables">
<title>Packing Using Tables</title>

<para>Let's take a look at another way of packing - Tables. These can be
extremely useful in certain situations.</para>

<para>Using tables, we create a grid that we can place widgets in. The
widgets may take up as many spaces as we specify.</para>

<para>The first thing to look at, of course, is the gtkTable() function:</para>

<programlisting role="R">
gtkTable(rows = NULL, columns = NULL, homogeneous = NULL)
</programlisting>

<para>The first argument is the number of rows to make in the table, while
the second, obviously, is the number of columns.</para>

<para>The homogeneous argument has to do with how the table's boxes are
sized. If homogeneous is TRUE, the table boxes are resized to the size
of the largest widget in the table. If homogeneous is FALSE, the size
of a table boxes is dictated by the tallest widget in its same row,
and the widest widget in its column.</para>

<para>The rows and columns are laid out from 0 to n, where n was the number
specified in the call to gtkTable. So, if you specify rows = 2
and columns = 2, the layout would look something like this:</para>

<programlisting role="R">
 0          1          2
0+----------+----------+
 |          |          |
1+----------+----------+
 |          |          |
2+----------+----------+
</programlisting>

<para>Note that the coordinate system starts in the upper left hand corner.
To place a widget into a box, use the following function:</para>

<programlisting role="R">
gtkTableAttach(table, child, leftAttach, rightAttach, topAttach, bottomAttach, 
  xoptions = GtkAttachOptions["expand"] + GtkAttachOptions["fill"], 
  yoptions = GtkAttachOptions["expand"] + GtkAttachOptions["fill"], 
  xpadding = 0, ypadding = 0)
</programlisting>

<para>The first argument ("table") is the table you've created and the
second ("child") the widget you wish to place in the table.</para>

<para>The left and right attach arguments specify where to place the widget,
and how many boxes to use. If you want a button in the lower right
table entry of our 2x2 table, and want it to fill that entry <emphasis>only</emphasis>,
leftAttach would be = 1, rightAttach = 2, topAttach = 1,
bottomAttach = 2.</para>

<para>Now, if you wanted a widget to take up the whole top row of our 2x2
table, you'd use leftAttach = 0, rightAttach = 2, topAttach = 0,
bottomAttach = 1.</para>

<para>The xoptions and yoptions are used to specify packing options and may
be bitwise OR'ed together to allow multiple options.</para>

<para>These options are:</para>

<variablelist>
<varlistentry>
<term><literal>GTK_FILL</literal></term>
<listitem><para>If the table box is larger than the widget, and
<literal>GTK_FILL</literal> is specified, the widget will expand to use all the room
available.</para>
</listitem>
</varlistentry>

<varlistentry>
<term><literal>GTK_SHRINK</literal></term>
<listitem><para>If the table widget was allocated less space
then was requested (usually by the user resizing the window), then the
widgets would normally just be pushed off the bottom of the window and
disappear. If <literal>GTK_SHRINK</literal> is specified, the widgets will shrink
with the table.</para>
</listitem>
</varlistentry>

<varlistentry>
<term><literal>GTK_EXPAND</literal></term>
<listitem><para>This will cause the table to expand to use up
any remaining space in the window.</para>
</listitem>
</varlistentry>
</variablelist>

<para>Padding is just like in boxes, creating a clear area around the widget
specified in pixels.</para>

<para>We also have gtkTableSetRowSpacing() and
gtkTableSetColSpacing(). These places spacing between the rows at
the specified row or column.</para>

<programlisting role="R">
gtkTableSetRowSpacing(table, row, spacing)
</programlisting>

<para>and</para>

<programlisting role="R">
gtkTableSetColSpacing(table, column, spacing)
</programlisting>

<para>Note that for columns, the space goes to the right of the column, and
for rows, the space goes below the row.</para>

<para>You can also set a consistent spacing of all rows and/or columns with:</para>

<programlisting role="R">
gtkTableSetRowSpacings(table, spacing)
</programlisting>

<para>And,</para>

<programlisting role="R">
gtkTableSetColSpacings(table, spacing)
</programlisting>

<para>Note that with these calls, the last row and last column do not get
any spacing.</para>

</sect1>

<!-- ----------------------------------------------------------------- -->
<sect1 id="sec-TablePackingExamples">
<title>Table Packing Example</title>

<para>Here we make a window with three buttons in a 2x2 table.
The first two buttons will be placed in the upper row.
A third, quit button, is placed in the lower row, spanning both columns.
Which means it should look something like this:</para>

<para>
<inlinemediaobject>
<imageobject>
<imagedata fileref="images/table.png" format="png">
</imageobject>
</inlinemediaobject>
</para>

<para>Here's the source code:</para>

<programlisting role="R">
<!-- example-start table table.R -->

# Our callback.
# The data passed to this function is printed to stdout 
callback &lt;- function(widget, data)
{
    cat(sprintf("Hello again - %s was pressed\n", data))
}

# Create a  window
window &lt;- gtkWindow("toplevel")

# Set the window title
window$setTitle("Table")

# Sets the border width of the window.
window$setBorderWidth(20)

# Create a 2x2 table
table &lt;- gtkTable(2, 2, TRUE)

# Put the table in the main window
window$add(table)

# Create first button
button &lt;- gtkButton("button 1")

# When the button is clicked, we call the "callback" function
# with a pointer to "button 1" as its argument
gSignalConnect(button, "clicked", callback, "button 1")

# Insert button 1 into the upper left quadrant of the table
table$attach(button, 0, 1, 0, 1)

# Create second button

button &lt;- gtkButton("button 2")

# When the button is clicked, we call the "callback" function
# with a pointer to "button 2" as its argument
gSignalConnect(button, "clicked", callback, "button 2")

# Insert button 2 into the upper right quadrant of the table
table$attach(button, 1, 2, 0, 1)

# Insert the quit button into the both 
# lower quadrants of the table
table$attach(button, 0, 2, 1, 2)

<!-- example-end -->
</programlisting>

</sect1>
</chapter>

<!--**************************************************************** -->
<chapter id="ch-WidgetOverview">
<title>Widget Overview</title>

<para>The general steps to creating a widget in GTK are:</para>
<orderedlist>
<listitem><simpara> Calling the function with the same name as the widget class,
except the first character is lowercase. These are all detailed in this section.</simpara>
</listitem>

<listitem><simpara> Connect all signals and events we wish to use to the
appropriate handlers.</simpara>
</listitem>

<listitem><simpara> Set the attributes of the widget.</simpara>
</listitem>

<listitem><simpara> Pack the widget into a container using the appropriate call
such as gtkContainerAdd() or gtkBoxPackStart().</simpara>
</listitem>

<listitem><simpara> gtkWidgetShow() the widget if show = FALSE was passed
to the widget constructor.</simpara>
</listitem>
</orderedlist>

<para>gtkWidgetShow() lets GTK know that we are done setting the
attributes of the widget, and it is ready to be displayed. You may
also use gtkWidgetHide() to make it disappear again. The order in
which you show the widgets is not important, but for complex interfaces
I suggest using show = F when constructing the GtkWindow and then showing it
at the end, so the whole window pops up at once. Otherwise, the user will see the
individual widgets come up on the screen as they're formed. The
children of a widget (a window is a widget too) will not be displayed
until the window itself is shown using the gtkWidgetShow() function.</para>

<!-- ----------------------------------------------------------------- -->
<sect1 id="sec-WidgetsWithoutWindows">
<title>Widgets Without Windows</title>

<para>The following widgets do not have an underlying GdkWindow. Thus,
they are unable to capture user events. If you want to
capture events, you'll have to use the GtkEventBox. See the section on
the <link linkend="sec-EventBox">GtkEventBox</link> widget. Note that
this list is probably out of date.</para>

<programlisting role="R">
GtkAlignment
GtkArrow
GtkBin
GtkBox
GtkButton
GtkCheckButton
GtkFixed
GtkImage
GtkLabel
GtkMenuItem
GtkNotebook
GtkPaned
GtkRadioButton
GtkRange
GtkScrolledWindow
GtkSeparator
GtkTable
GtkToolbar
GtkAspectFrame
GtkFrame
GtkVBox
GtkHBox
GtkVSeparator
GtkHSeparator
</programlisting>

<para>We'll further our exploration of GTK by examining each widget in turn,
creating a few simple functions to display them. Another good source
is the <literal>testgtk</literal> program that comes with GTK. It can be found in
<filename>tests/testgtk.c</filename>.</para>

</sect1>
</chapter>

<!--**************************************************************** -->
<chapter id="ch-ButtonWidget">
<title>The Button Widget</title>

<!-- ----------------------------------------------------------------- -->
<sect1 id="sec-NormalButtons">
<title>Normal Buttons</title>

<para>We've almost seen all there is to see of the button widget. It's
pretty simple. There is however more than one way to create a button. The
gtkButton() function takes a number of arguments. The <literal>label</literal>
parameter specifies the button label. If the <literal>stock.id</literal>
parameter is specified, a button is created containing the image and text from
a stock item (overriding the <literal>label</literal> parameter). 
You can also use gtkButtonNewWithMnemonic() to create a button with "mnemonic" label, meaning
that one can "press" the button using the key combination ALT + the character
underlined in the label. Prefix the character to underline with "_" in the
button label text. You can also call gtkButton() without any parameters.
It's then up to you to pack a label or pixmap into 
this new button. To do this, create a new box, and then pack your objects into 
this box using the usual gtkBoxPackStart(), and then use gtkContainerAdd() 
to pack the box into the button.</para>

<para>Here's an example of using gtkButton() to create a button with a
image and a label in it. I've broken up the code to create a box from the rest 
so you can use it in your programs. There are further examples of using images 
later in the tutorial.</para>

<para>
<inlinemediaobject>
<imageobject>
<imagedata fileref="images/buttons.png" format="png">
</imageobject>
</inlinemediaobject>
</para>

<programlisting role="R">
<!-- example-start buttons buttons.c -->

# Create a new hbox with an image and a label packed into it
# and return the box. 

xpmLabelBox &lt;- function (xpmFilename, labelText)
{
    # Create box for image and label 
    box &lt;- gtkHBox(FALSE, 0)
    box$setBorderWidth(2)

    # Now on to the image stuff 
    image &lt;- gtkImage(filename = xpmFilename)

    # Create a label for the button 
    label &lt;- gtkLabel(labelText)

    # Pack the image and label into the box 
    box$packStart(image, FALSE, FALSE, 3)
    box$packStart(label, FALSE, FALSE, 3)
    
    box
}

# Our usual callback function 
callback &lt;- function(widget, data)
{
    cat(sprintf("Hello again - %s was pressed\n", data))
}

# Create a new window 
window &lt;- gtkWindow()
window$setTitle("Pixmap'd Buttons!")

# Sets the border width of the window. 
window$setBorderWidth(10)

# Create a new button 
button &lt;- gtkButton()

# Connect the "clicked" signal of the button to our callback 
gSignalConnect(button, "clicked", callback, "cool button")

# This calls our box creating function 
box &lt;- xpmLabelBox ("info.xpm", "cool button")

button$add(box)
window$add(button)

<!-- example-end -->
</programlisting>

<para>The xpmLabelBox() function could be used to pack images and labels into
any widget that can be a container.</para>

<para>The Button widget has the following signals:</para>

<itemizedlist>
<listitem><simpara><literal>pressed</literal> - emitted when pointer button is pressed within
Button widget</simpara>
</listitem>
<listitem><simpara><literal>released</literal> - emitted when pointer button is released within
Button widget</simpara>
</listitem>
<listitem><simpara><literal>clicked</literal> - emitted when pointer button is pressed and then
released within Button widget</simpara>
</listitem>
<listitem><simpara><literal>enter</literal> - emitted when pointer enters Button widget</simpara>
</listitem>
<listitem><simpara><literal>leave</literal> - emitted when pointer leaves Button widget</simpara>
</listitem>
</itemizedlist>

</sect1>

<!-- ----------------------------------------------------------------- -->
<sect1 id="sec-ToggleButtons">
<title>Toggle Buttons</title>

<para>Toggle buttons are derived from normal buttons and are very similar,
except they will always be in one of two states, alternated by a
click. They may be depressed, and when you click again, they will pop
back up. Click again, and they will pop back down.</para>

<para>Toggle buttons are the basis for check buttons and radio buttons, as
such, many of the calls used for toggle buttons are inherited by radio
and check buttons. I will point these out when we come to them.</para>

<para>Creating a new toggle button:</para>

<programlisting role="R">
gtkToggleButton()
gtkToggleButton(label)
gtkToggleButtonNewWithMnemonic(label)
</programlisting>

<para>As you can imagine, these work identically to the normal button widget
calls. The first creates a blank toggle button, and the last two, a
button with a label widget already packed into it. The Mnemonic() variant
additionally parses the label for ''-prefixed mnemonic characters.</para>

<para>To retrieve the state of the toggle widget, including radio and check
buttons, we use a construct as shown in our example below. This tests
the state of the toggle button, by accessing the <literal>active</literal> field of the
toggle widget's structure. The signal of interest to us emitted by toggle
buttons (the toggle button, check button, and radio button widgets) is
the "toggled" signal. To check the state of these buttons, set up a
signal handler to catch the toggled signal, and access the structure
to determine its state. The callback will look something like:</para>

<programlisting role="R">
toggleButtonCallback &lt;- function(widget, data)
{
    if (widget$getActive()) 
    {
        # If control reaches here, the toggle button is down 
    
    } else {
    
        # If control reaches here, the toggle button is up 
    }
}
</programlisting>

<para>To force the state of a toggle button, and its children, the radio and
check buttons, use this function:</para>

<programlisting role="R">
gtkToggleButtonSetActive(toggleButton, isActive)
</programlisting>

<para>The above call can be used to set the state of the toggle button, and
its children the radio and check buttons. Passing in your created
button as the first argument, and a TRUE or FALSE for the second state
argument to specify whether it should be down (depressed) or up
(released). Default is up, or FALSE.</para>

<para>Note that when you use the gtkToggleButtonSetActive() function, and
the state is actually changed, it causes the "clicked" and "toggled"
signals to be emitted from the button.</para>

<programlisting role="R">
gtkToggleButtonGetActive(toggleButton)
</programlisting>

<para>This returns the current state of the toggle button as a boolean
TRUE/FALSE value.</para>

</sect1>

<!-- ----------------------------------------------------------------- -->
<sect1 id="sec-CheckButtons">
<title>Check Buttons</title>

<para>Check buttons inherit many properties and functions from the the
toggle buttons above, but look a little different. Rather than being
buttons with text inside them, they are small squares with the text to
the right of them. These are often used for toggling options on and
off in applications.</para>

<para>The creation functions are similar to those of the normal button.</para>

<programlisting role="R">
gtkCheckButton()
gtkCheckButton(label)
gtkCheckButtonNewWithMnemonic(label)
</programlisting>

<para>The gtkCheckButtonNewWithLabel() function creates a check button 
with a label beside it.</para>

<para>Checking the state of the check button is identical to that of the
toggle button.</para>

</sect1>

<!-- ----------------------------------------------------------------- -->
<sect1 id="sec-RadioButtons">
<title>Radio Buttons</title>

<para>Radio buttons are similar to check buttons except they are grouped so
that only one may be selected/depressed at a time. This is good for
places in your application where you need to select from a short list
of options.</para>

<para>Creating a new radio button is done with one of these calls:</para>

<programlisting role="R">
gtkRadioButton(group)
gtkRadioButtonNewFromWidget(widget)
gtkRadioButton(group, label)
gtkRadioButtonNewWithLabelFromWidget(group, label)
gtkRadioButtonNewWithMnemonic(group, label)
gtkRadioButtonNewWithMnemonicFromWidget(group, label)
</programlisting>

<para>You'll notice the extra argument to these calls. They require a group
to perform their duty properly. The first call to gtkRadioButton()
should pass NULL as the first argument. 
Then create a group using:</para>

<programlisting role="R">
radioButton$getGroup()
</programlisting>

<para>The important thing to remember is that gtkRadioButtonGetGroup() must be
called for each new button added to the group, with the previous button passed 
in as an argument. The result is then passed into the next call to 
gtkRadioButton(). This allows a
chain of buttons to be established. The example below should make this clear.</para>

<para>You can shorten this slightly by using the following syntax, which
removes the need for a variable to hold the list of buttons:</para>

<programlisting role="R">
     button2 &lt;- gtkRadioButton(button1$getGroup(), "button2")
</programlisting>

<para>
The FromWidget() variants of the creation functions allow you to shorten this
further, by omitting the gtkRadioButtonGetGroup() call. This form is used 
in the example to create the third button:
</para>

<programlisting role="R">
     button2 &lt;- gtkRadioButtonNewWithLabelFromWidget(button1, "button2")
</programlisting>

<para>It is also a good idea to explicitly set which button should be the
default depressed button with:</para>

<programlisting role="R">
toggleButton$setActive(state)
</programlisting>

<para>This is described in the section on toggle buttons, and works in
exactly the same way.  Once the radio buttons are grouped together,
only one of the group may be active at a time. If the user clicks on
one radio button, and then on another, the first radio button will
first emit a "toggled" signal (to report becoming inactive), and then
the second will emit its "toggled" signal (to report becoming active).</para>

<para>The following example creates a radio button group with three buttons.</para>

<para>
<inlinemediaobject>
<imageobject>
<imagedata fileref="images/radiobuttons.png" format="png">
</imageobject>
</inlinemediaobject>
</para>

<programlisting role="R">
<!-- example-start radiobuttons radiobuttons.c -->

window &lt;- gtkWindow()

window$setTitle("radio buttons")
window$setBorderWidth(0)

box1 &lt;- gtkVbox(FALSE, 0)
window$add(box1)

box2 &lt;- gtkVbox(FALSE, 10)
box2$setBorderWidth(10)

box1$packStart(box2, TRUE, TRUE, 0)

button &lt;- gtkRadioButton(NULL, "button1")
box2$packStart(button, TRUE, TRUE, 0)

group &lt;- button$getGroup()
button &lt;- gtkRadioButton(group, "button2")
button$setActive(TRUE)
box2$packStart(button, TRUE, TRUE, 0)

button &lt;- gtkRadioButtonNewWithLabelFromWidget(button, "button3")
box2$packStart(button, TRUE, TRUE, 0)

separator &lt;- gtkHseparator()
box1$packStart(separator, FALSE, TRUE, 0)

box2 &lt;- gtkVbox(FALSE, 10)
box2$setBorderWidth(10)
box1$packStart(box2, FALSE, TRUE, 0)

button &lt;- gtkButton("close")
box2$packStart(button, TRUE, TRUE, 0)
button$setFlags("can-default")
button$grabDefault()

<!-- example-end -->
</programlisting>

</sect1>
</chapter>

<!--**************************************************************** -->
<chapter id="ch-Adjustments">
<title>Adjustments</title>

<para>GTK has various widgets that can be visually adjusted by the user
using the mouse or the keyboard, such as the range widgets, described
in the <link linkend="ch-RangeWidgets">Range Widgets</link>
section. There are also a few widgets that display some adjustable
portion of a larger area of data, such as the text widget and the
viewport widget.</para>

<para>Obviously, an application needs to be able to react to changes the
user makes in range widgets. One way to do this would be to have each
widget emit its own type of signal when its adjustment changes, and
either pass the new value to the signal handler, or require it to look
inside the widget's data structure in order to ascertain the value.
But you may also want to connect the adjustments of several widgets
together, so that adjusting one adjusts the others. The most obvious
example of this is connecting a scrollbar to a panning viewport or a
scrolling text area. If each widget has its own way of setting or
getting the adjustment value, then the programmer may have to write
their own signal handlers to translate between the output of one
widget's signal and the "input" of another's adjustment setting
function.</para>

<para>GTK solves this problem using the Adjustment object, which is not a
widget but a way for widgets to store and pass adjustment information
in an abstract and flexible form. The most obvious use of Adjustment
is to store the configuration parameters and values of range widgets,
such as scrollbars and scale controls. However, since Adjustments are
derived from Object, they have some special powers beyond those of
normal data structures. Most importantly, they can emit signals, just
like widgets, and these signals can be used not only to allow your
program to react to user input on adjustable widgets, but also to
propagate adjustment values transparently between adjustable widgets.</para>

<para>You will see how adjustments fit in when you see the other widgets
that incorporate them:
<link linkend="sec-ProgressBars">Progress Bars</link>,
<link linkend="sec-Viewports">Viewports</link>,
<link linkend="sec-ScrolledWindows">Scrolled Windows</link>, and others.</para>

<!-- ----------------------------------------------------------------- -->
<sect1 id="sec-CreatingAnAdjustment">
<title>Creating an Adjustment</title>

<para>Many of the widgets which use adjustment objects do so automatically,
but some cases will be shown in later examples where you may need to
create one yourself. You create an adjustment using:</para>

<programlisting role="R">
gtkAdjustment(value, lower, upper, stepIncrement, pageIncrement, pageSize)
</programlisting>

<para>The <literal>value</literal> argument is the initial value you want to give to the
adjustment, usually corresponding to the topmost or leftmost position
of an adjustable widget. The <literal>lower</literal> argument specifies the lowest
value which the adjustment can hold. The <literal>stepIncrement</literal> argument
specifies the "smaller" of the two increments by which the user can
change the value, while the <literal>pageIncrement</literal> is the "larger" one.
The <literal>pageSize</literal> argument usually corresponds somehow to the visible
area of a panning widget. The <literal>upper</literal> argument is used to represent
the bottom most or right most coordinate in a panning widget's
child. Therefore it is <emphasis>not</emphasis> always the largest number that
<literal>value</literal> can take, since the <literal>pageSize</literal> of such widgets is
usually non-zero.</para>

</sect1>

<!-- ----------------------------------------------------------------- -->
<sect1 id="sec-UsingAdjustments">
<title>Using Adjustments the Easy Way</title>

<para>The adjustable widgets can be roughly divided into those which use and
require specific units for these values and those which treat them as
arbitrary numbers. The group which treats the values as arbitrary
numbers includes the range widgets (scrollbars and scales, the
progress bar widget, and the spin button widget). These widgets are
all the widgets which are typically "adjusted" directly by the user
with the mouse or keyboard. They will treat the <literal>lower</literal> and
<literal>upper</literal> values of an adjustment as a range within which the user
can manipulate the adjustment's <literal>value</literal>. By default, they will only
modify the <literal>value</literal> of an adjustment.</para>

<para>The other group includes the text widget, the viewport widget, the
compound list widget, and the scrolled window widget. All of these
widgets use pixel values for their adjustments. These are also all
widgets which are typically "adjusted" indirectly using scrollbars.
While all widgets which use adjustments can either create their own
adjustments or use ones you supply, you'll generally want to let this
particular category of widgets create its own adjustments. Usually,
they will eventually override all the values except the <literal>value</literal>
itself in whatever adjustments you give them, but the results are, in
general, undefined (meaning, you'll have to read the source code to
find out, and it may be different from widget to widget).</para>

<para>Now, you're probably thinking, since text widgets and viewports insist
on setting everything except the <literal>value</literal> of their adjustments,
while scrollbars will <emphasis>only</emphasis> touch the adjustment's 
<literal>value</literal>, if you <emphasis>share</emphasis> an adjustment
object between a scrollbar and a text widget, manipulating the scrollbar will 
automagically adjust the viewport widget?  Of course it will! Just like this:</para>

<programlisting role="R">
  # creates its own adjustments 
  viewport &lt;- gtkViewport()
  # uses the newly-created adjustment for the scrollbar as well 
  vscrollbar &lt;- gtkVScrollbar(viewport$getVadjustment())
</programlisting>

</sect1>

<!-- ----------------------------------------------------------------- -->
<sect1 id="sec-AdjustmentInternals">
<title>Adjustment Internals</title>

<para>Ok, you say, that's nice, but what if I want to create my own handlers
to respond when the user adjusts a range widget or a spin button, and
how do I get at the value of the adjustment in these handlers? 

<programlisting role="R">
adjustment$getValue()
</programlisting>

<para>Since, when you set the <literal>value</literal> of an Adjustment, you generally
want the change to be reflected by every widget that uses this
adjustment, GTK provides this convenience function to do this:</para>

<programlisting role="R">
adjustment$setValue(value)
</programlisting>

<para>As mentioned earlier, Adjustment is a subclass of Object just
like all the various widgets, and thus it is able to emit signals.
This is, of course, why updates happen automagically when you share an
adjustment object between a scrollbar and another adjustable widget;
all adjustable widgets connect signal handlers to their adjustment's
<literal>valueChanged</literal> signal, as can your program. Here's the definition
of this signal in <literal>GtkAdjustmentClass</literal>:</para>

<programlisting role="R">
  valueChanged(adjustment)
</programlisting>

<para>The various widgets that use the Adjustment object will emit this
signal on an adjustment whenever they change its value. This happens
both when user input causes the slider to move on a range widget, as
well as when the program explicitly changes the value with
gtkAdjustmentSetValue(). So, for example, if you have a scale
widget, and you want to change the rotation of a picture whenever its
value changes, you would create a callback like this:</para>

<programlisting role="R">
cbRotatePicture &lt;- function(adj, picture)
{
  setPictureRotation (picture, adj$getValue())
...
</programlisting>

<para>and connect it to the scale widget's adjustment like this:</para>

<programlisting role="R">
gSignalConnect (adj, "valueChanged", cbRotatePicture, picture)
</programlisting>

<para>What about when a widget reconfigures the <literal>upper</literal> or <literal>lower</literal>
fields of its adjustment, such as when a user adds more text to a text
widget?  In this case, it emits the <literal>changed</literal> signal, which looks
like this:</para>

<programlisting role="R">
  changed(adjustment)
</programlisting>

<para>Range widgets typically connect a handler to this signal, which
changes their appearance to reflect the change - for example, the size
of the slider in a scrollbar will grow or shrink in inverse proportion
to the difference between the <literal>lower</literal> and <literal>upper</literal> values of its
adjustment.</para>

<para>You probably won't ever need to attach a handler to this signal,
unless you're writing a new type of range widget.  However, if you
change any of the values in a Adjustment directly, you should emit
this signal on it to reconfigure whatever widgets are using it, like
this:</para>

<programlisting role="R">
gSignalEmit(adjustment, "changed")
</programlisting>

<para>Now go forth and adjust!</para>

</sect1>
</chapter>

<!--**************************************************************** -->
<chapter id="ch-RangeWidgets">
<title>Range Widgets</title>

<para>The category of range widgets includes the ubiquitous scrollbar widget
and the less common scale widget. Though these two types of widgets
are generally used for different purposes, they are quite similar in
function and implementation. All range widgets share a set of common
graphic elements, each of which has its own X window and receives
events. They all contain a "trough" and a "slider" (what is sometimes
called a "thumbwheel" in other GUI environments). Dragging the slider
with the pointer moves it back and forth within the trough, while
clicking in the trough advances the slider towards the location of the
click, either completely, or by a designated amount, depending on
which mouse button is used.</para>

<para>As mentioned in <link linkend="ch-Adjustments">Adjustments</link> above,
all range widgets are associated with an adjustment object, from which
they calculate the length of the slider and its position within the
trough. When the user manipulates the slider, the range widget will
change the value of the adjustment.</para>

<!-- ----------------------------------------------------------------- -->
<sect1 id="sec-ScrollbarWidgets">
<title>Scrollbar Widgets</title>

<para>These are your standard, run-of-the-mill scrollbars. These should be
used only for scrolling some other widget, such as a list, a text box,
or a viewport (and it's generally easier to use the scrolled window
widget in most cases).  For other purposes, you should use scale
widgets, as they are friendlier and more featureful.</para>

<para>There are separate types for horizontal and vertical scrollbars.
There really isn't much to say about these. You create them with the
following functions:</para>

<programlisting role="R">
gtkHScrollbar(adjustment)

gtkVScrollbar(adjustment)
</programlisting>

<para>and that's about it (if you don't believe me, look in the header
files!).  The <literal>adjustment</literal> argument can either be a pointer to an
existing Adjustment, or NULL, in which case one will be created for
you. Specifying NULL might actually be useful in this case, if you
wish to pass the newly-created adjustment to the constructor function
of some other widget which will configure it for you, such as a text
widget.</para>

</sect1>

<!-- ----------------------------------------------------------------- -->
<sect1 id="sec-ScaleWidgets">
<title>Scale Widgets</title>

<para>Scale widgets are used to allow the user to visually select and
manipulate a value within a specific range. You might want to use a
scale widget, for example, to adjust the magnification level on a
zoomed preview of a picture, or to control the brightness of a color,
or to specify the number of minutes of inactivity before a screensaver
takes over the screen.</para>

<!-- ----------------------------------------------------------------- -->
<sect2>
<title>Creating a Scale Widget</title>

<para>As with scrollbars, there are separate widget types for horizontal and
vertical scale widgets. (Most programmers seem to favour horizontal
scale widgets.) Since they work essentially the same way, there's no
need to treat them separately here. The following functions create vertical and 
horizontal scale widgets, respectively:</para>

<programlisting role="R">
gtkVScale(adjustment)
gtkVScale(, min, max, step)

gtkHScale(adjustment)
gtkHScale(, min, max, step)
</programlisting>

<para>The <literal>adjustment</literal> argument can either be an adjustment which has
already been created with gtkAdjustment(), or NULL, in
which case, an anonymous Adjustment is created with all of its
values set to <literal>0.0</literal> (which isn't very useful in this case). 
In order to avoid confusing yourself, you probably want to create your
adjustment with a <literal>pageSize</literal> of <literal>0.0</literal> so 
that its <literal>upper</literal> value actually corresponds to the highest 
value the user can select. (If you're <emphasis>already</emphasis> thoroughly
confused, read the section on <link linkend="ch-Adjustments">Adjustments</link> 
again for an explanation of what exactly adjustments do and how to create and 
manipulate them.)</para>

</sect2>

<!-- ----------------------------------------------------------------- -->
<sect2>
<title>Functions and Signals (well, functions, at least)</title>

<para>Scale widgets can display their current value as a number beside the
trough. The default behaviour is to show the value, but you can change
this with this function:</para>

<programlisting role="R">
void gtkScaleSetDrawValue( GtkScale#scale,
                               gboolean drawValue );
</programlisting>

<para>As you might have guessed, <literal>drawValue</literal> is either <literal>TRUE</literal> or
<literal>FALSE</literal>, with predictable consequences for either one.</para>

<para>The value displayed by a scale widget is rounded to one decimal point
by default, as is the <literal>value</literal> field in its Adjustment. You can
change this with:</para>

<programlisting role="R">
void gtkScaleSetDigits( GtkScale#scale,
                            gint     digits );
</programlisting>

<para>where <literal>digits</literal> is the number of decimal places you want. You can
set <literal>digits</literal> to anything you like, but no more than 13 decimal
places will actually be drawn on screen.</para>

<para>Finally, the value can be drawn in different positions
relative to the trough:</para>

<programlisting role="R">
void gtkScaleSetValuePos( GtkScale       #scale,
                              GtkPositionType  pos );
</programlisting>

<para>The argument <literal>pos</literal> is of type <literal>GtkPositionType</literal>,
which can take one of the following values:</para>

<programlisting role="R">
  GTKPOSLEFT
  GTKPOSRIGHT
  GTKPOSTOP
  GTKPOSBOTTOM
</programlisting>

<para>If you position the value on the "side" of the trough (e.g., on the
top or bottom of a horizontal scale widget), then it will follow the
slider up and down the trough.</para>

<para>All the preceding functions are defined in
<literal>&lt;gtk/gtkscale.h&gt;</literal>. The header files for all GTK widgets
are automatically included when you include
<literal>&lt;gtk/gtk.h&gt;</literal>. But you should look over the header files
of all widgets that interest you, in order to learn more about their functions
and features.</para>

</sect2>
</sect1>

<!-- ----------------------------------------------------------------- -->
<sect1 id="sec-CommonRangeFunctions">
<title>Common Range Functions</title>

<para>The Range widget class is fairly complicated internally, but, like
all the "base class" widgets, most of its complexity is only
interesting if you want to hack on it. Also, almost all of the
functions and signals it defines are only really used in writing
derived widgets. There are, however, a few useful functions that are
defined in <literal>&lt;gtk/gtkrange.h&gt;</literal> and will work on all range
widgets.</para>

<!-- ----------------------------------------------------------------- -->
<sect2>
<title>Setting the Update Policy</title>

<para>The "update policy" of a range widget defines at what points during
user interaction it will change the <literal>value</literal> field of its
Adjustment and emit the "valueChanged" signal on this
Adjustment. The update policies, defined in
<literal>&lt;gtk/gtkenums.h&gt;</literal> as type <literal>enum GtkUpdateType</literal>,
are:</para>

<variablelist>
<varlistentry>
<term><literal>GTKUPDATECONTINUOUS</literal></term>
<listitem><para>This is the default. The
"valueChanged" signal is emitted continuously, i.e., whenever the
slider is moved by even the tiniest amount.</para>
</listitem>
</varlistentry>
<varlistentry>
<term><literal>GTKUPDATEDISCONTINUOUS</literal></term>
<listitem><para>The "valueChanged" signal is
only emitted once the slider has stopped moving and the user has
released the mouse button.</para>
</listitem>
</varlistentry>
<varlistentry>
<term><literal>GTKUPDATEDELAYED</literal></term>
<listitem><para>The "valueChanged" signal is emitted
when the user releases the mouse button, or if the slider stops moving
for a short period of time.</para>
</listitem>
</varlistentry>
</variablelist>

<para>The update policy of a range widget can be set by casting it using the
<literal>GTKRANGE(widget)</literal> macro and passing it to this function:</para>

<programlisting role="R">
void gtkRangeSetUpdatePolicy( GtkRange     #range,
	                          GtkUpdateType  policy);
</programlisting>

</sect2>

<!-- ----------------------------------------------------------------- -->
<sect2>
<title>Getting and Setting Adjustments</title>

<para>Getting and setting the adjustment for a range widget "on the fly" is
done, predictably, with:</para>

<programlisting role="R">
GtkAdjustment* gtkRangeGetAdjustment( GtkRange#range );

void gtkRangeSetAdjustment( GtkRange     #range,
                               GtkAdjustment#adjustment );
</programlisting>

<para><literal>gtkRangeGetAdjustment()</literal> returns a pointer to the adjustment to
which <literal>range</literal> is connected.</para>

<para><literal>gtkRangeSetAdjustment()</literal> does absolutely nothing if you pass it
the adjustment that <literal>range</literal> is already using, regardless of whether
you changed any of its fields or not. If you pass it a new
Adjustment, it will unreference the old one if it exists (possibly
destroying it), connect the appropriate signals to the new one, and
call the private function <literal>gtkRangeAdjustmentChanged()</literal>, which
will (or at least, is supposed to...) recalculate the size and/or
position of the slider and redraw if necessary. As mentioned in the
section on adjustments, if you wish to reuse the same Adjustment,
when you modify its values directly, you should emit the "changed"
signal on it, like this:</para>

<programlisting role="R">
gSignalEmitByName (GOBJECT (adjustment), "changed");
</programlisting>

</sect2>
</sect1>

<!-- ----------------------------------------------------------------- -->
<sect1 id="sec-KeyAndMouseBindings">
<title>Key and Mouse bindings</title>

<para>All of the GTK range widgets react to mouse clicks in more or less
the same way. Clicking button-1 in the trough will cause its
adjustment's <literal>pageIncrement</literal> to be added or subtracted from its
<literal>value</literal>, and the slider to be moved accordingly. Clicking mouse
button-2 in the trough will jump the slider to the point at which the
button was clicked. Clicking button-3 in the trough of a range or any button on 
a scrollbar's arrows will cause its adjustment's value to change by
<literal>stepIncrement</literal> at a time.</para>

<para>Scrollbars are not focusable, thus have no key bindings. The key bindings
for the other range widgets (which are, of course, only active when the widget 
has focus) are do <emphasis>not</emphasis> differentiate between horizontal and 
vertical range widgets.</para>

<para>All range widgets can be operated with the left, right, up and down arrow
keys, as well as with the <literal>Page Up</literal> and <literal>Page Down</literal> 
keys. The arrows move the slider up and down by <literal>stepIncrement</literal>, while
<literal>Page Up</literal> and <literal>Page Down</literal> move it by 
<literal>pageIncrement</literal>.</para>

<para>The user can also move the slider all the way to one end or the other
of the trough using the keyboard. This is done with the <literal>Home</literal> 
and <literal>End</literal> keys.</para>

</sect1>

<!-- ----------------------------------------------------------------- -->
<sect1 id="sec-RangeWidgetsExample">
<title>Example</title>

<para>This example is a somewhat modified version of the "range controls"
test from <filename>testgtk.c</filename>. It basically puts up a window with three
range widgets all connected to the same adjustment, and a couple of
controls for adjusting some of the parameters mentioned above and in
the section on adjustments, so you can see how they affect the way
these widgets work for the user.</para>

<para>
<inlinemediaobject>
<imageobject>
<imagedata fileref="images/rangewidgets.png" format="png">
</imageobject>
</inlinemediaobject>
</para>

<programlisting role="R">
<!-- example-start rangewidgets rangewidgets.c -->

#include &lt;gtk/gtk.h&gt;

GtkWidget#hscale,#vscale;

static void cbPosMenuSelect( GtkWidget      #item,
                                GtkPositionType  pos )
{
    # Set the value position on both scale widgets 
    gtkScaleSetValuePos (GTKSCALE (hscale), pos);
    gtkScaleSetValuePos (GTKSCALE (vscale), pos);
}

static void cbUpdateMenuSelect( GtkWidget    #item,
                                   GtkUpdateType  policy )
{
    # Set the update policy for both scale widgets 
    gtkRangeSetUpdatePolicy (GTKRANGE (hscale), policy);
    gtkRangeSetUpdatePolicy (GTKRANGE (vscale), policy);
}

static void cbDigitsScale( GtkAdjustment#adj )
{
    # Set the number of decimal places to which adj->value is rounded 
    gtkScaleSetDigits (GTKSCALE (hscale), (gint) adj->value);
    gtkScaleSetDigits (GTKSCALE (vscale), (gint) adj->value);
}

static void cbPageSize( GtkAdjustment#get,
                          GtkAdjustment#set )
{
    # Set the page size and page increment size of the sample
    # adjustment to the value specified by the "Page Size" scale 
    set->pageSize = get->value;
    set->pageIncrement = get->value;

    # This sets the adjustment and makes it emit the "changed" signal to 
       reconfigure all the widgets that are attached to this signal.  
    gtkAdjustmentSetValue (set, CLAMP (set->value,
					  set->lower,
					  (set->upper - set->pageSize)));
    gSignalEmitByName(GOBJECT(set), "changed");
}

static void cbDrawValue( GtkToggleButton#button )
{
    # Turn the value display on the scale widgets off or on depending
    #  on the state of the checkbutton 
    gtkScaleSetDrawValue (GTKSCALE (hscale), button->active);
    gtkScaleSetDrawValue (GTKSCALE (vscale), button->active);  
}

# Convenience functions 

static GtkWidget#makeMenuItem ( gchar    #name,
                                   GCallback  callback,
                                   gpointer   data )
{
    GtkWidget#item;
  
    item = gtkMenuItemNewWithLabel (name);
    gSignalConnect (GOBJECT (item), "activate",
	              callback, (gpointer) data);
    gtkWidgetShow (item);

    return item;
}

static void scaleSetDefaultValues( GtkScale#scale )
{
    gtkRangeSetUpdatePolicy (GTKRANGE (scale),
                                 GTKUPDATECONTINUOUS);
    gtkScaleSetDigits (scale, 1);
    gtkScaleSetValuePos (scale, GTKPOSTOP);
    gtkScaleSetDrawValue (scale, TRUE);
}

# makes the sample window 

static void createRangeControls( void )
{
    GtkWidget#window;
    GtkWidget#box1,#box2,#box3;
    GtkWidget#button;
    GtkWidget#scrollbar;
    GtkWidget#separator;
    GtkWidget#opt,#menu,#item;
    GtkWidget#label;
    GtkWidget#scale;
    GtkObject#adj1,#adj2;

    # Standard window-creating stuff 
    window = gtkWindowNew (GTKWINDOWTOPLEVEL);
    gSignalConnect (GOBJECT (window), "destroy",
                      GCALLBACK (gtkMainQuit),
                      NULL);
    gtkWindowSetTitle (GTKWINDOW (window), "range controls");

    box1 = gtkVboxNew (FALSE, 0);
    gtkContainerAdd (GTKCONTAINER (window), box1);
    gtkWidgetShow (box1);

    box2 = gtkHboxNew (FALSE, 10);
    gtkContainerSetBorderWidth (GTKCONTAINER (box2), 10);
    gtkBoxPackStart (GTKBOX (box1), box2, TRUE, TRUE, 0);
    gtkWidgetShow (box2);

    # value, lower, upper, stepIncrement, pageIncrement, pageSize 
    # Note that the pageSize value only makes a difference for
    # scrollbar widgets, and the highest value you'll get is actually
    # (upper - pageSize). 
    adj1 = gtkAdjustmentNew (0.0, 0.0, 101.0, 0.1, 1.0, 1.0);
  
    vscale = gtkVscaleNew (GTKADJUSTMENT (adj1));
    scaleSetDefaultValues (GTKSCALE (vscale));
    gtkBoxPackStart (GTKBOX (box2), vscale, TRUE, TRUE, 0);
    gtkWidgetShow (vscale);

    box3 = gtkVboxNew (FALSE, 10);
    gtkBoxPackStart (GTKBOX (box2), box3, TRUE, TRUE, 0);
    gtkWidgetShow (box3);

    # Reuse the same adjustment 
    hscale = gtkHscaleNew (GTKADJUSTMENT (adj1));
    gtkWidgetSetSizeRequest (GTKWIDGET (hscale), 200, -1);
    scaleSetDefaultValues (GTKSCALE (hscale));
    gtkBoxPackStart (GTKBOX (box3), hscale, TRUE, TRUE, 0);
    gtkWidgetShow (hscale);

    # Reuse the same adjustment again 
    scrollbar = gtkHscrollbarNew (GTKADJUSTMENT (adj1));
    # Notice how this causes the scales to always be updated
    # continuously when the scrollbar is moved 
    gtkRangeSetUpdatePolicy (GTKRANGE (scrollbar), 
                                 GTKUPDATECONTINUOUS);
    gtkBoxPackStart (GTKBOX (box3), scrollbar, TRUE, TRUE, 0);
    gtkWidgetShow (scrollbar);

    box2 = gtkHboxNew (FALSE, 10);
    gtkContainerSetBorderWidth (GTKCONTAINER (box2), 10);
    gtkBoxPackStart (GTKBOX (box1), box2, TRUE, TRUE, 0);
    gtkWidgetShow (box2);

    # A checkbutton to control whether the value is displayed or not 
    button = gtkCheckButtonNewWithLabel("Display value on scale widgets");
    gtkToggleButtonSetActive (GTKTOGGLEBUTTON (button), TRUE);
    gSignalConnect (GOBJECT (button), "toggled",
                      GCALLBACK (cbDrawValue), NULL);
    gtkBoxPackStart (GTKBOX (box2), button, TRUE, TRUE, 0);
    gtkWidgetShow (button);
  
    box2 = gtkHboxNew (FALSE, 10);
    gtkContainerSetBorderWidth (GTKCONTAINER (box2), 10);

    # An option menu to change the position of the value 
    label = gtkLabelNew ("Scale Value Position:");
    gtkBoxPackStart (GTKBOX (box2), label, FALSE, FALSE, 0);
    gtkWidgetShow (label);
  
    opt = gtkOptionMenuNew ();
    menu = gtkMenuNew ();

    item = makeMenuItem ("Top",
                           GCALLBACK (cbPosMenuSelect),
                           GINTTOPOINTER (GTKPOSTOP));
    gtkMenuShellAppend (GTKMENUSHELL (menu), item);
  
    item = makeMenuItem ("Bottom", GCALLBACK (cbPosMenuSelect), 
                           GINTTOPOINTER (GTKPOSBOTTOM));
    gtkMenuShellAppend (GTKMENUSHELL (menu), item);
  
    item = makeMenuItem ("Left", GCALLBACK (cbPosMenuSelect),
                           GINTTOPOINTER (GTKPOSLEFT));
    gtkMenuShellAppend (GTKMENUSHELL (menu), item);
  
    item = makeMenuItem ("Right", GCALLBACK (cbPosMenuSelect),
                           GINTTOPOINTER (GTKPOSRIGHT));
    gtkMenuShellAppend (GTKMENUSHELL (menu), item);
  
    gtkOptionMenuSetMenu (GTKOPTIONMENU (opt), menu);
    gtkBoxPackStart (GTKBOX (box2), opt, TRUE, TRUE, 0);
    gtkWidgetShow (opt);

    gtkBoxPackStart (GTKBOX (box1), box2, TRUE, TRUE, 0);
    gtkWidgetShow (box2);

    box2 = gtkHboxNew (FALSE, 10);
    gtkContainerSetBorderWidth (GTKCONTAINER (box2), 10);

    # Yet another option menu, this time for the update policy of the
    # scale widgets 
    label = gtkLabelNew ("Scale Update Policy:");
    gtkBoxPackStart (GTKBOX (box2), label, FALSE, FALSE, 0);
    gtkWidgetShow (label);
  
    opt = gtkOptionMenuNew ();
    menu = gtkMenuNew ();
  
    item = makeMenuItem ("Continuous",
                           GCALLBACK (cbUpdateMenuSelect),
                           GINTTOPOINTER (GTKUPDATECONTINUOUS));
    gtkMenuShellAppend (GTKMENUSHELL (menu), item);
  
    item = makeMenuItem ("Discontinuous",
                           GCALLBACK (cbUpdateMenuSelect),
                           GINTTOPOINTER (GTKUPDATEDISCONTINUOUS));
    gtkMenuShellAppend (GTKMENUSHELL (menu), item);
  
    item = makeMenuItem ("Delayed",
                           GCALLBACK (cbUpdateMenuSelect),
                           GINTTOPOINTER (GTKUPDATEDELAYED));
    gtkMenuShellAppend (GTKMENUSHELL (menu), item);
  
    gtkOptionMenuSetMenu (GTKOPTIONMENU (opt), menu);
    gtkBoxPackStart (GTKBOX (box2), opt, TRUE, TRUE, 0);
    gtkWidgetShow (opt);
  
    gtkBoxPackStart (GTKBOX (box1), box2, TRUE, TRUE, 0);
    gtkWidgetShow (box2);

    box2 = gtkHboxNew (FALSE, 10);
    gtkContainerSetBorderWidth (GTKCONTAINER (box2), 10);
  
    # An HScale widget for adjusting the number of digits on the
    # sample scales. 
    label = gtkLabelNew ("Scale Digits:");
    gtkBoxPackStart (GTKBOX (box2), label, FALSE, FALSE, 0);
    gtkWidgetShow (label);

    adj2 = gtkAdjustmentNew (1.0, 0.0, 5.0, 1.0, 1.0, 0.0);
    gSignalConnect (GOBJECT (adj2), "valueChanged",
                      GCALLBACK (cbDigitsScale), NULL);
    scale = gtkHscaleNew (GTKADJUSTMENT (adj2));
    gtkScaleSetDigits (GTKSCALE (scale), 0);
    gtkBoxPackStart (GTKBOX (box2), scale, TRUE, TRUE, 0);
    gtkWidgetShow (scale);

    gtkBoxPackStart (GTKBOX (box1), box2, TRUE, TRUE, 0);
    gtkWidgetShow (box2);
  
    box2 = gtkHboxNew (FALSE, 10);
    gtkContainerSetBorderWidth (GTKCONTAINER (box2), 10);
  
    # And, one last HScale widget for adjusting the page size of the
    # scrollbar. 
    label = gtkLabelNew ("Scrollbar Page Size:");
    gtkBoxPackStart (GTKBOX (box2), label, FALSE, FALSE, 0);
    gtkWidgetShow (label);

    adj2 = gtkAdjustmentNew (1.0, 1.0, 101.0, 1.0, 1.0, 0.0);
    gSignalConnect (GOBJECT (adj2), "valueChanged",
                      GCALLBACK (cbPageSize), (gpointer) adj1);
    scale = gtkHscaleNew (GTKADJUSTMENT (adj2));
    gtkScaleSetDigits (GTKSCALE (scale), 0);
    gtkBoxPackStart (GTKBOX (box2), scale, TRUE, TRUE, 0);
    gtkWidgetShow (scale);

    gtkBoxPackStart (GTKBOX (box1), box2, TRUE, TRUE, 0);
    gtkWidgetShow (box2);

    separator = gtkHseparatorNew ();
    gtkBoxPackStart (GTKBOX (box1), separator, FALSE, TRUE, 0);
    gtkWidgetShow (separator);

    box2 = gtkVboxNew (FALSE, 10);
    gtkContainerSetBorderWidth (GTKCONTAINER (box2), 10);
    gtkBoxPackStart (GTKBOX (box1), box2, FALSE, TRUE, 0);
    gtkWidgetShow (box2);

    button = gtkButtonNewWithLabel ("Quit");
    gSignalConnectSwapped (GOBJECT (button), "clicked",
                              GCALLBACK (gtkMainQuit),
                              NULL);
    gtkBoxPackStart (GTKBOX (box2), button, TRUE, TRUE, 0);
    GTKWIDGETSETFLAGS (button, GTKCANDEFAULT);
    gtkWidgetGrabDefault (button);
    gtkWidgetShow (button);

    gtkWidgetShow (window);
}

int main( int   argc,
          char#argv[] )
{
    gtkInit (&amp;argc, &amp;argv);

    createRangeControls ();

    gtkMain ();

    return 0;
}

<!-- example-end -->
</programlisting>

<para>You will notice that the program does not call gSignalConnect()
for the "deleteEvent", but only for the "destroy" signal. This will
still perform the desired function, because an unhandled
"deleteEvent" will result in a "destroy" signal being given to the
window.</para>

</sect1>
</chapter>

<!--**************************************************************** -->
<chapter id="ch-MiscWidgets">
<title>Miscellaneous Widgets</title>

<!-- ----------------------------------------------------------------- -->
<sect1 id="sec-Labels">
<title>Labels</title>

<para>Labels are used a lot in GTK, and are relatively simple. Labels emit
no signals as they do not have an associated X window. If you need to
catch signals, or do clipping, place it inside a <link linkend="sec-EventBox">
EventBox</link> widget or a Button widget.</para>

<para>To create a new label, use:</para>

<programlisting role="R">
GtkWidget#gtkLabelNew( const char#str );

GtkWidget#gtkLabelNewWithMnemonic( const char#str );
</programlisting>

<para>The sole argument is the string you wish the label to display.</para>

<para>To change the label's text after creation, use the function:</para>

<programlisting role="R">
void gtkLabelSetText( GtkLabel  #label,
                         const char#str );
</programlisting>

<para>The first argument is the label you created previously (cast
using the <literal>GTKLABEL()</literal> macro), and the second is the new string.</para>

<para>The space needed for the new string will be automatically adjusted if
needed. You can produce multi-line labels by putting line breaks in
the label string.</para>

<para>To retrieve the current string, use:</para>

<programlisting role="R">
const gchar* gtkLabelGetText( GtkLabel #label );                    
</programlisting>

<para>Do not free the returned string, as it is used internally by GTK.</para>

<para>The label text can be justified using:</para>

<programlisting role="R">
void gtkLabelSetJustify( GtkLabel        #label,
                            GtkJustification  jtype );
</programlisting>

<para>Values for <literal>jtype</literal> are:</para>
<programlisting role="R">
  GTKJUSTIFYLEFT
  GTKJUSTIFYRIGHT
  GTKJUSTIFYCENTER (the default)
  GTKJUSTIFYFILL
</programlisting>

<para>The label widget is also capable of line wrapping the text
automatically. This can be activated using:</para>

<programlisting role="R">
void gtkLabelSetLineWrap (GtkLabel#label,
                              gboolean  wrap);
</programlisting>

<para>The <literal>wrap</literal> argument takes a TRUE or FALSE value.</para>

<para>If you want your label underlined, then you can set a pattern on the
label:</para>

<programlisting role="R">
void       gtkLabelSetPattern   (GtkLabel         #label,
                                    const gchar      #pattern);
</programlisting>

<para>The pattern argument indicates how the underlining should look. It
consists of a string of underscore and space characters. An underscore
indicates that the corresponding character in the label should be
underlined. For example, the string <literal>"_     _"</literal> would underline the
first two characters and eight and ninth characters.</para>

<note><para>If you simply want to have an underlined accelerator ("mnemonic") 
in your label, you should use gtkLabelNewWithMnemonic() or 
gtkLabelSetTextWithMnemonic(), not gtkLabelSetPattern().</para>
</note>

<para>Below is a short example to illustrate these functions. This example
makes use of the Frame widget to better demonstrate the label
styles. You can ignore this for now as the <link linkend="sec-Frames">Frame</link> 
widget is explained later on.</para>

<para>In GTK+ 2.0, label texts can contain markup for font and other text attribute 
changes, and labels may be selectable (for copy-and-paste). These advanced features
won't be explained here.</para>

<para>
<inlinemediaobject>
<imageobject>
<imagedata fileref="images/label.png" format="png">
</imageobject>
</inlinemediaobject>
</para>

<programlisting role="R">
<!-- example-start label label.c -->

#include &lt;gtk/gtk.h&gt;

int main( int   argc,
          char#argv[] )
{
  static GtkWidget#window = NULL;
  GtkWidget#hbox;
  GtkWidget#vbox;
  GtkWidget#frame;
  GtkWidget#label;

  # Initialise GTK 
  gtkInit (&amp;argc, &amp;argv);

  window = gtkWindowNew (GTKWINDOWTOPLEVEL);
  gSignalConnect (GOBJECT (window), "destroy",
		    GCALLBACK (gtkMainQuit),
		    NULL);

  gtkWindowSetTitle (GTKWINDOW (window), "Label");
  vbox = gtkVboxNew (FALSE, 5);
  hbox = gtkHboxNew (FALSE, 5);
  gtkContainerAdd (GTKCONTAINER (window), hbox);
  gtkBoxPackStart (GTKBOX (hbox), vbox, FALSE, FALSE, 0);
  gtkContainerSetBorderWidth (GTKCONTAINER (window), 5);
  
  frame = gtkFrameNew ("Normal Label");
  label = gtkLabelNew ("This is a Normal label");
  gtkContainerAdd (GTKCONTAINER (frame), label);
  gtkBoxPackStart (GTKBOX (vbox), frame, FALSE, FALSE, 0);
  
  frame = gtkFrameNew ("Multi-line Label");
  label = gtkLabelNew ("This is a Multi-line label.\nSecond line\n" \
			 "Third line");
  gtkContainerAdd (GTKCONTAINER (frame), label);
  gtkBoxPackStart (GTKBOX (vbox), frame, FALSE, FALSE, 0);
  
  frame = gtkFrameNew ("Left Justified Label");
  label = gtkLabelNew ("This is a Left-Justified\n" \
			 "Multi-line label.\nThird      line");
  gtkLabelSetJustify (GTKLABEL (label), GTKJUSTIFYLEFT);
  gtkContainerAdd (GTKCONTAINER (frame), label);
  gtkBoxPackStart (GTKBOX (vbox), frame, FALSE, FALSE, 0);
  
  frame = gtkFrameNew ("Right Justified Label");
  label = gtkLabelNew ("This is a Right-Justified\nMulti-line label.\n" \
			 "Fourth line, (j/k)");
  gtkLabelSetJustify (GTKLABEL (label), GTKJUSTIFYRIGHT);
  gtkContainerAdd (GTKCONTAINER (frame), label);
  gtkBoxPackStart (GTKBOX (vbox), frame, FALSE, FALSE, 0);

  vbox = gtkVboxNew (FALSE, 5);
  gtkBoxPackStart (GTKBOX (hbox), vbox, FALSE, FALSE, 0);
  frame = gtkFrameNew ("Line wrapped label");
  label = gtkLabelNew ("This is an example of a line-wrapped label.  It " \
			 "should not be taking up the entire             " # big space to test spacing \
			 "width allocated to it, but automatically " \
			 "wraps the words to fit.  " \
			 "The time has come, for all good men, to come to " \
			 "the aid of their party.  " \
			 "The sixth sheik's six sheep's sick.\n" \
			 "     It supports multiple paragraphs correctly, " \
			 "and  correctly   adds "\
			 "many          extra  spaces. ");
  gtkLabelSetLineWrap (GTKLABEL (label), TRUE);
  gtkContainerAdd (GTKCONTAINER (frame), label);
  gtkBoxPackStart (GTKBOX (vbox), frame, FALSE, FALSE, 0);
  
  frame = gtkFrameNew ("Filled, wrapped label");
  label = gtkLabelNew ("This is an example of a line-wrapped, filled label.  " \
			 "It should be taking "\
			 "up the entire              width allocated to it.  " \
			 "Here is a sentence to prove "\
			 "my point.  Here is another sentence. "\
			 "Here comes the sun, do de do de do.\n"\
			 "    This is a new paragraph.\n"\
			 "    This is another newer, longer, better " \
			 "paragraph.  It is coming to an end, "\
			 "unfortunately.");
  gtkLabelSetJustify (GTKLABEL (label), GTKJUSTIFYFILL);
  gtkLabelSetLineWrap (GTKLABEL (label), TRUE);
  gtkContainerAdd (GTKCONTAINER (frame), label);
  gtkBoxPackStart (GTKBOX (vbox), frame, FALSE, FALSE, 0);
  
  frame = gtkFrameNew ("Underlined label");
  label = gtkLabelNew ("This label is underlined!\n"
			 "This one is underlined in quite a funky fashion");
  gtkLabelSetJustify (GTKLABEL (label), GTKJUSTIFYLEFT);
  gtkLabelSetPattern (GTKLABEL (label),
			 "____________  ____  ___     _ ___ _");
  gtkContainerAdd (GTKCONTAINER (frame), label);
  gtkBoxPackStart (GTKBOX (vbox), frame, FALSE, FALSE, 0);
  
  gtkWidgetShowAll (window);

  gtkMain ();
  
  return 0;
}
<!-- example-end -->
</programlisting>

</sect1>

<!-- ----------------------------------------------------------------- -->
<sect1 id="sec-Arrows">
<title>Arrows</title>

<para>The Arrow widget draws an arrowhead, facing in a number of possible
directions and having a number of possible styles. It can be very
useful when placed on a button in many applications. Like the Label
widget, it emits no signals.</para>

<para>There are only two functions for manipulating an Arrow widget:</para>

<programlisting role="R">
GtkWidget#gtkArrowNew( GtkArrowType   arrowType,
                          GtkShadowType  shadowType );

void gtkArrowSet( GtkArrow     #arrow,
                    GtkArrowType   arrowType,
                    GtkShadowType  shadowType );
</programlisting>

<para>The first creates a new arrow widget with the indicated type and
appearance. The second allows these values to be altered
retrospectively. The <literal>arrowType</literal> argument may take one of the
following values:</para>

<programlisting role="R">
  GTKARROWUP
  GTKARROWDOWN
  GTKARROWLEFT
  GTKARROWRIGHT
</programlisting>

<para>These values obviously indicate the direction in which the arrow will
point. The <literal>shadowType</literal> argument may take one of these values:</para>

<programlisting role="R">
  GTKSHADOWIN
  GTKSHADOWOUT (the default)
  GTKSHADOWETCHEDIN
  GTKSHADOWETCHEDOUT
</programlisting>

<para>Here's a brief example to illustrate their use.</para>

<para>
<inlinemediaobject>
<imageobject>
<imagedata fileref="images/arrow.png" format="png">
</imageobject>
</inlinemediaobject>
</para>

<programlisting role="R">
<!-- example-start arrow arrow.c -->

#include &lt;gtk/gtk.h&gt;

# Create an Arrow widget with the specified parameters
# and pack it into a button 
static GtkWidget#createArrowButton( GtkArrowType  arrowType,
                                       GtkShadowType shadowType )
{
  GtkWidget#button;
  GtkWidget#arrow;

  button = gtkButtonNew ();
  arrow = gtkArrowNew (arrowType, shadowType);

  gtkContainerAdd (GTKCONTAINER (button), arrow);
  
  gtkWidgetShow (button);
  gtkWidgetShow (arrow);

  return button;
}

int main( int   argc,
          char#argv[] )
{
  # GtkWidget is the storage type for widgets 
  GtkWidget#window;
  GtkWidget#button;
  GtkWidget#box;

  # Initialize the toolkit 
  gtkInit (&amp;argc, &amp;argv);

  # Create a new window 
  window = gtkWindowNew (GTKWINDOWTOPLEVEL);

  gtkWindowSetTitle (GTKWINDOW (window), "Arrow Buttons");

  # It's a good idea to do this for all windows. 
  gSignalConnect (GOBJECT (window), "destroy",
                    GCALLBACK (gtkMainQuit), NULL);

  # Sets the border width of the window. 
  gtkContainerSetBorderWidth (GTKCONTAINER (window), 10);

  # Create a box to hold the arrows/buttons 
  box = gtkHboxNew (FALSE, 0);
  gtkContainerSetBorderWidth (GTKCONTAINER (box), 2);
  gtkContainerAdd (GTKCONTAINER (window), box);

  # Pack and show all our widgets 
  gtkWidgetShow (box);

  button = createArrowButton (GTKARROWUP, GTKSHADOWIN);
  gtkBoxPackStart (GTKBOX (box), button, FALSE, FALSE, 3);

  button = createArrowButton (GTKARROWDOWN, GTKSHADOWOUT);
  gtkBoxPackStart (GTKBOX (box), button, FALSE, FALSE, 3);
  
  button = createArrowButton (GTKARROWLEFT, GTKSHADOWETCHEDIN);
  gtkBoxPackStart (GTKBOX (box), button, FALSE, FALSE, 3);
  
  button = createArrowButton (GTKARROWRIGHT, GTKSHADOWETCHEDOUT);
  gtkBoxPackStart (GTKBOX (box), button, FALSE, FALSE, 3);
  
  gtkWidgetShow (window);
  
  # Rest in gtkMain and wait for the fun to begin! 
  gtkMain ();
  
  return 0;
}
<!-- example-end -->
</programlisting>

</sect1>

<!-- ----------------------------------------------------------------- -->
<sect1 id="sec-TheTooltipsObject">
<title>The Tooltips Object</title>

<para>These are the little text strings that pop up when you leave your
pointer over a button or other widget for a few seconds. They are easy
to use, so I will just explain them without giving an example. If you
want to see some code, take a look at the <filename>testgtk.c</filename> program
distributed with GTK.</para>

<para>Widgets that do not receive events (widgets that do not have their
own window) will not work with tooltips.</para>

<para>The first call you will use creates a new tooltip. You only need to do
this once for a set of tooltips as the <literal>GtkTooltips</literal> object this
function returns can be used to create multiple tooltips.</para>

<programlisting role="R">
GtkTooltips#gtkTooltipsNew( void );
</programlisting>

<para>Once you have created a new tooltip, and the widget you wish to use it
on, simply use this call to set it:</para>

<programlisting role="R">
void gtkTooltipsSetTip( GtkTooltips#tooltips,
                           GtkWidget  #widget,
                           const gchar#tipText,
                           const gchar#tipPrivate );
</programlisting>

<para>The first argument is the tooltip you've already created, followed by
the widget you wish to have this tooltip pop up for, and the text you
wish it to say. The last argument is a text string that can be used as
an identifier when using GtkTipsQuery to implement context sensitive
help. For now, you can set it to NULL.</para>

<!-- TODO: sort out what how to do the context sensitive help -->

<para>Here's a short example:</para>

<programlisting role="R">
GtkTooltips#tooltips;
GtkWidget#button;
.
.
.
tooltips = gtkTooltipsNew ();
button = gtkButtonNewWithLabel ("button 1");
.
.
.
gtkTooltipsSetTip (tooltips, button, "This is button 1", NULL);
</programlisting>

<para>There are other calls that can be used with tooltips. I will just list
them with a brief description of what they do.</para>

<programlisting role="R">
void gtkTooltipsEnable( GtkTooltips#tooltips );
</programlisting>

<para>Enable a disabled set of tooltips.</para>

<programlisting role="R">
void gtkTooltipsDisable( GtkTooltips#tooltips );
</programlisting>

<para>Disable an enabled set of tooltips.</para>

<para>And that's all the functions associated with tooltips. More than
you'll ever want to know :-)</para>

</sect1>

<!-- ----------------------------------------------------------------- -->
<sect1 id="sec-ProgressBars">
<title>Progress Bars</title>

<para>Progress bars are used to show the status of an operation. They are
pretty easy to use, as you will see with the code below. But first
lets start out with the calls to create a new progress bar.</para>

<programlisting role="R">
GtkWidget#gtkProgressBarNew( void );
</programlisting>

<para>Now that the progress bar has been created we can use it.</para>

<programlisting role="R">
void gtkProgressBarSetFraction ( GtkProgressBar#pbar,
                                     gdouble        fraction );
</programlisting>

<para>The first argument is the progress bar you wish to operate on, and the
second argument is the amount "completed", meaning the amount the
progress bar has been filled from 0-100%. This is passed to the
function as a real number ranging from 0 to 1.</para>

<para>GTK v1.2 has added new functionality to the progress bar that enables
it to display its value in different ways, and to inform the user of
its current value and its range.</para>

<para>A progress bar may be set to one of a number of orientations using the
function</para>

<programlisting role="R">
void gtkProgressBarSetOrientation( GtkProgressBar#pbar,
                                       GtkProgressBarOrientation orientation );
</programlisting>

<para>The <literal>orientation</literal> argument may take one of the following
values to indicate the direction in which the progress bar moves:</para>

<programlisting role="R">
  GTKPROGRESSLEFTTORIGHT
  GTKPROGRESSRIGHTTOLEFT
  GTKPROGRESSBOTTOMTOTOP
  GTKPROGRESSTOPTOBOTTOM
</programlisting>

<para>As well as indicating the amount of progress that has occured, the
progress bar may be set to just indicate that there is some activity. 
This can be useful in situations where progress cannot be measured against 
a value range. The following function indicates that some progress has been 
made.</para>

<programlisting role="R">
void gtkProgressBarPulse ( GtkProgressBar#progress );
</programlisting>

<para>The step size of the activity indicator is set using the following 
function.</para>

<programlisting role="R">
void gtkProgressBarSetPulseStep( GtkProgressBar#pbar,
                                      gdouble         fraction );
</programlisting>

<para>When not in activity mode, the progress bar can also display a
configurable text string within its trough, using the following
function.</para>

<programlisting role="R">
void gtkProgressBarSetText( GtkProgressBar#progress,
                                const gchar   #text );
</programlisting>

<note><para>Note that gtkProgressSetText() doesn't support the printf()-like formatting
of the GTK+ 1.2 Progressbar.</para></note>

<para>You can turn off the display of the string by calling gtkProgessBarSetText()
again with NULL as second argument.</para>

<para>The current text setting of a progressbar can be retrieved with the 
following function. Do not free the returned string.</para>

<programlisting role="R">
const gchar#gtkProgressBarGetText( GtkProgressBar#pbar );
</programlisting>

<para>Progress Bars are usually used with timeouts or other such functions
(see section on <link linkend="ch-Timeouts">Timeouts, I/O and Idle Functions</link>) 
to give the illusion of multitasking. All will employ the
gtkProgressBarSetFraction() or gtkProgressBarPulse() functions in the 
same manner.</para>

<para>Here is an example of the progress bar, updated using timeouts. This
code also shows you how to reset the Progress Bar.</para>

<para>
<inlinemediaobject>
<imageobject>
<imagedata fileref="images/progressbar.png" format="png">
</imageobject>
</inlinemediaobject>
</para>

<programlisting role="R">
<!-- example-start progressbar progressbar.c -->

#include &lt;gtk/gtk.h&gt;

typedef struct ProgressData {
  GtkWidget#window;
  GtkWidget#pbar;
  int timer;
  gboolean activityMode;
} ProgressData;

# Update the value of the progress bar so that we get
# some movement 
static gboolean progressTimeout( gpointer data )
{
  ProgressData#pdata = (ProgressData#)data;
  gdouble newVal;
  
  if (pdata-&gt;activityMode) 
    gtkProgressBarPulse (GTKPROGRESSBAR (pdata-&gt;pbar));
  else 
    {
      # Calculate the value of the progress bar using the
      # value range set in the adjustment object 
      
      newVal = gtkProgressBarGetFraction (GTKPROGRESSBAR (pdata-&gt;pbar)) + 0.01;
      
      if (newVal &gt; 1.0)
	newVal = 0.0;
      
      # Set the new value 
      gtkProgressBarSetFraction (GTKPROGRESSBAR (pdata-&gt;pbar), newVal);
    }
  
  # As this is a timeout function, return TRUE so that it
  # continues to get called 
  return TRUE;
} 

# Callback that toggles the text display within the progress bar trough 
static void toggleShowText( GtkWidget   #widget,
                              ProgressData#pdata )
{
  const gchar#text;
  
  text = gtkProgressBarGetText (GTKPROGRESSBAR (pdata-&gt;pbar));
  if (text &amp;&amp;#text)
    gtkProgressBarSetText (GTKPROGRESSBAR (pdata-&gt;pbar), "");
  else 
    gtkProgressBarSetText (GTKPROGRESSBAR (pdata-&gt;pbar), "some text");
}

# Callback that toggles the activity mode of the progress bar 
static void toggleActivityMode( GtkWidget   #widget,
                                  ProgressData#pdata )
{
  pdata-&gt;activityMode = !pdata-&gt;activityMode;
  if (pdata-&gt;activityMode) 
      gtkProgressBarPulse (GTKPROGRESSBAR (pdata-&gt;pbar));
  else
      gtkProgressBarSetFraction (GTKPROGRESSBAR (pdata-&gt;pbar), 0.0);
}

 
# Callback that toggles the orientation of the progress bar 
static void toggleOrientation( GtkWidget   #widget,
                                ProgressData#pdata )
{
  switch (gtkProgressBarGetOrientation (GTKPROGRESSBAR (pdata-&gt;pbar))) {
  case GTKPROGRESSLEFTTORIGHT:
    gtkProgressBarSetOrientation (GTKPROGRESSBAR (pdata-&gt;pbar), 
				      GTKPROGRESSRIGHTTOLEFT);
    break;
  case GTKPROGRESSRIGHTTOLEFT:
    gtkProgressBarSetOrientation (GTKPROGRESSBAR (pdata-&gt;pbar), 
				      GTKPROGRESSLEFTTORIGHT);
    break;
  default:;
    # do nothing 
  }
}

 
# Clean up allocated memory and remove the timer 
static void destroyProgress( GtkWidget   #widget,
                              ProgressData#pdata)
{
    gSourceRemove (pdata-&gt;timer);
    pdata-&gt;timer = 0;
    pdata-&gt;window = NULL;
    gFree (pdata);
    gtkMainQuit ();
}

int main( int   argc,
          char#argv[])
{
    ProgressData#pdata;
    GtkWidget#align;
    GtkWidget#separator;
    GtkWidget#table;
    GtkWidget#button;
    GtkWidget#check;
    GtkWidget#vbox;

    gtkInit (&amp;argc, &amp;argv);

    # Allocate memory for the data that is passed to the callbacks 
    pdata = gMalloc (sizeof (ProgressData));
  
    pdata-&gt;window = gtkWindowNew (GTKWINDOWTOPLEVEL);
    gtkWindowSetResizable (GTKWINDOW (pdata-&gt;window), TRUE);

    gSignalConnect (GOBJECT (pdata-&gt;window), "destroy",
	              GCALLBACK (destroyProgress),
                      (gpointer) pdata);
    gtkWindowSetTitle (GTKWINDOW (pdata-&gt;window), "GtkProgressBar");
    gtkContainerSetBorderWidth (GTKCONTAINER (pdata-&gt;window), 0);

    vbox = gtkVboxNew (FALSE, 5);
    gtkContainerSetBorderWidth (GTKCONTAINER (vbox), 10);
    gtkContainerAdd (GTKCONTAINER (pdata-&gt;window), vbox);
    gtkWidgetShow (vbox);
  
    # Create a centering alignment object 
    align = gtkAlignmentNew (0.5, 0.5, 0, 0);
    gtkBoxPackStart (GTKBOX (vbox), align, FALSE, FALSE, 5);
    gtkWidgetShow (align);

    # Create the GtkProgressBar 
    pdata-&gt;pbar = gtkProgressBarNew ();
    pdata-&gt;activityMode = FALSE;

    gtkContainerAdd (GTKCONTAINER (align), pdata-&gt;pbar);
    gtkWidgetShow (pdata-&gt;pbar);

    # Add a timer callback to update the value of the progress bar 
    pdata-&gt;timer = gTimeoutAdd (100, progressTimeout, pdata);

    separator = gtkHseparatorNew ();
    gtkBoxPackStart (GTKBOX (vbox), separator, FALSE, FALSE, 0);
    gtkWidgetShow (separator);

    # rows, columns, homogeneous 
    table = gtkTableNew (2, 3, FALSE);
    gtkBoxPackStart (GTKBOX (vbox), table, FALSE, TRUE, 0);
    gtkWidgetShow (table);

    # Add a check button to select displaying of the trough text 
    check = gtkCheckButtonNewWithLabel ("Show text");
    gtkTableAttach (GTKTABLE (table), check, 0, 1, 0, 1,
                      GTKEXPAND | GTKFILL, GTKEXPAND | GTKFILL,
		      5, 5);
    gSignalConnect (GOBJECT (check), "clicked",
                      GCALLBACK (toggleShowText),
                      (gpointer) pdata);
    gtkWidgetShow (check);

    # Add a check button to toggle activity mode 
    check = gtkCheckButtonNewWithLabel ("Activity mode");
    gtkTableAttach (GTKTABLE (table), check, 0, 1, 1, 2,
                      GTKEXPAND | GTKFILL, GTKEXPAND | GTKFILL,
                      5, 5);
    gSignalConnect (GOBJECT (check), "clicked",
                      GCALLBACK (toggleActivityMode),
                      (gpointer) pdata);
    gtkWidgetShow (check);

    # Add a check button to toggle orientation 
    check = gtkCheckButtonNewWithLabel ("Right to Left");
    gtkTableAttach (GTKTABLE (table), check, 0, 1, 2, 3,
                      GTKEXPAND | GTKFILL, GTKEXPAND | GTKFILL,
                      5, 5);
    gSignalConnect (GOBJECT (check), "clicked",
                      GCALLBACK (toggleOrientation),
                      (gpointer) pdata);
    gtkWidgetShow (check);

    # Add a button to exit the program 
    button = gtkButtonNewWithLabel ("close");
    gSignalConnectSwapped (GOBJECT (button), "clicked",
                              GCALLBACK (gtkWidgetDestroy),
                              GOBJECT (pdata-&gt;window));
    gtkBoxPackStart (GTKBOX (vbox), button, FALSE, FALSE, 0);

    # This makes it so the button is the default. 
    GTKWIDGETSETFLAGS (button, GTKCANDEFAULT);

    # This grabs this button to be the default button. Simply hitting
    # the "Enter" key will cause this button to activate. 
    gtkWidgetGrabDefault (button);
    gtkWidgetShow (button);

    gtkWidgetShow (pdata-&gt;window);

    gtkMain ();
    
    return 0;
}
<!-- example-end -->
</programlisting>

</sect1>

<!-- ----------------------------------------------------------------- -->
<sect1 id="sec-Dialogs">
<title>Dialogs</title>

<para>The Dialog widget is very simple, and is actually just a window with a
few things pre-packed into it for you. The structure for a Dialog is:</para>

<programlisting role="R">
struct GtkDialog
{
      GtkWindow window;
    
      GtkWidget#vbox;
      GtkWidget#actionArea;
};
</programlisting>

<para>So you see, it simply creates a window, and then packs a vbox into the
top, which contains a separator and then an hbox called the
"actionArea".</para>

<para>The Dialog widget can be used for pop-up messages to the user, and
other similar tasks. There are two functions to create a new Dialog.</para>

<programlisting role="R">
GtkWidget#gtkDialogNew( void );

GtkWidget#gtkDialogNewWithButtons( const gchar   #title,
                                        GtkWindow     #parent,
                                        GtkDialogFlags  flags, 
                                        const gchar   #firstButtonText,
                                        ... );
</programlisting>

<para>The first function will create an empty dialog, and it is now up to you to use
 it. You could pack a button in the actionArea by doing something like this:</para>

<programlisting role="R">
    button = ...
    gtkBoxPackStart (GTKBOX (GTKDIALOG (window)->actionArea),
                        button, TRUE, TRUE, 0);
    gtkWidgetShow (button);
</programlisting>

<para>And you could add to the vbox area by packing, for instance, a label 
in it, try something like this:</para>

<programlisting role="R">
    label = gtkLabelNew ("Dialogs are groovy");
    gtkBoxPackStart (GTKBOX (GTKDIALOG (window)->vbox),
                        label, TRUE, TRUE, 0);
    gtkWidgetShow (label);
</programlisting>

<para>As an example in using the dialog box, you could put two buttons in
the actionArea, a Cancel button and an Ok button, and a label in the
vbox area, asking the user a question or giving an error etc. Then
you could attach a different signal to each of the buttons and perform
the operation the user selects.</para>

<para>If the simple functionality provided by the default vertical and
horizontal boxes in the two areas doesn't give you enough control for
your application, then you can simply pack another layout widget into
the boxes provided. For example, you could pack a table into the
vertical box.</para>

<para>The more complicated NewWithButtons() variant allows to set one or
more of the following flags.</para>

<variablelist>
<varlistentry>
<term><literal>GTKDIALOGMODAL</literal></term>
<listitem><para>make the dialog modal.
</para></listitem>
</varlistentry>
<varlistentry>
<term><literal>GTKDIALOGDESTROYWITHPARENT</literal></term>
<listitem><para>ensures that the dialog window is destroyed together with the specified
parent.</para></listitem>
</varlistentry>
<varlistentry>
<term><literal>GTKDIALOGNOSEPARATOR</literal></term>
<listitem><para>omits the separator between the vbox and the actionArea.
</para></listitem>
</varlistentry>
</variablelist>
</sect1>

<!-- ----------------------------------------------------------------- -->
<sect1 id="sec-Rulers">
<title>Rulers</title>

<para>Ruler widgets are used to indicate the location of the mouse pointer
in a given window. A window can have a vertical ruler spanning across
the height and a horizontal ruler spanning down the width. A small
triangular indicator on the ruler shows the exact location of the
pointer relative to the ruler.</para>

<para>A ruler must first be created. Horizontal and vertical rulers are
created using</para>

<programlisting role="R">
GtkWidget#gtkHrulerNew( void );    # horizontal ruler 

GtkWidget#gtkVrulerNew( void );    # vertical ruler   
</programlisting>

<para>Once a ruler is created, we can define the unit of measurement. Units
of measure for rulers can be<literal>GTKPIXELS</literal>, <literal>GTKINCHES</literal> or
<literal>GTKCENTIMETERS</literal>. This is set using</para>

<programlisting role="R">
void gtkRulerSetMetric( GtkRuler     #ruler,
                           GtkMetricType  metric );
</programlisting>

<para>The default measure is <literal>GTKPIXELS</literal>.</para>

<programlisting role="R">
    gtkRulerSetMetric( GTKRULER(ruler), GTKPIXELS );
</programlisting>

<para>Other important characteristics of a ruler are how to mark the units
of scale and where the position indicator is initially placed. These
are set for a ruler using</para>

<programlisting role="R">
void gtkRulerSetRange( GtkRuler#ruler,
                          gdouble   lower,
                          gdouble   upper,
                          gdouble   position,
                          gdouble   maxSize );
</programlisting>

<para>The lower and upper arguments define the extent of the ruler, and
maxSize is the largest possible number that will be displayed.
Position defines the initial position of the pointer indicator within
the ruler.</para>

<para>A vertical ruler can span an 800 pixel wide window thus</para>

<programlisting role="R">
    gtkRulerSetRange( GTKRULER(vruler), 0, 800, 0, 800);
</programlisting>

<para>The markings displayed on the ruler will be from 0 to 800, with a
number for every 100 pixels. If instead we wanted the ruler to range
from 7 to 16, we would code</para>

<programlisting role="R">
    gtkRulerSetRange( GTKRULER(vruler), 7, 16, 0, 20);
</programlisting>

<para>The indicator on the ruler is a small triangular mark that indicates
the position of the pointer relative to the ruler. If the ruler is
used to follow the mouse pointer, the motionNotifyEvent signal
should be connected to the motionNotifyEvent method of the ruler.
To follow all mouse movements within a window area, we would use</para>

<programlisting role="R">
#define EVENTMETHOD(i, x) GTKWIDGETGETCLASS(i)->x

    gSignalConnectSwapped (GOBJECT (area), "motionNotifyEvent",
           GCALLBACK (EVENTMETHOD (ruler, motionNotifyEvent)),
           GOBJECT (ruler));
</programlisting>

<para>The following example creates a drawing area with a horizontal ruler
above it and a vertical ruler to the left of it. The size of the
drawing area is 600 pixels wide by 400 pixels high. The horizontal
ruler spans from 7 to 13 with a mark every 100 pixels, while the
vertical ruler spans from 0 to 400 with a mark every 100 pixels.
Placement of the drawing area and the rulers is done using a table.</para>

<para>
<inlinemediaobject>
<imageobject>
<imagedata fileref="images/rulers.png" format="png">
</imageobject>
</inlinemediaobject>
</para>

<programlisting role="R">
<!-- example-start rulers rulers.c -->

#include &lt;gtk/gtk.h&gt;

#define EVENTMETHOD(i, x) GTKWIDGETGETCLASS(i)-&gt;x

#define XSIZE  600
#define YSIZE  400

# This routine gets control when the close button is clicked 
static gboolean closeApplication( GtkWidget#widget,
                                   GdkEvent #event,
                                   gpointer   data )
{
    gtkMainQuit ();
    return FALSE;
}

# The main routine 
int main( int   argc,
          char#argv[] ) {
    GtkWidget#window,#table,#area,#hrule,#vrule;

    # Initialize GTK and create the main window 
    gtkInit (&amp;argc, &amp;argv);

    window = gtkWindowNew (GTKWINDOWTOPLEVEL);
    gSignalConnect (GOBJECT (window), "deleteEvent",
                      GCALLBACK (closeApplication), NULL);
    gtkContainerSetBorderWidth (GTKCONTAINER (window), 10);

    # Create a table for placing the ruler and the drawing area 
    table = gtkTableNew (3, 2, FALSE);
    gtkContainerAdd (GTKCONTAINER (window), table);

    area = gtkDrawingAreaNew ();
    gtkWidgetSetSizeRequest (GTKWIDGET (area), XSIZE, YSIZE);
    gtkTableAttach (GTKTABLE (table), area, 1, 2, 1, 2,
                      GTKEXPAND|GTKFILL, GTKFILL, 0, 0);
    gtkWidgetSetEvents (area, GDKPOINTERMOTIONMASK |
                                 GDKPOINTERMOTIONHINTMASK);

    # The horizontal ruler goes on top. As the mouse moves across the
    # drawing area, a motionNotifyEvent is passed to the
    # appropriate event handler for the ruler. 
    hrule = gtkHrulerNew ();
    gtkRulerSetMetric (GTKRULER (hrule), GTKPIXELS);
    gtkRulerSetRange (GTKRULER (hrule), 7, 13, 0, 20);
    gSignalConnectSwapped (GOBJECT (area), "motionNotifyEvent",
                              GCALLBACK (EVENTMETHOD (hrule, motionNotifyEvent)),
                              GOBJECT (hrule));
    gtkTableAttach (GTKTABLE (table), hrule, 1, 2, 0, 1,
                      GTKEXPAND|GTKSHRINK|GTKFILL, GTKFILL, 0, 0);
    
    # The vertical ruler goes on the left. As the mouse moves across
    # the drawing area, a motionNotifyEvent is passed to the
    # appropriate event handler for the ruler. 
    vrule = gtkVrulerNew ();
    gtkRulerSetMetric (GTKRULER (vrule), GTKPIXELS);
    gtkRulerSetRange (GTKRULER (vrule), 0, YSIZE, 10, YSIZE );
    gSignalConnectSwapped (GOBJECT (area), "motionNotifyEvent",
                              GCALLBACK (EVENTMETHOD (vrule, motionNotifyEvent)),
                              GOBJECT (vrule));
    gtkTableAttach (GTKTABLE (table), vrule, 0, 1, 1, 2,
                      GTKFILL, GTKEXPAND|GTKSHRINK|GTKFILL, 0, 0);

    # Now show everything 
    gtkWidgetShow (area);
    gtkWidgetShow (hrule);
    gtkWidgetShow (vrule);
    gtkWidgetShow (table);
    gtkWidgetShow (window);
    gtkMain ();

    return 0;
}
<!-- example-end -->
</programlisting>

</sect1>

<!-- ----------------------------------------------------------------- -->
<sect1 id="sec-Statusbars">
<title>Statusbars</title>

<para>Statusbars are simple widgets used to display a text message. They
keep a stack of the messages pushed onto them, so that popping the
current message will re-display the previous text message.</para>

<para>In order to allow different parts of an application to use the same
statusbar to display messages, the statusbar widget issues Context
Identifiers which are used to identify different "users". The message
on top of the stack is the one displayed, no matter what context it is
in. Messages are stacked in last-in-first-out order, not context
identifier order.</para>

<para>A statusbar is created with a call to:</para>

<programlisting role="R">
GtkWidget#gtkStatusbarNew( void );
</programlisting>

<para>A new Context Identifier is requested using a call to the following 
function with a short textual description of the context:</para>

<programlisting role="R">
guint gtkStatusbarGetContextId( GtkStatusbar#statusbar,
                                    const gchar #contextDescription );
</programlisting>

<para>There are three functions that can operate on statusbars:</para>

<programlisting role="R">
guint gtkStatusbarPush( GtkStatusbar#statusbar,
                          guint         contextId,
                          const gchar #text );

void gtkStatusbarPop( GtkStatusbar#statusbar)
                        guint         contextId );

void gtkStatusbarRemove( GtkStatusbar#statusbar,
                           guint         contextId,
                           guint         messageId ); 
</programlisting>

<para>The first, gtkStatusbarPush(), is used to add a new message to the
statusbar.  It returns a Message Identifier, which can be passed later
to the function gtkStatusbarRemove to remove the message with the
given Message and Context Identifiers from the statusbar's stack.</para>

<para>The function gtkStatusbarPop() removes the message highest in the
stack with the given Context Identifier.</para>

<para>In addition to messages, statusbars may also display a resize grip, which 
can be dragged with the mouse to resize the toplevel window containing the statusbar,
similar to dragging the window frame. The following functions control the display
of the resize grip.</para>

<programlisting role="R">
void     gtkStatusbarSetHasResizeGrip( GtkStatusbar#statusbar,
					    gboolean      setting );

gboolean gtkStatusbarGetHasResizeGrip( GtkStatusbar#statusbar );
</programlisting>

<para>The following example creates a statusbar and two buttons, one for
pushing items onto the statusbar, and one for popping the last item
back off.</para>

<para>
<inlinemediaobject>
<imageobject>
<imagedata fileref="images/statusbar.png" format="png">
</imageobject>
</inlinemediaobject>
</para>

<programlisting role="R">
<!-- example-start statusbar statusbar.c -->

#include &lt;stdlib.h&gt;
#include &lt;gtk/gtk.h&gt;
#include &lt;glib.h&gt;

GtkWidget#statusBar;

static void pushItem( GtkWidget#widget,
                       gpointer   data )
{
  static int count = 1;
  gchar#buff;

  buff = gStrdupPrintf ("Item %d", count++);
  gtkStatusbarPush (GTKSTATUSBAR (statusBar), GPOINTERTOINT (data), buff);
  gFree (buff);
}

static void popItem( GtkWidget#widget,
                      gpointer   data )
{
  gtkStatusbarPop (GTKSTATUSBAR (statusBar), GPOINTERTOINT (data));
}

int main( int   argc,
          char#argv[] )
{

    GtkWidget#window;
    GtkWidget#vbox;
    GtkWidget#button;

    gint contextId;

    gtkInit (&amp;argc, &amp;argv);

    # create a new window 
    window = gtkWindowNew (GTKWINDOWTOPLEVEL);
    gtkWidgetSetSizeRequest (GTKWIDGET (window), 200, 100);
    gtkWindowSetTitle (GTKWINDOW (window), "GTK Statusbar Example");
    gSignalConnect (GOBJECT (window), "deleteEvent",
                      GCALLBACK (exit), NULL);
 
    vbox = gtkVboxNew (FALSE, 1);
    gtkContainerAdd (GTKCONTAINER (window), vbox);
    gtkWidgetShow (vbox);
          
    statusBar = gtkStatusbarNew ();      
    gtkBoxPackStart (GTKBOX (vbox), statusBar, TRUE, TRUE, 0);
    gtkWidgetShow (statusBar);

    contextId = gtkStatusbarGetContextId(
                          GTKSTATUSBAR (statusBar), "Statusbar example");

    button = gtkButtonNewWithLabel ("push item");
    gSignalConnect (GOBJECT (button), "clicked",
                      GCALLBACK (pushItem), GINTTOPOINTER (contextId));
    gtkBoxPackStart (GTKBOX (vbox), button, TRUE, TRUE, 2);
    gtkWidgetShow (button);              

    button = gtkButtonNewWithLabel ("pop last item");
    gSignalConnect (GOBJECT (button), "clicked",
                      GCALLBACK (popItem), GINTTOPOINTER (contextId));
    gtkBoxPackStart (GTKBOX (vbox), button, TRUE, TRUE, 2);
    gtkWidgetShow (button);

    # always display the window as the last step so it all splashes on
    # the screen at once. 
    gtkWidgetShow (window);

    gtkMain ();

    return 0;
}
<!-- example-end -->
</programlisting>

</sect1>

<!-- ----------------------------------------------------------------- -->
<sect1 id="sec-TextEntries">
<title>Text Entries</title>

<para>The Entry widget allows text to be typed and displayed in a single line
text box. The text may be set with function calls that allow new text
to replace, prepend or append the current contents of the Entry widget.</para>

<para>Create a new Entry widget with the following function.</para>

<programlisting role="R">
GtkWidget#gtkEntryNew( void );
</programlisting>

<para>The next function alters the text which is currently
within the Entry widget.</para>

<programlisting role="R">
void gtkEntrySetText( GtkEntry   #entry,
                         const gchar#text );
</programlisting>

<para>The function gtkEntrySetText() sets the contents of the Entry widget,
replacing the current contents. Note that the class Entry implements the Editable
interface (yes, gobject supports Java-like interfaces) which contains some more
functions for manipulating the contents.
 </para>

<para>The contents of the Entry can be retrieved by using a call to the
following function. This is useful in the callback functions described below.</para>

<programlisting role="R">
const gchar#gtkEntryGetText( GtkEntry#entry );
</programlisting>

<para>The value returned by this function is used internally, and must not
be freed using either free() or gFree().</para>

<para>If we don't want the contents of the Entry to be changed by someone typing
into it, we can change its editable state.</para>

<programlisting role="R">
void gtkEditableSetEditable( GtkEditable#entry,
                                gboolean     editable );
</programlisting>

<para>The function above allows us to toggle the editable state of the
Entry widget by passing in a TRUE or FALSE value for the <literal>editable</literal>
argument.</para>

<para>If we are using the Entry where we don't want the text entered to be
visible, for example when a password is being entered, we can use the
following function, which also takes a boolean flag.</para>

<programlisting role="R">
void gtkEntrySetVisibility( GtkEntry#entry,
                               gboolean  visible );
</programlisting>

<para>A region of the text may be set as selected by using the following
function. This would most often be used after setting some default
text in an Entry, making it easy for the user to remove it.</para>

<programlisting role="R">
void gtkEditableSelectRegion( GtkEditable#entry,
                                 gint         start,
                                 gint         end );
</programlisting>

<para>If we want to catch when the user has entered text, we can connect to
the <literal>activate</literal> or <literal>changed</literal> signal. Activate is raised when the
user hits the enter key within the Entry widget. Changed is raised
when the text changes at all, e.g., for every character entered or
removed.</para>

<para>The following code is an example of using an Entry widget.</para>

<para>
<inlinemediaobject>
<imageobject>
<imagedata fileref="images/entry.png" format="png">
</imageobject>
</inlinemediaobject>
</para>

<programlisting role="R">
<!-- example-start entry entry.c -->

#include &lt;stdio.h&gt;
#include &lt;stdlib.h&gt;
#include &lt;gtk/gtk.h&gt;

static void enterCallback( GtkWidget#widget,
                            GtkWidget#entry )
{
  const gchar#entryText;
  entryText = gtkEntryGetText (GTKENTRY (entry));
  printf ("Entry contents: %s\n", entryText);
}

static void entryToggleEditable( GtkWidget#checkbutton,
                                   GtkWidget#entry )
{
  gtkEditableSetEditable (GTKEDITABLE (entry),
                             GTKTOGGLEBUTTON (checkbutton)-&gt;active);
}

static void entryToggleVisibility( GtkWidget#checkbutton,
                                     GtkWidget#entry )
{
  gtkEntrySetVisibility (GTKENTRY (entry),
			    GTKTOGGLEBUTTON (checkbutton)-&gt;active);
}

int main( int   argc,
          char#argv[] )
{

    GtkWidget#window;
    GtkWidget#vbox,#hbox;
    GtkWidget#entry;
    GtkWidget#button;
    GtkWidget#check;
    gint tmpPos;

    gtkInit (&amp;argc, &amp;argv);

    # create a new window 
    window = gtkWindowNew (GTKWINDOWTOPLEVEL);
    gtkWidgetSetSizeRequest (GTKWIDGET (window), 200, 100);
    gtkWindowSetTitle (GTKWINDOW (window), "GTK Entry");
    gSignalConnect (GOBJECT (window), "destroy",
                      GCALLBACK (gtkMainQuit), NULL);
    gSignalConnectSwapped (GOBJECT (window), "deleteEvent",
                              GCALLBACK (gtkWidgetDestroy), 
                              GOBJECT (window));

    vbox = gtkVboxNew (FALSE, 0);
    gtkContainerAdd (GTKCONTAINER (window), vbox);
    gtkWidgetShow (vbox);

    entry = gtkEntryNew ();
    gtkEntrySetMaxLength (GTKENTRY (entry), 50);
    gSignalConnect (GOBJECT (entry), "activate",
		      GCALLBACK (enterCallback),
		      (gpointer) entry);
    gtkEntrySetText (GTKENTRY (entry), "hello");
    tmpPos = GTKENTRY (entry)-&gt;textLength;
    gtkEditableInsertText (GTKEDITABLE (entry), " world", -1, &amp;tmpPos);
    gtkEditableSelectRegion (GTKEDITABLE (entry),
			        0, GTKENTRY (entry)-&gt;textLength);
    gtkBoxPackStart (GTKBOX (vbox), entry, TRUE, TRUE, 0);
    gtkWidgetShow (entry);

    hbox = gtkHboxNew (FALSE, 0);
    gtkContainerAdd (GTKCONTAINER (vbox), hbox);
    gtkWidgetShow (hbox);
                                  
    check = gtkCheckButtonNewWithLabel ("Editable");
    gtkBoxPackStart (GTKBOX (hbox), check, TRUE, TRUE, 0);
    gSignalConnect (GOBJECT (check), "toggled",
	              GCALLBACK (entryToggleEditable), (gpointer) entry);
    gtkToggleButtonSetActive (GTKTOGGLEBUTTON (check), TRUE);
    gtkWidgetShow (check);
    
    check = gtkCheckButtonNewWithLabel ("Visible");
    gtkBoxPackStart (GTKBOX (hbox), check, TRUE, TRUE, 0);
    gSignalConnect (GOBJECT (check), "toggled",
	              GCALLBACK (entryToggleVisibility), (gpointer) entry);
    gtkToggleButtonSetActive (GTKTOGGLEBUTTON (check), TRUE);
    gtkWidgetShow (check);
                                   
    button = gtkButtonNewFromStock (GTKSTOCKCLOSE);
    gSignalConnectSwapped (GOBJECT (button), "clicked",
			      GCALLBACK (gtkWidgetDestroy),
			      GOBJECT (window));
    gtkBoxPackStart (GTKBOX (vbox), button, TRUE, TRUE, 0);
    GTKWIDGETSETFLAGS (button, GTKCANDEFAULT);
    gtkWidgetGrabDefault (button);
    gtkWidgetShow (button);
    
    gtkWidgetShow (window);

    gtkMain();

    return 0;
}
<!-- example-end -->
</programlisting>

</sect1>

<!-- ----------------------------------------------------------------- -->
<sect1 id="sec-SpinButtons">
<title>Spin Buttons</title>

<para>The Spin Button widget is generally used to allow the user to select a
value from a range of numeric values. It consists of a text
entry box with up and down arrow buttons attached to the
side. Selecting one of the buttons causes the value to "spin" up and
down the range of possible values. The entry box may also be edited
directly to enter a specific value.</para>

<para>The Spin Button allows the value to have zero or a number of decimal
places and to be incremented/decremented in configurable steps. The
action of holding down one of the buttons optionally results in an
acceleration of change in the value according to how long it is
depressed.</para>

<para>The Spin Button uses an <link linkend="ch-Adjustments">Adjustment</link>
object to hold information about the range of values that the spin
button can take. This makes for a powerful Spin Button widget.</para>

<para>Recall that an adjustment widget is created with the following
function, which illustrates the information that it holds:</para>

<programlisting role="R">
GtkObject#gtkAdjustmentNew( gdouble value,
                               gdouble lower,
                               gdouble upper,
                               gdouble stepIncrement,
                               gdouble pageIncrement,
                               gdouble pageSize );
</programlisting>

<para>These attributes of an Adjustment are used by the Spin Button in the
following way:</para>

<itemizedlist>
<listitem><simpara> <literal>value</literal>: initial value for the Spin Button</simpara>
</listitem>
<listitem><simpara> <literal>lower</literal>: lower range value</simpara>
</listitem>
<listitem><simpara> <literal>upper</literal>: upper range value</simpara>
</listitem>
<listitem><simpara> <literal>stepIncrement</literal>: value to increment/decrement when pressing
mouse button 1 on a button</simpara>
</listitem>
<listitem><simpara> <literal>pageIncrement</literal>: value to increment/decrement when pressing
mouse button 2 on a button</simpara>
</listitem>
<listitem><simpara> <literal>pageSize</literal>: unused</simpara>
</listitem>
</itemizedlist>

<para>Additionally, mouse button 3 can be used to jump directly to the
<literal>upper</literal> or <literal>lower</literal> values when used to select one of the
buttons. Lets look at how to create a Spin Button:</para>

<programlisting role="R">
GtkWidget#gtkSpinButtonNew( GtkAdjustment#adjustment,
                                gdouble         climbRate,
                                guint          digits );
</programlisting>

<para>The <literal>climbRate</literal> argument take a value between 0.0 and 1.0 and
indicates the amount of acceleration that the Spin Button has. The
<literal>digits</literal> argument specifies the number of decimal places to which
the value will be displayed.</para>

<para>A Spin Button can be reconfigured after creation using the following
function:</para>

<programlisting role="R">
void gtkSpinButtonConfigure( GtkSpinButton#spinButton,
                                GtkAdjustment#adjustment,
                                gdouble        climbRate,
                                guint          digits );
</programlisting>

<para>The <literal>spinButton</literal> argument specifies the Spin Button widget that is
to be reconfigured. The other arguments are as specified above.</para>

<para>The adjustment can be set and retrieved independantly using the
following two functions:</para>

<programlisting role="R">
void gtkSpinButtonSetAdjustment( GtkSpinButton #spinButton,
                                     GtkAdjustment #adjustment );

GtkAdjustment#gtkSpinButtonGetAdjustment( GtkSpinButton#spinButton );
</programlisting>

<para>The number of decimal places can also be altered using:</para>

<programlisting role="R">
void gtkSpinButtonSetDigits( GtkSpinButton#spinButton,
                                 guint          digits) ;
</programlisting>

<para>The value that a Spin Button is currently displaying can be changed
using the following function:</para>

<programlisting role="R">
void gtkSpinButtonSetValue( GtkSpinButton#spinButton,
                                gdouble        value );
</programlisting>

<para>The current value of a Spin Button can be retrieved as either a
floating point or integer value with the following functions:</para>

<programlisting role="R">
gdouble gtkSpinButtonGetValue ( GtkSpinButton#spinButton );

gint gtkSpinButtonGetValueAsInt( GtkSpinButton#spinButton );
</programlisting>

<para>If you want to alter the value of a Spin Button relative to its current
value, then the following function can be used:</para>

<programlisting role="R">
void gtkSpinButtonSpin( GtkSpinButton#spinButton,
                           GtkSpinType    direction,
                           gdouble        increment );
</programlisting>

<para>The <literal>direction</literal> parameter can take one of the following values:</para>

<programlisting role="R">
  GTKSPINSTEPFORWARD
  GTKSPINSTEPBACKWARD
  GTKSPINPAGEFORWARD
  GTKSPINPAGEBACKWARD
  GTKSPINHOME
  GTKSPINEND
  GTKSPINUSERDEFINED
</programlisting>

<para>This function packs in quite a bit of functionality, which I will
attempt to clearly explain. Many of these settings use values from the
Adjustment object that is associated with a Spin Button.</para>

<para><literal>GTKSPINSTEPFORWARD</literal> and <literal>GTKSPINSTEPBACKWARD</literal> change the
value of the Spin Button by the amount specified by <literal>increment</literal>,
unless <literal>increment</literal> is equal to 0, in which case the value is
changed by the value of <literal>stepIncrement</literal> in theAdjustment.</para>

<para><literal>GTKSPINPAGEFORWARD</literal> and <literal>GTKSPINPAGEBACKWARD</literal> simply
alter the value of the Spin Button by <literal>increment</literal>.</para>

<para><literal>GTKSPINHOME</literal> sets the value of the Spin Button to the bottom of
the Adjustments range.</para>

<para><literal>GTKSPINEND</literal> sets the value of the Spin Button to the top of the
Adjustments range.</para>

<para><literal>GTKSPINUSERDEFINED</literal> simply alters the value of the Spin Button
by the specified amount.</para>

<para>We move away from functions for setting and retreving the range attributes
of the Spin Button now, and move onto functions that affect the
appearance and behaviour of the Spin Button widget itself.</para>

<para>The first of these functions is used to constrain the text box of the
Spin Button such that it may only contain a numeric value. This
prevents a user from typing anything other than numeric values into
the text box of a Spin Button:</para>

<programlisting role="R">
void gtkSpinButtonSetNumeric( GtkSpinButton#spinButton,
                                  gboolean       numeric );
</programlisting>

<para>You can set whether a Spin Button will wrap around between the upper
and lower range values with the following function:</para>

<programlisting role="R">
void gtkSpinButtonSetWrap( GtkSpinButton#spinButton,
                               gboolean       wrap );
</programlisting>

<para>You can set a Spin Button to round the value to the nearest
<literal>stepIncrement</literal>, which is set within the Adjustment object used
with the Spin Button. This is accomplished with the following
function:</para>

<programlisting role="R">
void gtkSpinButtonSetSnapToTicks( GtkSpinButton #spinButton,
                                        gboolean        snapToTicks );
</programlisting>

<para>The update policy of a Spin Button can be changed with the following
function:</para>

<programlisting role="R">
void gtkSpinButtonSetUpdatePolicy( GtkSpinButton #spinButton,
                                        GtkSpinButtonUpdatePolicy policy );
</programlisting>

<para>The possible values of <literal>policy</literal> are either <literal>GTKUPDATEALWAYS</literal> or
<literal>GTKUPDATEIFVALID</literal>.</para>

<para>These policies affect the behavior of a Spin Button when parsing
inserted text and syncing its value with the values of the
Adjustment.</para>

<para>In the case of <literal>GTKUPDATEIFVALID</literal> the Spin Button only value
gets changed if the text input is a numeric value that is within the
range specified by the Adjustment. Otherwise the text is reset to the
current value.</para>

<para>In case of <literal>GTKUPDATEALWAYS</literal> we ignore errors while converting
text into a numeric value.</para>

<para>Finally, you can explicitly request that a Spin Button update itself:</para>

<programlisting role="R">
void gtkSpinButtonUpdate( GtkSpinButton #spinButton );
</programlisting>

<para>It's example time again.</para>

<para>
<inlinemediaobject>
<imageobject>
<imagedata fileref="images/spinbutton.png" format="png">
</imageobject>
</inlinemediaobject>
</para>

<programlisting role="R">
<!-- example-start spinbutton spinbutton.c -->

#include &lt;stdio.h&gt;
#include &lt;gtk/gtk.h&gt;

static GtkWidget#spinner1;

static void toggleSnap( GtkWidget    #widget,
                         GtkSpinButton#spin )
{
  gtkSpinButtonSetSnapToTicks (spin, GTKTOGGLEBUTTON (widget)-&gt;active);
}

static void toggleNumeric( GtkWidget#widget,
                            GtkSpinButton#spin )
{
  gtkSpinButtonSetNumeric (spin, GTKTOGGLEBUTTON (widget)-&gt;active);
}

static void changeDigits( GtkWidget#widget,
                           GtkSpinButton#spin )
{
  gtkSpinButtonSetDigits (GTKSPINBUTTON (spinner1),
                              gtkSpinButtonGetValueAsInt (spin));
}

static void getValue( GtkWidget#widget,
                       gpointer data )
{
  gchar#buf;
  GtkLabel#label;
  GtkSpinButton#spin;

  spin = GTKSPINBUTTON (spinner1);
  label = GTKLABEL (gObjectGetData (GOBJECT (widget), "userData"));
  if (GPOINTERTOINT (data) == 1)
    buf = gStrdupPrintf ("%d", gtkSpinButtonGetValueAsInt (spin));
  else
    buf = gStrdupPrintf ("%0.*f", spin-&gt;digits,
                           gtkSpinButtonGetValue (spin));
  gtkLabelSetText (label, buf);
  gFree (buf);
}


int main( int   argc,
          char#argv[] )
{
  GtkWidget#window;
  GtkWidget#frame;
  GtkWidget#hbox;
  GtkWidget#mainVbox;
  GtkWidget#vbox;
  GtkWidget#vbox2;
  GtkWidget#spinner2;
  GtkWidget#spinner;
  GtkWidget#button;
  GtkWidget#label;
  GtkWidget#valLabel;
  GtkAdjustment#adj;

  # Initialise GTK 
  gtkInit (&amp;argc, &amp;argv);

  window = gtkWindowNew (GTKWINDOWTOPLEVEL);

  gSignalConnect (GOBJECT (window), "destroy",
		    GCALLBACK (gtkMainQuit),
		    NULL);

  gtkWindowSetTitle (GTKWINDOW (window), "Spin Button");

  mainVbox = gtkVboxNew (FALSE, 5);
  gtkContainerSetBorderWidth (GTKCONTAINER (mainVbox), 10);
  gtkContainerAdd (GTKCONTAINER (window), mainVbox);
  
  frame = gtkFrameNew ("Not accelerated");
  gtkBoxPackStart (GTKBOX (mainVbox), frame, TRUE, TRUE, 0);
  
  vbox = gtkVboxNew (FALSE, 0);
  gtkContainerSetBorderWidth (GTKCONTAINER (vbox), 5);
  gtkContainerAdd (GTKCONTAINER (frame), vbox);
  
  # Day, month, year spinners 
  
  hbox = gtkHboxNew (FALSE, 0);
  gtkBoxPackStart (GTKBOX (vbox), hbox, TRUE, TRUE, 5);
  
  vbox2 = gtkVboxNew (FALSE, 0);
  gtkBoxPackStart (GTKBOX (hbox), vbox2, TRUE, TRUE, 5);
  
  label = gtkLabelNew ("Day :");
  gtkMiscSetAlignment (GTKMISC (label), 0, 0.5);
  gtkBoxPackStart (GTKBOX (vbox2), label, FALSE, TRUE, 0);
  
  adj = (GtkAdjustment#) gtkAdjustmentNew (1.0, 1.0, 31.0, 1.0,
					      5.0, 0.0);
  spinner = gtkSpinButtonNew (adj, 0, 0);
  gtkSpinButtonSetWrap (GTKSPINBUTTON (spinner), TRUE);
  gtkBoxPackStart (GTKBOX (vbox2), spinner, FALSE, TRUE, 0);
  
  vbox2 = gtkVboxNew (FALSE, 0);
  gtkBoxPackStart (GTKBOX (hbox), vbox2, TRUE, TRUE, 5);
  
  label = gtkLabelNew ("Month :");
  gtkMiscSetAlignment (GTKMISC (label), 0, 0.5);
  gtkBoxPackStart (GTKBOX (vbox2), label, FALSE, TRUE, 0);
  
  adj = (GtkAdjustment#) gtkAdjustmentNew (1.0, 1.0, 12.0, 1.0,
					      5.0, 0.0);
  spinner = gtkSpinButtonNew (adj, 0, 0);
  gtkSpinButtonSetWrap (GTKSPINBUTTON (spinner), TRUE);
  gtkBoxPackStart (GTKBOX (vbox2), spinner, FALSE, TRUE, 0);
  
  vbox2 = gtkVboxNew (FALSE, 0);
  gtkBoxPackStart (GTKBOX (hbox), vbox2, TRUE, TRUE, 5);
  
  label = gtkLabelNew ("Year :");
  gtkMiscSetAlignment (GTKMISC (label), 0, 0.5);
  gtkBoxPackStart (GTKBOX (vbox2), label, FALSE, TRUE, 0);
  
  adj = (GtkAdjustment#) gtkAdjustmentNew (1998.0, 0.0, 2100.0,
					      1.0, 100.0, 0.0);
  spinner = gtkSpinButtonNew (adj, 0, 0);
  gtkSpinButtonSetWrap (GTKSPINBUTTON (spinner), FALSE);
  gtkWidgetSetSizeRequest (spinner, 55, -1);
  gtkBoxPackStart (GTKBOX (vbox2), spinner, FALSE, TRUE, 0);
  
  frame = gtkFrameNew ("Accelerated");
  gtkBoxPackStart (GTKBOX (mainVbox), frame, TRUE, TRUE, 0);
  
  vbox = gtkVboxNew (FALSE, 0);
  gtkContainerSetBorderWidth (GTKCONTAINER (vbox), 5);
  gtkContainerAdd (GTKCONTAINER (frame), vbox);
  
  hbox = gtkHboxNew (FALSE, 0);
  gtkBoxPackStart (GTKBOX (vbox), hbox, FALSE, TRUE, 5);
  
  vbox2 = gtkVboxNew (FALSE, 0);
  gtkBoxPackStart (GTKBOX (hbox), vbox2, TRUE, TRUE, 5);
  
  label = gtkLabelNew ("Value :");
  gtkMiscSetAlignment (GTKMISC (label), 0, 0.5);
  gtkBoxPackStart (GTKBOX (vbox2), label, FALSE, TRUE, 0);
  
  adj = (GtkAdjustment#) gtkAdjustmentNew (0.0, -10000.0, 10000.0,
					      0.5, 100.0, 0.0);
  spinner1 = gtkSpinButtonNew (adj, 1.0, 2);
  gtkSpinButtonSetWrap (GTKSPINBUTTON (spinner1), TRUE);
  gtkWidgetSetSizeRequest (spinner1, 100, -1);
  gtkBoxPackStart (GTKBOX (vbox2), spinner1, FALSE, TRUE, 0);
  
  vbox2 = gtkVboxNew (FALSE, 0);
  gtkBoxPackStart (GTKBOX (hbox), vbox2, TRUE, TRUE, 5);
  
  label = gtkLabelNew ("Digits :");
  gtkMiscSetAlignment (GTKMISC (label), 0, 0.5);
  gtkBoxPackStart (GTKBOX (vbox2), label, FALSE, TRUE, 0);
  
  adj = (GtkAdjustment#) gtkAdjustmentNew (2, 1, 5, 1, 1, 0);
  spinner2 = gtkSpinButtonNew (adj, 0.0, 0);
  gtkSpinButtonSetWrap (GTKSPINBUTTON (spinner2), TRUE);
  gSignalConnect (GOBJECT (adj), "valueChanged",
		    GCALLBACK (changeDigits),
		    (gpointer) spinner2);
  gtkBoxPackStart (GTKBOX (vbox2), spinner2, FALSE, TRUE, 0);
  
  hbox = gtkHboxNew (FALSE, 0);
  gtkBoxPackStart (GTKBOX (vbox), hbox, FALSE, TRUE, 5);
  
  button = gtkCheckButtonNewWithLabel ("Snap to 0.5-ticks");
  gSignalConnect (GOBJECT (button), "clicked",
		    GCALLBACK (toggleSnap),
		    (gpointer) spinner1);
  gtkBoxPackStart (GTKBOX (vbox), button, TRUE, TRUE, 0);
  gtkToggleButtonSetActive (GTKTOGGLEBUTTON (button), TRUE);
  
  button = gtkCheckButtonNewWithLabel ("Numeric only input mode");
  gSignalConnect (GOBJECT (button), "clicked",
		    GCALLBACK (toggleNumeric),
		    (gpointer) spinner1);
  gtkBoxPackStart (GTKBOX (vbox), button, TRUE, TRUE, 0);
  gtkToggleButtonSetActive (GTKTOGGLEBUTTON (button), TRUE);
  
  valLabel = gtkLabelNew ("");
  
  hbox = gtkHboxNew (FALSE, 0);
  gtkBoxPackStart (GTKBOX (vbox), hbox, FALSE, TRUE, 5);
  button = gtkButtonNewWithLabel ("Value as Int");
  gObjectSetData (GOBJECT (button), "userData", valLabel);
  gSignalConnect (GOBJECT (button), "clicked",
		    GCALLBACK (getValue),
		    GINTTOPOINTER (1));
  gtkBoxPackStart (GTKBOX (hbox), button, TRUE, TRUE, 5);
  
  button = gtkButtonNewWithLabel ("Value as Float");
  gObjectSetData (GOBJECT (button), "userData", valLabel);
  gSignalConnect (GOBJECT (button), "clicked",
		    GCALLBACK (getValue),
		    GINTTOPOINTER (2));
  gtkBoxPackStart (GTKBOX (hbox), button, TRUE, TRUE, 5);
  
  gtkBoxPackStart (GTKBOX (vbox), valLabel, TRUE, TRUE, 0);
  gtkLabelSetText (GTKLABEL (valLabel), "0");
  
  hbox = gtkHboxNew (FALSE, 0);
  gtkBoxPackStart (GTKBOX (mainVbox), hbox, FALSE, TRUE, 0);
  
  button = gtkButtonNewWithLabel ("Close");
  gSignalConnectSwapped (GOBJECT (button), "clicked",
                            GCALLBACK (gtkWidgetDestroy),
			    GOBJECT (window));
  gtkBoxPackStart (GTKBOX (hbox), button, TRUE, TRUE, 5);

  gtkWidgetShowAll (window);

  # Enter the event loop 
  gtkMain ();
    
  return 0;
}

<!-- example-end -->
</programlisting>

</sect1>

<!-- ----------------------------------------------------------------- -->
<sect1 id="sec-ComboBox">
<title>Combo Box</title>

<para>The combo box is another fairly simple widget that is really just a
collection of other widgets. From the user's point of view, the widget
consists of a text entry box and a pull down menu from which the user
can select one of a set of predefined entries. Alternatively, the user
can type a different option directly into the text box.</para>

<para>The following extract from the structure that defines a Combo Box
identifies several of the components:</para>

<programlisting role="R">
struct GtkCombo { 
        GtkHBox hbox; 
        GtkWidget#entry; 
        GtkWidget#button;
        GtkWidget#popup; 
        GtkWidget#popwin; 
        GtkWidget#list;
	...  };
</programlisting>

<para>As you can see, the Combo Box has two principal parts that you really
care about: an entry and a list.</para>

<para>First off, to create a combo box, use:</para>

<programlisting role="R">
GtkWidget#gtkComboNew( void );
</programlisting>

<para>Now, if you want to set the string in the entry section of the combo
box, this is done by manipulating the <literal>entry</literal> widget directly:</para>

<programlisting role="R">
    gtkEntrySetText (GTKENTRY (GTKCOMBO (combo)->entry), "My String.");
</programlisting>

<para>To set the values in the popdown list, one uses the function:</para>

<programlisting role="R">
void gtkComboSetPopdownStrings( GtkCombo#combo,
                                    GList   #strings );
</programlisting>

<para>Before you can do this, you have to assemble a GList of the strings
that you want. GList is a linked list implementation that is part of
<link linkend="ch-GLib">GLib</link>, a library supporting GTK. For the
moment, the quick and dirty explanation is that you need to set up a
GList pointer, set it equal to NULL, then append strings to it with</para>

<programlisting role="R">
GList#gListAppend( GList#glist, 
                      gpointer data );
</programlisting>

<para>It is important that you set the initial GList pointer to NULL. The
value returned from the gListAppend() function must be used as the new
pointer to the GList.</para>

<para>Here's a typical code segment for creating a set of options:</para>

<programlisting role="R">
    GList#glist = NULL;

    glist = gListAppend (glist, "String 1");
    glist = gListAppend (glist, "String 2");
    glist = gListAppend (glist, "String 3"); 
    glist = gListAppend (glist, "String 4");

    gtkComboSetPopdownStrings (GTKCOMBO (combo), glist);
    
    # can free glist now, combo takes a copy 
</programlisting>

<para>The combo widget makes a copy of the strings passed to it in the glist
structure. As a result, you need to make sure you free the memory used
by the list if that is appropriate for your application.</para>

<para>At this point you have a working combo box that has been set up.
There are a few aspects of its behavior that you can change. These
are accomplished with the functions: </para>

<programlisting role="R">
void gtkComboSetUseArrows( GtkCombo#combo,
                               gboolean  val );

void gtkComboSetUseArrowsAlways( GtkCombo#combo,
                                      gboolean  val );

void gtkComboSetCaseSensitive( GtkCombo#combo,
                                   gboolean  val );
</programlisting>

<para>gtkComboSetUseArrows() lets the user change the value in the
entry using the up/down arrow keys. This doesn't bring up the list, but
rather replaces the current text in the entry with the next list entry
(up or down, as your key choice indicates). It does this by searching
in the list for the item corresponding to the current value in the
entry and selecting the previous/next item accordingly. Usually in an
entry the arrow keys are used to change focus (you can do that anyway
using TAB). Note that when the current item is the last of the list
and you press arrow-down it changes the focus (the same applies with
the first item and arrow-up).</para>

<para>If the current value in the entry is not in the list, then the
function of gtkComboSetUseArrows() is disabled.</para>

<para>gtkComboSetUseArrowsAlways() similarly allows the use the
the up/down arrow keys to cycle through the choices in the dropdown
list, except that it wraps around the values in the list, completely
disabling the use of the up and down arrow keys for changing focus.</para>

<para>gtkComboSetCaseSensitive() toggles whether or not GTK
searches for entries in a case sensitive manner. This is used when the
Combo widget is asked to find a value from the list using the current
entry in the text box. This completion can be performed in either a
case sensitive or insensitive manner, depending upon the use of this
function. The Combo widget can also simply complete the current entry
if the user presses the key combination MOD-1 and "Tab". MOD-1 is
often mapped to the "Alt" key, by the <literal>xmodmap</literal> utility. Note,
however that some window managers also use this key combination, which
will override its use within GTK.</para>

<para>Now that we have a combo box, tailored to look and act how we want it,
all that remains is being able to get data from the combo box. This is
relatively straightforward. The majority of the time, all you are
going to care about getting data from is the entry. The entry is
accessed simply by <literal>GTKENTRY (GTKCOMBO (combo)->entry)</literal>. The
two principal things that you are going to want to do with it are
connect to the activate signal, which indicates that the user has
pressed the Return or Enter key, and read the text. The first is
accomplished using something like:</para>

<programlisting role="R">
    gSignalConnect (GOBJECT (GTKCOMBO (combo)->entry), "activate",
                      GCALLBACK (myCallbackFunction), (gpointer) myData);
</programlisting>

<para>Getting the text at any arbitrary time is accomplished by simply using
the entry function:</para>

<programlisting role="R">
gchar#gtkEntryGetText( GtkEntry#entry );
</programlisting>

<para>Such as:</para>

<programlisting role="R">
    gchar#string;

    string = gtkEntryGetText (GTKENTRY (GTKCOMBO (combo)->entry));
</programlisting>

<para>That's about all there is to it. There is a function</para>

<programlisting role="R">
void gtkComboDisableActivate( GtkCombo#combo );
</programlisting>

<para>that will disable the activate signal on the entry widget in the combo
box. Personally, I can't think of why you'd want to use it, but it
does exist.</para>

<!-- There is also a function to set the string on a particular item, void
gtkComboSetItemString(GtkCombo#combo, GtkItem#item, const gchar
*itemValue), but this requires that you have a pointer to the
appropriate Item. Frankly, I have no idea how to do that.
-->

</sect1>

<!-- ----------------------------------------------------------------- -->
<sect1 id="sec-Calendar">
<title>Calendar</title>

<para>The Calendar widget is an effective way to display and retrieve
monthly date related information. It is a very simple widget to create
and work with.</para>

<para>Creating a GtkCalendar widget is a simple as: </para>

<programlisting role="R">
GtkWidget#gtkCalendarNew( void );
</programlisting>

<para>There might be times where you need to change a lot of information
within this widget and the following functions allow you to make
multiple change to a Calendar widget without the user seeing multiple
on-screen updates.</para>

<programlisting role="R">
void gtkCalendarFreeze( GtkCalendar#Calendar );

void gtkCalendarThaw( GtkCalendar#Calendar );
</programlisting>

<para>They work just like the freeze/thaw functions of every other
widget.</para>

<para>The Calendar widget has a few options that allow you to change the way
the widget both looks and operates by using the function</para>

<programlisting role="R">
void gtkCalendarDisplayOptions( GtkCalendar              #calendar,
                                   GtkCalendarDisplayOptions  flags );
</programlisting>

<para>The <literal>flags</literal> argument can be formed by combining either of the
following five options using the logical bitwise OR (|) operation:</para>

<variablelist>
<varlistentry>
<term><literal>GTKCALENDARSHOWHEADING</literal></term>
<listitem><para>this option specifies that the month and year should be shown 
when drawing the calendar.</para>
</listitem>
</varlistentry>
<varlistentry>
<term><literal>GTKCALENDARSHOWDAYNAMES</literal></term>
<listitem><para>this option specifies that the three letter descriptions should 
be displayed for each day (eg Mon,Tue, etc.).</para>
</listitem>
</varlistentry>
<varlistentry>
<term><literal>GTKCALENDARNOMONTHCHANGE</literal></term>
<listitem><para>this option states that the user
should not and can not change the currently displayed month. This can
be good if you only need to display a particular month such as if you
are displaying 12 calendar widgets for every month in a particular
year.</para>
</listitem>
</varlistentry>
<varlistentry>
<term><literal>GTKCALENDARSHOWWEEKNUMBERS</literal></term>
<listitem><para>this option specifies that the
number for each week should be displayed down the left side of the
calendar. (eg. Jan 1 = Week 1,Dec 31 = Week 52).</para>
</listitem>
</varlistentry>
<varlistentry>
<term><literal>GTKCALENDARWEEKSTARTMONDAY</literal></term>
<listitem><para>this option states that the
calander week will start on Monday instead of Sunday which is the
default. This only affects the order in which days are displayed from
left to right.</para>
</listitem>
</varlistentry>
</variablelist>

<para>The following functions are used to set the the currently displayed
date:</para>

<programlisting role="R">
gint gtkCalendarSelectMonth( GtkCalendar#calendar, 
                                guint        month,
                                guint        year );

void gtkCalendarSelectDay( GtkCalendar#calendar,
                              guint        day );
</programlisting>

<para>The return value from <literal>gtkCalendarSelectMonth()</literal> is a boolean
value indicating whether the selection was successful.</para>

<para>With <literal>gtkCalendarSelectDay()</literal> the specified day number is
selected within the current month, if that is possible. A
<literal>day</literal> value of 0 will deselect any current selection.</para>

<para>In addition to having a day selected, any number of days in the month
may be "marked". A marked day is highlighted within the calendar
display. The following functions are provided to manipulate marked
days:</para>

<programlisting role="R">
gint gtkCalendarMarkDay( GtkCalendar#calendar,
                            guint        day);

gint gtkCalendarUnmarkDay( GtkCalendar#calendar,
                              guint        day);

void gtkCalendarClearMarks( GtkCalendar#calendar);
</programlisting>

<para>The currently marked days are stored within an array within the
GtkCalendar structure. This array is 31 elements long so to test
whether a particular day is currently marked, you need to access the
corresponding element of the array (don't forget in C that array
elements are numbered 0 to n-1). For example:</para>

<programlisting role="R">
    GtkCalendar#calendar;
    calendar = gtkCalendarNew ();

    ...

    # Is day 7 marked? 
    if (calendar->markedDate[7-1])
       # day is marked 
</programlisting>

<para>Note that marks are persistent across month and year changes.</para>

<para>The final Calendar widget function is used to retrieve the currently
selected date, month and/or year.</para>

<programlisting role="R">
void gtkCalendarGetDate( GtkCalendar#calendar, 
                            guint      #year,
                            guint      #month,
                            guint      #day );
</programlisting>

<para>This function requires you to pass the addresses of <literal>guint</literal>
variables, into which the result will be placed. Passing <literal>NULL</literal> as
a value will result in the corresponding value not being returned.</para>

<para>The Calendar widget can generate a number of signals indicating date
selection and change. The names of these signals are self explanatory,
and are:</para>

<itemizedlist>
<listitem><simpara> <literal>monthChanged</literal></simpara>
</listitem>
<listitem><simpara> <literal>daySelected</literal></simpara>
</listitem>
<listitem><simpara> <literal>daySelectedDoubleClick</literal></simpara>
</listitem>
<listitem><simpara> <literal>prevMonth</literal></simpara>
</listitem>
<listitem><simpara> <literal>nextMonth</literal></simpara>
</listitem>
<listitem><simpara> <literal>prevYear</literal></simpara>
</listitem>
<listitem><simpara> <literal>nextYear</literal></simpara>
</listitem>
</itemizedlist>

<para>That just leaves us with the need to put all of this together into
example code.</para>

<para>
<inlinemediaobject>
<imageobject>
<imagedata fileref="images/calendar.png" format="png">
</imageobject>
</inlinemediaobject>
</para>

<programlisting role="R">
<!-- example-start calendar calendar.c -->
#
# Copyright (C) 1998 Cesar Miquel, Shawn T. Amundson, Mattias Gr?nlund
# Copyright (C) 2000 Tony Gale
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 2 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program; if not, write to the Free Software
# Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
 

#include &lt;stdio.h&gt;
#include &lt;string.h&gt;
#include &lt;gtk/gtk.h&gt;

#define DEFPAD 10
#define DEFPADSMALL 5

#define TMYEARBASE 1900

typedef struct CalendarData {
  GtkWidget#flagCheckboxes[5];
  gboolean  settings[5];
  GtkWidget#fontDialog;
  GtkWidget#window;
  GtkWidget#prev2Sig;
  GtkWidget#prevSig;
  GtkWidget#lastSig;
  GtkWidget#month;
} CalendarData;

enum {
  calendarShowHeader,
  calendarShowDays,
  calendarMonthChange, 
  calendarShowWeek,
  calendarMondayFirst
};

#
# GtkCalendar
 

static void calendarDateToString( CalendarData#data,
                                     char        #buffer,
                                     gint          buffLen )
{
  GDate date;
  guint year, month, day;

  gtkCalendarGetDate (GTKCALENDAR (data-&gt;window),
			 &amp;year, &amp;month, &amp;day);
  gDateSetDmy (&amp;date, day, month + 1, year);
  gDateStrftime (buffer, buffLen - 1, "%x", &amp;date);

}

static void calendarSetSignalStrings( char        #sigStr,
                                         CalendarData#data )
{
  const gchar#prevSig;

  prevSig = gtkLabelGetText (GTKLABEL (data-&gt;prevSig));
  gtkLabelSetText (GTKLABEL (data-&gt;prev2Sig), prevSig);

  prevSig = gtkLabelGetText (GTKLABEL (data-&gt;lastSig));
  gtkLabelSetText (GTKLABEL (data-&gt;prevSig), prevSig);
  gtkLabelSetText (GTKLABEL (data-&gt;lastSig), sigStr);
}

static void calendarMonthChanged( GtkWidget   #widget,
                                    CalendarData#data )
{
  char buffer[256] = "monthChanged: ";

  calendarDateToString (data, buffer + 15, 256 - 15);
  calendarSetSignalStrings (buffer, data);
}

static void calendarDaySelected( GtkWidget   #widget,
                                   CalendarData#data )
{
  char buffer[256] = "daySelected: ";

  calendarDateToString (data, buffer + 14, 256 - 14);
  calendarSetSignalStrings (buffer, data);
}

static void calendarDaySelectedDoubleClick ( GtkWidget   #widget,
                                                 CalendarData#data )
{
  char buffer[256] = "daySelectedDoubleClick: ";
  guint day;

  calendarDateToString (data, buffer + 27, 256 - 27);
  calendarSetSignalStrings (buffer, data);

  gtkCalendarGetDate (GTKCALENDAR (data-&gt;window),
			 NULL, NULL, &amp;day);

  if (GTKCALENDAR (data-&gt;window)-&gt;markedDate[day-1] == 0) {
    gtkCalendarMarkDay (GTKCALENDAR (data-&gt;window), day);
  } else { 
    gtkCalendarUnmarkDay (GTKCALENDAR (data-&gt;window), day);
  }
}

static void calendarPrevMonth( GtkWidget   #widget,
                                 CalendarData#data )
{
  char buffer[256] = "prevMonth: ";

  calendarDateToString (data, buffer + 12, 256 - 12);
  calendarSetSignalStrings (buffer, data);
}

static void calendarNextMonth( GtkWidget   #widget,
                                 CalendarData#data )
{
  char buffer[256] = "nextMonth: ";

  calendarDateToString (data, buffer + 12, 256 - 12);
  calendarSetSignalStrings (buffer, data);
}

static void calendarPrevYear( GtkWidget   #widget,
                                CalendarData#data )
{
  char buffer[256] = "prevYear: ";

  calendarDateToString (data, buffer + 11, 256 - 11);
  calendarSetSignalStrings (buffer, data);
}

static void calendarNextYear( GtkWidget   #widget,
                                CalendarData#data )
{
  char buffer[256] = "nextYear: ";

  calendarDateToString (data, buffer + 11, 256 - 11);
  calendarSetSignalStrings (buffer, data);
}


static void calendarSetFlags( CalendarData#calendar )
{
  gint i;
  gint options = 0;
  for (i = 0;i &lt; 5; i++) 
    if (calendar-&gt;settings[i])
      {
	options = options + (1 &lt;&lt; i);
      }
  if (calendar-&gt;window)
    gtkCalendarDisplayOptions (GTKCALENDAR (calendar-&gt;window), options);
}

static void calendarToggleFlag( GtkWidget   #toggle,
                                  CalendarData#calendar)
{
  gint i;
  gint j;
  j = 0;
  for (i = 0; i &lt; 5; i++)
    if (calendar-&gt;flagCheckboxes[i] == toggle)
      j = i;

  calendar-&gt;settings[j] = !calendar-&gt;settings[j];
  calendarSetFlags (calendar);
  
}

static void calendarFontSelectionOk( GtkWidget   #button,
                                        CalendarData#calendar )
{
  GtkRcStyle#style;
  char#fontName;

  if (calendar-&gt;window)
    {
      fontName = gtkFontSelectionDialogGetFontName (GTKFONTSELECTIONDIALOG (calendar-&gt;fontDialog));
      if (fontName) 
	{
	  style = gtkRcStyleNew ();
	  pangoFontDescriptionFree (style-&gt;fontDesc);
	  style-&gt;fontDesc = pangoFontDescriptionFromString (fontName);
	  gtkWidgetModifyStyle (calendar-&gt;window, style);
	  gFree (fontName);
	}
    }

  gtkWidgetDestroy (calendar-&gt;fontDialog);
}

static void calendarSelectFont( GtkWidget   #button,
                                  CalendarData#calendar )
{
  GtkWidget#window;

  if (!calendar-&gt;fontDialog) {
    window = gtkFontSelectionDialogNew ("Font Selection Dialog");
    gReturnIfFail (GTKISFONTSELECTIONDIALOG (window));
    calendar-&gt;fontDialog = window;
    
    gtkWindowSetPosition (GTKWINDOW (window), GTKWINPOSMOUSE);
    
    gSignalConnect (window, "destroy",
		      GCALLBACK (gtkWidgetDestroyed),
		      &amp;calendar-&gt;fontDialog);
    
    gSignalConnect (GTKFONTSELECTIONDIALOG (window)-&gt;okButton,
		      "clicked", GCALLBACK (calendarFontSelectionOk),
		      calendar);
    gSignalConnectSwapped (GTKFONTSELECTIONDIALOG (window)-&gt;cancelButton,
			     "clicked", GCALLBACK (gtkWidgetDestroy), 
			     calendar-&gt;fontDialog);
  }
  window = calendar-&gt;fontDialog;
  if (!GTKWIDGETVISIBLE (window))
    gtkWidgetShow (window);
  else
    gtkWidgetDestroy (window);

}

static void createCalendar( void )
{
  GtkWidget#window;
  GtkWidget#vbox,#vbox2,#vbox3;
  GtkWidget#hbox;
  GtkWidget#hbbox;
  GtkWidget#calendar;
  GtkWidget#toggle;
  GtkWidget#button;
  GtkWidget#frame;
  GtkWidget#separator;
  GtkWidget#label;
  GtkWidget#bbox;
  static CalendarData calendarData;
  gint i;
  
  struct {
    char#label;
  } flags[] =
    {
      { "Show Heading" },
      { "Show Day Names" },
      { "No Month Change" },
      { "Show Week Numbers" },
      { "Week Start Monday" }
    };

  
  calendarData.window = NULL;
  calendarData.fontDialog = NULL;

  for (i = 0; i &lt; 5; i++) {
    calendarData.settings[i] = 0;
  }

  window = gtkWindowNew (GTKWINDOWTOPLEVEL);
  gtkWindowSetTitle (GTKWINDOW (window), "GtkCalendar Example");
  gtkContainerSetBorderWidth (GTKCONTAINER (window), 5);
  gSignalConnect (window, "destroy",
		    GCALLBACK (gtkMainQuit),
		    NULL);
  gSignalConnect (window, "delete-event",
		    GCALLBACK (gtkFalse),
		    NULL);
  gtkWindowSetResizable (GTKWINDOW (window), FALSE);

  vbox = gtkVboxNew (FALSE, DEFPAD);
  gtkContainerAdd (GTKCONTAINER (window), vbox);

  #
  # The top part of the window, Calendar, flags and fontsel.
   

  hbox = gtkHboxNew (FALSE, DEFPAD);
  gtkBoxPackStart (GTKBOX (vbox), hbox, TRUE, TRUE, DEFPAD);
  hbbox = gtkHbuttonBoxNew ();
  gtkBoxPackStart (GTKBOX (hbox), hbbox, FALSE, FALSE, DEFPAD);
  gtkButtonBoxSetLayout (GTKBUTTONBOX (hbbox), GTKBUTTONBOXSPREAD);
  gtkBoxSetSpacing (GTKBOX (hbbox), 5);

  # Calendar widget 
  frame = gtkFrameNew ("Calendar");
  gtkBoxPackStart(GTKBOX (hbbox), frame, FALSE, TRUE, DEFPAD);
  calendar=gtkCalendarNew ();
  calendarData.window = calendar;
  calendarSetFlags (&amp;calendarData);
  gtkCalendarMarkDay (GTKCALENDAR (calendar), 19);	
  gtkContainerAdd (GTKCONTAINER (frame), calendar);
  gSignalConnect (calendar, "monthChanged", 
		    GCALLBACK (calendarMonthChanged),
		    &amp;calendarData);
  gSignalConnect (calendar, "daySelected", 
		    GCALLBACK (calendarDaySelected),
		    &amp;calendarData);
  gSignalConnect (calendar, "daySelectedDoubleClick", 
		    GCALLBACK (calendarDaySelectedDoubleClick),
		    &amp;calendarData);
  gSignalConnect (calendar, "prevMonth", 
		    GCALLBACK (calendarPrevMonth),
		    &amp;calendarData);
  gSignalConnect (calendar, "nextMonth", 
		    GCALLBACK (calendarNextMonth),
		    &amp;calendarData);
  gSignalConnect (calendar, "prevYear", 
		    GCALLBACK (calendarPrevYear),
		    &amp;calendarData);
  gSignalConnect (calendar, "nextYear", 
		    GCALLBACK (calendarNextYear),
		    &amp;calendarData);


  separator = gtkVseparatorNew ();
  gtkBoxPackStart (GTKBOX (hbox), separator, FALSE, TRUE, 0);

  vbox2 = gtkVboxNew (FALSE, DEFPAD);
  gtkBoxPackStart (GTKBOX (hbox), vbox2, FALSE, FALSE, DEFPAD);
  
  # Build the Right frame with the flags in  

  frame = gtkFrameNew ("Flags");
  gtkBoxPackStart (GTKBOX (vbox2), frame, TRUE, TRUE, DEFPAD);
  vbox3 = gtkVboxNew (TRUE, DEFPADSMALL);
  gtkContainerAdd (GTKCONTAINER (frame), vbox3);

  for (i = 0; i &lt; 5; i++)
    {
      toggle = gtkCheckButtonNewWithLabel (flags[i].label);
      gSignalConnect (toggle,
			"toggled",
			GCALLBACK (calendarToggleFlag),
			&amp;calendarData);
      gtkBoxPackStart (GTKBOX (vbox3), toggle, TRUE, TRUE, 0);
      calendarData.flagCheckboxes[i] = toggle;
    }
  # Build the right font-button  
  button = gtkButtonNewWithLabel ("Font...");
  gSignalConnect (button,
		    "clicked",
		    GCALLBACK (calendarSelectFont),
		    &amp;calendarData);
  gtkBoxPackStart (GTKBOX (vbox2), button, FALSE, FALSE, 0);

  #
  #  Build the Signal-event part.
   

  frame = gtkFrameNew ("Signal events");
  gtkBoxPackStart (GTKBOX (vbox), frame, TRUE, TRUE, DEFPAD);

  vbox2 = gtkVboxNew (TRUE, DEFPADSMALL);
  gtkContainerAdd (GTKCONTAINER (frame), vbox2);
  
  hbox = gtkHboxNew (FALSE, 3);
  gtkBoxPackStart (GTKBOX (vbox2), hbox, FALSE, TRUE, 0);
  label = gtkLabelNew ("Signal:");
  gtkBoxPackStart (GTKBOX (hbox), label, FALSE, TRUE, 0);
  calendarData.lastSig = gtkLabelNew ("");
  gtkBoxPackStart (GTKBOX (hbox), calendarData.lastSig, FALSE, TRUE, 0);

  hbox = gtkHboxNew (FALSE, 3);
  gtkBoxPackStart (GTKBOX (vbox2), hbox, FALSE, TRUE, 0);
  label = gtkLabelNew ("Previous signal:");
  gtkBoxPackStart (GTKBOX (hbox), label, FALSE, TRUE, 0);
  calendarData.prevSig = gtkLabelNew ("");
  gtkBoxPackStart (GTKBOX (hbox), calendarData.prevSig, FALSE, TRUE, 0);

  hbox = gtkHboxNew (FALSE, 3);
  gtkBoxPackStart (GTKBOX (vbox2), hbox, FALSE, TRUE, 0);
  label = gtkLabelNew ("Second previous signal:");
  gtkBoxPackStart (GTKBOX (hbox), label, FALSE, TRUE, 0);
  calendarData.prev2Sig = gtkLabelNew ("");
  gtkBoxPackStart (GTKBOX (hbox), calendarData.prev2Sig, FALSE, TRUE, 0);

  bbox = gtkHbuttonBoxNew ();
  gtkBoxPackStart (GTKBOX (vbox), bbox, FALSE, FALSE, 0);
  gtkButtonBoxSetLayout (GTKBUTTONBOX (bbox), GTKBUTTONBOXEND);

  button = gtkButtonNewWithLabel ("Close");
  gSignalConnect (button, "clicked", 
		    GCALLBACK (gtkMainQuit), 
		    NULL);
  gtkContainerAdd (GTKCONTAINER (bbox), button);
  GTKWIDGETSETFLAGS (button, GTKCANDEFAULT);
  gtkWidgetGrabDefault (button);

  gtkWidgetShowAll (window);
}


int main (int   argc,
          char#argv[])
{
  gtkInit (&amp;argc, &amp;argv);

  createCalendar ();

  gtkMain ();

  return 0;
}
<!-- example-end -->
</programlisting>

</sect1>

<!-- ----------------------------------------------------------------- -->
<sect1 id="sec-ColorSelection">
<title>Color Selection</title>

<para>The color selection widget is, not surprisingly, a widget for
interactive selection of colors. This composite widget lets the user
select a color by manipulating RGB (Red, Green, Blue) and HSV (Hue,
Saturation, Value) triples.  This is done either by adjusting single
values with sliders or entries, or by picking the desired color from a
hue-saturation wheel/value bar.  Optionally, the opacity of the color
can also be set.</para>

<para>The color selection widget currently emits only one signal,
"colorChanged", which is emitted whenever the current color in the
widget changes, either when the user changes it or if it's set
explicitly through gtkColorSelectionSetColor().</para>

<para>Lets have a look at what the color selection widget has to offer
us. The widget comes in two flavours: GtkColorSelection and
GtkColorSelectionDialog.</para>

<programlisting role="R">
GtkWidget#gtkColorSelectionNew( void );
</programlisting>
	
<para>You'll probably not be using this constructor directly. It creates an
orphan ColorSelection widget which you'll have to parent
yourself. The ColorSelection widget inherits from the VBox
widget.</para>

<programlisting role="R">
GtkWidget#gtkColorSelectionDialogNew( const gchar#title );
</programlisting>

<para>This is the most common color selection constructor. It creates a
ColorSelectionDialog. It consists of a Frame containing a
ColorSelection widget, an HSeparator and an HBox with three buttons,
"Ok", "Cancel" and "Help". You can reach these buttons by accessing
the "okButton", "cancelButton" and "helpButton" widgets in the
ColorSelectionDialog structure,
(i.e., <literal>GTKCOLORSELECTIONDIALOG (colorseldialog)->okButton</literal>)).</para>

<programlisting role="R">
void gtkColorSelectionSetHasOpacityControl( GtkColorSelection#colorsel,
                                                  gboolean           hasOpacity );
</programlisting>

<para>The color selection widget supports adjusting the opacity of a color
(also known as the alpha channel). This is disabled by
default. Calling this function with hasOpacity set to TRUE enables
opacity. Likewise, hasOpacity set to FALSE will disable opacity.</para>

<programlisting role="R">
void gtkColorSelectionSetCurrentColor( GtkColorSelection#colorsel,
                                            GdkColor         #color );

void gtkColorSelectionSetCurrentAlpha( GtkColorSelection#colorsel,
                                            guint16            alpha );
</programlisting>

<para>You can set the current color explicitly by calling 
gtkColorSelectionSetCurrentColor() with a pointer to a GdkColor. 
Setting the opacity (alpha channel) is done with 
gtkColorSelectionSetCurrentAlpha(). The alpha value should be between
0 (fully transparent) and 65535 (fully opaque).
</para>

<programlisting role="R">
void gtkColorSelectionGetCurrentColor( GtkColorSelection#colorsel,
	                                    GdkColor#color );

void gtkColorSelectionGetCurrentAlpha( GtkColorSelection#colorsel,
                                            guint16          #alpha );
</programlisting>

<para>When you need to query the current color, typically when you've
received a "colorChanged" signal, you use these functions.</para>

<para><!-- Need to do a whole section on DnD - TRG
Drag and drop
-------------</para>

<para>The color sample areas (right under the hue-saturation wheel) supports
drag and drop. The type of drag and drop is "application/x-color". The
message data consists of an array of 4 (or 5 if opacity is enabled)
gdouble values, where the value at position 0 is 0.0 (opacity on) or
1.0 (opacity off) followed by the red, green and blue values at
positions 1,2 and 3 respectively.  If opacity is enabled, the opacity
is passed in the value at position 4.
--></para>

<para>Here's a simple example demonstrating the use of the
ColorSelectionDialog. The program displays a window containing a
drawing area. Clicking on it opens a color selection dialog, and
changing the color in the color selection dialog changes the
background color.</para>

<para>
<inlinemediaobject>
<imageobject>
<imagedata fileref="images/colorsel.png" format="png">
</imageobject>
</inlinemediaobject>
</para>

<programlisting role="R">
<!-- example-start colorsel colorsel.c -->

#include &lt;glib.h&gt;
#include &lt;gdk/gdk.h&gt;
#include &lt;gtk/gtk.h&gt;

GtkWidget#colorseldlg = NULL;
GtkWidget#drawingarea = NULL;
GdkColor color;

# Color changed handler 

static void colorChangedCb( GtkWidget        #widget,
                              GtkColorSelection#colorsel )
{
  GdkColor ncolor;

  gtkColorSelectionGetCurrentColor (colorsel, &amp;ncolor);
  gtkWidgetModifyBg (drawingarea, GTKSTATENORMAL, &amp;ncolor);       
}

# Drawingarea event handler 

static gboolean areaEvent( GtkWidget#widget,
                            GdkEvent #event,
                            gpointer   clientData )
{
  gint handled = FALSE;
  gint response;
  GtkColorSelection#colorsel;

  # Check if we've received a button pressed event 

  if (event-&gt;type == GDKBUTTONPRESS)
    {
      handled = TRUE;

       # Create color selection dialog 
      if (colorseldlg == NULL)
        colorseldlg = gtkColorSelectionDialogNew ("Select background color");

      # Get the ColorSelection widget 
      colorsel = GTKCOLORSELECTION (GTKCOLORSELECTIONDIALOG (colorseldlg)-&gt;colorsel);

      gtkColorSelectionSetPreviousColor (colorsel, &amp;color);
      gtkColorSelectionSetCurrentColor (colorsel, &amp;color);
      gtkColorSelectionSetHasPalette (colorsel, TRUE);

      # Connect to the "colorChanged" signal, set the client-data
      # to the colorsel widget 
      gSignalConnect (GOBJECT (colorsel), "colorChanged",
                        GCALLBACK (colorChangedCb), (gpointer) colorsel);

      # Show the dialog 
      response = gtkDialogRun (GTKDIALOG (colorseldlg));

      if (response == GTKRESPONSEOK)
        gtkColorSelectionGetCurrentColor (colorsel, &amp;color);
      else 
        gtkWidgetModifyBg (drawingarea, GTKSTATENORMAL, &amp;color);

      gtkWidgetHide (colorseldlg);
    }

  return handled;
}

# Close down and exit handler 

static gboolean destroyWindow( GtkWidget#widget,
                                GdkEvent #event,
                                gpointer   clientData )
{
  gtkMainQuit ();
  return TRUE;
}

# Main 

gint main( gint   argc,
           gchar#argv[] )
{
  GtkWidget#window;

  # Initialize the toolkit, remove gtk-related commandline stuff 

  gtkInit (&amp;argc, &amp;argv);

  # Create toplevel window, set title and policies 

  window = gtkWindowNew (GTKWINDOWTOPLEVEL);
  gtkWindowSetTitle (GTKWINDOW (window), "Color selection test");
  gtkWindowSetPolicy (GTKWINDOW (window), TRUE, TRUE, TRUE);

  # Attach to the "delete" and "destroy" events so we can exit 

  gSignalConnect (GTKOBJECT (window), "deleteEvent",
                    GTKSIGNALFUNC (destroyWindow), (gpointer) window);
  
  # Create drawingarea, set size and catch button events 

  drawingarea = gtkDrawingAreaNew ();

  color.red = 0;
  color.blue = 65535;
  color.green = 0;
  gtkWidgetModifyBg (drawingarea, GTKSTATENORMAL, &amp;color);       

  gtkWidgetSetSizeRequest (GTKWIDGET (drawingarea), 200, 200);

  gtkWidgetSetEvents (drawingarea, GDKBUTTONPRESSMASK);

  gSignalConnect (GTKOBJECT (drawingarea), "event", 
	            GTKSIGNALFUNC (areaEvent), (gpointer) drawingarea);
  
  # Add drawingarea to window, then show them both 

  gtkContainerAdd (GTKCONTAINER (window), drawingarea);

  gtkWidgetShow (drawingarea);
  gtkWidgetShow (window);
  
  # Enter the gtk main loop (this never returns) 

  gtkMain ();

  # Satisfy grumpy compilers 

  return 0;
}
<!-- example-end -->
</programlisting>

</sect1>

<!-- ----------------------------------------------------------------- -->
<sect1 id="sec-FileSelections">
<title>File Selections</title>

<para>The file selection widget is a quick and simple way to display a File
dialog box. It comes complete with Ok, Cancel, and Help buttons, a
great way to cut down on programming time.</para>

<para>To create a new file selection box use:</para>

<programlisting role="R">
GtkWidget#gtkFileSelectionNew( const gchar#title );
</programlisting>

<para>To set the filename, for example to bring up a specific directory, or
give a default filename, use this function:</para>

<programlisting role="R">
void gtkFileSelectionSetFilename( GtkFileSelection#filesel,
                                      const gchar     #filename );
</programlisting>

<para>To grab the text that the user has entered or clicked on, use this 
function:</para>

<programlisting role="R">
gchar#gtkFileSelectionGetFilename( GtkFileSelection#filesel );
</programlisting>

<para>There are also pointers to the widgets contained within the file 
selection widget. These are:</para>

<programlisting role="R">
  dirList
  fileList
  selectionEntry
  selectionText
  mainVbox
  okButton
  cancelButton
  helpButton
</programlisting>
 
<para>Most likely you will want to use the okButton, cancelButton, and
helpButton pointers in signaling their use.</para>

<para>Included here is an example stolen from <filename>testgtk.c</filename>,
modified to run on its own. As you will see, there is nothing much to creating a file
selection widget. While in this example the Help button appears on the
screen, it does nothing as there is not a signal attached to it.</para>

<para>
<inlinemediaobject>
<imageobject>
<imagedata fileref="images/filesel.png" format="png">
</imageobject>
</inlinemediaobject>
</para>

<programlisting role="R">
<!-- example-start filesel filesel.c -->

#include &lt;gtk/gtk.h&gt;

# Get the selected filename and print it to the console 
static void fileOkSel( GtkWidget       #w,
                         GtkFileSelection#fs )
{
    gPrint ("%s\n", gtkFileSelectionGetFilename (GTKFILESELECTION (fs)));
}

int main( int   argc,
          char#argv[] )
{
    GtkWidget#filew;
    
    gtkInit (&amp;argc, &amp;argv);
    
    # Create a new file selection widget 
    filew = gtkFileSelectionNew ("File selection");
    
    gSignalConnect (GOBJECT (filew), "destroy",
	              GCALLBACK (gtkMainQuit), NULL);
    # Connect the okButton to fileOkSel function 
    gSignalConnect (GOBJECT (GTKFILESELECTION (filew)-&gt;okButton),
		      "clicked", GCALLBACK (fileOkSel), (gpointer) filew);
    
    # Connect the cancelButton to destroy the widget 
    gSignalConnectSwapped (GOBJECT (GTKFILESELECTION (filew)-&gt;cancelButton),
	                      "clicked", GCALLBACK (gtkWidgetDestroy),
			      GOBJECT (filew));
    
    # Lets set the filename, as if this were a save dialog, and we are giving
     a default filename 
    gtkFileSelectionSetFilename (GTKFILESELECTION(filew), 
				     "penguin.png");
    
    gtkWidgetShow (filew);
    gtkMain ();
    return 0;
}
<!-- example-end -->
</programlisting>

</sect1>
</chapter>

<!--**************************************************************** -->
<chapter id="ch-ContainerWidgets">
<title>Container Widgets</title>

<!-- ----------------------------------------------------------------- -->   
<sect1 id="sec-EventBox">
<title>The EventBox</title>

<para>Some GTK widgets don't have associated X windows, so they just draw on
their parents. Because of this, they cannot receive events and if they
are incorrectly sized, they don't clip so you can get messy
overwriting, etc. If you require more from these widgets, the EventBox
is for you.</para>

<para>At first glance, the EventBox widget might appear to be totally
useless. It draws nothing on the screen and responds to no
events. However, it does serve a function - it provides an X window
for its child widget. This is important as many GTK widgets do not
have an associated X window. Not having an X window saves memory and
improves performance, but also has some drawbacks. A widget without an
X window cannot receive events, and does not perform any clipping on
its contents. Although the name <emphasis>EventBox</emphasis> emphasizes the
event-handling function, the widget can also be used for clipping.
(and more, see the example below).</para>

<para>To create a new EventBox widget, use:</para>

<programlisting role="R">
GtkWidget#gtkEventBoxNew( void );
</programlisting>

<para>A child widget can then be added to this EventBox:</para>

<programlisting role="R">
    gtkContainerAdd (GTKCONTAINER (eventBox), childWidget);
</programlisting>

<para>The following example demonstrates both uses of an EventBox - a label
is created that is clipped to a small box, and set up so that a
mouse-click on the label causes the program to exit. Resizing the
window reveals varying amounts of the label.</para>

<para>
<inlinemediaobject>
<imageobject>
<imagedata fileref="images/eventbox.png" format="png">
</imageobject>
</inlinemediaobject>
</para>

<programlisting role="R">
<!-- example-start eventbox eventbox.c -->

#include &lt;stdlib.h&gt;
#include &lt;gtk/gtk.h&gt;

int main( int argc,
          char#argv[] )
{
    GtkWidget#window;
    GtkWidget#eventBox;
    GtkWidget#label;
    
    gtkInit (&amp;argc, &amp;argv);
    
    window = gtkWindowNew (GTKWINDOWTOPLEVEL);
    
    gtkWindowSetTitle (GTKWINDOW (window), "Event Box");
    
    gSignalConnect (GOBJECT (window), "destroy",
	              GCALLBACK (exit), NULL);
    
    gtkContainerSetBorderWidth (GTKCONTAINER (window), 10);
    
    # Create an EventBox and add it to our toplevel window 
    
    eventBox = gtkEventBoxNew ();
    gtkContainerAdd (GTKCONTAINER (window), eventBox);
    gtkWidgetShow (eventBox);
    
    # Create a long label 
    
    label = gtkLabelNew ("Click here to quit, quit, quit, quit, quit");
    gtkContainerAdd (GTKCONTAINER (eventBox), label);
    gtkWidgetShow (label);
    
    # Clip it short. 
    gtkWidgetSetSizeRequest (label, 110, 20);
    
    # And bind an action to it 
    gtkWidgetSetEvents (eventBox, GDKBUTTONPRESSMASK);
    gSignalConnect (GOBJECT (eventBox), "buttonPressEvent",
	              GCALLBACK (exit), NULL);
    
    # Yet one more thing you need an X window for ... 
    
    gtkWidgetRealize (eventBox);
    gdkWindowSetCursor (eventBox-&gt;window, gdkCursorNew (GDKHAND1));
    
    gtkWidgetShow (window);
    
    gtkMain ();
    
    return 0;
}
<!-- example-end -->
</programlisting>

</sect1>

<!-- ----------------------------------------------------------------- -->   
<sect1 id="sec-TheAlignmentWidget">
<title>The Alignment widget</title>

<para>The alignment widget allows you to place a widget within its window at
a position and size relative to the size of the Alignment widget
itself. For example, it can be very useful for centering a widget
within the window.</para>

<para>There are only two functions associated with the Alignment widget:</para>

<programlisting role="R">
GtkWidget* gtkAlignmentNew( gfloat xalign,
                              gfloat yalign,
                              gfloat xscale,
                              gfloat yscale );

void gtkAlignmentSet( GtkAlignment#alignment,
                        gfloat        xalign,
                        gfloat        yalign,
                        gfloat        xscale,
                        gfloat        yscale );
</programlisting>

<para>The first function creates a new Alignment widget with the specified
parameters. The second function allows the alignment parameters of an
exisiting Alignment widget to be altered.</para>

<para>All four alignment parameters are floating point numbers which can
range from 0.0 to 1.0. The <literal>xalign</literal> and <literal>yalign</literal> arguments
affect the position of the widget placed within the Alignment
widget. The <literal>xscale</literal> and <literal>yscale</literal> arguments affect the amount of
space allocated to the widget.</para>

<para>A child widget can be added to this Alignment widget using:</para>

<programlisting role="R">
    gtkContainerAdd (GTKCONTAINER (alignment), childWidget);
</programlisting>

<para>For an example of using an Alignment widget, refer to the example for
the <link linkend="sec-ProgressBars">Progress Bar</link> widget.</para>

</sect1>

<!-- ----------------------------------------------------------------- -->
<sect1 id="sec-FixedContainer">
<title>Fixed Container</title>

<para>The Fixed container allows you to place widgets at a fixed position
within it's window, relative to it's upper left hand corner. The
position of the widgets can be changed dynamically.</para>

<para>There are only a few functions associated with the fixed widget:</para>

<programlisting role="R">
GtkWidget* gtkFixedNew( void );

void gtkFixedPut( GtkFixed #fixed,
                    GtkWidget#widget,
                    gint       x,
                    gint       y );

void gtkFixedMove( GtkFixed #fixed,
                     GtkWidget#widget,
                     gint       x,
                     gint       y );
</programlisting>

<para>The function gtkFixedNew() allows you to create a new Fixed
container.</para>

<para>gtkFixedPut() places <literal>widget</literal> in the container <literal>fixed</literal> at
the position specified by <literal>x</literal> and <literal>y</literal>.</para>

<para>gtkFixedMove() allows the specified widget to be moved to a new
position.</para>

<programlisting role="R">
void gtkFixedSetHasWindow( GtkFixed #fixed,
                               gboolean   hasWindow );

gboolean gtkFixedGetHasWindow( GtkFixed#fixed );
</programlisting>

<para>Normally, Fixed widgets don't have their own X window. Since this is
different from the behaviour of Fixed widgets in earlier releases of GTK, 
the function gtkFixedSetHasWindow() allows the creation of Fixed widgets 
<emphasis>with</emphasis> their own window. It has to be called before
realizing the widget.</para>

<para>The following example illustrates how to use the Fixed Container.</para>

<para>
<inlinemediaobject>
<imageobject>
<imagedata fileref="images/fixed.png" format="png">
</imageobject>
</inlinemediaobject>
</para>

<programlisting role="R">
<!-- example-start fixed fixed.c -->

#include &lt;gtk/gtk.h&gt;

# I'm going to be lazy and use some global variables to
# store the position of the widget within the fixed
# container 
gint x = 50;
gint y = 50;

# This callback function moves the button to a new position
# in the Fixed container. 
static void moveButton( GtkWidget#widget,
                         GtkWidget#fixed )
{
  x = (x + 30) % 300;
  y = (y + 50) % 300;
  gtkFixedMove (GTKFIXED (fixed), widget, x, y); 
}

int main( int   argc,
          char#argv[] )
{
  # GtkWidget is the storage type for widgets 
  GtkWidget#window;
  GtkWidget#fixed;
  GtkWidget#button;
  gint i;

  # Initialise GTK 
  gtkInit (&amp;argc, &amp;argv);
    
  # Create a new window 
  window = gtkWindowNew (GTKWINDOWTOPLEVEL);
  gtkWindowSetTitle (GTKWINDOW (window), "Fixed Container");

  # Here we connect the "destroy" event to a signal handler  
  gSignalConnect (GOBJECT (window), "destroy",
		    GCALLBACK (gtkMainQuit), NULL);
 
  # Sets the border width of the window. 
  gtkContainerSetBorderWidth (GTKCONTAINER (window), 10);

  # Create a Fixed Container 
  fixed = gtkFixedNew ();
  gtkContainerAdd (GTKCONTAINER (window), fixed);
  gtkWidgetShow (fixed);
  
  for (i = 1 ; i &lt;= 3 ; i++) {
    # Creates a new button with the label "Press me" 
    button = gtkButtonNewWithLabel ("Press me");
  
    # When the button receives the "clicked" signal, it will call the
    # function moveButton() passing it the Fixed Container as its
    # argument. 
    gSignalConnect (GOBJECT (button), "clicked",
		      GCALLBACK (moveButton), (gpointer) fixed);
  
    # This packs the button into the fixed containers window. 
    gtkFixedPut (GTKFIXED (fixed), button, i*50, i*50);
  
    # The final step is to display this newly created widget. 
    gtkWidgetShow (button);
  }

  # Display the window 
  gtkWidgetShow (window);
    
  # Enter the event loop 
  gtkMain ();
    
  return 0;
}
<!-- example-end -->
</programlisting>

</sect1>

<!-- ----------------------------------------------------------------- -->
<sect1 id="sec-LayoutContainer">
<title>Layout Container</title>

<para>The Layout container is similar to the Fixed container except that it
implements an infinite (where infinity is less than 2^32) scrolling
area. The X window system has a limitation where windows can be at
most 32767 pixels wide or tall. The Layout container gets around this
limitation by doing some exotic stuff using window and bit gravities,
so that you can have smooth scrolling even when you have many child
widgets in your scrolling area.</para>

<para>A Layout container is created using:</para>

<programlisting role="R">
GtkWidget#gtkLayoutNew( GtkAdjustment#hadjustment,
                           GtkAdjustment#vadjustment );
</programlisting>

<para>As you can see, you can optionally specify the Adjustment objects that
the Layout widget will use for its scrolling.</para>

<para>You can add and move widgets in the Layout container using the
following two functions:</para>

<programlisting role="R">
void gtkLayoutPut( GtkLayout#layout,
                     GtkWidget#widget,
                     gint       x,
                     gint       y );

void gtkLayoutMove( GtkLayout#layout,
                      GtkWidget#widget,
                      gint       x,
                      gint       y );
</programlisting>

<para>The size of the Layout container can be set using the next function:</para>

<programlisting role="R">
void gtkLayoutSetSize( GtkLayout#layout,
                          guint      width,
                          guint      height );
</programlisting>

<para>The final four functions for use with Layout widgets are for
manipulating the horizontal and vertical adjustment widgets:</para>

<programlisting role="R">
GtkAdjustment* gtkLayoutGetHadjustment( GtkLayout#layout );

GtkAdjustment* gtkLayoutGetVadjustment( GtkLayout#layout );

void gtkLayoutSetHadjustment( GtkLayout    #layout,
                                 GtkAdjustment#adjustment );

void gtkLayoutSetVadjustment( GtkLayout    #layout,
                                 GtkAdjustment#adjustment);
</programlisting>

</sect1>

<!-- ----------------------------------------------------------------- -->
<sect1 id="sec-Frames">
<title>Frames</title>

<para>Frames can be used to enclose one or a group of widgets with a box
which can optionally be labelled. The position of the label and the
style of the box can be altered to suit.</para>

<para>A Frame can be created with the following function:</para>

<programlisting role="R">
GtkWidget#gtkFrameNew( const gchar#label );
</programlisting>

<para>The label is by default placed in the upper left hand corner of the
frame. A value of NULL for the <literal>label</literal> argument will result in no
label being displayed. The text of the label can be changed using the
next function.</para>

<programlisting role="R">
void gtkFrameSetLabel( GtkFrame   #frame,
                          const gchar#label );
</programlisting>

<para>The position of the label can be changed using this function:</para>

<programlisting role="R">
void gtkFrameSetLabelAlign( GtkFrame#frame,
                                gfloat    xalign,
                                gfloat    yalign );
</programlisting>

<para><literal>xalign</literal> and <literal>yalign</literal> take values between 0.0 and 1.0. <literal>xalign</literal>
indicates the position of the label along the top horizontal of the
frame. <literal>yalign</literal> is not currently used. The default value of xalign
is 0.0 which places the label at the left hand end of the frame.</para>

<para>The next function alters the style of the box that is used to outline
the frame.</para>

<programlisting role="R">
void gtkFrameSetShadowType( GtkFrame     #frame,
                                GtkShadowType  type);
</programlisting>

<para>The <literal>type</literal> argument can take one of the following values:</para>
<programlisting role="R">
  GTKSHADOWNONE
  GTKSHADOWIN
  GTKSHADOWOUT
  GTKSHADOWETCHEDIN (the default)
  GTKSHADOWETCHEDOUT
</programlisting>

<para>The following code example illustrates the use of the Frame widget.</para>

<para>
<inlinemediaobject>
<imageobject>
<imagedata fileref="images/frame.png" format="png">
</imageobject>
</inlinemediaobject>
</para>

<programlisting role="R">
<!-- example-start frame frame.c -->

#include &lt;gtk/gtk.h&gt;

int main( int   argc,
          char#argv[] )
{
  # GtkWidget is the storage type for widgets 
  GtkWidget#window;
  GtkWidget#frame;

  # Initialise GTK 
  gtkInit (&amp;argc, &amp;argv);
    
  # Create a new window 
  window = gtkWindowNew (GTKWINDOWTOPLEVEL);
  gtkWindowSetTitle (GTKWINDOW (window), "Frame Example");

  # Here we connect the "destroy" event to a signal handler  
  gSignalConnect (GOBJECT (window), "destroy",
		    GCALLBACK (gtkMainQuit), NULL);

  gtkWidgetSetSizeRequest (window, 300, 300);
  # Sets the border width of the window. 
  gtkContainerSetBorderWidth (GTKCONTAINER (window), 10);

  # Create a Frame 
  frame = gtkFrameNew (NULL);
  gtkContainerAdd (GTKCONTAINER (window), frame);

  # Set the frame's label 
  gtkFrameSetLabel (GTKFRAME (frame), "GTK Frame Widget");

  # Align the label at the right of the frame 
  gtkFrameSetLabelAlign (GTKFRAME (frame), 1.0, 0.0);

  # Set the style of the frame 
  gtkFrameSetShadowType (GTKFRAME (frame), GTKSHADOWETCHEDOUT);

  gtkWidgetShow (frame);
  
  # Display the window 
  gtkWidgetShow (window);
    
  # Enter the event loop 
  gtkMain ();
    
  return 0;
}
<!-- example-end -->
</programlisting>
</sect1>

<!-- ----------------------------------------------------------------- -->   
<sect1 id="sec-AspectFrames">
<title>Aspect Frames</title>

<para>The aspect frame widget is like a frame widget, except that it also
enforces the aspect ratio (that is, the ratio of the width to the
height) of the child widget to have a certain value, adding extra
space if necessary. This is useful, for instance, if you want to
preview a larger image. The size of the preview should vary when the
user resizes the window, but the aspect ratio needs to always match
the original image.</para>
  
<para>To create a new aspect frame use:</para>

<programlisting role="R">
GtkWidget#gtkAspectFrameNew( const gchar#label,
                                 gfloat       xalign,
                                 gfloat       yalign,
                                 gfloat       ratio,
                                 gboolean     obeyChild);
</programlisting>
   
<para><literal>xalign</literal> and <literal>yalign</literal> specify alignment as with Alignment
widgets. If <literal>obeyChild</literal> is TRUE, the aspect ratio of a child
widget will match the aspect ratio of the ideal size it requests.
Otherwise, it is given by <literal>ratio</literal>.</para>
   
<para>To change the options of an existing aspect frame, you can use:</para>

<programlisting role="R">
void gtkAspectFrameSet( GtkAspectFrame#aspectFrame,
                           gfloat          xalign,
                           gfloat          yalign,
                           gfloat          ratio,
                           gboolean        obeyChild);
</programlisting>
   
<para>As an example, the following program uses an AspectFrame to present a
drawing area whose aspect ratio will always be 2:1, no matter how the
user resizes the top-level window.</para>

<para>
<inlinemediaobject>
<imageobject>
<imagedata fileref="images/aspectframe.png" format="png">
</imageobject>
</inlinemediaobject>
</para>

<programlisting role="R">
<!-- example-start aspectframe aspectframe.c -->

#include &lt;gtk/gtk.h&gt;
   
int main( int argc,
          char#argv[] )
{
    GtkWidget#window;
    GtkWidget#aspectFrame;
    GtkWidget#drawingArea;
    gtkInit (&amp;argc, &amp;argv);
   
    window = gtkWindowNew (GTKWINDOWTOPLEVEL);
    gtkWindowSetTitle (GTKWINDOW (window), "Aspect Frame");
    gSignalConnect (GOBJECT (window), "destroy",
	              GCALLBACK (gtkMainQuit), NULL);
    gtkContainerSetBorderWidth (GTKCONTAINER (window), 10);
   
    # Create an aspectFrame and add it to our toplevel window 
   
    aspectFrame = gtkAspectFrameNew ("2x1", # label 
                                         0.5, # center x 
                                         0.5, # center y 
                                         2, # xsize/ysize = 2 
                                         FALSE # ignore child's aspect );
   
    gtkContainerAdd (GTKCONTAINER (window), aspectFrame);
    gtkWidgetShow (aspectFrame);
   
    # Now add a child widget to the aspect frame 
   
    drawingArea = gtkDrawingAreaNew ();
   
    # Ask for a 200x200 window, but the AspectFrame will give us a 200x100
    # window since we are forcing a 2x1 aspect ratio 
    gtkWidgetSetSizeRequest (drawingArea, 200, 200);
    gtkContainerAdd (GTKCONTAINER (aspectFrame), drawingArea);
    gtkWidgetShow (drawingArea);
   
    gtkWidgetShow (window);
    gtkMain ();
    return 0;
}
<!-- example-end -->
</programlisting>

</sect1>

<!-- ----------------------------------------------------------------- -->   
<sect1 id="sec-PanedWindowWidgets">
<title>Paned Window Widgets</title>

<para>The paned window widgets are useful when you want to divide an area
into two parts, with the relative size of the two parts controlled by
the user. A groove is drawn between the two portions with a handle
that the user can drag to change the ratio. The division can either be
horizontal (HPaned) or vertical (VPaned).</para>
   
<para>To create a new paned window, call one of:</para>

<programlisting role="R">
GtkWidget#gtkHpanedNew (void);

GtkWidget#gtkVpanedNew (void);
</programlisting>

<para>After creating the paned window widget, you need to add child widgets
to its two halves. To do this, use the functions:</para>

<programlisting role="R">
void gtkPanedAdd1 (GtkPaned#paned, GtkWidget#child);

void gtkPanedAdd2 (GtkPaned#paned, GtkWidget#child);
</programlisting>

<para><literal>gtkPanedAdd1()</literal> adds the child widget to the left or top half of
the paned window. <literal>gtkPanedAdd2()</literal> adds the child widget to the
right or bottom half of the paned window.</para>

<para>As an example, we will create part of the user interface of an
imaginary email program. A window is divided into two portions
vertically, with the top portion being a list of email messages and
the bottom portion the text of the email message. Most of the program
is pretty straightforward. A couple of points to note: text can't be
added to a Text widget until it is realized. This could be done by
calling gtkWidgetRealize(), but as a demonstration of an
alternate technique, we connect a handler to the "realize" signal to
add the text. Also, we need to add the <literal>GTKSHRINK</literal> option to some
of the items in the table containing the text window and its
scrollbars, so that when the bottom portion is made smaller, the
correct portions shrink instead of being pushed off the bottom of the
window.</para>

<para>
<inlinemediaobject>
<imageobject>
<imagedata fileref="images/paned.png" format="png">
</imageobject>
</inlinemediaobject>
</para>

<programlisting role="R">
<!-- example-start paned paned.c -->

#include &lt;stdio.h&gt;
#include &lt;gtk/gtk.h&gt;
   
# Create the list of "messages" 
static GtkWidget#createList( void )
{

    GtkWidget#scrolledWindow;
    GtkWidget#treeView;
    GtkListStore#model;
    GtkTreeIter iter;
    GtkCellRenderer#cell;
    GtkTreeViewColumn#column;

    int i;
   
    # Create a new scrolled window, with scrollbars only if needed 
    scrolledWindow = gtkScrolledWindowNew (NULL, NULL);
    gtkScrolledWindowSetPolicy (GTKSCROLLEDWINDOW (scrolledWindow),
				    GTKPOLICYAUTOMATIC, 
				    GTKPOLICYAUTOMATIC);
   
    model = gtkListStoreNew (1, GTYPESTRING);
    treeView = gtkTreeViewNew ();
    gtkScrolledWindowAddWithViewport (GTKSCROLLEDWINDOW (scrolledWindow), 
                                           treeView);
    gtkTreeViewSetModel (GTKTREEVIEW (treeView), GTKTREEMODEL (model));
    gtkWidgetShow (treeView);
   
    # Add some messages to the window 
    for (i = 0; i &lt; 10; i++) {
        gchar#msg = gStrdupPrintf ("Message #%d", i);
        gtkListStoreAppend (GTKLISTSTORE (model), &amp;iter);
        gtkListStoreSet (GTKLISTSTORE (model), 
	                    &amp;iter,
                            0, msg,
	                    -1);
	gFree (msg);
    }
   
    cell = gtkCellRendererTextNew ();

    column = gtkTreeViewColumnNewWithAttributes ("Messages",
                                                       cell,
                                                       "text", 0,
                                                       NULL);
  
    gtkTreeViewAppendColumn (GTKTREEVIEW (treeView),
	  		         GTKTREEVIEWCOLUMN (column));

    return scrolledWindow;
}
   
# Add some text to our text widget - this is a callback that is invoked
when our window is realized. We could also force our window to be
realized with gtkWidgetRealize, but it would have to be part of
a hierarchy first 

static void insertText( GtkTextBuffer#buffer )
{
   GtkTextIter iter;
 
   gtkTextBufferGetIterAtOffset (buffer, &amp;iter, 0);

   gtkTextBufferInsert (buffer, &amp;iter,   
    "From: pathfinder@nasa.gov\n"
    "To: mom@nasa.gov\n"
    "Subject: Made it!\n"
    "\n"
    "We just got in this morning. The weather has been\n"
    "great - clear but cold, and there are lots of fun sights.\n"
    "Sojourner says hi. See you soon.\n"
    " -Path\n", -1);
}
   
# Create a scrolled text area that displays a "message" 
static GtkWidget#createText( void )
{
   GtkWidget#scrolledWindow;
   GtkWidget#view;
   GtkTextBuffer#buffer;

   view = gtkTextViewNew ();
   buffer = gtkTextViewGetBuffer (GTKTEXTVIEW (view));

   scrolledWindow = gtkScrolledWindowNew (NULL, NULL);
   gtkScrolledWindowSetPolicy (GTKSCROLLEDWINDOW (scrolledWindow),
		   	           GTKPOLICYAUTOMATIC,
				   GTKPOLICYAUTOMATIC);

   gtkContainerAdd (GTKCONTAINER (scrolledWindow), view);
   insertText (buffer);

   gtkWidgetShowAll (scrolledWindow);

   return scrolledWindow;
}
   
int main( int   argc,
          char#argv[] )
{
    GtkWidget#window;
    GtkWidget#vpaned;
    GtkWidget#list;
    GtkWidget#text;

    gtkInit (&amp;argc, &amp;argv);
   
    window = gtkWindowNew (GTKWINDOWTOPLEVEL);
    gtkWindowSetTitle (GTKWINDOW (window), "Paned Windows");
    gSignalConnect (GOBJECT (window), "destroy",
	              GCALLBACK (gtkMainQuit), NULL);
    gtkContainerSetBorderWidth (GTKCONTAINER (window), 10);
    gtkWidgetSetSizeRequest (GTKWIDGET (window), 450, 400);

    # create a vpaned widget and add it to our toplevel window 
   
    vpaned = gtkVpanedNew ();
    gtkContainerAdd (GTKCONTAINER (window), vpaned);
    gtkWidgetShow (vpaned);
   
    # Now create the contents of the two halves of the window 
   
    list = createList ();
    gtkPanedAdd1 (GTKPANED (vpaned), list);
    gtkWidgetShow (list);
   
    text = createText ();
    gtkPanedAdd2 (GTKPANED (vpaned), text);
    gtkWidgetShow (text);
    gtkWidgetShow (window);

    gtkMain ();

    return 0;
}
<!-- example-end -->
</programlisting>

</sect1>

<!-- ----------------------------------------------------------------- -->
<sect1 id="sec-Viewports">
<title>Viewports</title>

<para>It is unlikely that you will ever need to use the Viewport widget
directly. You are much more likely to use the
<link linkend="sec-ScrolledWindows">Scrolled Window</link> widget which
itself uses the Viewport.</para>

<para>A viewport widget allows you to place a larger widget within it such
that you can view a part of it at a time. It uses
<link linkend="ch-Adjustments">Adjustments</link> to define the area that
is currently in view.</para>

<para>A Viewport is created with the function</para>

<programlisting role="R">
GtkWidget#gtkViewportNew( GtkAdjustment#hadjustment,
                             GtkAdjustment#vadjustment );
</programlisting>

<para>As you can see you can specify the horizontal and vertical Adjustments
that the widget is to use when you create the widget. It will create
its own if you pass NULL as the value of the arguments.</para>

<para>You can get and set the adjustments after the widget has been created
using the following four functions:</para>

<programlisting role="R">
GtkAdjustment#gtkViewportGetHadjustment( GtkViewport#viewport );

GtkAdjustment#gtkViewportGetVadjustment( GtkViewport#viewport );

void gtkViewportSetHadjustment( GtkViewport  #viewport,
                                   GtkAdjustment#adjustment );

void gtkViewportSetVadjustment( GtkViewport  #viewport,
                                   GtkAdjustment#adjustment );
</programlisting>

<para>The only other viewport function is used to alter its appearance:</para>

<programlisting role="R">
void gtkViewportSetShadowType( GtkViewport  #viewport,
                                   GtkShadowType  type );
</programlisting>

<para>Possible values for the <literal>type</literal> parameter are:</para>
<programlisting role="R">
  GTKSHADOWNONE,
  GTKSHADOWIN,
  GTKSHADOWOUT,
  GTKSHADOWETCHEDIN,
  GTKSHADOWETCHEDOUT
</programlisting>
 
</sect1>

<!-- ----------------------------------------------------------------- -->
<sect1 id="sec-ScrolledWindows"
<title>Scrolled Windows</title>

<para>Scrolled windows are used to create a scrollable area with another
widget inside it. You may insert any type of widget into a scrolled
window, and it will be accessible regardless of the size by using the
scrollbars.</para>

<para>The following function is used to create a new scrolled window.</para>

<programlisting role="R">
GtkWidget#gtkScrolledWindowNew( GtkAdjustment#hadjustment,
                                    GtkAdjustment#vadjustment );
</programlisting>

<para>Where the first argument is the adjustment for the horizontal
direction, and the second, the adjustment for the vertical direction.
These are almost always set to NULL.</para>

<programlisting role="R">
void gtkScrolledWindowSetPolicy( GtkScrolledWindow#scrolledWindow,
                                     GtkPolicyType      hscrollbarPolicy,
                                     GtkPolicyType      vscrollbarPolicy );
</programlisting>

<para>This sets the policy to be used with respect to the scrollbars.
The first argument is the scrolled window you wish to change. The second
sets the policy for the horizontal scrollbar, and the third the policy for 
the vertical scrollbar.</para>

<para>The policy may be one of <literal>GTKPOLICYAUTOMATIC</literal> or
<literal>GTKPOLICYALWAYS</literal>. <literal>GTKPOLICYAUTOMATIC</literal> will automatically
decide whether you need scrollbars, whereas <literal>GTKPOLICYALWAYS</literal>
will always leave the scrollbars there.</para>

<para>You can then place your object into the scrolled window using the
following function.</para>

<programlisting role="R">
void gtkScrolledWindowAddWithViewport( GtkScrolledWindow#scrolledWindow,
                                            GtkWidget        #child);
</programlisting>

<para>Here is a simple example that packs a table with 100 toggle buttons
into a scrolled window. I've only commented on the parts that may be
new to you.</para>

<para>
<inlinemediaobject>
<imageobject>
<imagedata fileref="images/scrolledwin.png" format="png">
</imageobject>
</inlinemediaobject>
</para>

<programlisting role="R">
<!-- example-start scrolledwin scrolledwin.c -->

#include &lt;stdio.h&gt;
#include &lt;gtk/gtk.h&gt;

static void destroy( GtkWidget#widget,
                     gpointer   data )
{
    gtkMainQuit ();
}

int main( int   argc,
          char#argv[] )
{
    static GtkWidget#window;
    GtkWidget#scrolledWindow;
    GtkWidget#table;
    GtkWidget#button;
    char buffer[32];
    int i, j;
    
    gtkInit (&amp;argc, &amp;argv);
    
    # Create a new dialog window for the scrolled window to be
    # packed into.  
    window = gtkDialogNew ();
    gSignalConnect (GOBJECT (window), "destroy",
		      GCALLBACK (destroy), NULL);
    gtkWindowSetTitle (GTKWINDOW (window), "GtkScrolledWindow example");
    gtkContainerSetBorderWidth (GTKCONTAINER (window), 0);
    gtkWidgetSetSizeRequest (window, 300, 300);
    
    # create a new scrolled window. 
    scrolledWindow = gtkScrolledWindowNew (NULL, NULL);
    
    gtkContainerSetBorderWidth (GTKCONTAINER (scrolledWindow), 10);
    
    # the policy is one of GTKPOLICY AUTOMATIC, or GTKPOLICYALWAYS.
    # GTKPOLICYAUTOMATIC will automatically decide whether you need
    # scrollbars, whereas GTKPOLICYALWAYS will always leave the scrollbars
    # there.  The first one is the horizontal scrollbar, the second, 
    # the vertical. 
    gtkScrolledWindowSetPolicy (GTKSCROLLEDWINDOW (scrolledWindow),
                                    GTKPOLICYAUTOMATIC, GTKPOLICYALWAYS);
    # The dialog window is created with a vbox packed into it. 								
    gtkBoxPackStart (GTKBOX (GTKDIALOG(window)-&gt;vbox), scrolledWindow, 
			TRUE, TRUE, 0);
    gtkWidgetShow (scrolledWindow);
    
    # create a table of 10 by 10 squares. 
    table = gtkTableNew (10, 10, FALSE);
    
    # set the spacing to 10 on x and 10 on y 
    gtkTableSetRowSpacings (GTKTABLE (table), 10);
    gtkTableSetColSpacings (GTKTABLE (table), 10);
    
    # pack the table into the scrolled window 
    gtkScrolledWindowAddWithViewport (
                   GTKSCROLLEDWINDOW (scrolledWindow), table);
    gtkWidgetShow (table);
    
    # this simply creates a grid of toggle buttons on the table
    # to demonstrate the scrolled window. 
    for (i = 0; i &lt; 10; i++)
       for (j = 0; j &lt; 10; j++) {
          sprintf (buffer, "button (%d,%d)\n", i, j);
	  button = gtkToggleButtonNewWithLabel (buffer);
	  gtkTableAttachDefaults (GTKTABLE (table), button,
	                             i, i+1, j, j+1);
          gtkWidgetShow (button);
       }
    
    # Add a "close" button to the bottom of the dialog 
    button = gtkButtonNewWithLabel ("close");
    gSignalConnectSwapped (GOBJECT (button), "clicked",
			      GCALLBACK (gtkWidgetDestroy),
			      GOBJECT (window));
    
    # this makes it so the button is the default. 
    
    GTKWIDGETSETFLAGS (button, GTKCANDEFAULT);
    gtkBoxPackStart (GTKBOX (GTKDIALOG (window)-&gt;actionArea), button, TRUE, TRUE, 0);
    
    # This grabs this button to be the default button. Simply hitting
    # the "Enter" key will cause this button to activate. 
    gtkWidgetGrabDefault (button);
    gtkWidgetShow (button);
    
    gtkWidgetShow (window);
    
    gtkMain();
    
    return 0;
}
<!-- example-end -->
</programlisting>

<para>Try playing with resizing the window. You'll notice how the scrollbars
react. You may also wish to use the gtkWidgetSetSizeRequest() call to set
the default size of the window or other widgets.</para>

</sect1>

<!-- ----------------------------------------------------------------- -->   
<sect1 id="sec-ButtonBoxes">
<title>Button Boxes</title>

<para>Button Boxes are a convenient way to quickly layout a group of
buttons. They come in both horizontal and vertical flavours. You
create a new Button Box with one of the following calls, which create
a horizontal or vertical box, respectively:</para>

<programlisting role="R">
GtkWidget#gtkHbuttonBoxNew( void );

GtkWidget#gtkVbuttonBoxNew( void );
</programlisting>

<para>Buttons are added to a Button Box using the usual function:</para>

<programlisting role="R">
    gtkContainerAdd (GTKCONTAINER (buttonBox), childWidget);
</programlisting>

<para>Here's an example that illustrates all the different layout settings
for Button Boxes.</para>

<para>
<inlinemediaobject>
<imageobject>
<imagedata fileref="images/buttonbox.png" format="png">
</imageobject>
</inlinemediaobject>
</para>

<programlisting role="R">
<!-- example-start buttonbox buttonbox.c -->

#include &lt;gtk/gtk.h&gt;

# Create a Button Box with the specified parameters 
static GtkWidget#createBbox( gint  horizontal,
                               char#title,
                               gint  spacing,
                               gint  childW,
                               gint  childH,
                               gint  layout )
{
  GtkWidget#frame;
  GtkWidget#bbox;
  GtkWidget#button;

  frame = gtkFrameNew (title);

  if (horizontal)
    bbox = gtkHbuttonBoxNew ();
  else
    bbox = gtkVbuttonBoxNew ();

  gtkContainerSetBorderWidth (GTKCONTAINER (bbox), 5);
  gtkContainerAdd (GTKCONTAINER (frame), bbox);

  # Set the appearance of the Button Box 
  gtkButtonBoxSetLayout (GTKBUTTONBOX (bbox), layout);
  gtkBoxSetSpacing (GTKBOX (bbox), spacing);
  #gtkButtonBoxSetChildSize (GTKBUTTONBOX (bbox), childW, childH);

  button = gtkButtonNewFromStock (GTKSTOCKOK);
  gtkContainerAdd (GTKCONTAINER (bbox), button);

  button = gtkButtonNewFromStock (GTKSTOCKCANCEL);
  gtkContainerAdd (GTKCONTAINER (bbox), button);

  button = gtkButtonNewFromStock (GTKSTOCKHELP);
  gtkContainerAdd (GTKCONTAINER (bbox), button);

  return frame;
}

int main( int   argc,
          char#argv[] )
{
  static GtkWidget* window = NULL;
  GtkWidget#mainVbox;
  GtkWidget#vbox;
  GtkWidget#hbox;
  GtkWidget#frameHorz;
  GtkWidget#frameVert;

  # Initialize GTK 
  gtkInit (&amp;argc, &amp;argv);

  window = gtkWindowNew (GTKWINDOWTOPLEVEL);
  gtkWindowSetTitle (GTKWINDOW (window), "Button Boxes");

  gSignalConnect (GOBJECT (window), "destroy",
		    GCALLBACK (gtkMainQuit),
		    NULL);

  gtkContainerSetBorderWidth (GTKCONTAINER (window), 10);

  mainVbox = gtkVboxNew (FALSE, 0);
  gtkContainerAdd (GTKCONTAINER (window), mainVbox);

  frameHorz = gtkFrameNew ("Horizontal Button Boxes");
  gtkBoxPackStart (GTKBOX (mainVbox), frameHorz, TRUE, TRUE, 10);

  vbox = gtkVboxNew (FALSE, 0);
  gtkContainerSetBorderWidth (GTKCONTAINER (vbox), 10);
  gtkContainerAdd (GTKCONTAINER (frameHorz), vbox);

  gtkBoxPackStart (GTKBOX (vbox),
	   createBbox (TRUE, "Spread (spacing 40)", 40, 85, 20, GTKBUTTONBOXSPREAD),
		      TRUE, TRUE, 0);

  gtkBoxPackStart (GTKBOX (vbox),
	   createBbox (TRUE, "Edge (spacing 30)", 30, 85, 20, GTKBUTTONBOXEDGE),
		      TRUE, TRUE, 5);

  gtkBoxPackStart (GTKBOX (vbox),
           createBbox (TRUE, "Start (spacing 20)", 20, 85, 20, GTKBUTTONBOXSTART),
		      TRUE, TRUE, 5);

  gtkBoxPackStart (GTKBOX (vbox),
	   createBbox (TRUE, "End (spacing 10)", 10, 85, 20, GTKBUTTONBOXEND),
		      TRUE, TRUE, 5);

  frameVert = gtkFrameNew ("Vertical Button Boxes");
  gtkBoxPackStart (GTKBOX (mainVbox), frameVert, TRUE, TRUE, 10);

  hbox = gtkHboxNew (FALSE, 0);
  gtkContainerSetBorderWidth (GTKCONTAINER (hbox), 10);
  gtkContainerAdd (GTKCONTAINER (frameVert), hbox);

  gtkBoxPackStart (GTKBOX (hbox),
           createBbox (FALSE, "Spread (spacing 5)", 5, 85, 20, GTKBUTTONBOXSPREAD),
		      TRUE, TRUE, 0);

  gtkBoxPackStart (GTKBOX (hbox),
           createBbox (FALSE, "Edge (spacing 30)", 30, 85, 20, GTKBUTTONBOXEDGE),
		      TRUE, TRUE, 5);

  gtkBoxPackStart (GTKBOX (hbox),
           createBbox (FALSE, "Start (spacing 20)", 20, 85, 20, GTKBUTTONBOXSTART),
		      TRUE, TRUE, 5);

  gtkBoxPackStart (GTKBOX (hbox),
           createBbox (FALSE, "End (spacing 20)", 20, 85, 20, GTKBUTTONBOXEND),
		      TRUE, TRUE, 5);

  gtkWidgetShowAll (window);

  # Enter the event loop 
  gtkMain ();
    
  return 0;
}
<!-- example-end -->
</programlisting>

</sect1>

<!-- ----------------------------------------------------------------- -->   
<sect1 id="sec-Toolbar">
<title>Toolbar</title>

<para>Toolbars are usually used to group some number of widgets in order to
simplify customization of their look and layout. Typically a toolbar
consists of buttons with icons, labels and tooltips, but any other
widget can also be put inside a toolbar. Finally, items can be
arranged horizontally or vertically and buttons can be displayed with
icons, labels, or both.</para>

<para>Creating a toolbar is (as one may already suspect) done with the
following function:</para>

<programlisting role="R">
GtkWidget#gtkToolbarNew( void );
</programlisting>

<para>After creating a toolbar one can append, prepend and insert items
(that means simple text strings) or elements (that means any widget
types) into the toolbar. To describe an item we need a label text, a
tooltip text, a private tooltip text, an icon for the button and a
callback function for it. For example, to append or prepend an item
you may use the following functions:</para>

<programlisting role="R">
GtkWidget#gtkToolbarAppendItem( GtkToolbar   #toolbar,
                                    const char   #text,
                                    const char   #tooltipText,
                                    const char   #tooltipPrivateText,
                                    GtkWidget    #icon,
                                    GtkSignalFunc  callback,
                                    gpointer       userData );

GtkWidget#gtkToolbarPrependItem( GtkToolbar   #toolbar,
                                     const char   #text,
                                     const char   #tooltipText,
                                     const char   #tooltipPrivateText,
                                     GtkWidget    #icon,
                                     GtkSignalFunc  callback,
                                     gpointer       userData );
</programlisting>

<para>If you want to use gtkToolbarInsertItem(), the only additional
parameter which must be specified is the position in which the item
should be inserted, thus:</para>

<programlisting role="R">
GtkWidget#gtkToolbarInsertItem( GtkToolbar   #toolbar,
                                    const char   #text,
                                    const char   #tooltipText,
                                    const char   #tooltipPrivateText,
                                    GtkWidget    #icon,
                                    GtkSignalFunc  callback,
                                    gpointer       userData,
                                    gint           position );
</programlisting>

<para>To simplify adding spaces between toolbar items, you may use the
following functions:</para>

<programlisting role="R">
void gtkToolbarAppendSpace( GtkToolbar#toolbar );

void gtkToolbarPrependSpace( GtkToolbar#toolbar );

void gtkToolbarInsertSpace( GtkToolbar#toolbar,
                               gint        position );
</programlisting>

<para>If it's required, the orientation of a toolbar and its style can be
changed "on the fly" using the following functions:</para>

<programlisting role="R">
void gtkToolbarSetOrientation( GtkToolbar    #toolbar,
                                  GtkOrientation  orientation );

void gtkToolbarSetStyle( GtkToolbar     #toolbar,
                            GtkToolbarStyle  style );

void gtkToolbarSetTooltips( GtkToolbar#toolbar,
                               gint        enable );
</programlisting>

<para>Where <literal>orientation</literal> is one of <literal>GTKORIENTATIONHORIZONTAL</literal> or
<literal>GTKORIENTATIONVERTICAL</literal>. The <literal>style</literal> is used to set
appearance of the toolbar items by using one of
<literal>GTKTOOLBARICONS</literal>, <literal>GTKTOOLBARTEXT</literal>, or
<literal>GTKTOOLBARBOTH</literal>.</para>

<para>To show some other things that can be done with a toolbar, let's take
the following program (we'll interrupt the listing with some
additional explanations):</para>

<programlisting role="R">
#include &lt;gtk/gtk.h&gt;

# This function is connected to the Close button or
# closing the window from the WM 
static gboolean deleteEvent( GtkWidget#widget,
                              GdkEvent#event,
                              gpointer data )
{
  gtkMainQuit ();
  return FALSE;
}
</programlisting>

<para>The above beginning seems for sure familiar to you if it's not your first
GTK program. There is one additional thing though, we include a nice XPM
picture to serve as an icon for all of the buttons.</para>

<programlisting role="R">
GtkWidget* closeButton; # This button will emit signal to close
                         # application 
GtkWidget* tooltipsButton; # to enable/disable tooltips 
GtkWidget* textButton,
        # iconButton,
        # bothButton; # radio buttons for toolbar style 
GtkWidget* entry; # a text entry to show packing any widget into
                  # toolbar 
</programlisting>

<para>In fact not all of the above widgets are needed here, but to make things
clearer I put them all together.</para>

<programlisting role="R">
# that's easy... when one of the buttons is toggled, we just
# check which one is active and set the style of the toolbar
# accordingly
# ATTENTION: our toolbar is passed as data to callback ! 
static void radioEvent( GtkWidget#widget,
                         gpointer data )
{
  if (GTKTOGGLEBUTTON (textButton)->active) 
    gtkToolbarSetStyle (GTKTOOLBAR (data), GTKTOOLBARTEXT);
  else if (GTKTOGGLEBUTTON (iconButton)->active)
    gtkToolbarSetStyle (GTKTOOLBAR (data), GTKTOOLBARICONS);
  else if (GTKTOGGLEBUTTON (bothButton)->active)
    gtkToolbarSetStyle (GTKTOOLBAR (data), GTKTOOLBARBOTH);
}

# even easier, just check given toggle button and enable/disable 
# tooltips 
static void toggleEvent( GtkWidget#widget,
                          gpointer   data )
{
  gtkToolbarSetTooltips (GTKTOOLBAR (data),
                            GTKTOGGLEBUTTON (widget)->active );
}
</programlisting>

<para>The above are just two callback functions that will be called when
one of the buttons on a toolbar is pressed. You should already be
familiar with things like this if you've already used toggle buttons (and
radio buttons).</para>

<programlisting role="R">
int main (int argc, char#argv[])
{
  # Here is our main window (a dialog) and a handle for the handlebox 
  GtkWidget* dialog;
  GtkWidget* handlebox;

  # Ok, we need a toolbar, an icon with a mask (one for all of 
     the buttons) and an icon widget to put this icon in (but 
     we'll create a separate widget for each button) 
  GtkWidget# toolbar;
  GtkWidget# iconw;

  # this is called in all GTK application. 
  gtkInit (&amp;argc, &amp;argv);
  
  # create a new window with a given title, and nice size 
  dialog = gtkDialogNew ();
  gtkWindowSetTitle (GTKWINDOW (dialog), "GTKToolbar Tutorial");
  gtkWidgetSetSizeRequest (GTKWIDGET (dialog), 600, 300);
  GTKWINDOW (dialog)->allowShrink = TRUE;

  # typically we quit if someone tries to close us 
  gSignalConnect (GOBJECT (dialog), "deleteEvent",
                    GCALLBACK (deleteEvent), NULL);

  # we need to realize the window because we use pixmaps for 
  # items on the toolbar in the context of it 
  gtkWidgetRealize (dialog);

  # to make it nice we'll put the toolbar into the handle box, 
  # so that it can be detached from the main window 
  handlebox = gtkHandleBoxNew ();
  gtkBoxPackStart (GTKBOX (GTKDIALOG (dialog)->vbox),
                      handlebox, FALSE, FALSE, 5);
</programlisting>

<para>The above should be similar to any other GTK application. Just
initialization of GTK, creating the window, etc. There is only one
thing that probably needs some explanation: a handle box. A handle box
is just another box that can be used to pack widgets in to. The
difference between it and typical boxes is that it can be detached
from a parent window (or, in fact, the handle box remains in the
parent, but it is reduced to a very small rectangle, while all of its
contents are reparented to a new freely floating window). It is
usually nice to have a detachable toolbar, so these two widgets occur
together quite often.</para>

<programlisting role="R">
  # toolbar will be horizontal, with both icons and text, and
  # with 5pxl spaces between items and finally, 
  # we'll also put it into our handlebox 
  toolbar = gtkToolbarNew ();
  gtkToolbarSetOrientation (GTKTOOLBAR (toolbar), GTKORIENTATIONHORIZONTAL);
  gtkToolbarSetStyle (GTKTOOLBAR (toolbar), GTKTOOLBARBOTH);
  gtkContainerSetBorderWidth (GTKCONTAINER (toolbar), 5);
  gtkToolbarSetSpaceSize (GTKTOOLBAR (toolbar), 5);
  gtkContainerAdd (GTKCONTAINER (handlebox), toolbar);
</programlisting>

<para>Well, what we do above is just a straightforward initialization of
the toolbar widget.</para>

<programlisting role="R">
  # our first item is &lt;close&gt; button 
  iconw = gtkImageNewFromFile ("gtk.xpm"); # icon widget 
  closeButton = 
    gtkToolbarAppendItem (GTKTOOLBAR (toolbar), # our toolbar 
                             "Close",               # button label 
                             "Closes this app",     # this button's tooltip 
                             "Private",             # tooltip private info 
                             iconw,                 # icon widget 
                             GTKSIGNALFUNC (deleteEvent), # a signal 
                             NULL);
  gtkToolbarAppendSpace (GTKTOOLBAR (toolbar)); # space after item 
</programlisting>

<para>In the above code you see the simplest case: adding a button to
toolbar.  Just before appending a new item, we have to construct an
image widget to serve as an icon for this item; this step will have
to be repeated for each new item. Just after the item we also add a
space, so the following items will not touch each other. As you see
gtkToolbarAppendItem() returns a pointer to our newly created button
widget, so that we can work with it in the normal way.</para>

<programlisting role="R">
  # now, let's make our radio buttons group... 
  iconw = gtkImageNewFromFile ("gtk.xpm");
  iconButton = gtkToolbarAppendElement (
                    GTKTOOLBAR (toolbar),
                    GTKTOOLBARCHILDRADIOBUTTON, # a type of element 
                    NULL,                          # pointer to widget 
                    "Icon",                        # label 
                    "Only icons in toolbar",       # tooltip 
                    "Private",                     # tooltip private string 
                    iconw,                         # icon 
                    GTKSIGNALFUNC (radioEvent), # signal 
                    toolbar);                      # data for signal 
  gtkToolbarAppendSpace (GTKTOOLBAR (toolbar));
</programlisting>

<para>Here we begin creating a radio buttons group. To do this we use
gtkToolbarAppendElement.  In fact, using this function one can also
+add simple items or even spaces (type = <literal>GTKTOOLBARCHILDSPACE</literal>
or +<literal>GTKTOOLBARCHILDBUTTON</literal>). In the above case we start
creating a radio group. In creating other radio buttons for this group
a pointer to the previous button in the group is required, so that a
list of buttons can be easily constructed (see the section on <link
linkend="sec-RadioButtons">Radio Buttons</link> earlier in this
tutorial).</para>

<programlisting role="R">
  # following radio buttons refer to previous ones 
  iconw = gtkImageNewFromFile ("gtk.xpm");
  textButton = 
    gtkToolbarAppendElement (GTKTOOLBAR (toolbar),
                                GTKTOOLBARCHILDRADIOBUTTON,
                                iconButton,
                                "Text",
                                "Only texts in toolbar",
                                "Private",
                                iconw,
                                GTKSIGNALFUNC (radioEvent),
                                toolbar);
  gtkToolbarAppendSpace (GTKTOOLBAR (toolbar));
                                          
  iconw = gtkImageNewFromFile ("gtk.xpm");
  bothButton = 
    gtkToolbarAppendElement (GTKTOOLBAR (toolbar),
                                GTKTOOLBARCHILDRADIOBUTTON,
                                textButton,
                                "Both",
                                "Icons and text in toolbar",
                                "Private",
                                iconw,
                                GTKSIGNALFUNC (radioEvent),
                                toolbar);
  gtkToolbarAppendSpace (GTKTOOLBAR (toolbar));
  gtkToggleButtonSetActive (GTKTOGGLEBUTTON (bothButton), TRUE);
</programlisting>

<para>In the end we have to set the state of one of the buttons manually
(otherwise they all stay in active state, preventing us from switching
between them).</para>

<programlisting role="R">
  # here we have just a simple toggle button 
  iconw = gtkImageNewFromFile ("gtk.xpm");
  tooltipsButton = 
    gtkToolbarAppendElement (GTKTOOLBAR (toolbar),
                                GTKTOOLBARCHILDTOGGLEBUTTON,
                                NULL,
                                "Tooltips",
                                "Toolbar with or without tips",
                                "Private",
                                iconw,
                                GTKSIGNALFUNC (toggleEvent),
                                toolbar);
  gtkToolbarAppendSpace (GTKTOOLBAR (toolbar));
  gtkToggleButtonSetActive (GTKTOGGLEBUTTON (tooltipsButton), TRUE);
</programlisting>

<para>A toggle button can be created in the obvious way (if one knows how to create
radio buttons already).</para>

<programlisting role="R">
  # to pack a widget into toolbar, we only have to 
  # create it and append it with an appropriate tooltip 
  entry = gtkEntryNew ();
  gtkToolbarAppendWidget (GTKTOOLBAR (toolbar), 
                             entry, 
                             "This is just an entry", 
                             "Private");

  # well, it isn't created within the toolbar, so we must still show it 
  gtkWidgetShow (entry);
</programlisting>

<para>As you see, adding any kind of widget to a toolbar is simple. The
one thing you have to remember is that this widget must be shown manually
(contrary to other items which will be shown together with the toolbar).</para>

<programlisting role="R">
  # that's it ! let's show everything. 
  gtkWidgetShow (toolbar);
  gtkWidgetShow (handlebox);
  gtkWidgetShow (dialog);

  # rest in gtkMain and wait for the fun to begin! 
  gtkMain ();
  
  return 0;
}
</programlisting>

<para>So, here we are at the end of toolbar tutorial. Of course, to appreciate
it in full you need also this nice XPM icon, so here it is:</para>

<programlisting role="R">
# XPM 
static char# gtkXpm[] = {
"32 39 5 1",
".      c none",
"+      c black",
"@      c #3070E0",
"#      c #F05050",
"$      c #35E035",
"................+...............",
"..............+++++.............",
"............+++++@@++...........",
"..........+++++@@@@@@++.........",
"........++++@@@@@@@@@@++........",
"......++++@@++++++++@@@++.......",
".....+++@@@+++++++++++@@@++.....",
"...+++@@@@+++@@@@@@++++@@@@+....",
"..+++@@@@+++@@@@@@@@+++@@@@@++..",
".++@@@@@@+++@@@@@@@@@@@@@@@@@@++",
".+#+@@@@@@++@@@@+++@@@@@@@@@@@@+",
".+##++@@@@+++@@@+++++@@@@@@@@$@.",
".+###++@@@@+++@@@+++@@@@@++$$$@.",
".+####+++@@@+++++++@@@@@+@$$$$@.",
".+#####+++@@@@+++@@@@++@$$$$$$+.",
".+######++++@@@@@@@++@$$$$$$$$+.",
".+#######+##+@@@@+++$$$$$$@@$$+.",
".+###+++##+##+@@++@$$$$$$++$$$+.",
".+###++++##+##+@@$$$$$$$@+@$$@+.",
".+###++++++#+++@$$@+@$$@++$$$@+.",
".+####+++++++#++$$@+@$$++$$$$+..",
".++####++++++#++$$@+@$++@$$$$+..",
".+#####+++++##++$$++@+++$$$$$+..",
".++####+++##+#++$$+++++@$$$$$+..",
".++####+++####++$$++++++@$$$@+..",
".+#####++#####++$$+++@++++@$@+..",
".+#####++#####++$$++@$$@+++$@@..",
".++####++#####++$$++$$$$$+@$@++.",
".++####++#####++$$++$$$$$$$$+++.",
".+++####+#####++$$++$$$$$$$@+++.",
"..+++#########+@$$+@$$$$$$+++...",
"...+++########+@$$$$$$$$@+++....",
".....+++######+@$$$$$$$+++......",
"......+++#####+@$$$$$@++........",
".......+++####+@$$$$+++.........",
".........++###+$$$@++...........",
"..........++##+$@+++............",
"...........+++++++..............",
".............++++..............."};
</programlisting>

</sect1>

<!-- ----------------------------------------------------------------- -->
<sect1 id="sec-Notebooks">
<title>Notebooks</title>

<para>The NoteBook Widget is a collection of "pages" that overlap each
other, each page contains different information with only one page
visible at a time. This widget has become more common lately in GUI
programming, and it is a good way to show blocks of similar
information that warrant separation in their display.</para>

<para>The first function call you will need to know, as you can probably
guess by now, is used to create a new notebook widget.</para>

<programlisting role="R">
GtkWidget#gtkNotebookNew( void );
</programlisting>

<para>Once the notebook has been created, there are a number of functions
that operate on the notebook widget. Let's look at them individually.</para>

<para>The first one we will look at is how to position the page indicators.
These page indicators or "tabs" as they are referred to, can be
positioned in four ways: top, bottom, left, or right.</para>

<programlisting role="R">
void gtkNotebookSetTabPos( GtkNotebook    #notebook,
                               GtkPositionType  pos );
</programlisting>

<para>GtkPositionType will be one of the following, which are pretty self
explanatory:</para>
<programlisting role="R">
  GTKPOSLEFT
  GTKPOSRIGHT
  GTKPOSTOP
  GTKPOSBOTTOM
</programlisting>

<para><literal>GTKPOSTOP</literal> is the default.</para>

<para>Next we will look at how to add pages to the notebook. There are three
ways to add pages to the NoteBook. Let's look at the first two
together as they are quite similar.</para>

<programlisting role="R">
void gtkNotebookAppendPage( GtkNotebook#notebook,
                               GtkWidget  #child,
                               GtkWidget  #tabLabel );

void gtkNotebookPrependPage( GtkNotebook#notebook,
                                GtkWidget  #child,
                                GtkWidget  #tabLabel );
</programlisting>

<para>These functions add pages to the notebook by inserting them from the
back of the notebook (append), or the front of the notebook (prepend).
<literal>child</literal> is the widget that is placed within the notebook page, and
<literal>tabLabel</literal> is the label for the page being added. The <literal>child</literal>
widget must be created separately, and is typically a set of options
setup witin one of the other container widgets, such as a table.</para>

<para>The final function for adding a page to the notebook contains all of
the properties of the previous two, but it allows you to specify what
position you want the page to be in the notebook.</para>

<programlisting role="R">
void gtkNotebookInsertPage( GtkNotebook#notebook,
                               GtkWidget  #child,
                               GtkWidget  #tabLabel,
                               gint         position );
</programlisting>

<para>The parameters are the same as Append and Prepend except it
contains an extra parameter, <literal>position</literal>.  This parameter is used to
specify what place this page will be inserted into the first page
having position zero.</para>

<para>Now that we know how to add a page, lets see how we can remove a page
from the notebook.</para>

<programlisting role="R">
void gtkNotebookRemovePage( GtkNotebook#notebook,
                               gint         pageNum );
</programlisting>

<para>This function takes the page specified by <literal>pageNum</literal> and removes it
from the widget pointed to by <literal>notebook</literal>.</para>

<para>To find out what the current page is in a notebook use the function:</para>

<programlisting role="R">
gint gtkNotebookGetCurrentPage( GtkNotebook#notebook );
</programlisting>

<para>These next two functions are simple calls to move the notebook page
forward or backward. Simply provide the respective function call with
the notebook widget you wish to operate on. Note: When the NoteBook is
currently on the last page, and gtkNotebookNextPage() is called, the
notebook will wrap back to the first page. Likewise, if the NoteBook
is on the first page, and gtkNotebookPrevPage() is called, the
notebook will wrap to the last page.</para>

<programlisting role="R">
void gtkNotebookNextPage( GtkNoteBook#notebook );

void gtkNotebookPrevPage( GtkNoteBook#notebook );
</programlisting>

<para>This next function sets the "active" page. If you wish the notebook to
be opened to page 5 for example, you would use this function.  Without
using this function, the notebook defaults to the first page.</para>

<programlisting role="R">
void gtkNotebookSetCurrentPage( GtkNotebook#notebook,
                                    gint         pageNum );
</programlisting>

<para>The next two functions add or remove the notebook page tabs and the
notebook border respectively.</para>

<programlisting role="R">
void gtkNotebookSetShowTabs( GtkNotebook#notebook,
                                 gboolean     showTabs );

void gtkNotebookSetShowBorder( GtkNotebook#notebook,
                                   gboolean     showBorder );
</programlisting>

<para>The next function is useful when the you have a large number of pages,
and the tabs don't fit on the page. It allows the tabs to be scrolled
through using two arrow buttons.</para>

<programlisting role="R">
void gtkNotebookSetScrollable( GtkNotebook#notebook,
                                  gboolean     scrollable );
</programlisting>

<para><literal>showTabs</literal>, <literal>showBorder</literal> and <literal>scrollable</literal> can be either
TRUE or FALSE.</para>

<para>Now let's look at an example, it is expanded from the 
<filename>testgtk.c</filename> code
that comes with the GTK distribution. This small program creates a
window with a notebook and six buttons. The notebook contains 11
pages, added in three different ways, appended, inserted, and
prepended. The buttons allow you rotate the tab positions, add/remove
the tabs and border, remove a page, change pages in both a forward and
backward manner, and exit the program.</para>

<para>
<inlinemediaobject>
<imageobject>
<imagedata fileref="images/notebook.png" format="png">
</imageobject>
</inlinemediaobject>
</para>

<programlisting role="R">
<!-- example-start notebook notebook.c -->

#include &lt;stdio.h&gt;
#include &lt;gtk/gtk.h&gt;

# This function rotates the position of the tabs 
static void rotateBook( GtkButton  #button,
                         GtkNotebook#notebook )
{
    gtkNotebookSetTabPos (notebook, (notebook-&gt;tabPos + 1) % 4);
}

# Add/Remove the page tabs and the borders 
static void tabsborderBook( GtkButton  #button,
                             GtkNotebook#notebook )
{
    gint tval = FALSE;
    gint bval = FALSE;
    if (notebook-&gt;showTabs == 0)
	    tval = TRUE; 
    if (notebook-&gt;showBorder == 0)
	    bval = TRUE;
    
    gtkNotebookSetShowTabs (notebook, tval);
    gtkNotebookSetShowBorder (notebook, bval);
}

# Remove a page from the notebook 
static void removeBook( GtkButton  #button,
                         GtkNotebook#notebook )
{
    gint page;
    
    page = gtkNotebookGetCurrentPage (notebook);
    gtkNotebookRemovePage (notebook, page);
    # Need to refresh the widget -- 
     This forces the widget to redraw itself. 
    gtkWidgetQueueDraw (GTKWIDGET (notebook));
}

static gboolean delete( GtkWidget#widget,
                        GtkWidget#event,
                        gpointer   data )
{
    gtkMainQuit ();
    return FALSE;
}

int main( int argc,
          char#argv[] )
{
    GtkWidget#window;
    GtkWidget#button;
    GtkWidget#table;
    GtkWidget#notebook;
    GtkWidget#frame;
    GtkWidget#label;
    GtkWidget#checkbutton;
    int i;
    char bufferf[32];
    char bufferl[32];
    
    gtkInit (&amp;argc, &amp;argv);
    
    window = gtkWindowNew (GTKWINDOWTOPLEVEL);
    
    gSignalConnect (GOBJECT (window), "deleteEvent",
	              GCALLBACK (delete), NULL);
    
    gtkContainerSetBorderWidth (GTKCONTAINER (window), 10);

    table = gtkTableNew (3, 6, FALSE);
    gtkContainerAdd (GTKCONTAINER (window), table);
    
    # Create a new notebook, place the position of the tabs 
    notebook = gtkNotebookNew ();
    gtkNotebookSetTabPos (GTKNOTEBOOK (notebook), GTKPOSTOP);
    gtkTableAttachDefaults (GTKTABLE (table), notebook, 0, 6, 0, 1);
    gtkWidgetShow (notebook);
    
    # Let's append a bunch of pages to the notebook 
    for (i = 0; i &lt; 5; i++) {
	sprintf(bufferf, "Append Frame %d", i + 1);
	sprintf(bufferl, "Page %d", i + 1);
	
	frame = gtkFrameNew (bufferf);
	gtkContainerSetBorderWidth (GTKCONTAINER (frame), 10);
	gtkWidgetSetSizeRequest (frame, 100, 75);
	gtkWidgetShow (frame);
	
	label = gtkLabelNew (bufferf);
	gtkContainerAdd (GTKCONTAINER (frame), label);
	gtkWidgetShow (label);
	
	label = gtkLabelNew (bufferl);
	gtkNotebookAppendPage (GTKNOTEBOOK (notebook), frame, label);
    }
      
    # Now let's add a page to a specific spot 
    checkbutton = gtkCheckButtonNewWithLabel ("Check me please!");
    gtkWidgetSetSizeRequest (checkbutton, 100, 75);
    gtkWidgetShow (checkbutton);
   
    label = gtkLabelNew ("Add page");
    gtkNotebookInsertPage (GTKNOTEBOOK (notebook), checkbutton, label, 2);
    
    # Now finally let's prepend pages to the notebook 
    for (i = 0; i &lt; 5; i++) {
	sprintf (bufferf, "Prepend Frame %d", i + 1);
	sprintf (bufferl, "PPage %d", i + 1);
	
	frame = gtkFrameNew (bufferf);
	gtkContainerSetBorderWidth (GTKCONTAINER (frame), 10);
	gtkWidgetSetSizeRequest (frame, 100, 75);
	gtkWidgetShow (frame);
	
	label = gtkLabelNew (bufferf);
	gtkContainerAdd (GTKCONTAINER (frame), label);
	gtkWidgetShow (label);
	
	label = gtkLabelNew (bufferl);
	gtkNotebookPrependPage (GTKNOTEBOOK (notebook), frame, label);
    }
    
    # Set what page to start at (page 4) 
    gtkNotebookSetCurrentPage (GTKNOTEBOOK (notebook), 3);

    # Create a bunch of buttons 
    button = gtkButtonNewWithLabel ("close");
    gSignalConnectSwapped (GOBJECT (button), "clicked",
			      GCALLBACK (delete), NULL);
    gtkTableAttachDefaults (GTKTABLE (table), button, 0, 1, 1, 2);
    gtkWidgetShow (button);
    
    button = gtkButtonNewWithLabel ("next page");
    gSignalConnectSwapped (GOBJECT (button), "clicked",
			      GCALLBACK (gtkNotebookNextPage),
			      GOBJECT (notebook));
    gtkTableAttachDefaults (GTKTABLE (table), button, 1, 2, 1, 2);
    gtkWidgetShow (button);
    
    button = gtkButtonNewWithLabel ("prev page");
    gSignalConnectSwapped (GOBJECT (button), "clicked",
			      GCALLBACK (gtkNotebookPrevPage),
			      GOBJECT (notebook));
    gtkTableAttachDefaults (GTKTABLE (table), button, 2, 3, 1, 2);
    gtkWidgetShow (button);
    
    button = gtkButtonNewWithLabel ("tab position");
    gSignalConnect (GOBJECT (button), "clicked",
                      GCALLBACK (rotateBook),
	              (gpointer) notebook);
    gtkTableAttachDefaults (GTKTABLE (table), button, 3, 4, 1, 2);
    gtkWidgetShow (button);
    
    button = gtkButtonNewWithLabel ("tabs/border on/off");
    gSignalConnect (GOBJECT (button), "clicked",
                      GCALLBACK (tabsborderBook),
                      (gpointer) notebook);
    gtkTableAttachDefaults (GTKTABLE (table), button, 4, 5, 1, 2);
    gtkWidgetShow (button);
    
    button = gtkButtonNewWithLabel ("remove page");
    gSignalConnect (GOBJECT (button), "clicked",
                      GCALLBACK (removeBook),
                      (gpointer) notebook);
    gtkTableAttachDefaults (GTKTABLE (table), button, 5, 6, 1, 2);
    gtkWidgetShow (button);
    
    gtkWidgetShow (table);
    gtkWidgetShow (window);
    
    gtkMain ();
    
    return 0;
}
<!-- example-end -->
</programlisting>

<para>I hope this helps you on your way with creating notebooks for your
GTK applications.</para>

</sect1>
</chapter>

<!--**************************************************************** -->
<chapter id="ch-MenuWidget">
<title>Menu Widget</title>

<para>There are two ways to create menus: there's the easy way, and there's
the hard way. Both have their uses, but you can usually use the
Itemfactory (the easy way). The "hard" way is to create all the menus
using the calls directly. The easy way is to use the gtkItemFactory
calls. This is much simpler, but there are advantages and
disadvantages to each approach.</para>

<para>The Itemfactory is much easier to use, and to add new menus to,
although writing a few wrapper functions to create menus using the
manual method could go a long way towards usability. With the
Itemfactory, it is not possible to add images or the character '/' to
the menus.</para>

<!-- ----------------------------------------------------------------- -->
<sect1 id="sec-ManualMenuCreation">
<title>Manual Menu Creation</title>

<para>In the true tradition of teaching, we'll show you the hard way
first. <literal>:)</literal></para>

<para>There are three widgets that go into making a menubar and submenus:</para>

<itemizedlist>
<listitem><simpara>a menu item, which is what the user wants to select, e.g.,
"Save"</simpara>
</listitem>
<listitem><simpara>a menu, which acts as a container for the menu items, and</simpara>
</listitem>
<listitem><simpara>a menubar, which is a container for each of the individual
menus.</simpara>
</listitem>
</itemizedlist>

<para>This is slightly complicated by the fact that menu item widgets are
used for two different things. They are both the widgets that are
packed into the menu, and the widget that is packed into the menubar,
which, when selected, activates the menu.</para>

<para>Let's look at the functions that are used to create menus and
menubars.  This first function is used to create a new menubar.</para>

<programlisting role="R">
GtkWidget#gtkMenuBarNew( void );
</programlisting>

<para>This rather self explanatory function creates a new menubar. You use
gtkContainerAdd() to pack this into a window, or the boxPack
functions to pack it into a box - the same as buttons.</para>

<programlisting role="R">
GtkWidget#gtkMenuNew( void );
</programlisting>

<para>This function returns a pointer to a new menu; it is never actually
shown (with gtkWidgetShow()), it is just a container for the menu
items. I hope this will become more clear when you look at the
example below.</para>

<para>The next three calls are used to create menu items that are packed into
the menu (and menubar).</para>

<programlisting role="R">
GtkWidget#gtkMenuItemNew( void );

GtkWidget#gtkMenuItemNewWithLabel( const char#label );

GtkWidget#gtkMenuItemNewWithMnemnonic( const char#label );
</programlisting>

<para>These calls are used to create the menu items that are to be
displayed.  Remember to differentiate between a "menu" as created with
gtkMenuNew() and a "menu item" as created by the gtkMenuItemNew()
functions. The menu item will be an actual button with an associated
action, whereas a menu will be a container holding menu items.</para>

<para>The gtkMenuItemNewWithLabel() and gtkMenuItemNew() functions are just as
you'd expect after reading about the buttons. One creates a new menu
item with a label already packed into it, and the other just creates a
blank menu item.</para>

<para>Once you've created a menu item you have to put it into a menu. This
is done using the function gtkMenuShelllAppend. In order to capture when
the item is selected by the user, we need to connect to the
<literal>activate</literal> signal in the usual way. So, if we wanted to create a
standard <literal>File</literal> menu, with the options <literal>Open</literal>, <literal>Save</literal>, and
<literal>Quit</literal>, the code would look something like:</para>

<programlisting role="R">
    fileMenu = gtkMenuNew ();    # Don't need to show menus 

    # Create the menu items 
    openItem = gtkMenuItemNewWithLabel ("Open");
    saveItem = gtkMenuItemNewWithLabel ("Save");
    quitItem = gtkMenuItemNewWithLabel ("Quit");

    # Add them to the menu 
    gtkMenuShellAppend (GTKMENUSHELL (fileMenu), openItem);
    gtkMenuShellAppend (GTKMENUSHELL (fileMenu), saveItem);
    gtkMenuShellAppend (GTKMENUSHELL (fileMenu), quitItem);

    # Attach the callback functions to the activate signal 
    gSignalConnectSwapped (GOBJECT (openItem), "activate",
                              GCALLBACK (menuitemResponse),
                              (gpointer) "file.open");
    gSignalConnectSwapped (GOBJECT (saveItem), "activate",
                              GCALLBACK (menuitemResponse),
                              (gpointer) "file.save");

    # We can attach the Quit menu item to our exit function 
    gSignalConnectSwapped (GOBJECT (quitItem), "activate",
                              GCALLBACK (destroy),
                              (gpointer) "file.quit");

    # We do need to show menu items 
    gtkWidgetShow (openItem);
    gtkWidgetShow (saveItem);
    gtkWidgetShow (quitItem);
</programlisting>

<para>At this point we have our menu. Now we need to create a menubar and a
menu item for the <literal>File</literal> entry, to which we add our menu. The code
looks like this:</para>

<programlisting role="R">
    menuBar = gtkMenuBarNew ();
    gtkContainerAdd (GTKCONTAINER (window), menuBar);
    gtkWidgetShow (menuBar);

    fileItem = gtkMenuItemNewWithLabel ("File");
    gtkWidgetShow (fileItem);
</programlisting>

<para>Now we need to associate the menu with <literal>fileItem</literal>. This is done
with the function</para>

<programlisting role="R">
void gtkMenuItemSetSubmenu( GtkMenuItem#menuItem,
                                GtkWidget  #submenu );
</programlisting>

<para>So, our example would continue with</para>

<programlisting role="R">
    gtkMenuItemSetSubmenu (GTKMENUITEM (fileItem), fileMenu);
</programlisting>

<para>All that is left to do is to add the menu to the menubar, which is
accomplished using the function</para>

<programlisting role="R">
void gtkMenuBarAppend( GtkMenuBar#menuBar,
                          GtkWidget #menuItem );
</programlisting>

<para>which in our case looks like this:</para>

<programlisting role="R">
    gtkMenuBarAppend (GTKMENUBAR (menuBar), fileItem);
</programlisting>

<para>If we wanted the menu right justified on the menubar, such as help
menus often are, we can use the following function (again on
<literal>fileItem</literal> in the current example) before attaching it to the
menubar.</para>

<programlisting role="R">
void gtkMenuItemRightJustify( GtkMenuItem#menuItem );
</programlisting>

<para>Here is a summary of the steps needed to create a menu bar with menus
attached:</para>

<itemizedlist>
<listitem><simpara> Create a new menu using gtkMenuNew()</simpara>
</listitem>

<listitem><simpara> Use multiple calls to gtkMenuItemNew() for each item you
wish to have on your menu. And use gtkMenuShellAppend() to put each of
these new items on to the menu.</simpara>
</listitem>

<listitem><simpara> Create a menu item using gtkMenuItemNew(). This will be the
root of the menu, the text appearing here will be on the menubar
itself.</simpara>
</listitem>

<listitem><simpara>Use gtkMenuItemSetSubmenu() to attach the menu to the root
menu item (the one created in the above step).</simpara>
</listitem>

<listitem><simpara> Create a new menubar using gtkMenuBarNew. This step only
needs to be done once when creating a series of menus on one menu bar.</simpara>
</listitem>

<listitem><simpara> Use gtkMenuBarAppend() to put the root menu onto the menubar.</simpara>
</listitem>
</itemizedlist>

<para>Creating a popup menu is nearly the same. The difference is that the
menu is not posted "automatically" by a menubar, but explicitly by
calling the function gtkMenuPopup() from a button-press event, for
example.  Take these steps:</para>

<itemizedlist>
<listitem><simpara>Create an event handling function. It needs to have the
prototype</simpara>
<programlisting role="R">
static gboolean handler( GtkWidget#widget,
                         GdkEvent #event );
</programlisting>
<simpara>and it will use the event to find out where to pop up the menu.</simpara>
</listitem>

<listitem><simpara>In the event handler, if the event is a mouse button press,
treat <literal>event</literal> as a button event (which it is) and use it as
shown in the sample code to pass information to gtkMenuPopup().</simpara>
</listitem>

<listitem><simpara>Bind that event handler to a widget with</simpara>
<programlisting role="R">
    gSignalConnectSwapped (GOBJECT (widget), "event",
                              GCALLBACK (handler),
                              GOBJECT (menu));
</programlisting>
<simpara>where <literal>widget</literal> is the widget you are binding to,
<literal>handler</literal> is the handling function, and <literal>menu</literal> is a menu
created with gtkMenuNew(). This can be a menu which is also posted
by a menu bar, as shown in the sample code.</simpara>
</listitem>
</itemizedlist>

</sect1>

<!-- ----------------------------------------------------------------- -->
<sect1 id="sec-ManualMenuExample">
<title>Manual Menu Example</title>

<para>That should about do it. Let's take a look at an example to help clarify.</para>

<para>
<inlinemediaobject>
<imageobject>
<imagedata fileref="images/menu.png" format="png">
</imageobject>
</inlinemediaobject>
</para>

<programlisting role="R">
<!-- example-start menu menu.c -->

#include &lt;stdio.h&gt;
#include &lt;gtk/gtk.h&gt;

static gboolean buttonPress (GtkWidget#, GdkEvent#);
static void menuitemResponse (gchar#);

int main( int   argc,
          char#argv[] )
{

    GtkWidget#window;
    GtkWidget#menu;
    GtkWidget#menuBar;
    GtkWidget#rootMenu;
    GtkWidget#menuItems;
    GtkWidget#vbox;
    GtkWidget#button;
    char buf[128];
    int i;

    gtkInit (&amp;argc, &amp;argv);

    # create a new window 
    window = gtkWindowNew (GTKWINDOWTOPLEVEL);
    gtkWidgetSetSizeRequest (GTKWIDGET (window), 200, 100);
    gtkWindowSetTitle (GTKWINDOW (window), "GTK Menu Test");
    gSignalConnect (GOBJECT (window), "deleteEvent",
                      GCALLBACK (gtkMainQuit), NULL);

    # Init the menu-widget, and remember -- never
    # gtkShowWidget() the menu widget!! 
    # This is the menu that holds the menu items, the one that
    # will pop up when you click on the "Root Menu" in the app 
    menu = gtkMenuNew ();

    # Next we make a little loop that makes three menu-entries for "test-menu".
    # Notice the call to gtkMenuShellAppend.  Here we are adding a list of
    # menu items to our menu.  Normally, we'd also catch the "clicked"
    # signal on each of the menu items and setup a callback for it,
    # but it's omitted here to save space. 

    for (i = 0; i &lt; 3; i++)
        {
            # Copy the names to the buf. 
            sprintf (buf, "Test-undermenu - %d", i);

            # Create a new menu-item with a name... 
            menuItems = gtkMenuItemNewWithLabel (buf);

            # ...and add it to the menu. 
            gtkMenuShellAppend (GTKMENUSHELL (menu), menuItems);

	    # Do something interesting when the menuitem is selected 
	    gSignalConnectSwapped (GOBJECT (menuItems), "activate",
		                      GCALLBACK (menuitemResponse), 
                                      (gpointer) gStrdup (buf));

            # Show the widget 
            gtkWidgetShow (menuItems);
        }

    # This is the root menu, and will be the label
    # displayed on the menu bar.  There won't be a signal handler attached,
    # as it only pops up the rest of the menu when pressed. 
    rootMenu = gtkMenuItemNewWithLabel ("Root Menu");

    gtkWidgetShow (rootMenu);

    # Now we specify that we want our newly created "menu" to be the menu
    # for the "root menu" 
    gtkMenuItemSetSubmenu (GTKMENUITEM (rootMenu), menu);

    # A vbox to put a menu and a button in: 
    vbox = gtkVboxNew (FALSE, 0);
    gtkContainerAdd (GTKCONTAINER (window), vbox);
    gtkWidgetShow (vbox);

    # Create a menu-bar to hold the menus and add it to our main window 
    menuBar = gtkMenuBarNew ();
    gtkBoxPackStart (GTKBOX (vbox), menuBar, FALSE, FALSE, 2);
    gtkWidgetShow (menuBar);

    # Create a button to which to attach menu as a popup 
    button = gtkButtonNewWithLabel ("press me");
    gSignalConnectSwapped (GOBJECT (button), "event",
	                      GCALLBACK (buttonPress), 
                              GOBJECT (menu));
    gtkBoxPackEnd (GTKBOX (vbox), button, TRUE, TRUE, 2);
    gtkWidgetShow (button);

    # And finally we append the menu-item to the menu-bar -- this is the
    # "root" menu-item I have been raving about =) 
    gtkMenuShellAppend (GTKMENUSHELL (menuBar), rootMenu);

    # always display the window as the last step so it all splashes on
    # the screen at once. 
    gtkWidgetShow (window);

    gtkMain ();

    return 0;
}

# Respond to a button-press by posting a menu passed in as widget.
#
# Note that the "widget" argument is the menu being posted, NOT
# the button that was pressed.
 

static gboolean buttonPress( GtkWidget#widget,
                              GdkEvent#event )
{

    if (event-&gt;type == GDKBUTTONPRESS) {
        GdkEventButton#bevent = (GdkEventButton#) event; 
        gtkMenuPopup (GTKMENU (widget), NULL, NULL, NULL, NULL,
                        bevent-&gt;button, bevent-&gt;time);
        # Tell calling code that we have handled this event; the buck
        # stops here. 
        return TRUE;
    }

    # Tell calling code that we have not handled this event; pass it on. 
    return FALSE;
}


# Print a string when a menu item is selected 

static void menuitemResponse( gchar#string )
{
    printf ("%s\n", string);
}
<!-- example-end -->
</programlisting>

<para>You may also set a menu item to be insensitive and, using an accelerator
table, bind keys to menu functions.</para>

</sect1>

<!-- ----------------------------------------------------------------- -->
<sect1 id="sec-UsingItemFactory">
<title>Using ItemFactory</title>

<para>Now that we've shown you the hard way, here's how you do it using the
gtkItemFactory calls.</para>

<para>ItemFactory creates a menu out of an array of ItemFactory entries. This 
means you can define your menu in its simplest form and then create the
menu/menubar widgets with a minimum of function calls.</para>

<!-- ----------------------------------------------------------------- -->
<sect2 id="sec-ItemFactoryEntries">
<title>ItemFactory entries</title>

<para>At the core of ItemFactory is the ItemFactoryEntry. This structure defines
one menu item, and when an array of these entries is defined a whole
menu is formed. The ItemFactory entry struct definition looks like this:</para>

<programlisting role="R">
struct GtkItemFactoryEntry
{
  gchar#path;
  gchar#accelerator;

  GtkItemFactoryCallback callback;
  guint                  callbackAction;

  gchar         #itemType;
};
</programlisting>

<para>Each field defines part of the menu item.</para>

<para><literal>*path</literal> is a string which defines both the name and the
path of a menu item, for example, "/File/Open" would be the name of a menu
item which would come under the ItemFactory entry with path "/File". Note however
that "/File/Open" would be displayed in the File menu as "Open". Also note
since the forward slashes are used to define the path of the menu,
they cannot be used as part of the name. A letter preceded by an underscore
indicates an accelerator (shortcut) key once the menu is open.</para>

<para>
<literal>*accelerator</literal> is a string that indicates a key combination
that can be used as a shortcut to that menu item. The string can be made up
of either a single character, or a combination of modifier keys with a single
character. It is case insensitive.</para>


<para>The available modifier keys are:</para>

<programlisting role="R">
"&lt;ALT&gt;                             - alt
"&lt;CTL&gt;" or "&lt;CTRL&gt;" or "&lt;CONTROL&gt;" - control
"&lt;MOD1&gt;" to "&lt;MOD5&gt;"               - modn
"&lt;SHFT&gt;" or "&lt;SHIFT&gt;"              - shift
</programlisting>

<para>Examples:</para>
<programlisting role="R">
"&lt;ConTroL&gt;a"
"&lt;SHFT&gt;&lt;ALT&gt;&lt;CONTROL&gt;X"
</programlisting>

<para>
<literal>callback</literal> is the function that is called when the menu item
emits the "activate" signal. The form of the callback is described
in the <link linkend="sec-ItemFactoryCallback">Callback Description</link>
section.</para>

<para>
The value of <literal>callbackAction</literal> is passed to the callback
function. It also affects the function prototype, as shown
in the <link linkend="sec-ItemFactoryCallback">Callback Description</link>
section.</para>

<para>
<literal>itemType</literal> is a string that defines what type of widget is
packed into the menu items container. It can be:</para>

<programlisting role="R">
NULL or "" or "&lt;Item&gt;" - create a simple item
"&lt;Title&gt;"              - create a title item
"&lt;CheckItem&gt;"          - create a check item
"&lt;ToggleItem&gt;"         - create a toggle item
"&lt;RadioItem&gt;"          - create a (root) radio item
"Path"                 - create a sister radio item
"&lt;Tearoff&gt;"            - create a tearoff
"&lt;Separator&gt;"          - create a separator
"&lt;Branch&gt;"             - create an item to hold submenus (optional)
"&lt;LastBranch&gt;"         - create a right justified branch
"&lt;StockItem&gt;"          - create a simple item with a stock image. 
                               see <filename>gtkstock.h</filename> for builtin stock items
 
</programlisting>

<para>Note that &lt;LastBranch&gt; is only useful for one submenu of
a menubar.</para>

<!-- ----------------------------------------------------------------- -->
<sect3 id="sec-ItemFactoryCallback">
<title>Callback Description</title>

<para>
The callback for an ItemFactory entry can take two forms. If
<literal>callbackAction</literal> is zero, it is of the following
form:</para>

<programlisting role="R">
void callback( void )
</programlisting>

<para>otherwise it is of the form:</para>

<programlisting role="R">
void callback( gpointer    callbackData,
               guint       callbackAction,
               GtkWidget #widget )
</programlisting>

<para>
<literal>callbackData</literal> is a pointer to an arbitrary piece of data and
is set during the call to gtkItemFactoryCreateItems().</para>

<para>
<literal>callbackAction</literal> is the same value as
<literal>callbackAction</literal> in the ItemFactory entry.</para>

<para>
<literal>*widget</literal> is a pointer to a menu item widget
(described in <link linkend="sec-ManualMenuCreation">Manual Menu Creation</link>).
</para>
</sect3>

<!-- ----------------------------------------------------------------- -->
<sect3 id="sec-ItemFactoryEntryExamples">
<title>ItemFactory entry examples</title>

<para>Creating a simple menu item:</para>

<programlisting role="R">
GtkItemFactoryEntry entry = {"/File/Open...", "&lt;CTRL&gt;O", printHello,
				0, "&lt;Item&gt;"};
</programlisting>

<para>This will define a new simple menu entry "/File/Open" (displayed as "Open"),
under the menu entry "/File". It has the accelerator (shortcut) control+'O'
that when clicked calls the function printHello(). printHello() is of
the form <literal>void printHello(void)</literal> since the callbackAction
field is zero. When displayed the 'O' in "Open" will be underlined and if the
menu item is visible on the screen pressing 'O' will activate the item. Note
that "File/Open" could also have been used as the path instead of
"/File/Open".</para>

<para>Creating an entry with a more complex callback:</para>

<programlisting role="R">
GtkItemFactoryEntry entry = {"/View/Display FPS", NULL, printState,
				7,"&lt;CheckItem&gt;"};
</programlisting>

<para>This defines a new menu item displayed as "Display FPS" which is under
the menu item "View". When clicked the function printState() will be called.
Since <literal>callbackAction</literal> is not zero printState() is of the
form:</para>

<programlisting role="R">
void printState( gpointer    callbackData,
                  guint       callbackAction,
                  GtkWidget #widget )
</programlisting>

<para>with <literal>callbackAction</literal> equal to 7.</para>

<para>Creating a radio button set:</para>

<programlisting role="R">
GtkItemFactoryEntry entry1 = {"/View/Low Resolution", NULL, changeResolution,
				1, "&lt;RadioButton&gt;"};
GtkItemFactoryEntry entry2 = {"/View/High Resolution", NULL, changeResolution,
				2, "/View/Low Resolution"};
</programlisting>

<para><literal>entry1</literal> defines a lone radio button that when toggled
calls the function changeResolution() with the parameter
<literal>callbackAction</literal> equal to 1. changeResolution() is of
the form:</para>

<programlisting role="R">
void changeResolution(gpointer    callbackData,
                       guint       callbackAction,
                       GtkWidget #widget)
</programlisting>

<para><literal>entry2</literal> defines a radio button that belongs to the
radio group that entry1 belongs to. It calls the same function when toggled
but with the parameter <literal>callbackAction</literal> equal to 2. Note that
the itemType of <literal>entry2</literal> is the path of entry1
<emphasis>without</emphasis> the accelerators (''). If another radio button was
required in the same group then it would be defined in the same way as
<literal>entry2</literal> was with its <literal>itemType</literal> again
equal to "/View/Low Resolution".</para>
</sect3>

<!-- ----------------------------------------------------------------- -->
<sect3 id="sec-ItemFactoryEntryArrays">
<title>ItemFactoryEntry Arrays</title>

<para>An ItemFactoryEntry on it's own however isn't useful. An array of
entries is what's required to define a menu. Below is an example of how
you'd declare this array.</para>

<programlisting role="R">
static GtkItemFactoryEntry entries[] = {
  { "/File",         NULL,      NULL,         0, "&lt;Branch&gt;" },
  { "/File/tear1",    NULL,      NULL,         0, "&lt;Tearoff&gt;" },
  { "/File/New",     "&lt;CTRL&gt;N", newFile,     1, "&lt;Item&gt;" },
  { "/File/Open...", "&lt;CTRL&gt;O", openFile,    1, "&lt;Item&gt;" },
  { "/File/sep1",     NULL,      NULL,         0, "&lt;Separator&gt;" },
  { "/File/Quit",    "&lt;CTRL&gt;Q", quitProgram, 0, "&lt;StockItem&gt;", GTKSTOCKQUIT } };
</programlisting>
</sect3>
</sect2>

<!-- ----------------------------------------------------------------- -->
<sect2 id="sec-ItemFactoryCreation">
<title>Creating an ItemFactory</title>

<para>An array of GtkItemFactoryEntry items defines a menu. Once this
array is defined then the item factory can be created. The function that
does this is:</para>

<programlisting role="R">
GtkItemFactory* gtkItemFactoryNew( GtkType        containerType,
                                      const gchar  #path,
                                      GtkAccelGroup#accelGroup );
</programlisting>

<para><literal>containerType</literal> can be one of:</para>

<programlisting role="R">
GTKTYPEMENU
GTKTYPEMENUBAR
GTKTYPEOPTIONMENU
</programlisting>

<para><literal>containerType</literal> defines what type of menu
you want, so when you extract it later it is either a menu (for pop-ups
for instance), a menu bar, or an option menu (like a combo box but with
a menu of pull downs).</para>

<para><literal>path</literal> defines the path of the root of the menu.
Basically it is a unique name for the root of the menu, it must be
surrounded by "&lt;&gt;". This is important for the naming of the
accelerators and should be unique. It should be unique both for each
menu and between each program. For example in a program named 'foo', the
main menu should be called "&lt;FooMain&gt;", and a pop-up menu
"&lt;FooImagePopUp&gt;", or similar. What's important is that they're unique.</para>

<para><literal>accelGroup</literal> is a pointer to a gtkAccelGroup. The
item factory sets up the accelerator table while generating menus. New
accelerator groups are generated by gtkAccelGroupNew().</para>

<para>But this is just the first step. To convert the array of GtkItemFactoryEntry
information into widgets the following function is used:</para>

<programlisting role="R">
void gtkItemFactoryCreateItems( GtkItemFactory     #ifactory,
                                    guint                nEntries,
                                    GtkItemFactoryEntry#entries,
                                    gpointer             callbackData );
</programlisting>

<para><literal>*ifactory</literal> a pointer to the above created item factory.</para>
<para><literal>nEntries</literal> is the number of entries in the
GtkItemFactoryEntry array.</para>
<para><literal>*entries</literal> is a pointer to the GtkItemFactoryEntry array.</para>
<para><literal>callbackData</literal> is what gets passed to all the callback functions
for all the entries with callbackAction != 0.</para>

<para>The accelerator group has now been formed, so you'll probably want
to attach it to the window the menu is in:</para>

<programlisting role="R">
void gtkWindowAddAccelGroup( GtkWindow    #window,
                                 GtkAccelGroup#accelGroup);
</programlisting>
</sect2>

<!-- ----------------------------------------------------------------- -->
<sect2 id="sec-UsingMenuandItems">
<title>Making use of the menu and its menu items</title>

<para>The last thing to do is make use of the menu. The following function
extracts the relevant widgets from the ItemFactory:</para>

<programlisting role="R">
GtkWidget* gtkItemFactoryGetWidget( GtkItemFactory#ifactory,
                                        const gchar   #path );
</programlisting>

<para>For instance if an ItemFactory has two entries "/File" and "/File/New",
using a path of "/File" would retrieve a <emphasis>menu</emphasis> widget from the
ItemFactory. Using a path of "/File/New" would retrieve a
<emphasis>menu item</emphasis> widget. This makes it possible to set the initial state
of menu items. For example to set the default radio
item to the one with the path "/Shape/Oval" then the following code would
be used:</para>

<programlisting role="R">
gtkCheckMenuItemSetActive(
	GTKCHECKMENUITEM (gtkItemFactoryGetItem (itemFactory, "/Shape/Oval")),
	TRUE);
</programlisting>

<para>Finally to retrieve the root of the menu use gtkItemFactoryGetItem()
with a path of "&lt;main&gt;" (or whatever path was used in
gtkItemFactoryNew()). In the case of the ItemFactory being created with
type GTKTYPEMENUBAR this returns a menu bar widget. With type GTKTYPEMENU
a menu widget is returned. With type GTKTYPEOPTIONMENU an option menu
widget is returned.</para>

<para><emphasis>Remember</emphasis> for an entry defined with path "/File"
the path here is actually "/File".</para>

<para>Now you have a menubar or menu which can be manipulated in the same
way as shown in the
<link linkend="sec-ManualMenuCreation">Manual Menu Creation</link>
section.</para>
</sect2>
</sect1>

<!-- ----------------------------------------------------------------- -->
<sect1 id="sec-ItemFactoryExample">
<title>Item Factory Example</title>

<para>Here is an example using the GTK item factory.</para>

<programlisting role="R">
<!-- example-start menu itemfactory.c -->

#include &lt;gtk/gtk.h&gt;

# Obligatory basic callback 
static void printHello( GtkWidget#w,
                         gpointer   data )
{
  gMessage ("Hello, World!\n");
}

# For the check button 
static void printToggle( gpointer   callbackData,
                          guint      callbackAction,
                          GtkWidget#menuItem )
{
   gMessage ("Check button state - %d\n",
              GTKCHECKMENUITEM (menuItem)-&gt;active);
}

# For the radio buttons 
static void printSelected( gpointer   callbackData,
                            guint      callbackAction,
                            GtkWidget#menuItem )
{
   if(GTKCHECKMENUITEM(menuItem)-&gt;active)
     gMessage ("Radio button %d selected\n", callbackAction);
}

# Our menu, an array of GtkItemFactoryEntry structures that defines each menu item 
static GtkItemFactoryEntry menuItems[] = {
  { "/File",         NULL,         NULL,           0, "&lt;Branch&gt;" },
  { "/File/New",     "&lt;control&gt;N", printHello,    0, "&lt;StockItem&gt;", GTKSTOCKNEW },
  { "/File/Open",    "&lt;control&gt;O", printHello,    0, "&lt;StockItem&gt;", GTKSTOCKOPEN },
  { "/File/Save",    "&lt;control&gt;S", printHello,    0, "&lt;StockItem&gt;", GTKSTOCKSAVE },
  { "/File/Save As", NULL,         NULL,           0, "&lt;Item&gt;" },
  { "/File/sep1",     NULL,         NULL,           0, "&lt;Separator&gt;" },
  { "/File/Quit",    "&lt;CTRL&gt;Q", gtkMainQuit, 0, "&lt;StockItem&gt;", GTKSTOCKQUIT },
  { "/Options",      NULL,         NULL,           0, "&lt;Branch&gt;" },
  { "/Options/tear",  NULL,         NULL,           0, "&lt;Tearoff&gt;" },
  { "/Options/Check", NULL,         printToggle,   1, "&lt;CheckItem&gt;" },
  { "/Options/sep",   NULL,         NULL,           0, "&lt;Separator&gt;" },
  { "/Options/Rad1",  NULL,         printSelected, 1, "&lt;RadioItem&gt;" },
  { "/Options/Rad2",  NULL,         printSelected, 2, "/Options/Rad1" },
  { "/Options/Rad3",  NULL,         printSelected, 3, "/Options/Rad1" },
  { "/Help",         NULL,         NULL,           0, "&lt;LastBranch&gt;" },
  { "/Help/About",   NULL,         NULL,           0, "&lt;Item&gt;" },
};

static gint nmenuItems = sizeof (menuItems) / sizeof (menuItems[0]);

# Returns a menubar widget made from the above menu 
static GtkWidget#getMenubarMenu( GtkWidget #window )
{
  GtkItemFactory#itemFactory;
  GtkAccelGroup#accelGroup;

  # Make an accelerator group (shortcut keys) 
  accelGroup = gtkAccelGroupNew ();

  # Make an ItemFactory (that makes a menubar) 
  itemFactory = gtkItemFactoryNew (GTKTYPEMENUBAR, "&lt;main&gt;",
                                       accelGroup);

  # This function generates the menu items. Pass the item factory,
     the number of items in the array, the array itself, and any
     callback data for the the menu items. 
  gtkItemFactoryCreateItems (itemFactory, nmenuItems, menuItems, NULL);

  # Attach the new accelerator group to the window. 
  gtkWindowAddAccelGroup (GTKWINDOW (window), accelGroup);

  # Finally, return the actual menu bar created by the item factory. 
  return gtkItemFactoryGetWidget (itemFactory, "&lt;main&gt;");
}

# Popup the menu when the popup button is pressed 
static gboolean popupCb( GtkWidget#widget,
                          GdkEvent#event,
                          GtkWidget#menu )
{
   GdkEventButton#bevent = (GdkEventButton#)event;
  
   # Only take button presses 
   if (event-&gt;type != GDKBUTTONPRESS)
     return FALSE;
  
   # Show the menu 
   gtkMenuPopup (GTKMENU(menu), NULL, NULL,
                   NULL, NULL, bevent-&gt;button, bevent-&gt;time);
  
   return TRUE;
}

# Same as with getMenubarMenu() but just return a button with a signal to
   call a popup menu 
GtkWidget#getPopupMenu( void )
{
   GtkItemFactory#itemFactory;
   GtkWidget#button,#menu;
  
   # Same as before but don't bother with the accelerators 
   itemFactory = gtkItemFactoryNew (GTKTYPEMENU, "&lt;main&gt;",
                                        NULL);
   gtkItemFactoryCreateItems (itemFactory, nmenuItems, menuItems, NULL);
   menu = gtkItemFactoryGetWidget (itemFactory, "&lt;main&gt;");
  
   # Make a button to activate the popup menu 
   button = gtkButtonNewWithLabel ("Popup");
   # Make the menu popup when clicked 
   gSignalConnect (GOBJECT(button),
                     "event",
                     GCALLBACK(popupCb),
                     (gpointer) menu);

   return button;
}

# Same again but return an option menu 
GtkWidget#getOptionMenu( void )
{
   GtkItemFactory#itemFactory;
   GtkWidget#optionMenu;
  
   # Same again, not bothering with the accelerators 
   itemFactory = gtkItemFactoryNew (GTKTYPEOPTIONMENU, "&lt;main&gt;",
                                        NULL);
   gtkItemFactoryCreateItems (itemFactory, nmenuItems, menuItems, NULL);
   optionMenu = gtkItemFactoryGetWidget (itemFactory, "&lt;main&gt;");

   return optionMenu;
}

# You have to start somewhere 
int main( int argc,
          char#argv[] )
{
  GtkWidget#window;
  GtkWidget#mainVbox;
  GtkWidget#menubar,#optionMenu,#popupButton;
 
  # Initialize GTK 
  gtkInit (&amp;argc, &amp;argv);
 
  # Make a window 
  window = gtkWindowNew (GTKWINDOWTOPLEVEL);
  gSignalConnect (GOBJECT (window), "destroy",
                    GCALLBACK (gtkMainQuit),
                    NULL);
  gtkWindowSetTitle (GTKWINDOW(window), "Item Factory");
  gtkWidgetSetSizeRequest (GTKWIDGET(window), 300, 200);
 
  # Make a vbox to put the three menus in 
  mainVbox = gtkVboxNew (FALSE, 1);
  gtkContainerSetBorderWidth (GTKCONTAINER (mainVbox), 1);
  gtkContainerAdd (GTKCONTAINER (window), mainVbox);
 
  # Get the three types of menu 
  # Note: all three menus are separately created, so they are not the
     same menu 
  menubar = getMenubarMenu (window);
  popupButton = getPopupMenu ();
  optionMenu = getOptionMenu ();
  
  # Pack it all together 
  gtkBoxPackStart (GTKBOX (mainVbox), menubar, FALSE, TRUE, 0);
  gtkBoxPackEnd (GTKBOX (mainVbox), popupButton, FALSE, TRUE, 0);
  gtkBoxPackEnd (GTKBOX (mainVbox), optionMenu, FALSE, TRUE, 0);

  # Show the widgets 
  gtkWidgetShowAll (window);
  
  # Finished! 
  gtkMain ();
 
  return 0;
}
<!-- example-end -->
</programlisting>

</sect1>
</chapter>

<!--**************************************************************** -->
<chapter id="ch-UndocWidgets">
<title>Undocumented Widgets</title>

<para>These all require authors! :) Please consider contributing to our
tutorial.</para>

<para>If you must use one of these widgets that are undocumented, I strongly
suggest you take a look at their respective header files in the GTK
distribution. GTK's function names are very descriptive. Once you
have an understanding of how things work, it's not difficult to figure
out how to use a widget simply by looking at its function
declarations. This, along with a few examples from others' code, and
it should be no problem.</para>

<para>When you do come to understand all the functions of a new undocumented
widget, please consider writing a tutorial on it so others may benefit
from your time.</para>

<!-- ----------------------------------------------------------------- -->
<sect1 id="sec-AccelLabel">
<title>Accel Label</title>

<para></para>

</sect1>

<!-- ----------------------------------------------------------------- -->
<sect1 id="sec-OptionMenu">
<title>Option Menu</title>

<para></para>

</sect1>

<!-- ----------------------------------------------------------------- -->
<sect1 id="sec-MenuItems">
<title>Menu Items</title>

<para></para>

<sect2 id="sec-CheckMenuItem">
<title>Check Menu Item</title>

<para></para>
</sect2>

<sect2 id="sec-RadioMenuItem">
<title>Radio Menu Item</title>

<para></para>
</sect2>

<sect2 id="sec-SeparatorMenuItem">
<title>Separator Menu Item</title>

<para></para>
</sect2>

<sect2 id="sec-TearoffMenuItem">
<title>Tearoff Menu Item</title>

<para></para>
</sect2>
</sect1>

<!-- ----------------------------------------------------------------- -->
<sect1 id="sec-Curves">
<title>Curves</title>

<para></para>

</sect1>

<!-- ----------------------------------------------------------------- -->
<sect1 id="sec-DrawingArea">
<title>Drawing Area</title>

<para></para>

</sect1>

<!-- ----------------------------------------------------------------- -->
<sect1 id="sec-FontSelectionDialog">
<title>Font Selection Dialog</title>

<para></para>

</sect1>

<!-- ----------------------------------------------------------------- -->
<sect1 id="sec-MessageDialog">
<title>Message Dialog</title>

<para></para>

</sect1>

<!-- ----------------------------------------------------------------- -->
<sect1 id="sec-GammaCurve">
<title>Gamma Curve</title>

<para></para>

</sect1>

<!-- ----------------------------------------------------------------- -->
<sect1 id="sec-Image">
<title>Image</title>

<para></para>

</sect1>

<!-- ----------------------------------------------------------------- -->
<sect1 id="sec-PlugsAndSockets">
<title>Plugs and Sockets</title>

<para></para>

</sect1>

<!-- ----------------------------------------------------------------- -->
<sect1 id="sec-TreeView">
<title>Tree View</title>

<para></para>

</sect1>

<!-- ----------------------------------------------------------------- -->
<sect1 id="sec-TextView">
<title>Text View</title>

<para></para>

</sect1>
</chapter>

<!--**************************************************************** -->
<chapter id="ch-SettingWidgetAttributes">
<title>Setting Widget Attributes</title>

<para>This describes the functions used to operate on widgets. These can be
used to set style, padding, size, etc.</para>

<para>(Maybe I should make a whole section on accelerators.)</para>

<programlisting role="R">
void gtkWidgetActivate( GtkWidget#widget );

void gtkWidgetSetName( GtkWidget#widget,
                          gchar    #name );

gchar#gtkWidgetGetName( GtkWidget#widget );

void gtkWidgetSetSensitive( GtkWidget#widget,
                               gboolean   sensitive );

void gtkWidgetSetStyle( GtkWidget#widget,
                           GtkStyle #style );
					   
GtkStyle#gtkWidgetGetStyle( GtkWidget#widget );

GtkStyle#gtkWidgetGetDefaultStyle( void );

void gtkWidgetSetSizeRequest( GtkWidget#widget,
                                  gint       width,
                                  gint       height );

void gtkWidgetGrabFocus( GtkWidget#widget );

void gtkWidgetShow( GtkWidget#widget );

void gtkWidgetHide( GtkWidget#widget );
</programlisting>

</chapter>

<!--**************************************************************** -->
<chapter id="ch-Timeouts">
<title>Timeouts, IO and Idle Functions</title>

<!-- ----------------------------------------------------------------- -->
<sect1 id="sec-Timeouts">
<title>Timeouts</title>

<para>You may be wondering how you make GTK do useful work when in gtkMain.
Well, you have several options. Using the following function you can
create a timeout function that will be called every "interval"
milliseconds.</para>

<programlisting role="R">
gint gTimeoutAdd (guint32     interval,
                    GtkFunction function,
                    gpointer    data);
</programlisting>

<para>The first argument is the number of milliseconds between calls to your
function. The second argument is the function you wish to have called,
and the third, the data passed to this callback function. The return
value is an integer "tag" which may be used to stop the timeout by
calling:</para>

<programlisting role="R">
void gSourceRemove (gint tag);
</programlisting>

<para>You may also stop the timeout function by returning zero or FALSE from
your callback function. Obviously this means if you want your function
to continue to be called, it should return a non-zero value,
i.e., TRUE.</para>

<para>The declaration of your callback should look something like this:</para>

<programlisting role="R">
gint timeoutCallback (gpointer data);
</programlisting>

</sect1>

<!-- ----------------------------------------------------------------- -->
<sect1 id="sec-MonitoringIO">
<title>Monitoring IO</title>

<para>A nifty feature of GDK (the library that underlies GTK), is the
ability to have it check for data on a file descriptor for you (as
returned by open(2) or socket(2)). This is especially useful for
networking applications. The function:</para>

<programlisting role="R">
gint gdkInputAdd( gint              source,
                    GdkInputCondition condition,
                    GdkInputFunction  function,
                    gpointer          data );
</programlisting>

<para>Where the first argument is the file descriptor you wish to have
watched, and the second specifies what you want GDK to look for. This
may be one of:</para>

<itemizedlist>
<listitem><simpara><literal>GDKINPUTREAD</literal> - Call your function when there is data
ready for reading on your file descriptor.</simpara>
</listitem>

<listitem><simpara><literal>GDKINPUTWRITE</literal> - Call your function when the file
descriptor is ready for writing.</simpara>
</listitem>
</itemizedlist>

<para>As I'm sure you've figured out already, the third argument is the
function you wish to have called when the above conditions are
satisfied, and the fourth is the data to pass to this function.</para>

<para>The return value is a tag that may be used to stop GDK from monitoring
this file descriptor using the following function.</para>

<programlisting role="R">
void gdkInputRemove( gint tag );
</programlisting>

<para>The callback function should be declared as:</para>

<programlisting role="R">
void inputCallback( gpointer          data,
                     gint              source, 
                     GdkInputCondition condition );
</programlisting>

<para>Where <literal>source</literal> and <literal>condition</literal> are as specified above.</para>

</sect1>

<!-- ----------------------------------------------------------------- -->
<sect1 id="sec-IdleFunctions">
<title>Idle Functions</title>

<para><!-- TODO: Need to check on idle priorities - TRG -->
What if you have a function which you want to be called when nothing
else is happening ?</para>

<programlisting role="R">
gint gtkIdleAdd( GtkFunction function,
                   gpointer    data );
</programlisting>

<para>This causes GTK to call the specified function whenever nothing else
is happening.</para>

<programlisting role="R">
void gtkIdleRemove( gint tag );
</programlisting>

<para>I won't explain the meaning of the arguments as they follow very much
like the ones above. The function pointed to by the first argument to
gtkIdleAdd will be called whenever the opportunity arises. As with
the others, returning FALSE will stop the idle function from being
called.</para>

</sect1>
</chapter>

<!--**************************************************************** -->
<chapter id="ch-AdvancedEventsAndSignals">
<title>Advanced Event and Signal Handling</title>

<!-- ----------------------------------------------------------------- -->
<sect1 id="sec-SignalFunctions">
<title>Signal Functions</title>

<!-- ----------------------------------------------------------------- -->
<sect2>
<title>Connecting and Disconnecting Signal Handlers</title>

<programlisting role="R">
gulong gSignalConnect( GObject    #object,
                         const gchar#name,
                         GCallback    func,
                         gpointer     funcData );

gulong gSignalConnectAfter( GObject      #object,
                               const gchar  #name,
                               GCallback      func,
                               gpointer       funcData );

gulong gSignalConnectSwapped( GObject      #object,
                                 const gchar  #name,
                                 GCallback      func,
                                 GObject      #slotObject );

void gSignalHandlerDisconnect( GObject#object,
                                  gulong   handlerId );

void gSignalHandlersDisconnectByFunc( GObject  #object,
                                           GCallback  func,
                                           gpointer   data );
</programlisting>

</sect2>

<!-- ----------------------------------------------------------------- -->
<sect2>
<title>Blocking and Unblocking Signal Handlers</title>

<programlisting role="R">
void gSignalHandlerBlock( GObject#object,
                             gulong   handlerId);

void gSignalHandlersBlockByFunc( GObject  #object,
                                      GCallback  func,
                                      gpointer   data );

void gSignalHandlerUnblock( GObject#object,
                               gulong   handlerId );

void gSignalHandlerUnblockByFunc( GObject  #object,
                                       GCallback  func,
                                       gpointer   data );
</programlisting>

</sect2>

<!-- ----------------------------------------------------------------- -->
<sect2>
<title>Emitting and Stopping Signals</title>

<programlisting role="R">
void gSignalEmit( GObject#object,
                    guint      signalId,
                    ... );

void gSignalEmitByName( GObject    #object,
                            const gchar#name,
                            ... );

void gSignalEmitv( const GValue#instanceAndParams,
                     guint         signalId,
                     GQuark        detail,
                     GValue      #returnValue );

void gSignalStopEmission( GObject#object,
                             guint    signalId,
                             GQuark   detail );

void gSignalStopEmissionByName( GObject  #object,
                                     const gchar#detailedSignal );
</programlisting>

</sect2>
</sect1>

<!-- ----------------------------------------------------------------- -->
<sect1 id="sec-SignalEmissionAndPropagation">
<title>Signal Emission and Propagation</title>

<para>Signal emission is the process whereby GTK runs all handlers for a
specific object and signal.</para>

<para>First, note that the return value from a signal emission is the return
value of the <emphasis>last</emphasis> handler executed. Since event signals are
all of type <literal>GTKRUNLAST</literal>, this will be the default (GTK supplied)
handler, unless you connect with gtkSignalConnectAfter().</para>

<para>The way an event (say "buttonPressEvent") is handled, is:</para>

<itemizedlist>
<listitem><simpara>Start with the widget where the event occured.</simpara>
</listitem>

<listitem><simpara>Emit the generic "event" signal. If that signal handler returns
a value of TRUE, stop all processing.</simpara>
</listitem>

<listitem><simpara>Otherwise, emit a specific, "buttonPressEvent" signal. If that
returns TRUE, stop all processing.</simpara>
</listitem>

<listitem><simpara>Otherwise, go to the widget's parent, and repeat the above two
steps.</simpara>
</listitem>

<listitem><simpara>Continue until some signal handler returns TRUE, or until the
top-level widget is reached.</simpara>
</listitem>
</itemizedlist>

<para>Some consequences of the above are:</para>

<itemizedlist>
<listitem><simpara>Your handler's return value will have no effect if there is a
default handler, unless you connect with gtkSignalConnectAfter().</simpara>
</listitem>

<listitem><simpara>To prevent the default handler from being run, you need to
connect with gtkSignalConnect() and use
gtkSignalEmitStopByName() - the return value only affects whether
the signal is propagated, not the current emission.</simpara>
</listitem>
</itemizedlist>

</sect1>
</chapter>

<!-- continue GTK+ 2.0 review here -->

<!--**************************************************************** -->
<chapter id="ch-ManagingSelections">
<title>Managing Selections</title>

<!-- ----------------------------------------------------------------- -->
<sect1 id="sec-SelectionsOverview">
<title>Overview</title>

<para>One type of interprocess communication supported by X and GTK is
<emphasis>selections</emphasis>. A selection identifies a chunk of data, for
instance, a portion of text, selected by the user in some fashion, for
instance, by dragging with the mouse. Only one application on a
display (the <emphasis>owner</emphasis>) can own a particular selection at one
time, so when a selection is claimed by one application, the previous
owner must indicate to the user that selection has been
relinquished. Other applications can request the contents of a
selection in different forms, called <emphasis>targets</emphasis>. There can be
any number of selections, but most X applications only handle one, the
<emphasis>primary selection</emphasis>.</para>

<para>In most cases, it isn't necessary for a GTK application to deal with
selections itself. The standard widgets, such as the Entry widget,
already have the capability to claim the selection when appropriate
(e.g., when the user drags over text), and to retrieve the contents of
the selection owned by another widget or another application (e.g.,
when the user clicks the second mouse button). However, there may be
cases in which you want to give other widgets the ability to supply
the selection, or you wish to retrieve targets not supported by
default.</para>

<para>A fundamental concept needed to understand selection handling is that
of the <emphasis>atom</emphasis>. An atom is an integer that uniquely identifies a
string (on a certain display). Certain atoms are predefined by the X
server, and in some cases there are constants in <literal>gtk.h</literal>
corresponding to these atoms. For instance the constant
<literal>GDKPRIMARYSELECTION</literal> corresponds to the string "PRIMARY".
In other cases, you should use the functions
<literal>gdkAtomIntern()</literal>, to get the atom corresponding to a string,
and <literal>gdkAtomName()</literal>, to get the name of an atom. Both
selections and targets are identified by atoms.</para>

</sect1>
<!-- ----------------------------------------------------------------- -->
<sect1 id="sec-RetrievingTheSelection">
<title>Retrieving the selection</title>

<para>Retrieving the selection is an asynchronous process. To start the
process, you call:</para>

<programlisting role="R">
gboolean gtkSelectionConvert( GtkWidget#widget, 
                                GdkAtom    selection, 
                                GdkAtom    target,
                                guint32    time );
</programlisting>

<para>This <emphasis>converts</emphasis> the selection into the form specified by
<literal>target</literal>. If at all possible, the time field should be the time
from the event that triggered the selection. This helps make sure that
events occur in the order that the user requested them. However, if it
is not available (for instance, if the conversion was triggered by a
"clicked" signal), then you can use the constant
<literal>GDKCURRENTTIME</literal>.</para>

<para>When the selection owner responds to the request, a
"selectionReceived" signal is sent to your application. The handler
for this signal receives a pointer to a <literal>GtkSelectionData</literal>
structure, which is defined as:</para>

<programlisting role="R">
struct GtkSelectionData
{
  GdkAtom selection;
  GdkAtom target;
  GdkAtom type;
  gint    format;
  guchar#data;
  gint    length;
};
</programlisting>

<para><literal>selection</literal> and <literal>target</literal> are the values you gave in your
<literal>gtkSelectionConvert()</literal> call. <literal>type</literal> is an atom that
identifies the type of data returned by the selection owner. Some
possible values are "STRING", a string of latin-1 characters, "ATOM",
a series of atoms, "INTEGER", an integer, etc. Most targets can only
return one type. <literal>format</literal> gives the length of the units (for
instance characters) in bits. Usually, you don't care about this when
receiving data. <literal>data</literal> is a pointer to the returned data, and
<literal>length</literal> gives the length of the returned data, in bytes. If
<literal>length</literal> is negative, then an error occurred and the selection
could not be retrieved. This might happen if no application owned the
selection, or if you requested a target that the application didn't
support. The buffer is actually guaranteed to be one byte longer than
<literal>length</literal>; the extra byte will always be zero, so it isn't
necessary to make a copy of strings just to nul-terminate them.</para>

<para>In the following example, we retrieve the special target "TARGETS",
which is a list of all targets into which the selection can be
converted.</para>

<programlisting role="R">
<!-- example-start selection gettargets.c -->

#include &lt;stdlib.h&gt;
#include &lt;gtk/gtk.h&gt;

static void selectionReceived( GtkWidget       #widget, 
                                GtkSelectionData#selectionData, 
                                gpointer          data );

# Signal handler invoked when user clicks on the "Get Targets" button 
static void getTargets( GtkWidget#widget,
                         gpointer data )
{
  static GdkAtom targetsAtom = GDKNONE;
  GtkWidget#window = (GtkWidget#)data;	

  # Get the atom corresponding to the string "TARGETS" 
  if (targetsAtom == GDKNONE)
    targetsAtom = gdkAtomIntern ("TARGETS", FALSE);

  # And request the "TARGETS" target for the primary selection 
  gtkSelectionConvert (window, GDKSELECTIONPRIMARY, targetsAtom,
			 GDKCURRENTTIME);
}

# Signal handler called when the selections owner returns the data 
static void selectionReceived( GtkWidget       #widget,
                                GtkSelectionData#selectionData, 
                                gpointer          data )
{
  GdkAtom#atoms;
  GList#itemList;
  int i;

  #*** IMPORTANT*** Check to see if retrieval succeeded  
  if (selectionData-&gt;length &lt; 0)
    {
      gPrint ("Selection retrieval failed\n");
      return;
    }
  # Make sure we got the data in the expected form 
  if (selectionData-&gt;type != GDKSELECTIONTYPEATOM)
    {
      gPrint ("Selection \"TARGETS\" was not returned as atoms!\n");
      return;
    }
  
  # Print out the atoms we received 
  atoms = (GdkAtom#)selectionData-&gt;data;

  itemList = NULL;
  for (i = 0; i &lt; selectionData-&gt;length / sizeof(GdkAtom); i++)
    {
      char#name;
      name = gdkAtomName (atoms[i]);
      if (name != NULL)
	gPrint ("%s\n",name);
      else
	gPrint ("(bad atom)\n");
    }

  return;
}

int main( int   argc,
          char#argv[] )
{
  GtkWidget#window;
  GtkWidget#button;
  
  gtkInit (&amp;argc, &amp;argv);

  # Create the toplevel window 

  window = gtkWindowNew (GTKWINDOWTOPLEVEL);
  gtkWindowSetTitle (GTKWINDOW (window), "Event Box");
  gtkContainerSetBorderWidth (GTKCONTAINER (window), 10);

  gSignalConnect (GOBJECT (window), "destroy",
	            GCALLBACK (exit), NULL);

  # Create a button the user can click to get targets 

  button = gtkButtonNewWithLabel ("Get Targets");
  gtkContainerAdd (GTKCONTAINER (window), button);

  gSignalConnect (GOBJECT (button), "clicked",
		    GCALLBACK (getTargets), (gpointer) window);
  gSignalConnect (GOBJECT (window), "selectionReceived",
		    GCALLBACK (selectionReceived), NULL);

  gtkWidgetShow (button);
  gtkWidgetShow (window);
  
  gtkMain ();
  
  return 0;
}
<!-- example-end -->
</programlisting>

</sect1>
<!-- ----------------------------------------------------------------- -->
<sect1 id="sec-SupplyingTheSelection">
<title>Supplying the selection</title>

<para>Supplying the selection is a bit more complicated. You must register 
handlers that will be called when your selection is requested. For
each selection/target pair you will handle, you make a call to:</para>

<programlisting role="R">
void gtkSelectionAddTarget( GtkWidget          #widget, 
                               GdkAtom              selection,
                               GdkAtom              target,
                               guint                info );
</programlisting>

<para><literal>widget</literal>, <literal>selection</literal>, and <literal>target</literal> identify the requests
this handler will manage. When a request for a selection is received,
the "selectionGet" signal will be called. <literal>info</literal> can be used as an
enumerator to identify the specific target within the callback function.</para>

<para>The callback function has the signature:</para>

<programlisting role="R">
void  "selectionGet"( GtkWidget         #widget,
                       GtkSelectionData  #selectionData,
                       guint               info,
                       guint               time );
</programlisting>

<para>The GtkSelectionData is the same as above, but this time, we're
responsible for filling in the fields <literal>type</literal>, <literal>format</literal>,
<literal>data</literal>, and <literal>length</literal>. (The <literal>format</literal> field is actually
important here - the X server uses it to figure out whether the data
needs to be byte-swapped or not. Usually it will be 8 - <emphasis>i.e.</emphasis> a
character - or 32 - <emphasis>i.e.</emphasis> an integer.) This is done by calling the
function:</para>

<programlisting role="R">
void gtkSelectionDataSet( GtkSelectionData#selectionData,
                             GdkAtom           type,
                             gint              format,
                             guchar          #data,
                             gint              length );
</programlisting>

<para>This function takes care of properly making a copy of the data so that
you don't have to worry about keeping it around. (You should not fill
in the fields of the GtkSelectionData structure by hand.)</para>

<para>When prompted by the user, you claim ownership of the selection by
calling:</para>

<programlisting role="R">
gboolean gtkSelectionOwnerSet( GtkWidget#widget,
                                  GdkAtom    selection,
                                  guint32    time );
</programlisting>

<para>If another application claims ownership of the selection, you will
receive a "selectionClearEvent".</para>

<para>As an example of supplying the selection, the following program adds
selection functionality to a toggle button. When the toggle button is
depressed, the program claims the primary selection. The only target
supported (aside from certain targets like "TARGETS" supplied by GTK
itself), is the "STRING" target. When this target is requested, a
string representation of the time is returned.</para>

<programlisting role="R">
<!-- example-start selection setselection.c -->

#include &lt;stdlib.h&gt;
#include &lt;gtk/gtk.h&gt;
#include &lt;time.h&gt;
#include &lt;string.h&gt;

GtkWidget#selectionButton;
GtkWidget#selectionWidget;

# Callback when the user toggles the selection 
static void selectionToggled( GtkWidget#widget,
                               gint     #haveSelection )
{
  if (GTKTOGGLEBUTTON (widget)-&gt;active)
    {
     #haveSelection = gtkSelectionOwnerSet (selectionWidget,
						 GDKSELECTIONPRIMARY,
						 GDKCURRENTTIME);
      # if claiming the selection failed, we return the button to
	 the out state 
      if (!*haveSelection)
	gtkToggleButtonSetActive (GTKTOGGLEBUTTON (widget), FALSE);
    }
  else
    {
      if (*haveSelection)
	{
	  # Before clearing the selection by setting the owner to NULL,
	     we check if we are the actual owner 
	  if (gdkSelectionOwnerGet (GDKSELECTIONPRIMARY) == widget-&gt;window)
	    gtkSelectionOwnerSet (NULL, GDKSELECTIONPRIMARY,
				     GDKCURRENTTIME);
	 #haveSelection = FALSE;
	}
    }
}

# Called when another application claims the selection 
static gboolean selectionClear( GtkWidget        #widget,
                                 GdkEventSelection#event,
                                 gint             #haveSelection )
{
 #haveSelection = FALSE;
  gtkToggleButtonSetActive (GTKTOGGLEBUTTON (selectionButton), FALSE);

  return TRUE;
}

# Supplies the current time as the selection. 
static void selectionHandle( GtkWidget       #widget, 
                              GtkSelectionData#selectionData,
                              guint             info,
                              guint             timeStamp,
                              gpointer          data )
{
  gchar#timestr;
  timeT currentTime;

  currentTime = time (NULL);
  timestr = asctime (localtime (&amp;currentTime)); 
  # When we return a single string, it should not be null terminated.
     That will be done for us 

  gtkSelectionDataSet (selectionData, GDKSELECTIONTYPESTRING,
			  8, timestr, strlen (timestr));
}

int main( int   argc,
          char#argv[] )
{
  GtkWidget#window;

  static int haveSelection = FALSE;
  
  gtkInit (&amp;argc, &amp;argv);

  # Create the toplevel window 

  window = gtkWindowNew (GTKWINDOWTOPLEVEL);
  gtkWindowSetTitle (GTKWINDOW (window), "Event Box");
  gtkContainerSetBorderWidth (GTKCONTAINER (window), 10);

  gSignalConnect (GOBJECT (window), "destroy",
		    GCALLBACK (exit), NULL);

  # Create a toggle button to act as the selection 

  selectionWidget = gtkInvisibleNew ();
  selectionButton = gtkToggleButtonNewWithLabel ("Claim Selection");
  gtkContainerAdd (GTKCONTAINER (window), selectionButton);
  gtkWidgetShow (selectionButton);

  gSignalConnect (GOBJECT (selectionButton), "toggled",
		    GCALLBACK (selectionToggled), (gpointer) &amp;haveSelection);
  gSignalConnect (GOBJECT (selectionWidget), "selectionClearEvent",
		    GCALLBACK (selectionClear), (gpointer) &amp;haveSelection);

  gtkSelectionAddTarget (selectionWidget,
			    GDKSELECTIONPRIMARY,
			    GDKSELECTIONTYPESTRING,
		            1);
  gSignalConnect (GOBJECT (selectionWidget), "selectionGet",
		    GCALLBACK (selectionHandle), (gpointer) &amp;haveSelection);

  gtkWidgetShow (selectionButton);
  gtkWidgetShow (window);
  
  gtkMain ();
  
  return 0;
}
<!-- example-end -->
</programlisting>

</sect1>
</chapter>

<!--**************************************************************** -->
<chapter id="ch-DragAngDrop">
<title>Drag-and-drop (DND)</title>

<para>GTK+ has a high level set of functions for doing inter-process
communication via the drag-and-drop system. GTK+ can perform
drag-and-drop on top of the low level Xdnd and Motif drag-and-drop
protocols.</para>

<!-- ----------------------------------------------------------------- -->
<sect1 id="sec-DragAndDropOverview">
<title>Overview</title>

<para>An application capable of GTK+ drag-and-drop first defines and sets up
the GTK+ widget(s) for drag-and-drop. Each widget can be a source
and/or destination for drag-and-drop. Note that these GTK+ widgets must have
an associated X Window, check using GTKWIDGETNOWINDOW(widget)).</para>

<para>Source widgets can send out drag data, thus allowing the user to drag
things off of them, while destination widgets can receive drag data.
Drag-and-drop destinations can limit who they accept drag data from,
e.g. the same application or any application (including itself).</para>

<para>Sending and receiving drop data makes use of GTK+ signals.
Dropping an item to a destination widget requires both a data
request (for the source widget) and data received signal handler (for
the target widget). Additional signal handers can be connected if you
want to know when a drag begins (at the very instant it starts), to
when a drop is made, and when the entire drag-and-drop procedure has
ended (successfully or not).</para>

<para>Your application will need to provide data for source widgets when
requested, that involves having a drag data request signal handler. For
destination widgets they will need a drop data received signal
handler. </para>

<para>So a typical drag-and-drop cycle would look as follows:</para>
<orderedlist>
<listitem><simpara> Drag begins.</simpara>
</listitem>
<listitem><simpara> Drag data request (when a drop occurs).</simpara>
</listitem>
<listitem><simpara> Drop data received (may be on same or different
application).</simpara>
</listitem>
<listitem><simpara> Drag data delete (if the drag was a move).</simpara>
</listitem>
<listitem><simpara> Drag-and-drop procedure done.</simpara>
</listitem>
</orderedlist>

<para>There are a few minor steps that go in between here and there, but we
will get into detail about that later.</para>

</sect1>

<!-- ----------------------------------------------------------------- -->
<sect1 id="sec-DragAndDropProperties">
<title>Properties</title>

<para>Drag data has the following properties:</para>

<itemizedlist>
<listitem><simpara> Drag action type (ie GDKACTIONCOPY, GDKACTIONMOVE).</simpara>
</listitem>

<listitem><simpara> Client specified arbitrary drag-and-drop type (a name and number pair).</simpara>
</listitem>

<listitem><simpara> Sent and received data format type.</simpara>
</listitem>
</itemizedlist>

<para>Drag actions are quite obvious, they specify if the widget can
drag with the specified action(s), e.g. GDKACTIONCOPY and/or
GDKACTIONMOVE. A GDKACTIONCOPY would be a typical drag-and-drop
without the source data being deleted while GDKACTIONMOVE would be
just like GDKACTIONCOPY but the source data will be 'suggested' to be
deleted after the received signal handler is called. There are
additional drag actions including GDKACTIONLINK which you may want to
look into when you get to more advanced levels of drag-and-drop.</para>

<para>The client specified arbitrary drag-and-drop type is much more
flexible, because your application will be defining and checking for
that specifically. You will need to set up your destination widgets to
receive certain drag-and-drop types by specifying a name and/or number.
It would be more reliable to use a name since another application may
just happen to use the same number for an entirely different
meaning.</para>

<para>Sent and received data format types (<emphasis>selection
target</emphasis>) come into play only in your request and received
data handler functions. The term <emphasis>selection target</emphasis>
is somewhat misleading. It is a term adapted from GTK+ selection
(cut/copy and paste). What <emphasis>selection target</emphasis>
actually means is the data's format type (i.e. GdkAtom, integer, or
string) that being sent or received. Your request data handler function
needs to specify the type (<emphasis>selection target</emphasis>) of
data that it sends out and your received data handler needs to handle
the type (<emphasis>selection target</emphasis>) of data
received.</para>

</sect1>

<!-- ----------------------------------------------------------------- -->
<sect1 id="sec-DragAndDropFunctions">
<title>Functions</title>

<!-- ----------------------------------------------------------------- -->
<sect2 id="sec-DNDSourceWidgets">
<title>Setting up the source widget</title>

<para>The function <literal>gtkDragSourceSet()</literal> specifies a
set of target types for a drag operation on a widget.</para>

<programlisting role="R">
void gtkDragSourceSet( GtkWidget           #widget,
                          GdkModifierType       startButtonMask,
                          const GtkTargetEntry#targets,
                          gint                  nTargets,
                          GdkDragAction         actions );
</programlisting>

<para>The parameters signify the following:</para>
<itemizedlist>
<listitem><simpara><literal>widget</literal> specifies the drag source
widget</simpara>
</listitem>
<listitem><simpara><literal>startButtonMask</literal> specifies a
bitmask of buttons that can start the drag (e.g. GDKBUTTON1MASK)</simpara>
</listitem>
<listitem><simpara><literal>targets</literal> specifies a table of
target data types the drag will support</simpara>
</listitem>
<listitem><simpara><literal>nTargets</literal> specifies the number of
targets above</simpara>
</listitem>
<listitem><simpara><literal>actions</literal> specifies a bitmask of
possible actions for a drag from this window</simpara>
</listitem>
</itemizedlist>

<para>The <literal>targets</literal> parameter is an array of the
following structure:</para>

<programlisting role="R">
struct GtkTargetEntry {
   gchar#target;
   guint  flags;
   guint  info;
 };
</programlisting>

<para>The fields specify a string representing the drag type, optional
flags and application assigned integer identifier.</para>

<para>If a widget is no longer required to act as a source for
drag-and-drop operations, the function
<literal>gtkDragSourceUnset()</literal> can be used to remove a set
of drag-and-drop target types.</para>

<programlisting role="R">
void gtkDragSourceUnset( GtkWidget#widget );
</programlisting>

</sect2>

<!-- ----------------------------------------------------------------- -->
<sect2 id="sec-SignalsOnSourceWidgets">
<title>Signals on the source widget:</title>

<para>The source widget is sent the following signals during a
drag-and-drop operation.</para>

<table pgwide="1">
<title>Source widget signals</title>
<tgroup cols="2">
<colspec colname="Name" colwidth="150">
<colspec colname="Prototype">
<tbody>
<row>
<entry align="left" valign="middle">dragBegin</entry>
<entry align="left" valign="middle"><literal>void (*dragBegin)(GtkWidget#widget,
GdkDragContext#dc, gpointer data)</literal></entry>
</row>
<row>
<entry align="left" valign="middle">dragMotion</entry>
<entry align="left" valign="middle"><literal>gboolean (*dragMotion)(GtkWidget#widget,
GdkDragContext#dc, gint x, gint y, guint t, gpointer data)</literal></entry>
</row>
<row>
<entry align="left" valign="middle">dragDataGet</entry>
<entry align="left" valign="middle"><literal>void (*dragDataGet)(GtkWidget#widget,
GdkDragContext#dc, GtkSelectionData#selectionData, guint info, guint t, gpointer data)</literal></entry>
</row>
<row>
<entry align="left" valign="middle">dragDataDelete</entry>
<entry align="left" valign="middle"><literal>void (*dragDataDelete)(GtkWidget#widget,
GdkDragContext#dc, gpointer data)</literal></entry>
</row>
<row>
<entry align="left" valign="middle">dragDrop</entry>
<entry align="left" valign="middle"><literal>gboolean (*dragDrop)(GtkWidget#widget,
GdkDragContext#dc, gint x, gint y, guint t, gpointer data)</literal></entry>
</row>
<row>
<entry align="left" valign="middle">dragEnd</entry>
<entry align="left" valign="middle"><literal>void (*dragEnd)(GtkWidget#widget,
GdkDragContext#dc, gpointer data)</literal></entry>
</row>
</tbody>
</tgroup>
</table>

</sect2>

<!-- ----------------------------------------------------------------- -->
<sect2 id="sec-DNDDestWidgets">
<title>Setting up a destination widget:</title>

<para> <literal> gtkDragDestSet()</literal> specifies
that this widget can receive drops and specifies what types of drops it
can receive.</para>

<para> <literal> gtkDragDestUnset()</literal> specifies
that the widget can no longer receive drops.</para>

<programlisting role="R">
void gtkDragDestSet( GtkWidget           #widget,
                        GtkDestDefaults       flags,
                        const GtkTargetEntry#targets,
                        gint                  nTargets,
                        GdkDragAction         actions );

void gtkDragDestUnset( GtkWidget#widget );
</programlisting>

</sect2>

<!-- ----------------------------------------------------------------- -->
<sect2 id="sec-SignalsOnDestWidgets">
<title>Signals on the destination widget:</title>

<para>The destination widget is sent the following signals during a
drag-and-drop operation.</para>

<table pgwide="1">
<title>Destination widget signals</title>
<tgroup cols="2">
<colspec colname="Name" colwidth="150">
<colspec colname="Prototype">
<tbody>
<row>
<entry align="left" valign="middle">dragDataReceived</entry>
<entry align="left" valign="middle"><literal>void (*dragDataReceived)(GtkWidget#widget,
GdkDragContext#dc, gint x, gint y, GtkSelectionData#selectionData, guint info, guint t,
gpointer data)</literal></entry>
</row>
</tbody>
</tgroup>
</table>

</sect2>
</sect1>
</chapter>

<!--**************************************************************** -->
<chapter id="ch-GLib">
<title>GLib</title>

<para>GLib is a lower-level library that provides many useful definitions
and functions available for use when creating GDK and GTK
applications. These include definitions for basic types and their
limits, standard macros, type conversions, byte order, memory
allocation, warnings and assertions, message logging, timers, string
utilities, hook functions, a lexical scanner, dynamic loading of
modules, and automatic string completion. A number of data structures
(and their related operations) are also defined, including memory
chunks, doubly-linked lists, singly-linked lists, hash tables, strings
(which can grow dynamically), string chunks (groups of strings),
arrays (which can grow in size as elements are added), balanced binary
trees, N-ary trees, quarks (a two-way association of a string and a
unique integer identifier), keyed data lists (lists of data elements
accessible by a string or integer id), relations and tuples (tables of
data which can be indexed on any number of fields), and caches.</para>

<para>A summary of some of GLib's capabilities follows; not every function,
data structure, or operation is covered here.  For more complete
information about the GLib routines, see the GLib documentation. One
source of GLib documentation is <ulink url="http://www.gtk.org/">http://www.gtk.org/</ulink>.</para>

<para>If you are using a language other than C, you should consult your
language's binding documentation. In some cases your language may
have equivalent functionality built-in, while in other cases it may
not.</para>

<!-- ----------------------------------------------------------------- -->
<sect1 id="sec-Definitions">
<title>Definitions</title>

<para>Definitions for the extremes of many of the standard types are:</para>

<programlisting role="R">
GMINFLOAT
GMAXFLOAT
GMINDOUBLE
GMAXDOUBLE
GMINSHORT
GMAXSHORT
GMAXUSHORT
GMININT
GMAXINT
GMAXUINT
GMINLONG
GMAXLONG
GMAXULONG
GMININT64
GMAXINT64
GMAXUINT64
</programlisting>

<para>Also, the following typedefs. The ones left unspecified are dynamically set
depending on the architecture. Remember to avoid counting on the size of a
pointer if you want to be portable! E.g., a pointer on an Alpha is 8
bytes, but 4 on Intel 80x86 family CPUs.</para>

<programlisting role="R">
char   gchar;
short  gshort;
long   glong;
int    gint;
int    gboolean;

unsigned char   guchar;
unsigned short  gushort;
unsigned long   gulong;
unsigned int    guint;

float   gfloat;
double  gdouble;

unsigned int  gsize;
signed int    gssize;

void*       gpointer;
const void* gconstpointer;

gint8
guint8
gint16
guint16
gint32
guint32
gint64
guint64
</programlisting>

</sect1>

<!-- ----------------------------------------------------------------- -->
<sect1 id="sec-DoublyLinkedLists">
<title>Doubly Linked Lists</title>

<para>The following functions are used to create, manage, and destroy
standard doubly linked lists. Each element in the list contains a
piece of data, together with pointers which link to the previous and
next elements in the list. This enables easy movement in either
direction through the list. The data item is of type "gpointer",
which means the data can be a pointer to your real data or (through
casting) a numeric value (but do not assume that int and gpointer have
the same size!). These routines internally allocate list elements in
blocks, which is more efficient than allocating elements individually.</para>

<para>There is no function to specifically create a list. Instead, simply
create a variable of type GList* and set its value to NULL; NULL is
considered to be the empty list.</para>

<para>To add elements to a list, use the gListAppend(), gListPrepend(),
gListInsert(), or gListInsertSorted() routines. In all cases
they accept a pointer to the beginning of the list, and return the
(possibly changed) pointer to the beginning of the list. Thus, for
all of the operations that add or remove elements, be sure to save the
returned value!</para>

<programlisting role="R">
GList#gListAppend( GList   #list,
                      gpointer  data );
</programlisting>

<para>This adds a new element (with value <literal>data</literal>) onto the end of the
list.</para>
  
<programlisting role="R">
GList#gListPrepend( GList   #list,
                       gpointer  data );
</programlisting>

<para>This adds a new element (with value <literal>data</literal>) to the beginning of the
list.</para>

<programlisting role="R">
GList#gListInsert( GList   #list,
                      gpointer  data,
                      gint      position );
</programlisting>

<para>This inserts a new element (with value data) into the list at the
given position. If position is 0, this is just like gListPrepend();
if position is less than 0, this is just like gListAppend().</para>

<programlisting role="R">
GList#gListRemove( GList   #list,
                      gpointer  data );
</programlisting>

<para>This removes the element in the list with the value <literal>data</literal>;
if the element isn't there, the list is unchanged.</para>

<programlisting role="R">
void gListFree( GList#list );
</programlisting>

<para>This frees all of the memory used by a GList. If the list elements
refer to dynamically-allocated memory, then they should be freed
first.</para>

<para>There are many other GLib functions that support doubly linked lists;
see the glib documentation for more information.  Here are a few of
the more useful functions' signatures:</para>

<programlisting role="R">  
GList#gListRemoveLink( GList#list,
                           GList#link );

GList#gListReverse( GList#list );

GList#gListNth( GList#list,
                   gint   n );
			   
GList#gListFind( GList   #list,
                    gpointer  data );

GList#gListLast( GList#list );

GList#gListFirst( GList#list );

gint gListLength( GList#list );

void gListForeach( GList   #list,
                     GFunc     func,
                     gpointer  userData );
</programlisting>

</sect1>

<!-- ----------------------------------------------------------------- -->
<sect1 id="sec-SinglyLinkedLists">
<title>Singly Linked Lists</title>

<para>Many of the above functions for singly linked lists are identical to the
above. Here is a list of some of their operations:</para>

<programlisting role="R">
GSList#gSlistAppend( GSList  #list,
                        gpointer  data );
		
GSList#gSlistPrepend( GSList  #list,
                         gpointer  data );
			     
GSList#gSlistInsert( GSList  #list,
                        gpointer  data,
		        gint      position );
			     
GSList#gSlistRemove( GSList  #list,
                        gpointer  data );
			     
GSList#gSlistRemoveLink( GSList#list,
                             GSList#link );
			     
GSList#gSlistReverse( GSList#list );

GSList#gSlistNth( GSList#list,
                     gint    n );
			     
GSList#gSlistFind( GSList  #list,
                      gpointer  data );
			     
GSList#gSlistLast( GSList#list );

gint gSlistLength( GSList#list );

void gSlistForeach( GSList  #list,
                      GFunc     func,
                      gpointer  userData );
	
</programlisting>

</sect1>

<!-- ----------------------------------------------------------------- -->
<sect1 id="sec-MemoryManagement">
<title>Memory Management</title>

<programlisting role="R">
gpointer gMalloc( gulong size );
</programlisting>

<para>This is a replacement for malloc(). You do not need to check the return
value as it is done for you in this function. If the memory allocation
fails for whatever reasons, your applications will be terminated.</para>

<programlisting role="R">
gpointer gMalloc0( gulong size );
</programlisting>

<para>Same as above, but zeroes the memory before returning a pointer to it.</para>

<programlisting role="R">
gpointer gRealloc( gpointer mem,
                    gulong   size );
</programlisting>

<para>Relocates "size" bytes of memory starting at "mem".  Obviously, the
memory should have been previously allocated.</para>

<programlisting role="R">
void gFree( gpointer mem );
</programlisting>

<para>Frees memory. Easy one. If <literal>mem</literal> is NULL it simply returns.</para>

<programlisting role="R">
void gMemProfile( void );
</programlisting>

<para>Dumps a profile of used memory, but requires that you add <literal>#define
MEMPROFILE</literal> to the top of glib/gmem.c and re-make and make install.</para>

<programlisting role="R">
void gMemCheck( gpointer mem );
</programlisting>

<para>Checks that a memory location is valid. Requires you add <literal>#define
MEMCHECK</literal> to the top of gmem.c and re-make and make install.</para>

</sect1>

<!-- ----------------------------------------------------------------- -->
<sect1 id="sec-Timers">
<title>Timers</title>

<para>Timer functions can be used to time operations (e.g., to see how much
time has elapsed). First, you create a new timer with gTimerNew().
You can then use gTimerStart() to start timing an operation,
gTimerStop() to stop timing an operation, and gTimerElapsed() to
determine the elapsed time.</para>

<programlisting role="R">
GTimer#gTimerNew( void );

void gTimerDestroy( GTimer#timer );

void gTimerStart( GTimer #timer );

void gTimerStop( GTimer #timer );

void gTimerReset( GTimer #timer );

gdouble gTimerElapsed( GTimer#timer,
                         gulong#microseconds );
</programlisting>

</sect1>

<!-- ----------------------------------------------------------------- -->
<sect1 id="sec-StringHandling">
<title>String Handling</title>

<para>GLib defines a new type called a GString, which is similar to a
standard C string but one that grows automatically. Its string data
is null-terminated. What this gives you is protection from buffer
overflow programming errors within your program. This is a very
important feature, and hence I recommend that you make use of
GStrings. GString itself has a simple public definition:</para>

<programlisting role="R">
struct GString 
{
  gchar#str; # Points to the string's current \0-terminated value. 
  gint len; # Current length 
};
</programlisting>

<para>As you might expect, there are a number of operations you can do with
a GString.</para>

<programlisting role="R">
GString#gStringNew( gchar#init );
</programlisting>

<para>This constructs a GString, copying the string value of <literal>init</literal>
into the GString and returning a pointer to it. NULL may be given as
the argument for an initially empty GString.</para>

<programlisting role="R">
void gStringFree( GString#string,
                    gint     freeSegment );
</programlisting>

<para>This frees the memory for the given GString. If <literal>freeSegment</literal> is
TRUE, then this also frees its character data.</para>

<programlisting role="R">	     
GString#gStringAssign( GString    #lval,
                          const gchar#rval );
</programlisting>

<para>This copies the characters from rval into lval, destroying the
previous contents of lval. Note that lval will be lengthened as
necessary to hold the string's contents, unlike the standard strcpy()
function.</para>

<para>The rest of these functions should be relatively obvious (the C
versions accept a character instead of a string):</para>
	     
<programlisting role="R">	     
GString#gStringTruncate( GString#string,
                            gint     len );
			     
GString#gStringAppend( GString#string,
                          gchar  #val );
			    
GString#gStringAppendC( GString#string,
                            gchar    c );
	
GString#gStringPrepend( GString#string,
                           gchar  #val );
			     
GString#gStringPrependC( GString#string,
                             gchar    c );
	
void gStringSprintf( GString#string,
                       gchar  #fmt,
                       ...);
	
void gStringSprintfa ( GString#string,
                         gchar  #fmt,
                         ... );
</programlisting>

</sect1>

<!-- ----------------------------------------------------------------- -->
<sect1 id="sec-UtilityAndErrorFunctions">
<title>Utility and Error Functions</title>

<programlisting role="R">
gchar#gStrdup( const gchar#str );
</programlisting>

<para>Replacement strdup function.  Copies the original strings contents to
newly allocated memory, and returns a pointer to it.</para>

<programlisting role="R">
gchar#gStrerror( gint errnum );
</programlisting>

<para>I recommend using this for all error messages.  It's much nicer, and more
portable than perror() or others.  The output is usually of the form:</para>

<programlisting role="R">
program name:function that failed:file or further description:strerror
</programlisting>

<para>Here's an example of one such call used in our helloWorld program:</para>

<programlisting role="R">
gPrint("helloWorld:open:%s:%s\n", filename, gStrerror(errno));
</programlisting>

<programlisting role="R">
void gError( gchar#format, ... );
</programlisting>

<para>Prints an error message. The format is just like printf, but it
prepends "** ERROR*: " to your message, and exits the program.  
Use only for fatal errors.</para>

<programlisting role="R">
void gWarning( gchar#format, ... );
</programlisting>

<para>Same as above, but prepends "** WARNING*: ", and does not exit the
program.</para>

<programlisting role="R">
void gMessage( gchar#format, ... );
</programlisting>

<para>Prints "message: " prepended to the string you pass in.</para>

<programlisting role="R">
void gPrint( gchar#format, ... );
</programlisting>

<para>Replacement for printf().</para>

<para>And our last function:</para>

<programlisting role="R">
gchar#gStrsignal( gint signum );
</programlisting>

<para>Prints out the name of the Unix system signal given the signal number.
Useful in generic signal handling functions.</para>

<para>All of the above are more or less just stolen from glib.h.  If anyone cares
to document any function, just send me an email!</para>

</sect1>
</chapter>

<!--**************************************************************** -->
<chapter id="ch-GTKRCFiles">
<title>GTK's rc Files</title>

<para>GTK has its own way of dealing with application defaults, by using rc
files. These can be used to set the colors of just about any widget, and
can also be used to tile pixmaps onto the background of some widgets.  </para>

<!-- ----------------------------------------------------------------- -->
<sect1 id="sec-FunctionsForRCFiles">
<title>Functions For rc Files</title>

<para>When your application starts, you should include a call to:</para>

<programlisting role="R">
void gtkRcParse( char#filename );
</programlisting>

<para>Passing in the filename of your rc file. This will cause GTK to parse
this file, and use the style settings for the widget types defined
there.</para>

<para>If you wish to have a special set of widgets that can take on a
different style from others, or any other logical division of widgets,
use a call to:</para>

<programlisting role="R">
void gtkWidgetSetName( GtkWidget#widget,
                          gchar    #name );
</programlisting>

<para>Passing your newly created widget as the first argument, and the name
you wish to give it as the second. This will allow you to change the
attributes of this widget by name through the rc file.</para>

<para>If we use a call something like this:</para>

<programlisting role="R">
button = gtkButtonNewWithLabel ("Special Button");
gtkWidgetSetName (button, "special button");
</programlisting>

<para>Then this button is given the name "special button" and may be addressed by
name in the rc file as "special button.GtkButton".  [<--- Verify ME!]</para>

<para>The example rc file below, sets the properties of the main window, and lets
all children of that main window inherit the style described by the "main
button" style.  The code used in the application is:</para>

<programlisting role="R">
window = gtkWindowNew (GTKWINDOWTOPLEVEL);
gtkWidgetSetName (window, "main window");
</programlisting>

<para>And then the style is defined in the rc file using:</para>

<programlisting role="R">
widget "main window.*GtkButton*" style "mainButton"
</programlisting>

<para>Which sets all the Button widgets in the "main window" to the
"mainButtons" style as defined in the rc file.</para>

<para>As you can see, this is a fairly powerful and flexible system.  Use your
imagination as to how best to take advantage of this.</para>

</sect1>

<!-- ----------------------------------------------------------------- -->
<sect1 id="sec-GTKsRCFileFormat">
<title>GTK's rc File Format</title>

<para>The format of the GTK file is illustrated in the example below. This is
the testgtkrc file from the GTK distribution, but I've added a
few comments and things. You may wish to include this explanation in
your application to allow the user to fine tune his application.</para>

<para>There are several directives to change the attributes of a widget.</para>

<itemizedlist>
<listitem><simpara>fg - Sets the foreground color of a widget.</simpara>
</listitem>
<listitem><simpara>bg - Sets the background color of a widget.</simpara>
</listitem>
<listitem><simpara>bgPixmap - Sets the background of a widget to a tiled pixmap.</simpara>
</listitem>
<listitem><simpara>font - Sets the font to be used with the given widget.</simpara>
</listitem>
</itemizedlist>

<para>In addition to this, there are several states a widget can be in, and you
can set different colors, pixmaps and fonts for each state. These states are:</para>

<itemizedlist>
<listitem><simpara>NORMAL - The normal state of a widget, without the mouse over top of
it, and not being pressed, etc.</simpara>
</listitem>
<listitem><simpara>PRELIGHT - When the mouse is over top of the widget, colors defined
using this state will be in effect.</simpara>
</listitem>
<listitem><simpara>ACTIVE - When the widget is pressed or clicked it will be active, and
the attributes assigned by this tag will be in effect.</simpara>
</listitem>
<listitem><simpara>INSENSITIVE - When a widget is set insensitive, and cannot be
activated, it will take these attributes.</simpara>
</listitem>
<listitem><simpara>SELECTED - When an object is selected, it takes these attributes.</simpara>
</listitem>
</itemizedlist>

<para>When using the "fg" and "bg" keywords to set the colors of widgets, the
format is:</para>

<programlisting role="R">
fg[&lt;STATE>] = { Red, Green, Blue }
</programlisting>

<para>Where STATE is one of the above states (PRELIGHT, ACTIVE, etc), and the Red,
Green and Blue are values in the range of 0 - 1.0,  { 1.0, 1.0, 1.0 } being
white. They must be in float form, or they will register as 0, so a straight 
"1" will not work, it must be "1.0".  A straight "0" is fine because it 
doesn't matter if it's not recognized.  Unrecognized values are set to 0.</para>

<para>bgPixmap is very similar to the above, except the colors are replaced by a
filename.</para>

<para>pixmapPath is a list of paths separated by ":"'s.  These paths will be
searched for any pixmap you specify.</para>

<para>The font directive is simply:</para>

<programlisting role="R">
font = "&lt;font name>"
</programlisting>

<para>The only hard part is figuring out the font string. Using xfontsel or
a similar utility should help.</para>

<para>The "widgetClass" sets the style of a class of widgets. These classes are
listed in the widget overview on the class hierarchy.</para>

<para>The "widget" directive sets a specifically named set of widgets to a
given style, overriding any style set for the given widget class.
These widgets are registered inside the application using the
gtkWidgetSetName() call. This allows you to specify the attributes of a
widget on a per widget basis, rather than setting the attributes of an
entire widget class. I urge you to document any of these special widgets so
users may customize them.</para>

<para>When the keyword <literal>parent</> is used as an attribute, the widget will take on
the attributes of its parent in the application.</para>

<para>When defining a style, you may assign the attributes of a previously defined
style to this new one.</para>

<programlisting role="R">
style "mainButton" = "button"
{
  font = "-adobe-helvetica-medium-r-normal--*-100-*-*-*-*-*-*"
  bg[PRELIGHT] = { 0.75, 0, 0 }
}
</programlisting>

<para>This example takes the "button" style, and creates a new "mainButton" style
simply by changing the font and prelight background color of the "button"
style.</para>

<para>Of course, many of these attributes don't apply to all widgets. It's a
simple matter of common sense really. Anything that could apply, should.</para>

</sect1>

<!-- ----------------------------------------------------------------- -->
<sect1 id="sec-ExampleRCFile">
<title>Example rc file</title>

<programlisting role="R">
# pixmapPath "&lt;dir 1>:&lt;dir 2>:&lt;dir 3>:..."
#
pixmapPath "/usr/include/X11R6/pixmaps:/home/imain/pixmaps"
#
# style &lt;name> [= &lt;name>]
# {
#   &lt;option>
# }
#
# widget &lt;widgetSet> style &lt;styleName>
# widgetClass &lt;widgetClassSet> style &lt;styleName>

# Here is a list of all the possible states.  Note that some do not apply to
# certain widgets.
#
# NORMAL - The normal state of a widget, without the mouse over top of
# it, and not being pressed, etc.
#
# PRELIGHT - When the mouse is over top of the widget, colors defined
# using this state will be in effect.
#
# ACTIVE - When the widget is pressed or clicked it will be active, and
# the attributes assigned by this tag will be in effect.
#
# INSENSITIVE - When a widget is set insensitive, and cannot be
# activated, it will take these attributes.
#
# SELECTED - When an object is selected, it takes these attributes.
#
# Given these states, we can set the attributes of the widgets in each of
# these states using the following directives.
#
# fg - Sets the foreground color of a widget.
# fg - Sets the background color of a widget.
# bgPixmap - Sets the background of a widget to a tiled pixmap.
# font - Sets the font to be used with the given widget.
#

# This sets a style called "button".  The name is not really important, as
# it is assigned to the actual widgets at the bottom of the file.

style "window"
{
  #This sets the padding around the window to the pixmap specified.
  #bgPixmap[&lt;STATE>] = "&lt;pixmap filename>"
  bgPixmap[NORMAL] = "warning.xpm"
}

style "scale"
{
  #Sets the foreground color (font color) to red when in the "NORMAL"
  #state.
  
  fg[NORMAL] = { 1.0, 0, 0 }
  
  #Sets the background pixmap of this widget to that of its parent.
  bgPixmap[NORMAL] = "&lt;parent>"
}

style "button"
{
  # This shows all the possible states for a button.  The only one that
  # doesn't apply is the SELECTED state.
  
  fg[PRELIGHT] = { 0, 1.0, 1.0 }
  bg[PRELIGHT] = { 0, 0, 1.0 }
  bg[ACTIVE] = { 1.0, 0, 0 }
  fg[ACTIVE] = { 0, 1.0, 0 }
  bg[NORMAL] = { 1.0, 1.0, 0 }
  fg[NORMAL] = { .99, 0, .99 }
  bg[INSENSITIVE] = { 1.0, 1.0, 1.0 }
  fg[INSENSITIVE] = { 1.0, 0, 1.0 }
}

# In this example, we inherit the attributes of the "button" style and then
# override the font and background color when prelit to create a new
# "mainButton" style.

style "mainButton" = "button"
{
  font = "-adobe-helvetica-medium-r-normal--*-100-*-*-*-*-*-*"
  bg[PRELIGHT] = { 0.75, 0, 0 }
}

style "toggleButton" = "button"
{
  fg[NORMAL] = { 1.0, 0, 0 }
  fg[ACTIVE] = { 1.0, 0, 0 }
  
  # This sets the background pixmap of the toggleButton to that of its
  # parent widget (as defined in the application).
  bgPixmap[NORMAL] = "&lt;parent>"
}

style "text"
{
  bgPixmap[NORMAL] = "marble.xpm"
  fg[NORMAL] = { 1.0, 1.0, 1.0 }
}

style "ruler"
{
  font = "-adobe-helvetica-medium-r-normal--*-80-*-*-*-*-*-*"
}

# pixmapPath "~/.pixmaps"

# These set the widget types to use the styles defined above.
# The widget types are listed in the class hierarchy, but could probably be
# just listed in this document for the users reference.

widgetClass "GtkWindow" style "window"
widgetClass "GtkDialog" style "window"
widgetClass "GtkFileSelection" style "window"
widgetClass "*Gtk*Scale" style "scale"
widgetClass "*GtkCheckButton*" style "toggleButton"
widgetClass "*GtkRadioButton*" style "toggleButton"
widgetClass "*GtkButton*" style "button"
widgetClass "*Ruler" style "ruler"
widgetClass "*GtkText" style "text"

# This sets all the buttons that are children of the "main window" to
# the mainButton style.  These must be documented to be taken advantage of.
widget "main window.*GtkButton*" style "mainButton"
</programlisting>

</sect1>
</chapter>

<!--**************************************************************** -->
<chapter id="ch-WritingYourOwnWidgets">
<title>Writing Your Own Widgets</title>

<!-- ----------------------------------------------------------------- -->
<sect1 id="sec-WidgetsOverview">
<title>Overview</title>

<para>Although the GTK distribution comes with many types of widgets that
should cover most basic needs, there may come a time when you need to
create your own new widget type. Since GTK uses widget inheritance
extensively, and there is already a widget that is close to what you want,
it is often possible to make a useful new widget type in
just a few lines of code. But before starting work on a new widget, check
around first to make sure that someone has not already written
it. This will prevent duplication of effort and keep the number of
GTK widgets out there to a minimum, which will help keep both the code
and the interface of different applications consistent. As a flip side
to this, once you finish your widget, announce it to the world so
other people can benefit. The best place to do this is probably the
<literal>gtk-list</literal>.</para>

<para>Complete sources for the example widgets are available at the place you 
got this tutorial, or from:</para>

<para><ulink url="http://www.gtk.org/~otaylor/gtk/tutorial/">http://www.gtk.org/~otaylor/gtk/tutorial/</ulink></para>


</sect1>

<!-- ----------------------------------------------------------------- -->
<sect1 id="sec-TheAnatomyOfAWidget">
<title>The Anatomy Of A Widget</title>

<para>In order to create a new widget, it is important to have an
understanding of how GTK objects work. This section is just meant as a
brief overview. See the reference documentation for the details. </para>

<para>GTK widgets are implemented in an object oriented fashion. However,
they are implemented in standard C. This greatly improves portability
and stability over using current generation C++ compilers; however,
it does mean that the widget writer has to pay attention to some of
the implementation details. The information common to all instances of
one class of widgets (e.g., to all Button widgets) is stored in the 
<emphasis>class structure</emphasis>. There is only one copy of this in
which is stored information about the class's signals
(which act like virtual functions in C). To support inheritance, the
first field in the class structure must be a copy of the parent's
class structure. The declaration of the class structure of GtkButtton
looks like:</para>

<programlisting role="R">
struct GtkButtonClass
{
  GtkContainerClass parentClass;

  void (* pressed)  (GtkButton#button);
  void (* released) (GtkButton#button);
  void (* clicked)  (GtkButton#button);
  void (* enter)    (GtkButton#button);
  void (* leave)    (GtkButton#button);
};
</programlisting>

<para>When a button is treated as a container (for instance, when it is
resized), its class structure can be cast to GtkContainerClass, and
the relevant fields used to handle the signals.</para>

<para>There is also a structure for each widget that is created on a
per-instance basis. This structure has fields to store information that
is different for each instance of the widget. We'll call this
structure the <emphasis>object structure</emphasis>. For the Button class, it looks
like:</para>

<programlisting role="R">
struct GtkButton
{
  GtkContainer container;

  GtkWidget#child;

  guint inButton : 1;
  guint buttonDown : 1;
};
</programlisting>

<para>Note that, similar to the class structure, the first field is the
object structure of the parent class, so that this structure can be
cast to the parent class' object structure as needed.</para>

</sect1>

<!-- ----------------------------------------------------------------- -->
<sect1 id="sec-CreatingACompositeWidget">
<title>Creating a Composite widget</title>

<!-- ----------------------------------------------------------------- -->
<sect2>
<title>Introduction</title>

<para>One type of widget that you may be interested in creating is a
widget that is merely an aggregate of other GTK widgets. This type of
widget does nothing that couldn't be done without creating new
widgets, but provides a convenient way of packaging user interface
elements for reuse. The FileSelection and ColorSelection widgets in
the standard distribution are examples of this type of widget.</para>

<para>The example widget that we'll create in this section is the Tictactoe
widget, a 3x3 array of toggle buttons which triggers a signal when all
three buttons in a row, column, or on one of the diagonals are
depressed. </para>

<para><emphasis>Note: the full source code for the Tictactoe example described
below is in the <link linkend="sec-Tictactoe">Code Examples Appendix</link>
</emphasis></para>

<para>
<inlinemediaobject>
<imageobject>
<imagedata fileref="images/tictactoe.png" format="png">
</imageobject>
</inlinemediaobject>
</para>

</sect2>

<!-- ----------------------------------------------------------------- -->
<sect2>
<title>Choosing a parent class</title>

<para>The parent class for a composite widget is typically the container
class that holds all of the elements of the composite widget. For
example, the parent class of the FileSelection widget is the
Dialog class. Since our buttons will be arranged in a table, it
is natural to make our parent class the Table class.</para>

</sect2>

<!-- ----------------------------------------------------------------- -->
<sect2>
<title>The header file</title>

<para>Each GObject class has a header file which declares the object and
class structures for that object, along with public functions. 
A couple of features are worth pointing out. To prevent duplicate
definitions, we wrap the entire header file in:</para>

<programlisting role="R">
#ifndef _TICTACTOEH_
#define _TICTACTOEH_
.
.
.
#endif # _TICTACTOEH_ 
</programlisting>

<para>And to keep C++ programs that include the header file happy, in:</para>

<programlisting role="R">
#include &lt;glib.h&gt;

GBEGINDECLS
.
.
.
GENDDECLS
</programlisting>

<para>Along with the functions and structures, we declare five standard
macros in our header file, <literal>TICTACTOETYPE</literal>,
<literal>TICTACTOE(obj)</literal>,
<literal>TICTACTOECLASS(klass)</literal>,
<literal>ISTICTACTOE(obj)</literal>, and
<literal>ISTICTACTOECLASS(klass)</literal>, which cast a
pointer into a pointer to the object or class structure, and check
if an object is a Tictactoe widget respectively.</para>

</sect2>

<!-- ----------------------------------------------------------------- -->
<sect2>
<title>The <literal>GetType()</literal> function</title>

<para>We now continue on to the implementation of our widget. A core
function for every object is the function
<literal>WIDGETNAMEGetType()</literal>. This function, when first called, tells
Glib about the new class, and gets an ID that uniquely identifies
the class. Upon subsequent calls, it just returns the ID.</para>

<programlisting role="R">
GType
tictactoeGetType (void)
{
  static GType tttType = 0;

  if (!tttType)
    {
      static const GTypeInfo tttInfo =
      {
	sizeof (TictactoeClass),
	NULL, # baseInit 
	NULL, # baseFinalize 
	(GClassInitFunc) tictactoeClassInit,
	NULL, # classFinalize 
	NULL, # classData 
	sizeof (Tictactoe),
	0,    # nPreallocs 
	(GInstanceInitFunc) tictactoeInit,
      };

      tttType = gTypeRegisterStatic (GTKTYPETABLE,
                                         "Tictactoe",
                                         &amp;tttInfo,
                                         0);
    }

  return tttType;
}
</programlisting>

<para>The GTypeInfo structure has the following definition:</para>

<programlisting role="R">
struct GTypeInfo
{
  # interface types, classed types, instantiated types 
  guint16                classSize;
   
  GBaseInitFunc          baseInit;
  GBaseFinalizeFunc      baseFinalize;
   
  # classed types, instantiated types 
  GClassInitFunc         classInit;
  GClassFinalizeFunc     classFinalize;
  gconstpointer          classData;
   
  # instantiated types 
  guint16                instanceSize;
  guint16                nPreallocs;
  GInstanceInitFunc      instanceInit;
   
  # value handling 
  const GTypeValueTable#valueTable;
};
</programlisting>

<para>The important fields of this structure are pretty self-explanatory.
We'll ignore the <literal>baseInit</literal> and
 <literal>baseFinalize</literal> as well as the <literal>valueTable</literal>
fields here. Once Glib has a correctly filled in copy of
this structure, it knows how to create objects of a particular type. </para>

</sect2>

<!-- ----------------------------------------------------------------- -->
<sect2>
<title>The <literal>ClassInit()</literal> function</title>

<para>The <literal>WIDGETNAMEClassInit()</literal> function initializes the fields of
the widget's class structure, and sets up any signals for the
class. For our Tictactoe widget it looks like:</para>

<programlisting role="R">
enum {
  TICTACTOESIGNAL,
  LASTSIGNAL
};


static guint tictactoeSignals[LASTSIGNAL] = { 0 };

static void
tictactoeClassInit (TictactoeClass#klass)
{
  tictactoeSignals[TICTACTOESIGNAL] =
    gSignalNew ("tictactoe",
                  GTYPEFROMCLASS (klass),
                  GSIGNALRUNFIRST | GSIGNALACTION,
                  GSTRUCTOFFSET (TictactoeClass, tictactoe),
                  NULL, NULL,
                  gCclosureMarshalVOID_VOID, GTYPENONE, 0);
}
</programlisting>

<para>Our widget has just one signal, the <literal>tictactoe</literal> signal that is
invoked when a row, column, or diagonal is completely filled in. Not
every composite widget needs signals, so if you are reading this for
the first time, you may want to skip to the next section now, as
things are going to get a bit complicated.</para>

<para>The function:</para>

<programlisting role="R">
guint gSignalNew( const gchar        #signalName,
                    GType                itype,
                    GSignalFlags         signalFlags,
                    guint                classOffset,
                    GSignalAccumulator #accumulator,
                    gpointer             accuData,
                    GSignalCMarshaller #cMarshaller,
                    GType                returnType,
                    guint                nParams,
                    ...);
</programlisting>

<para>Creates a new signal. The parameters are:</para>

<itemizedlist>
<listitem><simpara> <literal>signalName</literal>: The name of the signal.</simpara>
</listitem>

<listitem><simpara> <literal>itype</literal>: The ID of the object that this signal applies
to. (It will also apply to that objects descendants.)</simpara>
</listitem>
                                                                                
<listitem><simpara> <literal>signalFlags</literal>: Whether the default handler runs before or after
user handlers and other flags. Usually this will be one of
<literal>GSIGNALRUNFIRST</literal> or <literal>GSIGNALRUNLAST</literal>,
although there are other possibilities. The flag
<literal>GSIGNALACTION</literal> specifies that no extra code needs to
run that performs special pre or post emission adjustments. This means that
the signal can also be emitted from object external code.</simpara>
</listitem>

<listitem><simpara> <literal>classOffset</literal>: The offset within the class structure of
a pointer to the default handler.</simpara>
</listitem>

<listitem><simpara> <literal>accumulator</literal>: For most classes this can
be set to NULL.</simpara></listitem>

<listitem><simpara> <literal>accuData</literal>: User data that will be handed
to the accumulator function.</simpara></listitem>

<listitem><simpara> <literal>cMarshaller</literal>: A function that is used to invoke the signal
handler. For signal handlers that have no arguments other than the
object that emitted the signal and user data, we can use the
pre-supplied marshaller function <literal>gCclosureMarshalVOID_VOID</literal>.</simpara>
</listitem>

<listitem><simpara> <literal>returnType</literal>: The type of the return value.</simpara>
</listitem>

<listitem><simpara> <literal>nParams</literal>: The number of parameters of the signal handler
(other than the two default ones mentioned above)</simpara>
</listitem>

<listitem><simpara> <literal>...</literal>: The types of the parameters.</simpara>
</listitem>
</itemizedlist>

<para>When specifying types, the following standard types can be used:</para>

<programlisting role="R">
GTYPEINVALID
GTYPENONE
GTYPEINTERFACE
GTYPECHAR
GTYPEUCHAR
GTYPEBOOLEAN
GTYPEINT
GTYPEUINT
GTYPELONG
GTYPEULONG
GTYPEINT64
GTYPEUINT64
GTYPEENUM
GTYPEFLAGS
GTYPEFLOAT
GTYPEDOUBLE
GTYPESTRING
GTYPEPOINTER
GTYPEBOXED
GTYPEPARAM
GTYPEOBJECT
</programlisting>

<para><literal>gSignalNew()</literal> returns a unique integer identifier for the
signal, that we store in the <literal>tictactoeSignals</literal> array, which we
index using an enumeration. (Conventionally, the enumeration elements
are the signal name, uppercased, but here there would be a conflict
with the <literal>TICTACTOE()</literal> macro, so we called it <literal>TICTACTOESIGNAL</literal>
instead.</para>

</sect2>

<!-- ----------------------------------------------------------------- -->
<sect2>
<title>The <literal>Init()</literal> function</title>

<para>Each class also needs a function to initialize the object
structure. Usually, this function has the fairly limited role of
setting the fields of the structure to default values. For composite
widgets, however, this function also creates the component widgets.</para>

<programlisting role="R">
static void
tictactoeInit (Tictactoe#ttt)
{
  gint i,j;

  gtkTableResize (GTKTABLE (ttt), 3, 3);
  gtkTableSetHomogeneous (GTKTABLE (ttt), TRUE);

  for (i=0;i&lt;3; i++)
    for (j=0;j&lt;3; j++)
      {
	ttt->buttons[i][j] = gtkToggleButtonNew ();
	gtkTableAttachDefaults (GTKTABLE (ttt), ttt->buttons[i][j], 
				   i, i+1, j, j+1);
	gSignalConnect (GOBJECT (ttt->buttons[i][j]), "toggled",
			  GCALLBACK (tictactoeToggle), ttt);
	gtkWidgetSetSizeRequest (ttt->buttons[i][j], 20, 20);
	gtkWidgetShow (ttt->buttons[i][j]);
      }
}
</programlisting>

</sect2>

<!-- ----------------------------------------------------------------- -->
<sect2>
<title>And the rest...</title>

<para>There is one more function that every object (except for abstract
classes like Bin that cannot be instantiated) needs to have - the
function that the user calls to create an object of that type. This is
conventionally called <literal>OBJECTNAMENew()</literal>. In some
widgets, though not for the Tictactoe widgets, this function takes
arguments, and does some setup based on the arguments. The other two
functions are specific to the Tictactoe widget. </para>

<para><literal>tictactoeClear()</literal> is a public function that resets all the
buttons in the widget to the up position. Note the use of
<literal>gSignalHandlersBlockMatched()</literal> to keep our signal handler for
button toggles from being triggered unnecessarily.</para>

<para><literal>tictactoeToggle()</literal> is the signal handler that is invoked when the
user clicks on a button. It checks to see if there are any winning
combinations that involve the toggled button, and if so, emits
the "tictactoe" signal.</para>

<programlisting role="R">
GtkWidget*
tictactoeNew (void)
{
  return GTKWIDGET ( gObjectNew (TICTACTOETYPE, NULL));
}

void	       
tictactoeClear (Tictactoe#ttt)
{
  int i,j;

  for (i=0;i&lt;3;i++)
    for (j=0;j&lt;3;j++)
      {
	gSignalHandlersBlockMatched (GOBJECT (ttt->buttons[i][j]),
                                         GSIGNALMATCHDATA,
                                         0, 0, NULL, NULL, ttt);
	gtkToggleButtonSetActive (GTKTOGGLEBUTTON (ttt->buttons[i][j]),
				     FALSE);
	gSignalHandlersUnblockMatched (GOBJECT (ttt->buttons[i][j]),
                                           GSIGNALMATCHDATA,
                                           0, 0, NULL, NULL, ttt);
      }
}

static void
tictactoeToggle (GtkWidget#widget, Tictactoe#ttt)
{
  int i,k;

  static int rwins[8][3] = { { 0, 0, 0 }, { 1, 1, 1 }, { 2, 2, 2 },
			     { 0, 1, 2 }, { 0, 1, 2 }, { 0, 1, 2 },
			     { 0, 1, 2 }, { 0, 1, 2 } };
  static int cwins[8][3] = { { 0, 1, 2 }, { 0, 1, 2 }, { 0, 1, 2 },
			     { 0, 0, 0 }, { 1, 1, 1 }, { 2, 2, 2 },
			     { 0, 1, 2 }, { 2, 1, 0 } };

  int success, found;

  for (k=0; k&lt;8; k++)
    {
      success = TRUE;
      found = FALSE;

      for (i=0;i&lt;3;i++)
	{
	  success = success &amp;&amp; 
	    GTKTOGGLEBUTTON(ttt->buttons[rwins[k][i]][cwins[k][i]])->active;
	  found = found ||
	    ttt->buttons[rwins[k][i]][cwins[k][i]] == widget;
	}
      
      if (success &amp;&amp; found)
	{
	  gSignalEmit (GOBJECT (ttt), 
			 tictactoeSignals[TICTACTOESIGNAL], 0);
	  break;
	}
    }
}
</programlisting>

<para>And finally, an example program using our Tictactoe widget:</para>

<programlisting role="R">
#include &lt;gtk/gtk.h&gt;
#include "tictactoe.h"

# Invoked when a row, column or diagonal is completed 
void
win (GtkWidget#widget, gpointer data)
{
  gPrint ("Yay!\n");
  tictactoeClear (TICTACTOE (widget));
}

int 
main (int argc, char#argv[])
{
  GtkWidget#window;
  GtkWidget#ttt;
  
  gtkInit (&amp;argc, &amp;argv);

  window = gtkWindowNew (GTKWINDOWTOPLEVEL);
  
  gtkWindowSetTitle (GTKWINDOW (window), "Aspect Frame");
  
  gSignalConnect (GOBJECT (window), "destroy",
                    GCALLBACK (exit), NULL);
  
  gtkContainerSetBorderWidth (GTKCONTAINER (window), 10);

  # Create a new Tictactoe widget 
  ttt = tictactoeNew ();
  gtkContainerAdd (GTKCONTAINER (window), ttt);
  gtkWidgetShow (ttt);

  # And attach to its "tictactoe" signal 
  gSignalConnect (GOBJECT (ttt), "tictactoe",
                    GCALLBACK (win), NULL);

  gtkWidgetShow (window);
  
  gtkMain ();
  
  return 0;
}
</programlisting>

</sect2>
</sect1>

<!-- ----------------------------------------------------------------- -->
<sect1 id="sec-CreatingAWidgetFromScratch">
<title>Creating a widget from scratch</title>

<!-- ----------------------------------------------------------------- -->
<sect2>
<title>Introduction</title>

<para>In this section, we'll learn more about how widgets display themselves
on the screen and interact with events. As an example of this, we'll
create an analog dial widget with a pointer that the user can drag to
set the value.</para>

<para>
<inlinemediaobject>
<imageobject>
<imagedata fileref="images/gtkdial.png" format="png">
</imageobject>
</inlinemediaobject>
</para>

</sect2>

<!-- ----------------------------------------------------------------- -->
<sect2>
<title>Displaying a widget on the screen</title>

<para>There are several steps that are involved in displaying on the screen.
After the widget is created with a call to <literal>WIDGETNAMENew()</literal>,
several more functions are needed:</para>

<itemizedlist>
<listitem><simpara> <literal>WIDGETNAMERealize()</literal> is responsible for creating an X
window for the widget if it has one.</simpara>
</listitem>
<listitem><simpara> <literal>WIDGETNAMEMap()</literal> is invoked after the user calls
<literal>gtkWidgetShow()</literal>. It is responsible for making sure the widget
is actually drawn on the screen (<emphasis>mapped</emphasis>). For a container class,
it must also make calls to <literal>map()</literal> functions of any child widgets.</simpara>
</listitem>
<listitem><simpara> <literal>WIDGETNAMEDraw()</literal> is invoked when <literal>gtkWidgetDraw()</literal>
is called for the widget or one of its ancestors. It makes the actual
calls to the drawing functions to draw the widget on the screen. For
container widgets, this function must make calls to
<literal>gtkWidgetDraw()</literal> for its child widgets.</simpara>
</listitem>
<listitem><simpara> <literal>WIDGETNAMEExpose()</literal> is a handler for expose events for the
widget. It makes the necessary calls to the drawing functions to draw
the exposed portion on the screen. For container widgets, this
function must generate expose events for its child widgets which don't
have their own windows. (If they have their own windows, then X will
generate the necessary expose events.)</simpara>
</listitem>
</itemizedlist>

<para>You might notice that the last two functions are quite similar - each
is responsible for drawing the widget on the screen. In fact many
types of widgets don't really care about the difference between the
two. The default <literal>draw()</literal> function in the widget class simply
generates a synthetic expose event for the redrawn area. However, some
types of widgets can save work by distinguishing between the two
functions. For instance, if a widget has multiple X windows, then
since expose events identify the exposed window, it can redraw only
the affected window, which is not possible for calls to <literal>draw()</literal>.</para>

<para>Container widgets, even if they don't care about the difference for
themselves, can't simply use the default <literal>draw()</literal> function because
their child widgets might care about the difference. However,
it would be wasteful to duplicate the drawing code between the two
functions. The convention is that such widgets have a function called
<literal>WIDGETNAMEPaint()</literal> that does the actual work of drawing the
widget, that is then called by the <literal>draw()</literal> and <literal>expose()</literal>
functions.</para>

<para>In our example approach, since the dial widget is not a container
widget, and only has a single window, we can take the simplest
approach and use the default <literal>draw()</literal> function and only implement
an <literal>expose()</literal> function.</para>

</sect2>

<!-- ----------------------------------------------------------------- -->
<sect2>
<title>The origins of the Dial Widget</title>

<para>Just as all land animals are just variants on the first amphibian that
crawled up out of the mud, GTK widgets tend to start off as variants
of some other, previously written widget. Thus, although this section
is entitled "Creating a Widget from Scratch", the Dial widget really
began with the source code for the Range widget. This was picked as a
starting point because it would be nice if our Dial had the same
interface as the Scale widgets which are just specialized descendants
of the Range widget. So, though the source code is presented below in
finished form, it should not be implied that it was written, <emphasis>ab
initio</emphasis> in this fashion. Also, if you aren't yet familiar with
how scale widgets work from the application writer's point of view, it
would be a good idea to look them over before continuing.</para>

</sect2>

<!-- ----------------------------------------------------------------- -->
<sect2>
<title>The Basics</title>

<para>Quite a bit of our widget should look pretty familiar from the
Tictactoe widget. First, we have a header file:</para>

<programlisting role="R">
# GTK - The GIMP Toolkit
# Copyright (C) 1995-1997 Peter Mattis, Spencer Kimball and Josh MacDonald
#
# This library is free software; you can redistribute it and/or
# modify it under the terms of the GNU Library General Public
# License as published by the Free Software Foundation; either
# version 2 of the License, or (at your option) any later version.
#
# This library is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
# Library General Public License for more details.
#
# You should have received a copy of the GNU Library General Public
# License along with this library; if not, write to the Free
# Software Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
 

#ifndef _GTKDIALH_
#define _GTKDIALH_

#include &lt;gdk/gdk.h&gt;
#include &lt;gtk/gtkadjustment.h&gt;
#include &lt;gtk/gtkwidget.h&gt;


#ifdef _cplusplus
extern "C" {
#endif # _cplusplus 


#define GTKDIAL(obj)          GTKCHECKCAST (obj, gtkDialGetType (), GtkDial)
#define GTKDIALCLASS(klass)  GTKCHECKCLASSCAST (klass, gtkDialGetType (), GtkDialClass)
#define GTKISDIAL(obj)       GTKCHECKTYPE (obj, gtkDialGetType ())


typedef struct GtkDial        GtkDial;
typedef struct GtkDialClass   GtkDialClass;

struct GtkDial
{
  GtkWidget widget;

  # update policy (GTKUPDATE[CONTINUOUS/DELAYED/DISCONTINUOUS]) 
  guint policy : 2;

  # Button currently pressed or 0 if none 
  guint8 button;

  # Dimensions of dial components 
  gint radius;
  gint pointerWidth;

  # ID of update timer, or 0 if none 
  guint32 timer;

  # Current angle 
  gfloat angle;

  # Old values from adjustment stored so we know when something changes 
  gfloat oldValue;
  gfloat oldLower;
  gfloat oldUpper;

  # The adjustment object that stores the data for this dial 
  GtkAdjustment#adjustment;
};

struct GtkDialClass
{
  GtkWidgetClass parentClass;
};


GtkWidget*     gtkDialNew                    (GtkAdjustment#adjustment);
GtkType        gtkDialGetType               (void);
GtkAdjustment* gtkDialGetAdjustment         (GtkDial     #dial);
void           gtkDialSetUpdatePolicy      (GtkDial     #dial,
						GtkUpdateType  policy);

void           gtkDialSetAdjustment         (GtkDial     #dial,
						GtkAdjustment#adjustment);
#ifdef _cplusplus
}
#endif # _cplusplus 


#endif # _GTKDIALH_ 
</programlisting>

<para>Since there is quite a bit more going on in this widget than the last
one, we have more fields in the data structure, but otherwise things
are pretty similar.</para>

<para>Next, after including header files and declaring a few constants,
we have some functions to provide information about the widget
and initialize it:</para>

<programlisting role="R">
#include &lt;math.h&gt;
#include &lt;stdio.h&gt;
#include &lt;gtk/gtkmain.h&gt;
#include &lt;gtk/gtksignal.h&gt;

#include "gtkdial.h"

#define SCROLLDELAYLENGTH  300
#define DIALDEFAULTSIZE 100

# Forward declarations 

[ omitted to save space ]

# Local data 

static GtkWidgetClass#parentClass = NULL;

GtkType
gtkDialGetType ()
{
  static GtkType dialType = 0;

  if (!dialType)
    {
      static const GtkTypeInfo dialInfo =
      {
	"GtkDial",
	sizeof (GtkDial),
	sizeof (GtkDialClass),
	(GtkClassInitFunc) gtkDialClassInit,
	(GtkObjectInitFunc) gtkDialInit,
	# reserved1  NULL,
	# reserved1  NULL,
	(GtkClassInitFunc) NULL
      };

      dialType = gtkTypeUnique (GTKTYPEWIDGET, &amp;dialInfo);
    }

  return dialType;
}

static void
gtkDialClassInit (GtkDialClass#class)
{
  GtkObjectClass#objectClass;
  GtkWidgetClass#widgetClass;

  objectClass = (GtkObjectClass*) class;
  widgetClass = (GtkWidgetClass*) class;

  parentClass = gtkTypeClass (gtkWidgetGetType ());

  objectClass->destroy = gtkDialDestroy;

  widgetClass->realize = gtkDialRealize;
  widgetClass->exposeEvent = gtkDialExpose;
  widgetClass->sizeRequest = gtkDialSizeRequest;
  widgetClass->sizeAllocate = gtkDialSizeAllocate;
  widgetClass->buttonPressEvent = gtkDialButtonPress;
  widgetClass->buttonReleaseEvent = gtkDialButtonRelease;
  widgetClass->motionNotifyEvent = gtkDialMotionNotify;
}

static void
gtkDialInit (GtkDial#dial)
{
  dial->button = 0;
  dial->policy = GTKUPDATECONTINUOUS;
  dial->timer = 0;
  dial->radius = 0;
  dial->pointerWidth = 0;
  dial->angle = 0.0;
  dial->oldValue = 0.0;
  dial->oldLower = 0.0;
  dial->oldUpper = 0.0;
  dial->adjustment = NULL;
}

GtkWidget*
gtkDialNew (GtkAdjustment#adjustment)
{
  GtkDial#dial;

  dial = gtkTypeNew (gtkDialGetType ());

  if (!adjustment)
    adjustment = (GtkAdjustment*) gtkAdjustmentNew (0.0, 0.0, 0.0, 0.0, 0.0, 0.0);

  gtkDialSetAdjustment (dial, adjustment);

  return GTKWIDGET (dial);
}

static void
gtkDialDestroy (GtkObject#object)
{
  GtkDial#dial;

  gReturnIfFail (object != NULL);
  gReturnIfFail (GTKISDIAL (object));

  dial = GTKDIAL (object);

  if (dial->adjustment)
    gtkObjectUnref (GTKOBJECT (dial->adjustment));

  if (GTKOBJECTCLASS (parentClass)->destroy)
    (* GTKOBJECTCLASS (parentClass)->destroy) (object);
}
</programlisting>

<para>Note that this <literal>init()</literal> function does less than for the Tictactoe
widget, since this is not a composite widget, and the <literal>new()</literal>
function does more, since it now has an argument. Also, note that when
we store a pointer to the Adjustment object, we increment its
reference count, (and correspondingly decrement it when we no longer
use it) so that GTK can keep track of when it can be safely destroyed.</para>

<para>Also, there are a few function to manipulate the widget's options:</para>

<programlisting role="R">
GtkAdjustment*
gtkDialGetAdjustment (GtkDial#dial)
{
  gReturnValIfFail (dial != NULL, NULL);
  gReturnValIfFail (GTKISDIAL (dial), NULL);

  return dial->adjustment;
}

void
gtkDialSetUpdatePolicy (GtkDial     #dial,
			     GtkUpdateType  policy)
{
  gReturnIfFail (dial != NULL);
  gReturnIfFail (GTKISDIAL (dial));

  dial->policy = policy;
}

void
gtkDialSetAdjustment (GtkDial     #dial,
			  GtkAdjustment#adjustment)
{
  gReturnIfFail (dial != NULL);
  gReturnIfFail (GTKISDIAL (dial));

  if (dial->adjustment)
    {
      gtkSignalDisconnectByData (GTKOBJECT (dial->adjustment), (gpointer) dial);
      gtkObjectUnref (GTKOBJECT (dial->adjustment));
    }

  dial->adjustment = adjustment;
  gtkObjectRef (GTKOBJECT (dial->adjustment));

  gtkSignalConnect (GTKOBJECT (adjustment), "changed",
		      (GtkSignalFunc) gtkDialAdjustmentChanged,
		      (gpointer) dial);
  gtkSignalConnect (GTKOBJECT (adjustment), "valueChanged",
		      (GtkSignalFunc) gtkDialAdjustmentValueChanged,
		      (gpointer) dial);

  dial->oldValue = adjustment->value;
  dial->oldLower = adjustment->lower;
  dial->oldUpper = adjustment->upper;

  gtkDialUpdate (dial);
}
</programlisting>

</sect2>

<!-- ----------------------------------------------------------------- -->
<sect2>
<title><literal>gtkDialRealize()</literal></title>

<para>Now we come to some new types of functions. First, we have a function
that does the work of creating the X window. Notice that a mask is
passed to the function <literal>gdkWindowNew()</literal> which specifies which fields of
the GdkWindowAttr structure actually have data in them (the remaining
fields will be given default values). Also worth noting is the way the
event mask of the widget is created. We call
<literal>gtkWidgetGetEvents()</literal> to retrieve the event mask that the user
has specified for this widget (with <literal>gtkWidgetSetEvents()</literal>), and
add the events that we are interested in ourselves.</para>

<para>After creating the window, we set its style and background, and put a
pointer to the widget in the user data field of the GdkWindow. This
last step allows GTK to dispatch events for this window to the correct
widget.</para>

<programlisting role="R">
static void
gtkDialRealize (GtkWidget#widget)
{
  GtkDial#dial;
  GdkWindowAttr attributes;
  gint attributesMask;

  gReturnIfFail (widget != NULL);
  gReturnIfFail (GTKISDIAL (widget));

  GTKWIDGETSETFLAGS (widget, GTKREALIZED);
  dial = GTKDIAL (widget);

  attributes.x = widget->allocation.x;
  attributes.y = widget->allocation.y;
  attributes.width = widget->allocation.width;
  attributes.height = widget->allocation.height;
  attributes.wclass = GDKINPUTOUTPUT;
  attributes.windowType = GDKWINDOWCHILD;
  attributes.eventMask = gtkWidgetGetEvents (widget) | 
    GDKEXPOSUREMASK | GDKBUTTONPRESSMASK | 
    GDKBUTTONRELEASEMASK | GDKPOINTERMOTIONMASK |
    GDKPOINTERMOTIONHINTMASK;
  attributes.visual = gtkWidgetGetVisual (widget);
  attributes.colormap = gtkWidgetGetColormap (widget);

  attributesMask = GDKWAX | GDKWAY | GDKWAVISUAL | GDKWACOLORMAP;
  widget->window = gdkWindowNew (widget->parent->window, &amp;attributes, attributesMask);

  widget->style = gtkStyleAttach (widget->style, widget->window);

  gdkWindowSetUserData (widget->window, widget);

  gtkStyleSetBackground (widget->style, widget->window, GTKSTATEACTIVE);
}
</programlisting>

</sect2>

<!-- ----------------------------------------------------------------- -->
<sect2>
<title>Size negotiation</title>

<para>Before the first time that the window containing a widget is
displayed, and whenever the layout of the window changes, GTK asks
each child widget for its desired size. This request is handled by the
function <literal>gtkDialSizeRequest()</literal>. Since our widget isn't a
container widget, and has no real constraints on its size, we just
return a reasonable default value.</para>

<programlisting role="R">
static void 
gtkDialSizeRequest (GtkWidget     #widget,
		       GtkRequisition#requisition)
{
  requisition->width = DIALDEFAULTSIZE;
  requisition->height = DIALDEFAULTSIZE;
}
</programlisting>

<para>After all the widgets have requested an ideal size, the layout of the
window is computed and each child widget is notified of its actual
size. Usually, this will be at least as large as the requested size,
but if for instance the user has resized the window, it may
occasionally be smaller than the requested size. The size notification
is handled by the function <literal>gtkDialSizeAllocate()</literal>. Notice that
as well as computing the sizes of some component pieces for future
use, this routine also does the grunt work of moving the widget's X
window into the new position and size.</para>

<programlisting role="R">
static void
gtkDialSizeAllocate (GtkWidget    #widget,
			GtkAllocation#allocation)
{
  GtkDial#dial;

  gReturnIfFail (widget != NULL);
  gReturnIfFail (GTKISDIAL (widget));
  gReturnIfFail (allocation != NULL);

  widget->allocation =#allocation;
  if (GTKWIDGETREALIZED (widget))
    {
      dial = GTKDIAL (widget);

      gdkWindowMoveResize (widget->window,
			      allocation->x, allocation->y,
			      allocation->width, allocation->height);

      dial->radius = MAX(allocation->width,allocation->height)# 0.45;
      dial->pointerWidth = dial->radius / 5;
    }
}
</programlisting>

</sect2>

<!-- ----------------------------------------------------------------- -->
<sect2>
<title><literal>gtkDialExpose()</literal></title>

<para>As mentioned above, all the drawing of this widget is done in the
handler for expose events. There's not much to remark on here except
the use of the function <literal>gtkDrawPolygon</literal> to draw the pointer with
three dimensional shading according to the colors stored in the
widget's style.</para>

<programlisting role="R">
static gboolean
gtkDialExpose( GtkWidget     #widget,
		 GdkEventExpose#event )
{
  GtkDial#dial;
  GdkPoint points[3];
  gdouble s,c;
  gdouble theta;
  gint xc, yc;
  gint tickLength;
  gint i;

  gReturnValIfFail (widget != NULL, FALSE);
  gReturnValIfFail (GTKISDIAL (widget), FALSE);
  gReturnValIfFail (event != NULL, FALSE);

  if (event->count > 0)
    return FALSE;
  
  dial = GTKDIAL (widget);

  gdkWindowClearArea (widget->window,
			 0, 0,
			 widget->allocation.width,
			 widget->allocation.height);

  xc = widget->allocation.width/2;
  yc = widget->allocation.height/2;

  # Draw ticks 

  for (i=0; i<25; i++)
    {
      theta = (i*MPI/18. - MPI/6.);
      s = sin(theta);
      c = cos(theta);

      tickLength = (i%6 == 0) ? dial->pointerWidth : dial->pointerWidth/2;
      
      gdkDrawLine (widget->window,
		     widget->style->fgGc[widget->state],
		     xc + c*(dial->radius - tickLength),
		     yc - s*(dial->radius - tickLength),
		     xc + c*dial->radius,
		     yc - s*dial->radius);
    }

  # Draw pointer 

  s = sin(dial->angle);
  c = cos(dial->angle);


  points[0].x = xc + s*dial->pointerWidth/2;
  points[0].y = yc + c*dial->pointerWidth/2;
  points[1].x = xc + c*dial->radius;
  points[1].y = yc - s*dial->radius;
  points[2].x = xc - s*dial->pointerWidth/2;
  points[2].y = yc - c*dial->pointerWidth/2;

  gtkDrawPolygon (widget->style,
		    widget->window,
		    GTKSTATENORMAL,
		    GTKSHADOWOUT,
		    points, 3,
		    TRUE);
  
  return FALSE;
}
</programlisting>

</sect2>

<!-- ----------------------------------------------------------------- -->
<sect2>
<title>Event handling</title>

<para>The rest of the widget's code handles various types of events, and
isn't too different from what would be found in many GTK
applications. Two types of events can occur - either the user can
click on the widget with the mouse and drag to move the pointer, or
the value of the Adjustment object can change due to some external
circumstance.</para>

<para>When the user clicks on the widget, we check to see if the click was
appropriately near the pointer, and if so, store the button that the
user clicked with in the <literal>button</literal> field of the widget
structure, and grab all mouse events with a call to
<literal>gtkGrabAdd()</literal>. Subsequent motion of the mouse causes the
value of the control to be recomputed (by the function
<literal>gtkDialUpdateMouse</literal>). Depending on the policy that has been
set, "valueChanged" events are either generated instantly
(<literal>GTKUPDATECONTINUOUS</literal>), after a delay in a timer added with
<literal>gTimeoutAdd()</literal> (<literal>GTKUPDATEDELAYED</literal>), or only when the
button is released (<literal>GTKUPDATEDISCONTINUOUS</literal>).</para>

<programlisting role="R">
static gboolean
gtkDialButtonPress( GtkWidget     #widget,
		       GdkEventButton#event )
{
  GtkDial#dial;
  gint dx, dy;
  double s, c;
  double dParallel;
  double dPerpendicular;

  gReturnValIfFail (widget != NULL, FALSE);
  gReturnValIfFail (GTKISDIAL (widget), FALSE);
  gReturnValIfFail (event != NULL, FALSE);

  dial = GTKDIAL (widget);

  # Determine if button press was within pointer region - we 
     do this by computing the parallel and perpendicular distance of
     the point where the mouse was pressed from the line passing through
     the pointer 
  
  dx = event->x - widget->allocation.width / 2;
  dy = widget->allocation.height / 2 - event->y;
  
  s = sin(dial->angle);
  c = cos(dial->angle);
  
  dParallel = s*dy + c*dx;
  dPerpendicular = fabs(s*dx - c*dy);
  
  if (!dial->button &&
      (dPerpendicular < dial->pointerWidth/2) &&
      (dParallel > - dial->pointerWidth))
    {
      gtkGrabAdd (widget);

      dial->button = event->button;

      gtkDialUpdateMouse (dial, event->x, event->y);
    }

  return FALSE;
}

static gboolean
gtkDialButtonRelease( GtkWidget     #widget,
			 GdkEventButton#event )
{
  GtkDial#dial;

  gReturnValIfFail (widget != NULL, FALSE);
  gReturnValIfFail (GTKISDIAL (widget), FALSE);
  gReturnValIfFail (event != NULL, FALSE);

  dial = GTKDIAL (widget);

  if (dial->button == event->button)
    {
      gtkGrabRemove (widget);

      dial->button = 0;

      if (dial->policy == GTKUPDATEDELAYED)
	gSourceRemove (dial->timer);
      
      if ((dial->policy != GTKUPDATECONTINUOUS) &&
	  (dial->oldValue != dial->adjustment->value))
	gtkSignalEmitByName (GTKOBJECT (dial->adjustment), "valueChanged");
    }

  return FALSE;
}

static gboolean
gtkDialMotionNotify( GtkWidget     #widget,
                        GdkEventMotion#event )
{
  GtkDial#dial;
  GdkModifierType mods;
  gint x, y, mask;

  gReturnValIfFail (widget != NULL, FALSE);
  gReturnValIfFail (GTKISDIAL (widget), FALSE);
  gReturnValIfFail (event != NULL, FALSE);

  dial = GTKDIAL (widget);

  if (dial->button != 0)
    {
      x = event->x;
      y = event->y;

      if (event->isHint || (event->window != widget->window))
	gdkWindowGetPointer (widget->window, &amp;x, &amp;y, &amp;mods);

      switch (dial->button)
	{
	case 1:
	  mask = GDKBUTTON1MASK;
	  break;
	case 2:
	  mask = GDKBUTTON2MASK;
	  break;
	case 3:
	  mask = GDKBUTTON3MASK;
	  break;
	default:
	  mask = 0;
	  break;
	}

      if (mods & mask)
	gtkDialUpdateMouse (dial, x,y);
    }

  return FALSE;
}

static gboolean
gtkDialTimer( GtkDial#dial )
{
  gReturnValIfFail (dial != NULL, FALSE);
  gReturnValIfFail (GTKISDIAL (dial), FALSE);

  if (dial->policy == GTKUPDATEDELAYED)
    gtkSignalEmitByName (GTKOBJECT (dial->adjustment), "valueChanged");

  return FALSE;
}

static void
gtkDialUpdateMouse (GtkDial#dial, gint x, gint y)
{
  gint xc, yc;
  gfloat oldValue;

  gReturnIfFail (dial != NULL);
  gReturnIfFail (GTKISDIAL (dial));

  xc = GTKWIDGET(dial)->allocation.width / 2;
  yc = GTKWIDGET(dial)->allocation.height / 2;

  oldValue = dial->adjustment->value;
  dial->angle = atan2(yc-y, x-xc);

  if (dial->angle < -MPI/2.)
    dial->angle += 2*MPI;

  if (dial->angle < -MPI/6)
    dial->angle = -MPI/6;

  if (dial->angle > 7.*MPI/6.)
    dial->angle = 7.*MPI/6.;

  dial->adjustment->value = dial->adjustment->lower + (7.*MPI/6 - dial->angle)#
    (dial->adjustment->upper - dial->adjustment->lower) / (4.*MPI/3.);

  if (dial->adjustment->value != oldValue)
    {
      if (dial->policy == GTKUPDATECONTINUOUS)
	{
	  gtkSignalEmitByName (GTKOBJECT (dial->adjustment), "valueChanged");
	}
      else
	{
	  gtkWidgetDraw (GTKWIDGET(dial), NULL);

	  if (dial->policy == GTKUPDATEDELAYED)
	    {
	      if (dial->timer)
		gSourceRemove (dial->timer);

	      dial->timer = gTimeoutAdd (SCROLLDELAYLENGTH,
				           (GtkFunction) gtkDialTimer,
					   (gpointer) dial);
	    }
	}
    }
}
</programlisting>

<para>Changes to the Adjustment by external means are communicated to our
widget by the "changed" and "valueChanged" signals. The handlers
for these functions call <literal>gtkDialUpdate()</literal> to validate the
arguments, compute the new pointer angle, and redraw the widget (by
calling <literal>gtkWidgetDraw()</literal>).</para>

<programlisting role="R">
static void
gtkDialUpdate (GtkDial#dial)
{
  gfloat newValue;
  
  gReturnIfFail (dial != NULL);
  gReturnIfFail (GTKISDIAL (dial));

  newValue = dial->adjustment->value;
  
  if (newValue < dial->adjustment->lower)
    newValue = dial->adjustment->lower;

  if (newValue > dial->adjustment->upper)
    newValue = dial->adjustment->upper;

  if (newValue != dial->adjustment->value)
    {
      dial->adjustment->value = newValue;
      gtkSignalEmitByName (GTKOBJECT (dial->adjustment), "valueChanged");
    }

  dial->angle = 7.*MPI/6. - (newValue - dial->adjustment->lower)# 4.*MPI/3. /
    (dial->adjustment->upper - dial->adjustment->lower);

  gtkWidgetDraw (GTKWIDGET(dial), NULL);
}

static void
gtkDialAdjustmentChanged (GtkAdjustment#adjustment,
			      gpointer       data)
{
  GtkDial#dial;

  gReturnIfFail (adjustment != NULL);
  gReturnIfFail (data != NULL);

  dial = GTKDIAL (data);

  if ((dial->oldValue != adjustment->value) ||
      (dial->oldLower != adjustment->lower) ||
      (dial->oldUpper != adjustment->upper))
    {
      gtkDialUpdate (dial);

      dial->oldValue = adjustment->value;
      dial->oldLower = adjustment->lower;
      dial->oldUpper = adjustment->upper;
    }
}

static void
gtkDialAdjustmentValueChanged (GtkAdjustment#adjustment,
				    gpointer       data)
{
  GtkDial#dial;

  gReturnIfFail (adjustment != NULL);
  gReturnIfFail (data != NULL);

  dial = GTKDIAL (data);

  if (dial->oldValue != adjustment->value)
    {
      gtkDialUpdate (dial);

      dial->oldValue = adjustment->value;
    }
}
</programlisting>

</sect2>

<!-- ----------------------------------------------------------------- -->
<sect2>
<title>Possible Enhancements</title>

<para>The Dial widget as we've described it so far runs about 670 lines of
code. Although that might sound like a fair bit, we've really
accomplished quite a bit with that much code, especially since much of
that length is headers and boilerplate. However, there are quite a few
more enhancements that could be made to this widget:</para>

<itemizedlist>
<listitem><simpara> If you try this widget out, you'll find that there is some
flashing as the pointer is dragged around. This is because the entire
widget is erased every time the pointer is moved before being
redrawn. Often, the best way to handle this problem is to draw to an
offscreen pixmap, then copy the final results onto the screen in one
step. (The ProgressBar widget draws itself in this fashion.)</simpara>
</listitem>

<listitem><simpara> The user should be able to use the up and down arrow keys to
increase and decrease the value.</simpara>
</listitem>

<listitem><simpara> It would be nice if the widget had buttons to increase and
decrease the value in small or large steps. Although it would be
possible to use embedded Button widgets for this, we would also like
the buttons to auto-repeat when held down, as the arrows on a
scrollbar do. Most of the code to implement this type of behavior can
be found in the Range widget.</simpara>
</listitem>

<listitem><simpara> The Dial widget could be made into a container widget with a
single child widget positioned at the bottom between the buttons
mentioned above. The user could then add their choice of a label or
entry widget to display the current value of the dial.</simpara>
</listitem>
</itemizedlist>

</sect2>
</sect1>

<!-- ----------------------------------------------------------------- -->
<sect1 id="sec-LearningMore">
<title>Learning More</title>

<para>Only a small part of the many details involved in creating widgets
could be described above. If you want to write your own widgets, the
best source of examples is the GTK source itself. Ask yourself some
questions about the widget you want to write: IS it a Container
widget? Does it have its own window? Is it a modification of an
existing widget? Then find a similar widget, and start making changes.
Good luck!</para>

</sect1>
</chapter>

<!--**************************************************************** -->
<chapter id="ch-Scribble">
<title>Scribble, A Simple Example Drawing Program</title>

<!-- ----------------------------------------------------------------- -->
<sect1 id="sec-ScribbleOverview">
<title>Overview</title>

<para>In this section, we will build a simple drawing program. In the
process, we will examine how to handle mouse events, how to draw in a
window, and how to do drawing better by using a backing pixmap. After
creating the simple drawing program, we will extend it by adding
support for XInput devices, such as drawing tablets. GTK provides
support routines which makes getting extended information, such as
pressure and tilt, from such devices quite easy.</para>

<para>
<inlinemediaobject>
<imageobject>
<imagedata fileref="images/scribble.png" format="png">
</imageobject>
</inlinemediaobject>
</para>

</sect1>

<!-- ----------------------------------------------------------------- -->
<sect1 id="sec-EventHandling">
<title>Event Handling</title>

<para>The GTK signals we have already discussed are for high-level actions,
such as a menu item being selected. However, sometimes it is useful to
learn about lower-level occurrences, such as the mouse being moved, or
a key being pressed. There are also GTK signals corresponding to these
low-level <emphasis>events</emphasis>. The handlers for these signals have an
extra parameter which is a pointer to a structure containing
information about the event. For instance, motion event handlers are
passed a pointer to a GdkEventMotion structure which looks (in part)
like:</para>

<programlisting role="R">
struct GdkEventMotion
{
  GdkEventType type;
  GdkWindow#window;
  guint32 time;
  gdouble x;
  gdouble y;
  ...
  guint state;
  ...
};
</programlisting>

<para><literal>type</literal> will be set to the event type, in this case
<literal>GDKMOTIONNOTIFY</literal>, window is the window in which the event
occurred. <literal>x</literal> and <literal>y</literal> give the coordinates of the event.
<literal>state</literal> specifies the modifier state when the event
occurred (that is, it specifies which modifier keys and mouse buttons
were pressed). It is the bitwise OR of some of the following:</para>

<programlisting role="R">
GDKSHIFTMASK  
GDKLOCKMASK   
GDKCONTROLMASK
GDKMOD1MASK   
GDKMOD2MASK   
GDKMOD3MASK   
GDKMOD4MASK   
GDKMOD5MASK   
GDKBUTTON1MASK
GDKBUTTON2MASK
GDKBUTTON3MASK
GDKBUTTON4MASK
GDKBUTTON5MASK
</programlisting>

<para>As for other signals, to determine what happens when an event occurs
we call <literal>gtkSignalConnect()</literal>. But we also need let GTK
know which events we want to be notified about. To do this, we call
the function:</para>

<programlisting role="R">
void gtkWidgetSetEvents (GtkWidget#widget,
                            gint      events);
</programlisting>

<para>The second field specifies the events we are interested in. It
is the bitwise OR of constants that specify different types
of events. For future reference the event types are:</para>

<programlisting role="R">
GDKEXPOSUREMASK
GDKPOINTERMOTIONMASK
GDKPOINTERMOTIONHINTMASK
GDKBUTTONMOTIONMASK     
GDKBUTTON1MOTIONMASK    
GDKBUTTON2MOTIONMASK    
GDKBUTTON3MOTIONMASK    
GDKBUTTONPRESSMASK      
GDKBUTTONRELEASEMASK    
GDKKEYPRESSMASK         
GDKKEYRELEASEMASK       
GDKENTERNOTIFYMASK      
GDKLEAVENOTIFYMASK      
GDKFOCUSCHANGEMASK      
GDKSTRUCTUREMASK         
GDKPROPERTYCHANGEMASK   
GDKPROXIMITYINMASK      
GDKPROXIMITYOUTMASK     
</programlisting>

<para>There are a few subtle points that have to be observed when calling
<literal>gtkWidgetSetEvents()</literal>. First, it must be called before the X window
for a GTK widget is created. In practical terms, this means you
should call it immediately after creating the widget. Second, the
widget must have an associated X window. For efficiency, many widget
types do not have their own window, but draw in their parent's window.
These widgets are:</para>

<programlisting role="R">
GtkAlignment
GtkArrow
GtkBin
GtkBox
GtkImage
GtkItem
GtkLabel
GtkPixmap
GtkScrolledWindow
GtkSeparator
GtkTable
GtkAspectFrame
GtkFrame
GtkVBox
GtkHBox
GtkVSeparator
GtkHSeparator
</programlisting>

<para>To capture events for these widgets, you need to use an EventBox
widget. See the section on the <link linkend="sec-EventBox">EventBox</link> widget for details.</para>

<para>For our drawing program, we want to know when the mouse button is
pressed and when the mouse is moved, so we specify
<literal>GDKPOINTERMOTIONMASK</literal> and <literal>GDKBUTTONPRESSMASK</literal>. We also
want to know when we need to redraw our window, so we specify
<literal>GDKEXPOSUREMASK</literal>. Although we want to be notified via a
Configure event when our window size changes, we don't have to specify
the corresponding <literal>GDKSTRUCTUREMASK</literal> flag, because it is
automatically specified for all windows.</para>

<para>It turns out, however, that there is a problem with just specifying
<literal>GDKPOINTERMOTIONMASK</literal>. This will cause the server to add a new
motion event to the event queue every time the user moves the mouse.
Imagine that it takes us 0.1 seconds to handle a motion event, but the
X server queues a new motion event every 0.05 seconds. We will soon
get way behind the users drawing. If the user draws for 5 seconds,
it will take us another 5 seconds to catch up after they release 
the mouse button! What we would like is to only get one motion
event for each event we process. The way to do this is to 
specify <literal>GDKPOINTERMOTIONHINTMASK</literal>. </para>

<para>When we specify <literal>GDKPOINTERMOTIONHINTMASK</literal>, the server sends
us a motion event the first time the pointer moves after entering
our window, or after a button press or release event. Subsequent 
motion events will be suppressed until we explicitly ask for
the position of the pointer using the function:</para>

<programlisting role="R">
GdkWindow*    gdkWindowGetPointer     (GdkWindow      #window,
					  gint           #x,
					  gint           #y,
					  GdkModifierType#mask);
</programlisting>

<para>(There is another function, <literal>gtkWidgetGetPointer()</literal> which
has a simpler interface, but turns out not to be very useful, since
it only retrieves the position of the mouse, not whether the buttons
are pressed.)</para>

<para>The code to set the events for our window then looks like:</para>

<programlisting role="R">
  gtkSignalConnect (GTKOBJECT (drawingArea), "exposeEvent",
		      (GtkSignalFunc) exposeEvent, NULL);
  gtkSignalConnect (GTKOBJECT(drawingArea),"configureEvent",
		      (GtkSignalFunc) configureEvent, NULL);
  gtkSignalConnect (GTKOBJECT (drawingArea), "motionNotifyEvent",
		      (GtkSignalFunc) motionNotifyEvent, NULL);
  gtkSignalConnect (GTKOBJECT (drawingArea), "buttonPressEvent",
		      (GtkSignalFunc) buttonPressEvent, NULL);

  gtkWidgetSetEvents (drawingArea, GDKEXPOSUREMASK
			 | GDKLEAVENOTIFYMASK
			 | GDKBUTTONPRESSMASK
			 | GDKPOINTERMOTIONMASK
			 | GDKPOINTERMOTIONHINTMASK);
</programlisting>

<para>We'll save the "exposeEvent" and "configureEvent" handlers for
later. The "motionNotifyEvent" and "buttonPressEvent" handlers
are pretty simple:</para>

<programlisting role="R">
static gboolean
buttonPressEvent( GtkWidget#widget, GdkEventButton#event )
{
  if (event->button == 1 &amp;&amp; pixmap != NULL)
      drawBrush (widget, event->x, event->y);

  return TRUE;
}

static gboolean
motionNotifyEvent( GtkWidget#widget, GdkEventMotion#event )
{
  int x, y;
  GdkModifierType state;

  if (event->isHint)
    gdkWindowGetPointer (event->window, &amp;x, &amp;y, &amp;state);
  else
    {
      x = event->x;
      y = event->y;
      state = event->state;
    }
    
  if (state &amp; GDKBUTTON1MASK &amp;&amp; pixmap != NULL)
    drawBrush (widget, x, y);
  
  return TRUE;
}
</programlisting>

</sect1>

<!-- ----------------------------------------------------------------- -->
<sect1 id="sec-TheDrawingAreaWidget">
<title>The DrawingArea Widget, And Drawing</title>

<para>We now turn to the process of drawing on the screen. The 
widget we use for this is the DrawingArea widget. A drawing area
widget is essentially an X window and nothing more. It is a blank
canvas in which we can draw whatever we like. A drawing area
is created using the call:</para>

<programlisting role="R">
GtkWidget* gtkDrawingAreaNew        (void);
</programlisting>

<para>A default size for the widget can be specified by calling:</para>

<programlisting role="R">
void       gtkDrawingAreaSize       (GtkDrawingArea     #darea,
					gint                 width,
					gint                 height);
</programlisting>

<para>This default size can be overridden, as is true for all widgets,
by calling <literal>gtkWidgetSetSizeRequest()</literal>, and that, in turn, can
be overridden if the user manually resizes the the window containing
the drawing area.</para>

<para>It should be noted that when we create a DrawingArea widget, we are
<emphasis>completely</emphasis> responsible for drawing the contents. If our
window is obscured then uncovered, we get an exposure event and must
redraw what was previously hidden.</para>

<para>Having to remember everything that was drawn on the screen so we
can properly redraw it can, to say the least, be a nuisance. In
addition, it can be visually distracting if portions of the
window are cleared, then redrawn step by step. The solution to
this problem is to use an offscreen <emphasis>backing pixmap</emphasis>.
Instead of drawing directly to the screen, we draw to an image
stored in server memory but not displayed, then when the image
changes or new portions of the image are displayed, we copy the
relevant portions onto the screen.</para>

<para>To create an offscreen pixmap, we call the function:</para>

<programlisting role="R">
GdkPixmap* gdkPixmapNew               (GdkWindow #window,
					 gint        width,
					 gint        height,
					 gint        depth);
</programlisting>

<para>The <literal>window</literal> parameter specifies a GDK window that this pixmap
takes some of its properties from. <literal>width</literal> and <literal>height</literal>
specify the size of the pixmap. <literal>depth</literal> specifies the <emphasis>color
depth</emphasis>, that is the number of bits per pixel, for the new window.
If the depth is specified as <literal>-1</literal>, it will match the depth
of <literal>window</literal>.</para>

<para>We create the pixmap in our "configureEvent" handler. This event
is generated whenever the window changes size, including when it
is originally created.</para>

<programlisting role="R">
# Backing pixmap for drawing area 
static GdkPixmap#pixmap = NULL;

# Create a new backing pixmap of the appropriate size 
static gboolean
configureEvent( GtkWidget#widget, GdkEventConfigure#event )
{
  if (pixmap)
    gObjectUnref(pixmap);

  pixmap = gdkPixmapNew(widget->window,
			  widget->allocation.width,
			  widget->allocation.height,
			  -1);
  gdkDrawRectangle (pixmap,
		      widget->style->whiteGc,
		      TRUE,
		      0, 0,
		      widget->allocation.width,
		      widget->allocation.height);

  return TRUE;
}
</programlisting>

<para>The call to <literal>gdkDrawRectangle()</literal> clears the pixmap
initially to white. We'll say more about that in a moment.</para>

<para>Our exposure event handler then simply copies the relevant portion
of the pixmap onto the screen (we determine the area we need
to redraw by using the event->area field of the exposure event):</para>

<programlisting role="R">
# Redraw the screen from the backing pixmap 
static gboolean
exposeEvent( GtkWidget#widget, GdkEventExpose#event )
{
  gdkDrawDrawable(widget->window,
		    widget->style->fgGc[GTKWIDGETSTATE (widget)],
		    pixmap,
		    event->area.x, event->area.y,
		    event->area.x, event->area.y,
		    event->area.width, event->area.height);

  return FALSE;
}
</programlisting>

<para>We've now seen how to keep the screen up to date with our pixmap, but
how do we actually draw interesting stuff on our pixmap?  There are a
large number of calls in GTK's GDK library for drawing on
<emphasis>drawables</emphasis>. A drawable is simply something that can be drawn
upon. It can be a window, a pixmap, or a bitmap (a black and white
image).  We've already seen two such calls above,
<literal>gdkDrawRectangle()</literal> and <literal>gdkDrawDrawable()</literal>. The
complete list is:</para>

<programlisting role="R">
gdkDrawPoint ()
gdkDrawLine ()
gdkDrawRectangle ()
gdkDrawArc ()
gdkDrawPolygon ()
gdkDrawPixmap ()
gdkDrawBitmap ()
gdkDrawImage ()
gdkDrawPoints ()
gdkDrawSegments ()
gdkDrawLines ()
gdkDrawPixbuf ()
gdkDrawGlyphs ()
gdkDrawLayoutLine ()
gdkDrawLayout ()
gdkDrawLayoutLineWithColors ()
gdkDrawLayoutWithColors ()
gdkDrawGlyphsTransformed ()
gdkDrawGlyphsTrapezoids ()
</programlisting>

<para>See the reference documentation or the header file
<literal>&lt;gdk/gdkdrawable.h&gt;</literal> for further details on these functions.
These functions all share the same first two arguments. The first
argument is the drawable to draw upon, the second argument is a
<emphasis>graphics context</emphasis> (GC).</para>

<para>A graphics context encapsulates information about things such as
foreground and background color and line width. GDK has a full set of
functions for creating and modifying graphics contexts, but to keep
things simple we'll just use predefined graphics contexts. Each widget
has an associated style. (Which can be modified in a gtkrc file, see
the section GTK's rc file.) This, among other things, stores a number
of graphics contexts. Some examples of accessing these graphics
contexts are:</para>

<programlisting role="R">
widget->style->whiteGc
widget->style->blackGc
widget->style->fgGc[GTKSTATENORMAL]
widget->style->bgGc[GTKWIDGETSTATE(widget)]
</programlisting>

<para>The fields <literal>fgGc</literal>, <literal>bgGc</literal>, <literal>darkGc</literal>, and
<literal>lightGc</literal> are indexed by a parameter of type
<literal>GtkStateType</literal> which can take on the values:</para>

<programlisting role="R">
GTKSTATENORMAL,
GTKSTATEACTIVE,
GTKSTATEPRELIGHT,
GTKSTATESELECTED,
GTKSTATEINSENSITIVE
</programlisting>

<para>For instance, for <literal>GTKSTATESELECTED</literal> the default foreground
color is white and the default background color, dark blue.</para>

<para>Our function <literal>drawBrush()</literal>, which does the actual drawing
on the screen, is then:</para>

<programlisting role="R">
# Draw a rectangle on the screen 
static void
drawBrush (GtkWidget#widget, gdouble x, gdouble y)
{
  GdkRectangle updateRect;

  updateRect.x = x - 5;
  updateRect.y = y - 5;
  updateRect.width = 10;
  updateRect.height = 10;
  gdkDrawRectangle (pixmap,
  		      widget->style->blackGc,
  		      TRUE,
		      updateRect.x, updateRect.y,
		      updateRect.width, updateRect.height);
  gtkWidgetQueueDrawArea (widget, 		      
                              updateRect.x, updateRect.y,
		              updateRect.width, updateRect.height);
}
</programlisting>

<para>After we draw the rectangle representing the brush onto the pixmap,
we call the function:</para>

<programlisting role="R">
void       gtkWidgetQueueDrawArea (GtkWidget          #widget,
			               gint                 x,
			               gint                 y,
			               gint                 width,
			               gint                 height)
</programlisting>

<para>which notifies X that the area given by the <literal>x</literal>, 
<literal>y</literal>, <literal>width</literal> and <literal>height</literal> parameters
needs to be updated. X will eventually generate an expose event
(possibly combining the areas passed in several calls to
<literal>gtkWidgetQueueDrawArea()</literal>) which will cause our expose event handler
to copy the relevant portions to the screen.</para>

<para>We have now covered the entire drawing program except for a few
mundane details like creating the main window.</para>

</sect1>

<!-- ----------------------------------------------------------------- -->
<sect1 id="sec-AddingXInputSupport">
<title>Adding XInput support</title>

<para>It is now possible to buy quite inexpensive input devices such 
as drawing tablets, which allow drawing with a much greater
ease of artistic expression than does a mouse. The simplest way
to use such devices is simply as a replacement for the mouse,
but that misses out many of the advantages of these devices,
such as:</para>

<itemizedlist>
<listitem><simpara> Pressure sensitivity</simpara>
</listitem>
<listitem><simpara> Tilt reporting</simpara>
</listitem>
<listitem><simpara> Sub-pixel positioning</simpara>
</listitem>
<listitem><simpara> Multiple inputs (for example, a stylus with a point and eraser)</simpara>
</listitem>
</itemizedlist>

<para>For information about the XInput extension, see the <ulink
url="http://www.gtk.org/~otaylor/xinput/howto/index.html">XInput HOWTO</ulink>.</para>

<para>If we examine the full definition of, for example, the GdkEventMotion
structure, we see that it has fields to support extended device
information.</para>

<programlisting role="R">
struct GdkEventMotion
{
  GdkEventType type;
  GdkWindow#window;
  guint32 time;
  gdouble x;
  gdouble y;
  gdouble pressure;
  gdouble xtilt;
  gdouble ytilt;
  guint state;
  gint16 isHint;
  GdkInputSource source;
  guint32 deviceid;
};
</programlisting>

<para><literal>pressure</literal> gives the pressure as a floating point number between
0 and 1. <literal>xtilt</literal> and <literal>ytilt</literal> can take on values between 
-1 and 1, corresponding to the degree of tilt in each direction.
<literal>source</literal> and <literal>deviceid</literal> specify the device for which the
event occurred in two different ways. <literal>source</literal> gives some simple
information about the type of device. It can take the enumeration
values:</para>

<programlisting role="R">
GDKSOURCEMOUSE
GDKSOURCEPEN
GDKSOURCEERASER
GDKSOURCECURSOR
</programlisting>

<para><literal>deviceid</literal> specifies a unique numeric ID for the device. This can
be used to find out further information about the device using the
<literal>gdkInputListDevices()</literal> call (see below). The special value
<literal>GDKCOREPOINTER</literal> is used for the core pointer device. (Usually
the mouse.)</para>

<!-- ----------------------------------------------------------------- -->
<sect2>
<title>Enabling extended device information</title>

<para>To let GTK know about our interest in the extended device information,
we merely have to add a single line to our program:</para>

<programlisting role="R">
gtkWidgetSetExtensionEvents (drawingArea, GDKEXTENSIONEVENTSCURSOR);
</programlisting>

<para>By giving the value <literal>GDKEXTENSIONEVENTSCURSOR</literal> we say that
we are interested in extension events, but only if we don't have
to draw our own cursor. See the section <link
linkend="sec-FurtherSophistications"> Further Sophistications </link> below
for more information about drawing the cursor. We could also 
give the values <literal>GDKEXTENSIONEVENTSALL</literal> if we were willing 
to draw our own cursor, or <literal>GDKEXTENSIONEVENTSNONE</literal> to revert
back to the default condition.</para>

<para>This is not completely the end of the story however. By default,
no extension devices are enabled. We need a mechanism to allow
users to enable and configure their extension devices. GTK provides
the InputDialog widget to automate this process. The following
procedure manages an InputDialog widget. It creates the dialog if
it isn't present, and raises it to the top otherwise.</para>

<programlisting role="R">
void
inputDialogDestroy (GtkWidget#w, gpointer data)
{
 #((GtkWidget*)data) = NULL;
}

void
createInputDialog ()
{
  static GtkWidget#inputd = NULL;

  if (!inputd)
    {
      inputd = gtkInputDialogNew();

      gtkSignalConnect (GTKOBJECT(inputd), "destroy",
			  (GtkSignalFunc)inputDialogDestroy, &amp;inputd);
      gtkSignalConnectObject (GTKOBJECT(GTKINPUTDIALOG(inputd)->closeButton),
				 "clicked",
				 (GtkSignalFunc)gtkWidgetHide,
				 GTKOBJECT(inputd));
      gtkWidgetHide ( GTKINPUTDIALOG(inputd)->saveButton);

      gtkWidgetShow (inputd);
    }
  else
    {
      if (!GTKWIDGETMAPPED(inputd))
	gtkWidgetShow(inputd);
      else
	gdkWindowRaise(inputd->window);
    }
}
</programlisting>

<para>(You might want to take note of the way we handle this dialog.  By
connecting to the "destroy" signal, we make sure that we don't keep a
pointer to dialog around after it is destroyed - that could lead to a
segfault.)</para>

<para>The InputDialog has two buttons "Close" and "Save", which by default
have no actions assigned to them. In the above function we make
"Close" hide the dialog, hide the "Save" button, since we don't
implement saving of XInput options in this program.</para>

</sect2>

<!-- ----------------------------------------------------------------- -->
<sect2>
<title>Using extended device information</title>

<para>Once we've enabled the device, we can just use the extended 
device information in the extra fields of the event structures.
In fact, it is always safe to use this information since these
fields will have reasonable default values even when extended
events are not enabled.</para>

<para>Once change we do have to make is to call
<literal>gdkInputWindowGetPointer()</literal> instead of
<literal>gdkWindowGetPointer</literal>. This is necessary because
<literal>gdkWindowGetPointer</literal> doesn't return the extended device
information.</para>

<programlisting role="R">
void gdkInputWindowGetPointer( GdkWindow      #window,
                                   guint32         deviceid,
                                   gdouble        #x,
                                   gdouble        #y,
                                   gdouble        #pressure,
                                   gdouble        #xtilt,
                                   gdouble        #ytilt,
                                   GdkModifierType#mask);
</programlisting>

<para>When calling this function, we need to specify the device ID as
well as the window. Usually, we'll get the device ID from the
<literal>deviceid</literal> field of an event structure. Again, this function
will return reasonable values when extension events are not
enabled. (In this case, <literal>event->deviceid</literal> will have the value
<literal>GDKCOREPOINTER</literal>).</para>

<para>So the basic structure of our button-press and motion event handlers
doesn't change much - we just need to add code to deal with the
extended information.</para>

<programlisting role="R">
static gboolean
buttonPressEvent( GtkWidget#widget, GdkEventButton#event )
{
  printButtonPress (event->deviceid);
  
  if (event->button == 1 &amp;&amp; pixmap != NULL)
    drawBrush (widget, event->source, event->x, event->y, event->pressure);

  return TRUE;
}

static gboolean
motionNotifyEvent( GtkWidget#widget, GdkEventMotion#event )
{
  gdouble x, y;
  gdouble pressure;
  GdkModifierType state;

  if (event->isHint)
    gdkInputWindowGetPointer (event->window, event->deviceid,
				  &amp;x, &amp;y, &amp;pressure, NULL, NULL, &amp;state);
  else
    {
      x = event->x;
      y = event->y;
      pressure = event->pressure;
      state = event->state;
    }
    
  if (state &amp; GDKBUTTON1MASK &amp;&amp; pixmap != NULL)
    drawBrush (widget, event->source, x, y, pressure);
  
  return TRUE;
}
</programlisting>

<para>We also need to do something with the new information. Our new
<literal>drawBrush()</literal> function draws with a different color for
each <literal>event->source</literal> and changes the brush size depending
on the pressure.</para>

<programlisting role="R">
# Draw a rectangle on the screen, size depending on pressure,
   and color on the type of device 
static void
drawBrush (GtkWidget#widget, GdkInputSource source,
	    gdouble x, gdouble y, gdouble pressure)
{
  GdkGC#gc;
  GdkRectangle updateRect;

  switch (source)
    {
    case GDKSOURCEMOUSE:
      gc = widget->style->darkGc[GTKWIDGETSTATE (widget)];
      break;
    case GDKSOURCEPEN:
      gc = widget->style->blackGc;
      break;
    case GDKSOURCEERASER:
      gc = widget->style->whiteGc;
      break;
    default:
      gc = widget->style->lightGc[GTKWIDGETSTATE (widget)];
    }

  updateRect.x = x - 10# pressure;
  updateRect.y = y - 10# pressure;
  updateRect.width = 20# pressure;
  updateRect.height = 20# pressure;
  gdkDrawRectangle (pixmap, gc, TRUE,
		      updateRect.x, updateRect.y,
		      updateRect.width, updateRect.height);
  gtkWidgetDraw (widget, &amp;updateRect);
}
</programlisting>

</sect2>

<!-- ----------------------------------------------------------------- -->
<sect2>
<title>Finding out more about a device</title>

<para>As an example of how to find out more about a device, our program
will print the name of the device that generates each button
press. To find out the name of a device, we call the function:</para>

<programlisting role="R">
GList#gdkInputListDevices               (void);
</programlisting>

<para>which returns a GList (a linked list type from the GLib library)
of GdkDeviceInfo structures. The GdkDeviceInfo structure is defined
as:</para>

<programlisting role="R">
struct GdkDeviceInfo
{
  guint32 deviceid;
  gchar#name;
  GdkInputSource source;
  GdkInputMode mode;
  gint hasCursor;
  gint numAxes;
  GdkAxisUse#axes;
  gint numKeys;
  GdkDeviceKey#keys;
};
</programlisting>

<para>Most of these fields are configuration information that you can ignore
unless you are implementing XInput configuration saving. The fieldwe
are interested in here is <literal>name</literal> which is simply the name that X
assigns to the device. The other field that isn't configuration
information is <literal>hasCursor</literal>. If <literal>hasCursor</literal> is false, then we
we need to draw our own cursor. But since we've specified
<literal>GDKEXTENSIONEVENTSCURSOR</literal>, we don't have to worry about this.</para>

<para>Our <literal>printButtonPress()</literal> function simply iterates through
the returned list until it finds a match, then prints out
the name of the device.</para>

<programlisting role="R">
static void
printButtonPress (guint32 deviceid)
{
  GList#tmpList;

  # gdkInputListDevices returns an internal list, so we shouldn't
     free it afterwards 
  tmpList = gdkInputListDevices();

  while (tmpList)
    {
      GdkDeviceInfo#info = (GdkDeviceInfo#)tmpList->data;

      if (info->deviceid == deviceid)
	{
	  printf("Button press on device '%s'\n", info->name);
	  return;
	}

      tmpList = tmpList->next;
    }
}
</programlisting>

<para>That completes the changes to "XInputize" our program.</para>

</sect2>

<!-- ----------------------------------------------------------------- -->
<sect2 id="sec-FurtherSophistications">
<title>Further sophistications</title>

<para>Although our program now supports XInput quite well, it lacks some
features we would want in a full-featured application. First, the user
probably doesn't want to have to configure their device each time they
run the program, so we should allow them to save the device
configuration. This is done by iterating through the return of
<literal>gdkInputListDevices()</literal> and writing out the configuration to a
file.</para>

<para>To restore the state next time the program is run, GDK provides
functions to change device configuration:</para>

<programlisting role="R">
gdkInputSetExtensionEvents()
gdkInputSetSource()
gdkInputSetMode()
gdkInputSetAxes()
gdkInputSetKey()
</programlisting>

<para>(The list returned from <literal>gdkInputListDevices()</literal> should not be
modified directly.) An example of doing this can be found in the
drawing program gsumi. (Available from <ulink
url="http://www.msc.cornell.edu/~otaylor/gsumi/">http://www.msc.cornell.edu/~otaylor/gsumi/</ulink>) Eventually, it
would be nice to have a standard way of doing this for all
applications. This probably belongs at a slightly higher level than
GTK, perhaps in the GNOME library.</para>

<para>Another major omission that we have mentioned above is the lack of
cursor drawing. Platforms other than XFree86 currently do not allow
simultaneously using a device as both the core pointer and directly by
an application. See the <ulink
url="http://www.msc.cornell.edu/~otaylor/xinput/XInput-HOWTO.html">XInput-HOWTO</ulink> for more information about this. This means that
applications that want to support the widest audience need to draw
their own cursor.</para>

<para>An application that draws its own cursor needs to do two things:
determine if the current device needs a cursor drawn or not, and
determine if the current device is in proximity. (If the current
device is a drawing tablet, it's a nice touch to make the cursor 
disappear when the stylus is lifted from the tablet. When the
device is touching the stylus, that is called "in proximity.")
The first is done by searching the device list, as we did
to find out the device name. The second is achieved by selecting
"proximityOut" events. An example of drawing one's own cursor is
found in the "testinput" program found in the GTK distribution.</para>

</sect2>

</sect1>
</chapter>

<!--**************************************************************** -->
<chapter id="ch-Tips">
<title>Tips For Writing GTK Applications</title>

<para>This section is simply a gathering of wisdom, general style guidelines
and hints to creating good GTK applications. Currently this section
is very short, but I hope it will get longer in future editions of
this tutorial.</para>

<para>Use GNU autoconf and automake! They are your friends :) Automake
examines C files, determines how they depend on each other, and
generates a Makefile so the files can be compiled in the correct
order. Autoconf permits automatic configuration of software
installation, handling a large number of system quirks to increase
portability. I am planning to make a quick intro on them here.</para>

<para>When writing C code, use only C comments (beginning with "#" and
ending with ""), and don't use C++-style comments ("//").  Although
many C compilers understand C++ comments, others don't, and the ANSI C
standard does not require that C++-style comments be processed as
comments.</para>

</chapter>

<!--**************************************************************** -->
<chapter id="ch-Contributing">
<title>Contributing</title>

<para>This document, like so much other great software out there, was
created for free by volunteers.  If you are at all knowledgeable about
any aspect of GTK that does not already have documentation, please
consider contributing to this document.</para>

<para>If you do decide to contribute, please mail your text to Tony Gale,
<literal><ulink url="mailto:gale@gtk.org">gale@gtk.org</ulink></literal>. Also, be aware that the entirety of this
document is free, and any addition by you provide must also be
free. That is, people may use any portion of your examples in their
programs, and copies of this document may be distributed at will, etc.</para>

<para>Thank you.</para>

</chapter>

<!--**************************************************************** -->
<chapter id="ch-Credits">
<title>Credits</title>

<para>We would like to thank the following for their contributions to this text.</para>

<itemizedlist>
<listitem><simpara>Bawer Dagdeviren, <literal><ulink url="mailto:chamele0n@geocities.com">chamele0n@geocities.com</ulink></literal> for the menus tutorial.</simpara>
</listitem>

<listitem><simpara>Raph Levien, <literal><ulink url="mailto:raph@acm.org">raph@acm.org</ulink></literal>
for hello world ala GTK, widget packing, and general all around wisdom.
He's also generously donated a home for this tutorial.</simpara>
</listitem>

<listitem><simpara>Peter Mattis, <literal><ulink url="mailto:petm@xcf.berkeley.edu">petm@xcf.berkeley.edu</ulink></literal> for the simplest GTK program.. 
and the ability to make it :)</simpara>
</listitem>

<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
SGML, and the widget class hierarchy.</simpara>
</listitem>

<listitem><simpara>Mark Crichton <literal><ulink
url="mailto:crichton@expert.cc.purdue.edu">crichton@expert.cc.purdue.edu</ulink></literal> for the menu factory code,
and the table packing tutorial.</simpara>
</listitem>

<listitem><simpara>Owen Taylor <literal><ulink url="mailto:owt1@cornell.edu">owt1@cornell.edu</ulink></literal> for the EventBox widget section (and the
patch to the distro).  He's also responsible for the selections code
and tutorial, as well as the sections on writing your own GTK widgets,
and the example application. Thanks a lot Owen for all you help!</simpara>
</listitem>

<listitem><simpara>Mark VanderBoom <literal><ulink url="mailto:mvboom42@calvin.edu">mvboom42@calvin.edu</ulink></literal> for his wonderful work on the
Notebook, Progress Bar, Dialogs, and File selection widgets.  Thanks a
lot Mark!  You've been a great help.</simpara>
</listitem>

<listitem><simpara>Tim Janik <literal><ulink url="mailto:timj@gtk.org">timj@gtk.org</ulink></literal> for his great job on the Lists
Widget. His excellent work on automatically extracting the widget tree
and signal information from GTK. Thanks Tim :)</simpara>
</listitem>

<listitem><simpara>Rajat Datta <literal><ulink url="mailto:rajat@ix.netcom.com">rajat@ix.netcom.com</ulink>
</literal> for the excellent job on the Pixmap
tutorial.</simpara>
</listitem>

<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>
</listitem>

<listitem><simpara>David Huggins-Daines <literal><ulink
url="mailto:bn711@freenet.carleton.ca">bn711@freenet.carleton.ca</ulink></literal> for the Range Widgets and Tree
Widget sections.</simpara>
</listitem>

<listitem><simpara>Stefan Mars <literal><ulink url="mailto:mars@lysator.liu.se">mars@lysator.liu.se</ulink></literal> for the CList section.</simpara>
</listitem>

<listitem><simpara>David A. Wheeler <literal><ulink url="mailto:dwheeler@ida.org">dwheeler@ida.org</ulink></literal> for portions of the text on GLib
and various tutorial fixups and improvements.
The GLib text was in turn based on material developed by Damon Chaplin
<literal><ulink url="mailto:DAChaplin@msn.com">DAChaplin@msn.com</ulink></literal></simpara>
</listitem>

<listitem><simpara>David King for style checking the entire document.</simpara>
</listitem>
</itemizedlist>

<para>And to all of you who commented on and helped refine this document.</para>

<para>Thanks.</para>

</chapter>

<!--**************************************************************** -->
<chapter id="ch-Copyright">
<title>Tutorial Copyright and Permissions Notice</title>

<para>The GTK Tutorial is Copyright (C) 1997 Ian Main. </para>

<para>Copyright (C) 1998-2002 Tony Gale.</para>

<para>Permission is granted to make and distribute verbatim copies of this 
manual provided the copyright notice and this permission notice are 
preserved on all copies.</para>

<para>Permission is granted to copy and distribute modified versions of 
this document under the conditions for verbatim copying, provided that 
this copyright notice is included exactly as in the original,
and that the entire resulting derived work is distributed under 
the terms of a permission notice identical to this one.</para>

<para>Permission is granted to copy and distribute translations of this 
document into another language, under the above conditions for modified 
versions.</para>

<para>If you are intending to incorporate this document into a published 
work, please contact the maintainer, and we will make an effort 
to ensure that you have the most up to date information available.</para>

<para>There is no guarantee that this document lives up to its intended
purpose.  This is simply provided as a free resource.  As such,
the authors and maintainers of the information provided within can
not make any guarantee that the information is even accurate.</para>

</chapter>

<!--**************************************************************** -->
<!--**************************************************************** -->

<!--**************************************************************** -->
<appendix id="app-GTKSignals">
<title>GTK Signals</title>

<para>As GTK is an object oriented widget set, it has a hierarchy of
inheritance. This inheritance mechanism applies for
signals. Therefore, you should refer to the widget hierarchy tree when
using the signals listed in this section.</para>

<!-- ----------------------------------------------------------------- -->
<sect1 id="sec-GtkObject">
<title>GtkObject</title>

<programlisting role="R">
void GtkObject::destroy	(GtkObject#,
                       	 gpointer);
</programlisting>

</sect1>

<!-- ----------------------------------------------------------------- -->
<sect1 id="sec-GtkWidget">
<title>GtkWidget</title>

<programlisting role="R">
void GtkWidget::show	(GtkWidget#,
                    	 gpointer);
void GtkWidget::hide	(GtkWidget#,
                    	 gpointer);
void GtkWidget::map	(GtkWidget#,
                   	 gpointer);
void GtkWidget::unmap	(GtkWidget#,
                     	 gpointer);
void GtkWidget::realize	(GtkWidget#,
                       	 gpointer);
void GtkWidget::unrealize	(GtkWidget#,
                         	 gpointer);
void GtkWidget::draw	(GtkWidget#,
                    	 ggpointer,
                    	 gpointer);
void GtkWidget::draw-focus	(GtkWidget#,
                          	 gpointer);
void GtkWidget::draw-default	(GtkWidget#,
                            	 gpointer);
void GtkWidget::size-request	(GtkWidget#,
                            	 ggpointer,
                            	 gpointer);
void GtkWidget::size-allocate	(GtkWidget#,
                             	 ggpointer,
                             	 gpointer);
void GtkWidget::state-changed	(GtkWidget#,
                             	 GtkStateType,
                             	 gpointer);
void GtkWidget::parent-set	(GtkWidget#,
                          	 GtkObject#,
                          	 gpointer);
void GtkWidget::style-set	(GtkWidget#,
                         	 GtkStyle#,
                         	 gpointer);
void GtkWidget::add-accelerator	(GtkWidget#,
                               	 gguint,
                               	 GtkAccelGroup#,
                               	 gguint,
                               	 GdkModifierType,
                               	 GtkAccelFlags,
                               	 gpointer);
void GtkWidget::remove-accelerator	(GtkWidget#,
                                  	 GtkAccelGroup#,
                                  	 gguint,
                                  	 GdkModifierType,
                                  	 gpointer);
gboolean GtkWidget::event	(GtkWidget#,
                         	 GdkEvent#,
                         	 gpointer);
gboolean GtkWidget::button-press-event	(GtkWidget#,
                                      	 GdkEvent#,
                                      	 gpointer);
gboolean GtkWidget::button-release-event	(GtkWidget#,
                                        	 GdkEvent#,
                                        	 gpointer);
gboolean GtkWidget::motion-notify-event	(GtkWidget#,
                                       	 GdkEvent#,
                                       	 gpointer);
gboolean GtkWidget::delete-event	(GtkWidget#,
                                	 GdkEvent#,
                                	 gpointer);
gboolean GtkWidget::destroy-event	(GtkWidget#,
                                 	 GdkEvent#,
                                 	 gpointer);
gboolean GtkWidget::expose-event	(GtkWidget#,
                                	 GdkEvent#,
                                	 gpointer);
gboolean GtkWidget::key-press-event	(GtkWidget#,
                                   	 GdkEvent#,
                                   	 gpointer);
gboolean GtkWidget::key-release-event	(GtkWidget#,
                                     	 GdkEvent#,
                                     	 gpointer);
gboolean GtkWidget::enter-notify-event	(GtkWidget#,
                                      	 GdkEvent#,
                                      	 gpointer);
gboolean GtkWidget::leave-notify-event	(GtkWidget#,
                                      	 GdkEvent#,
                                      	 gpointer);
gboolean GtkWidget::configure-event	(GtkWidget#,
                                   	 GdkEvent#,
                                   	 gpointer);
gboolean GtkWidget::focus-in-event	(GtkWidget#,
                                  	 GdkEvent#,
                                  	 gpointer);
gboolean GtkWidget::focus-out-event	(GtkWidget#,
                                   	 GdkEvent#,
                                   	 gpointer);
gboolean GtkWidget::map-event	(GtkWidget#,
                             	 GdkEvent#,
                             	 gpointer);
gboolean GtkWidget::unmap-event	(GtkWidget#,
                               	 GdkEvent#,
                               	 gpointer);
gboolean GtkWidget::property-notify-event	(GtkWidget#,
                                         	 GdkEvent#,
                                         	 gpointer);
gboolean GtkWidget::selection-clear-event	(GtkWidget#,
                                         	 GdkEvent#,
                                         	 gpointer);
gboolean GtkWidget::selection-request-event	(GtkWidget#,
                                           	 GdkEvent#,
                                           	 gpointer);
gboolean GtkWidget::selection-notify-event	(GtkWidget#,
                                          	 GdkEvent#,
                                          	 gpointer);
void GtkWidget::selection-get	(GtkWidget#,
                             	 GtkSelectionData#,
                             	 gguint,
                             	 gpointer);
void GtkWidget::selection-received	(GtkWidget#,
                                  	 GtkSelectionData#,
                                  	 gguint,
                                  	 gpointer);
gboolean GtkWidget::proximity-in-event	(GtkWidget#,
                                      	 GdkEvent#,
                                      	 gpointer);
gboolean GtkWidget::proximity-out-event	(GtkWidget#,
                                       	 GdkEvent#,
                                       	 gpointer);
void GtkWidget::drag-begin	(GtkWidget#,
                          	 GdkDragContext#,
                          	 gpointer);
void GtkWidget::drag-end	(GtkWidget#,
                        	 GdkDragContext#,
                        	 gpointer);
void GtkWidget::drag-data-delete	(GtkWidget#,
                                	 GdkDragContext#,
                                	 gpointer);
void GtkWidget::drag-leave	(GtkWidget#,
                          	 GdkDragContext#,
                          	 gguint,
                          	 gpointer);
gboolean GtkWidget::drag-motion	(GtkWidget#,
                               	 GdkDragContext#,
                               	 ggint,
                               	 ggint,
                               	 gguint,
                               	 gpointer);
gboolean GtkWidget::drag-drop	(GtkWidget#,
                             	 GdkDragContext#,
                             	 ggint,
                             	 ggint,
                             	 gguint,
                             	 gpointer);
void GtkWidget::drag-data-get	(GtkWidget#,
                             	 GdkDragContext#,
                             	 GtkSelectionData#,
                             	 gguint,
                             	 gguint,
                             	 gpointer);
void GtkWidget::drag-data-received	(GtkWidget#,
                                  	 GdkDragContext#,
                                  	 ggint,
                                  	 ggint,
                                  	 GtkSelectionData#,
                                  	 gguint,
                                  	 gguint,
                                  	 gpointer);
gboolean GtkWidget::client-event	(GtkWidget#,
                                	 GdkEvent#,
                                	 gpointer);
gboolean GtkWidget::no-expose-event	(GtkWidget#,
                                   	 GdkEvent#,
                                   	 gpointer);
gboolean GtkWidget::visibility-notify-event	(GtkWidget#,
                                           	 GdkEvent#,
                                           	 gpointer);
void GtkWidget::debug-msg	(GtkWidget#,
                         	 GtkString#,
                         	 gpointer);
</programlisting>

</sect1>

<!-- ----------------------------------------------------------------- -->
<sect1 id="sec-GtkData">
<title>GtkData</title>

<programlisting role="R">
void GtkData::disconnect	(GtkData#,
                        	 gpointer);
</programlisting>

</sect1>

<!-- ----------------------------------------------------------------- -->
<sect1 id="sec-GtkContainer">
<title>GtkContainer</title>

<programlisting role="R">
void GtkContainer::add	(GtkContainer#,
                      	 GtkWidget#,
                      	 gpointer);
void GtkContainer::remove	(GtkContainer#,
                         	 GtkWidget#,
                         	 gpointer);
void GtkContainer::check-resize	(GtkContainer#,
                               	 gpointer);
GtkDirectionType GtkContainer::focus	(GtkContainer#,
                                    	 GtkDirectionType,
                                    	 gpointer);
void GtkContainer::set-focus-child	(GtkContainer#,
                                  	 GtkWidget#,
                                  	 gpointer);
</programlisting>

</sect1>

<!-- ----------------------------------------------------------------- -->
<sect1 id="sec-GtkCalendar">
<title>GtkCalendar</title>

<programlisting role="R">
void GtkCalendar::month-changed	(GtkCalendar#,
                               	 gpointer);
void GtkCalendar::day-selected	(GtkCalendar#,
                              	 gpointer);
void GtkCalendar::day-selected-double-click	(GtkCalendar#,
                                           	 gpointer);
void GtkCalendar::prev-month	(GtkCalendar#,
                            	 gpointer);
void GtkCalendar::next-month	(GtkCalendar#,
                            	 gpointer);
void GtkCalendar::prev-year	(GtkCalendar#,
                           	 gpointer);
void GtkCalendar::next-year	(GtkCalendar#,
                           	 gpointer);
</programlisting>

</sect1>

<!-- ----------------------------------------------------------------- -->
<sect1 id="sec-GtkEditable">
<title>GtkEditable</title>

<programlisting role="R">
void GtkEditable::changed	(GtkEditable#,
                         	 gpointer);
void GtkEditable::insert-text	(GtkEditable#,
                             	 GtkString#,
                             	 ggint,
                             	 ggpointer,
                             	 gpointer);
void GtkEditable::delete-text	(GtkEditable#,
                             	 ggint,
                             	 ggint,
                             	 gpointer);
void GtkEditable::activate	(GtkEditable#,
                          	 gpointer);
void GtkEditable::set-editable	(GtkEditable#,
                              	 gboolean,
                              	 gpointer);
void GtkEditable::move-cursor	(GtkEditable#,
                             	 ggint,
                             	 ggint,
                             	 gpointer);
void GtkEditable::move-word	(GtkEditable#,
                           	 ggint,
                           	 gpointer);
void GtkEditable::move-page	(GtkEditable#,
                           	 ggint,
                           	 ggint,
                           	 gpointer);
void GtkEditable::move-to-row	(GtkEditable#,
                             	 ggint,
                             	 gpointer);
void GtkEditable::move-to-column	(GtkEditable#,
                                	 ggint,
                                	 gpointer);
void GtkEditable::kill-char	(GtkEditable#,
                           	 ggint,
                           	 gpointer);
void GtkEditable::kill-word	(GtkEditable#,
                           	 ggint,
                           	 gpointer);
void GtkEditable::kill-line	(GtkEditable#,
                           	 ggint,
                           	 gpointer);
void GtkEditable::cut-clipboard	(GtkEditable#,
                               	 gpointer);
void GtkEditable::copy-clipboard	(GtkEditable#,
                                	 gpointer);
void GtkEditable::paste-clipboard	(GtkEditable#,
                                 	 gpointer);
</programlisting>

</sect1>

<!-- ----------------------------------------------------------------- -->
<sect1 id="sec-GtkNotebook">
<title>GtkNotebook</title>

<programlisting role="R">
void GtkNotebook::switch-page	(GtkNotebook#,
                             	 ggpointer,
                             	 gguint,
                             	 gpointer);
</programlisting>

</sect1>

<!-- ----------------------------------------------------------------- -->
<sect1 id="sec-GtkList">
<title>GtkList</title>

<programlisting role="R">
void GtkList::selection-changed	(GtkList#,
                               	 gpointer);
void GtkList::select-child	(GtkList#,
                          	 GtkWidget#,
                          	 gpointer);
void GtkList::unselect-child	(GtkList#,
                            	 GtkWidget#,
                            	 gpointer);
</programlisting>

</sect1>

<!-- ----------------------------------------------------------------- -->
<sect1 id="sec-GtkMenuShell">
<title>GtkMenuShell</title>

<programlisting role="R">
void GtkMenuShell::deactivate	(GtkMenuShell#,
                             	 gpointer);
void GtkMenuShell::selection-done	(GtkMenuShell#,
                                 	 gpointer);
void GtkMenuShell::move-current	(GtkMenuShell#,
                               	 GtkMenuDirectionType,
                               	 gpointer);
void GtkMenuShell::activate-current	(GtkMenuShell#,
                                   	 gboolean,
                                   	 gpointer);
void GtkMenuShell::cancel	(GtkMenuShell#,
                         	 gpointer);
</programlisting>

</sect1>

<!-- ----------------------------------------------------------------- -->
<sect1 id="sec-GtkToolbar">
<title>GtkToolbar</title>

<programlisting role="R">
void GtkToolbar::orientation-changed	(GtkToolbar#,
                                    	 ggint,
                                    	 gpointer);
void GtkToolbar::style-changed	(GtkToolbar#,
                              	 ggint,
                              	 gpointer);
</programlisting>

</sect1>

<!-- ----------------------------------------------------------------- -->
<sect1 id="sec-GtkButton">
<title>GtkButton</title>

<programlisting role="R">
void GtkButton::pressed	(GtkButton#,
                       	 gpointer);
void GtkButton::released	(GtkButton#,
                        	 gpointer);
void GtkButton::clicked	(GtkButton#,
                       	 gpointer);
void GtkButton::enter	(GtkButton#,
                     	 gpointer);
void GtkButton::leave	(GtkButton#,
                     	 gpointer);
</programlisting>

</sect1>

<!-- ----------------------------------------------------------------- -->
<sect1 id="sec-GtkItem">
<title>GtkItem</title>

<programlisting role="R">
void GtkItem::select	(GtkItem#,
                    	 gpointer);
void GtkItem::deselect	(GtkItem#,
                      	 gpointer);
void GtkItem::toggle	(GtkItem#,
                    	 gpointer);
</programlisting>

</sect1>

<!-- ----------------------------------------------------------------- -->
<sect1 id="sec-GtkWindow">
<title>GtkWindow</title>

<programlisting role="R">
void GtkWindow::set-focus	(GtkWindow#,
                         	 ggpointer,
                         	 gpointer);
</programlisting>

</sect1>

<!-- ----------------------------------------------------------------- -->
<sect1 id="sec-GtkHandleBox">
<title>GtkHandleBox</title>

<programlisting role="R">
void GtkHandleBox::child-attached	(GtkHandleBox#,
                                 	 GtkWidget#,
                                 	 gpointer);
void GtkHandleBox::child-detached	(GtkHandleBox#,
                                 	 GtkWidget#,
                                 	 gpointer);
</programlisting>

</sect1>

<!-- ----------------------------------------------------------------- -->
<sect1 id="sec-GtkToggleButton">
<title>GtkToggleButton</title>

<programlisting role="R">
void GtkToggleButton::toggled	(GtkToggleButton#,
                             	 gpointer);
</programlisting>

</sect1>

<!-- ----------------------------------------------------------------- -->
<sect1 id="sec-GtkMenuItem">
<title>GtkMenuItem</title>

<programlisting role="R">
void GtkMenuItem::activate	(GtkMenuItem#,
                          	 gpointer);
void GtkMenuItem::activate-item	(GtkMenuItem#,
                               	 gpointer);
</programlisting>

</sect1>

<!-- ----------------------------------------------------------------- -->
<sect1 id="sec-GtkCheckMenuItem">
<title>GtkCheckMenuItem</title>

<programlisting role="R">
void GtkCheckMenuItem::toggled	(GtkCheckMenuItem#,
                              	 gpointer);
</programlisting>

</sect1>

<!-- ----------------------------------------------------------------- -->
<sect1 id="sec-GtkInputDialog">
<title>GtkInputDialog</title>

<programlisting role="R">
void GtkInputDialog::enable-device	(GtkInputDialog#,
                                  	 ggint,
                                  	 gpointer);
void GtkInputDialog::disable-device	(GtkInputDialog#,
                                   	 ggint,
                                   	 gpointer);
</programlisting>

</sect1>

<!-- ----------------------------------------------------------------- -->
<sect1 id="sec-GtkColorSelection">
<title>GtkColorSelection</title>

<programlisting role="R">
void GtkColorSelection::color-changed	(GtkColorSelection#,
                                     	 gpointer);
</programlisting>

</sect1>

<!-- ----------------------------------------------------------------- -->
<sect1 id="sec-GtkStatusBar">
<title>GtkStatusBar</title>

<programlisting role="R">
void GtkStatusbar::text-pushed	(GtkStatusbar#,
                              	 gguint,
                              	 GtkString#,
                              	 gpointer);
void GtkStatusbar::text-popped	(GtkStatusbar#,
                              	 gguint,
                              	 GtkString#,
                              	 gpointer);
</programlisting>

</sect1>

<!-- ----------------------------------------------------------------- -->
<sect1 id="sec-GtkCurve">
<title>GtkCurve</title>

<programlisting role="R">
void GtkCurve::curve-type-changed	(GtkCurve#,
                                 	 gpointer);
</programlisting>

</sect1>

<!-- ----------------------------------------------------------------- -->
<sect1 id="sec-GtkAdjustment">
<title>GtkAdjustment</title>

<programlisting role="R">
void GtkAdjustment::changed	(GtkAdjustment#,
                           	 gpointer);
void GtkAdjustment::value-changed	(GtkAdjustment#,
                                 	 gpointer);
</programlisting>

</sect1>
</appendix>

<!--**************************************************************** -->
<appendix id="app-GDKEventTypes">
<title>GDK Event Types</title>

<para>The following data types are passed into event handlers by GTK+. For
each data type listed, the signals that use this data type are listed.</para>

<itemizedlist>
<listitem><simpara>  GdkEvent</simpara>
          <itemizedlist>
          <listitem><simpara>dragEndEvent</simpara>
	  </listitem>
          </itemizedlist>
</listitem>

<listitem><simpara>  GdkEventType<</simpara>
</listitem>

<listitem><simpara>  GdkEventAny</simpara>
          <itemizedlist>
          <listitem><simpara>deleteEvent</simpara>
	  </listitem>
          <listitem><simpara>destroyEvent</simpara>
	  </listitem>
          <listitem><simpara>mapEvent</simpara>
	  </listitem>
          <listitem><simpara>unmapEvent</simpara>
	  </listitem>
          <listitem><simpara>noExposeEvent</simpara>
	  </listitem>
          </itemizedlist>
</listitem>

<listitem><simpara>  GdkEventExpose</simpara>
          <itemizedlist>
          <listitem><simpara>exposeEvent</simpara>
	  </listitem>
          </itemizedlist>
</listitem>

<listitem><simpara>  GdkEventNoExpose</simpara>
</listitem>

<listitem><simpara>  GdkEventVisibility</simpara>
</listitem>

<listitem><simpara>  GdkEventMotion</simpara>
          <itemizedlist>
          <listitem><simpara>motionNotifyEvent</simpara>
	  </listitem>
	  </itemizedlist>
</listitem>
<listitem><simpara>  GdkEventButton</simpara>
          <itemizedlist>
          <listitem><simpara>buttonPressEvent</simpara>
	  </listitem>
	  <listitem><simpara>buttonReleaseEvent</simpara>
	  </listitem>
	  </itemizedlist>
</listitem>

<listitem><simpara>  GdkEventKey</simpara>
          <itemizedlist>
          <listitem><simpara>keyPressEvent</simpara>
	  </listitem>
          <listitem><simpara>keyReleaseEvent</simpara>
	  </listitem>
	  </itemizedlist>
</listitem>

<listitem><simpara>  GdkEventCrossing</simpara>
          <itemizedlist>
          <listitem><simpara>enterNotifyEvent</simpara>
	  </listitem>
          <listitem><simpara>leaveNotifyEvent</simpara>
	  </listitem>
	  </itemizedlist>
</listitem>

<listitem><simpara>  GdkEventFocus</simpara>
          <itemizedlist>
          <listitem><simpara>focusInEvent</simpara>
	  </listitem>
          <listitem><simpara>focusOutEvent</simpara>
	  </listitem>
	  </itemizedlist>
</listitem>

<listitem><simpara>  GdkEventConfigure</simpara>
          <itemizedlist>
          <listitem><simpara>configureEvent</simpara>
	  </listitem>
	  </itemizedlist>
</listitem>

<listitem><simpara>  GdkEventProperty</simpara>
          <itemizedlist>
          <listitem><simpara>propertyNotifyEvent</simpara>
	  </listitem>
	  </itemizedlist>
</listitem>

<listitem><simpara>  GdkEventSelection</simpara>
          <itemizedlist>
          <listitem><simpara>selectionClearEvent</simpara>
	  </listitem>
          <listitem><simpara>selectionRequestEvent</simpara>
	  </listitem>
          <listitem><simpara>selectionNotifyEvent</simpara>
	  </listitem>
	  </itemizedlist>
</listitem>

<listitem><simpara>  GdkEventProximity</simpara>
          <itemizedlist>
          <listitem><simpara>proximityInEvent</simpara>
	  </listitem>
          <listitem><simpara>proximityOutEvent</simpara>
	  </listitem>
	  </itemizedlist>
</listitem>

<listitem><simpara>  GdkEventDragBegin</simpara>
          <itemizedlist>
          <listitem><simpara>dragBeginEvent</simpara>
	  </listitem>
	  </itemizedlist>
</listitem>

<listitem><simpara>  GdkEventDragRequest</simpara>
          <itemizedlist>
          <listitem><simpara>dragRequestEvent</simpara>
	  </listitem>
	  </itemizedlist>
</listitem>

<listitem><simpara>  GdkEventDropEnter</simpara>
          <itemizedlist>
          <listitem><simpara>dropEnterEvent</simpara>
	  </listitem>
	  </itemizedlist>
</listitem>

<listitem><simpara>  GdkEventDropLeave</simpara>
          <itemizedlist>
          <listitem><simpara>dropLeaveEvent</simpara>
	  </listitem>
	  </itemizedlist>
</listitem>

<listitem><simpara>  GdkEventDropDataAvailable</simpara>
          <itemizedlist>
          <listitem><simpara>dropDataAvailableEvent</simpara>
	  </listitem>
	  </itemizedlist>
</listitem>

<listitem><simpara>  GdkEventClient</simpara>
          <itemizedlist>
          <listitem><simpara>clientEvent</simpara>
	  </listitem>
	  </itemizedlist>
</listitem>

<listitem><simpara>  GdkEventOther</simpara>
          <itemizedlist>
          <listitem><simpara>otherEvent</simpara>
	  </listitem>
	  </itemizedlist>
</listitem>
</itemizedlist>

<para>The data type <literal>GdkEventType</literal> is a special data type that is used by
all the other data types as an indicator of the data type being passed
to the signal handler. As you will see below, each of the event data
structures has a member of this type. It is defined as an enumeration
type as follows:</para>

<programlisting role="R">
typedef enum
{
  GDKNOTHING           = -1,
  GDKDELETE            = 0,
  GDKDESTROY           = 1,
  GDKEXPOSE            = 2,
  GDKMOTIONNOTIFY     = 3,
  GDKBUTTONPRESS      = 4,
  GDK2BUTTONPRESS     = 5,
  GDK3BUTTONPRESS     = 6,
  GDKBUTTONRELEASE    = 7,
  GDKKEYPRESS         = 8,
  GDKKEYRELEASE       = 9,
  GDKENTERNOTIFY      = 10,
  GDKLEAVENOTIFY      = 11,
  GDKFOCUSCHANGE      = 12,
  GDKCONFIGURE         = 13,
  GDKMAP               = 14,
  GDKUNMAP             = 15,
  GDKPROPERTYNOTIFY   = 16,
  GDKSELECTIONCLEAR   = 17,
  GDKSELECTIONREQUEST = 18,
  GDKSELECTIONNOTIFY  = 19,
  GDKPROXIMITYIN      = 20,
  GDKPROXIMITYOUT     = 21,
  GDKDRAGBEGIN        = 22,
  GDKDRAGREQUEST      = 23,
  GDKDROPENTER        = 24,
  GDKDROPLEAVE        = 25,
  GDKDROPDATAAVAIL   = 26,
  GDKCLIENTEVENT      = 27,
  GDKVISIBILITYNOTIFY = 28,
  GDKNOEXPOSE         = 29,
  GDKOTHEREVENT       = 9999  # Deprecated, use filters instead 
} GdkEventType;
</programlisting>

<para>The other event type that is different from the others is
<literal>GdkEvent</literal> itself. This is a union of all the other
data types, which allows it to be cast to a specific
event data type within a signal handler.</para>

<!-- Just a big list for now, needs expanding upon - TRG -->
<para>So, the event data types are defined as follows:</para>

<programlisting role="R">
struct GdkEventAny
{
  GdkEventType type;
  GdkWindow#window;
  gint8 sendEvent;
};

struct GdkEventExpose
{
  GdkEventType type;
  GdkWindow#window;
  gint8 sendEvent;
  GdkRectangle area;
  gint count; # If non-zero, how many more events follow. 
};

struct GdkEventNoExpose
{
  GdkEventType type;
  GdkWindow#window;
  gint8 sendEvent;
  # XXX: does anyone need the X majorCode or minorCode fields? 
};

struct GdkEventVisibility
{
  GdkEventType type;
  GdkWindow#window;
  gint8 sendEvent;
  GdkVisibilityState state;
};

struct GdkEventMotion
{
  GdkEventType type;
  GdkWindow#window;
  gint8 sendEvent;
  guint32 time;
  gdouble x;
  gdouble y;
  gdouble pressure;
  gdouble xtilt;
  gdouble ytilt;
  guint state;
  gint16 isHint;
  GdkInputSource source;
  guint32 deviceid;
  gdouble xRoot, yRoot;
};

struct GdkEventButton
{
  GdkEventType type;
  GdkWindow#window;
  gint8 sendEvent;
  guint32 time;
  gdouble x;
  gdouble y;
  gdouble pressure;
  gdouble xtilt;
  gdouble ytilt;
  guint state;
  guint button;
  GdkInputSource source;
  guint32 deviceid;
  gdouble xRoot, yRoot;
};

struct GdkEventKey
{
  GdkEventType type;
  GdkWindow#window;
  gint8 sendEvent;
  guint32 time;
  guint state;
  guint keyval;
  gint length;
  gchar#string;
};

struct GdkEventCrossing
{
  GdkEventType type;
  GdkWindow#window;
  gint8 sendEvent;
  GdkWindow#subwindow;
  GdkNotifyType detail;
};

struct GdkEventFocus
{
  GdkEventType type;
  GdkWindow#window;
  gint8 sendEvent;
  gint16 in;
};

struct GdkEventConfigure
{
  GdkEventType type;
  GdkWindow#window;
  gint8 sendEvent;
  gint16 x, y;
  gint16 width;
  gint16 height;
};

struct GdkEventProperty
{
  GdkEventType type;
  GdkWindow#window;
  gint8 sendEvent;
  GdkAtom atom;
  guint32 time;
  guint state;
};

struct GdkEventSelection
{
  GdkEventType type;
  GdkWindow#window;
  gint8 sendEvent;
  GdkAtom selection;
  GdkAtom target;
  GdkAtom property;
  guint32 requestor;
  guint32 time;
};

# This event type will be used pretty rarely. It only is important
   for XInput aware programs that are drawing their own cursor 

struct GdkEventProximity
{
  GdkEventType type;
  GdkWindow#window;
  gint8 sendEvent;
  guint32 time;
  GdkInputSource source;
  guint32 deviceid;
};

struct GdkEventDragRequest
{
  GdkEventType type;
  GdkWindow#window;
  gint8 sendEvent;
  guint32 requestor;
  union {
    struct {
      guint protocolVersion:4;
      guint sendreply:1;
      guint willaccept:1;
      guint deleteData:1; # Do#not* delete if link is sent, only
                              if data is sent 
      guint senddata:1;
      guint reserved:22;
    } flags;
    glong allflags;
  } u;
  guint8 isdrop; # This gdk event can be generated by a couple of
                    X events - this lets the app know whether the
                    drop really occurred or we just set the data 

  GdkPoint dropCoords;
  gchar#dataType;
  guint32 timestamp;
};

struct GdkEventDragBegin
{
  GdkEventType type;
  GdkWindow#window;
  gint8 sendEvent;
  union {
    struct {
      guint protocolVersion:4;
      guint reserved:28;
    } flags;
    glong allflags;
  } u;
};

struct GdkEventDropEnter
{
  GdkEventType type;
  GdkWindow#window;
  gint8 sendEvent;
  guint32 requestor;
  union {
    struct {
      guint protocolVersion:4;
      guint sendreply:1;
      guint extendedTypelist:1;
      guint reserved:26;
    } flags;
    glong allflags;
  } u;
};

struct GdkEventDropLeave
{
  GdkEventType type;
  GdkWindow#window;
  gint8 sendEvent;
  guint32 requestor;
  union {
    struct {
      guint protocolVersion:4;
      guint reserved:28;
    } flags;
    glong allflags;
  } u;
};

struct GdkEventDropDataAvailable
{
  GdkEventType type;
  GdkWindow#window;
  gint8 sendEvent;
  guint32 requestor;
  union {
    struct {
      guint protocolVersion:4;
      guint isdrop:1;
      guint reserved:25;
    } flags;
    glong allflags;
  } u;
  gchar#dataType; # MIME type 
  gulong dataNumbytes;
  gpointer data;
  guint32 timestamp;
  GdkPoint coords;
};

struct GdkEventClient
{
  GdkEventType type;
  GdkWindow#window;
  gint8 sendEvent;
  GdkAtom messageType;
  gushort dataFormat;
  union {
    char b[20];
    short s[10];
    long l[5];
  } data;
};

struct GdkEventOther
{
  GdkEventType type;
  GdkWindow#window;
  gint8 sendEvent;
  GdkXEvent#xevent;
};
</programlisting>

</appendix>

<!--**************************************************************** -->
<appendix id="app-CodeExamples">
<title>Code Examples</title>

<para>Below are the code examples that are used in the above text
which are not included in complete form elsewhere.</para>

<!-- ----------------------------------------------------------------- -->
<sect1 id="sec-Tictactoe">
<title>Tictactoe</title>
<!-- ----------------------------------------------------------------- -->
<sect2>
<title>tictactoe.h</title>

<programlisting role="R">
<!-- example-start tictactoe tictactoe.h -->
# GTK - The GIMP Toolkit
# Copyright (C) 1995-1997 Peter Mattis, Spencer Kimball and Josh MacDonald
#
# This library is free software; you can redistribute it and/or
# modify it under the terms of the GNU Library General Public
# License as published by the Free Software Foundation; either
# version 2 of the License, or (at your option) any later version.
#
# This library is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
# Library General Public License for more details.
#
# You should have received a copy of the GNU Library General Public
# License along with this library; if not, write to the
# Free Software Foundation, Inc., 59 Temple Place - Suite 330,
# Boston, MA 02111-1307, USA.
 
#ifndef _TICTACTOEH_
#define _TICTACTOEH_


#include &lt;glib.h&gt;
#include &lt;glib-object.h&gt;
#include &lt;gtk/gtktable.h&gt;


GBEGINDECLS

#define TICTACTOETYPE            (tictactoeGetType ())
#define TICTACTOE(obj)            (GTYPECHECKINSTANCECAST ((obj), TICTACTOETYPE, Tictactoe))
#define TICTACTOECLASS(klass)    (GTYPECHECKCLASSCAST ((klass), TICTACTOETYPE, TictactoeClass))
#define ISTICTACTOE(obj)         (GTYPECHECKINSTANCETYPE ((obj), TICTACTOETYPE))
#define ISTICTACTOECLASS(klass) (GTYPECHECKCLASSTYPE ((klass), TICTACTOETYPE))


typedef struct Tictactoe       Tictactoe;
typedef struct TictactoeClass  TictactoeClass;

struct Tictactoe
{
  GtkTable table;
  
  GtkWidget#buttons[3][3];
};

struct TictactoeClass
{
  GtkTableClass parentClass;

  void (* tictactoe) (Tictactoe#ttt);
};

GType          tictactoeGetType        (void);
GtkWidget*     tictactoeNew             (void);
void	       tictactoeClear           (Tictactoe#ttt);

GENDDECLS

#endif # _TICTACTOEH_ 

<!-- example-end -->
</programlisting>

</sect2>

<!-- ----------------------------------------------------------------- -->
<sect2>
<title>tictactoe.c</title>

<programlisting role="R">
<!-- example-start tictactoe tictactoe.c -->

# GTK - The GIMP Toolkit
# Copyright (C) 1995-1997 Peter Mattis, Spencer Kimball and Josh MacDonald
#
# This library is free software; you can redistribute it and/or
# modify it under the terms of the GNU Library General Public
# License as published by the Free Software Foundation; either
# version 2 of the License, or (at your option) any later version.
#
# This library is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
# Library General Public License for more details.
#
# You should have received a copy of the GNU Library General Public
# License along with this library; if not, write to the
# Free Software Foundation, Inc., 59 Temple Place - Suite 330,
# Boston, MA 02111-1307, USA.
 
#include &lt;gtk/gtksignal.h&gt;
#include &lt;gtk/gtktable.h&gt;
#include &lt;gtk/gtktogglebutton.h&gt;
#include "tictactoe.h"

enum {
  TICTACTOESIGNAL,
  LASTSIGNAL
};

static void tictactoeClassInit          (TictactoeClass#klass);
static void tictactoeInit                (Tictactoe     #ttt);
static void tictactoeToggle              (GtkWidget#widget, Tictactoe#ttt);

static guint tictactoeSignals[LASTSIGNAL] = { 0 };

GType
tictactoeGetType (void)
{
  static GType tttType = 0;

  if (!tttType)
    {
      static const GTypeInfo tttInfo =
      {
	sizeof (TictactoeClass),
	NULL, # baseInit 
        NULL, # baseFinalize 
	(GClassInitFunc) tictactoeClassInit,
        NULL, # classFinalize 
	NULL, # classData 
        sizeof (Tictactoe),
	0,
	(GInstanceInitFunc) tictactoeInit,
      };

      tttType = gTypeRegisterStatic (GTKTYPETABLE, "Tictactoe", &amp;tttInfo, 0);
    }

  return tttType;
}

static void
tictactoeClassInit (TictactoeClass#klass)
{
  
  tictactoeSignals[TICTACTOESIGNAL] = gSignalNew ("tictactoe",
					 GTYPEFROMCLASS (klass),
	                                 GSIGNALRUNFIRST | GSIGNALACTION,
	                                 GSTRUCTOFFSET (TictactoeClass, tictactoe),
                                         NULL, 
                                         NULL,                
					 gCclosureMarshalVOID_VOID,
                                         GTYPENONE, 0);


}

static void
tictactoeInit (Tictactoe#ttt)
{
  gint i,j;
  
  gtkTableResize (GTKTABLE (ttt), 3, 3);
  gtkTableSetHomogeneous (GTKTABLE (ttt), TRUE);

  for (i=0;i&lt;3; i++)
    for (j=0;j&lt;3; j++)      {
	ttt-&gt;buttons[i][j] = gtkToggleButtonNew ();
	gtkTableAttachDefaults (GTKTABLE (ttt), ttt-&gt;buttons[i][j], 
				   i, i+1, j, j+1);
	gSignalConnect (GOBJECT (ttt-&gt;buttons[i][j]), "toggled",
			  GCALLBACK (tictactoeToggle), (gpointer) ttt);
	gtkWidgetSetSizeRequest (ttt-&gt;buttons[i][j], 20, 20);
	gtkWidgetShow (ttt-&gt;buttons[i][j]);
      }
}

GtkWidget*
tictactoeNew ()
{
  return GTKWIDGET (gObjectNew (tictactoeGetType (), NULL));
}

void	       
tictactoeClear (Tictactoe#ttt)
{
  int i,j;

  for (i = 0; i&lt;3; i++)
    for (j = 0; j&lt;3; j++)
      {
	gSignalHandlersBlockMatched (GOBJECT (ttt-&gt;buttons[i][j]), 
                                         GSIGNALMATCHDATA,
                                         0, 0, NULL, NULL, ttt);
	gtkToggleButtonSetActive (GTKTOGGLEBUTTON (ttt-&gt;buttons[i][j]),
				      FALSE);
	gSignalHandlersUnblockMatched (GOBJECT (ttt->buttons[i][j]),
                                           GSIGNALMATCHDATA,
                                           0, 0, NULL, NULL, ttt);
      }
}

static void
tictactoeToggle (GtkWidget#widget, Tictactoe#ttt)
{
  int i,k;

  static int rwins[8][3] = { { 0, 0, 0 }, { 1, 1, 1 }, { 2, 2, 2 },
			     { 0, 1, 2 }, { 0, 1, 2 }, { 0, 1, 2 },
			     { 0, 1, 2 }, { 0, 1, 2 } };
  static int cwins[8][3] = { { 0, 1, 2 }, { 0, 1, 2 }, { 0, 1, 2 },
			     { 0, 0, 0 }, { 1, 1, 1 }, { 2, 2, 2 },
			     { 0, 1, 2 }, { 2, 1, 0 } };

  int success, found;

  for (k = 0; k&lt;8; k++)
    {
      success = TRUE;
      found = FALSE;

      for (i = 0; i&lt;3; i++)
	{
	  success = success &amp;&amp; 
	    GTKTOGGLEBUTTON (ttt-&gt;buttons[rwins[k][i]][cwins[k][i]])-&gt;active;
	  found = found ||
	    ttt-&gt;buttons[rwins[k][i]][cwins[k][i]] == widget;
	}
      
      if (success &amp;&amp; found)
	{
	  gSignalEmit (GOBJECT (ttt), 
	                 tictactoeSignals[TICTACTOESIGNAL], 0);
	  break;
	}
    }
}

<!-- example-end -->
</programlisting>

</sect2>

<!-- ----------------------------------------------------------------- -->
<sect2>
<title>tttTest.c</title>

<programlisting role="R">
<!-- example-start tictactoe tttTest.c -->

#include &lt;stdlib.h&gt;
#include &lt;gtk/gtk.h&gt;
#include "tictactoe.h"

void win( GtkWidget#widget,
          gpointer   data )
{
  gPrint ("Yay!\n");
  tictactoeClear (TICTACTOE (widget));
}

int main( int   argc,
          char#argv[] )
{
  GtkWidget#window;
  GtkWidget#ttt;
  
  gtkInit (&amp;argc, &amp;argv);

  window = gtkWindowNew (GTKWINDOWTOPLEVEL);
  
  gtkWindowSetTitle (GTKWINDOW (window), "Aspect Frame");
  
  gSignalConnect (GOBJECT (window), "destroy",
		    GCALLBACK (exit), NULL);
  
  gtkContainerSetBorderWidth (GTKCONTAINER (window), 10);

  ttt = tictactoeNew ();
  
  gtkContainerAdd (GTKCONTAINER (window), ttt);
  gtkWidgetShow (ttt);

  # And attach to its "tictactoe" signal 
  gSignalConnect (GOBJECT (ttt), "tictactoe",
		    GCALLBACK (win), NULL);

  gtkWidgetShow (window);
  
  gtkMain ();
  
  return 0;
}

<!-- example-end -->
</programlisting>

</sect2>
</sect1>

<!-- ----------------------------------------------------------------- -->
<sect1 id="sec-GtkDial">
<title>GtkDial</title>

<!-- ----------------------------------------------------------------- -->
<sect2>
<title>gtkdial.h</title>

<programlisting role="R">
<!-- example-start gtkdial gtkdial.h -->

# GTK - The GIMP Toolkit
# Copyright (C) 1995-1997 Peter Mattis, Spencer Kimball and Josh MacDonald
#
# This library is free software; you can redistribute it and/or
# modify it under the terms of the GNU Library General Public
# License as published by the Free Software Foundation; either
# version 2 of the License, or (at your option) any later version.
#
# This library is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
# Library General Public License for more details.
#
# You should have received a copy of the GNU Library General Public
# License along with this library; if not, write to the
# Free Software Foundation, Inc., 59 Temple Place - Suite 330,
# Boston, MA 02111-1307, USA.
 
#ifndef _GTKDIALH_
#define _GTKDIALH_


#include &lt;gdk/gdk.h&gt;
#include &lt;gtk/gtkadjustment.h&gt;
#include &lt;gtk/gtkwidget.h&gt;


#ifdef _cplusplus
extern "C" {
#endif # _cplusplus 


#define GTKDIAL(obj)          GTKCHECKCAST (obj, gtkDialGetType (), GtkDial)
#define GTKDIALCLASS(klass)  GTKCHECKCLASSCAST (klass, gtkDialGetType (), GtkDialClass)
#define GTKISDIAL(obj)       GTKCHECKTYPE (obj, gtkDialGetType ())


typedef struct GtkDial        GtkDial;
typedef struct GtkDialClass   GtkDialClass;

struct GtkDial
{
  GtkWidget widget;

  # update policy (GTKUPDATE[CONTINUOUS/DELAYED/DISCONTINUOUS]) 
  guint policy : 2;

  # Button currently pressed or 0 if none 
  guint8 button;

  # Dimensions of dial components 
  gint radius;
  gint pointerWidth;

  # ID of update timer, or 0 if none 
  guint32 timer;

  # Current angle 
  gfloat angle;
  gfloat lastAngle;

  # Old values from adjustment stored so we know when something changes 
  gfloat oldValue;
  gfloat oldLower;
  gfloat oldUpper;

  # The adjustment object that stores the data for this dial 
  GtkAdjustment#adjustment;
};

struct GtkDialClass
{
  GtkWidgetClass parentClass;
};


GtkWidget*     gtkDialNew                    (GtkAdjustment#adjustment);
GtkType        gtkDialGetType               (void);
GtkAdjustment* gtkDialGetAdjustment         (GtkDial     #dial);
void           gtkDialSetUpdatePolicy      (GtkDial     #dial,
						GtkUpdateType  policy);

void           gtkDialSetAdjustment         (GtkDial     #dial,
						GtkAdjustment#adjustment);
#ifdef _cplusplus
}
#endif # _cplusplus 


#endif # _GTKDIALH_ 
<!-- example-end -->
</programlisting>

</sect2>

<!-- ----------------------------------------------------------------- -->
<sect2>
<title>gtkdial.c</title>

<programlisting role="R">
<!-- example-start gtkdial gtkdial.c -->

# GTK - The GIMP Toolkit
# Copyright (C) 1995-1997 Peter Mattis, Spencer Kimball and Josh MacDonald
#
# This library is free software; you can redistribute it and/or
# modify it under the terms of the GNU Library General Public
# License as published by the Free Software Foundation; either
# version 2 of the License, or (at your option) any later version.
#
# This library is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
# Library General Public License for more details.
#
# You should have received a copy of the GNU Library General Public
# License along with this library; if not, write to the
# Free Software Foundation, Inc., 59 Temple Place - Suite 330,
# Boston, MA 02111-1307, USA.
 
#include &lt;math.h&gt;
#include &lt;stdio.h&gt;
#include &lt;gtk/gtkmain.h&gt;
#include &lt;gtk/gtksignal.h&gt;

#include "gtkdial.h"

#define SCROLLDELAYLENGTH  300
#define DIALDEFAULTSIZE 100

# Forward declarations 

static void gtkDialClassInit               (GtkDialClass    #klass);
static void gtkDialInit                     (GtkDial         #dial);
static void gtkDialDestroy                  (GtkObject       #object);
static void gtkDialRealize                  (GtkWidget       #widget);
static void gtkDialSizeRequest             (GtkWidget       #widget,
                                               GtkRequisition  #requisition);
static void gtkDialSizeAllocate            (GtkWidget       #widget,
                                               GtkAllocation   #allocation);
static gboolean gtkDialExpose               (GtkWidget       #widget,
                                               GdkEventExpose  #event);
static gboolean gtkDialButtonPress         (GtkWidget       #widget,
                                               GdkEventButton  #event);
static gboolean gtkDialButtonRelease       (GtkWidget       #widget,
                                               GdkEventButton  #event);
static gboolean gtkDialMotionNotify        (GtkWidget       #widget,
                                               GdkEventMotion  #event);
static gboolean gtkDialTimer                (GtkDial         #dial);

static void gtkDialUpdateMouse             (GtkDial#dial, gint x, gint y);
static void gtkDialUpdate                   (GtkDial#dial);
static void gtkDialAdjustmentChanged       (GtkAdjustment   #adjustment,
						gpointer          data);
static void gtkDialAdjustmentValueChanged (GtkAdjustment   #adjustment,
						gpointer          data);

# Local data 

static GtkWidgetClass#parentClass = NULL;

GType
gtkDialGetType ()
{
  static GType dialType = 0;

  if (!dialType)
    {
      static const GTypeInfo dialInfo =
      {
	sizeof (GtkDialClass),
	NULL,
	NULL,
	(GClassInitFunc) gtkDialClassInit,
	NULL,
	NULL,
	sizeof (GtkDial),
        0,
	(GInstanceInitFunc) gtkDialInit,
      };

      dialType = gTypeRegisterStatic (GTKTYPEWIDGET, "GtkDial", &amp;dialInfo, 0);
    }

  return dialType;
}

static void
gtkDialClassInit (GtkDialClass#class)
{
  GtkObjectClass#objectClass;
  GtkWidgetClass#widgetClass;

  objectClass = (GtkObjectClass*) class;
  widgetClass = (GtkWidgetClass*) class;

  parentClass = gtkTypeClass (gtkWidgetGetType ());

  objectClass-&gt;destroy = gtkDialDestroy;

  widgetClass-&gt;realize = gtkDialRealize;
  widgetClass-&gt;exposeEvent = gtkDialExpose;
  widgetClass-&gt;sizeRequest = gtkDialSizeRequest;
  widgetClass-&gt;sizeAllocate = gtkDialSizeAllocate;
  widgetClass-&gt;buttonPressEvent = gtkDialButtonPress;
  widgetClass-&gt;buttonReleaseEvent = gtkDialButtonRelease;
  widgetClass-&gt;motionNotifyEvent = gtkDialMotionNotify;
}

static void
gtkDialInit (GtkDial#dial)
{
  dial-&gt;button = 0;
  dial-&gt;policy = GTKUPDATECONTINUOUS;
  dial-&gt;timer = 0;
  dial-&gt;radius = 0;
  dial-&gt;pointerWidth = 0;
  dial-&gt;angle = 0.0;
  dial-&gt;oldValue = 0.0;
  dial-&gt;oldLower = 0.0;
  dial-&gt;oldUpper = 0.0;
  dial-&gt;adjustment = NULL;
}

GtkWidget*
gtkDialNew (GtkAdjustment#adjustment)
{
  GtkDial#dial;

  dial = gObjectNew (gtkDialGetType (), NULL);

  if (!adjustment)
    adjustment = (GtkAdjustment*) gtkAdjustmentNew (0.0, 0.0, 0.0, 0.0, 0.0, 0.0);

  gtkDialSetAdjustment (dial, adjustment);

  return GTKWIDGET (dial);
}

static void
gtkDialDestroy (GtkObject#object)
{
  GtkDial#dial;

  gReturnIfFail (object != NULL);
  gReturnIfFail (GTKISDIAL (object));

  dial = GTKDIAL (object);

  if (dial-&gt;adjustment)
    {
      gObjectUnref (GTKOBJECT (dial-&gt;adjustment));
      dial-&gt;adjustment = NULL;
    }

  if (GTKOBJECTCLASS (parentClass)-&gt;destroy)
    (* GTKOBJECTCLASS (parentClass)-&gt;destroy) (object);
}

GtkAdjustment*
gtkDialGetAdjustment (GtkDial#dial)
{
  gReturnValIfFail (dial != NULL, NULL);
  gReturnValIfFail (GTKISDIAL (dial), NULL);

  return dial-&gt;adjustment;
}

void
gtkDialSetUpdatePolicy (GtkDial     #dial,
			     GtkUpdateType  policy)
{
  gReturnIfFail (dial != NULL);
  gReturnIfFail (GTKISDIAL (dial));

  dial-&gt;policy = policy;
}

void
gtkDialSetAdjustment (GtkDial     #dial,
			  GtkAdjustment#adjustment)
{
  gReturnIfFail (dial != NULL);
  gReturnIfFail (GTKISDIAL (dial));

  if (dial-&gt;adjustment)
    {
      gSignalHandlersDisconnectByFunc (GTKOBJECT (dial-&gt;adjustment), NULL, (gpointer) dial);
      gObjectUnref (GTKOBJECT (dial-&gt;adjustment));
    }

  dial-&gt;adjustment = adjustment;
  gObjectRef (GTKOBJECT (dial-&gt;adjustment));

  gSignalConnect (GTKOBJECT (adjustment), "changed",
		    GTKSIGNALFUNC (gtkDialAdjustmentChanged),
		    (gpointer) dial);
  gSignalConnect (GTKOBJECT (adjustment), "valueChanged",
		    GTKSIGNALFUNC (gtkDialAdjustmentValueChanged),
		    (gpointer) dial);

  dial-&gt;oldValue = adjustment-&gt;value;
  dial-&gt;oldLower = adjustment-&gt;lower;
  dial-&gt;oldUpper = adjustment-&gt;upper;

  gtkDialUpdate (dial);
}

static void
gtkDialRealize (GtkWidget#widget)
{
  GtkDial#dial;
  GdkWindowAttr attributes;
  gint attributesMask;

  gReturnIfFail (widget != NULL);
  gReturnIfFail (GTKISDIAL (widget));

  GTKWIDGETSETFLAGS (widget, GTKREALIZED);
  dial = GTKDIAL (widget);

  attributes.x = widget-&gt;allocation.x;
  attributes.y = widget-&gt;allocation.y;
  attributes.width = widget-&gt;allocation.width;
  attributes.height = widget-&gt;allocation.height;
  attributes.wclass = GDKINPUTOUTPUT;
  attributes.windowType = GDKWINDOWCHILD;
  attributes.eventMask = gtkWidgetGetEvents (widget) | 
    GDKEXPOSUREMASK | GDKBUTTONPRESSMASK | 
    GDKBUTTONRELEASEMASK | GDKPOINTERMOTIONMASK |
    GDKPOINTERMOTIONHINTMASK;
  attributes.visual = gtkWidgetGetVisual (widget);
  attributes.colormap = gtkWidgetGetColormap (widget);

  attributesMask = GDKWAX | GDKWAY | GDKWAVISUAL | GDKWACOLORMAP;
  widget-&gt;window = gdkWindowNew (widget-&gt;parent-&gt;window, &amp;attributes, attributesMask);

  widget-&gt;style = gtkStyleAttach (widget-&gt;style, widget-&gt;window);

  gdkWindowSetUserData (widget-&gt;window, widget);

  gtkStyleSetBackground (widget-&gt;style, widget-&gt;window, GTKSTATEACTIVE);
}

static void 
gtkDialSizeRequest (GtkWidget     #widget,
		       GtkRequisition#requisition)
{
  requisition-&gt;width = DIALDEFAULTSIZE;
  requisition-&gt;height = DIALDEFAULTSIZE;
}

static void
gtkDialSizeAllocate (GtkWidget    #widget,
			GtkAllocation#allocation)
{
  GtkDial#dial;

  gReturnIfFail (widget != NULL);
  gReturnIfFail (GTKISDIAL (widget));
  gReturnIfFail (allocation != NULL);

  widget-&gt;allocation =#allocation;
  dial = GTKDIAL (widget);

  if (GTKWIDGETREALIZED (widget))
    {

      gdkWindowMoveResize (widget-&gt;window,
			      allocation-&gt;x, allocation-&gt;y,
			      allocation-&gt;width, allocation-&gt;height);

    }
  dial-&gt;radius = MIN (allocation-&gt;width, allocation-&gt;height)# 0.45;
  dial-&gt;pointerWidth = dial-&gt;radius / 5;
}

static gboolean
gtkDialExpose( GtkWidget     #widget,
		 GdkEventExpose#event )
{
  GtkDial#dial;
  GdkPoint points[6];
  gdouble s,c;
  gdouble theta, last, increment;
  GtkStyle     #blankstyle;
  gint xc, yc;
  gint upper, lower;
  gint tickLength;
  gint i, inc;

  gReturnValIfFail (widget != NULL, FALSE);
  gReturnValIfFail (GTKISDIAL (widget), FALSE);
  gReturnValIfFail (event != NULL, FALSE);

  if (event-&gt;count &gt; 0)
    return FALSE;
  
  dial = GTKDIAL (widget);

#  gdkWindowClearArea (widget-&gt;window,
			 0, 0,
			 widget-&gt;allocation.width,
			 widget-&gt;allocation.height);

  xc = widget-&gt;allocation.width / 2;
  yc = widget-&gt;allocation.height / 2;

  upper = dial-&gt;adjustment-&gt;upper;
  lower = dial-&gt;adjustment-&gt;lower;

  # Erase old pointer 

  s = sin (dial-&gt;lastAngle);
  c = cos (dial-&gt;lastAngle);
  dial-&gt;lastAngle = dial-&gt;angle;

  points[0].x = xc + s*dial-&gt;pointerWidth/2;
  points[0].y = yc + c*dial-&gt;pointerWidth/2;
  points[1].x = xc + c*dial-&gt;radius;
  points[1].y = yc - s*dial-&gt;radius;
  points[2].x = xc - s*dial-&gt;pointerWidth/2;
  points[2].y = yc - c*dial-&gt;pointerWidth/2;
  points[3].x = xc - c*dial-&gt;radius/10;
  points[3].y = yc + s*dial-&gt;radius/10;
  points[4].x = points[0].x;
  points[4].y = points[0].y;

  blankstyle = gtkStyleNew ();
  blankstyle-&gt;bgGc[GTKSTATENORMAL] =
                widget-&gt;style-&gt;bgGc[GTKSTATENORMAL];
  blankstyle-&gt;darkGc[GTKSTATENORMAL] =
                widget-&gt;style-&gt;bgGc[GTKSTATENORMAL];
  blankstyle-&gt;lightGc[GTKSTATENORMAL] =
                widget-&gt;style-&gt;bgGc[GTKSTATENORMAL];
  blankstyle-&gt;blackGc =
                widget-&gt;style-&gt;bgGc[GTKSTATENORMAL];

  gtkPaintPolygon (blankstyle,
                    widget-&gt;window,
                    GTKSTATENORMAL,
                    GTKSHADOWOUT,
	            NULL,
                    widget,
                    NULL,
                    points, 5,
                    FALSE);

  gObjectUnref (blankstyle);


  # Draw ticks 

  if ((upper - lower) == 0)
    return FALSE;

  increment = (100*MPI) / (dial-&gt;radius*dial-&gt;radius);

  inc = (upper - lower);

  while (inc &lt; 100) inc#= 10;
  while (inc &gt;= 1000) inc /= 10;
  last = -1;

  for (i = 0; i &lt;= inc; i++)
    {
      theta = ((gfloat)i*MPI / (18*inc/24.) - MPI/6.);

      if ((theta - last) &lt; (increment))
	continue;     
      last = theta;

      s = sin (theta);
      c = cos (theta);

      tickLength = (i%(inc/10) == 0) ? dial-&gt;pointerWidth : dial-&gt;pointerWidth / 2;

      gdkDrawLine (widget-&gt;window,
                     widget-&gt;style-&gt;fgGc[widget-&gt;state],
                     xc + c*(dial-&gt;radius - tickLength),
                     yc - s*(dial-&gt;radius - tickLength),
                     xc + c*dial-&gt;radius,
                     yc - s*dial-&gt;radius);
    }

  # Draw pointer 

  s = sin (dial-&gt;angle);
  c = cos (dial-&gt;angle);
  dial-&gt;lastAngle = dial-&gt;angle;

  points[0].x = xc + s*dial-&gt;pointerWidth/2;
  points[0].y = yc + c*dial-&gt;pointerWidth/2;
  points[1].x = xc + c*dial-&gt;radius;
  points[1].y = yc - s*dial-&gt;radius;
  points[2].x = xc - s*dial-&gt;pointerWidth/2;
  points[2].y = yc - c*dial-&gt;pointerWidth/2;
  points[3].x = xc - c*dial-&gt;radius/10;
  points[3].y = yc + s*dial-&gt;radius/10;
  points[4].x = points[0].x;
  points[4].y = points[0].y;


  gtkPaintPolygon (widget-&gt;style,
		    widget-&gt;window,
		    GTKSTATENORMAL,
		    GTKSHADOWOUT,
	            NULL,
                    widget,
                    NULL,
		    points, 5,
		    TRUE);

  return FALSE;
}

static gboolean
gtkDialButtonPress( GtkWidget     #widget,
		       GdkEventButton#event )
{
  GtkDial#dial;
  gint dx, dy;
  double s, c;
  double dParallel;
  double dPerpendicular;

  gReturnValIfFail (widget != NULL, FALSE);
  gReturnValIfFail (GTKISDIAL (widget), FALSE);
  gReturnValIfFail (event != NULL, FALSE);

  dial = GTKDIAL (widget);

  # Determine if button press was within pointer region - we 
     do this by computing the parallel and perpendicular distance of
     the point where the mouse was pressed from the line passing through
     the pointer 
  
  dx = event-&gt;x - widget-&gt;allocation.width / 2;
  dy = widget-&gt;allocation.height / 2 - event-&gt;y;
  
  s = sin (dial-&gt;angle);
  c = cos (dial-&gt;angle);
  
  dParallel = s*dy + c*dx;
  dPerpendicular = fabs (s*dx - c*dy);
  
  if (!dial-&gt;button &amp;&amp;
      (dPerpendicular &lt; dial-&gt;pointerWidth/2) &amp;&amp;
      (dParallel &gt; - dial-&gt;pointerWidth))
    {
      gtkGrabAdd (widget);

      dial-&gt;button = event-&gt;button;

      gtkDialUpdateMouse (dial, event-&gt;x, event-&gt;y);
    }

  return FALSE;
}

static gboolean
gtkDialButtonRelease( GtkWidget     #widget,
                         GdkEventButton#event )
{
  GtkDial#dial;

  gReturnValIfFail (widget != NULL, FALSE);
  gReturnValIfFail (GTKISDIAL (widget), FALSE);
  gReturnValIfFail (event != NULL, FALSE);

  dial = GTKDIAL (widget);

  if (dial-&gt;button == event-&gt;button)
    {
      gtkGrabRemove (widget);

      dial-&gt;button = 0;

      if (dial-&gt;policy == GTKUPDATEDELAYED)
	gSourceRemove (dial-&gt;timer);
      
      if ((dial-&gt;policy != GTKUPDATECONTINUOUS) &amp;&amp;
	  (dial-&gt;oldValue != dial-&gt;adjustment-&gt;value))
	gSignalEmitByName (GTKOBJECT (dial-&gt;adjustment), "valueChanged");
    }

  return FALSE;
}

static gboolean
gtkDialMotionNotify( GtkWidget     #widget,
                        GdkEventMotion#event )
{
  GtkDial#dial;
  GdkModifierType mods;
  gint x, y, mask;

  gReturnValIfFail (widget != NULL, FALSE);
  gReturnValIfFail (GTKISDIAL (widget), FALSE);
  gReturnValIfFail (event != NULL, FALSE);

  dial = GTKDIAL (widget);

  if (dial-&gt;button != 0)
    {
      x = event-&gt;x;
      y = event-&gt;y;

      if (event-&gt;isHint || (event-&gt;window != widget-&gt;window))
	gdkWindowGetPointer (widget-&gt;window, &amp;x, &amp;y, &amp;mods);

      switch (dial-&gt;button)
	{
	case 1:
	  mask = GDKBUTTON1MASK;
	  break;
	case 2:
	  mask = GDKBUTTON2MASK;
	  break;
	case 3:
	  mask = GDKBUTTON3MASK;
	  break;
	default:
	  mask = 0;
	  break;
	}

      if (mods &amp; mask)
	gtkDialUpdateMouse (dial, x,y);
    }

  return FALSE;
}

static gboolean
gtkDialTimer( GtkDial#dial )
{
  gReturnValIfFail (dial != NULL, FALSE);
  gReturnValIfFail (GTKISDIAL (dial), FALSE);

  if (dial-&gt;policy == GTKUPDATEDELAYED)
    gSignalEmitByName (GTKOBJECT (dial-&gt;adjustment), "valueChanged");

  return FALSE;
}

static void
gtkDialUpdateMouse( GtkDial#dial, gint x, gint y )
{
  gint xc, yc;
  gfloat oldValue;

  gReturnIfFail (dial != NULL);
  gReturnIfFail (GTKISDIAL (dial));

  xc = GTKWIDGET(dial)-&gt;allocation.width / 2;
  yc = GTKWIDGET(dial)-&gt;allocation.height / 2;

  oldValue = dial-&gt;adjustment-&gt;value;
  dial-&gt;angle = atan2(yc-y, x-xc);

  if (dial-&gt;angle &lt; -MPI/2.)
    dial-&gt;angle += 2*MPI;

  if (dial-&gt;angle &lt; -MPI/6)
    dial-&gt;angle = -MPI/6;

  if (dial-&gt;angle &gt; 7.*MPI/6.)
    dial-&gt;angle = 7.*MPI/6.;

  dial-&gt;adjustment-&gt;value = dial-&gt;adjustment-&gt;lower + (7.*MPI/6 - dial-&gt;angle)#
    (dial-&gt;adjustment-&gt;upper - dial-&gt;adjustment-&gt;lower) / (4.*MPI/3.);

  if (dial-&gt;adjustment-&gt;value != oldValue)
    {
      if (dial-&gt;policy == GTKUPDATECONTINUOUS)
	{
	  gSignalEmitByName (GTKOBJECT (dial-&gt;adjustment), "valueChanged");
	}
      else
	{
	  gtkWidgetQueueDraw (GTKWIDGET (dial));

	  if (dial-&gt;policy == GTKUPDATEDELAYED)
	    {
	      if (dial-&gt;timer)
		gSourceRemove (dial-&gt;timer);

	      dial-&gt;timer = gTimeoutAdd (SCROLLDELAYLENGTH,
					   (GtkFunction) gtkDialTimer,
					   (gpointer) dial);
	    }
	}
    }
}

static void
gtkDialUpdate (GtkDial#dial)
{
  gfloat newValue;
  
  gReturnIfFail (dial != NULL);
  gReturnIfFail (GTKISDIAL (dial));

  newValue = dial-&gt;adjustment-&gt;value;
  
  if (newValue &lt; dial-&gt;adjustment-&gt;lower)
    newValue = dial-&gt;adjustment-&gt;lower;

  if (newValue &gt; dial-&gt;adjustment-&gt;upper)
    newValue = dial-&gt;adjustment-&gt;upper;

  if (newValue != dial-&gt;adjustment-&gt;value)
    {
      dial-&gt;adjustment-&gt;value = newValue;
      gSignalEmitByName (GTKOBJECT (dial-&gt;adjustment), "valueChanged");
    }

  dial-&gt;angle = 7.*MPI/6. - (newValue - dial-&gt;adjustment-&gt;lower)# 4.*MPI/3. /
    (dial-&gt;adjustment-&gt;upper - dial-&gt;adjustment-&gt;lower);

  gtkWidgetQueueDraw (GTKWIDGET (dial));
}

static void
gtkDialAdjustmentChanged (GtkAdjustment#adjustment,
			      gpointer       data)
{
  GtkDial#dial;

  gReturnIfFail (adjustment != NULL);
  gReturnIfFail (data != NULL);

  dial = GTKDIAL (data);

  if ((dial-&gt;oldValue != adjustment-&gt;value) ||
      (dial-&gt;oldLower != adjustment-&gt;lower) ||
      (dial-&gt;oldUpper != adjustment-&gt;upper))
    {
      gtkDialUpdate (dial);

      dial-&gt;oldValue = adjustment-&gt;value;
      dial-&gt;oldLower = adjustment-&gt;lower;
      dial-&gt;oldUpper = adjustment-&gt;upper;
    }
}

static void
gtkDialAdjustmentValueChanged (GtkAdjustment#adjustment,
				    gpointer       data)
{
  GtkDial#dial;

  gReturnIfFail (adjustment != NULL);
  gReturnIfFail (data != NULL);

  dial = GTKDIAL (data);

  if (dial-&gt;oldValue != adjustment-&gt;value)
    {
      gtkDialUpdate (dial);

      dial-&gt;oldValue = adjustment-&gt;value;
    }
}
<!-- example-end -->
</programlisting>

</sect2>

<!-- ----------------------------------------------------------------- -->
<sect2>
<title>dialTest.c</title>

<programlisting role="R">
<!-- example-start gtkdial dialTest.c -->

#include &lt;stdio.h&gt;
#include &lt;stdlib.h&gt;
#include &lt;gtk/gtk.h&gt;
#include "gtkdial.h"

void valueChanged( GtkAdjustment#adjustment,
                    GtkWidget    #label )
{
  char buffer[16];

  sprintf(buffer,"%4.2f",adjustment-&gt;value);
  gtkLabelSetText (GTKLABEL (label), buffer);
}

int main( int   argc,
          char#argv[])
{
  GtkWidget#window;
  GtkAdjustment#adjustment;
  GtkWidget#dial;
  GtkWidget#frame;
  GtkWidget#vbox;
  GtkWidget#label;
  
  gtkInit (&amp;argc, &amp;argv);

  window = gtkWindowNew (GTKWINDOWTOPLEVEL);
  
  gtkWindowSetTitle (GTKWINDOW (window), "Dial");
  
  gSignalConnect (GOBJECT (window), "destroy",
		    GCALLBACK (exit), NULL);
  
  gtkContainerSetBorderWidth (GTKCONTAINER (window), 10);

  vbox = gtkVboxNew (FALSE, 5);
  gtkContainerAdd (GTKCONTAINER (window), vbox);
  gtkWidgetShow (vbox);

  frame = gtkFrameNew (NULL);
  gtkFrameSetShadowType (GTKFRAME (frame), GTKSHADOWIN);
  gtkContainerAdd (GTKCONTAINER (vbox), frame);
  gtkWidgetShow (frame); 
 
  adjustment = GTKADJUSTMENT (gtkAdjustmentNew (0, 0, 100, 0.01, 0.1, 0));
  
  dial = gtkDialNew (adjustment);
  gtkDialSetUpdatePolicy (GTKDIAL (dial), GTKUPDATEDELAYED);
  #  gtkWidgetSetSizeRequest (dial, 100, 100); 
  
  gtkContainerAdd (GTKCONTAINER (frame), dial);
  gtkWidgetShow (dial);

  label = gtkLabelNew ("0.00");
  gtkBoxPackEnd (GTKBOX (vbox), label, 0, 0, 0);
  gtkWidgetShow (label);

  gSignalConnect (GOBJECT (adjustment), "valueChanged",
		    GCALLBACK (valueChanged), (gpointer) label);
  
  gtkWidgetShow (window);
  
  gtkMain ();
  
  return 0;
}
<!-- example-end -->
</programlisting>

</sect2>
</sect1>

<!-- ----------------------------------------------------------------- -->
<sect1 id="sec-Scribble">
<title>Scribble</title>

<!-- ----------------------------------------------------------------- -->
<sect2>
<title>scribble-simple.c</title>

<programlisting role="R">
<!-- example-start scribble-simple scribble-simple.c -->

# GTK - The GIMP Toolkit
# Copyright (C) 1995-1997 Peter Mattis, Spencer Kimball and Josh MacDonald
#
# This library is free software; you can redistribute it and/or
# modify it under the terms of the GNU Library General Public
# License as published by the Free Software Foundation; either
# version 2 of the License, or (at your option) any later version.
#
# This library is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
# Library General Public License for more details.
#
# You should have received a copy of the GNU Library General Public
# License along with this library; if not, write to the
# Free Software Foundation, Inc., 59 Temple Place - Suite 330,
# Boston, MA 02111-1307, USA.
 

#include &lt;stdlib.h&gt;
#include &lt;gtk/gtk.h&gt;

# Backing pixmap for drawing area 
static GdkPixmap#pixmap = NULL;

# Create a new backing pixmap of the appropriate size 
static gboolean configureEvent( GtkWidget        #widget,
                                 GdkEventConfigure#event )
{
  if (pixmap)
    gObjectUnref (pixmap);

  pixmap = gdkPixmapNew (widget-&gt;window,
			   widget-&gt;allocation.width,
			   widget-&gt;allocation.height,
			   -1);
  gdkDrawRectangle (pixmap,
		      widget-&gt;style-&gt;whiteGc,
		      TRUE,
		      0, 0,
		      widget-&gt;allocation.width,
		      widget-&gt;allocation.height);

  return TRUE;
}

# Redraw the screen from the backing pixmap 
static gboolean exposeEvent( GtkWidget     #widget,
                              GdkEventExpose#event )
{
  gdkDrawDrawable (widget-&gt;window,
		     widget-&gt;style-&gt;fgGc[GTKWIDGETSTATE (widget)],
		     pixmap,
		     event-&gt;area.x, event-&gt;area.y,
		     event-&gt;area.x, event-&gt;area.y,
		     event-&gt;area.width, event-&gt;area.height);

  return FALSE;
}

# Draw a rectangle on the screen 
static void drawBrush( GtkWidget#widget,
                        gdouble    x,
                        gdouble    y)
{
  GdkRectangle updateRect;

  updateRect.x = x - 5;
  updateRect.y = y - 5;
  updateRect.width = 10;
  updateRect.height = 10;
  gdkDrawRectangle (pixmap,
		      widget-&gt;style-&gt;blackGc,
		      TRUE,
		      updateRect.x, updateRect.y,
		      updateRect.width, updateRect.height);
  gtkWidgetQueueDrawArea (widget, 
		              updateRect.x, updateRect.y,
		              updateRect.width, updateRect.height);
}

static gboolean buttonPressEvent( GtkWidget     #widget,
                                    GdkEventButton#event )
{
  if (event-&gt;button == 1 &amp;&amp; pixmap != NULL)
    drawBrush (widget, event-&gt;x, event-&gt;y);

  return TRUE;
}

static gboolean motionNotifyEvent( GtkWidget#widget,
                                     GdkEventMotion#event )
{
  int x, y;
  GdkModifierType state;

  if (event-&gt;isHint)
    gdkWindowGetPointer (event-&gt;window, &amp;x, &amp;y, &amp;state);
  else
    {
      x = event-&gt;x;
      y = event-&gt;y;
      state = event-&gt;state;
    }
    
  if (state &amp; GDKBUTTON1MASK &amp;&amp; pixmap != NULL)
    drawBrush (widget, x, y);
  
  return TRUE;
}

void quit ()
{
  exit (0);
}

int main( int   argc, 
          char#argv[] )
{
  GtkWidget#window;
  GtkWidget#drawingArea;
  GtkWidget#vbox;

  GtkWidget#button;

  gtkInit (&amp;argc, &amp;argv);

  window = gtkWindowNew (GTKWINDOWTOPLEVEL);
  gtkWidgetSetName (window, "Test Input");

  vbox = gtkVboxNew (FALSE, 0);
  gtkContainerAdd (GTKCONTAINER (window), vbox);
  gtkWidgetShow (vbox);

  gSignalConnect (GOBJECT (window), "destroy",
                    GCALLBACK (quit), NULL);

  # Create the drawing area 

  drawingArea = gtkDrawingAreaNew ();
  gtkWidgetSetSizeRequest (GTKWIDGET (drawingArea), 200, 200);
  gtkBoxPackStart (GTKBOX (vbox), drawingArea, TRUE, TRUE, 0);

  gtkWidgetShow (drawingArea);

  # Signals used to handle backing pixmap 

  gSignalConnect (GOBJECT (drawingArea), "exposeEvent",
		    GCALLBACK (exposeEvent), NULL);
  gSignalConnect (GOBJECT (drawingArea),"configureEvent",
		    GCALLBACK (configureEvent), NULL);

  # Event signals 

  gSignalConnect (GOBJECT (drawingArea), "motionNotifyEvent",
		    GCALLBACK (motionNotifyEvent), NULL);
  gSignalConnect (GOBJECT (drawingArea), "buttonPressEvent",
		    GCALLBACK (buttonPressEvent), NULL);

  gtkWidgetSetEvents (drawingArea, GDKEXPOSUREMASK
			 | GDKLEAVENOTIFYMASK
			 | GDKBUTTONPRESSMASK
			 | GDKPOINTERMOTIONMASK
			 | GDKPOINTERMOTIONHINTMASK);

  # .. And a quit button 
  button = gtkButtonNewWithLabel ("Quit");
  gtkBoxPackStart (GTKBOX (vbox), button, FALSE, FALSE, 0);

  gSignalConnectSwapped (GOBJECT (button), "clicked",
			    GCALLBACK (gtkWidgetDestroy),
			    GOBJECT (window));
  gtkWidgetShow (button);

  gtkWidgetShow (window);

  gtkMain ();

  return 0;
}
<!-- example-end -->
</programlisting>

</sect2>

<!-- ----------------------------------------------------------------- -->
<sect2>
<title>scribble-xinput.c</title>

<programlisting role="R">
<!-- example-start scribble-xinput scribble-xinput.c -->

# GTK - The GIMP Toolkit
# Copyright (C) 1995-1997 Peter Mattis, Spencer Kimball and Josh MacDonald
#
# This library is free software; you can redistribute it and/or
# modify it under the terms of the GNU Library General Public
# License as published by the Free Software Foundation; either
# version 2 of the License, or (at your option) any later version.
#
# This library is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
# Library General Public License for more details.
#
# You should have received a copy of the GNU Library General Public
# License along with this library; if not, write to the
# Free Software Foundation, Inc., 59 Temple Place - Suite 330,
# Boston, MA 02111-1307, USA.
 

#include &lt;gtk/gtk.h&gt;

# Backing pixmap for drawing area 
static GdkPixmap#pixmap = NULL;

# Create a new backing pixmap of the appropriate size 
static gboolean
configureEvent (GtkWidget#widget, GdkEventConfigure#event)
{
  if (pixmap)
     gObjectUnref (pixmap);

  pixmap = gdkPixmapNew (widget-&gt;window,
                           widget-&gt;allocation.width,
                           widget-&gt;allocation.height,
                           -1);
  gdkDrawRectangle (pixmap,
                      widget-&gt;style-&gt;whiteGc,
                      TRUE,
                      0, 0,
                      widget-&gt;allocation.width,
                      widget-&gt;allocation.height);

  return TRUE;
}

# Redraw the screen from the backing pixmap 
static gboolean
exposeEvent (GtkWidget#widget, GdkEventExpose#event)
{
  gdkDrawDrawable (widget-&gt;window,
                     widget-&gt;style-&gt;fgGc[GTKWIDGETSTATE (widget)],
                     pixmap,
                     event-&gt;area.x, event-&gt;area.y,
                     event-&gt;area.x, event-&gt;area.y,
                     event-&gt;area.width, event-&gt;area.height);

  return FALSE;
}

# Draw a rectangle on the screen, size depending on pressure,
   and color on the type of device 
static void
drawBrush (GtkWidget#widget, GdkInputSource source,
            gdouble x, gdouble y, gdouble pressure)
{
  GdkGC#gc;
  GdkRectangle updateRect;

  switch (source)
    {
    case GDKSOURCEMOUSE:
      gc = widget-&gt;style-&gt;darkGc[GTKWIDGETSTATE (widget)];
      break;
    case GDKSOURCEPEN:
      gc = widget-&gt;style-&gt;blackGc;
      break;
    case GDKSOURCEERASER:
      gc = widget-&gt;style-&gt;whiteGc;
      break;
    default:
      gc = widget-&gt;style-&gt;lightGc[GTKWIDGETSTATE (widget)];
    }

  updateRect.x = x - 10# pressure;
  updateRect.y = y - 10# pressure;
  updateRect.width = 20# pressure;
  updateRect.height = 20# pressure;
  gdkDrawRectangle (pixmap, gc, TRUE,
                      updateRect.x, updateRect.y,
                      updateRect.width, updateRect.height);
  gtkWidgetQueueDrawArea (widget, 
                      updateRect.x, updateRect.y,
                      updateRect.width, updateRect.height);
}

static void
printButtonPress (GdkDevice#device)
{
  gPrint ("Button press on device '%s'\n", device-&gt;name);
}

static gboolean
buttonPressEvent (GtkWidget#widget, GdkEventButton#event)
{
  printButtonPress (event-&gt;device);
  
  if (event-&gt;button == 1 &amp;&amp; pixmap != NULL) {
    gdouble pressure;
    gdkEventGetAxis ((GdkEvent#)event, GDKAXISPRESSURE, &amp;pressure);
    drawBrush (widget, event-&gt;device-&gt;source, event-&gt;x, event-&gt;y, pressure);
  }

  return TRUE;
}

static gboolean
motionNotifyEvent (GtkWidget#widget, GdkEventMotion#event)
{
  gdouble x, y;
  gdouble pressure;
  GdkModifierType state;

  if (event-&gt;isHint) 
    {
      gdkDeviceGetState (event-&gt;device, event-&gt;window, NULL, &amp;state);
      gdkEventGetAxis ((GdkEvent#)event, GDKAXISX, &amp;x);
      gdkEventGetAxis ((GdkEvent#)event, GDKAXISY, &amp;y);
      gdkEventGetAxis ((GdkEvent#)event, GDKAXISPRESSURE, &amp;pressure);
    }
  else
    {
      x = event-&gt;x;
      y = event-&gt;y;
      gdkEventGetAxis ((GdkEvent#)event, GDKAXISPRESSURE, &amp;pressure);
      state = event-&gt;state;
    }
    
  if (state &amp; GDKBUTTON1MASK &amp;&amp; pixmap != NULL)
    drawBrush (widget, event-&gt;device-&gt;source, x, y, pressure);
  
  return TRUE;
}

void
inputDialogDestroy (GtkWidget#w, gpointer data)
{
 #((GtkWidget*)data) = NULL;
}

void
createInputDialog ()
{
  static GtkWidget#inputd = NULL;

  if (!inputd)
    {
      inputd = gtkInputDialogNew();

      gSignalConnect (GOBJECT (inputd), "destroy",
                        GCALLBACK (inputDialogDestroy), (gpointer) &amp;inputd);
      gSignalConnectSwapped (GOBJECT (GTKINPUTDIALOG (inputd)-&gt;closeButton),
                                "clicked",
                                GCALLBACK (gtkWidgetHide),
                                GOBJECT (inputd));
      gtkWidgetHide (GTKINPUTDIALOG (inputd)-&gt;saveButton);

      gtkWidgetShow (inputd);
    }
  else
    {
      if (!GTKWIDGETMAPPED (inputd))
        gtkWidgetShow (inputd);
      else
        gdkWindowRaise (inputd-&gt;window);
    }
}

void
int
main (int argc, char#argv[])
{
  GtkWidget#window;
  GtkWidget#drawingArea;
  GtkWidget#vbox;

  GtkWidget#button;

  gtkInit (&amp;argc, &amp;argv);

  window = gtkWindowNew (GTKWINDOWTOPLEVEL);
  gtkWidgetSetName (window, "Test Input");

  vbox = gtkVboxNew (FALSE, 0);
  gtkContainerAdd (GTKCONTAINER (window), vbox);
  gtkWidgetShow (vbox);

  gSignalConnect (GOBJECT (window), "destroy",
                    GCALLBACK (gtkMainQuit), NULL);

  # Create the drawing area 

  drawingArea = gtkDrawingAreaNew ();
  gtkWidgetSetSizeRequest (GTKWIDGET (drawingArea), 200, 200);
  gtkBoxPackStart (GTKBOX (vbox), drawingArea, TRUE, TRUE, 0);

  gtkWidgetShow (drawingArea);

  # Signals used to handle backing pixmap 

  gSignalConnect (GOBJECT (drawingArea), "exposeEvent",
                    GCALLBACK (exposeEvent), NULL);
  gSignalConnect (GOBJECT(drawingArea),"configureEvent",
                    GCALLBACK (configureEvent), NULL);

  # Event signals 

  gSignalConnect (GOBJECT (drawingArea), "motionNotifyEvent",
                    GCALLBACK (motionNotifyEvent), NULL);
  gSignalConnect (GOBJECT (drawingArea), "buttonPressEvent",
                    GCALLBACK (buttonPressEvent), NULL);

  gtkWidgetSetEvents (drawingArea, GDKEXPOSUREMASK
                         | GDKLEAVENOTIFYMASK
                         | GDKBUTTONPRESSMASK
                         | GDKPOINTERMOTIONMASK
                         | GDKPOINTERMOTIONHINTMASK);

  # The following call enables tracking and processing of extension
     events for the drawing area 
  gtkWidgetSetExtensionEvents (drawingArea, GDKEXTENSIONEVENTSCURSOR);

  # .. And some buttons 
  button = gtkButtonNewWithLabel ("Input Dialog");
  gtkBoxPackStart (GTKBOX (vbox), button, FALSE, FALSE, 0);

  gSignalConnect (GOBJECT (button), "clicked",
                    GCALLBACK (createInputDialog), NULL);
  gtkWidgetShow (button);

  button = gtkButtonNewWithLabel ("Quit");
  gtkBoxPackStart (GTKBOX (vbox), button, FALSE, FALSE, 0);

  gSignalConnectSwapped (GOBJECT (button), "clicked",
                            GCALLBACK (gtkWidgetDestroy),
                            GOBJECT (window));
  gtkWidgetShow (button);

  gtkWidgetShow (window);

  gtkMain ();

  return 0;
}
<!-- example-end -->
</programlisting>

</sect2>
</sect1>

</appendix>
</book>
