1 <!doctype linuxdoc system>
3 <!-- This is the tutorial marked up in SGML
4 (just to show how to write a comment)
9 <author>Ian Main <tt><htmlurl url="mailto:slow@intergate.bc.ca"
10 name="<slow@intergate.bc.ca>"></tt>,
11 Tony Gale <tt><htmlurl url="mailto:gale@gimp.org"
12 name="<gale@gimp.org>"></tt
15 <!-- ***************************************************************** -->
17 <!-- ***************************************************************** -->
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
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>
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).
40 There is also a third component called glib which contains a few
41 replacements for some standard calls, as well as some additional functions
42 for handling linked lists etc. The replacement functions are used to
43 increase GTK's portability, as some of the functions implemented
44 here are not available or are nonstandard on other unicies such as
45 g_strerror(). Some also contain enhancements to the libc versions such as
46 g_malloc has enhanced debugging utilities.
48 This tutorial is an attempt to document as much as possible of GTK, it is by
49 no means complete. This
50 tutorial assumes a good understanding of C, and how to create C programs.
51 It would be a great benefit for the reader to have previous X programming
52 experience, but it shouldn't be necessary. If you are learning GTK as your
53 first widget set, please comment on how you found this tutorial, and what
54 you had troubles with.
55 Note that there is also a C++ API for GTK (GTK--) in the works, so if you
56 prefer to use C++, you should look into this instead. There's also an
57 Objective C wrapper, and guile bindings available, but I don't follow these.
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.
62 <!-- ***************************************************************** -->
64 <!-- ***************************************************************** -->
67 The first thing to do of course, is download the GTK source and install
68 it. You can always get the latest version from ftp.gimp.org in /pub/gtk.
69 You can also view other sources of GTK information on http://www.gimp.org/gtk
70 GTK uses GNU autoconf for
71 configuration. Once untar'd, type ./configure --help to see a list of options.
73 To begin our introduction to GTK, we'll start with the simplest program
74 possible. This program will
75 create a 200x200 pixel window and has no way of exiting except to be
76 killed using the shell.
81 int main (int argc, char *argv[])
85 gtk_init (&argc, &argv);
87 window = gtk_window_new (GTK_WINDOW_TOPLEVEL);
88 gtk_widget_show (window);
96 All programs will of course include the gtk/gtk.h which declares the
97 variables, functions, structures etc. that will be used in your GTK
103 gtk_init (&argc, &argv);
106 calls the function gtk_init(gint *argc, gchar ***argv) which will be
107 called in all GTK applications. This sets up a few things for us such
108 as the default visual and color map and then proceeds to call
109 gdk_init(gint *argc, gchar ***argv). This function initializes the
110 library for use, sets up default signal handlers, and checks the
111 arguments passed to your application on the command line, looking for one
115 <item> <tt/--display/
116 <item> <tt/--debug-level/
117 <item> <tt/--no-xshm/
119 <item> <tt/--show-events/
120 <item> <tt/--no-show-events/
123 It removes these from the argument list, leaving anything it does
124 not recognize for your application to parse or ignore. This creates a set
125 of standard arguments excepted by all GTK applications.
127 The next two lines of code create and display a window.
130 window = gtk_window_new (GTK_WINDOW_TOPLEVEL);
131 gtk_widget_show (window);
134 The GTK_WINDOW_TOPLEVEL argument specifies that we want the window to
135 undergo window manager decoration and placement. Rather than create a
136 window of 0x0 size, a window without children is set to 200x200 by default
137 so you can still manipulate it.
139 The gtk_widget_show() function, lets GTK know that we are done setting the
140 attributes of this widget, and it can display it.
142 The last line enters the GTK main processing loop.
148 gtk_main() is another call you will see in every GTK application. When
149 control reaches this point, GTK will sleep waiting for X events (such as
150 button or key presses), timeouts, or file IO notifications to occur.
151 In our simple example however, events are ignored.
153 <!-- ----------------------------------------------------------------- -->
154 <sect1>Hello World in GTK
156 OK, now for a program with a widget (a button). It's the classic hello
164 /* this is a callback function. the data arguments are ignored in this example..
165 * More on callbacks below. */
166 void hello (GtkWidget *widget, gpointer data)
168 g_print ("Hello World\n");
171 gint delete_event(GtkWidget *widget, gpointer data)
173 g_print ("delete event occured\n");
174 /* if you return TRUE in the "delete_event" signal handler,
175 * GTK will emit the "destroy" signal. Returning FALSE means
176 * you don't want the window to be destroyed.
177 * This is useful for popping up 'are you sure you want to quit ?'
180 /* Change FALSE to TRUE and the main window will be destroyed with
181 * a "delete_event". */
186 /* another callback */
187 void destroy (GtkWidget *widget, gpointer data)
192 int main (int argc, char *argv[])
194 /* GtkWidget is the storage type for widgets */
198 /* this is called in all GTK applications. arguments are parsed from
199 * the command line and are returned to the application. */
200 gtk_init (&argc, &argv);
202 /* create a new window */
203 window = gtk_window_new (GTK_WINDOW_TOPLEVEL);
205 /* when the window is given the "delete_event" signal (this is given
206 * by the window manager (usually the 'close' option, or on the
207 * titlebar), we ask it to call the delete_event () function
208 * as defined above. The data passed to the callback
209 * function is NULL and is ignored in the callback. */
210 gtk_signal_connect (GTK_OBJECT (window), "delete_event",
211 GTK_SIGNAL_FUNC (delete_event), NULL);
213 /* here we connect the "destroy" event to a signal handler.
214 * This event occurs when we call gtk_widget_destroy() on the window,
215 * or if we return 'TRUE' in the "delete_event" callback. */
216 gtk_signal_connect (GTK_OBJECT (window), "destroy",
217 GTK_SIGNAL_FUNC (destroy), NULL);
219 /* sets the border width of the window. */
220 gtk_container_border_width (GTK_CONTAINER (window), 10);
222 /* creates a new button with the label "Hello World". */
223 button = gtk_button_new_with_label ("Hello World");
225 /* When the button receives the "clicked" signal, it will call the
226 * function hello() passing it NULL as it's argument. The hello() function is
228 gtk_signal_connect (GTK_OBJECT (button), "clicked",
229 GTK_SIGNAL_FUNC (hello), NULL);
231 /* This will cause the window to be destroyed by calling
232 * gtk_widget_destroy(window) when "clicked". Again, the destroy
233 * signal could come from here, or the window manager. */
234 gtk_signal_connect_object (GTK_OBJECT (button), "clicked",
235 GTK_SIGNAL_FUNC (gtk_widget_destroy),
236 GTK_OBJECT (window));
238 /* this packs the button into the window (a gtk container). */
239 gtk_container_add (GTK_CONTAINER (window), button);
241 /* the final step is to display this newly created widget... */
242 gtk_widget_show (button);
245 gtk_widget_show (window);
247 /* all GTK applications must have a gtk_main(). Control ends here
248 * and waits for an event to occur (like a key press or mouse event). */
255 <!-- ----------------------------------------------------------------- -->
256 <sect1>Compiling Hello World
261 gcc -Wall -g helloworld.c -o hello_world -L/usr/X11R6/lib \
262 -lgtk -lgdk -lglib -lX11 -lXext -lm
265 The libraries above must all be in your default search paths, if not, add
266 -L<library directory> and gcc will look in these directories for
268 libraries. For instance, on my Debian Linux system, I have to add
269 <tt>-L/usr/X11R6/lib</> for it to find the X11 libraries.
271 The order of the libraries are significant. The linker has to know what
272 functions it needs from a library before it processes it.
274 The libraries we are linking in are:
276 <item>The GTK library (-lgtk), the widget library, based on top of GDK.
277 <item>The GDK library (-lgdk), the Xlib wrapper.
278 <item>The glib library (-lglib), containing miscellaneous functions, only
279 g_print() is used in this particular example. GTK is built on top
280 of glib so you will always require this library. See the section on
281 <ref id="sec_glib" name="glib"> for details.
282 <item>The Xlib library (-lX11) which is used by GDK.
283 <item>The Xext library (-lXext). This contains code for shared memory
284 pixmaps and other X extensions.
285 <item>The math library (-lm). This is used by GTK for various purposes.
288 <!-- ----------------------------------------------------------------- -->
289 <sect1>Theory of Signals and Callbacks
291 Before we look in detail at hello world, we'll discuss events and callbacks.
292 GTK is an event driven toolkit, which means it will sleep in
293 gtk_main until an event occurs and control is passed to the appropriate
296 This passing of control is done using the idea of "signals". When an
297 event occurs, such as the press of a mouse button, the
298 appropriate signal will be "emitted" by the widget that was pressed.
300 most of its useful work. To make a button perform an action,
301 we set up a signal handler to catch these
302 signals and call the appropriate function. This is done by using a
306 gint gtk_signal_connect (GtkObject *object,
312 Where the first argument is the widget which will be emitting the signal, and
313 the second, the name of the signal you wish to catch. The third is the function
314 you wish to be called when it is caught, and the fourth, the data you wish
315 to have passed to this function.
317 The function specified in the third argument is called a "callback
318 function", and should be of the form:
321 void callback_func(GtkWidget *widget, gpointer *callback_data);
324 Where the first argument will be a pointer to the widget that emitted the signal, and
325 the second, a pointer to the data given as the last argument to the
326 gtk_signal_connect() function as shown above.
328 Another call used in the hello world example, is:
331 gint gtk_signal_connect_object (GtkObject *object,
334 GtkObject *slot_object);
337 gtk_signal_connect_object() is the same as gtk_signal_connect() except that
338 the callback function only uses one argument, a
340 object. So when using this function to connect signals, the callback should be of
344 void callback_func (GtkObject *object);
347 Where the object is usually a widget. We usually don't setup callbacks for
348 gtk_signal_connect_object however. They are usually used
349 to call a GTK function that accept a single widget or object as an
350 argument, as is the case in our hello world example.
352 The purpose of having two functions to connect signals is simply to allow
353 the callbacks to have a different number of arguments. Many functions in
354 the GTK library accept only a single GtkWidget pointer as an argument, so you
355 want to use the gtk_signal_connect_object() for these, whereas for your
356 functions, you may need to have additional data supplied to the callbacks.
358 <!-- ----------------------------------------------------------------- -->
359 <sect1>Stepping Through Hello World
361 Now that we know the theory behind this, lets clarify by walking through
362 the example hello world program.
364 Here is the callback function that will be called when the button is
365 "clicked". We ignore both the widget and the data in this example, but it
366 is not hard to do things with them. The next example will use the data
367 argument to tell us which button was pressed.
370 void hello (GtkWidget *widget, gpointer *data)
372 g_print ("Hello World\n");
377 This callback is a bit special. The "delete_event" occurs when the
378 window manager sends this event to the application. We have a choice here
379 as to what to do about these events. We can ignore them, make some sort of
380 response, or simply quit the application.
382 The value you return in this callback lets GTK know what action to take.
383 By returning FALSE, we let it know that we don't want to have the "destroy"
384 signal emitted, keeping our application running. By returning TRUE, we
385 ask that "destroy" is emitted, which in turn will call our "destroy"
389 gint delete_event(GtkWidget *widget, gpointer data)
391 g_print ("delete event occured\n");
398 Here is another callback function which just quits by calling
399 gtk_main_quit(). Not really much to say about this, it is pretty self
402 void destroy (GtkWidget *widget, gpointer *data)
408 I assume you know about the main() function... yes, as with other
409 applications, all GTK applications will also have one of these.
411 int main (int argc, char *argv[])
415 This next part, declares a pointer to a structure of type GtkWidget. These
416 are used below to create a window and a button.
422 Here is our gtk_init again. As before, this initializes the toolkit, and
423 parses the arguments found on the command line. Any argument it
424 recognizes from the command line, it removes from the list, and modifies
425 argc and argv to make it look like they never existed, allowing your
426 application to parse the remaining arguments.
428 gtk_init (&argc, &argv);
431 Create a new window. This is fairly straight forward. Memory is allocated
432 for the GtkWidget *window structure so it now points to a valid structure.
433 It sets up a new window, but it is not displayed until below where we call
434 gtk_widget_show(window) near the end of our program.
436 window = gtk_window_new (GTK_WINDOW_TOPLEVEL);
439 Here is an example of connecting a signal handler to an object, in this case, the
440 window. Here, the "destroy" signal is caught. This is emitted when we use
441 the window manager to kill the window (and we return TRUE in the
442 "delete_event" handler), or when we use the
443 gtk_widget_destroy() call passing in the window widget as the object to
444 destroy. By setting this up, we handle both cases with a single call.
445 Here, it just calls the destroy() function defined above with a NULL
446 argument, which quits GTK for us.
448 The GTK_OBJECT and GTK_SIGNAL_FUNC are macros that perform type casting and
449 checking for us, as well as aid the readability of the code.
451 gtk_signal_connect (GTK_OBJECT (window), "destroy",
452 GTK_SIGNAL_FUNC (destroy), NULL);
455 This next function is used to set an attribute of a container object.
456 This just sets the window
457 so it has a blank area along the inside of it 10 pixels wide where no
458 widgets will go. There are other similar functions which we will look at
460 <ref id="sec_setting_widget_attributes" name="Setting Widget Attributes">
462 And again, GTK_CONTAINER is a macro to perform type casting.
464 gtk_container_border_width (GTK_CONTAINER (window), 10);
467 This call creates a new button. It allocates space for a new GtkWidget
468 structure in memory, initializes it, and makes the button pointer point to
469 it. It will have the label "Hello World" on it when displayed.
471 button = gtk_button_new_with_label ("Hello World");
474 Here, we take this button, and make it do something useful. We attach a
475 signal handler to it so when it emits the "clicked" signal, our hello()
476 function is called. The data is ignored, so we simply pass in NULL to the
477 hello() callback function. Obviously, the "clicked" signal is emitted when
478 we click the button with our mouse pointer.
481 gtk_signal_connect (GTK_OBJECT (button), "clicked",
482 GTK_SIGNAL_FUNC (hello), NULL);
485 We are also going to use this button to exit our program. This will
486 illustrate how the "destroy"
487 signal may come from either the window manager, or our program. When the
488 button is "clicked", same as above, it calls the first hello() callback function,
489 and then this one in the order they are set up. You may have as many
490 callback function as you need, and all will be executed in the order you
491 connected them. Because the gtk_widget_destroy() function accepts only a
492 GtkWidget *widget as an argument, we use the gtk_signal_connect_object()
493 function here instead of straight gtk_signal_connect().
496 gtk_signal_connect_object (GTK_OBJECT (button), "clicked",
497 GTK_SIGNAL_FUNC (gtk_widget_destroy),
498 GTK_OBJECT (window));
501 This is a packing call, which will be explained in depth later on. But it
502 is fairly easy to understand. It simply tells GTK that the button is to be
503 placed in the window where it will be displayed.
505 gtk_container_add (GTK_CONTAINER (window), button);
508 Now that we have everything setup the way we want it to be. With all the
509 signal handlers in place, and the button placed in the window where it
510 should be, we ask GTK to "show" the widgets on the screen. The window
511 widget is shown last so the whole window will pop up at once rather than
512 seeing the window pop up, and then the button form inside of it. Although
513 with such simple example, you'd never notice.
515 gtk_widget_show (button);
517 gtk_widget_show (window);
520 And of course, we call gtk_main() which waits for events to come from the X
521 server and will call on the widgets to emit signals when these events come.
525 And the final return. Control returns here after gtk_quit() is called.
530 Now, when we click the mouse button on a GTK button, the
531 widget emits a "clicked" signal. In order for us to use this information, our
532 program sets up a signal handler to catch that signal, which dispatches the function
533 of our choice. In our example, when the button we created is "clicked", the
534 hello() function is called with a NULL
535 argument, and then the next handler for this signal is called. This calls
536 the gtk_widget_destroy() function, passing it the window widget as it's
537 argument, destroying the window widget. This causes the window to emit the
538 "destroy" signal, which is
539 caught, and calls our destroy() callback function, which simply exits GTK.
541 Another course of events, is to use the window manager to kill the window.
542 This will cause the "delete_event" to be emitted. This will call our
543 "delete_event" handler. If we return FALSE here, the window will be left as
544 is and nothing will happen. Returning TRUE will cause GTK to emit the
545 "destroy" signal which of course, calls the "destroy" callback, exiting GTK.
547 Note that these signals are not the same as the Unix system
548 signals, and are not implemented using them, although the terminology is
551 <!-- ***************************************************************** -->
553 <!-- ***************************************************************** -->
555 <!-- ----------------------------------------------------------------- -->
558 There are a few things you probably noticed in the previous examples that
560 gint, gchar etc. that you see are typedefs to int and char respectively. This is done
561 to get around that nasty dependency on the size of simple data types when doing calculations.
562 A good example is "gint32" which will be
563 typedef'd to a 32 bit integer for any given platform, whether it be the 64 bit
564 alpha, or the 32 bit i386. The
565 typedefs are very straight forward and intuitive. They are all defined in
566 glib/glib.h (which gets included from gtk.h).
568 You'll also notice the ability to use GtkWidget when the function calls for a GtkObject.
569 GTK is an object oriented design, and a widget is an object.
571 <!-- ----------------------------------------------------------------- -->
572 <sect1>More on Signal Handlers
574 Lets take another look at the gtk_signal_connect declaration.
577 gint gtk_signal_connect (GtkObject *object, gchar *name,
578 GtkSignalFunc func, gpointer func_data);
581 Notice the gint return value ? This is a tag that identifies your callback
582 function. As said above, you may have as many callbacks per signal and per
583 object as you need, and each will be executed in turn, in the order they were attached.
584 This tag allows you to remove this callback from the list by using:
586 void gtk_signal_disconnect (GtkObject *object,
589 So, by passing in the widget you wish to remove the handler from, and the
590 tag or id returned by one of the signal_connect functions, you can
591 disconnect a signal handler.
593 Another function to remove all the signal handers from an object is:
595 gtk_signal_handlers_destroy (GtkObject *object);
598 This call is fairly self explanatory. It simply removes all the current
599 signal handlers from the object passed in as the first argument.
601 <!-- ----------------------------------------------------------------- -->
602 <sect1>An Upgraded Hello World
604 Let's take a look at a slightly improved hello world with better examples
605 of callbacks. This will also introduce us to our next topic, packing
613 /* Our new improved callback. The data passed to this function is printed
615 void callback (GtkWidget *widget, gpointer *data)
617 g_print ("Hello again - %s was pressed\n", (char *) data);
620 /* another callback */
621 void delete_event (GtkWidget *widget, gpointer *data)
626 int main (int argc, char *argv[])
628 /* GtkWidget is the storage type for widgets */
633 /* this is called in all GTK applications. arguments are parsed from
634 * the command line and are returned to the application. */
635 gtk_init (&argc, &argv);
637 /* create a new window */
638 window = gtk_window_new (GTK_WINDOW_TOPLEVEL);
640 /* this is a new call, this just sets the title of our
641 * new window to "Hello Buttons!" */
642 gtk_window_set_title (GTK_WINDOW (window), "Hello Buttons!");
644 /* Here we just set a handler for delete_event that immediately
646 gtk_signal_connect (GTK_OBJECT (window), "delete_event",
647 GTK_SIGNAL_FUNC (delete_event), NULL);
650 /* sets the border width of the window. */
651 gtk_container_border_width (GTK_CONTAINER (window), 10);
653 /* we create a box to pack widgets into. this is described in detail
654 * in the "packing" section below. The box is not really visible, it
655 * is just used as a tool to arrange widgets. */
656 box1 = gtk_hbox_new(FALSE, 0);
658 /* put the box into the main window. */
659 gtk_container_add (GTK_CONTAINER (window), box1);
661 /* creates a new button with the label "Button 1". */
662 button = gtk_button_new_with_label ("Button 1");
664 /* Now when the button is clicked, we call the "callback" function
665 * with a pointer to "button 1" as it's argument */
666 gtk_signal_connect (GTK_OBJECT (button), "clicked",
667 GTK_SIGNAL_FUNC (callback), (gpointer) "button 1");
669 /* instead of gtk_container_add, we pack this button into the invisible
670 * box, which has been packed into the window. */
671 gtk_box_pack_start(GTK_BOX(box1), button, TRUE, TRUE, 0);
673 /* always remember this step, this tells GTK that our preparation for
674 * this button is complete, and it can be displayed now. */
675 gtk_widget_show(button);
677 /* do these same steps again to create a second button */
678 button = gtk_button_new_with_label ("Button 2");
680 /* call the same callback function with a different argument,
681 * passing a pointer to "button 2" instead. */
682 gtk_signal_connect (GTK_OBJECT (button), "clicked",
683 GTK_SIGNAL_FUNC (callback), (gpointer) "button 2");
685 gtk_box_pack_start(GTK_BOX(box1), button, TRUE, TRUE, 0);
687 /* The order in which we show the buttons is not really important, but I
688 * recommend showing the window last, so it all pops up at once. */
689 gtk_widget_show(button);
691 gtk_widget_show(box1);
693 gtk_widget_show (window);
695 /* rest in gtk_main and wait for the fun to begin! */
702 Compile this program using the same linking arguments as our first example.
703 You'll notice this time there is no easy way to exit the program, you have to use
704 your window manager or command line to kill it. A good exercise for the
705 reader would be to insert a third "Quit" button that will exit the
706 program. You may also wish to play with the options to
707 gtk_box_pack_start() while reading the next section.
708 Try resizing the window, and observe the behavior.
710 Just as a side note, there is another useful define for gtk_window_new() -
711 GTK_WINDOW_DIALOG. This interacts with the window manager a little
712 differently and should be used for transient windows.
714 <!-- ***************************************************************** -->
715 <sect>Packing Widgets
716 <!-- ***************************************************************** -->
719 When creating an application, you'll want to put more than one button
720 inside a window. Our first hello world example only used one widget so we
721 could simply use a gtk_container_add call to "pack" the widget into the
722 window. But when you want to put more than one widget into a window, how
723 do you control where that widget is positioned ? This is where packing
726 <!-- ----------------------------------------------------------------- -->
727 <sect1>Theory of Packing Boxes
729 Most packing is done by creating boxes as in the example above. These are
730 invisible widget containers that we can pack our widgets into and come in
731 two forms, a horizontal box, and a vertical box. When packing widgets
732 into a horizontal box, the objects are inserted horizontally from left to
733 right or right to left depending on the call used. In a vertical box,
734 widgets are packed from top to bottom or vice versa. You may use any
735 combination of boxes inside or beside other boxes to create the desired
738 To create a new horizontal box, we use a call to gtk_hbox_new(), and for
739 vertical boxes, gtk_vbox_new(). The gtk_box_pack_start() and
740 gtk_box_pack_end() functions are used to place objects inside of these
741 containers. The gtk_box_pack_start() function will start at the top and
742 work its way down in a vbox, and pack left to right in an hbox.
743 gtk_box_pack_end() will do the opposite, packing from bottom to top in a
744 vbox, and right to left in an hbox. Using these functions allow us to
745 right justify or left justify our widgets and may be mixed in any way to
746 achieve the desired effect. We will use gtk_box_pack_start() in most of
747 our examples. An object may be another container or a widget. And in
748 fact, many widgets are actually containers themselves including the
749 button, but we usually only use a label inside a button.
751 By using these calls, GTK knows where you want to place your widgets so it
752 can do automatic resizing and other nifty things. there's also a number
753 of options as to how your widgets should be packed. As you can imagine,
754 this method gives us a quite a bit of flexibility when placing and
757 <!-- ----------------------------------------------------------------- -->
758 <sect1>Details of Boxes
760 Because of this flexibility, packing boxes in GTK can be confusing at
761 first. There are a lot of options, and it's not immediately obvious how
762 they all fit together. In the end however, there are basically five
763 different styles you can get.
768 <IMG SRC="packbox1.gif" VSPACE="15" HSPACE="10" WIDTH="528" HEIGHT="235"
769 ALT="Box Packing Example Image">
773 Each line contains one horizontal box (hbox) with several buttons. The
774 call to gtk_box_pack is shorthand for the call to pack each of the buttons
775 into the hbox. Each of the buttons is packed into the hbox the same way
776 (i.e. same arguments to the gtk_box_pack_start () function).
778 This is the declaration of the gtk_box_pack_start function.
781 void gtk_box_pack_start (GtkBox *box,
788 The first argument is the box you are packing the object into, the second
789 is this object. The objects will all be buttons for now, so we'll be
790 packing buttons into boxes.
792 The expand argument to gtk_box_pack_start() or gtk_box_pack_end() controls
793 whether the widgets are laid out in the box to fill in all the extra space
794 in the box so the box is expanded to fill the area alloted to it (TRUE).
795 Or the box is shrunk to just fit the widgets (FALSE). Setting expand to
796 FALSE will allow you to do right and left
797 justifying of your widgets. Otherwise, they will all expand to fit in the
798 box, and the same effect could be achieved by using only one of
799 gtk_box_pack_start or pack_end functions.
801 The fill argument to the gtk_box_pack functions control whether the extra
802 space is allocated to the objects themselves (TRUE), or as extra padding
803 in the box around these objects (FALSE). It only has an effect if the
804 expand argument is also TRUE.
806 When creating a new box, the function looks like this:
809 GtkWidget * gtk_hbox_new (gint homogeneous,
813 The homogeneous argument to gtk_hbox_new (and the same for gtk_vbox_new)
814 controls whether each object in the box has the same size (i.e. the same
815 width in an hbox, or the same height in a vbox). If it is set, the expand
816 argument to the gtk_box_pack routines is always turned on.
818 What's the difference between spacing (set when the box is created) and
819 padding (set when elements are packed)? Spacing is added between objects,
820 and padding is added on either side of an object. The following figure
821 should make it clearer:
825 <IMG ALIGN="center" SRC="packbox2.gif" WIDTH="509" HEIGHT="213"
826 VSPACE="15" HSPACE="10" ALT="Box Packing Example Image">
830 Here is the code used to create the above images. I've commented it fairly
831 heavily so hopefully you won't have any problems following it. Compile it yourself
834 <!-- ----------------------------------------------------------------- -->
835 <sect1>Packing Demonstration Program
843 delete_event (GtkWidget *widget, gpointer *data)
848 /* Make a new hbox filled with button-labels. Arguments for the
849 * variables we're interested are passed in to this function.
850 * We do not show the box, but do show everything inside. */
851 GtkWidget *make_box (gint homogeneous, gint spacing,
852 gint expand, gint fill, gint padding)
858 /* create a new hbox with the appropriate homogeneous and spacing
860 box = gtk_hbox_new (homogeneous, spacing);
862 /* create a series of buttons with the appropriate settings */
863 button = gtk_button_new_with_label ("gtk_box_pack");
864 gtk_box_pack_start (GTK_BOX (box), button, expand, fill, padding);
865 gtk_widget_show (button);
867 button = gtk_button_new_with_label ("(box,");
868 gtk_box_pack_start (GTK_BOX (box), button, expand, fill, padding);
869 gtk_widget_show (button);
871 button = gtk_button_new_with_label ("button,");
872 gtk_box_pack_start (GTK_BOX (box), button, expand, fill, padding);
873 gtk_widget_show (button);
875 /* create a button with the label depending on the value of
878 button = gtk_button_new_with_label ("TRUE,");
880 button = gtk_button_new_with_label ("FALSE,");
882 gtk_box_pack_start (GTK_BOX (box), button, expand, fill, padding);
883 gtk_widget_show (button);
885 /* This is the same as the button creation for "expand"
886 * above, but uses the shorthand form. */
887 button = gtk_button_new_with_label (fill ? "TRUE," : "FALSE,");
888 gtk_box_pack_start (GTK_BOX (box), button, expand, fill, padding);
889 gtk_widget_show (button);
891 sprintf (padstr, "%d);", padding);
893 button = gtk_button_new_with_label (padstr);
894 gtk_box_pack_start (GTK_BOX (box), button, expand, fill, padding);
895 gtk_widget_show (button);
901 main (int argc, char *argv[])
907 GtkWidget *separator;
912 /* Our init, don't forget this! :) */
913 gtk_init (&argc, &argv);
916 fprintf (stderr, "usage: packbox num, where num is 1, 2, or 3.\n");
917 /* this just does cleanup in GTK, and exits with an exit status of 1. */
921 which = atoi (argv[1]);
923 /* Create our window */
924 window = gtk_window_new (GTK_WINDOW_TOPLEVEL);
926 /* You should always remember to connect the destroy signal to the
927 * main window. This is very important for proper intuitive
929 gtk_signal_connect (GTK_OBJECT (window), "delete_event",
930 GTK_SIGNAL_FUNC (delete_event), NULL);
931 gtk_container_border_width (GTK_CONTAINER (window), 10);
933 /* We create a vertical box (vbox) to pack the horizontal boxes into.
934 * This allows us to stack the horizontal boxes filled with buttons one
935 * on top of the other in this vbox. */
936 box1 = gtk_vbox_new (FALSE, 0);
938 /* which example to show. These correspond to the pictures above. */
941 /* create a new label. */
942 label = gtk_label_new ("gtk_hbox_new (FALSE, 0);");
944 /* Align the label to the left side. We'll discuss this function and
945 * others in the section on Widget Attributes. */
946 gtk_misc_set_alignment (GTK_MISC (label), 0, 0);
948 /* Pack the label into the vertical box (vbox box1). Remember that
949 * widgets added to a vbox will be packed one on top of the other in
951 gtk_box_pack_start (GTK_BOX (box1), label, FALSE, FALSE, 0);
954 gtk_widget_show (label);
956 /* call our make box function - homogeneous = FALSE, spacing = 0,
957 * expand = FALSE, fill = FALSE, padding = 0 */
958 box2 = make_box (FALSE, 0, FALSE, FALSE, 0);
959 gtk_box_pack_start (GTK_BOX (box1), box2, FALSE, FALSE, 0);
960 gtk_widget_show (box2);
962 /* call our make box function - homogeneous = FALSE, spacing = 0,
963 * expand = FALSE, fill = FALSE, padding = 0 */
964 box2 = make_box (FALSE, 0, TRUE, FALSE, 0);
965 gtk_box_pack_start (GTK_BOX (box1), box2, FALSE, FALSE, 0);
966 gtk_widget_show (box2);
968 /* Args are: homogeneous, spacing, expand, fill, padding */
969 box2 = make_box (FALSE, 0, TRUE, TRUE, 0);
970 gtk_box_pack_start (GTK_BOX (box1), box2, FALSE, FALSE, 0);
971 gtk_widget_show (box2);
973 /* creates a separator, we'll learn more about these later,
974 * but they are quite simple. */
975 separator = gtk_hseparator_new ();
977 /* pack the separator into the vbox. Remember each of these
978 * widgets are being packed into a vbox, so they'll be stacked
980 gtk_box_pack_start (GTK_BOX (box1), separator, FALSE, TRUE, 5);
981 gtk_widget_show (separator);
983 /* create another new label, and show it. */
984 label = gtk_label_new ("gtk_hbox_new (TRUE, 0);");
985 gtk_misc_set_alignment (GTK_MISC (label), 0, 0);
986 gtk_box_pack_start (GTK_BOX (box1), label, FALSE, FALSE, 0);
987 gtk_widget_show (label);
989 /* Args are: homogeneous, spacing, expand, fill, padding */
990 box2 = make_box (TRUE, 0, TRUE, FALSE, 0);
991 gtk_box_pack_start (GTK_BOX (box1), box2, FALSE, FALSE, 0);
992 gtk_widget_show (box2);
994 /* Args are: homogeneous, spacing, expand, fill, padding */
995 box2 = make_box (TRUE, 0, TRUE, TRUE, 0);
996 gtk_box_pack_start (GTK_BOX (box1), box2, FALSE, FALSE, 0);
997 gtk_widget_show (box2);
999 /* another new separator. */
1000 separator = gtk_hseparator_new ();
1001 /* The last 3 arguments to gtk_box_pack_start are: expand, fill, padding. */
1002 gtk_box_pack_start (GTK_BOX (box1), separator, FALSE, TRUE, 5);
1003 gtk_widget_show (separator);
1009 /* create a new label, remember box1 is a vbox as created
1010 * near the beginning of main() */
1011 label = gtk_label_new ("gtk_hbox_new (FALSE, 10);");
1012 gtk_misc_set_alignment (GTK_MISC (label), 0, 0);
1013 gtk_box_pack_start (GTK_BOX (box1), label, FALSE, FALSE, 0);
1014 gtk_widget_show (label);
1016 /* Args are: homogeneous, spacing, expand, fill, padding */
1017 box2 = make_box (FALSE, 10, TRUE, FALSE, 0);
1018 gtk_box_pack_start (GTK_BOX (box1), box2, FALSE, FALSE, 0);
1019 gtk_widget_show (box2);
1021 /* Args are: homogeneous, spacing, expand, fill, padding */
1022 box2 = make_box (FALSE, 10, TRUE, TRUE, 0);
1023 gtk_box_pack_start (GTK_BOX (box1), box2, FALSE, FALSE, 0);
1024 gtk_widget_show (box2);
1026 separator = gtk_hseparator_new ();
1027 /* The last 3 arguments to gtk_box_pack_start are: expand, fill, padding. */
1028 gtk_box_pack_start (GTK_BOX (box1), separator, FALSE, TRUE, 5);
1029 gtk_widget_show (separator);
1031 label = gtk_label_new ("gtk_hbox_new (FALSE, 0);");
1032 gtk_misc_set_alignment (GTK_MISC (label), 0, 0);
1033 gtk_box_pack_start (GTK_BOX (box1), label, FALSE, FALSE, 0);
1034 gtk_widget_show (label);
1036 /* Args are: homogeneous, spacing, expand, fill, padding */
1037 box2 = make_box (FALSE, 0, TRUE, FALSE, 10);
1038 gtk_box_pack_start (GTK_BOX (box1), box2, FALSE, FALSE, 0);
1039 gtk_widget_show (box2);
1041 /* Args are: homogeneous, spacing, expand, fill, padding */
1042 box2 = make_box (FALSE, 0, TRUE, TRUE, 10);
1043 gtk_box_pack_start (GTK_BOX (box1), box2, FALSE, FALSE, 0);
1044 gtk_widget_show (box2);
1046 separator = gtk_hseparator_new ();
1047 /* The last 3 arguments to gtk_box_pack_start are: expand, fill, padding. */
1048 gtk_box_pack_start (GTK_BOX (box1), separator, FALSE, TRUE, 5);
1049 gtk_widget_show (separator);
1054 /* This demonstrates the ability to use gtk_box_pack_end() to
1055 * right justify widgets. First, we create a new box as before. */
1056 box2 = make_box (FALSE, 0, FALSE, FALSE, 0);
1057 /* create the label that will be put at the end. */
1058 label = gtk_label_new ("end");
1059 /* pack it using gtk_box_pack_end(), so it is put on the right side
1060 * of the hbox created in the make_box() call. */
1061 gtk_box_pack_end (GTK_BOX (box2), label, FALSE, FALSE, 0);
1062 /* show the label. */
1063 gtk_widget_show (label);
1065 /* pack box2 into box1 (the vbox remember ? :) */
1066 gtk_box_pack_start (GTK_BOX (box1), box2, FALSE, FALSE, 0);
1067 gtk_widget_show (box2);
1069 /* a separator for the bottom. */
1070 separator = gtk_hseparator_new ();
1071 /* this explicitly sets the separator to 400 pixels wide by 5 pixels
1072 * high. This is so the hbox we created will also be 400 pixels wide,
1073 * and the "end" label will be separated from the other labels in the
1074 * hbox. Otherwise, all the widgets in the hbox would be packed as
1075 * close together as possible. */
1076 gtk_widget_set_usize (separator, 400, 5);
1077 /* pack the separator into the vbox (box1) created near the start
1079 gtk_box_pack_start (GTK_BOX (box1), separator, FALSE, TRUE, 5);
1080 gtk_widget_show (separator);
1083 /* Create another new hbox.. remember we can use as many as we need! */
1084 quitbox = gtk_hbox_new (FALSE, 0);
1086 /* Our quit button. */
1087 button = gtk_button_new_with_label ("Quit");
1089 /* setup the signal to destroy the window. Remember that this will send
1090 * the "destroy" signal to the window which will be caught by our signal
1091 * handler as defined above. */
1092 gtk_signal_connect_object (GTK_OBJECT (button), "clicked",
1093 GTK_SIGNAL_FUNC (gtk_main_quit),
1094 GTK_OBJECT (window));
1095 /* pack the button into the quitbox.
1096 * The last 3 arguments to gtk_box_pack_start are: expand, fill, padding. */
1097 gtk_box_pack_start (GTK_BOX (quitbox), button, TRUE, FALSE, 0);
1098 /* pack the quitbox into the vbox (box1) */
1099 gtk_box_pack_start (GTK_BOX (box1), quitbox, FALSE, FALSE, 0);
1101 /* pack the vbox (box1) which now contains all our widgets, into the
1103 gtk_container_add (GTK_CONTAINER (window), box1);
1105 /* and show everything left */
1106 gtk_widget_show (button);
1107 gtk_widget_show (quitbox);
1109 gtk_widget_show (box1);
1110 /* Showing the window last so everything pops up at once. */
1111 gtk_widget_show (window);
1113 /* And of course, our main function. */
1116 /* control returns here when gtk_main_quit() is called, but not when
1117 * gtk_exit is used. */
1123 <!-- ----------------------------------------------------------------- -->
1124 <sect1>Packing Using Tables
1126 Let's take a look at another way of packing - Tables. These can be
1127 extremely useful in certain situations.
1129 Using tables, we create a grid that we can place widgets in. The widgets
1130 may take up as many spaces as we specify.
1132 The first thing to look at of course, is the gtk_table_new function:
1135 GtkWidget* gtk_table_new (gint rows,
1140 The first argument is the number of rows to make in the table, while the
1141 second, obviously, the number of columns.
1143 The homogeneous argument has to do with how the table's boxes are sized. If homogeneous
1144 is TRUE, the table boxes are resized to the size of the largest widget in the table.
1145 If homogeneous is FALSE, the size of a table boxes is dictated by the tallest widget
1146 in its same row, and the widest widget in its column.
1148 The rows and columnts are laid out starting with 0 to n, where n was the
1149 number specified in the call to gtk_table_new. So, if you specify rows = 2 and
1150 columns = 2, the layout would look something like this:
1154 0+----------+----------+
1156 1+----------+----------+
1158 2+----------+----------+
1161 Note that the coordinate system starts in the upper left hand corner. To place a
1162 widget into a box, use the following function:
1165 void gtk_table_attach (GtkTable *table,
1177 Where the first argument ("table") is the table you've created and the second
1178 ("child") the widget you wish to place in the table.
1180 The left and right attach
1181 arguments specify where to place the widget, and how many boxes to use. If you want
1182 a button in the lower right table entry
1183 of our 2x2 table, and want it to fill that entry ONLY. left_attach would be = 1,
1184 right_attach = 2, top_attach = 1, bottom_attach = 2.
1186 Now, if you wanted a widget to take up the whole
1187 top row of our 2x2 table, you'd use left_attach = 0, right_attach =2, top_attach = 0,
1190 The xoptions and yoptions are used to specify packing options and may be OR'ed
1191 together to allow multiple options.
1195 <item>GTK_FILL - If the table box is larger than the widget, and GTK_FILL is
1196 specified, the widget will expand to use all the room available.
1198 <item>GTK_SHRINK - If the table widget was allocated less space then was
1199 requested (usually by the user resizing the window), then the widgets would
1200 normally just be pushed off the bottom of
1201 the window and disappear. If GTK_SHRINK is specified, the widgets will
1202 shrink with the table.
1204 <item>GTK_EXPAND - This will cause the table to expand to use up any remaining
1205 space in the window.
1208 Padding is just like in boxes, creating a clear area around the widget
1209 specified in pixels.
1211 gtk_table_attach() has a LOT of options. So, there's a shortcut:
1214 void gtk_table_attach_defaults (GtkTable *table,
1219 gint bottom_attach);
1222 The X and Y options default to GTK_FILL | GTK_EXPAND, and X and Y padding
1223 are set to 0. The rest of the arguments are identical to the previous
1226 We also have gtk_table_set_row_spacing() and gtk_table_set_col_spacing(). This places
1227 spacing between the rows at the specified row or column.
1230 void gtk_table_set_row_spacing (GtkTable *table,
1236 void gtk_table_set_col_spacing (GtkTable *table,
1241 Note that for columns, the space goes to the right of the column, and for rows,
1242 the space goes below the row.
1244 You can also set a consistent spacing of all rows and/or columns with:
1247 void gtk_table_set_row_spacings (GtkTable *table,
1253 void gtk_table_set_col_spacings (GtkTable *table,
1257 Note that with these calls, the last row and last column do not get any spacing
1259 <!-- ----------------------------------------------------------------- -->
1260 <sect1>Table Packing Example
1262 Here we make a window with three buttons in a 2x2 table.
1263 The first two buttons will be placed in the upper row.
1264 A third, quit button, is placed in the lower row, spanning both columns.
1265 Which means it should look something like this:
1269 <IMG SRC="table.gif" VSPACE="15" HSPACE="10"
1270 ALT="Table Packing Example Image" WIDTH="180" HEIGHT="120">
1274 Here's the source code:
1278 #include <gtk/gtk.h>
1281 * the data passed to this function is printed to stdout */
1282 void callback (GtkWidget *widget, gpointer *data)
1284 g_print ("Hello again - %s was pressed\n", (char *) data);
1287 /* this callback quits the program */
1288 void delete_event (GtkWidget *widget, gpointer *data)
1293 int main (int argc, char *argv[])
1299 gtk_init (&argc, &argv);
1301 /* create a new window */
1302 window = gtk_window_new (GTK_WINDOW_TOPLEVEL);
1304 /* set the window title */
1305 gtk_window_set_title (GTK_WINDOW (window), "Table");
1307 /* set a handler for delete_event that immediately
1309 gtk_signal_connect (GTK_OBJECT (window), "delete_event",
1310 GTK_SIGNAL_FUNC (delete_event), NULL);
1312 /* sets the border width of the window. */
1313 gtk_container_border_width (GTK_CONTAINER (window), 20);
1315 /* create a 2x2 table */
1316 table = gtk_table_new (2, 2, TRUE);
1318 /* put the table in the main window */
1319 gtk_container_add (GTK_CONTAINER (window), table);
1321 /* create first button */
1322 button = gtk_button_new_with_label ("button 1");
1324 /* when the button is clicked, we call the "callback" function
1325 * with a pointer to "button 1" as it's argument */
1326 gtk_signal_connect (GTK_OBJECT (button), "clicked",
1327 GTK_SIGNAL_FUNC (callback), (gpointer) "button 1");
1330 /* insert button 1 into the upper left quadrant of the table */
1331 gtk_table_attach_defaults (GTK_TABLE(table), button, 0, 1, 0, 1);
1333 gtk_widget_show (button);
1335 /* create second button */
1337 button = gtk_button_new_with_label ("button 2");
1339 /* when the button is clicked, we call the "callback" function
1340 * with a pointer to "button 2" as it's argument */
1341 gtk_signal_connect (GTK_OBJECT (button), "clicked",
1342 GTK_SIGNAL_FUNC (callback), (gpointer) "button 2");
1343 /* insert button 2 into the upper right quadrant of the table */
1344 gtk_table_attach_defaults (GTK_TABLE(table), button, 1, 2, 0, 1);
1346 gtk_widget_show (button);
1348 /* create "Quit" button */
1349 button = gtk_button_new_with_label ("Quit");
1351 /* when the button is clicked, we call the "delete_event" function
1352 * and the program exits */
1353 gtk_signal_connect (GTK_OBJECT (button), "clicked",
1354 GTK_SIGNAL_FUNC (delete_event), NULL);
1356 /* insert the quit button into the both
1357 * lower quadrants of the table */
1358 gtk_table_attach_defaults (GTK_TABLE(table), button, 0, 2, 1, 2);
1360 gtk_widget_show (button);
1362 gtk_widget_show (table);
1363 gtk_widget_show (window);
1371 You can compile this program with something like:
1374 gcc -g -Wall -ansi -o table table.c -L/usr/X11R6/lib \
1375 -lgdk -lgtk -lglib -lX11 -lXext -lm
1378 <!-- ***************************************************************** -->
1379 <sect>Widget Overview
1380 <!-- ***************************************************************** -->
1383 The general steps to creating a widget in GTK are:
1385 <item> gtk_*_new - one of various functions to create a new widget. These
1386 are all detailed in this section.
1388 <item> Connect all signals we wish to use to the appropriate handlers.
1390 <item> Set the attributes of the widget.
1392 <item> Pack the widget into a container using the appropriate call such as
1393 gtk_container_add() or gtk_box_pack_start().
1395 <item> gtk_widget_show() the widget.
1398 gtk_widget_show() lets GTK know that we are done setting the attributes
1399 of the widget, and it is ready to be displayed. You may also use
1400 gtk_widget_hide to make it disappear again. The order in which you
1401 show the widgets is not important, but I suggest showing the window
1402 last so the whole window pops up at once rather than seeing the individual
1403 widgets come up on the screen as they're formed. The children of a widget
1404 (a window is a widget too)
1405 will not be displayed until the window itself is shown using the
1406 gtk_widget_show() function.
1408 <!-- ----------------------------------------------------------------- -->
1411 You'll notice as you go on, that GTK uses a type casting system. This is
1412 always done using macros that both test the ability to cast the given item,
1413 and perform the cast. Some common ones you will see are:
1416 <item> GTK_WIDGET(widget)
1417 <item> GTK_OBJECT(object)
1418 <item> GTK_SIGNAL_FUNC(function)
1419 <item> GTK_CONTAINER(container)
1420 <item> GTK_WINDOW(window)
1424 These are all used to cast arguments in functions. You'll see them in the
1425 examples, and can usually tell when to use them simply by looking at the
1426 function's declaration.
1428 As you can see below in the class hierarchy, all GtkWidgets are derived from
1429 the GtkObject base class. This means you can use an widget in any place the
1430 function asks for an object - simply use the GTK_OBJECT() macro.
1435 gtk_signal_connect(GTK_OBJECT(button), "clicked",
1436 GTK_SIGNAL_FUNC(callback_function), callback_data);
1439 This casts the button into an object, and provides a cast for the function
1440 pointer to the callback.
1442 Many widgets are also containers. If you look in the class hierarchy below,
1443 you'll notice that many widgets drive from the GtkContainer class. Any one
1444 of those widgets may use with the GTK_CONTAINER macro to
1445 pass them to functions that ask for containers.
1447 Unfortunately, these macros are not extensively covered in the tutorial, but I
1448 recomend taking a look through the GTK header files. It can be very
1449 educational. In fact, it's not difficult to learn how a widget works just
1450 by looking at the function declarations.
1452 <!-- ----------------------------------------------------------------- -->
1453 <sect1>Widget Hierarchy
1455 For your reference, here is the class hierarchy tree used to implement widgets.
1468 | | | `GtkAspectFrame
1473 | | | | `GtkCheckMenuItem
1474 | | | | `GtkRadioMenuItem
1478 | | +GtkColorSelectionDialog
1480 | | | `GtkInputDialog
1481 | | `GtkFileSelection
1484 | | | +GtkHButtonBox
1485 | | | `GtkVButtonBox
1490 | | +GtkColorSelection
1494 | | `GtkToggleButton
1507 | +GtkScrolledWindow
1540 <!-- ----------------------------------------------------------------- -->
1541 <sect1>Widgets Without Windows
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">
1571 We'll further our exploration of GTK by examining each widget in turn,
1572 creating a few simple functions to display them. Another good source is
1573 the testgtk.c program that comes with GTK. It can be found in
1576 <!-- ***************************************************************** -->
1577 <sect>The Button Widget
1578 <!-- ***************************************************************** -->
1580 <!-- ----------------------------------------------------------------- -->
1581 <sect1>Normal Buttons
1583 We've almost seen all there is to see of the button widget. It's pretty
1584 simple. There is however two ways to create a button. You can use the
1585 gtk_button_new_with_label() to create a button with a label, or use
1586 gtk_button_new() to create a blank button. It's then up to you to pack a
1587 label or pixmap into this new button. To do this, create a new box, and
1588 then pack your objects into this box using the usual gtk_box_pack_start,
1589 and then use gtk_container_add to pack the box into the button.
1591 Here's an example of using gtk_button_new to create a button with a
1592 picture and a label in it. I've broken the code to create a box up from
1593 the rest so you can use it in your programs.
1598 #include <gtk/gtk.h>
1600 /* create a new hbox with an image and a label packed into it
1601 * and return the box.. */
1603 GtkWidget *xpm_label_box (GtkWidget *parent, gchar *xpm_filename, gchar *label_text)
1607 GtkWidget *pixmapwid;
1612 /* create box for xpm and label */
1613 box1 = gtk_hbox_new (FALSE, 0);
1614 gtk_container_border_width (GTK_CONTAINER (box1), 2);
1616 /* get style of button.. I assume it's to get the background color.
1617 * if someone knows the real reason, please enlighten me. */
1618 style = gtk_widget_get_style(parent);
1620 /* now on to the xpm stuff.. load xpm */
1621 pixmap = gdk_pixmap_create_from_xpm (parent->window, &mask,
1622 &style->bg[GTK_STATE_NORMAL],
1624 pixmapwid = gtk_pixmap_new (pixmap, mask);
1626 /* create label for button */
1627 label = gtk_label_new (label_text);
1629 /* pack the pixmap and label into the box */
1630 gtk_box_pack_start (GTK_BOX (box1),
1631 pixmapwid, FALSE, FALSE, 3);
1633 gtk_box_pack_start (GTK_BOX (box1), label, FALSE, FALSE, 3);
1635 gtk_widget_show(pixmapwid);
1636 gtk_widget_show(label);
1641 /* our usual callback function */
1642 void callback (GtkWidget *widget, gpointer *data)
1644 g_print ("Hello again - %s was pressed\n", (char *) data);
1648 int main (int argc, char *argv[])
1650 /* GtkWidget is the storage type for widgets */
1655 gtk_init (&argc, &argv);
1657 /* create a new window */
1658 window = gtk_window_new (GTK_WINDOW_TOPLEVEL);
1660 gtk_window_set_title (GTK_WINDOW (window), "Pixmap'd Buttons!");
1662 /* It's a good idea to do this for all windows. */
1663 gtk_signal_connect (GTK_OBJECT (window), "destroy",
1664 GTK_SIGNAL_FUNC (gtk_exit), NULL);
1666 gtk_signal_connect (GTK_OBJECT (window), "delete_event",
1667 GTK_SIGNAL_FUNC (gtk_exit), NULL);
1670 /* sets the border width of the window. */
1671 gtk_container_border_width (GTK_CONTAINER (window), 10);
1672 gtk_widget_realize(window);
1674 /* create a new button */
1675 button = gtk_button_new ();
1677 /* You should be getting used to seeing most of these functions by now */
1678 gtk_signal_connect (GTK_OBJECT (button), "clicked",
1679 GTK_SIGNAL_FUNC (callback), (gpointer) "cool button");
1681 /* this calls our box creating function */
1682 box1 = xpm_label_box(window, "info.xpm", "cool button");
1684 /* pack and show all our widgets */
1685 gtk_widget_show(box1);
1687 gtk_container_add (GTK_CONTAINER (button), box1);
1689 gtk_widget_show(button);
1691 gtk_container_add (GTK_CONTAINER (window), button);
1693 gtk_widget_show (window);
1695 /* rest in gtk_main and wait for the fun to begin! */
1702 The xpm_label_box function could be used to pack xpm's and labels into any
1703 widget that can be a container.
1705 <!-- ----------------------------------------------------------------- -->
1706 <sect1> Toggle Buttons
1708 Toggle buttons are very similar to normal buttons, except they will always
1709 be in one of two states, alternated by a click. They may be depressed, and
1710 when you click again, they will pop back up. Click again, and they will pop
1713 Toggle buttons are the basis for check buttons and radio buttons, as such,
1714 many of the calls used for toggle buttons are inherited by radio and check
1715 buttons. I will point these out when we come to them.
1717 Creating a new toggle button:
1720 GtkWidget* gtk_toggle_button_new (void);
1722 GtkWidget* gtk_toggle_button_new_with_label (gchar *label);
1725 As you can imagine, these work identically to the normal button widget
1726 calls. The first creates a blank toggle button, and the second, a button
1727 with a label widget already packed into it.
1729 To retrieve the state of the toggle widget, including radio and check
1730 buttons, we use a macro as shown in our example below. This tests the state
1731 of the toggle in a callback. The signal of interest emitted to us by toggle
1732 buttons (the toggle button, check button, and radio button widgets), is the
1733 "toggled" signal. To check the state of these buttons, set up a signal
1734 handler to catch the toggled signal, and use the macro to determine it's
1735 state. The callback will look something like:
1738 void toggle_button_callback (GtkWidget *widget, gpointer data)
1740 if (GTK_TOGGLE_BUTTON (widget)->active)
1742 /* If control reaches here, the toggle button is down */
1746 /* If control reaches here, the toggle button is up */
1756 guint gtk_toggle_button_get_type (void);
1759 No idea... they all have this, but I dunno what it is :)
1763 void gtk_toggle_button_set_mode (GtkToggleButton *toggle_button,
1764 gint draw_indicator);
1771 void gtk_toggle_button_set_state (GtkToggleButton *toggle_button,
1775 The above call can be used to set the state of the toggle button, and it's
1776 children the radio and check buttons. Passing
1777 in your created button as the first argument, and a TRUE or FALSE
1778 for the second state argument to specify whether it should be up (released) or
1779 down (depressed). Default is up, or FALSE.
1781 Note that when you use the gtk_toggle_button_set_state() function, and the
1782 state is actually changed, it causes
1783 the "clicked" signal to be emitted from the button.
1786 void gtk_toggle_button_toggled (GtkToggleButton *toggle_button);
1789 This simply toggles the button, and emits the "toggled" signal.
1791 <!-- ----------------------------------------------------------------- -->
1792 <sect1> Check Buttons
1794 Check buttons inherent many properties and functions from the the toggle buttons above,
1796 different. Rather than being buttons with text inside them, they are small
1797 squares with the text to the right of them. These are often seen for
1798 toggling options on and off in applications.
1800 The two creation functions are the same as for the normal button.
1803 GtkWidget* gtk_check_button_new (void);
1805 GtkWidget* gtk_check_button_new_with_label (gchar *label);
1808 The new_with_label function creates a check button with a label beside it.
1810 Checking the state of the check button is identical to that of the toggle
1813 <!-- ----------------------------------------------------------------- -->
1814 <sect1> Radio Buttons
1816 Radio buttons are similar to check buttons except they are grouped so that
1817 only one may be selected/depressed at a time. This is good for places in
1818 your application where you need to select from a short list of options.
1820 Creating a new radio button is done with one of these calls:
1823 GtkWidget* gtk_radio_button_new (GSList *group);
1825 GtkWidget* gtk_radio_button_new_with_label (GSList *group,
1829 You'll notice the extra argument to these calls. They require a group to
1830 perform they're duty properly. The first call should pass NULL as the first
1831 argument. Then create a group using:
1834 GSList* gtk_radio_button_group (GtkRadioButton *radio_button);
1838 The important thing to remember is that gtk_radio_button_group must be
1839 called for each new button added to the group, with the previous button
1840 passed in as an argument. The result is then passed into the call to
1841 gtk_radio_button_new or gtk_radio_button_new_with_label. This allows a
1842 chain of buttons to be established. The example below should make this
1845 It is also a good idea to explicitly set which button should be the
1846 default depressed button with:
1849 void gtk_toggle_button_set_state (GtkToggleButton *toggle_button,
1853 This is described in the section on toggle buttons, and works in exactly the
1856 The following example creates a radio button group with three buttons.
1859 /* radiobuttons.c */
1861 #include <gtk/gtk.h>
1864 void close_application( GtkWidget *widget, gpointer *data ) {
1868 main(int argc,char *argv[])
1870 static GtkWidget *window = NULL;
1874 GtkWidget *separator;
1877 gtk_init(&argc,&argv);
1878 window = gtk_window_new (GTK_WINDOW_TOPLEVEL);
1880 gtk_signal_connect (GTK_OBJECT (window), "delete_event",
1881 GTK_SIGNAL_FUNC(close_application),
1884 gtk_window_set_title (GTK_WINDOW (window), "radio buttons");
1885 gtk_container_border_width (GTK_CONTAINER (window), 0);
1887 box1 = gtk_vbox_new (FALSE, 0);
1888 gtk_container_add (GTK_CONTAINER (window), box1);
1889 gtk_widget_show (box1);
1891 box2 = gtk_vbox_new (FALSE, 10);
1892 gtk_container_border_width (GTK_CONTAINER (box2), 10);
1893 gtk_box_pack_start (GTK_BOX (box1), box2, TRUE, TRUE, 0);
1894 gtk_widget_show (box2);
1896 button = gtk_radio_button_new_with_label (NULL, "button1");
1897 gtk_box_pack_start (GTK_BOX (box2), button, TRUE, TRUE, 0);
1898 gtk_widget_show (button);
1900 group = gtk_radio_button_group (GTK_RADIO_BUTTON (button));
1901 button = gtk_radio_button_new_with_label(group, "button2");
1902 gtk_toggle_button_set_state (GTK_TOGGLE_BUTTON (button), TRUE);
1903 gtk_box_pack_start (GTK_BOX (box2), button, TRUE, TRUE, 0);
1904 gtk_widget_show (button);
1906 group = gtk_radio_button_group (GTK_RADIO_BUTTON (button));
1907 button = gtk_radio_button_new_with_label(group, "button3");
1908 gtk_box_pack_start (GTK_BOX (box2), button, TRUE, TRUE, 0);
1909 gtk_widget_show (button);
1911 separator = gtk_hseparator_new ();
1912 gtk_box_pack_start (GTK_BOX (box1), separator, FALSE, TRUE, 0);
1913 gtk_widget_show (separator);
1915 box2 = gtk_vbox_new (FALSE, 10);
1916 gtk_container_border_width (GTK_CONTAINER (box2), 10);
1917 gtk_box_pack_start (GTK_BOX (box1), box2, FALSE, TRUE, 0);
1918 gtk_widget_show (box2);
1920 button = gtk_button_new_with_label ("close");
1921 gtk_signal_connect_object (GTK_OBJECT (button), "clicked",
1922 GTK_SIGNAL_FUNC(close_application),
1923 GTK_OBJECT (window));
1924 gtk_box_pack_start (GTK_BOX (box2), button, TRUE, TRUE, 0);
1925 GTK_WIDGET_SET_FLAGS (button, GTK_CAN_DEFAULT);
1926 gtk_widget_grab_default (button);
1927 gtk_widget_show (button);
1928 gtk_widget_show (window);
1935 You can shorten this slightly by using the following syntax, which
1936 removes the need for a variable to hold the list of buttons:
1939 button2 = gtk_radio_button_new_with_label(
1940 gtk_radio_button_group (GTK_RADIO_BUTTON (button1)),
1944 <!-- ***************************************************************** -->
1945 <sect> Miscallaneous Widgets
1946 <!-- ***************************************************************** -->
1948 <!-- ----------------------------------------------------------------- -->
1951 Labels are used a lot in GTK, and are relatively simple. Labels emit no
1952 signals as they do not have an associated X window. If you need to catch
1953 signals, or do clipping, use the EventBox widget.
1955 To create a new label, use:
1958 GtkWidget* gtk_label_new (char *str);
1961 Where the sole argument is the string you wish the label to display.
1963 To change the label's text after creation, use the function:
1966 void gtk_label_set (GtkLabel *label,
1970 Where the first argument is the label you created previously (casted using
1971 the GTK_LABEL() macro), and the second is the new string.
1973 The space needed for the new string will be automatically adjusted if needed.
1975 To retrieve the current string, use:
1978 void gtk_label_get (GtkLabel *label,
1982 Where the first arguement is the label you've created, and the second, the
1983 return for the string.
1985 <!-- ----------------------------------------------------------------- -->
1986 <sect1>The Tooltips Widget
1988 These are the little text strings that pop up when you leave your pointer
1989 over a button or other widget for a few seconds. They are easy to use, so I
1990 will just explain them without giving an example. If you want to see some
1991 code, take a look at the testgtk.c program distributed with GDK.
1993 Some widgets (such as the label) will not work with tooltips.
1995 The first call you will use to create a new tooltip. You only need to do
1996 this once in a given function. The GtkTooltip this function returns can be
1997 used to create multiple tooltips.
2000 GtkTooltips *gtk_tooltips_new (void);
2003 Once you have created a new tooltip, and the widget you wish to use it on,
2004 simply use this call to set it.
2007 void gtk_tooltips_set_tips (GtkTooltips *tooltips,
2012 The first argument is the tooltip you've already created, followed by the
2013 widget you wish to have this tooltip pop up for, and the text you wish it to
2016 Here's a short example:
2019 GtkTooltips *tooltips;
2022 tooltips = gtk_tooltips_new ();
2023 button = gtk_button_new_with_label ("button 1");
2025 gtk_tooltips_set_tips (tooltips, button, "This is button 1");
2029 There are other calls used with tooltips. I will just list them with a
2030 brief description of what they do.
2033 void gtk_tooltips_destroy (GtkTooltips *tooltips);
2036 Destroy the created tooltips.
2039 void gtk_tooltips_enable (GtkTooltips *tooltips);
2042 Enable a disabled set of tooltips.
2045 void gtk_tooltips_disable (GtkTooltips *tooltips);
2048 Disable an enabled set of tooltips.
2051 void gtk_tooltips_set_delay (GtkTooltips *tooltips,
2055 Sets how many milliseconds you have to hold you pointer over the widget before the
2056 tooltip will pop up. The default is 1000 milliseconds or 1 second.
2059 void gtk_tooltips_set_tips (GtkTooltips *tooltips,
2064 Change the tooltip text of an already created tooltip.
2067 void gtk_tooltips_set_colors (GtkTooltips *tooltips,
2068 GdkColor *background,
2069 GdkColor *foreground);
2072 Set the foreground and background color of the tooltips. Again, I have no
2073 idea how to specify the colors.
2075 And that's all the functions associated with tooltips. More than you'll
2076 ever want to know :)
2078 <!-- ----------------------------------------------------------------- -->
2079 <sect1> Progress Bars
2081 Progress bars are used to show the status of an operation. They are pretty
2082 easy to use, as you will see with the code below. But first lets start out
2083 with the call to create a new progress bar.
2086 GtkWidget *gtk_progress_bar_new (void);
2089 Now that the progress bar has been created we can use it.
2092 void gtk_progress_bar_update (GtkProgressBar *pbar, gfloat percentage);
2095 The first argument is the progress bar you wish to operate on, and the second
2096 argument is the amount 'completed', meaning the amount the progress bar has
2097 been filled from 0-100% (a real number between 0 and 1).
2099 Progress Bars are usually used with timeouts or other such functions (see
2100 section on <ref id="sec_timeouts" name="Timeouts, I/O and Idle Functions">)
2101 to give the illusion of multitasking. All will employ
2102 the gtk_progress_bar_update function in the same manner.
2104 Here is an example of the progress bar, updated using timeouts. This
2105 code also shows you how to reset the Progress Bar.
2110 #include <gtk/gtk.h>
2112 static int ptimer = 0;
2115 /* This function increments and updates the progress bar, it also resets
2116 the progress bar if pstat is FALSE */
2117 gint progress (gpointer data)
2121 /* get the current value of the progress bar */
2122 pvalue = GTK_PROGRESS_BAR (data)->percentage;
2124 if ((pvalue >= 1.0) || (pstat == FALSE)) {
2130 gtk_progress_bar_update (GTK_PROGRESS_BAR (data), pvalue);
2135 /* This function signals a reset of the progress bar */
2136 void progress_r (void)
2141 void destroy (GtkWidget *widget, gpointer *data)
2146 int main (int argc, char *argv[])
2154 gtk_init (&argc, &argv);
2156 window = gtk_window_new (GTK_WINDOW_TOPLEVEL);
2158 gtk_signal_connect (GTK_OBJECT (window), "delete_event",
2159 GTK_SIGNAL_FUNC (destroy), NULL);
2161 gtk_container_border_width (GTK_CONTAINER (window), 10);
2163 table = gtk_table_new(3,2,TRUE);
2164 gtk_container_add (GTK_CONTAINER (window), table);
2166 label = gtk_label_new ("Progress Bar Example");
2167 gtk_table_attach_defaults(GTK_TABLE(table), label, 0,2,0,1);
2168 gtk_widget_show(label);
2170 /* Create a new progress bar, pack it into the table, and show it */
2171 pbar = gtk_progress_bar_new ();
2172 gtk_table_attach_defaults(GTK_TABLE(table), pbar, 0,2,1,2);
2173 gtk_widget_show (pbar);
2175 /* Set the timeout to handle automatic updating of the progress bar */
2176 ptimer = gtk_timeout_add (100, progress, pbar);
2178 /* This button signals the progress bar to be reset */
2179 button = gtk_button_new_with_label ("Reset");
2180 gtk_signal_connect (GTK_OBJECT (button), "clicked",
2181 GTK_SIGNAL_FUNC (progress_r), NULL);
2182 gtk_table_attach_defaults(GTK_TABLE(table), button, 0,1,2,3);
2183 gtk_widget_show(button);
2185 button = gtk_button_new_with_label ("Cancel");
2186 gtk_signal_connect (GTK_OBJECT (button), "clicked",
2187 GTK_SIGNAL_FUNC (destroy), NULL);
2189 gtk_table_attach_defaults(GTK_TABLE(table), button, 1,2,2,3);
2190 gtk_widget_show (button);
2192 gtk_widget_show(table);
2193 gtk_widget_show(window);
2201 In this small program there are four areas that concern the general operation
2202 of Progress Bars, we will look at them in the order they are called.
2205 pbar = gtk_progress_bar_new ();
2208 This code creates a new progress bar, called pbar.
2211 ptimer = gtk_timeout_add (100, progress, pbar);
2214 This code, uses timeouts to enable a constant time interval, timeouts are
2215 not necessary in the use of Progress Bars.
2218 pvalue = GTK_PROGRESS_BAR (data)->percentage;
2221 This code assigns the current value of the percentage bar to pvalue.
2224 gtk_progress_bar_update (GTK_PROGRESS_BAR (data), pvalue);
2227 Finally, this code updates the progress bar with the value of pvalue
2229 And that is all there is to know about Progress Bars, enjoy.
2231 <!-- ----------------------------------------------------------------- -->
2235 The Dialog widget is very simple, and is actually just a window with a few
2236 things pre-packed into it for you. The structure for a Dialog is:
2244 GtkWidget *action_area;
2248 So you see, it simple creates a window, and then packs a vbox into the top,
2249 then a seperator, and then an hbox for the "action_area".
2251 The Dialog widget can be used for pop-up messages to the user, and
2252 other similar tasks. It is really basic, and there is only one
2253 function for the dialog box, which is:
2256 GtkWidget* gtk_dialog_new (void);
2259 So to create a new dialog box, use,
2263 window = gtk_dialog_new ();
2266 This will create the dialog box, and it is now up to you to use it.
2267 you could pack a button in the action_area by doing something like so:
2271 gtk_box_pack_start (GTK_BOX (GTK_DIALOG (window)->action_area), button,
2273 gtk_widget_show (button);
2276 And you could add to the vbox area by packing, for instance, a label
2277 in it, try something like this:
2280 label = gtk_label_new ("Dialogs are groovy");
2281 gtk_box_pack_start (GTK_BOX (GTK_DIALOG (window)->vbox), label, TRUE,
2283 gtk_widget_show (label);
2286 As an example in using the dialog box, you could put two buttons in
2287 the action_area, a Cancel button and an Ok button, and a label in the vbox
2288 area, asking the user a question or giving an error etc. Then you could
2289 attach a different signal to each of the buttons and perform the
2290 operation the user selects.
2292 <!-- ----------------------------------------------------------------- -->
2295 Pixmaps are data structures that contain pictures. These pictures can be
2296 used in various places, but most visibly as icons on the X-Windows desktop,
2297 or as cursors. A bitmap is a 2-color pixmap.
2299 To use pixmaps in GTK, we must first build a GdkPixmap structure using
2300 routines from the GDK layer. Pixmaps can either be created from in-memory
2301 data, or from data read from a file. We'll go through each of the calls
2305 GdkPixmap *gdk_bitmap_create_from_data( GdkWindow *window,
2311 This routine is used to create a single-plane pixmap (2 colors) from data in
2312 memory. Each bit of the data represents whether that pixel is off or on.
2313 Width and height are in pixels. The GdkWindow pointer is to the current
2314 window, since a pixmap resources are meaningful only in the context of the
2315 screen where it is to be displayed.
2318 GdkPixmap* gdk_pixmap_create_from_data( GdkWindow *window,
2327 This is used to create a pixmap of the given depth (number of colors) from
2328 the bitmap data specified. fg and bg are the foreground and background
2332 GdkPixmap* gdk_pixmap_create_from_xpm( GdkWindow *window,
2334 GdkColor *transparent_color,
2335 const gchar *filename );
2338 XPM format is a readable pixmap representation for the X Window System. It
2339 is widely used and many different utilities are available for creating image
2340 files in this format. The file specified by filename must contain an image
2341 in that format and it is loaded into the pixmap structure. The mask specifies
2342 what bits of the pixmap are opaque. All other bits are colored using the
2343 color specified by transparent_color. An example using this follows below.
2346 GdkPixmap* gdk_pixmap_create_from_xpm_d (GdkWindow *window,
2348 GdkColor *transparent_color,
2352 Small images can be incorporated into a program as data in the XPM format.
2353 A pixmap is created using this data, instead of reading it from a file.
2354 An example of such data is
2358 static const char * xpm_data[] = {
2361 ". c #000000000000",
2362 "X c #FFFFFFFFFFFF",
2382 void gdk_pixmap_destroy( GdkPixmap *pixmap );
2385 When we're done using a pixmap and not likely to reuse it again soon,
2386 it is a good idea to release the resource using gdk_pixmap_destroy. Pixmaps
2387 should be considered a precious resource.
2390 Once we've created a pixmap, we can display it as a GTK widget. We must
2391 create a pixmap widget to contain the GDK pixmap. This is done using
2394 GtkWidget* gtk_pixmap_new( GdkPixmap *pixmap,
2398 The other pixmap widget calls are
2401 guint gtk_pixmap_get_type( void );
2402 void gtk_pixmap_set( GtkPixmap *pixmap,
2405 void gtk_pixmap_get( GtkPixmap *pixmap,
2410 gtk_pixmap_set is used to change the pixmap that the widget is currently
2411 managing. Val is the pixmap created using GDK.
2413 The following is an example of using a pixmap in a button.
2418 #include <gtk/gtk.h>
2421 /* XPM data of Open-File icon */
2422 static const char * xpm_data[] = {
2425 ". c #000000000000",
2426 "X c #FFFFFFFFFFFF",
2445 /* when invoked (via signal delete_event), terminates the application.
2447 void close_application( GtkWidget *widget, gpointer *data ) {
2452 /* is invoked when the button is clicked. It just prints a message.
2454 void button_clicked( GtkWidget *widget, gpointer *data ) {
2455 printf( "button clicked\n" );
2458 int main( int argc, char *argv[] )
2460 /* GtkWidget is the storage type for widgets */
2461 GtkWidget *window, *pixmapwid, *button;
2466 /* create the main window, and attach delete_event signal to terminating
2468 gtk_init( &argc, &argv );
2469 window = gtk_window_new( GTK_WINDOW_TOPLEVEL );
2470 gtk_signal_connect( GTK_OBJECT (window), "delete_event",
2471 GTK_SIGNAL_FUNC (close_application), NULL );
2472 gtk_container_border_width( GTK_CONTAINER (window), 10 );
2473 gtk_widget_show( window );
2475 /* now for the pixmap from gdk */
2476 style = gtk_widget_get_style( window );
2477 pixmap = gdk_pixmap_create_from_xpm_d( window->window, &mask,
2478 &style->bg[GTK_STATE_NORMAL],
2479 (gchar **)xpm_data );
2481 /* a pixmap widget to contain the pixmap */
2482 pixmapwid = gtk_pixmap_new( pixmap, mask );
2483 gtk_widget_show( pixmapwid );
2485 /* a button to contain the pixmap widget */
2486 button = gtk_button_new();
2487 gtk_container_add( GTK_CONTAINER(button), pixmapwid );
2488 gtk_container_add( GTK_CONTAINER(window), button );
2489 gtk_widget_show( button );
2491 gtk_signal_connect( GTK_OBJECT(button), "clicked",
2492 GTK_SIGNAL_FUNC(button_clicked), NULL );
2494 /* show the window */
2502 To load a file from an XPM data file called icon0.xpm in the current
2503 directory, we would have created the pixmap thus
2506 /* load a pixmap from a file */
2507 pixmap = gdk_pixmap_create_from_xpm( window->window, &mask,
2508 &style->bg[GTK_STATE_NORMAL],
2510 pixmapwid = gtk_pixmap_new( pixmap, mask );
2511 gtk_widget_show( pixmapwid );
2512 gtk_container_add( GTK_CONTAINER(window), pixmapwid );
2519 A disadvantage of using pixmaps is that the displayed object is always
2520 rectangular, regardless of the image. We would like to create desktops
2521 and applications with icons that have more natural shapes. For example,
2522 for a game interface, we would like to have round buttons to push. The
2523 way to do this is using shaped windows.
2525 A shaped window is simply a pixmap where the background pixels are
2526 transparent. This way, when the background image is multi-colored, we
2527 don't overwrite it with a rectangular, non-matching border around our
2528 icon. The following example displays a full wheelbarrow image on the
2534 #include <gtk/gtk.h>
2537 static char * WheelbarrowFull_xpm[] = {
2540 ". c #DF7DCF3CC71B",
2541 "X c #965875D669A6",
2542 "o c #71C671C671C6",
2543 "O c #A699A289A699",
2544 "+ c #965892489658",
2545 "@ c #8E38410330C2",
2546 "# c #D75C7DF769A6",
2547 "$ c #F7DECF3CC71B",
2548 "% c #96588A288E38",
2549 "& c #A69992489E79",
2550 "* c #8E3886178E38",
2551 "= c #104008200820",
2552 "- c #596510401040",
2553 "; c #C71B30C230C2",
2554 ": c #C71B9A699658",
2555 "> c #618561856185",
2556 ", c #20811C712081",
2557 "< c #104000000000",
2558 "1 c #861720812081",
2559 "2 c #DF7D4D344103",
2560 "3 c #79E769A671C6",
2561 "4 c #861782078617",
2562 "5 c #41033CF34103",
2563 "6 c #000000000000",
2564 "7 c #49241C711040",
2565 "8 c #492445144924",
2566 "9 c #082008200820",
2567 "0 c #69A618611861",
2568 "q c #B6DA71C65144",
2569 "w c #410330C238E3",
2570 "e c #CF3CBAEAB6DA",
2571 "r c #71C6451430C2",
2572 "t c #EFBEDB6CD75C",
2573 "y c #28A208200820",
2574 "u c #186110401040",
2575 "i c #596528A21861",
2576 "p c #71C661855965",
2577 "a c #A69996589658",
2578 "s c #30C228A230C2",
2579 "d c #BEFBA289AEBA",
2580 "f c #596545145144",
2581 "g c #30C230C230C2",
2582 "h c #8E3882078617",
2583 "j c #208118612081",
2584 "k c #38E30C300820",
2585 "l c #30C2208128A2",
2586 "z c #38E328A238E3",
2587 "x c #514438E34924",
2588 "c c #618555555965",
2589 "v c #30C2208130C2",
2590 "b c #38E328A230C2",
2591 "n c #28A228A228A2",
2592 "m c #41032CB228A2",
2593 "M c #104010401040",
2594 "N c #492438E34103",
2595 "B c #28A2208128A2",
2596 "V c #A699596538E3",
2597 "C c #30C21C711040",
2598 "Z c #30C218611040",
2599 "A c #965865955965",
2600 "S c #618534D32081",
2601 "D c #38E31C711040",
2602 "F c #082000000820",
2611 "ty> 459@>+&& ",
2613 "%$;=* *3:.Xa.dfg> ",
2614 "Oh$;ya *3d.a8j,Xe.d3g8+ ",
2615 " Oh$;ka *3d$a8lz,,xxc:.e3g54 ",
2616 " Oh$;kO *pd$%svbzz,sxxxxfX..&wn> ",
2617 " Oh$@mO *3dthwlsslszjzxxxxxxx3:td8M4 ",
2618 " Oh$@g& *3d$XNlvvvlllm,mNwxxxxxxxfa.:,B* ",
2619 " Oh$@,Od.czlllllzlmmqV@V#V@fxxxxxxxf:%j5& ",
2620 " Oh$1hd5lllslllCCZrV#r#:#2AxxxxxxxxxcdwM* ",
2621 " OXq6c.%8vvvllZZiqqApA:mq:Xxcpcxxxxxfdc9* ",
2622 " 2r<6gde3bllZZrVi7S@SV77A::qApxxxxxxfdcM ",
2623 " :,q-6MN.dfmZZrrSS:#riirDSAX@Af5xxxxxfevo",
2624 " +A26jguXtAZZZC7iDiCCrVVii7Cmmmxxxxxx%3g",
2625 " *#16jszN..3DZZZZrCVSA2rZrV7Dmmwxxxx&en",
2626 " p2yFvzssXe:fCZZCiiD7iiZDiDSSZwwxx8e*>",
2627 " OA1<jzxwwc:$d%NDZZZZCCCZCCZZCmxxfd.B ",
2628 " 3206Bwxxszx%et.eaAp77m77mmmf3&eeeg* ",
2629 " @26MvzxNzvlbwfpdettttttttttt.c,n& ",
2630 " *;16=lsNwwNwgsvslbwwvccc3pcfu<o ",
2631 " p;<69BvwwsszslllbBlllllllu<5+ ",
2632 " OS0y6FBlvvvzvzss,u=Blllj=54 ",
2633 " c1-699Blvlllllu7k96MMMg4 ",
2634 " *10y8n6FjvllllB<166668 ",
2635 " S-kg+>666<M<996-y6n<8* ",
2636 " p71=4 m69996kD8Z-66698&& ",
2637 " &i0ycm6n4 ogk17,0<6666g ",
2638 " N-k-<> >=01-kuu666> ",
2639 " ,6ky& &46-10ul,66, ",
2640 " Ou0<> o66y<ulw<66& ",
2641 " *kk5 >66By7=xu664 ",
2642 " <<M4 466lj<Mxu66o ",
2643 " *>> +66uv,zN666* ",
2653 /* when invoked (via signal delete_event), terminates the application.
2655 void close_application( GtkWidget *widget, gpointer *data ) {
2659 int main (int argc, char *argv[])
2661 /* GtkWidget is the storage type for widgets */
2662 GtkWidget *window, *pixmap, *fixed;
2663 GdkPixmap *gdk_pixmap;
2668 /* create the main window, and attach delete_event signal to terminate
2669 the application. Note that the main window will not have a titlebar
2670 since we're making it a popup. */
2671 gtk_init (&argc, &argv);
2672 window = gtk_window_new( GTK_WINDOW_POPUP );
2673 gtk_signal_connect (GTK_OBJECT (window), "delete_event",
2674 GTK_SIGNAL_FUNC (close_application), NULL);
2675 gtk_widget_show (window);
2677 /* now for the pixmap and the pixmap widget */
2678 style = gtk_widget_get_default_style();
2679 gc = style->black_gc;
2680 gdk_pixmap = gdk_pixmap_create_from_xpm_d( window->window, &mask,
2681 &style->bg[GTK_STATE_NORMAL],
2682 WheelbarrowFull_xpm );
2683 pixmap = gtk_pixmap_new( gdk_pixmap, mask );
2684 gtk_widget_show( pixmap );
2686 /* To display the pixmap, we use a fixed widget to place the pixmap */
2687 fixed = gtk_fixed_new();
2688 gtk_widget_set_usize( fixed, 200, 200 );
2689 gtk_fixed_put( GTK_FIXED(fixed), pixmap, 0, 0 );
2690 gtk_container_add( GTK_CONTAINER(window), fixed );
2691 gtk_widget_show( fixed );
2693 /* This masks out everything except for the image itself */
2694 gtk_widget_shape_combine_mask( window, mask, 0, 0 );
2696 /* show the window */
2697 gtk_widget_set_uposition( window, 20, 400 );
2698 gtk_widget_show( window );
2705 To make the wheelbarrow image sensitive, we could attach the button press
2706 event signal to make it do something. The following few lines would make
2707 the picture sensitive to a mouse button being pressed which makes the
2708 application terminate.
2711 gtk_widget_set_events( window,
2712 gtk_widget_get_events( window ) |
2713 GDK_BUTTON_PRESS_MASK );
2715 gtk_signal_connect( GTK_OBJECT(window), "button_press_event",
2716 GTK_SIGNAL_FUNC(close_application), NULL );
2719 <!-- ----------------------------------------------------------------- -->
2722 Ruler widgets are used to indicate the location of the mouse pointer
2723 in a given window. A window can have a vertical ruler spanning across
2724 the width and a horizontal ruler spanning down the height. A small
2725 triangular indicator on the ruler shows the exact location of the
2726 pointer relative to the ruler.
2728 A ruler must first be created. Horizontal and vertical rulers are
2732 GtkWidget *gtk_hruler_new(void); /* horizontal ruler */
2733 GtkWidget *gtk_vruler_new(void); /* vertical ruler */
2736 Once a ruler is created, we can define the unit of measurement. Units
2737 of measure for rulers can be GTK_PIXELS, GTK_INCHES or
2738 GTK_CENTIMETERS. This is set using
2741 void gtk_ruler_set_metric( GtkRuler *ruler,
2742 GtkMetricType metric );
2745 The default measure is GTK_PIXELS.
2748 gtk_ruler_set_metric( GTK_RULER(ruler), GTK_PIXELS );
2751 Other important characteristics of a ruler are how to mark the units
2752 of scale and where the position indicator is initially placed. These
2753 are set for a ruler using
2756 void gtk_ruler_set_range (GtkRuler *ruler,
2763 The lower and upper arguments define the extents of the ruler, and
2764 max_size is the largest possible number that will be displayed.
2765 Position defines the initial position of the pointer indicator within
2768 A vertical ruler can span an 800 pixel wide window thus
2771 gtk_ruler_set_range( GTK_RULER(vruler), 0, 800, 0, 800);
2774 The markings displayed on the ruler will be from 0 to 800, with
2775 a number for every 100 pixels. If instead we wanted the ruler to
2776 range from 7 to 16, we would code
2779 gtk_ruler_set_range( GTK_RULER(vruler), 7, 16, 0, 20);
2782 The indicator on the ruler is a small triangular mark that indicates
2783 the position of the pointer relative to the ruler. If the ruler is
2784 used to follow the mouse pointer, the motion_notify_event signal
2785 should be connected to the motion_notify_event method of the ruler.
2786 To follow all mouse movements within a window area, we would use
2789 #define EVENT_METHOD(i, x) GTK_WIDGET_CLASS(GTK_OBJECT(i)->klass)->x
2791 gtk_signal_connect_object( GTK_OBJECT(area), "motion_notify_event",
2792 (GtkSignalFunc)EVENT_METHOD(ruler, motion_notify_event),
2793 GTK_OBJECT(ruler) );
2796 The following example creates a drawing area with a horizontal ruler
2797 above it and a vertical ruler to the left of it. The size of the
2798 drawing area is 600 pixels wide by 400 pixels high. The horizontal
2799 ruler spans from 7 to 13 with a mark every 100 pixels, while the
2800 vertical ruler spans from 0 to 400 with a mark every 100 pixels.
2801 Placement of the drawing area and the rulers are done using a table.
2806 #include <gtk/gtk.h>
2808 #define EVENT_METHOD(i, x) GTK_WIDGET_CLASS(GTK_OBJECT(i)->klass)->x
2813 /* this routine gets control when the close button is clicked
2815 void close_application( GtkWidget *widget, gpointer *data ) {
2822 int main( int argc, char *argv[] ) {
2823 GtkWidget *window, *table, *area, *hrule, *vrule;
2825 /* initialize gtk and create the main window */
2826 gtk_init( &argc, &argv );
2828 window = gtk_window_new( GTK_WINDOW_TOPLEVEL );
2829 gtk_signal_connect (GTK_OBJECT (window), "delete_event",
2830 GTK_SIGNAL_FUNC( close_application ), NULL);
2831 gtk_container_border_width (GTK_CONTAINER (window), 10);
2833 /* create a table for placing the ruler and the drawing area */
2834 table = gtk_table_new( 3, 2, FALSE );
2835 gtk_container_add( GTK_CONTAINER(window), table );
2837 area = gtk_drawing_area_new();
2838 gtk_drawing_area_size( (GtkDrawingArea *)area, XSIZE, YSIZE );
2839 gtk_table_attach( GTK_TABLE(table), area, 1, 2, 1, 2,
2840 GTK_EXPAND|GTK_FILL, GTK_FILL, 0, 0 );
2841 gtk_widget_set_events( area, GDK_POINTER_MOTION_MASK | GDK_POINTER_MOTION_HINT_MASK );
2843 /* The horizontal ruler goes on top. As the mouse moves across the drawing area,
2844 a motion_notify_event is passed to the appropriate event handler for the ruler. */
2845 hrule = gtk_hruler_new();
2846 gtk_ruler_set_metric( GTK_RULER(hrule), GTK_PIXELS );
2847 gtk_ruler_set_range( GTK_RULER(hrule), 7, 13, 0, 20 );
2848 gtk_signal_connect_object( GTK_OBJECT(area), "motion_notify_event",
2849 (GtkSignalFunc)EVENT_METHOD(hrule, motion_notify_event),
2850 GTK_OBJECT(hrule) );
2851 /* GTK_WIDGET_CLASS(GTK_OBJECT(hrule)->klass)->motion_notify_event, */
2852 gtk_table_attach( GTK_TABLE(table), hrule, 1, 2, 0, 1,
2853 GTK_EXPAND|GTK_SHRINK|GTK_FILL, GTK_FILL, 0, 0 );
2855 /* The vertical ruler goes on the left. As the mouse moves across the drawing area,
2856 a motion_notify_event is passed to the appropriate event handler for the ruler. */
2857 vrule = gtk_vruler_new();
2858 gtk_ruler_set_metric( GTK_RULER(vrule), GTK_PIXELS );
2859 gtk_ruler_set_range( GTK_RULER(vrule), 0, YSIZE, 10, YSIZE );
2860 gtk_signal_connect_object( GTK_OBJECT(area), "motion_notify_event",
2862 GTK_WIDGET_CLASS(GTK_OBJECT(vrule)->klass)->motion_notify_event,
2863 GTK_OBJECT(vrule) );
2864 gtk_table_attach( GTK_TABLE(table), vrule, 0, 1, 1, 2,
2865 GTK_FILL, GTK_EXPAND|GTK_SHRINK|GTK_FILL, 0, 0 );
2867 /* now show everything */
2868 gtk_widget_show( area );
2869 gtk_widget_show( hrule );
2870 gtk_widget_show( vrule );
2871 gtk_widget_show( table );
2872 gtk_widget_show( window );
2879 <!-- ----------------------------------------------------------------- -->
2882 Statusbars are simple widgets used to display a text message. They keep a stack
2883 of the messages pushed onto them, so that popping the current message
2884 will re-display the previous text message.
2886 In order to allow different parts of an application to use the same statusbar to display
2887 messages, the statusbar widget issues Context Identifiers which are used to identify
2888 different 'users'. The message on top of the stack is the one displayed, no matter what context
2889 it is in. Messages are stacked in last-in-first-out order, not context identifier order.
2891 A statusbar is created with a call to:
2893 GtkWidget* gtk_statusbar_new (void);
2896 A new Context Identifier is requested using a call to the following function with a short
2897 textual description of the context:
2899 guint gtk_statusbar_get_context_id (GtkStatusbar *statusbar,
2900 const gchar *context_description);
2903 There are three functions that can operate on statusbars.
2905 guint gtk_statusbar_push (GtkStatusbar *statusbar,
2909 void gtk_statusbar_pop (GtkStatusbar *statusbar)
2911 void gtk_statusbar_remove (GtkStatusbar *statusbar,
2916 The first, gtk_statusbar_push, is used to add a new message to the statusbar.
2917 It returns a Message Identifier, which can be passed later to the function gtk_statusbar_remove
2918 to remove the message with the given Message and Context Identifiers from the statusbar's stack.
2920 The function gtk_statusbar_pop removes the message highest in the stack with the given
2923 The following example creates a statusbar and two buttons, one for pushing items
2924 onto the statusbar, and one for popping the last item back off.
2929 #include <gtk/gtk.h>
2932 GtkWidget *status_bar;
2934 void push_item (GtkWidget *widget, gpointer *data)
2936 static int count = 1;
2939 g_snprintf(buff, 20, "Item %d", count++);
2940 gtk_statusbar_push( GTK_STATUSBAR(status_bar), (guint) &data, buff);
2945 void pop_item (GtkWidget *widget, gpointer *data)
2947 gtk_statusbar_pop( GTK_STATUSBAR(status_bar), (guint) &data );
2951 int main (int argc, char *argv[])
2960 gtk_init (&argc, &argv);
2962 /* create a new window */
2963 window = gtk_window_new(GTK_WINDOW_TOPLEVEL);
2964 gtk_widget_set_usize( GTK_WIDGET (window), 200, 100);
2965 gtk_window_set_title(GTK_WINDOW (window), "GTK Statusbar Example");
2966 gtk_signal_connect(GTK_OBJECT (window), "delete_event",
2967 (GtkSignalFunc) gtk_exit, NULL);
2969 vbox = gtk_vbox_new(FALSE, 1);
2970 gtk_container_add(GTK_CONTAINER(window), vbox);
2971 gtk_widget_show(vbox);
2973 status_bar = gtk_statusbar_new();
2974 gtk_box_pack_start (GTK_BOX (vbox), status_bar, TRUE, TRUE, 0);
2975 gtk_widget_show (status_bar);
2977 context_id = gtk_statusbar_get_context_id( GTK_STATUSBAR(status_bar), "Statusbar example");
2979 button = gtk_button_new_with_label("push item");
2980 gtk_signal_connect(GTK_OBJECT(button), "clicked",
2981 GTK_SIGNAL_FUNC (push_item), &context_id);
2982 gtk_box_pack_start(GTK_BOX(vbox), button, TRUE, TRUE, 2);
2983 gtk_widget_show(button);
2985 button = gtk_button_new_with_label("pop last item");
2986 gtk_signal_connect(GTK_OBJECT(button), "clicked",
2987 GTK_SIGNAL_FUNC (pop_item), &context_id);
2988 gtk_box_pack_start(GTK_BOX(vbox), button, TRUE, TRUE, 2);
2989 gtk_widget_show(button);
2991 /* always display the window as the last step so it all splashes on
2992 * the screen at once. */
2993 gtk_widget_show(window);
3001 <!-- ----------------------------------------------------------------- -->
3004 The Entry widget allows text to be typed and displayed in a single line text box.
3005 The text may be set with functions calls that allow new text to replace,
3006 prepend or append the current contents of the Entry widget.
3008 There are two functions for creating Entry widgets:
3010 GtkWidget* gtk_entry_new (void);
3012 GtkWidget* gtk_entry_new_with_max_length (guint16 max);
3015 The first just creates a new Entry widget, whilst the second creates a new Entry and
3016 sets a limit on the length of the text within the Entry..
3018 The maximum length of the text within an entry widget may be changed by a call to the following
3019 function. If the current text is longer than this maximum, then it is upto us to alter the Entries
3020 contents appropriately.
3023 void gtk_entry_set_max_length (GtkEntry *entry,
3027 There are several functions for altering the text which is currently within the Entry widget.
3029 void gtk_entry_set_text (GtkEntry *entry,
3031 void gtk_entry_append_text (GtkEntry *entry,
3033 void gtk_entry_prepend_text (GtkEntry *entry,
3037 The function gtk_entry_set_text sets the contents of the Entry widget, replacing the
3038 current contents. The functions gtk_entry_append_text and gtk_entry_prepend_text allow
3039 the current contents to be appended and prepended to.
3041 The next function allows the current insertion point to be set.
3043 void gtk_entry_set_position (GtkEntry *entry,
3047 The contents of the Entry can be retrieved by using a call to the following function. This
3048 is useful in the callback functions described below.
3050 gchar* gtk_entry_get_text (GtkEntry *entry);
3053 If we don't want the contents of the Entry to be changed by someone typing into it, we
3054 can change it's edittable state.
3056 void gtk_entry_set_editable (GtkEntry *entry,
3060 This function allows us to toggle the edittable state of the Entry widget by passing in
3061 TRUE or FALSE values for the editable argument.
3063 If we are using the Entry where we don't want the text entered to be visible, for
3064 example when a password is being entered, we can use the following function, which
3065 also takes a boolean flag.
3067 void gtk_entry_set_visibility (GtkEntry *entry,
3071 A region of the text may be set as selected by using the following function. This would
3072 most often be used after setting some default text in an Entry, making it easy for the user
3075 void gtk_entry_select_region (GtkEntry *entry,
3080 If we want to catch when the user has entered text, we can connect to the
3081 <tt/activate/ or <tt/changed/ signal. Activate is raised when the user hits
3082 the enter key within the Entry widget. Changed is raised when the text changes at all,
3083 e.g. for every character entered or removed.
3085 The following code is an example of using an Entry widget.
3089 #include <gtk/gtk.h>
3091 void enter_callback(GtkWidget *widget, GtkWidget *entry)
3094 entry_text = gtk_entry_get_text(GTK_ENTRY(entry));
3095 printf("Entry contents: %s\n", entry_text);
3098 void entry_toggle_editable (GtkWidget *checkbutton,
3101 gtk_entry_set_editable(GTK_ENTRY(entry),
3102 GTK_TOGGLE_BUTTON(checkbutton)->active);
3105 void entry_toggle_visibility (GtkWidget *checkbutton,
3108 gtk_entry_set_visibility(GTK_ENTRY(entry),
3109 GTK_TOGGLE_BUTTON(checkbutton)->active);
3112 int main (int argc, char *argv[])
3116 GtkWidget *vbox, *hbox;
3121 gtk_init (&argc, &argv);
3123 /* create a new window */
3124 window = gtk_window_new(GTK_WINDOW_TOPLEVEL);
3125 gtk_widget_set_usize( GTK_WIDGET (window), 200, 100);
3126 gtk_window_set_title(GTK_WINDOW (window), "GTK Entry");
3127 gtk_signal_connect(GTK_OBJECT (window), "delete_event",
3128 (GtkSignalFunc) gtk_exit, NULL);
3130 vbox = gtk_vbox_new (FALSE, 0);
3131 gtk_container_add (GTK_CONTAINER (window), vbox);
3132 gtk_widget_show (vbox);
3134 entry = gtk_entry_new_with_max_length (50);
3135 gtk_signal_connect(GTK_OBJECT(entry), "activate",
3136 GTK_SIGNAL_FUNC(enter_callback),
3138 gtk_entry_set_text (GTK_ENTRY (entry), "hello");
3139 gtk_entry_append_text (GTK_ENTRY (entry), " world");
3140 gtk_entry_select_region (GTK_ENTRY (entry),
3141 0, GTK_ENTRY(entry)->text_length);
3142 gtk_box_pack_start (GTK_BOX (vbox), entry, TRUE, TRUE, 0);
3143 gtk_widget_show (entry);
3145 hbox = gtk_hbox_new (FALSE, 0);
3146 gtk_container_add (GTK_CONTAINER (vbox), hbox);
3147 gtk_widget_show (hbox);
3149 check = gtk_check_button_new_with_label("Editable");
3150 gtk_box_pack_start (GTK_BOX (hbox), check, TRUE, TRUE, 0);
3151 gtk_signal_connect (GTK_OBJECT(check), "toggled",
3152 GTK_SIGNAL_FUNC(entry_toggle_editable), entry);
3153 gtk_toggle_button_set_state(GTK_TOGGLE_BUTTON(check), TRUE);
3154 gtk_widget_show (check);
3156 check = gtk_check_button_new_with_label("Visible");
3157 gtk_box_pack_start (GTK_BOX (hbox), check, TRUE, TRUE, 0);
3158 gtk_signal_connect (GTK_OBJECT(check), "toggled",
3159 GTK_SIGNAL_FUNC(entry_toggle_visibility), entry);
3160 gtk_toggle_button_set_state(GTK_TOGGLE_BUTTON(check), TRUE);
3161 gtk_widget_show (check);
3163 button = gtk_button_new_with_label ("Close");
3164 gtk_signal_connect_object (GTK_OBJECT (button), "clicked",
3165 GTK_SIGNAL_FUNC(gtk_exit),
3166 GTK_OBJECT (window));
3167 gtk_box_pack_start (GTK_BOX (vbox), button, TRUE, TRUE, 0);
3168 GTK_WIDGET_SET_FLAGS (button, GTK_CAN_DEFAULT);
3169 gtk_widget_grab_default (button);
3170 gtk_widget_show (button);
3172 gtk_widget_show(window);
3179 <!-- ***************************************************************** -->
3180 <sect> Container Widgets
3181 <!-- ***************************************************************** -->
3183 <!-- ----------------------------------------------------------------- -->
3186 The NoteBook Widget is a collection of 'pages' that overlap each other,
3187 each page contains different information. This widget has become more common
3188 lately in GUI programming, and it is a good way to show blocks similar
3189 information that warrant separation in their display.
3191 The first function call you will need to know, as you can probably
3192 guess by now, is used to create a new notebook widget.
3195 GtkWidget* gtk_notebook_new (void);
3198 Once the notebook has been created, there are 12 functions that
3199 operate on the notebook widget. Let's look at them individually.
3201 The first one we will look at is how to position the page indicators.
3202 These page indicators or 'tabs' as they are referred to, can be positioned
3203 in four ways; top, bottom, left, or right.
3206 void gtk_notebook_set_tab_pos (GtkNotebook *notebook, GtkPositionType pos);
3209 GtkPostionType will be one of the following, and they are pretty self explanatory.
3212 <item> GTK_POS_RIGHT
3214 <item> GTK_POS_BOTTOM
3217 GTK_POS_TOP is the default.
3219 Next we will look at how to add pages to the notebook. There are three
3220 ways to add pages to the NoteBook. Let's look at the first two together as
3221 they are quite similar.
3224 void gtk_notebook_append_page (GtkNotebook *notebook, GtkWidget *child, GtkWidget *tab_label);
3226 void gtk_notebook_prepend_page (GtkNotebook *notebook, GtkWidget *child, GtkWidget *tab_label);
3229 These functions add pages to the notebook by inserting them from the
3230 back of the notebook (append), or the front of the notebook (prepend).
3231 *child is the widget that is placed within the notebook page, and *tab_label is
3232 the label for the page being added.
3234 The final function for adding a page to the notebook contains all of
3235 the properties of the previous two, but it allows you to specify what position
3236 you want the page to be in the notebook.
3239 void gtk_notebook_insert_page (GtkNotebook *notebook, GtkWidget *child, GtkWidget *tab_label, gint position);
3242 The parameters are the same as _append_ and _prepend_ except it
3243 contains an extra parameter, position. This parameter is used to specify what
3244 place this page will inserted to.
3246 Now that we know how to add a page, lets see how we can remove a page
3250 void gtk_notebook_remove_page (GtkNotebook *notebook, gint page_num);
3253 This function takes the page specified by page_num and removes it from
3254 the widget *notebook.
3256 To find out what the current page is in a notebook use the function:
3259 gint gtk_notebook_current_page (GtkNotebook *notebook);
3262 These next two functions are simple calls to move the notebook page
3263 forward or backward. Simply provide the respective function call with the
3264 notebook widget you wish to operate on. Note: When the NoteBook is currently
3265 on the last page, and gtk_notebook_next_page is called, the notebook will
3266 wrap back to the first page. Likewise, if the NoteBook is on the first page,
3267 and gtk_notebook_prev_page is called, the notebook will wrap to the last page.
3270 void gtk_notebook_next_page (GtkNoteBook *notebook);
3271 void gtk_notebook_prev_page (GtkNoteBook *notebook);
3274 This next function sets the 'active' page. If you wish the
3275 notebook to be opened to page 5 for example, you would use this function.
3276 Without using this function, the notebook defaults to the first page.
3279 void gtk_notebook_set_page (GtkNotebook *notebook, gint page_num);
3282 The next two functions add or remove the notebook page tabs and the
3283 notebook border respectively.
3286 void gtk_notebook_set_show_tabs (GtkNotebook *notebook, gint show_tabs);
3287 void gtk_notebook_set_show_border (GtkNotebook *notebook, gint show_border);
3290 show_tabs and show_border can both be either TRUE or FALSE (0 or 1).
3292 Now lets look at an example, it is expanded from the testgtk.c code
3293 that comes with the GTK distribution, and it shows all 13 functions. This
3294 small program, creates a window with a notebook and six buttons. The notebook
3295 contains 11 pages, added in three different ways, appended, inserted, and
3296 prepended. The buttons allow you rotate the tab positions, add/remove the tabs
3297 and border, remove a page, change pages in both a forward and backward manner,
3298 and exit the program.
3303 #include <gtk/gtk.h>
3305 /* This function rotates the position of the tabs */
3306 void rotate_book (GtkButton *button, GtkNotebook *notebook)
3308 gtk_notebook_set_tab_pos (notebook, (notebook->tab_pos +1) %4);
3311 /* Add/Remove the page tabs and the borders */
3312 void tabsborder_book (GtkButton *button, GtkNotebook *notebook)
3316 if (notebook->show_tabs == 0)
3318 if (notebook->show_border == 0)
3321 gtk_notebook_set_show_tabs (notebook, tval);
3322 gtk_notebook_set_show_border (notebook, bval);
3325 /* Remove a page from the notebook */
3326 void remove_book (GtkButton *button, GtkNotebook *notebook)
3330 page = gtk_notebook_current_page(notebook);
3331 gtk_notebook_remove_page (notebook, page);
3332 /* Need to refresh the widget --
3333 This forces the widget to redraw itself. */
3334 gtk_widget_draw(GTK_WIDGET(notebook), NULL);
3337 void delete (GtkWidget *widget, gpointer *data)
3342 int main (int argc, char *argv[])
3347 GtkWidget *notebook;
3350 GtkWidget *checkbutton;
3355 gtk_init (&argc, &argv);
3357 window = gtk_window_new (GTK_WINDOW_TOPLEVEL);
3359 gtk_signal_connect (GTK_OBJECT (window), "delete_event",
3360 GTK_SIGNAL_FUNC (delete), NULL);
3362 gtk_container_border_width (GTK_CONTAINER (window), 10);
3364 table = gtk_table_new(2,6,TRUE);
3365 gtk_container_add (GTK_CONTAINER (window), table);
3367 /* Create a new notebook, place the position of the tabs */
3368 notebook = gtk_notebook_new ();
3369 gtk_notebook_set_tab_pos (GTK_NOTEBOOK (notebook), GTK_POS_TOP);
3370 gtk_table_attach_defaults(GTK_TABLE(table), notebook, 0,6,0,1);
3371 gtk_widget_show(notebook);
3373 /* lets append a bunch of pages to the notebook */
3374 for (i=0; i < 5; i++) {
3375 sprintf(bufferf, "Append Frame %d", i+1);
3376 sprintf(bufferl, "Page %d", i+1);
3378 frame = gtk_frame_new (bufferf);
3379 gtk_container_border_width (GTK_CONTAINER (frame), 10);
3380 gtk_widget_set_usize (frame, 100, 75);
3381 gtk_widget_show (frame);
3383 label = gtk_label_new (bufferf);
3384 gtk_container_add (GTK_CONTAINER (frame), label);
3385 gtk_widget_show (label);
3387 label = gtk_label_new (bufferl);
3388 gtk_notebook_append_page (GTK_NOTEBOOK (notebook), frame, label);
3392 /* now lets add a page to a specific spot */
3393 checkbutton = gtk_check_button_new_with_label ("Check me please!");
3394 gtk_widget_set_usize(checkbutton, 100, 75);
3395 gtk_widget_show (checkbutton);
3397 label = gtk_label_new ("Add spot");
3398 gtk_container_add (GTK_CONTAINER (checkbutton), label);
3399 gtk_widget_show (label);
3400 label = gtk_label_new ("Add page");
3401 gtk_notebook_insert_page (GTK_NOTEBOOK (notebook), checkbutton, label, 2);
3403 /* Now finally lets prepend pages to the notebook */
3404 for (i=0; i < 5; i++) {
3405 sprintf(bufferf, "Prepend Frame %d", i+1);
3406 sprintf(bufferl, "PPage %d", i+1);
3408 frame = gtk_frame_new (bufferf);
3409 gtk_container_border_width (GTK_CONTAINER (frame), 10);
3410 gtk_widget_set_usize (frame, 100, 75);
3411 gtk_widget_show (frame);
3413 label = gtk_label_new (bufferf);
3414 gtk_container_add (GTK_CONTAINER (frame), label);
3415 gtk_widget_show (label);
3417 label = gtk_label_new (bufferl);
3418 gtk_notebook_prepend_page (GTK_NOTEBOOK(notebook), frame, label);
3421 /* Set what page to start at (page 4) */
3422 gtk_notebook_set_page (GTK_NOTEBOOK(notebook), 3);
3425 /* create a bunch of buttons */
3426 button = gtk_button_new_with_label ("close");
3427 gtk_signal_connect_object (GTK_OBJECT (button), "clicked",
3428 GTK_SIGNAL_FUNC (delete), NULL);
3429 gtk_table_attach_defaults(GTK_TABLE(table), button, 0,1,1,2);
3430 gtk_widget_show(button);
3432 button = gtk_button_new_with_label ("next page");
3433 gtk_signal_connect_object (GTK_OBJECT (button), "clicked",
3434 (GtkSignalFunc) gtk_notebook_next_page,
3435 GTK_OBJECT (notebook));
3436 gtk_table_attach_defaults(GTK_TABLE(table), button, 1,2,1,2);
3437 gtk_widget_show(button);
3439 button = gtk_button_new_with_label ("prev page");
3440 gtk_signal_connect_object (GTK_OBJECT (button), "clicked",
3441 (GtkSignalFunc) gtk_notebook_prev_page,
3442 GTK_OBJECT (notebook));
3443 gtk_table_attach_defaults(GTK_TABLE(table), button, 2,3,1,2);
3444 gtk_widget_show(button);
3446 button = gtk_button_new_with_label ("tab position");
3447 gtk_signal_connect_object (GTK_OBJECT (button), "clicked",
3448 (GtkSignalFunc) rotate_book, GTK_OBJECT(notebook));
3449 gtk_table_attach_defaults(GTK_TABLE(table), button, 3,4,1,2);
3450 gtk_widget_show(button);
3452 button = gtk_button_new_with_label ("tabs/border on/off");
3453 gtk_signal_connect_object (GTK_OBJECT (button), "clicked",
3454 (GtkSignalFunc) tabsborder_book,
3455 GTK_OBJECT (notebook));
3456 gtk_table_attach_defaults(GTK_TABLE(table), button, 4,5,1,2);
3457 gtk_widget_show(button);
3459 button = gtk_button_new_with_label ("remove page");
3460 gtk_signal_connect_object (GTK_OBJECT (button), "clicked",
3461 (GtkSignalFunc) remove_book,
3462 GTK_OBJECT(notebook));
3463 gtk_table_attach_defaults(GTK_TABLE(table), button, 5,6,1,2);
3464 gtk_widget_show(button);
3466 gtk_widget_show(table);
3467 gtk_widget_show(window);
3475 Hopefully this helps you on your way with creating notebooks for your
3478 <!-- ----------------------------------------------------------------- -->
3479 <sect1> Scrolled Windows
3481 Scrolled windows are used to create a scrollable area inside a real window.
3482 You may insert any types of widgets to these scrolled windows, and they will
3483 all be accessable regardless of the size by using the scrollbars.
3485 The following function is used to create a new scolled window.
3488 GtkWidget* gtk_scrolled_window_new (GtkAdjustment *hadjustment,
3489 GtkAdjustment *vadjustment);
3492 Where the first argument is the adjustment for the horizontal
3493 direction, and the second, the adjustment for the vertical direction.
3494 These are almost always set to NULL.
3497 void gtk_scrolled_window_set_policy (GtkScrolledWindow *scrolled_window,
3498 GtkPolicyType hscrollbar_policy,
3499 GtkPolicyType vscrollbar_policy);
3502 This sets the policy to be used with respect to the scrollbars.
3503 The first arguement is the scrolled window you wish to change. The second
3504 sets the policiy for the horizontal scrollbar, and the third,
3505 the vertical scrollbar.
3507 The policy may be one of GTK_POLICY AUTOMATIC, or GTK_POLICY_ALWAYS.
3508 GTK_POLICY_AUTOMATIC will automatically decide whether you need
3509 scrollbars, wheras GTK_POLICY_ALWAYS will always leave the scrollbars
3512 Here is a simple example that packs 100 toggle buttons into a scrolled window.
3513 I've only commented on the parts that may be new to you.
3518 #include <gtk/gtk.h>
3520 void destroy(GtkWidget *widget, gpointer *data)
3525 int main (int argc, char *argv[])
3527 static GtkWidget *window;
3528 GtkWidget *scrolled_window;
3534 gtk_init (&argc, &argv);
3536 /* Create a new dialog window for the scrolled window to be
3537 * packed into. A dialog is just like a normal window except it has a
3538 * vbox and a horizontal seperator packed into it. It's just a shortcut
3539 * for creating dialogs */
3540 window = gtk_dialog_new ();
3541 gtk_signal_connect (GTK_OBJECT (window), "destroy",
3542 (GtkSignalFunc) destroy, NULL);
3543 gtk_window_set_title (GTK_WINDOW (window), "dialog");
3544 gtk_container_border_width (GTK_CONTAINER (window), 0);
3545 gtk_widget_set_usize(window, 300, 300);
3547 /* create a new scrolled window. */
3548 scrolled_window = gtk_scrolled_window_new (NULL, NULL);
3550 gtk_container_border_width (GTK_CONTAINER (scrolled_window), 10);
3552 /* the policy is one of GTK_POLICY AUTOMATIC, or GTK_POLICY_ALWAYS.
3553 * GTK_POLICY_AUTOMATIC will automatically decide whether you need
3554 * scrollbars, wheras GTK_POLICY_ALWAYS will always leave the scrollbars
3555 * there. The first one is the horizontal scrollbar, the second,
3557 gtk_scrolled_window_set_policy (GTK_SCROLLED_WINDOW (scrolled_window),
3558 GTK_POLICY_AUTOMATIC, GTK_POLICY_ALWAYS);
3559 /* The dialog window is created with a vbox packed into it. */
3560 gtk_box_pack_start (GTK_BOX (GTK_DIALOG(window)->vbox), scrolled_window,
3562 gtk_widget_show (scrolled_window);
3564 /* create a table of 10 by 10 squares. */
3565 table = gtk_table_new (10, 10, FALSE);
3567 /* set the spacing to 10 on x and 10 on y */
3568 gtk_table_set_row_spacings (GTK_TABLE (table), 10);
3569 gtk_table_set_col_spacings (GTK_TABLE (table), 10);
3571 /* pack the table into the scrolled window */
3572 gtk_container_add (GTK_CONTAINER (scrolled_window), table);
3573 gtk_widget_show (table);
3575 /* this simply creates a grid of toggle buttons on the table
3576 * to demonstrate the scrolled window. */
3577 for (i = 0; i < 10; i++)
3578 for (j = 0; j < 10; j++) {
3579 sprintf (buffer, "button (%d,%d)\n", i, j);
3580 button = gtk_toggle_button_new_with_label (buffer);
3581 gtk_table_attach_defaults (GTK_TABLE (table), button,
3583 gtk_widget_show (button);
3586 /* Add a "close" button to the bottom of the dialog */
3587 button = gtk_button_new_with_label ("close");
3588 gtk_signal_connect_object (GTK_OBJECT (button), "clicked",
3589 (GtkSignalFunc) gtk_widget_destroy,
3590 GTK_OBJECT (window));
3592 /* this makes it so the button is the default. */
3594 GTK_WIDGET_SET_FLAGS (button, GTK_CAN_DEFAULT);
3595 gtk_box_pack_start (GTK_BOX (GTK_DIALOG (window)->action_area), button, TRUE, TRUE, 0);
3597 /* This grabs this button to be the default button. Simply hitting
3598 * the "Enter" key will cause this button to activate. */
3599 gtk_widget_grab_default (button);
3600 gtk_widget_show (button);
3602 gtk_widget_show (window);
3610 Try playing with resizing the window. You'll notice how the scrollbars
3611 react. You may also wish to use the gtk_widget_set_usize() call to set the default
3612 size of the window or other widgets.
3614 <!-- ***************************************************************** -->
3616 <!-- ***************************************************************** -->
3619 The GtkList widget is designed to act as a vertical container for widgets
3620 that should be of the type GtkListItem.
3622 A GtkList widget has its own window to receive events and it's own
3623 background color which is usualy white. As it is directly derived from a
3624 GtkContainer it can be treated as such by using the GTK_CONTAINER(List)
3625 macro, see the GtkContainer widget for more on this.
3626 One should already be familar whith the usage of a GList and its
3627 related functions g_list_*() to be able to use the GtkList widget to
3630 There is one field inside the structure definition of the GtkList widget
3631 that will be of greater interest to us, this is:
3638 guint selection_mode;
3643 The selection field of a GtkList points to a linked list of all items
3644 that are cureently selected, or `NULL' if the selection is empty.
3645 So to learn about the current selection we read the GTK_LIST()->selection
3646 field, but do not modify it since the internal fields are maintained by
3647 the gtk_list_*() functions.
3649 The selection_mode of the GtkList determines the selection facilities
3650 of a GtkList and therefore the contents of the GTK_LIST()->selection
3653 The selection_mode may be one of the following:
3655 <item> GTK_SELECTION_SINGLE - The selection is either `NULL'
3656 or contains a GList* pointer
3657 for a single selected item.
3659 <item> GTK_SELECTION_BROWSE - The selection is `NULL' if the list
3660 contains no widgets or insensitive
3661 ones only, otherwise it contains
3662 a GList pointer for one GList
3663 structure, and therefore exactly
3666 <item> GTK_SELECTION_MULTIPLE - The selection is `NULL' if no list
3667 items are selected or a GList pointer
3668 for the first selected item. That
3669 in turn points to a GList structure
3670 for the second selected item and so
3673 <item> GTK_SELECTION_EXTENDED - The selection is always `NULL'.
3676 The default is GTK_SELECTION_MULTIPLE.
3678 <!-- ----------------------------------------------------------------- -->
3682 void selection_changed (GtkList *LIST)
3685 This signal will be invoked whenever a the selection field
3686 of a GtkList has changed. This happens when a child of
3687 the GtkList got selected or unselected.
3690 void select_child (GtkList *LIST, GtkWidget *CHILD)
3693 This signal is invoked when a child of the GtkList is about
3694 to get selected. This happens mainly on calls to
3695 gtk_list_select_item(), gtk_list_select_child(), button presses
3696 and sometimes indirectly triggered on some else occasions where
3697 children get added to or removed from the GtkList.
3700 void unselect_child (GtkList *LIST, GtkWidget *CHILD)
3703 This signal is invoked when a child of the GtkList is about
3704 to get unselected. This happens mainly on calls to
3705 gtk_list_unselect_item(), gtk_list_unselect_child(), button presses
3706 and sometimes indirectly triggered on some else occasions where
3707 children get added to or removed from the GtkList.
3709 <!-- ----------------------------------------------------------------- -->
3713 guint gtk_list_get_type (void)
3716 Returns the `GtkList' type identifier.
3719 GtkWidget* gtk_list_new (void)
3722 Create a new `GtkList' object. The new widget is
3723 returned as a pointer to a `GtkWidget' object.
3724 `NULL' is returned on failure.
3727 void gtk_list_insert_items (GtkList *LIST, GList *ITEMS, gint POSITION)
3730 Insert list items into the LIST, starting at POSITION.
3731 ITEMS is a doubly linked list where each nodes data
3732 pointer is expected to point to a newly created GtkListItem.
3733 The GList nodes of ITEMS are taken over by the LIST.
3736 void gtk_list_append_items (GtkList *LIST, GList *ITEMS)
3739 Insert list items just like gtk_list_insert_items() at the end
3740 of the LIST. The GList nodes of ITEMS are taken over by the LIST.
3743 void gtk_list_prepend_items (GtkList *LIST, GList *ITEMS)
3746 Insert list items just like gtk_list_insert_items() at the very
3747 beginning of the LIST. The GList nodes of ITEMS are taken over
3751 void gtk_list_remove_items (GtkList *LIST, GList *ITEMS)
3754 Remove list items from the LIST. ITEMS is a doubly linked
3755 list where each nodes data pointer is expected to point to a
3756 direct child of LIST. It is the callers responsibility to make a
3757 call to g_list_free(ITEMS) afterwards. Also the caller has to
3758 destroy the list items himself.
3761 void gtk_list_clear_items (GtkList *LIST, gint START, gint END)
3764 Remove and destroy list items from the LIST. a widget is affected if
3765 its current position within LIST is in the range specified by START
3769 void gtk_list_select_item (GtkList *LIST, gint ITEM)
3772 Invoke the select_child signal for a list item
3773 specified through its current position within LIST.
3776 void gtk_list_unselect_item (GtkList *LIST, gint ITEM)
3779 Invoke the unselect_child signal for a list item
3780 specified through its current position within LIST.
3783 void gtk_list_select_child (GtkList *LIST, GtkWidget *CHILD)
3786 Invoke the select_child signal for the specified CHILD.
3789 void gtk_list_unselect_child (GtkList *LIST, GtkWidget *CHILD)
3792 Invoke the unselect_child signal for the specified CHILD.
3795 gint gtk_list_child_position (GtkList *LIST, GtkWidget *CHILD)
3798 Return the position of CHILD within LIST. `-1' is returned on failure.
3801 void gtk_list_set_selection_mode (GtkList *LIST, GtkSelectionMode MODE)
3804 Set LIST to the selection mode MODE wich can be of GTK_SELECTION_SINGLE,
3805 GTK_SELECTION_BROWSE, GTK_SELECTION_MULTIPLE or GTK_SELECTION_EXTENDED.
3808 GtkList* GTK_LIST (gpointer OBJ)
3811 Cast a generic pointer to `GtkList*'. *Note Standard Macros::, for
3815 GtkListClass* GTK_LIST_CLASS (gpointer CLASS)
3818 Cast a generic pointer to `GtkListClass*'. *Note Standard Macros::,
3822 gint GTK_IS_LIST (gpointer OBJ)
3825 Determine if a generic pointer refers to a `GtkList' object. *Note
3826 Standard Macros::, for more info.
3828 <!-- ----------------------------------------------------------------- -->
3831 Following is an example program that will print out the changes
3832 of the selection of a GtkList, and lets you "arrest" list items
3833 into a prison by selecting them with the rightmost mouse button:
3838 /* include the gtk+ header files
3839 * include stdio.h, we need that for the printf() function
3841 #include <gtk/gtk.h>
3844 /* this is our data identification string to store
3845 * data in list items
3847 const gchar *list_item_data_key="list_item_data";
3850 /* prototypes for signal handler that we are going to connect
3851 * to the GtkList widget
3853 static void sigh_print_selection (GtkWidget *gtklist,
3854 gpointer func_data);
3855 static void sigh_button_event (GtkWidget *gtklist,
3856 GdkEventButton *event,
3860 /* main function to set up the user interface */
3862 gint main (int argc, gchar *argv[])
3864 GtkWidget *separator;
3867 GtkWidget *scrolled_window;
3871 GtkWidget *list_item;
3877 /* initialize gtk+ (and subsequently gdk) */
3879 gtk_init(&argc, &argv);
3882 /* create a window to put all the widgets in
3883 * connect gtk_main_quit() to the "destroy" event of
3884 * the window to handle window manager close-window-events
3886 window=gtk_window_new(GTK_WINDOW_TOPLEVEL);
3887 gtk_window_set_title(GTK_WINDOW(window), "GtkList Example");
3888 gtk_signal_connect(GTK_OBJECT(window),
3890 GTK_SIGNAL_FUNC(gtk_main_quit),
3894 /* inside the window we need a box to arrange the widgets
3896 vbox=gtk_vbox_new(FALSE, 5);
3897 gtk_container_border_width(GTK_CONTAINER(vbox), 5);
3898 gtk_container_add(GTK_CONTAINER(window), vbox);
3899 gtk_widget_show(vbox);
3901 /* this is the scolled window to put the GtkList widget inside */
3902 scrolled_window=gtk_scrolled_window_new(NULL, NULL);
3903 gtk_widget_set_usize(scrolled_window, 250, 150);
3904 gtk_container_add(GTK_CONTAINER(vbox), scrolled_window);
3905 gtk_widget_show(scrolled_window);
3907 /* create the GtkList widget
3908 * connect the sigh_print_selection() signal handler
3909 * function to the "selection_changed" signal of the GtkList
3910 * to print out the selected items each time the selection
3912 gtklist=gtk_list_new();
3913 gtk_container_add(GTK_CONTAINER(scrolled_window), gtklist);
3914 gtk_widget_show(gtklist);
3915 gtk_signal_connect(GTK_OBJECT(gtklist),
3916 "selection_changed",
3917 GTK_SIGNAL_FUNC(sigh_print_selection),
3920 /* we create a "Prison" to put a list item in ;)
3922 frame=gtk_frame_new("Prison");
3923 gtk_widget_set_usize(frame, 200, 50);
3924 gtk_container_border_width(GTK_CONTAINER(frame), 5);
3925 gtk_frame_set_shadow_type(GTK_FRAME(frame), GTK_SHADOW_OUT);
3926 gtk_container_add(GTK_CONTAINER(vbox), frame);
3927 gtk_widget_show(frame);
3929 /* connect the sigh_button_event() signal handler to the GtkList
3930 * wich will handle the "arresting" of list items
3932 gtk_signal_connect(GTK_OBJECT(gtklist),
3933 "button_release_event",
3934 GTK_SIGNAL_FUNC(sigh_button_event),
3937 /* create a separator
3939 separator=gtk_hseparator_new();
3940 gtk_container_add(GTK_CONTAINER(vbox), separator);
3941 gtk_widget_show(separator);
3943 /* finaly create a button and connect it´s "clicked" signal
3944 * to the destroyment of the window
3946 button=gtk_button_new_with_label("Close");
3947 gtk_container_add(GTK_CONTAINER(vbox), button);
3948 gtk_widget_show(button);
3949 gtk_signal_connect_object(GTK_OBJECT(button),
3951 GTK_SIGNAL_FUNC(gtk_widget_destroy),
3952 GTK_OBJECT(window));
3955 /* now we create 5 list items, each having it´s own
3956 * label and add them to the GtkList using gtk_container_add()
3957 * also we query the text string from the label and
3958 * associate it with the list_item_data_key for each list item
3960 for (i=0; i<5; i++) {
3964 sprintf(buffer, "ListItemContainer with Label #%d", i);
3965 label=gtk_label_new(buffer);
3966 list_item=gtk_list_item_new();
3967 gtk_container_add(GTK_CONTAINER(list_item), label);
3968 gtk_widget_show(label);
3969 gtk_container_add(GTK_CONTAINER(gtklist), list_item);
3970 gtk_widget_show(list_item);
3971 gtk_label_get(GTK_LABEL(label), &string);
3972 gtk_object_set_data(GTK_OBJECT(list_item),
3976 /* here, we are creating another 5 labels, this time
3977 * we use gtk_list_item_new_with_label() for the creation
3978 * we can´t query the text string from the label because
3979 * we don´t have the labels pointer and therefore
3980 * we just associate the list_item_data_key of each
3981 * list item with the same text string
3982 * for adding of the list items we put them all into a doubly
3983 * linked list (GList), and then add them by a single call to
3984 * gtk_list_append_items()
3985 * because we use g_list_prepend() to put the items into the
3986 * doubly linked list, their order will be descending (instead
3987 * of ascending when using g_list_append())
3991 sprintf(buffer, "List Item with Label %d", i);
3992 list_item=gtk_list_item_new_with_label(buffer);
3993 dlist=g_list_prepend(dlist, list_item);
3994 gtk_widget_show(list_item);
3995 gtk_object_set_data(GTK_OBJECT(list_item),
3997 "ListItem with integrated Label");
3999 gtk_list_append_items(GTK_LIST(gtklist), dlist);
4001 /* finaly we want to see the window, don´t we? ;)
4003 gtk_widget_show(window);
4005 /* fire up the main event loop of gtk
4009 /* we get here after gtk_main_quit() has been called which
4010 * happens if the main window gets destroyed
4015 /* this is the signal handler that got connected to button
4016 * press/release events of the GtkList
4019 sigh_button_event (GtkWidget *gtklist,
4020 GdkEventButton *event,
4023 /* we only do something if the third (rightmost mouse button
4026 if (event->type==GDK_BUTTON_RELEASE &&
4028 GList *dlist, *free_list;
4029 GtkWidget *new_prisoner;
4031 /* fetch the currently selected list item which
4032 * will be our next prisoner ;)
4034 dlist=GTK_LIST(gtklist)->selection;
4036 new_prisoner=GTK_WIDGET(dlist->data);
4040 /* look for already prisoned list items, we
4041 * will put them back into the list
4042 * remember to free the doubly linked list that
4043 * gtk_container_children() returns
4045 dlist=gtk_container_children(GTK_CONTAINER(frame));
4048 GtkWidget *list_item;
4050 list_item=dlist->data;
4052 gtk_widget_reparent(list_item, gtklist);
4056 g_list_free(free_list);
4058 /* if we have a new prisoner, remove him from the
4059 * GtkList and put him into the frame "Prison"
4060 * we need to unselect the item before
4065 static_dlist.data=new_prisoner;
4066 static_dlist.next=NULL;
4067 static_dlist.prev=NULL;
4069 gtk_list_unselect_child(GTK_LIST(gtklist),
4071 gtk_widget_reparent(new_prisoner, frame);
4076 /* this is the signal handler that gets called if GtkList
4077 * emits the "selection_changed" signal
4080 sigh_print_selection (GtkWidget *gtklist,
4085 /* fetch the doubly linked list of selected items
4086 * of the GtkList, remember to treat this as read-only!
4088 dlist=GTK_LIST(gtklist)->selection;
4090 /* if there are no selected items there is nothing more
4091 * to do than just telling the user so
4094 g_print("Selection cleared\n");
4097 /* ok, we got a selection and so we print it
4099 g_print("The selection is a ");
4101 /* get the list item from the doubly linked list
4102 * and then query the data associated with list_item_data_key
4103 * we then just print it
4106 GtkObject *list_item;
4107 gchar *item_data_string;
4109 list_item=GTK_OBJECT(dlist->data);
4110 item_data_string=gtk_object_get_data(list_item,
4111 list_item_data_key);
4112 g_print("%s ", item_data_string);
4120 <!-- ----------------------------------------------------------------- -->
4121 <sect1> List Item Widget
4123 The GtkListItem widget is designed to act as a container holding up
4124 to one child, providing functions for selection/deselection just like
4125 the GtkList widget requires them for its children.
4127 A GtkListItem has its own window to receive events and has its own
4128 background color which is usualy white.
4130 As it is directly derived from a
4131 GtkItem it can be treated as such by using the GTK_ITEM(ListItem)
4132 macro, see the GtkItem widget for more on this.
4133 Usualy a GtkListItem just holds a label to identify e.g. a filename
4134 within a GtkList -- therefore the convenient function
4135 gtk_list_item_new_with_label() is provided. The same effect can be
4136 achieved by creating a GtkLabel on its own, setting its alignment
4137 to xalign=0 and yalign=0.5 with a subsequent container addition
4140 As one is not forced to add a GtkLabel to a GtkListItem, you could
4141 also add a GtkVBox or a GtkArrow etc. to the GtkListItem.
4143 <!-- ----------------------------------------------------------------- -->
4146 A GtkListItem does not create new signals on its own, but inherits
4147 the signals of a GtkItem. *Note GtkItem::, for more info.
4149 <!-- ----------------------------------------------------------------- -->
4154 guint gtk_list_item_get_type (void)
4157 Returns the `GtkListItem' type identifier.
4160 GtkWidget* gtk_list_item_new (void)
4163 Create a new `GtkListItem' object. The new widget is
4164 returned as a pointer to a `GtkWidget' object.
4165 `NULL' is returned on failure.
4168 GtkWidget* gtk_list_item_new_with_label (gchar *LABEL)
4171 Create a new `GtkListItem' object, having a single GtkLabel as
4172 the sole child. The new widget is returned as a pointer to a
4174 `NULL' is returned on failure.
4177 void gtk_list_item_select (GtkListItem *LIST_ITEM)
4180 This function is basicaly a wrapper around a call to
4181 gtk_item_select (GTK_ITEM (list_item)) which will emit the
4183 *Note GtkItem::, for more info.
4186 void gtk_list_item_deselect (GtkListItem *LIST_ITEM)
4189 This function is basicaly a wrapper around a call to
4190 gtk_item_deselect (GTK_ITEM (list_item)) which will emit the
4192 *Note GtkItem::, for more info.
4195 GtkListItem* GTK_LIST_ITEM (gpointer OBJ)
4198 Cast a generic pointer to `GtkListItem*'. *Note Standard Macros::,
4202 GtkListItemClass* GTK_LIST_ITEM_CLASS (gpointer CLASS)
4205 Cast a generic pointer to `GtkListItemClass*'. *Note Standard
4206 Macros::, for more info.
4209 gint GTK_IS_LIST_ITEM (gpointer OBJ)
4212 Determine if a generic pointer refers to a `GtkListItem' object.
4213 *Note Standard Macros::, for more info.
4215 <!-- ----------------------------------------------------------------- -->
4218 Please see the GtkList example on this, which covers the usage of a
4219 GtkListItem as well.
4221 <!-- ***************************************************************** -->
4222 <sect> File Selections
4223 <!-- ***************************************************************** -->
4225 The file selection widget is a quick and simple way to display a File
4226 dialog box. It comes complete with Ok, Cancel, and Help buttons, a great way
4227 to cut down on programming time.
4229 To create a new file selection box use:
4232 GtkWidget* gtk_file_selection_new (gchar *title);
4235 To set the filename, for example to bring up a specific directory, or
4236 give a default filename, use this function:
4239 void gtk_file_selection_set_filename (GtkFileSelection *filesel, gchar *filename);
4242 To grab the text that the user has entered or clicked on, use this
4246 gchar* gtk_file_selection_get_filename (GtkFileSelection *filesel);
4249 There are also pointers to the widgets contained within the file
4250 selection widget. These are:
4255 <item>selection_entry
4256 <item>selection_text
4263 Most likely you will want to use the ok_button, cancel_button, and
4264 help_button pointers in signaling their use.
4266 Included here is an example stolen from testgtk.c, modified to run
4267 on it's own. As you will see, there is nothing much to creating a file
4268 selection widget. While, in this example, the Help button appears on the
4269 screen, it does nothing as there is not a signal attached to it.
4274 #include <gtk/gtk.h>
4276 /* Get the selected filename and print it to the console */
4277 void file_ok_sel (GtkWidget *w, GtkFileSelection *fs)
4279 g_print ("%s\n", gtk_file_selection_get_filename (GTK_FILE_SELECTION (fs)));
4282 void destroy (GtkWidget *widget, gpointer *data)
4287 int main (int argc, char *argv[])
4291 gtk_init (&argc, &argv);
4293 /* Create a new file selection widget */
4294 filew = gtk_file_selection_new ("File selection");
4296 gtk_signal_connect (GTK_OBJECT (filew), "destroy",
4297 (GtkSignalFunc) destroy, &filew);
4298 /* Connect the ok_button to file_ok_sel function */
4299 gtk_signal_connect (GTK_OBJECT (GTK_FILE_SELECTION (filew)->ok_button),
4300 "clicked", (GtkSignalFunc) file_ok_sel, filew );
4302 /* Connect the cancel_button to destroy the widget */
4303 gtk_signal_connect_object (GTK_OBJECT (GTK_FILE_SELECTION (filew)->cancel_button),
4304 "clicked", (GtkSignalFunc) gtk_widget_destroy,
4305 GTK_OBJECT (filew));
4307 /* Lets set the filename, as if this were a save dialog, and we are giving
4308 a default filename */
4309 gtk_file_selection_set_filename (GTK_FILE_SELECTION(filew),
4312 gtk_widget_show(filew);
4318 <!-- ***************************************************************** -->
4320 <!-- ***************************************************************** -->
4323 There are two ways to create menus, there's the easy way, and there's the
4324 hard way. Both have their uses, but you can usually use the menufactory
4325 (the easy way). The "hard" way is to create all the menus using the calls
4326 directly. The easy way is to use the gtk_menu_factory calls. This is
4327 much simpler, but there are advantages and disadvantages to each approach.
4329 The menufactory is much easier to use, and to add new menus to, although
4330 writing a few wrapper functions to create menus using the manual method
4331 could go a long way towards usability. With the menufactory, it is not
4332 possible to add images or the character '/' to the menus.
4334 <!-- ----------------------------------------------------------------- -->
4335 <sect1>Manual Menu Creation
4337 In the true tradition of teaching, we'll show you the hard
4338 way first. <tt>:)</>
4340 There are three widgets that go into making a menubar and submenus:
4342 <item>a menu item, which is what the user wants to select, e.g. 'Save'
4343 <item>a menu, which acts as a container for the menu items, and
4344 <item>a menubar, which is a container for each of the individual menus,
4347 This is slightly complicated by the fact that menu item widgets are used for two different things. They are
4348 both the widets that are packed into the menu, and the widget that is packed into the menubar, which,
4349 when selected, activiates the menu.
4351 Let's look at the functions that are used to create menus and menubars.
4352 This first function is used to create a new menubar.
4355 GtkWidget *gtk_menu_bar_new(void);
4358 This rather self explanatory function creates a new menubar. You use
4359 gtk_container_add to pack this into a window, or the box_pack functions to
4360 pack it into a box - the same as buttons.
4363 GtkWidget *gtk_menu_new();
4366 This function returns a pointer to a new menu, it is never actually shown
4367 (with gtk_widget_show), it is just a container for the menu items. Hopefully this will
4368 become more clear when you look at the example below.
4370 The next two calls are used to create menu items that are packed into
4371 the menu (and menubar).
4374 GtkWidget *gtk_menu_item_new();
4380 GtkWidget *gtk_menu_item_new_with_label(const char *label);
4383 These calls are used to create the menu items that are to be displayed.
4384 Remember to differentiate between a "menu" as created with gtk_menu_new
4385 and a "menu item" as created by the gtk_menu_item_new functions. The
4386 menu item will be an actual button with an associated action,
4387 whereas a menu will be a container holding menu items.
4389 The gtk_menu_new_with_label and gtk_menu_new functions are just as you'd expect after
4390 reading about the buttons. One creates a new menu item with a label
4391 already packed into it, and the other just creates a blank menu item.
4393 Once you've created a menu item you have to put it into a menu. This is done using the function
4394 gtk_menu_append. In order to capture when the item is selected by the user, we need to connect
4395 to the <tt/activate/ signal in the usual way.
4396 So, if we wanted to create a standard <tt/File/ menu, with the options <tt/Open/,
4397 <tt/Save/ and <tt/Quit/ the code would look something like
4400 file_menu = gtk_menu_new(); /* Don't need to show menus */
4402 /* Create the menu items */
4403 open_item = gtk_menu_item_new_with_label("Open");
4404 save_item = gtk_menu_item_new_with_label("Save");
4405 quit_item = gtk_menu_item_new_with_label("Quit");
4407 /* Add them to the menu */
4408 gtk_menu_append( GTK_MENU(file_menu), open_item);
4409 gtk_menu_append( GTK_MENU(file_menu), save_item);
4410 gtk_menu_append( GTK_MENU(file_menu), quit_item);
4412 /* Attach the callback functions to the activate signal */
4413 gtk_signal_connect_object( GTK_OBJECT(open_items), "activate",
4414 GTK_SIGNAL_FUNC(menuitem_response), (gpointer) "file.open");
4415 gtk_signal_connect_object( GTK_OBJECT(save_items), "activate",
4416 GTK_SIGNAL_FUNC(menuitem_response), (gpointer) "file.save");
4418 /* We can attach the Quit menu item to our exit function */
4419 gtk_signal_connect_object( GTK_OBJECT(quit_items), "activate",
4420 GTK_SIGNAL_FUNC(destroy), (gpointer) "file.quit");
4422 /* We do need to show menu items */
4423 gtk_widget_show( open_item );
4424 gtk_widget_show( save_item );
4425 gtk_widget_show( quit_item );
4428 At this point we have our menu. Now we need to create a menubar and a menu item for the <tt/File/ entry,
4429 to which we add our menu. The code looks like this
4432 menu_bar = gtk_menu_bar_new();
4433 gtk_container_add( GTK_CONTAINER(window), menu_bar);
4434 gtk_widget_show( menu_bar );
4436 file_item = gtk_menu_item_new_with_label("File");
4437 gtk_widget_show(file_item);
4440 Now we need to associate the menu with <tt/file_item/. This is done with the function
4443 void gtk_menu_item_set_submenu( GtkMenuItem *menu_item,
4444 GtkWidget *submenu);
4447 So, our example would continue with
4450 gtk_menu_item_set_submenu( GTK_MENU_ITEM(file_item), file_menu);
4453 All that is left to do is to add the menu to the menubar, which is accomplished using the function
4456 void gtk_menu_bar_append( GtkMenuBar *menu_bar, GtkWidget *menu_item);
4459 which in our case looks like this:
4462 gtk_menu_bar_append( menu_bar, file_item );
4465 If we wanted the menu right justified on the menubar, such as help menus often are, we can
4466 use the following function (again on <tt/file_item/ in the current example) before attaching
4469 void gtk_menu_item_right_justify (GtkMenuItem *menu_item);
4472 Here is a summary of the steps needed to create a menu bar with menus attached:
4474 <item> Create a new menu using gtk_menu_new()
4475 <item> Use multiple calls to gtk_menu_item_new() for each item you wish to have on
4476 your menu. And use gtk_menu_append() to put each of these new items on
4478 <item> Create a menu item using gtk_menu_item_new(). This will be the root of
4479 the menu, the text appearing here will be on the menubar itself.
4480 <item> Use gtk_menu_item_set_submenu() to attach the menu to
4481 the root menu item (The one created in the above step).
4482 <item> Create a new menubar using gtk_menu_bar_new. This step only needs
4483 to be done once when creating a series of menus on one menu bar.
4484 <item> Use gtk_menu_bar_append to put the root menu onto the menubar.
4487 Creating a popup menu is nearly the same. The difference is that the
4488 menu is not posted `automatically' by a menubar, but explicitly
4489 by calling the function gtk_menu_popup() from a button-press event, for example.
4492 <item>Create an event handling function. It needs to have the prototype
4494 static gint handler(GtkWidget *widget, GdkEvent *event);
4496 and it will use the event to find out where to pop up the menu.
4497 <item>In the event handler, if event is a mouse button press, treat
4498 <tt>event</tt> as a button event (which it is) and use it as
4499 shown in the sample code to pass information to gtk_menu_popup().
4500 <item>Bind that event handler to a widget with
4502 gtk_signal_connect_object(GTK_OBJECT(widget), "event",
4503 GTK_SIGNAL_FUNC (handler), GTK_OBJECT(menu));
4505 where <tt>widget</tt> is the widget you are binding to, <tt>handler</tt>
4506 is the handling function, and <tt>menu</tt> is a menu created with
4507 gtk_menu_new(). This can be a menu which is also posted by a menu bar,
4508 as shown in the sample code.
4511 <!-- ----------------------------------------------------------------- -->
4512 <sect1>Manual Menu Example
4514 That should about do it. Let's take a look at an example to help clarify.
4519 #include <gtk/gtk.h>
4521 static gint button_press (GtkWidget *, GdkEvent *);
4522 static void menuitem_response (gchar *);
4524 int main (int argc, char *argv[])
4529 GtkWidget *menu_bar;
4530 GtkWidget *root_menu;
4531 GtkWidget *menu_items;
4537 gtk_init (&argc, &argv);
4539 /* create a new window */
4540 window = gtk_window_new(GTK_WINDOW_TOPLEVEL);
4541 gtk_widget_set_usize( GTK_WIDGET (window), 200, 100);
4542 gtk_window_set_title(GTK_WINDOW (window), "GTK Menu Test");
4543 gtk_signal_connect(GTK_OBJECT (window), "delete_event",
4544 (GtkSignalFunc) gtk_exit, NULL);
4546 /* Init the menu-widget, and remember -- never
4547 * gtk_show_widget() the menu widget!!
4548 * This is the menu that holds the menu items, the one that
4549 * will pop up when you click on the "Root Menu" in the app */
4550 menu = gtk_menu_new();
4552 /* Next we make a little loop that makes three menu-entries for "test-menu".
4553 * Notice the call to gtk_menu_append. Here we are adding a list of
4554 * menu items to our menu. Normally, we'd also catch the "clicked"
4555 * signal on each of the menu items and setup a callback for it,
4556 * but it's omitted here to save space. */
4558 for(i = 0; i < 3; i++)
4560 /* Copy the names to the buf. */
4561 sprintf(buf, "Test-undermenu - %d", i);
4563 /* Create a new menu-item with a name... */
4564 menu_items = gtk_menu_item_new_with_label(buf);
4566 /* ...and add it to the menu. */
4567 gtk_menu_append(GTK_MENU (menu), menu_items);
4569 /* Do something interesting when the menuitem is selected */
4570 gtk_signal_connect_object(GTK_OBJECT(menu_items), "activate",
4571 GTK_SIGNAL_FUNC(menuitem_response), (gpointer) g_strdup(buf));
4573 /* Show the widget */
4574 gtk_widget_show(menu_items);
4577 /* This is the root menu, and will be the label
4578 * displayed on the menu bar. There won't be a signal handler attached,
4579 * as it only pops up the rest of the menu when pressed. */
4580 root_menu = gtk_menu_item_new_with_label("Root Menu");
4582 gtk_widget_show(root_menu);
4584 /* Now we specify that we want our newly created "menu" to be the menu
4585 * for the "root menu" */
4586 gtk_menu_item_set_submenu(GTK_MENU_ITEM (root_menu), menu);
4588 /* A vbox to put a menu and a button in: */
4589 vbox = gtk_vbox_new(FALSE, 0);
4590 gtk_container_add(GTK_CONTAINER(window), vbox);
4591 gtk_widget_show(vbox);
4593 /* Create a menu-bar to hold the menus and add it to our main window */
4594 menu_bar = gtk_menu_bar_new();
4595 gtk_box_pack_start(GTK_BOX(vbox), menu_bar, FALSE, FALSE, 2);
4596 gtk_widget_show(menu_bar);
4598 /* Create a button to which to attach menu as a popup */
4599 button = gtk_button_new_with_label("press me");
4600 gtk_signal_connect_object(GTK_OBJECT(button), "event",
4601 GTK_SIGNAL_FUNC (button_press), GTK_OBJECT(menu));
4602 gtk_box_pack_end(GTK_BOX(vbox), button, TRUE, TRUE, 2);
4603 gtk_widget_show(button);
4605 /* And finally we append the menu-item to the menu-bar -- this is the
4606 * "root" menu-item I have been raving about =) */
4607 gtk_menu_bar_append(GTK_MENU_BAR (menu_bar), root_menu);
4609 /* always display the window as the last step so it all splashes on
4610 * the screen at once. */
4611 gtk_widget_show(window);
4620 /* Respond to a button-press by posting a menu passed in as widget.
4622 * Note that the "widget" argument is the menu being posted, NOT
4623 * the button that was pressed.
4626 static gint button_press (GtkWidget *widget, GdkEvent *event)
4629 if (event->type == GDK_BUTTON_PRESS) {
4630 GdkEventButton *bevent = (GdkEventButton *) event;
4631 gtk_menu_popup (GTK_MENU(widget), NULL, NULL, NULL, NULL,
4632 bevent->button, bevent->time);
4633 /* Tell calling code that we have handled this event; the buck
4638 /* Tell calling code that we have not handled this event; pass it on. */
4643 /* Print a string when a menu item is selected */
4645 static void menuitem_response (gchar *string)
4647 printf("%s\n", string);
4651 You may also set a menu item to be insensitive and, using an accelerator
4652 table, bind keys to menu functions.
4654 <!-- ----------------------------------------------------------------- -->
4655 <sect1>Using GtkMenuFactory
4657 Now that we've shown you the hard way, here's how you do it using the
4658 gtk_menu_factory calls.
4660 <!-- ----------------------------------------------------------------- -->
4661 <sect1>Menu Factory Example
4663 Here is an example using the GTK menu factory. This is the first file,
4664 menufactory.h. We keep a separate menufactory.c and mfmain.c because of the global variables used
4665 in the menufactory.c file.
4670 #ifndef __MENUFACTORY_H__
4671 #define __MENUFACTORY_H__
4675 #endif /* __cplusplus */
4677 void get_main_menu (GtkWidget **menubar, GtkAcceleratorTable **table);
4678 void menus_create(GtkMenuEntry *entries, int nmenu_entries);
4682 #endif /* __cplusplus */
4684 #endif /* __MENUFACTORY_H__ */
4687 And here is the menufactory.c file.
4692 #include <gtk/gtk.h>
4693 #include <strings.h>
4698 static void menus_remove_accel(GtkWidget * widget, gchar * signal_name, gchar * path);
4699 static gint menus_install_accel(GtkWidget * widget, gchar * signal_name, gchar key, gchar modifiers, gchar * path);
4700 void menus_init(void);
4701 void menus_create(GtkMenuEntry * entries, int nmenu_entries);
4704 /* this is the GtkMenuEntry structure used to create new menus. The
4705 * first member is the menu definition string. The second, the
4706 * default accelerator key used to access this menu function with
4707 * the keyboard. The third is the callback function to call when
4708 * this menu item is selected (by the accelerator key, or with the
4709 * mouse.) The last member is the data to pass to your callback function.
4712 static GtkMenuEntry menu_items[] =
4714 {"<Main>/File/New", "<control>N", NULL, NULL},
4715 {"<Main>/File/Open", "<control>O", NULL, NULL},
4716 {"<Main>/File/Save", "<control>S", NULL, NULL},
4717 {"<Main>/File/Save as", NULL, NULL, NULL},
4718 {"<Main>/File/<separator>", NULL, NULL, NULL},
4719 {"<Main>/File/Quit", "<control>Q", file_quit_cmd_callback, "OK, I'll quit"},
4720 {"<Main>/Options/Test", NULL, NULL, NULL}
4723 /* calculate the number of menu_item's */
4724 static int nmenu_items = sizeof(menu_items) / sizeof(menu_items[0]);
4726 static int initialize = TRUE;
4727 static GtkMenuFactory *factory = NULL;
4728 static GtkMenuFactory *subfactory[1];
4729 static GHashTable *entry_ht = NULL;
4731 void get_main_menu(GtkWidget ** menubar, GtkAcceleratorTable ** table)
4737 *menubar = subfactory[0]->widget;
4739 *table = subfactory[0]->table;
4742 void menus_init(void)
4747 factory = gtk_menu_factory_new(GTK_MENU_FACTORY_MENU_BAR);
4748 subfactory[0] = gtk_menu_factory_new(GTK_MENU_FACTORY_MENU_BAR);
4750 gtk_menu_factory_add_subfactory(factory, subfactory[0], "<Main>");
4751 menus_create(menu_items, nmenu_items);
4755 void menus_create(GtkMenuEntry * entries, int nmenu_entries)
4764 for (i = 0; i < nmenu_entries; i++) {
4765 accelerator = g_hash_table_lookup(entry_ht, entries[i].path);
4767 if (accelerator[0] == '\0')
4768 entries[i].accelerator = NULL;
4770 entries[i].accelerator = accelerator;
4773 gtk_menu_factory_add_entries(factory, entries, nmenu_entries);
4775 for (i = 0; i < nmenu_entries; i++)
4776 if (entries[i].widget) {
4777 gtk_signal_connect(GTK_OBJECT(entries[i].widget), "install_accelerator",
4778 (GtkSignalFunc) menus_install_accel,
4780 gtk_signal_connect(GTK_OBJECT(entries[i].widget), "remove_accelerator",
4781 (GtkSignalFunc) menus_remove_accel,
4786 static gint menus_install_accel(GtkWidget * widget, gchar * signal_name, gchar key, gchar modifiers, gchar * path)
4792 if (modifiers & GDK_CONTROL_MASK)
4793 strcat(accel, "<control>");
4794 if (modifiers & GDK_SHIFT_MASK)
4795 strcat(accel, "<shift>");
4796 if (modifiers & GDK_MOD1_MASK)
4797 strcat(accel, "<alt>");
4804 t1 = g_hash_table_lookup(entry_ht, path);
4807 entry_ht = g_hash_table_new(g_str_hash, g_str_equal);
4809 g_hash_table_insert(entry_ht, path, g_strdup(accel));
4814 static void menus_remove_accel(GtkWidget * widget, gchar * signal_name, gchar * path)
4819 t = g_hash_table_lookup(entry_ht, path);
4822 g_hash_table_insert(entry_ht, path, g_strdup(""));
4826 void menus_set_sensitive(char *path, int sensitive)
4828 GtkMenuPath *menu_path;
4833 menu_path = gtk_menu_factory_find(factory, path);
4835 gtk_widget_set_sensitive(menu_path->widget, sensitive);
4837 g_warning("Unable to set sensitivity for menu which doesn't exist: %s", path);
4842 And here's the mfmain.h
4847 #ifndef __MFMAIN_H__
4848 #define __MFMAIN_H__
4853 #endif /* __cplusplus */
4855 void file_quit_cmd_callback(GtkWidget *widget, gpointer data);
4859 #endif /* __cplusplus */
4861 #endif /* __MFMAIN_H__ */
4869 #include <gtk/gtk.h>
4872 #include "menufactory.h"
4875 int main(int argc, char *argv[])
4878 GtkWidget *main_vbox;
4881 GtkAcceleratorTable *accel;
4883 gtk_init(&argc, &argv);
4885 window = gtk_window_new(GTK_WINDOW_TOPLEVEL);
4886 gtk_signal_connect(GTK_OBJECT(window), "destroy",
4887 GTK_SIGNAL_FUNC(file_quit_cmd_callback),
4889 gtk_window_set_title(GTK_WINDOW(window), "Menu Factory");
4890 gtk_widget_set_usize(GTK_WIDGET(window), 300, 200);
4892 main_vbox = gtk_vbox_new(FALSE, 1);
4893 gtk_container_border_width(GTK_CONTAINER(main_vbox), 1);
4894 gtk_container_add(GTK_CONTAINER(window), main_vbox);
4895 gtk_widget_show(main_vbox);
4897 get_main_menu(&menubar, &accel);
4898 gtk_window_add_accelerator_table(GTK_WINDOW(window), accel);
4899 gtk_box_pack_start(GTK_BOX(main_vbox), menubar, FALSE, TRUE, 0);
4900 gtk_widget_show(menubar);
4902 gtk_widget_show(window);
4908 /* This is just to demonstrate how callbacks work when using the
4909 * menufactory. Often, people put all the callbacks from the menus
4910 * in a separate file, and then have them call the appropriate functions
4911 * from there. Keeps it more organized. */
4912 void file_quit_cmd_callback (GtkWidget *widget, gpointer data)
4914 g_print ("%s\n", (char *) data);
4919 And a makefile so it'll be easier to compile it.
4926 C_FLAGS = -Wall $(PROF) -L/usr/local/include -DDEBUG
4927 L_FLAGS = $(PROF) -L/usr/X11R6/lib -L/usr/local/lib
4928 L_POSTFLAGS = -lgtk -lgdk -lglib -lXext -lX11 -lm
4929 PROGNAME = menufactory
4931 O_FILES = menufactory.o mfmain.o
4933 $(PROGNAME): $(O_FILES)
4935 $(CC) $(L_FLAGS) -o $(PROGNAME) $(O_FILES) $(L_POSTFLAGS)
4938 $(CC) -c $(C_FLAGS) $<
4941 rm -f core *.o $(PROGNAME) nohup.out
4946 For now, there's only this example. An explanation and lots 'o' comments
4949 <!-- ***************************************************************** -->
4950 <sect> Undocumented Widgets
4951 <!-- ***************************************************************** -->
4954 These all require authors! :) Please consider contributing to our tutorial.
4956 If you must use one of these widgets that are undocumented, I strongly
4957 suggest you take a look at their respective header files in the GTK distro.
4958 GTK's function names are very descriptive. Once you have an understanding
4959 of how things work, it's not easy to figure out how to use a widget simply
4960 by looking at it's function declarations. This, along with a few examples
4961 from others' code, and it should be no problem.
4963 When you do come to understand all the functions of a new undocumented
4964 widget, please consider writing a tutorial on it so others may benifit from
4967 <!-- ----------------------------------------------------------------- -->
4968 <sect1> Color Selections
4970 <!-- ----------------------------------------------------------------- -->
4971 <sect1> Range Controls
4973 <!-- ----------------------------------------------------------------- -->
4977 <!-- ----------------------------------------------------------------- -->
4981 (This may need to be rewritten to follow the style of the rest of the tutorial)
4985 Previews serve a number of purposes in GIMP/GTK. The most important one is
4986 this. High quality images may take up to tens of megabytes of memory - easy!
4987 Any operation on an image that big is bound to take a long time. If it takes
4988 you 5-10 trial-and-errors (i.e. 10-20 steps, since you have to revert after
4989 you make an error) to choose the desired modification, it make take you
4990 literally hours to make the right one - if you don't run out of memory
4991 first. People who have spent hours in color darkrooms know the feeling.
4992 Previews to the rescue!
4994 But the annoyance of the delay is not the only issue. Oftentimes it is
4995 helpful to compare the Before and After versions side-by-side or at least
4996 back-to-back. If you're working with big images and 10 second delays,
4997 obtaining the Before and After impressions is, to say the least, difficult.
4998 For 30M images (4"x6", 600dpi, 24 bit) the side-by-side comparison is right
4999 out for most people, while back-to-back is more like back-to-1001, 1002,
5000 ..., 1010-back! Previews to the rescue!
5002 But there's more. Previews allow for side-by-side pre-previews. In other
5003 words, you write a plug-in (e.g. the filterpack simulation) which would have
5004 a number of here's-what-it-would-look-like-if-you-were-to-do-this previews.
5005 An approach like this acts as a sort of a preview palette and is very
5006 effective fow subtle changes. Let's go previews!
5008 There's more. For certain plug-ins real-time image-specific human
5009 intervention maybe necessary. In the SuperNova plug-in, for example, the
5010 user is asked to enter the coordinates of the center of the future
5011 supernova. The easiest way to do this, really, is to present the user with a
5012 preview and ask him to intereactively select the spot. Let's go previews!
5014 Finally, a couple of misc uses. One can use previews even when not working
5015 with big images. For example, they are useful when rendering compicated
5016 patterns. (Just check out the venerable Diffraction plug-in + many other
5017 ones!) As another example, take a look at the colormap rotation plug-in
5018 (work in progress). You can also use previews for little logo's inside you
5019 plug-ins and even for an image of yourself, The Author. Let's go previews!
5021 When Not to Use Previews
5023 Don't use previews for graphs, drawing etc. GDK is much faster for that. Use
5024 previews only for rendered images!
5028 You can stick a preview into just about anything. In a vbox, an hbox, a
5029 table, a button, etc. But they look their best in tight frames around them.
5030 Previews by themselves do not have borders and look flat without them. (Of
5031 course, if the flat look is what you want...) Tight frames provide the
5036 Previews in many ways are like any other widgets in GTK (whatever that
5037 means) except they possess an addtional feature: they need to be filled with
5038 some sort of an image! First, we will deal exclusively with the GTK aspect
5039 of previews and then we'll discuss how to fill them.
5045 /* Create a preview widget,
5046 set its size, an show it */
5048 preview=gtk_preview_new(GTK_PREVIEW_COLOR)
5050 GTK_PREVIEW_GRAYSCALE);*/
5051 gtk_preview_size (GTK_PREVIEW (preview), WIDTH, HEIGHT);
5052 gtk_widget_show(preview);
5053 my_preview_rendering_function(preview);
5055 Oh yeah, like I said, previews look good inside frames, so how about:
5057 GtkWidget *create_a_preview(int Width,
5064 frame = gtk_frame_new(NULL);
5065 gtk_frame_set_shadow_type (GTK_FRAME (frame), GTK_SHADOW_IN);
5066 gtk_container_border_width (GTK_CONTAINER(frame),0);
5067 gtk_widget_show(frame);
5069 preview=gtk_preview_new (Colorfulness?GTK_PREVIEW_COLOR
5070 :GTK_PREVIEW_GRAYSCALE);
5071 gtk_preview_size (GTK_PREVIEW (preview), Width, Height);
5072 gtk_container_add(GTK_CONTAINER(frame),preview);
5073 gtk_widget_show(preview);
5075 my_preview_rendering_function(preview);
5079 That's my basic preview. This routine returns the "parent" frame so you can
5080 place it somewhere else in your interface. Of course, you can pass the
5081 parent frame to this routine as a parameter. In many situations, however,
5082 the contents of the preview are changed continually by your application. In
5083 this case you may want to pass a pointer to the preview to a
5084 "create_a_preview()" and thus have control of it later.
5086 One more important note that may one day save you a lot of time. Sometimes
5087 it is desirable to label you preview. For example, you may label the preview
5088 containing the original image as "Original" and the one containing the
5089 modified image as "Less Original". It might occure to you to pack the
5090 preview along with the appropriate label into a vbox. The unexpected caveat
5091 is that if the label is wider than the preview (which may happen for a
5092 variety of reasons unforseeable to you, from the dynamic decision on the
5093 size of the preview to the size of the font) the frame expands and no longer
5094 fits tightly over the preview. The same problem can probably arise in other
5099 The solution is to place the preview and the label into a 2x1 table and by
5100 attaching them with the following paramters (this is one possible variations
5101 of course. The key is no GTK_FILL in the second attachment):
5103 gtk_table_attach(GTK_TABLE(table),label,0,1,0,1,
5105 GTK_EXPAND|GTK_FILL,
5107 gtk_table_attach(GTK_TABLE(table),frame,0,1,1,2,
5113 And here's the result:
5119 Making a preview clickable is achieved most easily by placing it in a
5120 button. It also adds a nice border around the preview and you may not even
5121 need to place it in a frame. See the Filter Pack Simulation plug-in for an
5124 This is pretty much it as far as GTK is concerned.
5126 Filling In a Preview
5128 In order to familiarize ourselves with the basics of filling in previews,
5129 let's create the following pattern (contrived by trial and error):
5134 my_preview_rendering_function(GtkWidget *preview)
5137 #define HALF (SIZE/2)
5139 guchar *row=(guchar *) malloc(3*SIZE); /* 3 bits per dot */
5140 gint i, j; /* Coordinates */
5141 double r, alpha, x, y;
5143 if (preview==NULL) return; /* I usually add this when I want */
5144 /* to avoid silly crashes. You */
5145 /* should probably make sure that */
5146 /* everything has been nicely */
5148 for (j=0; j < ABS(cos(2*alpha)) ) { /* Are we inside the shape? */
5149 /* glib.h contains ABS(x). */
5150 row[i*3+0] = sqrt(1-r)*255; /* Define Red */
5151 row[i*3+1] = 128; /* Define Green */
5152 row[i*3+2] = 224; /* Define Blue */
5153 } /* "+0" is for alignment! */
5156 row[i*3+1] = ABS(sin((float)i/SIZE*2*PI))*255;
5157 row[i*3+2] = ABS(sin((float)j/SIZE*2*PI))*255;
5160 gtk_preview_draw_row( GTK_PREVIEW(preview),row,0,j,SIZE);
5161 /* Insert "row" into "preview" starting at the point with */
5162 /* coordinates (0,j) first column, j_th row extending SIZE */
5163 /* pixels to the right */
5166 free(row); /* save some space */
5167 gtk_widget_draw(preview,NULL); /* what does this do? */
5168 gdk_flush(); /* or this? */
5171 Non-GIMP users can have probably seen enough to do a lot of things already.
5172 For the GIMP users I have a few pointers to add.
5176 It is probably wize to keep a reduced version of the image around with just
5177 enough pixels to fill the preview. This is done by selecting every n'th
5178 pixel where n is the ratio of the size of the image to the size of the
5179 preview. All further operations (including filling in the previews) are then
5180 performed on the reduced number of pixels only. The following is my
5181 implementation of reducing the image. (Keep in mind that I've had only basic
5184 (UNTESTED CODE ALERT!!!)
5196 SELCTION_IN_CONTEXT,
5200 ReducedImage *Reduce_The_Image(GDrawable *drawable,
5205 /* This function reduced the image down to the the selected preview size */
5206 /* The preview size is determine by LongerSize, i.e. the greater of the */
5207 /* two dimentions. Works for RGB images only! */
5208 gint RH, RW; /* Reduced height and reduced width */
5209 gint width, height; /* Width and Height of the area being reduced */
5210 gint bytes=drawable->bpp;
5211 ReducedImage *temp=(ReducedImage *)malloc(sizeof(ReducedImage));
5213 guchar *tempRGB, *src_row, *tempmask, *src_mask_row,R,G,B;
5214 gint i, j, whichcol, whichrow, x1, x2, y1, y2;
5215 GPixelRgn srcPR, srcMask;
5216 gint NoSelectionMade=TRUE; /* Assume that we're dealing with the entire */
5219 gimp_drawable_mask_bounds (drawable->id, &x1, &y1, &x2, &y2);
5222 /* If there's a SELECTION, we got its bounds!)
5224 if (width != drawable->width && height != drawable->height)
5225 NoSelectionMade=FALSE;
5226 /* Become aware of whether the user has made an active selection */
5227 /* This will become important later, when creating a reduced mask. */
5229 /* If we want to preview the entire image, overrule the above! */
5230 /* Of course, if no selection has been made, this does nothing! */
5231 if (Selection==ENTIRE_IMAGE) {
5235 y2=drawable->height;
5238 /* If we want to preview a selection with some surronding area we */
5239 /* have to expand it a little bit. Consider it a bit of a riddle. */
5240 if (Selection==SELECTION_IN_CONTEXT) {
5241 x1=MAX(0, x1-width/2.0);
5242 x2=MIN(drawable->width, x2+width/2.0);
5243 y1=MAX(0, y1-height/2.0);
5244 y2=MIN(drawable->height, y2+height/2.0);
5247 /* How we can determine the width and the height of the area being */
5252 /* The lines below determine which dimension is to be the longer */
5253 /* side. The idea borrowed from the supernova plug-in. I suspect I */
5254 /* could've thought of it myself, but the truth must be told. */
5255 /* Plagiarism stinks! */
5258 RH=(float) height * (float) LongerSize/ (float) width;
5262 RW=(float)width * (float) LongerSize/ (float) height;
5265 /* The intire image is stretched into a string! */
5266 tempRGB = (guchar *) malloc(RW*RH*bytes);
5267 tempmask = (guchar *) malloc(RW*RH);
5269 gimp_pixel_rgn_init (&srcPR, drawable, x1, y1, width, height, FALSE, FALSE);
5270 gimp_pixel_rgn_init (&srcMask, mask, x1, y1, width, height, FALSE, FALSE);
5272 /* Grab enough to save a row of image and a row of mask. */
5273 src_row = (guchar *) malloc (width*bytes);
5274 src_mask_row = (guchar *) malloc (width);
5276 for (i=0; i < RH; i++) {
5277 whichrow=(float)i*(float)height/(float)RH;
5278 gimp_pixel_rgn_get_row (&srcPR, src_row, x1, y1+whichrow, width);
5279 gimp_pixel_rgn_get_row (&srcMask, src_mask_row, x1, y1+whichrow, width);
5281 for (j=0; j < RW; j++) {
5282 whichcol=(float)j*(float)width/(float)RW;
5284 /* No selection made = each point is completely selected! */
5285 if (NoSelectionMade)
5286 tempmask[i*RW+j]=255;
5288 tempmask[i*RW+j]=src_mask_row[whichcol];
5290 /* Add the row to the one long string which now contains the image! */
5291 tempRGB[i*RW*bytes+j*bytes+0]=src_row[whichcol*bytes+0];
5292 tempRGB[i*RW*bytes+j*bytes+1]=src_row[whichcol*bytes+1];
5293 tempRGB[i*RW*bytes+j*bytes+2]=src_row[whichcol*bytes+2];
5295 /* Hold on to the alpha as well */
5297 tempRGB[i*RW*bytes+j*bytes+3]=src_row[whichcol*bytes+3];
5304 temp->mask=tempmask;
5308 The following is a preview function which used the same ReducedImage type!
5309 Note that it uses fakes transparancy (if one is present by means of
5310 fake_transparancy which is defined as follows:
5312 gint fake_transparency(gint i, gint j)
5314 if ( ((i%20)- 10) * ((j%20)- 10)>0 )
5320 Now here's the preview function:
5323 my_preview_render_function(GtkWidget *preview,
5327 gint Inten, bytes=drawable->bpp;
5330 gint RW=reduced->width;
5331 gint RH=reduced->height;
5332 guchar *row=malloc(bytes*RW);;
5335 for (i=0; i < RH; i++) {
5336 for (j=0; j < RW; j++) {
5338 row[j*3+0] = reduced->rgb[i*RW*bytes + j*bytes + 0];
5339 row[j*3+1] = reduced->rgb[i*RW*bytes + j*bytes + 1];
5340 row[j*3+2] = reduced->rgb[i*RW*bytes + j*bytes + 2];
5343 for (k=0; k<3; k++) {
5344 float transp=reduced->rgb[i*RW*bytes+j*bytes+3]/255.0;
5345 row[3*j+k]=transp*a[3*j+k]+(1-transp)*fake_transparency(i,j);
5348 gtk_preview_draw_row( GTK_PREVIEW(preview),row,0,i,RW);
5352 gtk_widget_draw(preview,NULL);
5358 guint gtk_preview_get_type (void);
5360 void gtk_preview_uninit (void);
5362 GtkWidget* gtk_preview_new (GtkPreviewType type);
5363 /* Described above */
5364 void gtk_preview_size (GtkPreview *preview,
5367 /* Allows you to resize an existing preview. */
5368 /* Apparantly there's a bug in GTK which makes */
5369 /* this process messy. A way to clean up a mess */
5370 /* is to manually resize the window containing */
5371 /* the preview after resizing the preview. */
5373 void gtk_preview_put (GtkPreview *preview,
5384 void gtk_preview_put_row (GtkPreview *preview,
5392 void gtk_preview_draw_row (GtkPreview *preview,
5397 /* Described in the text */
5399 void gtk_preview_set_expand (GtkPreview *preview,
5403 /* No clue for any of the below but */
5404 /* should be standard for most widgets */
5405 void gtk_preview_set_gamma (double gamma);
5406 void gtk_preview_set_color_cube (guint nred_shades,
5407 guint ngreen_shades,
5409 guint ngray_shades);
5410 void gtk_preview_set_install_cmap (gint install_cmap);
5411 void gtk_preview_set_reserved (gint nreserved);
5412 GdkVisual* gtk_preview_get_visual (void);
5413 GdkColormap* gtk_preview_get_cmap (void);
5414 GtkPreviewInfo* gtk_preview_get_info (void);
5420 <!-- ----------------------------------------------------------------- -->
5424 <!-- ***************************************************************** -->
5425 <sect>The EventBox Widget<label id="sec_The_EventBox_Widget">
5426 <!-- ***************************************************************** -->
5429 Some gtk widgets don't have associated X windows, so they just draw on
5430 thier parents. Because of this, they cannot recieve events
5431 and if they are incorrectly sized, they don't clip so you can get
5432 messy overwritting etc. If you require more from these widgets, the
5433 EventBox is for you.
5435 At first glance, the EventBox widget might appear to be totally
5436 useless. It draws nothing on the screen and responds to no
5437 events. However, it does serve a function - it provides an X window for
5438 its child widget. This is important as many GTK widgets do not
5439 have an associated X window. Not having an X window saves memory and
5440 improves performance, but also has some drawbacks. A widget without an
5441 X window cannot receive events, and does not perform any clipping on
5442 it's contents. Although the name ``EventBox'' emphasizes the
5443 event-handling function, the widget also can be used for clipping.
5444 (And more ... see the example below.)
5447 To create a new EventBox widget, use:
5450 GtkWidget* gtk_event_box_new (void);
5454 A child widget can then be added to this EventBox:
5457 gtk_container_add (GTK_CONTAINER(event_box), widget);
5461 The following example demonstrates both uses of an EventBox - a label
5462 is created that clipped to a small box, and set up so that a
5463 mouse-click on the label causes the program to exit.
5468 #include <gtk/gtk.h>
5471 main (int argc, char *argv[])
5474 GtkWidget *event_box;
5477 gtk_init (&argc, &argv);
5479 window = gtk_window_new (GTK_WINDOW_TOPLEVEL);
5481 gtk_window_set_title (GTK_WINDOW (window), "Event Box");
5483 gtk_signal_connect (GTK_OBJECT (window), "destroy",
5484 GTK_SIGNAL_FUNC (gtk_exit), NULL);
5486 gtk_container_border_width (GTK_CONTAINER (window), 10);
5488 /* Create an EventBox and add it to our toplevel window */
5490 event_box = gtk_event_box_new ();
5491 gtk_container_add (GTK_CONTAINER(window), event_box);
5492 gtk_widget_show (event_box);
5494 /* Create a long label */
5496 label = gtk_label_new ("Click here to quit, quit, quit, quit, quit");
5497 gtk_container_add (GTK_CONTAINER (event_box), label);
5498 gtk_widget_show (label);
5500 /* Clip it short. */
5501 gtk_widget_set_usize (label, 110, 20);
5503 /* And bind an action to it */
5504 gtk_widget_set_events (event_box, GDK_BUTTON_PRESS_MASK);
5505 gtk_signal_connect (GTK_OBJECT(event_box), "button_press_event",
5506 GTK_SIGNAL_FUNC (gtk_exit), NULL);
5508 /* Yet one more thing you need an X window for ... */
5510 gtk_widget_realize (event_box);
5511 gdk_window_set_cursor (event_box->window, gdk_cursor_new (GDK_HAND1));
5513 gtk_widget_show (window);
5521 <!-- ***************************************************************** -->
5522 <sect>Setting Widget Attributes<label id="sec_setting_widget_attributes">
5523 <!-- ***************************************************************** -->
5526 This describes the functions used to operate on widgets. These can be used
5527 to set style, padding, size etc.
5529 (Maybe I should make a whole section on accelerators.)
5532 void gtk_widget_install_accelerator (GtkWidget *widget,
5533 GtkAcceleratorTable *table,
5538 void gtk_widget_remove_accelerator (GtkWidget *widget,
5539 GtkAcceleratorTable *table,
5540 gchar *signal_name);
5542 void gtk_widget_activate (GtkWidget *widget);
5544 void gtk_widget_set_name (GtkWidget *widget,
5546 gchar* gtk_widget_get_name (GtkWidget *widget);
5548 void gtk_widget_set_sensitive (GtkWidget *widget,
5551 void gtk_widget_set_style (GtkWidget *widget,
5554 GtkStyle* gtk_widget_get_style (GtkWidget *widget);
5556 GtkStyle* gtk_widget_get_default_style (void);
5558 void gtk_widget_set_uposition (GtkWidget *widget,
5561 void gtk_widget_set_usize (GtkWidget *widget,
5565 void gtk_widget_grab_focus (GtkWidget *widget);
5567 void gtk_widget_show (GtkWidget *widget);
5569 void gtk_widget_hide (GtkWidget *widget);
5572 <!-- ***************************************************************** -->
5573 <sect>Timeouts, IO and Idle Functions<label id="sec_timeouts">
5574 <!-- ***************************************************************** -->
5576 <!-- ----------------------------------------------------------------- -->
5579 You may be wondering how you make GTK do useful work when in gtk_main.
5580 Well, you have several options. Using the following functions you can
5581 create a timeout function that will be called every "interval" milliseconds.
5584 gint gtk_timeout_add (guint32 interval,
5585 GtkFunction function,
5589 The first argument is the number of milliseconds
5590 between calls to your function. The second argument is the function
5591 you wish to have called, and
5592 the third, the data passed to this callback function. The return value is
5593 an integer "tag" which may be used to stop the timeout by calling:
5596 void gtk_timeout_remove (gint tag);
5599 You may also stop the timeout function by returning zero or FALSE from
5600 your callback function. Obviously this means if you want your function to
5601 continue to be called, it should return a non-zero value, ie TRUE.
5603 The declaration of your callback should look something like this:
5606 gint timeout_callback (gpointer data);
5609 <!-- ----------------------------------------------------------------- -->
5610 <sect1>Monitoring IO
5612 Another nifty feature of GTK, is the ability to have it check for data on a
5613 file descriptor for you (as returned by open(2) or socket(2)). This is
5614 especially useful for networking applications. The function:
5617 gint gdk_input_add (gint source,
5618 GdkInputCondition condition,
5619 GdkInputFunction function,
5623 Where the first argument is the file descriptor you wish to have watched,
5624 and the second specifies what you want GDK to look for. This may be one of:
5626 GDK_INPUT_READ - Call your function when there is data ready for reading on
5627 your file descriptor.
5629 GDK_INPUT_WRITE - Call your function when the file descriptor is ready for
5632 As I'm sure you've figured out already, the third argument is the function
5633 you wish to have called when the above conditions are satisfied, and the
5634 fourth is the data to pass to this function.
5636 The return value is a tag that may be used to stop GDK from monitoring this
5637 file descriptor using the following function.
5640 void gdk_input_remove (gint tag);
5643 The callback function should be declared:
5646 void input_callback (gpointer data, gint source,
5647 GdkInputCondition condition);
5651 <!-- ----------------------------------------------------------------- -->
5652 <sect1>Idle Functions
5654 What if you have a function you want called when nothing else is
5658 gint gtk_idle_add (GtkFunction function,
5662 This causes GTK to call the specified function whenever nothing else is
5666 void gtk_idle_remove (gint tag);
5669 I won't explain the meaning of the arguments as they follow very much like
5670 the ones above. The function pointed to by the first argument to
5671 gtk_idle_add will be called whenever the opportunity arises. As with the
5672 others, returning FALSE will stop the idle function from being called.
5674 <!-- ***************************************************************** -->
5675 <sect>Managing Selections
5676 <!-- ***************************************************************** -->
5678 <!-- ----------------------------------------------------------------- -->
5683 One type of interprocess communication supported by GTK is
5684 <em>selections</em>. A selection identifies a chunk of data, for
5685 instance, a portion of text, selected by the user in some fashion, for
5686 instance, by dragging with the mouse. Only one application on a
5687 display, (he <em>owner</em>_ can own a particular selection at one
5688 time, so when a selection is claimed by one application, the previous
5689 owner must indicate to the user that selection has been
5690 relinquished. Other applications can request the contents of a
5691 selection in different forms, called <em>targets</em>. There can be
5692 any number of selections, but most X applications only handle one, the
5693 <em>primary selection</em>.
5696 In most cases, it isn't necessary for a GTK application to deal with
5697 selections itself. The standard widgets, such as the Entry widget,
5698 already have the capability to claim the selection when appropriate
5699 (e.g., when the user drags over text), and to retrieve the contents of
5700 the selection owned by another widget, or another application (e.g.,
5701 when the user clicks the second mouse button). However, there may be
5702 cases in which you want to give other widgets the ability to supply
5703 the selection, or you wish to retrieve targets not supported by
5707 A fundamental concept needed to understand selection handling is that
5708 of the <em>atom</em>. An atom is an integer that uniquely identifies a
5709 string (on a certain display). Certain atoms are predefined by the X
5710 server, and in some cases there are constants in in <tt>gtk.h</tt>
5711 corresponding to these atoms. For instance the constant
5712 <tt>GDK_PRIMARY_SELECTION</tt> corresponds to the string "PRIMARY".
5713 In other cases, you should use the functions
5714 <tt>gdk_atom_intern()</tt>, to get the atom corresponding to a string,
5715 and <tt>gdk_atom_name()</tt>, to get the name of an atom. Both
5716 selections and targets are identifed by atoms.
5718 <!-- ----------------------------------------------------------------- -->
5719 <sect1> Retrieving the selection
5723 Retrieving the selection is an asynchronous process. To start the
5727 gint gtk_selection_convert (GtkWidget *widget,
5733 This <em>converts</em> the selection into the form specified by
5734 <tt/target/. If it all possible, the time field should be the time
5735 from the event that triggered the selection. This helps make sure that
5736 events occur in the order that the user requested them.
5737 However, if it is not available (for instance, if the conversion was
5738 triggered by a "clicked" signal), then you can use the constant
5739 <tt>GDK_CURRENT_TIME</tt>.
5742 When the selection owner responds to the request, a
5743 "selection_received" signal is sent to your application. The handler
5744 for this signal receives a pointer to a <tt>GtkSelectionData</tt>
5745 structure, which is defined as:
5748 struct _GtkSelectionData
5759 <tt>selection</tt> and <tt>target</tt> are the values you gave in your
5760 <tt>gtk_selection_convert()</tt> call. <tt>type</tt> is an atom that
5761 identifies the type of data returned by the selection owner. Some
5762 possible values are "STRING", a string of latin-1 characters, "ATOM",
5763 a series of atoms, "INTEGER", an integer, etc. Most targets can only
5764 return one type. <tt/format/ gives the length of the units (for
5765 instance characters) in bits. Usually, you don't care about this when
5766 receiving data. <tt>data</tt> is a pointer to the returned data, and
5767 <tt>length</tt> gives the length of the returned data, in bytes. If
5768 <tt>length</tt> is negative, then an error occurred and the selection
5769 could not be retrieved. This might happen if no application owned the
5770 selection, or if you requested a target that the application didn't
5771 support. The buffer is actually guaranteed to be one byte longer than
5772 <tt>length</tt>; the extra byte will always be zero, so it isn't
5773 necessary to make a copy of strings just to null terminate them.
5776 In the following example, we retrieve the special target "TARGETS",
5777 which is a list of all targets into which the selection can be
5783 #include <gtk/gtk.h>
5785 void selection_received (GtkWidget *widget,
5786 GtkSelectionData *selection_data,
5789 /* Signal handler invoked when user clicks on the "Get Targets" button */
5791 get_targets (GtkWidget *widget, gpointer data)
5793 static GdkAtom targets_atom = GDK_NONE;
5795 /* Get the atom corresonding to the string "TARGETS" */
5796 if (targets_atom == GDK_NONE)
5797 targets_atom = gdk_atom_intern ("TARGETS", FALSE);
5799 /* And request the "TARGETS" target for the primary selection */
5800 gtk_selection_convert (widget, GDK_SELECTION_PRIMARY, targets_atom,
5804 /* Signal handler called when the selections owner returns the data */
5806 selection_received (GtkWidget *widget, GtkSelectionData *selection_data,
5813 /* **** IMPORTANT **** Check to see if retrieval succeeded */
5814 if (selection_data->length < 0)
5816 g_print ("Selection retrieval failed\n");
5819 /* Make sure we got the data in the expected form */
5820 if (selection_data->type != GDK_SELECTION_TYPE_ATOM)
5822 g_print ("Selection \"TARGETS\" was not returned as atoms!\n");
5826 /* Print out the atoms we received */
5827 atoms = (GdkAtom *)selection_data->data;
5830 for (i=0; i<selection_data->length/sizeof(GdkAtom); i++)
5833 name = gdk_atom_name (atoms[i]);
5835 g_print ("%s\n",name);
5837 g_print ("(bad atom)\n");
5844 main (int argc, char *argv[])
5849 gtk_init (&argc, &argv);
5851 /* Create the toplevel window */
5853 window = gtk_window_new (GTK_WINDOW_TOPLEVEL);
5854 gtk_window_set_title (GTK_WINDOW (window), "Event Box");
5855 gtk_container_border_width (GTK_CONTAINER (window), 10);
5857 gtk_signal_connect (GTK_OBJECT (window), "destroy",
5858 GTK_SIGNAL_FUNC (gtk_exit), NULL);
5860 /* Create a button the user can click to get targets */
5862 button = gtk_button_new_with_label ("Get Targets");
5863 gtk_container_add (GTK_CONTAINER (window), button);
5865 gtk_signal_connect (GTK_OBJECT(button), "clicked",
5866 GTK_SIGNAL_FUNC (get_targets), NULL);
5867 gtk_signal_connect (GTK_OBJECT(button), "selection_received",
5868 GTK_SIGNAL_FUNC (selection_received), NULL);
5870 gtk_widget_show (button);
5871 gtk_widget_show (window);
5879 <!-- ----------------------------------------------------------------- -->
5880 <sect1> Supplying the selection
5884 Supplying the selection is a bit more complicated. You must register
5885 handlers that will be called when your selection is requested. For
5886 each selection/target pair you will handle, you make a call to:
5889 void gtk_selection_add_handler (GtkWidget *widget,
5892 GtkSelectionFunction function,
5893 GtkRemoveFunction remove_func,
5897 <tt/widget/, <tt/selection/, and <tt/target/ identify the requests
5898 this handler will manage. <tt/remove_func/ if not
5899 NULL, will be called when the signal handler is removed. This is
5900 useful, for instance, for interpreted languages which need to
5901 keep track of a reference count for <tt/data/.
5904 The callback function has the signature:
5907 typedef void (*GtkSelectionFunction) (GtkWidget *widget,
5908 GtkSelectionData *selection_data,
5913 The GtkSelectionData is the same as above, but this time, we're
5914 responsible for filling in the fields <tt/type/, <tt/format/,
5915 <tt/data/, and <tt/length/. (The <tt/format/ field is actually
5916 important here - the X server uses it to figure out whether the data
5917 needs to be byte-swapped or not. Usually it will be 8 - <em/i.e./ a
5918 character - or 32 - <em/i.e./ a. integer.) This is done by calling the
5922 void gtk_selection_data_set (GtkSelectionData *selection_data,
5929 This function takes care of properly making a copy of the data so that
5930 you don't have to worry about keeping it around. (You should not fill
5931 in the fields of the GtkSelectionData structure by hand.)
5934 When prompted by the user, you claim ownership of the selection by
5938 gint gtk_selection_owner_set (GtkWidget *widget,
5943 If another application claims ownership of the selection, you will
5944 receive a "selection_clear_event".
5946 As an example of supplying the selection, the following program adds
5947 selection functionality to a toggle button. When the toggle button is
5948 depressed, the program claims the primary selection. The only target
5949 supported (aside from certain targets like "TARGETS" supplied by GTK
5950 itself), is the "STRING" target. When this target is requested, a
5951 string representation of the time is returned.
5954 /* setselection.c */
5956 #include <gtk/gtk.h>
5959 /* Callback when the user toggles the selection */
5961 selection_toggled (GtkWidget *widget, gint *have_selection)
5963 if (GTK_TOGGLE_BUTTON(widget)->active)
5965 *have_selection = gtk_selection_owner_set (widget,
5966 GDK_SELECTION_PRIMARY,
5968 /* if claiming the selection failed, we return the button to
5970 if (!*have_selection)
5971 gtk_toggle_button_set_state (GTK_TOGGLE_BUTTON(widget), FALSE);
5975 if (*have_selection)
5977 /* Before clearing the selection by setting the owner to NULL,
5978 we check if we are the actual owner */
5979 if (gdk_selection_owner_get (GDK_SELECTION_PRIMARY) == widget->window)
5980 gtk_selection_owner_set (NULL, GDK_SELECTION_PRIMARY,
5982 *have_selection = FALSE;
5987 /* Called when another application claims the selection */
5989 selection_clear (GtkWidget *widget, GdkEventSelection *event,
5990 gint *have_selection)
5992 *have_selection = FALSE;
5993 gtk_toggle_button_set_state (GTK_TOGGLE_BUTTON(widget), FALSE);
5998 /* Supplies the current time as the selection. */
6000 selection_handle (GtkWidget *widget,
6001 GtkSelectionData *selection_data,
6005 time_t current_time;
6007 current_time = time (NULL);
6008 timestr = asctime (localtime(&current_time));
6009 /* When we return a single string, it should not be null terminated.
6010 That will be done for us */
6012 gtk_selection_data_set (selection_data, GDK_SELECTION_TYPE_STRING,
6013 8, timestr, strlen(timestr));
6017 main (int argc, char *argv[])
6021 GtkWidget *selection_button;
6023 static int have_selection = FALSE;
6025 gtk_init (&argc, &argv);
6027 /* Create the toplevel window */
6029 window = gtk_window_new (GTK_WINDOW_TOPLEVEL);
6030 gtk_window_set_title (GTK_WINDOW (window), "Event Box");
6031 gtk_container_border_width (GTK_CONTAINER (window), 10);
6033 gtk_signal_connect (GTK_OBJECT (window), "destroy",
6034 GTK_SIGNAL_FUNC (gtk_exit), NULL);
6036 /* Create a toggle button to act as the selection */
6038 selection_button = gtk_toggle_button_new_with_label ("Claim Selection");
6039 gtk_container_add (GTK_CONTAINER (window), selection_button);
6040 gtk_widget_show (selection_button);
6042 gtk_signal_connect (GTK_OBJECT(selection_button), "toggled",
6043 GTK_SIGNAL_FUNC (selection_toggled), &have_selection);
6044 gtk_signal_connect (GTK_OBJECT(selection_button), "selection_clear_event",
6045 GTK_SIGNAL_FUNC (selection_clear), &have_selection);
6047 gtk_selection_add_handler (selection_button, GDK_SELECTION_PRIMARY,
6048 GDK_SELECTION_TYPE_STRING,
6049 selection_handle, NULL);
6051 gtk_widget_show (selection_button);
6052 gtk_widget_show (window);
6061 <!-- ***************************************************************** -->
6062 <sect>glib<label id="sec_glib">
6063 <!-- ***************************************************************** -->
6066 glib provides many useful functions and definitions available for use
6068 and GTK applications. I will list them all here with a brief explanation.
6069 Many are duplicates of standard libc functions so I won't go into
6070 detail on those. This is mostly to be used as a reference, so you know what is
6073 <!-- ----------------------------------------------------------------- -->
6076 Definitions for the extremes of many of the standard types are:
6091 Also, the following typedefs. The ones left unspecified are dynamically set
6092 depending on the architecture. Remember to avoid counting on the size of a
6093 pointer if you want to be portable! Eg, a pointer on an Alpha is 8 bytes, but 4
6103 unsigned char guchar;
6104 unsigned short gushort;
6105 unsigned long gulong;
6110 long double gldouble;
6122 <!-- ----------------------------------------------------------------- -->
6123 <sect1>Doubly Linked Lists
6125 The following functions are used to create, manage, and destroy doubly
6126 linked lists. I assume you know what linked lists are, as it is beyond the scope
6127 of this document to explain them. Of course, it's not required that you
6128 know these for general use of GTK, but they are nice to know.
6131 GList* g_list_alloc (void);
6133 void g_list_free (GList *list);
6135 void g_list_free_1 (GList *list);
6137 GList* g_list_append (GList *list,
6140 GList* g_list_prepend (GList *list,
6143 GList* g_list_insert (GList *list,
6147 GList* g_list_remove (GList *list,
6150 GList* g_list_remove_link (GList *list,
6153 GList* g_list_reverse (GList *list);
6155 GList* g_list_nth (GList *list,
6158 GList* g_list_find (GList *list,
6161 GList* g_list_last (GList *list);
6163 GList* g_list_first (GList *list);
6165 gint g_list_length (GList *list);
6167 void g_list_foreach (GList *list,
6169 gpointer user_data);
6172 <!-- ----------------------------------------------------------------- -->
6173 <sect1>Singly Linked Lists
6175 Many of the above functions for singly linked lists are identical to the
6176 above. Here is a complete list:
6178 GSList* g_slist_alloc (void);
6180 void g_slist_free (GSList *list);
6182 void g_slist_free_1 (GSList *list);
6184 GSList* g_slist_append (GSList *list,
6187 GSList* g_slist_prepend (GSList *list,
6190 GSList* g_slist_insert (GSList *list,
6194 GSList* g_slist_remove (GSList *list,
6197 GSList* g_slist_remove_link (GSList *list,
6200 GSList* g_slist_reverse (GSList *list);
6202 GSList* g_slist_nth (GSList *list,
6205 GSList* g_slist_find (GSList *list,
6208 GSList* g_slist_last (GSList *list);
6210 gint g_slist_length (GSList *list);
6212 void g_slist_foreach (GSList *list,
6214 gpointer user_data);
6218 <!-- ----------------------------------------------------------------- -->
6219 <sect1>Memory Management
6222 gpointer g_malloc (gulong size);
6225 This is a replacement for malloc(). You do not need to check the return
6226 vaule as it is done for you in this function.
6229 gpointer g_malloc0 (gulong size);
6232 Same as above, but zeroes the memory before returning a pointer to it.
6235 gpointer g_realloc (gpointer mem,
6239 Relocates "size" bytes of memory starting at "mem". Obviously, the memory should have been
6240 previously allocated.
6243 void g_free (gpointer mem);
6246 Frees memory. Easy one.
6249 void g_mem_profile (void);
6252 Dumps a profile of used memory, but requries that you add #define
6253 MEM_PROFILE to the top of glib/gmem.c and re-make and make install.
6256 void g_mem_check (gpointer mem);
6259 Checks that a memory location is valid. Requires you add #define
6260 MEM_CHECK to the top of gmem.c and re-make and make install.
6262 <!-- ----------------------------------------------------------------- -->
6268 GTimer* g_timer_new (void);
6270 void g_timer_destroy (GTimer *timer);
6272 void g_timer_start (GTimer *timer);
6274 void g_timer_stop (GTimer *timer);
6276 void g_timer_reset (GTimer *timer);
6278 gdouble g_timer_elapsed (GTimer *timer,
6279 gulong *microseconds);
6282 <!-- ----------------------------------------------------------------- -->
6283 <sect1>String Handling
6285 A whole mess of string handling functions. They all look very interesting, and
6286 probably better for many purposes than the standard C string functions, but
6287 require documentation.
6290 GString* g_string_new (gchar *init);
6291 void g_string_free (GString *string,
6294 GString* g_string_assign (GString *lval,
6297 GString* g_string_truncate (GString *string,
6300 GString* g_string_append (GString *string,
6303 GString* g_string_append_c (GString *string,
6306 GString* g_string_prepend (GString *string,
6309 GString* g_string_prepend_c (GString *string,
6312 void g_string_sprintf (GString *string,
6316 void g_string_sprintfa (GString *string,
6321 <!-- ----------------------------------------------------------------- -->
6322 <sect1>Utility and Error Functions
6325 gchar* g_strdup (const gchar *str);
6328 Replacement strdup function. Copies the
6329 original strings contents to newly allocated memory, and returns a pointer to it.
6332 gchar* g_strerror (gint errnum);
6335 I recommend using this for all error messages. It's much nicer, and more
6336 portable than perror() or others. The output is usually of the form:
6339 program name:function that failed:file or further description:strerror
6342 Here's an example of one such call used in our hello_world program:
6345 g_print("hello_world:open:%s:%s\n", filename, g_strerror(errno));
6349 void g_error (gchar *format, ...);
6352 Prints an error message. The format is just like printf, but it
6353 prepends "** ERROR **: " to your message, and exits the program.
6354 Use only for fatal errors.
6357 void g_warning (gchar *format, ...);
6360 Same as above, but prepends "** WARNING **: ", and does not exit the
6364 void g_message (gchar *format, ...);
6367 Prints "message: " prepended to the string you pass in.
6370 void g_print (gchar *format, ...);
6373 Replacement for printf().
6375 And our last function:
6378 gchar* g_strsignal (gint signum);
6381 Prints out the name of the Unix system signal given the signal number.
6382 Useful in generic signal handling functions.
6384 All of the above are more or less just stolen from glib.h. If anyone cares
6385 to document any function, just send me an email!
6387 <!-- ***************************************************************** -->
6388 <sect>GTK's rc Files
6389 <!-- ***************************************************************** -->
6392 GTK has it's own way of dealing with application defaults, by using rc
6393 files. These can be used to set the colors of just about any widget, and
6394 can also be used to tile pixmaps onto the background of some widgets.
6396 <!-- ----------------------------------------------------------------- -->
6397 <sect1>Functions For rc Files
6399 When your application starts, you should include a call to:
6401 void gtk_rc_parse (char *filename);
6404 Passing in the filename of your rc file. This will cause GTK to parse this
6405 file, and use the style settings for the widget types defined there.
6407 If you wish to have a special set of widgets that can take on a different
6408 style from others, or any other logical division of widgets, use a call to:
6410 void gtk_widget_set_name (GtkWidget *widget,
6414 Passing your newly created widget as the first argument, and the name
6415 you wish to give it as the second. This will allow you to change the
6416 attributes of this widget by name through the rc file.
6418 If we use a call something like this:
6421 button = gtk_button_new_with_label ("Special Button");
6422 gtk_widget_set_name (button, "special button");
6425 Then this button is given the name "special button" and may be addressed by
6426 name in the rc file as "special button.GtkButton". [<--- Verify ME!]
6428 The example rc file below, sets the properties of the main window, and lets
6429 all children of that main window inherit the style described by the "main
6430 button" style. The code used in the application is:
6433 window = gtk_window_new (GTK_WINDOW_TOPLEVEL);
6434 gtk_widget_set_name (window, "main window");
6437 And then the style is defined in the rc file using:
6440 widget "main window.*GtkButton*" style "main_button"
6443 Which sets all the GtkButton widgets in the "main window" to the
6444 "main_buttons" style as defined in the rc file.
6446 As you can see, this is a fairly powerful and flexible system. Use your
6447 imagination as to how best to take advantage of this.
6449 <!-- ----------------------------------------------------------------- -->
6450 <sect1>GTK's rc File Format
6452 The format of the GTK file is illustrated in the example below. This is
6453 the testgtkrc file from the GTK distribution, but I've added a
6454 few comments and things. You may wish to include this explanation
6455 your application to allow the user to fine tune his application.
6457 There are several directives to change the attributes of a widget.
6459 <item>fg - Sets the foreground color of a widget.
6460 <item>bg - Sets the background color of a widget.
6461 <item>bg_pixmap - Sets the background of a widget to a tiled pixmap.
6462 <item>font - Sets the font to be used with the given widget.
6465 In addition to this, there are several states a widget can be in, and you
6466 can set different colors, pixmaps and fonts for each state. These states are:
6468 <item>NORMAL - The normal state of a widget, without the mouse over top of
6469 it, and not being pressed etc.
6470 <item>PRELIGHT - When the mouse is over top of the widget, colors defined
6471 using this state will be in effect.
6472 <item>ACTIVE - When the widget is pressed or clicked it will be active, and
6473 the attributes assigned by this tag will be in effect.
6474 <item>INSENSITIVE - When a widget is set insensitive, and cannot be
6475 activated, it will take these attributes.
6476 <item>SELECTED - When an object is selected, it takes these attributes.
6479 When using the "fg" and "bg" keywords to set the colors of widgets, the
6482 fg[<STATE>] = { Red, Green, Blue }
6485 Where STATE is one of the above states (PRELIGHT, ACTIVE etc), and the Red,
6486 Green and Blue are values in the range of 0 - 1.0, { 1.0, 1.0, 1.0 } being
6488 They must be in float form, or they will register as 0, so a straight
6489 "1" will not work, it must
6490 be "1.0". A straight "0" is fine because it doesn't matter if it's not
6491 recognized. Unrecognized values are set to 0.
6493 bg_pixmap is very similar to the above, except the colors are replaced by a
6496 pixmap_path is a list of paths seperated by ":"'s. These paths will be
6497 searched for any pixmap you specify.
6500 The font directive is simply:
6502 font = "<font name>"
6505 Where the only hard part is figuring out the font string. Using xfontsel or
6506 similar utility should help.
6508 The "widget_class" sets the style of a class of widgets. These classes are
6509 listed in the widget overview on the class hierarchy.
6511 The "widget" directive sets a specificaly named set of widgets to a
6512 given style, overriding any style set for the given widget class.
6513 These widgets are registered inside the application using the
6514 gtk_widget_set_name() call. This allows you to specify the attributes of a
6515 widget on a per widget basis, rather than setting the attributes of an
6516 entire widget class. I urge you to document any of these special widgets so
6517 users may customize them.
6519 When the keyword "<tt>parent</>" is used as an attribute, the widget will take on
6520 the attributes of it's parent in the application.
6522 When defining a style, you may assign the attributes of a previously defined
6523 style to this new one.
6525 style "main_button" = "button"
6527 font = "-adobe-helvetica-medium-r-normal--*-100-*-*-*-*-*-*"
6528 bg[PRELIGHT] = { 0.75, 0, 0 }
6532 This example takes the "button" style, and creates a new "main_button" style
6533 simply by changing the font and prelight background color of the "button"
6536 Of course, many of these attributes don't apply to all widgets. It's a
6537 simple matter of common sense really. Anything that could apply, should.
6539 <!-- ----------------------------------------------------------------- -->
6540 <sect1>Example rc file
6544 # pixmap_path "<dir 1>:<dir 2>:<dir 3>:..."
6546 pixmap_path "/usr/include/X11R6/pixmaps:/home/imain/pixmaps"
6548 # style <name> [= <name>]
6553 # widget <widget_set> style <style_name>
6554 # widget_class <widget_class_set> style <style_name>
6557 # Here is a list of all the possible states. Note that some do not apply to
6560 # NORMAL - The normal state of a widget, without the mouse over top of
6561 # it, and not being pressed etc.
6563 # PRELIGHT - When the mouse is over top of the widget, colors defined
6564 # using this state will be in effect.
6566 # ACTIVE - When the widget is pressed or clicked it will be active, and
6567 # the attributes assigned by this tag will be in effect.
6569 # INSENSITIVE - When a widget is set insensitive, and cannot be
6570 # activated, it will take these attributes.
6572 # SELECTED - When an object is selected, it takes these attributes.
6574 # Given these states, we can set the attributes of the widgets in each of
6575 # these states using the following directives.
6577 # fg - Sets the foreground color of a widget.
6578 # fg - Sets the background color of a widget.
6579 # bg_pixmap - Sets the background of a widget to a tiled pixmap.
6580 # font - Sets the font to be used with the given widget.
6583 # This sets a style called "button". The name is not really important, as
6584 # it is assigned to the actual widgets at the bottom of the file.
6588 #This sets the padding around the window to the pixmap specified.
6589 #bg_pixmap[<STATE>] = "<pixmap filename>"
6590 bg_pixmap[NORMAL] = "warning.xpm"
6595 #Sets the foreground color (font color) to red when in the "NORMAL"
6598 fg[NORMAL] = { 1.0, 0, 0 }
6600 #Sets the background pixmap of this widget to that of it's parent.
6601 bg_pixmap[NORMAL] = "<parent>"
6606 # This shows all the possible states for a button. The only one that
6607 # doesn't apply is the SELECTED state.
6609 fg[PRELIGHT] = { 0, 1.0, 1.0 }
6610 bg[PRELIGHT] = { 0, 0, 1.0 }
6611 bg[ACTIVE] = { 1.0, 0, 0 }
6612 fg[ACTIVE] = { 0, 1.0, 0 }
6613 bg[NORMAL] = { 1.0, 1.0, 0 }
6614 fg[NORMAL] = { .99, 0, .99 }
6615 bg[INSENSITIVE] = { 1.0, 1.0, 1.0 }
6616 fg[INSENSITIVE] = { 1.0, 0, 1.0 }
6619 # In this example, we inherit the attributes of the "button" style and then
6620 # override the font and background color when prelit to create a new
6621 # "main_button" style.
6623 style "main_button" = "button"
6625 font = "-adobe-helvetica-medium-r-normal--*-100-*-*-*-*-*-*"
6626 bg[PRELIGHT] = { 0.75, 0, 0 }
6629 style "toggle_button" = "button"
6631 fg[NORMAL] = { 1.0, 0, 0 }
6632 fg[ACTIVE] = { 1.0, 0, 0 }
6634 # This sets the background pixmap of the toggle_button to that of it's
6635 # parent widget (as defined in the application).
6636 bg_pixmap[NORMAL] = "<parent>"
6641 bg_pixmap[NORMAL] = "marble.xpm"
6642 fg[NORMAL] = { 1.0, 1.0, 1.0 }
6647 font = "-adobe-helvetica-medium-r-normal--*-80-*-*-*-*-*-*"
6650 # pixmap_path "~/.pixmaps"
6652 # These set the widget types to use the styles defined above.
6653 # The widget types are listed in the class hierarchy, but could probably be
6654 # just listed in this document for the users reference.
6656 widget_class "GtkWindow" style "window"
6657 widget_class "GtkDialog" style "window"
6658 widget_class "GtkFileSelection" style "window"
6659 widget_class "*Gtk*Scale" style "scale"
6660 widget_class "*GtkCheckButton*" style "toggle_button"
6661 widget_class "*GtkRadioButton*" style "toggle_button"
6662 widget_class "*GtkButton*" style "button"
6663 widget_class "*Ruler" style "ruler"
6664 widget_class "*GtkText" style "text"
6666 # This sets all the buttons that are children of the "main window" to
6667 # the main_buton style. These must be documented to be taken advantage of.
6668 widget "main window.*GtkButton*" style "main_button"
6671 <!-- ***************************************************************** -->
6672 <sect>Writing Your Own Widgets
6673 <!-- ***************************************************************** -->
6675 <!-- ----------------------------------------------------------------- -->
6678 Although the GTK distribution comes with many types of widgets that
6679 should cover most basic needs, there may come a time when you need to
6680 create your own new widget type. Since GTK uses widget inheretence
6681 extensively, and there is already a widget that
6682 is close to what you want, it is often possible to make a useful new widget type in
6683 just a few lines of code. But before starting work on a new widget, check
6684 around first to make sure that someone has not already written
6685 it. This will prevent duplication of effort and keep the number of
6686 GTK widgets out there to a minimum, which will help keep both the code
6687 and the interface of different applications consistent. As a flip side
6688 to this, once you finish your widget, announce it to the world so
6689 other people can benefit. The best place to do this is probably the
6692 Complete sources for the example widgets are available at the place you
6693 got this tutorial, or from:
6695 <htmlurl url="http://www.msc.cornell.edu/~otaylor/gtk-gimp/tutorial"
6696 name="http://www.msc.cornell.edu/~otaylor/gtk-gimp/tutorial">
6699 <!-- ----------------------------------------------------------------- -->
6700 <sect1> The Anatomy Of A Widget
6703 In order to create a new widget, it is important to have an
6704 understanding of how GTK objects work. This section is just meant as a
6705 brief overview. See the reference documentation for the details.
6708 GTK widgets are implemented in an object oriented fashion. However,
6709 they are implemented in standard C. This greatly improves portability
6710 and stability over using current generation C++ compilers; however,
6711 it does mean that the widget writer has to pay attention to some of
6712 the implementation details. The information common to all instances of
6713 one class of widgets (e.g., to all Button widgets) is stored in the
6714 <em>class structure</em>. There is only one copy of this in
6715 which is stored information about the class's signals
6716 (which act like virtual functions in C). To support inheritance, the
6717 first field in the class structure must be a copy of the parent's
6718 class structure. The declaration of the class structure of GtkButtton
6722 struct _GtkButtonClass
6724 GtkContainerClass parent_class;
6726 void (* pressed) (GtkButton *button);
6727 void (* released) (GtkButton *button);
6728 void (* clicked) (GtkButton *button);
6729 void (* enter) (GtkButton *button);
6730 void (* leave) (GtkButton *button);
6735 When a button is treated as a container (for instance, when it is
6736 resized), its class structure can be casted to GtkContainerClass, and
6737 the relevant fields used to handle the signals.
6740 There is also a structure for each widget that is created on a
6741 per-instance basis. This structure has fields to store information that
6742 is different for each instance of the widget. We'll call this
6743 structure the <em>object structure</em>. For the Button class, it looks
6749 GtkContainer container;
6753 guint in_button : 1;
6754 guint button_down : 1;
6759 Note that, similar to the class structure, the first field is the
6760 object structure of the parent class, so that this structure can be
6761 casted to the parent class's object structure as needed.
6763 <!-- ----------------------------------------------------------------- -->
6764 <sect1> Creating a Composite widget
6766 <!-- ----------------------------------------------------------------- -->
6767 <sect2> Introduction
6770 One type of widget that you may be interested in creating is a
6771 widget that is merely an aggregate of other GTK widgets. This type of
6772 widget does nothing that couldn't be done without creating new
6773 widgets, but provides a convenient way of packaging user interface
6774 elements for reuse. The FileSelection and ColorSelection widgets in
6775 the standard distribution are examples of this type of widget.
6778 The example widget that we'll create in this section is the Tictactoe
6779 widget, a 3x3 array of toggle buttons which triggers a signal when all
6780 three buttons in a row, column, or on one of the diagonals are
6783 <!-- ----------------------------------------------------------------- -->
6784 <sect2> Choosing a parent class
6787 The parent class for a composite widget is typically the container
6788 class that holds all of the elements of the composite widget. For
6789 example, the parent class of the FileSelection widget is the
6790 Dialog class. Since our buttons will be arranged in a table, it
6791 might seem natural to make our parent class the GtkTable
6792 class. Unfortunately, this turns out not to work. The creation of a
6793 widget is divided among two functions - a <tt/WIDGETNAME_new()/
6794 function that the user calls, and a <tt/WIDGETNAME_init()/ function
6795 which does the basic work of initializing the widget which is
6796 independent of the arguments passed to the <tt/_new()/
6797 function. Descendent widgets only call the <tt/_init/ function of
6798 their parent widget. But this division of labor doesn't work well for
6799 tables, which when created, need to know the number of rows and
6800 columns in the table. Unless we want to duplicate most of the
6801 functionality of <tt/gtk_table_new()/ in our Tictactoe widget, we had
6802 best avoid deriving it from GtkTable. For that reason, we derive it
6803 from GtkVBox instead, and stick our table inside the VBox.
6805 <!-- ----------------------------------------------------------------- -->
6806 <sect2> The header file
6809 Each widget class has a header file which declares the object and
6810 class structures for that widget, along with public functions.
6811 A couple of features are worth pointing out. To prevent duplicate
6812 definitions, we wrap the entire header file in:
6815 #ifndef __TICTACTOE_H__
6816 #define __TICTACTOE_H__
6820 #endif /* __TICTACTOE_H__ */
6823 And to keep C++ programs that include the header file happy, in:
6828 #endif /* __cplusplus */
6834 #endif /* __cplusplus */
6837 Along with the functions and structures, we declare three standard
6838 macros in our header file, <tt/TICTACTOE(obj)/,
6839 <tt/TICTACTOE_CLASS(klass)/, and <tt/IS_TICTACTOE(obj)/, which cast a
6840 pointer into a pointer to the the object or class structure, and check
6841 if an object is a Tictactoe widget respectively.
6844 Here is the complete header file:
6849 #ifndef __TICTACTOE_H__
6850 #define __TICTACTOE_H__
6852 #include <gdk/gdk.h>
6853 #include <gtk/gtkvbox.h>
6857 #endif /* __cplusplus */
6859 #define TICTACTOE(obj) GTK_CHECK_CAST (obj, tictactoe_get_type (), Tictactoe)
6860 #define TICTACTOE_CLASS(klass) GTK_CHECK_CLASS_CAST (klass, tictactoe_get_type (), TictactoeClass)
6861 #define IS_TICTACTOE(obj) GTK_CHECK_TYPE (obj, tictactoe_get_type ())
6864 typedef struct _Tictactoe Tictactoe;
6865 typedef struct _TictactoeClass TictactoeClass;
6871 GtkWidget *buttons[3][3];
6874 struct _TictactoeClass
6876 GtkVBoxClass parent_class;
6878 void (* tictactoe) (Tictactoe *ttt);
6881 guint tictactoe_get_type (void);
6882 GtkWidget* tictactoe_new (void);
6883 void tictactoe_clear (Tictactoe *ttt);
6887 #endif /* __cplusplus */
6889 #endif /* __TICTACTOE_H__ */
6893 <!-- ----------------------------------------------------------------- -->
6894 <sect2> The <tt/_get_type()/ function.
6897 We now continue on to the implementation of our widget. A core
6898 function for every widget is the function
6899 <tt/WIDGETNAME_get_type()/. This function, when first called, tells
6900 GTK about the widget class, and gets an ID that uniquely identifies
6901 the widget class. Upon subsequent calls, it just returns the ID.
6905 tictactoe_get_type ()
6907 static guint ttt_type = 0;
6911 GtkTypeInfo ttt_info =
6915 sizeof (TictactoeClass),
6916 (GtkClassInitFunc) tictactoe_class_init,
6917 (GtkObjectInitFunc) tictactoe_init,
6921 ttt_type = gtk_type_unique (gtk_vbox_get_type (), &ttt_info);
6929 The GtkTypeInfo structure has the following definition:
6937 GtkClassInitFunc class_init_func;
6938 GtkObjectInitFunc object_init_func;
6939 GtkArgFunc arg_func;
6944 The fields of this structure are pretty self-explanatory. We'll ignore
6945 the <tt/arg_func/ field here: It has an important, but as yet largely
6946 unimplemented, role in allowing widget options to be conveniently set
6947 from interpreted languages. Once GTK has a correctly filled in copy of
6948 this structure, it knows how to create objects of a particular widget
6951 <!-- ----------------------------------------------------------------- -->
6952 <sect2> The <tt/_class_init()/ function
6955 The <tt/WIDGETNAME_class_init()/ function initializes the fields of
6956 the widget's class structure, and sets up any signals for the
6957 class. For our Tictactoe widget it looks like:
6966 static gint tictactoe_signals[LAST_SIGNAL] = { 0 };
6969 tictactoe_class_init (TictactoeClass *class)
6971 GtkObjectClass *object_class;
6973 object_class = (GtkObjectClass*) class;
6975 tictactoe_signals[TICTACTOE_SIGNAL] = gtk_signal_new ("tictactoe",
6978 GTK_SIGNAL_OFFSET (TictactoeClass, tictactoe),
6979 gtk_signal_default_marshaller, GTK_ARG_NONE, 0);
6982 gtk_object_class_add_signals (object_class, tictactoe_signals, LAST_SIGNAL);
6984 class->tictactoe = NULL;
6989 Our widget has just one signal, the ``tictactoe'' signal that is
6990 invoked when a row, column, or diagonal is completely filled in. Not
6991 every composite widget needs signals, so if you are reading this for
6992 the first time, you may want to skip to the next section now, as
6993 things are going to get a bit complicated.
6998 gint gtk_signal_new (gchar *name,
6999 GtkSignalRunType run_type,
7001 gint function_offset,
7002 GtkSignalMarshaller marshaller,
7003 GtkArgType return_val,
7008 Creates a new signal. The parameters are:
7011 <item> <tt/name/: The name of the signal.
7012 <item> <tt/run_type/: Whether the default handler runs before or after
7013 user handlers. Usually this will be <tt/GTK_RUN_FIRST/, or <tt/GTK_RUN_LAST/,
7014 although there are other possibilities.
7015 <item> <tt/object_type/: The ID of the object that this signal applies
7016 to. (It will also apply to that objects descendents)
7017 <item> <tt/function_offset/: The offset within the class structure of
7018 a pointer to the default handler.
7019 <item> <tt/marshaller/: A function that is used to invoke the signal
7020 handler. For signal handlers that have no arguments other than the
7021 object that emitted the signal and user data, we can use the
7022 presupplied marshaller function <tt/gtk_signal_default_marshaller/.
7023 <item> <tt/return_val/: The type of the return val.
7024 <item> <tt/nparams/: The number of parameters of the signal handler
7025 (other than the two default ones mentioned above)
7026 <item> <tt/.../: The types of the parameters.
7029 When specifying types, the <tt/GtkArgType/ enumeration is used:
7048 <tt/gtk_signal_new()/ returns a unique integer identifier for the
7049 signal, that we store in the <tt/tictactoe_signals/ array, which we
7050 index using an enumeration. (Conventionally, the enumeration elements
7051 are the signal name, uppercased, but here there would be a conflict
7052 with the <tt/TICTACTOE()/ macro, so we called it <tt/TICTACTOE_SIGNAL/
7055 After creating our signals, we need to tell GTK to associate our
7056 signals with the Tictactoe class. We do that by calling
7057 <tt/gtk_object_class_add_signals()/. We then set the pointer which
7058 points to the default handler for the ``tictactoe'' signal to NULL,
7059 indicating that there is no default action.
7061 <!-- ----------------------------------------------------------------- -->
7062 <sect2> The <tt/_init()/ function.
7066 Each widget class also needs a function to initialize the object
7067 structure. Usually, this function has the fairly limited role of
7068 setting the fields of the structure to default values. For composite
7069 widgets, however, this function also creates the component widgets.
7074 tictactoe_init (Tictactoe *ttt)
7079 table = gtk_table_new (3, 3, TRUE);
7080 gtk_container_add (GTK_CONTAINER(ttt), table);
7081 gtk_widget_show (table);
7086 ttt->buttons[i][j] = gtk_toggle_button_new ();
7087 gtk_table_attach_defaults (GTK_TABLE(table), ttt->buttons[i][j],
7089 gtk_signal_connect (GTK_OBJECT (ttt->buttons[i][j]), "toggled",
7090 GTK_SIGNAL_FUNC (tictactoe_toggle), ttt);
7091 gtk_widget_set_usize (ttt->buttons[i][j], 20, 20);
7092 gtk_widget_show (ttt->buttons[i][j]);
7097 <!-- ----------------------------------------------------------------- -->
7098 <sect2> And the rest...
7102 There is one more function that every widget (except for base widget
7103 types like GtkBin that cannot be instantiated) needs to have - the
7104 function that the user calls to create an object of that type. This is
7105 conventionally called <tt/WIDGETNAME_new()/In some
7106 widgets, thought not for the Tictactoe widgets, this function takes
7107 arguments, and does some setup based on the arguments. The other two
7108 functions are specific to the Tictactoe widget.
7111 <tt/tictactoe_clear()/ is a public function that resets all the
7112 buttons in the widget to the up position. Note the use of
7113 <tt/gtk_signal_handler_block_by_data()/ to keep our signal handler for
7114 button toggles from being triggered unnecessarily.
7117 <tt/tictactoe_toggle()/ is the signal handler that is invoked when the
7118 user clicks on a button. It checks to see if there are any winning
7119 combinations that involve the toggled button, and if so, emits
7120 the "tictactoe" signal.
7126 return GTK_WIDGET ( gtk_type_new (tictactoe_get_type ()));
7130 tictactoe_clear (Tictactoe *ttt)
7137 gtk_signal_handler_block_by_data (GTK_OBJECT(ttt->buttons[i][j]), ttt);
7138 gtk_toggle_button_set_state (GTK_TOGGLE_BUTTON (ttt->buttons[i][j]),
7140 gtk_signal_handler_unblock_by_data (GTK_OBJECT(ttt->buttons[i][j]), ttt);
7145 tictactoe_toggle (GtkWidget *widget, Tictactoe *ttt)
7149 static int rwins[8][3] = { { 0, 0, 0 }, { 1, 1, 1 }, { 2, 2, 2 },
7150 { 0, 1, 2 }, { 0, 1, 2 }, { 0, 1, 2 },
7151 { 0, 1, 2 }, { 0, 1, 2 } };
7152 static int cwins[8][3] = { { 0, 1, 2 }, { 0, 1, 2 }, { 0, 1, 2 },
7153 { 0, 0, 0 }, { 1, 1, 1 }, { 2, 2, 2 },
7154 { 0, 1, 2 }, { 2, 1, 0 } };
7165 success = success &&
7166 GTK_TOGGLE_BUTTON(ttt->buttons[rwins[k][i]][cwins[k][i]])->active;
7168 ttt->buttons[rwins[k][i]][cwins[k][i]] == widget;
7171 if (success && found)
7173 gtk_signal_emit (GTK_OBJECT (ttt),
7174 tictactoe_signals[TICTACTOE_SIGNAL]);
7183 And finally, an example program using our Tictactoe widget:
7186 #include <gtk/gtk.h>
7187 #include "tictactoe.h"
7189 /* Invoked when a row, column or diagonal is completed */
7191 win (GtkWidget *widget, gpointer data)
7194 tictactoe_clear (TICTACTOE (widget));
7198 main (int argc, char *argv[])
7203 gtk_init (&argc, &argv);
7205 window = gtk_window_new (GTK_WINDOW_TOPLEVEL);
7207 gtk_window_set_title (GTK_WINDOW (window), "Aspect Frame");
7209 gtk_signal_connect (GTK_OBJECT (window), "destroy",
7210 GTK_SIGNAL_FUNC (gtk_exit), NULL);
7212 gtk_container_border_width (GTK_CONTAINER (window), 10);
7214 /* Create a new Tictactoe widget */
7215 ttt = tictactoe_new ();
7216 gtk_container_add (GTK_CONTAINER (window), ttt);
7217 gtk_widget_show (ttt);
7219 /* And attach to its "tictactoe" signal */
7220 gtk_signal_connect (GTK_OBJECT (ttt), "tictactoe",
7221 GTK_SIGNAL_FUNC (win), NULL);
7223 gtk_widget_show (window);
7232 <!-- ----------------------------------------------------------------- -->
7233 <sect1> Creating a widget from scratch.
7235 <!-- ----------------------------------------------------------------- -->
7236 <sect2> Introduction
7240 In this section, we'll learn more about how widgets display themselves
7241 on the screen and interact with events. As an example of this, we'll
7242 create a analog dial widget with a pointer that the user can drag to
7245 <!-- ----------------------------------------------------------------- -->
7246 <sect2> Displaying a widget on the screen
7249 There are several steps that are involved in displaying on the screen.
7250 After the widget is created with a call to <tt/WIDGETNAME_new()/,
7251 several more functions are needed:
7254 <item> <tt/WIDGETNAME_realize()/ is responsible for creating an X
7255 window for the widget if it has one.
7256 <item> <tt/WIDGETNAME_map()/ is invoked after the user calls
7257 <tt/gtk_widget_show()/. It is responsible for making sure the widget
7258 is actually drawn on the screen (<em/mapped/). For a container class,
7259 it must also make calls to <tt/map()/> functions of any child widgets.
7260 <item> <tt/WIDGETNAME_draw()/ is invoked when <tt/gtk_widget_draw()/
7261 is called for the widget or one of its ancestors. It makes the actual
7262 calls to the drawing functions to draw the widget on the screen. For
7263 container widgets, this function must make calls to
7264 <tt/gtk_widget_draw()/ for its child widgets.
7265 <item> <tt/WIDGETNAME_expose()/ is a handler for expose events for the
7266 widget. It makes the necessary calls to the drawing functions to draw
7267 the exposed portion on the screen. For container widgets, this
7268 function must generate expose events for its child widgets which don't
7269 have their own windows. (If they have their own windows, then X will
7270 generate the necessary expose events)
7274 You might notice that the last two functions are quite similar - each
7275 is responsible for drawing the widget on the screen. In fact many
7276 types of widgets don't really care about the difference between the
7277 two. The default <tt/draw()/ function in the widget class simply
7278 generates a synthetic expose event for the redrawn area. However, some
7279 types of widgets can save work by distinguishing between the two
7280 functions. For instance, if a widget has multiple X windows, then
7281 since expose events identify the exposed window, it can redraw only
7282 the affected window, which is not possible for calls to <tt/draw()/.
7285 Container widgets, even if they don't care about the difference for
7286 themselves, can't simply use the default <tt/draw()/ function because
7287 their child widgets might care about the difference. However,
7288 it would be wasteful to duplicate the drawing code between the two
7289 functions. The convention is that such widgets have a function called
7290 <tt/WIDGETNAME_paint()/ that does the actual work of drawing the
7291 widget, that is then called by the <tt/draw()/ and <tt/expose()/
7295 In our example approach, since the dial widget is not a container
7296 widget, and only has a single window, we can take the simplest
7297 approach and use the default <tt/draw()/ function and only implement
7298 an <tt/expose()/ function.
7300 <!-- ----------------------------------------------------------------- -->
7301 <sect2> The origins of the Dial Widget
7304 Just as all land animals are just variants on the first amphibian that
7305 crawled up out of the mud, Gtk widgets tend to start off as variants
7306 of some other, previously written widget. Thus, although this section
7307 is entilted ``Creating a Widget from Scratch'', the Dial widget really
7308 began with the source code for the Range widget. This was picked as a
7309 starting point because it would be nice if our Dial had the same
7310 interface as the Scale widgets which are just specialized descendents
7311 of the Range widget. So, though the source code is presented below in
7312 finished form, it should not be implied that it was written, <em>deus
7313 ex machina</em> in this fashion. Also, if you aren't yet familiar with
7314 how scale widgets work from the application writer's point of view, it
7315 would be a good idea to look them over before continuing.
7317 <!-- ----------------------------------------------------------------- -->
7321 Quite a bit of our widget should look pretty familiar from the
7322 Tictactoe widget. First, we have a header file:
7325 /* GTK - The GIMP Toolkit
7326 * Copyright (C) 1995-1997 Peter Mattis, Spencer Kimball and Josh MacDonald
7328 * This library is free software; you can redistribute it and/or
7329 * modify it under the terms of the GNU Library General Public
7330 * License as published by the Free Software Foundation; either
7331 * version 2 of the License, or (at your option) any later version.
7333 * This library is distributed in the hope that it will be useful,
7334 * but WITHOUT ANY WARRANTY; without even the implied warranty of
7335 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
7336 * Library General Public License for more details.
7338 * You should have received a copy of the GNU Library General Public
7339 * License along with this library; if not, write to the Free
7340 * Software Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
7343 #ifndef __GTK_DIAL_H__
7344 #define __GTK_DIAL_H__
7346 #include <gdk/gdk.h>
7347 #include <gtk/gtkadjustment.h>
7348 #include <gtk/gtkwidget.h>
7353 #endif /* __cplusplus */
7356 #define GTK_DIAL(obj) GTK_CHECK_CAST (obj, gtk_dial_get_type (), GtkDial)
7357 #define GTK_DIAL_CLASS(klass) GTK_CHECK_CLASS_CAST (klass, gtk_dial_get_type (), GtkDialClass)
7358 #define GTK_IS_DIAL(obj) GTK_CHECK_TYPE (obj, gtk_dial_get_type ())
7361 typedef struct _GtkDial GtkDial;
7362 typedef struct _GtkDialClass GtkDialClass;
7368 /* update policy (GTK_UPDATE_[CONTINUOUS/DELAYED/DISCONTINUOUS]) */
7371 /* Button currently pressed or 0 if none */
7374 /* Dimensions of dial components */
7378 /* ID of update timer, or 0 if none */
7384 /* Old values from adjustment stored so we know when something changes */
7389 /* The adjustment object that stores the data for this dial */
7390 GtkAdjustment *adjustment;
7393 struct _GtkDialClass
7395 GtkWidgetClass parent_class;
7399 GtkWidget* gtk_dial_new (GtkAdjustment *adjustment);
7400 guint gtk_dial_get_type (void);
7401 GtkAdjustment* gtk_dial_get_adjustment (GtkDial *dial);
7402 void gtk_dial_set_update_policy (GtkDial *dial,
7403 GtkUpdateType policy);
7405 void gtk_dial_set_adjustment (GtkDial *dial,
7406 GtkAdjustment *adjustment);
7409 #endif /* __cplusplus */
7412 #endif /* __GTK_DIAL_H__ */
7416 Since there is quite a bit more going on in this widget, than the last
7417 one, we have more fields in the data structure, but otherwise things
7422 Next, after including header files, and declaring a few constants,
7423 we have some functions to provide information about the widget
7429 #include <gtk/gtkmain.h>
7430 #include <gtk/gtksignal.h>
7432 #include "gtkdial.h"
7434 #define SCROLL_DELAY_LENGTH 300
7435 #define DIAL_DEFAULT_SIZE 100
7437 /* Forward declararations */
7439 [ omitted to save space ]
7443 static GtkWidgetClass *parent_class = NULL;
7446 gtk_dial_get_type ()
7448 static guint dial_type = 0;
7452 GtkTypeInfo dial_info =
7456 sizeof (GtkDialClass),
7457 (GtkClassInitFunc) gtk_dial_class_init,
7458 (GtkObjectInitFunc) gtk_dial_init,
7462 dial_type = gtk_type_unique (gtk_widget_get_type (), &dial_info);
7469 gtk_dial_class_init (GtkDialClass *class)
7471 GtkObjectClass *object_class;
7472 GtkWidgetClass *widget_class;
7474 object_class = (GtkObjectClass*) class;
7475 widget_class = (GtkWidgetClass*) class;
7477 parent_class = gtk_type_class (gtk_widget_get_type ());
7479 object_class->destroy = gtk_dial_destroy;
7481 widget_class->realize = gtk_dial_realize;
7482 widget_class->expose_event = gtk_dial_expose;
7483 widget_class->size_request = gtk_dial_size_request;
7484 widget_class->size_allocate = gtk_dial_size_allocate;
7485 widget_class->button_press_event = gtk_dial_button_press;
7486 widget_class->button_release_event = gtk_dial_button_release;
7487 widget_class->motion_notify_event = gtk_dial_motion_notify;
7491 gtk_dial_init (GtkDial *dial)
7494 dial->policy = GTK_UPDATE_CONTINUOUS;
7497 dial->pointer_width = 0;
7499 dial->old_value = 0.0;
7500 dial->old_lower = 0.0;
7501 dial->old_upper = 0.0;
7502 dial->adjustment = NULL;
7506 gtk_dial_new (GtkAdjustment *adjustment)
7510 dial = gtk_type_new (gtk_dial_get_type ());
7513 adjustment = (GtkAdjustment*) gtk_adjustment_new (0.0, 0.0, 0.0, 0.0, 0.0, 0.0);
7515 gtk_dial_set_adjustment (dial, adjustment);
7517 return GTK_WIDGET (dial);
7521 gtk_dial_destroy (GtkObject *object)
7525 g_return_if_fail (object != NULL);
7526 g_return_if_fail (GTK_IS_DIAL (object));
7528 dial = GTK_DIAL (object);
7530 if (dial->adjustment)
7531 gtk_object_unref (GTK_OBJECT (dial->adjustment));
7533 if (GTK_OBJECT_CLASS (parent_class)->destroy)
7534 (* GTK_OBJECT_CLASS (parent_class)->destroy) (object);
7538 Note that this <tt/init()/ function does less than for the Tictactoe
7539 widget, since this is not a composite widget, and the <tt/new()/
7540 function does more, since it now has an argument. Also, note that when
7541 we store a pointer to the Adjustment object, we increment its
7542 reference count, (and correspondingly decrement when we no longer use
7543 it) so that GTK can keep track of when it can be safely destroyed.
7546 Also, there are a few function to manipulate the widget's options:
7550 gtk_dial_get_adjustment (GtkDial *dial)
7552 g_return_val_if_fail (dial != NULL, NULL);
7553 g_return_val_if_fail (GTK_IS_DIAL (dial), NULL);
7555 return dial->adjustment;
7559 gtk_dial_set_update_policy (GtkDial *dial,
7560 GtkUpdateType policy)
7562 g_return_if_fail (dial != NULL);
7563 g_return_if_fail (GTK_IS_DIAL (dial));
7565 dial->policy = policy;
7569 gtk_dial_set_adjustment (GtkDial *dial,
7570 GtkAdjustment *adjustment)
7572 g_return_if_fail (dial != NULL);
7573 g_return_if_fail (GTK_IS_DIAL (dial));
7575 if (dial->adjustment)
7577 gtk_signal_disconnect_by_data (GTK_OBJECT (dial->adjustment), (gpointer) dial);
7578 gtk_object_unref (GTK_OBJECT (dial->adjustment));
7581 dial->adjustment = adjustment;
7582 gtk_object_ref (GTK_OBJECT (dial->adjustment));
7584 gtk_signal_connect (GTK_OBJECT (adjustment), "changed",
7585 (GtkSignalFunc) gtk_dial_adjustment_changed,
7587 gtk_signal_connect (GTK_OBJECT (adjustment), "value_changed",
7588 (GtkSignalFunc) gtk_dial_adjustment_value_changed,
7591 dial->old_value = adjustment->value;
7592 dial->old_lower = adjustment->lower;
7593 dial->old_upper = adjustment->upper;
7595 gtk_dial_update (dial);
7599 <sect2> <tt/gtk_dial_realize()/
7602 Now we come to some new types of functions. First, we have a function
7603 that does the work of creating the X window. Notice that a mask is
7604 passed to the function <tt/gdk_window_new()/ which specifies which fields of
7605 the GdkWindowAttr structure actually have data in them (the remaining
7606 fields wll be given default values). Also worth noting is the way the
7607 event mask of the widget is created. We call
7608 <tt/gtk_widget_get_events()/ to retrieve the event mask that the user
7609 has specified for this widget (with <tt/gtk_widget_set_events()/, and
7610 add the events that we are interested in ourselves.
7613 After creating the window, we set its style and background, and put a
7614 pointer to the widget in the user data field of the GdkWindow. This
7615 last step allows GTK to dispatch events for this window to the correct
7620 gtk_dial_realize (GtkWidget *widget)
7623 GdkWindowAttr attributes;
7624 gint attributes_mask;
7626 g_return_if_fail (widget != NULL);
7627 g_return_if_fail (GTK_IS_DIAL (widget));
7629 GTK_WIDGET_SET_FLAGS (widget, GTK_REALIZED);
7630 dial = GTK_DIAL (widget);
7632 attributes.x = widget->allocation.x;
7633 attributes.y = widget->allocation.y;
7634 attributes.width = widget->allocation.width;
7635 attributes.height = widget->allocation.height;
7636 attributes.wclass = GDK_INPUT_OUTPUT;
7637 attributes.window_type = GDK_WINDOW_CHILD;
7638 attributes.event_mask = gtk_widget_get_events (widget) |
7639 GDK_EXPOSURE_MASK | GDK_BUTTON_PRESS_MASK |
7640 GDK_BUTTON_RELEASE_MASK | GDK_POINTER_MOTION_MASK |
7641 GDK_POINTER_MOTION_HINT_MASK;
7642 attributes.visual = gtk_widget_get_visual (widget);
7643 attributes.colormap = gtk_widget_get_colormap (widget);
7645 attributes_mask = GDK_WA_X | GDK_WA_Y | GDK_WA_VISUAL | GDK_WA_COLORMAP;
7646 widget->window = gdk_window_new (widget->parent->window, &attributes, attributes_mask);
7648 widget->style = gtk_style_attach (widget->style, widget->window);
7650 gdk_window_set_user_data (widget->window, widget);
7652 gtk_style_set_background (widget->style, widget->window, GTK_STATE_ACTIVE);
7656 <sect2> Size negotiation
7659 Before the first time that the window containing a widget is
7660 displayed, and whenever the layout of the window changes, GTK asks
7661 each child widget for its desired size. This request is handled by the
7662 function, <tt/gtk_dial_size_request()/. Since our widget isn't a
7663 container widget, and has no real constraints on its size, we just
7664 return a reasonable default value.
7668 gtk_dial_size_request (GtkWidget *widget,
7669 GtkRequisition *requisition)
7671 requisition->width = DIAL_DEFAULT_SIZE;
7672 requisition->height = DIAL_DEFAULT_SIZE;
7677 After all the widgets have requested an ideal size, the layout of the
7678 window is computed and each child widget is notified of its actual
7679 size. Usually, this will at least as large as the requested size, but
7680 if for instance, the user has resized the window, it may occasionally
7681 be smaller than the requested size. The size notification is handled
7682 by the function <tt/gtk_dial_size_allocate()/. Notice that as well as
7683 computing the sizes of some component pieces for future use, this
7684 routine also does the grunt work of moving the widgets X window into
7685 the new position and size.
7689 gtk_dial_size_allocate (GtkWidget *widget,
7690 GtkAllocation *allocation)
7694 g_return_if_fail (widget != NULL);
7695 g_return_if_fail (GTK_IS_DIAL (widget));
7696 g_return_if_fail (allocation != NULL);
7698 widget->allocation = *allocation;
7699 if (GTK_WIDGET_REALIZED (widget))
7701 dial = GTK_DIAL (widget);
7703 gdk_window_move_resize (widget->window,
7704 allocation->x, allocation->y,
7705 allocation->width, allocation->height);
7707 dial->radius = MAX(allocation->width,allocation->height) * 0.45;
7708 dial->pointer_width = dial->radius / 5;
7713 <!-- ----------------------------------------------------------------- -->
7714 <sect2> <tt/gtk_dial_expose()/
7717 As mentioned above, all the drawing of this widget is done in the
7718 handler for expose events. There's not much to remark on here except
7719 the use of the function <tt/gtk_draw_polygon/ to draw the pointer with
7720 three dimensional shading according to the colors stored in the
7725 gtk_dial_expose (GtkWidget *widget,
7726 GdkEventExpose *event)
7736 g_return_val_if_fail (widget != NULL, FALSE);
7737 g_return_val_if_fail (GTK_IS_DIAL (widget), FALSE);
7738 g_return_val_if_fail (event != NULL, FALSE);
7740 if (event->count > 0)
7743 dial = GTK_DIAL (widget);
7745 gdk_window_clear_area (widget->window,
7747 widget->allocation.width,
7748 widget->allocation.height);
7750 xc = widget->allocation.width/2;
7751 yc = widget->allocation.height/2;
7755 for (i=0; i<25; i++)
7757 theta = (i*M_PI/18. - M_PI/6.);
7761 tick_length = (i%6 == 0) ? dial->pointer_width : dial->pointer_width/2;
7763 gdk_draw_line (widget->window,
7764 widget->style->fg_gc[widget->state],
7765 xc + c*(dial->radius - tick_length),
7766 yc - s*(dial->radius - tick_length),
7767 xc + c*dial->radius,
7768 yc - s*dial->radius);
7773 s = sin(dial->angle);
7774 c = cos(dial->angle);
7777 points[0].x = xc + s*dial->pointer_width/2;
7778 points[0].y = yc + c*dial->pointer_width/2;
7779 points[1].x = xc + c*dial->radius;
7780 points[1].y = yc - s*dial->radius;
7781 points[2].x = xc - s*dial->pointer_width/2;
7782 points[2].y = yc - c*dial->pointer_width/2;
7784 gtk_draw_polygon (widget->style,
7795 <!-- ----------------------------------------------------------------- -->
7796 <sect2> Event handling
7800 The rest of the widget's code handles various types of events, and
7801 isn't too different from what would be found in many GTK
7802 applications. Two types of events can occur - either the user can
7803 click on the widget with the mouse and drag to move the pointer, or
7804 the value of the Adjustment object can change due to some external
7808 When the user clicks on the widget, we check to see if the click was
7809 appropriately near the pointer, and if so, store then button that the
7810 user clicked with in the <tt/button/ field of the widget
7811 structure, and grab all mouse events with a call to
7812 <tt/gtk_grab_add()/. Subsequent motion of the mouse causes the
7813 value of the control to be recomputed (by the function
7814 <tt/gtk_dial_update_mouse/). Depending on the policy that has been
7815 set, "value_changed" events are either generated instantly
7816 (<tt/GTK_UPDATE_CONTINUOUS/), after a delay in a timer added with
7817 <tt/gtk_timeout_add()/ (<tt/GTK_UPDATE_DELAYED/), or only when the
7818 button is released (<tt/GTK_UPDATE_DISCONTINUOUS/).
7822 gtk_dial_button_press (GtkWidget *widget,
7823 GdkEventButton *event)
7829 double d_perpendicular;
7831 g_return_val_if_fail (widget != NULL, FALSE);
7832 g_return_val_if_fail (GTK_IS_DIAL (widget), FALSE);
7833 g_return_val_if_fail (event != NULL, FALSE);
7835 dial = GTK_DIAL (widget);
7837 /* Determine if button press was within pointer region - we
7838 do this by computing the parallel and perpendicular distance of
7839 the point where the mouse was pressed from the line passing through
7842 dx = event->x - widget->allocation.width / 2;
7843 dy = widget->allocation.height / 2 - event->y;
7845 s = sin(dial->angle);
7846 c = cos(dial->angle);
7848 d_parallel = s*dy + c*dx;
7849 d_perpendicular = fabs(s*dx - c*dy);
7851 if (!dial->button &&
7852 (d_perpendicular < dial->pointer_width/2) &&
7853 (d_parallel > - dial->pointer_width))
7855 gtk_grab_add (widget);
7857 dial->button = event->button;
7859 gtk_dial_update_mouse (dial, event->x, event->y);
7866 gtk_dial_button_release (GtkWidget *widget,
7867 GdkEventButton *event)
7871 g_return_val_if_fail (widget != NULL, FALSE);
7872 g_return_val_if_fail (GTK_IS_DIAL (widget), FALSE);
7873 g_return_val_if_fail (event != NULL, FALSE);
7875 dial = GTK_DIAL (widget);
7877 if (dial->button == event->button)
7879 gtk_grab_remove (widget);
7883 if (dial->policy == GTK_UPDATE_DELAYED)
7884 gtk_timeout_remove (dial->timer);
7886 if ((dial->policy != GTK_UPDATE_CONTINUOUS) &&
7887 (dial->old_value != dial->adjustment->value))
7888 gtk_signal_emit_by_name (GTK_OBJECT (dial->adjustment), "value_changed");
7895 gtk_dial_motion_notify (GtkWidget *widget,
7896 GdkEventMotion *event)
7899 GdkModifierType mods;
7902 g_return_val_if_fail (widget != NULL, FALSE);
7903 g_return_val_if_fail (GTK_IS_DIAL (widget), FALSE);
7904 g_return_val_if_fail (event != NULL, FALSE);
7906 dial = GTK_DIAL (widget);
7908 if (dial->button != 0)
7913 if (event->is_hint || (event->window != widget->window))
7914 gdk_window_get_pointer (widget->window, &x, &y, &mods);
7916 switch (dial->button)
7919 mask = GDK_BUTTON1_MASK;
7922 mask = GDK_BUTTON2_MASK;
7925 mask = GDK_BUTTON3_MASK;
7933 gtk_dial_update_mouse (dial, x,y);
7940 gtk_dial_timer (GtkDial *dial)
7942 g_return_val_if_fail (dial != NULL, FALSE);
7943 g_return_val_if_fail (GTK_IS_DIAL (dial), FALSE);
7945 if (dial->policy == GTK_UPDATE_DELAYED)
7946 gtk_signal_emit_by_name (GTK_OBJECT (dial->adjustment), "value_changed");
7952 gtk_dial_update_mouse (GtkDial *dial, gint x, gint y)
7957 g_return_if_fail (dial != NULL);
7958 g_return_if_fail (GTK_IS_DIAL (dial));
7960 xc = GTK_WIDGET(dial)->allocation.width / 2;
7961 yc = GTK_WIDGET(dial)->allocation.height / 2;
7963 old_value = dial->adjustment->value;
7964 dial->angle = atan2(yc-y, x-xc);
7966 if (dial->angle < -M_PI/2.)
7967 dial->angle += 2*M_PI;
7969 if (dial->angle < -M_PI/6)
7970 dial->angle = -M_PI/6;
7972 if (dial->angle > 7.*M_PI/6.)
7973 dial->angle = 7.*M_PI/6.;
7975 dial->adjustment->value = dial->adjustment->lower + (7.*M_PI/6 - dial->angle) *
7976 (dial->adjustment->upper - dial->adjustment->lower) / (4.*M_PI/3.);
7978 if (dial->adjustment->value != old_value)
7980 if (dial->policy == GTK_UPDATE_CONTINUOUS)
7982 gtk_signal_emit_by_name (GTK_OBJECT (dial->adjustment), "value_changed");
7986 gtk_widget_draw (GTK_WIDGET(dial), NULL);
7988 if (dial->policy == GTK_UPDATE_DELAYED)
7991 gtk_timeout_remove (dial->timer);
7993 dial->timer = gtk_timeout_add (SCROLL_DELAY_LENGTH,
7994 (GtkFunction) gtk_dial_timer,
8003 Changes to the Adjustment by external means are communicated to our
8004 widget by the ``changed'' and ``value_changed'' signals. The handlers
8005 for these functions call <tt/gtk_dial_update()/ to validate the
8006 arguments, compute the new pointer angle, and redraw the widget (by
8007 calling <tt/gtk_widget_draw()/).
8011 gtk_dial_update (GtkDial *dial)
8015 g_return_if_fail (dial != NULL);
8016 g_return_if_fail (GTK_IS_DIAL (dial));
8018 new_value = dial->adjustment->value;
8020 if (new_value < dial->adjustment->lower)
8021 new_value = dial->adjustment->lower;
8023 if (new_value > dial->adjustment->upper)
8024 new_value = dial->adjustment->upper;
8026 if (new_value != dial->adjustment->value)
8028 dial->adjustment->value = new_value;
8029 gtk_signal_emit_by_name (GTK_OBJECT (dial->adjustment), "value_changed");
8032 dial->angle = 7.*M_PI/6. - (new_value - dial->adjustment->lower) * 4.*M_PI/3. /
8033 (dial->adjustment->upper - dial->adjustment->lower);
8035 gtk_widget_draw (GTK_WIDGET(dial), NULL);
8039 gtk_dial_adjustment_changed (GtkAdjustment *adjustment,
8044 g_return_if_fail (adjustment != NULL);
8045 g_return_if_fail (data != NULL);
8047 dial = GTK_DIAL (data);
8049 if ((dial->old_value != adjustment->value) ||
8050 (dial->old_lower != adjustment->lower) ||
8051 (dial->old_upper != adjustment->upper))
8053 gtk_dial_update (dial);
8055 dial->old_value = adjustment->value;
8056 dial->old_lower = adjustment->lower;
8057 dial->old_upper = adjustment->upper;
8062 gtk_dial_adjustment_value_changed (GtkAdjustment *adjustment,
8067 g_return_if_fail (adjustment != NULL);
8068 g_return_if_fail (data != NULL);
8070 dial = GTK_DIAL (data);
8072 if (dial->old_value != adjustment->value)
8074 gtk_dial_update (dial);
8076 dial->old_value = adjustment->value;
8081 <!-- ----------------------------------------------------------------- -->
8082 <sect2> Possible Enhancements
8086 The Dial widget as we've described it so far runs about 670 lines of
8087 code. Although that might sound like a fair bit, we've really
8088 accomplished quite a bit with that much code, especially since much of
8089 that length is headers and boilerplate. However, there are quite a few
8090 more enhancements that could be made to this widget:
8093 <item> If you try this widget out, you'll find that there is some
8094 flashing as the pointer is dragged around. This is because the entire
8095 widget is erased every time the pointer is moved before being
8096 redrawn. Often, the best way to handle this problem is to draw to an
8097 offscreen pixmap, then copy the final results onto the screen in one
8098 step. (The ProgressBar widget draws itself in this fashion.)
8100 <item> The user should be able to use the up and down arrow keys to
8101 increase and decrease the value.
8103 <item> It would be nice if the widget had buttons to increase and
8104 decrease the value in small or large steps. Although it would be
8105 possible to use embedded Button widgets for this, we would also like
8106 the buttons to auto-repeat when held down, as the arrows on a
8107 scrollbar do. Most of the code to implement this type of behavior can
8108 be found in the GtkRange widget.
8110 <item> The Dial widget could be made into a container widget with a
8111 single child widget positioned at the bottom between the buttons
8112 mentioned above. The user could then add their choice of a label or
8113 entry widget to display the current value of the dial.
8117 <!-- ----------------------------------------------------------------- -->
8118 <sect1> Learning More
8121 Only a small part of the many details involved in creating widgets
8122 could be described above. If you want to write your own widgets, the
8123 best source of examples is the GTK source itself. Ask yourself some
8124 questions about the widget you want to write: is it a Container
8125 widget? does it have its own window? is it a modification of an
8126 existing widget? Then find a similar widget, and start making changes.
8129 <!-- ***************************************************************** -->
8130 <sect>Scribble, A Simple Example Drawing Program
8131 <!-- ***************************************************************** -->
8133 <!-- ----------------------------------------------------------------- -->
8137 In this section, we will build a simple drawing program. In the
8138 process, we will examine how to handle mouse events, how to draw in a
8139 window, and how to do drawing better by using a backing pixmap. After
8140 creating the simple drawing program, we will extend it by adding
8141 support for XInput devices, such as drawing tablets. GTK provides
8142 support routines which makes getting extended information, such as
8143 pressure and tilt, from such devices quite easy.
8145 <!-- ----------------------------------------------------------------- -->
8146 <sect1> Event Handling
8149 The GTK signals we have already discussed are for high-level actions,
8150 such as a menu item being selected. However, sometimes it is useful to
8151 learn about lower-level occurrences, such as the mouse being moved, or
8152 a key being pressed. There are also GTK signals corresponding to these
8153 low-level <em>events</em>. The handlers for these signals have an
8154 extra parameter which is a pointer to a structure containing
8155 information about the event. For instance, motion events handlers are
8156 passed a pointer to a GdkEventMotion structure which looks (in part)
8160 struct _GdkEventMotion
8173 <tt/type/ will be set to the event type, in this case
8174 <tt/GDK_MOTION_NOTIFY/, window is the window in which the event
8175 occured. <tt/x/ and <tt/y/ give the coordinates of the event,
8176 and <tt/state/ specifies the modifier state when the event
8177 occurred (that is, it specifies which modifier keys and mouse buttons
8178 were pressed.) It is the bitwise OR of some of the following:
8197 As for other signals, to determine what happens when an event occurs
8198 we call <tt>gtk_signal_connect()</tt>. But we also need let GTK
8199 know which events we want to be notified about. To do this, we call
8203 void gtk_widget_set_events (GtkWidget *widget,
8207 The second field specifies the events we are interested in. It
8208 is the bitwise OR of constants that specify different types
8209 of events. For future reference the event types are:
8213 GDK_POINTER_MOTION_MASK
8214 GDK_POINTER_MOTION_HINT_MASK
8215 GDK_BUTTON_MOTION_MASK
8216 GDK_BUTTON1_MOTION_MASK
8217 GDK_BUTTON2_MOTION_MASK
8218 GDK_BUTTON3_MOTION_MASK
8219 GDK_BUTTON_PRESS_MASK
8220 GDK_BUTTON_RELEASE_MASK
8222 GDK_KEY_RELEASE_MASK
8223 GDK_ENTER_NOTIFY_MASK
8224 GDK_LEAVE_NOTIFY_MASK
8225 GDK_FOCUS_CHANGE_MASK
8227 GDK_PROPERTY_CHANGE_MASK
8228 GDK_PROXIMITY_IN_MASK
8229 GDK_PROXIMITY_OUT_MASK
8232 There are a few subtle points that have to be observed when calling
8233 <tt/gtk_widget_set_events()/. First, it must be called before the X window
8234 for a GTK widget is created. In practical terms, this means you
8235 should call it immediately after creating the widget. Second, the
8236 widget must have an associated X window. For efficiency, many widget
8237 types do not have their own window, but draw in their parent's window.
8264 To capture events for these widgets, you need to use an EventBox
8265 widget. See the section on
8266 <ref id="sec_The_EventBox_Widget" name="The EventBox Widget"> for
8270 For our drawing program, we want to know when the mouse button is
8271 pressed and when the mouse is moved, so we specify
8272 <tt/GDK_POINTER_MOTION_MASK/ and <tt/GDK_BUTTON_PRESS_MASK/. We also
8273 want to know when we need to redraw our window, so we specify
8274 <tt/GDK_EXPOSURE_MASK/. Although we want to be notified via a
8275 Configure event when our window size changes, we don't have to specify
8276 the corresponding <tt/GDK_STRUCTURE_MASK/ flag, because it is
8277 automatically specified for all windows.
8280 It turns out, however, that there is a problem with just specifying
8281 <tt/GDK_POINTER_MOTION_MASK/. This will cause the server to add a new
8282 motion event to the event queue every time the user moves the mouse.
8283 Imagine that it takes us 0.1 seconds to handle a motion event, but the
8284 X server queues a new motion event every 0.05 seconds. We will soon
8285 get way behind the users drawing. If the user draws for 5 seconds,
8286 it will take us another 5 seconds to catch up after they release
8287 the mouse button! What we would like is to only get one motion
8288 event for each event we process. The way to do this is to
8289 specify <tt/GDK_POINTER_MOTION_HINT_MASK/.
8292 When we specify <tt/GDK_POINTER_MOTION_HINT_MASK/, the server sends
8293 us a motion event the first time the pointer moves after entering
8294 our window, or after a button press or release event. Subsequent
8295 motion events will be suppressed until we explicitely ask for
8296 the position of the pointer using the function:
8299 GdkWindow* gdk_window_get_pointer (GdkWindow *window,
8302 GdkModifierType *mask);
8305 (There is another function, <tt>gtk_widget_get_pointer()</tt> which
8306 has a simpler interface, but turns out not to be very useful, since
8307 it only retrieves the position of the mouse, not whether the buttons
8311 The code to set the events for our window then looks like:
8314 gtk_signal_connect (GTK_OBJECT (drawing_area), "expose_event",
8315 (GtkSignalFunc) expose_event, NULL);
8316 gtk_signal_connect (GTK_OBJECT(drawing_area),"configure_event",
8317 (GtkSignalFunc) configure_event, NULL);
8318 gtk_signal_connect (GTK_OBJECT (drawing_area), "motion_notify_event",
8319 (GtkSignalFunc) motion_notify_event, NULL);
8320 gtk_signal_connect (GTK_OBJECT (drawing_area), "button_press_event",
8321 (GtkSignalFunc) button_press_event, NULL);
8323 gtk_widget_set_events (drawing_area, GDK_EXPOSURE_MASK
8324 | GDK_LEAVE_NOTIFY_MASK
8325 | GDK_BUTTON_PRESS_MASK
8326 | GDK_POINTER_MOTION_MASK
8327 | GDK_POINTER_MOTION_HINT_MASK);
8330 We'll save the "expose_event" and "configure_event" handlers for
8331 later. The "motion_notify_event" and "button_press_event" handlers
8336 button_press_event (GtkWidget *widget, GdkEventButton *event)
8338 if (event->button == 1 && pixmap != NULL)
8339 draw_brush (widget, event->x, event->y);
8345 motion_notify_event (GtkWidget *widget, GdkEventMotion *event)
8348 GdkModifierType state;
8351 gdk_window_get_pointer (event->window, &x, &y, &state);
8356 state = event->state;
8359 if (state & GDK_BUTTON1_MASK && pixmap != NULL)
8360 draw_brush (widget, x, y);
8366 <!-- ----------------------------------------------------------------- -->
8367 <sect1> The DrawingArea Widget, And Drawing
8370 We know turn to the process of drawing on the screen. The
8371 widget we use for this is the DrawingArea widget. A drawing area
8372 widget is essentially an X window and nothing more. It is a blank
8373 canvas in which we can draw whatever we like. A drawing area
8374 is created using the call:
8377 GtkWidget* gtk_drawing_area_new (void);
8380 A default size for the widget can be specified by calling:
8383 void gtk_drawing_area_size (GtkDrawingArea *darea,
8388 This default size can be overriden, as is true for all widgets,
8389 by calling <tt>gtk_widget_set_usize()</tt>, and that, in turn, can
8390 be overridden if the user manually resizes the the window containing
8394 It should be noted that when we create a DrawingArea widget, we are,
8395 <em>completely</em> responsible for drawing the contents. If our
8396 window is obscured then uncovered, we get an exposure event and must
8397 redraw what was previously hidden.
8400 Having to remember everything that was drawn on the screen so we
8401 can properly redraw it can, to say the least, be a nuisance. In
8402 addition, it can be visually distracting if portions of the
8403 window are cleared, then redrawn step by step. The solution to
8404 this problem is to use an offscreen <em>backing pixmap</em>.
8405 Instead of drawing directly to the screen, we draw to an image
8406 stored in server memory but not displayed, then when the image
8407 changes or new portions of the image are displayed, we copy the
8408 relevant portions onto the screen.
8411 To create an offscreen pixmap, we call the function:
8414 GdkPixmap* gdk_pixmap_new (GdkWindow *window,
8420 The <tt>window</tt> parameter specifies a GDK window that this pixmap
8421 takes some of its properties from. <tt>width</tt> and <tt>height</tt>
8422 specify the size of the pixmap. <tt>depth</tt> specifies the <em>color
8423 depth</em>, that is the number of bits per pixel, for the new window.
8424 If the depth is specified as <tt>-1</tt>, it will match the depth
8428 We create the pixmap in our "configure_event" handler. This event
8429 is generated whenever the window changes size, including when it
8430 is originally created.
8433 /* Backing pixmap for drawing area */
8434 static GdkPixmap *pixmap = NULL;
8436 /* Create a new backing pixmap of the appropriate size */
8438 configure_event (GtkWidget *widget, GdkEventConfigure *event)
8442 gdk_pixmap_destroy(pixmap);
8444 pixmap = gdk_pixmap_new(widget->window,
8445 widget->allocation.width,
8446 widget->allocation.height,
8448 gdk_draw_rectangle (pixmap,
8449 widget->style->white_gc,
8452 widget->allocation.width,
8453 widget->allocation.height);
8459 The call to <tt>gdk_draw_rectangle()</tt> clears the pixmap
8460 initially to white. We'll say more about that in a moment.
8463 Our exposure event handler then simply copies the relevant portion
8464 of the pixmap onto the screen (we determine the area we need
8465 to redraw by using the event->area field of the exposure event):
8468 /* Refill the screen from the backing pixmap */
8470 expose_event (GtkWidget *widget, GdkEventExpose *event)
8472 gdk_draw_pixmap(widget->window,
8473 widget->style->fg_gc[GTK_WIDGET_STATE (widget)],
8475 event->area.x, event->area.y,
8476 event->area.x, event->area.y,
8477 event->area.width, event->area.height);
8483 We've now seen how to keep the screen up to date with our pixmap, but
8484 how do we actually draw interesting stuff on our pixmap? There are a
8485 large number of calls in GTK's GDK library for drawing on
8486 <em>drawables</em>. A drawable is simply something that can be drawn
8487 upon. It can be a window, a pixmap, or a bitmap (a black and white
8488 image). We've already seen two such calls above,
8489 <tt>gdk_draw_rectangle()</tt> and <tt>gdk_draw_pixmap()</tt>. The
8494 gdk_draw_rectangle ()
8503 gdk_draw_segments ()
8506 See the reference documentation or the header file
8507 <tt><gdk/gdk.h></tt> for further details on these functions.
8508 These functions all share the same first two arguments. The first
8509 argument is the drawable to draw upon, the second argument is a
8510 <em>graphics context</em> (GC).
8513 A graphics context encapsulates information about things such as
8514 foreground and background color and line width. GDK has a full set of
8515 functions for creating and modifying graphics contexts, but to keep
8516 things simple we'll just use predefined graphics contexts. Each widget
8517 has an associated style. (Which can be modified in a gtkrc file, see
8518 the section GTK's rc file.) This, among other things, stores a number
8519 of graphics contexts. Some examples of accessing these graphics
8523 widget->style->white_gc
8524 widget->style->black_gc
8525 widget->style->fg_gc[GTK_STATE_NORMAL]
8526 widget->style->bg_gc[GTK_WIDGET_STATE(widget)]
8529 The fields <tt>fg_gc</tt>, <tt>bg_gc</tt>, <tt>dark_gc</tt>, and
8530 <tt>light_gc</tt> are indexed by a parameter of type
8531 <tt>GtkStateType</tt> which can take on the values:
8538 GTK_STATE_INSENSITIVE
8541 For instance, the for <tt/GTK_STATE_SELECTED/ the default foreground
8542 color is white and the default background color, dark blue.
8545 Our function <tt>draw_brush()</tt>, which does the actual drawing
8546 on the screen, is then:
8549 /* Draw a rectangle on the screen */
8551 draw_brush (GtkWidget *widget, gdouble x, gdouble y)
8553 GdkRectangle update_rect;
8555 update_rect.x = x - 5;
8556 update_rect.y = y - 5;
8557 update_rect.width = 10;
8558 update_rect.height = 10;
8559 gdk_draw_rectangle (pixmap,
8560 widget->style->black_gc,
8562 update_rect.x, update_rect.y,
8563 update_rect.width, update_rect.height);
8564 gtk_widget_draw (widget, &update_rect);
8568 After we draw the rectangle representing the brush onto the pixmap,
8569 we call the function:
8572 void gtk_widget_draw (GtkWidget *widget,
8573 GdkRectangle *area);
8576 which notifies X that the area given by the <tt>area</tt> parameter
8577 needs to be updated. X will eventually generate an expose event
8578 (possibly combining the areas passed in several calls to
8579 <tt>gtk_widget_draw()</tt>) which will cause our expose event handler
8580 to copy the relevant portions to the screen.
8583 We have now covered the entire drawing program except for a few
8584 mundane details like creating the main window. The complete
8585 source code is available from the location from which you got
8586 this tutorial, or from:
8588 <htmlurl url="http://www.msc.cornell.edu/~otaylor/gtk-gimp/tutorial"
8589 name="http://www.msc.cornell.edu/~otaylor/gtk-gimp/tutorial">
8592 <!-- ----------------------------------------------------------------- -->
8593 <sect1> Adding XInput support
8597 It is now possible to buy quite inexpensive input devices such
8598 as drawing tablets, which allow drawing with a much greater
8599 ease of artistic expression than does a mouse. The simplest way
8600 to use such devices is simply as a replacement for the mouse,
8601 but that misses out many of the advantages of these devices,
8605 <item> Pressure sensitivity
8606 <item> Tilt reporting
8607 <item> Sub-pixel positioning
8608 <item> Multiple inputs (for example, a stylus with a point and eraser)
8611 For information about the XInput extension, see the <htmlurl
8612 url="http://www.msc.cornell.edu/~otaylor/xinput/XInput-HOWTO.html"
8613 name="XInput-HOWTO">.
8616 If we examine the full definition of, for example, the GdkEventMotion
8617 structure, we see that it has fields to support extended device
8621 struct _GdkEventMotion
8633 GdkInputSource source;
8638 <tt/pressure/ gives the pressure as a floating point number between
8639 0 and 1. <tt/xtilt/ and <tt/ytilt/ can take on values between
8640 -1 and 1, corresponding to the degree of tilt in each direction.
8641 <tt/source/ and <tt/deviceid/ specify the device for which the
8642 event occurred in two different ways. <tt/source/ gives some simple
8643 information about the type of device. It can take the enumeration
8653 <tt/deviceid/ specifies a unique numeric ID for the device. This can
8654 be used to find out further information about the device using the
8655 <tt/gdk_input_list_devices()/ call (see below). The special value
8656 <tt/GDK_CORE_POINTER/ is used for the core pointer device. (Usually
8659 <sect2> Enabling extended device information
8662 To let GTK know about our interest in the extended device information,
8663 we merely have to add a single line to our program:
8666 gtk_widget_set_extension_events (drawing_area, GDK_EXTENSION_EVENTS_CURSOR);
8669 By giving the value <tt/GDK_EXTENSION_EVENTS_CURSOR/ we say that
8670 we are interested in extension events, but only if we don't have
8671 to draw our own cursor. See the section <ref
8672 id="sec_Further_Sophistications" name="Further Sophistications"> below
8673 for more information about drawing the cursor. We could also
8674 give the values <tt/GDK_EXTENSION_EVENTS_ALL/ if we were willing
8675 to draw our own cursor, or <tt/GDK_EXTENSION_EVENTS_NONE/ to revert
8676 back to the default condition.
8679 This is not completely the end of the story however. By default,
8680 no extension devices are enabled. We need a mechanism to allow
8681 users to enable and configure their extension devices. GTK provides
8682 the InputDialog widget to automate this process. The following
8683 procedure manages an InputDialog widget. It creates the dialog if
8684 it isn't present, and raises it to the top otherwise.
8688 input_dialog_destroy (GtkWidget *w, gpointer data)
8690 *((GtkWidget **)data) = NULL;
8694 create_input_dialog ()
8696 static GtkWidget *inputd = NULL;
8700 inputd = gtk_input_dialog_new();
8702 gtk_signal_connect (GTK_OBJECT(inputd), "destroy",
8703 (GtkSignalFunc)input_dialog_destroy, &inputd);
8704 gtk_signal_connect_object (GTK_OBJECT(GTK_INPUT_DIALOG(inputd)->close_button),
8706 (GtkSignalFunc)gtk_widget_hide,
8707 GTK_OBJECT(inputd));
8708 gtk_widget_hide ( GTK_INPUT_DIALOG(inputd)->save_button);
8710 gtk_widget_show (inputd);
8714 if (!GTK_WIDGET_MAPPED(inputd))
8715 gtk_widget_show(inputd);
8717 gdk_window_raise(inputd->window);
8722 (You might want to take note of the way we handle this dialog. By
8723 connecting to the "destroy" signal, we make sure that we don't keep a
8724 pointer to dialog around after it is destroyed - that could lead to a
8728 The InputDialog has two buttons "Close" and "Save", which by default
8729 have no actions assigned to them. In the above function we make
8730 "Close" hide the dialog, hide the "Save" button, since we don't
8731 implement saving of XInput options in this program.
8733 <sect2> Using extended device information
8736 Once we've enabled the device, we can just use the extended
8737 device information in the extra fields of the event structures.
8738 In fact, it is always safe to use this information since these
8739 fields will have reasonable default values even when extended
8740 events are not enabled.
8743 Once change we do have to make is to call
8744 <tt/gdk_input_window_get_pointer()/ instead of
8745 <tt/gdk_window_get_pointer/. This is necessary because
8746 <tt/gdk_window_get_pointer/ doesn't return the extended device
8750 void gdk_input_window_get_pointer (GdkWindow *window,
8757 GdkModifierType *mask);
8760 When calling this function, we need to specify the device ID as
8761 well as the window. Usually, we'll get the device ID from the
8762 <tt/deviceid/ field of an event structure. Again, this function
8763 will return reasonable values when extension events are not
8764 enabled. (In this case, <tt/event->deviceid/ will have the value
8765 <tt/GDK_CORE_POINTER/).
8767 So the basic structure of our button-press and motion event handlers,
8768 doesn't change much - we just need to add code to deal with the
8769 extended information.
8773 button_press_event (GtkWidget *widget, GdkEventButton *event)
8775 print_button_press (event->deviceid);
8777 if (event->button == 1 && pixmap != NULL)
8778 draw_brush (widget, event->source, event->x, event->y, event->pressure);
8784 motion_notify_event (GtkWidget *widget, GdkEventMotion *event)
8788 GdkModifierType state;
8791 gdk_input_window_get_pointer (event->window, event->deviceid,
8792 &x, &y, &pressure, NULL, NULL, &state);
8797 pressure = event->pressure;
8798 state = event->state;
8801 if (state & GDK_BUTTON1_MASK && pixmap != NULL)
8802 draw_brush (widget, event->source, x, y, pressure);
8808 We also need to do something with the new information. Our new
8809 <tt/draw_brush()/ function draws with a different color for
8810 each <tt/event->source/ and changes the brush size depending
8814 /* Draw a rectangle on the screen, size depending on pressure,
8815 and color on the type of device */
8817 draw_brush (GtkWidget *widget, GdkInputSource source,
8818 gdouble x, gdouble y, gdouble pressure)
8821 GdkRectangle update_rect;
8825 case GDK_SOURCE_MOUSE:
8826 gc = widget->style->dark_gc[GTK_WIDGET_STATE (widget)];
8828 case GDK_SOURCE_PEN:
8829 gc = widget->style->black_gc;
8831 case GDK_SOURCE_ERASER:
8832 gc = widget->style->white_gc;
8835 gc = widget->style->light_gc[GTK_WIDGET_STATE (widget)];
8838 update_rect.x = x - 10 * pressure;
8839 update_rect.y = y - 10 * pressure;
8840 update_rect.width = 20 * pressure;
8841 update_rect.height = 20 * pressure;
8842 gdk_draw_rectangle (pixmap, gc, TRUE,
8843 update_rect.x, update_rect.y,
8844 update_rect.width, update_rect.height);
8845 gtk_widget_draw (widget, &update_rect);
8849 <sect2> Finding out more about a device
8852 As an example of how to find out more about a device, our program
8853 will print the name of the device that generates each button
8854 press. To find out the name of a device, we call the function:
8857 GList *gdk_input_list_devices (void);
8860 which returns a GList (a linked list type from the glib library)
8861 of GdkDeviceInfo structures. The GdkDeviceInfo strucure is defined
8865 struct _GdkDeviceInfo
8869 GdkInputSource source;
8879 Most of these fields are configuration information that you
8880 can ignore unless you are implemented XInput configuration
8881 saving. The we are interested in here is <tt/name/ which is
8882 simply the name that X assigns to the device. The other field
8883 that isn't configuration information is <tt/has_cursor/. If
8884 <tt/has_cursor/ is false, then we we need to draw our own
8885 cursor. But since we've specified <tt/GDK_EXTENSION_EVENTS_CURSOR/,
8886 we don't have to worry about this.
8889 Our <tt/print_button_press()/ function simply iterates through
8890 the returned list until it finds a match, then prints out
8891 the name of the device.
8895 print_button_press (guint32 deviceid)
8899 /* gdk_input_list_devices returns an internal list, so we shouldn't
8900 free it afterwards */
8901 tmp_list = gdk_input_list_devices();
8905 GdkDeviceInfo *info = (GdkDeviceInfo *)tmp_list->data;
8907 if (info->deviceid == deviceid)
8909 printf("Button press on device '%s'\n", info->name);
8913 tmp_list = tmp_list->next;
8918 That completes the changes to ``XInputize'' our program. As with
8919 the first version, the complete source is available at the location
8920 from which you got this tutorial, or from:
8922 <htmlurl url="http://www.msc.cornell.edu/~otaylor/gtk-gimp/tutorial"
8923 name="http://www.msc.cornell.edu/~otaylor/gtk-gimp/tutorial">
8926 <sect2> Further sophistications <label id="sec_Further_Sophistications">
8929 Although our program now supports XInput quite well, it lacks some
8930 features we would want in a full-featured application. First, the user
8931 probably doesn't want to have to configure their device each time they
8932 run the program, so we should allow them to save the device
8933 configuration. This is done by iterating through the return of
8934 <tt/gdk_input_list_devices()/ and writing out the configuration to a
8938 To restore the state next time the program is run, GDK provides
8939 functions to change device configuration:
8942 gdk_input_set_extension_events()
8943 gdk_input_set_source()
8944 gdk_input_set_mode()
8945 gdk_input_set_axes()
8949 (The list returned from <tt/gdk_input_list_devices()/ should not be
8950 modified directly.) An example of doing this can be found in the
8951 drawing program gsumi. (Available from <htmlurl
8952 url="http://www.msc.cornell.edu/~otaylor/gsumi/"
8953 name="http://www.msc.cornell.edu/~otaylor/gsumi/">) Eventually, it
8954 would be nice to have a standard way of doing this for all
8955 applications. This probably belongs at a slightly higher level than
8956 GTK, perhaps in the GNOME library.
8959 Another major ommission that we have mentioned above is the lack of
8960 cursor drawing. Platforms other than XFree86 currently do not allow
8961 simultaneously using a device as both the core pointer and directly by
8962 an application. See the <url
8963 url="http://www.msc.cornell.edu/~otaylor/xinput/XInput-HOWTO.html"
8964 name="XInput-HOWTO"> for more information about this. This means that
8965 applications that want to support the widest audience need to draw
8969 An application that draws it's own cursor needs to do two things:
8970 determine if the current device needs a cursor drawn or not, and
8971 determine if the current device is in proximity. (If the current
8972 device is a drawing tablet, it's a nice touch to make the cursor
8973 disappear when the stylus is lifted from the tablet. When the
8974 device is touching the stylus, that is called "in proximity.")
8975 The first is done by searching the device list, as we did
8976 to find out the device name. The second is achieved by selecting
8977 "proximity_out" events. An example of drawing one's own cursor is
8978 found in the 'testinput' program found in the GTK distribution.
8980 <!-- ***************************************************************** -->
8981 <sect>Tips For Writing GTK Applications
8982 <!-- ***************************************************************** -->
8985 This section is simply a gathering of wisdom, general style guidelines and hints to
8986 creating good GTK applications. It is totally useless right now cause it's
8987 only a topic sentence :)
8989 Use GNU autoconf and automake! They are your friends :) I am planning to
8990 make a quick intro on them here.
8992 <!-- ***************************************************************** -->
8994 <!-- ***************************************************************** -->
8997 This document, like so much other great software out there, was created for
8998 free by volunteers. If you are at all knowledgeable about any aspect of GTK
8999 that does not already have documentation, please consider contributing to
9002 If you do decide to contribute, please mail your text to Tony Gale,
9003 <tt><htmlurl url="mailto:gale@gimp.org"
9004 name="gale@gimp.org"></tt>. Also, be aware that the entirety of this
9005 document is free, and any addition by yourself must also be free. That is,
9006 people may use any portion of your examples in their programs, and copies
9007 of this document may be distributed at will etc.
9011 <!-- ***************************************************************** -->
9013 <!-- ***************************************************************** -->
9015 I would like to thank the following for their contributions to this text.
9018 <item>Bawer Dagdeviren, <tt><htmlurl url="mailto:chamele0n@geocities.com"
9019 name="chamele0n@geocities.com"></tt> for the menus tutorial.
9021 <item>Raph Levien, <tt><htmlurl url="mailto:raph@acm.org"
9022 name="raph@acm.org"></tt>
9023 for hello world ala GTK, widget packing, and general all around wisdom.
9024 He's also generously donated a home for this tutorial.
9026 <item>Peter Mattis, <tt><htmlurl url="mailto:petm@xcf.berkeley.edu"
9027 name="petm@xcf.berkeley.edu"></tt> for the simplest GTK program..
9028 and the ability to make it :)
9030 <item>Werner Koch <tt><htmlurl url="mailto:werner.koch@guug.de"
9031 name="werner.koch@guug.de"></tt> for converting the original plain text to
9032 SGML, and the widget class hierarchy.
9034 <item>Mark Crichton <tt><htmlurl url="mailto:crichton@expert.cc.purdue.edu"
9035 name="crichton@expert.cc.purdue.edu"></tt> for the menu factory code, and
9036 the table packing tutorial.
9038 <item>Owen Taylor <tt><htmlurl url="mailto:owt1@cornell.edu"
9039 name="owt1@cornell.edu"></tt> for the EventBox widget section (and
9040 the patch to the distro). He's also responsible for the selections code and
9041 tutorial, as well as the sections on writing your own GTK widgets, and the
9042 example application. Thanks a lot Owen for all you help!
9044 <item>Mark VanderBoom <tt><htmlurl url="mailto:mvboom42@calvin.edu"
9045 name="mvboom42@calvin.edu"></tt> for his wonderful work on the Notebook,
9046 Progress Bar, Dialogs, and File selection widgets. Thanks a lot Mark!
9047 You've been a great help.
9049 <item>Tim Janik <tt><htmlurl url="mailto:timj@psynet.net"
9050 name="timj@psynet.net"></tt> for his great job on the Lists Widget.
9053 <item>Rajat Datta <tt><htmlurl url="mailto:rajat@ix.netcom.com"
9054 name="rajat@ix.netcom.com"</tt> for the excellent job on the Pixmap tutorial.
9056 <item>Michael K. Johnson <tt><htmlurl url="mailto:johnsonm@redhat.com"
9057 name="johnsonm@redhat.com"></tt> for info and code for popup menus.
9061 And to all of you who commented and helped refine this document.
9065 <!-- ***************************************************************** -->
9066 <sect> Tutorial Copyright and Permissions Notice
9067 <!-- ***************************************************************** -->
9070 The GTK Tutorial is Copyright (C) 1997 Ian Main.
9072 Copyright (C) 1998 Tony Gale.
9074 Permission is granted to make and distribute verbatim copies of this
9075 manual provided the copyright notice and this permission notice are
9076 preserved on all copies.
9077 <P>Permission is granted to copy and distribute modified versions of
9078 this document under the conditions for verbatim copying, provided that
9079 this copyright notice is included exactly as in the original,
9080 and that the entire resulting derived work is distributed under
9081 the terms of a permission notice identical to this one.
9082 <P>Permission is granted to copy and distribute translations of this
9083 document into another language, under the above conditions for modified
9085 <P>If you are intending to incorporate this document into a published
9086 work, please contact the maintainer, and we will make an effort
9087 to ensure that you have the most up to date information available.
9088 <P>There is no guarentee that this document lives up to its intended
9089 purpose. This is simply provided as a free resource. As such,
9090 the authors and maintainers of the information provided within can
9091 not make any guarentee that the information is even accurate.