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