\input texinfo   @c -*-texinfo-*-
@c %**start of header
@setfilename gtkada_ug.info
@settitle GtkAda User's Guide
@syncodeindex fn cp

@dircategory User Interface Toolkit
@direntry
* GtkAda_Ug: (gtkada_ug).          Ada graphical tookit based on GTK+ (User's Guide)
@end direntry

@set GtkAdaVersion 2.22.0

@titlepage

@title GtkAda User's Guide
@subtitle Version @value{GtkAdaVersion}
@subtitle Document revision level $Revision: 167385 $
@subtitle Date: $Date: 2010-11-23 17:58:38 +0100 (Tue, 23 Nov 2010) $
@author E. Briot, J. Brobecker, A. Charlet

@page
@vskip 0pt plus 1filll

Copyright @copyright{} 1998-2000, Emmanuel Briot, Joel Brobecker, Arnaud Charlet

Copyright @copyright{} 2000-2010, AdaCore

Permission is granted to copy, distribute and/or modify this document
under the terms of the GNU Free Documentation License, Version 1.1
or any later version published by the Free Software Foundation;
with the Invariant Sections being ``GNU Free Documentation License'', with the
Front-Cover Texts being
``GtkAda User's Guide'',
and with no Back-Cover Texts.
A copy of the license is included in the section entitled
``GNU Free Documentation License''.

@end titlepage

@ifinfo
@node Top, Introduction, (dir), (dir)
@top GtkAda User's Guide

GtkAda User's Guide

GtkAda, the Ada graphical toolkit

Version @value{GtkAdaVersion}

Date: $Date: 2010-11-23 17:58:38 +0100 (Tue, 23 Nov 2010) $

Copyright @copyright{} 1998-2000, Emmanuel Briot, Joel Brobecker, Arnaud Charlet

Copyright @copyright{} 2000-2010, AdaCore

Permission is granted to copy, distribute and/or modify this document
under the terms of the GNU Free Documentation License, Version 1.1
or any later version published by the Free Software Foundation;
with the Invariant Sections being ``GNU Free Documentation License'', with the
Front-Cover Texts being
``GtkAda User's Guide'',
and with no Back-Cover Texts.
A copy of the license is included in the section entitled
``GNU Free Documentation License''.

@menu
* Introduction::
* Getting started with GtkAda::
* Hierarchical composition of a window::
* Signal handling::
* Starting an application with GtkAda::
* Resource files::
* Memory management::
* Tasking with GtkAda::
* Processing external events::
* Object-oriented features::
* Support for Glade the Gtk GUI builder::
* Binding new widgets::
* Debugging GtkAda applications::
* How to report bugs::
* Bibliography::
* GNU Free Documentation License::

@detailmenu
 --- The Detailed Node Listing ---

Getting started with GtkAda

* How to build and install GtkAda::
* How to distribute a GtkAda application::
* Organization of the GtkAda package::
* How to compile an application with GtkAda::
* Architecture of the toolkit::
* Widgets Hierarchy::

Signal handling
* Predefined signals::
* Connecting signals::
* Handling user data::

Object-oriented features
* Using tagged types to extend Gtk widgets::
* Creating new widgets in Ada::

@end detailmenu
@end menu
@end ifinfo

@c --------------------------------------------------------------------
@node Introduction
@chapter Introduction: What is GtkAda ?
@c --------------------------------------------------------------------

@noindent
GtkAda is a high-level portable graphical toolkit, based on the gtk+
toolkit, one of the official GNU toolkits. It makes it easy to create
portable user interfaces for multiple platforms, including most
platforms that have a X11 server and Win32 platforms.

Although it is based on a C library, GtkAda uses some advanced Ada
features such as tagged types, generic packages, access to subprograms,
and exceptions to make it easier to use and design interfaces.
For efficiency reasons, it does not use controlled types, but takes care
of all the memory management for you in other ways.

As a result, this library provides a @i{secure}, @i{easy to use} and
@i{extensible} toolkit.

Compared to the C library, GtkAda provides type safety (especially in the
callbacks area), and object-oriented programming. As opposed to common
knowledge, it requires @i{less} type casting than with in C.
Its efficiency is about the same as the C library through the use of inline
subprograms.

GtkAda comes with a complete integration to the graphical interface
builder @code{Glade}@footnote{Glade was written by Damon Chaplin}. This
makes it even easier to develop interfaces, since you just have to click
to create a window and all the dialogs. Ada code can then be generated
with a single click.

Under some platforms, GtkAda also provides a bridge to use OpenGL, with
which you can create graphical applications that display 3D graphics, and
display them in a GtkAda window, as with any other 2D graphics.
This manual does not
document OpenGL at all, see any book on OpenGL, or the specification
that came with your OpenGL library, for more information.

The following Internet sites will always contain the latest public
packages for @code{GtkAda}, @code{gtk+}, @code{Glade} and @code{Cairo}

     @uref{http://libre.adacore.com/libre/tools/GtkAda/}

     @uref{http://www.gtk.org/}

     @uref{http://glade.gnome.org/}

     @uref{http://www.cairographics.org/}

The scheme used for GtkAda's version numbers is the following: the major
and minor version number is the same as for the underlying gtk+ library
(e.g 2.18).
The micro version number depends on GtkAda's release number.

This toolkit was tested on the following systems:
@itemize @bullet
@item GNU Linux/x86
@item GNU Linux/x86-64
@item GNU Linux/ia64
@item Solaris/sparc
@item Windows XP/Vista/2003
@end itemize

with the latest version of the @code{GNAT} compiler, developed and supported by
Ada Core Technologies (see @uref{http://www.adacore.com}).

This version of GtkAda is known to be compatible with @code{gtk+} @b{2.16.x}
and @b{2.18.x}.
This release may or may not be compatible with older versions of gtk+.

This version of GtkAda is compatible with @code{Glade} @b{version
2.0.0}.  Due to some modification in the output format of Glade, this
release will not work with older versions. It is also not guaranteed to
work with more recent versions.

This document does not describe all the widgets available in GtkAda, nor
does it try to explain all the subprograms. The GtkAda Reference Manual
provides this documentation instead, as well as
the GtkAda sources spec files themselves, whose extension is @file{.ads}.

No complete example is provided in this documentation. Instead, please
refer to the examples that you can find in the @file{testgtk/} and
@file{examples/} directory in the GtkAda distribution, since these are
more up-to-date (and more extensive).
They are heavily commented, and are likely to contain a lot of
information that you might find interesting.

If you are interested in getting support for GtkAda--including priority
bug fixes, early releases, help in using the toolkit, help in designing
your interface, and on site consulting--please contact AdaCore
(@uref{mailto:sales@@adacore.com}).

@c --------------------------------------------------------------------
@node Getting started with GtkAda
@chapter Getting started with GtkAda
@c --------------------------------------------------------------------

@noindent
This chapter describes how to start a new GtkAda application. It explains
the basic features of the toolkit, and shows how to compile and run your
application.

It also gives a brief overview of the extensive widget hierarchy available
in GtkAda.

@menu
* How to build and install GtkAda::
* How to distribute a GtkAda application::
* Organization of the GtkAda package::
* How to compile an application with GtkAda::
* Architecture of the toolkit::
* Widgets Hierarchy::
@end menu

@c ---------------------------------------------------------------------
@node How to build and install GtkAda
@section How to build and install GtkAda
@c ---------------------------------------------------------------------

@noindent
This section explains how to build and install GtkAda on your machine.

On Windows systems, we provide an automatic installer that installs
GtkAda along with dependent components like gtk+ libraries and
@code{Glade}.  If you are a Windows user, you can skip the rest of
this section which will address installation on Unix systems.

On Unix systems, you first need to install the glib and gtk+
libraries. Download the compatible packages from the gtk+ web site
(@url{http://www.gtk.org}), compile and install it.  Alternatively,
if your operating system vendor provides glib and gtk+ development
packages, you can install the libraries they provide.

Change your PATH environment variable so that the script @code{pkg-config},
which indicates where gtk+ was installed and what libraries it needs is
automatically found by GtkAda. You will no longer need this script once
GtkAda is installed, unless you develop part of your application in C.

OpenGL support will not be activated in GtkAda unless you already have
the OpenGL libraries on your systems. You can for instance look at
Mesa, which is free implementation.

Optionally, you can also install the @code{Glade} interface builder. Get
the compatible package from the Glade web site, compile and install it.
The official version already knows about Ada (at least enough to call
GtkAda's own programs), so no patch is needed.

You can finally download the latest version of GtkAda from the web site.
Untar and uncompress the package, then simply do the following
steps:
@smallexample
$ ./configure
$ make
$ make tests     (this step is optional)
$ make install
@end smallexample

As usual with the @code{configure} script, you can specify where you want
to install the GtkAda libraries by using the @code{--prefix} switch.

You can specify the switch @code{--disable-shared} to prevent building
shared libraries, even if your system supports them (by default, both
shared and static libraries are installed). By default, your application
will be linked statically with the GtkAda libraries. You can override this
default by specifying @code{--enable-shared} as a switch to @code{configure},
although you can override it later through the LIBRARY_TYPE scenario
variable.

If you have some OpenGL libraries installed on your system, you can make
sure that @code{configure} finds them by specifying the
@code{--with-GL-prefix} switch on the command line. @code{configure}
should be able to automatically detect the libraries however.

You must then make sure that the system will be able to find the dynamic
libraries at run time if your application uses them. Typically, you
would do one of the following:
@itemize @bullet
@item run @code{ldconfig} if you installed GtkAda in one of the standard
  location and you are super-user on your machine
@item edit @code{/etc/ld.conf} if you are super-user but did not install
  GtkAda in one of the standard location. Add the path that contains
  libgtkada.so (by default @file{/usr/local/lib} or @file{$prefix/lib}.
@item modify your @code{LD_LIBRARY_PATH} environment variable if you are
  not super-user. You should simply add the path to libgtkada.
@end itemize

In addition, if you are using precompiled Gtk+ binary packages, you will
also need to set the @code{FONTCONFIG_FILE} environment variable to point to
the @file{prefix/etc/fonts/fonts.conf} file of your binary installation.

For example, assuming you have installed Gtk+ under @file{/opt/gtk} and
using bash:

@smallexample
$ export FONTCONFIG_FILE=/opt/gtk/etc/fonts/fonts.conf
@end smallexample

If your application is using printing, on UNIX and Linux you will need to
point your environment variable GTK_EXE_PREFIX to the root directory of your
Gtk+ installation:

@smallexample
$ export GTK_EXE_PREFIX=/opt/gtk/
@end smallexample

@c ---------------------------------------------------------------------
@node How to distribute a GtkAda application
@section How to distribute a GtkAda application
@c ---------------------------------------------------------------------

@noindent
Since GtkAda depends on Gtk+, you usually need to distribute some Gtk+
libraries along with your application.

Under some OSes such as Linux, Gtk+ comes preinstalled, so in this case,
a simple solution is to rely on the preinstalled Gtk+ libraries. See
below for more information on the gtkada library itself.

Under other unix systems, GtkAda usually comes with a precompiled set of Gtk+
libraries that have been specifically designed to be easily redistributed.

In order to use the precompiled Gtk+ binaries that we distribute
with GtkAda, you need to distribute all the Gtk+ .so libraries along
with your application, and use the LD_LIBRARY_PATH environment variable to
point to these libraries.

The list of libraries needed is @file{<gtkada-prefix>/lib/lib*.so.?}
along with your executable, and set LD_LIBRARY_PATH.

You may also need the @file{libgtkada-xxx.so} file. This dependency
is optional since gtkada supports both static and dynamic linking, so
by e.g. using @code{gtkada-config --static} or by using
@file{gtkada_static.gpr}, you will end up linking with @file{libgtkada.a}.

Under Windows, you need to distribute the following files and directories
along with your application, and respect the original directory set up:

@itemize @bullet
@item @file{bin/*.dll}
@item @file{etc/}
@item @file{lib/gtk-2.0}
@end itemize

@c ----------------------------------------------------------------------
@node Organization of the GtkAda package
@section Organization of the GtkAda package
@c ----------------------------------------------------------------------

@noindent
In addition to the full sources, the GtkAda package contains a lot of
heavily commented examples. If you haven't been through those examples, we
really recommend that you look at them and try to understand them, since
they contain some examples of code that you might find interesting for
your own application.

@itemize @bullet

@item @file{testgtk/} directory:

This directory contains the application @code{testgtk} that tests all the
widgets in GtkAda. It gives you a quick overview of what can be found in the
toolkit, as well as some detailed information on the widgets and their
parameters.

Each demo is associated with contextual help pointing to aspects worth
studying.

It also contains an OpenGL demo, if GtkAda was compiled with support for
OpenGL.

This program is far more extensive that its C counterpart, and the GtkAda
team has added a lot of new examples.

This directory also contains the application @code{testcairo} which
demonstrates the use of various Cairo functions in GtkAda.

@item @file{examples/} directory:

This directory contains some small examples, unrelated to @file{testgtk}.
For instance, this is where you will find some sample XML files for
@code{Gate} and @code{Dgate}, as well as some new widgets created
directly in Ada, as examples of how to create your own callback
marshallers.

On the whole these examples are a little more complex than @file{testgtk} but
since they focus on demonstrating a precise concept, they are still quite
easy to understand.

@item @file{docs/} directory:

It contains the html, info, text and @TeX{} versions of the documentation you
are currently reading. Note that the documentation is divided into two
subdirectories, one containing the user guide, which you are currently
reading, the other containing the reference manual, which gives detailed
information on all the widgets found in GtkAda. The docs directory also
contains a subdirectory with some slides that were used to present GtkAda
at various shows.

@end itemize

@c ----------------------------------------------------------------------
@node How to compile an application with GtkAda
@section How to compile an application with GtkAda
@c ----------------------------------------------------------------------

This section explains how you can compile your own applications.

There are several ways to use GtkAda in your applications

@subsection Using project files

A set of project files is installed along with GtkAda. If you have installed
GtkAda in the same location as GNAT itself, nothing else needs to be done.

Otherwise, you need to make the directory that contains these project files
visible to the compiler. This is done by adding the directory to the
@code{ADA_PROJECT_PATH} environment variable. Assuming you have installed the
library in @file{prefix}, the directory you need to add is
@file{prefix/lib/gnat}.

On Unix, this is done with

@smallexample
csh:
   setenv ADA_PROJECT_PATH $prefix/lib/gnat:$ADA_PROJECT_PATH
sh:
   ADA_PROJECT_PATH=$prefix/lib/gnat:$ADA_PROJECT_PATH
   export ADA_PROJECT_PATH
@end smallexample

To build your own application, you should then setup a project file (see
the GNAT documentation for more details on project files), which simply
contains the statement

@smallexample
with "gtkada";
@end smallexample

This will automatically set the right compiler and linker options, so that
your application is linked with GtkAda.

By default, the linker will use GtkAda's shared library, if it was built.
If you would prefer to link with the static library, you can set the
environment variable
    LIBRARY_TYPE=static
    export LIBRARY_TYPE
before launching the compiler or linker, which will force it to use the
static library instead.

@subsection Using the command line

The procedure is system-dependent, and thus is divided into two
subsections.

@subsubsection Unix systems

@noindent
On Unix systems, a script called @code{gtkada-config} is automatically
created when you build GtkAda. This script is copied in a subdirectory
@file{bin/} in the installation directory.

The easiest and recommended way to build a GtkAda application is to
use the @code{gnatmake} program distributed with GNAT, that takes care of
all the dependencies for you. Use the @code{gtkada-config} to specify
where GtkAda and gtk+ libraries have been installed.

@smallexample
> gnatmake <main-file> `gtkada-config`
@end smallexample

Note the use of back-ticks around gtkada-config, which force the shell to
evaluate the script and put the output on the command line.

However, on complex systems, gnatmake might not be enough. Users frequently
like to create @code{Makefile}s. The script @code{gtkada-config} remains
useful in that case, since you can call it from your Makefile (same
syntax as above with the back-ticks) to create variables like FLAGS and
LIBS. See the switches of @code{gtkada-config} below for more information.

The script @code{gtkada-config} understands the following command line
switches (chosen to be compatible with the ones set by @code{gtk-config}):

@itemize @bullet
@item @code{--cflags}: Output only the compiler flags, i.e the  include
  directories where the GtkAda spec files are found. This should be used
  if you only want to compile your files, but do not want to bind or link
  them.
@item @code{--libs}: Output only the switches for the linker. This lists
  the directories where all the GtkAda, gtk+, and dependant libraries are
  found. For instance, if GtkAda was compiled with support for OpenGL,
  the OpenGL libraries will automatically be present.
@item @code{--static}: Forces linking with the static gtkada library. This
  option will still use the dynamic gtk+ libraries.
@end itemize

@subsubsection Windows systems

Things are somewhat easier on Windows systems. You don't have access to the
@code{gtkada-config} script. On the other hand you also don't
have to specify which libraries to use or where to find them.

The only thing you should specify on the @code{gnatmake} command line is
where the GtkAda spec files are found, as in:

@smallexample
> gnatmake <main-file> -Ic:\gtkada\include\gtkada
@end smallexample

if GtkAda was installed under @file{c:\gtkada}.

@c ---------------------------------------------------------------------
@node Architecture of the toolkit
@section Architecture of the toolkit
@c ---------------------------------------------------------------------

@noindent
The gtk+ toolkit has been designed from the beginning to be portable.
It is made of two libraries: @code{gtk} and @code{gdk}.
In addition, GtkAda provides binding to three supporting libraries:
@code{pango}, @code{cairo} and @code{glib}.

@code{Glib} is a non-graphical library that includes support for lists,
h-tables, threads, and so on. It is a highly optimized,
platform-independent library. Since most of its contents are already
available in Ada (or in the @file{GNAT.*} hierarchy in the GNAT
distribution), GtkAda does not include a complete binding to it.
For the parts of @code{Glib} that we do depend on, we provide
@file{Glib.*} packages in the GtkAda distribution.

@code{Gdk} is the platform-dependent part of gtk+, and so there are
different implementations (for instance, for Win32 and X11 based
systems) that implement a common API. @code{Gdk} provides basic
graphical functionality to, for instance, draw lines, rectangles and
pixmaps on the screen, as well as manipulate colors. The @file{Gdk.*}
packages provide a full Ada interface to @code{Gdk}.

@code{Pango} is a modern font handling system. Bindings in GtkAda
gives access to the API to manipulate font descriptions and text
attributes.

@code{Cairo} is the low-level 2D drawing library used by @code{Gdk} to
render widgets. @code{Cairo} provides a rich set of vector drawing
features, supporting anti-aliasing, transparency, and 2D matrix
transformations.The @file{Cairo.*} packages provide a complete Ada
binding to @code{Cairo}.

@code{Gtk} is the top level library. It is platform independent, and
does all its drawing through calls to Gdk and Cairo. This is where the
high-level widgets are defined. It also includes support for callbacks. Its
equivalent in the GtkAda libraries are the @file{Gtk.*} packages. It is
made of a fully object-oriented hierarchy of widgets (see @ref{Widgets
Hierarchy}).

Since your application only calls GtkAda, it is fully portable, and can
be recompiled as-is on other platforms.

@smallexample
+------------------------------- ----------+
|             Your Application             |
+------------------------------------------+
|                 GtkAda                   |
|              +-----------------+         |
|              |      GTK        |         |
|         +----+-----------------+----+    |
|         |           GDK             |    |
|    +----+------+         +----------+----+
|    |   Pango   |         |     Cairo     |
+----+-----------+----+----+---------------+
|        GLIB         |   X-Window / Win32  |
+---------------------+--------------------+
@end smallexample

Although the packages have been evolving a lot since the first versions
of GtkAda, the specs are stabilizing now. We will try as much as possible
to provide backward compatibility whenever possible.

Since GtkAda is based on gtk+ we have tried to stay as close to it as possible
while using high-level features of the Ada language. It is
thus relatively easy to convert external examples from C to Ada.

We have tried to adopt a consistent naming scheme for Ada identifiers:
@itemize @bullet

@item The widget names are the same as in C, except that an underscore
sign (_) is used to separate words, e.g
@smallexample
Gtk_Button   Gtk_Color_Selection_Dialog
@end smallexample

@item Because of a clash between Ada keywords and widget names, there
are two exceptions to the above general rule:
@smallexample
Gtk.GEntry.Gtk_Entry   Gtk.GRange.Gtk_Range
@end smallexample

@item The function names are the same as in  C, ignoring the leading
@code{gtk_} and the widget name, e.g
@smallexample
gtk_misc_set_padding        @result{}  Gtk.Misc.Set_Padding
gtk_toggle_button_set_state @result{}  Gtk.Toggle_Button.Set_State
@end smallexample

@item Most enum types have been grouped in the @file{gtk-enums.ads} file

@item Some features have been implemented as generic packages. These
are the timeout functions (see @code{Gtk.Main.Timeout}), the idle functions
(see @code{Gtk.Main.Idle}), and the data that can be attached to any object
(see @code{Gtk.Object.User_Data}). Type safety is ensured through these
generic packages.

@item Callbacks were the most difficult thing to interface with. These
are extremely powerful and versatile, since the callbacks can have any
number of arguments and may or may not return values. These are once
again implemented as generic packages, that require more explanation
(@pxref{Signal handling}).

@end itemize

@cartouche
@b{WARNING:} all the generic packages allocate some memory for internal
structures, and call internal functions. This memory is freed by gtk
itself, by calling some Ada functions. Therefore the generic packages
have to be instantiated at library level, not inside a subprogram, so
that the functions are still defined when gtk needs to free the memory.
@end cartouche

@cartouche
@b{WARNING} Before any other call to the GtkAda library is performed,
@code{Gtk.Main.Init} must be invoked first. Most of the time, this
procedure is invoked from the main procedure of the application, in
which case no use of GtkAda can be done during the application
elaboration.
@end cartouche

@c ----------------------------------------------------------------------
@node Widgets Hierarchy
@section Widgets Hierarchy
@c ----------------------------------------------------------------------

@noindent
All widgets in @code{GtkAda} are implemented as tagged types. They all have
a common ancestor, called @code{Gtk.Object.Gtk_Object}. All visual objects
have a common ancestor called @code{Gtk.Widget.Gtk_Widget}.

The following table describes the list of objects and their inheritance
tree. As usual with tagged types, all the primitive subprograms defined
for a type are also known for all of its children. This is a very
powerful way to create new widgets, as will be explained in
@ref{Creating new widgets in Ada}.

Although gtk+ was written in C its design is object-oriented, and thus
GtkAda has the same structure. The following rules have been applied to
convert from C names to Ada names: a widget @code{Gtk_XXX} is defined in
the Ada package @code{Gtk.XXX}, in the file @file{gtk-xxx.ads}. This
follows the GNAT convention for file names.  For instance, the
@code{Gtk_Text} widget is defined in the package @code{Gtk.Text}, in the
file @file{gtk-text.ads}.

Note also that most of the documentation for GtkAda is found in the spec
files themselves.

It is important to be familiar with this hierarchy. It is then easier to
know how to build and organize your windows. Most widgets are demonstrated
in the @file{testgtk/} directory in the GtkAda distribution.

@cartouche
@image{hierarchy, 22.8cm}
@smallexample
            @strong{Hierarchy of widgets in GtkAda}
@end smallexample
@end cartouche

@c ----------------------------------------------------------------------
@node Hierarchical composition of a window
@chapter Hierarchical composition of a window
@c ----------------------------------------------------------------------

@noindent
Interfaces in GtkAda are built in layers, as in Motif.
For instance, a typical dialog is basically a Gtk_Window, that in turn
contains a Gtk_Box, itself divided into two boxes and a Gtk_Separator,
and so on.

@iftex
@image{boxes, 14cm}
@end iftex

Altough this may seem more complicated than setting absolute positions
for children, this is the simplest way to automatically handle the
resizing of windows. Each container that creates a layer knows how it
should behave when it is resized, and how it should move its children.
Thus almost everything is handled automatically, and you don't have to do
anything to support resizing.

If you really insist on moving the children to a specific position, look
at the @code{Gtk_Fixed} widget and its demo in @file{testgtk/}. But you
really should not use this container, since you will then have to do
everything by hand.

All the containers are demonstrated in @file{testgtk/}, in the GtkAda
distribution. This should help you understand all the parameters
associated with the containers. It is very important to master these
containers, since using the appropriate containers will make building
interfaces a lot easier.

If you look at the widget hierarchy (@pxref{Widgets Hierarchy}),
you can see that a Gtk_Window inherits from Gtk_Bin, and thus can have
only one child. In most cases, the child of a Gtk_Window will thus
be a Gtk_Box, which can have any number of children.

Some widgets in GtkAda itself are built using this strategy, from the
very basic @code{Gtk_Button} to the more advanced
@code{Gtk_File_Selection}.

For example, by default a Gtk_Button contains a Gtk_Label, which
displays the text of the button (like ``OK'' or ``Cancel'').

However, it is easy to put a pixmap in a button instead. When you
create the button, do not specify any label. Thus, no child will be
added, and you can give it your own. See @file{testgtk/create_pixmap.adb}
for an example on how to do that.


@c ----------------------------------------------------------------------
@node Signal handling
@chapter Signal handling
@c ----------------------------------------------------------------------

@noindent
In GtkAda, the interaction between the interface and the core
application is done via signals. Most user actions on the graphical
application trigger some signals to be @samp{emitted}.

A signal is a message that an object wants to broadcast. It is
identified by its name, and each one is associated with certain events
which happen during the widget's lifetime. For instance, when the user
clicks on a Gtk_Button, a ``clicked'' signal is emitted by that
button. More examples of signals can be found in the GtkAda reference
manual.

It is possible to cause the application to react to such events by
@samp{connecting} to a signal a special procedure called a
@samp{handler} or @samp{callback}.  This handler will be called every
time that signal is emitted, giving the application a chance to do any
processing it needs. More than one handler can be connected to the
same signal on the same object; the handlers are invoked in the order
they were connected.

@menu
* Predefined signals::
* Connecting signals::
* Handling user data::
@end menu

@c ----------------------------------------------------------------------
@node Predefined signals
@section Predefined signals
@c ----------------------------------------------------------------------

@noindent
Widgets, depending on their type, may define zero or more different signals.
The signals defined for the parent widget are also automatically inherited;
thus every widget answers many signals.

The easiest way to find out which signals can be emitted by a widget is to
look at the GtkAda reference manual. Every widget will
be documented there. The GtkAda RM explains when particular signals are
emitted, and the general form that their handlers should have (although
you can always add a @code{User_Data} if you wish, see below).

You can also look directly at the C header files
distributed with the gtk+ library. Each widget is described in its own C
file and has two C structures associated with it. One of them is the
``class'' structure, which contains a series of pointers to
functions. Each of these functions has the same name as the signal name.
@c ??? doesn't follow ... first, two structures are mentioned, but
@c ??? only one structure is explained.

For instance, consider the following extract from gtkbutton.h:
@smallexample
@b{struct} _GtkButtonClass
@{
  GtkBinClass        parent_class;

  @b{void} (* pressed)  (GtkButton *button);
  @b{void} (* released) (GtkButton *button);
  @b{void} (* clicked)  (GtkButton *button);
  @b{void} (* enter)    (GtkButton *button);
  @b{void} (* leave)    (GtkButton *button);
@};
@end smallexample

This means that the Gtk_Button widget redefines five new signals
called @code{pressed}, @code{released}, and so on, respectively.

The profile of the handler can also be deduced from those pointers:
The handler has the same arguments, plus an optional @code{User_Data} parameter
that can be used to pass any kind of data to the handler.  When the
@code{User_Data} parameter is used, the value of this data is specified when
connecting the handler to the signal. It is then given back to the
handler when the signal is raised.

Therefore, the profile of a handler should look like:
@smallexample
procedure Pressed_Handler
  (Button    : access Gtk_Button_Record'Class;
   User_Data : ...);
@end smallexample

The callback does not need to use all the arguments. It is legal to use
a procedure that "drops" some of the last arguments.
There is one special case, however: if, at connection time, you decided to
use @code{User_Data}, your callback must handle it.  This is checked by
the compiler.

Any number of arguments can be dropped as long as those arguments are
the last ones in the list and you keep the first one. For instance,
the signal "button_press_event" normally can be connected to a
handler with any of the following profiles:

@smallexample
--  with a user_data argument
procedure Handler
  (Widget    : access Gtk_Widget_Record'Class;
   Event     : Gdk.Event.Gdk_Event;
   User_Data : ...);
procedure Handler
  (Widget    : access Gtk_Widget_Record'Class;
   User_Data : ...);

--  without a user_data argument
procedure Handler
  (Widget : access Gtk_Widget_Record'Class;
   Event  : Gdk.Event.Gdk_Event);
procedure Handler (Widget : access Gtk_Widget_Record'Class);
@end smallexample

Beware that adding new arguments is not possible, since no value would
be provided for them. When connecting a handler, GtkAda will not always
verify that your handler does not have more arguments than expected, so
caution is recommended (it only does so if you use the @code{Gtk.Marshallers}
package, see below).

@c ----------------------------------------------------------------------
@node Connecting signals
@section Connecting signals
@c ----------------------------------------------------------------------

@noindent
All signal handling work is performed using services provided
by the @code{Gtk.Handlers} package. This package is self-documented,
so please read the documentation for this package either in the GtkAda
Reference Manual or in the specs themselves. The rest of this section assumes
that you have this documentation handy.

A short, annotated example of connecting signals follows; a complete
example can be found in create_file_selection.adb (inside the @file{testgtk/}
directory). In our example, an application opens a file selector to
allow the user to select a file.  GtkAda provides a high-level widget
called Gtk_File_Selection which can be used in this case:

@smallexample
declare
   Window : Gtk_File_Selection;
begin
   Gtk.File_Selection.Gtk_New (Window, Title => "Select a file");
end;
@end smallexample

When the ``OK'' button is pressed, the application needs to retrieve the
@c ??? "name of the" ...?
selected file and then close the dialog. The only information that the
handler for the button press needs is which widget to operate upon.
This can be achieved by the following handler:

@need 3000
@smallexample
procedure OK (Files : access Gtk_File_Selection_Record'Class) is
begin
   Ada.Text_IO.Put_Line ("Selected " & Get_Filename (Files));
   --  Prints the name of the selected file.
   Destroy (Files);
   --  Destroys the file selector dialog
end Ok;
@end smallexample

We now need to connect the object we created in the first part with the
new callback we just defined. @code{Gtk.Handlers} defines four types of
generic packages, depending on the arguments one expects in the callback and
whether the callback returns a value or not. Note that you can not
use an arbitrary list of arguments; this depends on the signal, as
explained in the previous section.

In our example, since the callback does not return any value and does not
handle any @code{User_Data} (that is, we don't pass it extra data,
which will be specified at connection time), the appropriate package
to use is @code{Gtk.Handlers.Callback}. We thus instantiate that package.

Remember that generic package instantiations in GtkAda must be present
in memory at all times, since they take care of freeing allocated memory
when finished. GtkAda generic package instantiations must therefore
always be performed at the library level, and not inside any inner block.
@c ??? should this really read "always be performed in a package at the
@c ??? library level, and not inside any inner block or subprogram."?

@smallexample
package Files_Cb is new
  Handlers.Callback (Gtk_File_Selection_Record);
@end smallexample

The @code{Files_Cb} package now provides a set of Connect subprograms
that can be used to establish a tie between a widget and a handler.
It also provides a set of other subprograms which you can use to emit
the signals manually, although most of the time, the signals are simply
emitted internally by GtkAda. We will not discuss the Emit_By_Name
subprograms here.

The general form of handler, as used in @code{Gtk.Handlers}, expects some
handlers that take two or three arguments: the widget on which the
signal was applied, an array of all the extra arguments sent internally
by GtkAda, and possibly some user data given when the connection was
made.

This is the most general form of handler and it covers all the possible
cases. However, it also expects the user to manually extract the needed
values from the array of arguments. This is not always the most convenient
solution. This is why GtkAda provides a second package related to signals,
@code{Gtk.Marshallers}.

The @code{Gtk.Marshallers} package provides a set of functions that can
be used as callbacks directly for GtkAda, and that will call your
application's handlers after extracting the required values from the array of
arguments. Although this might sound somewhat complicated, in practice
it simplifies the task of connecting signals. In fact, the techniques
employed are similar to what is done internally by gtk+ in C. Because of
the similarity of techniques, there is no overhead involved in using
@code{Gtk.Marshallers} with Ada over the C code in gtk+.
@c ??? do we really care to include that last sentence?

A set of functions @code{To_Marshaller} is found in every generic package
in @code{Gtk.Handlers}. They each take a single argument, the name of the
function you want to call, and return a handler that can be used directly in
@code{Connect}.

The connection is then done with the following piece of code:

@smallexample
Files_Cb.Object_Connect
  (Get_Ok_Button (Window),  --  The object to connect to the handler
   "clicked",               --  The name of the signal
   Files_Cb.To_Marshaller (Ok'Access),  --  The signal handler
   Slot_Object => Window);
@end smallexample

Note that this can be done just after creating the widget, in the same
block. As soon as it is created, a widget is ready to accept
connections (although no signals will be emitted before the widget is
shown on the screen).

We use @code{To_Marshaller} since our handler does not accept the array
of arguments as a parameter, and we use the special
@code{Object_Connect} procedure. This means that the parameter to
our callback (Files) will be the Slot_Object given in Object_Connect,
instead of being the button itself.

@c ----------------------------------------------------------------------
@node Handling user data
@section Handling user data
@c ----------------------------------------------------------------------

@noindent
As described above, it is possible to define some data that is that
passed to the callback when it is called. This data is called
user_data, and is passed to the @code{Connect} or
@code{Object_Connect} subprograms.

GtkAda will automatically free any memory it has allocated internally
to store this user data. For instance, if you instantiated the
generic package @code{User_Callback} with a String, it means that you
want to be able to have a callback of the form:

@smallexample
   procedure My_Callback (Widget : access Gtk_Widget_Record'Class;
                           User_Data : String);
@end smallexample

and connect it with a call similar to:

@smallexample
   Connect (Button, "Clicked", To_Marshaller (My_Callback'Access),
            User_Data => "any string");
@end smallexample

GtkAda needs to allocate some memory to store the string (an
unconstrained type). However, this memory is automatically freed when
the callback is destroyed.

There are a few subtleties in the use of user_data, most importantly
when the user data is itself a widget.

The following four examples do exactly the same thing: each creates two
buttons, where clicking on the first one will destroy the second one.
They all work fine the first time, while both buttons exist. However,
some of them will fail if you press on the first button a second time.

Complete, compilable source code for these examples can be found in the
distribution's @file{examples/user_data} directory, from which the code
samples below are excerpted.

@subsection First case: simple user data

This code will fail: even after @code{Button2} is destroyed, the Ada
pointer continues to reference memory that has been deallocated.  The
second call to @code{Destroy} will fail with a Storage_Error.

@smallexample
   package User_Callback is new Gtk.Handlers.User_Callback
     (Gtk_Widget_Record, Gtk_Widget);

   procedure My_Destroy2
     (Button : access Gtk_Widget_Record'Class; Data : Gtk_Widget) is
   begin
      Destroy (Data);
   end My_Destroy2;

   begin
      User_Callback.Connect
        (Button1, "clicked",
         User_Callback.To_Marshaller (My_Destroy2'Access),
         Gtk_Widget (Button2));
   end;
@end smallexample

@subsection Second case: using Object_Connect instead

One of the solutions to fix the above problem is to use
@code{Object_Connect} instead of @code{Connect}. In that case, GtkAda
automatically takes care of disconnecting the callback when either of
the two widgets is destroyed.

@smallexample
   procedure My_Destroy (Button : access Gtk_Widget_Record'Class) is
   begin
      Destroy (Button);
   end My_Destroy;

   begin
      Widget_Callback.Object_Connect
        (Button1, "clicked",
         Widget_Callback.To_Marshaller (My_Destroy'Access),
         Button2);
   end;
@end smallexample

@subsection Third case: manually disconnecting the callback

Using @code{Object_Connect} is not always possible. In that case, one
of the possibilities is to store the @code{Id} of the callback, and
properly disconnect it when appropriate. This is the most complex
method, and very often is not applicable, since you cannot know for
sure when the callback is no longer needed.

@smallexample
   type My_Data3 is record
      Button, Object : Gtk_Widget;
      Id             : Handler_Id;
   end record;
   type My_Data3_Access is access My_Data3;

   package User_Callback3 is new Gtk.Handlers.User_Callback
     (Gtk_Widget_Record, My_Data3_Access);

   procedure My_Destroy3
     (Button : access Gtk_Widget_Record'Class;
      Data   : My_Data3_Access) is
   begin
      Destroy (Data.Button);
      Disconnect (Data.Object, Data.Id);
   end My_Destroy3;

      Id : Handler_Id;
   begin
      Data3 := new My_Data3' (Object => Gtk_Widget (Button1),
                              Button => Gtk_Widget (Button2),
                              Id     => (Null_Signal_Id, null));
      Id := User_Callback3.Connect
        (Button1, "clicked",
         User_Callback3.To_Marshaller (My_Destroy3'Access),
         Data3);
      Data3.Id := Id;
   end;
@end smallexample

@subsection Fourth case: setting a watch on a specific widget

GtkAda provides a function @code{Add_Watch}, that will automatically
disconnect a callback when a given widget is destroyed. This is the
function used internally by @code{Object_Connect}. In the example
below, the callback is automatically disconnected whenever
@code{Button2} is destroyed.

@smallexample
   procedure My_Destroy2
     (Button : access Gtk_Widget_Record'Class; Data : Gtk_Widget) is
   begin
      Destroy (Data);
   end My_Destroy2;

      Id : Handler_Id;
   begin
      Id := User_Callback.Connect
        (Button1, "clicked",
         User_Callback.To_Marshaller (My_Destroy2'Access),
         Gtk_Widget (Button2));
      Add_Watch (Id, Button2);
   end;
@end smallexample


@c ----------------------------------------------------------------------
@node Starting an application with GtkAda
@chapter Starting an application with GtkAda
@c ----------------------------------------------------------------------

You need to perform some initializations to start a GtkAda application:
@smallexample
@c @group
@c @cartouche
--  predefined units of the library
@b{with} Gtk.Rc;
@b{with} Gtk.Main;
@b{with} Gtk.Enums;
@b{with} Gtk.Window;
...
--  My units
@b{with} Callbacks;
...
@b{procedure} Application is
   @b{procedure} Create_Window @b{is} ...

@b{begin}
   --  Set the locale specific datas (e.g time and date format)
   Gtk.Main.Set_Locale;

   --  Initializes GtkAda
   Gtk.Main.Init;

   --  Load the resources. Note that this part is optional.
   Gtk.Rc.Parse ("application.rc");

   --  Create the main window
   Create_Window;

   --  Signal handling loop
   Gtk.Main.Main;
@b{end} Application;
@c @end cartouche
@c @end group
@end smallexample

the @code{Create_Window} procedure looks like

@smallexample
@c @group
@c @cartouche
   @b{procedure} Create_Window @b{is}
      Main_Window : Gtk.Window.Gtk_Window;
      ...
   @b{begin}
      Gtk.Window.Gtk_New
        (Window   => Main_Window,
         The_Type => Gtk.Enums.Window_Toplevel);

      --  From Gtk.Widget:
      Gtk.Window.Set_Title (Window => Main_Window, Title  => "Editor");

      --  Construct the window and connect various callbacks

      ...
      Gtk.Window.Show_All (Main_Window);
   @b{end} Create_Window;
@c @end cartouche
@c @end group
@end smallexample

@node Resource files
@chapter Resource files

Resource files let you parametrize aspects of the widgets in a GtkAda
application without having to recompile it.

A resource file needs to be loaded (@code{Gtk.Rc.Parse}) @var{before} setting
the corresponding window.

In this file, it is possible to specify visual characteristics of
widgets, such as their colors and fonts.
Under X, the @code{xfontsel} command allows you to easily select a font.
The FontSelection widget is also a simple way to select fonts.

Here is an example of a resource file:
@smallexample
# application.rc
#
# resource file for "Application"

# Buttons style
style "button"
@{
# BackGround Colors
#                  Red  Green  Blue
  bg[PRELIGHT] = @{ 0.0,  0.75, 0.0 @} # Green when the mouse is on
                                     # the button
  bg[ACTIVE]   = @{ 0.75, 0.0,  0.0 @} # Red on click
# ForeGround Colors
#                  Red  Green  Blue
  fg[PRELIGHT] = @{ 1.0,  1.0,  1.0 @} # White when the mouse is on
                                     # the button
  fg[ACTIVE]   = @{ 1.0,  1.0,  1.0 @} # White on click
@}

# All the buttons will have the style "button"
widget_class "*GtkButton*" style "button"

# Text style
style "text"
@{
  font = "-adobe-courier-medium-r-normal-*-15-*-*-*-*-*-*-*"
  text[NORMAL] = @{ 0.0, 0.0, 0.0 @} # black
  fg[NORMAL]   = @{ 0.0, 0.0, 0.0 @} # black
  base[NORMAL] = @{ 1.0, 1.0, 1.0 @} # white : background color
@}

# All Gtk_Text will have the "text" style
widget_class "*GtkText" style "text"
@end smallexample

@node Memory management
@chapter Memory management

GtkAda takes care of almost all the memory management for you.
Here is a brief overview of how this works, you'll have to check the sources
if you want more detailed information.
Gtk+ (the C library) does its own memory management through reference
counting, i.e. any widget is destroyed when it is no longer referenced anywhere
in the application.

In GtkAda itself, a ``user_data'' is associated with each object
allocated by a @code{Gtk_New} procedure. A ``destroy'' callback is also
associated, to be called when the object to which the
user_data belongs is destroyed.
Thus, every time a C object is destroyed, the equivalent Ada structure is also
destroyed (see @code{Gtk.Free_User_Data}).

Concerning widgets containing children,
every container holds a reference to its children, whose reference counting is
thus different from 0 (and generally 1). When the container is destroyed, the
reference of all its children and grand-children is decremented, and they are
destroyed in turn if needed. So the deallocation of a widget hierarchy is also
performed automatically.

@node Tasking with GtkAda
@chapter Tasking with GtkAda

Note that Gtk+ under Windows does not interact properly with threads,
so the only safe approach under this operating system is to perform all your
Gtk+ calls in the same task.

On other platforms, the Glib library can be used in a task-safe mode by
calling @code{Gdk.Threads.G_Init} and @code{Gdk.Threads.Init} before
making any other Glib/Gdk calls.
Gdk routines may then be called simultaneously by multiple tasks, thanks to
task-safe construction of Gdk's internal data structures. However, Gdk objects
such as hash tables are not automatically protected, so it is the application's
responsibility to prevent simultaneous access to user-defined objects
(e.g. by using protected objects).

When Gdk is initialized to be task-safe, GtkAda becomes task aware. There is
a single global lock that you must acquire with @code{Gdk.Threads.Enter} before
making any Gdk/Gtk call, and which you must release with
@code{Gdk.Threads.Leave} afterwards.

@code{Gtk.Main.Main} should be called with the lock acquired (see example
below), ensuring that all the functions executed in the task that started
the main loop do not need to protect themselves again.

Beware that the GtkAda main loop (@code{Gtk.Main.Main}) can only be be
run inside
one specific task. In other words, you cannot call @code{Gtk.Main.Main} from
any task other than the one that started the outer level main loop.

Note that @code{Gdk.Threads} assumes that you are using a tasking run time
that maps Ada tasks to native threads.

A minimal main program for a tasking GtkAda application looks like:

@smallexample
@b{with} Gdk.Threads;
@b{with} Gtk.Main;
@b{with} Gtk.Enums; @b{use} Gtk.Enums;
@b{with} Gtk.Window; @b{use} Gtk.Window;

@b{procedure} GtkAda_With_Tasks @b{is}
   Window : Gtk_Window;
@b{begin}
   Gdk.Threads.G_Init;
   Gdk.Threads.Init;
   Gtk.Main.Init;

   Gtk_New (Window, Window_Toplevel);
   Show (Window);

   Gdk.Threads.Enter;
   Gtk.Main.Main;
   Gdk.Threads.Leave;
@b{end} GtkAda_With_Tasks;
@end smallexample

Callbacks require a bit of attention. Callbacks from GtkAda (signals) are made
within the GtkAda lock. However, callbacks from Glib (timeouts, IO callbacks,
and idle functions) are made outside of the GtkAda lock. So, within a signal
handler you do not need to call @code{Gdk.Threads.Enter}, but within the other
types of callbacks, you do.

@node Processing external events
@chapter Processing external events

It often happens that your application, in addition to processing graphical
events through the GtkAda main loop, also needs to monitor external events.
This is the case if, for instance, you are running external processes and need
to display their output, or if you are listening to incoming data on a socket.
If you implement your own main loop to poll for these external events and then
invoke the GUI, the GUI will enter its main loop and not return control back
to you.

There are several ways to handle this situation:

@itemize @bullet
@item The cleanest solution, especially if you intend to make the GUI a
 major part of your application (as opposed to just popping up a
 few dialogs here and there), would be to use the gtk+ main loop as the
 infinite loop, instead of yours.

 You can then use gtk+ ``idle callbacks'' (which are called
 every time the gtk+ loop is not busy processing graphical events)
 or ``timeout callbacks'' (which are called every n milliseconds), and
 in those callbacks do the work you were doing before in your own
 main loop (that assumes the check is relatively fast,
 otherwise the GUI will be frozen during that time). Such callbacks
 are created through packages in glib-main.ads

@item Another approach is to not start the gtk+ main loop, but to check
 periodically whether there are some events to be handled.
 See the subprogram @code{Gtk.Main.Main_Iteration}.

 This second approach is not necessarily recommended, since you would
 basically duplicate code that's already in gtk+ to manage the main
 loop, and you also get finer control using idle and timeout callbacks

@end itemize

@node Object-oriented features
@chapter Object-oriented features

GtkAda has been designed from the beginning to provide a full object
oriented layer over gtk+. This means that features such as type
extension and dynamic dispatching are made available through the
standard Ada language.

This section will describe how things work, how you can extend existing
widgets, and even how to create your own widgets.

@menu
* General description of the tagged types::
* Using tagged types to extend Gtk widgets::
* Creating new widgets in Ada::
@end menu

@node General description of the tagged types
@section General description of the tagged types

@subsection Why should I use object-oriented programming ?

Every widget in the @code{Gtk.*} packages in GtkAda is a tagged type with a
number of primitive subprograms that are inherited by all of its children.
Tagged types in Ada make it possible to perform safe, automatic type
conversions without using explicit casts (such as is necessary when coding in
C). It is also possible for the compiler to verify whether or not these type
conversions are valid. Most errors are found at compile time, which leads to a
safer and more robust application.

As a further example, imagine a table that has been populated by some widgets.
It is possible to query for this table's children and operate on these widgets
without knowing details about their type, their creator, and so on--the tagged
objects that are returned contain all the information necessary.
It becomes possible to use dynamic dispatching without ever having to cast
to a known type.

Modifying a standard widget to draw itself differently or display different
data is easy using tagged types.  Simply create a new type that extends the
current one (see the section @ref{Using tagged types to extend Gtk widgets}
below.

Creating a new reusable widget from scratch is also possible.  Create a new
tagged type and specify properties of the widget--such as how it is to draw
itself and how it should react to events.
See the section @ref{Creating new widgets in Ada} below.

Object oriented programming through the use of Ada tagged types makes
GtkAda a very powerful, flexible, and safe tool for designing graphical
interfaces.

@subsection Type conversions from C to Ada widgets

There are three kinds of widgets that you can use with GtkAda:
@itemize @bullet
@item @i{Ada widgets}:
These are widgets that are written directly in Ada, using the object
oriented features of GtkAda
@item @i{Standard widgets}:
These are the widgets that are part of the standard gtk+ and GtkAda
distributions. This include all the basic widgets you need to build
advanced interfaces.
@item @i{third party C widgets}
These are widgets that were created in C, and for which you (or someone else)
created an Ada binding. This is most probably the kind of widgets you will
have if you want to use third party widgets.
@end itemize

GtkAda will always be able to find and/or create a valid tagged type in
the first two cases, no matter if you explicitly created the widget or if it
was created automatically by gtk+. For instance, if you created a widget
in Ada, put it in a table, and later on extracted it from the table, then you
will still have the same widget.

In the third case (third party C widgets), GtkAda is not, by default, able to
create the corresponding Ada type.

The case of third party C widgets is a little bit trickier. Since GtkAda does
not know anything about them when it is built, it can't magically convert the C
widgets to Ada widgets. This is your job to teach GtkAda how to do the
conversion.

We thus provide a 'hook' function which you need to modify. This function is
defined in the package @b{Glib.Type_Conversion}. This function takes
a string with the name of the C widget (ex/ "GtkButton"), and should return a
newly allocated pointer. If you don't know this type either, simply
return @b{null}.

@node Using tagged types to extend Gtk widgets
@section Using tagged types to extend Gtk widgets

With this toolkit, it's possible to associate your
own data with existing widgets simply by creating new types. This
section will show you a simple example, but you should rather read the
source code in the @file{testgtk/} directory where we used this feature
instead of using
@code{user_data} as is used in the C version.

@smallexample
@c @group
@c @cartouche
@b{type} My_Button_Record @b{is new} Gtk_Button_Record @b{with record}
    --  whatever data you want to associate with your button
@b{end record};
@b{type} My_Button @b{is access all} My_Button_Record'@b{Class};
@c @end cartouche
@c @end group
@end smallexample

With the above statements, your new type is defined. Every function
available for @code{Gtk_Button} is also available for @code{My_Button}.
Of course, as with every tagged type in Ada, you can create your own
primitive functions with the following prototype:

@smallexample
@c @group
@c @cartouche
@b{procedure} My_Primitive_Func (Myb : @b{access} My_Button_Record);
@c @end cartouche
@c @end group
@end smallexample

To instanciate an object of type @code{My_Button} in your application, do
the following:

@smallexample
@c @group
@c @cartouche
@b{declare}
   Myb : My_Button;
@b{begin}
   Myb := @b{new} My_Button_Record;
   Initialize (Myb);   --  from Gtk.Button
@b{end};
@c @end cartouche
@c @end group
@end smallexample

The first line creates the Ada type, whereas the @code{Initialize} call
actually creates the C widget and associates it with the Ada type.

@node Creating new widgets in Ada
@section Creating new widgets in Ada

With GtkAda, you can create widgets directly in Ada. These new
widgets can be used directly, as if they were part of gtk itself.

Creating new widgets is a way to create reuseable components. You can
apply to them the same functions as you would for any other widget, such as
@code{Show}, @code{Hide}, and so on.

This section will explain how to create two types of widgets: composite
widgets and widgets created from scratch. Two examples are provided with
GtkAda, in the directories @file{examples/composite_widget} and
@file{examples/base_widget}. Please also refer to the gtk+ tutorial,
which describes the basic mechanisms that you need to know to create
a widget.

@menu
* Creating composite widgets::
* Creating widgets from scratch::
@end menu

@node Creating composite widgets
@subsection Creating composite widgets

A composite widget is a widget that does not do much by itself. Rather,
this is a collection of subwidgets grouped into a more general entity.
For instance, among the standard widgets, @code{Gtk_File_Selection} and
@code{Gtk_Font_Selection} belong to this category.

The good news is that there is nothing special to know. Just create a
new tagged type, extending one of the standard widgets (or even another
of your own widgets), provide a @code{Gtk_New} function that allocates
memory for this widget, and call the @code{Initialize} function that does
the actual creation of the widget and the subwidgets.
There is only one thing to do: @code{Initialize} should call the
parent class's @code{Initialize} function, to create the underlying C
widget.

The example directory @file{examples/composite_widget} reimplements the
@code{Gtk_Dialog} widget as written in C by the creators of gtk+.

@node Creating widgets from scratch
@subsection Creating widgets from scratch

Creating a working widget from scratch requires a certain level of familiary
with the GtkAda signal mechanism and entails much work with low level signals.
This is therefore not an activity recommended for novice GtkAda programmers.

Creating a widget from scratch is what you want to do if your widget should
be drawn in a special way, should create and emit new signals, or otherwise
perform differently than pre-existing widgets.
The example we give in @file{examples/base_widget} is a small target on
which the user can click, and that sends one of two signals: "bullseye" or
"missed", depending on where the user has clicked.

See also the example in @file{examples/tutorial/gtkdial} for a more complex
widget, that implements a gauge where the user can move the arrow to select
a new value.

Once again, the only two functions that you must create are @code{Gtk_New}
and @code{Initialize}.
This time, @code{Initialize} has to do two things:

@smallexample
Parent_Package.Initialize (Widget);

--  The above line calls the Initialize function from the parent.
--  This creates the underlying C widget, which we are going to
--  modify with the following call:

Gtk.Object.Initialize_Class_Record
  (Widget, Signals, Class_Record);
--  This initializes the "class record" for the widget and
--  creates the signals.
@end smallexample

In the above example, the new part is the second call. It takes three or four
arguments:
@itemize @bullet
@item @code{Widget}
This is the widget that you want to initialize

@item @code{Signals}
This is an array of string access containing the name of the signals
you want to create. For instance, you could create Signals with
@smallexample
Signals : Gtkada.Types.Chars_Ptr_Array := "bullseye" + "missed";
@end smallexample
This will create two signals, named "bullseye" and "missed", whose callbacks'
arguments can be specified with the fourth parameter.

@item @code{Class_Record}
Every widget in C is associated with two records. The first one, which exists
only once per widget type, is the ``class record''. It contains the list of
signals that are known by this widget type, the list of default callbacks for
the signals, ...; the second record is an ``instance record'', which contains
data specific to a particular instance.

In GtkAda, the ``instance record'' is simply your tagged type and its fields.
The call to @code{Initialize_Class_Record} is provided to initialize the
``class record''. As we said, there should be only one such record per widget
type. This parameter ``Class_Record'' will point to this records, once it is
created, and will be reused for every instanciation of the widget.

@item @code{Parameters}
This fourth argument is in fact optional, and is used to specify which
kind of parameters each new signal is expecting.
By default (ie if you don't give any value for this parameter), all the
signals won't expect any argument, except of course a possible user_data.
However, you can decide for instance that the first signal ("bullseye") should
in fact take a second argument (say a Gint), and that "missed" will take
two parameters (two Gints).

@code{Parameters} should thus contain a value of
@smallexample
(1 => (1 => Gtk_Type_Int, 2 => Gtk_Type_None),
 2 => (1 => Gtk_Type_Int, 2 => Gtk_Type_Int));
@end smallexample

Due to the way arrays are handled in Ada, each component must have the same
number of signals. However, if you specify a type of @code{Gtk_Type_None}, this
will in fact be considered as no argument. Thus, the first signal above has
only one parameter.

Note also that to be able to emit a signal such a the second one, ie with
multiple arguments, you will have to extend the packages defined in
Gtk.Handlers. By default, the provided packages can only emit up to one
argument (and only for a few specific types). Creating your own
@code{Emit_By_Name} subprograms should not be hard if you look at what is done
in @file{gtk-marshallers.adb}. Basically, something like:

@smallexample
@b{procedure} Emit_With_Two_Ints
  (Object : @b{access} Widget_Type'Class;
   Name   : String;
   Arg1   : Gint;
   Arg2   : Gint);
@b{pragma} Import (C, Emit_With_Two_Ints,
    "gtk_signal_emit_by_name");

Emit_With_Two_Ints (Gtk.Get_Object (Your_Widget),
    "missed" & ASCII.NUL, 1, 2);
@end smallexample

will emit the "missed" signal with the two parameters 1 and 2.

@end itemize

Then of course @code{Initialize} should set up some signal handlers for
the functions you want to redefine.
Three signals are especially useful:

@itemize @bullet

@item "size_request"

This callback is passed one parameter, as in :
@smallexample
@b{procedure} Size_Request
   (Widget      : @b{access} My_Widget_Record;
    Requisition : @b{in out} Gtk.Widget.Gtk_Requisition);
@end smallexample
This function should modify Requisition to specify the widget's ideal
size. This might not be the exact size that will be set, since some
containers might decide to enlarge or to shrink it.

@item "size_allocate"

This callback is called every time the widget is moved in its parent
window, or it is resized. It is passed one paramater, as in :
@smallexample
@b{procedure} Size_Allocate
   (Widget     : @b{access} My_Widget_Record;
    Allocation : @b{in out} Gtk.Widget.Gtk_Allocation)
@end smallexample
This function should take the responsability to move the widget, using
for instance @code{Gdk.Window.Move_Resize}.

@item "expose_event"

This callback is called every time the widget needs to be redrawn. It
is passed one parameter, the area to be redrawn (to speed things up, you
don't need to redraw the whole widget, just this area).

@end itemize


@node Support for Glade the Gtk GUI builder
@chapter Support for Glade, the Gtk GUI builder

@section Introduction
GtkAda now comes with support for the GUI builder Glade (this is not
the glade released with Gnat for distributed systems).
Using Glade itself is straightforward: it is an intuitive point and click
GUI builder. The main difference from other builders is that, since GtkAda
builds a UI with blocks by default, you will not be asked to set the size and
position of your windows by default. If you are looking for this kind of
interaction you should consider using the Gtk_Fixed container. However, please
read the GtkAda reference manual before considering using Gtk_Fixed.

@section Using Glade
Note that we only recommend using version 2.0.0 of Glade, as previous
versions are not compatible. Using this version you can directly create Ada
files from Glade by selecting Ada95 as the language under project options.
Glade saves your interface in a project file whose syntax is XML
based. In the following sections, we will refer to this file as either
@code{the XML file} or @code{the project file} interchangeably.

@subsection Taking advantage of Glade's options
In this XML file, Glade will save various options that Gate can take
advantage of. In particular, going to the project options window, some General
Options in the @code{C Options} section will also be used by Gate: Gettext
support, if enabled, will generate an additional package called <project>_intl
that will use Gtkada.Intl;
The @code{Set Widget Names} option is also recognized and will generate
additional calls to Set_Name for each widget.

@subsection Associating icons with buttons
Up to now, the only way to specify an icon for a button was to associate a
pixmap file to it. As an alternative, if the name specified in the @code{Icon}
field does not contain any dots, Gate will consider the name as a variable
rather than a file name. It is up to you to provide the necessary definitions
in order to compile properly the generated code.

@subsection Note for GNU/Linux users
Some GNU/Linux systems come with a precompiled version of Glade that will
usually have support for Gnome. Gate currently does not provide support
for Gnome, which means that you should not enable Gnome support in Glade.

@section Gate
@subsection Invoking Gate
Gate is a program that is delivered with GtkAda. Gate
takes the Glade XML file as an argument and generates a set of Ada files.
When compiled, these files will recreate the interface you just designed with
Glade.

Gate is generally invoked through the @code{Write source code} button in
Glade's menu bar.

In addition, you can also invoke it from the command line by providing a
Glade project file. This will generate Ada files in the directory set
as the @code{Source Directory} project option, or otherwise in the
current working directory. Note that under Windows, the @code{Source Directory}
option is ignored, and the current directory is always used instead.

@subsection Structure of the generated files
@subsubsection The main file
The main file is the name of the program name specified in the XML Glade file:
@file{<program name>.adb}. It contains initialization and creation code for
each top level widget contained in the XML file. This is intended as a
convenient default to visualize your GUI, but you will usually want to modify
this initialization.

@subsubsection Top level widget files
For each top level widget, Gate will generate a package
@code{<widget>_Pkg} in the files @file{<widget>_pkg.ads} and
@file{.adb}. These packages contain all the GtkAda calls needed to create the
widgets you designed within Glade. You will usually not need to modify these
files yourself.

@subsubsection Main handler file
This file, called @file{callbacks_<program name>.ads} contains all the Handler
package instantiations needed by your application. You will usually not need
to modify it.

@subsubsection Top level widget signal files
These are the most important files created by Gate. Each is called
@file{<widget_name>_pkg-callbacks.adb}.
They contain stubs for all the callbacks related to a top level widget
you declared in Glade. With the main file, this the only files you should modify
yourself. Note that it is recommended that you structure your application such that
the real code is put in separate packages (i.e not generated files) as much
as possible, to avoid potential merging problems when your interface is
significantly changed within Glade. See next section for more details.

Currently, Gate will generate callback stub procedures that can
handle the expected number of arguments for each signal. This is done using
a relatively low level mechanism explained in the reference manual
(package @code{Gtk.Handlers}). Basically, callbacks expecting arguments
will take
a Gtk_Argument as their only parameter, and Gate will generate the appropriate
variable declaration and conversion calls to provide the expected GtkAda
arguments. You should not modify this code by hand unless you know what
you are doing.

For example, given a signal @code{delete_event}, Gate will generate the
following procedure body, giving access to the arguments of this callback:
a @code{Gtk_Window_Record} (Object) and a @code{Gdk_Event} (Arg1)

@smallexample
@b{function} On_Main_Window_Delete_Event
  (Object : @b{access} Gtk_Window_Record'Class;
   Params : Gtk.Arguments.Gtk_Args) return Boolean
@b{is}
   Arg1 : Gdk_Event := To_Event (Params, 1);
@b{begin}
   return False;
@b{end} On_Main_Window_Delete_Event;
@end smallexample

@subsection Modifying generated files
Note that you can easily go back to Glade any time, modify your interface,
and have Gate re-generate a set of files. All your modifications will be
kept in the new files. For that, Gate creates a directory @file{.gate} in the
current directory. Please do not delete it if you want Gate to be able to
keep your changes from one version to the next.

Also note that to keep track of your modifications, gate relies on either
@code{merge}, or @code{patch} and @code{diff} being available on your system.
If you don't have a working set of @code{diff/patch}, @code{configure} will
simply replace them by null operations, which means that regenerated
files will override the previous ones.

Under Windows, Gate will not attempt to merge changes. Instead,
it will always regenerate and overwrite every file.

In some cases, due to major changes in the project file, Gate may not be
able to merge all the changes. In this case, it will notify you so, and
will either keep the old and new sections in the files (if you are using
@code{merge}), or files with a @file{.rej} extension will be generated to help
you do the merge manually.

@subsection Adding Gate support for new widgets

This section is intended for developpers that wish to add support for new
GtkAda widgets in Gate. Note that this section is not complete yet.

@subsubsection Implementing the @code{Generate} procedure
To provide support for a new widget, you first need to write a @code{Generate}
procedure that will take care of generating the piece of code related to
the widget's properties. Note that the parents properties do not
have to be handled by this function.

@itemize @bullet
@item Glib.Glade API
The Glib.Glade package contains a self documented API that will help you
automate most of the work for common widgets.
@item Most common mapping
  @itemize @bullet
  @item Gen_New
  @item Gen_Set
  @item Gen_Call_Child
  @item example
  @end itemize
@item Registering @code{Generate} functions
  Gtk.Glade.Register_Generate (Widget, Func)
This procedure associates a given Generate procedure with a given widget C name.
@end itemize

@section Dynamic loading of XML files
@subsection Introduction to Libglade
Libglade is an external library provided by default on some systems (e.g
GNU/Linux, Gnome) that supports dynamic loading of XML files and creation of
widgets at run time. The advantage of using libglade is that you do not need
to recompile your application to change your user interface. On the other
hand, everything is done at run time, meaning less compile checks, and also the
inability to take advantage of the object oriented features of GtkAda and Ada
such as deriving from a widget creating using the GUI builder, to add fields
and properties.
See packages Glade and Glade.XML for more information.

@section Limitations
Gate currently support all Gtk+ widgets and properties available
under Glade. But, to help you identify widgets that may not be supported (e.g
Gnome widgets), Gate will generate a warning on the standard error:

@smallexample
$ gate warning.glade
Generating Ada files...

GtkAda-WARNING **: Unsupported widget GnomeCanvas (canvas1)
The following files have been created/updated in src:
[...]
@end smallexample

and add a comment in the @file{<widget>_pkg.adb} file that looks like:

@smallexample
--  WARNING: Unsupported widget GnomeCanvas (canvas1)
@end smallexample

This means that while generating the file Gate detected an unsupported
widget (in this case GnomeCanvas) whose name is canvas1.
If you get such a warning your file may or may not compile properly, but
you won't get the complete widget hierarchy at run time.

Feel free to send us (see @ref{How to report bugs}) the XML file that
causes this problem. We don't guarantee a rapid fix for each particular
problem but receiving real examples of missing functionnalities will
certainly help implementing them faster.

@c -------------------------------------------------------------------
@node Binding new widgets
@chapter Binding new widgets
@c -------------------------------------------------------------------

GtkAda comes with a Perl script to help you create a binding to a C widget
(this is the script we have used ourselves).  This will not fully
automate the process, although it should really speed things up. You
will probably need less than 15 min to create a new binding once you
will get used to the way GtkAda works. Note that your C file should
have the same format as is used by Gtk+ itself.

To get started on a new binding, launch the script @file{contrib/binding.pl}
as follows:

@smallexample
$ touch gtk-button.ads
$ binding.pl ../include/gtk/gtkbutton.h > temporary
@end smallexample

This dumps several kind of information on the standard output:

@itemize
@item List of subprograms defined in the @file{.h} file. Their
  documentation is also added, since binding.pl will parse the @file{.c} file
  as appropriate.
@item List of properties and signals for the widget
@item Tentative bodies for the subprograms
  These will often need adjustements, but provide a good start
@end itemize

You can also use this script to update existing bindings:

@smallexample
$ binding.pl ../include/gtk/*.h
@end smallexample

@c -------------------------------------------------------------------
@node Debugging GtkAda applications
@chapter Debugging GtkAda applications
@c -------------------------------------------------------------------

@noindent

This chapter presents a number of technics that can be used when
debugging GtkAda applications. First, the standard tools to debug
Ada applications can be used:

@table @asis
@item Compile with -g
You should almost always include debugging information when compiling
and linking your code. This gives you the possibility to use the
debugger. See below the variable GDK_DEBUG for how to disable grabs.

@item bind with -E
Using this argument on the @code{gnatbind} or @code{gnatmake} command
line will force the compiler to include backtraces when an exception is
raised. These backtraces can be converted to symbolic backtraces by
using the @code{addr2line} tool.

@item Link with -lgmem
Using this switch gives access to the @code{gnatmem} tool, that helps
you to detect memory leaks or doubly-deallocated memory. The latter
often results in hard-to-fix Storage_Error exceptions. See the GNAT
User's guide for more information.

@end table

There are also a number of technics specific to GtkAda or gtk+
applications. For most of them, you might need to recompile these
libraries with the appropriate switches to get access to the extended
debugging features.

@table @asis
@item Use the @code{--sync} switch
Under unix systems, all applications compiled with gtk+ automatically
support this switch, which forces events to be processed synchronously,
thus making it easier to detect problems as soon as they happen.
This switch is not relevant to Windows systems.

@item break on g_log
In the debugger, it is often useful to put a breakpoint on the glib
function @code{g_log}. When gtk+ is linked dynamically, you will need
to first start your application with @code{begin}, then put the
breakpoint and continue the application with @code{cont}. This helps
understand internal errors or warnings reported by gtk+ and glib

@item compile glib with @code{--disable-mem-pools}
Glib, the underlying layer that provides system-independent services
to gtk+, has an extensive and optimized system for memory
allocation. Bigger chunks of Memory are allocated initially, and then
subdivided by glib itself. Although this is extremely performant, this
also make the debugging of memory-related problems (storage_error)
more difficult. Compiling with the above switch forces glib to use the
standard malloc() and free() system calls. On GNU/Linux systems, it might
be useful to set the variable @code{MALLOC_CHECK_} to 1 to use
error-detecting algorithms (see the man page for malloc()).

@item compile glib and gtk+ with @code{--enable-debug=yes}
It is recommended that you specify this switch on the @code{configure}
command line when compiling these two libraries.
In addition to compiling the libraries with debugging information for
the debugger, additional runtime debug options (controllable via
environment variables) become available.
Specifying @code{--enable-debug=no} is not recommended for production
releases (see glib or gtk+ documentation for details).

For these three variables, the possible values are given below. These
are lists of colon-separated keywords. You can choose to remove any of
these value from the variable

@table @samp
@item GOBJECT_DEBUG=objects:signals
This sets up the debugging output for glib. The value @samp{objects}
is probably the most useful, and displays, on exit of the application,
the list of unfreed objects. This helps detect memory leaks. The
second value @samp{signals} will display all the signals emitted by
the objects. Note that this results in a significant amount of output.

@item GDK_DEBUG=updates:nograbs:events:dnd:misc:@*xim:colormap:gdkrgb:gc:pixmap:image:input:cursor
This sets up the debugging output for gdk. The most useful value is
@samp{nograbs}, which prevents the application from ever grabbing the
mouse or keyboards. If you don't set this, it might happen that the
debugger becomes unusable, since you don't have access to the mouse
when the debugger stops on a breakpoint. Another simpler solution is
to debug remotely from another machine, in which case the grabs
won't affect the terminal on which the debugger is running.

@item GTK_DEBUG=misc:plugsocket:text:tree:updates:keybindings
This sets up the debugging output for gtk. Almost all of these values
are mostly for internal use by gtk+ developpers, although
@samp{keybindings} might prove useful sometimes.

@end table

@item Import the C function ada_gtk_debug_get_ref_count
This function has the following Ada profile:
@smallexample
@b{function} Ref_Count (Add : System.Address) @b{return} Guint;
@b{pragma Import} (C, Ref_Count, "ada_gtk_debug_get_ref_count");
@end smallexample

and should be called in a manner similar to

@smallexample
@b{declare}
   Widget : Gtk_Widget;
   Count  : Guint;
@b{begin}
   Count := Ref_Count (Get_Object (Widget));
@b{end};
@end smallexample

and returns the internal reference counter for the widget. When this
counter reaches 0, the memory allocated for the widget is
automatically freed.

This is mostly a debugging aid for people writting their own
containers, and shouldn't generally be needed. You shouldn't rely on
the internal reference counter in your actual code, which is why it
isn't exported by default in GtkAda.

@end table


@c -------------------------------------------------------------------
@node How to report bugs
@chapter How to report bugs
@c -------------------------------------------------------------------

@noindent

GtkAda is a mature, stable toolkit that is heavily and widely used on a variety
of platforms.  We test GtkAda using an Ada version of the @file{testgtk.c} file
found in the gtk+ distribution, as well as by generating a significant
number of interfaces using the GUI builder and Gate.  For code examples that
demonstrate the use of this toolkit, look within the @file{testgtk/} directory.

There are two kinds of problems you can encounter:
@itemize @bullet
@item If the gtk library itself was compiled with warnings turned on, you
may get some  warning messages,  mainly because of types problems.
These warnings should not appear, as we have tried to be as type safe
as possible  in this package. To know exactly where the problem is,
compile your program with debug information, run gdb, and set a
breakpoint on the function @code{g_log}. Then run your program as usual,
using the @code{run} command. Then send us the result of the @code{where}
command. Here is a summary:

@smallexample
@c @group
@c @cartouche
$ gnatmake -f -g <your_program_name> `gtkada-config`
$ gdb <your_program_name>
(gdb) break main
(gdb) run
(gdb) break g_log
(gdb) continue
....
(gdb) where
@c @end cartouche
@c @end group
@end smallexample

@item In  some  (hopefully) rare cases,   you can even get a  segmentation
fault within gtk.  That means there is definitly something wrong either
in your program or in the toolkit.  Please check your program carefully
and, if you think this is a problem in GtkAda itself, send us an e-mail.
@end itemize

If you are a supported user of GNAT, send mail to
@uref{mailto:report@@gnat.com} to report errors, otherwise send mail
to the GtkAda list (@uref{mailto:gtkada@@lists.adacore.com}) explaining exactly
what your are  doing,  what  is  the  expected  result  and  what  you
actually get. Please include the required sources to reproduce the
problem, in a  format usable  by @code{gnatchop}  (basically, insert
all  the required sources at  the end of  the mail). Please  try to
provide as small as possible a  subset of your sources.

Of course, we will  welcome any patch   you can provide, so  that this
toolkit may be as useful as possible.

@c --------------------------------------------------------------
@node Bibliography
@chapter Bibliography

We recommand the following documents. Most of them were written with C
in mind, but should be easily adapted after you've read the rest of
this document.

@itemize @bullet
@item [1] "Gtk+/Gome Application Development" -- Havoc Pennington
This book, by one of the main authors of the the GNOME environment,
describes in detail some of the inner mechanisms of gtk+, including
signal handling, and a complete description of all the widgets and all
the events found in @code{Gdk.Event}.

It is worth noting that this book has been published under the Open
Publication License. You can get an electronic copy of it at
@url{http://www.opencontent.org/}.
@end itemize

@c **********************************
@c * GNU Free Documentation License *
@c **********************************
@include gfdl.texi
@c GNU Free Documentation License

@c @printindex cp
@contents

@bye
