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