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