]> Pileus Git - ~andy/gtk/blob - docs/tutorial/gtk_tut.sgml
added graphics, update tutorials appropriately
[~andy/gtk] / docs / tutorial / gtk_tut.sgml
1 <!doctype linuxdoc system>
2
3 <!-- This is the tutorial marked up in SGML
4      (just to show how to write a comment)
5 -->
6
7 <article>
8 <title>GTK Tutorial
9 <author>Ian Main <tt><htmlurl url="mailto:slow@intergate.bc.ca"
10                               name="&lt;slow@intergate.bc.ca&gt;"></tt>,
11 Tony Gale <tt><htmlurl url="mailto:gale@gimp.org"
12                               name="&lt;gale@gimp.org&gt;"></tt
13 <date>March 8th, 1998
14
15 <!-- ***************************************************************** -->
16 <sect>Introduction
17 <!-- ***************************************************************** -->
18 <p>
19 GTK (GIMP Toolkit) was originally developed as a toolkit for the GIMP
20 (General Image Manipulation Program).  GTK is built on top of GDK (GIMP
21 Drawing Kit)  which is basically wrapper around the Xlib functions.  It's
22 called the GIMP toolkit because it was original written for developing
23 the GIMP, but has now been used in several free software projects.  The
24 authors are
25 <itemize>
26 <item> Peter Mattis   <tt><htmlurl url="mailto:petm@xcf.berkeley.edu"
27                            name="petm@xcf.berkeley.edu"></tt>
28 <item> Spencer Kimball <tt><htmlurl url="mailto:spencer@xcf.berkeley.edu"
29                            name="spencer@xcf.berkeley.edu"></tt>
30 <item> Josh MacDonald <tt><htmlurl url="mailto:jmacd@xcf.berkeley.edu"
31                            name="jmacd@xcf.berkeley.edu"></tt>
32 </itemize>
33
34 <p>
35 GTK is essentially an object oriented application programmers interface (API).  
36 Although written completely in
37 C, it is implemented using the idea of classes and callback functions
38 (pointers to functions).
39 <p>
40 There is also a third component called glib which contains a few
41 replacements for some standard calls, as well as some additional functions
42 for handling linked lists etc.  The replacement functions are used to 
43 increase GTK's portability, as some of the functions implemented 
44 here are not available or are nonstandard on other unicies such as 
45 g_strerror().   Some also contain enhancements to the libc versions such as
46 g_malloc has enhanced debugging utilities.
47 <p>
48 This tutorial is an attempt to document as much as possible of GTK, it is by 
49 no means complete.  This
50 tutorial assumes a good understanding of C, and how to create C programs.
51 It would be a great benefit for the reader to have previous X programming
52 experience, but it shouldn't be necessary.  If you are learning GTK as your
53 first widget set, please comment on how you found this tutorial, and what
54 you had troubles with.
55 Note that there is also a C++ API for GTK (GTK--) in the works, so if you
56 prefer to use C++, you should look into this instead.  There's also an
57 Objective C wrapper, and guile bindings available, but I don't follow these.
58 <p>
59 I would very much like to hear any problems you have learning GTK from this
60 document, and would appreciate input as to how it may be improved.
61
62 <!-- ***************************************************************** -->
63 <sect>Getting Started
64 <!-- ***************************************************************** -->
65
66 <p>
67 The first thing to do of course, is download the GTK source and install
68 it.  You can always get the latest version from ftp.gimp.org in /pub/gtk.
69 You can also view other sources of GTK information on http://www.gimp.org/gtk
70 GTK uses GNU autoconf for
71 configuration.  Once untar'd, type ./configure --help to see a list of options.
72 <p>
73 To begin our introduction to GTK, we'll start with the simplest program 
74 possible.  This program will
75 create a 200x200 pixel window and has no way of exiting except to be
76 killed using the shell.
77
78 <tscreen><verb>
79 #include <gtk/gtk.h>
80
81 int main (int argc, char *argv[])
82 {
83     GtkWidget *window;
84     
85     gtk_init (&amp;argc, &amp;argv);
86     
87     window = gtk_window_new (GTK_WINDOW_TOPLEVEL);
88     gtk_widget_show (window);
89     
90     gtk_main ();
91     
92     return 0;
93 }
94 </verb></tscreen>
95
96 All programs will of course include the gtk/gtk.h which declares the
97 variables, functions, structures etc. that will be used in your GTK 
98 application.
99 <p>
100 The next line:
101
102 <tscreen><verb>
103 gtk_init (&amp;argc, &amp;argv);
104 </verb></tscreen>
105
106 calls the function gtk_init(gint *argc, gchar ***argv) which will be
107 called in all GTK applications.  This sets up a few things for us such
108 as the default visual and color map and then proceeds to call
109 gdk_init(gint *argc, gchar ***argv).  This function initializes the
110 library for use, sets up default signal handlers, and checks the
111 arguments passed to your application on the command line, looking for one
112 of the following:
113
114 <itemize>
115 <item> <tt/--display/
116 <item> <tt/--debug-level/
117 <item> <tt/--no-xshm/
118 <item> <tt/--sync/
119 <item> <tt/--show-events/
120 <item> <tt/--no-show-events/
121 </itemize>
122 <p>
123 It removes these from the argument list, leaving anything it does
124 not recognize for your application to parse or ignore.  This creates a set
125 of standard arguments excepted by all GTK applications.
126 <p>
127 The next two lines of code create and display a window.
128
129 <tscreen><verb>
130   window = gtk_window_new (GTK_WINDOW_TOPLEVEL);
131   gtk_widget_show (window);
132 </verb></tscreen>
133
134 The GTK_WINDOW_TOPLEVEL argument specifies that we want the window to
135 undergo window manager decoration and placement. Rather than create a
136 window of 0x0 size, a window without children is set to 200x200 by default
137 so you can still manipulate it.
138 <p>
139 The gtk_widget_show() function, lets GTK know that we are done setting the
140 attributes of this widget, and it can display it.
141 <p>
142 The last line enters the GTK main processing loop.
143
144 <tscreen><verb>
145 gtk_main ();
146 </verb></tscreen>
147
148 gtk_main() is another call you will see in every GTK application.  When
149 control reaches this point, GTK will sleep waiting for X events (such as
150 button or key presses), timeouts, or file IO notifications to occur.
151 In our simple example however, events are ignored.
152
153 <!-- ----------------------------------------------------------------- -->
154 <sect1>Hello World in GTK
155 <p>
156 OK, now for a program with a widget (a button).  It's the classic hello
157 world ala GTK.
158
159 <tscreen><verb>
160 /* helloworld.c */
161
162 #include <gtk/gtk.h>
163
164 /* this is a callback function. the data arguments are ignored in this example..
165  * More on callbacks below. */
166 void hello (GtkWidget *widget, gpointer data)
167 {
168     g_print ("Hello World\n");
169 }
170
171 gint delete_event(GtkWidget *widget, gpointer data)
172 {
173     g_print ("delete event occured\n");
174     /* if you return TRUE in the "delete_event" signal handler, 
175      * GTK will emit the "destroy" signal.  Returning FALSE means
176      * you don't want the window to be destroyed.
177      * This is useful for popping up 'are you sure you want to quit ?'
178      * type dialogs. */
179     
180     /* Change FALSE to TRUE and the main window will be destroyed with
181      * a "delete_event". */
182     
183     return (FALSE); 
184 }
185
186 /* another callback */
187 void destroy (GtkWidget *widget, gpointer data)
188 {
189     gtk_main_quit ();
190 }
191
192 int main (int argc, char *argv[])
193 {
194     /* GtkWidget is the storage type for widgets */
195     GtkWidget *window;
196     GtkWidget *button;
197     
198     /* this is called in all GTK applications.  arguments are parsed from
199      * the command line and are returned to the application. */
200     gtk_init (&amp;argc, &amp;argv);
201     
202     /* create a new window */
203     window = gtk_window_new (GTK_WINDOW_TOPLEVEL);
204     
205     /* when the window is given the "delete_event" signal (this is given
206     * by the window manager (usually the 'close' option, or on the
207     * titlebar), we ask it to call the delete_event () function
208     * as defined above.  The data passed to the callback
209     * function is NULL and is ignored in the callback. */
210     gtk_signal_connect (GTK_OBJECT (window), "delete_event",
211                         GTK_SIGNAL_FUNC (delete_event), NULL);
212     
213     /* here we connect the "destroy" event to a signal handler.  
214      * This event occurs when we call gtk_widget_destroy() on the window,
215      * or if we return 'TRUE' in the "delete_event" callback. */
216     gtk_signal_connect (GTK_OBJECT (window), "destroy",
217                         GTK_SIGNAL_FUNC (destroy), NULL);
218     
219     /* sets the border width of the window. */
220     gtk_container_border_width (GTK_CONTAINER (window), 10);
221     
222     /* creates a new button with the label "Hello World". */
223     button = gtk_button_new_with_label ("Hello World");
224     
225     /* When the button receives the "clicked" signal, it will call the
226      * function hello() passing it NULL as it's argument.  The hello() function is
227      * defined above. */
228     gtk_signal_connect (GTK_OBJECT (button), "clicked",
229                         GTK_SIGNAL_FUNC (hello), NULL);
230     
231     /* This will cause the window to be destroyed by calling
232      * gtk_widget_destroy(window) when "clicked".  Again, the destroy
233      * signal could come from here, or the window manager. */
234     gtk_signal_connect_object (GTK_OBJECT (button), "clicked",
235                                GTK_SIGNAL_FUNC (gtk_widget_destroy),
236                                GTK_OBJECT (window));
237     
238     /* this packs the button into the window (a gtk container). */
239     gtk_container_add (GTK_CONTAINER (window), button);
240     
241     /* the final step is to display this newly created widget... */
242     gtk_widget_show (button);
243     
244     /* and the window */
245     gtk_widget_show (window);
246     
247     /* all GTK applications must have a gtk_main().     Control ends here
248      * and waits for an event to occur (like a key press or mouse event). */
249     gtk_main ();
250     
251     return 0;
252 }
253 </verb></tscreen>
254
255 <!-- ----------------------------------------------------------------- -->
256 <sect1>Compiling Hello World
257 <p>
258 To compile use:
259
260 <tscreen><verb>
261 gcc -Wall -g helloworld.c -o hello_world -L/usr/X11R6/lib \
262     -lgtk -lgdk -lglib -lX11 -lXext -lm
263 </verb></tscreen>
264 <p>
265 The libraries above must all be in your default search paths, if not, add
266 -L&lt;library directory&gt; and gcc will look in these directories for
267 the needed
268 libraries.  For instance, on my Debian Linux system, I have to add
269 <tt>-L/usr/X11R6/lib</> for it to find the X11 libraries.
270 <p>
271 The order of the libraries are significant.  The linker has to know what
272 functions it needs from a library before it processes it.
273 <p>
274 The libraries we are linking in are:
275 <itemize>
276 <item>The GTK library (-lgtk), the widget library, based on top of GDK.
277 <item>The GDK library (-lgdk), the Xlib wrapper.
278 <item>The glib library (-lglib), containing miscellaneous functions, only
279 g_print() is used in this particular example.  GTK is built on top
280 of glib so you will always require this library.  See the section on 
281 <ref id="sec_glib" name="glib"> for details.  
282 <item>The Xlib library (-lX11) which is used by GDK.
283 <item>The Xext library (-lXext).  This contains code for shared memory
284 pixmaps and other X extensions.
285 <item>The math library (-lm).  This is used by GTK for various purposes.
286 </itemize>
287
288 <!-- ----------------------------------------------------------------- -->
289 <sect1>Theory of Signals and Callbacks
290 <p>
291 Before we look in detail at hello world, we'll discuss events and callbacks.
292 GTK is an event driven toolkit, which means it will sleep in
293 gtk_main until an event occurs and control is passed to the appropriate
294 function.
295 <p>
296 This passing of control is done using the idea of "signals".  When an 
297 event occurs, such as the press of a mouse button, the
298 appropriate signal will be "emitted" by the widget that was pressed.  
299 This is how GTK does
300 most of its useful work.  To make a button perform an action, 
301 we set up a signal handler to catch these
302 signals and call the appropriate function.  This is done by using a 
303 function such as:
304
305 <tscreen><verb>
306 gint gtk_signal_connect (GtkObject *object,
307                          gchar *name,
308                          GtkSignalFunc func,
309                          gpointer func_data);
310 </verb></tscreen>
311 <p>
312 Where the first argument is the widget which will be emitting the signal, and
313 the second, the name of the signal you wish to catch.  The third is the function
314 you wish to be called when it is caught, and the fourth, the data you wish
315 to have passed to this function.
316 <p>
317 The function specified in the third argument is called a "callback
318 function", and should be of the form:
319
320 <tscreen><verb>
321 void callback_func(GtkWidget *widget, gpointer *callback_data);
322 </verb></tscreen>
323 <p>
324 Where the first argument will be a pointer to the widget that emitted the signal, and
325 the second, a pointer to the data given as the last argument to the
326 gtk_signal_connect() function as shown above.
327 <p>
328 Another call used in the hello world example, is:
329
330 <tscreen><verb>
331 gint gtk_signal_connect_object (GtkObject *object,
332                                 gchar  *name,
333                                 GtkSignalFunc func,
334                                 GtkObject *slot_object);
335 </verb></tscreen>
336 <p>
337 gtk_signal_connect_object() is the same as gtk_signal_connect() except that
338 the callback function only uses one argument, a
339 pointer to a GTK 
340 object.  So when using this function to connect signals, the callback should be of
341 the form:
342
343 <tscreen><verb>
344 void callback_func (GtkObject *object);
345 </verb></tscreen>
346 <p>
347 Where the object is usually a widget.  We usually don't setup callbacks for
348 gtk_signal_connect_object however.  They are usually used 
349 to call a GTK function that accept a single widget or object as an
350 argument, as is the case in our hello world example.
351
352 The purpose of having two functions to connect signals is simply to allow
353 the callbacks to have a different number of arguments.  Many functions in
354 the GTK library accept only a single GtkWidget pointer as an argument, so you
355 want to use the gtk_signal_connect_object() for these, whereas for your 
356 functions, you may need to have additional data supplied to the callbacks.
357
358 <!-- ----------------------------------------------------------------- -->
359 <sect1>Stepping Through Hello World
360 <p>
361 Now that we know the theory behind this, lets clarify by walking through 
362 the example hello world program.
363 <p>
364 Here is the callback function that will be called when the button is
365 "clicked".  We ignore both the widget and the data in this example, but it 
366 is not hard to do things with them.  The next example will use the data 
367 argument to tell us which button was pressed.
368
369 <tscreen><verb>
370 void hello (GtkWidget *widget, gpointer *data)
371 {
372     g_print ("Hello World\n");
373 }
374 </verb></tscreen>
375
376 <p>
377 This callback is a bit special.  The "delete_event" occurs when the
378 window manager sends this event to the application.  We have a choice here
379 as to what to do about these events.  We can ignore them, make some sort of
380 response, or simply quit the application.
381
382 The value you return in this callback lets GTK know what action to take.
383 By returning FALSE, we let it know that we don't want to have the "destroy"
384 signal emitted, keeping our application running.  By returning TRUE, we 
385 ask that "destroy" is emitted, which in turn will call our "destroy" 
386 signal handler.
387
388 <tscreen><verb>
389 gint delete_event(GtkWidget *widget, gpointer data)
390 {
391     g_print ("delete event occured\n");
392
393     return (FALSE); 
394 }
395 </verb></tscreen>
396
397 <p>
398 Here is another callback function which just quits by calling
399 gtk_main_quit().  Not really much to say about this, it is pretty self
400 explanatory.
401 <tscreen><verb>
402 void destroy (GtkWidget *widget, gpointer *data)
403 {
404     gtk_main_quit ();
405 }
406 </verb></tscreen>
407 <p>
408 I assume you know about the main() function... yes, as with other
409 applications, all GTK applications will also have one of these.
410 <tscreen><verb>
411 int main (int argc, char *argv[])
412 {
413 </verb></tscreen>
414 <p>
415 This next part, declares a pointer to a structure of type GtkWidget.  These
416 are used below to create a window and a button.
417 <tscreen><verb>
418     GtkWidget *window;
419     GtkWidget *button;
420 </verb></tscreen>
421 <p>
422 Here is our gtk_init again.  As before, this initializes the toolkit, and
423 parses the arguments found on the command line.  Any argument it
424 recognizes from the command line, it removes from the list, and modifies
425 argc and argv to make it look like they never existed, allowing your
426 application to parse the remaining arguments.
427 <tscreen><verb>
428     gtk_init (&amp;argc, &amp;argv);
429 </verb></tscreen>
430 <p>
431 Create a new window.  This is fairly straight forward.  Memory is allocated
432 for the GtkWidget *window structure so it now points to a valid structure.
433 It sets up a new window, but it is not displayed until below where we call
434 gtk_widget_show(window) near the end of our program.
435 <tscreen><verb>
436     window = gtk_window_new (GTK_WINDOW_TOPLEVEL);
437 </verb></tscreen>
438 <p>
439 Here is an example of connecting a signal handler to an object, in this case, the
440 window.  Here, the "destroy" signal is caught.  This is emitted when we use
441 the window manager to kill the window (and we return TRUE in the
442 "delete_event" handler), or when we use the
443 gtk_widget_destroy() call passing in the window widget as the object to
444 destroy.  By setting this up, we handle both cases with a single call.
445 Here, it just calls the destroy() function defined above with a NULL
446 argument, which quits GTK for us.  
447 <p>
448 The GTK_OBJECT and GTK_SIGNAL_FUNC are macros that perform type casting and
449 checking for us, as well as aid the readability of the code.
450 <tscreen><verb>
451     gtk_signal_connect (GTK_OBJECT (window), "destroy",
452                         GTK_SIGNAL_FUNC (destroy), NULL);
453 </verb></tscreen>
454 <p>
455 This next function is used to set an attribute of a container object.  
456 This just sets the window
457 so it has a blank area along the inside of it 10 pixels wide where no
458 widgets will go.  There are other similar functions which we will look at 
459 in the section on 
460 <ref id="sec_setting_widget_attributes" name="Setting Widget Attributes">
461 <p>
462 And again, GTK_CONTAINER is a macro to perform type casting.
463 <tscreen><verb>
464     gtk_container_border_width (GTK_CONTAINER (window), 10);
465 </verb></tscreen>
466 <p>
467 This call creates a new button.  It allocates space for a new GtkWidget
468 structure in memory, initializes it, and makes the button pointer point to
469 it.  It will have the label "Hello World" on it when displayed.
470 <tscreen><verb>
471     button = gtk_button_new_with_label ("Hello World");
472 </verb></tscreen>
473 <p>
474 Here, we take this button, and make it do something useful.  We attach a
475 signal handler to it so when it emits the "clicked" signal, our hello()
476 function is called.  The data is ignored, so we simply pass in NULL to the
477 hello() callback function.  Obviously, the "clicked" signal is emitted when
478 we click the button with our mouse pointer.
479
480 <tscreen><verb>
481     gtk_signal_connect (GTK_OBJECT (button), "clicked",
482                         GTK_SIGNAL_FUNC (hello), NULL);
483 </verb></tscreen>
484 <p>
485 We are also going to use this button to exit our program.  This will
486 illustrate how the "destroy"
487 signal may come from either the window manager, or our program.  When the
488 button is "clicked", same as above, it calls the first hello() callback function,
489 and then this one in the order they are set up.  You may have as many
490 callback function as you need, and all will be executed in the order you
491 connected them.  Because the gtk_widget_destroy() function accepts only a
492 GtkWidget *widget as an argument, we use the gtk_signal_connect_object()
493 function here instead of straight gtk_signal_connect().
494
495 <tscreen><verb>
496     gtk_signal_connect_object (GTK_OBJECT (button), "clicked",
497                                GTK_SIGNAL_FUNC (gtk_widget_destroy),
498                                GTK_OBJECT (window));
499 </verb></tscreen>
500 <p>
501 This is a packing call, which will be explained in depth later on.  But it
502 is fairly easy to understand.  It simply tells GTK that the button is to be 
503 placed in the window where it will be displayed.
504 <tscreen><verb>
505     gtk_container_add (GTK_CONTAINER (window), button);
506 </verb></tscreen>
507 <p>
508 Now that we have everything setup the way we want it to be.  With all the
509 signal handlers in place, and the button placed in the window where it
510 should be, we ask GTK to "show" the widgets on the screen.  The window
511 widget is shown last so the whole window will pop up at once rather than
512 seeing the window pop up, and then the button form inside of it.  Although
513 with such simple example, you'd never notice.
514 <tscreen><verb>
515     gtk_widget_show (button);
516
517     gtk_widget_show (window);
518 </verb></tscreen>
519 <p>
520 And of course, we call gtk_main() which waits for events to come from the X
521 server and will call on the widgets to emit signals when these events come.
522 <tscreen><verb>
523     gtk_main ();
524 </verb></tscreen>
525 And the final return.  Control returns here after gtk_quit() is called.
526 <tscreen><verb>
527     return 0;
528 </verb></tscreen>
529 <p>
530 Now, when we click the mouse button on a GTK button, the
531 widget emits a "clicked" signal.  In order for us to use this information, our
532 program sets up a signal handler to catch that signal, which dispatches the function 
533 of our choice. In our example, when the button we created is "clicked", the 
534 hello() function is called with a NULL
535 argument, and then the next handler for this signal is called.  This calls
536 the gtk_widget_destroy() function, passing it the window widget as it's
537 argument, destroying the window widget.  This causes the window to emit the 
538 "destroy" signal, which is
539 caught, and calls our destroy() callback function, which simply exits GTK.
540 <p>
541 Another course of events, is to use the window manager to kill the window.
542 This will cause the "delete_event" to be emitted.  This will call our
543 "delete_event" handler.  If we return FALSE here, the window will be left as
544 is and nothing will happen.  Returning TRUE will cause GTK to emit the
545 "destroy" signal which of course, calls the "destroy" callback, exiting GTK.
546 <p>
547 Note that these signals are not the same as the Unix system
548 signals, and are not implemented using them, although the terminology is
549 almost identical.
550
551 <!-- ***************************************************************** -->
552 <sect>Moving On
553 <!-- ***************************************************************** -->
554
555 <!-- ----------------------------------------------------------------- -->
556 <sect1>Data Types
557 <p>
558 There are a few things you probably noticed in the previous examples that
559 need explaining.  The 
560 gint, gchar etc. that you see are typedefs to int and char respectively.  This is done
561 to get around that nasty dependency on the size of simple data types when doing calculations.
562 A good example is "gint32" which will be
563 typedef'd to a 32 bit integer for any given platform, whether it be the 64 bit
564 alpha, or the 32 bit i386.  The
565 typedefs are very straight forward and intuitive.  They are all defined in
566 glib/glib.h (which gets included from gtk.h).
567 <p>
568 You'll also notice the ability to use GtkWidget when the function calls for a GtkObject.  
569 GTK is an object oriented design, and a widget is an object.
570
571 <!-- ----------------------------------------------------------------- -->
572 <sect1>More on Signal Handlers
573 <p>
574 Lets take another look at the gtk_signal_connect declaration.
575
576 <tscreen><verb>
577 gint gtk_signal_connect (GtkObject *object, gchar *name,
578                          GtkSignalFunc func, gpointer func_data);
579 </verb></tscreen>
580
581 Notice the gint return value ?  This is a tag that identifies your callback
582 function.  As said above, you may have as many callbacks per signal and per
583 object as you need, and each will be executed in turn, in the order they were attached.  
584 This tag allows you to remove this callback from the list by using:
585 <tscreen><verb>
586 void gtk_signal_disconnect (GtkObject *object,
587                             gint id);
588 </verb></tscreen>
589 So, by passing in the widget you wish to remove the handler from, and the
590 tag or id returned by one of the signal_connect functions, you can
591 disconnect a signal handler.
592 <p>
593 Another function to remove all the signal handers from an object is:
594 <tscreen><verb>
595 gtk_signal_handlers_destroy (GtkObject *object);
596 </verb></tscreen>
597 <p>
598 This call is fairly self explanatory.  It simply removes all the current
599 signal handlers from the object passed in as the first argument.
600
601 <!-- ----------------------------------------------------------------- -->
602 <sect1>An Upgraded Hello World
603 <p>
604 Let's take a look at a slightly improved hello world with better examples
605 of callbacks.  This will also introduce us to our next topic, packing
606 widgets.
607
608 <tscreen><verb>
609 /* helloworld2.c */
610
611 #include <gtk/gtk.h>
612
613 /* Our new improved callback.  The data passed to this function is printed
614  * to stdout. */
615 void callback (GtkWidget *widget, gpointer *data)
616 {
617     g_print ("Hello again - %s was pressed\n", (char *) data);
618 }
619
620 /* another callback */
621 void delete_event (GtkWidget *widget, gpointer *data)
622 {
623     gtk_main_quit ();
624 }
625
626 int main (int argc, char *argv[])
627 {
628     /* GtkWidget is the storage type for widgets */
629     GtkWidget *window;
630     GtkWidget *button;
631     GtkWidget *box1;
632
633     /* this is called in all GTK applications.  arguments are parsed from
634      * the command line and are returned to the application. */
635     gtk_init (&amp;argc, &amp;argv);
636
637     /* create a new window */
638     window = gtk_window_new (GTK_WINDOW_TOPLEVEL);
639
640     /* this is a new call, this just sets the title of our
641      * new window to "Hello Buttons!" */
642     gtk_window_set_title (GTK_WINDOW (window), "Hello Buttons!");
643
644     /* Here we just set a handler for delete_event that immediately
645      * exits GTK. */
646     gtk_signal_connect (GTK_OBJECT (window), "delete_event",
647                         GTK_SIGNAL_FUNC (delete_event), NULL);
648
649
650     /* sets the border width of the window. */
651     gtk_container_border_width (GTK_CONTAINER (window), 10);
652
653     /* we create a box to pack widgets into.  this is described in detail
654      * in the "packing" section below.  The box is not really visible, it
655      * is just used as a tool to arrange widgets. */
656     box1 = gtk_hbox_new(FALSE, 0);
657
658     /* put the box into the main window. */
659     gtk_container_add (GTK_CONTAINER (window), box1);
660
661     /* creates a new button with the label "Button 1". */
662     button = gtk_button_new_with_label ("Button 1");
663
664     /* Now when the button is clicked, we call the "callback" function
665      * with a pointer to "button 1" as it's argument */
666     gtk_signal_connect (GTK_OBJECT (button), "clicked",
667                         GTK_SIGNAL_FUNC (callback), (gpointer) "button 1");
668
669     /* instead of gtk_container_add, we pack this button into the invisible
670      * box, which has been packed into the window. */
671     gtk_box_pack_start(GTK_BOX(box1), button, TRUE, TRUE, 0);
672
673     /* always remember this step, this tells GTK that our preparation for
674      * this button is complete, and it can be displayed now. */
675     gtk_widget_show(button);
676
677     /* do these same steps again to create a second button */
678     button = gtk_button_new_with_label ("Button 2");
679
680     /* call the same callback function with a different argument,
681      * passing a pointer to "button 2" instead. */
682     gtk_signal_connect (GTK_OBJECT (button), "clicked",
683                         GTK_SIGNAL_FUNC (callback), (gpointer) "button 2");
684
685     gtk_box_pack_start(GTK_BOX(box1), button, TRUE, TRUE, 0);
686
687     /* The order in which we show the buttons is not really important, but I
688      * recommend showing the window last, so it all pops up at once. */
689     gtk_widget_show(button);
690
691     gtk_widget_show(box1);
692
693     gtk_widget_show (window);
694
695     /* rest in gtk_main and wait for the fun to begin! */
696     gtk_main ();
697
698     return 0;
699 }
700 </verb></tscreen>
701 <p>
702 Compile this program using the same linking arguments as our first example.
703 You'll notice this time there is no easy way to exit the program, you have to use
704 your window manager or command line to kill it.  A good exercise for the
705 reader would be to insert a third "Quit" button that will exit the
706 program.  You may also wish to play with the options to
707 gtk_box_pack_start() while reading the next section.  
708 Try resizing the window, and observe the behavior.
709 <p>
710 Just as a side note, there is another useful define for gtk_window_new() -
711 GTK_WINDOW_DIALOG.  This interacts with the window manager a little
712 differently and should be used for transient windows.
713
714 <!-- ***************************************************************** -->
715 <sect>Packing Widgets
716 <!-- ***************************************************************** -->
717
718 <p>
719 When creating an application, you'll want to put more than one button
720 inside a window.  Our first hello world example only used one widget so we
721 could simply use a gtk_container_add call to "pack" the widget into the
722 window.  But when you want to put more than one widget into a window, how
723 do you control where that widget is positioned ?  This is where packing
724 comes in.
725
726 <!-- ----------------------------------------------------------------- -->
727 <sect1>Theory of Packing Boxes
728 <p>
729 Most packing is done by creating boxes as in the example above.  These are
730 invisible widget containers that we can pack our widgets into and come in
731 two forms, a horizontal box, and a vertical box.  When packing widgets
732 into a horizontal box, the objects are inserted horizontally from left to
733 right or right to left depending on the call used. In a vertical box,
734 widgets are packed from top to bottom or vice versa.  You may use any
735 combination of boxes inside or beside other boxes to create the desired
736 effect.
737 <p>
738 To create a new horizontal box, we use a call to gtk_hbox_new(), and for
739 vertical boxes, gtk_vbox_new().  The gtk_box_pack_start() and
740 gtk_box_pack_end() functions are used to place objects inside of these
741 containers.  The gtk_box_pack_start() function will start at the top and
742 work its way down in a vbox, and pack left to right in an hbox.
743 gtk_box_pack_end() will do the opposite, packing from bottom to top in a
744 vbox, and right to left in an hbox.  Using these functions allow us to
745 right justify or left justify our widgets and may be mixed in any way to
746 achieve the desired effect.  We will use gtk_box_pack_start() in most of
747 our examples.  An object may be another container or a widget.  And in
748 fact, many widgets are actually containers themselves including the
749 button, but we usually only use a label inside a button.
750 <p>
751 By using these calls, GTK knows where you want to place your widgets so it
752 can do automatic resizing and other nifty things.  there's also a number
753 of options as to how your widgets should be packed. As you can imagine,
754 this method gives us a quite a bit of flexibility when placing and
755 creating widgets.
756
757 <!-- ----------------------------------------------------------------- -->
758 <sect1>Details of Boxes
759 <p>
760 Because of this flexibility, packing boxes in GTK can be confusing at
761 first. There are a lot of options, and it's not immediately obvious how
762 they all fit together.  In the end however, there are basically five
763 different styles you can get.
764
765 <p>
766 <? <CENTER> >
767 <?
768 <IMG SRC="gtk_tut_packbox1.gif" VSPACE="15" HSPACE="10" WIDTH="528" HEIGHT="235"
769 ALT="Box Packing Example Image">
770 >
771 <? </CENTER> >
772
773 Each line contains one horizontal box (hbox) with several buttons. The
774 call to gtk_box_pack is shorthand for the call to pack each of the buttons
775 into the hbox. Each of the buttons is packed into the hbox the same way
776 (i.e. same arguments to the gtk_box_pack_start () function).
777 <p>
778 This is the declaration of the gtk_box_pack_start function.
779
780 <tscreen><verb>
781 void gtk_box_pack_start (GtkBox    *box,
782                          GtkWidget *child,
783                          gint       expand,
784                          gint       fill,
785                          gint       padding);
786 </verb></tscreen>
787
788 The first argument is the box you are packing the object into, the second
789 is this object.  The objects will all be buttons for now, so we'll be
790 packing buttons into boxes.
791 <p>
792 The expand argument to gtk_box_pack_start() or gtk_box_pack_end() controls
793 whether the widgets are laid out in the box to fill in all the extra space
794 in the box so the box is expanded to fill the area alloted to it (TRUE).
795 Or the box is shrunk to just fit the widgets (FALSE).  Setting expand to
796 FALSE will allow you to do right and left
797 justifying of your widgets.  Otherwise, they will all expand to fit in the
798 box, and the same effect could be achieved by using only one of
799 gtk_box_pack_start or pack_end functions.
800 <p>
801 The fill argument to the gtk_box_pack functions control whether the extra
802 space is allocated to the objects themselves (TRUE), or as extra padding
803 in the box around these objects (FALSE). It only has an effect if the
804 expand argument is also TRUE.
805 <p>
806 When creating a new box, the function looks like this:
807
808 <tscreen><verb>
809 GtkWidget * gtk_hbox_new (gint homogeneous,
810                           gint spacing);
811 </verb></tscreen>
812
813 The homogeneous argument to gtk_hbox_new (and the same for gtk_vbox_new)
814 controls whether each object in the box has the same size (i.e. the same
815 width in an hbox, or the same height in a vbox). If it is set, the expand
816 argument to the gtk_box_pack routines is always turned on.
817 <p>
818 What's the difference between spacing (set when the box is created) and
819 padding (set when elements are packed)? Spacing is added between objects,
820 and padding is added on either side of an object.  The following figure
821 should make it clearer:
822
823 <? <CENTER> >
824 <?
825 <IMG ALIGN="center" SRC="gtk_tut_packbox2.gif" WIDTH="509" HEIGHT="213"
826 VSPACE="15" HSPACE="10" ALT="Box Packing Example Image">
827 >
828 <? </CENTER> >
829
830 Here is the code used to create the above images.  I've commented it fairly
831 heavily so hopefully you won't have any problems following it.  Compile it yourself
832 and play with it.
833
834 <!-- ----------------------------------------------------------------- -->
835 <sect1>Packing Demonstration Program
836 <p>
837 <tscreen><verb>
838 /* packbox.c */
839
840 #include "gtk/gtk.h"
841
842 void
843 delete_event (GtkWidget *widget, gpointer *data)
844 {
845     gtk_main_quit ();
846 }
847
848 /* Make a new hbox filled with button-labels. Arguments for the 
849  * variables we're interested are passed in to this function. 
850  * We do not show the box, but do show everything inside. */
851 GtkWidget *make_box (gint homogeneous, gint spacing,
852                      gint expand, gint fill, gint padding) 
853 {
854     GtkWidget *box;
855     GtkWidget *button;
856     char padstr[80];
857     
858     /* create a new hbox with the appropriate homogeneous and spacing
859      * settings */
860     box = gtk_hbox_new (homogeneous, spacing);
861     
862     /* create a series of buttons with the appropriate settings */
863     button = gtk_button_new_with_label ("gtk_box_pack");
864     gtk_box_pack_start (GTK_BOX (box), button, expand, fill, padding);
865     gtk_widget_show (button);
866     
867     button = gtk_button_new_with_label ("(box,");
868     gtk_box_pack_start (GTK_BOX (box), button, expand, fill, padding);
869     gtk_widget_show (button);
870     
871     button = gtk_button_new_with_label ("button,");
872     gtk_box_pack_start (GTK_BOX (box), button, expand, fill, padding);
873     gtk_widget_show (button);
874     
875     /* create a button with the label depending on the value of
876      * expand. */
877     if (expand == TRUE)
878             button = gtk_button_new_with_label ("TRUE,");
879     else
880             button = gtk_button_new_with_label ("FALSE,");
881     
882     gtk_box_pack_start (GTK_BOX (box), button, expand, fill, padding);
883     gtk_widget_show (button);
884     
885     /* This is the same as the button creation for "expand"
886      * above, but uses the shorthand form. */
887     button = gtk_button_new_with_label (fill ? "TRUE," : "FALSE,");
888     gtk_box_pack_start (GTK_BOX (box), button, expand, fill, padding);
889     gtk_widget_show (button);
890     
891     sprintf (padstr, "%d);", padding);
892     
893     button = gtk_button_new_with_label (padstr);
894     gtk_box_pack_start (GTK_BOX (box), button, expand, fill, padding);
895     gtk_widget_show (button);
896     
897     return box;
898 }
899
900 int
901 main (int argc, char *argv[])
902 {
903     GtkWidget *window;
904     GtkWidget *button;
905     GtkWidget *box1;
906     GtkWidget *box2;
907     GtkWidget *separator;
908     GtkWidget *label;
909     GtkWidget *quitbox;
910     int which;
911     
912     /* Our init, don't forget this! :) */
913     gtk_init (&amp;argc, &amp;argv);
914     
915     if (argc != 2) {
916         fprintf (stderr, "usage: packbox num, where num is 1, 2, or 3.\n");
917         /* this just does cleanup in GTK, and exits with an exit status of 1. */
918         gtk_exit (1);
919     }
920     
921     which = atoi (argv[1]);
922
923     /* Create our window */
924     window = gtk_window_new (GTK_WINDOW_TOPLEVEL);
925
926     /* You should always remember to connect the destroy signal to the
927      * main window.  This is very important for proper intuitive
928      * behavior */
929     gtk_signal_connect (GTK_OBJECT (window), "delete_event",
930                         GTK_SIGNAL_FUNC (delete_event), NULL);
931     gtk_container_border_width (GTK_CONTAINER (window), 10);
932     
933     /* We create a vertical box (vbox) to pack the horizontal boxes into.
934      * This allows us to stack the horizontal boxes filled with buttons one
935      * on top of the other in this vbox. */
936     box1 = gtk_vbox_new (FALSE, 0);
937     
938     /* which example to show.  These correspond to the pictures above. */
939     switch (which) {
940     case 1:
941         /* create a new label. */
942         label = gtk_label_new ("gtk_hbox_new (FALSE, 0);");
943         
944         /* Align the label to the left side.  We'll discuss this function and 
945          * others in the section on Widget Attributes. */
946         gtk_misc_set_alignment (GTK_MISC (label), 0, 0);
947
948         /* Pack the label into the vertical box (vbox box1).  Remember that 
949          * widgets added to a vbox will be packed one on top of the other in
950          * order. */
951         gtk_box_pack_start (GTK_BOX (box1), label, FALSE, FALSE, 0);
952         
953         /* show the label */
954         gtk_widget_show (label);
955         
956         /* call our make box function - homogeneous = FALSE, spacing = 0,
957          * expand = FALSE, fill = FALSE, padding = 0 */
958         box2 = make_box (FALSE, 0, FALSE, FALSE, 0);
959         gtk_box_pack_start (GTK_BOX (box1), box2, FALSE, FALSE, 0);
960         gtk_widget_show (box2);
961
962         /* call our make box function - homogeneous = FALSE, spacing = 0,
963          * expand = FALSE, fill = FALSE, padding = 0 */
964         box2 = make_box (FALSE, 0, TRUE, FALSE, 0);
965         gtk_box_pack_start (GTK_BOX (box1), box2, FALSE, FALSE, 0);
966         gtk_widget_show (box2);
967         
968         /* Args are: homogeneous, spacing, expand, fill, padding */
969         box2 = make_box (FALSE, 0, TRUE, TRUE, 0);
970         gtk_box_pack_start (GTK_BOX (box1), box2, FALSE, FALSE, 0);
971         gtk_widget_show (box2);
972         
973         /* creates a separator, we'll learn more about these later, 
974          * but they are quite simple. */
975         separator = gtk_hseparator_new ();
976         
977         /* pack the separator into the vbox.  Remember each of these
978          * widgets are being packed into a vbox, so they'll be stacked
979          * vertically. */
980         gtk_box_pack_start (GTK_BOX (box1), separator, FALSE, TRUE, 5);
981         gtk_widget_show (separator);
982         
983         /* create another new label, and show it. */
984         label = gtk_label_new ("gtk_hbox_new (TRUE, 0);");
985         gtk_misc_set_alignment (GTK_MISC (label), 0, 0);
986         gtk_box_pack_start (GTK_BOX (box1), label, FALSE, FALSE, 0);
987         gtk_widget_show (label);
988         
989         /* Args are: homogeneous, spacing, expand, fill, padding */
990         box2 = make_box (TRUE, 0, TRUE, FALSE, 0);
991         gtk_box_pack_start (GTK_BOX (box1), box2, FALSE, FALSE, 0);
992         gtk_widget_show (box2);
993         
994         /* Args are: homogeneous, spacing, expand, fill, padding */
995         box2 = make_box (TRUE, 0, TRUE, TRUE, 0);
996         gtk_box_pack_start (GTK_BOX (box1), box2, FALSE, FALSE, 0);
997         gtk_widget_show (box2);
998         
999         /* another new separator. */
1000         separator = gtk_hseparator_new ();
1001         /* The last 3 arguments to gtk_box_pack_start are: expand, fill, padding. */
1002         gtk_box_pack_start (GTK_BOX (box1), separator, FALSE, TRUE, 5);
1003         gtk_widget_show (separator);
1004         
1005         break;
1006
1007     case 2:
1008
1009         /* create a new label, remember box1 is a vbox as created 
1010          * near the beginning of main() */
1011         label = gtk_label_new ("gtk_hbox_new (FALSE, 10);");
1012         gtk_misc_set_alignment (GTK_MISC (label), 0, 0);
1013         gtk_box_pack_start (GTK_BOX (box1), label, FALSE, FALSE, 0);
1014         gtk_widget_show (label);
1015         
1016         /* Args are: homogeneous, spacing, expand, fill, padding */
1017         box2 = make_box (FALSE, 10, TRUE, FALSE, 0);
1018         gtk_box_pack_start (GTK_BOX (box1), box2, FALSE, FALSE, 0);
1019         gtk_widget_show (box2);
1020         
1021         /* Args are: homogeneous, spacing, expand, fill, padding */
1022         box2 = make_box (FALSE, 10, TRUE, TRUE, 0);
1023         gtk_box_pack_start (GTK_BOX (box1), box2, FALSE, FALSE, 0);
1024         gtk_widget_show (box2);
1025         
1026         separator = gtk_hseparator_new ();
1027         /* The last 3 arguments to gtk_box_pack_start are: expand, fill, padding. */
1028         gtk_box_pack_start (GTK_BOX (box1), separator, FALSE, TRUE, 5);
1029         gtk_widget_show (separator);
1030         
1031         label = gtk_label_new ("gtk_hbox_new (FALSE, 0);");
1032         gtk_misc_set_alignment (GTK_MISC (label), 0, 0);
1033         gtk_box_pack_start (GTK_BOX (box1), label, FALSE, FALSE, 0);
1034         gtk_widget_show (label);
1035         
1036         /* Args are: homogeneous, spacing, expand, fill, padding */
1037         box2 = make_box (FALSE, 0, TRUE, FALSE, 10);
1038         gtk_box_pack_start (GTK_BOX (box1), box2, FALSE, FALSE, 0);
1039         gtk_widget_show (box2);
1040         
1041         /* Args are: homogeneous, spacing, expand, fill, padding */
1042         box2 = make_box (FALSE, 0, TRUE, TRUE, 10);
1043         gtk_box_pack_start (GTK_BOX (box1), box2, FALSE, FALSE, 0);
1044         gtk_widget_show (box2);
1045         
1046         separator = gtk_hseparator_new ();
1047         /* The last 3 arguments to gtk_box_pack_start are: expand, fill, padding. */
1048         gtk_box_pack_start (GTK_BOX (box1), separator, FALSE, TRUE, 5);
1049         gtk_widget_show (separator);
1050         break;
1051     
1052     case 3:
1053
1054     /* This demonstrates the ability to use gtk_box_pack_end() to
1055          * right justify widgets.  First, we create a new box as before. */
1056         box2 = make_box (FALSE, 0, FALSE, FALSE, 0);
1057         /* create the label that will be put at the end. */
1058         label = gtk_label_new ("end");
1059         /* pack it using gtk_box_pack_end(), so it is put on the right side
1060          * of the hbox created in the make_box() call. */
1061         gtk_box_pack_end (GTK_BOX (box2), label, FALSE, FALSE, 0);
1062         /* show the label. */
1063         gtk_widget_show (label);
1064         
1065         /* pack box2 into box1 (the vbox remember ? :) */
1066         gtk_box_pack_start (GTK_BOX (box1), box2, FALSE, FALSE, 0);
1067         gtk_widget_show (box2);
1068         
1069         /* a separator for the bottom. */
1070         separator = gtk_hseparator_new ();
1071         /* this explicitly sets the separator to 400 pixels wide by 5 pixels
1072          * high.  This is so the hbox we created will also be 400 pixels wide,
1073          * and the "end" label will be separated from the other labels in the
1074          * hbox.  Otherwise, all the widgets in the hbox would be packed as
1075          * close together as possible. */
1076         gtk_widget_set_usize (separator, 400, 5);
1077         /* pack the separator into the vbox (box1) created near the start 
1078          * of main() */
1079         gtk_box_pack_start (GTK_BOX (box1), separator, FALSE, TRUE, 5);
1080         gtk_widget_show (separator);    
1081     }
1082     
1083     /* Create another new hbox.. remember we can use as many as we need! */
1084     quitbox = gtk_hbox_new (FALSE, 0);
1085     
1086     /* Our quit button. */
1087     button = gtk_button_new_with_label ("Quit");
1088     
1089     /* setup the signal to destroy the window.  Remember that this will send
1090      * the "destroy" signal to the window which will be caught by our signal
1091      * handler as defined above. */
1092     gtk_signal_connect_object (GTK_OBJECT (button), "clicked",
1093                                GTK_SIGNAL_FUNC (gtk_main_quit),
1094                                GTK_OBJECT (window));
1095     /* pack the button into the quitbox.
1096      * The last 3 arguments to gtk_box_pack_start are: expand, fill, padding. */
1097     gtk_box_pack_start (GTK_BOX (quitbox), button, TRUE, FALSE, 0);
1098     /* pack the quitbox into the vbox (box1) */
1099     gtk_box_pack_start (GTK_BOX (box1), quitbox, FALSE, FALSE, 0);
1100     
1101     /* pack the vbox (box1) which now contains all our widgets, into the
1102      * main window. */
1103     gtk_container_add (GTK_CONTAINER (window), box1);
1104     
1105     /* and show everything left */
1106     gtk_widget_show (button);
1107     gtk_widget_show (quitbox);
1108     
1109     gtk_widget_show (box1);
1110     /* Showing the window last so everything pops up at once. */
1111     gtk_widget_show (window);
1112     
1113     /* And of course, our main function. */
1114     gtk_main ();
1115
1116     /* control returns here when gtk_main_quit() is called, but not when 
1117      * gtk_exit is used. */
1118     
1119     return 0;
1120 }
1121 </verb></tscreen>
1122
1123 <!-- ----------------------------------------------------------------- -->
1124 <sect1>Packing Using Tables
1125 <p>
1126 Let's take a look at another way of packing - Tables.  These can be
1127 extremely useful in certain situations.
1128
1129 Using tables, we create a grid that we can place widgets in.  The widgets
1130 may take up as many spaces as we specify.
1131
1132 The first thing to look at of course, is the gtk_table_new function:
1133
1134 <tscreen><verb>
1135 GtkWidget* gtk_table_new (gint rows,
1136                           gint columns,
1137                           gint homogeneous);
1138 </verb></tscreen>
1139 <p>
1140 The first argument is the number of rows to make in the table, while the
1141 second, obviously, the number of columns.
1142
1143 The homogeneous argument has to do with how the table's boxes are sized.  If homogeneous 
1144 is TRUE, the table boxes are resized to the size of the largest widget in the table.
1145 If homogeneous is FALSE, the size of a table boxes is dictated by the tallest widget 
1146 in its same row, and the widest widget in its column.
1147
1148 The rows and columnts are laid out starting with 0 to n, where n was the
1149 number specified in the call to gtk_table_new.  So, if you specify rows = 2 and 
1150 columns = 2, the layout would look something like this:
1151
1152 <tscreen><verb>
1153  0          1          2
1154 0+----------+----------+
1155  |          |          |
1156 1+----------+----------+
1157  |          |          |
1158 2+----------+----------+
1159 </verb></tscreen>
1160 <p>
1161 Note that the coordinate system starts in the upper left hand corner.  To place a 
1162 widget into a box, use the following function:
1163
1164 <tscreen><verb>
1165 void gtk_table_attach (GtkTable      *table,
1166                        GtkWidget     *child,
1167                        gint           left_attach,
1168                        gint           right_attach,
1169                        gint           top_attach,
1170                        gint           bottom_attach,
1171                        gint           xoptions,
1172                        gint           yoptions,
1173                        gint           xpadding,
1174                        gint           ypadding);
1175 </verb></tscreen>                                      
1176 <p>
1177 Where the first argument ("table") is the table you've created and the second
1178 ("child") the widget you wish to place in the table.
1179
1180 The left and right attach 
1181 arguments specify where to place the widget, and how many boxes to use.  If you want 
1182 a button in the lower right table entry 
1183 of our 2x2 table, and want it to fill that entry ONLY.  left_attach would be = 1, 
1184 right_attach = 2, top_attach = 1, bottom_attach = 2.
1185
1186 Now, if you wanted a widget to take up the whole 
1187 top row of our 2x2 table, you'd use left_attach = 0, right_attach =2, top_attach = 0, 
1188 bottom_attach = 1.
1189
1190 The xoptions and yoptions are used to specify packing options and may be OR'ed 
1191 together to allow multiple options.  
1192
1193 These options are:
1194 <itemize>
1195 <item>GTK_FILL - If the table box is larger than the widget, and GTK_FILL is
1196 specified, the widget will expand to use all the room available.
1197
1198 <item>GTK_SHRINK - If the table widget was allocated less space then was
1199 requested (usually by the user resizing the window), then the widgets would 
1200 normally just be pushed off the bottom of
1201 the window and disappear.  If GTK_SHRINK is specified, the widgets will
1202 shrink with the table.
1203
1204 <item>GTK_EXPAND - This will cause the table to expand to use up any remaining
1205 space in the window.
1206 </itemize>
1207
1208 Padding is just like in boxes, creating a clear area around the widget
1209 specified in pixels.  
1210
1211 gtk_table_attach() has a LOT of options.  So, there's a shortcut:
1212
1213 <tscreen><verb>
1214 void gtk_table_attach_defaults (GtkTable   *table,
1215                                 GtkWidget  *widget,
1216                                 gint        left_attach,
1217                                 gint        right_attach,
1218                                 gint        top_attach,
1219                                 gint        bottom_attach);
1220 </verb></tscreen>
1221
1222 The X and Y options default to GTK_FILL | GTK_EXPAND, and X and Y padding
1223 are set to 0.  The rest of the arguments are identical to the previous
1224 function.
1225
1226 We also have gtk_table_set_row_spacing() and gtk_table_set_col_spacing().  This places 
1227 spacing between the rows at the specified row or column.
1228
1229 <tscreen><verb>
1230 void gtk_table_set_row_spacing (GtkTable      *table,
1231                                 gint           row,
1232                                 gint           spacing);
1233 </verb></tscreen>
1234 and
1235 <tscreen><verb>
1236 void       gtk_table_set_col_spacing  (GtkTable      *table,
1237                                        gint           column,
1238                                        gint           spacing);
1239 </verb></tscreen>
1240
1241 Note that for columns, the space goes to the right of the column, and for rows, 
1242 the space goes below the row.
1243
1244 You can also set a consistent spacing of all rows and/or columns with:
1245
1246 <tscreen><verb>
1247 void gtk_table_set_row_spacings (GtkTable *table,
1248                                  gint      spacing);
1249 </verb></tscreen>
1250 <p>
1251 And,
1252 <tscreen><verb>
1253 void gtk_table_set_col_spacings (GtkTable  *table,
1254                                  gint       spacing);
1255 </verb></tscreen>
1256 <p>
1257 Note that with these calls, the last row and last column do not get any spacing 
1258
1259 <!-- ----------------------------------------------------------------- -->
1260 <sect1>Table Packing Example
1261 <p>
1262 Here we make a window with three buttons in a 2x2 table.
1263 The first two buttons will be placed in the upper row.
1264 A third, quit button, is placed in the lower row, spanning both columns.
1265 Which means it should look something like this:
1266 <p>
1267 <? <CENTER> >
1268 <?
1269 <IMG SRC="gtk_tut_table.gif" VSPACE="15" HSPACE="10" 
1270 ALT="Table Packing Example Image" WIDTH="180" HEIGHT="120">
1271 >
1272 <? </CENTER> >
1273
1274 Here's the source code:
1275
1276 <tscreen><verb>
1277 /* table.c */
1278 #include <gtk/gtk.h>
1279
1280 /* our callback.
1281  * the data passed to this function is printed to stdout */
1282 void callback (GtkWidget *widget, gpointer *data)
1283 {
1284     g_print ("Hello again - %s was pressed\n", (char *) data);
1285 }
1286
1287 /* this callback quits the program */
1288 void delete_event (GtkWidget *widget, gpointer *data)
1289 {
1290     gtk_main_quit ();
1291 }
1292
1293 int main (int argc, char *argv[])
1294 {
1295     GtkWidget *window;
1296     GtkWidget *button;
1297     GtkWidget *table;
1298
1299     gtk_init (&amp;argc, &amp;argv);
1300
1301     /* create a new window */
1302     window = gtk_window_new (GTK_WINDOW_TOPLEVEL);
1303
1304     /* set the window title */
1305     gtk_window_set_title (GTK_WINDOW (window), "Table");
1306
1307     /* set a handler for delete_event that immediately
1308      * exits GTK. */
1309     gtk_signal_connect (GTK_OBJECT (window), "delete_event",
1310                         GTK_SIGNAL_FUNC (delete_event), NULL);
1311
1312     /* sets the border width of the window. */
1313     gtk_container_border_width (GTK_CONTAINER (window), 20);
1314
1315     /* create a 2x2 table */
1316     table = gtk_table_new (2, 2, TRUE);
1317
1318     /* put the table in the main window */
1319     gtk_container_add (GTK_CONTAINER (window), table);
1320
1321     /* create first button */
1322     button = gtk_button_new_with_label ("button 1");
1323
1324     /* when the button is clicked, we call the "callback" function
1325      * with a pointer to "button 1" as it's argument */
1326     gtk_signal_connect (GTK_OBJECT (button), "clicked",
1327               GTK_SIGNAL_FUNC (callback), (gpointer) "button 1");
1328
1329
1330     /* insert button 1 into the upper left quadrant of the table */
1331     gtk_table_attach_defaults (GTK_TABLE(table), button, 0, 1, 0, 1);
1332
1333     gtk_widget_show (button);
1334
1335     /* create second button */
1336
1337     button = gtk_button_new_with_label ("button 2");
1338
1339     /* when the button is clicked, we call the "callback" function
1340      * with a pointer to "button 2" as it's argument */
1341     gtk_signal_connect (GTK_OBJECT (button), "clicked",
1342               GTK_SIGNAL_FUNC (callback), (gpointer) "button 2");
1343     /* insert button 2 into the upper right quadrant of the table */
1344     gtk_table_attach_defaults (GTK_TABLE(table), button, 1, 2, 0, 1);
1345
1346     gtk_widget_show (button);
1347
1348     /* create "Quit" button */
1349     button = gtk_button_new_with_label ("Quit");
1350
1351     /* when the button is clicked, we call the "delete_event" function
1352      * and the program exits */
1353     gtk_signal_connect (GTK_OBJECT (button), "clicked",
1354                         GTK_SIGNAL_FUNC (delete_event), NULL);
1355
1356     /* insert the quit button into the both 
1357      * lower quadrants of the table */
1358     gtk_table_attach_defaults (GTK_TABLE(table), button, 0, 2, 1, 2);
1359
1360     gtk_widget_show (button);
1361
1362     gtk_widget_show (table);
1363     gtk_widget_show (window);
1364
1365     gtk_main ();
1366
1367     return 0;
1368 }
1369 </verb></tscreen>
1370
1371 You can compile this program with something like:
1372
1373 <tscreen><verb>
1374 gcc -g -Wall -ansi -o table table.c -L/usr/X11R6/lib \
1375     -lgdk -lgtk -lglib -lX11 -lXext -lm
1376 </verb></tscreen>
1377
1378 <!-- ***************************************************************** -->
1379 <sect>Widget Overview
1380 <!-- ***************************************************************** -->
1381
1382 <p>
1383 The general steps to creating a widget in GTK are:
1384 <enum>
1385 <item> gtk_*_new - one of various functions to create a new widget.  These
1386 are all detailed in this section.
1387
1388 <item> Connect all signals we wish to use to the appropriate handlers.
1389
1390 <item> Set the attributes of the widget.
1391
1392 <item> Pack the widget into a container using the appropriate call such as 
1393 gtk_container_add() or gtk_box_pack_start().
1394
1395 <item> gtk_widget_show() the widget.
1396 </enum>
1397 <p>
1398 gtk_widget_show() lets GTK know that we are done setting the attributes
1399 of the widget, and it is ready to be displayed.  You may also use
1400 gtk_widget_hide to make it disappear again.  The order in which you
1401 show the widgets is not important, but I suggest showing the window
1402 last so the whole window pops up at once rather than seeing the individual
1403 widgets come up on the screen as they're formed.  The children of a widget
1404 (a window is a widget too)
1405 will not be displayed until the window itself is shown using the
1406 gtk_widget_show() function.
1407
1408 <!-- ----------------------------------------------------------------- -->
1409 <sect1> Casting
1410 <p>
1411 You'll notice as you go on, that GTK uses a type casting system.  This is
1412 always done using macros that both test the ability to cast the given item,
1413 and perform the cast.  Some common ones you will see are:
1414
1415 <itemize>
1416 <item> GTK_WIDGET(widget)
1417 <item> GTK_OBJECT(object)
1418 <item> GTK_SIGNAL_FUNC(function)
1419 <item> GTK_CONTAINER(container)
1420 <item> GTK_WINDOW(window)
1421 <item> GTK_BOX(box)
1422 </itemize>
1423
1424 These are all used to cast arguments in functions.  You'll see them in the
1425 examples, and can usually tell when to use them simply by looking at the
1426 function's declaration.
1427
1428 As you can see below in the class hierarchy, all GtkWidgets are derived from
1429 the GtkObject base class.  This means you can use an widget in any place the 
1430 function asks for an object - simply use the GTK_OBJECT() macro.
1431
1432 For example:
1433
1434 <tscreen><verb>
1435 gtk_signal_connect(GTK_OBJECT(button), "clicked",
1436                    GTK_SIGNAL_FUNC(callback_function), callback_data);
1437 </verb></tscreen> 
1438
1439 This casts the button into an object, and provides a cast for the function
1440 pointer to the callback.
1441
1442 Many widgets are also containers.  If you look in the class hierarchy below,
1443 you'll notice that many widgets drive from the GtkContainer class.  Any one
1444 of those widgets may use with the GTK_CONTAINER macro to
1445 pass them to functions that ask for containers.
1446
1447 Unfortunately, these macros are not extensively covered in the tutorial, but I
1448 recomend taking a look through the GTK header files.  It can be very
1449 educational.  In fact, it's not difficult to learn how a widget works just
1450 by looking at the function declarations.
1451
1452 <!-- ----------------------------------------------------------------- -->
1453 <sect1>Widget Hierarchy
1454 <p>
1455 For your reference, here is the class hierarchy tree used to implement widgets.
1456
1457 <tscreen><verb>
1458   GtkObject
1459    +GtkData
1460    | +GtkAdjustment
1461    | `GtkTooltips
1462    `GtkWidget
1463      +GtkContainer
1464      | +GtkBin
1465      | | +GtkAlignment
1466      | | +GtkEventBox
1467      | | +GtkFrame
1468      | | | `GtkAspectFrame
1469      | | +GtkHandleBox
1470      | | +GtkItem
1471      | | | +GtkListItem
1472      | | | +GtkMenuItem
1473      | | | | `GtkCheckMenuItem
1474      | | | |   `GtkRadioMenuItem
1475      | | | `GtkTreeItem
1476      | | +GtkViewport
1477      | | `GtkWindow
1478      | |   +GtkColorSelectionDialog
1479      | |   +GtkDialog
1480      | |   | `GtkInputDialog
1481      | |   `GtkFileSelection
1482      | +GtkBox
1483      | | +GtkButtonBox
1484      | | | +GtkHButtonBox
1485      | | | `GtkVButtonBox
1486      | | +GtkHBox
1487      | | | +GtkCombo
1488      | | | `GtkStatusbar
1489      | | `GtkVBox
1490      | |   +GtkColorSelection
1491      | |   `GtkGammaCurve
1492      | +GtkButton
1493      | | +GtkOptionMenu
1494      | | `GtkToggleButton
1495      | |   `GtkCheckButton
1496      | |     `GtkRadioButton
1497      | +GtkCList
1498      | +GtkFixed
1499      | +GtkList
1500      | +GtkMenuShell
1501      | | +GtkMenuBar
1502      | | `GtkMenu
1503      | +GtkNotebook
1504      | +GtkPaned
1505      | | +GtkHPaned
1506      | | `GtkVPaned
1507      | +GtkScrolledWindow
1508      | +GtkTable
1509      | +GtkToolbar
1510      | `GtkTree
1511      +GtkDrawingArea
1512      | `GtkCurve
1513      +GtkEditable
1514      | +GtkEntry
1515      | | `GtkSpinButton
1516      | `GtkText
1517      +GtkMisc
1518      | +GtkArrow
1519      | +GtkImage
1520      | +GtkLabel
1521      | | `GtkTipsQuery
1522      | `GtkPixmap
1523      +GtkPreview
1524      +GtkProgressBar
1525      +GtkRange
1526      | +GtkScale
1527      | | +GtkHScale
1528      | | `GtkVScale
1529      | `GtkScrollbar
1530      |   +GtkHScrollbar
1531      |   `GtkVScrollbar
1532      +GtkRuler
1533      | +GtkHRuler
1534      | `GtkVRuler
1535      `GtkSeparator
1536        +GtkHSeparator
1537        `GtkVSeparator
1538 </verb></tscreen>
1539
1540 <!-- ----------------------------------------------------------------- -->
1541 <sect1>Widgets Without Windows
1542 <p>
1543 The following widgets do not have an associated window.  If you want to
1544 capture events, you'll have to use the GtkEventBox.  See the section on   
1545 <ref id="sec_The_EventBox_Widget" name="The EventBox Widget">
1546
1547 <tscreen><verb>
1548 GtkAlignment
1549 GtkArrow
1550 GtkBin
1551 GtkBox
1552 GtkImage
1553 GtkItem
1554 GtkLabel
1555 GtkPaned
1556 GtkPixmap
1557 GtkScrolledWindow
1558 GtkSeparator
1559 GtkTable
1560 GtkViewport
1561 GtkAspectFrame
1562 GtkFrame
1563 GtkVPaned
1564 GtkHPaned
1565 GtkVBox
1566 GtkHBox
1567 GtkVSeparator
1568 GtkHSeparator
1569 </verb></tscreen>
1570 <p>
1571 We'll further our exploration of GTK by examining each widget in turn,
1572 creating a few simple functions to display them.  Another good source is
1573 the testgtk.c program that comes with GTK.  It can be found in
1574 gtk/testgtk.c.
1575
1576 <!-- ***************************************************************** -->
1577 <sect>The Button Widget
1578 <!-- ***************************************************************** -->
1579
1580 <!-- ----------------------------------------------------------------- -->
1581 <sect1>Normal Buttons
1582 <p>
1583 We've almost seen all there is to see of the button widget.  It's pretty
1584 simple.  There is however two ways to create a button.  You can use the
1585 gtk_button_new_with_label() to create a button with a label, or use
1586 gtk_button_new() to create a blank button.  It's then up to you to pack a
1587 label or pixmap into this new button.  To do this, create a new box, and
1588 then pack your objects into this box using the usual gtk_box_pack_start,
1589 and then use gtk_container_add to pack the box into the button.
1590 <p>
1591 Here's an example of using gtk_button_new to create a button with a
1592 picture and a label in it.  I've broken the code to create a box up from
1593 the rest so you can use it in your programs.
1594
1595 <tscreen><verb>
1596 /* buttons.c */
1597
1598 #include <gtk/gtk.h>
1599
1600 /* create a new hbox with an image and a label packed into it
1601  * and return the box.. */
1602
1603 GtkWidget *xpm_label_box (GtkWidget *parent, gchar *xpm_filename, gchar *label_text)
1604 {
1605     GtkWidget *box1;
1606     GtkWidget *label;
1607     GtkWidget *pixmapwid;
1608     GdkPixmap *pixmap;
1609     GdkBitmap *mask;
1610     GtkStyle *style;
1611
1612     /* create box for xpm and label */
1613     box1 = gtk_hbox_new (FALSE, 0);
1614     gtk_container_border_width (GTK_CONTAINER (box1), 2);
1615
1616     /* get style of button.. I assume it's to get the background color.
1617      * if someone knows the real reason, please enlighten me. */
1618     style = gtk_widget_get_style(parent);
1619
1620     /* now on to the xpm stuff.. load xpm */
1621     pixmap = gdk_pixmap_create_from_xpm (parent->window, &amp;mask,
1622                                          &amp;style->bg[GTK_STATE_NORMAL],
1623                                          xpm_filename);
1624     pixmapwid = gtk_pixmap_new (pixmap, mask);
1625
1626     /* create label for button */
1627     label = gtk_label_new (label_text);
1628
1629     /* pack the pixmap and label into the box */
1630     gtk_box_pack_start (GTK_BOX (box1),
1631                         pixmapwid, FALSE, FALSE, 3);
1632
1633     gtk_box_pack_start (GTK_BOX (box1), label, FALSE, FALSE, 3);
1634
1635     gtk_widget_show(pixmapwid);
1636     gtk_widget_show(label);
1637
1638     return (box1);
1639 }
1640
1641 /* our usual callback function */
1642 void callback (GtkWidget *widget, gpointer *data)
1643 {
1644     g_print ("Hello again - %s was pressed\n", (char *) data);
1645 }
1646
1647
1648 int main (int argc, char *argv[])
1649 {
1650     /* GtkWidget is the storage type for widgets */
1651     GtkWidget *window;
1652     GtkWidget *button;
1653     GtkWidget *box1;
1654
1655     gtk_init (&amp;argc, &amp;argv);
1656
1657     /* create a new window */
1658     window = gtk_window_new (GTK_WINDOW_TOPLEVEL);
1659
1660     gtk_window_set_title (GTK_WINDOW (window), "Pixmap'd Buttons!");
1661
1662     /* It's a good idea to do this for all windows. */
1663     gtk_signal_connect (GTK_OBJECT (window), "destroy",
1664                         GTK_SIGNAL_FUNC (gtk_exit), NULL);
1665
1666     gtk_signal_connect (GTK_OBJECT (window), "delete_event",
1667                         GTK_SIGNAL_FUNC (gtk_exit), NULL);
1668
1669
1670     /* sets the border width of the window. */
1671     gtk_container_border_width (GTK_CONTAINER (window), 10);
1672     gtk_widget_realize(window);
1673
1674     /* create a new button */
1675     button = gtk_button_new ();
1676
1677     /* You should be getting used to seeing most of these functions by now */
1678     gtk_signal_connect (GTK_OBJECT (button), "clicked",
1679                         GTK_SIGNAL_FUNC (callback), (gpointer) "cool button");
1680
1681     /* this calls our box creating function */
1682     box1 = xpm_label_box(window, "info.xpm", "cool button");
1683
1684     /* pack and show all our widgets */
1685     gtk_widget_show(box1);
1686
1687     gtk_container_add (GTK_CONTAINER (button), box1);
1688
1689     gtk_widget_show(button);
1690
1691     gtk_container_add (GTK_CONTAINER (window), button);
1692
1693     gtk_widget_show (window);
1694
1695     /* rest in gtk_main and wait for the fun to begin! */
1696     gtk_main ();
1697
1698     return 0;
1699 }
1700 </verb></tscreen>
1701
1702 The xpm_label_box function could be used to pack xpm's and labels into any
1703 widget that can be a container.
1704
1705 <!-- ----------------------------------------------------------------- -->
1706 <sect1> Toggle Buttons
1707 <p>
1708 Toggle buttons are very similar to normal buttons, except they will always
1709 be in one of two states, alternated by a click.  They may be depressed, and
1710 when you click again, they will pop back up.  Click again, and they will pop
1711 back down. 
1712
1713 Toggle buttons are the basis for check buttons and radio buttons, as such,
1714 many of the calls used for toggle buttons are inherited by radio and check
1715 buttons.  I will point these out when we come to them.
1716
1717 Creating a new toggle button:
1718
1719 <tscreen><verb>
1720 GtkWidget* gtk_toggle_button_new (void);
1721
1722 GtkWidget* gtk_toggle_button_new_with_label (gchar *label);
1723 </verb></tscreen>
1724 <p>
1725 As you can imagine, these work identically to the normal button widget
1726 calls.  The first creates a blank toggle button, and the second, a button 
1727 with a label widget already packed into it.
1728 <p>
1729 To retrieve the state of the toggle widget, including radio and check
1730 buttons, we use a macro as shown in our example below.  This tests the state
1731 of the toggle in a callback.  The signal of interest emitted to us by toggle
1732 buttons (the toggle button, check button, and radio button widgets), is the
1733 "toggled" signal.  To check the state of these buttons, set up a signal
1734 handler to catch the toggled signal, and use the macro to determine it's
1735 state.  The callback will look something like:
1736
1737 <tscreen><verb>
1738 void toggle_button_callback (GtkWidget *widget, gpointer   data)
1739 {
1740     if (GTK_TOGGLE_BUTTON (widget)->active) 
1741     {
1742         /* If control reaches here, the toggle button is down */
1743     
1744     } else {
1745     
1746         /* If control reaches here, the toggle button is up */
1747     }
1748 }
1749 </verb></tscreen>
1750
1751 <!--
1752
1753 COMMENTED!
1754
1755 <tscreen><verb>
1756 guint gtk_toggle_button_get_type (void);
1757 </verb></tscreen>
1758 <p>
1759 No idea... they all have this, but I dunno what it is :)
1760
1761
1762 <tscreen><verb>
1763 void gtk_toggle_button_set_mode (GtkToggleButton *toggle_button,
1764                                  gint draw_indicator);
1765 </verb></tscreen>
1766 <p>
1767 No idea.
1768 -->
1769
1770 <tscreen><verb>
1771 void gtk_toggle_button_set_state (GtkToggleButton *toggle_button,
1772                                   gint state);
1773 </verb></tscreen>
1774 <p>
1775 The above call can be used to set the state of the toggle button, and it's
1776 children the radio and check buttons.  Passing
1777 in your created button as the first argument, and a TRUE or FALSE
1778 for the second state argument to specify whether it should be up (released) or
1779 down (depressed).  Default is up, or FALSE.
1780
1781 Note that when you use the gtk_toggle_button_set_state() function, and the
1782 state is actually changed, it causes
1783 the "clicked" signal to be emitted from the button.
1784
1785 <tscreen><verb>
1786 void       gtk_toggle_button_toggled        (GtkToggleButton *toggle_button);
1787 </verb></tscreen>
1788 <p>
1789 This simply toggles the button, and emits the "toggled" signal.
1790
1791 <!-- ----------------------------------------------------------------- -->
1792 <sect1> Check Buttons
1793 <p>
1794 Check buttons inherent many properties and functions from the the toggle buttons above, 
1795 but look a little
1796 different.  Rather than being buttons with text inside them, they are small
1797 squares with the text to the right of them.  These are often seen for
1798 toggling options on and off in applications.
1799
1800 The two creation functions are the same as for the normal button.
1801
1802 <tscreen><verb>
1803 GtkWidget* gtk_check_button_new (void);
1804
1805 GtkWidget* gtk_check_button_new_with_label (gchar *label);
1806 </verb></tscreen>
1807
1808 The new_with_label function creates a check button with a label beside it.
1809
1810 Checking the state of the check button is identical to that of the toggle
1811 button.
1812
1813 <!-- ----------------------------------------------------------------- -->
1814 <sect1> Radio Buttons
1815 <p>
1816 Radio buttons are similar to check buttons except they are grouped so that
1817 only one may be selected/depressed at a time.  This is good for places in
1818 your application where you need to select from a short list of options.
1819
1820 Creating a new radio button is done with one of these calls:
1821
1822 <tscreen><verb>
1823 GtkWidget* gtk_radio_button_new (GSList *group);
1824
1825 GtkWidget* gtk_radio_button_new_with_label (GSList *group,
1826                                             gchar *label);
1827 </verb></tscreen>
1828 <p>
1829 You'll notice the extra argument to these calls.  They require a group to
1830 perform they're duty properly.  The first call should pass NULL as the first
1831 argument.  Then create a group using:
1832
1833 <tscreen><verb>
1834 GSList* gtk_radio_button_group (GtkRadioButton *radio_button);
1835 </verb></tscreen>
1836
1837 <p>
1838 The important thing to remember is that gtk_radio_button_group must be
1839 called for each new button added to the group, with the previous button
1840 passed in as an argument. The result is then passed into the call to
1841 gtk_radio_button_new or gtk_radio_button_new_with_label. This allows a
1842 chain of buttons to be established. The example below should make this
1843 clear.
1844
1845 It is also a good idea to explicitly set which button should be the 
1846 default depressed button with:
1847
1848 <tscreen><verb>
1849 void gtk_toggle_button_set_state (GtkToggleButton *toggle_button,
1850                                   gint state);
1851 </verb></tscreen>
1852 <p>
1853 This is described in the section on toggle buttons, and works in exactly the
1854 same way.
1855 <p>
1856 The following example creates a radio button group with three buttons.
1857
1858 <tscreen><verb>
1859 /* radiobuttons.c */
1860
1861 #include <gtk/gtk.h>
1862 #include <glib.h>
1863
1864 void close_application( GtkWidget *widget, gpointer *data ) {
1865   gtk_main_quit();
1866 }
1867
1868 main(int argc,char *argv[])
1869 {
1870   static GtkWidget *window = NULL;
1871   GtkWidget *box1;
1872   GtkWidget *box2;
1873   GtkWidget *button;
1874   GtkWidget *separator;
1875   GSList *group;
1876   
1877   gtk_init(&amp;argc,&amp;argv);          
1878   window = gtk_window_new (GTK_WINDOW_TOPLEVEL);
1879   
1880   gtk_signal_connect (GTK_OBJECT (window), "delete_event",
1881                       GTK_SIGNAL_FUNC(close_application),
1882                       NULL);
1883
1884   gtk_window_set_title (GTK_WINDOW (window), "radio buttons");
1885   gtk_container_border_width (GTK_CONTAINER (window), 0);
1886
1887   box1 = gtk_vbox_new (FALSE, 0);
1888   gtk_container_add (GTK_CONTAINER (window), box1);
1889   gtk_widget_show (box1);
1890
1891   box2 = gtk_vbox_new (FALSE, 10);
1892   gtk_container_border_width (GTK_CONTAINER (box2), 10);
1893   gtk_box_pack_start (GTK_BOX (box1), box2, TRUE, TRUE, 0);
1894   gtk_widget_show (box2);
1895
1896   button = gtk_radio_button_new_with_label (NULL, "button1");
1897   gtk_box_pack_start (GTK_BOX (box2), button, TRUE, TRUE, 0);
1898   gtk_widget_show (button);
1899
1900   group = gtk_radio_button_group (GTK_RADIO_BUTTON (button));
1901   button = gtk_radio_button_new_with_label(group, "button2");
1902   gtk_toggle_button_set_state (GTK_TOGGLE_BUTTON (button), TRUE);
1903   gtk_box_pack_start (GTK_BOX (box2), button, TRUE, TRUE, 0);
1904   gtk_widget_show (button);
1905
1906   group = gtk_radio_button_group (GTK_RADIO_BUTTON (button));
1907   button = gtk_radio_button_new_with_label(group, "button3");
1908   gtk_box_pack_start (GTK_BOX (box2), button, TRUE, TRUE, 0);
1909   gtk_widget_show (button);
1910
1911   separator = gtk_hseparator_new ();
1912   gtk_box_pack_start (GTK_BOX (box1), separator, FALSE, TRUE, 0);
1913   gtk_widget_show (separator);
1914
1915   box2 = gtk_vbox_new (FALSE, 10);
1916   gtk_container_border_width (GTK_CONTAINER (box2), 10);
1917   gtk_box_pack_start (GTK_BOX (box1), box2, FALSE, TRUE, 0);
1918   gtk_widget_show (box2);
1919
1920   button = gtk_button_new_with_label ("close");
1921   gtk_signal_connect_object (GTK_OBJECT (button), "clicked",
1922                              GTK_SIGNAL_FUNC(close_application),
1923                              GTK_OBJECT (window));
1924   gtk_box_pack_start (GTK_BOX (box2), button, TRUE, TRUE, 0);
1925   GTK_WIDGET_SET_FLAGS (button, GTK_CAN_DEFAULT);
1926   gtk_widget_grab_default (button);
1927   gtk_widget_show (button);
1928   gtk_widget_show (window);
1929      
1930   gtk_main();
1931   return(0);
1932 }
1933 </verb></tscreen>
1934
1935 You can shorten this slightly by using the following syntax, which
1936 removes the need for a variable to hold the list of buttons:
1937
1938 <tscreen><verb>
1939      button2 = gtk_radio_button_new_with_label(
1940                  gtk_radio_button_group (GTK_RADIO_BUTTON (button1)),
1941                  "button2");
1942 </verb></tscreen>
1943
1944 <!-- ***************************************************************** -->
1945 <sect> Miscallaneous Widgets
1946 <!-- ***************************************************************** -->
1947
1948 <!-- ----------------------------------------------------------------- -->
1949 <sect1> Labels
1950 <p>
1951 Labels are used a lot in GTK, and are relatively simple.  Labels emit no
1952 signals as they do not have an associated X window.  If you need to catch
1953 signals, or do clipping, use the EventBox widget.
1954
1955 To create a new label, use:
1956
1957 <tscreen><verb>
1958 GtkWidget* gtk_label_new (char *str);
1959 </verb></tscreen>
1960
1961 Where the sole argument is the string you wish the label to display.
1962
1963 To change the label's text after creation, use the function:
1964
1965 <tscreen><verb>
1966 void gtk_label_set (GtkLabel  *label,
1967                     char      *str);
1968 </verb></tscreen>
1969 <p>
1970 Where the first argument is the label you created previously (casted using
1971 the GTK_LABEL() macro), and the second is the new string.
1972
1973 The space needed for the new string will be automatically adjusted if needed.
1974
1975 To retrieve the current string, use:
1976
1977 <tscreen><verb>
1978 void gtk_label_get (GtkLabel  *label,
1979                     char     **str);
1980 </verb></tscreen>
1981
1982 Where the first arguement is the label you've created, and the second, the
1983 return for the string.
1984
1985 <!-- ----------------------------------------------------------------- -->
1986 <sect1>The Tooltips Widget
1987 <p>
1988 These are the little text strings that pop up when you leave your pointer
1989 over a button or other widget for a few seconds.  They are easy to use, so I
1990 will just explain them without giving an example.  If you want to see some
1991 code, take a look at the testgtk.c program distributed with GDK.
1992 <p>
1993 Some widgets (such as the label) will not work with tooltips.
1994 <p>
1995 The first call you will use to create a new tooltip.  You only need to do
1996 this once in a given function.  The GtkTooltip this function returns can be
1997 used to create multiple tooltips.
1998
1999 <tscreen><verb>
2000 GtkTooltips *gtk_tooltips_new (void);
2001 </verb></tscreen>
2002
2003 Once you have created a new tooltip, and the widget you wish to use it on,
2004 simply use this call to set it.
2005
2006 <tscreen><verb>
2007 void gtk_tooltips_set_tips   (GtkTooltips *tooltips,
2008                               GtkWidget   *widget,
2009                               gchar       *tips_text);
2010 </verb></tscreen>
2011
2012 The first argument is the tooltip you've already created, followed by the
2013 widget you wish to have this tooltip pop up for, and the text you wish it to
2014 say.
2015 <p>
2016 Here's a short example:
2017
2018 <tscreen><verb>
2019 GtkTooltips *tooltips;
2020 GtkWidget *button;
2021 ...
2022 tooltips = gtk_tooltips_new ();
2023 button = gtk_button_new_with_label ("button 1");
2024 ...
2025 gtk_tooltips_set_tips (tooltips, button, "This is button 1");
2026 </verb></tscreen>
2027
2028
2029 There are other calls used with tooltips.  I will just list them with a
2030 brief description of what they do.
2031
2032 <tscreen><verb>
2033 void gtk_tooltips_destroy    (GtkTooltips *tooltips);
2034 </verb></tscreen>
2035
2036 Destroy the created tooltips.
2037
2038 <tscreen><verb>
2039 void gtk_tooltips_enable     (GtkTooltips *tooltips);
2040 </verb></tscreen>
2041
2042 Enable a disabled set of tooltips.
2043
2044 <tscreen><verb>
2045 void gtk_tooltips_disable    (GtkTooltips *tooltips);
2046 </verb></tscreen>
2047
2048 Disable an enabled set of tooltips.
2049
2050 <tscreen><verb>
2051 void gtk_tooltips_set_delay  (GtkTooltips *tooltips,
2052                               gint         delay);
2053
2054 </verb></tscreen>
2055 Sets how many milliseconds you have to hold you pointer over the widget before the
2056 tooltip will pop up.  The default is 1000 milliseconds or 1 second.
2057
2058 <tscreen><verb>
2059 void      gtk_tooltips_set_tips (GtkTooltips *tooltips,
2060                                  GtkWidget   *widget,
2061                                  gchar    *tips_text);
2062 </verb></tscreen>
2063
2064 Change the tooltip text of an already created tooltip.
2065
2066 <tscreen><verb>
2067 void gtk_tooltips_set_colors (GtkTooltips *tooltips,
2068                               GdkColor    *background,
2069                               GdkColor    *foreground);
2070 </verb></tscreen>
2071
2072 Set the foreground and background color of the tooltips.  Again, I have no
2073 idea how to specify the colors.
2074 <p>
2075 And that's all the functions associated with tooltips.  More than you'll
2076 ever want to know :)
2077
2078 <!-- ----------------------------------------------------------------- -->
2079 <sect1> Progress Bars
2080 <p>
2081 Progress bars are used to show the status of an operation.  They are pretty 
2082 easy to use, as you will see with the code below. But first lets start out 
2083 with the call to create a new progress bar.
2084
2085 <tscreen><verb>
2086 GtkWidget *gtk_progress_bar_new (void);
2087 </verb></tscreen>
2088
2089 Now that the progress bar has been created we can use it.
2090
2091 <tscreen><verb>
2092 void gtk_progress_bar_update (GtkProgressBar *pbar, gfloat percentage);
2093 </verb></tscreen>
2094
2095 The first argument is the progress bar you wish to operate on, and the second 
2096 argument is the amount 'completed', meaning the amount the progress bar has 
2097 been filled from 0-100% (a real number between 0 and 1).
2098
2099 Progress Bars are usually used with timeouts or other such functions (see
2100 section on <ref id="sec_timeouts" name="Timeouts, I/O and Idle Functions">) 
2101 to give the illusion of multitasking.  All will employ 
2102 the gtk_progress_bar_update function in the same manner.
2103
2104 Here is an example of the progress bar, updated using timeouts.  This 
2105 code also shows you how to reset the Progress Bar.
2106
2107 <tscreen><verb>
2108 /* progressbar.c */
2109
2110 #include <gtk/gtk.h>
2111
2112 static int ptimer = 0;
2113 int pstat = TRUE;
2114
2115 /* This function increments and updates the progress bar, it also resets
2116  the progress bar if pstat is FALSE */
2117 gint progress (gpointer data)
2118 {
2119     gfloat pvalue;
2120     
2121     /* get the current value of the progress bar */
2122     pvalue = GTK_PROGRESS_BAR (data)->percentage;
2123     
2124     if ((pvalue >= 1.0) || (pstat == FALSE)) {
2125         pvalue = 0.0;
2126         pstat = TRUE;
2127     }
2128     pvalue += 0.01;
2129     
2130     gtk_progress_bar_update (GTK_PROGRESS_BAR (data), pvalue);
2131     
2132     return TRUE;
2133 }
2134
2135 /* This function signals a reset of the progress bar */
2136 void progress_r (void)
2137 {  
2138     pstat = FALSE;  
2139 }
2140
2141 void destroy (GtkWidget *widget, gpointer *data)
2142 {
2143     gtk_main_quit ();
2144 }
2145
2146 int main (int argc, char *argv[])
2147 {
2148     GtkWidget *window;
2149     GtkWidget *button;
2150     GtkWidget *label;
2151     GtkWidget *table;
2152     GtkWidget *pbar;
2153     
2154     gtk_init (&amp;argc, &amp;argv);
2155     
2156     window = gtk_window_new (GTK_WINDOW_TOPLEVEL);
2157     
2158     gtk_signal_connect (GTK_OBJECT (window), "delete_event",
2159                         GTK_SIGNAL_FUNC (destroy), NULL);
2160     
2161     gtk_container_border_width (GTK_CONTAINER (window), 10);
2162     
2163     table = gtk_table_new(3,2,TRUE);
2164     gtk_container_add (GTK_CONTAINER (window), table);
2165     
2166     label = gtk_label_new ("Progress Bar Example");
2167     gtk_table_attach_defaults(GTK_TABLE(table), label, 0,2,0,1);
2168     gtk_widget_show(label);
2169     
2170     /* Create a new progress bar, pack it into the table, and show it */
2171     pbar = gtk_progress_bar_new ();
2172     gtk_table_attach_defaults(GTK_TABLE(table), pbar, 0,2,1,2);
2173     gtk_widget_show (pbar);
2174     
2175     /* Set the timeout to handle automatic updating of the progress bar */
2176     ptimer = gtk_timeout_add (100, progress, pbar);
2177     
2178     /* This button signals the progress bar to be reset */
2179     button = gtk_button_new_with_label ("Reset");
2180     gtk_signal_connect (GTK_OBJECT (button), "clicked",
2181                         GTK_SIGNAL_FUNC (progress_r), NULL);
2182     gtk_table_attach_defaults(GTK_TABLE(table), button, 0,1,2,3);
2183     gtk_widget_show(button);
2184     
2185     button = gtk_button_new_with_label ("Cancel");
2186     gtk_signal_connect (GTK_OBJECT (button), "clicked",
2187                         GTK_SIGNAL_FUNC (destroy), NULL);
2188     
2189     gtk_table_attach_defaults(GTK_TABLE(table), button, 1,2,2,3);
2190     gtk_widget_show (button);
2191     
2192     gtk_widget_show(table);
2193     gtk_widget_show(window);
2194     
2195     gtk_main ();
2196     
2197     return 0;
2198 }
2199 </verb></tscreen>
2200
2201 In this small program there are four areas that concern the general operation
2202 of Progress Bars, we will look at them in the order they are called.
2203
2204 <tscreen><verb>
2205 pbar = gtk_progress_bar_new ();
2206 </verb></tscreen>
2207
2208 This code creates a new progress bar, called pbar.
2209
2210 <tscreen><verb>
2211 ptimer = gtk_timeout_add (100, progress, pbar);
2212 </verb></tscreen>
2213
2214 This code, uses timeouts to enable a constant time interval, timeouts are 
2215 not necessary in the use of Progress Bars. 
2216
2217 <tscreen><verb>
2218 pvalue = GTK_PROGRESS_BAR (data)->percentage;
2219 </verb></tscreen>
2220
2221 This code assigns the current value of the percentage bar to pvalue.
2222
2223 <tscreen><verb>
2224 gtk_progress_bar_update (GTK_PROGRESS_BAR (data), pvalue);
2225 </verb></tscreen>
2226
2227 Finally, this code updates the progress bar with the value of pvalue
2228
2229 And that is all there is to know about Progress Bars, enjoy.
2230
2231 <!-- ----------------------------------------------------------------- -->
2232 <sect1> Dialogs
2233 <p>
2234
2235 The Dialog widget is very simple, and is actually just a window with a few
2236 things pre-packed into it for you.  The structure for a Dialog is:
2237
2238 <tscreen><verb>
2239 struct GtkDialog
2240 {
2241       GtkWindow window;
2242     
2243       GtkWidget *vbox;
2244       GtkWidget *action_area;
2245 };
2246 </verb></tscreen>
2247
2248 So you see, it simple creates a window, and then packs a vbox into the top,
2249 then a seperator, and then an hbox for the "action_area".
2250
2251 The Dialog widget can be used for pop-up messages to the user, and 
2252 other similar tasks.  It is really basic, and there is only one 
2253 function for the dialog box, which is:
2254
2255 <tscreen><verb>
2256 GtkWidget* gtk_dialog_new (void);
2257 </verb></tscreen>
2258
2259 So to create a new dialog box, use,
2260
2261 <tscreen><verb>
2262 GtkWidget window;
2263 window = gtk_dialog_new ();
2264 </verb></tscreen>
2265
2266 This will create the dialog box, and it is now up to you to use it.
2267 you could pack a button in the action_area by doing something like so:
2268
2269 <tscreen><verb>
2270 button = ...
2271 gtk_box_pack_start (GTK_BOX (GTK_DIALOG (window)->action_area), button,
2272                     TRUE, TRUE, 0);
2273 gtk_widget_show (button);
2274 </verb></tscreen>
2275
2276 And you could add to the vbox area by packing, for instance, a label 
2277 in it, try something like this:
2278
2279 <tscreen><verb>
2280 label = gtk_label_new ("Dialogs are groovy");
2281 gtk_box_pack_start (GTK_BOX (GTK_DIALOG (window)->vbox), label, TRUE,
2282                     TRUE, 0);
2283 gtk_widget_show (label);
2284 </verb></tscreen>
2285
2286 As an example in using the dialog box, you could put two buttons in 
2287 the action_area, a Cancel button and an Ok button, and a label in the vbox 
2288 area, asking the user a question or giving an error etc.  Then you could 
2289 attach a different signal to each of the buttons and perform the 
2290 operation the user selects.
2291
2292 <!-- ----------------------------------------------------------------- -->
2293 <sect1> Pixmaps
2294 <p>
2295 Pixmaps are data structures that contain pictures.  These pictures can be
2296 used in various places, but most visibly as icons on the X-Windows desktop,
2297 or as cursors.  A bitmap is a 2-color pixmap.
2298
2299 To use pixmaps in GTK, we must first build a GdkPixmap structure using
2300 routines from the GDK layer.  Pixmaps can either be created from in-memory
2301 data, or from data read from a file.  We'll go through each of the calls
2302 to create a pixmap.
2303
2304 <tscreen><verb>
2305 GdkPixmap *gdk_bitmap_create_from_data( GdkWindow *window,
2306                                         gchar     *data,
2307                                         gint      width,
2308                                         gint      height );
2309 </verb></tscreen>
2310 <p>
2311 This routine is used to create a single-plane pixmap (2 colors) from data in
2312 memory.  Each bit of the data represents whether that pixel is off or on.
2313 Width and height are in pixels.  The GdkWindow pointer is to the current
2314 window, since a pixmap resources are meaningful only in the context of the
2315 screen where it is to be displayed.
2316
2317 <tscreen><verb>
2318 GdkPixmap* gdk_pixmap_create_from_data( GdkWindow  *window,
2319                                         gchar      *data,
2320                                         gint        width,
2321                                         gint        height,
2322                                         gint        depth,
2323                                         GdkColor   *fg,
2324                                         GdkColor   *bg );
2325 </verb></tscreen>
2326
2327 This is used to create a pixmap of the given depth (number of colors) from
2328 the bitmap data specified.  fg and bg are the foreground and background
2329 color to use.
2330
2331 <tscreen><verb>
2332 GdkPixmap* gdk_pixmap_create_from_xpm( GdkWindow  *window,
2333                                        GdkBitmap **mask,
2334                                        GdkColor   *transparent_color,
2335                                        const gchar *filename );
2336 </verb></tscreen>
2337
2338 XPM format is a readable pixmap representation for the X Window System.  It
2339 is widely used and many different utilities are available for creating image
2340 files in this format.  The file specified by filename must contain an image
2341 in that format and it is loaded into the pixmap structure.  The mask specifies
2342 what bits of the pixmap are opaque.  All other bits are colored using the
2343 color specified by transparent_color.  An example using this follows below.  
2344
2345 <tscreen><verb>
2346 GdkPixmap* gdk_pixmap_create_from_xpm_d (GdkWindow  *window,
2347                                          GdkBitmap **mask,
2348                                          GdkColor   *transparent_color,
2349                                          gchar     **data);
2350 </verb></tscreen>
2351
2352 Small images can be incorporated into a program as data in the XPM format.
2353 A pixmap is created using this data, instead of reading it from a file.
2354 An example of such data is
2355
2356 <tscreen><verb>
2357 /* XPM */
2358 static const char * xpm_data[] = {
2359 "16 16 3 1",
2360 "       c None",
2361 ".      c #000000000000",
2362 "X      c #FFFFFFFFFFFF",
2363 "                ",
2364 "   ......       ",
2365 "   .XXX.X.      ",
2366 "   .XXX.XX.     ",
2367 "   .XXX.XXX.    ",
2368 "   .XXX.....    ",
2369 "   .XXXXXXX.    ",
2370 "   .XXXXXXX.    ",
2371 "   .XXXXXXX.    ",
2372 "   .XXXXXXX.    ",
2373 "   .XXXXXXX.    ",
2374 "   .XXXXXXX.    ",
2375 "   .XXXXXXX.    ",
2376 "   .........    ",
2377 "                ",
2378 "                "};
2379 </verb></tscreen>
2380
2381 <tscreen><verb>
2382 void gdk_pixmap_destroy( GdkPixmap  *pixmap );
2383 </verb></tscreen>
2384 <p>
2385 When we're done using a pixmap and not likely to reuse it again soon,
2386 it is a good idea to release the resource using gdk_pixmap_destroy.  Pixmaps
2387 should be considered a precious resource.
2388
2389
2390 Once we've created a pixmap, we can display it as a GTK widget.  We must
2391 create a pixmap widget to contain the GDK pixmap.  This is done using
2392
2393 <tscreen><verb>
2394 GtkWidget* gtk_pixmap_new( GdkPixmap  *pixmap,
2395                            GdkBitmap  *mask );
2396 </verb></tscreen>
2397 <p>
2398 The other pixmap widget calls are
2399
2400 <tscreen><verb>
2401 guint gtk_pixmap_get_type( void );
2402 void  gtk_pixmap_set( GtkPixmap  *pixmap,
2403                       GdkPixmap  *val,
2404                       GdkBitmap  *mask);
2405 void  gtk_pixmap_get( GtkPixmap  *pixmap,
2406                       GdkPixmap **val,
2407                       GdkBitmap **mask);
2408 </verb></tscreen>
2409 <p>
2410 gtk_pixmap_set is used to change the pixmap that the widget is currently
2411 managing.  Val is the pixmap created using GDK.
2412
2413 The following is an example of using a pixmap in a button.
2414
2415 <tscreen><verb>
2416 /* pixmap.c */
2417
2418 #include <gtk/gtk.h>
2419
2420
2421 /* XPM data of Open-File icon */
2422 static const char * xpm_data[] = {
2423 "16 16 3 1",
2424 "       c None",
2425 ".      c #000000000000",
2426 "X      c #FFFFFFFFFFFF",
2427 "                ",
2428 "   ......       ",
2429 "   .XXX.X.      ",
2430 "   .XXX.XX.     ",
2431 "   .XXX.XXX.    ",
2432 "   .XXX.....    ",
2433 "   .XXXXXXX.    ",
2434 "   .XXXXXXX.    ",
2435 "   .XXXXXXX.    ",
2436 "   .XXXXXXX.    ",
2437 "   .XXXXXXX.    ",
2438 "   .XXXXXXX.    ",
2439 "   .XXXXXXX.    ",
2440 "   .........    ",
2441 "                ",
2442 "                "};
2443
2444
2445 /* when invoked (via signal delete_event), terminates the application.
2446  */
2447 void close_application( GtkWidget *widget, gpointer *data ) {
2448     gtk_main_quit();
2449 }
2450
2451
2452 /* is invoked when the button is clicked.  It just prints a message.
2453  */
2454 void button_clicked( GtkWidget *widget, gpointer *data ) {
2455     printf( "button clicked\n" );
2456 }
2457
2458 int main( int argc, char *argv[] )
2459 {
2460     /* GtkWidget is the storage type for widgets */
2461     GtkWidget *window, *pixmapwid, *button;
2462     GdkPixmap *pixmap;
2463     GdkBitmap *mask;
2464     GtkStyle *style;
2465     
2466     /* create the main window, and attach delete_event signal to terminating
2467        the application */
2468     gtk_init( &amp;argc, &amp;argv );
2469     window = gtk_window_new( GTK_WINDOW_TOPLEVEL );
2470     gtk_signal_connect( GTK_OBJECT (window), "delete_event",
2471                         GTK_SIGNAL_FUNC (close_application), NULL );
2472     gtk_container_border_width( GTK_CONTAINER (window), 10 );
2473     gtk_widget_show( window );
2474
2475     /* now for the pixmap from gdk */
2476     style = gtk_widget_get_style( window );
2477     pixmap = gdk_pixmap_create_from_xpm_d( window->window,  &amp;mask,
2478                                            &amp;style->bg[GTK_STATE_NORMAL],
2479                                            (gchar **)xpm_data );
2480
2481     /* a pixmap widget to contain the pixmap */
2482     pixmapwid = gtk_pixmap_new( pixmap, mask );
2483     gtk_widget_show( pixmapwid );
2484
2485     /* a button to contain the pixmap widget */
2486     button = gtk_button_new();
2487     gtk_container_add( GTK_CONTAINER(button), pixmapwid );
2488     gtk_container_add( GTK_CONTAINER(window), button );
2489     gtk_widget_show( button );
2490
2491     gtk_signal_connect( GTK_OBJECT(button), "clicked",
2492                         GTK_SIGNAL_FUNC(button_clicked), NULL );
2493
2494     /* show the window */
2495     gtk_main ();
2496           
2497     return 0;
2498 }
2499 </verb></tscreen>
2500
2501
2502 To load a file from an XPM data file called icon0.xpm in the current
2503 directory, we would have created the pixmap thus
2504
2505 <tscreen><verb>
2506     /* load a pixmap from a file */
2507     pixmap = gdk_pixmap_create_from_xpm( window->window, &amp;mask,
2508                                          &amp;style->bg[GTK_STATE_NORMAL],
2509                                          "./icon0.xpm" );
2510     pixmapwid = gtk_pixmap_new( pixmap, mask );
2511     gtk_widget_show( pixmapwid );
2512     gtk_container_add( GTK_CONTAINER(window), pixmapwid );
2513 </verb></tscreen>
2514
2515
2516
2517 Using Shapes
2518 <p>
2519 A disadvantage of using pixmaps is that the displayed object is always
2520 rectangular, regardless of the image.  We would like to create desktops
2521 and applications with icons that have more natural shapes.  For example,
2522 for a game interface, we would like to have round buttons to push.  The
2523 way to do this is using shaped windows.
2524
2525 A shaped window is simply a pixmap where the background pixels are
2526 transparent.  This way, when the background image is multi-colored, we
2527 don't overwrite it with a rectangular, non-matching border around our
2528 icon.  The following example displays a full wheelbarrow image on the
2529 desktop.
2530
2531 <tscreen><verb>
2532 /* wheelbarrow.c */
2533
2534 #include <gtk/gtk.h>
2535
2536 /* XPM */
2537 static char * WheelbarrowFull_xpm[] = {
2538 "48 48 64 1",
2539 "       c None",
2540 ".      c #DF7DCF3CC71B",
2541 "X      c #965875D669A6",
2542 "o      c #71C671C671C6",
2543 "O      c #A699A289A699",
2544 "+      c #965892489658",
2545 "@      c #8E38410330C2",
2546 "#      c #D75C7DF769A6",
2547 "$      c #F7DECF3CC71B",
2548 "%      c #96588A288E38",
2549 "&amp;      c #A69992489E79",
2550 "*      c #8E3886178E38",
2551 "=      c #104008200820",
2552 "-      c #596510401040",
2553 ";      c #C71B30C230C2",
2554 ":      c #C71B9A699658",
2555 ">      c #618561856185",
2556 ",      c #20811C712081",
2557 "<      c #104000000000",
2558 "1      c #861720812081",
2559 "2      c #DF7D4D344103",
2560 "3      c #79E769A671C6",
2561 "4      c #861782078617",
2562 "5      c #41033CF34103",
2563 "6      c #000000000000",
2564 "7      c #49241C711040",
2565 "8      c #492445144924",
2566 "9      c #082008200820",
2567 "0      c #69A618611861",
2568 "q      c #B6DA71C65144",
2569 "w      c #410330C238E3",
2570 "e      c #CF3CBAEAB6DA",
2571 "r      c #71C6451430C2",
2572 "t      c #EFBEDB6CD75C",
2573 "y      c #28A208200820",
2574 "u      c #186110401040",
2575 "i      c #596528A21861",
2576 "p      c #71C661855965",
2577 "a      c #A69996589658",
2578 "s      c #30C228A230C2",
2579 "d      c #BEFBA289AEBA",
2580 "f      c #596545145144",
2581 "g      c #30C230C230C2",
2582 "h      c #8E3882078617",
2583 "j      c #208118612081",
2584 "k      c #38E30C300820",
2585 "l      c #30C2208128A2",
2586 "z      c #38E328A238E3",
2587 "x      c #514438E34924",
2588 "c      c #618555555965",
2589 "v      c #30C2208130C2",
2590 "b      c #38E328A230C2",
2591 "n      c #28A228A228A2",
2592 "m      c #41032CB228A2",
2593 "M      c #104010401040",
2594 "N      c #492438E34103",
2595 "B      c #28A2208128A2",
2596 "V      c #A699596538E3",
2597 "C      c #30C21C711040",
2598 "Z      c #30C218611040",
2599 "A      c #965865955965",
2600 "S      c #618534D32081",
2601 "D      c #38E31C711040",
2602 "F      c #082000000820",
2603 "                                                ",
2604 "          .XoO                                  ",
2605 "         +@#$%o&amp;                                ",
2606 "         *=-;#::o+                              ",
2607 "           >,<12#:34                            ",
2608 "             45671#:X3                          ",
2609 "               +89<02qwo                        ",
2610 "e*                >,67;ro                       ",
2611 "ty>                 459@>+&amp;&amp;                    ",
2612 "$2u+                  ><ipas8*                  ",
2613 "%$;=*                *3:.Xa.dfg>                ",
2614 "Oh$;ya             *3d.a8j,Xe.d3g8+             ",
2615 " Oh$;ka          *3d$a8lz,,xxc:.e3g54           ",
2616 "  Oh$;kO       *pd$%svbzz,sxxxxfX..&amp;wn>         ",
2617 "   Oh$@mO    *3dthwlsslszjzxxxxxxx3:td8M4       ",
2618 "    Oh$@g&amp; *3d$XNlvvvlllm,mNwxxxxxxxfa.:,B*     ",
2619 "     Oh$@,Od.czlllllzlmmqV@V#V@fxxxxxxxf:%j5&amp;   ",
2620 "      Oh$1hd5lllslllCCZrV#r#:#2AxxxxxxxxxcdwM*  ",
2621 "       OXq6c.%8vvvllZZiqqApA:mq:Xxcpcxxxxxfdc9* ",
2622 "        2r<6gde3bllZZrVi7S@SV77A::qApxxxxxxfdcM ",
2623 "        :,q-6MN.dfmZZrrSS:#riirDSAX@Af5xxxxxfevo",
2624 "         +A26jguXtAZZZC7iDiCCrVVii7Cmmmxxxxxx%3g",
2625 "          *#16jszN..3DZZZZrCVSA2rZrV7Dmmwxxxx&amp;en",
2626 "           p2yFvzssXe:fCZZCiiD7iiZDiDSSZwwxx8e*>",
2627 "           OA1<jzxwwc:$d%NDZZZZCCCZCCZZCmxxfd.B ",
2628 "            3206Bwxxszx%et.eaAp77m77mmmf3&amp;eeeg* ",
2629 "             @26MvzxNzvlbwfpdettttttttttt.c,n&amp;  ",
2630 "             *;16=lsNwwNwgsvslbwwvccc3pcfu<o    ",
2631 "              p;<69BvwwsszslllbBlllllllu<5+     ",
2632 "              OS0y6FBlvvvzvzss,u=Blllj=54       ",
2633 "               c1-699Blvlllllu7k96MMMg4         ",
2634 "               *10y8n6FjvllllB<166668           ",
2635 "                S-kg+>666<M<996-y6n<8*          ",
2636 "                p71=4 m69996kD8Z-66698&amp;&amp;        ",
2637 "                &amp;i0ycm6n4 ogk17,0<6666g         ",
2638 "                 N-k-<>     >=01-kuu666>        ",
2639 "                 ,6ky&amp;      &amp;46-10ul,66,        ",
2640 "                 Ou0<>       o66y<ulw<66&amp;       ",
2641 "                  *kk5       >66By7=xu664       ",
2642 "                   <<M4      466lj<Mxu66o       ",
2643 "                   *>>       +66uv,zN666*       ",
2644 "                              566,xxj669        ",
2645 "                              4666FF666>        ",
2646 "                               >966666M         ",
2647 "                                oM6668+         ",
2648 "                                  *4            ",
2649 "                                                ",
2650 "                                                "};
2651
2652
2653 /* when invoked (via signal delete_event), terminates the application.
2654  */
2655 void close_application( GtkWidget *widget, gpointer *data ) {
2656     gtk_main_quit();
2657 }
2658
2659 int main (int argc, char *argv[])
2660 {
2661     /* GtkWidget is the storage type for widgets */
2662     GtkWidget *window, *pixmap, *fixed;
2663     GdkPixmap *gdk_pixmap;
2664     GdkBitmap *mask;
2665     GtkStyle *style;
2666     GdkGC *gc;
2667     
2668     /* create the main window, and attach delete_event signal to terminate
2669        the application.  Note that the main window will not have a titlebar
2670        since we're making it a popup. */
2671     gtk_init (&amp;argc, &amp;argv);
2672     window = gtk_window_new( GTK_WINDOW_POPUP );
2673     gtk_signal_connect (GTK_OBJECT (window), "delete_event",
2674                         GTK_SIGNAL_FUNC (close_application), NULL);
2675     gtk_widget_show (window);
2676
2677     /* now for the pixmap and the pixmap widget */
2678     style = gtk_widget_get_default_style();
2679     gc = style->black_gc;
2680     gdk_pixmap = gdk_pixmap_create_from_xpm_d( window->window, &amp;mask,
2681                                              &amp;style->bg[GTK_STATE_NORMAL],
2682                                              WheelbarrowFull_xpm );
2683     pixmap = gtk_pixmap_new( gdk_pixmap, mask );
2684     gtk_widget_show( pixmap );
2685
2686     /* To display the pixmap, we use a fixed widget to place the pixmap */
2687     fixed = gtk_fixed_new();
2688     gtk_widget_set_usize( fixed, 200, 200 );
2689     gtk_fixed_put( GTK_FIXED(fixed), pixmap, 0, 0 );
2690     gtk_container_add( GTK_CONTAINER(window), fixed );
2691     gtk_widget_show( fixed );
2692
2693     /* This masks out everything except for the image itself */
2694     gtk_widget_shape_combine_mask( window, mask, 0, 0 );
2695     
2696     /* show the window */
2697     gtk_widget_set_uposition( window, 20, 400 );
2698     gtk_widget_show( window );
2699     gtk_main ();
2700           
2701     return 0;
2702 }
2703 </verb></tscreen>
2704 <p>
2705 To make the wheelbarrow image sensitive, we could attach the button press
2706 event signal to make it do something.  The following few lines would make
2707 the picture sensitive to a mouse button being pressed which makes the
2708 application terminate.
2709
2710 <tscreen><verb>
2711 gtk_widget_set_events( window,
2712                        gtk_widget_get_events( window ) |
2713                        GDK_BUTTON_PRESS_MASK );
2714
2715 gtk_signal_connect( GTK_OBJECT(window), "button_press_event",
2716                     GTK_SIGNAL_FUNC(close_application), NULL );
2717 </verb></tscreen>
2718
2719 <!-- ----------------------------------------------------------------- -->
2720 <sect1>Rulers
2721 <p>
2722 Ruler widgets are used to indicate the location of the mouse pointer
2723 in a given window.  A window can have a vertical ruler spanning across
2724 the width and a horizontal ruler spanning down the height.  A small
2725 triangular indicator on the ruler shows the exact location of the
2726 pointer relative to the ruler.
2727
2728 A ruler must first be created.  Horizontal and vertical rulers are
2729 created using
2730
2731 <tscreen><verb>
2732 GtkWidget *gtk_hruler_new(void);    /* horizontal ruler */
2733 GtkWidget *gtk_vruler_new(void);    /* vertical ruler   */
2734 </verb></tscreen>
2735
2736 Once a ruler is created, we can define the unit of measurement.  Units
2737 of measure for rulers can be GTK_PIXELS, GTK_INCHES or
2738 GTK_CENTIMETERS.  This is set using
2739
2740 <tscreen><verb>
2741 void gtk_ruler_set_metric( GtkRuler        *ruler,
2742                            GtkMetricType   metric );
2743 </verb></tscreen>
2744
2745 The default measure is GTK_PIXELS.
2746
2747 <tscreen><verb>
2748 gtk_ruler_set_metric( GTK_RULER(ruler), GTK_PIXELS );
2749 </verb></tscreen>
2750
2751 Other important characteristics of a ruler are how to mark the units
2752 of scale and where the position indicator is initially placed.  These
2753 are set for a ruler using
2754
2755 <tscreen><verb>
2756 void  gtk_ruler_set_range  (GtkRuler       *ruler,
2757                             gfloat          lower,
2758                             gfloat          upper,
2759                             gfloat          position,
2760                             gfloat          max_size);
2761 </verb></tscreen>
2762
2763 The lower and upper arguments define the extents of the ruler, and
2764 max_size is the largest possible number that will be displayed.
2765 Position defines the initial position of the pointer indicator within
2766 the ruler.
2767
2768 A vertical ruler can span an 800 pixel wide window thus
2769
2770 <tscreen><verb>
2771 gtk_ruler_set_range( GTK_RULER(vruler), 0, 800, 0, 800);
2772 </verb></tscreen>
2773
2774 The markings displayed on the ruler will be from 0 to 800, with
2775 a number for every 100 pixels.  If instead we wanted the ruler to
2776 range from 7 to 16, we would code
2777
2778 <tscreen><verb>
2779 gtk_ruler_set_range( GTK_RULER(vruler), 7, 16, 0, 20);
2780 </verb></tscreen>
2781
2782 The indicator on the ruler is a small triangular mark that indicates
2783 the position of the pointer relative to the ruler.  If the ruler is
2784 used to follow the mouse pointer, the motion_notify_event signal
2785 should be connected to the motion_notify_event method of the ruler.
2786 To follow all mouse movements within a window area, we would use
2787
2788 <tscreen><verb>
2789 #define EVENT_METHOD(i, x) GTK_WIDGET_CLASS(GTK_OBJECT(i)->klass)->x
2790
2791 gtk_signal_connect_object( GTK_OBJECT(area), "motion_notify_event",
2792          (GtkSignalFunc)EVENT_METHOD(ruler, motion_notify_event),
2793          GTK_OBJECT(ruler) );
2794 </verb></tscreen>
2795
2796 The following example creates a drawing area with a horizontal ruler
2797 above it and a vertical ruler to the left of it.  The size of the
2798 drawing area is 600 pixels wide by 400 pixels high.  The horizontal
2799 ruler spans from 7 to 13 with a mark every 100 pixels, while the
2800 vertical ruler spans from 0 to 400 with a mark every 100 pixels.
2801 Placement of the drawing area and the rulers are done using a table.
2802
2803 <tscreen><verb>
2804 /* rulers.c */
2805
2806 #include <gtk/gtk.h>
2807
2808 #define EVENT_METHOD(i, x) GTK_WIDGET_CLASS(GTK_OBJECT(i)->klass)->x
2809
2810 #define XSIZE  600
2811 #define YSIZE  400
2812
2813 /* this routine gets control when the close button is clicked
2814  */
2815 void close_application( GtkWidget *widget, gpointer *data ) {
2816     gtk_main_quit();
2817 }
2818
2819
2820 /* the main routine
2821  */
2822 int main( int argc, char *argv[] ) {
2823     GtkWidget *window, *table, *area, *hrule, *vrule;
2824
2825     /* initialize gtk and create the main window */
2826     gtk_init( &amp;argc, &amp;argv );
2827
2828     window = gtk_window_new( GTK_WINDOW_TOPLEVEL );
2829     gtk_signal_connect (GTK_OBJECT (window), "delete_event",
2830             GTK_SIGNAL_FUNC( close_application ), NULL);
2831     gtk_container_border_width (GTK_CONTAINER (window), 10);
2832
2833     /* create a table for placing the ruler and the drawing area */
2834     table = gtk_table_new( 3, 2, FALSE );
2835     gtk_container_add( GTK_CONTAINER(window), table );
2836
2837     area = gtk_drawing_area_new();
2838     gtk_drawing_area_size( (GtkDrawingArea *)area, XSIZE, YSIZE );
2839     gtk_table_attach( GTK_TABLE(table), area, 1, 2, 1, 2,
2840                       GTK_EXPAND|GTK_FILL, GTK_FILL, 0, 0 );
2841     gtk_widget_set_events( area, GDK_POINTER_MOTION_MASK | GDK_POINTER_MOTION_HINT_MASK );
2842
2843     /* The horizontal ruler goes on top.  As the mouse moves across the drawing area,
2844        a motion_notify_event is passed to the appropriate event handler for the ruler. */
2845     hrule = gtk_hruler_new();
2846     gtk_ruler_set_metric( GTK_RULER(hrule), GTK_PIXELS );
2847     gtk_ruler_set_range( GTK_RULER(hrule), 7, 13, 0, 20 );
2848     gtk_signal_connect_object( GTK_OBJECT(area), "motion_notify_event",
2849                                (GtkSignalFunc)EVENT_METHOD(hrule, motion_notify_event),
2850                                GTK_OBJECT(hrule) );
2851     /*  GTK_WIDGET_CLASS(GTK_OBJECT(hrule)->klass)->motion_notify_event, */
2852     gtk_table_attach( GTK_TABLE(table), hrule, 1, 2, 0, 1,
2853                       GTK_EXPAND|GTK_SHRINK|GTK_FILL, GTK_FILL, 0, 0 );
2854     
2855     /* The vertical ruler goes on the left.  As the mouse moves across the drawing area,
2856        a motion_notify_event is passed to the appropriate event handler for the ruler. */
2857     vrule = gtk_vruler_new();
2858     gtk_ruler_set_metric( GTK_RULER(vrule), GTK_PIXELS );
2859     gtk_ruler_set_range( GTK_RULER(vrule), 0, YSIZE, 10, YSIZE );
2860     gtk_signal_connect_object( GTK_OBJECT(area), "motion_notify_event",
2861                                (GtkSignalFunc)
2862                                   GTK_WIDGET_CLASS(GTK_OBJECT(vrule)->klass)->motion_notify_event,
2863                                GTK_OBJECT(vrule) );
2864     gtk_table_attach( GTK_TABLE(table), vrule, 0, 1, 1, 2,
2865                       GTK_FILL, GTK_EXPAND|GTK_SHRINK|GTK_FILL, 0, 0 );
2866
2867     /* now show everything */
2868     gtk_widget_show( area );
2869     gtk_widget_show( hrule );
2870     gtk_widget_show( vrule );
2871     gtk_widget_show( table );
2872     gtk_widget_show( window );
2873     gtk_main();
2874
2875     return 0;
2876 }
2877 </verb></tscreen>
2878
2879 <!-- ----------------------------------------------------------------- -->
2880 <sect1>Statusbars
2881 <p>
2882 Statusbars are simple widgets used to display a text message. They keep a stack 
2883 of the messages pushed onto them, so that popping the current message 
2884 will re-display the previous text message.
2885
2886 In order to allow different parts of an application to use the same statusbar to display
2887 messages, the statusbar widget issues Context Identifiers which are used to identify
2888 different 'users'. The message on top of the stack is the one displayed, no matter what context
2889 it is in. Messages are stacked in last-in-first-out order, not context identifier order.
2890
2891 A statusbar is created with a call to:
2892 <tscreen><verb>
2893 GtkWidget* gtk_statusbar_new (void);
2894 </verb></tscreen>
2895
2896 A new Context Identifier is requested using a call to the following function with a short
2897 textual description of the context:
2898 <tscreen><verb>
2899 guint gtk_statusbar_get_context_id (GtkStatusbar *statusbar,
2900                                     const gchar  *context_description);
2901 </verb></tscreen>
2902
2903 There are three functions that can operate on statusbars.
2904 <tscreen><verb>
2905 guint       gtk_statusbar_push           (GtkStatusbar *statusbar,
2906                                          guint          context_id,
2907                                          gchar         *text);
2908
2909 void       gtk_statusbar_pop            (GtkStatusbar *statusbar)
2910                                          guint         context_id);
2911 void       gtk_statusbar_remove         (GtkStatusbar *statusbar,
2912                                          guint         context_id,
2913                                          guint         message_id); 
2914 </verb></tscreen>
2915
2916 The first, gtk_statusbar_push, is used to add a new message to the statusbar. 
2917 It returns a Message Identifier, which can be passed later to the function gtk_statusbar_remove
2918 to remove the message with the given Message and Context Identifiers from the statusbar's stack.
2919
2920 The function gtk_statusbar_pop removes the message highest in the stack with the given
2921 Context Identifier.
2922
2923 The following example creates a statusbar and two buttons, one for pushing items
2924 onto the statusbar, and one for popping the last item back off.
2925
2926 <tscreen><verb>
2927 /* statusbar.c */
2928
2929 #include <gtk/gtk.h>
2930 #include <glib.h>
2931
2932 GtkWidget *status_bar;
2933
2934 void push_item (GtkWidget *widget, gpointer *data)
2935 {
2936   static int count = 1;
2937   char buff[20];
2938
2939   g_snprintf(buff, 20, "Item %d", count++);
2940   gtk_statusbar_push( GTK_STATUSBAR(status_bar), (guint) &amp;data, buff);
2941
2942   return;
2943 }
2944
2945 void pop_item (GtkWidget *widget, gpointer *data)
2946 {
2947   gtk_statusbar_pop( GTK_STATUSBAR(status_bar), (guint) &amp;data );
2948   return;
2949 }
2950
2951 int main (int argc, char *argv[])
2952 {
2953
2954     GtkWidget *window;
2955     GtkWidget *vbox;
2956     GtkWidget *button;
2957
2958     int context_id;
2959
2960     gtk_init (&amp;argc, &amp;argv);
2961
2962     /* create a new window */
2963     window = gtk_window_new(GTK_WINDOW_TOPLEVEL);
2964     gtk_widget_set_usize( GTK_WIDGET (window), 200, 100);
2965     gtk_window_set_title(GTK_WINDOW (window), "GTK Statusbar Example");
2966     gtk_signal_connect(GTK_OBJECT (window), "delete_event",
2967                        (GtkSignalFunc) gtk_exit, NULL);
2968  
2969     vbox = gtk_vbox_new(FALSE, 1);
2970     gtk_container_add(GTK_CONTAINER(window), vbox);
2971     gtk_widget_show(vbox);
2972           
2973     status_bar = gtk_statusbar_new();      
2974     gtk_box_pack_start (GTK_BOX (vbox), status_bar, TRUE, TRUE, 0);
2975     gtk_widget_show (status_bar);
2976
2977     context_id = gtk_statusbar_get_context_id( GTK_STATUSBAR(status_bar), "Statusbar example");
2978
2979     button = gtk_button_new_with_label("push item");
2980     gtk_signal_connect(GTK_OBJECT(button), "clicked",
2981         GTK_SIGNAL_FUNC (push_item), &amp;context_id);
2982     gtk_box_pack_start(GTK_BOX(vbox), button, TRUE, TRUE, 2);
2983     gtk_widget_show(button);              
2984
2985     button = gtk_button_new_with_label("pop last item");
2986     gtk_signal_connect(GTK_OBJECT(button), "clicked",
2987         GTK_SIGNAL_FUNC (pop_item), &amp;context_id);
2988     gtk_box_pack_start(GTK_BOX(vbox), button, TRUE, TRUE, 2);
2989     gtk_widget_show(button);              
2990
2991     /* always display the window as the last step so it all splashes on
2992      * the screen at once. */
2993     gtk_widget_show(window);
2994
2995     gtk_main ();
2996
2997     return 0;
2998 }
2999 </verb></tscreen>
3000
3001 <!-- ----------------------------------------------------------------- -->
3002 <sect1>Text Entries
3003 <p>
3004 The Entry widget allows text to be typed and displayed in a single line text box. 
3005 The text may be set with functions calls that allow new text to replace, 
3006 prepend or append the current contents of the Entry widget.
3007
3008 There are two functions for creating Entry widgets:
3009 <tscreen><verb>
3010 GtkWidget* gtk_entry_new (void);
3011
3012 GtkWidget* gtk_entry_new_with_max_length (guint16 max);
3013 </verb></tscreen>
3014
3015 The first just creates a new Entry widget, whilst the second creates a new Entry and 
3016 sets a limit on the length of the text within the Entry..
3017
3018 The maximum length of the text within an entry widget may be changed by a call to the following
3019 function. If the current text is longer than this maximum, then it is upto us to alter the Entries
3020 contents appropriately.
3021
3022 <tscreen><verb>
3023 void gtk_entry_set_max_length (GtkEntry *entry,
3024                                guint16  max);
3025 </verb></tscreen>
3026
3027 There are several functions for altering the text which is currently within the Entry widget.
3028 <tscreen><verb>
3029 void gtk_entry_set_text       (GtkEntry    *entry,
3030                                const gchar *text);
3031 void gtk_entry_append_text    (GtkEntry    *entry,
3032                                const gchar *text);
3033 void gtk_entry_prepend_text   (GtkEntry    *entry,
3034                                const gchar *text);
3035 </verb></tscreen>
3036
3037 The function gtk_entry_set_text sets the contents of the Entry widget, replacing the
3038 current contents. The functions gtk_entry_append_text and gtk_entry_prepend_text allow
3039 the current contents to be appended and prepended to.
3040
3041 The next function allows the current insertion point to be set.
3042 <tscreen><verb>
3043 void gtk_entry_set_position   (GtkEntry *entry,
3044                                gint     position);
3045 </verb></tscreen>
3046
3047 The contents of the Entry can be retrieved by using a call to the following function. This
3048 is useful in the callback functions described below.
3049 <tscreen><verb>
3050 gchar* gtk_entry_get_text (GtkEntry *entry);
3051 </verb></tscreen>
3052
3053 If we don't want the contents of the Entry to be changed by someone typing into it, we
3054 can change it's edittable state.
3055 <tscreen><verb>
3056 void gtk_entry_set_editable (GtkEntry *entry,
3057                              gboolean editable);
3058 </verb></tscreen>
3059
3060 This function allows us to toggle the edittable state of the Entry widget by passing in
3061 TRUE or FALSE values for the editable argument.
3062
3063 If we are using the Entry where we don't want the text entered to be visible, for
3064 example when a password is being entered, we can use the following function, which
3065 also takes a boolean flag.
3066 <tscreen><verb>
3067 void gtk_entry_set_visibility (GtkEntry *entry,
3068                                gboolean visible);
3069 </verb></tscreen>
3070
3071 A region of the text may be set as selected by using the following function. This would
3072 most often be used after setting some default text in an Entry, making it easy for the user
3073 to remove it.
3074 <tscreen><verb>
3075 void gtk_entry_select_region (GtkEntry *entry,
3076                               gint     start,
3077                               gint     end);
3078 </verb></tscreen>
3079
3080 If we want to catch when the user has entered text, we can connect to the
3081 <tt/activate/ or <tt/changed/ signal. Activate is raised when the user hits 
3082 the enter key within the Entry widget. Changed is raised when the text changes at all, 
3083 e.g. for every character entered or removed.
3084
3085 The following code is an example of using an Entry widget.
3086 <tscreen><verb>
3087 /* entry.c */
3088
3089 #include <gtk/gtk.h>
3090
3091 void enter_callback(GtkWidget *widget, GtkWidget *entry)
3092 {
3093   gchar *entry_text;
3094   entry_text = gtk_entry_get_text(GTK_ENTRY(entry));
3095   printf("Entry contents: %s\n", entry_text);
3096 }
3097
3098 void entry_toggle_editable (GtkWidget *checkbutton,
3099                                    GtkWidget *entry)
3100 {
3101   gtk_entry_set_editable(GTK_ENTRY(entry),
3102                          GTK_TOGGLE_BUTTON(checkbutton)->active);
3103 }
3104
3105 void entry_toggle_visibility (GtkWidget *checkbutton,
3106                                    GtkWidget *entry)
3107 {
3108   gtk_entry_set_visibility(GTK_ENTRY(entry),
3109                          GTK_TOGGLE_BUTTON(checkbutton)->active);
3110 }
3111
3112 int main (int argc, char *argv[])
3113 {
3114
3115     GtkWidget *window;
3116     GtkWidget *vbox, *hbox;
3117     GtkWidget *entry;
3118     GtkWidget *button;
3119     GtkWidget *check;
3120
3121     gtk_init (&amp;argc, &amp;argv);
3122
3123     /* create a new window */
3124     window = gtk_window_new(GTK_WINDOW_TOPLEVEL);
3125     gtk_widget_set_usize( GTK_WIDGET (window), 200, 100);
3126     gtk_window_set_title(GTK_WINDOW (window), "GTK Entry");
3127     gtk_signal_connect(GTK_OBJECT (window), "delete_event",
3128                        (GtkSignalFunc) gtk_exit, NULL);
3129
3130     vbox = gtk_vbox_new (FALSE, 0);
3131     gtk_container_add (GTK_CONTAINER (window), vbox);
3132     gtk_widget_show (vbox);
3133
3134     entry = gtk_entry_new_with_max_length (50);
3135     gtk_signal_connect(GTK_OBJECT(entry), "activate",
3136                        GTK_SIGNAL_FUNC(enter_callback),
3137                        entry);
3138     gtk_entry_set_text (GTK_ENTRY (entry), "hello");
3139     gtk_entry_append_text (GTK_ENTRY (entry), " world");
3140     gtk_entry_select_region (GTK_ENTRY (entry),
3141                              0, GTK_ENTRY(entry)->text_length);
3142     gtk_box_pack_start (GTK_BOX (vbox), entry, TRUE, TRUE, 0);
3143     gtk_widget_show (entry);
3144
3145     hbox = gtk_hbox_new (FALSE, 0);
3146     gtk_container_add (GTK_CONTAINER (vbox), hbox);
3147     gtk_widget_show (hbox);
3148                                   
3149     check = gtk_check_button_new_with_label("Editable");
3150     gtk_box_pack_start (GTK_BOX (hbox), check, TRUE, TRUE, 0);
3151     gtk_signal_connect (GTK_OBJECT(check), "toggled",
3152                         GTK_SIGNAL_FUNC(entry_toggle_editable), entry);
3153     gtk_toggle_button_set_state(GTK_TOGGLE_BUTTON(check), TRUE);
3154     gtk_widget_show (check);
3155     
3156     check = gtk_check_button_new_with_label("Visible");
3157     gtk_box_pack_start (GTK_BOX (hbox), check, TRUE, TRUE, 0);
3158     gtk_signal_connect (GTK_OBJECT(check), "toggled",
3159                         GTK_SIGNAL_FUNC(entry_toggle_visibility), entry);
3160     gtk_toggle_button_set_state(GTK_TOGGLE_BUTTON(check), TRUE);
3161     gtk_widget_show (check);
3162                                    
3163     button = gtk_button_new_with_label ("Close");
3164     gtk_signal_connect_object (GTK_OBJECT (button), "clicked",
3165                                GTK_SIGNAL_FUNC(gtk_exit),
3166                                GTK_OBJECT (window));
3167     gtk_box_pack_start (GTK_BOX (vbox), button, TRUE, TRUE, 0);
3168     GTK_WIDGET_SET_FLAGS (button, GTK_CAN_DEFAULT);
3169     gtk_widget_grab_default (button);
3170     gtk_widget_show (button);
3171     
3172     gtk_widget_show(window);
3173
3174     gtk_main();
3175     return(0);
3176 }
3177 </verb></tscreen>
3178
3179 <!-- ***************************************************************** -->
3180 <sect> Container Widgets
3181 <!-- ***************************************************************** -->
3182
3183 <!-- ----------------------------------------------------------------- -->
3184 <sect1> Notebooks
3185 <p>
3186 The NoteBook Widget is a collection of 'pages' that overlap each other,
3187 each page contains different information.  This widget has become more common 
3188 lately in GUI programming, and it is a good way to show blocks similar 
3189 information that warrant separation in their display.
3190
3191 The first function call you will need to know, as you can probably 
3192 guess by now, is used to create a new notebook widget.
3193
3194 <tscreen><verb>
3195 GtkWidget* gtk_notebook_new (void);
3196 </verb></tscreen>
3197
3198 Once the notebook has been created, there are 12 functions that 
3199 operate on the notebook widget.  Let's look at them individually.
3200
3201 The first one we will look at is how to position the page indicators.
3202 These page indicators or 'tabs' as they are referred to, can be positioned
3203 in four ways; top, bottom, left, or right.
3204
3205 <tscreen><verb>
3206 void gtk_notebook_set_tab_pos (GtkNotebook *notebook, GtkPositionType pos);
3207 </verb></tscreen>
3208
3209 GtkPostionType will be one of the following, and they are pretty self explanatory.
3210 <itemize>
3211 <item> GTK_POS_LEFT
3212 <item> GTK_POS_RIGHT
3213 <item> GTK_POS_TOP
3214 <item> GTK_POS_BOTTOM
3215 </itemize>
3216
3217 GTK_POS_TOP is the default.
3218
3219 Next we will look at how to add pages to the notebook.  There are three
3220 ways to add pages to the NoteBook.  Let's look at the first two together as 
3221 they are quite similar.
3222
3223 <tscreen><verb>
3224 void gtk_notebook_append_page (GtkNotebook *notebook, GtkWidget *child, GtkWidget *tab_label);
3225
3226 void gtk_notebook_prepend_page (GtkNotebook *notebook, GtkWidget *child, GtkWidget *tab_label);
3227 </verb></tscreen>
3228
3229 These functions add pages to the notebook by inserting them from the 
3230 back of the notebook (append), or the front of the notebook (prepend).  
3231 *child is the widget that is placed within the notebook page, and *tab_label is
3232 the label for the page being added.
3233
3234 The final function for adding a page to the notebook contains all of 
3235 the properties of the previous two, but it allows you to specify what position
3236 you want the page to be in the notebook.
3237
3238 <tscreen><verb>
3239 void gtk_notebook_insert_page (GtkNotebook *notebook, GtkWidget *child, GtkWidget *tab_label, gint position);
3240 </verb></tscreen>
3241
3242 The parameters are the same as _append_ and _prepend_ except it 
3243 contains an extra parameter, position.  This parameter is used to specify what
3244 place this page will inserted to.
3245
3246 Now that we know how to add a page, lets see how we can remove a page 
3247 from the notebook.
3248
3249 <tscreen><verb>
3250 void gtk_notebook_remove_page (GtkNotebook *notebook, gint page_num);
3251 </verb></tscreen>
3252
3253 This function takes the page specified by page_num and removes it from 
3254 the widget *notebook.
3255
3256 To find out what the current page is in a notebook use the function:
3257
3258 <tscreen><verb>
3259 gint gtk_notebook_current_page (GtkNotebook *notebook);
3260 </verb></tscreen>
3261
3262 These next two functions are simple calls to move the notebook page 
3263 forward or backward.  Simply provide the respective function call with the
3264 notebook widget you wish to operate on.  Note:  When the NoteBook is currently
3265 on the last page, and gtk_notebook_next_page is called, the notebook will 
3266 wrap back to the first page.  Likewise, if the NoteBook is on the first page, 
3267 and gtk_notebook_prev_page is called, the notebook will wrap to the last page.
3268
3269 <tscreen><verb>
3270 void gtk_notebook_next_page (GtkNoteBook *notebook);
3271 void gtk_notebook_prev_page (GtkNoteBook *notebook);
3272 </verb></tscreen>
3273
3274 This next function sets the 'active' page.  If you wish the
3275 notebook to be opened to page 5 for example, you would use this function.  
3276 Without using this function, the notebook defaults to the first page.
3277
3278 <tscreen><verb>
3279 void gtk_notebook_set_page (GtkNotebook *notebook, gint page_num);
3280 </verb></tscreen>
3281
3282 The next two functions add or remove the notebook page tabs and the 
3283 notebook border respectively.
3284
3285 <tscreen><verb>
3286 void gtk_notebook_set_show_tabs (GtkNotebook *notebook, gint show_tabs);
3287 void gtk_notebook_set_show_border (GtkNotebook *notebook, gint show_border);
3288 </verb></tscreen>
3289
3290 show_tabs and show_border can both be either TRUE or FALSE (0 or 1).
3291
3292 Now lets look at an example, it is expanded from the testgtk.c code 
3293 that comes with the GTK distribution, and it shows all 13 functions. This 
3294 small program, creates a window with a notebook and six buttons.  The notebook 
3295 contains 11 pages, added in three different ways, appended, inserted, and 
3296 prepended.  The buttons allow you rotate the tab positions, add/remove the tabs
3297 and border, remove a page, change pages in both a forward and backward manner,
3298 and exit the program. 
3299
3300 <tscreen><verb>
3301 /* notebook.c */
3302
3303 #include <gtk/gtk.h>
3304
3305 /* This function rotates the position of the tabs */
3306 void rotate_book (GtkButton *button, GtkNotebook *notebook)
3307 {
3308     gtk_notebook_set_tab_pos (notebook, (notebook->tab_pos +1) %4);
3309 }
3310
3311 /* Add/Remove the page tabs and the borders */
3312 void tabsborder_book (GtkButton *button, GtkNotebook *notebook)
3313 {
3314     gint tval = FALSE;
3315     gint bval = FALSE;
3316     if (notebook->show_tabs == 0)
3317             tval = TRUE; 
3318     if (notebook->show_border == 0)
3319             bval = TRUE;
3320     
3321     gtk_notebook_set_show_tabs (notebook, tval);
3322     gtk_notebook_set_show_border (notebook, bval);
3323 }
3324
3325 /* Remove a page from the notebook */
3326 void remove_book (GtkButton *button, GtkNotebook *notebook)
3327 {
3328     gint page;
3329     
3330     page = gtk_notebook_current_page(notebook);
3331     gtk_notebook_remove_page (notebook, page);
3332     /* Need to refresh the widget -- 
3333      This forces the widget to redraw itself. */
3334     gtk_widget_draw(GTK_WIDGET(notebook), NULL);
3335 }
3336
3337 void delete (GtkWidget *widget, gpointer *data)
3338 {
3339     gtk_main_quit ();
3340 }
3341
3342 int main (int argc, char *argv[])
3343 {
3344     GtkWidget *window;
3345     GtkWidget *button;
3346     GtkWidget *table;
3347     GtkWidget *notebook;
3348     GtkWidget *frame;
3349     GtkWidget *label;
3350     GtkWidget *checkbutton;
3351     int i;
3352     char bufferf[32];
3353     char bufferl[32];
3354     
3355     gtk_init (&amp;argc, &amp;argv);
3356     
3357     window = gtk_window_new (GTK_WINDOW_TOPLEVEL);
3358     
3359     gtk_signal_connect (GTK_OBJECT (window), "delete_event",
3360                         GTK_SIGNAL_FUNC (delete), NULL);
3361     
3362     gtk_container_border_width (GTK_CONTAINER (window), 10);
3363     
3364     table = gtk_table_new(2,6,TRUE);
3365     gtk_container_add (GTK_CONTAINER (window), table);
3366     
3367     /* Create a new notebook, place the position of the tabs */
3368     notebook = gtk_notebook_new ();
3369     gtk_notebook_set_tab_pos (GTK_NOTEBOOK (notebook), GTK_POS_TOP);
3370     gtk_table_attach_defaults(GTK_TABLE(table), notebook, 0,6,0,1);
3371     gtk_widget_show(notebook);
3372     
3373     /* lets append a bunch of pages to the notebook */
3374     for (i=0; i < 5; i++) {
3375         sprintf(bufferf, "Append Frame %d", i+1);
3376         sprintf(bufferl, "Page %d", i+1);
3377         
3378         frame = gtk_frame_new (bufferf);
3379         gtk_container_border_width (GTK_CONTAINER (frame), 10);
3380         gtk_widget_set_usize (frame, 100, 75);
3381         gtk_widget_show (frame);
3382         
3383         label = gtk_label_new (bufferf);
3384         gtk_container_add (GTK_CONTAINER (frame), label);
3385         gtk_widget_show (label);
3386         
3387         label = gtk_label_new (bufferl);
3388         gtk_notebook_append_page (GTK_NOTEBOOK (notebook), frame, label);
3389     }
3390     
3391     
3392     /* now lets add a page to a specific spot */
3393     checkbutton = gtk_check_button_new_with_label ("Check me please!");
3394     gtk_widget_set_usize(checkbutton, 100, 75);
3395     gtk_widget_show (checkbutton);
3396     
3397     label = gtk_label_new ("Add spot");
3398     gtk_container_add (GTK_CONTAINER (checkbutton), label);
3399     gtk_widget_show (label);
3400     label = gtk_label_new ("Add page");
3401     gtk_notebook_insert_page (GTK_NOTEBOOK (notebook), checkbutton, label, 2);
3402     
3403     /* Now finally lets prepend pages to the notebook */
3404     for (i=0; i < 5; i++) {
3405         sprintf(bufferf, "Prepend Frame %d", i+1);
3406         sprintf(bufferl, "PPage %d", i+1);
3407         
3408         frame = gtk_frame_new (bufferf);
3409         gtk_container_border_width (GTK_CONTAINER (frame), 10);
3410         gtk_widget_set_usize (frame, 100, 75);
3411         gtk_widget_show (frame);
3412         
3413         label = gtk_label_new (bufferf);
3414         gtk_container_add (GTK_CONTAINER (frame), label);
3415         gtk_widget_show (label);
3416         
3417         label = gtk_label_new (bufferl);
3418         gtk_notebook_prepend_page (GTK_NOTEBOOK(notebook), frame, label);
3419     }
3420     
3421     /* Set what page to start at (page 4) */
3422     gtk_notebook_set_page (GTK_NOTEBOOK(notebook), 3);
3423     
3424     
3425     /* create a bunch of buttons */
3426     button = gtk_button_new_with_label ("close");
3427     gtk_signal_connect_object (GTK_OBJECT (button), "clicked",
3428                                GTK_SIGNAL_FUNC (delete), NULL);
3429     gtk_table_attach_defaults(GTK_TABLE(table), button, 0,1,1,2);
3430     gtk_widget_show(button);
3431     
3432     button = gtk_button_new_with_label ("next page");
3433     gtk_signal_connect_object (GTK_OBJECT (button), "clicked",
3434                                (GtkSignalFunc) gtk_notebook_next_page,
3435                                GTK_OBJECT (notebook));
3436     gtk_table_attach_defaults(GTK_TABLE(table), button, 1,2,1,2);
3437     gtk_widget_show(button);
3438     
3439     button = gtk_button_new_with_label ("prev page");
3440     gtk_signal_connect_object (GTK_OBJECT (button), "clicked",
3441                                (GtkSignalFunc) gtk_notebook_prev_page,
3442                                GTK_OBJECT (notebook));
3443     gtk_table_attach_defaults(GTK_TABLE(table), button, 2,3,1,2);
3444     gtk_widget_show(button);
3445     
3446     button = gtk_button_new_with_label ("tab position");
3447     gtk_signal_connect_object (GTK_OBJECT (button), "clicked",
3448                                (GtkSignalFunc) rotate_book, GTK_OBJECT(notebook));
3449     gtk_table_attach_defaults(GTK_TABLE(table), button, 3,4,1,2);
3450     gtk_widget_show(button);
3451     
3452     button = gtk_button_new_with_label ("tabs/border on/off");
3453     gtk_signal_connect_object (GTK_OBJECT (button), "clicked",
3454                                (GtkSignalFunc) tabsborder_book,
3455                                GTK_OBJECT (notebook));
3456     gtk_table_attach_defaults(GTK_TABLE(table), button, 4,5,1,2);
3457     gtk_widget_show(button);
3458     
3459     button = gtk_button_new_with_label ("remove page");
3460     gtk_signal_connect_object (GTK_OBJECT (button), "clicked",
3461                                (GtkSignalFunc) remove_book,
3462                                GTK_OBJECT(notebook));
3463     gtk_table_attach_defaults(GTK_TABLE(table), button, 5,6,1,2);
3464     gtk_widget_show(button);
3465     
3466     gtk_widget_show(table);
3467     gtk_widget_show(window);
3468     
3469     gtk_main ();
3470     
3471     return 0;
3472 }
3473 </verb></tscreen>
3474 <p>
3475 Hopefully this helps you on your way with creating notebooks for your
3476 GTK applications.
3477
3478 <!-- ----------------------------------------------------------------- -->
3479 <sect1> Scrolled Windows
3480 <p>
3481 Scrolled windows are used to create a scrollable area inside a real window.  
3482 You may insert any types of widgets to these scrolled windows, and they will
3483 all be accessable regardless of the size by using the scrollbars.
3484
3485 The following function is used to create a new scolled window.
3486
3487 <tscreen><verb>
3488 GtkWidget* gtk_scrolled_window_new (GtkAdjustment *hadjustment,
3489                                     GtkAdjustment *vadjustment);
3490 </verb></tscreen>
3491 <p>
3492 Where the first argument is the adjustment for the horizontal
3493 direction, and the second, the adjustment for the vertical direction.
3494 These are almost always set to NULL.
3495
3496 <tscreen><verb>
3497 void gtk_scrolled_window_set_policy      (GtkScrolledWindow *scrolled_window,
3498                                           GtkPolicyType      hscrollbar_policy,
3499                                                                                   GtkPolicyType      vscrollbar_policy);
3500 </verb></tscreen>
3501
3502 This sets the policy to be used with respect to the scrollbars.
3503 The first arguement is the scrolled window you wish to change. The second
3504 sets the policiy for the horizontal scrollbar, and the third, 
3505 the vertical scrollbar.  
3506
3507 The policy may be one of GTK_POLICY AUTOMATIC, or GTK_POLICY_ALWAYS.
3508 GTK_POLICY_AUTOMATIC will automatically decide whether you need
3509 scrollbars, wheras GTK_POLICY_ALWAYS will always leave the scrollbars
3510 there.
3511
3512 Here is a simple example that packs 100 toggle buttons into a scrolled window.
3513 I've only commented on the parts that may be new to you.
3514
3515 <tscreen><verb>
3516 /* scrolledwin.c */
3517
3518 #include <gtk/gtk.h>
3519
3520 void destroy(GtkWidget *widget, gpointer *data)
3521 {
3522     gtk_main_quit();
3523 }
3524
3525 int main (int argc, char *argv[])
3526 {
3527     static GtkWidget *window;
3528     GtkWidget *scrolled_window;
3529     GtkWidget *table;
3530     GtkWidget *button;
3531     char buffer[32];
3532     int i, j;
3533     
3534     gtk_init (&amp;argc, &amp;argv);
3535     
3536     /* Create a new dialog window for the scrolled window to be
3537      * packed into.  A dialog is just like a normal window except it has a 
3538      * vbox and a horizontal seperator packed into it.  It's just a shortcut
3539      * for creating dialogs */
3540     window = gtk_dialog_new ();
3541     gtk_signal_connect (GTK_OBJECT (window), "destroy",
3542                         (GtkSignalFunc) destroy, NULL);
3543     gtk_window_set_title (GTK_WINDOW (window), "dialog");
3544     gtk_container_border_width (GTK_CONTAINER (window), 0);
3545     gtk_widget_set_usize(window, 300, 300);
3546     
3547     /* create a new scrolled window. */
3548     scrolled_window = gtk_scrolled_window_new (NULL, NULL);
3549     
3550     gtk_container_border_width (GTK_CONTAINER (scrolled_window), 10);
3551     
3552     /* the policy is one of GTK_POLICY AUTOMATIC, or GTK_POLICY_ALWAYS.
3553      * GTK_POLICY_AUTOMATIC will automatically decide whether you need
3554      * scrollbars, wheras GTK_POLICY_ALWAYS will always leave the scrollbars
3555      * there.  The first one is the horizontal scrollbar, the second, 
3556      * the vertical. */
3557     gtk_scrolled_window_set_policy (GTK_SCROLLED_WINDOW (scrolled_window),
3558                                     GTK_POLICY_AUTOMATIC, GTK_POLICY_ALWAYS);
3559     /* The dialog window is created with a vbox packed into it. */                                                              
3560     gtk_box_pack_start (GTK_BOX (GTK_DIALOG(window)->vbox), scrolled_window, 
3561                         TRUE, TRUE, 0);
3562     gtk_widget_show (scrolled_window);
3563     
3564     /* create a table of 10 by 10 squares. */
3565     table = gtk_table_new (10, 10, FALSE);
3566     
3567     /* set the spacing to 10 on x and 10 on y */
3568     gtk_table_set_row_spacings (GTK_TABLE (table), 10);
3569     gtk_table_set_col_spacings (GTK_TABLE (table), 10);
3570     
3571     /* pack the table into the scrolled window */
3572     gtk_container_add (GTK_CONTAINER (scrolled_window), table);
3573     gtk_widget_show (table);
3574     
3575     /* this simply creates a grid of toggle buttons on the table
3576      * to demonstrate the scrolled window. */
3577     for (i = 0; i < 10; i++)
3578             for (j = 0; j < 10; j++) {
3579                 sprintf (buffer, "button (%d,%d)\n", i, j);
3580                 button = gtk_toggle_button_new_with_label (buffer);
3581                 gtk_table_attach_defaults (GTK_TABLE (table), button,
3582                                            i, i+1, j, j+1);
3583                 gtk_widget_show (button);
3584             }
3585     
3586     /* Add a "close" button to the bottom of the dialog */
3587     button = gtk_button_new_with_label ("close");
3588     gtk_signal_connect_object (GTK_OBJECT (button), "clicked",
3589                                (GtkSignalFunc) gtk_widget_destroy,
3590                                GTK_OBJECT (window));
3591     
3592     /* this makes it so the button is the default. */
3593     
3594     GTK_WIDGET_SET_FLAGS (button, GTK_CAN_DEFAULT);
3595     gtk_box_pack_start (GTK_BOX (GTK_DIALOG (window)->action_area), button, TRUE, TRUE, 0);
3596     
3597     /* This grabs this button to be the default button. Simply hitting
3598      * the "Enter" key will cause this button to activate. */
3599     gtk_widget_grab_default (button);
3600     gtk_widget_show (button);
3601     
3602     gtk_widget_show (window);
3603     
3604     gtk_main();
3605     
3606     return(0);
3607 }
3608 </verb></tscreen>
3609 <p>
3610 Try playing with resizing the window.  You'll notice how the scrollbars
3611 react.  You may also wish to use the gtk_widget_set_usize() call to set the default
3612 size of the window or other widgets.
3613
3614 <!-- ***************************************************************** -->
3615 <sect> List Widgets
3616 <!-- ***************************************************************** -->
3617
3618 <p>
3619 The GtkList widget is designed to act as a vertical container for widgets
3620 that should be of the type GtkListItem.
3621
3622 A GtkList widget has its own window to receive events and it's own
3623 background color which is usualy white.  As it is directly derived from a
3624 GtkContainer it can be treated as such by using the GTK_CONTAINER(List)
3625 macro, see the GtkContainer widget for more on this.
3626 One should already be familar whith the usage of a GList and its
3627 related functions g_list_*() to be able to use the GtkList widget to
3628 its fully extends.
3629
3630 There is one field inside the structure definition of the GtkList widget
3631 that will be of greater interest to us, this is:
3632
3633 <tscreen><verb>
3634 struct _GtkList
3635 {
3636   ...
3637   GList *selection;
3638   guint selection_mode;
3639   ...
3640 }; 
3641 </verb></tscreen>
3642
3643 The selection field of a GtkList points to a linked list of all items
3644 that are cureently selected, or `NULL' if the selection is empty.
3645 So to learn about the current selection we read the GTK_LIST()->selection
3646 field, but do not modify it since the internal fields are maintained by
3647 the gtk_list_*() functions.
3648
3649 The selection_mode of the GtkList determines the selection facilities
3650 of a GtkList and therefore the contents of the GTK_LIST()->selection
3651 field:
3652
3653 The selection_mode may be one of the following:
3654 <itemize>
3655 <item> GTK_SELECTION_SINGLE -   The selection is either `NULL'
3656                         or contains a GList* pointer
3657                         for a single selected item.
3658
3659 <item> GTK_SELECTION_BROWSE -  The selection is `NULL' if the list
3660                         contains no widgets or insensitive
3661                         ones only, otherwise it contains
3662                         a GList pointer for one GList
3663                         structure, and therefore exactly
3664                         one list item.
3665
3666 <item> GTK_SELECTION_MULTIPLE -  The selection is `NULL' if no list
3667                         items are selected or a GList pointer
3668                         for the first selected item. That
3669                         in turn points to a GList structure
3670                         for the second selected item and so
3671                         on.
3672
3673 <item> GTK_SELECTION_EXTENDED - The selection is always `NULL'.
3674 </itemize>
3675 <p>
3676 The default is GTK_SELECTION_MULTIPLE.
3677
3678 <!-- ----------------------------------------------------------------- -->
3679 <sect1> Signals
3680 <p>
3681 <tscreen><verb>
3682 void selection_changed (GtkList *LIST)
3683 </verb></tscreen>
3684
3685 This signal will be invoked whenever a the selection field
3686 of a GtkList has changed. This happens when a child of
3687 the GtkList got selected or unselected.
3688
3689 <tscreen><verb>
3690 void select_child (GtkList *LIST, GtkWidget *CHILD)
3691 </verb></tscreen>
3692
3693 This signal is invoked when a child of the GtkList is about
3694 to get selected. This happens mainly on calls to
3695 gtk_list_select_item(), gtk_list_select_child(), button presses
3696 and sometimes indirectly triggered on some else occasions where
3697 children get added to or removed from the GtkList.
3698
3699 <tscreen><verb>
3700 void unselect_child (GtkList *LIST, GtkWidget *CHILD)
3701 </verb></tscreen>
3702
3703 This signal is invoked when a child of the GtkList is about
3704 to get unselected. This happens mainly on calls to
3705 gtk_list_unselect_item(), gtk_list_unselect_child(), button presses
3706 and sometimes indirectly triggered on some else occasions where
3707 children get added to or removed from the GtkList.
3708
3709 <!-- ----------------------------------------------------------------- -->
3710 <sect1> Functions
3711 <p>
3712 <tscreen><verb>
3713 guint gtk_list_get_type (void)
3714 </verb></tscreen>
3715
3716 Returns the `GtkList' type identifier.
3717
3718 <tscreen><verb>
3719 GtkWidget* gtk_list_new (void)
3720 </verb></tscreen>
3721
3722 Create a new `GtkList' object. The new widget is
3723 returned as a pointer to a `GtkWidget' object.
3724 `NULL' is returned on failure.
3725
3726 <tscreen><verb>
3727 void gtk_list_insert_items (GtkList *LIST, GList *ITEMS, gint POSITION)
3728 </verb></tscreen>
3729
3730 Insert list items into the LIST, starting at POSITION.
3731 ITEMS is a doubly linked list where each nodes data
3732 pointer is expected to point to a newly created GtkListItem.
3733 The GList nodes of ITEMS are taken over by the LIST.
3734
3735 <tscreen><verb>
3736 void gtk_list_append_items (GtkList *LIST, GList *ITEMS)
3737 </verb></tscreen>
3738
3739 Insert list items just like gtk_list_insert_items() at the end
3740 of the LIST. The GList nodes of ITEMS are taken over by the LIST.
3741
3742 <tscreen><verb>
3743 void gtk_list_prepend_items (GtkList *LIST, GList *ITEMS)
3744 </verb></tscreen>
3745
3746 Insert list items just like gtk_list_insert_items() at the very
3747 beginning of the LIST. The GList nodes of ITEMS are taken over
3748 by the LIST.
3749
3750 <tscreen><verb>
3751 void gtk_list_remove_items (GtkList *LIST, GList *ITEMS)
3752 </verb></tscreen>
3753
3754 Remove list items from the LIST. ITEMS is a doubly linked
3755 list where each nodes data pointer is expected to point to a
3756 direct child of LIST. It is the callers responsibility to make a
3757 call to g_list_free(ITEMS) afterwards. Also the caller has to
3758 destroy the list items himself.
3759
3760 <tscreen><verb>
3761 void gtk_list_clear_items (GtkList *LIST, gint START, gint END)
3762 </verb></tscreen>
3763
3764 Remove and destroy list items from the LIST. a widget is affected if
3765 its current position within LIST is in the range specified by START
3766 and END.
3767
3768 <tscreen><verb>
3769 void gtk_list_select_item (GtkList *LIST, gint ITEM)
3770 </verb></tscreen>
3771
3772 Invoke the select_child signal for a list item
3773 specified through its current position within LIST.
3774
3775 <tscreen><verb>
3776 void gtk_list_unselect_item (GtkList *LIST, gint ITEM)
3777 </verb></tscreen>
3778
3779 Invoke the unselect_child signal for a list item
3780 specified through its current position within LIST.
3781
3782 <tscreen><verb>
3783 void gtk_list_select_child (GtkList *LIST, GtkWidget *CHILD)
3784 </verb></tscreen>
3785
3786 Invoke the select_child signal for the specified CHILD.
3787
3788 <tscreen><verb>
3789 void gtk_list_unselect_child (GtkList *LIST, GtkWidget *CHILD)
3790 </verb></tscreen>
3791
3792 Invoke the unselect_child signal for the specified CHILD.
3793
3794 <tscreen><verb>
3795 gint gtk_list_child_position (GtkList *LIST, GtkWidget *CHILD)
3796 </verb></tscreen>
3797
3798 Return the position of CHILD within LIST. `-1' is returned on failure.
3799
3800 <tscreen><verb>
3801 void gtk_list_set_selection_mode (GtkList *LIST, GtkSelectionMode MODE)
3802 </verb></tscreen>
3803
3804 Set LIST to the selection mode MODE wich can be of GTK_SELECTION_SINGLE,
3805 GTK_SELECTION_BROWSE, GTK_SELECTION_MULTIPLE or GTK_SELECTION_EXTENDED.
3806
3807 <tscreen><verb>
3808 GtkList* GTK_LIST (gpointer OBJ)
3809 </verb></tscreen>
3810
3811 Cast a generic pointer to `GtkList*'. *Note Standard Macros::, for
3812 more info.
3813
3814 <tscreen><verb>
3815 GtkListClass* GTK_LIST_CLASS (gpointer CLASS)
3816 </verb></tscreen>
3817
3818 Cast a generic pointer to `GtkListClass*'. *Note Standard Macros::,
3819 for more info.
3820
3821 <tscreen><verb>
3822 gint GTK_IS_LIST (gpointer OBJ)
3823 </verb></tscreen>
3824
3825 Determine if a generic pointer refers to a `GtkList' object. *Note
3826 Standard Macros::, for more info.
3827
3828 <!-- ----------------------------------------------------------------- -->
3829 <sect1> Example
3830 <p>
3831 Following is an example program that will print out the changes
3832 of the selection of a GtkList, and lets you "arrest" list items
3833 into a prison by selecting them with the rightmost mouse button:
3834
3835 <tscreen><verb>
3836 /* list.c */
3837
3838 /* include the gtk+ header files
3839  * include stdio.h, we need that for the printf() function
3840  */
3841 #include        <gtk/gtk.h>
3842 #include        <stdio.h>
3843
3844 /* this is our data identification string to store
3845  * data in list items
3846  */
3847 const   gchar   *list_item_data_key="list_item_data";
3848
3849
3850 /* prototypes for signal handler that we are going to connect
3851  * to the GtkList widget
3852  */
3853 static  void    sigh_print_selection    (GtkWidget      *gtklist,
3854                                          gpointer       func_data);
3855 static  void    sigh_button_event       (GtkWidget      *gtklist,
3856                                          GdkEventButton *event,
3857                                          GtkWidget      *frame);
3858
3859
3860 /* main function to set up the user interface */
3861
3862 gint main (int argc, gchar *argv[])
3863 {                                  
3864     GtkWidget       *separator;
3865     GtkWidget       *window;
3866     GtkWidget       *vbox;
3867     GtkWidget       *scrolled_window;
3868     GtkWidget       *frame;
3869     GtkWidget       *gtklist;
3870     GtkWidget       *button;
3871     GtkWidget       *list_item;
3872     GList           *dlist;
3873     guint           i;
3874     gchar           buffer[64];
3875     
3876     
3877     /* initialize gtk+ (and subsequently gdk) */
3878
3879     gtk_init(&amp;argc, &amp;argv);
3880     
3881     
3882     /* create a window to put all the widgets in
3883      * connect gtk_main_quit() to the "destroy" event of
3884      * the window to handle window manager close-window-events
3885      */
3886     window=gtk_window_new(GTK_WINDOW_TOPLEVEL);
3887     gtk_window_set_title(GTK_WINDOW(window), "GtkList Example");
3888     gtk_signal_connect(GTK_OBJECT(window),
3889                        "destroy",
3890                        GTK_SIGNAL_FUNC(gtk_main_quit),
3891                        NULL);
3892     
3893     
3894     /* inside the window we need a box to arrange the widgets
3895      * vertically */
3896     vbox=gtk_vbox_new(FALSE, 5);
3897     gtk_container_border_width(GTK_CONTAINER(vbox), 5);
3898     gtk_container_add(GTK_CONTAINER(window), vbox);
3899     gtk_widget_show(vbox);
3900     
3901     /* this is the scolled window to put the GtkList widget inside */
3902     scrolled_window=gtk_scrolled_window_new(NULL, NULL);
3903     gtk_widget_set_usize(scrolled_window, 250, 150);
3904     gtk_container_add(GTK_CONTAINER(vbox), scrolled_window);
3905     gtk_widget_show(scrolled_window);
3906     
3907     /* create the GtkList widget
3908      * connect the sigh_print_selection() signal handler
3909      * function to the "selection_changed" signal of the GtkList
3910      * to print out the selected items each time the selection
3911      * has changed */
3912     gtklist=gtk_list_new();
3913     gtk_container_add(GTK_CONTAINER(scrolled_window), gtklist);
3914     gtk_widget_show(gtklist);
3915     gtk_signal_connect(GTK_OBJECT(gtklist),
3916                        "selection_changed",
3917                        GTK_SIGNAL_FUNC(sigh_print_selection),
3918                        NULL);
3919     
3920     /* we create a "Prison" to put a list item in ;)
3921      */
3922     frame=gtk_frame_new("Prison");
3923     gtk_widget_set_usize(frame, 200, 50);
3924     gtk_container_border_width(GTK_CONTAINER(frame), 5);
3925     gtk_frame_set_shadow_type(GTK_FRAME(frame), GTK_SHADOW_OUT);
3926     gtk_container_add(GTK_CONTAINER(vbox), frame);
3927     gtk_widget_show(frame);
3928     
3929     /* connect the sigh_button_event() signal handler to the GtkList
3930      * wich will handle the "arresting" of list items
3931      */
3932     gtk_signal_connect(GTK_OBJECT(gtklist),
3933                        "button_release_event",
3934                        GTK_SIGNAL_FUNC(sigh_button_event),
3935                        frame);
3936     
3937     /* create a separator
3938      */
3939     separator=gtk_hseparator_new();
3940     gtk_container_add(GTK_CONTAINER(vbox), separator);
3941     gtk_widget_show(separator);
3942     
3943     /* finaly create a button and connect it´s "clicked" signal
3944      * to the destroyment of the window
3945      */
3946     button=gtk_button_new_with_label("Close");
3947     gtk_container_add(GTK_CONTAINER(vbox), button);
3948     gtk_widget_show(button);
3949     gtk_signal_connect_object(GTK_OBJECT(button),
3950                               "clicked",
3951                               GTK_SIGNAL_FUNC(gtk_widget_destroy),
3952                               GTK_OBJECT(window));
3953     
3954     
3955     /* now we create 5 list items, each having it´s own
3956      * label and add them to the GtkList using gtk_container_add()
3957      * also we query the text string from the label and
3958      * associate it with the list_item_data_key for each list item
3959      */
3960     for (i=0; i<5; i++) {
3961         GtkWidget       *label;
3962         gchar           *string;
3963         
3964         sprintf(buffer, "ListItemContainer with Label #%d", i);
3965         label=gtk_label_new(buffer);
3966         list_item=gtk_list_item_new();
3967         gtk_container_add(GTK_CONTAINER(list_item), label);
3968         gtk_widget_show(label);
3969         gtk_container_add(GTK_CONTAINER(gtklist), list_item);
3970         gtk_widget_show(list_item);
3971         gtk_label_get(GTK_LABEL(label), &amp;string);
3972         gtk_object_set_data(GTK_OBJECT(list_item),
3973                             list_item_data_key,
3974                             string);
3975     }
3976     /* here, we are creating another 5 labels, this time
3977      * we use gtk_list_item_new_with_label() for the creation
3978      * we can´t query the text string from the label because
3979      * we don´t have the labels pointer and therefore
3980      * we just associate the list_item_data_key of each
3981      * list item with the same text string
3982      * for adding of the list items we put them all into a doubly
3983      * linked list (GList), and then add them by a single call to
3984      * gtk_list_append_items()
3985      * because we use g_list_prepend() to put the items into the
3986      * doubly linked list, their order will be descending (instead
3987      * of ascending when using g_list_append())
3988      */
3989     dlist=NULL;
3990     for (; i<10; i++) {
3991         sprintf(buffer, "List Item with Label %d", i);
3992         list_item=gtk_list_item_new_with_label(buffer);
3993         dlist=g_list_prepend(dlist, list_item);
3994         gtk_widget_show(list_item);
3995         gtk_object_set_data(GTK_OBJECT(list_item),
3996                             list_item_data_key,
3997                             "ListItem with integrated Label");
3998     }
3999     gtk_list_append_items(GTK_LIST(gtklist), dlist);
4000     
4001     /* finaly we want to see the window, don´t we? ;)
4002      */
4003     gtk_widget_show(window);
4004     
4005     /* fire up the main event loop of gtk
4006      */
4007     gtk_main();
4008     
4009     /* we get here after gtk_main_quit() has been called which
4010      * happens if the main window gets destroyed
4011      */
4012     return 0;
4013 }
4014
4015 /* this is the signal handler that got connected to button
4016  * press/release events of the GtkList
4017  */
4018 void
4019 sigh_button_event       (GtkWidget      *gtklist,
4020                          GdkEventButton *event,
4021                          GtkWidget      *frame)
4022 {
4023     /* we only do something if the third (rightmost mouse button
4024      * was released
4025      */
4026     if (event->type==GDK_BUTTON_RELEASE &amp;&amp;
4027         event->button==3) {
4028         GList           *dlist, *free_list;
4029         GtkWidget       *new_prisoner;
4030         
4031         /* fetch the currently selected list item which
4032          * will be our next prisoner ;)
4033          */
4034         dlist=GTK_LIST(gtklist)->selection;
4035         if (dlist)
4036                 new_prisoner=GTK_WIDGET(dlist->data);
4037         else
4038                 new_prisoner=NULL;
4039         
4040         /* look for already prisoned list items, we
4041          * will put them back into the list
4042          * remember to free the doubly linked list that
4043          * gtk_container_children() returns
4044          */
4045         dlist=gtk_container_children(GTK_CONTAINER(frame));
4046         free_list=dlist;
4047         while (dlist) {
4048             GtkWidget       *list_item;
4049             
4050             list_item=dlist->data;
4051             
4052             gtk_widget_reparent(list_item, gtklist);
4053             
4054             dlist=dlist->next;
4055         }
4056         g_list_free(free_list);
4057         
4058         /* if we have a new prisoner, remove him from the
4059          * GtkList and put him into the frame "Prison"
4060          * we need to unselect the item before
4061          */
4062         if (new_prisoner) {
4063             GList   static_dlist;
4064             
4065             static_dlist.data=new_prisoner;
4066             static_dlist.next=NULL;
4067             static_dlist.prev=NULL;
4068             
4069             gtk_list_unselect_child(GTK_LIST(gtklist),
4070                                     new_prisoner);
4071             gtk_widget_reparent(new_prisoner, frame);
4072         }
4073     }
4074 }
4075
4076 /* this is the signal handler that gets called if GtkList
4077  * emits the "selection_changed" signal
4078  */
4079 void
4080 sigh_print_selection    (GtkWidget      *gtklist,
4081                          gpointer       func_data)
4082 {
4083     GList   *dlist;
4084     
4085     /* fetch the doubly linked list of selected items
4086      * of the GtkList, remember to treat this as read-only!
4087      */
4088     dlist=GTK_LIST(gtklist)->selection;
4089     
4090     /* if there are no selected items there is nothing more
4091      * to do than just telling the user so
4092      */
4093     if (!dlist) {
4094         g_print("Selection cleared\n");
4095         return;
4096     }
4097     /* ok, we got a selection and so we print it
4098      */
4099     g_print("The selection is a ");
4100     
4101     /* get the list item from the doubly linked list
4102      * and then query the data associated with list_item_data_key
4103      * we then just print it
4104      */
4105     while (dlist) {
4106         GtkObject       *list_item;
4107         gchar           *item_data_string;
4108         
4109         list_item=GTK_OBJECT(dlist->data);
4110         item_data_string=gtk_object_get_data(list_item,
4111                                              list_item_data_key);
4112         g_print("%s ", item_data_string);
4113         
4114         dlist=dlist->next;
4115     }
4116     g_print("\n");
4117 }
4118 </verb></tscreen>
4119
4120 <!-- ----------------------------------------------------------------- -->
4121 <sect1> List Item Widget
4122 <p>
4123 The GtkListItem widget is designed to act as a container holding up
4124 to one child, providing functions for selection/deselection just like
4125 the GtkList widget requires them for its children.
4126
4127 A GtkListItem has its own window to receive events and has its own
4128 background color which is usualy white.  
4129
4130 As it is directly derived from a
4131 GtkItem it can be treated as such by using the GTK_ITEM(ListItem)
4132 macro, see the GtkItem widget for more on this.
4133 Usualy a GtkListItem just holds a label to identify e.g. a filename
4134 within a GtkList -- therefore the convenient function
4135 gtk_list_item_new_with_label() is provided.  The same effect can be
4136 achieved by creating a GtkLabel on its own, setting its alignment
4137 to xalign=0 and yalign=0.5 with a subsequent container addition
4138 to the GtkListItem.
4139
4140 As one is not forced to add a GtkLabel to a GtkListItem, you could
4141 also add a GtkVBox or a GtkArrow etc. to the GtkListItem.
4142
4143 <!-- ----------------------------------------------------------------- -->
4144 <sect1> Signals
4145 <p>
4146 A GtkListItem does not create new signals on its own, but inherits
4147 the signals of a GtkItem. *Note GtkItem::, for more info.
4148
4149 <!-- ----------------------------------------------------------------- -->
4150 <sect1> Functions
4151 <p>
4152
4153 <tscreen><verb>
4154 guint gtk_list_item_get_type (void)
4155 </verb></tscreen>
4156
4157 Returns the `GtkListItem' type identifier.
4158
4159 <tscreen><verb>
4160 GtkWidget* gtk_list_item_new (void)
4161 </verb></tscreen>
4162
4163 Create a new `GtkListItem' object. The new widget is
4164 returned as a pointer to a `GtkWidget' object.
4165 `NULL' is returned on failure.
4166
4167 <tscreen><verb>
4168 GtkWidget* gtk_list_item_new_with_label (gchar *LABEL)
4169 </verb></tscreen>
4170
4171 Create a new `GtkListItem' object, having a single GtkLabel as
4172 the sole child. The new widget is returned as a pointer to a
4173 `GtkWidget' object.
4174 `NULL' is returned on failure.
4175
4176 <tscreen><verb>
4177 void gtk_list_item_select (GtkListItem *LIST_ITEM)
4178 </verb></tscreen>
4179
4180 This function is basicaly a wrapper around a call to
4181 gtk_item_select (GTK_ITEM (list_item)) which will emit the
4182 select signal.
4183 *Note GtkItem::, for more info.
4184
4185 <tscreen><verb>
4186 void gtk_list_item_deselect (GtkListItem *LIST_ITEM)
4187 </verb></tscreen>
4188
4189 This function is basicaly a wrapper around a call to
4190 gtk_item_deselect (GTK_ITEM (list_item)) which will emit the
4191 deselect signal.
4192 *Note GtkItem::, for more info.
4193
4194 <tscreen><verb>
4195 GtkListItem* GTK_LIST_ITEM (gpointer OBJ)
4196 </verb></tscreen>
4197
4198 Cast a generic pointer to `GtkListItem*'. *Note Standard Macros::,
4199 for more info.
4200
4201 <tscreen><verb>
4202 GtkListItemClass* GTK_LIST_ITEM_CLASS (gpointer CLASS)
4203 </verb></tscreen>
4204
4205 Cast a generic pointer to `GtkListItemClass*'. *Note Standard
4206 Macros::, for more info.
4207
4208 <tscreen><verb>
4209 gint GTK_IS_LIST_ITEM (gpointer OBJ)
4210 </verb></tscreen>
4211
4212 Determine if a generic pointer refers to a `GtkListItem' object.
4213 *Note Standard Macros::, for more info.
4214  
4215 <!-- ----------------------------------------------------------------- -->
4216 <sect1> Example
4217 <p>
4218 Please see the GtkList example on this, which covers the usage of a
4219 GtkListItem as well.
4220
4221 <!-- ***************************************************************** -->
4222 <sect> File Selections
4223 <!-- ***************************************************************** -->
4224 <p>
4225 The file selection widget is a quick and simple way to display a File 
4226 dialog box.  It comes complete with Ok, Cancel, and Help buttons, a great way
4227 to cut down on programming time.
4228
4229 To create a new file selection box use:
4230
4231 <tscreen><verb>
4232 GtkWidget* gtk_file_selection_new (gchar *title);
4233 </verb></tscreen>
4234
4235 To set the filename, for example to bring up a specific directory, or
4236 give a default filename, use this function: 
4237
4238 <tscreen><verb>
4239 void gtk_file_selection_set_filename (GtkFileSelection *filesel, gchar *filename);
4240 </verb></tscreen>
4241
4242 To grab the text that the user has entered or clicked on, use this 
4243 function:
4244
4245 <tscreen><verb>
4246 gchar* gtk_file_selection_get_filename (GtkFileSelection *filesel);
4247 </verb></tscreen>
4248
4249 There are also pointers to the widgets contained within the file 
4250 selection widget. These are:
4251
4252 <itemize>
4253 <item>dir_list
4254 <item>file_list
4255 <item>selection_entry
4256 <item>selection_text
4257 <item>main_vbox
4258 <item>ok_button
4259 <item>cancel_button
4260 <item>help_button
4261 </itemize>
4262
4263 Most likely you will want to use the ok_button, cancel_button, and
4264 help_button pointers in signaling their use.
4265
4266 Included here is an example stolen from testgtk.c, modified to run
4267 on it's own.  As you will see, there is nothing much to creating a file 
4268 selection widget.  While, in this example, the Help button appears on the 
4269 screen, it does nothing as there is not a signal attached to it. 
4270
4271 <tscreen><verb>
4272 /* filesel.c */
4273
4274 #include <gtk/gtk.h>
4275
4276 /* Get the selected filename and print it to the console */
4277 void file_ok_sel (GtkWidget *w, GtkFileSelection *fs)
4278 {
4279     g_print ("%s\n", gtk_file_selection_get_filename (GTK_FILE_SELECTION (fs)));
4280 }
4281
4282 void destroy (GtkWidget *widget, gpointer *data)
4283 {
4284     gtk_main_quit ();
4285 }
4286
4287 int main (int argc, char *argv[])
4288 {
4289     GtkWidget *filew;
4290     
4291     gtk_init (&amp;argc, &amp;argv);
4292     
4293     /* Create a new file selection widget */
4294     filew = gtk_file_selection_new ("File selection");
4295     
4296     gtk_signal_connect (GTK_OBJECT (filew), "destroy",
4297                         (GtkSignalFunc) destroy, &amp;filew);
4298     /* Connect the ok_button to file_ok_sel function */
4299     gtk_signal_connect (GTK_OBJECT (GTK_FILE_SELECTION (filew)->ok_button),
4300                         "clicked", (GtkSignalFunc) file_ok_sel, filew );
4301     
4302     /* Connect the cancel_button to destroy the widget */
4303     gtk_signal_connect_object (GTK_OBJECT (GTK_FILE_SELECTION (filew)->cancel_button),
4304                                "clicked", (GtkSignalFunc) gtk_widget_destroy,
4305                                GTK_OBJECT (filew));
4306     
4307     /* Lets set the filename, as if this were a save dialog, and we are giving
4308      a default filename */
4309     gtk_file_selection_set_filename (GTK_FILE_SELECTION(filew), 
4310                                      "penguin.png");
4311     
4312     gtk_widget_show(filew);
4313     gtk_main ();
4314     return 0;
4315 }
4316 </verb></tscreen>
4317
4318 <!-- ***************************************************************** -->
4319 <sect>Menu Widgets
4320 <!-- ***************************************************************** -->
4321
4322 <p>
4323 There are two ways to create menus, there's the easy way, and there's the
4324 hard way.  Both have their uses, but you can usually use the menufactory
4325 (the easy way).  The "hard" way is to create all the menus using the calls
4326 directly.  The easy way is to use the gtk_menu_factory calls.  This is
4327 much simpler, but there are advantages and disadvantages to each approach.
4328
4329 The menufactory is much easier to use, and to add new menus to, although
4330 writing a few wrapper functions to create menus using the manual method 
4331 could go a long way towards usability.  With the menufactory, it is not 
4332 possible to add images or the character '/' to the menus.
4333
4334 <!-- ----------------------------------------------------------------- -->
4335 <sect1>Manual Menu Creation
4336 <p>
4337 In the true tradition of teaching, we'll show you the hard
4338 way first. <tt>:)</>
4339 <p>
4340 There are three widgets that go into making a menubar and submenus:
4341 <itemize>
4342 <item>a menu item, which is what the user wants to select, e.g. 'Save'
4343 <item>a menu, which acts as a container for the menu items, and
4344 <item>a menubar, which is a container for each of the individual menus,
4345 </itemize>
4346
4347 This is slightly complicated by the fact that menu item widgets are used for two different things. They are
4348 both the widets that are packed into the menu, and the widget that is packed into the menubar, which,
4349 when selected, activiates the menu.
4350
4351 Let's look at the functions that are used to create menus and menubars.
4352 This first function is used to create a new menubar.
4353
4354 <tscreen><verb>
4355 GtkWidget *gtk_menu_bar_new(void);
4356 </verb></tscreen>
4357
4358 This rather self explanatory function creates a new menubar.  You use
4359 gtk_container_add to pack this into a window, or the box_pack functions to
4360 pack it into a box - the same as buttons.
4361
4362 <tscreen><verb>
4363 GtkWidget *gtk_menu_new();
4364 </verb></tscreen>
4365
4366 This function returns a pointer to a new menu, it is never actually shown
4367 (with gtk_widget_show), it is just a container for the menu items.  Hopefully this will
4368 become more clear when you look at the example below.
4369 <p>
4370 The next two calls are used to create menu items that are packed into
4371 the menu (and menubar).
4372
4373 <tscreen><verb>
4374 GtkWidget *gtk_menu_item_new();
4375 </verb></tscreen>
4376
4377 and
4378
4379 <tscreen><verb>
4380 GtkWidget *gtk_menu_item_new_with_label(const char *label);
4381 </verb></tscreen>
4382
4383 These calls are used to create the menu items that are to be displayed.
4384 Remember to differentiate between a "menu" as created with gtk_menu_new
4385 and a "menu item" as created by the gtk_menu_item_new functions.  The
4386 menu item will be an actual button with an associated action,
4387 whereas a menu will be a container holding menu items.
4388
4389 The gtk_menu_new_with_label and gtk_menu_new functions are just as you'd expect after
4390 reading about the buttons.  One creates a new menu item with a label
4391 already packed into it, and the other just creates a blank menu item.
4392
4393 Once you've created a menu item you have to put it into a menu. This is done using the function
4394 gtk_menu_append. In order to capture when the item is selected by the user, we need to connect
4395 to the <tt/activate/ signal in the usual way.
4396 So, if we wanted to create a standard <tt/File/ menu, with the options <tt/Open/, 
4397 <tt/Save/ and <tt/Quit/ the code would look something like
4398
4399 <tscreen><verb>
4400 file_menu = gtk_menu_new();    /* Don't need to show menus */
4401
4402 /* Create the menu items */
4403 open_item = gtk_menu_item_new_with_label("Open");
4404 save_item = gtk_menu_item_new_with_label("Save");
4405 quit_item = gtk_menu_item_new_with_label("Quit");
4406
4407 /* Add them to the menu */
4408 gtk_menu_append( GTK_MENU(file_menu), open_item);
4409 gtk_menu_append( GTK_MENU(file_menu), save_item);
4410 gtk_menu_append( GTK_MENU(file_menu), quit_item);
4411
4412 /* Attach the callback functions to the activate signal */
4413 gtk_signal_connect_object( GTK_OBJECT(open_items), "activate",
4414                            GTK_SIGNAL_FUNC(menuitem_response), (gpointer) "file.open");
4415 gtk_signal_connect_object( GTK_OBJECT(save_items), "activate",
4416                            GTK_SIGNAL_FUNC(menuitem_response), (gpointer) "file.save");
4417
4418 /* We can attach the Quit menu item to our exit function */
4419 gtk_signal_connect_object( GTK_OBJECT(quit_items), "activate",
4420                            GTK_SIGNAL_FUNC(destroy), (gpointer) "file.quit");
4421
4422 /* We do need to show menu items */
4423 gtk_widget_show( open_item );
4424 gtk_widget_show( save_item );
4425 gtk_widget_show( quit_item );
4426 </verb></tscreen>
4427
4428 At this point we have our menu. Now we need to create a menubar and a menu item for the <tt/File/ entry,
4429 to which we add our menu. The code looks like this 
4430
4431 <tscreen><verb>
4432 menu_bar = gtk_menu_bar_new();
4433 gtk_container_add( GTK_CONTAINER(window), menu_bar);
4434 gtk_widget_show( menu_bar );
4435
4436 file_item = gtk_menu_item_new_with_label("File");
4437 gtk_widget_show(file_item);
4438 </verb></tscreen>
4439
4440 Now we need to associate the menu with <tt/file_item/. This is done with the function
4441
4442 <tscreen>
4443 void gtk_menu_item_set_submenu( GtkMenuItem *menu_item,
4444                                 GtkWidget *submenu);
4445 </tscreen>
4446
4447 So, our example would continue with
4448
4449 <tscreen><verb>
4450 gtk_menu_item_set_submenu( GTK_MENU_ITEM(file_item), file_menu);
4451 </verb></tscreen>
4452
4453 All that is left to do is to add the menu to the menubar, which is accomplished using the function
4454
4455 <tscreen>
4456 void gtk_menu_bar_append( GtkMenuBar *menu_bar, GtkWidget *menu_item);
4457 </tscreen>
4458
4459 which in our case looks like this:
4460
4461 <tscreen><verb>
4462 gtk_menu_bar_append( menu_bar, file_item );
4463 </verb></tscreen>
4464
4465 If we wanted the menu right justified on the menubar, such as help menus often are, we can
4466 use the following function (again on <tt/file_item/ in the current example) before attaching 
4467 it to the menubar.
4468 <tscreen><verb>
4469 void gtk_menu_item_right_justify (GtkMenuItem *menu_item);
4470 </verb></tscreen>
4471
4472 Here is a summary of the steps needed to create a menu bar with menus attached:
4473 <itemize>
4474 <item>  Create a new menu using gtk_menu_new()
4475 <item>  Use multiple calls to gtk_menu_item_new() for each item you wish to have on
4476   your menu.  And use gtk_menu_append() to put each of these new items on
4477   to the menu.
4478 <item>  Create a menu item using gtk_menu_item_new().  This will be the root of
4479   the menu, the text appearing here will be on the menubar itself.
4480 <item>  Use gtk_menu_item_set_submenu() to attach the menu to
4481   the root menu item (The one created in the above step).
4482 <item>  Create a new menubar using gtk_menu_bar_new.  This step only needs
4483   to be done once when creating a series of menus on one menu bar.
4484 <item> Use gtk_menu_bar_append to put the root menu onto the menubar.
4485 </itemize>
4486 <p>
4487 Creating a popup menu is nearly the same.  The difference is that the
4488 menu is not posted `automatically' by a menubar, but explicitly
4489 by calling the function gtk_menu_popup() from a button-press event, for example.
4490 Take these steps:
4491 <itemize>
4492 <item>Create an event handling function.  It needs to have the prototype
4493 <tscreen>
4494 static gint handler(GtkWidget *widget, GdkEvent *event);
4495 </tscreen>
4496 and it will use the event to find out where to pop up the menu.
4497 <item>In the event handler, if event is a mouse button press, treat
4498 <tt>event</tt> as a button event (which it is) and use it as
4499 shown in the sample code to pass information to gtk_menu_popup().
4500 <item>Bind that event handler to a widget with
4501 <tscreen>
4502 gtk_signal_connect_object(GTK_OBJECT(widget), "event",
4503                           GTK_SIGNAL_FUNC (handler), GTK_OBJECT(menu));
4504 </tscreen>
4505 where <tt>widget</tt> is the widget you are binding to, <tt>handler</tt>
4506 is the handling function, and <tt>menu</tt> is a menu created with
4507 gtk_menu_new().  This can be a menu which is also posted by a menu bar,
4508 as shown in the sample code.
4509 </itemize>
4510
4511 <!-- ----------------------------------------------------------------- -->
4512 <sect1>Manual Menu Example
4513 <p>
4514 That should about do it.  Let's take a look at an example to help clarify.
4515
4516 <tscreen><verb>
4517 /* menu.c */
4518
4519 #include <gtk/gtk.h>
4520
4521 static gint button_press (GtkWidget *, GdkEvent *);
4522 static void menuitem_response (gchar *);
4523
4524 int main (int argc, char *argv[])
4525 {
4526
4527     GtkWidget *window;
4528     GtkWidget *menu;
4529     GtkWidget *menu_bar;
4530     GtkWidget *root_menu;
4531     GtkWidget *menu_items;
4532     GtkWidget *vbox;
4533     GtkWidget *button;
4534     char buf[128];
4535     int i;
4536
4537     gtk_init (&amp;argc, &amp;argv);
4538
4539     /* create a new window */
4540     window = gtk_window_new(GTK_WINDOW_TOPLEVEL);
4541     gtk_widget_set_usize( GTK_WIDGET (window), 200, 100);
4542     gtk_window_set_title(GTK_WINDOW (window), "GTK Menu Test");
4543     gtk_signal_connect(GTK_OBJECT (window), "delete_event",
4544                        (GtkSignalFunc) gtk_exit, NULL);
4545
4546     /* Init the menu-widget, and remember -- never
4547      * gtk_show_widget() the menu widget!! 
4548      * This is the menu that holds the menu items, the one that
4549      * will pop up when you click on the "Root Menu" in the app */
4550     menu = gtk_menu_new();
4551
4552     /* Next we make a little loop that makes three menu-entries for "test-menu".
4553      * Notice the call to gtk_menu_append.  Here we are adding a list of
4554      * menu items to our menu.  Normally, we'd also catch the "clicked"
4555      * signal on each of the menu items and setup a callback for it,
4556      * but it's omitted here to save space. */
4557
4558     for(i = 0; i < 3; i++)
4559         {
4560             /* Copy the names to the buf. */
4561             sprintf(buf, "Test-undermenu - %d", i);
4562
4563             /* Create a new menu-item with a name... */
4564             menu_items = gtk_menu_item_new_with_label(buf);
4565
4566             /* ...and add it to the menu. */
4567             gtk_menu_append(GTK_MENU (menu), menu_items);
4568
4569             /* Do something interesting when the menuitem is selected */
4570             gtk_signal_connect_object(GTK_OBJECT(menu_items), "activate",
4571                 GTK_SIGNAL_FUNC(menuitem_response), (gpointer) g_strdup(buf));
4572
4573             /* Show the widget */
4574             gtk_widget_show(menu_items);
4575         }
4576
4577     /* This is the root menu, and will be the label
4578      * displayed on the menu bar.  There won't be a signal handler attached,
4579      * as it only pops up the rest of the menu when pressed. */
4580     root_menu = gtk_menu_item_new_with_label("Root Menu");
4581
4582     gtk_widget_show(root_menu);
4583
4584     /* Now we specify that we want our newly created "menu" to be the menu
4585      * for the "root menu" */
4586     gtk_menu_item_set_submenu(GTK_MENU_ITEM (root_menu), menu);
4587
4588     /* A vbox to put a menu and a button in: */
4589     vbox = gtk_vbox_new(FALSE, 0);
4590     gtk_container_add(GTK_CONTAINER(window), vbox);
4591     gtk_widget_show(vbox);
4592
4593     /* Create a menu-bar to hold the menus and add it to our main window */
4594     menu_bar = gtk_menu_bar_new();
4595     gtk_box_pack_start(GTK_BOX(vbox), menu_bar, FALSE, FALSE, 2);
4596     gtk_widget_show(menu_bar);
4597
4598     /* Create a button to which to attach menu as a popup */
4599     button = gtk_button_new_with_label("press me");
4600     gtk_signal_connect_object(GTK_OBJECT(button), "event",
4601         GTK_SIGNAL_FUNC (button_press), GTK_OBJECT(menu));
4602     gtk_box_pack_end(GTK_BOX(vbox), button, TRUE, TRUE, 2);
4603     gtk_widget_show(button);
4604
4605     /* And finally we append the menu-item to the menu-bar -- this is the
4606      * "root" menu-item I have been raving about =) */
4607     gtk_menu_bar_append(GTK_MENU_BAR (menu_bar), root_menu);
4608
4609     /* always display the window as the last step so it all splashes on
4610      * the screen at once. */
4611     gtk_widget_show(window);
4612
4613     gtk_main ();
4614
4615     return 0;
4616 }
4617
4618
4619
4620 /* Respond to a button-press by posting a menu passed in as widget.
4621  *
4622  * Note that the "widget" argument is the menu being posted, NOT
4623  * the button that was pressed.
4624  */
4625
4626 static gint button_press (GtkWidget *widget, GdkEvent *event)
4627 {
4628
4629     if (event->type == GDK_BUTTON_PRESS) {
4630         GdkEventButton *bevent = (GdkEventButton *) event; 
4631         gtk_menu_popup (GTK_MENU(widget), NULL, NULL, NULL, NULL,
4632                         bevent->button, bevent->time);
4633         /* Tell calling code that we have handled this event; the buck
4634          * stops here. */
4635         return TRUE;
4636     }
4637
4638     /* Tell calling code that we have not handled this event; pass it on. */
4639     return FALSE;
4640 }
4641
4642
4643 /* Print a string when a menu item is selected */
4644
4645 static void menuitem_response (gchar *string)
4646 {
4647     printf("%s\n", string);
4648 }
4649 </verb></tscreen>
4650
4651 You may also set a menu item to be insensitive and, using an accelerator
4652 table, bind keys to menu functions.
4653
4654 <!-- ----------------------------------------------------------------- -->
4655 <sect1>Using GtkMenuFactory
4656 <p>
4657 Now that we've shown you the hard way, here's how you do it using the
4658 gtk_menu_factory calls.
4659
4660 <!-- ----------------------------------------------------------------- -->
4661 <sect1>Menu Factory Example
4662 <p>
4663 Here is an example using the GTK menu factory.  This is the first file,
4664 menufactory.h.  We keep a separate menufactory.c and mfmain.c because of the global variables used
4665 in the menufactory.c file.  
4666
4667 <tscreen><verb>
4668 /* menufactory.h */
4669
4670 #ifndef __MENUFACTORY_H__
4671 #define __MENUFACTORY_H__
4672
4673 #ifdef __cplusplus
4674 extern "C" {
4675 #endif /* __cplusplus */
4676
4677 void get_main_menu (GtkWidget **menubar, GtkAcceleratorTable **table);
4678 void menus_create(GtkMenuEntry *entries, int nmenu_entries);
4679
4680 #ifdef __cplusplus
4681 }
4682 #endif /* __cplusplus */
4683
4684 #endif /* __MENUFACTORY_H__ */
4685 </verb></tscreen>
4686 <p>
4687 And here is the menufactory.c file.
4688
4689 <tscreen><verb>
4690 /* menufactory.c */
4691
4692 #include <gtk/gtk.h>
4693 #include <strings.h>
4694
4695 #include "mfmain.h"
4696
4697
4698 static void menus_remove_accel(GtkWidget * widget, gchar * signal_name, gchar * path);
4699 static gint menus_install_accel(GtkWidget * widget, gchar * signal_name, gchar key, gchar modifiers, gchar * path);
4700 void menus_init(void);
4701 void menus_create(GtkMenuEntry * entries, int nmenu_entries);
4702
4703
4704 /* this is the GtkMenuEntry structure used to create new menus.  The
4705  * first member is the menu definition string.  The second, the
4706  * default accelerator key used to access this menu function with
4707  * the keyboard.  The third is the callback function to call when
4708  * this menu item is selected (by the accelerator key, or with the
4709  * mouse.) The last member is the data to pass to your callback function.
4710  */
4711
4712 static GtkMenuEntry menu_items[] =
4713 {
4714         {"<Main>/File/New", "<control>N", NULL, NULL},
4715         {"<Main>/File/Open", "<control>O", NULL, NULL},
4716         {"<Main>/File/Save", "<control>S", NULL, NULL},
4717         {"<Main>/File/Save as", NULL, NULL, NULL},
4718         {"<Main>/File/<separator>", NULL, NULL, NULL},
4719         {"<Main>/File/Quit", "<control>Q", file_quit_cmd_callback, "OK, I'll quit"},
4720         {"<Main>/Options/Test", NULL, NULL, NULL}
4721 };
4722
4723 /* calculate the number of menu_item's */
4724 static int nmenu_items = sizeof(menu_items) / sizeof(menu_items[0]);
4725
4726 static int initialize = TRUE;
4727 static GtkMenuFactory *factory = NULL;
4728 static GtkMenuFactory *subfactory[1];
4729 static GHashTable *entry_ht = NULL;
4730
4731 void get_main_menu(GtkWidget ** menubar, GtkAcceleratorTable ** table)
4732 {
4733     if (initialize)
4734             menus_init();
4735     
4736     if (menubar)
4737             *menubar = subfactory[0]->widget;
4738     if (table)
4739             *table = subfactory[0]->table;
4740 }
4741
4742 void menus_init(void)
4743 {
4744     if (initialize) {
4745         initialize = FALSE;
4746         
4747         factory = gtk_menu_factory_new(GTK_MENU_FACTORY_MENU_BAR);
4748         subfactory[0] = gtk_menu_factory_new(GTK_MENU_FACTORY_MENU_BAR);
4749         
4750         gtk_menu_factory_add_subfactory(factory, subfactory[0], "<Main>");
4751         menus_create(menu_items, nmenu_items);
4752     }
4753 }
4754
4755 void menus_create(GtkMenuEntry * entries, int nmenu_entries)
4756 {
4757     char *accelerator;
4758     int i;
4759     
4760     if (initialize)
4761             menus_init();
4762     
4763     if (entry_ht)
4764             for (i = 0; i < nmenu_entries; i++) {
4765                 accelerator = g_hash_table_lookup(entry_ht, entries[i].path);
4766                 if (accelerator) {
4767                     if (accelerator[0] == '\0')
4768                             entries[i].accelerator = NULL;
4769                     else
4770                             entries[i].accelerator = accelerator;
4771                 }
4772             }
4773     gtk_menu_factory_add_entries(factory, entries, nmenu_entries);
4774     
4775     for (i = 0; i < nmenu_entries; i++)
4776             if (entries[i].widget) {
4777                 gtk_signal_connect(GTK_OBJECT(entries[i].widget), "install_accelerator",
4778                                    (GtkSignalFunc) menus_install_accel,
4779                                    entries[i].path);
4780                 gtk_signal_connect(GTK_OBJECT(entries[i].widget), "remove_accelerator",
4781                                    (GtkSignalFunc) menus_remove_accel,
4782                                    entries[i].path);
4783             }
4784 }
4785
4786 static gint menus_install_accel(GtkWidget * widget, gchar * signal_name, gchar key, gchar modifiers, gchar * path)
4787 {
4788     char accel[64];
4789     char *t1, t2[2];
4790     
4791     accel[0] = '\0';
4792     if (modifiers & GDK_CONTROL_MASK)
4793             strcat(accel, "<control>");
4794     if (modifiers & GDK_SHIFT_MASK)
4795             strcat(accel, "<shift>");
4796     if (modifiers & GDK_MOD1_MASK)
4797             strcat(accel, "<alt>");
4798     
4799     t2[0] = key;
4800     t2[1] = '\0';
4801     strcat(accel, t2);
4802     
4803     if (entry_ht) {
4804         t1 = g_hash_table_lookup(entry_ht, path);
4805         g_free(t1);
4806     } else
4807             entry_ht = g_hash_table_new(g_str_hash, g_str_equal);
4808     
4809     g_hash_table_insert(entry_ht, path, g_strdup(accel));
4810     
4811     return TRUE;
4812 }
4813
4814 static void menus_remove_accel(GtkWidget * widget, gchar * signal_name, gchar * path)
4815 {
4816     char *t;
4817     
4818     if (entry_ht) {
4819         t = g_hash_table_lookup(entry_ht, path);
4820         g_free(t);
4821         
4822         g_hash_table_insert(entry_ht, path, g_strdup(""));
4823     }
4824 }
4825
4826 void menus_set_sensitive(char *path, int sensitive)
4827 {
4828     GtkMenuPath *menu_path;
4829     
4830     if (initialize)
4831             menus_init();
4832     
4833     menu_path = gtk_menu_factory_find(factory, path);
4834     if (menu_path)
4835             gtk_widget_set_sensitive(menu_path->widget, sensitive);
4836     else
4837             g_warning("Unable to set sensitivity for menu which doesn't exist: %s", path);
4838 }
4839
4840 </verb></tscreen>
4841 <p>
4842 And here's the mfmain.h
4843
4844 <tscreen><verb>
4845 /* mfmain.h */
4846
4847 #ifndef __MFMAIN_H__
4848 #define __MFMAIN_H__
4849
4850
4851 #ifdef __cplusplus
4852 extern "C" {
4853 #endif /* __cplusplus */
4854
4855 void file_quit_cmd_callback(GtkWidget *widget, gpointer data);
4856
4857 #ifdef __cplusplus
4858 }
4859 #endif /* __cplusplus */
4860
4861 #endif /* __MFMAIN_H__ */
4862 </verb></tscreen>
4863 <p>
4864 And mfmain.c
4865
4866 <tscreen><verb>
4867 /* mfmain.c */
4868
4869 #include <gtk/gtk.h>
4870
4871 #include "mfmain.h"
4872 #include "menufactory.h"
4873
4874
4875 int main(int argc, char *argv[])
4876 {
4877     GtkWidget *window;
4878     GtkWidget *main_vbox;
4879     GtkWidget *menubar;
4880     
4881     GtkAcceleratorTable *accel;
4882     
4883     gtk_init(&amp;argc, &amp;argv);
4884     
4885     window = gtk_window_new(GTK_WINDOW_TOPLEVEL);
4886     gtk_signal_connect(GTK_OBJECT(window), "destroy", 
4887                        GTK_SIGNAL_FUNC(file_quit_cmd_callback), 
4888                        "WM destroy");
4889     gtk_window_set_title(GTK_WINDOW(window), "Menu Factory");
4890     gtk_widget_set_usize(GTK_WIDGET(window), 300, 200);
4891     
4892     main_vbox = gtk_vbox_new(FALSE, 1);
4893     gtk_container_border_width(GTK_CONTAINER(main_vbox), 1);
4894     gtk_container_add(GTK_CONTAINER(window), main_vbox);
4895     gtk_widget_show(main_vbox);
4896     
4897     get_main_menu(&amp;menubar, &amp;accel);
4898     gtk_window_add_accelerator_table(GTK_WINDOW(window), accel);
4899     gtk_box_pack_start(GTK_BOX(main_vbox), menubar, FALSE, TRUE, 0);
4900     gtk_widget_show(menubar);
4901     
4902     gtk_widget_show(window);
4903     gtk_main();
4904     
4905     return(0);
4906 }
4907
4908 /* This is just to demonstrate how callbacks work when using the
4909  * menufactory.  Often, people put all the callbacks from the menus
4910  * in a separate file, and then have them call the appropriate functions
4911  * from there.  Keeps it more organized. */
4912 void file_quit_cmd_callback (GtkWidget *widget, gpointer data)
4913 {
4914     g_print ("%s\n", (char *) data);
4915     gtk_exit(0);
4916 }
4917 </verb></tscreen>
4918 <p>
4919 And a makefile so it'll be easier to compile it.
4920
4921 <tscreen><verb>
4922 # Makefile.mf
4923
4924 CC      = gcc
4925 PROF    = -g
4926 C_FLAGS =  -Wall $(PROF) -L/usr/local/include -DDEBUG
4927 L_FLAGS =  $(PROF) -L/usr/X11R6/lib -L/usr/local/lib 
4928 L_POSTFLAGS = -lgtk -lgdk -lglib -lXext -lX11 -lm
4929 PROGNAME = menufactory
4930
4931 O_FILES = menufactory.o mfmain.o
4932
4933 $(PROGNAME): $(O_FILES)
4934         rm -f $(PROGNAME)
4935         $(CC) $(L_FLAGS) -o $(PROGNAME) $(O_FILES) $(L_POSTFLAGS)
4936
4937 .c.o: 
4938         $(CC) -c $(C_FLAGS) $<
4939
4940 clean: 
4941         rm -f core *.o $(PROGNAME) nohup.out
4942 distclean: clean 
4943         rm -f *~
4944 </verb></tscreen>
4945 <p>
4946 For now, there's only this example.  An explanation and lots 'o' comments
4947 will follow later.
4948
4949 <!-- ***************************************************************** -->
4950 <sect> Undocumented Widgets
4951 <!-- ***************************************************************** -->
4952
4953 <p>
4954 These all require authors! :)  Please consider contributing to our tutorial.
4955
4956 If you must use one of these widgets that are undocumented, I strongly
4957 suggest you take a look at their respective header files in the GTK distro.
4958 GTK's function names are very descriptive.  Once you have an understanding
4959 of how things work, it's not easy to figure out how to use a widget simply
4960 by looking at it's function declarations.  This, along with a few examples
4961 from others' code, and it should be no problem.
4962
4963 When you do come to understand all the functions of a new undocumented
4964 widget, please consider writing a tutorial on it so others may benifit from
4965 your time.
4966
4967 <!-- ----------------------------------------------------------------- -->
4968 <sect1> Color Selections
4969
4970 <!-- ----------------------------------------------------------------- -->
4971 <sect1> Range Controls
4972
4973 <!-- ----------------------------------------------------------------- -->
4974 <sect1> Text Boxes
4975 <p>
4976
4977 <!-- ----------------------------------------------------------------- -->
4978 <sect1> Previews
4979 <p>
4980
4981 (This may need to be rewritten to follow the style of the rest of the tutorial)
4982
4983 <tscreen><verb>
4984
4985 Previews serve a number of purposes in GIMP/GTK. The most important one is
4986 this. High quality images may take up to tens of megabytes of memory - easy!
4987 Any operation on an image that big is bound to take a long time. If it takes
4988 you 5-10 trial-and-errors (i.e. 10-20 steps, since you have to revert after
4989 you make an error) to choose the desired modification, it make take you
4990 literally hours to make the right one - if you don't run out of memory
4991 first. People who have spent hours in color darkrooms know the feeling.
4992 Previews to the rescue!
4993
4994 But the annoyance of the delay is not the only issue. Oftentimes it is
4995 helpful to compare the Before and After versions side-by-side or at least
4996 back-to-back. If you're working with big images and 10 second delays,
4997 obtaining the Before and After impressions is, to say the least, difficult.
4998 For 30M images (4"x6", 600dpi, 24 bit) the side-by-side comparison is right
4999 out for most people, while back-to-back is more like back-to-1001, 1002,
5000 ..., 1010-back! Previews to the rescue!
5001
5002 But there's more. Previews allow for side-by-side pre-previews. In other
5003 words, you write a plug-in (e.g. the filterpack simulation) which would have
5004 a number of here's-what-it-would-look-like-if-you-were-to-do-this previews.
5005 An approach like this acts as a sort of a preview palette and is very
5006 effective fow subtle changes. Let's go previews!
5007
5008 There's more. For certain plug-ins real-time image-specific human
5009 intervention maybe necessary. In the SuperNova plug-in, for example, the
5010 user is asked to enter the coordinates of the center of the future
5011 supernova. The easiest way to do this, really, is to present the user with a
5012 preview and ask him to intereactively select the spot. Let's go previews!
5013
5014 Finally, a couple of misc uses. One can use previews even when not working
5015 with big images. For example, they are useful when rendering compicated
5016 patterns. (Just check out the venerable Diffraction plug-in + many other
5017 ones!) As another example, take a look at the colormap rotation plug-in
5018 (work in progress). You can also use previews for little logo's inside you
5019 plug-ins and even for an image of yourself, The Author. Let's go previews!
5020
5021 When Not to Use Previews
5022
5023 Don't use previews for graphs, drawing etc. GDK is much faster for that. Use
5024 previews only for rendered images!
5025
5026 Let's go previews!
5027
5028 You can stick a preview into just about anything. In a vbox, an hbox, a
5029 table, a button, etc. But they look their best in tight frames around them.
5030 Previews by themselves do not have borders and look flat without them. (Of
5031 course, if the flat look is what you want...) Tight frames provide the
5032 necessary borders.
5033
5034                                [Image][Image]
5035
5036 Previews in many ways are like any other widgets in GTK (whatever that
5037 means) except they possess an addtional feature: they need to be filled with
5038 some sort of an image! First, we will deal exclusively with the GTK aspect
5039 of previews and then we'll discuss how to fill them.
5040
5041 GtkWidget *preview!
5042
5043 Without any ado:
5044
5045                               /* Create a preview widget,
5046                               set its size, an show it */
5047 GtkWidget *preview;
5048 preview=gtk_preview_new(GTK_PREVIEW_COLOR)
5049                               /*Other option:
5050                               GTK_PREVIEW_GRAYSCALE);*/
5051 gtk_preview_size (GTK_PREVIEW (preview), WIDTH, HEIGHT);
5052 gtk_widget_show(preview);
5053 my_preview_rendering_function(preview);
5054
5055 Oh yeah, like I said, previews look good inside frames, so how about:
5056
5057 GtkWidget *create_a_preview(int        Width,
5058                             int        Height,
5059                             int        Colorfulness)
5060 {
5061   GtkWidget *preview;
5062   GtkWidget *frame;
5063   
5064   frame = gtk_frame_new(NULL);
5065   gtk_frame_set_shadow_type (GTK_FRAME (frame), GTK_SHADOW_IN);
5066   gtk_container_border_width (GTK_CONTAINER(frame),0);
5067   gtk_widget_show(frame);
5068
5069   preview=gtk_preview_new (Colorfulness?GTK_PREVIEW_COLOR
5070                                        :GTK_PREVIEW_GRAYSCALE);
5071   gtk_preview_size (GTK_PREVIEW (preview), Width, Height);
5072   gtk_container_add(GTK_CONTAINER(frame),preview);
5073   gtk_widget_show(preview);
5074
5075   my_preview_rendering_function(preview);
5076   return frame;
5077 }
5078
5079 That's my basic preview. This routine returns the "parent" frame so you can
5080 place it somewhere else in your interface. Of course, you can pass the
5081 parent frame to this routine as a parameter. In many situations, however,
5082 the contents of the preview are changed continually by your application. In
5083 this case you may want to pass a pointer to the preview to a
5084 "create_a_preview()" and thus have control of it later.
5085
5086 One more important note that may one day save you a lot of time. Sometimes
5087 it is desirable to label you preview. For example, you may label the preview
5088 containing the original image as "Original" and the one containing the
5089 modified image as "Less Original". It might occure to you to pack the
5090 preview along with the appropriate label into a vbox. The unexpected caveat
5091 is that if the label is wider than the preview (which may happen for a
5092 variety of reasons unforseeable to you, from the dynamic decision on the
5093 size of the preview to the size of the font) the frame expands and no longer
5094 fits tightly over the preview. The same problem can probably arise in other
5095 situations as well.
5096
5097                                    [Image]
5098
5099 The solution is to place the preview and the label into a 2x1 table and by
5100 attaching them with the following paramters (this is one possible variations
5101 of course. The key is no GTK_FILL in the second attachment):
5102
5103 gtk_table_attach(GTK_TABLE(table),label,0,1,0,1,
5104                  0,
5105                  GTK_EXPAND|GTK_FILL,
5106                  0,0);
5107 gtk_table_attach(GTK_TABLE(table),frame,0,1,1,2,
5108                  GTK_EXPAND,
5109                  GTK_EXPAND,
5110                  0,0);
5111
5112
5113 And here's the result:
5114
5115                                    [Image]
5116
5117 Misc
5118
5119 Making a preview clickable is achieved most easily by placing it in a
5120 button. It also adds a nice border around the preview and you may not even
5121 need to place it in a frame. See the Filter Pack Simulation plug-in for an
5122 example.
5123
5124 This is pretty much it as far as GTK is concerned.
5125
5126 Filling In a Preview
5127
5128 In order to familiarize ourselves with the basics of filling in previews,
5129 let's create the following pattern (contrived by trial and error):
5130
5131                                    [Image]
5132
5133 void
5134 my_preview_rendering_function(GtkWidget     *preview)
5135 {
5136 #define SIZE 100
5137 #define HALF (SIZE/2)
5138
5139   guchar *row=(guchar *) malloc(3*SIZE); /* 3 bits per dot */
5140   gint i, j;                             /* Coordinates    */
5141   double r, alpha, x, y;
5142
5143   if (preview==NULL) return; /* I usually add this when I want */
5144                              /* to avoid silly crashes. You    */
5145                              /* should probably make sure that */
5146                              /* everything has been nicely     */
5147                              /* initialized!                   */
5148   for (j=0; j < ABS(cos(2*alpha)) ) { /* Are we inside the shape?  */
5149                                          /* glib.h contains ABS(x).   */
5150         row[i*3+0] = sqrt(1-r)*255;      /* Define Red                */
5151         row[i*3+1] = 128;                /* Define Green              */
5152         row[i*3+2] = 224;                /* Define Blue               */
5153       }                                  /* "+0" is for alignment!    */
5154       else {
5155         row[i*3+0] = r*255;
5156         row[i*3+1] = ABS(sin((float)i/SIZE*2*PI))*255;
5157         row[i*3+2] = ABS(sin((float)j/SIZE*2*PI))*255;
5158       }
5159     }
5160     gtk_preview_draw_row( GTK_PREVIEW(preview),row,0,j,SIZE);
5161     /* Insert "row" into "preview" starting at the point with  */
5162     /* coordinates (0,j) first column, j_th row extending SIZE */
5163     /* pixels to the right */
5164   }
5165
5166   free(row); /* save some space */
5167   gtk_widget_draw(preview,NULL); /* what does this do? */
5168   gdk_flush(); /* or this? */
5169 }
5170
5171 Non-GIMP users can have probably seen enough to do a lot of things already.
5172 For the GIMP users I have a few pointers to add.
5173
5174 Image Preview
5175
5176 It is probably wize to keep a reduced version of the image around with just
5177 enough pixels to fill the preview. This is done by selecting every n'th
5178 pixel where n is the ratio of the size of the image to the size of the
5179 preview. All further operations (including filling in the previews) are then
5180 performed on the reduced number of pixels only. The following is my
5181 implementation of reducing the image. (Keep in mind that I've had only basic
5182 C!)
5183
5184 (UNTESTED CODE ALERT!!!)
5185
5186 typedef struct {
5187   gint      width;
5188   gint      height;
5189   gint      bbp;
5190   guchar    *rgb;
5191   guchar    *mask;
5192 } ReducedImage;
5193
5194 enum {
5195   SELECTION_ONLY,
5196   SELCTION_IN_CONTEXT,
5197   ENTIRE_IMAGE
5198 };
5199
5200 ReducedImage *Reduce_The_Image(GDrawable *drawable,
5201                                GDrawable *mask,
5202                                gint LongerSize,
5203                                gint Selection)
5204 {
5205   /* This function reduced the image down to the the selected preview size */
5206   /* The preview size is determine by LongerSize, i.e. the greater of the  */
5207   /* two dimentions. Works for RGB images only!                            */
5208   gint RH, RW;          /* Reduced height and reduced width                */
5209   gint width, height;   /* Width and Height of the area being reduced      */
5210   gint bytes=drawable->bpp;
5211   ReducedImage *temp=(ReducedImage *)malloc(sizeof(ReducedImage));
5212
5213   guchar *tempRGB, *src_row, *tempmask, *src_mask_row,R,G,B;
5214   gint i, j, whichcol, whichrow, x1, x2, y1, y2;
5215   GPixelRgn srcPR, srcMask;
5216   gint NoSelectionMade=TRUE; /* Assume that we're dealing with the entire  */
5217                              /* image.                                     */
5218
5219   gimp_drawable_mask_bounds (drawable->id, &amp;x1, &amp;y1, &amp;x2, &amp;y2);
5220   width  = x2-x1;
5221   height = y2-y1;
5222   /* If there's a SELECTION, we got its bounds!)
5223
5224   if (width != drawable->width &amp;&amp; height != drawable->height)
5225     NoSelectionMade=FALSE;
5226   /* Become aware of whether the user has made an active selection   */
5227   /* This will become important later, when creating a reduced mask. */
5228
5229   /* If we want to preview the entire image, overrule the above!  */
5230   /* Of course, if no selection has been made, this does nothing! */
5231   if (Selection==ENTIRE_IMAGE) {
5232     x1=0;
5233     x2=drawable->width;
5234     y1=0;
5235     y2=drawable->height;
5236   }
5237
5238   /* If we want to preview a selection with some surronding area we */
5239   /* have to expand it a little bit. Consider it a bit of a riddle. */
5240   if (Selection==SELECTION_IN_CONTEXT) {
5241     x1=MAX(0,                x1-width/2.0);
5242     x2=MIN(drawable->width,  x2+width/2.0);
5243     y1=MAX(0,                y1-height/2.0);
5244     y2=MIN(drawable->height, y2+height/2.0);
5245   }
5246
5247   /* How we can determine the width and the height of the area being */
5248   /* reduced.                                                        */
5249   width  = x2-x1;
5250   height = y2-y1;
5251
5252   /* The lines below determine which dimension is to be the longer   */
5253   /* side. The idea borrowed from the supernova plug-in. I suspect I */
5254   /* could've thought of it myself, but the truth must be told.      */
5255   /* Plagiarism stinks!                                               */
5256   if (width>height) {
5257     RW=LongerSize;
5258     RH=(float) height * (float) LongerSize/ (float) width;
5259   }
5260   else {
5261     RH=LongerSize;
5262     RW=(float)width * (float) LongerSize/ (float) height;
5263   }
5264
5265   /* The intire image is stretched into a string! */
5266   tempRGB   = (guchar *) malloc(RW*RH*bytes);
5267   tempmask  = (guchar *) malloc(RW*RH);
5268
5269   gimp_pixel_rgn_init (&amp;srcPR, drawable, x1, y1, width, height, FALSE, FALSE);
5270   gimp_pixel_rgn_init (&amp;srcMask, mask, x1, y1, width, height, FALSE, FALSE);
5271
5272   /* Grab enough to save a row of image and a row of mask. */
5273   src_row       = (guchar *) malloc (width*bytes);
5274   src_mask_row  = (guchar *) malloc (width);
5275
5276   for (i=0; i < RH; i++) {
5277     whichrow=(float)i*(float)height/(float)RH;
5278     gimp_pixel_rgn_get_row (&amp;srcPR, src_row, x1, y1+whichrow, width);
5279     gimp_pixel_rgn_get_row (&amp;srcMask, src_mask_row, x1, y1+whichrow, width);
5280
5281     for (j=0; j < RW; j++) {
5282       whichcol=(float)j*(float)width/(float)RW;
5283
5284       /* No selection made = each point is completely selected! */
5285       if (NoSelectionMade)
5286         tempmask[i*RW+j]=255;
5287       else
5288         tempmask[i*RW+j]=src_mask_row[whichcol];
5289
5290       /* Add the row to the one long string which now contains the image! */
5291       tempRGB[i*RW*bytes+j*bytes+0]=src_row[whichcol*bytes+0];
5292       tempRGB[i*RW*bytes+j*bytes+1]=src_row[whichcol*bytes+1];
5293       tempRGB[i*RW*bytes+j*bytes+2]=src_row[whichcol*bytes+2];
5294
5295       /* Hold on to the alpha as well */
5296       if (bytes==4)
5297         tempRGB[i*RW*bytes+j*bytes+3]=src_row[whichcol*bytes+3];
5298     }
5299   }
5300   temp->bpp=bytes;
5301   temp->width=RW;
5302   temp->height=RH;
5303   temp->rgb=tempRGB;
5304   temp->mask=tempmask;
5305   return temp;
5306 }
5307
5308 The following is a preview function which used the same ReducedImage type!
5309 Note that it uses fakes transparancy (if one is present by means of
5310 fake_transparancy which is defined as follows:
5311
5312 gint fake_transparency(gint i, gint j)
5313 {
5314   if ( ((i%20)- 10) * ((j%20)- 10)>0   )
5315     return 64;
5316   else
5317     return 196;
5318 }
5319
5320 Now here's the preview function:
5321
5322 void
5323 my_preview_render_function(GtkWidget     *preview,
5324                            gint          changewhat,
5325                            gint          changewhich)
5326 {
5327   gint Inten, bytes=drawable->bpp;
5328   gint i, j, k;
5329   float partial;
5330   gint RW=reduced->width;
5331   gint RH=reduced->height;
5332   guchar *row=malloc(bytes*RW);;
5333
5334
5335   for (i=0; i < RH; i++) {
5336     for (j=0; j < RW; j++) {
5337
5338       row[j*3+0] = reduced->rgb[i*RW*bytes + j*bytes + 0];
5339       row[j*3+1] = reduced->rgb[i*RW*bytes + j*bytes + 1];
5340       row[j*3+2] = reduced->rgb[i*RW*bytes + j*bytes + 2];
5341
5342       if (bytes==4)
5343         for (k=0; k<3; k++) {
5344           float transp=reduced->rgb[i*RW*bytes+j*bytes+3]/255.0;
5345           row[3*j+k]=transp*a[3*j+k]+(1-transp)*fake_transparency(i,j);
5346         }
5347     }
5348     gtk_preview_draw_row( GTK_PREVIEW(preview),row,0,i,RW);
5349   }
5350
5351   free(a);
5352   gtk_widget_draw(preview,NULL);
5353   gdk_flush();
5354 }
5355
5356 Applicable Routines
5357
5358 guint           gtk_preview_get_type           (void);
5359 /* No idea */
5360 void            gtk_preview_uninit             (void);
5361 /* No idea */
5362 GtkWidget*      gtk_preview_new                (GtkPreviewType   type);
5363 /* Described above */
5364 void            gtk_preview_size               (GtkPreview      *preview,
5365                                                 gint             width,
5366                                                 gint             height);
5367 /* Allows you to resize an existing preview.    */
5368 /* Apparantly there's a bug in GTK which makes  */
5369 /* this process messy. A way to clean up a mess */
5370 /* is to manually resize the window containing  */
5371 /* the preview after resizing the preview.      */
5372
5373 void            gtk_preview_put                (GtkPreview      *preview,
5374                                                 GdkWindow       *window,
5375                                                 GdkGC           *gc,
5376                                                 gint             srcx,
5377                                                 gint             srcy,
5378                                                 gint             destx,
5379                                                 gint             desty,
5380                                                 gint             width,
5381                                                 gint             height);
5382 /* No idea */
5383
5384 void            gtk_preview_put_row            (GtkPreview      *preview,
5385                                                 guchar          *src,
5386                                                 guchar          *dest,
5387                                                 gint             x,
5388                                                 gint             y,
5389                                                 gint             w);
5390 /* No idea */
5391
5392 void            gtk_preview_draw_row           (GtkPreview      *preview,
5393                                                 guchar          *data,
5394                                                 gint             x,
5395                                                 gint             y,
5396                                                 gint             w);
5397 /* Described in the text */
5398
5399 void            gtk_preview_set_expand         (GtkPreview      *preview,
5400                                                 gint             expand);
5401 /* No idea */
5402
5403 /* No clue for any of the below but    */
5404 /* should be standard for most widgets */
5405 void            gtk_preview_set_gamma          (double           gamma);
5406 void            gtk_preview_set_color_cube     (guint            nred_shades,
5407                                                 guint            ngreen_shades,
5408                                                 guint            nblue_shades,
5409                                                 guint            ngray_shades);
5410 void            gtk_preview_set_install_cmap   (gint             install_cmap);
5411 void            gtk_preview_set_reserved       (gint             nreserved);
5412 GdkVisual*      gtk_preview_get_visual         (void);
5413 GdkColormap*    gtk_preview_get_cmap           (void);
5414 GtkPreviewInfo* gtk_preview_get_info           (void);
5415
5416 That's all, folks!
5417
5418 </verb></tscreen>
5419
5420 <!-- ----------------------------------------------------------------- -->
5421 <sect1> Curves
5422 <p>
5423
5424 <!-- ***************************************************************** -->
5425 <sect>The EventBox Widget<label id="sec_The_EventBox_Widget">
5426 <!-- ***************************************************************** -->
5427
5428 <p> 
5429 Some gtk widgets don't have associated X windows, so they just draw on 
5430 thier parents.  Because of this, they cannot recieve events
5431 and if they are incorrectly sized, they don't clip so you can get
5432 messy overwritting etc.  If you require more from these widgets, the
5433 EventBox is for you.
5434
5435 At first glance, the EventBox widget might appear to be totally
5436 useless. It draws nothing on the screen and responds to no
5437 events.  However, it does serve a function - it provides an X window for
5438 its child widget. This is important as many GTK widgets do not
5439 have an associated X window.  Not having an X window saves memory and
5440 improves performance, but also has some drawbacks. A widget without an
5441 X window cannot receive events, and does not perform any clipping on
5442 it's contents. Although the name ``EventBox'' emphasizes the
5443 event-handling function, the widget also can be used for clipping. 
5444 (And more ... see the example below.)
5445
5446 <p>
5447 To create a new EventBox widget, use:
5448
5449 <tscreen><verb>
5450 GtkWidget* gtk_event_box_new (void);
5451 </verb></tscreen>
5452
5453 <p>
5454 A child widget can then be added to this EventBox:
5455
5456 <tscreen><verb>
5457 gtk_container_add (GTK_CONTAINER(event_box), widget);
5458 </verb></tscreen>
5459
5460 <p>
5461 The following example demonstrates both uses of an EventBox - a label
5462 is created that clipped to a small box, and set up so that a
5463 mouse-click on the label causes the program to exit.
5464
5465 <tscreen><verb>
5466 /* eventbox.c */
5467
5468 #include <gtk/gtk.h>
5469
5470 int 
5471 main (int argc, char *argv[])
5472 {
5473     GtkWidget *window;
5474     GtkWidget *event_box;
5475     GtkWidget *label;
5476     
5477     gtk_init (&amp;argc, &amp;argv);
5478     
5479     window = gtk_window_new (GTK_WINDOW_TOPLEVEL);
5480     
5481     gtk_window_set_title (GTK_WINDOW (window), "Event Box");
5482     
5483     gtk_signal_connect (GTK_OBJECT (window), "destroy",
5484                         GTK_SIGNAL_FUNC (gtk_exit), NULL);
5485     
5486     gtk_container_border_width (GTK_CONTAINER (window), 10);
5487     
5488     /* Create an EventBox and add it to our toplevel window */
5489     
5490     event_box = gtk_event_box_new ();
5491     gtk_container_add (GTK_CONTAINER(window), event_box);
5492     gtk_widget_show (event_box);
5493     
5494     /* Create a long label */
5495     
5496     label = gtk_label_new ("Click here to quit, quit, quit, quit, quit");
5497     gtk_container_add (GTK_CONTAINER (event_box), label);
5498     gtk_widget_show (label);
5499     
5500     /* Clip it short. */
5501     gtk_widget_set_usize (label, 110, 20);
5502     
5503     /* And bind an action to it */
5504     gtk_widget_set_events (event_box, GDK_BUTTON_PRESS_MASK);
5505     gtk_signal_connect (GTK_OBJECT(event_box), "button_press_event",
5506                         GTK_SIGNAL_FUNC (gtk_exit), NULL);
5507     
5508     /* Yet one more thing you need an X window for ... */
5509     
5510     gtk_widget_realize (event_box);
5511     gdk_window_set_cursor (event_box->window, gdk_cursor_new (GDK_HAND1));
5512     
5513     gtk_widget_show (window);
5514     
5515     gtk_main ();
5516     
5517     return 0;
5518 }
5519 </verb></tscreen>
5520
5521 <!-- ***************************************************************** -->
5522 <sect>Setting Widget Attributes<label id="sec_setting_widget_attributes">
5523 <!-- ***************************************************************** -->
5524
5525 <p>
5526 This describes the functions used to operate on widgets.  These can be used
5527 to set style, padding, size etc.
5528
5529 (Maybe I should make a whole section on accelerators.)
5530
5531 <tscreen><verb>
5532 void       gtk_widget_install_accelerator (GtkWidget           *widget,
5533                                            GtkAcceleratorTable *table,
5534                                            gchar               *signal_name,
5535                                            gchar                key,
5536                                            guint8               modifiers);
5537
5538 void       gtk_widget_remove_accelerator  (GtkWidget           *widget,
5539                                            GtkAcceleratorTable *table,
5540                                            gchar               *signal_name);
5541
5542 void       gtk_widget_activate            (GtkWidget           *widget);
5543
5544 void       gtk_widget_set_name            (GtkWidget           *widget,
5545                                            gchar               *name);
5546 gchar*     gtk_widget_get_name            (GtkWidget           *widget);
5547
5548 void       gtk_widget_set_sensitive       (GtkWidget           *widget,
5549                                            gint                 sensitive);
5550
5551 void       gtk_widget_set_style           (GtkWidget           *widget,
5552                                            GtkStyle            *style);
5553                                            
5554 GtkStyle*    gtk_widget_get_style     (GtkWidget *widget);
5555
5556 GtkStyle*    gtk_widget_get_default_style    (void);
5557
5558 void       gtk_widget_set_uposition       (GtkWidget           *widget,
5559                                            gint                 x,
5560                                            gint                 y);
5561 void       gtk_widget_set_usize           (GtkWidget           *widget,
5562                                            gint                 width,
5563                                            gint                 height);
5564
5565 void       gtk_widget_grab_focus          (GtkWidget           *widget);
5566
5567 void       gtk_widget_show                (GtkWidget           *widget);
5568
5569 void       gtk_widget_hide                (GtkWidget           *widget);
5570 </verb></tscreen>
5571
5572 <!-- ***************************************************************** -->
5573 <sect>Timeouts, IO and Idle Functions<label id="sec_timeouts">
5574 <!-- ***************************************************************** -->
5575
5576 <!-- ----------------------------------------------------------------- -->
5577 <sect1>Timeouts
5578 <p>
5579 You may be wondering how you make GTK do useful work when in gtk_main.
5580 Well, you have several options.  Using the following functions you can
5581 create a timeout function that will be called every "interval" milliseconds.
5582
5583 <tscreen><verb>
5584 gint gtk_timeout_add (guint32 interval,
5585                       GtkFunction function,
5586                       gpointer data);
5587 </verb></tscreen>
5588
5589 The first argument is the number of milliseconds
5590 between calls to your function.  The second argument is the function
5591 you wish to have called, and
5592 the third, the data passed to this callback function.  The return value is
5593 an integer "tag" which may be used to stop the timeout by calling:
5594
5595 <tscreen><verb>
5596 void gtk_timeout_remove (gint tag);
5597 </verb></tscreen>
5598
5599 You may also stop the timeout function by returning zero or FALSE from
5600 your callback function.  Obviously this means if you want your function to
5601 continue to be called, it should return a non-zero value, ie TRUE.
5602
5603 The declaration of your callback should look something like this:
5604
5605 <tscreen><verb>
5606 gint timeout_callback (gpointer data);
5607 </verb></tscreen>
5608
5609 <!-- ----------------------------------------------------------------- -->
5610 <sect1>Monitoring IO
5611 <p>
5612 Another nifty feature of GTK, is the ability to have it check for data on a
5613 file descriptor for you (as returned by open(2) or socket(2)).  This is
5614 especially useful for networking applications.  The function:
5615
5616 <tscreen><verb>
5617 gint gdk_input_add (gint source,
5618                     GdkInputCondition condition,
5619                     GdkInputFunction  function,
5620                     gpointer data);
5621 </verb></tscreen>
5622
5623 Where the first argument is the file descriptor you wish to have watched,
5624 and the second specifies what you want GDK to look for.  This may be one of:
5625 <p>
5626 GDK_INPUT_READ - Call your function when there is data ready for reading on
5627 your file descriptor.
5628 <p>
5629 GDK_INPUT_WRITE - Call your function when the file descriptor is ready for
5630 writing.
5631 <p>
5632 As I'm sure you've figured out already, the third argument is the function
5633 you wish to have called when the above conditions are satisfied, and the
5634 fourth is the data to pass to this function.
5635 <p>
5636 The return value is a tag that may be used to stop GDK from monitoring this
5637 file descriptor using the following function.
5638 <p>
5639 <tscreen><verb>
5640 void gdk_input_remove (gint tag);
5641 </verb></tscreen>
5642 <p>
5643 The callback function should be declared:
5644 <p>
5645 <tscreen><verb>
5646 void input_callback (gpointer data, gint source, 
5647                      GdkInputCondition condition);
5648 </verb></tscreen>
5649 <p>
5650
5651 <!-- ----------------------------------------------------------------- -->
5652 <sect1>Idle Functions
5653 <p>
5654 What if you have a function you want called when nothing else is
5655 happening ?
5656
5657 <tscreen><verb>
5658 gint gtk_idle_add (GtkFunction function,
5659                    gpointer data);
5660 </verb></tscreen>
5661
5662 This causes GTK to call the specified function whenever nothing else is
5663 happening.
5664
5665 <tscreen><verb>
5666 void gtk_idle_remove (gint tag);
5667 </verb></tscreen>
5668 <p>
5669 I won't explain the meaning of the arguments as they follow very much like
5670 the ones above.  The function pointed to by the first argument to
5671 gtk_idle_add will be called whenever the opportunity arises.  As with the
5672 others, returning FALSE will stop the idle function from being called.
5673
5674 <!-- ***************************************************************** -->
5675 <sect>Managing Selections
5676 <!-- ***************************************************************** -->
5677
5678 <!-- ----------------------------------------------------------------- -->
5679 <sect1> Overview
5680
5681 <p>
5682
5683 One type of interprocess communication supported by GTK is
5684 <em>selections</em>. A selection identifies a chunk of data, for
5685 instance, a portion of text, selected by the user in some fashion, for
5686 instance, by dragging with the mouse. Only one application on a
5687 display, (he <em>owner</em>_ can own a particular selection at one
5688 time, so when a selection is claimed by one application, the previous
5689 owner must indicate to the user that selection has been
5690 relinquished. Other applications can request the contents of a
5691 selection in different forms, called <em>targets</em>.  There can be
5692 any number of selections, but most X applications only handle one, the
5693 <em>primary selection</em>.
5694
5695 <p>
5696 In most cases, it isn't necessary for a GTK application to deal with
5697 selections itself. The standard widgets, such as the Entry widget,
5698 already have the capability to claim the selection when appropriate
5699 (e.g., when the user drags over text), and to retrieve the contents of
5700 the selection owned by another widget, or another application (e.g.,
5701 when the user clicks the second mouse button). However, there may be
5702 cases in which you want to give other widgets the ability to supply
5703 the selection, or you wish to retrieve targets not supported by
5704 default.
5705
5706 <p>
5707 A fundamental concept needed to understand selection handling is that
5708 of the <em>atom</em>. An atom is an integer that uniquely identifies a
5709 string (on a certain display). Certain atoms are predefined by the X
5710 server, and in some cases there are constants in in <tt>gtk.h</tt>
5711 corresponding to these atoms. For instance the constant
5712 <tt>GDK_PRIMARY_SELECTION</tt> corresponds to the string "PRIMARY".
5713 In other cases, you should use the functions
5714 <tt>gdk_atom_intern()</tt>, to get the atom corresponding to a string,
5715 and <tt>gdk_atom_name()</tt>, to get the name of an atom. Both
5716 selections and targets are identifed by atoms.
5717
5718 <!-- ----------------------------------------------------------------- -->
5719 <sect1> Retrieving the selection
5720
5721 <p>
5722
5723 Retrieving the selection is an asynchronous process. To start the
5724 process, you call:
5725
5726 <tscreen><verb>
5727 gint gtk_selection_convert   (GtkWidget           *widget, 
5728                               GdkAtom              selection, 
5729                               GdkAtom              target,
5730                               guint32              time)
5731 </verb</tscreen>
5732
5733 This <em>converts</em> the selection into the form specified by
5734 <tt/target/. If it all possible, the time field should be the time
5735 from the event that triggered the selection. This helps make sure that
5736 events occur in the order that the user requested them.
5737  However, if it is not available (for instance, if the conversion was
5738 triggered by a "clicked" signal), then you can use the constant
5739 <tt>GDK_CURRENT_TIME</tt>.
5740
5741 <p>
5742 When the selection owner responds to the request, a
5743 "selection_received" signal is sent to your application. The handler
5744 for this signal receives a pointer to a <tt>GtkSelectionData</tt>
5745 structure, which is defined as:
5746
5747 <tscreen><verb>
5748 struct _GtkSelectionData
5749 {
5750   GdkAtom selection;
5751   GdkAtom target;
5752   GdkAtom type;
5753   gint    format;
5754   guchar *data;
5755   gint    length;
5756 };
5757 </verb></tscreen>
5758
5759 <tt>selection</tt> and <tt>target</tt> are the values you gave in your
5760 <tt>gtk_selection_convert()</tt> call. <tt>type</tt> is an atom that
5761 identifies the type of data returned by the selection owner. Some
5762 possible values are "STRING", a string of latin-1 characters, "ATOM",
5763 a series of atoms, "INTEGER", an integer, etc. Most targets can only
5764 return one type. <tt/format/ gives the length of the units (for
5765 instance characters) in bits. Usually, you don't care about this when
5766 receiving data.  <tt>data</tt> is a pointer to the returned data, and
5767 <tt>length</tt> gives the length of the returned data, in bytes. If
5768 <tt>length</tt> is negative, then an error occurred and the selection
5769 could not be retrieved. This might happen if no application owned the
5770 selection, or if you requested a target that the application didn't
5771 support. The buffer is actually guaranteed to be one byte longer than
5772 <tt>length</tt>; the extra byte will always be zero, so it isn't
5773 necessary to make a copy of strings just to null terminate them.
5774
5775 <p>
5776 In the following example, we retrieve the special target "TARGETS",
5777 which is a list of all targets into which the selection can be
5778 converted.
5779
5780 <tscreen><verb>
5781 /* gettargets.c */
5782
5783 #include <gtk/gtk.h>
5784
5785 void selection_received (GtkWidget *widget, 
5786                          GtkSelectionData *selection_data, 
5787                          gpointer data);
5788
5789 /* Signal handler invoked when user clicks on the "Get Targets" button */
5790 void
5791 get_targets (GtkWidget *widget, gpointer data)
5792 {
5793   static GdkAtom targets_atom = GDK_NONE;
5794
5795   /* Get the atom corresonding to the string "TARGETS" */
5796   if (targets_atom == GDK_NONE)
5797     targets_atom = gdk_atom_intern ("TARGETS", FALSE);
5798
5799   /* And request the "TARGETS" target for the primary selection */
5800   gtk_selection_convert (widget, GDK_SELECTION_PRIMARY, targets_atom,
5801                          GDK_CURRENT_TIME);
5802 }
5803
5804 /* Signal handler called when the selections owner returns the data */
5805 void
5806 selection_received (GtkWidget *widget, GtkSelectionData *selection_data, 
5807                     gpointer data)
5808 {
5809   GdkAtom *atoms;
5810   GList *item_list;
5811   int i;
5812
5813   /* **** IMPORTANT **** Check to see if retrieval succeeded  */
5814   if (selection_data->length < 0)
5815     {
5816       g_print ("Selection retrieval failed\n");
5817       return;
5818     }
5819   /* Make sure we got the data in the expected form */
5820   if (selection_data->type != GDK_SELECTION_TYPE_ATOM)
5821     {
5822       g_print ("Selection \"TARGETS\" was not returned as atoms!\n");
5823       return;
5824     }
5825   
5826   /* Print out the atoms we received */
5827   atoms = (GdkAtom *)selection_data->data;
5828
5829   item_list = NULL;
5830   for (i=0; i<selection_data->length/sizeof(GdkAtom); i++)
5831     {
5832       char *name;
5833       name = gdk_atom_name (atoms[i]);
5834       if (name != NULL)
5835         g_print ("%s\n",name);
5836       else
5837         g_print ("(bad atom)\n");
5838     }
5839
5840   return;
5841 }
5842
5843 int 
5844 main (int argc, char *argv[])
5845 {
5846   GtkWidget *window;
5847   GtkWidget *button;
5848   
5849   gtk_init (&amp;argc, &amp;argv);
5850
5851   /* Create the toplevel window */
5852
5853   window = gtk_window_new (GTK_WINDOW_TOPLEVEL);
5854   gtk_window_set_title (GTK_WINDOW (window), "Event Box");
5855   gtk_container_border_width (GTK_CONTAINER (window), 10);
5856
5857   gtk_signal_connect (GTK_OBJECT (window), "destroy",
5858                       GTK_SIGNAL_FUNC (gtk_exit), NULL);
5859
5860   /* Create a button the user can click to get targets */
5861
5862   button = gtk_button_new_with_label ("Get Targets");
5863   gtk_container_add (GTK_CONTAINER (window), button);
5864
5865   gtk_signal_connect (GTK_OBJECT(button), "clicked",
5866                       GTK_SIGNAL_FUNC (get_targets), NULL);
5867   gtk_signal_connect (GTK_OBJECT(button), "selection_received",
5868                       GTK_SIGNAL_FUNC (selection_received), NULL);
5869
5870   gtk_widget_show (button);
5871   gtk_widget_show (window);
5872   
5873   gtk_main ();
5874   
5875   return 0;
5876 }
5877 </verb></tscreen>
5878
5879 <!-- ----------------------------------------------------------------- -->
5880 <sect1> Supplying the selection 
5881
5882 <p>
5883
5884 Supplying the selection is a bit more complicated. You must register 
5885 handlers that will be called when your selection is requested. For
5886 each selection/target pair you will handle, you make a call to:
5887
5888 <tscreen><verb>
5889 void gtk_selection_add_handler (GtkWidget           *widget, 
5890                                 GdkAtom              selection,
5891                                 GdkAtom              target,
5892                                 GtkSelectionFunction function,
5893                                 GtkRemoveFunction    remove_func,
5894                                 gpointer             data);
5895 </verb></tscreen>
5896
5897 <tt/widget/, <tt/selection/, and <tt/target/ identify the requests
5898 this handler will manage.  <tt/remove_func/ if not
5899 NULL, will be called when the signal handler is removed. This is
5900 useful, for instance, for interpreted languages which need to
5901 keep track of a reference count for <tt/data/.
5902
5903 <p>
5904 The callback function has the signature:
5905
5906 <tscreen><verb>
5907 typedef void (*GtkSelectionFunction) (GtkWidget *widget, 
5908                                       GtkSelectionData *selection_data,
5909                                       gpointer data);
5910
5911 </verb></tscreen>
5912
5913 The GtkSelectionData is the same as above, but this time, we're
5914 responsible for filling in the fields <tt/type/, <tt/format/,
5915 <tt/data/, and <tt/length/. (The <tt/format/ field is actually
5916 important here - the X server uses it to figure out whether the data
5917 needs to be byte-swapped or not. Usually it will be 8 - <em/i.e./ a
5918 character - or 32 - <em/i.e./ a. integer.) This is done by calling the
5919 function:
5920
5921 <tscreen><verb>
5922 void gtk_selection_data_set (GtkSelectionData *selection_data,
5923                              GdkAtom           type,
5924                              gint              format,
5925                              guchar           *data,
5926                              gint              length);
5927 </verb></tscreen>
5928
5929 This function takes care of properly making a copy of the data so that
5930 you don't have to worry about keeping it around. (You should not fill
5931 in the fields of the GtkSelectionData structure by hand.)
5932
5933 <p>
5934 When prompted by the user, you claim ownership of the selection by
5935 calling:
5936
5937 <tscreen><verb>
5938 gint gtk_selection_owner_set (GtkWidget           *widget,
5939                               GdkAtom              selection,
5940                               guint32              time);
5941 </verb></tscreen>
5942
5943 If another application claims ownership of the selection, you will
5944 receive a "selection_clear_event".
5945
5946 As an example of supplying the selection, the following program adds
5947 selection functionality to a toggle button. When the toggle button is
5948 depressed, the program claims the primary selection. The only target
5949 supported (aside from certain targets like "TARGETS" supplied by GTK
5950 itself), is the "STRING" target. When this target is requested, a
5951 string representation of the time is returned.
5952
5953 <tscreen><verb>
5954 /* setselection.c */
5955
5956 #include <gtk/gtk.h>
5957 #include <time.h>
5958
5959 /* Callback when the user toggles the selection */
5960 void
5961 selection_toggled (GtkWidget *widget, gint *have_selection)
5962 {
5963   if (GTK_TOGGLE_BUTTON(widget)->active)
5964     {
5965       *have_selection = gtk_selection_owner_set (widget,
5966                                                  GDK_SELECTION_PRIMARY,
5967                                                  GDK_CURRENT_TIME);
5968       /* if claiming the selection failed, we return the button to
5969          the out state */
5970       if (!*have_selection)
5971         gtk_toggle_button_set_state (GTK_TOGGLE_BUTTON(widget), FALSE);
5972     }
5973   else
5974     {
5975       if (*have_selection)
5976         {
5977           /* Before clearing the selection by setting the owner to NULL,
5978              we check if we are the actual owner */
5979           if (gdk_selection_owner_get (GDK_SELECTION_PRIMARY) == widget->window)
5980             gtk_selection_owner_set (NULL, GDK_SELECTION_PRIMARY,
5981                                      GDK_CURRENT_TIME);
5982           *have_selection = FALSE;
5983         }
5984     }
5985 }
5986
5987 /* Called when another application claims the selection */
5988 gint
5989 selection_clear (GtkWidget *widget, GdkEventSelection *event,
5990                  gint *have_selection)
5991 {
5992   *have_selection = FALSE;
5993   gtk_toggle_button_set_state (GTK_TOGGLE_BUTTON(widget), FALSE);
5994
5995   return TRUE;
5996 }
5997
5998 /* Supplies the current time as the selection. */
5999 void
6000 selection_handle (GtkWidget *widget, 
6001                   GtkSelectionData *selection_data,
6002                   gpointer data)
6003 {
6004   gchar *timestr;
6005   time_t current_time;
6006
6007   current_time = time (NULL);
6008   timestr = asctime (localtime(&amp;current_time)); 
6009   /* When we return a single string, it should not be null terminated.
6010      That will be done for us */
6011
6012   gtk_selection_data_set (selection_data, GDK_SELECTION_TYPE_STRING,
6013                           8, timestr, strlen(timestr));
6014 }
6015
6016 int
6017 main (int argc, char *argv[])
6018 {
6019   GtkWidget *window;
6020
6021   GtkWidget *selection_button;
6022
6023   static int have_selection = FALSE;
6024   
6025   gtk_init (&amp;argc, &amp;argv);
6026
6027   /* Create the toplevel window */
6028
6029   window = gtk_window_new (GTK_WINDOW_TOPLEVEL);
6030   gtk_window_set_title (GTK_WINDOW (window), "Event Box");
6031   gtk_container_border_width (GTK_CONTAINER (window), 10);
6032
6033   gtk_signal_connect (GTK_OBJECT (window), "destroy",
6034                       GTK_SIGNAL_FUNC (gtk_exit), NULL);
6035
6036   /* Create a toggle button to act as the selection */
6037
6038   selection_button = gtk_toggle_button_new_with_label ("Claim Selection");
6039   gtk_container_add (GTK_CONTAINER (window), selection_button);
6040   gtk_widget_show (selection_button);
6041
6042   gtk_signal_connect (GTK_OBJECT(selection_button), "toggled",
6043                       GTK_SIGNAL_FUNC (selection_toggled), &amp;have_selection);
6044   gtk_signal_connect (GTK_OBJECT(selection_button), "selection_clear_event",
6045                       GTK_SIGNAL_FUNC (selection_clear), &amp;have_selection);
6046
6047   gtk_selection_add_handler (selection_button, GDK_SELECTION_PRIMARY,
6048                              GDK_SELECTION_TYPE_STRING,
6049                              selection_handle, NULL);
6050
6051   gtk_widget_show (selection_button);
6052   gtk_widget_show (window);
6053   
6054   gtk_main ();
6055   
6056   return 0;
6057 }
6058 </verb></tscreen>
6059
6060
6061 <!-- ***************************************************************** -->
6062 <sect>glib<label id="sec_glib">
6063 <!-- ***************************************************************** -->
6064
6065 <p>
6066 glib provides many useful functions and definitions available for use 
6067 when creating GDK
6068 and GTK applications.  I will list them all here with a brief explanation.
6069 Many are duplicates of standard libc functions so I won't go into
6070 detail on those.  This is mostly to be used as a reference, so you know what is
6071 available for use.
6072
6073 <!-- ----------------------------------------------------------------- -->
6074 <sect1>Definitions
6075 <p>
6076 Definitions for the extremes of many of the standard types are:
6077
6078 <tscreen><verb>
6079 G_MINFLOAT
6080 G_MAXFLOAT
6081 G_MINDOUBLE
6082 G_MAXDOUBLE
6083 G_MINSHORT
6084 G_MAXSHORT
6085 G_MININT
6086 G_MAXINT
6087 G_MINLONG
6088 G_MAXLONG
6089 </verb></tscreen>
6090
6091 Also, the following typedefs.  The ones left unspecified are dynamically set
6092 depending on the architecture.  Remember to avoid counting on the size of a
6093 pointer if you want to be portable!  Eg, a pointer on an Alpha is 8 bytes, but 4
6094 on Intel.
6095
6096 <tscreen><verb>
6097 char   gchar;
6098 short  gshort;
6099 long   glong;
6100 int    gint;
6101 char   gboolean;
6102
6103 unsigned char   guchar;
6104 unsigned short  gushort;
6105 unsigned long   gulong;
6106 unsigned int    guint;
6107
6108 float   gfloat;
6109 double  gdouble;
6110 long double gldouble;
6111
6112 void* gpointer;
6113
6114 gint8
6115 guint8
6116 gint16
6117 guint16
6118 gint32
6119 guint32
6120 </verb></tscreen>
6121
6122 <!-- ----------------------------------------------------------------- -->
6123 <sect1>Doubly Linked Lists
6124 <p>
6125 The following functions are used to create, manage, and destroy doubly
6126 linked lists.  I assume you know what linked lists are, as it is beyond the scope
6127 of this document to explain them.  Of course, it's not required that you
6128 know these for general use of GTK, but they are nice to know.
6129
6130 <tscreen><verb>
6131 GList* g_list_alloc       (void);
6132
6133 void   g_list_free        (GList     *list);
6134
6135 void   g_list_free_1      (GList     *list);
6136
6137 GList* g_list_append      (GList     *list,
6138                            gpointer   data);
6139                            
6140 GList* g_list_prepend     (GList     *list,
6141                            gpointer   data);
6142                         
6143 GList* g_list_insert      (GList     *list,
6144                            gpointer   data,
6145                            gint       position);
6146
6147 GList* g_list_remove      (GList     *list,
6148                            gpointer   data);
6149                            
6150 GList* g_list_remove_link (GList     *list,
6151                            GList     *link);
6152
6153 GList* g_list_reverse     (GList     *list);
6154
6155 GList* g_list_nth         (GList     *list,
6156                            gint       n);
6157                            
6158 GList* g_list_find        (GList     *list,
6159                            gpointer   data);
6160
6161 GList* g_list_last        (GList     *list);
6162
6163 GList* g_list_first       (GList     *list);
6164
6165 gint   g_list_length      (GList     *list);
6166
6167 void   g_list_foreach     (GList     *list,
6168                            GFunc      func,
6169                            gpointer   user_data);
6170 </verb></tscreen>                                             
6171
6172 <!-- ----------------------------------------------------------------- -->
6173 <sect1>Singly Linked Lists
6174 <p>
6175 Many of the above functions for singly linked lists are identical to the
6176 above.  Here is a complete list:
6177 <tscreen><verb>
6178 GSList* g_slist_alloc       (void);
6179
6180 void    g_slist_free        (GSList   *list);
6181
6182 void    g_slist_free_1      (GSList   *list);
6183
6184 GSList* g_slist_append      (GSList   *list,
6185                              gpointer  data);
6186                 
6187 GSList* g_slist_prepend     (GSList   *list,
6188                              gpointer  data);
6189                              
6190 GSList* g_slist_insert      (GSList   *list,
6191                              gpointer  data,
6192                              gint      position);
6193                              
6194 GSList* g_slist_remove      (GSList   *list,
6195                              gpointer  data);
6196                              
6197 GSList* g_slist_remove_link (GSList   *list,
6198                              GSList   *link);
6199                              
6200 GSList* g_slist_reverse     (GSList   *list);
6201
6202 GSList* g_slist_nth         (GSList   *list,
6203                              gint      n);
6204                              
6205 GSList* g_slist_find        (GSList   *list,
6206                              gpointer  data);
6207                              
6208 GSList* g_slist_last        (GSList   *list);
6209
6210 gint    g_slist_length      (GSList   *list);
6211
6212 void    g_slist_foreach     (GSList   *list,
6213                              GFunc     func,
6214                              gpointer  user_data);
6215         
6216 </verb></tscreen>
6217
6218 <!-- ----------------------------------------------------------------- -->
6219 <sect1>Memory Management
6220 <p>
6221 <tscreen><verb>
6222 gpointer g_malloc      (gulong    size);
6223 </verb></tscreen>
6224
6225 This is a replacement for malloc().  You do not need to check the return
6226 vaule as it is done for you in this function.
6227
6228 <tscreen><verb>
6229 gpointer g_malloc0     (gulong    size);
6230 </verb></tscreen>
6231
6232 Same as above, but zeroes the memory before returning a pointer to it.
6233
6234 <tscreen><verb>
6235 gpointer g_realloc     (gpointer  mem,
6236                         gulong    size);
6237 </verb></tscreen>
6238
6239 Relocates "size" bytes of memory starting at "mem".  Obviously, the memory should have been
6240 previously allocated.
6241
6242 <tscreen><verb>
6243 void     g_free        (gpointer  mem);
6244 </verb></tscreen>
6245
6246 Frees memory.  Easy one.
6247
6248 <tscreen><verb>
6249 void     g_mem_profile (void);
6250 </verb></tscreen>
6251
6252 Dumps a profile of used memory, but requries that you add #define
6253 MEM_PROFILE to the top of glib/gmem.c and re-make and make install.
6254
6255 <tscreen><verb>
6256 void     g_mem_check   (gpointer  mem);
6257 </verb></tscreen>
6258
6259 Checks that a memory location is valid.  Requires you add #define
6260 MEM_CHECK to the top of gmem.c and re-make and make install.
6261
6262 <!-- ----------------------------------------------------------------- -->
6263 <sect1>Timers
6264 <p>
6265 Timer functions..
6266
6267 <tscreen><verb>
6268 GTimer* g_timer_new     (void);
6269
6270 void    g_timer_destroy (GTimer  *timer);
6271
6272 void    g_timer_start   (GTimer  *timer);
6273
6274 void    g_timer_stop    (GTimer  *timer);
6275
6276 void    g_timer_reset   (GTimer  *timer);
6277
6278 gdouble g_timer_elapsed (GTimer  *timer,
6279                          gulong  *microseconds);
6280 </verb></tscreen>                        
6281
6282 <!-- ----------------------------------------------------------------- -->
6283 <sect1>String Handling
6284 <p>
6285 A whole mess of string handling functions.  They all look very interesting, and
6286 probably better for many purposes than the standard C string functions, but
6287 require documentation.
6288
6289 <tscreen><verb>
6290 GString* g_string_new       (gchar   *init);
6291 void     g_string_free      (GString *string,
6292                              gint     free_segment);
6293                              
6294 GString* g_string_assign    (GString *lval,
6295                              gchar   *rval);
6296                              
6297 GString* g_string_truncate  (GString *string,
6298                              gint     len);
6299                              
6300 GString* g_string_append    (GString *string,
6301                              gchar   *val);
6302                             
6303 GString* g_string_append_c  (GString *string,
6304                              gchar    c);
6305         
6306 GString* g_string_prepend   (GString *string,
6307                              gchar   *val);
6308                              
6309 GString* g_string_prepend_c (GString *string,
6310                              gchar    c);
6311         
6312 void     g_string_sprintf   (GString *string,
6313                              gchar   *fmt,
6314                              ...);
6315         
6316 void     g_string_sprintfa  (GString *string,
6317                              gchar   *fmt,
6318                              ...);
6319 </verb></tscreen>                                                         
6320
6321 <!-- ----------------------------------------------------------------- -->
6322 <sect1>Utility and Error Functions
6323 <p>
6324 <tscreen><verb>
6325 gchar* g_strdup    (const gchar *str);
6326 </verb></tscreen>
6327
6328 Replacement strdup function.  Copies the
6329 original strings contents to newly allocated memory, and returns a pointer to it.
6330
6331 <tscreen><verb>
6332 gchar* g_strerror  (gint errnum);
6333 </verb></tscreen>
6334
6335 I recommend using this for all error messages.  It's much nicer, and more
6336 portable than perror() or others.  The output is usually of the form:
6337
6338 <tscreen><verb>
6339 program name:function that failed:file or further description:strerror
6340 </verb></tscreen>
6341
6342 Here's an example of one such call used in our hello_world program:
6343
6344 <tscreen><verb>
6345 g_print("hello_world:open:%s:%s\n", filename, g_strerror(errno));
6346 </verb></tscreen>
6347
6348 <tscreen><verb>
6349 void g_error   (gchar *format, ...);
6350 </verb></tscreen>
6351
6352 Prints an error message.  The format is just like printf, but it
6353 prepends "** ERROR **: " to your message, and exits the program.  
6354 Use only for fatal errors.
6355
6356 <tscreen><verb>
6357 void g_warning (gchar *format, ...);
6358 </verb></tscreen>
6359
6360 Same as above, but prepends "** WARNING **: ", and does not exit the
6361 program.
6362
6363 <tscreen><verb>
6364 void g_message (gchar *format, ...);
6365 </verb></tscreen>
6366
6367 Prints "message: " prepended to the string you pass in.
6368
6369 <tscreen><verb>
6370 void g_print   (gchar *format, ...);
6371 </verb></tscreen>
6372
6373 Replacement for printf().
6374
6375 And our last function:
6376
6377 <tscreen><verb>
6378 gchar* g_strsignal (gint signum);
6379 </verb></tscreen>
6380
6381 Prints out the name of the Unix system signal given the signal number.
6382 Useful in generic signal handling functions.
6383
6384 All of the above are more or less just stolen from glib.h.  If anyone cares
6385 to document any function, just send me an email!
6386
6387 <!-- ***************************************************************** -->
6388 <sect>GTK's rc Files
6389 <!-- ***************************************************************** -->
6390
6391 <p>
6392 GTK has it's own way of dealing with application defaults, by using rc
6393 files.  These can be used to set the colors of just about any widget, and
6394 can also be used to tile pixmaps onto the background of some widgets.  
6395
6396 <!-- ----------------------------------------------------------------- -->
6397 <sect1>Functions For rc Files 
6398 <p>
6399 When your application starts, you should include a call to:
6400 <tscreen><verb>
6401 void gtk_rc_parse (char *filename);
6402 </verb></tscreen>
6403 <p>
6404 Passing in the filename of your rc file.  This will cause GTK to parse this
6405 file, and use the style settings for the widget types defined there.
6406 <p>
6407 If you wish to have a special set of widgets that can take on a different
6408 style from others, or any other logical division of widgets, use a call to:
6409 <tscreen><verb>
6410 void gtk_widget_set_name (GtkWidget *widget,
6411                           gchar *name);
6412 </verb></tscreen>
6413 <p>
6414 Passing your newly created widget as the first argument, and the name
6415 you wish to give it as the second.  This will allow you to change the
6416 attributes of this widget by name through the rc file.
6417 <p>
6418 If we use a call something like this:
6419
6420 <tscreen><verb>
6421 button = gtk_button_new_with_label ("Special Button");
6422 gtk_widget_set_name (button, "special button");
6423 </verb></tscreen>
6424 <p>
6425 Then this button is given the name "special button" and may be addressed by
6426 name in the rc file as "special button.GtkButton".  [<--- Verify ME!]
6427 <p>
6428 The example rc file below, sets the properties of the main window, and lets
6429 all children of that main window inherit the style described by the "main
6430 button" style.  The code used in the application is:
6431
6432 <tscreen><verb>
6433 window = gtk_window_new (GTK_WINDOW_TOPLEVEL);
6434 gtk_widget_set_name (window, "main window");
6435 </verb></tscreen>
6436 <p>
6437 And then the style is defined in the rc file using:
6438
6439 <tscreen><verb>
6440 widget "main window.*GtkButton*" style "main_button"
6441 </verb></tscreen>
6442 <p>
6443 Which sets all the GtkButton widgets in the "main window" to the
6444 "main_buttons" style as defined in the rc file.
6445 <p>
6446 As you can see, this is a fairly powerful and flexible system.  Use your
6447 imagination as to how best to take advantage of this.
6448
6449 <!-- ----------------------------------------------------------------- -->
6450 <sect1>GTK's rc File Format
6451 <p>
6452 The format of the GTK file is illustrated in the example below.  This is
6453 the testgtkrc file from the GTK distribution, but I've added a
6454 few comments and things.  You may wish to include this explanation
6455 your application to allow the user to fine tune his application.
6456 <p>
6457 There are several directives to change the attributes of a widget.
6458 <itemize>
6459 <item>fg - Sets the foreground color of a widget.
6460 <item>bg - Sets the background color of a widget.
6461 <item>bg_pixmap - Sets the background of a widget to a tiled pixmap.
6462 <item>font - Sets the font to be used with the given widget.
6463 </itemize>
6464 <p>
6465 In addition to this, there are several states a widget can be in, and you
6466 can set different colors, pixmaps and fonts for each state.  These states are:
6467 <itemize>
6468 <item>NORMAL - The normal state of a widget, without the mouse over top of
6469 it, and not being pressed etc.
6470 <item>PRELIGHT - When the mouse is over top of the widget, colors defined
6471 using this state will be in effect.
6472 <item>ACTIVE - When the widget is pressed or clicked it will be active, and
6473 the attributes assigned by this tag will be in effect.
6474 <item>INSENSITIVE - When a widget is set insensitive, and cannot be
6475 activated, it will take these attributes.
6476 <item>SELECTED - When an object is selected, it takes these attributes.
6477 </itemize>
6478 <p>
6479 When using the "fg" and "bg" keywords to set the colors of widgets, the
6480 format is:
6481 <tscreen><verb>
6482 fg[<STATE>] = { Red, Green, Blue }
6483 </verb></tscreen>
6484 <p>
6485 Where STATE is one of the above states (PRELIGHT, ACTIVE etc), and the Red,
6486 Green and Blue are values in the range of 0 - 1.0,  { 1.0, 1.0, 1.0 } being
6487 white.
6488 They must be in float form, or they will register as 0, so a straight 
6489 "1" will not work, it must
6490 be "1.0".  A straight "0" is fine because it doesn't matter if it's not
6491 recognized.  Unrecognized values are set to 0.
6492 <p>
6493 bg_pixmap is very similar to the above, except the colors are replaced by a
6494 filename.
6495
6496 pixmap_path is a list of paths seperated by ":"'s.  These paths will be
6497 searched for any pixmap you specify.
6498
6499 <p>
6500 The font directive is simply:
6501 <tscreen><verb>
6502 font = "<font name>"
6503 </verb></tscreen>
6504 <p>
6505 Where the only hard part is figuring out the font string.  Using xfontsel or
6506 similar utility should help.
6507 <p>
6508 The "widget_class" sets the style of a class of widgets.  These classes are
6509 listed in the widget overview on the class hierarchy.
6510 <p>
6511 The "widget" directive sets a specificaly named set of widgets to a
6512 given style, overriding any style set for the given widget class.
6513 These widgets are registered inside the application using the
6514 gtk_widget_set_name() call.  This allows you to specify the attributes of a
6515 widget on a per widget basis, rather than setting the attributes of an
6516 entire widget class.  I urge you to document any of these special widgets so
6517 users may customize them.
6518 <p>
6519 When the keyword "<tt>parent</>" is used as an attribute, the widget will take on
6520 the attributes of it's parent in the application.
6521 <p>
6522 When defining a style, you may assign the attributes of a previously defined
6523 style to this new one.
6524 <tscreen><verb>
6525 style "main_button" = "button"
6526 {
6527   font = "-adobe-helvetica-medium-r-normal--*-100-*-*-*-*-*-*"
6528   bg[PRELIGHT] = { 0.75, 0, 0 }
6529 }
6530 </verb></tscreen>
6531 <p>
6532 This example takes the "button" style, and creates a new "main_button" style
6533 simply by changing the font and prelight background color of the "button"
6534 style.
6535 <p>
6536 Of course, many of these attributes don't apply to all widgets.  It's a
6537 simple matter of common sense really.  Anything that could apply, should.
6538
6539 <!-- ----------------------------------------------------------------- -->
6540 <sect1>Example rc file
6541 <p>
6542
6543 <tscreen><verb>
6544 # pixmap_path "<dir 1>:<dir 2>:<dir 3>:..."
6545 #
6546 pixmap_path "/usr/include/X11R6/pixmaps:/home/imain/pixmaps"
6547 #
6548 # style <name> [= <name>]
6549 # {
6550 #   <option>
6551 # }
6552 #
6553 # widget <widget_set> style <style_name>
6554 # widget_class <widget_class_set> style <style_name>
6555
6556
6557 # Here is a list of all the possible states.  Note that some do not apply to
6558 # certain widgets.
6559 #
6560 # NORMAL - The normal state of a widget, without the mouse over top of
6561 # it, and not being pressed etc.
6562 #
6563 # PRELIGHT - When the mouse is over top of the widget, colors defined
6564 # using this state will be in effect.
6565 #
6566 # ACTIVE - When the widget is pressed or clicked it will be active, and
6567 # the attributes assigned by this tag will be in effect.
6568 #
6569 # INSENSITIVE - When a widget is set insensitive, and cannot be
6570 # activated, it will take these attributes.
6571 #
6572 # SELECTED - When an object is selected, it takes these attributes.
6573 #
6574 # Given these states, we can set the attributes of the widgets in each of
6575 # these states using the following directives.
6576 #
6577 # fg - Sets the foreground color of a widget.
6578 # fg - Sets the background color of a widget.
6579 # bg_pixmap - Sets the background of a widget to a tiled pixmap.
6580 # font - Sets the font to be used with the given widget.
6581 #
6582
6583 # This sets a style called "button".  The name is not really important, as
6584 # it is assigned to the actual widgets at the bottom of the file.
6585
6586 style "window"
6587 {
6588   #This sets the padding around the window to the pixmap specified.
6589   #bg_pixmap[<STATE>] = "<pixmap filename>"
6590   bg_pixmap[NORMAL] = "warning.xpm"
6591 }
6592
6593 style "scale"
6594 {
6595   #Sets the foreground color (font color) to red when in the "NORMAL"
6596   #state.
6597   
6598   fg[NORMAL] = { 1.0, 0, 0 }
6599   
6600   #Sets the background pixmap of this widget to that of it's parent.
6601   bg_pixmap[NORMAL] = "<parent>"
6602 }
6603
6604 style "button"
6605 {
6606   # This shows all the possible states for a button.  The only one that
6607   # doesn't apply is the SELECTED state.
6608   
6609   fg[PRELIGHT] = { 0, 1.0, 1.0 }
6610   bg[PRELIGHT] = { 0, 0, 1.0 }
6611   bg[ACTIVE] = { 1.0, 0, 0 }
6612   fg[ACTIVE] = { 0, 1.0, 0 }
6613   bg[NORMAL] = { 1.0, 1.0, 0 }
6614   fg[NORMAL] = { .99, 0, .99 }
6615   bg[INSENSITIVE] = { 1.0, 1.0, 1.0 }
6616   fg[INSENSITIVE] = { 1.0, 0, 1.0 }
6617 }
6618
6619 # In this example, we inherit the attributes of the "button" style and then
6620 # override the font and background color when prelit to create a new
6621 # "main_button" style.
6622
6623 style "main_button" = "button"
6624 {
6625   font = "-adobe-helvetica-medium-r-normal--*-100-*-*-*-*-*-*"
6626   bg[PRELIGHT] = { 0.75, 0, 0 }
6627 }
6628
6629 style "toggle_button" = "button"
6630 {
6631   fg[NORMAL] = { 1.0, 0, 0 }
6632   fg[ACTIVE] = { 1.0, 0, 0 }
6633   
6634   # This sets the background pixmap of the toggle_button to that of it's
6635   # parent widget (as defined in the application).
6636   bg_pixmap[NORMAL] = "<parent>"
6637 }
6638
6639 style "text"
6640 {
6641   bg_pixmap[NORMAL] = "marble.xpm"
6642   fg[NORMAL] = { 1.0, 1.0, 1.0 }
6643 }
6644
6645 style "ruler"
6646 {
6647   font = "-adobe-helvetica-medium-r-normal--*-80-*-*-*-*-*-*"
6648 }
6649
6650 # pixmap_path "~/.pixmaps"
6651
6652 # These set the widget types to use the styles defined above.
6653 # The widget types are listed in the class hierarchy, but could probably be
6654 # just listed in this document for the users reference.
6655
6656 widget_class "GtkWindow" style "window"
6657 widget_class "GtkDialog" style "window"
6658 widget_class "GtkFileSelection" style "window"
6659 widget_class "*Gtk*Scale" style "scale"
6660 widget_class "*GtkCheckButton*" style "toggle_button"
6661 widget_class "*GtkRadioButton*" style "toggle_button"
6662 widget_class "*GtkButton*" style "button"
6663 widget_class "*Ruler" style "ruler"
6664 widget_class "*GtkText" style "text"
6665
6666 # This sets all the buttons that are children of the "main window" to
6667 # the main_buton style.  These must be documented to be taken advantage of.
6668 widget "main window.*GtkButton*" style "main_button"
6669 </verb></tscreen>
6670
6671 <!-- ***************************************************************** -->
6672 <sect>Writing Your Own Widgets 
6673 <!-- ***************************************************************** -->
6674
6675 <!-- ----------------------------------------------------------------- -->
6676 <sect1> Overview
6677 <p>
6678 Although the GTK distribution comes with many types of widgets that
6679 should cover most basic needs, there may come a time when you need to
6680 create your own new widget type. Since GTK uses widget inheretence
6681 extensively, and there is already a widget that
6682 is close to what you want, it is often possible to make a useful new widget type in
6683 just a few lines of code.  But before starting work on a new widget, check
6684 around first to make sure that someone has not already written
6685 it. This will prevent duplication of effort and keep the number of
6686 GTK widgets out there to a minimum, which will help keep both the code
6687 and the interface of different applications consistent. As a flip side
6688 to this, once you finish your widget, announce it to the world so
6689 other people can benefit. The best place to do this is probably the
6690 <tt>gtk-list</tt>.
6691
6692 Complete sources for the example widgets are available at the place you 
6693 got this tutorial, or from:
6694
6695 <htmlurl url="http://www.msc.cornell.edu/~otaylor/gtk-gimp/tutorial"
6696 name="http://www.msc.cornell.edu/~otaylor/gtk-gimp/tutorial">
6697
6698
6699 <!-- ----------------------------------------------------------------- -->
6700 <sect1> The Anatomy Of A Widget
6701
6702 <p>
6703 In order to create a new widget, it is important to have an
6704 understanding of how GTK objects work. This section is just meant as a
6705 brief overview. See the reference documentation for the details. 
6706
6707 <p>
6708 GTK widgets are implemented in an object oriented fashion. However,
6709 they are implemented in standard C. This greatly improves portability
6710 and stability over using current generation C++ compilers; however,
6711 it does mean that the widget writer has to pay attention to some of
6712 the implementation details. The information common to all instances of
6713 one class of widgets (e.g., to all Button widgets) is stored in the 
6714 <em>class structure</em>. There is only one copy of this in
6715 which is stored information about the class's signals
6716 (which act like virtual functions in C). To support inheritance, the
6717 first field in the class structure must be a copy of the parent's
6718 class structure. The declaration of the class structure of GtkButtton
6719 looks like:
6720
6721 <tscreen><verb>
6722 struct _GtkButtonClass
6723 {
6724   GtkContainerClass parent_class;
6725
6726   void (* pressed)  (GtkButton *button);
6727   void (* released) (GtkButton *button);
6728   void (* clicked)  (GtkButton *button);
6729   void (* enter)    (GtkButton *button);
6730   void (* leave)    (GtkButton *button);
6731 };
6732 </verb></tscreen>
6733
6734 <p>
6735 When a button is treated as a container (for instance, when it is
6736 resized), its class structure can be casted to GtkContainerClass, and
6737 the relevant fields used to handle the signals.
6738
6739 <p>
6740 There is also a structure for each widget that is created on a
6741 per-instance basis. This structure has fields to store information that
6742 is different for each instance of the widget. We'll call this
6743 structure the <em>object structure</em>. For the Button class, it looks
6744 like:
6745
6746 <tscreen><verb>
6747 struct _GtkButton
6748 {
6749   GtkContainer container;
6750
6751   GtkWidget *child;
6752
6753   guint in_button : 1;
6754   guint button_down : 1;
6755 };
6756 </verb></tscreen>
6757
6758 <p>
6759 Note that, similar to the class structure, the first field is the
6760 object structure of the parent class, so that this structure can be
6761 casted to the parent class's object structure as needed.
6762
6763 <!-- ----------------------------------------------------------------- -->
6764 <sect1> Creating a Composite widget
6765
6766 <!-- ----------------------------------------------------------------- -->
6767 <sect2> Introduction
6768
6769 <p>
6770 One type of widget that you may be interested in creating is a
6771 widget that is merely an aggregate of other GTK widgets. This type of
6772 widget does nothing that couldn't be done without creating new
6773 widgets, but provides a convenient way of packaging user interface
6774 elements for reuse. The FileSelection and ColorSelection widgets in
6775 the standard distribution are examples of this type of widget.
6776
6777 <p>
6778 The example widget that we'll create in this section is the Tictactoe
6779 widget, a 3x3 array of toggle buttons which triggers a signal when all
6780 three buttons in a row, column, or on one of the diagonals are
6781 depressed. 
6782
6783 <!-- ----------------------------------------------------------------- -->
6784 <sect2> Choosing a parent class
6785
6786 <p>
6787 The parent class for a composite widget is typically the container
6788 class that holds all of the elements of the composite widget. For
6789 example, the parent class of the FileSelection widget is the
6790 Dialog class. Since our buttons will be arranged in a table, it
6791 might seem natural to make our parent class the GtkTable
6792 class. Unfortunately, this turns out not to work. The creation of a
6793 widget is divided among two functions - a <tt/WIDGETNAME_new()/
6794 function that the user calls, and a <tt/WIDGETNAME_init()/ function
6795 which does the basic work of initializing the widget which is
6796 independent of the arguments passed to the <tt/_new()/
6797 function. Descendent widgets only call the <tt/_init/ function of
6798 their parent widget. But this division of labor doesn't work well for
6799 tables, which when created, need to know the number of rows and
6800 columns in the table. Unless we want to duplicate most of the
6801 functionality of <tt/gtk_table_new()/ in our Tictactoe widget, we had
6802 best avoid deriving it from GtkTable. For that reason, we derive it
6803 from GtkVBox instead, and stick our table inside the VBox.
6804
6805 <!-- ----------------------------------------------------------------- -->
6806 <sect2> The header file
6807
6808 <p>
6809 Each widget class has a header file which declares the object and
6810 class structures for that widget, along with public functions. 
6811 A couple of features are worth pointing out. To prevent duplicate
6812 definitions, we wrap the entire header file in:
6813
6814 <tscreen><verb>
6815 #ifndef __TICTACTOE_H__
6816 #define __TICTACTOE_H__
6817 .
6818 .
6819 .
6820 #endif /* __TICTACTOE_H__ */
6821 </verb></tscreen>
6822
6823 And to keep C++ programs that include the header file happy, in:
6824
6825 <tscreen><verb>
6826 #ifdef __cplusplus
6827 extern "C" {
6828 #endif /* __cplusplus */
6829 .
6830 .
6831 .
6832 #ifdef __cplusplus
6833 }
6834 #endif /* __cplusplus */
6835 </verb></tscreen>
6836
6837 Along with the functions and structures, we declare three standard
6838 macros in our header file, <tt/TICTACTOE(obj)/,
6839 <tt/TICTACTOE_CLASS(klass)/, and <tt/IS_TICTACTOE(obj)/, which cast a
6840 pointer into a pointer to the the object or class structure, and check
6841 if an object is a Tictactoe widget respectively.
6842
6843 <p>
6844 Here is the complete header file:
6845
6846 <tscreen><verb>
6847 /* tictactoe.h */
6848
6849 #ifndef __TICTACTOE_H__
6850 #define __TICTACTOE_H__
6851
6852 #include <gdk/gdk.h>
6853 #include <gtk/gtkvbox.h>
6854
6855 #ifdef __cplusplus
6856 extern "C" {
6857 #endif /* __cplusplus */
6858
6859 #define TICTACTOE(obj)          GTK_CHECK_CAST (obj, tictactoe_get_type (), Tictactoe)
6860 #define TICTACTOE_CLASS(klass)  GTK_CHECK_CLASS_CAST (klass, tictactoe_get_type (), TictactoeClass)
6861 #define IS_TICTACTOE(obj)       GTK_CHECK_TYPE (obj, tictactoe_get_type ())
6862
6863
6864 typedef struct _Tictactoe       Tictactoe;
6865 typedef struct _TictactoeClass  TictactoeClass;
6866
6867 struct _Tictactoe
6868 {
6869   GtkVBox vbox;
6870   
6871   GtkWidget *buttons[3][3];
6872 };
6873
6874 struct _TictactoeClass
6875 {
6876   GtkVBoxClass parent_class;
6877
6878   void (* tictactoe) (Tictactoe *ttt);
6879 };
6880
6881 guint          tictactoe_get_type        (void);
6882 GtkWidget*     tictactoe_new             (void);
6883 void           tictactoe_clear           (Tictactoe *ttt);
6884
6885 #ifdef __cplusplus
6886 }
6887 #endif /* __cplusplus */
6888
6889 #endif /* __TICTACTOE_H__ */
6890
6891 </verb></tscreen>
6892
6893 <!-- ----------------------------------------------------------------- -->
6894 <sect2> The <tt/_get_type()/ function.
6895
6896 <p>
6897 We now continue on to the implementation of our widget. A core
6898 function for every widget is the function
6899 <tt/WIDGETNAME_get_type()/. This function, when first called, tells
6900 GTK about the widget class, and gets an ID that uniquely identifies
6901 the widget class. Upon subsequent calls, it just returns the ID.
6902
6903 <tscreen><verb>
6904 guint
6905 tictactoe_get_type ()
6906 {
6907   static guint ttt_type = 0;
6908
6909   if (!ttt_type)
6910     {
6911       GtkTypeInfo ttt_info =
6912       {
6913         "Tictactoe",
6914         sizeof (Tictactoe),
6915         sizeof (TictactoeClass),
6916         (GtkClassInitFunc) tictactoe_class_init,
6917         (GtkObjectInitFunc) tictactoe_init,
6918         (GtkArgFunc) NULL,
6919       };
6920
6921       ttt_type = gtk_type_unique (gtk_vbox_get_type (), &amp;ttt_info);
6922     }
6923
6924   return ttt_type;
6925 }
6926 </verb></tscreen>
6927
6928 <p>
6929 The GtkTypeInfo structure has the following definition:
6930
6931 <tscreen><verb>
6932 struct _GtkTypeInfo
6933 {
6934   gchar *type_name;
6935   guint object_size;
6936   guint class_size;
6937   GtkClassInitFunc class_init_func;
6938   GtkObjectInitFunc object_init_func;
6939   GtkArgFunc arg_func;
6940 };
6941 </verb></tscreen>
6942
6943 <p>
6944 The fields of this structure are pretty self-explanatory. We'll ignore
6945 the <tt/arg_func/ field here: It has an important, but as yet largely
6946 unimplemented, role in allowing widget options to be conveniently set
6947 from interpreted languages. Once GTK has a correctly filled in copy of
6948 this structure, it knows how to create objects of a particular widget
6949 type. 
6950
6951 <!-- ----------------------------------------------------------------- -->
6952 <sect2> The <tt/_class_init()/ function
6953
6954 <p>
6955 The <tt/WIDGETNAME_class_init()/ function initializes the fields of
6956 the widget's class structure, and sets up any signals for the
6957 class. For our Tictactoe widget it looks like:
6958
6959 <tscreen><verb>
6960
6961 enum {
6962   TICTACTOE_SIGNAL,
6963   LAST_SIGNAL
6964 };
6965
6966 static gint tictactoe_signals[LAST_SIGNAL] = { 0 };
6967
6968 static void
6969 tictactoe_class_init (TictactoeClass *class)
6970 {
6971   GtkObjectClass *object_class;
6972
6973   object_class = (GtkObjectClass*) class;
6974   
6975   tictactoe_signals[TICTACTOE_SIGNAL] = gtk_signal_new ("tictactoe",
6976                                          GTK_RUN_FIRST,
6977                                          object_class->type,
6978                                          GTK_SIGNAL_OFFSET (TictactoeClass, tictactoe),
6979                                          gtk_signal_default_marshaller, GTK_ARG_NONE, 0);
6980
6981
6982   gtk_object_class_add_signals (object_class, tictactoe_signals, LAST_SIGNAL);
6983
6984   class->tictactoe = NULL;
6985 }
6986 </verb></tscreen>
6987
6988 <p>
6989 Our widget has just one signal, the ``tictactoe'' signal that is
6990 invoked when a row, column, or diagonal is completely filled in. Not
6991 every composite widget needs signals, so if you are reading this for
6992 the first time, you may want to skip to the next section now, as
6993 things are going to get a bit complicated.
6994
6995 The function:
6996
6997 <tscreen><verb>
6998 gint   gtk_signal_new                     (gchar               *name,
6999                                            GtkSignalRunType     run_type,
7000                                            gint                 object_type,
7001                                            gint                 function_offset,
7002                                            GtkSignalMarshaller  marshaller,
7003                                            GtkArgType           return_val,
7004                                            gint                 nparams,
7005                                            ...);
7006 </verb></tscreen>
7007
7008 Creates a new signal. The parameters are:
7009
7010 <itemize>
7011 <item> <tt/name/: The name of the signal.
7012 <item> <tt/run_type/: Whether the default handler runs before or after
7013 user handlers. Usually this will be <tt/GTK_RUN_FIRST/, or <tt/GTK_RUN_LAST/,
7014 although there are other possibilities.
7015 <item> <tt/object_type/: The ID of the object that this signal applies
7016 to. (It will also apply to that objects descendents)
7017 <item> <tt/function_offset/: The offset within the class structure of
7018 a pointer to the default handler.
7019 <item> <tt/marshaller/: A function that is used to invoke the signal
7020 handler. For signal handlers that have no arguments other than the
7021 object that emitted the signal and user data, we can use the
7022 presupplied marshaller function <tt/gtk_signal_default_marshaller/.
7023 <item> <tt/return_val/: The type of the return val.
7024 <item> <tt/nparams/: The number of parameters of the signal handler
7025 (other than the two default ones mentioned above)
7026 <item> <tt/.../: The types of the parameters.
7027 </itemize>
7028
7029 When specifying types, the <tt/GtkArgType/ enumeration is used:
7030
7031 <tscreen><verb>
7032 typedef enum
7033 {
7034   GTK_ARG_INVALID,
7035   GTK_ARG_NONE,
7036   GTK_ARG_CHAR,
7037   GTK_ARG_SHORT,
7038   GTK_ARG_INT,
7039   GTK_ARG_LONG,
7040   GTK_ARG_POINTER,
7041   GTK_ARG_OBJECT,
7042   GTK_ARG_FUNCTION,
7043   GTK_ARG_SIGNAL
7044 } GtkArgType;
7045 </verb></tscreen>
7046
7047 <p>
7048 <tt/gtk_signal_new()/ returns a unique integer identifier for the
7049 signal, that we store in the <tt/tictactoe_signals/ array, which we
7050 index using an enumeration. (Conventionally, the enumeration elements
7051 are the signal name, uppercased, but here there would be a conflict
7052 with the <tt/TICTACTOE()/ macro, so we called it <tt/TICTACTOE_SIGNAL/
7053 instead.
7054
7055 After creating our signals, we need to tell GTK to associate our
7056 signals with the Tictactoe class. We do that by calling
7057 <tt/gtk_object_class_add_signals()/. We then set the pointer which
7058 points to the default handler for the ``tictactoe'' signal to NULL,
7059 indicating that there is no default action.
7060
7061 <!-- ----------------------------------------------------------------- -->
7062 <sect2> The <tt/_init()/ function.
7063
7064 <p>
7065
7066 Each widget class also needs a function to initialize the object
7067 structure. Usually, this function has the fairly limited role of
7068 setting the fields of the structure to default values. For composite
7069 widgets, however, this function also creates the component widgets.
7070
7071 <tscreen><verb>
7072
7073 static void
7074 tictactoe_init (Tictactoe *ttt)
7075 {
7076   GtkWidget *table;
7077   gint i,j;
7078   
7079   table = gtk_table_new (3, 3, TRUE);
7080   gtk_container_add (GTK_CONTAINER(ttt), table);
7081   gtk_widget_show (table);
7082
7083   for (i=0;i<3; i++)
7084     for (j=0;j<3; j++)
7085       {
7086         ttt->buttons[i][j] = gtk_toggle_button_new ();
7087         gtk_table_attach_defaults (GTK_TABLE(table), ttt->buttons[i][j], 
7088                                    i, i+1, j, j+1);
7089         gtk_signal_connect (GTK_OBJECT (ttt->buttons[i][j]), "toggled",
7090                             GTK_SIGNAL_FUNC (tictactoe_toggle), ttt);
7091         gtk_widget_set_usize (ttt->buttons[i][j], 20, 20);
7092         gtk_widget_show (ttt->buttons[i][j]);
7093       }
7094 }
7095 </verb></tscreen>
7096
7097 <!-- ----------------------------------------------------------------- -->
7098 <sect2> And the rest...
7099
7100 <p>
7101
7102 There is one more function that every widget (except for base widget
7103 types like GtkBin that cannot be instantiated) needs to have - the
7104 function that the user calls to create an object of that type. This is
7105 conventionally called <tt/WIDGETNAME_new()/In some
7106 widgets, thought not for the Tictactoe widgets, this function takes
7107 arguments, and does some setup based on the arguments. The other two
7108 functions are specific to the Tictactoe widget. 
7109
7110 <p>
7111 <tt/tictactoe_clear()/ is a public function that resets all the
7112 buttons in the widget to the up position. Note the use of
7113 <tt/gtk_signal_handler_block_by_data()/ to keep our signal handler for
7114 button toggles from being triggered unnecessarily.
7115
7116 <p>
7117 <tt/tictactoe_toggle()/ is the signal handler that is invoked when the
7118 user clicks on a button. It checks to see if there are any winning
7119 combinations that involve the toggled button, and if so, emits
7120 the "tictactoe" signal.
7121
7122 <tscreen><verb>  
7123 GtkWidget*
7124 tictactoe_new ()
7125 {
7126   return GTK_WIDGET ( gtk_type_new (tictactoe_get_type ()));
7127 }
7128
7129 void           
7130 tictactoe_clear (Tictactoe *ttt)
7131 {
7132   int i,j;
7133
7134   for (i=0;i<3;i++)
7135     for (j=0;j<3;j++)
7136       {
7137         gtk_signal_handler_block_by_data (GTK_OBJECT(ttt->buttons[i][j]), ttt);
7138         gtk_toggle_button_set_state (GTK_TOGGLE_BUTTON (ttt->buttons[i][j]),
7139                                      FALSE);
7140         gtk_signal_handler_unblock_by_data (GTK_OBJECT(ttt->buttons[i][j]), ttt);
7141       }
7142 }
7143
7144 static void
7145 tictactoe_toggle (GtkWidget *widget, Tictactoe *ttt)
7146 {
7147   int i,k;
7148
7149   static int rwins[8][3] = { { 0, 0, 0 }, { 1, 1, 1 }, { 2, 2, 2 },
7150                              { 0, 1, 2 }, { 0, 1, 2 }, { 0, 1, 2 },
7151                              { 0, 1, 2 }, { 0, 1, 2 } };
7152   static int cwins[8][3] = { { 0, 1, 2 }, { 0, 1, 2 }, { 0, 1, 2 },
7153                              { 0, 0, 0 }, { 1, 1, 1 }, { 2, 2, 2 },
7154                              { 0, 1, 2 }, { 2, 1, 0 } };
7155
7156   int success, found;
7157
7158   for (k=0; k<8; k++)
7159     {
7160       success = TRUE;
7161       found = FALSE;
7162
7163       for (i=0;i<3;i++)
7164         {
7165           success = success &amp;&amp; 
7166             GTK_TOGGLE_BUTTON(ttt->buttons[rwins[k][i]][cwins[k][i]])->active;
7167           found = found ||
7168             ttt->buttons[rwins[k][i]][cwins[k][i]] == widget;
7169         }
7170       
7171       if (success &amp;&amp; found)
7172         {
7173           gtk_signal_emit (GTK_OBJECT (ttt), 
7174                            tictactoe_signals[TICTACTOE_SIGNAL]);
7175           break;
7176         }
7177     }
7178 }
7179 </verb></tscreen>
7180
7181 <p>
7182
7183 And finally, an example program using our Tictactoe widget:
7184
7185 <tscreen><verb>
7186 #include <gtk/gtk.h>
7187 #include "tictactoe.h"
7188
7189 /* Invoked when a row, column or diagonal is completed */
7190 void
7191 win (GtkWidget *widget, gpointer data)
7192 {
7193   g_print ("Yay!\n");
7194   tictactoe_clear (TICTACTOE (widget));
7195 }
7196
7197 int 
7198 main (int argc, char *argv[])
7199 {
7200   GtkWidget *window;
7201   GtkWidget *ttt;
7202   
7203   gtk_init (&amp;argc, &amp;argv);
7204
7205   window = gtk_window_new (GTK_WINDOW_TOPLEVEL);
7206   
7207   gtk_window_set_title (GTK_WINDOW (window), "Aspect Frame");
7208   
7209   gtk_signal_connect (GTK_OBJECT (window), "destroy",
7210                       GTK_SIGNAL_FUNC (gtk_exit), NULL);
7211   
7212   gtk_container_border_width (GTK_CONTAINER (window), 10);
7213
7214   /* Create a new Tictactoe widget */
7215   ttt = tictactoe_new ();
7216   gtk_container_add (GTK_CONTAINER (window), ttt);
7217   gtk_widget_show (ttt);
7218
7219   /* And attach to its "tictactoe" signal */
7220   gtk_signal_connect (GTK_OBJECT (ttt), "tictactoe",
7221                       GTK_SIGNAL_FUNC (win), NULL);
7222
7223   gtk_widget_show (window);
7224   
7225   gtk_main ();
7226   
7227   return 0;
7228 }
7229
7230 </verb></tscreen>
7231
7232 <!-- ----------------------------------------------------------------- -->
7233 <sect1> Creating a widget from scratch.
7234
7235 <!-- ----------------------------------------------------------------- -->
7236 <sect2> Introduction
7237
7238 <p>
7239
7240 In this section, we'll learn more about how widgets display themselves
7241 on the screen and interact with events. As an example of this, we'll
7242 create a analog dial widget with a pointer that the user can drag to
7243 set the value.
7244
7245 <!-- ----------------------------------------------------------------- -->
7246 <sect2> Displaying a widget on the screen
7247
7248 <p>
7249 There are several steps that are involved in displaying on the screen.
7250 After the widget is created with a call to <tt/WIDGETNAME_new()/,
7251 several more functions are needed:
7252
7253 <itemize>
7254 <item> <tt/WIDGETNAME_realize()/ is responsible for creating an X
7255 window for the widget if it has one.
7256 <item> <tt/WIDGETNAME_map()/ is invoked after the user calls
7257 <tt/gtk_widget_show()/. It is responsible for making sure the widget
7258 is actually drawn on the screen (<em/mapped/). For a container class,
7259 it must also make calls to <tt/map()/> functions of any child widgets.
7260 <item> <tt/WIDGETNAME_draw()/ is invoked when <tt/gtk_widget_draw()/
7261 is called for the widget or one of its ancestors. It makes the actual
7262 calls to the drawing functions to draw the widget on the screen. For
7263 container widgets, this function must make calls to
7264 <tt/gtk_widget_draw()/ for its child widgets.
7265 <item> <tt/WIDGETNAME_expose()/ is a handler for expose events for the
7266 widget. It makes the necessary calls to the drawing functions to draw
7267 the exposed portion on the screen. For container widgets, this
7268 function must generate expose events for its child widgets which don't
7269 have their own windows. (If they have their own windows, then X will
7270 generate the necessary expose events)
7271 </itemize>
7272
7273 <p>
7274 You might notice that the last two functions are quite similar - each
7275 is responsible for drawing the widget on the screen. In fact many
7276 types of widgets don't really care about the difference between the
7277 two. The default <tt/draw()/ function in the widget class simply
7278 generates a synthetic expose event for the redrawn area. However, some
7279 types of widgets can save work by distinguishing between the two
7280 functions. For instance, if a widget has multiple X windows, then
7281 since expose events identify the exposed window, it can redraw only
7282 the affected window, which is not possible for calls to <tt/draw()/.
7283
7284 <p>
7285 Container widgets, even if they don't care about the difference for
7286 themselves, can't simply use the default <tt/draw()/ function because
7287 their child widgets might care about the difference. However,
7288 it would be wasteful to duplicate the drawing code between the two
7289 functions. The convention is that such widgets have a function called
7290 <tt/WIDGETNAME_paint()/ that does the actual work of drawing the
7291 widget, that is then called by the <tt/draw()/ and <tt/expose()/
7292 functions.
7293
7294 <p>
7295 In our example approach, since the dial widget is not a container
7296 widget, and only has a single window, we can take the simplest
7297 approach and use the default <tt/draw()/ function and only implement
7298 an <tt/expose()/ function.
7299
7300 <!-- ----------------------------------------------------------------- -->
7301 <sect2> The origins of the Dial Widget
7302
7303 <p>
7304 Just as all land animals are just variants on the first amphibian that
7305 crawled up out of the mud, Gtk widgets tend to start off as variants
7306 of some other, previously written widget.  Thus, although this section
7307 is entilted ``Creating a Widget from Scratch'', the Dial widget really
7308 began with the source code for the Range widget. This was picked as a
7309 starting point because it would be nice if our Dial had the same
7310 interface as the Scale widgets which are just specialized descendents
7311 of the Range widget. So, though the source code is presented below in
7312 finished form, it should not be implied that it was written, <em>deus
7313 ex machina</em> in this fashion. Also, if you aren't yet familiar with
7314 how scale widgets work from the application writer's point of view, it
7315 would be a good idea to look them over before continuing.
7316
7317 <!-- ----------------------------------------------------------------- -->
7318 <sect2> The Basics
7319
7320 <p>
7321 Quite a bit of our widget should look pretty familiar from the
7322 Tictactoe widget. First, we have a header file:
7323
7324 <tscreen><verb>
7325 /* GTK - The GIMP Toolkit
7326  * Copyright (C) 1995-1997 Peter Mattis, Spencer Kimball and Josh MacDonald
7327  *
7328  * This library is free software; you can redistribute it and/or
7329  * modify it under the terms of the GNU Library General Public
7330  * License as published by the Free Software Foundation; either
7331  * version 2 of the License, or (at your option) any later version.
7332  *
7333  * This library is distributed in the hope that it will be useful,
7334  * but WITHOUT ANY WARRANTY; without even the implied warranty of
7335  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
7336  * Library General Public License for more details.
7337  *
7338  * You should have received a copy of the GNU Library General Public
7339  * License along with this library; if not, write to the Free
7340  * Software Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
7341  */
7342
7343 #ifndef __GTK_DIAL_H__
7344 #define __GTK_DIAL_H__
7345
7346 #include <gdk/gdk.h>
7347 #include <gtk/gtkadjustment.h>
7348 #include <gtk/gtkwidget.h>
7349
7350
7351 #ifdef __cplusplus
7352 extern "C" {
7353 #endif /* __cplusplus */
7354
7355
7356 #define GTK_DIAL(obj)          GTK_CHECK_CAST (obj, gtk_dial_get_type (), GtkDial)
7357 #define GTK_DIAL_CLASS(klass)  GTK_CHECK_CLASS_CAST (klass, gtk_dial_get_type (), GtkDialClass)
7358 #define GTK_IS_DIAL(obj)       GTK_CHECK_TYPE (obj, gtk_dial_get_type ())
7359
7360
7361 typedef struct _GtkDial        GtkDial;
7362 typedef struct _GtkDialClass   GtkDialClass;
7363
7364 struct _GtkDial
7365 {
7366   GtkWidget widget;
7367
7368   /* update policy (GTK_UPDATE_[CONTINUOUS/DELAYED/DISCONTINUOUS]) */
7369   guint policy : 2;
7370
7371   /* Button currently pressed or 0 if none */
7372   guint8 button;
7373
7374   /* Dimensions of dial components */
7375   gint radius;
7376   gint pointer_width;
7377
7378   /* ID of update timer, or 0 if none */
7379   guint32 timer;
7380
7381   /* Current angle */
7382   gfloat angle;
7383
7384   /* Old values from adjustment stored so we know when something changes */
7385   gfloat old_value;
7386   gfloat old_lower;
7387   gfloat old_upper;
7388
7389   /* The adjustment object that stores the data for this dial */
7390   GtkAdjustment *adjustment;
7391 };
7392
7393 struct _GtkDialClass
7394 {
7395   GtkWidgetClass parent_class;
7396 };
7397
7398
7399 GtkWidget*     gtk_dial_new                    (GtkAdjustment *adjustment);
7400 guint          gtk_dial_get_type               (void);
7401 GtkAdjustment* gtk_dial_get_adjustment         (GtkDial      *dial);
7402 void           gtk_dial_set_update_policy      (GtkDial      *dial,
7403                                                 GtkUpdateType  policy);
7404
7405 void           gtk_dial_set_adjustment         (GtkDial      *dial,
7406                                                 GtkAdjustment *adjustment);
7407 #ifdef __cplusplus
7408 }
7409 #endif /* __cplusplus */
7410
7411
7412 #endif /* __GTK_DIAL_H__ */
7413
7414 </verb></tscreen>
7415
7416 Since there is quite a bit more going on in this widget, than the last
7417 one, we have more fields in the data structure, but otherwise things
7418 are pretty similar.
7419
7420 <p>
7421
7422 Next, after including header files, and declaring a few constants,
7423 we have some functions to provide information about the widget
7424 and initialize it:
7425
7426 <tscreen><verb>
7427 #include <math.h>
7428 #include <stdio.h>
7429 #include <gtk/gtkmain.h>
7430 #include <gtk/gtksignal.h>
7431
7432 #include "gtkdial.h"
7433
7434 #define SCROLL_DELAY_LENGTH  300
7435 #define DIAL_DEFAULT_SIZE 100
7436
7437 /* Forward declararations */
7438
7439 [ omitted to save space ]
7440
7441 /* Local data */
7442
7443 static GtkWidgetClass *parent_class = NULL;
7444
7445 guint
7446 gtk_dial_get_type ()
7447 {
7448   static guint dial_type = 0;
7449
7450   if (!dial_type)
7451     {
7452       GtkTypeInfo dial_info =
7453       {
7454         "GtkDial",
7455         sizeof (GtkDial),
7456         sizeof (GtkDialClass),
7457         (GtkClassInitFunc) gtk_dial_class_init,
7458         (GtkObjectInitFunc) gtk_dial_init,
7459         (GtkArgFunc) NULL,
7460       };
7461
7462       dial_type = gtk_type_unique (gtk_widget_get_type (), &amp;dial_info);
7463     }
7464
7465   return dial_type;
7466 }
7467
7468 static void
7469 gtk_dial_class_init (GtkDialClass *class)
7470 {
7471   GtkObjectClass *object_class;
7472   GtkWidgetClass *widget_class;
7473
7474   object_class = (GtkObjectClass*) class;
7475   widget_class = (GtkWidgetClass*) class;
7476
7477   parent_class = gtk_type_class (gtk_widget_get_type ());
7478
7479   object_class->destroy = gtk_dial_destroy;
7480
7481   widget_class->realize = gtk_dial_realize;
7482   widget_class->expose_event = gtk_dial_expose;
7483   widget_class->size_request = gtk_dial_size_request;
7484   widget_class->size_allocate = gtk_dial_size_allocate;
7485   widget_class->button_press_event = gtk_dial_button_press;
7486   widget_class->button_release_event = gtk_dial_button_release;
7487   widget_class->motion_notify_event = gtk_dial_motion_notify;
7488 }
7489
7490 static void
7491 gtk_dial_init (GtkDial *dial)
7492 {
7493   dial->button = 0;
7494   dial->policy = GTK_UPDATE_CONTINUOUS;
7495   dial->timer = 0;
7496   dial->radius = 0;
7497   dial->pointer_width = 0;
7498   dial->angle = 0.0;
7499   dial->old_value = 0.0;
7500   dial->old_lower = 0.0;
7501   dial->old_upper = 0.0;
7502   dial->adjustment = NULL;
7503 }
7504
7505 GtkWidget*
7506 gtk_dial_new (GtkAdjustment *adjustment)
7507 {
7508   GtkDial *dial;
7509
7510   dial = gtk_type_new (gtk_dial_get_type ());
7511
7512   if (!adjustment)
7513     adjustment = (GtkAdjustment*) gtk_adjustment_new (0.0, 0.0, 0.0, 0.0, 0.0, 0.0);
7514
7515   gtk_dial_set_adjustment (dial, adjustment);
7516
7517   return GTK_WIDGET (dial);
7518 }
7519
7520 static void
7521 gtk_dial_destroy (GtkObject *object)
7522 {
7523   GtkDial *dial;
7524
7525   g_return_if_fail (object != NULL);
7526   g_return_if_fail (GTK_IS_DIAL (object));
7527
7528   dial = GTK_DIAL (object);
7529
7530   if (dial->adjustment)
7531     gtk_object_unref (GTK_OBJECT (dial->adjustment));
7532
7533   if (GTK_OBJECT_CLASS (parent_class)->destroy)
7534     (* GTK_OBJECT_CLASS (parent_class)->destroy) (object);
7535 }
7536 </verb></tscreen>
7537
7538 Note that this <tt/init()/ function does less than for the Tictactoe
7539 widget, since this is not a composite widget, and the <tt/new()/
7540 function does more, since it now has an argument. Also, note that when
7541 we store a pointer to the Adjustment object, we increment its
7542 reference count, (and correspondingly decrement when we no longer use
7543 it) so that GTK can keep track of when it can be safely destroyed.
7544
7545 <p>
7546 Also, there are a few function to manipulate the widget's options:
7547
7548 <tscreen><verb>
7549 GtkAdjustment*
7550 gtk_dial_get_adjustment (GtkDial *dial)
7551 {
7552   g_return_val_if_fail (dial != NULL, NULL);
7553   g_return_val_if_fail (GTK_IS_DIAL (dial), NULL);
7554
7555   return dial->adjustment;
7556 }
7557
7558 void
7559 gtk_dial_set_update_policy (GtkDial      *dial,
7560                              GtkUpdateType  policy)
7561 {
7562   g_return_if_fail (dial != NULL);
7563   g_return_if_fail (GTK_IS_DIAL (dial));
7564
7565   dial->policy = policy;
7566 }
7567
7568 void
7569 gtk_dial_set_adjustment (GtkDial      *dial,
7570                           GtkAdjustment *adjustment)
7571 {
7572   g_return_if_fail (dial != NULL);
7573   g_return_if_fail (GTK_IS_DIAL (dial));
7574
7575   if (dial->adjustment)
7576     {
7577       gtk_signal_disconnect_by_data (GTK_OBJECT (dial->adjustment), (gpointer) dial);
7578       gtk_object_unref (GTK_OBJECT (dial->adjustment));
7579     }
7580
7581   dial->adjustment = adjustment;
7582   gtk_object_ref (GTK_OBJECT (dial->adjustment));
7583
7584   gtk_signal_connect (GTK_OBJECT (adjustment), "changed",
7585                       (GtkSignalFunc) gtk_dial_adjustment_changed,
7586                       (gpointer) dial);
7587   gtk_signal_connect (GTK_OBJECT (adjustment), "value_changed",
7588                       (GtkSignalFunc) gtk_dial_adjustment_value_changed,
7589                       (gpointer) dial);
7590
7591   dial->old_value = adjustment->value;
7592   dial->old_lower = adjustment->lower;
7593   dial->old_upper = adjustment->upper;
7594
7595   gtk_dial_update (dial);
7596 }
7597 </verb></tscreen>
7598
7599 <sect2> <tt/gtk_dial_realize()/
7600
7601 <p>
7602 Now we come to some new types of functions. First, we have a function
7603 that does the work of creating the X window. Notice that a mask is
7604 passed to the function <tt/gdk_window_new()/ which specifies which fields of
7605 the GdkWindowAttr structure actually have data in them (the remaining
7606 fields wll be given default values). Also worth noting is the way the
7607 event mask of the widget is created. We call
7608 <tt/gtk_widget_get_events()/ to retrieve the event mask that the user
7609 has specified for this widget (with <tt/gtk_widget_set_events()/, and
7610 add the events that we are interested in ourselves.
7611
7612 <p>
7613 After creating the window, we set its style and background, and put a
7614 pointer to the widget in the user data field of the GdkWindow. This
7615 last step allows GTK to dispatch events for this window to the correct
7616 widget.
7617
7618 <tscreen><verb>
7619 static void
7620 gtk_dial_realize (GtkWidget *widget)
7621 {
7622   GtkDial *dial;
7623   GdkWindowAttr attributes;
7624   gint attributes_mask;
7625
7626   g_return_if_fail (widget != NULL);
7627   g_return_if_fail (GTK_IS_DIAL (widget));
7628
7629   GTK_WIDGET_SET_FLAGS (widget, GTK_REALIZED);
7630   dial = GTK_DIAL (widget);
7631
7632   attributes.x = widget->allocation.x;
7633   attributes.y = widget->allocation.y;
7634   attributes.width = widget->allocation.width;
7635   attributes.height = widget->allocation.height;
7636   attributes.wclass = GDK_INPUT_OUTPUT;
7637   attributes.window_type = GDK_WINDOW_CHILD;
7638   attributes.event_mask = gtk_widget_get_events (widget) | 
7639     GDK_EXPOSURE_MASK | GDK_BUTTON_PRESS_MASK | 
7640     GDK_BUTTON_RELEASE_MASK | GDK_POINTER_MOTION_MASK |
7641     GDK_POINTER_MOTION_HINT_MASK;
7642   attributes.visual = gtk_widget_get_visual (widget);
7643   attributes.colormap = gtk_widget_get_colormap (widget);
7644
7645   attributes_mask = GDK_WA_X | GDK_WA_Y | GDK_WA_VISUAL | GDK_WA_COLORMAP;
7646   widget->window = gdk_window_new (widget->parent->window, &amp;attributes, attributes_mask);
7647
7648   widget->style = gtk_style_attach (widget->style, widget->window);
7649
7650   gdk_window_set_user_data (widget->window, widget);
7651
7652   gtk_style_set_background (widget->style, widget->window, GTK_STATE_ACTIVE);
7653 }
7654 </verb></tscreen>
7655
7656 <sect2> Size negotiation
7657
7658 <p>
7659 Before the first time that the window containing a widget is
7660 displayed, and whenever the layout of the window changes, GTK asks
7661 each child widget for its desired size. This request is handled by the
7662 function, <tt/gtk_dial_size_request()/. Since our widget isn't a
7663 container widget, and has no real constraints on its size, we just
7664 return a reasonable default value.
7665
7666 <tscreen><verb>
7667 static void 
7668 gtk_dial_size_request (GtkWidget      *widget,
7669                        GtkRequisition *requisition)
7670 {
7671   requisition->width = DIAL_DEFAULT_SIZE;
7672   requisition->height = DIAL_DEFAULT_SIZE;
7673 }
7674 </verb></tscreen>
7675
7676 <p>
7677 After all the widgets have requested an ideal size, the layout of the
7678 window is computed and each child widget is notified of its actual
7679 size. Usually, this will at least as large as the requested size, but
7680 if for instance, the user has resized the window, it may occasionally
7681 be smaller than the requested size. The size notification is handled
7682 by the function <tt/gtk_dial_size_allocate()/. Notice that as well as
7683 computing the sizes of some component pieces for future use, this
7684 routine also does the grunt work of moving the widgets X window into
7685 the new position and size.
7686
7687 <tscreen><verb>
7688 static void
7689 gtk_dial_size_allocate (GtkWidget     *widget,
7690                         GtkAllocation *allocation)
7691 {
7692   GtkDial *dial;
7693
7694   g_return_if_fail (widget != NULL);
7695   g_return_if_fail (GTK_IS_DIAL (widget));
7696   g_return_if_fail (allocation != NULL);
7697
7698   widget->allocation = *allocation;
7699   if (GTK_WIDGET_REALIZED (widget))
7700     {
7701       dial = GTK_DIAL (widget);
7702
7703       gdk_window_move_resize (widget->window,
7704                               allocation->x, allocation->y,
7705                               allocation->width, allocation->height);
7706
7707       dial->radius = MAX(allocation->width,allocation->height) * 0.45;
7708       dial->pointer_width = dial->radius / 5;
7709     }
7710 }
7711 </verb></tscreen>.
7712
7713 <!-- ----------------------------------------------------------------- -->
7714 <sect2> <tt/gtk_dial_expose()/
7715
7716 <p>
7717 As mentioned above, all the drawing of this widget is done in the
7718 handler for expose events. There's not much to remark on here except
7719 the use of the function <tt/gtk_draw_polygon/ to draw the pointer with
7720 three dimensional shading according to the colors stored in the
7721 widget's style.
7722
7723 <tscreen><verb>
7724 static gint
7725 gtk_dial_expose (GtkWidget      *widget,
7726                  GdkEventExpose *event)
7727 {
7728   GtkDial *dial;
7729   GdkPoint points[3];
7730   gdouble s,c;
7731   gdouble theta;
7732   gint xc, yc;
7733   gint tick_length;
7734   gint i;
7735
7736   g_return_val_if_fail (widget != NULL, FALSE);
7737   g_return_val_if_fail (GTK_IS_DIAL (widget), FALSE);
7738   g_return_val_if_fail (event != NULL, FALSE);
7739
7740   if (event->count > 0)
7741     return FALSE;
7742   
7743   dial = GTK_DIAL (widget);
7744
7745   gdk_window_clear_area (widget->window,
7746                          0, 0,
7747                          widget->allocation.width,
7748                          widget->allocation.height);
7749
7750   xc = widget->allocation.width/2;
7751   yc = widget->allocation.height/2;
7752
7753   /* Draw ticks */
7754
7755   for (i=0; i<25; i++)
7756     {
7757       theta = (i*M_PI/18. - M_PI/6.);
7758       s = sin(theta);
7759       c = cos(theta);
7760
7761       tick_length = (i%6 == 0) ? dial->pointer_width : dial->pointer_width/2;
7762       
7763       gdk_draw_line (widget->window,
7764                      widget->style->fg_gc[widget->state],
7765                      xc + c*(dial->radius - tick_length),
7766                      yc - s*(dial->radius - tick_length),
7767                      xc + c*dial->radius,
7768                      yc - s*dial->radius);
7769     }
7770
7771   /* Draw pointer */
7772
7773   s = sin(dial->angle);
7774   c = cos(dial->angle);
7775
7776
7777   points[0].x = xc + s*dial->pointer_width/2;
7778   points[0].y = yc + c*dial->pointer_width/2;
7779   points[1].x = xc + c*dial->radius;
7780   points[1].y = yc - s*dial->radius;
7781   points[2].x = xc - s*dial->pointer_width/2;
7782   points[2].y = yc - c*dial->pointer_width/2;
7783
7784   gtk_draw_polygon (widget->style,
7785                     widget->window,
7786                     GTK_STATE_NORMAL,
7787                     GTK_SHADOW_OUT,
7788                     points, 3,
7789                     TRUE);
7790   
7791   return FALSE;
7792 }
7793 </verb></tscreen>
7794
7795 <!-- ----------------------------------------------------------------- -->
7796 <sect2> Event handling
7797
7798 <p>
7799
7800 The rest of the widget's code handles various types of events, and
7801 isn't too different from what would be found in many GTK
7802 applications. Two types of events can occur - either the user can
7803 click on the widget with the mouse and drag to move the pointer, or
7804 the value of the Adjustment object can change due to some external
7805 circumstance. 
7806
7807 <p>
7808 When the user clicks on the widget, we check to see if the click was
7809 appropriately near the pointer, and if so, store then button that the
7810 user clicked with in the <tt/button/ field of the widget
7811 structure, and grab all mouse events with a call to
7812 <tt/gtk_grab_add()/. Subsequent motion of the mouse causes the
7813 value of the control to be recomputed (by the function
7814 <tt/gtk_dial_update_mouse/). Depending on the policy that has been
7815 set, "value_changed" events are either generated instantly
7816 (<tt/GTK_UPDATE_CONTINUOUS/), after a delay in a timer added with
7817 <tt/gtk_timeout_add()/ (<tt/GTK_UPDATE_DELAYED/), or only when the
7818 button is released (<tt/GTK_UPDATE_DISCONTINUOUS/).
7819
7820 <tscreen><verb>
7821 static gint
7822 gtk_dial_button_press (GtkWidget      *widget,
7823                        GdkEventButton *event)
7824 {
7825   GtkDial *dial;
7826   gint dx, dy;
7827   double s, c;
7828   double d_parallel;
7829   double d_perpendicular;
7830
7831   g_return_val_if_fail (widget != NULL, FALSE);
7832   g_return_val_if_fail (GTK_IS_DIAL (widget), FALSE);
7833   g_return_val_if_fail (event != NULL, FALSE);
7834
7835   dial = GTK_DIAL (widget);
7836
7837   /* Determine if button press was within pointer region - we 
7838      do this by computing the parallel and perpendicular distance of
7839      the point where the mouse was pressed from the line passing through
7840      the pointer */
7841   
7842   dx = event->x - widget->allocation.width / 2;
7843   dy = widget->allocation.height / 2 - event->y;
7844   
7845   s = sin(dial->angle);
7846   c = cos(dial->angle);
7847   
7848   d_parallel = s*dy + c*dx;
7849   d_perpendicular = fabs(s*dx - c*dy);
7850   
7851   if (!dial->button &&
7852       (d_perpendicular < dial->pointer_width/2) &&
7853       (d_parallel > - dial->pointer_width))
7854     {
7855       gtk_grab_add (widget);
7856
7857       dial->button = event->button;
7858
7859       gtk_dial_update_mouse (dial, event->x, event->y);
7860     }
7861
7862   return FALSE;
7863 }
7864
7865 static gint
7866 gtk_dial_button_release (GtkWidget      *widget,
7867                           GdkEventButton *event)
7868 {
7869   GtkDial *dial;
7870
7871   g_return_val_if_fail (widget != NULL, FALSE);
7872   g_return_val_if_fail (GTK_IS_DIAL (widget), FALSE);
7873   g_return_val_if_fail (event != NULL, FALSE);
7874
7875   dial = GTK_DIAL (widget);
7876
7877   if (dial->button == event->button)
7878     {
7879       gtk_grab_remove (widget);
7880
7881       dial->button = 0;
7882
7883       if (dial->policy == GTK_UPDATE_DELAYED)
7884         gtk_timeout_remove (dial->timer);
7885       
7886       if ((dial->policy != GTK_UPDATE_CONTINUOUS) &&
7887           (dial->old_value != dial->adjustment->value))
7888         gtk_signal_emit_by_name (GTK_OBJECT (dial->adjustment), "value_changed");
7889     }
7890
7891   return FALSE;
7892 }
7893
7894 static gint
7895 gtk_dial_motion_notify (GtkWidget      *widget,
7896                          GdkEventMotion *event)
7897 {
7898   GtkDial *dial;
7899   GdkModifierType mods;
7900   gint x, y, mask;
7901
7902   g_return_val_if_fail (widget != NULL, FALSE);
7903   g_return_val_if_fail (GTK_IS_DIAL (widget), FALSE);
7904   g_return_val_if_fail (event != NULL, FALSE);
7905
7906   dial = GTK_DIAL (widget);
7907
7908   if (dial->button != 0)
7909     {
7910       x = event->x;
7911       y = event->y;
7912
7913       if (event->is_hint || (event->window != widget->window))
7914         gdk_window_get_pointer (widget->window, &amp;x, &amp;y, &amp;mods);
7915
7916       switch (dial->button)
7917         {
7918         case 1:
7919           mask = GDK_BUTTON1_MASK;
7920           break;
7921         case 2:
7922           mask = GDK_BUTTON2_MASK;
7923           break;
7924         case 3:
7925           mask = GDK_BUTTON3_MASK;
7926           break;
7927         default:
7928           mask = 0;
7929           break;
7930         }
7931
7932       if (mods & mask)
7933         gtk_dial_update_mouse (dial, x,y);
7934     }
7935
7936   return FALSE;
7937 }
7938
7939 static gint
7940 gtk_dial_timer (GtkDial *dial)
7941 {
7942   g_return_val_if_fail (dial != NULL, FALSE);
7943   g_return_val_if_fail (GTK_IS_DIAL (dial), FALSE);
7944
7945   if (dial->policy == GTK_UPDATE_DELAYED)
7946     gtk_signal_emit_by_name (GTK_OBJECT (dial->adjustment), "value_changed");
7947
7948   return FALSE;
7949 }
7950
7951 static void
7952 gtk_dial_update_mouse (GtkDial *dial, gint x, gint y)
7953 {
7954   gint xc, yc;
7955   gfloat old_value;
7956
7957   g_return_if_fail (dial != NULL);
7958   g_return_if_fail (GTK_IS_DIAL (dial));
7959
7960   xc = GTK_WIDGET(dial)->allocation.width / 2;
7961   yc = GTK_WIDGET(dial)->allocation.height / 2;
7962
7963   old_value = dial->adjustment->value;
7964   dial->angle = atan2(yc-y, x-xc);
7965
7966   if (dial->angle < -M_PI/2.)
7967     dial->angle += 2*M_PI;
7968
7969   if (dial->angle < -M_PI/6)
7970     dial->angle = -M_PI/6;
7971
7972   if (dial->angle > 7.*M_PI/6.)
7973     dial->angle = 7.*M_PI/6.;
7974
7975   dial->adjustment->value = dial->adjustment->lower + (7.*M_PI/6 - dial->angle) *
7976     (dial->adjustment->upper - dial->adjustment->lower) / (4.*M_PI/3.);
7977
7978   if (dial->adjustment->value != old_value)
7979     {
7980       if (dial->policy == GTK_UPDATE_CONTINUOUS)
7981         {
7982           gtk_signal_emit_by_name (GTK_OBJECT (dial->adjustment), "value_changed");
7983         }
7984       else
7985         {
7986           gtk_widget_draw (GTK_WIDGET(dial), NULL);
7987
7988           if (dial->policy == GTK_UPDATE_DELAYED)
7989             {
7990               if (dial->timer)
7991                 gtk_timeout_remove (dial->timer);
7992
7993               dial->timer = gtk_timeout_add (SCROLL_DELAY_LENGTH,
7994                                              (GtkFunction) gtk_dial_timer,
7995                                              (gpointer) dial);
7996             }
7997         }
7998     }
7999 }
8000 </verb></tscreen>
8001
8002 <p>
8003 Changes to the Adjustment by external means are communicated to our
8004 widget by the ``changed'' and ``value_changed'' signals. The handlers
8005 for these functions call <tt/gtk_dial_update()/ to validate the
8006 arguments, compute the new pointer angle, and redraw the widget (by
8007 calling <tt/gtk_widget_draw()/).
8008
8009 <tscreen><verb>
8010 static void
8011 gtk_dial_update (GtkDial *dial)
8012 {
8013   gfloat new_value;
8014   
8015   g_return_if_fail (dial != NULL);
8016   g_return_if_fail (GTK_IS_DIAL (dial));
8017
8018   new_value = dial->adjustment->value;
8019   
8020   if (new_value < dial->adjustment->lower)
8021     new_value = dial->adjustment->lower;
8022
8023   if (new_value > dial->adjustment->upper)
8024     new_value = dial->adjustment->upper;
8025
8026   if (new_value != dial->adjustment->value)
8027     {
8028       dial->adjustment->value = new_value;
8029       gtk_signal_emit_by_name (GTK_OBJECT (dial->adjustment), "value_changed");
8030     }
8031
8032   dial->angle = 7.*M_PI/6. - (new_value - dial->adjustment->lower) * 4.*M_PI/3. /
8033     (dial->adjustment->upper - dial->adjustment->lower);
8034
8035   gtk_widget_draw (GTK_WIDGET(dial), NULL);
8036 }
8037
8038 static void
8039 gtk_dial_adjustment_changed (GtkAdjustment *adjustment,
8040                               gpointer       data)
8041 {
8042   GtkDial *dial;
8043
8044   g_return_if_fail (adjustment != NULL);
8045   g_return_if_fail (data != NULL);
8046
8047   dial = GTK_DIAL (data);
8048
8049   if ((dial->old_value != adjustment->value) ||
8050       (dial->old_lower != adjustment->lower) ||
8051       (dial->old_upper != adjustment->upper))
8052     {
8053       gtk_dial_update (dial);
8054
8055       dial->old_value = adjustment->value;
8056       dial->old_lower = adjustment->lower;
8057       dial->old_upper = adjustment->upper;
8058     }
8059 }
8060
8061 static void
8062 gtk_dial_adjustment_value_changed (GtkAdjustment *adjustment,
8063                                     gpointer       data)
8064 {
8065   GtkDial *dial;
8066
8067   g_return_if_fail (adjustment != NULL);
8068   g_return_if_fail (data != NULL);
8069
8070   dial = GTK_DIAL (data);
8071
8072   if (dial->old_value != adjustment->value)
8073     {
8074       gtk_dial_update (dial);
8075
8076       dial->old_value = adjustment->value;
8077     }
8078 }
8079 </verb></tscreen>
8080
8081 <!-- ----------------------------------------------------------------- -->
8082 <sect2> Possible Enhancements
8083
8084 <p>
8085
8086 The Dial widget as we've described it so far runs about 670 lines of
8087 code. Although that might sound like a fair bit, we've really
8088 accomplished quite a bit with that much code, especially since much of
8089 that length is headers and boilerplate. However, there are quite a few
8090 more enhancements that could be made to this widget:
8091
8092 <itemize>
8093 <item> If you try this widget out, you'll find that there is some
8094 flashing as the pointer is dragged around. This is because the entire
8095 widget is erased every time the pointer is moved before being
8096 redrawn. Often, the best way to handle this problem is to draw to an
8097 offscreen pixmap, then copy the final results onto the screen in one
8098 step. (The ProgressBar widget draws itself in this fashion.)
8099
8100 <item> The user should be able to use the up and down arrow keys to
8101 increase and decrease the value.
8102
8103 <item> It would be nice if the widget had buttons to increase and
8104 decrease the value in small or large steps. Although it would be
8105 possible to use embedded Button widgets for this, we would also like
8106 the buttons to auto-repeat when held down, as the arrows on a
8107 scrollbar do. Most of the code to implement this type of behavior can
8108 be found in the GtkRange widget.
8109
8110 <item> The Dial widget could be made into a container widget with a
8111 single child widget positioned at the bottom between the buttons
8112 mentioned above. The user could then add their choice of a label or
8113 entry widget to display the current value of the dial.
8114
8115 </itemize>
8116
8117 <!-- ----------------------------------------------------------------- -->
8118 <sect1> Learning More
8119
8120 <p>
8121 Only a small part of the many details involved in creating widgets
8122 could be described above. If you want to write your own widgets, the
8123 best source of examples is the GTK source itself. Ask yourself some
8124 questions about the widget you want to write: is it a Container
8125 widget? does it have its own window? is it a modification of an
8126 existing widget? Then find a similar widget, and start making changes.
8127 Good luck!
8128
8129 <!-- ***************************************************************** -->
8130 <sect>Scribble, A Simple Example Drawing Program
8131 <!-- ***************************************************************** -->
8132
8133 <!-- ----------------------------------------------------------------- -->
8134 <sect1> Overview
8135
8136 <p>
8137 In this section, we will build a simple drawing program. In the
8138 process, we will examine how to handle mouse events, how to draw in a
8139 window, and how to do drawing better by using a backing pixmap. After
8140 creating the simple drawing program, we will extend it by adding
8141 support for XInput devices, such as drawing tablets. GTK provides
8142 support routines which makes getting extended information, such as
8143 pressure and tilt, from such devices quite easy.
8144
8145 <!-- ----------------------------------------------------------------- -->
8146 <sect1> Event Handling
8147
8148 <p>
8149 The GTK signals we have already discussed are for high-level actions,
8150 such as a menu item being selected. However, sometimes it is useful to
8151 learn about lower-level occurrences, such as the mouse being moved, or
8152 a key being pressed. There are also GTK signals corresponding to these
8153 low-level <em>events</em>. The handlers for these signals have an
8154 extra parameter which is a pointer to a structure containing
8155 information about the event. For instance, motion events handlers are
8156 passed a pointer to a GdkEventMotion structure which looks (in part)
8157 like:
8158
8159 <tscreen><verb>
8160 struct _GdkEventMotion
8161 {
8162   GdkEventType type;
8163   GdkWindow *window;
8164   guint32 time;
8165   gdouble x;
8166   gdouble y;
8167   ...
8168   guint state;
8169   ...
8170 };
8171 </verb></tscreen>
8172
8173 <tt/type/ will be set to the event type, in this case
8174 <tt/GDK_MOTION_NOTIFY/, window is the window in which the event
8175 occured. <tt/x/ and <tt/y/ give the coordinates of the event,
8176 and <tt/state/ specifies the modifier state when the event
8177 occurred (that is, it specifies which modifier keys and mouse buttons
8178 were pressed.) It is the bitwise OR of some of the following:
8179
8180 <tscreen><verb>
8181 GDK_SHIFT_MASK  
8182 GDK_LOCK_MASK   
8183 GDK_CONTROL_MASK
8184 GDK_MOD1_MASK   
8185 GDK_MOD2_MASK   
8186 GDK_MOD3_MASK   
8187 GDK_MOD4_MASK   
8188 GDK_MOD5_MASK   
8189 GDK_BUTTON1_MASK
8190 GDK_BUTTON2_MASK
8191 GDK_BUTTON3_MASK
8192 GDK_BUTTON4_MASK
8193 GDK_BUTTON5_MASK
8194 </verb></tscreen>
8195
8196 <p>
8197 As for other signals, to determine what happens when an event occurs
8198 we call <tt>gtk_signal_connect()</tt>. But we also need let GTK
8199 know which events we want to be notified about. To do this, we call
8200 the function:
8201
8202 <tscreen><verb>
8203 void       gtk_widget_set_events          (GtkWidget           *widget,
8204                                            gint                 events);
8205 </verb></tscreen>
8206
8207 The second field specifies the events we are interested in. It
8208 is the bitwise OR of constants that specify different types
8209 of events. For future reference the event types are:
8210
8211 <tscreen><verb>
8212 GDK_EXPOSURE_MASK
8213 GDK_POINTER_MOTION_MASK
8214 GDK_POINTER_MOTION_HINT_MASK
8215 GDK_BUTTON_MOTION_MASK     
8216 GDK_BUTTON1_MOTION_MASK    
8217 GDK_BUTTON2_MOTION_MASK    
8218 GDK_BUTTON3_MOTION_MASK    
8219 GDK_BUTTON_PRESS_MASK      
8220 GDK_BUTTON_RELEASE_MASK    
8221 GDK_KEY_PRESS_MASK         
8222 GDK_KEY_RELEASE_MASK       
8223 GDK_ENTER_NOTIFY_MASK      
8224 GDK_LEAVE_NOTIFY_MASK      
8225 GDK_FOCUS_CHANGE_MASK      
8226 GDK_STRUCTURE_MASK         
8227 GDK_PROPERTY_CHANGE_MASK   
8228 GDK_PROXIMITY_IN_MASK      
8229 GDK_PROXIMITY_OUT_MASK     
8230 </verb></tscreen>
8231
8232 There are a few subtle points that have to be observed when calling
8233 <tt/gtk_widget_set_events()/. First, it must be called before the X window
8234 for a GTK widget is created. In practical terms, this means you
8235 should call it immediately after creating the widget. Second, the
8236 widget must have an associated X window. For efficiency, many widget
8237 types do not have their own window, but draw in their parent's window.
8238 These widgets are:
8239
8240 <tscreen><verb>
8241 GtkAlignment
8242 GtkArrow
8243 GtkBin
8244 GtkBox
8245 GtkImage
8246 GtkItem
8247 GtkLabel
8248 GtkPaned
8249 GtkPixmap
8250 GtkScrolledWindow
8251 GtkSeparator
8252 GtkTable
8253 GtkViewport
8254 GtkAspectFrame
8255 GtkFrame
8256 GtkVPaned
8257 GtkHPaned
8258 GtkVBox
8259 GtkHBox
8260 GtkVSeparator
8261 GtkHSeparator
8262 </verb></tscreen>
8263
8264 To capture events for these widgets, you need to use an EventBox 
8265 widget. See the section on   
8266 <ref id="sec_The_EventBox_Widget" name="The EventBox Widget"> for
8267 details.
8268
8269 <p>
8270 For our drawing program, we want to know when the mouse button is
8271 pressed and when the mouse is moved, so we specify
8272 <tt/GDK_POINTER_MOTION_MASK/ and <tt/GDK_BUTTON_PRESS_MASK/. We also
8273 want to know when we need to redraw our window, so we specify
8274 <tt/GDK_EXPOSURE_MASK/. Although we want to be notified via a
8275 Configure event when our window size changes, we don't have to specify
8276 the corresponding <tt/GDK_STRUCTURE_MASK/ flag, because it is
8277 automatically specified for all windows.
8278
8279 <p>
8280 It turns out, however, that there is a problem with just specifying
8281 <tt/GDK_POINTER_MOTION_MASK/. This will cause the server to add a new
8282 motion event to the event queue every time the user moves the mouse.
8283 Imagine that it takes us 0.1 seconds to handle a motion event, but the
8284 X server queues a new motion event every 0.05 seconds. We will soon
8285 get way behind the users drawing. If the user draws for 5 seconds,
8286 it will take us another 5 seconds to catch up after they release 
8287 the mouse button! What we would like is to only get one motion
8288 event for each event we process. The way to do this is to 
8289 specify <tt/GDK_POINTER_MOTION_HINT_MASK/. 
8290
8291 <p>
8292 When we specify <tt/GDK_POINTER_MOTION_HINT_MASK/, the server sends
8293 us a motion event the first time the pointer moves after entering
8294 our window, or after a button press or release event. Subsequent 
8295 motion events will be suppressed until we explicitely ask for
8296 the position of the pointer using the function:
8297
8298 <tscreen><verb>
8299 GdkWindow*    gdk_window_get_pointer     (GdkWindow       *window,
8300                                           gint            *x,
8301                                           gint            *y,
8302                                           GdkModifierType *mask);
8303 </verb></tscreen>
8304
8305 (There is another function, <tt>gtk_widget_get_pointer()</tt> which
8306 has a simpler interface, but turns out not to be very useful, since
8307 it only retrieves the position of the mouse, not whether the buttons
8308 are pressed.)
8309
8310 <p>
8311 The code to set the events for our window then looks like:
8312
8313 <tscreen><verb>
8314   gtk_signal_connect (GTK_OBJECT (drawing_area), "expose_event",
8315                       (GtkSignalFunc) expose_event, NULL);
8316   gtk_signal_connect (GTK_OBJECT(drawing_area),"configure_event",
8317                       (GtkSignalFunc) configure_event, NULL);
8318   gtk_signal_connect (GTK_OBJECT (drawing_area), "motion_notify_event",
8319                       (GtkSignalFunc) motion_notify_event, NULL);
8320   gtk_signal_connect (GTK_OBJECT (drawing_area), "button_press_event",
8321                       (GtkSignalFunc) button_press_event, NULL);
8322
8323   gtk_widget_set_events (drawing_area, GDK_EXPOSURE_MASK
8324                          | GDK_LEAVE_NOTIFY_MASK
8325                          | GDK_BUTTON_PRESS_MASK
8326                          | GDK_POINTER_MOTION_MASK
8327                          | GDK_POINTER_MOTION_HINT_MASK);
8328 </verb></tscreen>
8329
8330 We'll save the "expose_event" and "configure_event" handlers for
8331 later. The "motion_notify_event" and "button_press_event" handlers
8332 pretty simple:
8333
8334 <tscreen><verb>
8335 static gint
8336 button_press_event (GtkWidget *widget, GdkEventButton *event)
8337 {
8338   if (event->button == 1 &amp;&amp; pixmap != NULL)
8339       draw_brush (widget, event->x, event->y);
8340
8341   return TRUE;
8342 }
8343
8344 static gint
8345 motion_notify_event (GtkWidget *widget, GdkEventMotion *event)
8346 {
8347   int x, y;
8348   GdkModifierType state;
8349
8350   if (event->is_hint)
8351     gdk_window_get_pointer (event->window, &amp;x, &amp;y, &amp;state);
8352   else
8353     {
8354       x = event->x;
8355       y = event->y;
8356       state = event->state;
8357     }
8358     
8359   if (state &amp; GDK_BUTTON1_MASK &amp;&amp; pixmap != NULL)
8360     draw_brush (widget, x, y);
8361   
8362   return TRUE;
8363 }
8364 </verb></tscreen>
8365
8366 <!-- ----------------------------------------------------------------- -->
8367 <sect1> The DrawingArea Widget, And Drawing
8368
8369 <p>
8370 We know turn to the process of drawing on the screen. The 
8371 widget we use for this is the DrawingArea widget. A drawing area
8372 widget is essentially an X window and nothing more. It is a blank
8373 canvas in which we can draw whatever we like. A drawing area
8374 is created using the call:
8375
8376 <tscreen><verb>
8377 GtkWidget* gtk_drawing_area_new        (void);
8378 </verb></tscreen>
8379
8380 A default size for the widget can be specified by calling:
8381
8382 <tscreen><verb>
8383 void       gtk_drawing_area_size       (GtkDrawingArea      *darea,
8384                                         gint                 width,
8385                                         gint                 height);
8386 </verb></tscreen>
8387
8388 This default size can be overriden, as is true for all widgets,
8389 by calling <tt>gtk_widget_set_usize()</tt>, and that, in turn, can
8390 be overridden if the user manually resizes the the window containing
8391 the drawing area.
8392
8393 <p>
8394 It should be noted that when we create a DrawingArea widget, we are,
8395 <em>completely</em> responsible for drawing the contents. If our
8396 window is obscured then uncovered, we get an exposure event and must
8397 redraw what was previously hidden.
8398
8399 <p>
8400 Having to remember everything that was drawn on the screen so we
8401 can properly redraw it can, to say the least, be a nuisance. In
8402 addition, it can be visually distracting if portions of the
8403 window are cleared, then redrawn step by step. The solution to
8404 this problem is to use an offscreen <em>backing pixmap</em>.
8405 Instead of drawing directly to the screen, we draw to an image
8406 stored in server memory but not displayed, then when the image
8407 changes or new portions of the image are displayed, we copy the
8408 relevant portions onto the screen.
8409
8410 <p>
8411 To create an offscreen pixmap, we call the function:
8412
8413 <tscreen><verb>
8414 GdkPixmap* gdk_pixmap_new               (GdkWindow  *window,
8415                                          gint        width,
8416                                          gint        height,
8417                                          gint        depth);
8418 </verb></tscreen>
8419
8420 The <tt>window</tt> parameter specifies a GDK window that this pixmap
8421 takes some of its properties from. <tt>width</tt> and <tt>height</tt>
8422 specify the size of the pixmap. <tt>depth</tt> specifies the <em>color
8423 depth</em>, that is the number of bits per pixel, for the new window.
8424 If the depth is specified as <tt>-1</tt>, it will match the depth
8425 of <tt>window</tt>.
8426
8427 <p>
8428 We create the pixmap in our "configure_event" handler. This event
8429 is generated whenever the window changes size, including when it
8430 is originally created.
8431
8432 <tscreen><verb>
8433 /* Backing pixmap for drawing area */
8434 static GdkPixmap *pixmap = NULL;
8435
8436 /* Create a new backing pixmap of the appropriate size */
8437 static gint
8438 configure_event (GtkWidget *widget, GdkEventConfigure *event)
8439 {
8440   if (pixmap)
8441     {
8442       gdk_pixmap_destroy(pixmap);
8443     }
8444   pixmap = gdk_pixmap_new(widget->window,
8445                           widget->allocation.width,
8446                           widget->allocation.height,
8447                           -1);
8448   gdk_draw_rectangle (pixmap,
8449                       widget->style->white_gc,
8450                       TRUE,
8451                       0, 0,
8452                       widget->allocation.width,
8453                       widget->allocation.height);
8454
8455   return TRUE;
8456 }
8457 </verb></tscreen>
8458
8459 The call to <tt>gdk_draw_rectangle()</tt> clears the pixmap
8460 initially to white. We'll say more about that in a moment.
8461
8462 <p>
8463 Our exposure event handler then simply copies the relevant portion
8464 of the pixmap onto the screen (we determine the area we need
8465 to redraw by using the event->area field of the exposure event):
8466
8467 <tscreen><verb>
8468 /* Refill the screen from the backing pixmap */
8469 static gint
8470 expose_event (GtkWidget *widget, GdkEventExpose *event)
8471 {
8472   gdk_draw_pixmap(widget->window,
8473                   widget->style->fg_gc[GTK_WIDGET_STATE (widget)],
8474                   pixmap,
8475                   event->area.x, event->area.y,
8476                   event->area.x, event->area.y,
8477                   event->area.width, event->area.height);
8478
8479   return FALSE;
8480 }
8481 </verb></tscreen>
8482
8483 We've now seen how to keep the screen up to date with our pixmap, but
8484 how do we actually draw interesting stuff on our pixmap?  There are a
8485 large number of calls in GTK's GDK library for drawing on
8486 <em>drawables</em>. A drawable is simply something that can be drawn
8487 upon. It can be a window, a pixmap, or a bitmap (a black and white
8488 image).  We've already seen two such calls above,
8489 <tt>gdk_draw_rectangle()</tt> and <tt>gdk_draw_pixmap()</tt>. The
8490 complete list is:
8491
8492 <tscreen><verb>
8493 gdk_draw_line ()
8494 gdk_draw_rectangle ()
8495 gdk_draw_arc ()
8496 gdk_draw_polygon ()
8497 gdk_draw_string ()
8498 gdk_draw_text ()
8499 gdk_draw_pixmap ()
8500 gdk_draw_bitmap ()
8501 gdk_draw_image ()
8502 gdk_draw_points ()
8503 gdk_draw_segments ()
8504 </verb></tscreen>
8505
8506 See the reference documentation or the header file
8507 <tt>&lt;gdk/gdk.h&gt;</tt> for further details on these functions.
8508 These functions all share the same first two arguments. The first
8509 argument is the drawable to draw upon, the second argument is a
8510 <em>graphics context</em> (GC). 
8511
8512 <p>
8513 A graphics context encapsulates information about things such as
8514 foreground and background color and line width. GDK has a full set of
8515 functions for creating and modifying graphics contexts, but to keep
8516 things simple we'll just use predefined graphics contexts. Each widget
8517 has an associated style. (Which can be modified in a gtkrc file, see
8518 the section GTK's rc file.) This, among other things, stores a number
8519 of graphics contexts. Some examples of accessing these graphics
8520 contexts are:
8521
8522 <tscreen><verb>
8523 widget->style->white_gc
8524 widget->style->black_gc
8525 widget->style->fg_gc[GTK_STATE_NORMAL]
8526 widget->style->bg_gc[GTK_WIDGET_STATE(widget)]
8527 </verb></tscreen>
8528
8529 The fields <tt>fg_gc</tt>, <tt>bg_gc</tt>, <tt>dark_gc</tt>, and
8530 <tt>light_gc</tt> are indexed by a parameter of type
8531 <tt>GtkStateType</tt> which can take on the values:
8532
8533 <tscreen><verb>
8534 GTK_STATE_NORMAL,
8535 GTK_STATE_ACTIVE,
8536 GTK_STATE_PRELIGHT,
8537 GTK_STATE_SELECTED,
8538 GTK_STATE_INSENSITIVE
8539 </verb></tscreen>
8540
8541 For instance, the for <tt/GTK_STATE_SELECTED/ the default foreground
8542 color is white and the default background color, dark blue.
8543
8544 <p>
8545 Our function <tt>draw_brush()</tt>, which does the actual drawing
8546 on the screen, is then:
8547
8548 <tscreen><verb>
8549 /* Draw a rectangle on the screen */
8550 static void
8551 draw_brush (GtkWidget *widget, gdouble x, gdouble y)
8552 {
8553   GdkRectangle update_rect;
8554
8555   update_rect.x = x - 5;
8556   update_rect.y = y - 5;
8557   update_rect.width = 10;
8558   update_rect.height = 10;
8559   gdk_draw_rectangle (pixmap,
8560                       widget->style->black_gc,
8561                       TRUE,
8562                       update_rect.x, update_rect.y,
8563                       update_rect.width, update_rect.height);
8564   gtk_widget_draw (widget, &amp;update_rect);
8565 }
8566 </verb></tscreen>
8567
8568 After we draw the rectangle representing the brush onto the pixmap,
8569 we call the function:
8570
8571 <tscreen><verb>
8572 void       gtk_widget_draw                (GtkWidget           *widget,
8573                                            GdkRectangle        *area);
8574 </verb></tscreen>
8575
8576 which notifies X that the area given by the <tt>area</tt> parameter
8577 needs to be updated. X will eventually generate an expose event
8578 (possibly combining the areas passed in several calls to
8579 <tt>gtk_widget_draw()</tt>) which will cause our expose event handler
8580 to copy the relevant portions to the screen.
8581
8582 <p>
8583 We have now covered the entire drawing program except for a few
8584 mundane details like creating the main window. The complete
8585 source code is available from the location from which you got
8586 this tutorial, or from:
8587
8588 <htmlurl url="http://www.msc.cornell.edu/~otaylor/gtk-gimp/tutorial"
8589 name="http://www.msc.cornell.edu/~otaylor/gtk-gimp/tutorial">
8590
8591
8592 <!-- ----------------------------------------------------------------- -->
8593 <sect1> Adding XInput support
8594
8595 <p>
8596
8597 It is now possible to buy quite inexpensive input devices such 
8598 as drawing tablets, which allow drawing with a much greater
8599 ease of artistic expression than does a mouse. The simplest way
8600 to use such devices is simply as a replacement for the mouse,
8601 but that misses out many of the advantages of these devices,
8602 such as:
8603
8604 <itemize>
8605 <item> Pressure sensitivity
8606 <item> Tilt reporting
8607 <item> Sub-pixel positioning
8608 <item> Multiple inputs (for example, a stylus with a point and eraser)
8609 </itemize>
8610
8611 For information about the XInput extension, see the <htmlurl
8612 url="http://www.msc.cornell.edu/~otaylor/xinput/XInput-HOWTO.html"
8613 name="XInput-HOWTO">.
8614
8615 <p>
8616 If we examine the full definition of, for example, the GdkEventMotion
8617 structure, we see that it has fields to support extended device
8618 information.
8619
8620 <tscreen><verb>
8621 struct _GdkEventMotion
8622 {
8623   GdkEventType type;
8624   GdkWindow *window;
8625   guint32 time;
8626   gdouble x;
8627   gdouble y;
8628   gdouble pressure;
8629   gdouble xtilt;
8630   gdouble ytilt;
8631   guint state;
8632   gint16 is_hint;
8633   GdkInputSource source;
8634   guint32 deviceid;
8635 };
8636 </verb></tscreen>
8637
8638 <tt/pressure/ gives the pressure as a floating point number between
8639 0 and 1. <tt/xtilt/ and <tt/ytilt/ can take on values between 
8640 -1 and 1, corresponding to the degree of tilt in each direction.
8641 <tt/source/ and <tt/deviceid/ specify the device for which the
8642 event occurred in two different ways. <tt/source/ gives some simple
8643 information about the type of device. It can take the enumeration
8644 values.
8645
8646 <tscreen><verb>
8647 GDK_SOURCE_MOUSE
8648 GDK_SOURCE_PEN
8649 GDK_SOURCE_ERASER
8650 GDK_SOURCE_CURSOR
8651 </verb></tscreen>
8652
8653 <tt/deviceid/ specifies a unique numeric ID for the device. This can
8654 be used to find out further information about the device using the
8655 <tt/gdk_input_list_devices()/ call (see below). The special value
8656 <tt/GDK_CORE_POINTER/ is used for the core pointer device. (Usually
8657 the mouse.)
8658
8659 <sect2> Enabling extended device information
8660
8661 <p>
8662 To let GTK know about our interest in the extended device information,
8663 we merely have to add a single line to our program:
8664
8665 <tscreen><verb>
8666 gtk_widget_set_extension_events (drawing_area, GDK_EXTENSION_EVENTS_CURSOR);
8667 </verb></tscreen>
8668
8669 By giving the value <tt/GDK_EXTENSION_EVENTS_CURSOR/ we say that
8670 we are interested in extension events, but only if we don't have
8671 to draw our own cursor. See the section <ref
8672 id="sec_Further_Sophistications" name="Further Sophistications"> below
8673 for more information about drawing the cursor. We could also 
8674 give the values <tt/GDK_EXTENSION_EVENTS_ALL/ if we were willing 
8675 to draw our own cursor, or <tt/GDK_EXTENSION_EVENTS_NONE/ to revert
8676 back to the default condition.
8677
8678 <p>
8679 This is not completely the end of the story however. By default,
8680 no extension devices are enabled. We need a mechanism to allow
8681 users to enable and configure their extension devices. GTK provides
8682 the InputDialog widget to automate this process. The following
8683 procedure manages an InputDialog widget. It creates the dialog if
8684 it isn't present, and raises it to the top otherwise.
8685
8686 <tscreen><verb>
8687 void
8688 input_dialog_destroy (GtkWidget *w, gpointer data)
8689 {
8690   *((GtkWidget **)data) = NULL;
8691 }
8692
8693 void
8694 create_input_dialog ()
8695 {
8696   static GtkWidget *inputd = NULL;
8697
8698   if (!inputd)
8699     {
8700       inputd = gtk_input_dialog_new();
8701
8702       gtk_signal_connect (GTK_OBJECT(inputd), "destroy",
8703                           (GtkSignalFunc)input_dialog_destroy, &amp;inputd);
8704       gtk_signal_connect_object (GTK_OBJECT(GTK_INPUT_DIALOG(inputd)->close_button),
8705                                  "clicked",
8706                                  (GtkSignalFunc)gtk_widget_hide,
8707                                  GTK_OBJECT(inputd));
8708       gtk_widget_hide ( GTK_INPUT_DIALOG(inputd)->save_button);
8709
8710       gtk_widget_show (inputd);
8711     }
8712   else
8713     {
8714       if (!GTK_WIDGET_MAPPED(inputd))
8715         gtk_widget_show(inputd);
8716       else
8717         gdk_window_raise(inputd->window);
8718     }
8719 }
8720 </verb></tscreen>
8721
8722 (You might want to take note of the way we handle this dialog.  By
8723 connecting to the "destroy" signal, we make sure that we don't keep a
8724 pointer to dialog around after it is destroyed - that could lead to a
8725 segfault.)
8726
8727 <p>
8728 The InputDialog has two buttons "Close" and "Save", which by default
8729 have no actions assigned to them. In the above function we make
8730 "Close" hide the dialog, hide the "Save" button, since we don't
8731 implement saving of XInput options in this program.
8732
8733 <sect2> Using extended device information
8734
8735 <p>
8736 Once we've enabled the device, we can just use the extended 
8737 device information in the extra fields of the event structures.
8738 In fact, it is always safe to use this information since these
8739 fields will have reasonable default values even when extended
8740 events are not enabled.
8741
8742 <p>
8743 Once change we do have to make is to call
8744 <tt/gdk_input_window_get_pointer()/ instead of
8745 <tt/gdk_window_get_pointer/. This is necessary because
8746 <tt/gdk_window_get_pointer/ doesn't return the extended device
8747 information.
8748
8749 <tscreen><verb>
8750 void gdk_input_window_get_pointer     (GdkWindow       *window,
8751                                        guint32         deviceid,
8752                                        gdouble         *x,
8753                                        gdouble         *y,
8754                                        gdouble         *pressure,
8755                                        gdouble         *xtilt,
8756                                        gdouble         *ytilt,
8757                                        GdkModifierType *mask);
8758 </verb></tscreen>
8759
8760 When calling this function, we need to specify the device ID as
8761 well as the window. Usually, we'll get the device ID from the
8762 <tt/deviceid/ field of an event structure. Again, this function
8763 will return reasonable values when extension events are not
8764 enabled. (In this case, <tt/event->deviceid/ will have the value
8765 <tt/GDK_CORE_POINTER/).
8766
8767 So the basic structure of our button-press and motion event handlers,
8768 doesn't change much - we just need to add code to deal with the
8769 extended information.
8770
8771 <tscreen><verb>
8772 static gint
8773 button_press_event (GtkWidget *widget, GdkEventButton *event)
8774 {
8775   print_button_press (event->deviceid);
8776   
8777   if (event->button == 1 &amp;&amp; pixmap != NULL)
8778     draw_brush (widget, event->source, event->x, event->y, event->pressure);
8779
8780   return TRUE;
8781 }
8782
8783 static gint
8784 motion_notify_event (GtkWidget *widget, GdkEventMotion *event)
8785 {
8786   gdouble x, y;
8787   gdouble pressure;
8788   GdkModifierType state;
8789
8790   if (event->is_hint)
8791     gdk_input_window_get_pointer (event->window, event->deviceid,
8792                                   &amp;x, &amp;y, &amp;pressure, NULL, NULL, &amp;state);
8793   else
8794     {
8795       x = event->x;
8796       y = event->y;
8797       pressure = event->pressure;
8798       state = event->state;
8799     }
8800     
8801   if (state &amp; GDK_BUTTON1_MASK &amp;&amp; pixmap != NULL)
8802     draw_brush (widget, event->source, x, y, pressure);
8803   
8804   return TRUE;
8805 }
8806 </verb></tscreen>
8807
8808 We also need to do something with the new information. Our new
8809 <tt/draw_brush()/ function draws with a different color for
8810 each <tt/event->source/ and changes the brush size depending
8811 on the pressure.
8812
8813 <tscreen><verb>
8814 /* Draw a rectangle on the screen, size depending on pressure,
8815    and color on the type of device */
8816 static void
8817 draw_brush (GtkWidget *widget, GdkInputSource source,
8818             gdouble x, gdouble y, gdouble pressure)
8819 {
8820   GdkGC *gc;
8821   GdkRectangle update_rect;
8822
8823   switch (source)
8824     {
8825     case GDK_SOURCE_MOUSE:
8826       gc = widget->style->dark_gc[GTK_WIDGET_STATE (widget)];
8827       break;
8828     case GDK_SOURCE_PEN:
8829       gc = widget->style->black_gc;
8830       break;
8831     case GDK_SOURCE_ERASER:
8832       gc = widget->style->white_gc;
8833       break;
8834     default:
8835       gc = widget->style->light_gc[GTK_WIDGET_STATE (widget)];
8836     }
8837
8838   update_rect.x = x - 10 * pressure;
8839   update_rect.y = y - 10 * pressure;
8840   update_rect.width = 20 * pressure;
8841   update_rect.height = 20 * pressure;
8842   gdk_draw_rectangle (pixmap, gc, TRUE,
8843                       update_rect.x, update_rect.y,
8844                       update_rect.width, update_rect.height);
8845   gtk_widget_draw (widget, &amp;update_rect);
8846 }
8847 </verb></tscreen>
8848
8849 <sect2> Finding out more about a device
8850
8851 <p>
8852 As an example of how to find out more about a device, our program
8853 will print the name of the device that generates each button
8854 press. To find out the name of a device, we call the function:
8855
8856 <tscreen><verb>
8857 GList *gdk_input_list_devices               (void);
8858 </verb></tscreen>
8859
8860 which returns a GList (a linked list type from the glib library)
8861 of GdkDeviceInfo structures. The GdkDeviceInfo strucure is defined
8862 as:
8863
8864 <tscreen><verb>
8865 struct _GdkDeviceInfo
8866 {
8867   guint32 deviceid;
8868   gchar *name;
8869   GdkInputSource source;
8870   GdkInputMode mode;
8871   gint has_cursor;
8872   gint num_axes;
8873   GdkAxisUse *axes;
8874   gint num_keys;
8875   GdkDeviceKey *keys;
8876 };
8877 </verb></tscreen>
8878
8879 Most of these fields are configuration information that you
8880 can ignore unless you are implemented XInput configuration
8881 saving. The we are interested in here is <tt/name/ which is
8882 simply the name that X assigns to the device. The other field
8883 that isn't configuration information is <tt/has_cursor/. If
8884 <tt/has_cursor/ is false, then we we need to draw our own
8885 cursor. But since we've specified <tt/GDK_EXTENSION_EVENTS_CURSOR/,
8886 we don't have to worry about this.
8887
8888 <p>
8889 Our <tt/print_button_press()/ function simply iterates through
8890 the returned list until it finds a match, then prints out
8891 the name of the device.
8892
8893 <tscreen><verb>
8894 static void
8895 print_button_press (guint32 deviceid)
8896 {
8897   GList *tmp_list;
8898
8899   /* gdk_input_list_devices returns an internal list, so we shouldn't
8900      free it afterwards */
8901   tmp_list = gdk_input_list_devices();
8902
8903   while (tmp_list)
8904     {
8905       GdkDeviceInfo *info = (GdkDeviceInfo *)tmp_list->data;
8906
8907       if (info->deviceid == deviceid)
8908         {
8909           printf("Button press on device '%s'\n", info->name);
8910           return;
8911         }
8912
8913       tmp_list = tmp_list->next;
8914     }
8915 }
8916 </verb></tscreen>
8917
8918 That completes the changes to ``XInputize'' our program. As with
8919 the first version, the complete source is available at the location
8920 from which you got this tutorial, or from:
8921
8922 <htmlurl url="http://www.msc.cornell.edu/~otaylor/gtk-gimp/tutorial"
8923 name="http://www.msc.cornell.edu/~otaylor/gtk-gimp/tutorial">
8924
8925
8926 <sect2> Further sophistications <label id="sec_Further_Sophistications">
8927
8928 <p>
8929 Although our program now supports XInput quite well, it lacks some
8930 features we would want in a full-featured application. First, the user
8931 probably doesn't want to have to configure their device each time they
8932 run the program, so we should allow them to save the device
8933 configuration. This is done by iterating through the return of
8934 <tt/gdk_input_list_devices()/ and writing out the configuration to a
8935 file.
8936
8937 <p>
8938 To restore the state next time the program is run, GDK provides
8939 functions to change device configuration:
8940
8941 <tscreen><verb>
8942 gdk_input_set_extension_events()
8943 gdk_input_set_source()
8944 gdk_input_set_mode()
8945 gdk_input_set_axes()
8946 gdk_input_set_key()
8947 </verb></tscreen>
8948
8949 (The list returned from <tt/gdk_input_list_devices()/ should not be
8950 modified directly.) An example of doing this can be found in the
8951 drawing program gsumi. (Available from <htmlurl
8952 url="http://www.msc.cornell.edu/~otaylor/gsumi/"
8953 name="http://www.msc.cornell.edu/~otaylor/gsumi/">) Eventually, it
8954 would be nice to have a standard way of doing this for all
8955 applications. This probably belongs at a slightly higher level than
8956 GTK, perhaps in the GNOME library.
8957
8958 <p>
8959 Another major ommission that we have mentioned above is the lack of
8960 cursor drawing. Platforms other than XFree86 currently do not allow
8961 simultaneously using a device as both the core pointer and directly by
8962 an application. See the <url
8963 url="http://www.msc.cornell.edu/~otaylor/xinput/XInput-HOWTO.html"
8964 name="XInput-HOWTO"> for more information about this. This means that
8965 applications that want to support the widest audience need to draw
8966 their own cursor.
8967
8968 <p>
8969 An application that draws it's own cursor needs to do two things:
8970 determine if the current device needs a cursor drawn or not, and
8971 determine if the current device is in proximity. (If the current
8972 device is a drawing tablet, it's a nice touch to make the cursor 
8973 disappear when the stylus is lifted from the tablet. When the
8974 device is touching the stylus, that is called "in proximity.")
8975 The first is done by searching the device list, as we did
8976 to find out the device name. The second is achieved by selecting
8977 "proximity_out" events. An example of drawing one's own cursor is
8978 found in the 'testinput' program found in the GTK distribution.
8979
8980 <!-- ***************************************************************** -->
8981 <sect>Tips For Writing GTK Applications
8982 <!-- ***************************************************************** -->
8983
8984 <p>
8985 This section is simply a gathering of wisdom, general style guidelines and hints to
8986 creating good GTK applications. It is totally useless right now cause it's
8987 only a topic sentence :)
8988
8989 Use GNU autoconf and automake!  They are your friends :)  I am planning to
8990 make a quick intro on them here.
8991
8992 <!-- ***************************************************************** -->
8993 <sect>Contributing
8994 <!-- ***************************************************************** -->
8995
8996 <p>
8997 This document, like so much other great software out there, was created for
8998 free by volunteers.  If you are at all knowledgeable about any aspect of GTK
8999 that does not already have documentation, please consider contributing to
9000 this document.
9001 <p>
9002 If you do decide to contribute, please mail your text to Tony Gale, 
9003 <tt><htmlurl url="mailto:gale@gimp.org"
9004 name="gale@gimp.org"></tt>. Also, be aware that the entirety of this 
9005 document is free, and any addition by yourself must also be free.  That is, 
9006 people may use any portion of your examples in their programs, and copies 
9007 of this document may be distributed at will etc.
9008 <p>
9009 Thank you.
9010
9011 <!-- ***************************************************************** -->
9012 <sect>Credits
9013 <!-- ***************************************************************** -->
9014 <p>
9015 I would like to thank the following for their contributions to this text.
9016
9017 <itemize>
9018 <item>Bawer Dagdeviren, <tt><htmlurl url="mailto:chamele0n@geocities.com"
9019 name="chamele0n@geocities.com"></tt> for the menus tutorial.                          
9020
9021 <item>Raph Levien, <tt><htmlurl url="mailto:raph@acm.org"
9022 name="raph@acm.org"></tt>
9023 for hello world ala GTK, widget packing, and general all around wisdom.
9024 He's also generously donated a home for this tutorial.
9025
9026 <item>Peter Mattis, <tt><htmlurl url="mailto:petm@xcf.berkeley.edu"
9027 name="petm@xcf.berkeley.edu"></tt> for the simplest GTK program.. 
9028 and the ability to make it :)
9029
9030 <item>Werner Koch <tt><htmlurl url="mailto:werner.koch@guug.de"
9031 name="werner.koch@guug.de"></tt> for converting the original plain text to
9032 SGML, and the widget class hierarchy.
9033
9034 <item>Mark Crichton <tt><htmlurl url="mailto:crichton@expert.cc.purdue.edu"
9035 name="crichton@expert.cc.purdue.edu"></tt> for the menu factory code, and
9036 the table packing tutorial.
9037
9038 <item>Owen Taylor <tt><htmlurl url="mailto:owt1@cornell.edu"
9039 name="owt1@cornell.edu"></tt> for the EventBox widget section (and
9040 the patch to the distro).  He's also responsible for the selections code and
9041 tutorial, as well as the sections on writing your own GTK widgets, and the
9042 example application.  Thanks a lot Owen for all you help!
9043
9044 <item>Mark VanderBoom <tt><htmlurl url="mailto:mvboom42@calvin.edu"
9045 name="mvboom42@calvin.edu"></tt> for his wonderful work on the Notebook,
9046 Progress Bar, Dialogs, and File selection widgets.  Thanks a lot Mark!
9047 You've been a great help.
9048
9049 <item>Tim Janik <tt><htmlurl url="mailto:timj@psynet.net"
9050 name="timj@psynet.net"></tt> for his great job on the Lists Widget.
9051 Thanks Tim :)
9052
9053 <item>Rajat Datta <tt><htmlurl url="mailto:rajat@ix.netcom.com"
9054 name="rajat@ix.netcom.com"</tt> for the excellent job on the Pixmap tutorial.
9055
9056 <item>Michael K. Johnson <tt><htmlurl url="mailto:johnsonm@redhat.com"
9057 name="johnsonm@redhat.com"></tt> for info and code for popup menus. 
9058
9059 </itemize>
9060 <p>
9061 And to all of you who commented and helped refine this document.
9062 <p>
9063 Thanks.
9064
9065 <!-- ***************************************************************** -->
9066 <sect> Tutorial Copyright and Permissions Notice
9067 <!-- ***************************************************************** -->
9068
9069 <p>
9070 The GTK Tutorial is Copyright (C) 1997 Ian Main. 
9071
9072 Copyright (C) 1998 Tony Gale.
9073 <p>
9074 Permission is granted to make and distribute verbatim copies of this 
9075 manual provided the copyright notice and this permission notice are 
9076 preserved on all copies.
9077 <P>Permission is granted to copy and distribute modified versions of 
9078 this document under the conditions for verbatim copying, provided that 
9079 this copyright notice is included exactly as in the original,
9080 and that the entire resulting derived work is distributed under 
9081 the terms of a permission notice identical to this one.
9082 <P>Permission is granted to copy and distribute translations of this 
9083 document into another language, under the above conditions for modified 
9084 versions.
9085 <P>If you are intending to incorporate this document into a published 
9086 work, please contact the maintainer, and we will make an effort 
9087 to ensure that you have the most up to date information available.
9088 <P>There is no guarentee that this document lives up to its intended
9089 purpose.  This is simply provided as a free resource.  As such,
9090 the authors and maintainers of the information provided within can
9091 not make any guarentee that the information is even accurate.
9092 </article>