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:imain@gtk.org"
10 name="<imain@gtk.org>"></tt>,
11 Tony Gale <tt><htmlurl url="mailto:gale@gtk.org"
12 name="<gale@gtk.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 a wrapper around the Xlib functions. It's
22 called the GIMP toolkit because it was originally written for developing
23 the GIMP, but has now been used in several free software projects. The
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>
34 GTK is essentially an object oriented application programmers interface (API).
35 Although written completely in
36 C, it is implemented using the idea of classes and callback functions
37 (pointers to functions).
39 There is also a third component called glib which contains a few
40 replacements for some standard calls, as well as some additional functions
41 for handling linked lists etc. The replacement functions are used to
42 increase GTK's portability, as some of the functions implemented
43 here are not available or are nonstandard on other unicies such as
44 g_strerror(). Some also contain enhancements to the libc versions, such as
45 g_malloc that has enhanced debugging utilities.
47 This tutorial is an attempt to document as much as possible of GTK, it is by
48 no means complete. This
49 tutorial assumes a good understanding of C, and how to create C programs.
50 It would be a great benefit for the reader to have previous X programming
51 experience, but it shouldn't be necessary. If you are learning GTK as your
52 first widget set, please comment on how you found this tutorial, and what
54 Note that there is also a C++ API for GTK (GTK--) in the works, so if you
55 prefer to use C++, you should look into this instead. There's also an
56 Objective C wrapper, and Guile bindings available, but I don't follow these.
58 I would very much like to hear of any problems you have learning GTK from this
59 document, and would appreciate input as to how it may be improved.
61 <!-- ***************************************************************** -->
63 <!-- ***************************************************************** -->
66 The first thing to do of course, is download the GTK source and install
67 it. You can always get the latest version from ftp.gtk.org in /pub/gtk.
68 You can also view other sources of GTK information on http://www.gtk.org/
69 <htmlurl url="http://www.gtk.org/" name="http://www.gtk.org/">.
70 GTK uses GNU autoconf for
71 configuration. Once untar'd, type ./configure --help to see a list of options.
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 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/
125 It removes these from the argument list, leaving anything it does
126 not recognize for your application to parse or ignore. This creates a set
127 of standard arguments accepted by all GTK applications.
129 The next two lines of code create and display a window.
132 window = gtk_window_new (GTK_WINDOW_TOPLEVEL);
133 gtk_widget_show (window);
136 The GTK_WINDOW_TOPLEVEL argument specifies that we want the window to
137 undergo window manager decoration and placement. Rather than create a
138 window of 0x0 size, a window without children is set to 200x200 by default
139 so you can still manipulate it.
141 The gtk_widget_show() function lets GTK know that we are done setting the
142 attributes of this widget, and that it can display it.
144 The last line enters the GTK main processing loop.
150 gtk_main() is another call you will see in every GTK application. When
151 control reaches this point, GTK will sleep waiting for X events (such as
152 button or key presses), timeouts, or file IO notifications to occur.
153 In our simple example however, events are ignored.
155 <!-- ----------------------------------------------------------------- -->
156 <sect1>Hello World in GTK
158 OK, now for a program with a widget (a button). It's the classic hello
162 /* example-start helloworld/helloworld.c */
166 /* this is a callback function. the data arguments are ignored in this example..
167 * More on callbacks below. */
168 void hello (GtkWidget *widget, gpointer data)
170 g_print ("Hello World\n");
173 gint delete_event(GtkWidget *widget, GdkEvent *event, gpointer data)
175 g_print ("delete event occured\n");
176 /* if you return FALSE in the "delete_event" signal handler,
177 * GTK will emit the "destroy" signal. Returning TRUE means
178 * you don't want the window to be destroyed.
179 * This is useful for popping up 'are you sure you want to quit ?'
182 /* Change TRUE to FALSE and the main window will be destroyed with
183 * a "delete_event". */
188 /* another callback */
189 void destroy (GtkWidget *widget, gpointer data)
194 int main (int argc, char *argv[])
196 /* GtkWidget is the storage type for widgets */
200 /* this is called in all GTK applications. arguments are parsed from
201 * the command line and are returned to the application. */
202 gtk_init (&argc, &argv);
204 /* create a new window */
205 window = gtk_window_new (GTK_WINDOW_TOPLEVEL);
207 /* when the window is given the "delete_event" signal (this is given
208 * by the window manager, usually by the 'close' option, or on the
209 * titlebar), we ask it to call the delete_event () function
210 * as defined above. The data passed to the callback
211 * function is NULL and is ignored in the callback function. */
212 gtk_signal_connect (GTK_OBJECT (window), "delete_event",
213 GTK_SIGNAL_FUNC (delete_event), NULL);
215 /* here we connect the "destroy" event to a signal handler.
216 * This event occurs when we call gtk_widget_destroy() on the window,
217 * or if we return 'FALSE' in the "delete_event" callback. */
218 gtk_signal_connect (GTK_OBJECT (window), "destroy",
219 GTK_SIGNAL_FUNC (destroy), NULL);
221 /* sets the border width of the window. */
222 gtk_container_border_width (GTK_CONTAINER (window), 10);
224 /* creates a new button with the label "Hello World". */
225 button = gtk_button_new_with_label ("Hello World");
227 /* When the button receives the "clicked" signal, it will call the
228 * function hello() passing it NULL as it's argument. The hello() function is
230 gtk_signal_connect (GTK_OBJECT (button), "clicked",
231 GTK_SIGNAL_FUNC (hello), NULL);
233 /* This will cause the window to be destroyed by calling
234 * gtk_widget_destroy(window) when "clicked". Again, the destroy
235 * signal could come from here, or the window manager. */
236 gtk_signal_connect_object (GTK_OBJECT (button), "clicked",
237 GTK_SIGNAL_FUNC (gtk_widget_destroy),
238 GTK_OBJECT (window));
240 /* this packs the button into the window (a gtk container). */
241 gtk_container_add (GTK_CONTAINER (window), button);
243 /* the final step is to display this newly created widget... */
244 gtk_widget_show (button);
247 gtk_widget_show (window);
249 /* all GTK applications must have a gtk_main(). Control ends here
250 * and waits for an event to occur (like a key press or mouse event). */
258 <!-- ----------------------------------------------------------------- -->
259 <sect1>Compiling Hello World
264 gcc -Wall -g helloworld.c -o hello_world `gtk-config --cflags` \
268 This uses the program <tt>gtk-config</>, which comes with gtk. This
269 program 'knows' what compiler switches are needed to compile programs
270 that use gtk. <tt>gtk-config --cflags</> will output a list of include
271 directories for the compiler to look in, and <tt>gtk-config --libs</>
272 will output the list of libraries for the compiler to link with and
273 the directories to find them in.
275 The libraries that are usually linked in are:
277 <item>The GTK library (-lgtk), the widget library, based on top of GDK.
278 <item>The GDK library (-lgdk), the Xlib wrapper.
279 <item>The glib library (-lglib), containing miscellaneous functions, only
280 g_print() is used in this particular example. GTK is built on top
281 of glib so you will always require this library. See the section on
282 <ref id="sec_glib" name="glib"> for details.
283 <item>The Xlib library (-lX11) which is used by GDK.
284 <item>The Xext library (-lXext). This contains code for shared memory
285 pixmaps and other X extensions.
286 <item>The math library (-lm). This is used by GTK for various purposes.
289 <!-- ----------------------------------------------------------------- -->
290 <sect1>Theory of Signals and Callbacks
292 Before we look in detail at hello world, we'll discuss signals and callbacks.
293 GTK is an event driven toolkit, which means it will sleep in
294 gtk_main until an event occurs and control is passed to the appropriate
297 This passing of control is done using the idea of "signals". When an
298 event occurs, such as the press of a mouse button, the
299 appropriate signal will be "emitted" by the widget that was pressed.
300 This is how GTK does most of its useful work. There are a set of signals
301 that all widgets inherit, such as "destroy", and there are signals that are
302 widget specific, such as "toggled" on a toggle button.
304 To make a button perform an action, we set up a signal handler to catch these
305 signals and call the appropriate function. This is done by using a
309 gint gtk_signal_connect( GtkObject *object,
312 gpointer func_data );
315 Where the first argument is the widget which will be emitting the signal, and
316 the second, the name of the signal you wish to catch. The third is the function
317 you wish to be called when it is caught, and the fourth, the data you wish
318 to have passed to this function.
320 The function specified in the third argument is called a "callback
321 function", and should generally be of the form:
324 void callback_func( GtkWidget *widget,
325 gpointer callback_data );
328 Where the first argument will be a pointer to the widget that emitted the
329 signal, and the second, a pointer to the data given as the last argument
330 to the gtk_signal_connect() function as shown above.
332 Note that the above form for a signal callback function declaration is
333 only a general guide, as some widget specific signals generate different
334 calling parameters. For example, the GtkCList "select_row" signal provides
335 both row and column parameters.
337 Another call used in the hello world example, is:
340 gint gtk_signal_connect_object( GtkObject *object,
343 GtkObject *slot_object );
346 gtk_signal_connect_object() is the same as gtk_signal_connect() except that
347 the callback function only uses one argument, a pointer to a GTK
348 object. So when using this function to connect signals, the callback
349 should be of the form:
352 void callback_func( GtkObject *object );
355 Where the object is usually a widget. We usually don't setup callbacks for
356 gtk_signal_connect_object however. They are usually used
357 to call a GTK function that accepts a single widget or object as an
358 argument, as is the case in our hello world example.
360 The purpose of having two functions to connect signals is simply to allow
361 the callbacks to have a different number of arguments. Many functions in
362 the GTK library accept only a single GtkWidget pointer as an argument, so you
363 want to use the gtk_signal_connect_object() for these, whereas for your
364 functions, you may need to have additional data supplied to the callbacks.
366 <!-- ----------------------------------------------------------------- -->
369 In addition to the signal mechanism described above, there are a set of
370 <em>events</em> that reflect the X event mechanism. Callbacks may also be
371 attached to these events. These events are:
375 <item> button_press_event
376 <item> button_release_event
377 <item> motion_notify_event
381 <item> key_press_event
382 <item> key_release_event
383 <item> enter_notify_event
384 <item> leave_notify_event
385 <item> configure_event
386 <item> focus_in_event
387 <item> focus_out_event
390 <item> property_notify_event
391 <item> selection_clear_event
392 <item> selection_request_event
393 <item> selection_notify_event
394 <item> proximity_in_event
395 <item> proximity_out_event
396 <item> drag_begin_event
397 <item> drag_request_event
398 <item> drag_end_event
399 <item> drop_enter_event
400 <item> drop_leave_event
401 <item> drop_data_available_event
405 In order to connect a callback function to one of these events, you use
406 the function gtk_signal_connect, as described above, using one of the
407 above event names as the <tt/name/ parameter. The callback function for
408 events has a slighty different form than that for signals:
411 void callback_func( GtkWidget *widget,
413 gpointer callback_data );
416 GdkEvent is a C <tt/union/ structure whose type will depend upon which of the
417 above events has occured. In order for us to tell which event has been issued
418 each of the possible alternatives has a <tt/type/ parameter which reflects the
419 event being issued. The other components of the event structure will depend
420 upon the type of the event. Possible values for the type are:
442 GDK_SELECTION_REQUEST
452 GDK_VISIBILITY_NOTIFY
454 GDK_OTHER_EVENT /* Deprecated, use filters instead */
457 So, to connect a callback function to one of these events we would use
461 gtk_signal_connect( GTK_OBJECT(button), "button_press_event",
462 GTK_SIGNAL_FUNC(button_press_callback),
466 This assumes that <tt/button/ is a GtkButton widget. Now, when the mouse is
467 over the button and a mouse button is pressed, the function
468 <tt/button_press_callback/ will be called. This function may be declared as:
471 static gint button_press_event (GtkWidget *widget,
472 GdkEventButton *event,
476 Note that we can declare the second argument as type <tt/GdkEventButton/
477 as we know what type of event will occur for this function to be called.
479 <!-- Need an Annex with all the event types in it - TRG -->
481 <!-- Need to check this - TRG
482 The value returned from this function indicates whether the event should
483 be processed further by the GTK event handling mechanism. Returning
484 TRUE indicates that the event has been handled, and that it should not
485 propogate further. Returning FALSE continues the normal event handling.
488 <!-- ----------------------------------------------------------------- -->
489 <sect1>Stepping Through Hello World
491 Now that we know the theory behind this, lets clarify by walking through
492 the example hello world program.
494 Here is the callback function that will be called when the button is
495 "clicked". We ignore both the widget and the data in this example, but it
496 is not hard to do things with them. The next example will use the data
497 argument to tell us which button was pressed.
500 void hello (GtkWidget *widget, gpointer data)
502 g_print ("Hello World\n");
506 This callback is a bit special. The "delete_event" occurs when the
507 window manager sends this event to the application. We have a choice here
508 as to what to do about these events. We can ignore them, make some sort of
509 response, or simply quit the application.
511 The value you return in this callback lets GTK know what action to take.
512 By returning TRUE, we let it know that we don't want to have the "destroy"
513 signal emitted, keeping our application running. By returning FALSE, we
514 ask that "destroy" is emitted, which in turn will call our "destroy"
518 gint delete_event(GtkWidget *widget, GdkEvent *event, gpointer data)
520 g_print ("delete event occured\n");
526 Here is another callback function which causes the program to quit by calling
527 gtk_main_quit(). This function tells GTK that it is to exit from gtk_main
528 when control is returned to it.
531 void destroy (GtkWidget *widget, gpointer data)
537 I assume you know about the main() function... yes, as with other
538 applications, all GTK applications will also have one of these.
541 int main (int argc, char *argv[])
545 This next part, declares a pointer to a structure of type GtkWidget. These
546 are used below to create a window and a button.
553 Here is our gtk_init again. As before, this initializes the toolkit, and
554 parses the arguments found on the command line. Any argument it
555 recognizes from the command line, it removes from the list, and modifies
556 argc and argv to make it look like they never existed, allowing your
557 application to parse the remaining arguments.
560 gtk_init (&argc, &argv);
563 Create a new window. This is fairly straight forward. Memory is allocated
564 for the GtkWidget *window structure so it now points to a valid structure.
565 It sets up a new window, but it is not displayed until we call
566 gtk_widget_show(window) near the end of our program.
569 window = gtk_window_new (GTK_WINDOW_TOPLEVEL);
572 Here is an example of connecting a signal handler to an object, in
573 this case, the window. Here, the "destroy" signal is caught. This is
574 emitted when we use the window manager to kill the window (and we return
575 TRUE in the "delete_event" handler), or when we use the
576 gtk_widget_destroy() call passing in the window widget as the object to
577 destroy. By setting this up, we handle both cases with a single call.
578 Here, it just calls the destroy() function defined above with a NULL
579 argument, which quits GTK for us.
581 The GTK_OBJECT and GTK_SIGNAL_FUNC are macros that perform type
582 casting and checking for us, as well as aid the readability of the code.
585 gtk_signal_connect (GTK_OBJECT (window), "destroy",
586 GTK_SIGNAL_FUNC (destroy), NULL);
589 This next function is used to set an attribute of a container object.
590 This just sets the window
591 so it has a blank area along the inside of it 10 pixels wide where no
592 widgets will go. There are other similar functions which we will look at
594 <ref id="sec_setting_widget_attributes" name="Setting Widget Attributes">
596 And again, GTK_CONTAINER is a macro to perform type casting.
599 gtk_container_border_width (GTK_CONTAINER (window), 10);
602 This call creates a new button. It allocates space for a new GtkWidget
603 structure in memory, initializes it, and makes the button pointer point to
604 it. It will have the label "Hello World" on it when displayed.
607 button = gtk_button_new_with_label ("Hello World");
610 Here, we take this button, and make it do something useful. We attach a
611 signal handler to it so when it emits the "clicked" signal, our hello()
612 function is called. The data is ignored, so we simply pass in NULL to the
613 hello() callback function. Obviously, the "clicked" signal is emitted when
614 we click the button with our mouse pointer.
617 gtk_signal_connect (GTK_OBJECT (button), "clicked",
618 GTK_SIGNAL_FUNC (hello), NULL);
621 We are also going to use this button to exit our program. This will
622 illustrate how the "destroy"
623 signal may come from either the window manager, or our program. When the
624 button is "clicked", same as above, it calls the first hello() callback function,
625 and then this one in the order they are set up. You may have as many
626 callback functions as you need, and all will be executed in the order you
627 connected them. Because the gtk_widget_destroy() function accepts only a
628 GtkWidget *widget as an argument, we use the gtk_signal_connect_object()
629 function here instead of straight gtk_signal_connect().
632 gtk_signal_connect_object (GTK_OBJECT (button), "clicked",
633 GTK_SIGNAL_FUNC (gtk_widget_destroy),
634 GTK_OBJECT (window));
637 This is a packing call, which will be explained in depth later on. But it
638 is fairly easy to understand. It simply tells GTK that the button is to be
639 placed in the window where it will be displayed. Note that a GTK container
640 can only contain one widget. There are other widgets, that are described later,
641 which are designed to layout multiple widgets in various ways.
644 gtk_container_add (GTK_CONTAINER (window), button);
647 Now that we have everything setup the way we want it to be. With all the
648 signal handlers in place, and the button placed in the window where it
649 should be, we ask GTK to "show" the widgets on the screen. The window
650 widget is shown last so the whole window will pop up at once rather than
651 seeing the window pop up, and then the button form inside of it. Although
652 with such a simple example, you'd never notice.
655 gtk_widget_show (button);
657 gtk_widget_show (window);
660 And of course, we call gtk_main() which waits for events to come from the X
661 server and will call on the widgets to emit signals when these events come.
667 And the final return. Control returns here after gtk_quit() is called.
673 Now, when we click the mouse button on a GTK button, the
674 widget emits a "clicked" signal. In order for us to use this
675 information, our program sets up a signal handler to catch that signal,
676 which dispatches the function of our choice. In our example, when the
677 button we created is "clicked", the hello() function is called with a NULL
678 argument, and then the next handler for this signal is called. This calls
679 the gtk_widget_destroy() function, passing it the window widget as it's
680 argument, destroying the window widget. This causes the window to emit the
681 "destroy" signal, which is caught, and calls our destroy() callback
682 function, which simply exits GTK.
684 Another course of events, is to use the window manager to kill the window.
685 This will cause the "delete_event" to be emitted. This will call our
686 "delete_event" handler. If we return TRUE here, the window will be left as
687 is and nothing will happen. Returning FALSE will cause GTK to emit the
688 "destroy" signal which of course, calls the "destroy" callback, exiting GTK.
690 Note that these signals are not the same as the Unix system
691 signals, and are not implemented using them, although the terminology is
694 <!-- ***************************************************************** -->
696 <!-- ***************************************************************** -->
698 <!-- ----------------------------------------------------------------- -->
701 There are a few things you probably noticed in the previous examples that
702 need explaining. The gint, gchar etc. that you see are typedefs to int and
703 char respectively. This is done to get around that nasty dependency on the
704 size of simple data types when doing calculations.
706 A good example is "gint32" which will be typedef'd to a 32 bit integer for
707 any given platform, whether it be the 64 bit alpha, or the 32 bit i386. The
708 typedefs are very straight forward and intuitive. They are all defined in
709 glib/glib.h (which gets included from gtk.h).
711 You'll also notice the ability to use GtkWidget when the function calls for
712 a GtkObject. GTK is an object oriented design, and a widget is an object.
714 <!-- ----------------------------------------------------------------- -->
715 <sect1>More on Signal Handlers
717 Lets take another look at the gtk_signal_connect declaration.
720 gint gtk_signal_connect( GtkObject *object,
723 gpointer func_data );
726 Notice the gint return value ? This is a tag that identifies your callback
727 function. As said above, you may have as many callbacks per signal and per
728 object as you need, and each will be executed in turn, in the order they
731 This tag allows you to remove this callback from the list by using:
734 void gtk_signal_disconnect( GtkObject *object,
738 So, by passing in the widget you wish to remove the handler from, and the
739 tag or id returned by one of the signal_connect functions, you can
740 disconnect a signal handler.
742 Another function to remove all the signal handers from an object is:
745 void gtk_signal_handlers_destroy( GtkObject *object );
748 This call is fairly self explanatory. It simply removes all the current
749 signal handlers from the object passed in as the first argument.
751 <!-- ----------------------------------------------------------------- -->
752 <sect1>An Upgraded Hello World
754 Let's take a look at a slightly improved hello world with better examples
755 of callbacks. This will also introduce us to our next topic, packing
759 /* example-start helloworld2/helloworld2.c */
763 /* Our new improved callback. The data passed to this function is printed
765 void callback (GtkWidget *widget, gpointer data)
767 g_print ("Hello again - %s was pressed\n", (char *) data);
770 /* another callback */
771 void delete_event (GtkWidget *widget, GdkEvent *event, gpointer data)
776 int main (int argc, char *argv[])
778 /* GtkWidget is the storage type for widgets */
783 /* this is called in all GTK applications. arguments are parsed from
784 * the command line and are returned to the application. */
785 gtk_init (&argc, &argv);
787 /* create a new window */
788 window = gtk_window_new (GTK_WINDOW_TOPLEVEL);
790 /* this is a new call, this just sets the title of our
791 * new window to "Hello Buttons!" */
792 gtk_window_set_title (GTK_WINDOW (window), "Hello Buttons!");
794 /* Here we just set a handler for delete_event that immediately
796 gtk_signal_connect (GTK_OBJECT (window), "delete_event",
797 GTK_SIGNAL_FUNC (delete_event), NULL);
800 /* sets the border width of the window. */
801 gtk_container_border_width (GTK_CONTAINER (window), 10);
803 /* we create a box to pack widgets into. this is described in detail
804 * in the "packing" section below. The box is not really visible, it
805 * is just used as a tool to arrange widgets. */
806 box1 = gtk_hbox_new(FALSE, 0);
808 /* put the box into the main window. */
809 gtk_container_add (GTK_CONTAINER (window), box1);
811 /* creates a new button with the label "Button 1". */
812 button = gtk_button_new_with_label ("Button 1");
814 /* Now when the button is clicked, we call the "callback" function
815 * with a pointer to "button 1" as it's argument */
816 gtk_signal_connect (GTK_OBJECT (button), "clicked",
817 GTK_SIGNAL_FUNC (callback), (gpointer) "button 1");
819 /* instead of gtk_container_add, we pack this button into the invisible
820 * box, which has been packed into the window. */
821 gtk_box_pack_start(GTK_BOX(box1), button, TRUE, TRUE, 0);
823 /* always remember this step, this tells GTK that our preparation for
824 * this button is complete, and it can be displayed now. */
825 gtk_widget_show(button);
827 /* do these same steps again to create a second button */
828 button = gtk_button_new_with_label ("Button 2");
830 /* call the same callback function with a different argument,
831 * passing a pointer to "button 2" instead. */
832 gtk_signal_connect (GTK_OBJECT (button), "clicked",
833 GTK_SIGNAL_FUNC (callback), (gpointer) "button 2");
835 gtk_box_pack_start(GTK_BOX(box1), button, TRUE, TRUE, 0);
837 /* The order in which we show the buttons is not really important, but I
838 * recommend showing the window last, so it all pops up at once. */
839 gtk_widget_show(button);
841 gtk_widget_show(box1);
843 gtk_widget_show (window);
845 /* rest in gtk_main and wait for the fun to begin! */
853 Compile this program using the same linking arguments as our first example.
854 You'll notice this time there is no easy way to exit the program, you have
855 to use your window manager or command line to kill it. A good exercise
856 for the reader would be to insert a third "Quit" button that will exit the
857 program. You may also wish to play with the options to
858 gtk_box_pack_start() while reading the next section.
859 Try resizing the window, and observe the behavior.
861 Just as a side note, there is another useful define for gtk_window_new() -
862 GTK_WINDOW_DIALOG. This interacts with the window manager a little
863 differently and should be used for transient windows.
865 <!-- ***************************************************************** -->
866 <sect>Packing Widgets
867 <!-- ***************************************************************** -->
869 When creating an application, you'll want to put more than one widget
870 inside a window. Our first hello world example only used one widget so we
871 could simply use a gtk_container_add call to "pack" the widget into the
872 window. But when you want to put more than one widget into a window, how
873 do you control where that widget is positioned? This is where packing
876 <!-- ----------------------------------------------------------------- -->
877 <sect1>Theory of Packing Boxes
879 Most packing is done by creating boxes as in the example above. These are
880 invisible widget containers that we can pack our widgets into which come in
881 two forms, a horizontal box, and a vertical box. When packing widgets
882 into a horizontal box, the objects are inserted horizontally from left to
883 right or right to left depending on the call used. In a vertical box,
884 widgets are packed from top to bottom or vice versa. You may use any
885 combination of boxes inside or beside other boxes to create the desired
888 To create a new horizontal box, we use a call to gtk_hbox_new(), and for
889 vertical boxes, gtk_vbox_new(). The gtk_box_pack_start() and
890 gtk_box_pack_end() functions are used to place objects inside of these
891 containers. The gtk_box_pack_start() function will start at the top and
892 work its way down in a vbox, and pack left to right in an hbox.
893 gtk_box_pack_end() will do the opposite, packing from bottom to top in a
894 vbox, and right to left in an hbox. Using these functions allow us to
895 right justify or left justify our widgets and may be mixed in any way to
896 achieve the desired effect. We will use gtk_box_pack_start() in most of
897 our examples. An object may be another container or a widget. In
898 fact, many widgets are actually containers themselves, including the
899 button, but we usually only use a label inside a button.
901 By using these calls, GTK knows where you want to place your widgets so it
902 can do automatic resizing and other nifty things. There's also a number
903 of options as to how your widgets should be packed. As you can imagine,
904 this method gives us a quite a bit of flexibility when placing and
907 <!-- ----------------------------------------------------------------- -->
908 <sect1>Details of Boxes
910 Because of this flexibility, packing boxes in GTK can be confusing at
911 first. There are a lot of options, and it's not immediately obvious how
912 they all fit together. In the end however, there are basically five
917 <IMG SRC="gtk_tut_packbox1.gif" VSPACE="15" HSPACE="10" WIDTH="528" HEIGHT="235"
918 ALT="Box Packing Example Image">
922 Each line contains one horizontal box (hbox) with several buttons. The
923 call to gtk_box_pack is shorthand for the call to pack each of the buttons
924 into the hbox. Each of the buttons is packed into the hbox the same way
925 (i.e. same arguments to the gtk_box_pack_start() function).
927 This is the declaration of the gtk_box_pack_start function.
930 void gtk_box_pack_start( GtkBox *box,
937 The first argument is the box you are packing the object into, the second
938 is the object. The objects will all be buttons for now, so we'll be
939 packing buttons into boxes.
941 The expand argument to gtk_box_pack_start() and gtk_box_pack_end() controls
942 whether the widgets are laid out in the box to fill in all the extra space
943 in the box so the box is expanded to fill the area alloted to it (TRUE).
944 Or the box is shrunk to just fit the widgets (FALSE). Setting expand to
945 FALSE will allow you to do right and left justification of your widgets.
946 Otherwise, they will all expand to fit into the box, and the same effect
947 could be achieved by using only one of gtk_box_pack_start or pack_end functions.
949 The fill argument to the gtk_box_pack functions control whether the extra
950 space is allocated to the objects themselves (TRUE), or as extra padding
951 in the box around these objects (FALSE). It only has an effect if the
952 expand argument is also TRUE.
954 When creating a new box, the function looks like this:
957 GtkWidget *gtk_hbox_new (gint homogeneous,
961 The homogeneous argument to gtk_hbox_new (and the same for gtk_vbox_new)
962 controls whether each object in the box has the same size (i.e. the same
963 width in an hbox, or the same height in a vbox). If it is set, the expand
964 argument to the gtk_box_pack routines is always turned on.
966 What's the difference between spacing (set when the box is created) and
967 padding (set when elements are packed)? Spacing is added between objects,
968 and padding is added on either side of an object. The following figure
969 should make it clearer:
973 <IMG ALIGN="center" SRC="gtk_tut_packbox2.gif" WIDTH="509" HEIGHT="213"
974 VSPACE="15" HSPACE="10" ALT="Box Packing Example Image">
978 Here is the code used to create the above images. I've commented it fairly
979 heavily so hopefully you won't have any problems following it. Compile it
980 yourself and play with it.
982 <!-- ----------------------------------------------------------------- -->
983 <sect1>Packing Demonstration Program
986 /* example-start packbox/packbox.c */
991 delete_event (GtkWidget *widget, GdkEvent *event, gpointer data)
996 /* Make a new hbox filled with button-labels. Arguments for the
997 * variables we're interested are passed in to this function.
998 * We do not show the box, but do show everything inside. */
999 GtkWidget *make_box (gint homogeneous, gint spacing,
1000 gint expand, gint fill, gint padding)
1006 /* create a new hbox with the appropriate homogeneous and spacing
1008 box = gtk_hbox_new (homogeneous, spacing);
1010 /* create a series of buttons with the appropriate settings */
1011 button = gtk_button_new_with_label ("gtk_box_pack");
1012 gtk_box_pack_start (GTK_BOX (box), button, expand, fill, padding);
1013 gtk_widget_show (button);
1015 button = gtk_button_new_with_label ("(box,");
1016 gtk_box_pack_start (GTK_BOX (box), button, expand, fill, padding);
1017 gtk_widget_show (button);
1019 button = gtk_button_new_with_label ("button,");
1020 gtk_box_pack_start (GTK_BOX (box), button, expand, fill, padding);
1021 gtk_widget_show (button);
1023 /* create a button with the label depending on the value of
1026 button = gtk_button_new_with_label ("TRUE,");
1028 button = gtk_button_new_with_label ("FALSE,");
1030 gtk_box_pack_start (GTK_BOX (box), button, expand, fill, padding);
1031 gtk_widget_show (button);
1033 /* This is the same as the button creation for "expand"
1034 * above, but uses the shorthand form. */
1035 button = gtk_button_new_with_label (fill ? "TRUE," : "FALSE,");
1036 gtk_box_pack_start (GTK_BOX (box), button, expand, fill, padding);
1037 gtk_widget_show (button);
1039 sprintf (padstr, "%d);", padding);
1041 button = gtk_button_new_with_label (padstr);
1042 gtk_box_pack_start (GTK_BOX (box), button, expand, fill, padding);
1043 gtk_widget_show (button);
1049 main (int argc, char *argv[])
1055 GtkWidget *separator;
1060 /* Our init, don't forget this! :) */
1061 gtk_init (&argc, &argv);
1064 fprintf (stderr, "usage: packbox num, where num is 1, 2, or 3.\n");
1065 /* this just does cleanup in GTK, and exits with an exit status of 1. */
1069 which = atoi (argv[1]);
1071 /* Create our window */
1072 window = gtk_window_new (GTK_WINDOW_TOPLEVEL);
1074 /* You should always remember to connect the destroy signal to the
1075 * main window. This is very important for proper intuitive
1077 gtk_signal_connect (GTK_OBJECT (window), "delete_event",
1078 GTK_SIGNAL_FUNC (delete_event), NULL);
1079 gtk_container_border_width (GTK_CONTAINER (window), 10);
1081 /* We create a vertical box (vbox) to pack the horizontal boxes into.
1082 * This allows us to stack the horizontal boxes filled with buttons one
1083 * on top of the other in this vbox. */
1084 box1 = gtk_vbox_new (FALSE, 0);
1086 /* which example to show. These correspond to the pictures above. */
1089 /* create a new label. */
1090 label = gtk_label_new ("gtk_hbox_new (FALSE, 0);");
1092 /* Align the label to the left side. We'll discuss this function and
1093 * others in the section on Widget Attributes. */
1094 gtk_misc_set_alignment (GTK_MISC (label), 0, 0);
1096 /* Pack the label into the vertical box (vbox box1). Remember that
1097 * widgets added to a vbox will be packed one on top of the other in
1099 gtk_box_pack_start (GTK_BOX (box1), label, FALSE, FALSE, 0);
1101 /* show the label */
1102 gtk_widget_show (label);
1104 /* call our make box function - homogeneous = FALSE, spacing = 0,
1105 * expand = FALSE, fill = FALSE, padding = 0 */
1106 box2 = make_box (FALSE, 0, FALSE, FALSE, 0);
1107 gtk_box_pack_start (GTK_BOX (box1), box2, FALSE, FALSE, 0);
1108 gtk_widget_show (box2);
1110 /* call our make box function - homogeneous = FALSE, spacing = 0,
1111 * expand = FALSE, fill = FALSE, padding = 0 */
1112 box2 = make_box (FALSE, 0, TRUE, FALSE, 0);
1113 gtk_box_pack_start (GTK_BOX (box1), box2, FALSE, FALSE, 0);
1114 gtk_widget_show (box2);
1116 /* Args are: homogeneous, spacing, expand, fill, padding */
1117 box2 = make_box (FALSE, 0, TRUE, TRUE, 0);
1118 gtk_box_pack_start (GTK_BOX (box1), box2, FALSE, FALSE, 0);
1119 gtk_widget_show (box2);
1121 /* creates a separator, we'll learn more about these later,
1122 * but they are quite simple. */
1123 separator = gtk_hseparator_new ();
1125 /* pack the separator into the vbox. Remember each of these
1126 * widgets are being packed into a vbox, so they'll be stacked
1128 gtk_box_pack_start (GTK_BOX (box1), separator, FALSE, TRUE, 5);
1129 gtk_widget_show (separator);
1131 /* create another new label, and show it. */
1132 label = gtk_label_new ("gtk_hbox_new (TRUE, 0);");
1133 gtk_misc_set_alignment (GTK_MISC (label), 0, 0);
1134 gtk_box_pack_start (GTK_BOX (box1), label, FALSE, FALSE, 0);
1135 gtk_widget_show (label);
1137 /* Args are: homogeneous, spacing, expand, fill, padding */
1138 box2 = make_box (TRUE, 0, TRUE, FALSE, 0);
1139 gtk_box_pack_start (GTK_BOX (box1), box2, FALSE, FALSE, 0);
1140 gtk_widget_show (box2);
1142 /* Args are: homogeneous, spacing, expand, fill, padding */
1143 box2 = make_box (TRUE, 0, TRUE, TRUE, 0);
1144 gtk_box_pack_start (GTK_BOX (box1), box2, FALSE, FALSE, 0);
1145 gtk_widget_show (box2);
1147 /* another new separator. */
1148 separator = gtk_hseparator_new ();
1149 /* The last 3 arguments to gtk_box_pack_start are: expand, fill, padding. */
1150 gtk_box_pack_start (GTK_BOX (box1), separator, FALSE, TRUE, 5);
1151 gtk_widget_show (separator);
1157 /* create a new label, remember box1 is a vbox as created
1158 * near the beginning of main() */
1159 label = gtk_label_new ("gtk_hbox_new (FALSE, 10);");
1160 gtk_misc_set_alignment (GTK_MISC (label), 0, 0);
1161 gtk_box_pack_start (GTK_BOX (box1), label, FALSE, FALSE, 0);
1162 gtk_widget_show (label);
1164 /* Args are: homogeneous, spacing, expand, fill, padding */
1165 box2 = make_box (FALSE, 10, TRUE, FALSE, 0);
1166 gtk_box_pack_start (GTK_BOX (box1), box2, FALSE, FALSE, 0);
1167 gtk_widget_show (box2);
1169 /* Args are: homogeneous, spacing, expand, fill, padding */
1170 box2 = make_box (FALSE, 10, TRUE, TRUE, 0);
1171 gtk_box_pack_start (GTK_BOX (box1), box2, FALSE, FALSE, 0);
1172 gtk_widget_show (box2);
1174 separator = gtk_hseparator_new ();
1175 /* The last 3 arguments to gtk_box_pack_start are: expand, fill, padding. */
1176 gtk_box_pack_start (GTK_BOX (box1), separator, FALSE, TRUE, 5);
1177 gtk_widget_show (separator);
1179 label = gtk_label_new ("gtk_hbox_new (FALSE, 0);");
1180 gtk_misc_set_alignment (GTK_MISC (label), 0, 0);
1181 gtk_box_pack_start (GTK_BOX (box1), label, FALSE, FALSE, 0);
1182 gtk_widget_show (label);
1184 /* Args are: homogeneous, spacing, expand, fill, padding */
1185 box2 = make_box (FALSE, 0, TRUE, FALSE, 10);
1186 gtk_box_pack_start (GTK_BOX (box1), box2, FALSE, FALSE, 0);
1187 gtk_widget_show (box2);
1189 /* Args are: homogeneous, spacing, expand, fill, padding */
1190 box2 = make_box (FALSE, 0, TRUE, TRUE, 10);
1191 gtk_box_pack_start (GTK_BOX (box1), box2, FALSE, FALSE, 0);
1192 gtk_widget_show (box2);
1194 separator = gtk_hseparator_new ();
1195 /* The last 3 arguments to gtk_box_pack_start are: expand, fill, padding. */
1196 gtk_box_pack_start (GTK_BOX (box1), separator, FALSE, TRUE, 5);
1197 gtk_widget_show (separator);
1202 /* This demonstrates the ability to use gtk_box_pack_end() to
1203 * right justify widgets. First, we create a new box as before. */
1204 box2 = make_box (FALSE, 0, FALSE, FALSE, 0);
1205 /* create the label that will be put at the end. */
1206 label = gtk_label_new ("end");
1207 /* pack it using gtk_box_pack_end(), so it is put on the right side
1208 * of the hbox created in the make_box() call. */
1209 gtk_box_pack_end (GTK_BOX (box2), label, FALSE, FALSE, 0);
1210 /* show the label. */
1211 gtk_widget_show (label);
1213 /* pack box2 into box1 (the vbox remember ? :) */
1214 gtk_box_pack_start (GTK_BOX (box1), box2, FALSE, FALSE, 0);
1215 gtk_widget_show (box2);
1217 /* a separator for the bottom. */
1218 separator = gtk_hseparator_new ();
1219 /* this explicitly sets the separator to 400 pixels wide by 5 pixels
1220 * high. This is so the hbox we created will also be 400 pixels wide,
1221 * and the "end" label will be separated from the other labels in the
1222 * hbox. Otherwise, all the widgets in the hbox would be packed as
1223 * close together as possible. */
1224 gtk_widget_set_usize (separator, 400, 5);
1225 /* pack the separator into the vbox (box1) created near the start
1227 gtk_box_pack_start (GTK_BOX (box1), separator, FALSE, TRUE, 5);
1228 gtk_widget_show (separator);
1231 /* Create another new hbox.. remember we can use as many as we need! */
1232 quitbox = gtk_hbox_new (FALSE, 0);
1234 /* Our quit button. */
1235 button = gtk_button_new_with_label ("Quit");
1237 /* setup the signal to destroy the window. Remember that this will send
1238 * the "destroy" signal to the window which will be caught by our signal
1239 * handler as defined above. */
1240 gtk_signal_connect_object (GTK_OBJECT (button), "clicked",
1241 GTK_SIGNAL_FUNC (gtk_main_quit),
1242 GTK_OBJECT (window));
1243 /* pack the button into the quitbox.
1244 * The last 3 arguments to gtk_box_pack_start are: expand, fill, padding. */
1245 gtk_box_pack_start (GTK_BOX (quitbox), button, TRUE, FALSE, 0);
1246 /* pack the quitbox into the vbox (box1) */
1247 gtk_box_pack_start (GTK_BOX (box1), quitbox, FALSE, FALSE, 0);
1249 /* pack the vbox (box1) which now contains all our widgets, into the
1251 gtk_container_add (GTK_CONTAINER (window), box1);
1253 /* and show everything left */
1254 gtk_widget_show (button);
1255 gtk_widget_show (quitbox);
1257 gtk_widget_show (box1);
1258 /* Showing the window last so everything pops up at once. */
1259 gtk_widget_show (window);
1261 /* And of course, our main function. */
1264 /* control returns here when gtk_main_quit() is called, but not when
1265 * gtk_exit is used. */
1272 <!-- ----------------------------------------------------------------- -->
1273 <sect1>Packing Using Tables
1275 Let's take a look at another way of packing - Tables. These can be
1276 extremely useful in certain situations.
1278 Using tables, we create a grid that we can place widgets in. The widgets
1279 may take up as many spaces as we specify.
1281 The first thing to look at of course, is the gtk_table_new function:
1284 GtkWidget *gtk_table_new( gint rows,
1289 The first argument is the number of rows to make in the table, while the
1290 second, obviously, is the number of columns.
1292 The homogeneous argument has to do with how the table's boxes are sized. If
1293 homogeneous is TRUE, the table boxes are resized to the size of the largest
1294 widget in the table. If homogeneous is FALSE, the size of a table boxes is
1295 dictated by the tallest widget in its same row, and the widest widget in its
1298 The rows and columnts are laid out from 0 to n, where n was the
1299 number specified in the call to gtk_table_new. So, if you specify rows = 2 and
1300 columns = 2, the layout would look something like this:
1304 0+----------+----------+
1306 1+----------+----------+
1308 2+----------+----------+
1311 Note that the coordinate system starts in the upper left hand corner. To place a
1312 widget into a box, use the following function:
1315 void gtk_table_attach( GtkTable *table,
1327 Where the first argument ("table") is the table you've created and the second
1328 ("child") the widget you wish to place in the table.
1330 The left and right attach arguments specify where to place the widget, and how
1331 many boxes to use. If you want a button in the lower right table entry
1332 of our 2x2 table, and want it to fill that entry ONLY. left_attach would be = 1,
1333 right_attach = 2, top_attach = 1, bottom_attach = 2.
1335 Now, if you wanted a widget to take up the whole
1336 top row of our 2x2 table, you'd use left_attach = 0, right_attach = 2,
1337 top_attach = 0, bottom_attach = 1.
1339 The xoptions and yoptions are used to specify packing options and may be OR'ed
1340 together to allow multiple options.
1344 <item>GTK_FILL - If the table box is larger than the widget, and GTK_FILL is
1345 specified, the widget will expand to use all the room available.
1347 <item>GTK_SHRINK - If the table widget was allocated less space then was
1348 requested (usually by the user resizing the window), then the widgets would
1349 normally just be pushed off the bottom of
1350 the window and disappear. If GTK_SHRINK is specified, the widgets will
1351 shrink with the table.
1353 <item>GTK_EXPAND - This will cause the table to expand to use up any remaining
1354 space in the window.
1357 Padding is just like in boxes, creating a clear area around the widget
1358 specified in pixels.
1360 gtk_table_attach() has a LOT of options. So, there's a shortcut:
1363 void gtk_table_attach_defaults( GtkTable *table,
1368 gint bottom_attach );
1371 The X and Y options default to GTK_FILL | GTK_EXPAND, and X and Y padding
1372 are set to 0. The rest of the arguments are identical to the previous
1375 We also have gtk_table_set_row_spacing() and gtk_table_set_col_spacing().
1376 This places spacing between the rows at the specified row or column.
1379 void gtk_table_set_row_spacing( GtkTable *table,
1387 void gtk_table_set_col_spacing ( GtkTable *table,
1392 Note that for columns, the space goes to the right of the column, and for
1393 rows, the space goes below the row.
1395 You can also set a consistent spacing of all rows and/or columns with:
1398 void gtk_table_set_row_spacings( GtkTable *table,
1405 void gtk_table_set_col_spacings( GtkTable *table,
1409 Note that with these calls, the last row and last column do not get any
1412 <!-- ----------------------------------------------------------------- -->
1413 <sect1>Table Packing Example
1415 Here we make a window with three buttons in a 2x2 table.
1416 The first two buttons will be placed in the upper row.
1417 A third, quit button, is placed in the lower row, spanning both columns.
1418 Which means it should look something like this:
1422 <IMG SRC="gtk_tut_table.gif" VSPACE="15" HSPACE="10"
1423 ALT="Table Packing Example Image" WIDTH="180" HEIGHT="120">
1427 Here's the source code:
1430 /* example-start table/table.c */
1431 #include <gtk/gtk.h>
1434 * the data passed to this function is printed to stdout */
1435 void callback (GtkWidget *widget, gpointer data)
1437 g_print ("Hello again - %s was pressed\n", (char *) data);
1440 /* this callback quits the program */
1441 void delete_event (GtkWidget *widget, GdkEvent *event, gpointer data)
1446 int main (int argc, char *argv[])
1452 gtk_init (&argc, &argv);
1454 /* create a new window */
1455 window = gtk_window_new (GTK_WINDOW_TOPLEVEL);
1457 /* set the window title */
1458 gtk_window_set_title (GTK_WINDOW (window), "Table");
1460 /* set a handler for delete_event that immediately
1462 gtk_signal_connect (GTK_OBJECT (window), "delete_event",
1463 GTK_SIGNAL_FUNC (delete_event), NULL);
1465 /* sets the border width of the window. */
1466 gtk_container_border_width (GTK_CONTAINER (window), 20);
1468 /* create a 2x2 table */
1469 table = gtk_table_new (2, 2, TRUE);
1471 /* put the table in the main window */
1472 gtk_container_add (GTK_CONTAINER (window), table);
1474 /* create first button */
1475 button = gtk_button_new_with_label ("button 1");
1477 /* when the button is clicked, we call the "callback" function
1478 * with a pointer to "button 1" as it's argument */
1479 gtk_signal_connect (GTK_OBJECT (button), "clicked",
1480 GTK_SIGNAL_FUNC (callback), (gpointer) "button 1");
1483 /* insert button 1 into the upper left quadrant of the table */
1484 gtk_table_attach_defaults (GTK_TABLE(table), button, 0, 1, 0, 1);
1486 gtk_widget_show (button);
1488 /* create second button */
1490 button = gtk_button_new_with_label ("button 2");
1492 /* when the button is clicked, we call the "callback" function
1493 * with a pointer to "button 2" as it's argument */
1494 gtk_signal_connect (GTK_OBJECT (button), "clicked",
1495 GTK_SIGNAL_FUNC (callback), (gpointer) "button 2");
1496 /* insert button 2 into the upper right quadrant of the table */
1497 gtk_table_attach_defaults (GTK_TABLE(table), button, 1, 2, 0, 1);
1499 gtk_widget_show (button);
1501 /* create "Quit" button */
1502 button = gtk_button_new_with_label ("Quit");
1504 /* when the button is clicked, we call the "delete_event" function
1505 * and the program exits */
1506 gtk_signal_connect (GTK_OBJECT (button), "clicked",
1507 GTK_SIGNAL_FUNC (delete_event), NULL);
1509 /* insert the quit button into the both
1510 * lower quadrants of the table */
1511 gtk_table_attach_defaults (GTK_TABLE(table), button, 0, 2, 1, 2);
1513 gtk_widget_show (button);
1515 gtk_widget_show (table);
1516 gtk_widget_show (window);
1525 <!-- ***************************************************************** -->
1526 <sect>Widget Overview
1527 <!-- ***************************************************************** -->
1529 The general steps to creating a widget in GTK are:
1531 <item> gtk_*_new - one of various functions to create a new widget. These
1532 are all detailed in this section.
1534 <item> Connect all signals and events we wish to use to the
1535 appropriate handlers.
1537 <item> Set the attributes of the widget.
1539 <item> Pack the widget into a container using the appropriate call such as
1540 gtk_container_add() or gtk_box_pack_start().
1542 <item> gtk_widget_show() the widget.
1545 gtk_widget_show() lets GTK know that we are done setting the attributes
1546 of the widget, and it is ready to be displayed. You may also use
1547 gtk_widget_hide to make it disappear again. The order in which you
1548 show the widgets is not important, but I suggest showing the window
1549 last so the whole window pops up at once rather than seeing the individual
1550 widgets come up on the screen as they're formed. The children of a widget
1551 (a window is a widget too) will not be displayed until the window itself
1552 is shown using the gtk_widget_show() function.
1554 <!-- ----------------------------------------------------------------- -->
1557 You'll notice as you go on, that GTK uses a type casting system. This is
1558 always done using macros that both test the ability to cast the given item,
1559 and perform the cast. Some common ones you will see are:
1562 <item> GTK_WIDGET(widget)
1563 <item> GTK_OBJECT(object)
1564 <item> GTK_SIGNAL_FUNC(function)
1565 <item> GTK_CONTAINER(container)
1566 <item> GTK_WINDOW(window)
1570 These are all used to cast arguments in functions. You'll see them in the
1571 examples, and can usually tell when to use them simply by looking at the
1572 function's declaration.
1574 As you can see below in the class hierarchy, all GtkWidgets are derived from
1575 the GtkObject base class. This means you can use a widget in any place the
1576 function asks for an object - simply use the GTK_OBJECT() macro.
1581 gtk_signal_connect( GTK_OBJECT(button), "clicked",
1582 GTK_SIGNAL_FUNC(callback_function), callback_data);
1585 This casts the button into an object, and provides a cast for the function
1586 pointer to the callback.
1588 Many widgets are also containers. If you look in the class hierarchy below,
1589 you'll notice that many widgets derive from the GtkContainer class. Any one
1590 of these widgets may be used with the GTK_CONTAINER macro to pass them to
1591 functions that ask for containers.
1593 Unfortunately, these macros are not extensively covered in the tutorial, but I
1594 recomend taking a look through the GTK header files. It can be very
1595 educational. In fact, it's not difficult to learn how a widget works just
1596 by looking at the function declarations.
1598 <!-- ----------------------------------------------------------------- -->
1599 <sect1>Widget Hierarchy
1601 For your reference, here is the class hierarchy tree used to implement widgets.
1614 | | | `GtkAspectFrame
1619 | | | | `GtkCheckMenuItem
1620 | | | | `GtkRadioMenuItem
1624 | | +GtkColorSelectionDialog
1626 | | | `GtkInputDialog
1627 | | `GtkFileSelection
1630 | | | +GtkHButtonBox
1631 | | | `GtkVButtonBox
1636 | | +GtkColorSelection
1640 | | `GtkToggleButton
1654 | +GtkScrolledWindow
1687 <!-- ----------------------------------------------------------------- -->
1688 <sect1>Widgets Without Windows
1690 The following widgets do not have an associated window. If you want to
1691 capture events, you'll have to use the GtkEventBox. See the section on
1692 <ref id="sec_The_EventBox_Widget" name="The EventBox Widget">
1714 We'll further our exploration of GTK by examining each widget in turn,
1715 creating a few simple functions to display them. Another good source is
1716 the testgtk.c program that comes with GTK. It can be found in
1719 <!-- ***************************************************************** -->
1720 <sect>The Button Widget
1721 <!-- ***************************************************************** -->
1723 <!-- ----------------------------------------------------------------- -->
1724 <sect1>Normal Buttons
1726 We've almost seen all there is to see of the button widget. It's pretty
1727 simple. There is however two ways to create a button. You can use the
1728 gtk_button_new_with_label() to create a button with a label, or use
1729 gtk_button_new() to create a blank button. It's then up to you to pack a
1730 label or pixmap into this new button. To do this, create a new box, and
1731 then pack your objects into this box using the usual gtk_box_pack_start,
1732 and then use gtk_container_add to pack the box into the button.
1734 Here's an example of using gtk_button_new to create a button with a
1735 picture and a label in it. I've broken the code to create a box up from
1736 the rest so you can use it in your programs.
1739 /* example-start buttons/buttons.c */
1741 #include <gtk/gtk.h>
1743 /* create a new hbox with an image and a label packed into it
1744 * and return the box.. */
1746 GtkWidget *xpm_label_box (GtkWidget *parent, gchar *xpm_filename, gchar *label_text)
1750 GtkWidget *pixmapwid;
1755 /* create box for xpm and label */
1756 box1 = gtk_hbox_new (FALSE, 0);
1757 gtk_container_border_width (GTK_CONTAINER (box1), 2);
1759 /* get style of button.. I assume it's to get the background color.
1760 * if someone knows the real reason, please enlighten me. */
1761 style = gtk_widget_get_style(parent);
1763 /* now on to the xpm stuff.. load xpm */
1764 pixmap = gdk_pixmap_create_from_xpm (parent->window, &mask,
1765 &style->bg[GTK_STATE_NORMAL],
1767 pixmapwid = gtk_pixmap_new (pixmap, mask);
1769 /* create label for button */
1770 label = gtk_label_new (label_text);
1772 /* pack the pixmap and label into the box */
1773 gtk_box_pack_start (GTK_BOX (box1),
1774 pixmapwid, FALSE, FALSE, 3);
1776 gtk_box_pack_start (GTK_BOX (box1), label, FALSE, FALSE, 3);
1778 gtk_widget_show(pixmapwid);
1779 gtk_widget_show(label);
1784 /* our usual callback function */
1785 void callback (GtkWidget *widget, gpointer data)
1787 g_print ("Hello again - %s was pressed\n", (char *) data);
1791 int main (int argc, char *argv[])
1793 /* GtkWidget is the storage type for widgets */
1798 gtk_init (&argc, &argv);
1800 /* create a new window */
1801 window = gtk_window_new (GTK_WINDOW_TOPLEVEL);
1803 gtk_window_set_title (GTK_WINDOW (window), "Pixmap'd Buttons!");
1805 /* It's a good idea to do this for all windows. */
1806 gtk_signal_connect (GTK_OBJECT (window), "destroy",
1807 GTK_SIGNAL_FUNC (gtk_exit), NULL);
1809 gtk_signal_connect (GTK_OBJECT (window), "delete_event",
1810 GTK_SIGNAL_FUNC (gtk_exit), NULL);
1813 /* sets the border width of the window. */
1814 gtk_container_border_width (GTK_CONTAINER (window), 10);
1815 gtk_widget_realize(window);
1817 /* create a new button */
1818 button = gtk_button_new ();
1820 /* You should be getting used to seeing most of these functions by now */
1821 gtk_signal_connect (GTK_OBJECT (button), "clicked",
1822 GTK_SIGNAL_FUNC (callback), (gpointer) "cool button");
1824 /* this calls our box creating function */
1825 box1 = xpm_label_box(window, "info.xpm", "cool button");
1827 /* pack and show all our widgets */
1828 gtk_widget_show(box1);
1830 gtk_container_add (GTK_CONTAINER (button), box1);
1832 gtk_widget_show(button);
1834 gtk_container_add (GTK_CONTAINER (window), button);
1836 gtk_widget_show (window);
1838 /* rest in gtk_main and wait for the fun to begin! */
1846 The xpm_label_box function could be used to pack xpm's and labels into any
1847 widget that can be a container.
1849 The Buton widget has the following signals:
1859 <!-- ----------------------------------------------------------------- -->
1860 <sect1> Toggle Buttons
1862 Toggle buttons are derived from normal buttons and are very similar, except
1863 they will always be in one of two states, alternated by a click. They may
1864 be depressed, and when you click again, they will pop back up. Click again,
1865 and they will pop back down.
1867 Toggle buttons are the basis for check buttons and radio buttons, as such,
1868 many of the calls used for toggle buttons are inherited by radio and check
1869 buttons. I will point these out when we come to them.
1871 Creating a new toggle button:
1874 GtkWidget *gtk_toggle_button_new( void );
1876 GtkWidget *gtk_toggle_button_new_with_label( gchar *label );
1879 As you can imagine, these work identically to the normal button widget
1880 calls. The first creates a blank toggle button, and the second, a button
1881 with a label widget already packed into it.
1883 To retrieve the state of the toggle widget, including radio and check
1884 buttons, we use a macro as shown in our example below. This tests the state
1885 of the toggle in a callback. The signal of interest emitted to us by toggle
1886 buttons (the toggle button, check button, and radio button widgets), is the
1887 "toggled" signal. To check the state of these buttons, set up a signal
1888 handler to catch the toggled signal, and use the macro to determine it's
1889 state. The callback will look something like:
1892 void toggle_button_callback (GtkWidget *widget, gpointer data)
1894 if (GTK_TOGGLE_BUTTON (widget)->active)
1896 /* If control reaches here, the toggle button is down */
1900 /* If control reaches here, the toggle button is up */
1906 void gtk_toggle_button_set_state( GtkToggleButton *toggle_button,
1910 The above call can be used to set the state of the toggle button, and it's
1911 children the radio and check buttons. Passing in your created button as
1912 the first argument, and a TRUE or FALSE for the second state argument to
1913 specify whether it should be up (released) or down (depressed). Default
1916 Note that when you use the gtk_toggle_button_set_state() function, and the
1917 state is actually changed, it causes the "clicked" signal to be emitted
1921 void gtk_toggle_button_toggled (GtkToggleButton *toggle_button);
1924 This simply toggles the button, and emits the "toggled" signal.
1926 <!-- ----------------------------------------------------------------- -->
1927 <sect1> Check Buttons
1929 Check buttons inherent many properties and functions from the the toggle
1930 buttons above, but look a little different. Rather than being buttons with
1931 text inside them, they are small squares with the text to the right of
1932 them. These are often used for toggling options on and off in applications.
1934 The two creation functions are similar to those of the normal button.
1937 GtkWidget *gtk_check_button_new( void );
1939 GtkWidget *gtk_check_button_new_with_label ( gchar *label );
1942 The new_with_label function creates a check button with a label beside it.
1944 Checking the state of the check button is identical to that of the toggle
1947 <!-- ----------------------------------------------------------------- -->
1948 <sect1> Radio Buttons
1950 Radio buttons are similar to check buttons except they are grouped so that
1951 only one may be selected/depressed at a time. This is good for places in
1952 your application where you need to select from a short list of options.
1954 Creating a new radio button is done with one of these calls:
1957 GtkWidget *gtk_radio_button_new( GSList *group );
1959 GtkWidget *gtk_radio_button_new_with_label( GSList *group,
1963 You'll notice the extra argument to these calls. They require a group to
1964 perform they're duty properly. The first call should pass NULL as the first
1965 argument. Then create a group using:
1968 GSList *gtk_radio_button_group( GtkRadioButton *radio_button );
1971 The important thing to remember is that gtk_radio_button_group must be
1972 called for each new button added to the group, with the previous button
1973 passed in as an argument. The result is then passed into the call to
1974 gtk_radio_button_new or gtk_radio_button_new_with_label. This allows a
1975 chain of buttons to be established. The example below should make this
1978 It is also a good idea to explicitly set which button should be the
1979 default depressed button with:
1982 void gtk_toggle_button_set_state( GtkToggleButton *toggle_button,
1986 This is described in the section on toggle buttons, and works in exactly the
1989 The following example creates a radio button group with three buttons.
1992 /* example-start radiobuttons/radiobuttons.c */
1994 #include <gtk/gtk.h>
1997 void close_application( GtkWidget *widget, GdkEvent *event, gpointer data ) {
2001 main(int argc,char *argv[])
2003 static GtkWidget *window = NULL;
2007 GtkWidget *separator;
2010 gtk_init(&argc,&argv);
2011 window = gtk_window_new (GTK_WINDOW_TOPLEVEL);
2013 gtk_signal_connect (GTK_OBJECT (window), "delete_event",
2014 GTK_SIGNAL_FUNC(close_application),
2017 gtk_window_set_title (GTK_WINDOW (window), "radio buttons");
2018 gtk_container_border_width (GTK_CONTAINER (window), 0);
2020 box1 = gtk_vbox_new (FALSE, 0);
2021 gtk_container_add (GTK_CONTAINER (window), box1);
2022 gtk_widget_show (box1);
2024 box2 = gtk_vbox_new (FALSE, 10);
2025 gtk_container_border_width (GTK_CONTAINER (box2), 10);
2026 gtk_box_pack_start (GTK_BOX (box1), box2, TRUE, TRUE, 0);
2027 gtk_widget_show (box2);
2029 button = gtk_radio_button_new_with_label (NULL, "button1");
2030 gtk_box_pack_start (GTK_BOX (box2), button, TRUE, TRUE, 0);
2031 gtk_widget_show (button);
2033 group = gtk_radio_button_group (GTK_RADIO_BUTTON (button));
2034 button = gtk_radio_button_new_with_label(group, "button2");
2035 gtk_toggle_button_set_state (GTK_TOGGLE_BUTTON (button), TRUE);
2036 gtk_box_pack_start (GTK_BOX (box2), button, TRUE, TRUE, 0);
2037 gtk_widget_show (button);
2039 group = gtk_radio_button_group (GTK_RADIO_BUTTON (button));
2040 button = gtk_radio_button_new_with_label(group, "button3");
2041 gtk_box_pack_start (GTK_BOX (box2), button, TRUE, TRUE, 0);
2042 gtk_widget_show (button);
2044 separator = gtk_hseparator_new ();
2045 gtk_box_pack_start (GTK_BOX (box1), separator, FALSE, TRUE, 0);
2046 gtk_widget_show (separator);
2048 box2 = gtk_vbox_new (FALSE, 10);
2049 gtk_container_border_width (GTK_CONTAINER (box2), 10);
2050 gtk_box_pack_start (GTK_BOX (box1), box2, FALSE, TRUE, 0);
2051 gtk_widget_show (box2);
2053 button = gtk_button_new_with_label ("close");
2054 gtk_signal_connect_object (GTK_OBJECT (button), "clicked",
2055 GTK_SIGNAL_FUNC(close_application),
2056 GTK_OBJECT (window));
2057 gtk_box_pack_start (GTK_BOX (box2), button, TRUE, TRUE, 0);
2058 GTK_WIDGET_SET_FLAGS (button, GTK_CAN_DEFAULT);
2059 gtk_widget_grab_default (button);
2060 gtk_widget_show (button);
2061 gtk_widget_show (window);
2068 You can shorten this slightly by using the following syntax, which
2069 removes the need for a variable to hold the list of buttons:
2072 button2 = gtk_radio_button_new_with_label(
2073 gtk_radio_button_group (GTK_RADIO_BUTTON (button1)),
2077 <!-- TODO: checout out gtk_radio_button_new_from_widget function - TRG -->
2079 <!-- ***************************************************************** -->
2080 <sect> Miscallaneous Widgets
2081 <!-- ***************************************************************** -->
2083 <!-- ----------------------------------------------------------------- -->
2086 Labels are used a lot in GTK, and are relatively simple. Labels emit no
2087 signals as they do not have an associated X window. If you need to catch
2088 signals, or do clipping, use the EventBox widget.
2090 To create a new label, use:
2093 GtkWidget *gtk_label_new( char *str );
2096 Where the sole argument is the string you wish the label to display.
2098 To change the label's text after creation, use the function:
2101 void gtk_label_set( GtkLabel *label,
2105 Where the first argument is the label you created previously (cast using
2106 the GTK_LABEL() macro), and the second is the new string.
2108 The space needed for the new string will be automatically adjusted if needed.
2110 To retrieve the current string, use:
2113 void gtk_label_get( GtkLabel *label,
2117 Where the first arguement is the label you've created, and the second, the
2118 return for the string.
2120 <!-- ----------------------------------------------------------------- -->
2121 <sect1>The Tooltips Widget
2123 These are the little text strings that pop up when you leave your pointer
2124 over a button or other widget for a few seconds. They are easy to use, so I
2125 will just explain them without giving an example. If you want to see some
2126 code, take a look at the testgtk.c program distributed with GDK.
2128 Some widgets (such as the label) will not work with tooltips.
2130 The first call you will use to create a new tooltip. You only need to do
2131 this once in a given function. The <tt/GtkTooltip/ object this function
2132 returns can be used to create multiple tooltips.
2135 GtkTooltips *gtk_tooltips_new( void );
2138 Once you have created a new tooltip, and the widget you wish to use it on,
2139 simply use this call to set it:
2142 void gtk_tooltips_set_tip( GtkTooltips *tooltips,
2144 const gchar *tip_text,
2145 const gchar *tip_private );
2148 The first argument is the tooltip you've already created, followed by the
2149 widget you wish to have this tooltip pop up for, and the text you wish it to
2150 say. The last argument is a text string that can be used as an identifier when using
2151 GtkTipsQuery to implement context sensitive help. For now, you can set
2153 <!-- TODO: sort out what how to do the context sensitive help -->
2155 Here's a short example:
2158 GtkTooltips *tooltips;
2161 tooltips = gtk_tooltips_new ();
2162 button = gtk_button_new_with_label ("button 1");
2164 gtk_tooltips_set_tip (tooltips, button, "This is button 1", NULL);
2167 There are other calls that can be used with tooltips. I will just
2168 list them with a brief description of what they do.
2171 void gtk_tooltips_enable( GtkTooltips *tooltips );
2174 Enable a disabled set of tooltips.
2177 void gtk_tooltips_disable( GtkTooltips *tooltips );
2180 Disable an enabled set of tooltips.
2183 void gtk_tooltips_set_delay( GtkTooltips *tooltips,
2188 Sets how many milliseconds you have to hold your pointer over the
2189 widget before the tooltip will pop up. The default is 1000 milliseconds
2193 void gtk_tooltips_set_colors( GtkTooltips *tooltips,
2194 GdkColor *background,
2195 GdkColor *foreground );
2198 Set the foreground and background color of the tooltips. Again, I have no
2199 idea how to specify the colors.
2201 And that's all the functions associated with tooltips. More than you'll
2202 ever want to know :)
2204 <!-- ----------------------------------------------------------------- -->
2205 <sect1> Progress Bars
2207 Progress bars are used to show the status of an operation. They are pretty
2208 easy to use, as you will see with the code below. But first lets start out
2209 with the call to create a new progress bar.
2212 GtkWidget *gtk_progress_bar_new( void );
2215 Now that the progress bar has been created we can use it.
2218 void gtk_progress_bar_update( GtkProgressBar *pbar,
2219 gfloat percentage );
2222 The first argument is the progress bar you wish to operate on, and the second
2223 argument is the amount 'completed', meaning the amount the progress bar has
2224 been filled from 0-100%. This is passed to the function as a real number
2225 ranging from 0 to 1.
2227 Progress Bars are usually used with timeouts or other such functions (see
2228 section on <ref id="sec_timeouts" name="Timeouts, I/O and Idle Functions">)
2229 to give the illusion of multitasking. All will employ
2230 the gtk_progress_bar_update function in the same manner.
2232 Here is an example of the progress bar, updated using timeouts. This
2233 code also shows you how to reset the Progress Bar.
2236 /* example-start progressbar/progressbar.c */
2238 #include <gtk/gtk.h>
2240 static int ptimer = 0;
2243 /* This function increments and updates the progress bar, it also resets
2244 the progress bar if pstat is FALSE */
2245 gint progress (gpointer data)
2249 /* get the current value of the progress bar */
2250 pvalue = GTK_PROGRESS_BAR (data)->percentage;
2252 if ((pvalue >= 1.0) || (pstat == FALSE)) {
2258 gtk_progress_bar_update (GTK_PROGRESS_BAR (data), pvalue);
2263 /* This function signals a reset of the progress bar */
2264 void progress_r (void)
2269 void destroy (GtkWidget *widget, GdkEvent *event, gpointer data)
2274 int main (int argc, char *argv[])
2282 gtk_init (&argc, &argv);
2284 window = gtk_window_new (GTK_WINDOW_TOPLEVEL);
2286 gtk_signal_connect (GTK_OBJECT (window), "delete_event",
2287 GTK_SIGNAL_FUNC (destroy), NULL);
2289 gtk_container_border_width (GTK_CONTAINER (window), 10);
2291 table = gtk_table_new(3,2,TRUE);
2292 gtk_container_add (GTK_CONTAINER (window), table);
2294 label = gtk_label_new ("Progress Bar Example");
2295 gtk_table_attach_defaults(GTK_TABLE(table), label, 0,2,0,1);
2296 gtk_widget_show(label);
2298 /* Create a new progress bar, pack it into the table, and show it */
2299 pbar = gtk_progress_bar_new ();
2300 gtk_table_attach_defaults(GTK_TABLE(table), pbar, 0,2,1,2);
2301 gtk_widget_show (pbar);
2303 /* Set the timeout to handle automatic updating of the progress bar */
2304 ptimer = gtk_timeout_add (100, progress, pbar);
2306 /* This button signals the progress bar to be reset */
2307 button = gtk_button_new_with_label ("Reset");
2308 gtk_signal_connect (GTK_OBJECT (button), "clicked",
2309 GTK_SIGNAL_FUNC (progress_r), NULL);
2310 gtk_table_attach_defaults(GTK_TABLE(table), button, 0,1,2,3);
2311 gtk_widget_show(button);
2313 button = gtk_button_new_with_label ("Cancel");
2314 gtk_signal_connect (GTK_OBJECT (button), "clicked",
2315 GTK_SIGNAL_FUNC (destroy), NULL);
2317 gtk_table_attach_defaults(GTK_TABLE(table), button, 1,2,2,3);
2318 gtk_widget_show (button);
2320 gtk_widget_show(table);
2321 gtk_widget_show(window);
2330 In this small program there are four areas that concern the general operation
2331 of Progress Bars, we will look at them in the order they are called.
2334 pbar = gtk_progress_bar_new ();
2337 This code creates a new progress bar, called pbar.
2340 ptimer = gtk_timeout_add (100, progress, pbar);
2343 This code uses timeouts to enable a constant time interval, timeouts are
2344 not necessary in the use of Progress Bars.
2347 pvalue = GTK_PROGRESS_BAR (data)->percentage;
2350 This code assigns the current value of the percentage bar to pvalue.
2353 gtk_progress_bar_update (GTK_PROGRESS_BAR (data), pvalue);
2356 Finally, this code updates the progress bar with the value of pvalue
2358 And that is all there is to know about Progress Bars, enjoy.
2360 <!-- ----------------------------------------------------------------- -->
2363 The Dialog widget is very simple, and is actually just a window with a few
2364 things pre-packed into it for you. The structure for a Dialog is:
2372 GtkWidget *action_area;
2376 So you see, it simply creates a window, and then packs a vbox into the top,
2377 then a seperator, and then an hbox for the "action_area".
2379 The Dialog widget can be used for pop-up messages to the user, and
2380 other similar tasks. It is really basic, and there is only one
2381 function for the dialog box, which is:
2384 GtkWidget *gtk_dialog_new( void );
2387 So to create a new dialog box, use,
2391 window = gtk_dialog_new ();
2394 This will create the dialog box, and it is now up to you to use it.
2395 you could pack a button in the action_area by doing something like this:
2399 gtk_box_pack_start (GTK_BOX (GTK_DIALOG (window)->action_area), button,
2401 gtk_widget_show (button);
2404 And you could add to the vbox area by packing, for instance, a label
2405 in it, try something like this:
2408 label = gtk_label_new ("Dialogs are groovy");
2409 gtk_box_pack_start (GTK_BOX (GTK_DIALOG (window)->vbox), label, TRUE,
2411 gtk_widget_show (label);
2414 As an example in using the dialog box, you could put two buttons in
2415 the action_area, a Cancel button and an Ok button, and a label in the vbox
2416 area, asking the user a question or giving an error etc. Then you could
2417 attach a different signal to each of the buttons and perform the
2418 operation the user selects.
2420 If the simple functionality provided by the default vertical and
2421 horizontal boxes in the two areas don't give you enough control for your
2422 application, then you can simply pack another layout widget into the boxes
2423 provided. For example, you could pack a table into the vertical box.
2425 <!-- ----------------------------------------------------------------- -->
2428 Pixmaps are data structures that contain pictures. These pictures can be
2429 used in various places, but most visibly as icons on the X-Windows desktop,
2430 or as cursors. A bitmap is a 2-color pixmap.
2432 To use pixmaps in GTK, we must first build a GdkPixmap structure using
2433 routines from the GDK layer. Pixmaps can either be created from in-memory
2434 data, or from data read from a file. We'll go through each of the calls
2438 GdkPixmap *gdk_bitmap_create_from_data( GdkWindow *window,
2444 This routine is used to create a single-plane pixmap (2 colors) from data in
2445 memory. Each bit of the data represents whether that pixel is off or on.
2446 Width and height are in pixels. The GdkWindow pointer is to the current
2447 window, since a pixmap resources are meaningful only in the context of the
2448 screen where it is to be displayed.
2451 GdkPixmap *gdk_pixmap_create_from_data( GdkWindow *window,
2460 This is used to create a pixmap of the given depth (number of colors) from
2461 the bitmap data specified. <tt/fg/ and <tt/bg/ are the foreground and
2462 background color to use.
2465 GdkPixmap *gdk_pixmap_create_from_xpm( GdkWindow *window,
2467 GdkColor *transparent_color,
2468 const gchar *filename );
2471 XPM format is a readable pixmap representation for the X Window System. It
2472 is widely used and many different utilities are available for creating image
2473 files in this format. The file specified by filename must contain an image
2474 in that format and it is loaded into the pixmap structure. The mask specifies
2475 which bits of the pixmap are opaque. All other bits are colored using the
2476 color specified by transparent_color. An example using this follows below.
2479 GdkPixmap *gdk_pixmap_create_from_xpm_d( GdkWindow *window,
2481 GdkColor *transparent_color,
2485 Small images can be incorporated into a program as data in the XPM format.
2486 A pixmap is created using this data, instead of reading it from a file.
2487 An example of such data is
2491 static const char * xpm_data[] = {
2494 ". c #000000000000",
2495 "X c #FFFFFFFFFFFF",
2514 When we're done using a pixmap and not likely to reuse it again soon,
2515 it is a good idea to release the resource using gdk_pixmap_unref(). Pixmaps
2516 should be considered a precious resource.
2518 Once we've created a pixmap, we can display it as a GTK widget. We must
2519 create a pixmap widget to contain the GDK pixmap. This is done using
2522 GtkWidget *gtk_pixmap_new( GdkPixmap *pixmap,
2526 The other pixmap widget calls are
2529 guint gtk_pixmap_get_type( void );
2531 void gtk_pixmap_set( GtkPixmap *pixmap,
2535 void gtk_pixmap_get( GtkPixmap *pixmap,
2540 gtk_pixmap_set is used to change the pixmap that the widget is currently
2541 managing. Val is the pixmap created using GDK.
2543 The following is an example of using a pixmap in a button.
2546 /* example-start pixmap/pixmap.c */
2548 #include <gtk/gtk.h>
2551 /* XPM data of Open-File icon */
2552 static const char * xpm_data[] = {
2555 ". c #000000000000",
2556 "X c #FFFFFFFFFFFF",
2575 /* when invoked (via signal delete_event), terminates the application.
2577 void close_application( GtkWidget *widget, GdkEvent *event, gpointer data ) {
2582 /* is invoked when the button is clicked. It just prints a message.
2584 void button_clicked( GtkWidget *widget, gpointer data ) {
2585 printf( "button clicked\n" );
2588 int main( int argc, char *argv[] )
2590 /* GtkWidget is the storage type for widgets */
2591 GtkWidget *window, *pixmapwid, *button;
2596 /* create the main window, and attach delete_event signal to terminating
2598 gtk_init( &argc, &argv );
2599 window = gtk_window_new( GTK_WINDOW_TOPLEVEL );
2600 gtk_signal_connect( GTK_OBJECT (window), "delete_event",
2601 GTK_SIGNAL_FUNC (close_application), NULL );
2602 gtk_container_border_width( GTK_CONTAINER (window), 10 );
2603 gtk_widget_show( window );
2605 /* now for the pixmap from gdk */
2606 style = gtk_widget_get_style( window );
2607 pixmap = gdk_pixmap_create_from_xpm_d( window->window, &mask,
2608 &style->bg[GTK_STATE_NORMAL],
2609 (gchar **)xpm_data );
2611 /* a pixmap widget to contain the pixmap */
2612 pixmapwid = gtk_pixmap_new( pixmap, mask );
2613 gtk_widget_show( pixmapwid );
2615 /* a button to contain the pixmap widget */
2616 button = gtk_button_new();
2617 gtk_container_add( GTK_CONTAINER(button), pixmapwid );
2618 gtk_container_add( GTK_CONTAINER(window), button );
2619 gtk_widget_show( button );
2621 gtk_signal_connect( GTK_OBJECT(button), "clicked",
2622 GTK_SIGNAL_FUNC(button_clicked), NULL );
2624 /* show the window */
2632 To load a file from an XPM data file called icon0.xpm in the current
2633 directory, we would have created the pixmap thus
2636 /* load a pixmap from a file */
2637 pixmap = gdk_pixmap_create_from_xpm( window->window, &mask,
2638 &style->bg[GTK_STATE_NORMAL],
2640 pixmapwid = gtk_pixmap_new( pixmap, mask );
2641 gtk_widget_show( pixmapwid );
2642 gtk_container_add( GTK_CONTAINER(window), pixmapwid );
2645 A disadvantage of using pixmaps is that the displayed object is always
2646 rectangular, regardless of the image. We would like to create desktops
2647 and applications with icons that have more natural shapes. For example,
2648 for a game interface, we would like to have round buttons to push. The
2649 way to do this is using shaped windows.
2651 A shaped window is simply a pixmap where the background pixels are
2652 transparent. This way, when the background image is multi-colored, we
2653 don't overwrite it with a rectangular, non-matching border around our
2654 icon. The following example displays a full wheelbarrow image on the
2658 /* example-start wheelbarrow/wheelbarrow.c */
2660 #include <gtk/gtk.h>
2663 static char * WheelbarrowFull_xpm[] = {
2666 ". c #DF7DCF3CC71B",
2667 "X c #965875D669A6",
2668 "o c #71C671C671C6",
2669 "O c #A699A289A699",
2670 "+ c #965892489658",
2671 "@ c #8E38410330C2",
2672 "# c #D75C7DF769A6",
2673 "$ c #F7DECF3CC71B",
2674 "% c #96588A288E38",
2675 "& c #A69992489E79",
2676 "* c #8E3886178E38",
2677 "= c #104008200820",
2678 "- c #596510401040",
2679 "; c #C71B30C230C2",
2680 ": c #C71B9A699658",
2681 "> c #618561856185",
2682 ", c #20811C712081",
2683 "< c #104000000000",
2684 "1 c #861720812081",
2685 "2 c #DF7D4D344103",
2686 "3 c #79E769A671C6",
2687 "4 c #861782078617",
2688 "5 c #41033CF34103",
2689 "6 c #000000000000",
2690 "7 c #49241C711040",
2691 "8 c #492445144924",
2692 "9 c #082008200820",
2693 "0 c #69A618611861",
2694 "q c #B6DA71C65144",
2695 "w c #410330C238E3",
2696 "e c #CF3CBAEAB6DA",
2697 "r c #71C6451430C2",
2698 "t c #EFBEDB6CD75C",
2699 "y c #28A208200820",
2700 "u c #186110401040",
2701 "i c #596528A21861",
2702 "p c #71C661855965",
2703 "a c #A69996589658",
2704 "s c #30C228A230C2",
2705 "d c #BEFBA289AEBA",
2706 "f c #596545145144",
2707 "g c #30C230C230C2",
2708 "h c #8E3882078617",
2709 "j c #208118612081",
2710 "k c #38E30C300820",
2711 "l c #30C2208128A2",
2712 "z c #38E328A238E3",
2713 "x c #514438E34924",
2714 "c c #618555555965",
2715 "v c #30C2208130C2",
2716 "b c #38E328A230C2",
2717 "n c #28A228A228A2",
2718 "m c #41032CB228A2",
2719 "M c #104010401040",
2720 "N c #492438E34103",
2721 "B c #28A2208128A2",
2722 "V c #A699596538E3",
2723 "C c #30C21C711040",
2724 "Z c #30C218611040",
2725 "A c #965865955965",
2726 "S c #618534D32081",
2727 "D c #38E31C711040",
2728 "F c #082000000820",
2737 "ty> 459@>+&& ",
2739 "%$;=* *3:.Xa.dfg> ",
2740 "Oh$;ya *3d.a8j,Xe.d3g8+ ",
2741 " Oh$;ka *3d$a8lz,,xxc:.e3g54 ",
2742 " Oh$;kO *pd$%svbzz,sxxxxfX..&wn> ",
2743 " Oh$@mO *3dthwlsslszjzxxxxxxx3:td8M4 ",
2744 " Oh$@g& *3d$XNlvvvlllm,mNwxxxxxxxfa.:,B* ",
2745 " Oh$@,Od.czlllllzlmmqV@V#V@fxxxxxxxf:%j5& ",
2746 " Oh$1hd5lllslllCCZrV#r#:#2AxxxxxxxxxcdwM* ",
2747 " OXq6c.%8vvvllZZiqqApA:mq:Xxcpcxxxxxfdc9* ",
2748 " 2r<6gde3bllZZrVi7S@SV77A::qApxxxxxxfdcM ",
2749 " :,q-6MN.dfmZZrrSS:#riirDSAX@Af5xxxxxfevo",
2750 " +A26jguXtAZZZC7iDiCCrVVii7Cmmmxxxxxx%3g",
2751 " *#16jszN..3DZZZZrCVSA2rZrV7Dmmwxxxx&en",
2752 " p2yFvzssXe:fCZZCiiD7iiZDiDSSZwwxx8e*>",
2753 " OA1<jzxwwc:$d%NDZZZZCCCZCCZZCmxxfd.B ",
2754 " 3206Bwxxszx%et.eaAp77m77mmmf3&eeeg* ",
2755 " @26MvzxNzvlbwfpdettttttttttt.c,n& ",
2756 " *;16=lsNwwNwgsvslbwwvccc3pcfu<o ",
2757 " p;<69BvwwsszslllbBlllllllu<5+ ",
2758 " OS0y6FBlvvvzvzss,u=Blllj=54 ",
2759 " c1-699Blvlllllu7k96MMMg4 ",
2760 " *10y8n6FjvllllB<166668 ",
2761 " S-kg+>666<M<996-y6n<8* ",
2762 " p71=4 m69996kD8Z-66698&& ",
2763 " &i0ycm6n4 ogk17,0<6666g ",
2764 " N-k-<> >=01-kuu666> ",
2765 " ,6ky& &46-10ul,66, ",
2766 " Ou0<> o66y<ulw<66& ",
2767 " *kk5 >66By7=xu664 ",
2768 " <<M4 466lj<Mxu66o ",
2769 " *>> +66uv,zN666* ",
2779 /* when invoked (via signal delete_event), terminates the application.
2781 void close_application( GtkWidget *widget, GdkEvent *event, gpointer data ) {
2785 int main (int argc, char *argv[])
2787 /* GtkWidget is the storage type for widgets */
2788 GtkWidget *window, *pixmap, *fixed;
2789 GdkPixmap *gdk_pixmap;
2794 /* create the main window, and attach delete_event signal to terminate
2795 the application. Note that the main window will not have a titlebar
2796 since we're making it a popup. */
2797 gtk_init (&argc, &argv);
2798 window = gtk_window_new( GTK_WINDOW_POPUP );
2799 gtk_signal_connect (GTK_OBJECT (window), "delete_event",
2800 GTK_SIGNAL_FUNC (close_application), NULL);
2801 gtk_widget_show (window);
2803 /* now for the pixmap and the pixmap widget */
2804 style = gtk_widget_get_default_style();
2805 gc = style->black_gc;
2806 gdk_pixmap = gdk_pixmap_create_from_xpm_d( window->window, &mask,
2807 &style->bg[GTK_STATE_NORMAL],
2808 WheelbarrowFull_xpm );
2809 pixmap = gtk_pixmap_new( gdk_pixmap, mask );
2810 gtk_widget_show( pixmap );
2812 /* To display the pixmap, we use a fixed widget to place the pixmap */
2813 fixed = gtk_fixed_new();
2814 gtk_widget_set_usize( fixed, 200, 200 );
2815 gtk_fixed_put( GTK_FIXED(fixed), pixmap, 0, 0 );
2816 gtk_container_add( GTK_CONTAINER(window), fixed );
2817 gtk_widget_show( fixed );
2819 /* This masks out everything except for the image itself */
2820 gtk_widget_shape_combine_mask( window, mask, 0, 0 );
2822 /* show the window */
2823 gtk_widget_set_uposition( window, 20, 400 );
2824 gtk_widget_show( window );
2831 To make the wheelbarrow image sensitive, we could attach the button press
2832 event signal to make it do something. The following few lines would make
2833 the picture sensitive to a mouse button being pressed which makes the
2834 application terminate.
2837 gtk_widget_set_events( window,
2838 gtk_widget_get_events( window ) |
2839 GDK_BUTTON_PRESS_MASK );
2841 gtk_signal_connect( GTK_OBJECT(window), "button_press_event",
2842 GTK_SIGNAL_FUNC(close_application), NULL );
2845 <!-- ----------------------------------------------------------------- -->
2848 Ruler widgets are used to indicate the location of the mouse pointer
2849 in a given window. A window can have a vertical ruler spanning across
2850 the width and a horizontal ruler spanning down the height. A small
2851 triangular indicator on the ruler shows the exact location of the
2852 pointer relative to the ruler.
2854 A ruler must first be created. Horizontal and vertical rulers are
2858 GtkWidget *gtk_hruler_new( void ); /* horizontal ruler */
2859 GtkWidget *gtk_vruler_new( void ); /* vertical ruler */
2862 Once a ruler is created, we can define the unit of measurement. Units
2863 of measure for rulers can be GTK_PIXELS, GTK_INCHES or
2864 GTK_CENTIMETERS. This is set using
2867 void gtk_ruler_set_metric( GtkRuler *ruler,
2868 GtkMetricType metric );
2871 The default measure is GTK_PIXELS.
2874 gtk_ruler_set_metric( GTK_RULER(ruler), GTK_PIXELS );
2877 Other important characteristics of a ruler are how to mark the units
2878 of scale and where the position indicator is initially placed. These
2879 are set for a ruler using
2882 void gtk_ruler_set_range( GtkRuler *ruler,
2889 The lower and upper arguments define the extent of the ruler, and
2890 max_size is the largest possible number that will be displayed.
2891 Position defines the initial position of the pointer indicator within
2894 A vertical ruler can span an 800 pixel wide window thus
2897 gtk_ruler_set_range( GTK_RULER(vruler), 0, 800, 0, 800);
2900 The markings displayed on the ruler will be from 0 to 800, with
2901 a number for every 100 pixels. If instead we wanted the ruler to
2902 range from 7 to 16, we would code
2905 gtk_ruler_set_range( GTK_RULER(vruler), 7, 16, 0, 20);
2908 The indicator on the ruler is a small triangular mark that indicates
2909 the position of the pointer relative to the ruler. If the ruler is
2910 used to follow the mouse pointer, the motion_notify_event signal
2911 should be connected to the motion_notify_event method of the ruler.
2912 To follow all mouse movements within a window area, we would use
2915 #define EVENT_METHOD(i, x) GTK_WIDGET_CLASS(GTK_OBJECT(i)->klass)->x
2917 gtk_signal_connect_object( GTK_OBJECT(area), "motion_notify_event",
2918 (GtkSignalFunc)EVENT_METHOD(ruler, motion_notify_event),
2919 GTK_OBJECT(ruler) );
2922 The following example creates a drawing area with a horizontal ruler
2923 above it and a vertical ruler to the left of it. The size of the
2924 drawing area is 600 pixels wide by 400 pixels high. The horizontal
2925 ruler spans from 7 to 13 with a mark every 100 pixels, while the
2926 vertical ruler spans from 0 to 400 with a mark every 100 pixels.
2927 Placement of the drawing area and the rulers are done using a table.
2930 /* example-start rulers/rulers.c */
2932 #include <gtk/gtk.h>
2934 #define EVENT_METHOD(i, x) GTK_WIDGET_CLASS(GTK_OBJECT(i)->klass)->x
2939 /* this routine gets control when the close button is clicked
2941 void close_application( GtkWidget *widget, GdkEvent *event, gpointer data ) {
2948 int main( int argc, char *argv[] ) {
2949 GtkWidget *window, *table, *area, *hrule, *vrule;
2951 /* initialize gtk and create the main window */
2952 gtk_init( &argc, &argv );
2954 window = gtk_window_new( GTK_WINDOW_TOPLEVEL );
2955 gtk_signal_connect (GTK_OBJECT (window), "delete_event",
2956 GTK_SIGNAL_FUNC( close_application ), NULL);
2957 gtk_container_border_width (GTK_CONTAINER (window), 10);
2959 /* create a table for placing the ruler and the drawing area */
2960 table = gtk_table_new( 3, 2, FALSE );
2961 gtk_container_add( GTK_CONTAINER(window), table );
2963 area = gtk_drawing_area_new();
2964 gtk_drawing_area_size( (GtkDrawingArea *)area, XSIZE, YSIZE );
2965 gtk_table_attach( GTK_TABLE(table), area, 1, 2, 1, 2,
2966 GTK_EXPAND|GTK_FILL, GTK_FILL, 0, 0 );
2967 gtk_widget_set_events( area, GDK_POINTER_MOTION_MASK | GDK_POINTER_MOTION_HINT_MASK );
2969 /* The horizontal ruler goes on top. As the mouse moves across the drawing area,
2970 a motion_notify_event is passed to the appropriate event handler for the ruler. */
2971 hrule = gtk_hruler_new();
2972 gtk_ruler_set_metric( GTK_RULER(hrule), GTK_PIXELS );
2973 gtk_ruler_set_range( GTK_RULER(hrule), 7, 13, 0, 20 );
2974 gtk_signal_connect_object( GTK_OBJECT(area), "motion_notify_event",
2975 (GtkSignalFunc)EVENT_METHOD(hrule, motion_notify_event),
2976 GTK_OBJECT(hrule) );
2977 /* GTK_WIDGET_CLASS(GTK_OBJECT(hrule)->klass)->motion_notify_event, */
2978 gtk_table_attach( GTK_TABLE(table), hrule, 1, 2, 0, 1,
2979 GTK_EXPAND|GTK_SHRINK|GTK_FILL, GTK_FILL, 0, 0 );
2981 /* The vertical ruler goes on the left. As the mouse moves across the drawing area,
2982 a motion_notify_event is passed to the appropriate event handler for the ruler. */
2983 vrule = gtk_vruler_new();
2984 gtk_ruler_set_metric( GTK_RULER(vrule), GTK_PIXELS );
2985 gtk_ruler_set_range( GTK_RULER(vrule), 0, YSIZE, 10, YSIZE );
2986 gtk_signal_connect_object( GTK_OBJECT(area), "motion_notify_event",
2988 GTK_WIDGET_CLASS(GTK_OBJECT(vrule)->klass)->motion_notify_event,
2989 GTK_OBJECT(vrule) );
2990 gtk_table_attach( GTK_TABLE(table), vrule, 0, 1, 1, 2,
2991 GTK_FILL, GTK_EXPAND|GTK_SHRINK|GTK_FILL, 0, 0 );
2993 /* now show everything */
2994 gtk_widget_show( area );
2995 gtk_widget_show( hrule );
2996 gtk_widget_show( vrule );
2997 gtk_widget_show( table );
2998 gtk_widget_show( window );
3006 <!-- ----------------------------------------------------------------- -->
3009 Statusbars are simple widgets used to display a text message. They keep
3010 a stack of the messages pushed onto them, so that popping the current
3011 message will re-display the previous text message.
3013 In order to allow different parts of an application to use the same
3014 statusbar to display messages, the statusbar widget issues Context
3015 Identifiers which are used to identify different 'users'. The message on
3016 top of the stack is the one displayed, no matter what context it is in.
3017 Messages are stacked in last-in-first-out order, not context identifier order.
3019 A statusbar is created with a call to:
3022 GtkWidget *gtk_statusbar_new( void );
3025 A new Context Identifier is requested using a call to the following
3026 function with a short textual description of the context:
3029 guint gtk_statusbar_get_context_id( GtkStatusbar *statusbar,
3030 const gchar *context_description );
3033 There are three functions that can operate on statusbars:
3036 guint gtk_statusbar_push( GtkStatusbar *statusbar,
3040 void gtk_statusbar_pop( GtkStatusbar *statusbar)
3043 void gtk_statusbar_remove( GtkStatusbar *statusbar,
3048 The first, gtk_statusbar_push, is used to add a new message to the statusbar.
3049 It returns a Message Identifier, which can be passed later to the function
3050 gtk_statusbar_remove to remove the message with the given Message and Context
3051 Identifiers from the statusbar's stack.
3053 The function gtk_statusbar_pop removes the message highest in the stack with
3054 the given Context Identifier.
3056 The following example creates a statusbar and two buttons, one for pushing items
3057 onto the statusbar, and one for popping the last item back off.
3060 /* example-start statusbar/statusbar.c */
3062 #include <gtk/gtk.h>
3065 GtkWidget *status_bar;
3067 void push_item (GtkWidget *widget, gpointer data)
3069 static int count = 1;
3072 g_snprintf(buff, 20, "Item %d", count++);
3073 gtk_statusbar_push( GTK_STATUSBAR(status_bar), (guint) &data, buff);
3078 void pop_item (GtkWidget *widget, gpointer data)
3080 gtk_statusbar_pop( GTK_STATUSBAR(status_bar), (guint) &data );
3084 int main (int argc, char *argv[])
3093 gtk_init (&argc, &argv);
3095 /* create a new window */
3096 window = gtk_window_new(GTK_WINDOW_TOPLEVEL);
3097 gtk_widget_set_usize( GTK_WIDGET (window), 200, 100);
3098 gtk_window_set_title(GTK_WINDOW (window), "GTK Statusbar Example");
3099 gtk_signal_connect(GTK_OBJECT (window), "delete_event",
3100 (GtkSignalFunc) gtk_exit, NULL);
3102 vbox = gtk_vbox_new(FALSE, 1);
3103 gtk_container_add(GTK_CONTAINER(window), vbox);
3104 gtk_widget_show(vbox);
3106 status_bar = gtk_statusbar_new();
3107 gtk_box_pack_start (GTK_BOX (vbox), status_bar, TRUE, TRUE, 0);
3108 gtk_widget_show (status_bar);
3110 context_id = gtk_statusbar_get_context_id( GTK_STATUSBAR(status_bar), "Statusbar example");
3112 button = gtk_button_new_with_label("push item");
3113 gtk_signal_connect(GTK_OBJECT(button), "clicked",
3114 GTK_SIGNAL_FUNC (push_item), &context_id);
3115 gtk_box_pack_start(GTK_BOX(vbox), button, TRUE, TRUE, 2);
3116 gtk_widget_show(button);
3118 button = gtk_button_new_with_label("pop last item");
3119 gtk_signal_connect(GTK_OBJECT(button), "clicked",
3120 GTK_SIGNAL_FUNC (pop_item), &context_id);
3121 gtk_box_pack_start(GTK_BOX(vbox), button, TRUE, TRUE, 2);
3122 gtk_widget_show(button);
3124 /* always display the window as the last step so it all splashes on
3125 * the screen at once. */
3126 gtk_widget_show(window);
3135 <!-- ----------------------------------------------------------------- -->
3138 The Entry widget allows text to be typed and displayed in a single line
3139 text box. The text may be set with function calls that allow new text
3140 to replace, prepend or append the current contents of the Entry widget.
3142 There are two functions for creating Entry widgets:
3145 GtkWidget *gtk_entry_new( void );
3147 GtkWidget *gtk_entry_new_with_max_length( guint16 max );
3150 The first just creates a new Entry widget, whilst the second creates a
3151 new Entry and sets a limit on the length of the text within the Entry.
3153 There are several functions for altering the text which is currently
3154 within the Entry widget.
3157 void gtk_entry_set_text( GtkEntry *entry,
3158 const gchar *text );
3160 void gtk_entry_append_text( GtkEntry *entry,
3161 const gchar *text );
3163 void gtk_entry_prepend_text( GtkEntry *entry,
3164 const gchar *text );
3167 The function gtk_entry_set_text sets the contents of the Entry widget,
3168 replacing the current contents. The functions gtk_entry_append_text and
3169 gtk_entry_prepend_text allow the current contents to be appended and
3172 The next function allows the current insertion point to be set.
3175 void gtk_entry_set_position( GtkEntry *entry,
3179 The contents of the Entry can be retrieved by using a call to the
3180 following function. This is useful in the callback functions described below.
3183 gchar *gtk_entry_get_text( GtkEntry *entry );
3186 If we don't want the contents of the Entry to be changed by someone typing
3187 into it, we can change it's editable state.
3190 void gtk_entry_set_editable( GtkEntry *entry,
3191 gboolean editable );
3194 This function allows us to toggle the edittable state of the Entry widget
3195 by passing in a TRUE or FALSE value for the <tt/editable/ argument.
3197 If we are using the Entry where we don't want the text entered to be visible,
3198 for example when a password is being entered, we can use the following
3199 function, which also takes a boolean flag.
3202 void gtk_entry_set_visibility( GtkEntry *entry,
3206 A region of the text may be set as selected by using the following
3207 function. This would most often be used after setting some default text
3208 in an Entry, making it easy for the user to remove it.
3211 void gtk_entry_select_region( GtkEntry *entry,
3216 If we want to catch when the user has entered text, we can connect to the
3217 <tt/activate/ or <tt/changed/ signal. Activate is raised when the user hits
3218 the enter key within the Entry widget. Changed is raised when the text
3219 changes at all, e.g. for every character entered or removed.
3221 The following code is an example of using an Entry widget.
3224 /* example-start entry/entry.c */
3226 #include <gtk/gtk.h>
3228 void enter_callback(GtkWidget *widget, GtkWidget *entry)
3231 entry_text = gtk_entry_get_text(GTK_ENTRY(entry));
3232 printf("Entry contents: %s\n", entry_text);
3235 void entry_toggle_editable (GtkWidget *checkbutton,
3238 gtk_entry_set_editable(GTK_ENTRY(entry),
3239 GTK_TOGGLE_BUTTON(checkbutton)->active);
3242 void entry_toggle_visibility (GtkWidget *checkbutton,
3245 gtk_entry_set_visibility(GTK_ENTRY(entry),
3246 GTK_TOGGLE_BUTTON(checkbutton)->active);
3249 int main (int argc, char *argv[])
3253 GtkWidget *vbox, *hbox;
3258 gtk_init (&argc, &argv);
3260 /* create a new window */
3261 window = gtk_window_new(GTK_WINDOW_TOPLEVEL);
3262 gtk_widget_set_usize( GTK_WIDGET (window), 200, 100);
3263 gtk_window_set_title(GTK_WINDOW (window), "GTK Entry");
3264 gtk_signal_connect(GTK_OBJECT (window), "delete_event",
3265 (GtkSignalFunc) gtk_exit, NULL);
3267 vbox = gtk_vbox_new (FALSE, 0);
3268 gtk_container_add (GTK_CONTAINER (window), vbox);
3269 gtk_widget_show (vbox);
3271 entry = gtk_entry_new_with_max_length (50);
3272 gtk_signal_connect(GTK_OBJECT(entry), "activate",
3273 GTK_SIGNAL_FUNC(enter_callback),
3275 gtk_entry_set_text (GTK_ENTRY (entry), "hello");
3276 gtk_entry_append_text (GTK_ENTRY (entry), " world");
3277 gtk_entry_select_region (GTK_ENTRY (entry),
3278 0, GTK_ENTRY(entry)->text_length);
3279 gtk_box_pack_start (GTK_BOX (vbox), entry, TRUE, TRUE, 0);
3280 gtk_widget_show (entry);
3282 hbox = gtk_hbox_new (FALSE, 0);
3283 gtk_container_add (GTK_CONTAINER (vbox), hbox);
3284 gtk_widget_show (hbox);
3286 check = gtk_check_button_new_with_label("Editable");
3287 gtk_box_pack_start (GTK_BOX (hbox), check, TRUE, TRUE, 0);
3288 gtk_signal_connect (GTK_OBJECT(check), "toggled",
3289 GTK_SIGNAL_FUNC(entry_toggle_editable), entry);
3290 gtk_toggle_button_set_state(GTK_TOGGLE_BUTTON(check), TRUE);
3291 gtk_widget_show (check);
3293 check = gtk_check_button_new_with_label("Visible");
3294 gtk_box_pack_start (GTK_BOX (hbox), check, TRUE, TRUE, 0);
3295 gtk_signal_connect (GTK_OBJECT(check), "toggled",
3296 GTK_SIGNAL_FUNC(entry_toggle_visibility), entry);
3297 gtk_toggle_button_set_state(GTK_TOGGLE_BUTTON(check), TRUE);
3298 gtk_widget_show (check);
3300 button = gtk_button_new_with_label ("Close");
3301 gtk_signal_connect_object (GTK_OBJECT (button), "clicked",
3302 GTK_SIGNAL_FUNC(gtk_exit),
3303 GTK_OBJECT (window));
3304 gtk_box_pack_start (GTK_BOX (vbox), button, TRUE, TRUE, 0);
3305 GTK_WIDGET_SET_FLAGS (button, GTK_CAN_DEFAULT);
3306 gtk_widget_grab_default (button);
3307 gtk_widget_show (button);
3309 gtk_widget_show(window);
3317 <!-- ----------------------------------------------------------------- -->
3318 <sect1> Color Selection
3320 The color selection widget is, not surprisingly, a widget for interactive
3321 selection of colors. This composite widget lets the user select a color by
3322 manipulating RGB (Red, Green, Blue) and HSV (Hue, Saturation, Value) triples.
3323 This is done either by adjusting single values with sliders or entries, or
3324 by picking the desired color from a hue-saturation wheel/value bar.
3325 Optionally, the opacity of the color can also be set.
3327 The color selection widget currently emits only one signal,
3328 "color_changed", which is emitted whenever the current color in the widget
3329 changes, either when the user changes it or if it's set explicitly through
3330 gtk_color_selection_set_color().
3332 Lets have a look at what the color selection widget has to offer us. The
3333 widget comes in two flavours; gtk_color_selection and
3334 gtk_color_selection_dialog:
3337 GtkWidget *gtk_color_selection_new( void );
3340 You'll probably not be using this constructor directly. It creates an orphan
3341 GtkColorSelection widget which you'll have to parent yourself. The
3342 GtkColorSelection widget inherits from the GtkVBox widget.
3345 GtkWidget *gtk_color_selection_dialog_new( const gchar *title );
3348 This is the most common color selection constructor. It creates a
3349 GtkColorSelectionDialog, which inherits from a GtkDialog. It consists
3350 of a GtkFrame containing a GtkColorSelection widget, a GtkHSeparator and a
3351 GtkHBox with three buttons, "Ok", "Cancel" and "Help". You can reach these
3352 buttons by accessing the "ok_button", "cancel_button" and "help_button"
3353 widgets in the GtkColorSelectionDialog structure,
3354 (i.e. GTK_COLOR_SELECTION_DIALOG(colorseldialog)->ok_button).
3357 void gtk_color_selection_set_update_policy( GtkColorSelection *colorsel,
3358 GtkUpdateType policy );
3361 This function sets the update policy. The default policy is
3362 GTK_UPDATE_CONTINOUS which means that the current color is updated
3363 continously when the user drags the sliders or presses the mouse and drags
3364 in the hue-saturation wheel or value bar. If you experience performance
3365 problems, you may want to set the policy to GTK_UPDATE_DISCONTINOUS or
3369 void gtk_color_selection_set_opacity( GtkColorSelection *colorsel,
3373 The color selection widget supports adjusting the opacity of a color
3374 (also known as the alpha channel). This is disabled by default. Calling
3375 this function with use_opacity set to TRUE enables opacity. Likewise,
3376 use_opacity set to FALSE will disable opacity.
3379 void gtk_color_selection_set_color( GtkColorSelection *colorsel,
3383 You can set the current color explicitly by calling this function with
3384 a pointer to an array of colors (gdouble). The length of the array depends
3385 on whether opacity is enabled or not. Position 0 contains the red component,
3386 1 is green, 2 is blue and opacity is at position 3 (only if opacity is enabled,
3387 see gtk_color_selection_set_opacity()). All values are between 0.0 and 1.0.
3390 void gtk_color_selection_get_color( GtkColorSelection *colorsel,
3394 When you need to query the current color, typically when you've received a
3395 "color_changed" signal, you use this function. Color is a pointer to the
3396 array of colors to fill in. See the gtk_color_selection_set_color() function
3397 for the description of this array.
3399 <!-- Need to do a whole section on DnD - TRG
3403 The color sample areas (right under the hue-saturation wheel) supports drag and drop. The type of
3404 drag and drop is "application/x-color". The message data consists of an array of 4
3405 (or 5 if opacity is enabled) gdouble values, where the value at position 0 is 0.0 (opacity
3406 on) or 1.0 (opacity off) followed by the red, green and blue values at positions 1,2 and 3 respectively.
3407 If opacity is enabled, the opacity is passed in the value at position 4.
3410 Here's a simple example demonstrating the use of the GtkColorSelectionDialog.
3411 The program displays a window containing a drawing area. Clicking on it opens
3412 a color selection dialog, and changing the color in the color selection dialog
3413 changes the background color.
3416 /* example-start colorsel/colorsel.c */
3419 #include <gdk/gdk.h>
3420 #include <gtk/gtk.h>
3422 GtkWidget *colorseldlg = NULL;
3423 GtkWidget *drawingarea = NULL;
3425 /* Color changed handler */
3427 void color_changed_cb (GtkWidget *widget, GtkColorSelection *colorsel)
3431 GdkColormap *colormap;
3433 /* Get drawingarea colormap */
3435 colormap = gdk_window_get_colormap (drawingarea->window);
3437 /* Get current color */
3439 gtk_color_selection_get_color (colorsel,color);
3441 /* Fit to a unsigned 16 bit integer (0..65535) and insert into the GdkColor structure */
3443 gdk_color.red = (guint16)(color[0]*65535.0);
3444 gdk_color.green = (guint16)(color[1]*65535.0);
3445 gdk_color.blue = (guint16)(color[2]*65535.0);
3447 /* Allocate color */
3449 gdk_color_alloc (colormap, &gdk_color);
3451 /* Set window background color */
3453 gdk_window_set_background (drawingarea->window, &gdk_color);
3457 gdk_window_clear (drawingarea->window);
3460 /* Drawingarea event handler */
3462 gint area_event (GtkWidget *widget, GdkEvent *event, gpointer client_data)
3464 gint handled = FALSE;
3465 GtkWidget *colorsel;
3467 /* Check if we've received a button pressed event */
3469 if (event->type == GDK_BUTTON_PRESS && colorseldlg == NULL)
3471 /* Yes, we have an event and there's no colorseldlg yet! */
3475 /* Create color selection dialog */
3477 colorseldlg = gtk_color_selection_dialog_new("Select background color");
3479 /* Get the GtkColorSelection widget */
3481 colorsel = GTK_COLOR_SELECTION_DIALOG(colorseldlg)->colorsel;
3483 /* Connect to the "color_changed" signal, set the client-data to the colorsel widget */
3485 gtk_signal_connect(GTK_OBJECT(colorsel), "color_changed",
3486 (GtkSignalFunc)color_changed_cb, (gpointer)colorsel);
3488 /* Show the dialog */
3490 gtk_widget_show(colorseldlg);
3496 /* Close down and exit handler */
3498 void destroy_window (GtkWidget *widget, gpointer client_data)
3505 gint main (gint argc, gchar *argv[])
3509 /* Initialize the toolkit, remove gtk-related commandline stuff */
3511 gtk_init (&argc,&argv);
3513 /* Create toplevel window, set title and policies */
3515 window = gtk_window_new (GTK_WINDOW_TOPLEVEL);
3516 gtk_window_set_title (GTK_WINDOW(window), "Color selection test");
3517 gtk_window_set_policy (GTK_WINDOW(window), TRUE, TRUE, TRUE);
3519 /* Attach to the "delete" and "destroy" events so we can exit */
3521 gtk_signal_connect (GTK_OBJECT(window), "delete_event",
3522 (GtkSignalFunc)destroy_window, (gpointer)window);
3524 gtk_signal_connect (GTK_OBJECT(window), "destroy",
3525 (GtkSignalFunc)destroy_window, (gpointer)window);
3527 /* Create drawingarea, set size and catch button events */
3529 drawingarea = gtk_drawing_area_new ();
3531 gtk_drawing_area_size (GTK_DRAWING_AREA(drawingarea), 200, 200);
3533 gtk_widget_set_events (drawingarea, GDK_BUTTON_PRESS_MASK);
3535 gtk_signal_connect (GTK_OBJECT(drawingarea), "event",
3536 (GtkSignalFunc)area_event, (gpointer)drawingarea);
3538 /* Add drawingarea to window, then show them both */
3540 gtk_container_add (GTK_CONTAINER(window), drawingarea);
3542 gtk_widget_show (drawingarea);
3543 gtk_widget_show (window);
3545 /* Enter the gtk main loop (this never returns) */
3549 /* Satisfy grumpy compilers */
3556 <!-- ----------------------------------------------------------------- -->
3557 <sect1> File Selections
3559 The file selection widget is a quick and simple way to display a File
3560 dialog box. It comes complete with Ok, Cancel, and Help buttons, a great way
3561 to cut down on programming time.
3563 To create a new file selection box use:
3566 GtkWidget *gtk_file_selection_new( gchar *title );
3569 To set the filename, for example to bring up a specific directory, or
3570 give a default filename, use this function:
3573 void gtk_file_selection_set_filename( GtkFileSelection *filesel,
3577 To grab the text that the user has entered or clicked on, use this
3581 gchar *gtk_file_selection_get_filename( GtkFileSelection *filesel );
3584 There are also pointers to the widgets contained within the file
3585 selection widget. These are:
3590 <item>selection_entry
3591 <item>selection_text
3598 Most likely you will want to use the ok_button, cancel_button, and
3599 help_button pointers in signaling their use.
3601 Included here is an example stolen from testgtk.c, modified to run
3602 on it's own. As you will see, there is nothing much to creating a file
3603 selection widget. While in this example the Help button appears on the
3604 screen, it does nothing as there is not a signal attached to it.
3607 /* example-start filesel/filesel.c */
3609 #include <gtk/gtk.h>
3611 /* Get the selected filename and print it to the console */
3612 void file_ok_sel (GtkWidget *w, GtkFileSelection *fs)
3614 g_print ("%s\n", gtk_file_selection_get_filename (GTK_FILE_SELECTION (fs)));
3617 void destroy (GtkWidget *widget, gpointer data)
3622 int main (int argc, char *argv[])
3626 gtk_init (&argc, &argv);
3628 /* Create a new file selection widget */
3629 filew = gtk_file_selection_new ("File selection");
3631 gtk_signal_connect (GTK_OBJECT (filew), "destroy",
3632 (GtkSignalFunc) destroy, &filew);
3633 /* Connect the ok_button to file_ok_sel function */
3634 gtk_signal_connect (GTK_OBJECT (GTK_FILE_SELECTION (filew)->ok_button),
3635 "clicked", (GtkSignalFunc) file_ok_sel, filew );
3637 /* Connect the cancel_button to destroy the widget */
3638 gtk_signal_connect_object (GTK_OBJECT (GTK_FILE_SELECTION (filew)->cancel_button),
3639 "clicked", (GtkSignalFunc) gtk_widget_destroy,
3640 GTK_OBJECT (filew));
3642 /* Lets set the filename, as if this were a save dialog, and we are giving
3643 a default filename */
3644 gtk_file_selection_set_filename (GTK_FILE_SELECTION(filew),
3647 gtk_widget_show(filew);
3654 <!-- ***************************************************************** -->
3655 <sect> Container Widgets
3656 <!-- ***************************************************************** -->
3658 <!-- ----------------------------------------------------------------- -->
3661 The NoteBook Widget is a collection of 'pages' that overlap each other,
3662 each page contains different information. This widget has become more common
3663 lately in GUI programming, and it is a good way to show blocks similar
3664 information that warrant separation in their display.
3666 The first function call you will need to know, as you can probably
3667 guess by now, is used to create a new notebook widget.
3670 GtkWidget *gtk_notebook_new( void );
3673 Once the notebook has been created, there are 12 functions that
3674 operate on the notebook widget. Let's look at them individually.
3676 The first one we will look at is how to position the page indicators.
3677 These page indicators or 'tabs' as they are referred to, can be positioned
3678 in four ways: top, bottom, left, or right.
3681 void gtk_notebook_set_tab_pos( GtkNotebook *notebook,
3682 GtkPositionType pos );
3685 GtkPostionType will be one of the following, and they are pretty self explanatory:
3688 <item> GTK_POS_RIGHT
3690 <item> GTK_POS_BOTTOM
3693 GTK_POS_TOP is the default.
3695 Next we will look at how to add pages to the notebook. There are three
3696 ways to add pages to the NoteBook. Let's look at the first two together as
3697 they are quite similar.
3700 void gtk_notebook_append_page( GtkNotebook *notebook,
3702 GtkWidget *tab_label );
3704 void gtk_notebook_prepend_page( GtkNotebook *notebook,
3706 GtkWidget *tab_label );
3709 These functions add pages to the notebook by inserting them from the
3710 back of the notebook (append), or the front of the notebook (prepend).
3711 <tt/child/ is the widget that is placed within the notebook page, and
3712 <tt/tab_label/ is the label for the page being added.
3714 The final function for adding a page to the notebook contains all of
3715 the properties of the previous two, but it allows you to specify what position
3716 you want the page to be in the notebook.
3719 void gtk_notebook_insert_page( GtkNotebook *notebook,
3721 GtkWidget *tab_label,
3725 The parameters are the same as _append_ and _prepend_ except it
3726 contains an extra parameter, <tt/position/. This parameter is used to
3727 specify what place this page will be inserted into.
3729 Now that we know how to add a page, lets see how we can remove a page
3733 void gtk_notebook_remove_page( GtkNotebook *notebook,
3737 This function takes the page specified by page_num and removes it from
3738 the widget pointed to by <tt/notebook/.
3740 To find out what the current page is in a notebook use the function:
3743 gint gtk_notebook_current_page( GtkNotebook *notebook );
3746 These next two functions are simple calls to move the notebook page
3747 forward or backward. Simply provide the respective function call with the
3748 notebook widget you wish to operate on. Note: when the NoteBook is currently
3749 on the last page, and gtk_notebook_next_page is called, the notebook will
3750 wrap back to the first page. Likewise, if the NoteBook is on the first page,
3751 and gtk_notebook_prev_page is called, the notebook will wrap to the last page.
3754 void gtk_notebook_next_page( GtkNoteBook *notebook );
3756 void gtk_notebook_prev_page( GtkNoteBook *notebook );
3759 This next function sets the 'active' page. If you wish the
3760 notebook to be opened to page 5 for example, you would use this function.
3761 Without using this function, the notebook defaults to the first page.
3764 void gtk_notebook_set_page( GtkNotebook *notebook,
3768 The next two functions add or remove the notebook page tabs and the
3769 notebook border respectively.
3772 void gtk_notebook_set_show_tabs( GtkNotebook *notebook,
3775 void gtk_notebook_set_show_border( GtkNotebook *notebook,
3779 show_tabs and show_border can be either TRUE or FALSE.
3781 Now lets look at an example, it is expanded from the testgtk.c code
3782 that comes with the GTK distribution, and it shows all 13 functions. This
3783 small program creates a window with a notebook and six buttons. The notebook
3784 contains 11 pages, added in three different ways, appended, inserted, and
3785 prepended. The buttons allow you rotate the tab positions, add/remove the tabs
3786 and border, remove a page, change pages in both a forward and backward manner,
3787 and exit the program.
3790 /* example-start notebooknotebook.c */
3792 #include <gtk/gtk.h>
3794 /* This function rotates the position of the tabs */
3795 void rotate_book (GtkButton *button, GtkNotebook *notebook)
3797 gtk_notebook_set_tab_pos (notebook, (notebook->tab_pos +1) %4);
3800 /* Add/Remove the page tabs and the borders */
3801 void tabsborder_book (GtkButton *button, GtkNotebook *notebook)
3805 if (notebook->show_tabs == 0)
3807 if (notebook->show_border == 0)
3810 gtk_notebook_set_show_tabs (notebook, tval);
3811 gtk_notebook_set_show_border (notebook, bval);
3814 /* Remove a page from the notebook */
3815 void remove_book (GtkButton *button, GtkNotebook *notebook)
3819 page = gtk_notebook_current_page(notebook);
3820 gtk_notebook_remove_page (notebook, page);
3821 /* Need to refresh the widget --
3822 This forces the widget to redraw itself. */
3823 gtk_widget_draw(GTK_WIDGET(notebook), NULL);
3826 void delete (GtkWidget *widget, GtkWidget *event, gpointer data)
3831 int main (int argc, char *argv[])
3836 GtkWidget *notebook;
3839 GtkWidget *checkbutton;
3844 gtk_init (&argc, &argv);
3846 window = gtk_window_new (GTK_WINDOW_TOPLEVEL);
3848 gtk_signal_connect (GTK_OBJECT (window), "delete_event",
3849 GTK_SIGNAL_FUNC (delete), NULL);
3851 gtk_container_border_width (GTK_CONTAINER (window), 10);
3853 table = gtk_table_new(2,6,TRUE);
3854 gtk_container_add (GTK_CONTAINER (window), table);
3856 /* Create a new notebook, place the position of the tabs */
3857 notebook = gtk_notebook_new ();
3858 gtk_notebook_set_tab_pos (GTK_NOTEBOOK (notebook), GTK_POS_TOP);
3859 gtk_table_attach_defaults(GTK_TABLE(table), notebook, 0,6,0,1);
3860 gtk_widget_show(notebook);
3862 /* lets append a bunch of pages to the notebook */
3863 for (i=0; i < 5; i++) {
3864 sprintf(bufferf, "Append Frame %d", i+1);
3865 sprintf(bufferl, "Page %d", i+1);
3867 frame = gtk_frame_new (bufferf);
3868 gtk_container_border_width (GTK_CONTAINER (frame), 10);
3869 gtk_widget_set_usize (frame, 100, 75);
3870 gtk_widget_show (frame);
3872 label = gtk_label_new (bufferf);
3873 gtk_container_add (GTK_CONTAINER (frame), label);
3874 gtk_widget_show (label);
3876 label = gtk_label_new (bufferl);
3877 gtk_notebook_append_page (GTK_NOTEBOOK (notebook), frame, label);
3881 /* now lets add a page to a specific spot */
3882 checkbutton = gtk_check_button_new_with_label ("Check me please!");
3883 gtk_widget_set_usize(checkbutton, 100, 75);
3884 gtk_widget_show (checkbutton);
3886 label = gtk_label_new ("Add spot");
3887 gtk_container_add (GTK_CONTAINER (checkbutton), label);
3888 gtk_widget_show (label);
3889 label = gtk_label_new ("Add page");
3890 gtk_notebook_insert_page (GTK_NOTEBOOK (notebook), checkbutton, label, 2);
3892 /* Now finally lets prepend pages to the notebook */
3893 for (i=0; i < 5; i++) {
3894 sprintf(bufferf, "Prepend Frame %d", i+1);
3895 sprintf(bufferl, "PPage %d", i+1);
3897 frame = gtk_frame_new (bufferf);
3898 gtk_container_border_width (GTK_CONTAINER (frame), 10);
3899 gtk_widget_set_usize (frame, 100, 75);
3900 gtk_widget_show (frame);
3902 label = gtk_label_new (bufferf);
3903 gtk_container_add (GTK_CONTAINER (frame), label);
3904 gtk_widget_show (label);
3906 label = gtk_label_new (bufferl);
3907 gtk_notebook_prepend_page (GTK_NOTEBOOK(notebook), frame, label);
3910 /* Set what page to start at (page 4) */
3911 gtk_notebook_set_page (GTK_NOTEBOOK(notebook), 3);
3914 /* create a bunch of buttons */
3915 button = gtk_button_new_with_label ("close");
3916 gtk_signal_connect_object (GTK_OBJECT (button), "clicked",
3917 GTK_SIGNAL_FUNC (delete), NULL);
3918 gtk_table_attach_defaults(GTK_TABLE(table), button, 0,1,1,2);
3919 gtk_widget_show(button);
3921 button = gtk_button_new_with_label ("next page");
3922 gtk_signal_connect_object (GTK_OBJECT (button), "clicked",
3923 (GtkSignalFunc) gtk_notebook_next_page,
3924 GTK_OBJECT (notebook));
3925 gtk_table_attach_defaults(GTK_TABLE(table), button, 1,2,1,2);
3926 gtk_widget_show(button);
3928 button = gtk_button_new_with_label ("prev page");
3929 gtk_signal_connect_object (GTK_OBJECT (button), "clicked",
3930 (GtkSignalFunc) gtk_notebook_prev_page,
3931 GTK_OBJECT (notebook));
3932 gtk_table_attach_defaults(GTK_TABLE(table), button, 2,3,1,2);
3933 gtk_widget_show(button);
3935 button = gtk_button_new_with_label ("tab position");
3936 gtk_signal_connect_object (GTK_OBJECT (button), "clicked",
3937 (GtkSignalFunc) rotate_book, GTK_OBJECT(notebook));
3938 gtk_table_attach_defaults(GTK_TABLE(table), button, 3,4,1,2);
3939 gtk_widget_show(button);
3941 button = gtk_button_new_with_label ("tabs/border on/off");
3942 gtk_signal_connect_object (GTK_OBJECT (button), "clicked",
3943 (GtkSignalFunc) tabsborder_book,
3944 GTK_OBJECT (notebook));
3945 gtk_table_attach_defaults(GTK_TABLE(table), button, 4,5,1,2);
3946 gtk_widget_show(button);
3948 button = gtk_button_new_with_label ("remove page");
3949 gtk_signal_connect_object (GTK_OBJECT (button), "clicked",
3950 (GtkSignalFunc) remove_book,
3951 GTK_OBJECT(notebook));
3952 gtk_table_attach_defaults(GTK_TABLE(table), button, 5,6,1,2);
3953 gtk_widget_show(button);
3955 gtk_widget_show(table);
3956 gtk_widget_show(window);
3965 Hopefully this helps you on your way with creating notebooks for your
3968 <!-- ----------------------------------------------------------------- -->
3969 <sect1>Scrolled Windows
3971 Scrolled windows are used to create a scrollable area inside a real window.
3972 You may insert any type of widget into a scrolled window, and it will
3973 be accessable regardless of the size by using the scrollbars.
3975 The following function is used to create a new scolled window.
3978 GtkWidget *gtk_scrolled_window_new( GtkAdjustment *hadjustment,
3979 GtkAdjustment *vadjustment );
3982 Where the first argument is the adjustment for the horizontal
3983 direction, and the second, the adjustment for the vertical direction.
3984 These are almost always set to NULL.
3987 void gtk_scrolled_window_set_policy( GtkScrolledWindow *scrolled_window,
3988 GtkPolicyType hscrollbar_policy,
3989 GtkPolicyType vscrollbar_policy );
3992 This sets the policy to be used with respect to the scrollbars.
3993 The first arguement is the scrolled window you wish to change. The second
3994 sets the policiy for the horizontal scrollbar, and the third the policy for
3995 the vertical scrollbar.
3997 The policy may be one of GTK_POLICY AUTOMATIC, or GTK_POLICY_ALWAYS.
3998 GTK_POLICY_AUTOMATIC will automatically decide whether you need
3999 scrollbars, wheras GTK_POLICY_ALWAYS will always leave the scrollbars
4002 Here is a simple example that packs 100 toggle buttons into a scrolled window.
4003 I've only commented on the parts that may be new to you.
4006 /* example-start scrolledwin/scrolledwin.c */
4008 #include <gtk/gtk.h>
4010 void destroy(GtkWidget *widget, gpointer data)
4015 int main (int argc, char *argv[])
4017 static GtkWidget *window;
4018 GtkWidget *scrolled_window;
4024 gtk_init (&argc, &argv);
4026 /* Create a new dialog window for the scrolled window to be
4027 * packed into. A dialog is just like a normal window except it has a
4028 * vbox and a horizontal seperator packed into it. It's just a shortcut
4029 * for creating dialogs */
4030 window = gtk_dialog_new ();
4031 gtk_signal_connect (GTK_OBJECT (window), "destroy",
4032 (GtkSignalFunc) destroy, NULL);
4033 gtk_window_set_title (GTK_WINDOW (window), "dialog");
4034 gtk_container_border_width (GTK_CONTAINER (window), 0);
4035 gtk_widget_set_usize(window, 300, 300);
4037 /* create a new scrolled window. */
4038 scrolled_window = gtk_scrolled_window_new (NULL, NULL);
4040 gtk_container_border_width (GTK_CONTAINER (scrolled_window), 10);
4042 /* the policy is one of GTK_POLICY AUTOMATIC, or GTK_POLICY_ALWAYS.
4043 * GTK_POLICY_AUTOMATIC will automatically decide whether you need
4044 * scrollbars, wheras GTK_POLICY_ALWAYS will always leave the scrollbars
4045 * there. The first one is the horizontal scrollbar, the second,
4047 gtk_scrolled_window_set_policy (GTK_SCROLLED_WINDOW (scrolled_window),
4048 GTK_POLICY_AUTOMATIC, GTK_POLICY_ALWAYS);
4049 /* The dialog window is created with a vbox packed into it. */
4050 gtk_box_pack_start (GTK_BOX (GTK_DIALOG(window)->vbox), scrolled_window,
4052 gtk_widget_show (scrolled_window);
4054 /* create a table of 10 by 10 squares. */
4055 table = gtk_table_new (10, 10, FALSE);
4057 /* set the spacing to 10 on x and 10 on y */
4058 gtk_table_set_row_spacings (GTK_TABLE (table), 10);
4059 gtk_table_set_col_spacings (GTK_TABLE (table), 10);
4061 /* pack the table into the scrolled window */
4062 gtk_container_add (GTK_CONTAINER (scrolled_window), table);
4063 gtk_widget_show (table);
4065 /* this simply creates a grid of toggle buttons on the table
4066 * to demonstrate the scrolled window. */
4067 for (i = 0; i < 10; i++)
4068 for (j = 0; j < 10; j++) {
4069 sprintf (buffer, "button (%d,%d)\n", i, j);
4070 button = gtk_toggle_button_new_with_label (buffer);
4071 gtk_table_attach_defaults (GTK_TABLE (table), button,
4073 gtk_widget_show (button);
4076 /* Add a "close" button to the bottom of the dialog */
4077 button = gtk_button_new_with_label ("close");
4078 gtk_signal_connect_object (GTK_OBJECT (button), "clicked",
4079 (GtkSignalFunc) gtk_widget_destroy,
4080 GTK_OBJECT (window));
4082 /* this makes it so the button is the default. */
4084 GTK_WIDGET_SET_FLAGS (button, GTK_CAN_DEFAULT);
4085 gtk_box_pack_start (GTK_BOX (GTK_DIALOG (window)->action_area), button, TRUE, TRUE, 0);
4087 /* This grabs this button to be the default button. Simply hitting
4088 * the "Enter" key will cause this button to activate. */
4089 gtk_widget_grab_default (button);
4090 gtk_widget_show (button);
4092 gtk_widget_show (window);
4101 Try playing with resizing the window. You'll notice how the scrollbars
4102 react. You may also wish to use the gtk_widget_set_usize() call to set
4103 the default size of the window or other widgets.
4105 <!-- ----------------------------------------------------------------- -->
4106 <sect1> Paned Window Widgets
4108 The paned window widgets are useful when you want to divide an area
4109 into two parts, with the relative size of the two parts controlled by
4110 the user. A groove is drawn between the two portions with a handle
4111 that the user can drag to change the ratio. The division can either
4112 be horizontal (HPaned) or vertical (VPaned).
4114 To create a new paned window, call one of:
4117 GtkWidget *gtk_hpaned_new (void);
4119 GtkWidget *gtk_vpaned_new (void);
4122 After creating the paned window widget, you need to add child widgets
4123 to its two halves. To do this, use the functions:
4126 void gtk_paned_add1 (GtkPaned *paned, GtkWidget *child);
4128 void gtk_paned_add2 (GtkPaned *paned, GtkWidget *child);
4131 <tt/gtk_paned_add1()/ adds the child widget to the left or top half of
4132 the paned window. <tt/gtk_paned_add2()/ adds the child widget to the
4133 right or bottom half of the paned window.
4135 As an example, we will create part of the user interface of an
4136 imaginary email program. A window is divided into two portions
4137 vertically, with the top portion being a list of email messages and
4138 the bottom portion the text of the email message. Most of the program
4139 is pretty straightforward. A couple of points to note: text can't
4140 be added to a Text widget until it is realized. This could be done by
4141 calling <tt/gtk_widget_realize()/, but as a demonstration of an alternate
4142 technique, we connect a handler to the "realize" signal to add the
4143 text. Also, we need to add the <tt/GTK_SHRINK/ option to some of the
4144 items in the table containing the text window and its scrollbars, so
4145 that when the bottom portion is made smaller, the correct portions
4146 shrink instead of being pushed off the bottom of the window.
4149 /* example-start paned/paned.c */
4151 #include <gtk/gtk.h>
4153 /* Create the list of "messages" */
4158 GtkWidget *scrolled_window;
4160 GtkWidget *list_item;
4165 /* Create a new scrolled window, with scrollbars only if needed */
4166 scrolled_window = gtk_scrolled_window_new (NULL, NULL);
4167 gtk_scrolled_window_set_policy (GTK_SCROLLED_WINDOW (scrolled_window),
4168 GTK_POLICY_AUTOMATIC,
4169 GTK_POLICY_AUTOMATIC);
4171 /* Create a new list and put it in the scrolled window */
4172 list = gtk_list_new ();
4173 gtk_container_add (GTK_CONTAINER(scrolled_window), list);
4174 gtk_widget_show (list);
4176 /* Add some messages to the window */
4177 for (i=0; i<10; i++) {
4179 sprintf(buffer,"Message #%d",i);
4180 list_item = gtk_list_item_new_with_label (buffer);
4181 gtk_container_add (GTK_CONTAINER(list), list_item);
4182 gtk_widget_show (list_item);
4186 return scrolled_window;
4189 /* Add some text to our text widget - this is a callback that is invoked
4190 when our window is realized. We could also force our window to be
4191 realized with gtk_widget_realize, but it would have to be part of
4192 a hierarchy first */
4195 realize_text (GtkWidget *text, gpointer data)
4197 gtk_text_freeze (GTK_TEXT (text));
4198 gtk_text_insert (GTK_TEXT (text), NULL, &text->style->black, NULL,
4199 "From: pathfinder@nasa.gov\n"
4200 "To: mom@nasa.gov\n"
4201 "Subject: Made it!\n"
4203 "We just got in this morning. The weather has been\n"
4204 "great - clear but cold, and there are lots of fun sights.\n"
4205 "Sojourner says hi. See you soon.\n"
4208 gtk_text_thaw (GTK_TEXT (text));
4211 /* Create a scrolled text area that displays a "message" */
4217 GtkWidget *hscrollbar;
4218 GtkWidget *vscrollbar;
4220 /* Create a table to hold the text widget and scrollbars */
4221 table = gtk_table_new (2, 2, FALSE);
4223 /* Put a text widget in the upper left hand corner. Note the use of
4224 * GTK_SHRINK in the y direction */
4225 text = gtk_text_new (NULL, NULL);
4226 gtk_table_attach (GTK_TABLE (table), text, 0, 1, 0, 1,
4227 GTK_FILL | GTK_EXPAND,
4228 GTK_FILL | GTK_EXPAND | GTK_SHRINK, 0, 0);
4229 gtk_widget_show (text);
4231 /* Put a HScrollbar in the lower left hand corner */
4232 hscrollbar = gtk_hscrollbar_new (GTK_TEXT (text)->hadj);
4233 gtk_table_attach (GTK_TABLE (table), hscrollbar, 0, 1, 1, 2,
4234 GTK_EXPAND | GTK_FILL, GTK_FILL, 0, 0);
4235 gtk_widget_show (hscrollbar);
4237 /* And a VScrollbar in the upper right */
4238 vscrollbar = gtk_vscrollbar_new (GTK_TEXT (text)->vadj);
4239 gtk_table_attach (GTK_TABLE (table), vscrollbar, 1, 2, 0, 1,
4240 GTK_FILL, GTK_EXPAND | GTK_FILL | GTK_SHRINK, 0, 0);
4241 gtk_widget_show (vscrollbar);
4243 /* Add a handler to put a message in the text widget when it is realized */
4244 gtk_signal_connect (GTK_OBJECT (text), "realize",
4245 GTK_SIGNAL_FUNC (realize_text), NULL);
4251 main (int argc, char *argv[])
4258 gtk_init (&argc, &argv);
4260 window = gtk_window_new (GTK_WINDOW_TOPLEVEL);
4261 gtk_window_set_title (GTK_WINDOW (window), "Paned Windows");
4262 gtk_signal_connect (GTK_OBJECT (window), "destroy",
4263 GTK_SIGNAL_FUNC (gtk_main_quit), NULL);
4264 gtk_container_border_width (GTK_CONTAINER (window), 10);
4266 /* create a vpaned widget and add it to our toplevel window */
4268 vpaned = gtk_vpaned_new ();
4269 gtk_container_add (GTK_CONTAINER(window), vpaned);
4270 gtk_widget_show (vpaned);
4272 /* Now create the contents of the two halves of the window */
4274 list = create_list ();
4275 gtk_paned_add1 (GTK_PANED(vpaned), list);
4276 gtk_widget_show (list);
4278 text = create_text ();
4279 gtk_paned_add2 (GTK_PANED(vpaned), text);
4280 gtk_widget_show (text);
4281 gtk_widget_show (window);
4288 <!-- ----------------------------------------------------------------- -->
4289 <sect1> Aspect Frames
4291 The aspect frame widget is like a frame widget, except that it also
4292 enforces the aspect ratio (that is, the ratio of the width to the
4293 height) of the child widget to have a certain value, adding extra
4294 space if necessary. This is useful, for instance, if you want to
4295 preview a larger image. The size of the preview should vary when
4296 the user resizes the window, but the aspect ratio needs to always match
4299 To create a new aspect frame use:
4302 GtkWidget *gtk_aspect_frame_new( const gchar *label,
4309 <tt/xalign/ and <tt/yalign/ specifiy alignment as with Alignment
4310 widgets. If <tt/obey_child/ is true, the aspect ratio of a child
4311 widget will match the aspect ratio of the ideal size it requests.
4312 Otherwise, it is given by <tt/ratio/.
4314 To change the options of an existing aspect frame, you can use:
4317 void gtk_aspect_frame_set( GtkAspectFrame *aspect_frame,
4324 As an example, the following program uses an AspectFrame to
4325 present a drawing area whose aspect ratio will always be 2:1, no
4326 matter how the user resizes the top-level window.
4329 /* example-start aspectframe/aspectframe.c */
4331 #include <gtk/gtk.h>
4334 main (int argc, char *argv[])
4337 GtkWidget *aspect_frame;
4338 GtkWidget *drawing_area;
4339 gtk_init (&argc, &argv);
4341 window = gtk_window_new (GTK_WINDOW_TOPLEVEL);
4342 gtk_window_set_title (GTK_WINDOW (window), "Aspect Frame");
4343 gtk_signal_connect (GTK_OBJECT (window), "destroy",
4344 GTK_SIGNAL_FUNC (gtk_main_quit), NULL);
4345 gtk_container_border_width (GTK_CONTAINER (window), 10);
4347 /* Create an aspect_frame and add it to our toplevel window */
4349 aspect_frame = gtk_aspect_frame_new ("2x1", /* label */
4352 2, /* xsize/ysize = 2 */
4353 FALSE /* ignore child's aspect */);
4355 gtk_container_add (GTK_CONTAINER(window), aspect_frame);
4356 gtk_widget_show (aspect_frame);
4358 /* Now add a child widget to the aspect frame */
4360 drawing_area = gtk_drawing_area_new ();
4362 /* Ask for a 200x200 window, but the AspectFrame will give us a 200x100
4363 * window since we are forcing a 2x1 aspect ratio */
4364 gtk_widget_set_usize (drawing_area, 200, 200);
4365 gtk_container_add (GTK_CONTAINER(aspect_frame), drawing_area);
4366 gtk_widget_show (drawing_area);
4368 gtk_widget_show (window);
4375 <!-- ***************************************************************** -->
4377 <!-- ***************************************************************** -->
4379 NOTE: The GtkList widget has been superseded by the GtkCList widget.
4381 The GtkList widget is designed to act as a vertical container for widgets
4382 that should be of the type GtkListItem.
4384 A GtkList widget has its own window to receive events and it's own
4385 background color which is usualy white. As it is directly derived from a
4386 GtkContainer it can be treated as such by using the GTK_CONTAINER(List)
4387 macro, see the GtkContainer widget for more on this.
4388 One should already be familar whith the usage of a GList and its
4389 related functions g_list_*() to be able to use the GtkList widget to
4392 There is one field inside the structure definition of the GtkList widget
4393 that will be of greater interest to us, this is:
4400 guint selection_mode;
4405 The selection field of a GtkList points to a linked list of all items
4406 that are curently selected, or NULL if the selection is empty.
4407 So to learn about the current selection we read the GTK_LIST()->selection
4408 field, but do not modify it since the internal fields are maintained by
4409 the gtk_list_*() functions.
4411 The selection_mode of the GtkList determines the selection facilities
4412 of a GtkList and therefore the contents of the GTK_LIST()->selection
4413 field. The selection_mode may be one of the following:
4416 <item> GTK_SELECTION_SINGLE - The selection is either NULL
4417 or contains a GList pointer
4418 for a single selected item.
4420 <item> GTK_SELECTION_BROWSE - The selection is NULL if the list
4421 contains no widgets or insensitive
4422 ones only, otherwise it contains
4423 a GList pointer for one GList
4424 structure, and therefore exactly
4427 <item> GTK_SELECTION_MULTIPLE - The selection is NULL if no list
4428 items are selected or a GList pointer
4429 for the first selected item. That
4430 in turn points to a GList structure
4431 for the second selected item and so
4434 <item> GTK_SELECTION_EXTENDED - The selection is always NULL.
4437 The default is GTK_SELECTION_MULTIPLE.
4439 <!-- ----------------------------------------------------------------- -->
4443 void selection_changed( GtkList *list );
4446 This signal will be invoked whenever the selection field
4447 of a GtkList has changed. This happens when a child of
4448 the GtkList got selected or deselected.
4451 void select_child( GtkList *list,
4455 This signal is invoked when a child of the GtkList is about
4456 to get selected. This happens mainly on calls to
4457 gtk_list_select_item(), gtk_list_select_child(), button presses
4458 and sometimes indirectly triggered on some else occasions where
4459 children get added to or removed from the GtkList.
4462 void unselect_child( GtkList *list,
4466 This signal is invoked when a child of the GtkList is about
4467 to get deselected. This happens mainly on calls to
4468 gtk_list_unselect_item(), gtk_list_unselect_child(), button presses
4469 and sometimes indirectly triggered on some else occasions where
4470 children get added to or removed from the GtkList.
4472 <!-- ----------------------------------------------------------------- -->
4476 guint gtk_list_get_type( void );
4479 Returns the `GtkList' type identifier.
4482 GtkWidget *gtk_list_new( void );
4485 Create a new GtkList object. The new widget is returned as a pointer to a
4486 GtkWidget object. NULL is returned on failure.
4489 void gtk_list_insert_items( GtkList *list,
4494 Insert list items into the list, starting at <tt/position/.
4495 <tt/items/ is a doubly linked list where each nodes data
4496 pointer is expected to point to a newly created GtkListItem.
4497 The GList nodes of <tt/items/ are taken over by the list.
4500 void gtk_list_append_items( GtkList *list,
4504 Insert list items just like gtk_list_insert_items() at the end
4505 of the list. The GList nodes of <tt/items/ are taken over by the list.
4508 void gtk_list_prepend_items( GtkList *list,
4512 Insert list items just like gtk_list_insert_items() at the very
4513 beginning of the list. The GList nodes of <tt/items/ are taken over
4517 void gtk_list_remove_items( GtkList *list,
4521 Remove list items from the list. <tt/items/ is a doubly linked
4522 list where each nodes data pointer is expected to point to a
4523 direct child of list. It is the callers responsibility to make a
4524 call to g_list_free(items) afterwards. Also the caller has to
4525 destroy the list items himself.
4528 void gtk_list_clear_items( GtkList *list,
4533 Remove and destroy list items from the list. A widget is affected if
4534 its current position within the list is in the range specified by
4535 <tt/start/ and <tt/end/.
4538 void gtk_list_select_item( GtkList *list,
4542 Invoke the select_child signal for a list item
4543 specified through its current position within the list.
4546 void gtk_list_unselect_item( GtkList *list,
4550 Invoke the unselect_child signal for a list item
4551 specified through its current position within the list.
4554 void gtk_list_select_child( GtkList *list,
4558 Invoke the select_child signal for the specified child.
4561 void gtk_list_unselect_child( GtkList *list,
4565 Invoke the unselect_child signal for the specified child.
4568 gint gtk_list_child_position( GtkList *list,
4572 Return the position of <tt/child/ within the list. "-1" is returned on failure.
4575 void gtk_list_set_selection_mode( GtkList *list,
4576 GtkSelectionMode mode );
4579 Set the selection mode MODE which can be of GTK_SELECTION_SINGLE,
4580 GTK_SELECTION_BROWSE, GTK_SELECTION_MULTIPLE or GTK_SELECTION_EXTENDED.
4583 GtkList *GTK_LIST( gpointer obj );
4586 Cast a generic pointer to `GtkList *'. *Note Standard Macros::, for
4590 GtkListClass *GTK_LIST_CLASS( gpointer class);
4593 Cast a generic pointer to `GtkListClass*'. *Note Standard Macros::,
4597 gint GTK_IS_LIST( gpointer obj);
4600 Determine if a generic pointer refers to a `GtkList' object. *Note
4601 Standard Macros::, for more info.
4603 <!-- ----------------------------------------------------------------- -->
4606 Following is an example program that will print out the changes
4607 of the selection of a GtkList, and lets you "arrest" list items
4608 into a prison by selecting them with the rightmost mouse button.
4611 /* example-start list/list.c */
4613 /* include the gtk+ header files
4614 * include stdio.h, we need that for the printf() function
4616 #include <gtk/gtk.h>
4619 /* this is our data identification string to store
4620 * data in list items
4622 const gchar *list_item_data_key="list_item_data";
4625 /* prototypes for signal handler that we are going to connect
4626 * to the GtkList widget
4628 static void sigh_print_selection (GtkWidget *gtklist,
4629 gpointer func_data);
4630 static void sigh_button_event (GtkWidget *gtklist,
4631 GdkEventButton *event,
4635 /* main function to set up the user interface */
4637 gint main (int argc, gchar *argv[])
4639 GtkWidget *separator;
4642 GtkWidget *scrolled_window;
4646 GtkWidget *list_item;
4652 /* initialize gtk+ (and subsequently gdk) */
4654 gtk_init(&argc, &argv);
4657 /* create a window to put all the widgets in
4658 * connect gtk_main_quit() to the "destroy" event of
4659 * the window to handle window manager close-window-events
4661 window=gtk_window_new(GTK_WINDOW_TOPLEVEL);
4662 gtk_window_set_title(GTK_WINDOW(window), "GtkList Example");
4663 gtk_signal_connect(GTK_OBJECT(window),
4665 GTK_SIGNAL_FUNC(gtk_main_quit),
4669 /* inside the window we need a box to arrange the widgets
4671 vbox=gtk_vbox_new(FALSE, 5);
4672 gtk_container_border_width(GTK_CONTAINER(vbox), 5);
4673 gtk_container_add(GTK_CONTAINER(window), vbox);
4674 gtk_widget_show(vbox);
4676 /* this is the scolled window to put the GtkList widget inside */
4677 scrolled_window=gtk_scrolled_window_new(NULL, NULL);
4678 gtk_widget_set_usize(scrolled_window, 250, 150);
4679 gtk_container_add(GTK_CONTAINER(vbox), scrolled_window);
4680 gtk_widget_show(scrolled_window);
4682 /* create the GtkList widget
4683 * connect the sigh_print_selection() signal handler
4684 * function to the "selection_changed" signal of the GtkList
4685 * to print out the selected items each time the selection
4687 gtklist=gtk_list_new();
4688 gtk_container_add(GTK_CONTAINER(scrolled_window), gtklist);
4689 gtk_widget_show(gtklist);
4690 gtk_signal_connect(GTK_OBJECT(gtklist),
4691 "selection_changed",
4692 GTK_SIGNAL_FUNC(sigh_print_selection),
4695 /* we create a "Prison" to put a list item in ;)
4697 frame=gtk_frame_new("Prison");
4698 gtk_widget_set_usize(frame, 200, 50);
4699 gtk_container_border_width(GTK_CONTAINER(frame), 5);
4700 gtk_frame_set_shadow_type(GTK_FRAME(frame), GTK_SHADOW_OUT);
4701 gtk_container_add(GTK_CONTAINER(vbox), frame);
4702 gtk_widget_show(frame);
4704 /* connect the sigh_button_event() signal handler to the GtkList
4705 * wich will handle the "arresting" of list items
4707 gtk_signal_connect(GTK_OBJECT(gtklist),
4708 "button_release_event",
4709 GTK_SIGNAL_FUNC(sigh_button_event),
4712 /* create a separator
4714 separator=gtk_hseparator_new();
4715 gtk_container_add(GTK_CONTAINER(vbox), separator);
4716 gtk_widget_show(separator);
4718 /* finaly create a button and connect it´s "clicked" signal
4719 * to the destroyment of the window
4721 button=gtk_button_new_with_label("Close");
4722 gtk_container_add(GTK_CONTAINER(vbox), button);
4723 gtk_widget_show(button);
4724 gtk_signal_connect_object(GTK_OBJECT(button),
4726 GTK_SIGNAL_FUNC(gtk_widget_destroy),
4727 GTK_OBJECT(window));
4730 /* now we create 5 list items, each having it´s own
4731 * label and add them to the GtkList using gtk_container_add()
4732 * also we query the text string from the label and
4733 * associate it with the list_item_data_key for each list item
4735 for (i=0; i<5; i++) {
4739 sprintf(buffer, "ListItemContainer with Label #%d", i);
4740 label=gtk_label_new(buffer);
4741 list_item=gtk_list_item_new();
4742 gtk_container_add(GTK_CONTAINER(list_item), label);
4743 gtk_widget_show(label);
4744 gtk_container_add(GTK_CONTAINER(gtklist), list_item);
4745 gtk_widget_show(list_item);
4746 gtk_label_get(GTK_LABEL(label), &string);
4747 gtk_object_set_data(GTK_OBJECT(list_item),
4751 /* here, we are creating another 5 labels, this time
4752 * we use gtk_list_item_new_with_label() for the creation
4753 * we can´t query the text string from the label because
4754 * we don´t have the labels pointer and therefore
4755 * we just associate the list_item_data_key of each
4756 * list item with the same text string
4757 * for adding of the list items we put them all into a doubly
4758 * linked list (GList), and then add them by a single call to
4759 * gtk_list_append_items()
4760 * because we use g_list_prepend() to put the items into the
4761 * doubly linked list, their order will be descending (instead
4762 * of ascending when using g_list_append())
4766 sprintf(buffer, "List Item with Label %d", i);
4767 list_item=gtk_list_item_new_with_label(buffer);
4768 dlist=g_list_prepend(dlist, list_item);
4769 gtk_widget_show(list_item);
4770 gtk_object_set_data(GTK_OBJECT(list_item),
4772 "ListItem with integrated Label");
4774 gtk_list_append_items(GTK_LIST(gtklist), dlist);
4776 /* finaly we want to see the window, don´t we? ;)
4778 gtk_widget_show(window);
4780 /* fire up the main event loop of gtk
4784 /* we get here after gtk_main_quit() has been called which
4785 * happens if the main window gets destroyed
4790 /* this is the signal handler that got connected to button
4791 * press/release events of the GtkList
4794 sigh_button_event (GtkWidget *gtklist,
4795 GdkEventButton *event,
4798 /* we only do something if the third (rightmost mouse button
4801 if (event->type==GDK_BUTTON_RELEASE &&
4803 GList *dlist, *free_list;
4804 GtkWidget *new_prisoner;
4806 /* fetch the currently selected list item which
4807 * will be our next prisoner ;)
4809 dlist=GTK_LIST(gtklist)->selection;
4811 new_prisoner=GTK_WIDGET(dlist->data);
4815 /* look for already prisoned list items, we
4816 * will put them back into the list
4817 * remember to free the doubly linked list that
4818 * gtk_container_children() returns
4820 dlist=gtk_container_children(GTK_CONTAINER(frame));
4823 GtkWidget *list_item;
4825 list_item=dlist->data;
4827 gtk_widget_reparent(list_item, gtklist);
4831 g_list_free(free_list);
4833 /* if we have a new prisoner, remove him from the
4834 * GtkList and put him into the frame "Prison"
4835 * we need to unselect the item before
4840 static_dlist.data=new_prisoner;
4841 static_dlist.next=NULL;
4842 static_dlist.prev=NULL;
4844 gtk_list_unselect_child(GTK_LIST(gtklist),
4846 gtk_widget_reparent(new_prisoner, frame);
4851 /* this is the signal handler that gets called if GtkList
4852 * emits the "selection_changed" signal
4855 sigh_print_selection (GtkWidget *gtklist,
4860 /* fetch the doubly linked list of selected items
4861 * of the GtkList, remember to treat this as read-only!
4863 dlist=GTK_LIST(gtklist)->selection;
4865 /* if there are no selected items there is nothing more
4866 * to do than just telling the user so
4869 g_print("Selection cleared\n");
4872 /* ok, we got a selection and so we print it
4874 g_print("The selection is a ");
4876 /* get the list item from the doubly linked list
4877 * and then query the data associated with list_item_data_key
4878 * we then just print it
4881 GtkObject *list_item;
4882 gchar *item_data_string;
4884 list_item=GTK_OBJECT(dlist->data);
4885 item_data_string=gtk_object_get_data(list_item,
4886 list_item_data_key);
4887 g_print("%s ", item_data_string);
4896 <!-- ----------------------------------------------------------------- -->
4897 <sect1> List Item Widget
4899 The GtkListItem widget is designed to act as a container holding up
4900 to one child, providing functions for selection/deselection just like
4901 the GtkList widget requires them for its children.
4903 A GtkListItem has its own window to receive events and has its own
4904 background color which is usualy white.
4906 As it is directly derived from a
4907 GtkItem it can be treated as such by using the GTK_ITEM(ListItem)
4908 macro, see the GtkItem widget for more on this.
4909 Usualy a GtkListItem just holds a label to identify e.g. a filename
4910 within a GtkList -- therefore the convenience function
4911 gtk_list_item_new_with_label() is provided. The same effect can be
4912 achieved by creating a GtkLabel on its own, setting its alignment
4913 to xalign=0 and yalign=0.5 with a subsequent container addition
4916 As one is not forced to add a GtkLabel to a GtkListItem, you could
4917 also add a GtkVBox or a GtkArrow etc. to the GtkListItem.
4919 <!-- ----------------------------------------------------------------- -->
4922 A GtkListItem does not create new signals on its own, but inherits
4923 the signals of a GtkItem. *Note GtkItem::, for more info.
4925 <!-- ----------------------------------------------------------------- -->
4929 guint gtk_list_item_get_type( void );
4932 Returns the `GtkListItem' type identifier.
4935 GtkWidget *gtk_list_item_new( void );
4938 Create a new GtkListItem object. The new widget is returned as a pointer
4939 to a GtkWidget object. NULL is returned on failure.
4942 GtkWidget *gtk_list_item_new_with_label( gchar *label );
4945 Create a new GtkListItem object, having a single GtkLabel as
4946 the sole child. The new widget is returned as a pointer to a
4947 GtkWidget object. NULL is returned on failure.
4950 void gtk_list_item_select( GtkListItem *list_item );
4953 This function is basicaly a wrapper around a call to
4954 gtk_item_select (GTK_ITEM (list_item)) which will emit the
4956 *Note GtkItem::, for more info.
4959 void gtk_list_item_deselect( GtkListItem *list_item );
4962 This function is basicaly a wrapper around a call to
4963 gtk_item_deselect (GTK_ITEM (list_item)) which will emit the
4965 *Note GtkItem::, for more info.
4968 GtkListItem *GTK_LIST_ITEM( gpointer obj );
4971 Cast a generic pointer to `GtkListItem*'. *Note Standard Macros::,
4975 GtkListItemClass *GTK_LIST_ITEM_CLASS( gpointer class );
4978 Cast a generic pointer to GtkListItemClass*. *Note Standard
4979 Macros::, for more info.
4982 gint GTK_IS_LIST_ITEM( gpointer obj );
4985 Determine if a generic pointer refers to a `GtkListItem' object.
4986 *Note Standard Macros::, for more info.
4988 <!-- ----------------------------------------------------------------- -->
4991 Please see the GtkList example on this, which covers the usage of a
4992 GtkListItem as well.
4994 <!-- ***************************************************************** -->
4996 <!-- ***************************************************************** -->
4998 There are two ways to create menus, there's the easy way, and there's the
4999 hard way. Both have their uses, but you can usually use the menufactory
5000 (the easy way). The "hard" way is to create all the menus using the calls
5001 directly. The easy way is to use the gtk_menu_factory calls. This is
5002 much simpler, but there are advantages and disadvantages to each approach.
5004 The menufactory is much easier to use, and to add new menus to, although
5005 writing a few wrapper functions to create menus using the manual method
5006 could go a long way towards usability. With the menufactory, it is not
5007 possible to add images or the character '/' to the menus.
5009 <!-- ----------------------------------------------------------------- -->
5010 <sect1>Manual Menu Creation
5012 In the true tradition of teaching, we'll show you the hard
5013 way first. <tt>:)</>
5015 There are three widgets that go into making a menubar and submenus:
5017 <item>a menu item, which is what the user wants to select, e.g. 'Save'
5018 <item>a menu, which acts as a container for the menu items, and
5019 <item>a menubar, which is a container for each of the individual menus,
5022 This is slightly complicated by the fact that menu item widgets are used
5023 for two different things. They are both the widets that are packed into
5024 the menu, and the widget that is packed into the menubar, which,
5025 when selected, activiates the menu.
5027 Let's look at the functions that are used to create menus and menubars.
5028 This first function is used to create a new menubar.
5031 GtkWidget *gtk_menu_bar_new( void );
5034 This rather self explanatory function creates a new menubar. You use
5035 gtk_container_add to pack this into a window, or the box_pack functions to
5036 pack it into a box - the same as buttons.
5039 GtkWidget *gtk_menu_new( void );
5042 This function returns a pointer to a new menu, it is never actually shown
5043 (with gtk_widget_show), it is just a container for the menu items. Hopefully this will
5044 become more clear when you look at the example below.
5046 The next two calls are used to create menu items that are packed into
5047 the menu (and menubar).
5050 GtkWidget *gtk_menu_item_new( void );
5056 GtkWidget *gtk_menu_item_new_with_label( const char *label );
5059 These calls are used to create the menu items that are to be displayed.
5060 Remember to differentiate between a "menu" as created with gtk_menu_new
5061 and a "menu item" as created by the gtk_menu_item_new functions. The
5062 menu item will be an actual button with an associated action,
5063 whereas a menu will be a container holding menu items.
5065 The gtk_menu_new_with_label and gtk_menu_new functions are just as you'd expect after
5066 reading about the buttons. One creates a new menu item with a label
5067 already packed into it, and the other just creates a blank menu item.
5069 Once you've created a menu item you have to put it into a menu. This is
5070 done using the function gtk_menu_append. In order to capture when the item
5071 is selected by the user, we need to connect to the <tt/activate/ signal in
5072 the usual way. So, if we wanted to create a standard <tt/File/ menu, with
5073 the options <tt/Open/, <tt/Save/ and <tt/Quit/ the code would look something like
5076 file_menu = gtk_menu_new(); /* Don't need to show menus */
5078 /* Create the menu items */
5079 open_item = gtk_menu_item_new_with_label("Open");
5080 save_item = gtk_menu_item_new_with_label("Save");
5081 quit_item = gtk_menu_item_new_with_label("Quit");
5083 /* Add them to the menu */
5084 gtk_menu_append( GTK_MENU(file_menu), open_item);
5085 gtk_menu_append( GTK_MENU(file_menu), save_item);
5086 gtk_menu_append( GTK_MENU(file_menu), quit_item);
5088 /* Attach the callback functions to the activate signal */
5089 gtk_signal_connect_object( GTK_OBJECT(open_items), "activate",
5090 GTK_SIGNAL_FUNC(menuitem_response), (gpointer) "file.open");
5091 gtk_signal_connect_object( GTK_OBJECT(save_items), "activate",
5092 GTK_SIGNAL_FUNC(menuitem_response), (gpointer) "file.save");
5094 /* We can attach the Quit menu item to our exit function */
5095 gtk_signal_connect_object( GTK_OBJECT(quit_items), "activate",
5096 GTK_SIGNAL_FUNC(destroy), (gpointer) "file.quit");
5098 /* We do need to show menu items */
5099 gtk_widget_show( open_item );
5100 gtk_widget_show( save_item );
5101 gtk_widget_show( quit_item );
5104 At this point we have our menu. Now we need to create a menubar and a menu
5105 item for the <tt/File/ entry, to which we add our menu. The code looks like this
5108 menu_bar = gtk_menu_bar_new();
5109 gtk_container_add( GTK_CONTAINER(window), menu_bar);
5110 gtk_widget_show( menu_bar );
5112 file_item = gtk_menu_item_new_with_label("File");
5113 gtk_widget_show(file_item);
5116 Now we need to associate the menu with <tt/file_item/. This is done with the
5120 void gtk_menu_item_set_submenu( GtkMenuItem *menu_item,
5121 GtkWidget *submenu );
5124 So, our example would continue with
5127 gtk_menu_item_set_submenu( GTK_MENU_ITEM(file_item), file_menu );
5130 All that is left to do is to add the menu to the menubar, which is accomplished
5134 void gtk_menu_bar_append( GtkMenuBar *menu_bar, GtkWidget *menu_item);
5137 which in our case looks like this:
5140 gtk_menu_bar_append( GTK_MENU_BAR (menu_bar), file_item );
5143 If we wanted the menu right justified on the menubar, such as help menus
5144 often are, we can use the following function (again on <tt/file_item/
5145 in the current example) before attaching it to the menubar.
5148 void gtk_menu_item_right_justify( GtkMenuItem *menu_item );
5151 Here is a summary of the steps needed to create a menu bar with menus attached:
5154 <item> Create a new menu using gtk_menu_new()
5155 <item> Use multiple calls to gtk_menu_item_new() for each item you wish to have
5156 on your menu. And use gtk_menu_append() to put each of these new items on
5158 <item> Create a menu item using gtk_menu_item_new(). This will be the root of
5159 the menu, the text appearing here will be on the menubar itself.
5160 <item>Use gtk_menu_item_set_submenu() to attach the menu to the root menu
5161 item (the one created in the above step).
5162 <item> Create a new menubar using gtk_menu_bar_new. This step only needs
5163 to be done once when creating a series of menus on one menu bar.
5164 <item> Use gtk_menu_bar_append to put the root menu onto the menubar.
5167 Creating a popup menu is nearly the same. The difference is that the
5168 menu is not posted `automatically' by a menubar, but explicitly by calling
5169 the function gtk_menu_popup() from a button-press event, for example.
5173 <item>Create an event handling function. It needs to have the prototype
5175 static gint handler( GtkWidget *widget,
5178 and it will use the event to find out where to pop up the menu.
5179 <item>In the event handler, if the event is a mouse button press, treat
5180 <tt>event</tt> as a button event (which it is) and use it as
5181 shown in the sample code to pass information to gtk_menu_popup().
5182 <item>Bind that event handler to a widget with
5184 gtk_signal_connect_object(GTK_OBJECT(widget), "event",
5185 GTK_SIGNAL_FUNC (handler), GTK_OBJECT(menu));
5187 where <tt>widget</tt> is the widget you are binding to, <tt>handler</tt>
5188 is the handling function, and <tt>menu</tt> is a menu created with
5189 gtk_menu_new(). This can be a menu which is also posted by a menu bar,
5190 as shown in the sample code.
5193 <!-- ----------------------------------------------------------------- -->
5194 <sect1>Manual Menu Example
5196 That should about do it. Let's take a look at an example to help clarify.
5199 /* example-start menu/menu.c */
5201 #include <gtk/gtk.h>
5203 static gint button_press (GtkWidget *, GdkEvent *);
5204 static void menuitem_response (gchar *);
5206 int main (int argc, char *argv[])
5211 GtkWidget *menu_bar;
5212 GtkWidget *root_menu;
5213 GtkWidget *menu_items;
5219 gtk_init (&argc, &argv);
5221 /* create a new window */
5222 window = gtk_window_new(GTK_WINDOW_TOPLEVEL);
5223 gtk_widget_set_usize( GTK_WIDGET (window), 200, 100);
5224 gtk_window_set_title(GTK_WINDOW (window), "GTK Menu Test");
5225 gtk_signal_connect(GTK_OBJECT (window), "delete_event",
5226 (GtkSignalFunc) gtk_main_quit, NULL);
5228 /* Init the menu-widget, and remember -- never
5229 * gtk_show_widget() the menu widget!!
5230 * This is the menu that holds the menu items, the one that
5231 * will pop up when you click on the "Root Menu" in the app */
5232 menu = gtk_menu_new();
5234 /* Next we make a little loop that makes three menu-entries for "test-menu".
5235 * Notice the call to gtk_menu_append. Here we are adding a list of
5236 * menu items to our menu. Normally, we'd also catch the "clicked"
5237 * signal on each of the menu items and setup a callback for it,
5238 * but it's omitted here to save space. */
5240 for(i = 0; i < 3; i++)
5242 /* Copy the names to the buf. */
5243 sprintf(buf, "Test-undermenu - %d", i);
5245 /* Create a new menu-item with a name... */
5246 menu_items = gtk_menu_item_new_with_label(buf);
5248 /* ...and add it to the menu. */
5249 gtk_menu_append(GTK_MENU (menu), menu_items);
5251 /* Do something interesting when the menuitem is selected */
5252 gtk_signal_connect_object(GTK_OBJECT(menu_items), "activate",
5253 GTK_SIGNAL_FUNC(menuitem_response), (gpointer) g_strdup(buf));
5255 /* Show the widget */
5256 gtk_widget_show(menu_items);
5259 /* This is the root menu, and will be the label
5260 * displayed on the menu bar. There won't be a signal handler attached,
5261 * as it only pops up the rest of the menu when pressed. */
5262 root_menu = gtk_menu_item_new_with_label("Root Menu");
5264 gtk_widget_show(root_menu);
5266 /* Now we specify that we want our newly created "menu" to be the menu
5267 * for the "root menu" */
5268 gtk_menu_item_set_submenu(GTK_MENU_ITEM (root_menu), menu);
5270 /* A vbox to put a menu and a button in: */
5271 vbox = gtk_vbox_new(FALSE, 0);
5272 gtk_container_add(GTK_CONTAINER(window), vbox);
5273 gtk_widget_show(vbox);
5275 /* Create a menu-bar to hold the menus and add it to our main window */
5276 menu_bar = gtk_menu_bar_new();
5277 gtk_box_pack_start(GTK_BOX(vbox), menu_bar, FALSE, FALSE, 2);
5278 gtk_widget_show(menu_bar);
5280 /* Create a button to which to attach menu as a popup */
5281 button = gtk_button_new_with_label("press me");
5282 gtk_signal_connect_object(GTK_OBJECT(button), "event",
5283 GTK_SIGNAL_FUNC (button_press), GTK_OBJECT(menu));
5284 gtk_box_pack_end(GTK_BOX(vbox), button, TRUE, TRUE, 2);
5285 gtk_widget_show(button);
5287 /* And finally we append the menu-item to the menu-bar -- this is the
5288 * "root" menu-item I have been raving about =) */
5289 gtk_menu_bar_append(GTK_MENU_BAR (menu_bar), root_menu);
5291 /* always display the window as the last step so it all splashes on
5292 * the screen at once. */
5293 gtk_widget_show(window);
5300 /* Respond to a button-press by posting a menu passed in as widget.
5302 * Note that the "widget" argument is the menu being posted, NOT
5303 * the button that was pressed.
5306 static gint button_press (GtkWidget *widget, GdkEvent *event)
5309 if (event->type == GDK_BUTTON_PRESS) {
5310 GdkEventButton *bevent = (GdkEventButton *) event;
5311 gtk_menu_popup (GTK_MENU(widget), NULL, NULL, NULL, NULL,
5312 bevent->button, bevent->time);
5313 /* Tell calling code that we have handled this event; the buck
5318 /* Tell calling code that we have not handled this event; pass it on. */
5323 /* Print a string when a menu item is selected */
5325 static void menuitem_response (gchar *string)
5327 printf("%s\n", string);
5332 You may also set a menu item to be insensitive and, using an accelerator
5333 table, bind keys to menu functions.
5335 <!-- ----------------------------------------------------------------- -->
5336 <sect1>Using GtkMenuFactory
5338 Now that we've shown you the hard way, here's how you do it using the
5339 gtk_menu_factory calls.
5341 <!-- ----------------------------------------------------------------- -->
5342 <sect1>Menu Factory Example
5344 Here is an example using the GTK menu factory. This is the first file,
5345 menufactory.h. We keep a separate menufactory.c and mfmain.c because
5346 of the global variables used in the menufactory.c file.
5349 /* example-start menu/menufactory.h */
5351 #ifndef __MENUFACTORY_H__
5352 #define __MENUFACTORY_H__
5356 #endif /* __cplusplus */
5358 void get_main_menu (GtkWidget **menubar, GtkAcceleratorTable **table);
5359 void menus_create(GtkMenuEntry *entries, int nmenu_entries);
5363 #endif /* __cplusplus */
5365 #endif /* __MENUFACTORY_H__ */
5369 And here is the menufactory.c file.
5372 /* example-start menu/menufactory.c */
5374 #include <gtk/gtk.h>
5375 #include <strings.h>
5380 static void menus_remove_accel(GtkWidget * widget, gchar * signal_name, gchar * path);
5381 static gint menus_install_accel(GtkWidget * widget, gchar * signal_name, gchar key, gchar modifiers, gchar * path);
5382 void menus_init(void);
5383 void menus_create(GtkMenuEntry * entries, int nmenu_entries);
5386 /* this is the GtkMenuEntry structure used to create new menus. The
5387 * first member is the menu definition string. The second, the
5388 * default accelerator key used to access this menu function with
5389 * the keyboard. The third is the callback function to call when
5390 * this menu item is selected (by the accelerator key, or with the
5391 * mouse.) The last member is the data to pass to your callback function.
5394 static GtkMenuEntry menu_items[] =
5396 {"<Main>/File/New", "<control>N", NULL, NULL},
5397 {"<Main>/File/Open", "<control>O", NULL, NULL},
5398 {"<Main>/File/Save", "<control>S", NULL, NULL},
5399 {"<Main>/File/Save as", NULL, NULL, NULL},
5400 {"<Main>/File/<separator>", NULL, NULL, NULL},
5401 {"<Main>/File/Quit", "<control>Q", file_quit_cmd_callback, "OK, I'll quit"},
5402 {"<Main>/Options/Test", NULL, NULL, NULL}
5405 /* calculate the number of menu_item's */
5406 static int nmenu_items = sizeof(menu_items) / sizeof(menu_items[0]);
5408 static int initialize = TRUE;
5409 static GtkMenuFactory *factory = NULL;
5410 static GtkMenuFactory *subfactory[1];
5411 static GHashTable *entry_ht = NULL;
5413 void get_main_menu(GtkWidget ** menubar, GtkAcceleratorTable ** table)
5419 *menubar = subfactory[0]->widget;
5421 *table = subfactory[0]->table;
5424 void menus_init(void)
5429 factory = gtk_menu_factory_new(GTK_MENU_FACTORY_MENU_BAR);
5430 subfactory[0] = gtk_menu_factory_new(GTK_MENU_FACTORY_MENU_BAR);
5432 gtk_menu_factory_add_subfactory(factory, subfactory[0], "<Main>");
5433 menus_create(menu_items, nmenu_items);
5437 void menus_create(GtkMenuEntry * entries, int nmenu_entries)
5446 for (i = 0; i < nmenu_entries; i++) {
5447 accelerator = g_hash_table_lookup(entry_ht, entries[i].path);
5449 if (accelerator[0] == '\0')
5450 entries[i].accelerator = NULL;
5452 entries[i].accelerator = accelerator;
5455 gtk_menu_factory_add_entries(factory, entries, nmenu_entries);
5457 for (i = 0; i < nmenu_entries; i++)
5458 if (entries[i].widget) {
5459 gtk_signal_connect(GTK_OBJECT(entries[i].widget), "install_accelerator",
5460 (GtkSignalFunc) menus_install_accel,
5462 gtk_signal_connect(GTK_OBJECT(entries[i].widget), "remove_accelerator",
5463 (GtkSignalFunc) menus_remove_accel,
5468 static gint menus_install_accel(GtkWidget * widget, gchar * signal_name, gchar key, gchar modifiers, gchar * path)
5474 if (modifiers & GDK_CONTROL_MASK)
5475 strcat(accel, "<control>");
5476 if (modifiers & GDK_SHIFT_MASK)
5477 strcat(accel, "<shift>");
5478 if (modifiers & GDK_MOD1_MASK)
5479 strcat(accel, "<alt>");
5486 t1 = g_hash_table_lookup(entry_ht, path);
5489 entry_ht = g_hash_table_new(g_str_hash, g_str_equal);
5491 g_hash_table_insert(entry_ht, path, g_strdup(accel));
5496 static void menus_remove_accel(GtkWidget * widget, gchar * signal_name, gchar * path)
5501 t = g_hash_table_lookup(entry_ht, path);
5504 g_hash_table_insert(entry_ht, path, g_strdup(""));
5508 void menus_set_sensitive(char *path, int sensitive)
5510 GtkMenuPath *menu_path;
5515 menu_path = gtk_menu_factory_find(factory, path);
5517 gtk_widget_set_sensitive(menu_path->widget, sensitive);
5519 g_warning("Unable to set sensitivity for menu which doesn't exist: %s", path);
5524 And here's the mfmain.h
5527 /* example-start menu/mfmain.h */
5529 #ifndef __MFMAIN_H__
5530 #define __MFMAIN_H__
5535 #endif /* __cplusplus */
5537 void file_quit_cmd_callback(GtkWidget *widget, gpointer data);
5541 #endif /* __cplusplus */
5543 #endif /* __MFMAIN_H__ */
5550 /* example-start menu/mfmain.c */
5552 #include <gtk/gtk.h>
5555 #include "menufactory.h"
5558 int main(int argc, char *argv[])
5561 GtkWidget *main_vbox;
5564 GtkAcceleratorTable *accel;
5566 gtk_init(&argc, &argv);
5568 window = gtk_window_new(GTK_WINDOW_TOPLEVEL);
5569 gtk_signal_connect(GTK_OBJECT(window), "destroy",
5570 GTK_SIGNAL_FUNC(file_quit_cmd_callback),
5572 gtk_window_set_title(GTK_WINDOW(window), "Menu Factory");
5573 gtk_widget_set_usize(GTK_WIDGET(window), 300, 200);
5575 main_vbox = gtk_vbox_new(FALSE, 1);
5576 gtk_container_border_width(GTK_CONTAINER(main_vbox), 1);
5577 gtk_container_add(GTK_CONTAINER(window), main_vbox);
5578 gtk_widget_show(main_vbox);
5580 get_main_menu(&menubar, &accel);
5581 gtk_window_add_accelerator_table(GTK_WINDOW(window), accel);
5582 gtk_box_pack_start(GTK_BOX(main_vbox), menubar, FALSE, TRUE, 0);
5583 gtk_widget_show(menubar);
5585 gtk_widget_show(window);
5591 /* This is just to demonstrate how callbacks work when using the
5592 * menufactory. Often, people put all the callbacks from the menus
5593 * in a separate file, and then have them call the appropriate functions
5594 * from there. Keeps it more organized. */
5595 void file_quit_cmd_callback (GtkWidget *widget, gpointer data)
5597 g_print ("%s\n", (char *) data);
5603 And a makefile so it'll be easier to compile it.
5610 C_FLAGS = -Wall $(PROF) -L/usr/local/include -DDEBUG
5611 L_FLAGS = $(PROF) -L/usr/X11R6/lib -L/usr/local/lib
5612 L_POSTFLAGS = -lgtk -lgdk -lglib -lXext -lX11 -lm
5613 PROGNAME = menufactory
5615 O_FILES = menufactory.o mfmain.o
5617 $(PROGNAME): $(O_FILES)
5619 $(CC) $(L_FLAGS) -o $(PROGNAME) $(O_FILES) $(L_POSTFLAGS)
5622 $(CC) -c $(C_FLAGS) $<
5625 rm -f core *.o $(PROGNAME) nohup.out
5630 For now, there's only this example. An explanation and lots 'o' comments
5633 <!-- ***************************************************************** -->
5635 <!-- ***************************************************************** -->
5637 The Text widget allows multiple lines of text to be displayed and edited.
5638 It supports both multi-colored and multi-font text, allowing them to be
5639 mixed in any way we wish. It also has a wide set of key based text editing
5640 commands, which are compatible with Emacs.
5642 The text widget supports full cut-and-paste facilities, including the use
5643 of double- and triple-click to select a word and a whole line, respectively.
5645 <!-- ----------------------------------------------------------------- -->
5646 <sect1>Creating and Configuring a Text box
5648 There is only one function for creating a new Text widget.
5650 GtkWidget *gtk_text_new( GtkAdjustment *hadj,
5651 GtkAdjustment *vadj );
5654 The arguments allow us to give the Text widget pointers to Adjustments
5655 that can be used to track the viewing position of the widget. Passing NULL
5656 values to either or both of these arguments will cause the gtk_text_new
5657 function to create it's own.
5660 void gtk_text_set_adjustments( GtkText *text,
5661 GtkAdjustment *hadj,
5662 GtkAdjustment *vadj );
5665 The above function allows the horizontal and vertical adjustments of a
5666 Text widget to be changed at any time.
5668 The text widget will not automatically create it's own scrollbars when
5669 the amount of text to be displayed is too long for the display window. We
5670 therefore have to create and add them to the display layout ourselves.
5673 vscrollbar = gtk_vscrollbar_new (GTK_TEXT(text)->vadj);
5674 gtk_box_pack_start(GTK_BOX(hbox), vscrollbar, FALSE, FALSE, 0);
5675 gtk_widget_show (vscrollbar);
5678 The above code snippet creates a new vertical scrollbar, and attaches
5679 it to the vertical adjustment of the text widget, <tt/text/. It then packs
5680 it into a box in the normal way.
5682 Note, currently the GtkText widget does not support horizontal scrollbars.
5684 There are two main ways in which a Text widget can be used: to allow the
5685 user to edit a body of text, or to allow us to display multiple lines of
5686 text to the user. In order for us to switch between these modes of
5687 operation, the text widget has the following function:
5690 void gtk_text_set_editable( GtkText *text,
5694 The <tt/editable/ argument is a TRUE or FALSE value that specifies whether
5695 the user is permitted to edit the contents of the Text widget. When the
5696 text widget is editable, it will display a cursor at the current insertion
5699 You are not, however, restricted to just using the text widget in these
5700 two modes. You can toggle the editable state of the text widget at any
5701 time, and can insert text at any time.
5703 The text widget wraps lines of text that are too long to
5704 fit onto a single line of the display window. It's default behaviour is
5705 to break words across line breaks. This can be changed using the next
5709 void gtk_text_set_word_wrap( GtkText *text,
5713 Using this function allows us to specify that the text widget should
5714 wrap long lines on word boundaries. The <tt/word_wrap/ argument is a
5715 TRUE or FALSE value.
5717 <!-- ----------------------------------------------------------------- -->
5718 <sect1>Text Manipulation
5720 The current insertion point of a Text widget can be set using
5722 void gtk_text_set_point( GtkText *text,
5726 where <tt/index/ is the position to set the insertion point.
5728 Analogous to this is the function for getting the current insertion point:
5731 guint gtk_text_get_point( GtkText *text );
5734 A function that is useful in combination with the above two functions is
5737 guint gtk_text_get_length( GtkText *text );
5740 which returns the current length of the Text widget. The length is the
5741 number of characters that are within the text block of the widget,
5742 including characters such as carriage-return, which marks the end of lines.
5744 In order to insert text at the current insertion point of a Text
5745 widget, the function gtk_text_insert is used, which also allows us to
5746 specify background and foreground colors and a font for the text.
5749 void gtk_text_insert( GtkText *text,
5757 Passing a value of <tt/NULL/ in as the value for the foreground color,
5758 background colour or font will result in the values set within the widget
5759 style to be used. Using a value of <tt/-1/ for the length parameter will
5760 result in the whole of the text string given being inserted.
5762 The text widget is one of the few within GTK that redraws itself
5763 dynamically, outside of the gtk_main function. This means that all changes
5764 to the contents of the text widget take effect immediately. This may be
5765 undesirable when performing multiple changes to the text widget. In order
5766 to allow us to perform multiple updates to the text widget without it
5767 continuously redrawing, we can freeze the widget, which temporarily stops
5768 it from automatically redrawing itself every time it is changed. We can
5769 then thaw the widget after our updates are complete.
5771 The following two functions perform this freeze and thaw action:
5774 void gtk_text_freeze( GtkText *text );
5776 void gtk_text_thaw( GtkText *text );
5779 Text is deleted from the text widget relative to the current insertion
5780 point by the following two functions. The return value is a TRUE or
5781 FALSE indicator of whether the operation was successful.
5784 gint gtk_text_backward_delete( GtkText *text,
5787 gint gtk_text_forward_delete ( GtkText *text,
5791 If you want to retrieve the contents of the text widget, then the macro
5792 <tt/GTK_TEXT_INDEX(t, index)/ allows you to retrieve the character at
5793 position <tt/index/ within the text widget <tt/t/.
5795 To retrieve larger blocks of text, we can use the function
5798 gchar *gtk_editable_get_chars( GtkEditable *editable,
5803 This is a function of the parent class of the text widget. A value of -1 as
5804 <tt/end_pos/ signifies the end of the text. The index of the text starts at 0.
5806 The function allocates a new chunk of memory for the text block, so don't forget
5807 to free it with a call to g_free when you have finished with it.
5809 <!-- ----------------------------------------------------------------- -->
5810 <sect1>Keyboard Shortcuts
5812 The text widget has a number of pre-installed keyboard shotcuts for common
5813 editing, motion and selection functions. These are accessed using Control
5814 and Alt key combinations.
5816 In addition to these, holding down the Control key whilst using cursor key
5817 movement will move the cursor by words rather than characters. Holding down
5818 Shift whilst using cursor movement will extend the selection.
5820 <sect2>Motion Shotcuts
5823 <item> Ctrl-A Beginning of line
5824 <item> Ctrl-E End of line
5825 <item> Ctrl-N Next Line
5826 <item> Ctrl-P Previous Line
5827 <item> Ctrl-B Backward one character
5828 <item> Ctrl-F Forward one character
5829 <item> Alt-B Backward one word
5830 <item> Alt-F Forward one word
5833 <sect2>Editing Shortcuts
5836 <item> Ctrl-H Delete Backward Character (Backspace)
5837 <item> Ctrl-D Delete Forward Character (Delete)
5838 <item> Ctrl-W Delete Backward Word
5839 <item> Alt-D Delete Forward Word
5840 <item> Ctrl-K Delete to end of line
5841 <item> Ctrl-U Delete line
5844 <sect2>Selection Shortcuts
5847 <item> Ctrl-X Cut to clipboard
5848 <item> Ctrl-C Copy to clipboard
5849 <item> Ctrl-V Paste from clipboard
5852 <!-- ***************************************************************** -->
5853 <sect> Undocumented Widgets
5854 <!-- ***************************************************************** -->
5856 These all require authors! :) Please consider contributing to our tutorial.
5858 If you must use one of these widgets that are undocumented, I strongly
5859 suggest you take a look at their respective header files in the GTK
5860 distribution. GTK's function names are very descriptive. Once you have an
5861 understanding of how things work, it's not difficult to figure out how to
5862 use a widget simply by looking at it's function declarations. This, along
5863 with a few examples from others' code, and it should be no problem.
5865 When you do come to understand all the functions of a new undocumented
5866 widget, please consider writing a tutorial on it so others may benifit
5869 <!-- ----------------------------------------------------------------- -->
5872 <!-- ----------------------------------------------------------------- -->
5875 <!-- ----------------------------------------------------------------- -->
5876 <sect1> Fixed Container
5878 <!-- ----------------------------------------------------------------- -->
5881 <!-- ----------------------------------------------------------------- -->
5882 <sect1> Range Controls
5884 <!-- ----------------------------------------------------------------- -->
5887 <!-- ----------------------------------------------------------------- -->
5891 (This may need to be rewritten to follow the style of the rest of the tutorial)
5895 Previews serve a number of purposes in GIMP/GTK. The most important one is
5896 this. High quality images may take up to tens of megabytes of memory - easy!
5897 Any operation on an image that big is bound to take a long time. If it takes
5898 you 5-10 trial-and-errors (i.e. 10-20 steps, since you have to revert after
5899 you make an error) to choose the desired modification, it make take you
5900 literally hours to make the right one - if you don't run out of memory
5901 first. People who have spent hours in color darkrooms know the feeling.
5902 Previews to the rescue!
5904 But the annoyance of the delay is not the only issue. Oftentimes it is
5905 helpful to compare the Before and After versions side-by-side or at least
5906 back-to-back. If you're working with big images and 10 second delays,
5907 obtaining the Before and After impressions is, to say the least, difficult.
5908 For 30M images (4"x6", 600dpi, 24 bit) the side-by-side comparison is right
5909 out for most people, while back-to-back is more like back-to-1001, 1002,
5910 ..., 1010-back! Previews to the rescue!
5912 But there's more. Previews allow for side-by-side pre-previews. In other
5913 words, you write a plug-in (e.g. the filterpack simulation) which would have
5914 a number of here's-what-it-would-look-like-if-you-were-to-do-this previews.
5915 An approach like this acts as a sort of a preview palette and is very
5916 effective fow subtle changes. Let's go previews!
5918 There's more. For certain plug-ins real-time image-specific human
5919 intervention maybe necessary. In the SuperNova plug-in, for example, the
5920 user is asked to enter the coordinates of the center of the future
5921 supernova. The easiest way to do this, really, is to present the user with a
5922 preview and ask him to intereactively select the spot. Let's go previews!
5924 Finally, a couple of misc uses. One can use previews even when not working
5925 with big images. For example, they are useful when rendering compicated
5926 patterns. (Just check out the venerable Diffraction plug-in + many other
5927 ones!) As another example, take a look at the colormap rotation plug-in
5928 (work in progress). You can also use previews for little logo's inside you
5929 plug-ins and even for an image of yourself, The Author. Let's go previews!
5931 When Not to Use Previews
5933 Don't use previews for graphs, drawing etc. GDK is much faster for that. Use
5934 previews only for rendered images!
5938 You can stick a preview into just about anything. In a vbox, an hbox, a
5939 table, a button, etc. But they look their best in tight frames around them.
5940 Previews by themselves do not have borders and look flat without them. (Of
5941 course, if the flat look is what you want...) Tight frames provide the
5946 Previews in many ways are like any other widgets in GTK (whatever that
5947 means) except they possess an addtional feature: they need to be filled with
5948 some sort of an image! First, we will deal exclusively with the GTK aspect
5949 of previews and then we'll discuss how to fill them.
5955 /* Create a preview widget,
5956 set its size, an show it */
5958 preview=gtk_preview_new(GTK_PREVIEW_COLOR)
5960 GTK_PREVIEW_GRAYSCALE);*/
5961 gtk_preview_size (GTK_PREVIEW (preview), WIDTH, HEIGHT);
5962 gtk_widget_show(preview);
5963 my_preview_rendering_function(preview);
5965 Oh yeah, like I said, previews look good inside frames, so how about:
5967 GtkWidget *create_a_preview(int Width,
5974 frame = gtk_frame_new(NULL);
5975 gtk_frame_set_shadow_type (GTK_FRAME (frame), GTK_SHADOW_IN);
5976 gtk_container_border_width (GTK_CONTAINER(frame),0);
5977 gtk_widget_show(frame);
5979 preview=gtk_preview_new (Colorfulness?GTK_PREVIEW_COLOR
5980 :GTK_PREVIEW_GRAYSCALE);
5981 gtk_preview_size (GTK_PREVIEW (preview), Width, Height);
5982 gtk_container_add(GTK_CONTAINER(frame),preview);
5983 gtk_widget_show(preview);
5985 my_preview_rendering_function(preview);
5989 That's my basic preview. This routine returns the "parent" frame so you can
5990 place it somewhere else in your interface. Of course, you can pass the
5991 parent frame to this routine as a parameter. In many situations, however,
5992 the contents of the preview are changed continually by your application. In
5993 this case you may want to pass a pointer to the preview to a
5994 "create_a_preview()" and thus have control of it later.
5996 One more important note that may one day save you a lot of time. Sometimes
5997 it is desirable to label you preview. For example, you may label the preview
5998 containing the original image as "Original" and the one containing the
5999 modified image as "Less Original". It might occure to you to pack the
6000 preview along with the appropriate label into a vbox. The unexpected caveat
6001 is that if the label is wider than the preview (which may happen for a
6002 variety of reasons unforseeable to you, from the dynamic decision on the
6003 size of the preview to the size of the font) the frame expands and no longer
6004 fits tightly over the preview. The same problem can probably arise in other
6009 The solution is to place the preview and the label into a 2x1 table and by
6010 attaching them with the following paramters (this is one possible variations
6011 of course. The key is no GTK_FILL in the second attachment):
6013 gtk_table_attach(GTK_TABLE(table),label,0,1,0,1,
6015 GTK_EXPAND|GTK_FILL,
6017 gtk_table_attach(GTK_TABLE(table),frame,0,1,1,2,
6023 And here's the result:
6029 Making a preview clickable is achieved most easily by placing it in a
6030 button. It also adds a nice border around the preview and you may not even
6031 need to place it in a frame. See the Filter Pack Simulation plug-in for an
6034 This is pretty much it as far as GTK is concerned.
6036 Filling In a Preview
6038 In order to familiarize ourselves with the basics of filling in previews,
6039 let's create the following pattern (contrived by trial and error):
6044 my_preview_rendering_function(GtkWidget *preview)
6047 #define HALF (SIZE/2)
6049 guchar *row=(guchar *) malloc(3*SIZE); /* 3 bits per dot */
6050 gint i, j; /* Coordinates */
6051 double r, alpha, x, y;
6053 if (preview==NULL) return; /* I usually add this when I want */
6054 /* to avoid silly crashes. You */
6055 /* should probably make sure that */
6056 /* everything has been nicely */
6058 for (j=0; j < ABS(cos(2*alpha)) ) { /* Are we inside the shape? */
6059 /* glib.h contains ABS(x). */
6060 row[i*3+0] = sqrt(1-r)*255; /* Define Red */
6061 row[i*3+1] = 128; /* Define Green */
6062 row[i*3+2] = 224; /* Define Blue */
6063 } /* "+0" is for alignment! */
6066 row[i*3+1] = ABS(sin((float)i/SIZE*2*PI))*255;
6067 row[i*3+2] = ABS(sin((float)j/SIZE*2*PI))*255;
6070 gtk_preview_draw_row( GTK_PREVIEW(preview),row,0,j,SIZE);
6071 /* Insert "row" into "preview" starting at the point with */
6072 /* coordinates (0,j) first column, j_th row extending SIZE */
6073 /* pixels to the right */
6076 free(row); /* save some space */
6077 gtk_widget_draw(preview,NULL); /* what does this do? */
6078 gdk_flush(); /* or this? */
6081 Non-GIMP users can have probably seen enough to do a lot of things already.
6082 For the GIMP users I have a few pointers to add.
6086 It is probably wize to keep a reduced version of the image around with just
6087 enough pixels to fill the preview. This is done by selecting every n'th
6088 pixel where n is the ratio of the size of the image to the size of the
6089 preview. All further operations (including filling in the previews) are then
6090 performed on the reduced number of pixels only. The following is my
6091 implementation of reducing the image. (Keep in mind that I've had only basic
6094 (UNTESTED CODE ALERT!!!)
6106 SELCTION_IN_CONTEXT,
6110 ReducedImage *Reduce_The_Image(GDrawable *drawable,
6115 /* This function reduced the image down to the the selected preview size */
6116 /* The preview size is determine by LongerSize, i.e. the greater of the */
6117 /* two dimentions. Works for RGB images only! */
6118 gint RH, RW; /* Reduced height and reduced width */
6119 gint width, height; /* Width and Height of the area being reduced */
6120 gint bytes=drawable->bpp;
6121 ReducedImage *temp=(ReducedImage *)malloc(sizeof(ReducedImage));
6123 guchar *tempRGB, *src_row, *tempmask, *src_mask_row,R,G,B;
6124 gint i, j, whichcol, whichrow, x1, x2, y1, y2;
6125 GPixelRgn srcPR, srcMask;
6126 gint NoSelectionMade=TRUE; /* Assume that we're dealing with the entire */
6129 gimp_drawable_mask_bounds (drawable->id, &x1, &y1, &x2, &y2);
6132 /* If there's a SELECTION, we got its bounds!)
6134 if (width != drawable->width && height != drawable->height)
6135 NoSelectionMade=FALSE;
6136 /* Become aware of whether the user has made an active selection */
6137 /* This will become important later, when creating a reduced mask. */
6139 /* If we want to preview the entire image, overrule the above! */
6140 /* Of course, if no selection has been made, this does nothing! */
6141 if (Selection==ENTIRE_IMAGE) {
6145 y2=drawable->height;
6148 /* If we want to preview a selection with some surronding area we */
6149 /* have to expand it a little bit. Consider it a bit of a riddle. */
6150 if (Selection==SELECTION_IN_CONTEXT) {
6151 x1=MAX(0, x1-width/2.0);
6152 x2=MIN(drawable->width, x2+width/2.0);
6153 y1=MAX(0, y1-height/2.0);
6154 y2=MIN(drawable->height, y2+height/2.0);
6157 /* How we can determine the width and the height of the area being */
6162 /* The lines below determine which dimension is to be the longer */
6163 /* side. The idea borrowed from the supernova plug-in. I suspect I */
6164 /* could've thought of it myself, but the truth must be told. */
6165 /* Plagiarism stinks! */
6168 RH=(float) height * (float) LongerSize/ (float) width;
6172 RW=(float)width * (float) LongerSize/ (float) height;
6175 /* The intire image is stretched into a string! */
6176 tempRGB = (guchar *) malloc(RW*RH*bytes);
6177 tempmask = (guchar *) malloc(RW*RH);
6179 gimp_pixel_rgn_init (&srcPR, drawable, x1, y1, width, height, FALSE, FALSE);
6180 gimp_pixel_rgn_init (&srcMask, mask, x1, y1, width, height, FALSE, FALSE);
6182 /* Grab enough to save a row of image and a row of mask. */
6183 src_row = (guchar *) malloc (width*bytes);
6184 src_mask_row = (guchar *) malloc (width);
6186 for (i=0; i < RH; i++) {
6187 whichrow=(float)i*(float)height/(float)RH;
6188 gimp_pixel_rgn_get_row (&srcPR, src_row, x1, y1+whichrow, width);
6189 gimp_pixel_rgn_get_row (&srcMask, src_mask_row, x1, y1+whichrow, width);
6191 for (j=0; j < RW; j++) {
6192 whichcol=(float)j*(float)width/(float)RW;
6194 /* No selection made = each point is completely selected! */
6195 if (NoSelectionMade)
6196 tempmask[i*RW+j]=255;
6198 tempmask[i*RW+j]=src_mask_row[whichcol];
6200 /* Add the row to the one long string which now contains the image! */
6201 tempRGB[i*RW*bytes+j*bytes+0]=src_row[whichcol*bytes+0];
6202 tempRGB[i*RW*bytes+j*bytes+1]=src_row[whichcol*bytes+1];
6203 tempRGB[i*RW*bytes+j*bytes+2]=src_row[whichcol*bytes+2];
6205 /* Hold on to the alpha as well */
6207 tempRGB[i*RW*bytes+j*bytes+3]=src_row[whichcol*bytes+3];
6214 temp->mask=tempmask;
6218 The following is a preview function which used the same ReducedImage type!
6219 Note that it uses fakes transparancy (if one is present by means of
6220 fake_transparancy which is defined as follows:
6222 gint fake_transparency(gint i, gint j)
6224 if ( ((i%20)- 10) * ((j%20)- 10)>0 )
6230 Now here's the preview function:
6233 my_preview_render_function(GtkWidget *preview,
6237 gint Inten, bytes=drawable->bpp;
6240 gint RW=reduced->width;
6241 gint RH=reduced->height;
6242 guchar *row=malloc(bytes*RW);;
6245 for (i=0; i < RH; i++) {
6246 for (j=0; j < RW; j++) {
6248 row[j*3+0] = reduced->rgb[i*RW*bytes + j*bytes + 0];
6249 row[j*3+1] = reduced->rgb[i*RW*bytes + j*bytes + 1];
6250 row[j*3+2] = reduced->rgb[i*RW*bytes + j*bytes + 2];
6253 for (k=0; k<3; k++) {
6254 float transp=reduced->rgb[i*RW*bytes+j*bytes+3]/255.0;
6255 row[3*j+k]=transp*a[3*j+k]+(1-transp)*fake_transparency(i,j);
6258 gtk_preview_draw_row( GTK_PREVIEW(preview),row,0,i,RW);
6262 gtk_widget_draw(preview,NULL);
6268 guint gtk_preview_get_type (void);
6270 void gtk_preview_uninit (void);
6272 GtkWidget* gtk_preview_new (GtkPreviewType type);
6273 /* Described above */
6274 void gtk_preview_size (GtkPreview *preview,
6277 /* Allows you to resize an existing preview. */
6278 /* Apparantly there's a bug in GTK which makes */
6279 /* this process messy. A way to clean up a mess */
6280 /* is to manually resize the window containing */
6281 /* the preview after resizing the preview. */
6283 void gtk_preview_put (GtkPreview *preview,
6294 void gtk_preview_put_row (GtkPreview *preview,
6302 void gtk_preview_draw_row (GtkPreview *preview,
6307 /* Described in the text */
6309 void gtk_preview_set_expand (GtkPreview *preview,
6313 /* No clue for any of the below but */
6314 /* should be standard for most widgets */
6315 void gtk_preview_set_gamma (double gamma);
6316 void gtk_preview_set_color_cube (guint nred_shades,
6317 guint ngreen_shades,
6319 guint ngray_shades);
6320 void gtk_preview_set_install_cmap (gint install_cmap);
6321 void gtk_preview_set_reserved (gint nreserved);
6322 GdkVisual* gtk_preview_get_visual (void);
6323 GdkColormap* gtk_preview_get_cmap (void);
6324 GtkPreviewInfo* gtk_preview_get_info (void);
6330 <!-- ***************************************************************** -->
6331 <sect>The EventBox Widget<label id="sec_The_EventBox_Widget">
6332 <!-- ***************************************************************** -->
6334 Some gtk widgets don't have associated X windows, so they just draw on
6335 their parents. Because of this, they cannot recieve events
6336 and if they are incorrectly sized, they don't clip so you can get
6337 messy overwritting etc. If you require more from these widgets, the
6338 EventBox is for you.
6340 At first glance, the EventBox widget might appear to be totally
6341 useless. It draws nothing on the screen and responds to no
6342 events. However, it does serve a function - it provides an X window for
6343 its child widget. This is important as many GTK widgets do not
6344 have an associated X window. Not having an X window saves memory and
6345 improves performance, but also has some drawbacks. A widget without an
6346 X window cannot receive events, and does not perform any clipping on
6347 it's contents. Although the name <em/EventBox/ emphasizes the
6348 event-handling function, the widget can also be used for clipping.
6349 (And more ... see the example below.)
6351 To create a new EventBox widget, use:
6354 GtkWidget *gtk_event_box_new( void );
6357 A child widget can then be added to this EventBox:
6360 gtk_container_add( GTK_CONTAINER(event_box), widget );
6363 The following example demonstrates both uses of an EventBox - a label
6364 is created that is clipped to a small box, and set up so that a
6365 mouse-click on the label causes the program to exit.
6368 /* example-start eventbox/eventbox.c */
6370 #include <gtk/gtk.h>
6373 main (int argc, char *argv[])
6376 GtkWidget *event_box;
6379 gtk_init (&argc, &argv);
6381 window = gtk_window_new (GTK_WINDOW_TOPLEVEL);
6383 gtk_window_set_title (GTK_WINDOW (window), "Event Box");
6385 gtk_signal_connect (GTK_OBJECT (window), "destroy",
6386 GTK_SIGNAL_FUNC (gtk_exit), NULL);
6388 gtk_container_border_width (GTK_CONTAINER (window), 10);
6390 /* Create an EventBox and add it to our toplevel window */
6392 event_box = gtk_event_box_new ();
6393 gtk_container_add (GTK_CONTAINER(window), event_box);
6394 gtk_widget_show (event_box);
6396 /* Create a long label */
6398 label = gtk_label_new ("Click here to quit, quit, quit, quit, quit");
6399 gtk_container_add (GTK_CONTAINER (event_box), label);
6400 gtk_widget_show (label);
6402 /* Clip it short. */
6403 gtk_widget_set_usize (label, 110, 20);
6405 /* And bind an action to it */
6406 gtk_widget_set_events (event_box, GDK_BUTTON_PRESS_MASK);
6407 gtk_signal_connect (GTK_OBJECT(event_box), "button_press_event",
6408 GTK_SIGNAL_FUNC (gtk_exit), NULL);
6410 /* Yet one more thing you need an X window for ... */
6412 gtk_widget_realize (event_box);
6413 gdk_window_set_cursor (event_box->window, gdk_cursor_new (GDK_HAND1));
6415 gtk_widget_show (window);
6424 <!-- ***************************************************************** -->
6425 <sect>Setting Widget Attributes<label id="sec_setting_widget_attributes">
6426 <!-- ***************************************************************** -->
6428 This describes the functions used to operate on widgets. These can be used
6429 to set style, padding, size etc.
6431 (Maybe I should make a whole section on accelerators.)
6434 void gtk_widget_install_accelerator( GtkWidget *widget,
6435 GtkAcceleratorTable *table,
6440 void gtk_widget_remove_accelerator ( GtkWidget *widget,
6441 GtkAcceleratorTable *table,
6442 gchar *signal_name);
6444 void gtk_widget_activate( GtkWidget *widget );
6446 void gtk_widget_set_name( GtkWidget *widget,
6449 gchar *gtk_widget_get_name( GtkWidget *widget );
6451 void gtk_widget_set_sensitive( GtkWidget *widget,
6454 void gtk_widget_set_style( GtkWidget *widget,
6457 GtkStyle *gtk_widget_get_style( GtkWidget *widget );
6459 GtkStyle *gtk_widget_get_default_style( void );
6461 void gtk_widget_set_uposition( GtkWidget *widget,
6465 void gtk_widget_set_usize( GtkWidget *widget,
6469 void gtk_widget_grab_focus( GtkWidget *widget );
6471 void gtk_widget_show( GtkWidget *widget );
6473 void gtk_widget_hide( GtkWidget *widget );
6476 <!-- ***************************************************************** -->
6477 <sect>Timeouts, IO and Idle Functions<label id="sec_timeouts">
6478 <!-- ***************************************************************** -->
6480 <!-- ----------------------------------------------------------------- -->
6483 You may be wondering how you make GTK do useful work when in gtk_main.
6484 Well, you have several options. Using the following functions you can
6485 create a timeout function that will be called every "interval"
6489 gint gtk_timeout_add( guint32 interval,
6490 GtkFunction function,
6494 The first argument is the number of milliseconds between calls to your
6495 function. The second argument is the function you wish to have called, and
6496 the third, the data passed to this callback function. The return value is
6497 an integer "tag" which may be used to stop the timeout by calling:
6500 void gtk_timeout_remove( gint tag );
6503 You may also stop the timeout function by returning zero or FALSE from
6504 your callback function. Obviously this means if you want your function to
6505 continue to be called, it should return a non-zero value, ie TRUE.
6507 The declaration of your callback should look something like this:
6510 gint timeout_callback( gpointer data );
6513 <!-- ----------------------------------------------------------------- -->
6514 <sect1>Monitoring IO
6516 Another nifty feature of GTK, is the ability to have it check for data on a
6517 file descriptor for you (as returned by open(2) or socket(2)). This is
6518 especially useful for networking applications. The function:
6521 gint gdk_input_add( gint source,
6522 GdkInputCondition condition,
6523 GdkInputFunction function,
6527 Where the first argument is the file descriptor you wish to have watched,
6528 and the second specifies what you want GDK to look for. This may be one of:
6531 <item>GDK_INPUT_READ - Call your function when there is data ready for
6532 reading on your file descriptor.
6534 <item>GDK_INPUT_WRITE - Call your function when the file descriptor is
6538 As I'm sure you've figured out already, the third argument is the function
6539 you wish to have called when the above conditions are satisfied, and the
6540 fourth is the data to pass to this function.
6542 The return value is a tag that may be used to stop GDK from monitoring this
6543 file descriptor using the following function.
6546 void gdk_input_remove( gint tag );
6549 The callback function should be declared as:
6552 void input_callback( gpointer data,
6554 GdkInputCondition condition );
6557 <!-- ----------------------------------------------------------------- -->
6558 <sect1>Idle Functions
6560 <!-- Need to check on idle priorities - TRG -->
6561 What if you have a function you want called when nothing else is
6565 gint gtk_idle_add( GtkFunction function,
6569 This causes GTK to call the specified function whenever nothing else is
6573 void gtk_idle_remove( gint tag );
6576 I won't explain the meaning of the arguments as they follow very much like
6577 the ones above. The function pointed to by the first argument to
6578 gtk_idle_add will be called whenever the opportunity arises. As with the
6579 others, returning FALSE will stop the idle function from being called.
6581 <!-- ***************************************************************** -->
6582 <sect>Managing Selections
6583 <!-- ***************************************************************** -->
6585 <!-- ----------------------------------------------------------------- -->
6588 One type of interprocess communication supported by GTK is
6589 <em>selections</em>. A selection identifies a chunk of data, for
6590 instance, a portion of text, selected by the user in some fashion, for
6591 instance, by dragging with the mouse. Only one application on a
6592 display, (the <em>owner</em> can own a particular selection at one
6593 time, so when a selection is claimed by one application, the previous
6594 owner must indicate to the user that selection has been
6595 relinquished. Other applications can request the contents of a
6596 selection in different forms, called <em>targets</em>. There can be
6597 any number of selections, but most X applications only handle one, the
6598 <em>primary selection</em>.
6600 In most cases, it isn't necessary for a GTK application to deal with
6601 selections itself. The standard widgets, such as the Entry widget,
6602 already have the capability to claim the selection when appropriate
6603 (e.g., when the user drags over text), and to retrieve the contents of
6604 the selection owned by another widget, or another application (e.g.,
6605 when the user clicks the second mouse button). However, there may be
6606 cases in which you want to give other widgets the ability to supply
6607 the selection, or you wish to retrieve targets not supported by
6610 A fundamental concept needed to understand selection handling is that
6611 of the <em>atom</em>. An atom is an integer that uniquely identifies a
6612 string (on a certain display). Certain atoms are predefined by the X
6613 server, and in some cases there are constants in <tt>gtk.h</tt>
6614 corresponding to these atoms. For instance the constant
6615 <tt>GDK_PRIMARY_SELECTION</tt> corresponds to the string "PRIMARY".
6616 In other cases, you should use the functions
6617 <tt>gdk_atom_intern()</tt>, to get the atom corresponding to a string,
6618 and <tt>gdk_atom_name()</tt>, to get the name of an atom. Both
6619 selections and targets are identifed by atoms.
6621 <!-- ----------------------------------------------------------------- -->
6622 <sect1> Retrieving the selection
6624 Retrieving the selection is an asynchronous process. To start the
6628 gint gtk_selection_convert( GtkWidget *widget,
6634 This <em>converts</em> the selection into the form specified by
6635 <tt/target/. If at all possible, the time field should be the time
6636 from the event that triggered the selection. This helps make sure that
6637 events occur in the order that the user requested them. However, if it
6638 is not available (for instance, if the conversion was triggered by
6639 a "clicked" signal), then you can use the constant
6640 <tt>GDK_CURRENT_TIME</tt>.
6642 When the selection owner responds to the request, a
6643 "selection_received" signal is sent to your application. The handler
6644 for this signal receives a pointer to a <tt>GtkSelectionData</tt>
6645 structure, which is defined as:
6648 struct _GtkSelectionData
6659 <tt>selection</tt> and <tt>target</tt> are the values you gave in your
6660 <tt>gtk_selection_convert()</tt> call. <tt>type</tt> is an atom that
6661 identifies the type of data returned by the selection owner. Some
6662 possible values are "STRING", a string of latin-1 characters, "ATOM",
6663 a series of atoms, "INTEGER", an integer, etc. Most targets can only
6664 return one type. <tt/format/ gives the length of the units (for
6665 instance characters) in bits. Usually, you don't care about this when
6666 receiving data. <tt>data</tt> is a pointer to the returned data, and
6667 <tt>length</tt> gives the length of the returned data, in bytes. If
6668 <tt>length</tt> is negative, then an error occurred and the selection
6669 could not be retrieved. This might happen if no application owned the
6670 selection, or if you requested a target that the application didn't
6671 support. The buffer is actually guaranteed to be one byte longer than
6672 <tt>length</tt>; the extra byte will always be zero, so it isn't
6673 necessary to make a copy of strings just to null terminate them.
6675 In the following example, we retrieve the special target "TARGETS",
6676 which is a list of all targets into which the selection can be
6680 /* example-start selection/gettargets.c */
6682 #include <gtk/gtk.h>
6684 void selection_received (GtkWidget *widget,
6685 GtkSelectionData *selection_data,
6688 /* Signal handler invoked when user clicks on the "Get Targets" button */
6690 get_targets (GtkWidget *widget, gpointer data)
6692 static GdkAtom targets_atom = GDK_NONE;
6694 /* Get the atom corresonding to the string "TARGETS" */
6695 if (targets_atom == GDK_NONE)
6696 targets_atom = gdk_atom_intern ("TARGETS", FALSE);
6698 /* And request the "TARGETS" target for the primary selection */
6699 gtk_selection_convert (widget, GDK_SELECTION_PRIMARY, targets_atom,
6703 /* Signal handler called when the selections owner returns the data */
6705 selection_received (GtkWidget *widget, GtkSelectionData *selection_data,
6712 /* **** IMPORTANT **** Check to see if retrieval succeeded */
6713 if (selection_data->length < 0)
6715 g_print ("Selection retrieval failed\n");
6718 /* Make sure we got the data in the expected form */
6719 if (selection_data->type != GDK_SELECTION_TYPE_ATOM)
6721 g_print ("Selection \"TARGETS\" was not returned as atoms!\n");
6725 /* Print out the atoms we received */
6726 atoms = (GdkAtom *)selection_data->data;
6729 for (i=0; i<selection_data->length/sizeof(GdkAtom); i++)
6732 name = gdk_atom_name (atoms[i]);
6734 g_print ("%s\n",name);
6736 g_print ("(bad atom)\n");
6743 main (int argc, char *argv[])
6748 gtk_init (&argc, &argv);
6750 /* Create the toplevel window */
6752 window = gtk_window_new (GTK_WINDOW_TOPLEVEL);
6753 gtk_window_set_title (GTK_WINDOW (window), "Event Box");
6754 gtk_container_border_width (GTK_CONTAINER (window), 10);
6756 gtk_signal_connect (GTK_OBJECT (window), "destroy",
6757 GTK_SIGNAL_FUNC (gtk_exit), NULL);
6759 /* Create a button the user can click to get targets */
6761 button = gtk_button_new_with_label ("Get Targets");
6762 gtk_container_add (GTK_CONTAINER (window), button);
6764 gtk_signal_connect (GTK_OBJECT(button), "clicked",
6765 GTK_SIGNAL_FUNC (get_targets), NULL);
6766 gtk_signal_connect (GTK_OBJECT(button), "selection_received",
6767 GTK_SIGNAL_FUNC (selection_received), NULL);
6769 gtk_widget_show (button);
6770 gtk_widget_show (window);
6779 <!-- ----------------------------------------------------------------- -->
6780 <sect1> Supplying the selection
6782 Supplying the selection is a bit more complicated. You must register
6783 handlers that will be called when your selection is requested. For
6784 each selection/target pair you will handle, you make a call to:
6787 void gtk_selection_add_handler( GtkWidget *widget,
6790 GtkSelectionFunction function,
6791 GtkRemoveFunction remove_func,
6795 <tt/widget/, <tt/selection/, and <tt/target/ identify the requests
6796 this handler will manage. <tt/remove_func/, if not
6797 NULL, will be called when the signal handler is removed. This is
6798 useful, for instance, for interpreted languages which need to
6799 keep track of a reference count for <tt/data/.
6801 The callback function has the signature:
6804 typedef void (*GtkSelectionFunction)( GtkWidget *widget,
6805 GtkSelectionData *selection_data,
6810 The GtkSelectionData is the same as above, but this time, we're
6811 responsible for filling in the fields <tt/type/, <tt/format/,
6812 <tt/data/, and <tt/length/. (The <tt/format/ field is actually
6813 important here - the X server uses it to figure out whether the data
6814 needs to be byte-swapped or not. Usually it will be 8 - <em/i.e./ a
6815 character - or 32 - <em/i.e./ a. integer.) This is done by calling the
6819 void gtk_selection_data_set( GtkSelectionData *selection_data,
6826 This function takes care of properly making a copy of the data so that
6827 you don't have to worry about keeping it around. (You should not fill
6828 in the fields of the GtkSelectionData structure by hand.)
6830 When prompted by the user, you claim ownership of the selection by
6834 gint gtk_selection_owner_set( GtkWidget *widget,
6839 If another application claims ownership of the selection, you will
6840 receive a "selection_clear_event".
6842 As an example of supplying the selection, the following program adds
6843 selection functionality to a toggle button. When the toggle button is
6844 depressed, the program claims the primary selection. The only target
6845 supported (aside from certain targets like "TARGETS" supplied by GTK
6846 itself), is the "STRING" target. When this target is requested, a
6847 string representation of the time is returned.
6850 /* example-start selection/setselection.c */
6852 #include <gtk/gtk.h>
6855 /* Callback when the user toggles the selection */
6857 selection_toggled (GtkWidget *widget, gint *have_selection)
6859 if (GTK_TOGGLE_BUTTON(widget)->active)
6861 *have_selection = gtk_selection_owner_set (widget,
6862 GDK_SELECTION_PRIMARY,
6864 /* if claiming the selection failed, we return the button to
6866 if (!*have_selection)
6867 gtk_toggle_button_set_state (GTK_TOGGLE_BUTTON(widget), FALSE);
6871 if (*have_selection)
6873 /* Before clearing the selection by setting the owner to NULL,
6874 we check if we are the actual owner */
6875 if (gdk_selection_owner_get (GDK_SELECTION_PRIMARY) == widget->window)
6876 gtk_selection_owner_set (NULL, GDK_SELECTION_PRIMARY,
6878 *have_selection = FALSE;
6883 /* Called when another application claims the selection */
6885 selection_clear (GtkWidget *widget, GdkEventSelection *event,
6886 gint *have_selection)
6888 *have_selection = FALSE;
6889 gtk_toggle_button_set_state (GTK_TOGGLE_BUTTON(widget), FALSE);
6894 /* Supplies the current time as the selection. */
6896 selection_handle (GtkWidget *widget,
6897 GtkSelectionData *selection_data,
6901 time_t current_time;
6903 current_time = time (NULL);
6904 timestr = asctime (localtime(&current_time));
6905 /* When we return a single string, it should not be null terminated.
6906 That will be done for us */
6908 gtk_selection_data_set (selection_data, GDK_SELECTION_TYPE_STRING,
6909 8, timestr, strlen(timestr));
6913 main (int argc, char *argv[])
6917 GtkWidget *selection_button;
6919 static int have_selection = FALSE;
6921 gtk_init (&argc, &argv);
6923 /* Create the toplevel window */
6925 window = gtk_window_new (GTK_WINDOW_TOPLEVEL);
6926 gtk_window_set_title (GTK_WINDOW (window), "Event Box");
6927 gtk_container_border_width (GTK_CONTAINER (window), 10);
6929 gtk_signal_connect (GTK_OBJECT (window), "destroy",
6930 GTK_SIGNAL_FUNC (gtk_exit), NULL);
6932 /* Create a toggle button to act as the selection */
6934 selection_button = gtk_toggle_button_new_with_label ("Claim Selection");
6935 gtk_container_add (GTK_CONTAINER (window), selection_button);
6936 gtk_widget_show (selection_button);
6938 gtk_signal_connect (GTK_OBJECT(selection_button), "toggled",
6939 GTK_SIGNAL_FUNC (selection_toggled), &have_selection);
6940 gtk_signal_connect (GTK_OBJECT(selection_button), "selection_clear_event",
6941 GTK_SIGNAL_FUNC (selection_clear), &have_selection);
6943 gtk_selection_add_handler (selection_button, GDK_SELECTION_PRIMARY,
6944 GDK_SELECTION_TYPE_STRING,
6945 selection_handle, NULL);
6947 gtk_widget_show (selection_button);
6948 gtk_widget_show (window);
6958 <!-- ***************************************************************** -->
6959 <sect>glib<label id="sec_glib">
6960 <!-- ***************************************************************** -->
6962 glib provides many useful functions and definitions available for use
6963 when creating GDK and GTK applications. I will list them all here with
6964 a brief explanation. Many are duplicates of standard libc functions so
6965 I won't go into detail on those. This is mostly to be used as a reference,
6966 so you know what is available for use.
6968 <!-- ----------------------------------------------------------------- -->
6971 Definitions for the extremes of many of the standard types are:
6986 Also, the following typedefs. The ones left unspecified are dynamically set
6987 depending on the architecture. Remember to avoid counting on the size of a
6988 pointer if you want to be portable! Eg, a pointer on an Alpha is 8 bytes, but 4
6998 unsigned char guchar;
6999 unsigned short gushort;
7000 unsigned long gulong;
7005 long double gldouble;
7017 <!-- ----------------------------------------------------------------- -->
7018 <sect1>Doubly Linked Lists
7020 The following functions are used to create, manage, and destroy doubly
7021 linked lists. I assume you know what linked lists are, as it is beyond the scope
7022 of this document to explain them. Of course, it's not required that you
7023 know these for general use of GTK, but they are nice to know.
7026 GList *g_list_alloc( void );
7028 void g_list_free( GList *list );
7030 void g_list_free_1( GList *list );
7032 GList *g_list_append( GList *list,
7035 GList *g_list_prepend( GList *list,
7038 GList *g_list_insert( GList *list,
7042 GList *g_list_remove( GList *list,
7045 GList *g_list_remove_link( GList *list,
7048 GList *g_list_reverse( GList *list );
7050 GList *g_list_nth( GList *list,
7053 GList *g_list_find( GList *list,
7056 GList *g_list_last( GList *list );
7058 GList *g_list_first( GList *list );
7060 gint g_list_length( GList *list );
7062 void g_list_foreach( GList *list,
7064 gpointer user_data );
7067 <!-- ----------------------------------------------------------------- -->
7068 <sect1>Singly Linked Lists
7070 Many of the above functions for singly linked lists are identical to the
7071 above. Here is a complete list:
7073 GSList *g_slist_alloc( void );
7075 void g_slist_free( GSList *list );
7077 void g_slist_free_1( GSList *list );
7079 GSList *g_slist_append( GSList *list,
7082 GSList *g_slist_prepend( GSList *list,
7085 GSList *g_slist_insert( GSList *list,
7089 GSList *g_slist_remove( GSList *list,
7092 GSList *g_slist_remove_link( GSList *list,
7095 GSList *g_slist_reverse( GSList *list );
7097 GSList *g_slist_nth( GSList *list,
7100 GSList *g_slist_find( GSList *list,
7103 GSList *g_slist_last( GSList *list );
7105 gint g_slist_length( GSList *list );
7107 void g_slist_foreach( GSList *list,
7109 gpointer user_data );
7113 <!-- ----------------------------------------------------------------- -->
7114 <sect1>Memory Management
7117 gpointer g_malloc( gulong size );
7120 This is a replacement for malloc(). You do not need to check the return
7121 vaule as it is done for you in this function.
7124 gpointer g_malloc0( gulong size );
7127 Same as above, but zeroes the memory before returning a pointer to it.
7130 gpointer g_realloc( gpointer mem,
7134 Relocates "size" bytes of memory starting at "mem". Obviously, the
7135 memory should have been previously allocated.
7138 void g_free( gpointer mem );
7141 Frees memory. Easy one.
7144 void g_mem_profile( void );
7147 Dumps a profile of used memory, but requries that you add #define
7148 MEM_PROFILE to the top of glib/gmem.c and re-make and make install.
7151 void g_mem_check( gpointer mem );
7154 Checks that a memory location is valid. Requires you add #define
7155 MEM_CHECK to the top of gmem.c and re-make and make install.
7157 <!-- ----------------------------------------------------------------- -->
7163 GTimer *g_timer_new( void );
7165 void g_timer_destroy( GTimer *timer );
7167 void g_timer_start( GTimer *timer );
7169 void g_timer_stop( GTimer *timer );
7171 void g_timer_reset( GTimer *timer );
7173 gdouble g_timer_elapsed( GTimer *timer,
7174 gulong *microseconds );
7177 <!-- ----------------------------------------------------------------- -->
7178 <sect1>String Handling
7180 A whole mess of string handling functions. They all look very interesting, and
7181 probably better for many purposes than the standard C string functions, but
7182 require documentation.
7185 GString *g_string_new( gchar *init );
7187 void g_string_free( GString *string,
7188 gint free_segment );
7190 GString *g_string_assign( GString *lval,
7193 GString *g_string_truncate( GString *string,
7196 GString *g_string_append( GString *string,
7199 GString *g_string_append_c( GString *string,
7202 GString *g_string_prepend( GString *string,
7205 GString *g_string_prepend_c( GString *string,
7208 void g_string_sprintf( GString *string,
7212 void g_string_sprintfa ( GString *string,
7217 <!-- ----------------------------------------------------------------- -->
7218 <sect1>Utility and Error Functions
7221 gchar *g_strdup( const gchar *str );
7224 Replacement strdup function. Copies the original strings contents to
7225 newly allocated memory, and returns a pointer to it.
7228 gchar *g_strerror( gint errnum );
7231 I recommend using this for all error messages. It's much nicer, and more
7232 portable than perror() or others. The output is usually of the form:
7235 program name:function that failed:file or further description:strerror
7238 Here's an example of one such call used in our hello_world program:
7241 g_print("hello_world:open:%s:%s\n", filename, g_strerror(errno));
7245 void g_error( gchar *format, ... );
7248 Prints an error message. The format is just like printf, but it
7249 prepends "** ERROR **: " to your message, and exits the program.
7250 Use only for fatal errors.
7253 void g_warning( gchar *format, ... );
7256 Same as above, but prepends "** WARNING **: ", and does not exit the
7260 void g_message( gchar *format, ... );
7263 Prints "message: " prepended to the string you pass in.
7266 void g_print( gchar *format, ... );
7269 Replacement for printf().
7271 And our last function:
7274 gchar *g_strsignal( gint signum );
7277 Prints out the name of the Unix system signal given the signal number.
7278 Useful in generic signal handling functions.
7280 All of the above are more or less just stolen from glib.h. If anyone cares
7281 to document any function, just send me an email!
7283 <!-- ***************************************************************** -->
7284 <sect>GTK's rc Files
7285 <!-- ***************************************************************** -->
7287 GTK has it's own way of dealing with application defaults, by using rc
7288 files. These can be used to set the colors of just about any widget, and
7289 can also be used to tile pixmaps onto the background of some widgets.
7291 <!-- ----------------------------------------------------------------- -->
7292 <sect1>Functions For rc Files
7294 When your application starts, you should include a call to:
7297 void gtk_rc_parse( char *filename );
7300 Passing in the filename of your rc file. This will cause GTK to parse this
7301 file, and use the style settings for the widget types defined there.
7303 If you wish to have a special set of widgets that can take on a different
7304 style from others, or any other logical division of widgets, use a call to:
7307 void gtk_widget_set_name( GtkWidget *widget,
7311 Passing your newly created widget as the first argument, and the name
7312 you wish to give it as the second. This will allow you to change the
7313 attributes of this widget by name through the rc file.
7315 If we use a call something like this:
7318 button = gtk_button_new_with_label ("Special Button");
7319 gtk_widget_set_name (button, "special button");
7322 Then this button is given the name "special button" and may be addressed by
7323 name in the rc file as "special button.GtkButton". [<--- Verify ME!]
7325 The example rc file below, sets the properties of the main window, and lets
7326 all children of that main window inherit the style described by the "main
7327 button" style. The code used in the application is:
7330 window = gtk_window_new (GTK_WINDOW_TOPLEVEL);
7331 gtk_widget_set_name (window, "main window");
7334 And then the style is defined in the rc file using:
7337 widget "main window.*GtkButton*" style "main_button"
7340 Which sets all the GtkButton widgets in the "main window" to the
7341 "main_buttons" style as defined in the rc file.
7343 As you can see, this is a fairly powerful and flexible system. Use your
7344 imagination as to how best to take advantage of this.
7346 <!-- ----------------------------------------------------------------- -->
7347 <sect1>GTK's rc File Format
7349 The format of the GTK file is illustrated in the example below. This is
7350 the testgtkrc file from the GTK distribution, but I've added a
7351 few comments and things. You may wish to include this explanation
7352 your application to allow the user to fine tune his application.
7354 There are several directives to change the attributes of a widget.
7357 <item>fg - Sets the foreground color of a widget.
7358 <item>bg - Sets the background color of a widget.
7359 <item>bg_pixmap - Sets the background of a widget to a tiled pixmap.
7360 <item>font - Sets the font to be used with the given widget.
7363 In addition to this, there are several states a widget can be in, and you
7364 can set different colors, pixmaps and fonts for each state. These states are:
7367 <item>NORMAL - The normal state of a widget, without the mouse over top of
7368 it, and not being pressed etc.
7369 <item>PRELIGHT - When the mouse is over top of the widget, colors defined
7370 using this state will be in effect.
7371 <item>ACTIVE - When the widget is pressed or clicked it will be active, and
7372 the attributes assigned by this tag will be in effect.
7373 <item>INSENSITIVE - When a widget is set insensitive, and cannot be
7374 activated, it will take these attributes.
7375 <item>SELECTED - When an object is selected, it takes these attributes.
7378 When using the "fg" and "bg" keywords to set the colors of widgets, the
7382 fg[<STATE>] = { Red, Green, Blue }
7385 Where STATE is one of the above states (PRELIGHT, ACTIVE etc), and the Red,
7386 Green and Blue are values in the range of 0 - 1.0, { 1.0, 1.0, 1.0 } being
7387 white. They must be in float form, or they will register as 0, so a straight
7388 "1" will not work, it must be "1.0". A straight "0" is fine because it
7389 doesn't matter if it's not recognized. Unrecognized values are set to 0.
7391 bg_pixmap is very similar to the above, except the colors are replaced by a
7394 pixmap_path is a list of paths seperated by ":"'s. These paths will be
7395 searched for any pixmap you specify.
7397 The font directive is simply:
7399 font = "<font name>"
7402 Where the only hard part is figuring out the font string. Using xfontsel or
7403 similar utility should help.
7405 The "widget_class" sets the style of a class of widgets. These classes are
7406 listed in the widget overview on the class hierarchy.
7408 The "widget" directive sets a specificaly named set of widgets to a
7409 given style, overriding any style set for the given widget class.
7410 These widgets are registered inside the application using the
7411 gtk_widget_set_name() call. This allows you to specify the attributes of a
7412 widget on a per widget basis, rather than setting the attributes of an
7413 entire widget class. I urge you to document any of these special widgets so
7414 users may customize them.
7416 When the keyword <tt>parent</> is used as an attribute, the widget will take on
7417 the attributes of it's parent in the application.
7419 When defining a style, you may assign the attributes of a previously defined
7420 style to this new one.
7423 style "main_button" = "button"
7425 font = "-adobe-helvetica-medium-r-normal--*-100-*-*-*-*-*-*"
7426 bg[PRELIGHT] = { 0.75, 0, 0 }
7430 This example takes the "button" style, and creates a new "main_button" style
7431 simply by changing the font and prelight background color of the "button"
7434 Of course, many of these attributes don't apply to all widgets. It's a
7435 simple matter of common sense really. Anything that could apply, should.
7437 <!-- ----------------------------------------------------------------- -->
7438 <sect1>Example rc file
7442 # pixmap_path "<dir 1>:<dir 2>:<dir 3>:..."
7444 pixmap_path "/usr/include/X11R6/pixmaps:/home/imain/pixmaps"
7446 # style <name> [= <name>]
7451 # widget <widget_set> style <style_name>
7452 # widget_class <widget_class_set> style <style_name>
7455 # Here is a list of all the possible states. Note that some do not apply to
7458 # NORMAL - The normal state of a widget, without the mouse over top of
7459 # it, and not being pressed etc.
7461 # PRELIGHT - When the mouse is over top of the widget, colors defined
7462 # using this state will be in effect.
7464 # ACTIVE - When the widget is pressed or clicked it will be active, and
7465 # the attributes assigned by this tag will be in effect.
7467 # INSENSITIVE - When a widget is set insensitive, and cannot be
7468 # activated, it will take these attributes.
7470 # SELECTED - When an object is selected, it takes these attributes.
7472 # Given these states, we can set the attributes of the widgets in each of
7473 # these states using the following directives.
7475 # fg - Sets the foreground color of a widget.
7476 # fg - Sets the background color of a widget.
7477 # bg_pixmap - Sets the background of a widget to a tiled pixmap.
7478 # font - Sets the font to be used with the given widget.
7481 # This sets a style called "button". The name is not really important, as
7482 # it is assigned to the actual widgets at the bottom of the file.
7486 #This sets the padding around the window to the pixmap specified.
7487 #bg_pixmap[<STATE>] = "<pixmap filename>"
7488 bg_pixmap[NORMAL] = "warning.xpm"
7493 #Sets the foreground color (font color) to red when in the "NORMAL"
7496 fg[NORMAL] = { 1.0, 0, 0 }
7498 #Sets the background pixmap of this widget to that of it's parent.
7499 bg_pixmap[NORMAL] = "<parent>"
7504 # This shows all the possible states for a button. The only one that
7505 # doesn't apply is the SELECTED state.
7507 fg[PRELIGHT] = { 0, 1.0, 1.0 }
7508 bg[PRELIGHT] = { 0, 0, 1.0 }
7509 bg[ACTIVE] = { 1.0, 0, 0 }
7510 fg[ACTIVE] = { 0, 1.0, 0 }
7511 bg[NORMAL] = { 1.0, 1.0, 0 }
7512 fg[NORMAL] = { .99, 0, .99 }
7513 bg[INSENSITIVE] = { 1.0, 1.0, 1.0 }
7514 fg[INSENSITIVE] = { 1.0, 0, 1.0 }
7517 # In this example, we inherit the attributes of the "button" style and then
7518 # override the font and background color when prelit to create a new
7519 # "main_button" style.
7521 style "main_button" = "button"
7523 font = "-adobe-helvetica-medium-r-normal--*-100-*-*-*-*-*-*"
7524 bg[PRELIGHT] = { 0.75, 0, 0 }
7527 style "toggle_button" = "button"
7529 fg[NORMAL] = { 1.0, 0, 0 }
7530 fg[ACTIVE] = { 1.0, 0, 0 }
7532 # This sets the background pixmap of the toggle_button to that of it's
7533 # parent widget (as defined in the application).
7534 bg_pixmap[NORMAL] = "<parent>"
7539 bg_pixmap[NORMAL] = "marble.xpm"
7540 fg[NORMAL] = { 1.0, 1.0, 1.0 }
7545 font = "-adobe-helvetica-medium-r-normal--*-80-*-*-*-*-*-*"
7548 # pixmap_path "~/.pixmaps"
7550 # These set the widget types to use the styles defined above.
7551 # The widget types are listed in the class hierarchy, but could probably be
7552 # just listed in this document for the users reference.
7554 widget_class "GtkWindow" style "window"
7555 widget_class "GtkDialog" style "window"
7556 widget_class "GtkFileSelection" style "window"
7557 widget_class "*Gtk*Scale" style "scale"
7558 widget_class "*GtkCheckButton*" style "toggle_button"
7559 widget_class "*GtkRadioButton*" style "toggle_button"
7560 widget_class "*GtkButton*" style "button"
7561 widget_class "*Ruler" style "ruler"
7562 widget_class "*GtkText" style "text"
7564 # This sets all the buttons that are children of the "main window" to
7565 # the main_buton style. These must be documented to be taken advantage of.
7566 widget "main window.*GtkButton*" style "main_button"
7569 <!-- ***************************************************************** -->
7570 <sect>Writing Your Own Widgets
7571 <!-- ***************************************************************** -->
7573 <!-- ----------------------------------------------------------------- -->
7576 Although the GTK distribution comes with many types of widgets that
7577 should cover most basic needs, there may come a time when you need to
7578 create your own new widget type. Since GTK uses widget inheretence
7579 extensively, and there is already a widget that is close to what you want,
7580 it is often possible to make a useful new widget type in
7581 just a few lines of code. But before starting work on a new widget, check
7582 around first to make sure that someone has not already written
7583 it. This will prevent duplication of effort and keep the number of
7584 GTK widgets out there to a minimum, which will help keep both the code
7585 and the interface of different applications consistent. As a flip side
7586 to this, once you finish your widget, announce it to the world so
7587 other people can benefit. The best place to do this is probably the
7590 Complete sources for the example widgets are available at the place you
7591 got this tutorial, or from:
7593 <htmlurl url="http://www.msc.cornell.edu/~otaylor/gtk-gimp/tutorial"
7594 name="http://www.msc.cornell.edu/~otaylor/gtk-gimp/tutorial">
7597 <!-- ----------------------------------------------------------------- -->
7598 <sect1> The Anatomy Of A Widget
7600 In order to create a new widget, it is important to have an
7601 understanding of how GTK objects work. This section is just meant as a
7602 brief overview. See the reference documentation for the details.
7604 GTK widgets are implemented in an object oriented fashion. However,
7605 they are implemented in standard C. This greatly improves portability
7606 and stability over using current generation C++ compilers; however,
7607 it does mean that the widget writer has to pay attention to some of
7608 the implementation details. The information common to all instances of
7609 one class of widgets (e.g., to all Button widgets) is stored in the
7610 <em>class structure</em>. There is only one copy of this in
7611 which is stored information about the class's signals
7612 (which act like virtual functions in C). To support inheritance, the
7613 first field in the class structure must be a copy of the parent's
7614 class structure. The declaration of the class structure of GtkButtton
7618 struct _GtkButtonClass
7620 GtkContainerClass parent_class;
7622 void (* pressed) (GtkButton *button);
7623 void (* released) (GtkButton *button);
7624 void (* clicked) (GtkButton *button);
7625 void (* enter) (GtkButton *button);
7626 void (* leave) (GtkButton *button);
7630 When a button is treated as a container (for instance, when it is
7631 resized), its class structure can be cast to GtkContainerClass, and
7632 the relevant fields used to handle the signals.
7634 There is also a structure for each widget that is created on a
7635 per-instance basis. This structure has fields to store information that
7636 is different for each instance of the widget. We'll call this
7637 structure the <em>object structure</em>. For the Button class, it looks
7643 GtkContainer container;
7647 guint in_button : 1;
7648 guint button_down : 1;
7652 Note that, similar to the class structure, the first field is the
7653 object structure of the parent class, so that this structure can be
7654 cast to the parent class's object structure as needed.
7656 <!-- ----------------------------------------------------------------- -->
7657 <sect1> Creating a Composite widget
7659 <!-- ----------------------------------------------------------------- -->
7660 <sect2> Introduction
7662 One type of widget that you may be interested in creating is a
7663 widget that is merely an aggregate of other GTK widgets. This type of
7664 widget does nothing that couldn't be done without creating new
7665 widgets, but provides a convenient way of packaging user interface
7666 elements for reuse. The FileSelection and ColorSelection widgets in
7667 the standard distribution are examples of this type of widget.
7669 The example widget that we'll create in this section is the Tictactoe
7670 widget, a 3x3 array of toggle buttons which triggers a signal when all
7671 three buttons in a row, column, or on one of the diagonals are
7674 <!-- ----------------------------------------------------------------- -->
7675 <sect2> Choosing a parent class
7677 The parent class for a composite widget is typically the container
7678 class that holds all of the elements of the composite widget. For
7679 example, the parent class of the FileSelection widget is the
7680 Dialog class. Since our buttons will be arranged in a table, it
7681 might seem natural to make our parent class the GtkTable
7682 class. Unfortunately, this turns out not to work. The creation of a
7683 widget is divided among two functions - a <tt/WIDGETNAME_new()/
7684 function that the user calls, and a <tt/WIDGETNAME_init()/ function
7685 which does the basic work of initializing the widget which is
7686 independent of the arguments passed to the <tt/_new()/
7687 function. Descendent widgets only call the <tt/_init/ function of
7688 their parent widget. But this division of labor doesn't work well for
7689 tables, which when created, need to know the number of rows and
7690 columns in the table. Unless we want to duplicate most of the
7691 functionality of <tt/gtk_table_new()/ in our Tictactoe widget, we had
7692 best avoid deriving it from GtkTable. For that reason, we derive it
7693 from GtkVBox instead, and stick our table inside the VBox.
7695 <!-- ----------------------------------------------------------------- -->
7696 <sect2> The header file
7698 Each widget class has a header file which declares the object and
7699 class structures for that widget, along with public functions.
7700 A couple of features are worth pointing out. To prevent duplicate
7701 definitions, we wrap the entire header file in:
7704 #ifndef __TICTACTOE_H__
7705 #define __TICTACTOE_H__
7709 #endif /* __TICTACTOE_H__ */
7712 And to keep C++ programs that include the header file happy, in:
7717 #endif /* __cplusplus */
7723 #endif /* __cplusplus */
7726 Along with the functions and structures, we declare three standard
7727 macros in our header file, <tt/TICTACTOE(obj)/,
7728 <tt/TICTACTOE_CLASS(klass)/, and <tt/IS_TICTACTOE(obj)/, which cast a
7729 pointer into a pointer to the object or class structure, and check
7730 if an object is a Tictactoe widget respectively.
7732 Here is the complete header file:
7737 #ifndef __TICTACTOE_H__
7738 #define __TICTACTOE_H__
7740 #include <gdk/gdk.h>
7741 #include <gtk/gtkvbox.h>
7745 #endif /* __cplusplus */
7747 #define TICTACTOE(obj) GTK_CHECK_CAST (obj, tictactoe_get_type (), Tictactoe)
7748 #define TICTACTOE_CLASS(klass) GTK_CHECK_CLASS_CAST (klass, tictactoe_get_type (), TictactoeClass)
7749 #define IS_TICTACTOE(obj) GTK_CHECK_TYPE (obj, tictactoe_get_type ())
7752 typedef struct _Tictactoe Tictactoe;
7753 typedef struct _TictactoeClass TictactoeClass;
7759 GtkWidget *buttons[3][3];
7762 struct _TictactoeClass
7764 GtkVBoxClass parent_class;
7766 void (* tictactoe) (Tictactoe *ttt);
7769 guint tictactoe_get_type (void);
7770 GtkWidget* tictactoe_new (void);
7771 void tictactoe_clear (Tictactoe *ttt);
7775 #endif /* __cplusplus */
7777 #endif /* __TICTACTOE_H__ */
7781 <!-- ----------------------------------------------------------------- -->
7782 <sect2> The <tt/_get_type()/ function.
7784 We now continue on to the implementation of our widget. A core
7785 function for every widget is the function
7786 <tt/WIDGETNAME_get_type()/. This function, when first called, tells
7787 GTK about the widget class, and gets an ID that uniquely identifies
7788 the widget class. Upon subsequent calls, it just returns the ID.
7792 tictactoe_get_type ()
7794 static guint ttt_type = 0;
7798 GtkTypeInfo ttt_info =
7802 sizeof (TictactoeClass),
7803 (GtkClassInitFunc) tictactoe_class_init,
7804 (GtkObjectInitFunc) tictactoe_init,
7805 (GtkArgSetFunc) NULL,
7806 (GtkArgGetFunc) NULL
7809 ttt_type = gtk_type_unique (gtk_vbox_get_type (), &ttt_info);
7816 The GtkTypeInfo structure has the following definition:
7824 GtkClassInitFunc class_init_func;
7825 GtkObjectInitFunc object_init_func;
7826 GtkArgSetFunc arg_set_func;
7827 GtkArgGetFunc arg_get_func;
7831 The fields of this structure are pretty self-explanatory. We'll ignore
7832 the <tt/arg_set_func/ and <tt/arg_get_func/ fields here: they have an important,
7834 unimplemented, role in allowing widget options to be conveniently set
7835 from interpreted languages. Once GTK has a correctly filled in copy of
7836 this structure, it knows how to create objects of a particular widget
7839 <!-- ----------------------------------------------------------------- -->
7840 <sect2> The <tt/_class_init()/ function
7842 The <tt/WIDGETNAME_class_init()/ function initializes the fields of
7843 the widget's class structure, and sets up any signals for the
7844 class. For our Tictactoe widget it looks like:
7853 static gint tictactoe_signals[LAST_SIGNAL] = { 0 };
7856 tictactoe_class_init (TictactoeClass *class)
7858 GtkObjectClass *object_class;
7860 object_class = (GtkObjectClass*) class;
7862 tictactoe_signals[TICTACTOE_SIGNAL] = gtk_signal_new ("tictactoe",
7865 GTK_SIGNAL_OFFSET (TictactoeClass, tictactoe),
7866 gtk_signal_default_marshaller, GTK_TYPE_NONE, 0);
7869 gtk_object_class_add_signals (object_class, tictactoe_signals, LAST_SIGNAL);
7871 class->tictactoe = NULL;
7875 Our widget has just one signal, the <tt/tictactoe/ signal that is
7876 invoked when a row, column, or diagonal is completely filled in. Not
7877 every composite widget needs signals, so if you are reading this for
7878 the first time, you may want to skip to the next section now, as
7879 things are going to get a bit complicated.
7884 gint gtk_signal_new( const gchar *name,
7885 GtkSignalRunType run_type,
7886 GtkType object_type,
7887 gint function_offset,
7888 GtkSignalMarshaller marshaller,
7894 Creates a new signal. The parameters are:
7897 <item> <tt/name/: The name of the signal.
7898 <item> <tt/run_type/: Whether the default handler runs before or after
7899 user handlers. Usually this will be <tt/GTK_RUN_FIRST/, or <tt/GTK_RUN_LAST/,
7900 although there are other possibilities.
7901 <item> <tt/object_type/: The ID of the object that this signal applies
7902 to. (It will also apply to that objects descendents)
7903 <item> <tt/function_offset/: The offset within the class structure of
7904 a pointer to the default handler.
7905 <item> <tt/marshaller/: A function that is used to invoke the signal
7906 handler. For signal handlers that have no arguments other than the
7907 object that emitted the signal and user data, we can use the
7908 pre-supplied marshaller function <tt/gtk_signal_default_marshaller/.
7909 <item> <tt/return_val/: The type of the return val.
7910 <item> <tt/nparams/: The number of parameters of the signal handler
7911 (other than the two default ones mentioned above)
7912 <item> <tt/.../: The types of the parameters.
7915 When specifying types, the <tt/GtkType/ enumeration is used:
7940 /* it'd be great if the next two could be removed eventually */
7942 GTK_TYPE_C_CALLBACK,
7946 } GtkFundamentalType;
7949 <tt/gtk_signal_new()/ returns a unique integer identifier for the
7950 signal, that we store in the <tt/tictactoe_signals/ array, which we
7951 index using an enumeration. (Conventionally, the enumeration elements
7952 are the signal name, uppercased, but here there would be a conflict
7953 with the <tt/TICTACTOE()/ macro, so we called it <tt/TICTACTOE_SIGNAL/
7956 After creating our signals, we need to tell GTK to associate our
7957 signals with the Tictactoe class. We do that by calling
7958 <tt/gtk_object_class_add_signals()/. We then set the pointer which
7959 points to the default handler for the ``tictactoe'' signal to NULL,
7960 indicating that there is no default action.
7962 <!-- ----------------------------------------------------------------- -->
7963 <sect2> The <tt/_init()/ function.
7965 Each widget class also needs a function to initialize the object
7966 structure. Usually, this function has the fairly limited role of
7967 setting the fields of the structure to default values. For composite
7968 widgets, however, this function also creates the component widgets.
7972 tictactoe_init (Tictactoe *ttt)
7977 table = gtk_table_new (3, 3, TRUE);
7978 gtk_container_add (GTK_CONTAINER(ttt), table);
7979 gtk_widget_show (table);
7984 ttt->buttons[i][j] = gtk_toggle_button_new ();
7985 gtk_table_attach_defaults (GTK_TABLE(table), ttt->buttons[i][j],
7987 gtk_signal_connect (GTK_OBJECT (ttt->buttons[i][j]), "toggled",
7988 GTK_SIGNAL_FUNC (tictactoe_toggle), ttt);
7989 gtk_widget_set_usize (ttt->buttons[i][j], 20, 20);
7990 gtk_widget_show (ttt->buttons[i][j]);
7995 <!-- ----------------------------------------------------------------- -->
7996 <sect2> And the rest...
7998 There is one more function that every widget (except for base widget
7999 types like GtkBin that cannot be instantiated) needs to have - the
8000 function that the user calls to create an object of that type. This is
8001 conventionally called <tt/WIDGETNAME_new()/. In some
8002 widgets, though not for the Tictactoe widgets, this function takes
8003 arguments, and does some setup based on the arguments. The other two
8004 functions are specific to the Tictactoe widget.
8006 <tt/tictactoe_clear()/ is a public function that resets all the
8007 buttons in the widget to the up position. Note the use of
8008 <tt/gtk_signal_handler_block_by_data()/ to keep our signal handler for
8009 button toggles from being triggered unnecessarily.
8011 <tt/tictactoe_toggle()/ is the signal handler that is invoked when the
8012 user clicks on a button. It checks to see if there are any winning
8013 combinations that involve the toggled button, and if so, emits
8014 the "tictactoe" signal.
8020 return GTK_WIDGET ( gtk_type_new (tictactoe_get_type ()));
8024 tictactoe_clear (Tictactoe *ttt)
8031 gtk_signal_handler_block_by_data (GTK_OBJECT(ttt->buttons[i][j]), ttt);
8032 gtk_toggle_button_set_state (GTK_TOGGLE_BUTTON (ttt->buttons[i][j]),
8034 gtk_signal_handler_unblock_by_data (GTK_OBJECT(ttt->buttons[i][j]), ttt);
8039 tictactoe_toggle (GtkWidget *widget, Tictactoe *ttt)
8043 static int rwins[8][3] = { { 0, 0, 0 }, { 1, 1, 1 }, { 2, 2, 2 },
8044 { 0, 1, 2 }, { 0, 1, 2 }, { 0, 1, 2 },
8045 { 0, 1, 2 }, { 0, 1, 2 } };
8046 static int cwins[8][3] = { { 0, 1, 2 }, { 0, 1, 2 }, { 0, 1, 2 },
8047 { 0, 0, 0 }, { 1, 1, 1 }, { 2, 2, 2 },
8048 { 0, 1, 2 }, { 2, 1, 0 } };
8059 success = success &&
8060 GTK_TOGGLE_BUTTON(ttt->buttons[rwins[k][i]][cwins[k][i]])->active;
8062 ttt->buttons[rwins[k][i]][cwins[k][i]] == widget;
8065 if (success && found)
8067 gtk_signal_emit (GTK_OBJECT (ttt),
8068 tictactoe_signals[TICTACTOE_SIGNAL]);
8075 And finally, an example program using our Tictactoe widget:
8078 #include <gtk/gtk.h>
8079 #include "tictactoe.h"
8081 /* Invoked when a row, column or diagonal is completed */
8083 win (GtkWidget *widget, gpointer data)
8086 tictactoe_clear (TICTACTOE (widget));
8090 main (int argc, char *argv[])
8095 gtk_init (&argc, &argv);
8097 window = gtk_window_new (GTK_WINDOW_TOPLEVEL);
8099 gtk_window_set_title (GTK_WINDOW (window), "Aspect Frame");
8101 gtk_signal_connect (GTK_OBJECT (window), "destroy",
8102 GTK_SIGNAL_FUNC (gtk_exit), NULL);
8104 gtk_container_border_width (GTK_CONTAINER (window), 10);
8106 /* Create a new Tictactoe widget */
8107 ttt = tictactoe_new ();
8108 gtk_container_add (GTK_CONTAINER (window), ttt);
8109 gtk_widget_show (ttt);
8111 /* And attach to its "tictactoe" signal */
8112 gtk_signal_connect (GTK_OBJECT (ttt), "tictactoe",
8113 GTK_SIGNAL_FUNC (win), NULL);
8115 gtk_widget_show (window);
8124 <!-- ----------------------------------------------------------------- -->
8125 <sect1> Creating a widget from scratch.
8127 <!-- ----------------------------------------------------------------- -->
8128 <sect2> Introduction
8130 In this section, we'll learn more about how widgets display themselves
8131 on the screen and interact with events. As an example of this, we'll
8132 create an analog dial widget with a pointer that the user can drag to
8135 <!-- ----------------------------------------------------------------- -->
8136 <sect2> Displaying a widget on the screen
8138 There are several steps that are involved in displaying on the screen.
8139 After the widget is created with a call to <tt/WIDGETNAME_new()/,
8140 several more functions are needed:
8143 <item> <tt/WIDGETNAME_realize()/ is responsible for creating an X
8144 window for the widget if it has one.
8145 <item> <tt/WIDGETNAME_map()/ is invoked after the user calls
8146 <tt/gtk_widget_show()/. It is responsible for making sure the widget
8147 is actually drawn on the screen (<em/mapped/). For a container class,
8148 it must also make calls to <tt/map()/> functions of any child widgets.
8149 <item> <tt/WIDGETNAME_draw()/ is invoked when <tt/gtk_widget_draw()/
8150 is called for the widget or one of its ancestors. It makes the actual
8151 calls to the drawing functions to draw the widget on the screen. For
8152 container widgets, this function must make calls to
8153 <tt/gtk_widget_draw()/ for its child widgets.
8154 <item> <tt/WIDGETNAME_expose()/ is a handler for expose events for the
8155 widget. It makes the necessary calls to the drawing functions to draw
8156 the exposed portion on the screen. For container widgets, this
8157 function must generate expose events for its child widgets which don't
8158 have their own windows. (If they have their own windows, then X will
8159 generate the necessary expose events)
8162 You might notice that the last two functions are quite similar - each
8163 is responsible for drawing the widget on the screen. In fact many
8164 types of widgets don't really care about the difference between the
8165 two. The default <tt/draw()/ function in the widget class simply
8166 generates a synthetic expose event for the redrawn area. However, some
8167 types of widgets can save work by distinguishing between the two
8168 functions. For instance, if a widget has multiple X windows, then
8169 since expose events identify the exposed window, it can redraw only
8170 the affected window, which is not possible for calls to <tt/draw()/.
8172 Container widgets, even if they don't care about the difference for
8173 themselves, can't simply use the default <tt/draw()/ function because
8174 their child widgets might care about the difference. However,
8175 it would be wasteful to duplicate the drawing code between the two
8176 functions. The convention is that such widgets have a function called
8177 <tt/WIDGETNAME_paint()/ that does the actual work of drawing the
8178 widget, that is then called by the <tt/draw()/ and <tt/expose()/
8181 In our example approach, since the dial widget is not a container
8182 widget, and only has a single window, we can take the simplest
8183 approach and use the default <tt/draw()/ function and only implement
8184 an <tt/expose()/ function.
8186 <!-- ----------------------------------------------------------------- -->
8187 <sect2> The origins of the Dial Widget
8189 Just as all land animals are just variants on the first amphibian that
8190 crawled up out of the mud, Gtk widgets tend to start off as variants
8191 of some other, previously written widget. Thus, although this section
8192 is entilted ``Creating a Widget from Scratch'', the Dial widget really
8193 began with the source code for the Range widget. This was picked as a
8194 starting point because it would be nice if our Dial had the same
8195 interface as the Scale widgets which are just specialized descendents
8196 of the Range widget. So, though the source code is presented below in
8197 finished form, it should not be implied that it was written, <em>deus
8198 ex machina</em> in this fashion. Also, if you aren't yet familiar with
8199 how scale widgets work from the application writer's point of view, it
8200 would be a good idea to look them over before continuing.
8202 <!-- ----------------------------------------------------------------- -->
8205 Quite a bit of our widget should look pretty familiar from the
8206 Tictactoe widget. First, we have a header file:
8209 /* GTK - The GIMP Toolkit
8210 * Copyright (C) 1995-1997 Peter Mattis, Spencer Kimball and Josh MacDonald
8212 * This library is free software; you can redistribute it and/or
8213 * modify it under the terms of the GNU Library General Public
8214 * License as published by the Free Software Foundation; either
8215 * version 2 of the License, or (at your option) any later version.
8217 * This library is distributed in the hope that it will be useful,
8218 * but WITHOUT ANY WARRANTY; without even the implied warranty of
8219 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
8220 * Library General Public License for more details.
8222 * You should have received a copy of the GNU Library General Public
8223 * License along with this library; if not, write to the Free
8224 * Software Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
8227 #ifndef __GTK_DIAL_H__
8228 #define __GTK_DIAL_H__
8230 #include <gdk/gdk.h>
8231 #include <gtk/gtkadjustment.h>
8232 #include <gtk/gtkwidget.h>
8237 #endif /* __cplusplus */
8240 #define GTK_DIAL(obj) GTK_CHECK_CAST (obj, gtk_dial_get_type (), GtkDial)
8241 #define GTK_DIAL_CLASS(klass) GTK_CHECK_CLASS_CAST (klass, gtk_dial_get_type (), GtkDialClass)
8242 #define GTK_IS_DIAL(obj) GTK_CHECK_TYPE (obj, gtk_dial_get_type ())
8245 typedef struct _GtkDial GtkDial;
8246 typedef struct _GtkDialClass GtkDialClass;
8252 /* update policy (GTK_UPDATE_[CONTINUOUS/DELAYED/DISCONTINUOUS]) */
8255 /* Button currently pressed or 0 if none */
8258 /* Dimensions of dial components */
8262 /* ID of update timer, or 0 if none */
8268 /* Old values from adjustment stored so we know when something changes */
8273 /* The adjustment object that stores the data for this dial */
8274 GtkAdjustment *adjustment;
8277 struct _GtkDialClass
8279 GtkWidgetClass parent_class;
8283 GtkWidget* gtk_dial_new (GtkAdjustment *adjustment);
8284 guint gtk_dial_get_type (void);
8285 GtkAdjustment* gtk_dial_get_adjustment (GtkDial *dial);
8286 void gtk_dial_set_update_policy (GtkDial *dial,
8287 GtkUpdateType policy);
8289 void gtk_dial_set_adjustment (GtkDial *dial,
8290 GtkAdjustment *adjustment);
8293 #endif /* __cplusplus */
8296 #endif /* __GTK_DIAL_H__ */
8299 Since there is quite a bit more going on in this widget, than the last
8300 one, we have more fields in the data structure, but otherwise things
8303 Next, after including header files, and declaring a few constants,
8304 we have some functions to provide information about the widget
8310 #include <gtk/gtkmain.h>
8311 #include <gtk/gtksignal.h>
8313 #include "gtkdial.h"
8315 #define SCROLL_DELAY_LENGTH 300
8316 #define DIAL_DEFAULT_SIZE 100
8318 /* Forward declararations */
8320 [ omitted to save space ]
8324 static GtkWidgetClass *parent_class = NULL;
8327 gtk_dial_get_type ()
8329 static guint dial_type = 0;
8333 GtkTypeInfo dial_info =
8337 sizeof (GtkDialClass),
8338 (GtkClassInitFunc) gtk_dial_class_init,
8339 (GtkObjectInitFunc) gtk_dial_init,
8340 (GtkArgSetFunc) NULL,
8341 (GtkArgGetFunc) NULL,
8344 dial_type = gtk_type_unique (gtk_widget_get_type (), &dial_info);
8351 gtk_dial_class_init (GtkDialClass *class)
8353 GtkObjectClass *object_class;
8354 GtkWidgetClass *widget_class;
8356 object_class = (GtkObjectClass*) class;
8357 widget_class = (GtkWidgetClass*) class;
8359 parent_class = gtk_type_class (gtk_widget_get_type ());
8361 object_class->destroy = gtk_dial_destroy;
8363 widget_class->realize = gtk_dial_realize;
8364 widget_class->expose_event = gtk_dial_expose;
8365 widget_class->size_request = gtk_dial_size_request;
8366 widget_class->size_allocate = gtk_dial_size_allocate;
8367 widget_class->button_press_event = gtk_dial_button_press;
8368 widget_class->button_release_event = gtk_dial_button_release;
8369 widget_class->motion_notify_event = gtk_dial_motion_notify;
8373 gtk_dial_init (GtkDial *dial)
8376 dial->policy = GTK_UPDATE_CONTINUOUS;
8379 dial->pointer_width = 0;
8381 dial->old_value = 0.0;
8382 dial->old_lower = 0.0;
8383 dial->old_upper = 0.0;
8384 dial->adjustment = NULL;
8388 gtk_dial_new (GtkAdjustment *adjustment)
8392 dial = gtk_type_new (gtk_dial_get_type ());
8395 adjustment = (GtkAdjustment*) gtk_adjustment_new (0.0, 0.0, 0.0, 0.0, 0.0, 0.0);
8397 gtk_dial_set_adjustment (dial, adjustment);
8399 return GTK_WIDGET (dial);
8403 gtk_dial_destroy (GtkObject *object)
8407 g_return_if_fail (object != NULL);
8408 g_return_if_fail (GTK_IS_DIAL (object));
8410 dial = GTK_DIAL (object);
8412 if (dial->adjustment)
8413 gtk_object_unref (GTK_OBJECT (dial->adjustment));
8415 if (GTK_OBJECT_CLASS (parent_class)->destroy)
8416 (* GTK_OBJECT_CLASS (parent_class)->destroy) (object);
8420 Note that this <tt/init()/ function does less than for the Tictactoe
8421 widget, since this is not a composite widget, and the <tt/new()/
8422 function does more, since it now has an argument. Also, note that when
8423 we store a pointer to the Adjustment object, we increment its
8424 reference count, (and correspondingly decrement when we no longer use
8425 it) so that GTK can keep track of when it can be safely destroyed.
8428 Also, there are a few function to manipulate the widget's options:
8432 gtk_dial_get_adjustment (GtkDial *dial)
8434 g_return_val_if_fail (dial != NULL, NULL);
8435 g_return_val_if_fail (GTK_IS_DIAL (dial), NULL);
8437 return dial->adjustment;
8441 gtk_dial_set_update_policy (GtkDial *dial,
8442 GtkUpdateType policy)
8444 g_return_if_fail (dial != NULL);
8445 g_return_if_fail (GTK_IS_DIAL (dial));
8447 dial->policy = policy;
8451 gtk_dial_set_adjustment (GtkDial *dial,
8452 GtkAdjustment *adjustment)
8454 g_return_if_fail (dial != NULL);
8455 g_return_if_fail (GTK_IS_DIAL (dial));
8457 if (dial->adjustment)
8459 gtk_signal_disconnect_by_data (GTK_OBJECT (dial->adjustment), (gpointer) dial);
8460 gtk_object_unref (GTK_OBJECT (dial->adjustment));
8463 dial->adjustment = adjustment;
8464 gtk_object_ref (GTK_OBJECT (dial->adjustment));
8466 gtk_signal_connect (GTK_OBJECT (adjustment), "changed",
8467 (GtkSignalFunc) gtk_dial_adjustment_changed,
8469 gtk_signal_connect (GTK_OBJECT (adjustment), "value_changed",
8470 (GtkSignalFunc) gtk_dial_adjustment_value_changed,
8473 dial->old_value = adjustment->value;
8474 dial->old_lower = adjustment->lower;
8475 dial->old_upper = adjustment->upper;
8477 gtk_dial_update (dial);
8481 <sect2> <tt/gtk_dial_realize()/
8484 Now we come to some new types of functions. First, we have a function
8485 that does the work of creating the X window. Notice that a mask is
8486 passed to the function <tt/gdk_window_new()/ which specifies which fields of
8487 the GdkWindowAttr structure actually have data in them (the remaining
8488 fields wll be given default values). Also worth noting is the way the
8489 event mask of the widget is created. We call
8490 <tt/gtk_widget_get_events()/ to retrieve the event mask that the user
8491 has specified for this widget (with <tt/gtk_widget_set_events()/, and
8492 add the events that we are interested in ourselves.
8495 After creating the window, we set its style and background, and put a
8496 pointer to the widget in the user data field of the GdkWindow. This
8497 last step allows GTK to dispatch events for this window to the correct
8502 gtk_dial_realize (GtkWidget *widget)
8505 GdkWindowAttr attributes;
8506 gint attributes_mask;
8508 g_return_if_fail (widget != NULL);
8509 g_return_if_fail (GTK_IS_DIAL (widget));
8511 GTK_WIDGET_SET_FLAGS (widget, GTK_REALIZED);
8512 dial = GTK_DIAL (widget);
8514 attributes.x = widget->allocation.x;
8515 attributes.y = widget->allocation.y;
8516 attributes.width = widget->allocation.width;
8517 attributes.height = widget->allocation.height;
8518 attributes.wclass = GDK_INPUT_OUTPUT;
8519 attributes.window_type = GDK_WINDOW_CHILD;
8520 attributes.event_mask = gtk_widget_get_events (widget) |
8521 GDK_EXPOSURE_MASK | GDK_BUTTON_PRESS_MASK |
8522 GDK_BUTTON_RELEASE_MASK | GDK_POINTER_MOTION_MASK |
8523 GDK_POINTER_MOTION_HINT_MASK;
8524 attributes.visual = gtk_widget_get_visual (widget);
8525 attributes.colormap = gtk_widget_get_colormap (widget);
8527 attributes_mask = GDK_WA_X | GDK_WA_Y | GDK_WA_VISUAL | GDK_WA_COLORMAP;
8528 widget->window = gdk_window_new (widget->parent->window, &attributes, attributes_mask);
8530 widget->style = gtk_style_attach (widget->style, widget->window);
8532 gdk_window_set_user_data (widget->window, widget);
8534 gtk_style_set_background (widget->style, widget->window, GTK_STATE_ACTIVE);
8538 <sect2> Size negotiation
8541 Before the first time that the window containing a widget is
8542 displayed, and whenever the layout of the window changes, GTK asks
8543 each child widget for its desired size. This request is handled by the
8544 function, <tt/gtk_dial_size_request()/. Since our widget isn't a
8545 container widget, and has no real constraints on its size, we just
8546 return a reasonable default value.
8550 gtk_dial_size_request (GtkWidget *widget,
8551 GtkRequisition *requisition)
8553 requisition->width = DIAL_DEFAULT_SIZE;
8554 requisition->height = DIAL_DEFAULT_SIZE;
8559 After all the widgets have requested an ideal size, the layout of the
8560 window is computed and each child widget is notified of its actual
8561 size. Usually, this will at least as large as the requested size, but
8562 if for instance, the user has resized the window, it may occasionally
8563 be smaller than the requested size. The size notification is handled
8564 by the function <tt/gtk_dial_size_allocate()/. Notice that as well as
8565 computing the sizes of some component pieces for future use, this
8566 routine also does the grunt work of moving the widgets X window into
8567 the new position and size.
8571 gtk_dial_size_allocate (GtkWidget *widget,
8572 GtkAllocation *allocation)
8576 g_return_if_fail (widget != NULL);
8577 g_return_if_fail (GTK_IS_DIAL (widget));
8578 g_return_if_fail (allocation != NULL);
8580 widget->allocation = *allocation;
8581 if (GTK_WIDGET_REALIZED (widget))
8583 dial = GTK_DIAL (widget);
8585 gdk_window_move_resize (widget->window,
8586 allocation->x, allocation->y,
8587 allocation->width, allocation->height);
8589 dial->radius = MAX(allocation->width,allocation->height) * 0.45;
8590 dial->pointer_width = dial->radius / 5;
8595 <!-- ----------------------------------------------------------------- -->
8596 <sect2> <tt/gtk_dial_expose()/
8599 As mentioned above, all the drawing of this widget is done in the
8600 handler for expose events. There's not much to remark on here except
8601 the use of the function <tt/gtk_draw_polygon/ to draw the pointer with
8602 three dimensional shading according to the colors stored in the
8607 gtk_dial_expose (GtkWidget *widget,
8608 GdkEventExpose *event)
8618 g_return_val_if_fail (widget != NULL, FALSE);
8619 g_return_val_if_fail (GTK_IS_DIAL (widget), FALSE);
8620 g_return_val_if_fail (event != NULL, FALSE);
8622 if (event->count > 0)
8625 dial = GTK_DIAL (widget);
8627 gdk_window_clear_area (widget->window,
8629 widget->allocation.width,
8630 widget->allocation.height);
8632 xc = widget->allocation.width/2;
8633 yc = widget->allocation.height/2;
8637 for (i=0; i<25; i++)
8639 theta = (i*M_PI/18. - M_PI/6.);
8643 tick_length = (i%6 == 0) ? dial->pointer_width : dial->pointer_width/2;
8645 gdk_draw_line (widget->window,
8646 widget->style->fg_gc[widget->state],
8647 xc + c*(dial->radius - tick_length),
8648 yc - s*(dial->radius - tick_length),
8649 xc + c*dial->radius,
8650 yc - s*dial->radius);
8655 s = sin(dial->angle);
8656 c = cos(dial->angle);
8659 points[0].x = xc + s*dial->pointer_width/2;
8660 points[0].y = yc + c*dial->pointer_width/2;
8661 points[1].x = xc + c*dial->radius;
8662 points[1].y = yc - s*dial->radius;
8663 points[2].x = xc - s*dial->pointer_width/2;
8664 points[2].y = yc - c*dial->pointer_width/2;
8666 gtk_draw_polygon (widget->style,
8677 <!-- ----------------------------------------------------------------- -->
8678 <sect2> Event handling
8682 The rest of the widget's code handles various types of events, and
8683 isn't too different from what would be found in many GTK
8684 applications. Two types of events can occur - either the user can
8685 click on the widget with the mouse and drag to move the pointer, or
8686 the value of the Adjustment object can change due to some external
8690 When the user clicks on the widget, we check to see if the click was
8691 appropriately near the pointer, and if so, store then button that the
8692 user clicked with in the <tt/button/ field of the widget
8693 structure, and grab all mouse events with a call to
8694 <tt/gtk_grab_add()/. Subsequent motion of the mouse causes the
8695 value of the control to be recomputed (by the function
8696 <tt/gtk_dial_update_mouse/). Depending on the policy that has been
8697 set, "value_changed" events are either generated instantly
8698 (<tt/GTK_UPDATE_CONTINUOUS/), after a delay in a timer added with
8699 <tt/gtk_timeout_add()/ (<tt/GTK_UPDATE_DELAYED/), or only when the
8700 button is released (<tt/GTK_UPDATE_DISCONTINUOUS/).
8704 gtk_dial_button_press (GtkWidget *widget,
8705 GdkEventButton *event)
8711 double d_perpendicular;
8713 g_return_val_if_fail (widget != NULL, FALSE);
8714 g_return_val_if_fail (GTK_IS_DIAL (widget), FALSE);
8715 g_return_val_if_fail (event != NULL, FALSE);
8717 dial = GTK_DIAL (widget);
8719 /* Determine if button press was within pointer region - we
8720 do this by computing the parallel and perpendicular distance of
8721 the point where the mouse was pressed from the line passing through
8724 dx = event->x - widget->allocation.width / 2;
8725 dy = widget->allocation.height / 2 - event->y;
8727 s = sin(dial->angle);
8728 c = cos(dial->angle);
8730 d_parallel = s*dy + c*dx;
8731 d_perpendicular = fabs(s*dx - c*dy);
8733 if (!dial->button &&
8734 (d_perpendicular < dial->pointer_width/2) &&
8735 (d_parallel > - dial->pointer_width))
8737 gtk_grab_add (widget);
8739 dial->button = event->button;
8741 gtk_dial_update_mouse (dial, event->x, event->y);
8748 gtk_dial_button_release (GtkWidget *widget,
8749 GdkEventButton *event)
8753 g_return_val_if_fail (widget != NULL, FALSE);
8754 g_return_val_if_fail (GTK_IS_DIAL (widget), FALSE);
8755 g_return_val_if_fail (event != NULL, FALSE);
8757 dial = GTK_DIAL (widget);
8759 if (dial->button == event->button)
8761 gtk_grab_remove (widget);
8765 if (dial->policy == GTK_UPDATE_DELAYED)
8766 gtk_timeout_remove (dial->timer);
8768 if ((dial->policy != GTK_UPDATE_CONTINUOUS) &&
8769 (dial->old_value != dial->adjustment->value))
8770 gtk_signal_emit_by_name (GTK_OBJECT (dial->adjustment), "value_changed");
8777 gtk_dial_motion_notify (GtkWidget *widget,
8778 GdkEventMotion *event)
8781 GdkModifierType mods;
8784 g_return_val_if_fail (widget != NULL, FALSE);
8785 g_return_val_if_fail (GTK_IS_DIAL (widget), FALSE);
8786 g_return_val_if_fail (event != NULL, FALSE);
8788 dial = GTK_DIAL (widget);
8790 if (dial->button != 0)
8795 if (event->is_hint || (event->window != widget->window))
8796 gdk_window_get_pointer (widget->window, &x, &y, &mods);
8798 switch (dial->button)
8801 mask = GDK_BUTTON1_MASK;
8804 mask = GDK_BUTTON2_MASK;
8807 mask = GDK_BUTTON3_MASK;
8815 gtk_dial_update_mouse (dial, x,y);
8822 gtk_dial_timer (GtkDial *dial)
8824 g_return_val_if_fail (dial != NULL, FALSE);
8825 g_return_val_if_fail (GTK_IS_DIAL (dial), FALSE);
8827 if (dial->policy == GTK_UPDATE_DELAYED)
8828 gtk_signal_emit_by_name (GTK_OBJECT (dial->adjustment), "value_changed");
8834 gtk_dial_update_mouse (GtkDial *dial, gint x, gint y)
8839 g_return_if_fail (dial != NULL);
8840 g_return_if_fail (GTK_IS_DIAL (dial));
8842 xc = GTK_WIDGET(dial)->allocation.width / 2;
8843 yc = GTK_WIDGET(dial)->allocation.height / 2;
8845 old_value = dial->adjustment->value;
8846 dial->angle = atan2(yc-y, x-xc);
8848 if (dial->angle < -M_PI/2.)
8849 dial->angle += 2*M_PI;
8851 if (dial->angle < -M_PI/6)
8852 dial->angle = -M_PI/6;
8854 if (dial->angle > 7.*M_PI/6.)
8855 dial->angle = 7.*M_PI/6.;
8857 dial->adjustment->value = dial->adjustment->lower + (7.*M_PI/6 - dial->angle) *
8858 (dial->adjustment->upper - dial->adjustment->lower) / (4.*M_PI/3.);
8860 if (dial->adjustment->value != old_value)
8862 if (dial->policy == GTK_UPDATE_CONTINUOUS)
8864 gtk_signal_emit_by_name (GTK_OBJECT (dial->adjustment), "value_changed");
8868 gtk_widget_draw (GTK_WIDGET(dial), NULL);
8870 if (dial->policy == GTK_UPDATE_DELAYED)
8873 gtk_timeout_remove (dial->timer);
8875 dial->timer = gtk_timeout_add (SCROLL_DELAY_LENGTH,
8876 (GtkFunction) gtk_dial_timer,
8885 Changes to the Adjustment by external means are communicated to our
8886 widget by the ``changed'' and ``value_changed'' signals. The handlers
8887 for these functions call <tt/gtk_dial_update()/ to validate the
8888 arguments, compute the new pointer angle, and redraw the widget (by
8889 calling <tt/gtk_widget_draw()/).
8893 gtk_dial_update (GtkDial *dial)
8897 g_return_if_fail (dial != NULL);
8898 g_return_if_fail (GTK_IS_DIAL (dial));
8900 new_value = dial->adjustment->value;
8902 if (new_value < dial->adjustment->lower)
8903 new_value = dial->adjustment->lower;
8905 if (new_value > dial->adjustment->upper)
8906 new_value = dial->adjustment->upper;
8908 if (new_value != dial->adjustment->value)
8910 dial->adjustment->value = new_value;
8911 gtk_signal_emit_by_name (GTK_OBJECT (dial->adjustment), "value_changed");
8914 dial->angle = 7.*M_PI/6. - (new_value - dial->adjustment->lower) * 4.*M_PI/3. /
8915 (dial->adjustment->upper - dial->adjustment->lower);
8917 gtk_widget_draw (GTK_WIDGET(dial), NULL);
8921 gtk_dial_adjustment_changed (GtkAdjustment *adjustment,
8926 g_return_if_fail (adjustment != NULL);
8927 g_return_if_fail (data != NULL);
8929 dial = GTK_DIAL (data);
8931 if ((dial->old_value != adjustment->value) ||
8932 (dial->old_lower != adjustment->lower) ||
8933 (dial->old_upper != adjustment->upper))
8935 gtk_dial_update (dial);
8937 dial->old_value = adjustment->value;
8938 dial->old_lower = adjustment->lower;
8939 dial->old_upper = adjustment->upper;
8944 gtk_dial_adjustment_value_changed (GtkAdjustment *adjustment,
8949 g_return_if_fail (adjustment != NULL);
8950 g_return_if_fail (data != NULL);
8952 dial = GTK_DIAL (data);
8954 if (dial->old_value != adjustment->value)
8956 gtk_dial_update (dial);
8958 dial->old_value = adjustment->value;
8963 <!-- ----------------------------------------------------------------- -->
8964 <sect2> Possible Enhancements
8967 The Dial widget as we've described it so far runs about 670 lines of
8968 code. Although that might sound like a fair bit, we've really
8969 accomplished quite a bit with that much code, especially since much of
8970 that length is headers and boilerplate. However, there are quite a few
8971 more enhancements that could be made to this widget:
8974 <item> If you try this widget out, you'll find that there is some
8975 flashing as the pointer is dragged around. This is because the entire
8976 widget is erased every time the pointer is moved before being
8977 redrawn. Often, the best way to handle this problem is to draw to an
8978 offscreen pixmap, then copy the final results onto the screen in one
8979 step. (The ProgressBar widget draws itself in this fashion.)
8981 <item> The user should be able to use the up and down arrow keys to
8982 increase and decrease the value.
8984 <item> It would be nice if the widget had buttons to increase and
8985 decrease the value in small or large steps. Although it would be
8986 possible to use embedded Button widgets for this, we would also like
8987 the buttons to auto-repeat when held down, as the arrows on a
8988 scrollbar do. Most of the code to implement this type of behavior can
8989 be found in the GtkRange widget.
8991 <item> The Dial widget could be made into a container widget with a
8992 single child widget positioned at the bottom between the buttons
8993 mentioned above. The user could then add their choice of a label or
8994 entry widget to display the current value of the dial.
8998 <!-- ----------------------------------------------------------------- -->
8999 <sect1> Learning More
9002 Only a small part of the many details involved in creating widgets
9003 could be described above. If you want to write your own widgets, the
9004 best source of examples is the GTK source itself. Ask yourself some
9005 questions about the widget you want to write: is it a Container
9006 widget? does it have its own window? is it a modification of an
9007 existing widget? Then find a similar widget, and start making changes.
9010 <!-- ***************************************************************** -->
9011 <sect>Scribble, A Simple Example Drawing Program
9012 <!-- ***************************************************************** -->
9014 <!-- ----------------------------------------------------------------- -->
9018 In this section, we will build a simple drawing program. In the
9019 process, we will examine how to handle mouse events, how to draw in a
9020 window, and how to do drawing better by using a backing pixmap. After
9021 creating the simple drawing program, we will extend it by adding
9022 support for XInput devices, such as drawing tablets. GTK provides
9023 support routines which makes getting extended information, such as
9024 pressure and tilt, from such devices quite easy.
9026 <!-- ----------------------------------------------------------------- -->
9027 <sect1> Event Handling
9030 The GTK signals we have already discussed are for high-level actions,
9031 such as a menu item being selected. However, sometimes it is useful to
9032 learn about lower-level occurrences, such as the mouse being moved, or
9033 a key being pressed. There are also GTK signals corresponding to these
9034 low-level <em>events</em>. The handlers for these signals have an
9035 extra parameter which is a pointer to a structure containing
9036 information about the event. For instance, motion events handlers are
9037 passed a pointer to a GdkEventMotion structure which looks (in part)
9041 struct _GdkEventMotion
9054 <tt/type/ will be set to the event type, in this case
9055 <tt/GDK_MOTION_NOTIFY/, window is the window in which the event
9056 occured. <tt/x/ and <tt/y/ give the coordinates of the event,
9057 and <tt/state/ specifies the modifier state when the event
9058 occurred (that is, it specifies which modifier keys and mouse buttons
9059 were pressed.) It is the bitwise OR of some of the following:
9078 As for other signals, to determine what happens when an event occurs
9079 we call <tt>gtk_signal_connect()</tt>. But we also need let GTK
9080 know which events we want to be notified about. To do this, we call
9084 void gtk_widget_set_events (GtkWidget *widget,
9088 The second field specifies the events we are interested in. It
9089 is the bitwise OR of constants that specify different types
9090 of events. For future reference the event types are:
9094 GDK_POINTER_MOTION_MASK
9095 GDK_POINTER_MOTION_HINT_MASK
9096 GDK_BUTTON_MOTION_MASK
9097 GDK_BUTTON1_MOTION_MASK
9098 GDK_BUTTON2_MOTION_MASK
9099 GDK_BUTTON3_MOTION_MASK
9100 GDK_BUTTON_PRESS_MASK
9101 GDK_BUTTON_RELEASE_MASK
9103 GDK_KEY_RELEASE_MASK
9104 GDK_ENTER_NOTIFY_MASK
9105 GDK_LEAVE_NOTIFY_MASK
9106 GDK_FOCUS_CHANGE_MASK
9108 GDK_PROPERTY_CHANGE_MASK
9109 GDK_PROXIMITY_IN_MASK
9110 GDK_PROXIMITY_OUT_MASK
9113 There are a few subtle points that have to be observed when calling
9114 <tt/gtk_widget_set_events()/. First, it must be called before the X window
9115 for a GTK widget is created. In practical terms, this means you
9116 should call it immediately after creating the widget. Second, the
9117 widget must have an associated X window. For efficiency, many widget
9118 types do not have their own window, but draw in their parent's window.
9141 To capture events for these widgets, you need to use an EventBox
9142 widget. See the section on
9143 <ref id="sec_The_EventBox_Widget" name="The EventBox Widget"> for
9147 For our drawing program, we want to know when the mouse button is
9148 pressed and when the mouse is moved, so we specify
9149 <tt/GDK_POINTER_MOTION_MASK/ and <tt/GDK_BUTTON_PRESS_MASK/. We also
9150 want to know when we need to redraw our window, so we specify
9151 <tt/GDK_EXPOSURE_MASK/. Although we want to be notified via a
9152 Configure event when our window size changes, we don't have to specify
9153 the corresponding <tt/GDK_STRUCTURE_MASK/ flag, because it is
9154 automatically specified for all windows.
9157 It turns out, however, that there is a problem with just specifying
9158 <tt/GDK_POINTER_MOTION_MASK/. This will cause the server to add a new
9159 motion event to the event queue every time the user moves the mouse.
9160 Imagine that it takes us 0.1 seconds to handle a motion event, but the
9161 X server queues a new motion event every 0.05 seconds. We will soon
9162 get way behind the users drawing. If the user draws for 5 seconds,
9163 it will take us another 5 seconds to catch up after they release
9164 the mouse button! What we would like is to only get one motion
9165 event for each event we process. The way to do this is to
9166 specify <tt/GDK_POINTER_MOTION_HINT_MASK/.
9169 When we specify <tt/GDK_POINTER_MOTION_HINT_MASK/, the server sends
9170 us a motion event the first time the pointer moves after entering
9171 our window, or after a button press or release event. Subsequent
9172 motion events will be suppressed until we explicitely ask for
9173 the position of the pointer using the function:
9176 GdkWindow* gdk_window_get_pointer (GdkWindow *window,
9179 GdkModifierType *mask);
9182 (There is another function, <tt>gtk_widget_get_pointer()</tt> which
9183 has a simpler interface, but turns out not to be very useful, since
9184 it only retrieves the position of the mouse, not whether the buttons
9188 The code to set the events for our window then looks like:
9191 gtk_signal_connect (GTK_OBJECT (drawing_area), "expose_event",
9192 (GtkSignalFunc) expose_event, NULL);
9193 gtk_signal_connect (GTK_OBJECT(drawing_area),"configure_event",
9194 (GtkSignalFunc) configure_event, NULL);
9195 gtk_signal_connect (GTK_OBJECT (drawing_area), "motion_notify_event",
9196 (GtkSignalFunc) motion_notify_event, NULL);
9197 gtk_signal_connect (GTK_OBJECT (drawing_area), "button_press_event",
9198 (GtkSignalFunc) button_press_event, NULL);
9200 gtk_widget_set_events (drawing_area, GDK_EXPOSURE_MASK
9201 | GDK_LEAVE_NOTIFY_MASK
9202 | GDK_BUTTON_PRESS_MASK
9203 | GDK_POINTER_MOTION_MASK
9204 | GDK_POINTER_MOTION_HINT_MASK);
9207 We'll save the "expose_event" and "configure_event" handlers for
9208 later. The "motion_notify_event" and "button_press_event" handlers
9213 button_press_event (GtkWidget *widget, GdkEventButton *event)
9215 if (event->button == 1 && pixmap != NULL)
9216 draw_brush (widget, event->x, event->y);
9222 motion_notify_event (GtkWidget *widget, GdkEventMotion *event)
9225 GdkModifierType state;
9228 gdk_window_get_pointer (event->window, &x, &y, &state);
9233 state = event->state;
9236 if (state & GDK_BUTTON1_MASK && pixmap != NULL)
9237 draw_brush (widget, x, y);
9243 <!-- ----------------------------------------------------------------- -->
9244 <sect1> The DrawingArea Widget, And Drawing
9247 We know turn to the process of drawing on the screen. The
9248 widget we use for this is the DrawingArea widget. A drawing area
9249 widget is essentially an X window and nothing more. It is a blank
9250 canvas in which we can draw whatever we like. A drawing area
9251 is created using the call:
9254 GtkWidget* gtk_drawing_area_new (void);
9257 A default size for the widget can be specified by calling:
9260 void gtk_drawing_area_size (GtkDrawingArea *darea,
9265 This default size can be overriden, as is true for all widgets,
9266 by calling <tt>gtk_widget_set_usize()</tt>, and that, in turn, can
9267 be overridden if the user manually resizes the the window containing
9271 It should be noted that when we create a DrawingArea widget, we are,
9272 <em>completely</em> responsible for drawing the contents. If our
9273 window is obscured then uncovered, we get an exposure event and must
9274 redraw what was previously hidden.
9277 Having to remember everything that was drawn on the screen so we
9278 can properly redraw it can, to say the least, be a nuisance. In
9279 addition, it can be visually distracting if portions of the
9280 window are cleared, then redrawn step by step. The solution to
9281 this problem is to use an offscreen <em>backing pixmap</em>.
9282 Instead of drawing directly to the screen, we draw to an image
9283 stored in server memory but not displayed, then when the image
9284 changes or new portions of the image are displayed, we copy the
9285 relevant portions onto the screen.
9288 To create an offscreen pixmap, we call the function:
9291 GdkPixmap* gdk_pixmap_new (GdkWindow *window,
9297 The <tt>window</tt> parameter specifies a GDK window that this pixmap
9298 takes some of its properties from. <tt>width</tt> and <tt>height</tt>
9299 specify the size of the pixmap. <tt>depth</tt> specifies the <em>color
9300 depth</em>, that is the number of bits per pixel, for the new window.
9301 If the depth is specified as <tt>-1</tt>, it will match the depth
9305 We create the pixmap in our "configure_event" handler. This event
9306 is generated whenever the window changes size, including when it
9307 is originally created.
9310 /* Backing pixmap for drawing area */
9311 static GdkPixmap *pixmap = NULL;
9313 /* Create a new backing pixmap of the appropriate size */
9315 configure_event (GtkWidget *widget, GdkEventConfigure *event)
9319 gdk_pixmap_destroy(pixmap);
9321 pixmap = gdk_pixmap_new(widget->window,
9322 widget->allocation.width,
9323 widget->allocation.height,
9325 gdk_draw_rectangle (pixmap,
9326 widget->style->white_gc,
9329 widget->allocation.width,
9330 widget->allocation.height);
9336 The call to <tt>gdk_draw_rectangle()</tt> clears the pixmap
9337 initially to white. We'll say more about that in a moment.
9340 Our exposure event handler then simply copies the relevant portion
9341 of the pixmap onto the screen (we determine the area we need
9342 to redraw by using the event->area field of the exposure event):
9345 /* Refill the screen from the backing pixmap */
9347 expose_event (GtkWidget *widget, GdkEventExpose *event)
9349 gdk_draw_pixmap(widget->window,
9350 widget->style->fg_gc[GTK_WIDGET_STATE (widget)],
9352 event->area.x, event->area.y,
9353 event->area.x, event->area.y,
9354 event->area.width, event->area.height);
9360 We've now seen how to keep the screen up to date with our pixmap, but
9361 how do we actually draw interesting stuff on our pixmap? There are a
9362 large number of calls in GTK's GDK library for drawing on
9363 <em>drawables</em>. A drawable is simply something that can be drawn
9364 upon. It can be a window, a pixmap, or a bitmap (a black and white
9365 image). We've already seen two such calls above,
9366 <tt>gdk_draw_rectangle()</tt> and <tt>gdk_draw_pixmap()</tt>. The
9371 gdk_draw_rectangle ()
9380 gdk_draw_segments ()
9383 See the reference documentation or the header file
9384 <tt><gdk/gdk.h></tt> for further details on these functions.
9385 These functions all share the same first two arguments. The first
9386 argument is the drawable to draw upon, the second argument is a
9387 <em>graphics context</em> (GC).
9390 A graphics context encapsulates information about things such as
9391 foreground and background color and line width. GDK has a full set of
9392 functions for creating and modifying graphics contexts, but to keep
9393 things simple we'll just use predefined graphics contexts. Each widget
9394 has an associated style. (Which can be modified in a gtkrc file, see
9395 the section GTK's rc file.) This, among other things, stores a number
9396 of graphics contexts. Some examples of accessing these graphics
9400 widget->style->white_gc
9401 widget->style->black_gc
9402 widget->style->fg_gc[GTK_STATE_NORMAL]
9403 widget->style->bg_gc[GTK_WIDGET_STATE(widget)]
9406 The fields <tt>fg_gc</tt>, <tt>bg_gc</tt>, <tt>dark_gc</tt>, and
9407 <tt>light_gc</tt> are indexed by a parameter of type
9408 <tt>GtkStateType</tt> which can take on the values:
9415 GTK_STATE_INSENSITIVE
9418 For instance, the for <tt/GTK_STATE_SELECTED/ the default foreground
9419 color is white and the default background color, dark blue.
9422 Our function <tt>draw_brush()</tt>, which does the actual drawing
9423 on the screen, is then:
9426 /* Draw a rectangle on the screen */
9428 draw_brush (GtkWidget *widget, gdouble x, gdouble y)
9430 GdkRectangle update_rect;
9432 update_rect.x = x - 5;
9433 update_rect.y = y - 5;
9434 update_rect.width = 10;
9435 update_rect.height = 10;
9436 gdk_draw_rectangle (pixmap,
9437 widget->style->black_gc,
9439 update_rect.x, update_rect.y,
9440 update_rect.width, update_rect.height);
9441 gtk_widget_draw (widget, &update_rect);
9445 After we draw the rectangle representing the brush onto the pixmap,
9446 we call the function:
9449 void gtk_widget_draw (GtkWidget *widget,
9450 GdkRectangle *area);
9453 which notifies X that the area given by the <tt>area</tt> parameter
9454 needs to be updated. X will eventually generate an expose event
9455 (possibly combining the areas passed in several calls to
9456 <tt>gtk_widget_draw()</tt>) which will cause our expose event handler
9457 to copy the relevant portions to the screen.
9460 We have now covered the entire drawing program except for a few
9461 mundane details like creating the main window. The complete
9462 source code is available from the location from which you got
9463 this tutorial, or from:
9465 <htmlurl url="http://www.msc.cornell.edu/~otaylor/gtk-gimp/tutorial"
9466 name="http://www.msc.cornell.edu/~otaylor/gtk-gimp/tutorial">
9469 <!-- ----------------------------------------------------------------- -->
9470 <sect1> Adding XInput support
9474 It is now possible to buy quite inexpensive input devices such
9475 as drawing tablets, which allow drawing with a much greater
9476 ease of artistic expression than does a mouse. The simplest way
9477 to use such devices is simply as a replacement for the mouse,
9478 but that misses out many of the advantages of these devices,
9482 <item> Pressure sensitivity
9483 <item> Tilt reporting
9484 <item> Sub-pixel positioning
9485 <item> Multiple inputs (for example, a stylus with a point and eraser)
9488 For information about the XInput extension, see the <htmlurl
9489 url="http://www.msc.cornell.edu/~otaylor/xinput/XInput-HOWTO.html"
9490 name="XInput-HOWTO">.
9493 If we examine the full definition of, for example, the GdkEventMotion
9494 structure, we see that it has fields to support extended device
9498 struct _GdkEventMotion
9510 GdkInputSource source;
9515 <tt/pressure/ gives the pressure as a floating point number between
9516 0 and 1. <tt/xtilt/ and <tt/ytilt/ can take on values between
9517 -1 and 1, corresponding to the degree of tilt in each direction.
9518 <tt/source/ and <tt/deviceid/ specify the device for which the
9519 event occurred in two different ways. <tt/source/ gives some simple
9520 information about the type of device. It can take the enumeration
9530 <tt/deviceid/ specifies a unique numeric ID for the device. This can
9531 be used to find out further information about the device using the
9532 <tt/gdk_input_list_devices()/ call (see below). The special value
9533 <tt/GDK_CORE_POINTER/ is used for the core pointer device. (Usually
9536 <sect2> Enabling extended device information
9539 To let GTK know about our interest in the extended device information,
9540 we merely have to add a single line to our program:
9543 gtk_widget_set_extension_events (drawing_area, GDK_EXTENSION_EVENTS_CURSOR);
9546 By giving the value <tt/GDK_EXTENSION_EVENTS_CURSOR/ we say that
9547 we are interested in extension events, but only if we don't have
9548 to draw our own cursor. See the section <ref
9549 id="sec_Further_Sophistications" name="Further Sophistications"> below
9550 for more information about drawing the cursor. We could also
9551 give the values <tt/GDK_EXTENSION_EVENTS_ALL/ if we were willing
9552 to draw our own cursor, or <tt/GDK_EXTENSION_EVENTS_NONE/ to revert
9553 back to the default condition.
9556 This is not completely the end of the story however. By default,
9557 no extension devices are enabled. We need a mechanism to allow
9558 users to enable and configure their extension devices. GTK provides
9559 the InputDialog widget to automate this process. The following
9560 procedure manages an InputDialog widget. It creates the dialog if
9561 it isn't present, and raises it to the top otherwise.
9565 input_dialog_destroy (GtkWidget *w, gpointer data)
9567 *((GtkWidget **)data) = NULL;
9571 create_input_dialog ()
9573 static GtkWidget *inputd = NULL;
9577 inputd = gtk_input_dialog_new();
9579 gtk_signal_connect (GTK_OBJECT(inputd), "destroy",
9580 (GtkSignalFunc)input_dialog_destroy, &inputd);
9581 gtk_signal_connect_object (GTK_OBJECT(GTK_INPUT_DIALOG(inputd)->close_button),
9583 (GtkSignalFunc)gtk_widget_hide,
9584 GTK_OBJECT(inputd));
9585 gtk_widget_hide ( GTK_INPUT_DIALOG(inputd)->save_button);
9587 gtk_widget_show (inputd);
9591 if (!GTK_WIDGET_MAPPED(inputd))
9592 gtk_widget_show(inputd);
9594 gdk_window_raise(inputd->window);
9599 (You might want to take note of the way we handle this dialog. By
9600 connecting to the "destroy" signal, we make sure that we don't keep a
9601 pointer to dialog around after it is destroyed - that could lead to a
9605 The InputDialog has two buttons "Close" and "Save", which by default
9606 have no actions assigned to them. In the above function we make
9607 "Close" hide the dialog, hide the "Save" button, since we don't
9608 implement saving of XInput options in this program.
9610 <sect2> Using extended device information
9613 Once we've enabled the device, we can just use the extended
9614 device information in the extra fields of the event structures.
9615 In fact, it is always safe to use this information since these
9616 fields will have reasonable default values even when extended
9617 events are not enabled.
9620 Once change we do have to make is to call
9621 <tt/gdk_input_window_get_pointer()/ instead of
9622 <tt/gdk_window_get_pointer/. This is necessary because
9623 <tt/gdk_window_get_pointer/ doesn't return the extended device
9627 void gdk_input_window_get_pointer (GdkWindow *window,
9634 GdkModifierType *mask);
9637 When calling this function, we need to specify the device ID as
9638 well as the window. Usually, we'll get the device ID from the
9639 <tt/deviceid/ field of an event structure. Again, this function
9640 will return reasonable values when extension events are not
9641 enabled. (In this case, <tt/event->deviceid/ will have the value
9642 <tt/GDK_CORE_POINTER/).
9644 So the basic structure of our button-press and motion event handlers,
9645 doesn't change much - we just need to add code to deal with the
9646 extended information.
9650 button_press_event (GtkWidget *widget, GdkEventButton *event)
9652 print_button_press (event->deviceid);
9654 if (event->button == 1 && pixmap != NULL)
9655 draw_brush (widget, event->source, event->x, event->y, event->pressure);
9661 motion_notify_event (GtkWidget *widget, GdkEventMotion *event)
9665 GdkModifierType state;
9668 gdk_input_window_get_pointer (event->window, event->deviceid,
9669 &x, &y, &pressure, NULL, NULL, &state);
9674 pressure = event->pressure;
9675 state = event->state;
9678 if (state & GDK_BUTTON1_MASK && pixmap != NULL)
9679 draw_brush (widget, event->source, x, y, pressure);
9685 We also need to do something with the new information. Our new
9686 <tt/draw_brush()/ function draws with a different color for
9687 each <tt/event->source/ and changes the brush size depending
9691 /* Draw a rectangle on the screen, size depending on pressure,
9692 and color on the type of device */
9694 draw_brush (GtkWidget *widget, GdkInputSource source,
9695 gdouble x, gdouble y, gdouble pressure)
9698 GdkRectangle update_rect;
9702 case GDK_SOURCE_MOUSE:
9703 gc = widget->style->dark_gc[GTK_WIDGET_STATE (widget)];
9705 case GDK_SOURCE_PEN:
9706 gc = widget->style->black_gc;
9708 case GDK_SOURCE_ERASER:
9709 gc = widget->style->white_gc;
9712 gc = widget->style->light_gc[GTK_WIDGET_STATE (widget)];
9715 update_rect.x = x - 10 * pressure;
9716 update_rect.y = y - 10 * pressure;
9717 update_rect.width = 20 * pressure;
9718 update_rect.height = 20 * pressure;
9719 gdk_draw_rectangle (pixmap, gc, TRUE,
9720 update_rect.x, update_rect.y,
9721 update_rect.width, update_rect.height);
9722 gtk_widget_draw (widget, &update_rect);
9726 <sect2> Finding out more about a device
9729 As an example of how to find out more about a device, our program
9730 will print the name of the device that generates each button
9731 press. To find out the name of a device, we call the function:
9734 GList *gdk_input_list_devices (void);
9737 which returns a GList (a linked list type from the glib library)
9738 of GdkDeviceInfo structures. The GdkDeviceInfo strucure is defined
9742 struct _GdkDeviceInfo
9746 GdkInputSource source;
9756 Most of these fields are configuration information that you
9757 can ignore unless you are implemented XInput configuration
9758 saving. The we are interested in here is <tt/name/ which is
9759 simply the name that X assigns to the device. The other field
9760 that isn't configuration information is <tt/has_cursor/. If
9761 <tt/has_cursor/ is false, then we we need to draw our own
9762 cursor. But since we've specified <tt/GDK_EXTENSION_EVENTS_CURSOR/,
9763 we don't have to worry about this.
9766 Our <tt/print_button_press()/ function simply iterates through
9767 the returned list until it finds a match, then prints out
9768 the name of the device.
9772 print_button_press (guint32 deviceid)
9776 /* gdk_input_list_devices returns an internal list, so we shouldn't
9777 free it afterwards */
9778 tmp_list = gdk_input_list_devices();
9782 GdkDeviceInfo *info = (GdkDeviceInfo *)tmp_list->data;
9784 if (info->deviceid == deviceid)
9786 printf("Button press on device '%s'\n", info->name);
9790 tmp_list = tmp_list->next;
9795 That completes the changes to ``XInputize'' our program. As with
9796 the first version, the complete source is available at the location
9797 from which you got this tutorial, or from:
9799 <htmlurl url="http://www.msc.cornell.edu/~otaylor/gtk-gimp/tutorial"
9800 name="http://www.msc.cornell.edu/~otaylor/gtk-gimp/tutorial">
9803 <sect2> Further sophistications <label id="sec_Further_Sophistications">
9806 Although our program now supports XInput quite well, it lacks some
9807 features we would want in a full-featured application. First, the user
9808 probably doesn't want to have to configure their device each time they
9809 run the program, so we should allow them to save the device
9810 configuration. This is done by iterating through the return of
9811 <tt/gdk_input_list_devices()/ and writing out the configuration to a
9815 To restore the state next time the program is run, GDK provides
9816 functions to change device configuration:
9819 gdk_input_set_extension_events()
9820 gdk_input_set_source()
9821 gdk_input_set_mode()
9822 gdk_input_set_axes()
9826 (The list returned from <tt/gdk_input_list_devices()/ should not be
9827 modified directly.) An example of doing this can be found in the
9828 drawing program gsumi. (Available from <htmlurl
9829 url="http://www.msc.cornell.edu/~otaylor/gsumi/"
9830 name="http://www.msc.cornell.edu/~otaylor/gsumi/">) Eventually, it
9831 would be nice to have a standard way of doing this for all
9832 applications. This probably belongs at a slightly higher level than
9833 GTK, perhaps in the GNOME library.
9836 Another major ommission that we have mentioned above is the lack of
9837 cursor drawing. Platforms other than XFree86 currently do not allow
9838 simultaneously using a device as both the core pointer and directly by
9839 an application. See the <url
9840 url="http://www.msc.cornell.edu/~otaylor/xinput/XInput-HOWTO.html"
9841 name="XInput-HOWTO"> for more information about this. This means that
9842 applications that want to support the widest audience need to draw
9846 An application that draws it's own cursor needs to do two things:
9847 determine if the current device needs a cursor drawn or not, and
9848 determine if the current device is in proximity. (If the current
9849 device is a drawing tablet, it's a nice touch to make the cursor
9850 disappear when the stylus is lifted from the tablet. When the
9851 device is touching the stylus, that is called "in proximity.")
9852 The first is done by searching the device list, as we did
9853 to find out the device name. The second is achieved by selecting
9854 "proximity_out" events. An example of drawing one's own cursor is
9855 found in the 'testinput' program found in the GTK distribution.
9857 <!-- ***************************************************************** -->
9858 <sect>Tips For Writing GTK Applications
9859 <!-- ***************************************************************** -->
9862 This section is simply a gathering of wisdom, general style guidelines and hints to
9863 creating good GTK applications. It is totally useless right now cause it's
9864 only a topic sentence :)
9866 Use GNU autoconf and automake! They are your friends :) I am planning to
9867 make a quick intro on them here.
9869 <!-- ***************************************************************** -->
9871 <!-- ***************************************************************** -->
9874 This document, like so much other great software out there, was created for
9875 free by volunteers. If you are at all knowledgeable about any aspect of GTK
9876 that does not already have documentation, please consider contributing to
9879 If you do decide to contribute, please mail your text to Tony Gale,
9880 <tt><htmlurl url="mailto:gale@gtk.org"
9881 name="gale@gtk.org"></tt>. Also, be aware that the entirety of this
9882 document is free, and any addition by yourself must also be free. That is,
9883 people may use any portion of your examples in their programs, and copies
9884 of this document may be distributed at will etc.
9888 <!-- ***************************************************************** -->
9890 <!-- ***************************************************************** -->
9892 I would like to thank the following for their contributions to this text.
9895 <item>Bawer Dagdeviren, <tt><htmlurl url="mailto:chamele0n@geocities.com"
9896 name="chamele0n@geocities.com"></tt> for the menus tutorial.
9898 <item>Raph Levien, <tt><htmlurl url="mailto:raph@acm.org"
9899 name="raph@acm.org"></tt>
9900 for hello world ala GTK, widget packing, and general all around wisdom.
9901 He's also generously donated a home for this tutorial.
9903 <item>Peter Mattis, <tt><htmlurl url="mailto:petm@xcf.berkeley.edu"
9904 name="petm@xcf.berkeley.edu"></tt> for the simplest GTK program..
9905 and the ability to make it :)
9907 <item>Werner Koch <tt><htmlurl url="mailto:werner.koch@guug.de"
9908 name="werner.koch@guug.de"></tt> for converting the original plain text to
9909 SGML, and the widget class hierarchy.
9911 <item>Mark Crichton <tt><htmlurl url="mailto:crichton@expert.cc.purdue.edu"
9912 name="crichton@expert.cc.purdue.edu"></tt> for the menu factory code, and
9913 the table packing tutorial.
9915 <item>Owen Taylor <tt><htmlurl url="mailto:owt1@cornell.edu"
9916 name="owt1@cornell.edu"></tt> for the EventBox widget section (and
9917 the patch to the distro). He's also responsible for the selections code and
9918 tutorial, as well as the sections on writing your own GTK widgets, and the
9919 example application. Thanks a lot Owen for all you help!
9921 <item>Mark VanderBoom <tt><htmlurl url="mailto:mvboom42@calvin.edu"
9922 name="mvboom42@calvin.edu"></tt> for his wonderful work on the Notebook,
9923 Progress Bar, Dialogs, and File selection widgets. Thanks a lot Mark!
9924 You've been a great help.
9926 <item>Tim Janik <tt><htmlurl url="mailto:timj@psynet.net"
9927 name="timj@psynet.net"></tt> for his great job on the Lists Widget.
9930 <item>Rajat Datta <tt><htmlurl url="mailto:rajat@ix.netcom.com"
9931 name="rajat@ix.netcom.com"</tt> for the excellent job on the Pixmap tutorial.
9933 <item>Michael K. Johnson <tt><htmlurl url="mailto:johnsonm@redhat.com"
9934 name="johnsonm@redhat.com"></tt> for info and code for popup menus.
9938 And to all of you who commented and helped refine this document.
9942 <!-- ***************************************************************** -->
9943 <sect> Tutorial Copyright and Permissions Notice
9944 <!-- ***************************************************************** -->
9947 The GTK Tutorial is Copyright (C) 1997 Ian Main.
9949 Copyright (C) 1998 Tony Gale.
9951 Permission is granted to make and distribute verbatim copies of this
9952 manual provided the copyright notice and this permission notice are
9953 preserved on all copies.
9954 <P>Permission is granted to copy and distribute modified versions of
9955 this document under the conditions for verbatim copying, provided that
9956 this copyright notice is included exactly as in the original,
9957 and that the entire resulting derived work is distributed under
9958 the terms of a permission notice identical to this one.
9959 <P>Permission is granted to copy and distribute translations of this
9960 document into another language, under the above conditions for modified
9962 <P>If you are intending to incorporate this document into a published
9963 work, please contact the maintainer, and we will make an effort
9964 to ensure that you have the most up to date information available.
9965 <P>There is no guarentee that this document lives up to its intended
9966 purpose. This is simply provided as a free resource. As such,
9967 the authors and maintainers of the information provided within can
9968 not make any guarentee that the information is even accurate.