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 */
1432 #include <gtk/gtk.h>
1435 * the data passed to this function is printed to stdout */
1436 void callback (GtkWidget *widget, gpointer data)
1438 g_print ("Hello again - %s was pressed\n", (char *) data);
1441 /* this callback quits the program */
1442 void delete_event (GtkWidget *widget, GdkEvent *event, gpointer data)
1447 int main (int argc, char *argv[])
1453 gtk_init (&argc, &argv);
1455 /* create a new window */
1456 window = gtk_window_new (GTK_WINDOW_TOPLEVEL);
1458 /* set the window title */
1459 gtk_window_set_title (GTK_WINDOW (window), "Table");
1461 /* set a handler for delete_event that immediately
1463 gtk_signal_connect (GTK_OBJECT (window), "delete_event",
1464 GTK_SIGNAL_FUNC (delete_event), NULL);
1466 /* sets the border width of the window. */
1467 gtk_container_border_width (GTK_CONTAINER (window), 20);
1469 /* create a 2x2 table */
1470 table = gtk_table_new (2, 2, TRUE);
1472 /* put the table in the main window */
1473 gtk_container_add (GTK_CONTAINER (window), table);
1475 /* create first button */
1476 button = gtk_button_new_with_label ("button 1");
1478 /* when the button is clicked, we call the "callback" function
1479 * with a pointer to "button 1" as it's argument */
1480 gtk_signal_connect (GTK_OBJECT (button), "clicked",
1481 GTK_SIGNAL_FUNC (callback), (gpointer) "button 1");
1484 /* insert button 1 into the upper left quadrant of the table */
1485 gtk_table_attach_defaults (GTK_TABLE(table), button, 0, 1, 0, 1);
1487 gtk_widget_show (button);
1489 /* create second button */
1491 button = gtk_button_new_with_label ("button 2");
1493 /* when the button is clicked, we call the "callback" function
1494 * with a pointer to "button 2" as it's argument */
1495 gtk_signal_connect (GTK_OBJECT (button), "clicked",
1496 GTK_SIGNAL_FUNC (callback), (gpointer) "button 2");
1497 /* insert button 2 into the upper right quadrant of the table */
1498 gtk_table_attach_defaults (GTK_TABLE(table), button, 1, 2, 0, 1);
1500 gtk_widget_show (button);
1502 /* create "Quit" button */
1503 button = gtk_button_new_with_label ("Quit");
1505 /* when the button is clicked, we call the "delete_event" function
1506 * and the program exits */
1507 gtk_signal_connect (GTK_OBJECT (button), "clicked",
1508 GTK_SIGNAL_FUNC (delete_event), NULL);
1510 /* insert the quit button into the both
1511 * lower quadrants of the table */
1512 gtk_table_attach_defaults (GTK_TABLE(table), button, 0, 2, 1, 2);
1514 gtk_widget_show (button);
1516 gtk_widget_show (table);
1517 gtk_widget_show (window);
1526 <!-- ***************************************************************** -->
1527 <sect>Widget Overview
1528 <!-- ***************************************************************** -->
1530 The general steps to creating a widget in GTK are:
1532 <item> gtk_*_new - one of various functions to create a new widget. These
1533 are all detailed in this section.
1535 <item> Connect all signals and events we wish to use to the
1536 appropriate handlers.
1538 <item> Set the attributes of the widget.
1540 <item> Pack the widget into a container using the appropriate call such as
1541 gtk_container_add() or gtk_box_pack_start().
1543 <item> gtk_widget_show() the widget.
1546 gtk_widget_show() lets GTK know that we are done setting the attributes
1547 of the widget, and it is ready to be displayed. You may also use
1548 gtk_widget_hide to make it disappear again. The order in which you
1549 show the widgets is not important, but I suggest showing the window
1550 last so the whole window pops up at once rather than seeing the individual
1551 widgets come up on the screen as they're formed. The children of a widget
1552 (a window is a widget too) will not be displayed until the window itself
1553 is shown using the gtk_widget_show() function.
1555 <!-- ----------------------------------------------------------------- -->
1558 You'll notice as you go on, that GTK uses a type casting system. This is
1559 always done using macros that both test the ability to cast the given item,
1560 and perform the cast. Some common ones you will see are:
1563 <item> GTK_WIDGET(widget)
1564 <item> GTK_OBJECT(object)
1565 <item> GTK_SIGNAL_FUNC(function)
1566 <item> GTK_CONTAINER(container)
1567 <item> GTK_WINDOW(window)
1571 These are all used to cast arguments in functions. You'll see them in the
1572 examples, and can usually tell when to use them simply by looking at the
1573 function's declaration.
1575 As you can see below in the class hierarchy, all GtkWidgets are derived from
1576 the GtkObject base class. This means you can use a widget in any place the
1577 function asks for an object - simply use the GTK_OBJECT() macro.
1582 gtk_signal_connect( GTK_OBJECT(button), "clicked",
1583 GTK_SIGNAL_FUNC(callback_function), callback_data);
1586 This casts the button into an object, and provides a cast for the function
1587 pointer to the callback.
1589 Many widgets are also containers. If you look in the class hierarchy below,
1590 you'll notice that many widgets derive from the GtkContainer class. Any one
1591 of these widgets may be used with the GTK_CONTAINER macro to pass them to
1592 functions that ask for containers.
1594 Unfortunately, these macros are not extensively covered in the tutorial, but I
1595 recomend taking a look through the GTK header files. It can be very
1596 educational. In fact, it's not difficult to learn how a widget works just
1597 by looking at the function declarations.
1599 <!-- ----------------------------------------------------------------- -->
1600 <sect1>Widget Hierarchy
1602 For your reference, here is the class hierarchy tree used to implement widgets.
1615 | | | `GtkAspectFrame
1620 | | | | `GtkCheckMenuItem
1621 | | | | `GtkRadioMenuItem
1625 | | +GtkColorSelectionDialog
1627 | | | `GtkInputDialog
1628 | | `GtkFileSelection
1631 | | | +GtkHButtonBox
1632 | | | `GtkVButtonBox
1637 | | +GtkColorSelection
1641 | | `GtkToggleButton
1655 | +GtkScrolledWindow
1688 <!-- ----------------------------------------------------------------- -->
1689 <sect1>Widgets Without Windows
1691 The following widgets do not have an associated window. If you want to
1692 capture events, you'll have to use the GtkEventBox. See the section on
1693 <ref id="sec_The_EventBox_Widget" name="The EventBox Widget">
1715 We'll further our exploration of GTK by examining each widget in turn,
1716 creating a few simple functions to display them. Another good source is
1717 the testgtk.c program that comes with GTK. It can be found in
1720 <!-- ***************************************************************** -->
1721 <sect>The Button Widget
1722 <!-- ***************************************************************** -->
1724 <!-- ----------------------------------------------------------------- -->
1725 <sect1>Normal Buttons
1727 We've almost seen all there is to see of the button widget. It's pretty
1728 simple. There is however two ways to create a button. You can use the
1729 gtk_button_new_with_label() to create a button with a label, or use
1730 gtk_button_new() to create a blank button. It's then up to you to pack a
1731 label or pixmap into this new button. To do this, create a new box, and
1732 then pack your objects into this box using the usual gtk_box_pack_start,
1733 and then use gtk_container_add to pack the box into the button.
1735 Here's an example of using gtk_button_new to create a button with a
1736 picture and a label in it. I've broken the code to create a box up from
1737 the rest so you can use it in your programs.
1740 /* example-start buttons buttons.c */
1742 #include <gtk/gtk.h>
1744 /* create a new hbox with an image and a label packed into it
1745 * and return the box.. */
1747 GtkWidget *xpm_label_box (GtkWidget *parent, gchar *xpm_filename, gchar *label_text)
1751 GtkWidget *pixmapwid;
1756 /* create box for xpm and label */
1757 box1 = gtk_hbox_new (FALSE, 0);
1758 gtk_container_border_width (GTK_CONTAINER (box1), 2);
1760 /* get style of button.. I assume it's to get the background color.
1761 * if someone knows the real reason, please enlighten me. */
1762 style = gtk_widget_get_style(parent);
1764 /* now on to the xpm stuff.. load xpm */
1765 pixmap = gdk_pixmap_create_from_xpm (parent->window, &mask,
1766 &style->bg[GTK_STATE_NORMAL],
1768 pixmapwid = gtk_pixmap_new (pixmap, mask);
1770 /* create label for button */
1771 label = gtk_label_new (label_text);
1773 /* pack the pixmap and label into the box */
1774 gtk_box_pack_start (GTK_BOX (box1),
1775 pixmapwid, FALSE, FALSE, 3);
1777 gtk_box_pack_start (GTK_BOX (box1), label, FALSE, FALSE, 3);
1779 gtk_widget_show(pixmapwid);
1780 gtk_widget_show(label);
1785 /* our usual callback function */
1786 void callback (GtkWidget *widget, gpointer data)
1788 g_print ("Hello again - %s was pressed\n", (char *) data);
1792 int main (int argc, char *argv[])
1794 /* GtkWidget is the storage type for widgets */
1799 gtk_init (&argc, &argv);
1801 /* create a new window */
1802 window = gtk_window_new (GTK_WINDOW_TOPLEVEL);
1804 gtk_window_set_title (GTK_WINDOW (window), "Pixmap'd Buttons!");
1806 /* It's a good idea to do this for all windows. */
1807 gtk_signal_connect (GTK_OBJECT (window), "destroy",
1808 GTK_SIGNAL_FUNC (gtk_exit), NULL);
1810 gtk_signal_connect (GTK_OBJECT (window), "delete_event",
1811 GTK_SIGNAL_FUNC (gtk_exit), NULL);
1814 /* sets the border width of the window. */
1815 gtk_container_border_width (GTK_CONTAINER (window), 10);
1816 gtk_widget_realize(window);
1818 /* create a new button */
1819 button = gtk_button_new ();
1821 /* You should be getting used to seeing most of these functions by now */
1822 gtk_signal_connect (GTK_OBJECT (button), "clicked",
1823 GTK_SIGNAL_FUNC (callback), (gpointer) "cool button");
1825 /* this calls our box creating function */
1826 box1 = xpm_label_box(window, "info.xpm", "cool button");
1828 /* pack and show all our widgets */
1829 gtk_widget_show(box1);
1831 gtk_container_add (GTK_CONTAINER (button), box1);
1833 gtk_widget_show(button);
1835 gtk_container_add (GTK_CONTAINER (window), button);
1837 gtk_widget_show (window);
1839 /* rest in gtk_main and wait for the fun to begin! */
1847 The xpm_label_box function could be used to pack xpm's and labels into any
1848 widget that can be a container.
1850 The Buton widget has the following signals:
1860 <!-- ----------------------------------------------------------------- -->
1861 <sect1> Toggle Buttons
1863 Toggle buttons are derived from normal buttons and are very similar, except
1864 they will always be in one of two states, alternated by a click. They may
1865 be depressed, and when you click again, they will pop back up. Click again,
1866 and they will pop back down.
1868 Toggle buttons are the basis for check buttons and radio buttons, as such,
1869 many of the calls used for toggle buttons are inherited by radio and check
1870 buttons. I will point these out when we come to them.
1872 Creating a new toggle button:
1875 GtkWidget *gtk_toggle_button_new( void );
1877 GtkWidget *gtk_toggle_button_new_with_label( gchar *label );
1880 As you can imagine, these work identically to the normal button widget
1881 calls. The first creates a blank toggle button, and the second, a button
1882 with a label widget already packed into it.
1884 To retrieve the state of the toggle widget, including radio and check
1885 buttons, we use a macro as shown in our example below. This tests the state
1886 of the toggle in a callback. The signal of interest emitted to us by toggle
1887 buttons (the toggle button, check button, and radio button widgets), is the
1888 "toggled" signal. To check the state of these buttons, set up a signal
1889 handler to catch the toggled signal, and use the macro to determine it's
1890 state. The callback will look something like:
1893 void toggle_button_callback (GtkWidget *widget, gpointer data)
1895 if (GTK_TOGGLE_BUTTON (widget)->active)
1897 /* If control reaches here, the toggle button is down */
1901 /* If control reaches here, the toggle button is up */
1907 void gtk_toggle_button_set_state( GtkToggleButton *toggle_button,
1911 The above call can be used to set the state of the toggle button, and it's
1912 children the radio and check buttons. Passing in your created button as
1913 the first argument, and a TRUE or FALSE for the second state argument to
1914 specify whether it should be up (released) or down (depressed). Default
1917 Note that when you use the gtk_toggle_button_set_state() function, and the
1918 state is actually changed, it causes the "clicked" signal to be emitted
1922 void gtk_toggle_button_toggled (GtkToggleButton *toggle_button);
1925 This simply toggles the button, and emits the "toggled" signal.
1927 <!-- ----------------------------------------------------------------- -->
1928 <sect1> Check Buttons
1930 Check buttons inherent many properties and functions from the the toggle
1931 buttons above, but look a little different. Rather than being buttons with
1932 text inside them, they are small squares with the text to the right of
1933 them. These are often used for toggling options on and off in applications.
1935 The two creation functions are similar to those of the normal button.
1938 GtkWidget *gtk_check_button_new( void );
1940 GtkWidget *gtk_check_button_new_with_label ( gchar *label );
1943 The new_with_label function creates a check button with a label beside it.
1945 Checking the state of the check button is identical to that of the toggle
1948 <!-- ----------------------------------------------------------------- -->
1949 <sect1> Radio Buttons
1951 Radio buttons are similar to check buttons except they are grouped so that
1952 only one may be selected/depressed at a time. This is good for places in
1953 your application where you need to select from a short list of options.
1955 Creating a new radio button is done with one of these calls:
1958 GtkWidget *gtk_radio_button_new( GSList *group );
1960 GtkWidget *gtk_radio_button_new_with_label( GSList *group,
1964 You'll notice the extra argument to these calls. They require a group to
1965 perform they're duty properly. The first call should pass NULL as the first
1966 argument. Then create a group using:
1969 GSList *gtk_radio_button_group( GtkRadioButton *radio_button );
1972 The important thing to remember is that gtk_radio_button_group must be
1973 called for each new button added to the group, with the previous button
1974 passed in as an argument. The result is then passed into the call to
1975 gtk_radio_button_new or gtk_radio_button_new_with_label. This allows a
1976 chain of buttons to be established. The example below should make this
1979 It is also a good idea to explicitly set which button should be the
1980 default depressed button with:
1983 void gtk_toggle_button_set_state( GtkToggleButton *toggle_button,
1987 This is described in the section on toggle buttons, and works in exactly the
1990 The following example creates a radio button group with three buttons.
1993 /* example-start radiobuttons radiobuttons.c */
1995 #include <gtk/gtk.h>
1998 void close_application( GtkWidget *widget, GdkEvent *event, gpointer data ) {
2002 main(int argc,char *argv[])
2004 static GtkWidget *window = NULL;
2008 GtkWidget *separator;
2011 gtk_init(&argc,&argv);
2012 window = gtk_window_new (GTK_WINDOW_TOPLEVEL);
2014 gtk_signal_connect (GTK_OBJECT (window), "delete_event",
2015 GTK_SIGNAL_FUNC(close_application),
2018 gtk_window_set_title (GTK_WINDOW (window), "radio buttons");
2019 gtk_container_border_width (GTK_CONTAINER (window), 0);
2021 box1 = gtk_vbox_new (FALSE, 0);
2022 gtk_container_add (GTK_CONTAINER (window), box1);
2023 gtk_widget_show (box1);
2025 box2 = gtk_vbox_new (FALSE, 10);
2026 gtk_container_border_width (GTK_CONTAINER (box2), 10);
2027 gtk_box_pack_start (GTK_BOX (box1), box2, TRUE, TRUE, 0);
2028 gtk_widget_show (box2);
2030 button = gtk_radio_button_new_with_label (NULL, "button1");
2031 gtk_box_pack_start (GTK_BOX (box2), button, TRUE, TRUE, 0);
2032 gtk_widget_show (button);
2034 group = gtk_radio_button_group (GTK_RADIO_BUTTON (button));
2035 button = gtk_radio_button_new_with_label(group, "button2");
2036 gtk_toggle_button_set_state (GTK_TOGGLE_BUTTON (button), TRUE);
2037 gtk_box_pack_start (GTK_BOX (box2), button, TRUE, TRUE, 0);
2038 gtk_widget_show (button);
2040 group = gtk_radio_button_group (GTK_RADIO_BUTTON (button));
2041 button = gtk_radio_button_new_with_label(group, "button3");
2042 gtk_box_pack_start (GTK_BOX (box2), button, TRUE, TRUE, 0);
2043 gtk_widget_show (button);
2045 separator = gtk_hseparator_new ();
2046 gtk_box_pack_start (GTK_BOX (box1), separator, FALSE, TRUE, 0);
2047 gtk_widget_show (separator);
2049 box2 = gtk_vbox_new (FALSE, 10);
2050 gtk_container_border_width (GTK_CONTAINER (box2), 10);
2051 gtk_box_pack_start (GTK_BOX (box1), box2, FALSE, TRUE, 0);
2052 gtk_widget_show (box2);
2054 button = gtk_button_new_with_label ("close");
2055 gtk_signal_connect_object (GTK_OBJECT (button), "clicked",
2056 GTK_SIGNAL_FUNC(close_application),
2057 GTK_OBJECT (window));
2058 gtk_box_pack_start (GTK_BOX (box2), button, TRUE, TRUE, 0);
2059 GTK_WIDGET_SET_FLAGS (button, GTK_CAN_DEFAULT);
2060 gtk_widget_grab_default (button);
2061 gtk_widget_show (button);
2062 gtk_widget_show (window);
2070 You can shorten this slightly by using the following syntax, which
2071 removes the need for a variable to hold the list of buttons:
2074 button2 = gtk_radio_button_new_with_label(
2075 gtk_radio_button_group (GTK_RADIO_BUTTON (button1)),
2079 <!-- TODO: checout out gtk_radio_button_new_from_widget function - TRG -->
2081 <!-- ***************************************************************** -->
2082 <sect> Miscallaneous Widgets
2083 <!-- ***************************************************************** -->
2085 <!-- ----------------------------------------------------------------- -->
2088 Labels are used a lot in GTK, and are relatively simple. Labels emit no
2089 signals as they do not have an associated X window. If you need to catch
2090 signals, or do clipping, use the EventBox widget.
2092 To create a new label, use:
2095 GtkWidget *gtk_label_new( char *str );
2098 Where the sole argument is the string you wish the label to display.
2100 To change the label's text after creation, use the function:
2103 void gtk_label_set( GtkLabel *label,
2107 Where the first argument is the label you created previously (cast using
2108 the GTK_LABEL() macro), and the second is the new string.
2110 The space needed for the new string will be automatically adjusted if needed.
2112 To retrieve the current string, use:
2115 void gtk_label_get( GtkLabel *label,
2119 Where the first arguement is the label you've created, and the second, the
2120 return for the string.
2122 <!-- ----------------------------------------------------------------- -->
2123 <sect1>The Tooltips Widget
2125 These are the little text strings that pop up when you leave your pointer
2126 over a button or other widget for a few seconds. They are easy to use, so I
2127 will just explain them without giving an example. If you want to see some
2128 code, take a look at the testgtk.c program distributed with GDK.
2130 Some widgets (such as the label) will not work with tooltips.
2132 The first call you will use to create a new tooltip. You only need to do
2133 this once in a given function. The <tt/GtkTooltip/ object this function
2134 returns can be used to create multiple tooltips.
2137 GtkTooltips *gtk_tooltips_new( void );
2140 Once you have created a new tooltip, and the widget you wish to use it on,
2141 simply use this call to set it:
2144 void gtk_tooltips_set_tip( GtkTooltips *tooltips,
2146 const gchar *tip_text,
2147 const gchar *tip_private );
2150 The first argument is the tooltip you've already created, followed by the
2151 widget you wish to have this tooltip pop up for, and the text you wish it to
2152 say. The last argument is a text string that can be used as an identifier when using
2153 GtkTipsQuery to implement context sensitive help. For now, you can set
2155 <!-- TODO: sort out what how to do the context sensitive help -->
2157 Here's a short example:
2160 GtkTooltips *tooltips;
2163 tooltips = gtk_tooltips_new ();
2164 button = gtk_button_new_with_label ("button 1");
2166 gtk_tooltips_set_tip (tooltips, button, "This is button 1", NULL);
2169 There are other calls that can be used with tooltips. I will just
2170 list them with a brief description of what they do.
2173 void gtk_tooltips_enable( GtkTooltips *tooltips );
2176 Enable a disabled set of tooltips.
2179 void gtk_tooltips_disable( GtkTooltips *tooltips );
2182 Disable an enabled set of tooltips.
2185 void gtk_tooltips_set_delay( GtkTooltips *tooltips,
2190 Sets how many milliseconds you have to hold your pointer over the
2191 widget before the tooltip will pop up. The default is 1000 milliseconds
2195 void gtk_tooltips_set_colors( GtkTooltips *tooltips,
2196 GdkColor *background,
2197 GdkColor *foreground );
2200 Set the foreground and background color of the tooltips. Again, I have no
2201 idea how to specify the colors.
2203 And that's all the functions associated with tooltips. More than you'll
2204 ever want to know :)
2206 <!-- ----------------------------------------------------------------- -->
2207 <sect1> Progress Bars
2209 Progress bars are used to show the status of an operation. They are pretty
2210 easy to use, as you will see with the code below. But first lets start out
2211 with the call to create a new progress bar.
2214 GtkWidget *gtk_progress_bar_new( void );
2217 Now that the progress bar has been created we can use it.
2220 void gtk_progress_bar_update( GtkProgressBar *pbar,
2221 gfloat percentage );
2224 The first argument is the progress bar you wish to operate on, and the second
2225 argument is the amount 'completed', meaning the amount the progress bar has
2226 been filled from 0-100%. This is passed to the function as a real number
2227 ranging from 0 to 1.
2229 Progress Bars are usually used with timeouts or other such functions (see
2230 section on <ref id="sec_timeouts" name="Timeouts, I/O and Idle Functions">)
2231 to give the illusion of multitasking. All will employ
2232 the gtk_progress_bar_update function in the same manner.
2234 Here is an example of the progress bar, updated using timeouts. This
2235 code also shows you how to reset the Progress Bar.
2238 /* example-start progressbar progressbar.c */
2240 #include <gtk/gtk.h>
2242 static int ptimer = 0;
2245 /* This function increments and updates the progress bar, it also resets
2246 the progress bar if pstat is FALSE */
2247 gint progress (gpointer data)
2251 /* get the current value of the progress bar */
2252 pvalue = GTK_PROGRESS_BAR (data)->percentage;
2254 if ((pvalue >= 1.0) || (pstat == FALSE)) {
2260 gtk_progress_bar_update (GTK_PROGRESS_BAR (data), pvalue);
2265 /* This function signals a reset of the progress bar */
2266 void progress_r (void)
2271 void destroy (GtkWidget *widget, GdkEvent *event, gpointer data)
2276 int main (int argc, char *argv[])
2284 gtk_init (&argc, &argv);
2286 window = gtk_window_new (GTK_WINDOW_TOPLEVEL);
2288 gtk_signal_connect (GTK_OBJECT (window), "delete_event",
2289 GTK_SIGNAL_FUNC (destroy), NULL);
2291 gtk_container_border_width (GTK_CONTAINER (window), 10);
2293 table = gtk_table_new(3,2,TRUE);
2294 gtk_container_add (GTK_CONTAINER (window), table);
2296 label = gtk_label_new ("Progress Bar Example");
2297 gtk_table_attach_defaults(GTK_TABLE(table), label, 0,2,0,1);
2298 gtk_widget_show(label);
2300 /* Create a new progress bar, pack it into the table, and show it */
2301 pbar = gtk_progress_bar_new ();
2302 gtk_table_attach_defaults(GTK_TABLE(table), pbar, 0,2,1,2);
2303 gtk_widget_show (pbar);
2305 /* Set the timeout to handle automatic updating of the progress bar */
2306 ptimer = gtk_timeout_add (100, progress, pbar);
2308 /* This button signals the progress bar to be reset */
2309 button = gtk_button_new_with_label ("Reset");
2310 gtk_signal_connect (GTK_OBJECT (button), "clicked",
2311 GTK_SIGNAL_FUNC (progress_r), NULL);
2312 gtk_table_attach_defaults(GTK_TABLE(table), button, 0,1,2,3);
2313 gtk_widget_show(button);
2315 button = gtk_button_new_with_label ("Cancel");
2316 gtk_signal_connect (GTK_OBJECT (button), "clicked",
2317 GTK_SIGNAL_FUNC (destroy), NULL);
2319 gtk_table_attach_defaults(GTK_TABLE(table), button, 1,2,2,3);
2320 gtk_widget_show (button);
2322 gtk_widget_show(table);
2323 gtk_widget_show(window);
2332 In this small program there are four areas that concern the general operation
2333 of Progress Bars, we will look at them in the order they are called.
2336 pbar = gtk_progress_bar_new ();
2339 This code creates a new progress bar, called pbar.
2342 ptimer = gtk_timeout_add (100, progress, pbar);
2345 This code uses timeouts to enable a constant time interval, timeouts are
2346 not necessary in the use of Progress Bars.
2349 pvalue = GTK_PROGRESS_BAR (data)->percentage;
2352 This code assigns the current value of the percentage bar to pvalue.
2355 gtk_progress_bar_update (GTK_PROGRESS_BAR (data), pvalue);
2358 Finally, this code updates the progress bar with the value of pvalue
2360 And that is all there is to know about Progress Bars, enjoy.
2362 <!-- ----------------------------------------------------------------- -->
2365 The Dialog widget is very simple, and is actually just a window with a few
2366 things pre-packed into it for you. The structure for a Dialog is:
2374 GtkWidget *action_area;
2378 So you see, it simply creates a window, and then packs a vbox into the top,
2379 then a seperator, and then an hbox for the "action_area".
2381 The Dialog widget can be used for pop-up messages to the user, and
2382 other similar tasks. It is really basic, and there is only one
2383 function for the dialog box, which is:
2386 GtkWidget *gtk_dialog_new( void );
2389 So to create a new dialog box, use,
2393 window = gtk_dialog_new ();
2396 This will create the dialog box, and it is now up to you to use it.
2397 you could pack a button in the action_area by doing something like this:
2401 gtk_box_pack_start (GTK_BOX (GTK_DIALOG (window)->action_area), button,
2403 gtk_widget_show (button);
2406 And you could add to the vbox area by packing, for instance, a label
2407 in it, try something like this:
2410 label = gtk_label_new ("Dialogs are groovy");
2411 gtk_box_pack_start (GTK_BOX (GTK_DIALOG (window)->vbox), label, TRUE,
2413 gtk_widget_show (label);
2416 As an example in using the dialog box, you could put two buttons in
2417 the action_area, a Cancel button and an Ok button, and a label in the vbox
2418 area, asking the user a question or giving an error etc. Then you could
2419 attach a different signal to each of the buttons and perform the
2420 operation the user selects.
2422 If the simple functionality provided by the default vertical and
2423 horizontal boxes in the two areas don't give you enough control for your
2424 application, then you can simply pack another layout widget into the boxes
2425 provided. For example, you could pack a table into the vertical box.
2427 <!-- ----------------------------------------------------------------- -->
2430 Pixmaps are data structures that contain pictures. These pictures can be
2431 used in various places, but most visibly as icons on the X-Windows desktop,
2432 or as cursors. A bitmap is a 2-color pixmap.
2434 To use pixmaps in GTK, we must first build a GdkPixmap structure using
2435 routines from the GDK layer. Pixmaps can either be created from in-memory
2436 data, or from data read from a file. We'll go through each of the calls
2440 GdkPixmap *gdk_bitmap_create_from_data( GdkWindow *window,
2446 This routine is used to create a single-plane pixmap (2 colors) from data in
2447 memory. Each bit of the data represents whether that pixel is off or on.
2448 Width and height are in pixels. The GdkWindow pointer is to the current
2449 window, since a pixmap resources are meaningful only in the context of the
2450 screen where it is to be displayed.
2453 GdkPixmap *gdk_pixmap_create_from_data( GdkWindow *window,
2462 This is used to create a pixmap of the given depth (number of colors) from
2463 the bitmap data specified. <tt/fg/ and <tt/bg/ are the foreground and
2464 background color to use.
2467 GdkPixmap *gdk_pixmap_create_from_xpm( GdkWindow *window,
2469 GdkColor *transparent_color,
2470 const gchar *filename );
2473 XPM format is a readable pixmap representation for the X Window System. It
2474 is widely used and many different utilities are available for creating image
2475 files in this format. The file specified by filename must contain an image
2476 in that format and it is loaded into the pixmap structure. The mask specifies
2477 which bits of the pixmap are opaque. All other bits are colored using the
2478 color specified by transparent_color. An example using this follows below.
2481 GdkPixmap *gdk_pixmap_create_from_xpm_d( GdkWindow *window,
2483 GdkColor *transparent_color,
2487 Small images can be incorporated into a program as data in the XPM format.
2488 A pixmap is created using this data, instead of reading it from a file.
2489 An example of such data is
2493 static const char * xpm_data[] = {
2496 ". c #000000000000",
2497 "X c #FFFFFFFFFFFF",
2516 When we're done using a pixmap and not likely to reuse it again soon,
2517 it is a good idea to release the resource using gdk_pixmap_unref(). Pixmaps
2518 should be considered a precious resource.
2520 Once we've created a pixmap, we can display it as a GTK widget. We must
2521 create a pixmap widget to contain the GDK pixmap. This is done using
2524 GtkWidget *gtk_pixmap_new( GdkPixmap *pixmap,
2528 The other pixmap widget calls are
2531 guint gtk_pixmap_get_type( void );
2533 void gtk_pixmap_set( GtkPixmap *pixmap,
2537 void gtk_pixmap_get( GtkPixmap *pixmap,
2542 gtk_pixmap_set is used to change the pixmap that the widget is currently
2543 managing. Val is the pixmap created using GDK.
2545 The following is an example of using a pixmap in a button.
2548 /* example-start pixmap pixmap.c */
2550 #include <gtk/gtk.h>
2553 /* XPM data of Open-File icon */
2554 static const char * xpm_data[] = {
2557 ". c #000000000000",
2558 "X c #FFFFFFFFFFFF",
2577 /* when invoked (via signal delete_event), terminates the application.
2579 void close_application( GtkWidget *widget, GdkEvent *event, gpointer data ) {
2584 /* is invoked when the button is clicked. It just prints a message.
2586 void button_clicked( GtkWidget *widget, gpointer data ) {
2587 printf( "button clicked\n" );
2590 int main( int argc, char *argv[] )
2592 /* GtkWidget is the storage type for widgets */
2593 GtkWidget *window, *pixmapwid, *button;
2598 /* create the main window, and attach delete_event signal to terminating
2600 gtk_init( &argc, &argv );
2601 window = gtk_window_new( GTK_WINDOW_TOPLEVEL );
2602 gtk_signal_connect( GTK_OBJECT (window), "delete_event",
2603 GTK_SIGNAL_FUNC (close_application), NULL );
2604 gtk_container_border_width( GTK_CONTAINER (window), 10 );
2605 gtk_widget_show( window );
2607 /* now for the pixmap from gdk */
2608 style = gtk_widget_get_style( window );
2609 pixmap = gdk_pixmap_create_from_xpm_d( window->window, &mask,
2610 &style->bg[GTK_STATE_NORMAL],
2611 (gchar **)xpm_data );
2613 /* a pixmap widget to contain the pixmap */
2614 pixmapwid = gtk_pixmap_new( pixmap, mask );
2615 gtk_widget_show( pixmapwid );
2617 /* a button to contain the pixmap widget */
2618 button = gtk_button_new();
2619 gtk_container_add( GTK_CONTAINER(button), pixmapwid );
2620 gtk_container_add( GTK_CONTAINER(window), button );
2621 gtk_widget_show( button );
2623 gtk_signal_connect( GTK_OBJECT(button), "clicked",
2624 GTK_SIGNAL_FUNC(button_clicked), NULL );
2626 /* show the window */
2634 To load a file from an XPM data file called icon0.xpm in the current
2635 directory, we would have created the pixmap thus
2638 /* load a pixmap from a file */
2639 pixmap = gdk_pixmap_create_from_xpm( window->window, &mask,
2640 &style->bg[GTK_STATE_NORMAL],
2642 pixmapwid = gtk_pixmap_new( pixmap, mask );
2643 gtk_widget_show( pixmapwid );
2644 gtk_container_add( GTK_CONTAINER(window), pixmapwid );
2647 A disadvantage of using pixmaps is that the displayed object is always
2648 rectangular, regardless of the image. We would like to create desktops
2649 and applications with icons that have more natural shapes. For example,
2650 for a game interface, we would like to have round buttons to push. The
2651 way to do this is using shaped windows.
2653 A shaped window is simply a pixmap where the background pixels are
2654 transparent. This way, when the background image is multi-colored, we
2655 don't overwrite it with a rectangular, non-matching border around our
2656 icon. The following example displays a full wheelbarrow image on the
2660 /* example-start wheelbarrow wheelbarrow.c */
2662 #include <gtk/gtk.h>
2665 static char * WheelbarrowFull_xpm[] = {
2668 ". c #DF7DCF3CC71B",
2669 "X c #965875D669A6",
2670 "o c #71C671C671C6",
2671 "O c #A699A289A699",
2672 "+ c #965892489658",
2673 "@ c #8E38410330C2",
2674 "# c #D75C7DF769A6",
2675 "$ c #F7DECF3CC71B",
2676 "% c #96588A288E38",
2677 "& c #A69992489E79",
2678 "* c #8E3886178E38",
2679 "= c #104008200820",
2680 "- c #596510401040",
2681 "; c #C71B30C230C2",
2682 ": c #C71B9A699658",
2683 "> c #618561856185",
2684 ", c #20811C712081",
2685 "< c #104000000000",
2686 "1 c #861720812081",
2687 "2 c #DF7D4D344103",
2688 "3 c #79E769A671C6",
2689 "4 c #861782078617",
2690 "5 c #41033CF34103",
2691 "6 c #000000000000",
2692 "7 c #49241C711040",
2693 "8 c #492445144924",
2694 "9 c #082008200820",
2695 "0 c #69A618611861",
2696 "q c #B6DA71C65144",
2697 "w c #410330C238E3",
2698 "e c #CF3CBAEAB6DA",
2699 "r c #71C6451430C2",
2700 "t c #EFBEDB6CD75C",
2701 "y c #28A208200820",
2702 "u c #186110401040",
2703 "i c #596528A21861",
2704 "p c #71C661855965",
2705 "a c #A69996589658",
2706 "s c #30C228A230C2",
2707 "d c #BEFBA289AEBA",
2708 "f c #596545145144",
2709 "g c #30C230C230C2",
2710 "h c #8E3882078617",
2711 "j c #208118612081",
2712 "k c #38E30C300820",
2713 "l c #30C2208128A2",
2714 "z c #38E328A238E3",
2715 "x c #514438E34924",
2716 "c c #618555555965",
2717 "v c #30C2208130C2",
2718 "b c #38E328A230C2",
2719 "n c #28A228A228A2",
2720 "m c #41032CB228A2",
2721 "M c #104010401040",
2722 "N c #492438E34103",
2723 "B c #28A2208128A2",
2724 "V c #A699596538E3",
2725 "C c #30C21C711040",
2726 "Z c #30C218611040",
2727 "A c #965865955965",
2728 "S c #618534D32081",
2729 "D c #38E31C711040",
2730 "F c #082000000820",
2739 "ty> 459@>+&& ",
2741 "%$;=* *3:.Xa.dfg> ",
2742 "Oh$;ya *3d.a8j,Xe.d3g8+ ",
2743 " Oh$;ka *3d$a8lz,,xxc:.e3g54 ",
2744 " Oh$;kO *pd$%svbzz,sxxxxfX..&wn> ",
2745 " Oh$@mO *3dthwlsslszjzxxxxxxx3:td8M4 ",
2746 " Oh$@g& *3d$XNlvvvlllm,mNwxxxxxxxfa.:,B* ",
2747 " Oh$@,Od.czlllllzlmmqV@V#V@fxxxxxxxf:%j5& ",
2748 " Oh$1hd5lllslllCCZrV#r#:#2AxxxxxxxxxcdwM* ",
2749 " OXq6c.%8vvvllZZiqqApA:mq:Xxcpcxxxxxfdc9* ",
2750 " 2r<6gde3bllZZrVi7S@SV77A::qApxxxxxxfdcM ",
2751 " :,q-6MN.dfmZZrrSS:#riirDSAX@Af5xxxxxfevo",
2752 " +A26jguXtAZZZC7iDiCCrVVii7Cmmmxxxxxx%3g",
2753 " *#16jszN..3DZZZZrCVSA2rZrV7Dmmwxxxx&en",
2754 " p2yFvzssXe:fCZZCiiD7iiZDiDSSZwwxx8e*>",
2755 " OA1<jzxwwc:$d%NDZZZZCCCZCCZZCmxxfd.B ",
2756 " 3206Bwxxszx%et.eaAp77m77mmmf3&eeeg* ",
2757 " @26MvzxNzvlbwfpdettttttttttt.c,n& ",
2758 " *;16=lsNwwNwgsvslbwwvccc3pcfu<o ",
2759 " p;<69BvwwsszslllbBlllllllu<5+ ",
2760 " OS0y6FBlvvvzvzss,u=Blllj=54 ",
2761 " c1-699Blvlllllu7k96MMMg4 ",
2762 " *10y8n6FjvllllB<166668 ",
2763 " S-kg+>666<M<996-y6n<8* ",
2764 " p71=4 m69996kD8Z-66698&& ",
2765 " &i0ycm6n4 ogk17,0<6666g ",
2766 " N-k-<> >=01-kuu666> ",
2767 " ,6ky& &46-10ul,66, ",
2768 " Ou0<> o66y<ulw<66& ",
2769 " *kk5 >66By7=xu664 ",
2770 " <<M4 466lj<Mxu66o ",
2771 " *>> +66uv,zN666* ",
2781 /* when invoked (via signal delete_event), terminates the application.
2783 void close_application( GtkWidget *widget, GdkEvent *event, gpointer data ) {
2787 int main (int argc, char *argv[])
2789 /* GtkWidget is the storage type for widgets */
2790 GtkWidget *window, *pixmap, *fixed;
2791 GdkPixmap *gdk_pixmap;
2796 /* create the main window, and attach delete_event signal to terminate
2797 the application. Note that the main window will not have a titlebar
2798 since we're making it a popup. */
2799 gtk_init (&argc, &argv);
2800 window = gtk_window_new( GTK_WINDOW_POPUP );
2801 gtk_signal_connect (GTK_OBJECT (window), "delete_event",
2802 GTK_SIGNAL_FUNC (close_application), NULL);
2803 gtk_widget_show (window);
2805 /* now for the pixmap and the pixmap widget */
2806 style = gtk_widget_get_default_style();
2807 gc = style->black_gc;
2808 gdk_pixmap = gdk_pixmap_create_from_xpm_d( window->window, &mask,
2809 &style->bg[GTK_STATE_NORMAL],
2810 WheelbarrowFull_xpm );
2811 pixmap = gtk_pixmap_new( gdk_pixmap, mask );
2812 gtk_widget_show( pixmap );
2814 /* To display the pixmap, we use a fixed widget to place the pixmap */
2815 fixed = gtk_fixed_new();
2816 gtk_widget_set_usize( fixed, 200, 200 );
2817 gtk_fixed_put( GTK_FIXED(fixed), pixmap, 0, 0 );
2818 gtk_container_add( GTK_CONTAINER(window), fixed );
2819 gtk_widget_show( fixed );
2821 /* This masks out everything except for the image itself */
2822 gtk_widget_shape_combine_mask( window, mask, 0, 0 );
2824 /* show the window */
2825 gtk_widget_set_uposition( window, 20, 400 );
2826 gtk_widget_show( window );
2834 To make the wheelbarrow image sensitive, we could attach the button press
2835 event signal to make it do something. The following few lines would make
2836 the picture sensitive to a mouse button being pressed which makes the
2837 application terminate.
2840 gtk_widget_set_events( window,
2841 gtk_widget_get_events( window ) |
2842 GDK_BUTTON_PRESS_MASK );
2844 gtk_signal_connect( GTK_OBJECT(window), "button_press_event",
2845 GTK_SIGNAL_FUNC(close_application), NULL );
2848 <!-- ----------------------------------------------------------------- -->
2851 Ruler widgets are used to indicate the location of the mouse pointer
2852 in a given window. A window can have a vertical ruler spanning across
2853 the width and a horizontal ruler spanning down the height. A small
2854 triangular indicator on the ruler shows the exact location of the
2855 pointer relative to the ruler.
2857 A ruler must first be created. Horizontal and vertical rulers are
2861 GtkWidget *gtk_hruler_new( void ); /* horizontal ruler */
2862 GtkWidget *gtk_vruler_new( void ); /* vertical ruler */
2865 Once a ruler is created, we can define the unit of measurement. Units
2866 of measure for rulers can be GTK_PIXELS, GTK_INCHES or
2867 GTK_CENTIMETERS. This is set using
2870 void gtk_ruler_set_metric( GtkRuler *ruler,
2871 GtkMetricType metric );
2874 The default measure is GTK_PIXELS.
2877 gtk_ruler_set_metric( GTK_RULER(ruler), GTK_PIXELS );
2880 Other important characteristics of a ruler are how to mark the units
2881 of scale and where the position indicator is initially placed. These
2882 are set for a ruler using
2885 void gtk_ruler_set_range( GtkRuler *ruler,
2892 The lower and upper arguments define the extent of the ruler, and
2893 max_size is the largest possible number that will be displayed.
2894 Position defines the initial position of the pointer indicator within
2897 A vertical ruler can span an 800 pixel wide window thus
2900 gtk_ruler_set_range( GTK_RULER(vruler), 0, 800, 0, 800);
2903 The markings displayed on the ruler will be from 0 to 800, with
2904 a number for every 100 pixels. If instead we wanted the ruler to
2905 range from 7 to 16, we would code
2908 gtk_ruler_set_range( GTK_RULER(vruler), 7, 16, 0, 20);
2911 The indicator on the ruler is a small triangular mark that indicates
2912 the position of the pointer relative to the ruler. If the ruler is
2913 used to follow the mouse pointer, the motion_notify_event signal
2914 should be connected to the motion_notify_event method of the ruler.
2915 To follow all mouse movements within a window area, we would use
2918 #define EVENT_METHOD(i, x) GTK_WIDGET_CLASS(GTK_OBJECT(i)->klass)->x
2920 gtk_signal_connect_object( GTK_OBJECT(area), "motion_notify_event",
2921 (GtkSignalFunc)EVENT_METHOD(ruler, motion_notify_event),
2922 GTK_OBJECT(ruler) );
2925 The following example creates a drawing area with a horizontal ruler
2926 above it and a vertical ruler to the left of it. The size of the
2927 drawing area is 600 pixels wide by 400 pixels high. The horizontal
2928 ruler spans from 7 to 13 with a mark every 100 pixels, while the
2929 vertical ruler spans from 0 to 400 with a mark every 100 pixels.
2930 Placement of the drawing area and the rulers are done using a table.
2933 /* example-start rulers rulers.c */
2935 #include <gtk/gtk.h>
2937 #define EVENT_METHOD(i, x) GTK_WIDGET_CLASS(GTK_OBJECT(i)->klass)->x
2942 /* this routine gets control when the close button is clicked
2944 void close_application( GtkWidget *widget, GdkEvent *event, gpointer data ) {
2951 int main( int argc, char *argv[] ) {
2952 GtkWidget *window, *table, *area, *hrule, *vrule;
2954 /* initialize gtk and create the main window */
2955 gtk_init( &argc, &argv );
2957 window = gtk_window_new( GTK_WINDOW_TOPLEVEL );
2958 gtk_signal_connect (GTK_OBJECT (window), "delete_event",
2959 GTK_SIGNAL_FUNC( close_application ), NULL);
2960 gtk_container_border_width (GTK_CONTAINER (window), 10);
2962 /* create a table for placing the ruler and the drawing area */
2963 table = gtk_table_new( 3, 2, FALSE );
2964 gtk_container_add( GTK_CONTAINER(window), table );
2966 area = gtk_drawing_area_new();
2967 gtk_drawing_area_size( (GtkDrawingArea *)area, XSIZE, YSIZE );
2968 gtk_table_attach( GTK_TABLE(table), area, 1, 2, 1, 2,
2969 GTK_EXPAND|GTK_FILL, GTK_FILL, 0, 0 );
2970 gtk_widget_set_events( area, GDK_POINTER_MOTION_MASK | GDK_POINTER_MOTION_HINT_MASK );
2972 /* The horizontal ruler goes on top. As the mouse moves across the drawing area,
2973 a motion_notify_event is passed to the appropriate event handler for the ruler. */
2974 hrule = gtk_hruler_new();
2975 gtk_ruler_set_metric( GTK_RULER(hrule), GTK_PIXELS );
2976 gtk_ruler_set_range( GTK_RULER(hrule), 7, 13, 0, 20 );
2977 gtk_signal_connect_object( GTK_OBJECT(area), "motion_notify_event",
2978 (GtkSignalFunc)EVENT_METHOD(hrule, motion_notify_event),
2979 GTK_OBJECT(hrule) );
2980 /* GTK_WIDGET_CLASS(GTK_OBJECT(hrule)->klass)->motion_notify_event, */
2981 gtk_table_attach( GTK_TABLE(table), hrule, 1, 2, 0, 1,
2982 GTK_EXPAND|GTK_SHRINK|GTK_FILL, GTK_FILL, 0, 0 );
2984 /* The vertical ruler goes on the left. As the mouse moves across the drawing area,
2985 a motion_notify_event is passed to the appropriate event handler for the ruler. */
2986 vrule = gtk_vruler_new();
2987 gtk_ruler_set_metric( GTK_RULER(vrule), GTK_PIXELS );
2988 gtk_ruler_set_range( GTK_RULER(vrule), 0, YSIZE, 10, YSIZE );
2989 gtk_signal_connect_object( GTK_OBJECT(area), "motion_notify_event",
2991 GTK_WIDGET_CLASS(GTK_OBJECT(vrule)->klass)->motion_notify_event,
2992 GTK_OBJECT(vrule) );
2993 gtk_table_attach( GTK_TABLE(table), vrule, 0, 1, 1, 2,
2994 GTK_FILL, GTK_EXPAND|GTK_SHRINK|GTK_FILL, 0, 0 );
2996 /* now show everything */
2997 gtk_widget_show( area );
2998 gtk_widget_show( hrule );
2999 gtk_widget_show( vrule );
3000 gtk_widget_show( table );
3001 gtk_widget_show( window );
3009 <!-- ----------------------------------------------------------------- -->
3012 Statusbars are simple widgets used to display a text message. They keep
3013 a stack of the messages pushed onto them, so that popping the current
3014 message will re-display the previous text message.
3016 In order to allow different parts of an application to use the same
3017 statusbar to display messages, the statusbar widget issues Context
3018 Identifiers which are used to identify different 'users'. The message on
3019 top of the stack is the one displayed, no matter what context it is in.
3020 Messages are stacked in last-in-first-out order, not context identifier order.
3022 A statusbar is created with a call to:
3025 GtkWidget *gtk_statusbar_new( void );
3028 A new Context Identifier is requested using a call to the following
3029 function with a short textual description of the context:
3032 guint gtk_statusbar_get_context_id( GtkStatusbar *statusbar,
3033 const gchar *context_description );
3036 There are three functions that can operate on statusbars:
3039 guint gtk_statusbar_push( GtkStatusbar *statusbar,
3043 void gtk_statusbar_pop( GtkStatusbar *statusbar)
3046 void gtk_statusbar_remove( GtkStatusbar *statusbar,
3051 The first, gtk_statusbar_push, is used to add a new message to the statusbar.
3052 It returns a Message Identifier, which can be passed later to the function
3053 gtk_statusbar_remove to remove the message with the given Message and Context
3054 Identifiers from the statusbar's stack.
3056 The function gtk_statusbar_pop removes the message highest in the stack with
3057 the given Context Identifier.
3059 The following example creates a statusbar and two buttons, one for pushing items
3060 onto the statusbar, and one for popping the last item back off.
3063 /* example-start statusbar statusbar.c */
3065 #include <gtk/gtk.h>
3068 GtkWidget *status_bar;
3070 void push_item (GtkWidget *widget, gpointer data)
3072 static int count = 1;
3075 g_snprintf(buff, 20, "Item %d", count++);
3076 gtk_statusbar_push( GTK_STATUSBAR(status_bar), (guint) &data, buff);
3081 void pop_item (GtkWidget *widget, gpointer data)
3083 gtk_statusbar_pop( GTK_STATUSBAR(status_bar), (guint) &data );
3087 int main (int argc, char *argv[])
3096 gtk_init (&argc, &argv);
3098 /* create a new window */
3099 window = gtk_window_new(GTK_WINDOW_TOPLEVEL);
3100 gtk_widget_set_usize( GTK_WIDGET (window), 200, 100);
3101 gtk_window_set_title(GTK_WINDOW (window), "GTK Statusbar Example");
3102 gtk_signal_connect(GTK_OBJECT (window), "delete_event",
3103 (GtkSignalFunc) gtk_exit, NULL);
3105 vbox = gtk_vbox_new(FALSE, 1);
3106 gtk_container_add(GTK_CONTAINER(window), vbox);
3107 gtk_widget_show(vbox);
3109 status_bar = gtk_statusbar_new();
3110 gtk_box_pack_start (GTK_BOX (vbox), status_bar, TRUE, TRUE, 0);
3111 gtk_widget_show (status_bar);
3113 context_id = gtk_statusbar_get_context_id( GTK_STATUSBAR(status_bar), "Statusbar example");
3115 button = gtk_button_new_with_label("push item");
3116 gtk_signal_connect(GTK_OBJECT(button), "clicked",
3117 GTK_SIGNAL_FUNC (push_item), &context_id);
3118 gtk_box_pack_start(GTK_BOX(vbox), button, TRUE, TRUE, 2);
3119 gtk_widget_show(button);
3121 button = gtk_button_new_with_label("pop last item");
3122 gtk_signal_connect(GTK_OBJECT(button), "clicked",
3123 GTK_SIGNAL_FUNC (pop_item), &context_id);
3124 gtk_box_pack_start(GTK_BOX(vbox), button, TRUE, TRUE, 2);
3125 gtk_widget_show(button);
3127 /* always display the window as the last step so it all splashes on
3128 * the screen at once. */
3129 gtk_widget_show(window);
3138 <!-- ----------------------------------------------------------------- -->
3141 The Entry widget allows text to be typed and displayed in a single line
3142 text box. The text may be set with function calls that allow new text
3143 to replace, prepend or append the current contents of the Entry widget.
3145 There are two functions for creating Entry widgets:
3148 GtkWidget *gtk_entry_new( void );
3150 GtkWidget *gtk_entry_new_with_max_length( guint16 max );
3153 The first just creates a new Entry widget, whilst the second creates a
3154 new Entry and sets a limit on the length of the text within the Entry.
3156 There are several functions for altering the text which is currently
3157 within the Entry widget.
3160 void gtk_entry_set_text( GtkEntry *entry,
3161 const gchar *text );
3163 void gtk_entry_append_text( GtkEntry *entry,
3164 const gchar *text );
3166 void gtk_entry_prepend_text( GtkEntry *entry,
3167 const gchar *text );
3170 The function gtk_entry_set_text sets the contents of the Entry widget,
3171 replacing the current contents. The functions gtk_entry_append_text and
3172 gtk_entry_prepend_text allow the current contents to be appended and
3175 The next function allows the current insertion point to be set.
3178 void gtk_entry_set_position( GtkEntry *entry,
3182 The contents of the Entry can be retrieved by using a call to the
3183 following function. This is useful in the callback functions described below.
3186 gchar *gtk_entry_get_text( GtkEntry *entry );
3189 If we don't want the contents of the Entry to be changed by someone typing
3190 into it, we can change it's editable state.
3193 void gtk_entry_set_editable( GtkEntry *entry,
3194 gboolean editable );
3197 This function allows us to toggle the edittable state of the Entry widget
3198 by passing in a TRUE or FALSE value for the <tt/editable/ argument.
3200 If we are using the Entry where we don't want the text entered to be visible,
3201 for example when a password is being entered, we can use the following
3202 function, which also takes a boolean flag.
3205 void gtk_entry_set_visibility( GtkEntry *entry,
3209 A region of the text may be set as selected by using the following
3210 function. This would most often be used after setting some default text
3211 in an Entry, making it easy for the user to remove it.
3214 void gtk_entry_select_region( GtkEntry *entry,
3219 If we want to catch when the user has entered text, we can connect to the
3220 <tt/activate/ or <tt/changed/ signal. Activate is raised when the user hits
3221 the enter key within the Entry widget. Changed is raised when the text
3222 changes at all, e.g. for every character entered or removed.
3224 The following code is an example of using an Entry widget.
3227 /* example-start entry entry.c */
3229 #include <gtk/gtk.h>
3231 void enter_callback(GtkWidget *widget, GtkWidget *entry)
3234 entry_text = gtk_entry_get_text(GTK_ENTRY(entry));
3235 printf("Entry contents: %s\n", entry_text);
3238 void entry_toggle_editable (GtkWidget *checkbutton,
3241 gtk_entry_set_editable(GTK_ENTRY(entry),
3242 GTK_TOGGLE_BUTTON(checkbutton)->active);
3245 void entry_toggle_visibility (GtkWidget *checkbutton,
3248 gtk_entry_set_visibility(GTK_ENTRY(entry),
3249 GTK_TOGGLE_BUTTON(checkbutton)->active);
3252 int main (int argc, char *argv[])
3256 GtkWidget *vbox, *hbox;
3261 gtk_init (&argc, &argv);
3263 /* create a new window */
3264 window = gtk_window_new(GTK_WINDOW_TOPLEVEL);
3265 gtk_widget_set_usize( GTK_WIDGET (window), 200, 100);
3266 gtk_window_set_title(GTK_WINDOW (window), "GTK Entry");
3267 gtk_signal_connect(GTK_OBJECT (window), "delete_event",
3268 (GtkSignalFunc) gtk_exit, NULL);
3270 vbox = gtk_vbox_new (FALSE, 0);
3271 gtk_container_add (GTK_CONTAINER (window), vbox);
3272 gtk_widget_show (vbox);
3274 entry = gtk_entry_new_with_max_length (50);
3275 gtk_signal_connect(GTK_OBJECT(entry), "activate",
3276 GTK_SIGNAL_FUNC(enter_callback),
3278 gtk_entry_set_text (GTK_ENTRY (entry), "hello");
3279 gtk_entry_append_text (GTK_ENTRY (entry), " world");
3280 gtk_entry_select_region (GTK_ENTRY (entry),
3281 0, GTK_ENTRY(entry)->text_length);
3282 gtk_box_pack_start (GTK_BOX (vbox), entry, TRUE, TRUE, 0);
3283 gtk_widget_show (entry);
3285 hbox = gtk_hbox_new (FALSE, 0);
3286 gtk_container_add (GTK_CONTAINER (vbox), hbox);
3287 gtk_widget_show (hbox);
3289 check = gtk_check_button_new_with_label("Editable");
3290 gtk_box_pack_start (GTK_BOX (hbox), check, TRUE, TRUE, 0);
3291 gtk_signal_connect (GTK_OBJECT(check), "toggled",
3292 GTK_SIGNAL_FUNC(entry_toggle_editable), entry);
3293 gtk_toggle_button_set_state(GTK_TOGGLE_BUTTON(check), TRUE);
3294 gtk_widget_show (check);
3296 check = gtk_check_button_new_with_label("Visible");
3297 gtk_box_pack_start (GTK_BOX (hbox), check, TRUE, TRUE, 0);
3298 gtk_signal_connect (GTK_OBJECT(check), "toggled",
3299 GTK_SIGNAL_FUNC(entry_toggle_visibility), entry);
3300 gtk_toggle_button_set_state(GTK_TOGGLE_BUTTON(check), TRUE);
3301 gtk_widget_show (check);
3303 button = gtk_button_new_with_label ("Close");
3304 gtk_signal_connect_object (GTK_OBJECT (button), "clicked",
3305 GTK_SIGNAL_FUNC(gtk_exit),
3306 GTK_OBJECT (window));
3307 gtk_box_pack_start (GTK_BOX (vbox), button, TRUE, TRUE, 0);
3308 GTK_WIDGET_SET_FLAGS (button, GTK_CAN_DEFAULT);
3309 gtk_widget_grab_default (button);
3310 gtk_widget_show (button);
3312 gtk_widget_show(window);
3320 <!-- ----------------------------------------------------------------- -->
3321 <sect1> Color Selection
3323 The color selection widget is, not surprisingly, a widget for interactive
3324 selection of colors. This composite widget lets the user select a color by
3325 manipulating RGB (Red, Green, Blue) and HSV (Hue, Saturation, Value) triples.
3326 This is done either by adjusting single values with sliders or entries, or
3327 by picking the desired color from a hue-saturation wheel/value bar.
3328 Optionally, the opacity of the color can also be set.
3330 The color selection widget currently emits only one signal,
3331 "color_changed", which is emitted whenever the current color in the widget
3332 changes, either when the user changes it or if it's set explicitly through
3333 gtk_color_selection_set_color().
3335 Lets have a look at what the color selection widget has to offer us. The
3336 widget comes in two flavours; gtk_color_selection and
3337 gtk_color_selection_dialog:
3340 GtkWidget *gtk_color_selection_new( void );
3343 You'll probably not be using this constructor directly. It creates an orphan
3344 GtkColorSelection widget which you'll have to parent yourself. The
3345 GtkColorSelection widget inherits from the GtkVBox widget.
3348 GtkWidget *gtk_color_selection_dialog_new( const gchar *title );
3351 This is the most common color selection constructor. It creates a
3352 GtkColorSelectionDialog, which inherits from a GtkDialog. It consists
3353 of a GtkFrame containing a GtkColorSelection widget, a GtkHSeparator and a
3354 GtkHBox with three buttons, "Ok", "Cancel" and "Help". You can reach these
3355 buttons by accessing the "ok_button", "cancel_button" and "help_button"
3356 widgets in the GtkColorSelectionDialog structure,
3357 (i.e. GTK_COLOR_SELECTION_DIALOG(colorseldialog)->ok_button).
3360 void gtk_color_selection_set_update_policy( GtkColorSelection *colorsel,
3361 GtkUpdateType policy );
3364 This function sets the update policy. The default policy is
3365 GTK_UPDATE_CONTINOUS which means that the current color is updated
3366 continously when the user drags the sliders or presses the mouse and drags
3367 in the hue-saturation wheel or value bar. If you experience performance
3368 problems, you may want to set the policy to GTK_UPDATE_DISCONTINOUS or
3372 void gtk_color_selection_set_opacity( GtkColorSelection *colorsel,
3376 The color selection widget supports adjusting the opacity of a color
3377 (also known as the alpha channel). This is disabled by default. Calling
3378 this function with use_opacity set to TRUE enables opacity. Likewise,
3379 use_opacity set to FALSE will disable opacity.
3382 void gtk_color_selection_set_color( GtkColorSelection *colorsel,
3386 You can set the current color explicitly by calling this function with
3387 a pointer to an array of colors (gdouble). The length of the array depends
3388 on whether opacity is enabled or not. Position 0 contains the red component,
3389 1 is green, 2 is blue and opacity is at position 3 (only if opacity is enabled,
3390 see gtk_color_selection_set_opacity()). All values are between 0.0 and 1.0.
3393 void gtk_color_selection_get_color( GtkColorSelection *colorsel,
3397 When you need to query the current color, typically when you've received a
3398 "color_changed" signal, you use this function. Color is a pointer to the
3399 array of colors to fill in. See the gtk_color_selection_set_color() function
3400 for the description of this array.
3402 <!-- Need to do a whole section on DnD - TRG
3406 The color sample areas (right under the hue-saturation wheel) supports drag and drop. The type of
3407 drag and drop is "application/x-color". The message data consists of an array of 4
3408 (or 5 if opacity is enabled) gdouble values, where the value at position 0 is 0.0 (opacity
3409 on) or 1.0 (opacity off) followed by the red, green and blue values at positions 1,2 and 3 respectively.
3410 If opacity is enabled, the opacity is passed in the value at position 4.
3413 Here's a simple example demonstrating the use of the GtkColorSelectionDialog.
3414 The program displays a window containing a drawing area. Clicking on it opens
3415 a color selection dialog, and changing the color in the color selection dialog
3416 changes the background color.
3419 /* example-start colorsel colorsel.c */
3422 #include <gdk/gdk.h>
3423 #include <gtk/gtk.h>
3425 GtkWidget *colorseldlg = NULL;
3426 GtkWidget *drawingarea = NULL;
3428 /* Color changed handler */
3430 void color_changed_cb (GtkWidget *widget, GtkColorSelection *colorsel)
3434 GdkColormap *colormap;
3436 /* Get drawingarea colormap */
3438 colormap = gdk_window_get_colormap (drawingarea->window);
3440 /* Get current color */
3442 gtk_color_selection_get_color (colorsel,color);
3444 /* Fit to a unsigned 16 bit integer (0..65535) and insert into the GdkColor structure */
3446 gdk_color.red = (guint16)(color[0]*65535.0);
3447 gdk_color.green = (guint16)(color[1]*65535.0);
3448 gdk_color.blue = (guint16)(color[2]*65535.0);
3450 /* Allocate color */
3452 gdk_color_alloc (colormap, &gdk_color);
3454 /* Set window background color */
3456 gdk_window_set_background (drawingarea->window, &gdk_color);
3460 gdk_window_clear (drawingarea->window);
3463 /* Drawingarea event handler */
3465 gint area_event (GtkWidget *widget, GdkEvent *event, gpointer client_data)
3467 gint handled = FALSE;
3468 GtkWidget *colorsel;
3470 /* Check if we've received a button pressed event */
3472 if (event->type == GDK_BUTTON_PRESS && colorseldlg == NULL)
3474 /* Yes, we have an event and there's no colorseldlg yet! */
3478 /* Create color selection dialog */
3480 colorseldlg = gtk_color_selection_dialog_new("Select background color");
3482 /* Get the GtkColorSelection widget */
3484 colorsel = GTK_COLOR_SELECTION_DIALOG(colorseldlg)->colorsel;
3486 /* Connect to the "color_changed" signal, set the client-data to the colorsel widget */
3488 gtk_signal_connect(GTK_OBJECT(colorsel), "color_changed",
3489 (GtkSignalFunc)color_changed_cb, (gpointer)colorsel);
3491 /* Show the dialog */
3493 gtk_widget_show(colorseldlg);
3499 /* Close down and exit handler */
3501 void destroy_window (GtkWidget *widget, gpointer client_data)
3508 gint main (gint argc, gchar *argv[])
3512 /* Initialize the toolkit, remove gtk-related commandline stuff */
3514 gtk_init (&argc,&argv);
3516 /* Create toplevel window, set title and policies */
3518 window = gtk_window_new (GTK_WINDOW_TOPLEVEL);
3519 gtk_window_set_title (GTK_WINDOW(window), "Color selection test");
3520 gtk_window_set_policy (GTK_WINDOW(window), TRUE, TRUE, TRUE);
3522 /* Attach to the "delete" and "destroy" events so we can exit */
3524 gtk_signal_connect (GTK_OBJECT(window), "delete_event",
3525 (GtkSignalFunc)destroy_window, (gpointer)window);
3527 gtk_signal_connect (GTK_OBJECT(window), "destroy",
3528 (GtkSignalFunc)destroy_window, (gpointer)window);
3530 /* Create drawingarea, set size and catch button events */
3532 drawingarea = gtk_drawing_area_new ();
3534 gtk_drawing_area_size (GTK_DRAWING_AREA(drawingarea), 200, 200);
3536 gtk_widget_set_events (drawingarea, GDK_BUTTON_PRESS_MASK);
3538 gtk_signal_connect (GTK_OBJECT(drawingarea), "event",
3539 (GtkSignalFunc)area_event, (gpointer)drawingarea);
3541 /* Add drawingarea to window, then show them both */
3543 gtk_container_add (GTK_CONTAINER(window), drawingarea);
3545 gtk_widget_show (drawingarea);
3546 gtk_widget_show (window);
3548 /* Enter the gtk main loop (this never returns) */
3552 /* Satisfy grumpy compilers */
3559 <!-- ----------------------------------------------------------------- -->
3560 <sect1> File Selections
3562 The file selection widget is a quick and simple way to display a File
3563 dialog box. It comes complete with Ok, Cancel, and Help buttons, a great way
3564 to cut down on programming time.
3566 To create a new file selection box use:
3569 GtkWidget *gtk_file_selection_new( gchar *title );
3572 To set the filename, for example to bring up a specific directory, or
3573 give a default filename, use this function:
3576 void gtk_file_selection_set_filename( GtkFileSelection *filesel,
3580 To grab the text that the user has entered or clicked on, use this
3584 gchar *gtk_file_selection_get_filename( GtkFileSelection *filesel );
3587 There are also pointers to the widgets contained within the file
3588 selection widget. These are:
3593 <item>selection_entry
3594 <item>selection_text
3601 Most likely you will want to use the ok_button, cancel_button, and
3602 help_button pointers in signaling their use.
3604 Included here is an example stolen from testgtk.c, modified to run
3605 on it's own. As you will see, there is nothing much to creating a file
3606 selection widget. While in this example the Help button appears on the
3607 screen, it does nothing as there is not a signal attached to it.
3610 /* example-start filesel filesel.c */
3612 #include <gtk/gtk.h>
3614 /* Get the selected filename and print it to the console */
3615 void file_ok_sel (GtkWidget *w, GtkFileSelection *fs)
3617 g_print ("%s\n", gtk_file_selection_get_filename (GTK_FILE_SELECTION (fs)));
3620 void destroy (GtkWidget *widget, gpointer data)
3625 int main (int argc, char *argv[])
3629 gtk_init (&argc, &argv);
3631 /* Create a new file selection widget */
3632 filew = gtk_file_selection_new ("File selection");
3634 gtk_signal_connect (GTK_OBJECT (filew), "destroy",
3635 (GtkSignalFunc) destroy, &filew);
3636 /* Connect the ok_button to file_ok_sel function */
3637 gtk_signal_connect (GTK_OBJECT (GTK_FILE_SELECTION (filew)->ok_button),
3638 "clicked", (GtkSignalFunc) file_ok_sel, filew );
3640 /* Connect the cancel_button to destroy the widget */
3641 gtk_signal_connect_object (GTK_OBJECT (GTK_FILE_SELECTION (filew)->cancel_button),
3642 "clicked", (GtkSignalFunc) gtk_widget_destroy,
3643 GTK_OBJECT (filew));
3645 /* Lets set the filename, as if this were a save dialog, and we are giving
3646 a default filename */
3647 gtk_file_selection_set_filename (GTK_FILE_SELECTION(filew),
3650 gtk_widget_show(filew);
3657 <!-- ***************************************************************** -->
3658 <sect> Container Widgets
3659 <!-- ***************************************************************** -->
3661 <!-- ----------------------------------------------------------------- -->
3664 The NoteBook Widget is a collection of 'pages' that overlap each other,
3665 each page contains different information. This widget has become more common
3666 lately in GUI programming, and it is a good way to show blocks similar
3667 information that warrant separation in their display.
3669 The first function call you will need to know, as you can probably
3670 guess by now, is used to create a new notebook widget.
3673 GtkWidget *gtk_notebook_new( void );
3676 Once the notebook has been created, there are 12 functions that
3677 operate on the notebook widget. Let's look at them individually.
3679 The first one we will look at is how to position the page indicators.
3680 These page indicators or 'tabs' as they are referred to, can be positioned
3681 in four ways: top, bottom, left, or right.
3684 void gtk_notebook_set_tab_pos( GtkNotebook *notebook,
3685 GtkPositionType pos );
3688 GtkPostionType will be one of the following, and they are pretty self explanatory:
3691 <item> GTK_POS_RIGHT
3693 <item> GTK_POS_BOTTOM
3696 GTK_POS_TOP is the default.
3698 Next we will look at how to add pages to the notebook. There are three
3699 ways to add pages to the NoteBook. Let's look at the first two together as
3700 they are quite similar.
3703 void gtk_notebook_append_page( GtkNotebook *notebook,
3705 GtkWidget *tab_label );
3707 void gtk_notebook_prepend_page( GtkNotebook *notebook,
3709 GtkWidget *tab_label );
3712 These functions add pages to the notebook by inserting them from the
3713 back of the notebook (append), or the front of the notebook (prepend).
3714 <tt/child/ is the widget that is placed within the notebook page, and
3715 <tt/tab_label/ is the label for the page being added.
3717 The final function for adding a page to the notebook contains all of
3718 the properties of the previous two, but it allows you to specify what position
3719 you want the page to be in the notebook.
3722 void gtk_notebook_insert_page( GtkNotebook *notebook,
3724 GtkWidget *tab_label,
3728 The parameters are the same as _append_ and _prepend_ except it
3729 contains an extra parameter, <tt/position/. This parameter is used to
3730 specify what place this page will be inserted into.
3732 Now that we know how to add a page, lets see how we can remove a page
3736 void gtk_notebook_remove_page( GtkNotebook *notebook,
3740 This function takes the page specified by page_num and removes it from
3741 the widget pointed to by <tt/notebook/.
3743 To find out what the current page is in a notebook use the function:
3746 gint gtk_notebook_current_page( GtkNotebook *notebook );
3749 These next two functions are simple calls to move the notebook page
3750 forward or backward. Simply provide the respective function call with the
3751 notebook widget you wish to operate on. Note: when the NoteBook is currently
3752 on the last page, and gtk_notebook_next_page is called, the notebook will
3753 wrap back to the first page. Likewise, if the NoteBook is on the first page,
3754 and gtk_notebook_prev_page is called, the notebook will wrap to the last page.
3757 void gtk_notebook_next_page( GtkNoteBook *notebook );
3759 void gtk_notebook_prev_page( GtkNoteBook *notebook );
3762 This next function sets the 'active' page. If you wish the
3763 notebook to be opened to page 5 for example, you would use this function.
3764 Without using this function, the notebook defaults to the first page.
3767 void gtk_notebook_set_page( GtkNotebook *notebook,
3771 The next two functions add or remove the notebook page tabs and the
3772 notebook border respectively.
3775 void gtk_notebook_set_show_tabs( GtkNotebook *notebook,
3778 void gtk_notebook_set_show_border( GtkNotebook *notebook,
3782 show_tabs and show_border can be either TRUE or FALSE.
3784 Now lets look at an example, it is expanded from the testgtk.c code
3785 that comes with the GTK distribution, and it shows all 13 functions. This
3786 small program creates a window with a notebook and six buttons. The notebook
3787 contains 11 pages, added in three different ways, appended, inserted, and
3788 prepended. The buttons allow you rotate the tab positions, add/remove the tabs
3789 and border, remove a page, change pages in both a forward and backward manner,
3790 and exit the program.
3793 /* example-start notebook notebook.c */
3795 #include <gtk/gtk.h>
3797 /* This function rotates the position of the tabs */
3798 void rotate_book (GtkButton *button, GtkNotebook *notebook)
3800 gtk_notebook_set_tab_pos (notebook, (notebook->tab_pos +1) %4);
3803 /* Add/Remove the page tabs and the borders */
3804 void tabsborder_book (GtkButton *button, GtkNotebook *notebook)
3808 if (notebook->show_tabs == 0)
3810 if (notebook->show_border == 0)
3813 gtk_notebook_set_show_tabs (notebook, tval);
3814 gtk_notebook_set_show_border (notebook, bval);
3817 /* Remove a page from the notebook */
3818 void remove_book (GtkButton *button, GtkNotebook *notebook)
3822 page = gtk_notebook_current_page(notebook);
3823 gtk_notebook_remove_page (notebook, page);
3824 /* Need to refresh the widget --
3825 This forces the widget to redraw itself. */
3826 gtk_widget_draw(GTK_WIDGET(notebook), NULL);
3829 void delete (GtkWidget *widget, GtkWidget *event, gpointer data)
3834 int main (int argc, char *argv[])
3839 GtkWidget *notebook;
3842 GtkWidget *checkbutton;
3847 gtk_init (&argc, &argv);
3849 window = gtk_window_new (GTK_WINDOW_TOPLEVEL);
3851 gtk_signal_connect (GTK_OBJECT (window), "delete_event",
3852 GTK_SIGNAL_FUNC (delete), NULL);
3854 gtk_container_border_width (GTK_CONTAINER (window), 10);
3856 table = gtk_table_new(2,6,TRUE);
3857 gtk_container_add (GTK_CONTAINER (window), table);
3859 /* Create a new notebook, place the position of the tabs */
3860 notebook = gtk_notebook_new ();
3861 gtk_notebook_set_tab_pos (GTK_NOTEBOOK (notebook), GTK_POS_TOP);
3862 gtk_table_attach_defaults(GTK_TABLE(table), notebook, 0,6,0,1);
3863 gtk_widget_show(notebook);
3865 /* lets append a bunch of pages to the notebook */
3866 for (i=0; i < 5; i++) {
3867 sprintf(bufferf, "Append Frame %d", i+1);
3868 sprintf(bufferl, "Page %d", i+1);
3870 frame = gtk_frame_new (bufferf);
3871 gtk_container_border_width (GTK_CONTAINER (frame), 10);
3872 gtk_widget_set_usize (frame, 100, 75);
3873 gtk_widget_show (frame);
3875 label = gtk_label_new (bufferf);
3876 gtk_container_add (GTK_CONTAINER (frame), label);
3877 gtk_widget_show (label);
3879 label = gtk_label_new (bufferl);
3880 gtk_notebook_append_page (GTK_NOTEBOOK (notebook), frame, label);
3884 /* now lets add a page to a specific spot */
3885 checkbutton = gtk_check_button_new_with_label ("Check me please!");
3886 gtk_widget_set_usize(checkbutton, 100, 75);
3887 gtk_widget_show (checkbutton);
3889 label = gtk_label_new ("Add spot");
3890 gtk_container_add (GTK_CONTAINER (checkbutton), label);
3891 gtk_widget_show (label);
3892 label = gtk_label_new ("Add page");
3893 gtk_notebook_insert_page (GTK_NOTEBOOK (notebook), checkbutton, label, 2);
3895 /* Now finally lets prepend pages to the notebook */
3896 for (i=0; i < 5; i++) {
3897 sprintf(bufferf, "Prepend Frame %d", i+1);
3898 sprintf(bufferl, "PPage %d", i+1);
3900 frame = gtk_frame_new (bufferf);
3901 gtk_container_border_width (GTK_CONTAINER (frame), 10);
3902 gtk_widget_set_usize (frame, 100, 75);
3903 gtk_widget_show (frame);
3905 label = gtk_label_new (bufferf);
3906 gtk_container_add (GTK_CONTAINER (frame), label);
3907 gtk_widget_show (label);
3909 label = gtk_label_new (bufferl);
3910 gtk_notebook_prepend_page (GTK_NOTEBOOK(notebook), frame, label);
3913 /* Set what page to start at (page 4) */
3914 gtk_notebook_set_page (GTK_NOTEBOOK(notebook), 3);
3917 /* create a bunch of buttons */
3918 button = gtk_button_new_with_label ("close");
3919 gtk_signal_connect_object (GTK_OBJECT (button), "clicked",
3920 GTK_SIGNAL_FUNC (delete), NULL);
3921 gtk_table_attach_defaults(GTK_TABLE(table), button, 0,1,1,2);
3922 gtk_widget_show(button);
3924 button = gtk_button_new_with_label ("next page");
3925 gtk_signal_connect_object (GTK_OBJECT (button), "clicked",
3926 (GtkSignalFunc) gtk_notebook_next_page,
3927 GTK_OBJECT (notebook));
3928 gtk_table_attach_defaults(GTK_TABLE(table), button, 1,2,1,2);
3929 gtk_widget_show(button);
3931 button = gtk_button_new_with_label ("prev page");
3932 gtk_signal_connect_object (GTK_OBJECT (button), "clicked",
3933 (GtkSignalFunc) gtk_notebook_prev_page,
3934 GTK_OBJECT (notebook));
3935 gtk_table_attach_defaults(GTK_TABLE(table), button, 2,3,1,2);
3936 gtk_widget_show(button);
3938 button = gtk_button_new_with_label ("tab position");
3939 gtk_signal_connect_object (GTK_OBJECT (button), "clicked",
3940 (GtkSignalFunc) rotate_book, GTK_OBJECT(notebook));
3941 gtk_table_attach_defaults(GTK_TABLE(table), button, 3,4,1,2);
3942 gtk_widget_show(button);
3944 button = gtk_button_new_with_label ("tabs/border on/off");
3945 gtk_signal_connect_object (GTK_OBJECT (button), "clicked",
3946 (GtkSignalFunc) tabsborder_book,
3947 GTK_OBJECT (notebook));
3948 gtk_table_attach_defaults(GTK_TABLE(table), button, 4,5,1,2);
3949 gtk_widget_show(button);
3951 button = gtk_button_new_with_label ("remove page");
3952 gtk_signal_connect_object (GTK_OBJECT (button), "clicked",
3953 (GtkSignalFunc) remove_book,
3954 GTK_OBJECT(notebook));
3955 gtk_table_attach_defaults(GTK_TABLE(table), button, 5,6,1,2);
3956 gtk_widget_show(button);
3958 gtk_widget_show(table);
3959 gtk_widget_show(window);
3968 Hopefully this helps you on your way with creating notebooks for your
3971 <!-- ----------------------------------------------------------------- -->
3972 <sect1>Scrolled Windows
3974 Scrolled windows are used to create a scrollable area inside a real window.
3975 You may insert any type of widget into a scrolled window, and it will
3976 be accessable regardless of the size by using the scrollbars.
3978 The following function is used to create a new scolled window.
3981 GtkWidget *gtk_scrolled_window_new( GtkAdjustment *hadjustment,
3982 GtkAdjustment *vadjustment );
3985 Where the first argument is the adjustment for the horizontal
3986 direction, and the second, the adjustment for the vertical direction.
3987 These are almost always set to NULL.
3990 void gtk_scrolled_window_set_policy( GtkScrolledWindow *scrolled_window,
3991 GtkPolicyType hscrollbar_policy,
3992 GtkPolicyType vscrollbar_policy );
3995 This sets the policy to be used with respect to the scrollbars.
3996 The first arguement is the scrolled window you wish to change. The second
3997 sets the policiy for the horizontal scrollbar, and the third the policy for
3998 the vertical scrollbar.
4000 The policy may be one of GTK_POLICY AUTOMATIC, or GTK_POLICY_ALWAYS.
4001 GTK_POLICY_AUTOMATIC will automatically decide whether you need
4002 scrollbars, wheras GTK_POLICY_ALWAYS will always leave the scrollbars
4005 Here is a simple example that packs 100 toggle buttons into a scrolled window.
4006 I've only commented on the parts that may be new to you.
4009 /* example-start scrolledwin scrolledwin.c */
4011 #include <gtk/gtk.h>
4013 void destroy(GtkWidget *widget, gpointer data)
4018 int main (int argc, char *argv[])
4020 static GtkWidget *window;
4021 GtkWidget *scrolled_window;
4027 gtk_init (&argc, &argv);
4029 /* Create a new dialog window for the scrolled window to be
4030 * packed into. A dialog is just like a normal window except it has a
4031 * vbox and a horizontal seperator packed into it. It's just a shortcut
4032 * for creating dialogs */
4033 window = gtk_dialog_new ();
4034 gtk_signal_connect (GTK_OBJECT (window), "destroy",
4035 (GtkSignalFunc) destroy, NULL);
4036 gtk_window_set_title (GTK_WINDOW (window), "dialog");
4037 gtk_container_border_width (GTK_CONTAINER (window), 0);
4038 gtk_widget_set_usize(window, 300, 300);
4040 /* create a new scrolled window. */
4041 scrolled_window = gtk_scrolled_window_new (NULL, NULL);
4043 gtk_container_border_width (GTK_CONTAINER (scrolled_window), 10);
4045 /* the policy is one of GTK_POLICY AUTOMATIC, or GTK_POLICY_ALWAYS.
4046 * GTK_POLICY_AUTOMATIC will automatically decide whether you need
4047 * scrollbars, wheras GTK_POLICY_ALWAYS will always leave the scrollbars
4048 * there. The first one is the horizontal scrollbar, the second,
4050 gtk_scrolled_window_set_policy (GTK_SCROLLED_WINDOW (scrolled_window),
4051 GTK_POLICY_AUTOMATIC, GTK_POLICY_ALWAYS);
4052 /* The dialog window is created with a vbox packed into it. */
4053 gtk_box_pack_start (GTK_BOX (GTK_DIALOG(window)->vbox), scrolled_window,
4055 gtk_widget_show (scrolled_window);
4057 /* create a table of 10 by 10 squares. */
4058 table = gtk_table_new (10, 10, FALSE);
4060 /* set the spacing to 10 on x and 10 on y */
4061 gtk_table_set_row_spacings (GTK_TABLE (table), 10);
4062 gtk_table_set_col_spacings (GTK_TABLE (table), 10);
4064 /* pack the table into the scrolled window */
4065 gtk_container_add (GTK_CONTAINER (scrolled_window), table);
4066 gtk_widget_show (table);
4068 /* this simply creates a grid of toggle buttons on the table
4069 * to demonstrate the scrolled window. */
4070 for (i = 0; i < 10; i++)
4071 for (j = 0; j < 10; j++) {
4072 sprintf (buffer, "button (%d,%d)\n", i, j);
4073 button = gtk_toggle_button_new_with_label (buffer);
4074 gtk_table_attach_defaults (GTK_TABLE (table), button,
4076 gtk_widget_show (button);
4079 /* Add a "close" button to the bottom of the dialog */
4080 button = gtk_button_new_with_label ("close");
4081 gtk_signal_connect_object (GTK_OBJECT (button), "clicked",
4082 (GtkSignalFunc) gtk_widget_destroy,
4083 GTK_OBJECT (window));
4085 /* this makes it so the button is the default. */
4087 GTK_WIDGET_SET_FLAGS (button, GTK_CAN_DEFAULT);
4088 gtk_box_pack_start (GTK_BOX (GTK_DIALOG (window)->action_area), button, TRUE, TRUE, 0);
4090 /* This grabs this button to be the default button. Simply hitting
4091 * the "Enter" key will cause this button to activate. */
4092 gtk_widget_grab_default (button);
4093 gtk_widget_show (button);
4095 gtk_widget_show (window);
4104 Try playing with resizing the window. You'll notice how the scrollbars
4105 react. You may also wish to use the gtk_widget_set_usize() call to set
4106 the default size of the window or other widgets.
4108 <!-- ----------------------------------------------------------------- -->
4109 <sect1> Paned Window Widgets
4111 The paned window widgets are useful when you want to divide an area
4112 into two parts, with the relative size of the two parts controlled by
4113 the user. A groove is drawn between the two portions with a handle
4114 that the user can drag to change the ratio. The division can either
4115 be horizontal (HPaned) or vertical (VPaned).
4117 To create a new paned window, call one of:
4120 GtkWidget *gtk_hpaned_new (void);
4122 GtkWidget *gtk_vpaned_new (void);
4125 After creating the paned window widget, you need to add child widgets
4126 to its two halves. To do this, use the functions:
4129 void gtk_paned_add1 (GtkPaned *paned, GtkWidget *child);
4131 void gtk_paned_add2 (GtkPaned *paned, GtkWidget *child);
4134 <tt/gtk_paned_add1()/ adds the child widget to the left or top half of
4135 the paned window. <tt/gtk_paned_add2()/ adds the child widget to the
4136 right or bottom half of the paned window.
4138 As an example, we will create part of the user interface of an
4139 imaginary email program. A window is divided into two portions
4140 vertically, with the top portion being a list of email messages and
4141 the bottom portion the text of the email message. Most of the program
4142 is pretty straightforward. A couple of points to note: text can't
4143 be added to a Text widget until it is realized. This could be done by
4144 calling <tt/gtk_widget_realize()/, but as a demonstration of an alternate
4145 technique, we connect a handler to the "realize" signal to add the
4146 text. Also, we need to add the <tt/GTK_SHRINK/ option to some of the
4147 items in the table containing the text window and its scrollbars, so
4148 that when the bottom portion is made smaller, the correct portions
4149 shrink instead of being pushed off the bottom of the window.
4152 /* example-start paned paned.c */
4154 #include <gtk/gtk.h>
4156 /* Create the list of "messages" */
4161 GtkWidget *scrolled_window;
4163 GtkWidget *list_item;
4168 /* Create a new scrolled window, with scrollbars only if needed */
4169 scrolled_window = gtk_scrolled_window_new (NULL, NULL);
4170 gtk_scrolled_window_set_policy (GTK_SCROLLED_WINDOW (scrolled_window),
4171 GTK_POLICY_AUTOMATIC,
4172 GTK_POLICY_AUTOMATIC);
4174 /* Create a new list and put it in the scrolled window */
4175 list = gtk_list_new ();
4176 gtk_container_add (GTK_CONTAINER(scrolled_window), list);
4177 gtk_widget_show (list);
4179 /* Add some messages to the window */
4180 for (i=0; i<10; i++) {
4182 sprintf(buffer,"Message #%d",i);
4183 list_item = gtk_list_item_new_with_label (buffer);
4184 gtk_container_add (GTK_CONTAINER(list), list_item);
4185 gtk_widget_show (list_item);
4189 return scrolled_window;
4192 /* Add some text to our text widget - this is a callback that is invoked
4193 when our window is realized. We could also force our window to be
4194 realized with gtk_widget_realize, but it would have to be part of
4195 a hierarchy first */
4198 realize_text (GtkWidget *text, gpointer data)
4200 gtk_text_freeze (GTK_TEXT (text));
4201 gtk_text_insert (GTK_TEXT (text), NULL, &text->style->black, NULL,
4202 "From: pathfinder@nasa.gov\n"
4203 "To: mom@nasa.gov\n"
4204 "Subject: Made it!\n"
4206 "We just got in this morning. The weather has been\n"
4207 "great - clear but cold, and there are lots of fun sights.\n"
4208 "Sojourner says hi. See you soon.\n"
4211 gtk_text_thaw (GTK_TEXT (text));
4214 /* Create a scrolled text area that displays a "message" */
4220 GtkWidget *hscrollbar;
4221 GtkWidget *vscrollbar;
4223 /* Create a table to hold the text widget and scrollbars */
4224 table = gtk_table_new (2, 2, FALSE);
4226 /* Put a text widget in the upper left hand corner. Note the use of
4227 * GTK_SHRINK in the y direction */
4228 text = gtk_text_new (NULL, NULL);
4229 gtk_table_attach (GTK_TABLE (table), text, 0, 1, 0, 1,
4230 GTK_FILL | GTK_EXPAND,
4231 GTK_FILL | GTK_EXPAND | GTK_SHRINK, 0, 0);
4232 gtk_widget_show (text);
4234 /* Put a HScrollbar in the lower left hand corner */
4235 hscrollbar = gtk_hscrollbar_new (GTK_TEXT (text)->hadj);
4236 gtk_table_attach (GTK_TABLE (table), hscrollbar, 0, 1, 1, 2,
4237 GTK_EXPAND | GTK_FILL, GTK_FILL, 0, 0);
4238 gtk_widget_show (hscrollbar);
4240 /* And a VScrollbar in the upper right */
4241 vscrollbar = gtk_vscrollbar_new (GTK_TEXT (text)->vadj);
4242 gtk_table_attach (GTK_TABLE (table), vscrollbar, 1, 2, 0, 1,
4243 GTK_FILL, GTK_EXPAND | GTK_FILL | GTK_SHRINK, 0, 0);
4244 gtk_widget_show (vscrollbar);
4246 /* Add a handler to put a message in the text widget when it is realized */
4247 gtk_signal_connect (GTK_OBJECT (text), "realize",
4248 GTK_SIGNAL_FUNC (realize_text), NULL);
4254 main (int argc, char *argv[])
4261 gtk_init (&argc, &argv);
4263 window = gtk_window_new (GTK_WINDOW_TOPLEVEL);
4264 gtk_window_set_title (GTK_WINDOW (window), "Paned Windows");
4265 gtk_signal_connect (GTK_OBJECT (window), "destroy",
4266 GTK_SIGNAL_FUNC (gtk_main_quit), NULL);
4267 gtk_container_border_width (GTK_CONTAINER (window), 10);
4269 /* create a vpaned widget and add it to our toplevel window */
4271 vpaned = gtk_vpaned_new ();
4272 gtk_container_add (GTK_CONTAINER(window), vpaned);
4273 gtk_widget_show (vpaned);
4275 /* Now create the contents of the two halves of the window */
4277 list = create_list ();
4278 gtk_paned_add1 (GTK_PANED(vpaned), list);
4279 gtk_widget_show (list);
4281 text = create_text ();
4282 gtk_paned_add2 (GTK_PANED(vpaned), text);
4283 gtk_widget_show (text);
4284 gtk_widget_show (window);
4291 <!-- ----------------------------------------------------------------- -->
4292 <sect1> Aspect Frames
4294 The aspect frame widget is like a frame widget, except that it also
4295 enforces the aspect ratio (that is, the ratio of the width to the
4296 height) of the child widget to have a certain value, adding extra
4297 space if necessary. This is useful, for instance, if you want to
4298 preview a larger image. The size of the preview should vary when
4299 the user resizes the window, but the aspect ratio needs to always match
4302 To create a new aspect frame use:
4305 GtkWidget *gtk_aspect_frame_new( const gchar *label,
4312 <tt/xalign/ and <tt/yalign/ specifiy alignment as with Alignment
4313 widgets. If <tt/obey_child/ is true, the aspect ratio of a child
4314 widget will match the aspect ratio of the ideal size it requests.
4315 Otherwise, it is given by <tt/ratio/.
4317 To change the options of an existing aspect frame, you can use:
4320 void gtk_aspect_frame_set( GtkAspectFrame *aspect_frame,
4327 As an example, the following program uses an AspectFrame to
4328 present a drawing area whose aspect ratio will always be 2:1, no
4329 matter how the user resizes the top-level window.
4332 /* example-start aspectframe aspectframe.c */
4334 #include <gtk/gtk.h>
4337 main (int argc, char *argv[])
4340 GtkWidget *aspect_frame;
4341 GtkWidget *drawing_area;
4342 gtk_init (&argc, &argv);
4344 window = gtk_window_new (GTK_WINDOW_TOPLEVEL);
4345 gtk_window_set_title (GTK_WINDOW (window), "Aspect Frame");
4346 gtk_signal_connect (GTK_OBJECT (window), "destroy",
4347 GTK_SIGNAL_FUNC (gtk_main_quit), NULL);
4348 gtk_container_border_width (GTK_CONTAINER (window), 10);
4350 /* Create an aspect_frame and add it to our toplevel window */
4352 aspect_frame = gtk_aspect_frame_new ("2x1", /* label */
4355 2, /* xsize/ysize = 2 */
4356 FALSE /* ignore child's aspect */);
4358 gtk_container_add (GTK_CONTAINER(window), aspect_frame);
4359 gtk_widget_show (aspect_frame);
4361 /* Now add a child widget to the aspect frame */
4363 drawing_area = gtk_drawing_area_new ();
4365 /* Ask for a 200x200 window, but the AspectFrame will give us a 200x100
4366 * window since we are forcing a 2x1 aspect ratio */
4367 gtk_widget_set_usize (drawing_area, 200, 200);
4368 gtk_container_add (GTK_CONTAINER(aspect_frame), drawing_area);
4369 gtk_widget_show (drawing_area);
4371 gtk_widget_show (window);
4378 <!-- ***************************************************************** -->
4380 <!-- ***************************************************************** -->
4382 NOTE: The GtkList widget has been superseded by the GtkCList widget.
4384 The GtkList widget is designed to act as a vertical container for widgets
4385 that should be of the type GtkListItem.
4387 A GtkList widget has its own window to receive events and it's own
4388 background color which is usualy white. As it is directly derived from a
4389 GtkContainer it can be treated as such by using the GTK_CONTAINER(List)
4390 macro, see the GtkContainer widget for more on this.
4391 One should already be familar whith the usage of a GList and its
4392 related functions g_list_*() to be able to use the GtkList widget to
4395 There is one field inside the structure definition of the GtkList widget
4396 that will be of greater interest to us, this is:
4403 guint selection_mode;
4408 The selection field of a GtkList points to a linked list of all items
4409 that are curently selected, or NULL if the selection is empty.
4410 So to learn about the current selection we read the GTK_LIST()->selection
4411 field, but do not modify it since the internal fields are maintained by
4412 the gtk_list_*() functions.
4414 The selection_mode of the GtkList determines the selection facilities
4415 of a GtkList and therefore the contents of the GTK_LIST()->selection
4416 field. The selection_mode may be one of the following:
4419 <item> GTK_SELECTION_SINGLE - The selection is either NULL
4420 or contains a GList pointer
4421 for a single selected item.
4423 <item> GTK_SELECTION_BROWSE - The selection is NULL if the list
4424 contains no widgets or insensitive
4425 ones only, otherwise it contains
4426 a GList pointer for one GList
4427 structure, and therefore exactly
4430 <item> GTK_SELECTION_MULTIPLE - The selection is NULL if no list
4431 items are selected or a GList pointer
4432 for the first selected item. That
4433 in turn points to a GList structure
4434 for the second selected item and so
4437 <item> GTK_SELECTION_EXTENDED - The selection is always NULL.
4440 The default is GTK_SELECTION_MULTIPLE.
4442 <!-- ----------------------------------------------------------------- -->
4446 void selection_changed( GtkList *list );
4449 This signal will be invoked whenever the selection field
4450 of a GtkList has changed. This happens when a child of
4451 the GtkList got selected or deselected.
4454 void select_child( GtkList *list,
4458 This signal is invoked when a child of the GtkList is about
4459 to get selected. This happens mainly on calls to
4460 gtk_list_select_item(), gtk_list_select_child(), button presses
4461 and sometimes indirectly triggered on some else occasions where
4462 children get added to or removed from the GtkList.
4465 void unselect_child( GtkList *list,
4469 This signal is invoked when a child of the GtkList is about
4470 to get deselected. This happens mainly on calls to
4471 gtk_list_unselect_item(), gtk_list_unselect_child(), button presses
4472 and sometimes indirectly triggered on some else occasions where
4473 children get added to or removed from the GtkList.
4475 <!-- ----------------------------------------------------------------- -->
4479 guint gtk_list_get_type( void );
4482 Returns the `GtkList' type identifier.
4485 GtkWidget *gtk_list_new( void );
4488 Create a new GtkList object. The new widget is returned as a pointer to a
4489 GtkWidget object. NULL is returned on failure.
4492 void gtk_list_insert_items( GtkList *list,
4497 Insert list items into the list, starting at <tt/position/.
4498 <tt/items/ is a doubly linked list where each nodes data
4499 pointer is expected to point to a newly created GtkListItem.
4500 The GList nodes of <tt/items/ are taken over by the list.
4503 void gtk_list_append_items( GtkList *list,
4507 Insert list items just like gtk_list_insert_items() at the end
4508 of the list. The GList nodes of <tt/items/ are taken over by the list.
4511 void gtk_list_prepend_items( GtkList *list,
4515 Insert list items just like gtk_list_insert_items() at the very
4516 beginning of the list. The GList nodes of <tt/items/ are taken over
4520 void gtk_list_remove_items( GtkList *list,
4524 Remove list items from the list. <tt/items/ is a doubly linked
4525 list where each nodes data pointer is expected to point to a
4526 direct child of list. It is the callers responsibility to make a
4527 call to g_list_free(items) afterwards. Also the caller has to
4528 destroy the list items himself.
4531 void gtk_list_clear_items( GtkList *list,
4536 Remove and destroy list items from the list. A widget is affected if
4537 its current position within the list is in the range specified by
4538 <tt/start/ and <tt/end/.
4541 void gtk_list_select_item( GtkList *list,
4545 Invoke the select_child signal for a list item
4546 specified through its current position within the list.
4549 void gtk_list_unselect_item( GtkList *list,
4553 Invoke the unselect_child signal for a list item
4554 specified through its current position within the list.
4557 void gtk_list_select_child( GtkList *list,
4561 Invoke the select_child signal for the specified child.
4564 void gtk_list_unselect_child( GtkList *list,
4568 Invoke the unselect_child signal for the specified child.
4571 gint gtk_list_child_position( GtkList *list,
4575 Return the position of <tt/child/ within the list. "-1" is returned on failure.
4578 void gtk_list_set_selection_mode( GtkList *list,
4579 GtkSelectionMode mode );
4582 Set the selection mode MODE which can be of GTK_SELECTION_SINGLE,
4583 GTK_SELECTION_BROWSE, GTK_SELECTION_MULTIPLE or GTK_SELECTION_EXTENDED.
4586 GtkList *GTK_LIST( gpointer obj );
4589 Cast a generic pointer to `GtkList *'. *Note Standard Macros::, for
4593 GtkListClass *GTK_LIST_CLASS( gpointer class);
4596 Cast a generic pointer to `GtkListClass*'. *Note Standard Macros::,
4600 gint GTK_IS_LIST( gpointer obj);
4603 Determine if a generic pointer refers to a `GtkList' object. *Note
4604 Standard Macros::, for more info.
4606 <!-- ----------------------------------------------------------------- -->
4609 Following is an example program that will print out the changes
4610 of the selection of a GtkList, and lets you "arrest" list items
4611 into a prison by selecting them with the rightmost mouse button.
4614 /* example-start list list.c */
4616 /* include the gtk+ header files
4617 * include stdio.h, we need that for the printf() function
4619 #include <gtk/gtk.h>
4622 /* this is our data identification string to store
4623 * data in list items
4625 const gchar *list_item_data_key="list_item_data";
4628 /* prototypes for signal handler that we are going to connect
4629 * to the GtkList widget
4631 static void sigh_print_selection (GtkWidget *gtklist,
4632 gpointer func_data);
4633 static void sigh_button_event (GtkWidget *gtklist,
4634 GdkEventButton *event,
4638 /* main function to set up the user interface */
4640 gint main (int argc, gchar *argv[])
4642 GtkWidget *separator;
4645 GtkWidget *scrolled_window;
4649 GtkWidget *list_item;
4655 /* initialize gtk+ (and subsequently gdk) */
4657 gtk_init(&argc, &argv);
4660 /* create a window to put all the widgets in
4661 * connect gtk_main_quit() to the "destroy" event of
4662 * the window to handle window manager close-window-events
4664 window=gtk_window_new(GTK_WINDOW_TOPLEVEL);
4665 gtk_window_set_title(GTK_WINDOW(window), "GtkList Example");
4666 gtk_signal_connect(GTK_OBJECT(window),
4668 GTK_SIGNAL_FUNC(gtk_main_quit),
4672 /* inside the window we need a box to arrange the widgets
4674 vbox=gtk_vbox_new(FALSE, 5);
4675 gtk_container_border_width(GTK_CONTAINER(vbox), 5);
4676 gtk_container_add(GTK_CONTAINER(window), vbox);
4677 gtk_widget_show(vbox);
4679 /* this is the scolled window to put the GtkList widget inside */
4680 scrolled_window=gtk_scrolled_window_new(NULL, NULL);
4681 gtk_widget_set_usize(scrolled_window, 250, 150);
4682 gtk_container_add(GTK_CONTAINER(vbox), scrolled_window);
4683 gtk_widget_show(scrolled_window);
4685 /* create the GtkList widget
4686 * connect the sigh_print_selection() signal handler
4687 * function to the "selection_changed" signal of the GtkList
4688 * to print out the selected items each time the selection
4690 gtklist=gtk_list_new();
4691 gtk_container_add(GTK_CONTAINER(scrolled_window), gtklist);
4692 gtk_widget_show(gtklist);
4693 gtk_signal_connect(GTK_OBJECT(gtklist),
4694 "selection_changed",
4695 GTK_SIGNAL_FUNC(sigh_print_selection),
4698 /* we create a "Prison" to put a list item in ;)
4700 frame=gtk_frame_new("Prison");
4701 gtk_widget_set_usize(frame, 200, 50);
4702 gtk_container_border_width(GTK_CONTAINER(frame), 5);
4703 gtk_frame_set_shadow_type(GTK_FRAME(frame), GTK_SHADOW_OUT);
4704 gtk_container_add(GTK_CONTAINER(vbox), frame);
4705 gtk_widget_show(frame);
4707 /* connect the sigh_button_event() signal handler to the GtkList
4708 * wich will handle the "arresting" of list items
4710 gtk_signal_connect(GTK_OBJECT(gtklist),
4711 "button_release_event",
4712 GTK_SIGNAL_FUNC(sigh_button_event),
4715 /* create a separator
4717 separator=gtk_hseparator_new();
4718 gtk_container_add(GTK_CONTAINER(vbox), separator);
4719 gtk_widget_show(separator);
4721 /* finaly create a button and connect it´s "clicked" signal
4722 * to the destroyment of the window
4724 button=gtk_button_new_with_label("Close");
4725 gtk_container_add(GTK_CONTAINER(vbox), button);
4726 gtk_widget_show(button);
4727 gtk_signal_connect_object(GTK_OBJECT(button),
4729 GTK_SIGNAL_FUNC(gtk_widget_destroy),
4730 GTK_OBJECT(window));
4733 /* now we create 5 list items, each having it´s own
4734 * label and add them to the GtkList using gtk_container_add()
4735 * also we query the text string from the label and
4736 * associate it with the list_item_data_key for each list item
4738 for (i=0; i<5; i++) {
4742 sprintf(buffer, "ListItemContainer with Label #%d", i);
4743 label=gtk_label_new(buffer);
4744 list_item=gtk_list_item_new();
4745 gtk_container_add(GTK_CONTAINER(list_item), label);
4746 gtk_widget_show(label);
4747 gtk_container_add(GTK_CONTAINER(gtklist), list_item);
4748 gtk_widget_show(list_item);
4749 gtk_label_get(GTK_LABEL(label), &string);
4750 gtk_object_set_data(GTK_OBJECT(list_item),
4754 /* here, we are creating another 5 labels, this time
4755 * we use gtk_list_item_new_with_label() for the creation
4756 * we can´t query the text string from the label because
4757 * we don´t have the labels pointer and therefore
4758 * we just associate the list_item_data_key of each
4759 * list item with the same text string
4760 * for adding of the list items we put them all into a doubly
4761 * linked list (GList), and then add them by a single call to
4762 * gtk_list_append_items()
4763 * because we use g_list_prepend() to put the items into the
4764 * doubly linked list, their order will be descending (instead
4765 * of ascending when using g_list_append())
4769 sprintf(buffer, "List Item with Label %d", i);
4770 list_item=gtk_list_item_new_with_label(buffer);
4771 dlist=g_list_prepend(dlist, list_item);
4772 gtk_widget_show(list_item);
4773 gtk_object_set_data(GTK_OBJECT(list_item),
4775 "ListItem with integrated Label");
4777 gtk_list_append_items(GTK_LIST(gtklist), dlist);
4779 /* finaly we want to see the window, don´t we? ;)
4781 gtk_widget_show(window);
4783 /* fire up the main event loop of gtk
4787 /* we get here after gtk_main_quit() has been called which
4788 * happens if the main window gets destroyed
4793 /* this is the signal handler that got connected to button
4794 * press/release events of the GtkList
4797 sigh_button_event (GtkWidget *gtklist,
4798 GdkEventButton *event,
4801 /* we only do something if the third (rightmost mouse button
4804 if (event->type==GDK_BUTTON_RELEASE &&
4806 GList *dlist, *free_list;
4807 GtkWidget *new_prisoner;
4809 /* fetch the currently selected list item which
4810 * will be our next prisoner ;)
4812 dlist=GTK_LIST(gtklist)->selection;
4814 new_prisoner=GTK_WIDGET(dlist->data);
4818 /* look for already prisoned list items, we
4819 * will put them back into the list
4820 * remember to free the doubly linked list that
4821 * gtk_container_children() returns
4823 dlist=gtk_container_children(GTK_CONTAINER(frame));
4826 GtkWidget *list_item;
4828 list_item=dlist->data;
4830 gtk_widget_reparent(list_item, gtklist);
4834 g_list_free(free_list);
4836 /* if we have a new prisoner, remove him from the
4837 * GtkList and put him into the frame "Prison"
4838 * we need to unselect the item before
4843 static_dlist.data=new_prisoner;
4844 static_dlist.next=NULL;
4845 static_dlist.prev=NULL;
4847 gtk_list_unselect_child(GTK_LIST(gtklist),
4849 gtk_widget_reparent(new_prisoner, frame);
4854 /* this is the signal handler that gets called if GtkList
4855 * emits the "selection_changed" signal
4858 sigh_print_selection (GtkWidget *gtklist,
4863 /* fetch the doubly linked list of selected items
4864 * of the GtkList, remember to treat this as read-only!
4866 dlist=GTK_LIST(gtklist)->selection;
4868 /* if there are no selected items there is nothing more
4869 * to do than just telling the user so
4872 g_print("Selection cleared\n");
4875 /* ok, we got a selection and so we print it
4877 g_print("The selection is a ");
4879 /* get the list item from the doubly linked list
4880 * and then query the data associated with list_item_data_key
4881 * we then just print it
4884 GtkObject *list_item;
4885 gchar *item_data_string;
4887 list_item=GTK_OBJECT(dlist->data);
4888 item_data_string=gtk_object_get_data(list_item,
4889 list_item_data_key);
4890 g_print("%s ", item_data_string);
4899 <!-- ----------------------------------------------------------------- -->
4900 <sect1> List Item Widget
4902 The GtkListItem widget is designed to act as a container holding up
4903 to one child, providing functions for selection/deselection just like
4904 the GtkList widget requires them for its children.
4906 A GtkListItem has its own window to receive events and has its own
4907 background color which is usualy white.
4909 As it is directly derived from a
4910 GtkItem it can be treated as such by using the GTK_ITEM(ListItem)
4911 macro, see the GtkItem widget for more on this.
4912 Usualy a GtkListItem just holds a label to identify e.g. a filename
4913 within a GtkList -- therefore the convenience function
4914 gtk_list_item_new_with_label() is provided. The same effect can be
4915 achieved by creating a GtkLabel on its own, setting its alignment
4916 to xalign=0 and yalign=0.5 with a subsequent container addition
4919 As one is not forced to add a GtkLabel to a GtkListItem, you could
4920 also add a GtkVBox or a GtkArrow etc. to the GtkListItem.
4922 <!-- ----------------------------------------------------------------- -->
4925 A GtkListItem does not create new signals on its own, but inherits
4926 the signals of a GtkItem. *Note GtkItem::, for more info.
4928 <!-- ----------------------------------------------------------------- -->
4932 guint gtk_list_item_get_type( void );
4935 Returns the `GtkListItem' type identifier.
4938 GtkWidget *gtk_list_item_new( void );
4941 Create a new GtkListItem object. The new widget is returned as a pointer
4942 to a GtkWidget object. NULL is returned on failure.
4945 GtkWidget *gtk_list_item_new_with_label( gchar *label );
4948 Create a new GtkListItem object, having a single GtkLabel as
4949 the sole child. The new widget is returned as a pointer to a
4950 GtkWidget object. NULL is returned on failure.
4953 void gtk_list_item_select( GtkListItem *list_item );
4956 This function is basicaly a wrapper around a call to
4957 gtk_item_select (GTK_ITEM (list_item)) which will emit the
4959 *Note GtkItem::, for more info.
4962 void gtk_list_item_deselect( GtkListItem *list_item );
4965 This function is basicaly a wrapper around a call to
4966 gtk_item_deselect (GTK_ITEM (list_item)) which will emit the
4968 *Note GtkItem::, for more info.
4971 GtkListItem *GTK_LIST_ITEM( gpointer obj );
4974 Cast a generic pointer to `GtkListItem*'. *Note Standard Macros::,
4978 GtkListItemClass *GTK_LIST_ITEM_CLASS( gpointer class );
4981 Cast a generic pointer to GtkListItemClass*. *Note Standard
4982 Macros::, for more info.
4985 gint GTK_IS_LIST_ITEM( gpointer obj );
4988 Determine if a generic pointer refers to a `GtkListItem' object.
4989 *Note Standard Macros::, for more info.
4991 <!-- ----------------------------------------------------------------- -->
4994 Please see the GtkList example on this, which covers the usage of a
4995 GtkListItem as well.
4997 <!-- ***************************************************************** -->
4999 <!-- ***************************************************************** -->
5001 There are two ways to create menus, there's the easy way, and there's the
5002 hard way. Both have their uses, but you can usually use the menufactory
5003 (the easy way). The "hard" way is to create all the menus using the calls
5004 directly. The easy way is to use the gtk_menu_factory calls. This is
5005 much simpler, but there are advantages and disadvantages to each approach.
5007 The menufactory is much easier to use, and to add new menus to, although
5008 writing a few wrapper functions to create menus using the manual method
5009 could go a long way towards usability. With the menufactory, it is not
5010 possible to add images or the character '/' to the menus.
5012 <!-- ----------------------------------------------------------------- -->
5013 <sect1>Manual Menu Creation
5015 In the true tradition of teaching, we'll show you the hard
5016 way first. <tt>:)</>
5018 There are three widgets that go into making a menubar and submenus:
5020 <item>a menu item, which is what the user wants to select, e.g. 'Save'
5021 <item>a menu, which acts as a container for the menu items, and
5022 <item>a menubar, which is a container for each of the individual menus,
5025 This is slightly complicated by the fact that menu item widgets are used
5026 for two different things. They are both the widets that are packed into
5027 the menu, and the widget that is packed into the menubar, which,
5028 when selected, activiates the menu.
5030 Let's look at the functions that are used to create menus and menubars.
5031 This first function is used to create a new menubar.
5034 GtkWidget *gtk_menu_bar_new( void );
5037 This rather self explanatory function creates a new menubar. You use
5038 gtk_container_add to pack this into a window, or the box_pack functions to
5039 pack it into a box - the same as buttons.
5042 GtkWidget *gtk_menu_new( void );
5045 This function returns a pointer to a new menu, it is never actually shown
5046 (with gtk_widget_show), it is just a container for the menu items. Hopefully this will
5047 become more clear when you look at the example below.
5049 The next two calls are used to create menu items that are packed into
5050 the menu (and menubar).
5053 GtkWidget *gtk_menu_item_new( void );
5059 GtkWidget *gtk_menu_item_new_with_label( const char *label );
5062 These calls are used to create the menu items that are to be displayed.
5063 Remember to differentiate between a "menu" as created with gtk_menu_new
5064 and a "menu item" as created by the gtk_menu_item_new functions. The
5065 menu item will be an actual button with an associated action,
5066 whereas a menu will be a container holding menu items.
5068 The gtk_menu_new_with_label and gtk_menu_new functions are just as you'd expect after
5069 reading about the buttons. One creates a new menu item with a label
5070 already packed into it, and the other just creates a blank menu item.
5072 Once you've created a menu item you have to put it into a menu. This is
5073 done using the function gtk_menu_append. In order to capture when the item
5074 is selected by the user, we need to connect to the <tt/activate/ signal in
5075 the usual way. So, if we wanted to create a standard <tt/File/ menu, with
5076 the options <tt/Open/, <tt/Save/ and <tt/Quit/ the code would look something like
5079 file_menu = gtk_menu_new(); /* Don't need to show menus */
5081 /* Create the menu items */
5082 open_item = gtk_menu_item_new_with_label("Open");
5083 save_item = gtk_menu_item_new_with_label("Save");
5084 quit_item = gtk_menu_item_new_with_label("Quit");
5086 /* Add them to the menu */
5087 gtk_menu_append( GTK_MENU(file_menu), open_item);
5088 gtk_menu_append( GTK_MENU(file_menu), save_item);
5089 gtk_menu_append( GTK_MENU(file_menu), quit_item);
5091 /* Attach the callback functions to the activate signal */
5092 gtk_signal_connect_object( GTK_OBJECT(open_items), "activate",
5093 GTK_SIGNAL_FUNC(menuitem_response), (gpointer) "file.open");
5094 gtk_signal_connect_object( GTK_OBJECT(save_items), "activate",
5095 GTK_SIGNAL_FUNC(menuitem_response), (gpointer) "file.save");
5097 /* We can attach the Quit menu item to our exit function */
5098 gtk_signal_connect_object( GTK_OBJECT(quit_items), "activate",
5099 GTK_SIGNAL_FUNC(destroy), (gpointer) "file.quit");
5101 /* We do need to show menu items */
5102 gtk_widget_show( open_item );
5103 gtk_widget_show( save_item );
5104 gtk_widget_show( quit_item );
5107 At this point we have our menu. Now we need to create a menubar and a menu
5108 item for the <tt/File/ entry, to which we add our menu. The code looks like this
5111 menu_bar = gtk_menu_bar_new();
5112 gtk_container_add( GTK_CONTAINER(window), menu_bar);
5113 gtk_widget_show( menu_bar );
5115 file_item = gtk_menu_item_new_with_label("File");
5116 gtk_widget_show(file_item);
5119 Now we need to associate the menu with <tt/file_item/. This is done with the
5123 void gtk_menu_item_set_submenu( GtkMenuItem *menu_item,
5124 GtkWidget *submenu );
5127 So, our example would continue with
5130 gtk_menu_item_set_submenu( GTK_MENU_ITEM(file_item), file_menu );
5133 All that is left to do is to add the menu to the menubar, which is accomplished
5137 void gtk_menu_bar_append( GtkMenuBar *menu_bar, GtkWidget *menu_item);
5140 which in our case looks like this:
5143 gtk_menu_bar_append( GTK_MENU_BAR (menu_bar), file_item );
5146 If we wanted the menu right justified on the menubar, such as help menus
5147 often are, we can use the following function (again on <tt/file_item/
5148 in the current example) before attaching it to the menubar.
5151 void gtk_menu_item_right_justify( GtkMenuItem *menu_item );
5154 Here is a summary of the steps needed to create a menu bar with menus attached:
5157 <item> Create a new menu using gtk_menu_new()
5158 <item> Use multiple calls to gtk_menu_item_new() for each item you wish to have
5159 on your menu. And use gtk_menu_append() to put each of these new items on
5161 <item> Create a menu item using gtk_menu_item_new(). This will be the root of
5162 the menu, the text appearing here will be on the menubar itself.
5163 <item>Use gtk_menu_item_set_submenu() to attach the menu to the root menu
5164 item (the one created in the above step).
5165 <item> Create a new menubar using gtk_menu_bar_new. This step only needs
5166 to be done once when creating a series of menus on one menu bar.
5167 <item> Use gtk_menu_bar_append to put the root menu onto the menubar.
5170 Creating a popup menu is nearly the same. The difference is that the
5171 menu is not posted `automatically' by a menubar, but explicitly by calling
5172 the function gtk_menu_popup() from a button-press event, for example.
5176 <item>Create an event handling function. It needs to have the prototype
5178 static gint handler( GtkWidget *widget,
5181 and it will use the event to find out where to pop up the menu.
5182 <item>In the event handler, if the event is a mouse button press, treat
5183 <tt>event</tt> as a button event (which it is) and use it as
5184 shown in the sample code to pass information to gtk_menu_popup().
5185 <item>Bind that event handler to a widget with
5187 gtk_signal_connect_object(GTK_OBJECT(widget), "event",
5188 GTK_SIGNAL_FUNC (handler), GTK_OBJECT(menu));
5190 where <tt>widget</tt> is the widget you are binding to, <tt>handler</tt>
5191 is the handling function, and <tt>menu</tt> is a menu created with
5192 gtk_menu_new(). This can be a menu which is also posted by a menu bar,
5193 as shown in the sample code.
5196 <!-- ----------------------------------------------------------------- -->
5197 <sect1>Manual Menu Example
5199 That should about do it. Let's take a look at an example to help clarify.
5202 /* example-start menu menu.c */
5204 #include <gtk/gtk.h>
5206 static gint button_press (GtkWidget *, GdkEvent *);
5207 static void menuitem_response (gchar *);
5209 int main (int argc, char *argv[])
5214 GtkWidget *menu_bar;
5215 GtkWidget *root_menu;
5216 GtkWidget *menu_items;
5222 gtk_init (&argc, &argv);
5224 /* create a new window */
5225 window = gtk_window_new(GTK_WINDOW_TOPLEVEL);
5226 gtk_widget_set_usize( GTK_WIDGET (window), 200, 100);
5227 gtk_window_set_title(GTK_WINDOW (window), "GTK Menu Test");
5228 gtk_signal_connect(GTK_OBJECT (window), "delete_event",
5229 (GtkSignalFunc) gtk_main_quit, NULL);
5231 /* Init the menu-widget, and remember -- never
5232 * gtk_show_widget() the menu widget!!
5233 * This is the menu that holds the menu items, the one that
5234 * will pop up when you click on the "Root Menu" in the app */
5235 menu = gtk_menu_new();
5237 /* Next we make a little loop that makes three menu-entries for "test-menu".
5238 * Notice the call to gtk_menu_append. Here we are adding a list of
5239 * menu items to our menu. Normally, we'd also catch the "clicked"
5240 * signal on each of the menu items and setup a callback for it,
5241 * but it's omitted here to save space. */
5243 for(i = 0; i < 3; i++)
5245 /* Copy the names to the buf. */
5246 sprintf(buf, "Test-undermenu - %d", i);
5248 /* Create a new menu-item with a name... */
5249 menu_items = gtk_menu_item_new_with_label(buf);
5251 /* ...and add it to the menu. */
5252 gtk_menu_append(GTK_MENU (menu), menu_items);
5254 /* Do something interesting when the menuitem is selected */
5255 gtk_signal_connect_object(GTK_OBJECT(menu_items), "activate",
5256 GTK_SIGNAL_FUNC(menuitem_response), (gpointer) g_strdup(buf));
5258 /* Show the widget */
5259 gtk_widget_show(menu_items);
5262 /* This is the root menu, and will be the label
5263 * displayed on the menu bar. There won't be a signal handler attached,
5264 * as it only pops up the rest of the menu when pressed. */
5265 root_menu = gtk_menu_item_new_with_label("Root Menu");
5267 gtk_widget_show(root_menu);
5269 /* Now we specify that we want our newly created "menu" to be the menu
5270 * for the "root menu" */
5271 gtk_menu_item_set_submenu(GTK_MENU_ITEM (root_menu), menu);
5273 /* A vbox to put a menu and a button in: */
5274 vbox = gtk_vbox_new(FALSE, 0);
5275 gtk_container_add(GTK_CONTAINER(window), vbox);
5276 gtk_widget_show(vbox);
5278 /* Create a menu-bar to hold the menus and add it to our main window */
5279 menu_bar = gtk_menu_bar_new();
5280 gtk_box_pack_start(GTK_BOX(vbox), menu_bar, FALSE, FALSE, 2);
5281 gtk_widget_show(menu_bar);
5283 /* Create a button to which to attach menu as a popup */
5284 button = gtk_button_new_with_label("press me");
5285 gtk_signal_connect_object(GTK_OBJECT(button), "event",
5286 GTK_SIGNAL_FUNC (button_press), GTK_OBJECT(menu));
5287 gtk_box_pack_end(GTK_BOX(vbox), button, TRUE, TRUE, 2);
5288 gtk_widget_show(button);
5290 /* And finally we append the menu-item to the menu-bar -- this is the
5291 * "root" menu-item I have been raving about =) */
5292 gtk_menu_bar_append(GTK_MENU_BAR (menu_bar), root_menu);
5294 /* always display the window as the last step so it all splashes on
5295 * the screen at once. */
5296 gtk_widget_show(window);
5303 /* Respond to a button-press by posting a menu passed in as widget.
5305 * Note that the "widget" argument is the menu being posted, NOT
5306 * the button that was pressed.
5309 static gint button_press (GtkWidget *widget, GdkEvent *event)
5312 if (event->type == GDK_BUTTON_PRESS) {
5313 GdkEventButton *bevent = (GdkEventButton *) event;
5314 gtk_menu_popup (GTK_MENU(widget), NULL, NULL, NULL, NULL,
5315 bevent->button, bevent->time);
5316 /* Tell calling code that we have handled this event; the buck
5321 /* Tell calling code that we have not handled this event; pass it on. */
5326 /* Print a string when a menu item is selected */
5328 static void menuitem_response (gchar *string)
5330 printf("%s\n", string);
5335 You may also set a menu item to be insensitive and, using an accelerator
5336 table, bind keys to menu functions.
5338 <!-- ----------------------------------------------------------------- -->
5339 <sect1>Using GtkMenuFactory
5341 Now that we've shown you the hard way, here's how you do it using the
5342 gtk_menu_factory calls.
5344 <!-- ----------------------------------------------------------------- -->
5345 <sect1>Menu Factory Example
5347 Here is an example using the GTK menu factory. This is the first file,
5348 menufactory.h. We keep a separate menufactory.c and mfmain.c because
5349 of the global variables used in the menufactory.c file.
5352 /* example-start menu menufactory.h */
5354 #ifndef __MENUFACTORY_H__
5355 #define __MENUFACTORY_H__
5359 #endif /* __cplusplus */
5361 void get_main_menu (GtkWidget **menubar, GtkAcceleratorTable **table);
5362 void menus_create(GtkMenuEntry *entries, int nmenu_entries);
5366 #endif /* __cplusplus */
5368 #endif /* __MENUFACTORY_H__ */
5372 And here is the menufactory.c file.
5375 /* example-start menu menufactory.c */
5377 #include <gtk/gtk.h>
5378 #include <strings.h>
5383 static void menus_remove_accel(GtkWidget * widget, gchar * signal_name, gchar * path);
5384 static gint menus_install_accel(GtkWidget * widget, gchar * signal_name, gchar key, gchar modifiers, gchar * path);
5385 void menus_init(void);
5386 void menus_create(GtkMenuEntry * entries, int nmenu_entries);
5389 /* this is the GtkMenuEntry structure used to create new menus. The
5390 * first member is the menu definition string. The second, the
5391 * default accelerator key used to access this menu function with
5392 * the keyboard. The third is the callback function to call when
5393 * this menu item is selected (by the accelerator key, or with the
5394 * mouse.) The last member is the data to pass to your callback function.
5397 static GtkMenuEntry menu_items[] =
5399 {"<Main>/File/New", "<control>N", NULL, NULL},
5400 {"<Main>/File/Open", "<control>O", NULL, NULL},
5401 {"<Main>/File/Save", "<control>S", NULL, NULL},
5402 {"<Main>/File/Save as", NULL, NULL, NULL},
5403 {"<Main>/File/<separator>", NULL, NULL, NULL},
5404 {"<Main>/File/Quit", "<control>Q", file_quit_cmd_callback, "OK, I'll quit"},
5405 {"<Main>/Options/Test", NULL, NULL, NULL}
5408 /* calculate the number of menu_item's */
5409 static int nmenu_items = sizeof(menu_items) / sizeof(menu_items[0]);
5411 static int initialize = TRUE;
5412 static GtkMenuFactory *factory = NULL;
5413 static GtkMenuFactory *subfactory[1];
5414 static GHashTable *entry_ht = NULL;
5416 void get_main_menu(GtkWidget ** menubar, GtkAcceleratorTable ** table)
5422 *menubar = subfactory[0]->widget;
5424 *table = subfactory[0]->table;
5427 void menus_init(void)
5432 factory = gtk_menu_factory_new(GTK_MENU_FACTORY_MENU_BAR);
5433 subfactory[0] = gtk_menu_factory_new(GTK_MENU_FACTORY_MENU_BAR);
5435 gtk_menu_factory_add_subfactory(factory, subfactory[0], "<Main>");
5436 menus_create(menu_items, nmenu_items);
5440 void menus_create(GtkMenuEntry * entries, int nmenu_entries)
5449 for (i = 0; i < nmenu_entries; i++) {
5450 accelerator = g_hash_table_lookup(entry_ht, entries[i].path);
5452 if (accelerator[0] == '\0')
5453 entries[i].accelerator = NULL;
5455 entries[i].accelerator = accelerator;
5458 gtk_menu_factory_add_entries(factory, entries, nmenu_entries);
5460 for (i = 0; i < nmenu_entries; i++)
5461 if (entries[i].widget) {
5462 gtk_signal_connect(GTK_OBJECT(entries[i].widget), "install_accelerator",
5463 (GtkSignalFunc) menus_install_accel,
5465 gtk_signal_connect(GTK_OBJECT(entries[i].widget), "remove_accelerator",
5466 (GtkSignalFunc) menus_remove_accel,
5471 static gint menus_install_accel(GtkWidget * widget, gchar * signal_name, gchar key, gchar modifiers, gchar * path)
5477 if (modifiers & GDK_CONTROL_MASK)
5478 strcat(accel, "<control>");
5479 if (modifiers & GDK_SHIFT_MASK)
5480 strcat(accel, "<shift>");
5481 if (modifiers & GDK_MOD1_MASK)
5482 strcat(accel, "<alt>");
5489 t1 = g_hash_table_lookup(entry_ht, path);
5492 entry_ht = g_hash_table_new(g_str_hash, g_str_equal);
5494 g_hash_table_insert(entry_ht, path, g_strdup(accel));
5499 static void menus_remove_accel(GtkWidget * widget, gchar * signal_name, gchar * path)
5504 t = g_hash_table_lookup(entry_ht, path);
5507 g_hash_table_insert(entry_ht, path, g_strdup(""));
5511 void menus_set_sensitive(char *path, int sensitive)
5513 GtkMenuPath *menu_path;
5518 menu_path = gtk_menu_factory_find(factory, path);
5520 gtk_widget_set_sensitive(menu_path->widget, sensitive);
5522 g_warning("Unable to set sensitivity for menu which doesn't exist: %s", path);
5527 And here's the mfmain.h
5530 /* example-start menu mfmain.h */
5532 #ifndef __MFMAIN_H__
5533 #define __MFMAIN_H__
5538 #endif /* __cplusplus */
5540 void file_quit_cmd_callback(GtkWidget *widget, gpointer data);
5544 #endif /* __cplusplus */
5546 #endif /* __MFMAIN_H__ */
5553 /* example-start menu mfmain.c */
5555 #include <gtk/gtk.h>
5558 #include "menufactory.h"
5561 int main(int argc, char *argv[])
5564 GtkWidget *main_vbox;
5567 GtkAcceleratorTable *accel;
5569 gtk_init(&argc, &argv);
5571 window = gtk_window_new(GTK_WINDOW_TOPLEVEL);
5572 gtk_signal_connect(GTK_OBJECT(window), "destroy",
5573 GTK_SIGNAL_FUNC(file_quit_cmd_callback),
5575 gtk_window_set_title(GTK_WINDOW(window), "Menu Factory");
5576 gtk_widget_set_usize(GTK_WIDGET(window), 300, 200);
5578 main_vbox = gtk_vbox_new(FALSE, 1);
5579 gtk_container_border_width(GTK_CONTAINER(main_vbox), 1);
5580 gtk_container_add(GTK_CONTAINER(window), main_vbox);
5581 gtk_widget_show(main_vbox);
5583 get_main_menu(&menubar, &accel);
5584 gtk_window_add_accelerator_table(GTK_WINDOW(window), accel);
5585 gtk_box_pack_start(GTK_BOX(main_vbox), menubar, FALSE, TRUE, 0);
5586 gtk_widget_show(menubar);
5588 gtk_widget_show(window);
5594 /* This is just to demonstrate how callbacks work when using the
5595 * menufactory. Often, people put all the callbacks from the menus
5596 * in a separate file, and then have them call the appropriate functions
5597 * from there. Keeps it more organized. */
5598 void file_quit_cmd_callback (GtkWidget *widget, gpointer data)
5600 g_print ("%s\n", (char *) data);
5606 And a makefile so it'll be easier to compile it.
5613 C_FLAGS = -Wall $(PROF) -L/usr/local/include -DDEBUG
5614 L_FLAGS = $(PROF) -L/usr/X11R6/lib -L/usr/local/lib
5615 L_POSTFLAGS = -lgtk -lgdk -lglib -lXext -lX11 -lm
5616 PROGNAME = menufactory
5618 O_FILES = menufactory.o mfmain.o
5620 $(PROGNAME): $(O_FILES)
5622 $(CC) $(L_FLAGS) -o $(PROGNAME) $(O_FILES) $(L_POSTFLAGS)
5625 $(CC) -c $(C_FLAGS) $<
5628 rm -f core *.o $(PROGNAME) nohup.out
5633 For now, there's only this example. An explanation and lots 'o' comments
5636 <!-- ***************************************************************** -->
5638 <!-- ***************************************************************** -->
5640 The Text widget allows multiple lines of text to be displayed and edited.
5641 It supports both multi-colored and multi-font text, allowing them to be
5642 mixed in any way we wish. It also has a wide set of key based text editing
5643 commands, which are compatible with Emacs.
5645 The text widget supports full cut-and-paste facilities, including the use
5646 of double- and triple-click to select a word and a whole line, respectively.
5648 <!-- ----------------------------------------------------------------- -->
5649 <sect1>Creating and Configuring a Text box
5651 There is only one function for creating a new Text widget.
5653 GtkWidget *gtk_text_new( GtkAdjustment *hadj,
5654 GtkAdjustment *vadj );
5657 The arguments allow us to give the Text widget pointers to Adjustments
5658 that can be used to track the viewing position of the widget. Passing NULL
5659 values to either or both of these arguments will cause the gtk_text_new
5660 function to create it's own.
5663 void gtk_text_set_adjustments( GtkText *text,
5664 GtkAdjustment *hadj,
5665 GtkAdjustment *vadj );
5668 The above function allows the horizontal and vertical adjustments of a
5669 Text widget to be changed at any time.
5671 The text widget will not automatically create it's own scrollbars when
5672 the amount of text to be displayed is too long for the display window. We
5673 therefore have to create and add them to the display layout ourselves.
5676 vscrollbar = gtk_vscrollbar_new (GTK_TEXT(text)->vadj);
5677 gtk_box_pack_start(GTK_BOX(hbox), vscrollbar, FALSE, FALSE, 0);
5678 gtk_widget_show (vscrollbar);
5681 The above code snippet creates a new vertical scrollbar, and attaches
5682 it to the vertical adjustment of the text widget, <tt/text/. It then packs
5683 it into a box in the normal way.
5685 Note, currently the GtkText widget does not support horizontal scrollbars.
5687 There are two main ways in which a Text widget can be used: to allow the
5688 user to edit a body of text, or to allow us to display multiple lines of
5689 text to the user. In order for us to switch between these modes of
5690 operation, the text widget has the following function:
5693 void gtk_text_set_editable( GtkText *text,
5697 The <tt/editable/ argument is a TRUE or FALSE value that specifies whether
5698 the user is permitted to edit the contents of the Text widget. When the
5699 text widget is editable, it will display a cursor at the current insertion
5702 You are not, however, restricted to just using the text widget in these
5703 two modes. You can toggle the editable state of the text widget at any
5704 time, and can insert text at any time.
5706 The text widget wraps lines of text that are too long to
5707 fit onto a single line of the display window. It's default behaviour is
5708 to break words across line breaks. This can be changed using the next
5712 void gtk_text_set_word_wrap( GtkText *text,
5716 Using this function allows us to specify that the text widget should
5717 wrap long lines on word boundaries. The <tt/word_wrap/ argument is a
5718 TRUE or FALSE value.
5720 <!-- ----------------------------------------------------------------- -->
5721 <sect1>Text Manipulation
5723 The current insertion point of a Text widget can be set using
5725 void gtk_text_set_point( GtkText *text,
5729 where <tt/index/ is the position to set the insertion point.
5731 Analogous to this is the function for getting the current insertion point:
5734 guint gtk_text_get_point( GtkText *text );
5737 A function that is useful in combination with the above two functions is
5740 guint gtk_text_get_length( GtkText *text );
5743 which returns the current length of the Text widget. The length is the
5744 number of characters that are within the text block of the widget,
5745 including characters such as carriage-return, which marks the end of lines.
5747 In order to insert text at the current insertion point of a Text
5748 widget, the function gtk_text_insert is used, which also allows us to
5749 specify background and foreground colors and a font for the text.
5752 void gtk_text_insert( GtkText *text,
5760 Passing a value of <tt/NULL/ in as the value for the foreground color,
5761 background colour or font will result in the values set within the widget
5762 style to be used. Using a value of <tt/-1/ for the length parameter will
5763 result in the whole of the text string given being inserted.
5765 The text widget is one of the few within GTK that redraws itself
5766 dynamically, outside of the gtk_main function. This means that all changes
5767 to the contents of the text widget take effect immediately. This may be
5768 undesirable when performing multiple changes to the text widget. In order
5769 to allow us to perform multiple updates to the text widget without it
5770 continuously redrawing, we can freeze the widget, which temporarily stops
5771 it from automatically redrawing itself every time it is changed. We can
5772 then thaw the widget after our updates are complete.
5774 The following two functions perform this freeze and thaw action:
5777 void gtk_text_freeze( GtkText *text );
5779 void gtk_text_thaw( GtkText *text );
5782 Text is deleted from the text widget relative to the current insertion
5783 point by the following two functions. The return value is a TRUE or
5784 FALSE indicator of whether the operation was successful.
5787 gint gtk_text_backward_delete( GtkText *text,
5790 gint gtk_text_forward_delete ( GtkText *text,
5794 If you want to retrieve the contents of the text widget, then the macro
5795 <tt/GTK_TEXT_INDEX(t, index)/ allows you to retrieve the character at
5796 position <tt/index/ within the text widget <tt/t/.
5798 To retrieve larger blocks of text, we can use the function
5801 gchar *gtk_editable_get_chars( GtkEditable *editable,
5806 This is a function of the parent class of the text widget. A value of -1 as
5807 <tt/end_pos/ signifies the end of the text. The index of the text starts at 0.
5809 The function allocates a new chunk of memory for the text block, so don't forget
5810 to free it with a call to g_free when you have finished with it.
5812 <!-- ----------------------------------------------------------------- -->
5813 <sect1>Keyboard Shortcuts
5815 The text widget has a number of pre-installed keyboard shotcuts for common
5816 editing, motion and selection functions. These are accessed using Control
5817 and Alt key combinations.
5819 In addition to these, holding down the Control key whilst using cursor key
5820 movement will move the cursor by words rather than characters. Holding down
5821 Shift whilst using cursor movement will extend the selection.
5823 <sect2>Motion Shotcuts
5826 <item> Ctrl-A Beginning of line
5827 <item> Ctrl-E End of line
5828 <item> Ctrl-N Next Line
5829 <item> Ctrl-P Previous Line
5830 <item> Ctrl-B Backward one character
5831 <item> Ctrl-F Forward one character
5832 <item> Alt-B Backward one word
5833 <item> Alt-F Forward one word
5836 <sect2>Editing Shortcuts
5839 <item> Ctrl-H Delete Backward Character (Backspace)
5840 <item> Ctrl-D Delete Forward Character (Delete)
5841 <item> Ctrl-W Delete Backward Word
5842 <item> Alt-D Delete Forward Word
5843 <item> Ctrl-K Delete to end of line
5844 <item> Ctrl-U Delete line
5847 <sect2>Selection Shortcuts
5850 <item> Ctrl-X Cut to clipboard
5851 <item> Ctrl-C Copy to clipboard
5852 <item> Ctrl-V Paste from clipboard
5855 <!-- ***************************************************************** -->
5856 <sect> Undocumented Widgets
5857 <!-- ***************************************************************** -->
5859 These all require authors! :) Please consider contributing to our tutorial.
5861 If you must use one of these widgets that are undocumented, I strongly
5862 suggest you take a look at their respective header files in the GTK
5863 distribution. GTK's function names are very descriptive. Once you have an
5864 understanding of how things work, it's not difficult to figure out how to
5865 use a widget simply by looking at it's function declarations. This, along
5866 with a few examples from others' code, and it should be no problem.
5868 When you do come to understand all the functions of a new undocumented
5869 widget, please consider writing a tutorial on it so others may benifit
5872 <!-- ----------------------------------------------------------------- -->
5875 <!-- ----------------------------------------------------------------- -->
5878 <!-- ----------------------------------------------------------------- -->
5879 <sect1> Fixed Container
5881 <!-- ----------------------------------------------------------------- -->
5884 <!-- ----------------------------------------------------------------- -->
5885 <sect1> Range Controls
5887 <!-- ----------------------------------------------------------------- -->
5890 <!-- ----------------------------------------------------------------- -->
5894 (This may need to be rewritten to follow the style of the rest of the tutorial)
5898 Previews serve a number of purposes in GIMP/GTK. The most important one is
5899 this. High quality images may take up to tens of megabytes of memory - easy!
5900 Any operation on an image that big is bound to take a long time. If it takes
5901 you 5-10 trial-and-errors (i.e. 10-20 steps, since you have to revert after
5902 you make an error) to choose the desired modification, it make take you
5903 literally hours to make the right one - if you don't run out of memory
5904 first. People who have spent hours in color darkrooms know the feeling.
5905 Previews to the rescue!
5907 But the annoyance of the delay is not the only issue. Oftentimes it is
5908 helpful to compare the Before and After versions side-by-side or at least
5909 back-to-back. If you're working with big images and 10 second delays,
5910 obtaining the Before and After impressions is, to say the least, difficult.
5911 For 30M images (4"x6", 600dpi, 24 bit) the side-by-side comparison is right
5912 out for most people, while back-to-back is more like back-to-1001, 1002,
5913 ..., 1010-back! Previews to the rescue!
5915 But there's more. Previews allow for side-by-side pre-previews. In other
5916 words, you write a plug-in (e.g. the filterpack simulation) which would have
5917 a number of here's-what-it-would-look-like-if-you-were-to-do-this previews.
5918 An approach like this acts as a sort of a preview palette and is very
5919 effective fow subtle changes. Let's go previews!
5921 There's more. For certain plug-ins real-time image-specific human
5922 intervention maybe necessary. In the SuperNova plug-in, for example, the
5923 user is asked to enter the coordinates of the center of the future
5924 supernova. The easiest way to do this, really, is to present the user with a
5925 preview and ask him to intereactively select the spot. Let's go previews!
5927 Finally, a couple of misc uses. One can use previews even when not working
5928 with big images. For example, they are useful when rendering compicated
5929 patterns. (Just check out the venerable Diffraction plug-in + many other
5930 ones!) As another example, take a look at the colormap rotation plug-in
5931 (work in progress). You can also use previews for little logo's inside you
5932 plug-ins and even for an image of yourself, The Author. Let's go previews!
5934 When Not to Use Previews
5936 Don't use previews for graphs, drawing etc. GDK is much faster for that. Use
5937 previews only for rendered images!
5941 You can stick a preview into just about anything. In a vbox, an hbox, a
5942 table, a button, etc. But they look their best in tight frames around them.
5943 Previews by themselves do not have borders and look flat without them. (Of
5944 course, if the flat look is what you want...) Tight frames provide the
5949 Previews in many ways are like any other widgets in GTK (whatever that
5950 means) except they possess an addtional feature: they need to be filled with
5951 some sort of an image! First, we will deal exclusively with the GTK aspect
5952 of previews and then we'll discuss how to fill them.
5958 /* Create a preview widget,
5959 set its size, an show it */
5961 preview=gtk_preview_new(GTK_PREVIEW_COLOR)
5963 GTK_PREVIEW_GRAYSCALE);*/
5964 gtk_preview_size (GTK_PREVIEW (preview), WIDTH, HEIGHT);
5965 gtk_widget_show(preview);
5966 my_preview_rendering_function(preview);
5968 Oh yeah, like I said, previews look good inside frames, so how about:
5970 GtkWidget *create_a_preview(int Width,
5977 frame = gtk_frame_new(NULL);
5978 gtk_frame_set_shadow_type (GTK_FRAME (frame), GTK_SHADOW_IN);
5979 gtk_container_border_width (GTK_CONTAINER(frame),0);
5980 gtk_widget_show(frame);
5982 preview=gtk_preview_new (Colorfulness?GTK_PREVIEW_COLOR
5983 :GTK_PREVIEW_GRAYSCALE);
5984 gtk_preview_size (GTK_PREVIEW (preview), Width, Height);
5985 gtk_container_add(GTK_CONTAINER(frame),preview);
5986 gtk_widget_show(preview);
5988 my_preview_rendering_function(preview);
5992 That's my basic preview. This routine returns the "parent" frame so you can
5993 place it somewhere else in your interface. Of course, you can pass the
5994 parent frame to this routine as a parameter. In many situations, however,
5995 the contents of the preview are changed continually by your application. In
5996 this case you may want to pass a pointer to the preview to a
5997 "create_a_preview()" and thus have control of it later.
5999 One more important note that may one day save you a lot of time. Sometimes
6000 it is desirable to label you preview. For example, you may label the preview
6001 containing the original image as "Original" and the one containing the
6002 modified image as "Less Original". It might occure to you to pack the
6003 preview along with the appropriate label into a vbox. The unexpected caveat
6004 is that if the label is wider than the preview (which may happen for a
6005 variety of reasons unforseeable to you, from the dynamic decision on the
6006 size of the preview to the size of the font) the frame expands and no longer
6007 fits tightly over the preview. The same problem can probably arise in other
6012 The solution is to place the preview and the label into a 2x1 table and by
6013 attaching them with the following paramters (this is one possible variations
6014 of course. The key is no GTK_FILL in the second attachment):
6016 gtk_table_attach(GTK_TABLE(table),label,0,1,0,1,
6018 GTK_EXPAND|GTK_FILL,
6020 gtk_table_attach(GTK_TABLE(table),frame,0,1,1,2,
6026 And here's the result:
6032 Making a preview clickable is achieved most easily by placing it in a
6033 button. It also adds a nice border around the preview and you may not even
6034 need to place it in a frame. See the Filter Pack Simulation plug-in for an
6037 This is pretty much it as far as GTK is concerned.
6039 Filling In a Preview
6041 In order to familiarize ourselves with the basics of filling in previews,
6042 let's create the following pattern (contrived by trial and error):
6047 my_preview_rendering_function(GtkWidget *preview)
6050 #define HALF (SIZE/2)
6052 guchar *row=(guchar *) malloc(3*SIZE); /* 3 bits per dot */
6053 gint i, j; /* Coordinates */
6054 double r, alpha, x, y;
6056 if (preview==NULL) return; /* I usually add this when I want */
6057 /* to avoid silly crashes. You */
6058 /* should probably make sure that */
6059 /* everything has been nicely */
6061 for (j=0; j < ABS(cos(2*alpha)) ) { /* Are we inside the shape? */
6062 /* glib.h contains ABS(x). */
6063 row[i*3+0] = sqrt(1-r)*255; /* Define Red */
6064 row[i*3+1] = 128; /* Define Green */
6065 row[i*3+2] = 224; /* Define Blue */
6066 } /* "+0" is for alignment! */
6069 row[i*3+1] = ABS(sin((float)i/SIZE*2*PI))*255;
6070 row[i*3+2] = ABS(sin((float)j/SIZE*2*PI))*255;
6073 gtk_preview_draw_row( GTK_PREVIEW(preview),row,0,j,SIZE);
6074 /* Insert "row" into "preview" starting at the point with */
6075 /* coordinates (0,j) first column, j_th row extending SIZE */
6076 /* pixels to the right */
6079 free(row); /* save some space */
6080 gtk_widget_draw(preview,NULL); /* what does this do? */
6081 gdk_flush(); /* or this? */
6084 Non-GIMP users can have probably seen enough to do a lot of things already.
6085 For the GIMP users I have a few pointers to add.
6089 It is probably wize to keep a reduced version of the image around with just
6090 enough pixels to fill the preview. This is done by selecting every n'th
6091 pixel where n is the ratio of the size of the image to the size of the
6092 preview. All further operations (including filling in the previews) are then
6093 performed on the reduced number of pixels only. The following is my
6094 implementation of reducing the image. (Keep in mind that I've had only basic
6097 (UNTESTED CODE ALERT!!!)
6109 SELCTION_IN_CONTEXT,
6113 ReducedImage *Reduce_The_Image(GDrawable *drawable,
6118 /* This function reduced the image down to the the selected preview size */
6119 /* The preview size is determine by LongerSize, i.e. the greater of the */
6120 /* two dimentions. Works for RGB images only! */
6121 gint RH, RW; /* Reduced height and reduced width */
6122 gint width, height; /* Width and Height of the area being reduced */
6123 gint bytes=drawable->bpp;
6124 ReducedImage *temp=(ReducedImage *)malloc(sizeof(ReducedImage));
6126 guchar *tempRGB, *src_row, *tempmask, *src_mask_row,R,G,B;
6127 gint i, j, whichcol, whichrow, x1, x2, y1, y2;
6128 GPixelRgn srcPR, srcMask;
6129 gint NoSelectionMade=TRUE; /* Assume that we're dealing with the entire */
6132 gimp_drawable_mask_bounds (drawable->id, &x1, &y1, &x2, &y2);
6135 /* If there's a SELECTION, we got its bounds!)
6137 if (width != drawable->width && height != drawable->height)
6138 NoSelectionMade=FALSE;
6139 /* Become aware of whether the user has made an active selection */
6140 /* This will become important later, when creating a reduced mask. */
6142 /* If we want to preview the entire image, overrule the above! */
6143 /* Of course, if no selection has been made, this does nothing! */
6144 if (Selection==ENTIRE_IMAGE) {
6148 y2=drawable->height;
6151 /* If we want to preview a selection with some surronding area we */
6152 /* have to expand it a little bit. Consider it a bit of a riddle. */
6153 if (Selection==SELECTION_IN_CONTEXT) {
6154 x1=MAX(0, x1-width/2.0);
6155 x2=MIN(drawable->width, x2+width/2.0);
6156 y1=MAX(0, y1-height/2.0);
6157 y2=MIN(drawable->height, y2+height/2.0);
6160 /* How we can determine the width and the height of the area being */
6165 /* The lines below determine which dimension is to be the longer */
6166 /* side. The idea borrowed from the supernova plug-in. I suspect I */
6167 /* could've thought of it myself, but the truth must be told. */
6168 /* Plagiarism stinks! */
6171 RH=(float) height * (float) LongerSize/ (float) width;
6175 RW=(float)width * (float) LongerSize/ (float) height;
6178 /* The intire image is stretched into a string! */
6179 tempRGB = (guchar *) malloc(RW*RH*bytes);
6180 tempmask = (guchar *) malloc(RW*RH);
6182 gimp_pixel_rgn_init (&srcPR, drawable, x1, y1, width, height, FALSE, FALSE);
6183 gimp_pixel_rgn_init (&srcMask, mask, x1, y1, width, height, FALSE, FALSE);
6185 /* Grab enough to save a row of image and a row of mask. */
6186 src_row = (guchar *) malloc (width*bytes);
6187 src_mask_row = (guchar *) malloc (width);
6189 for (i=0; i < RH; i++) {
6190 whichrow=(float)i*(float)height/(float)RH;
6191 gimp_pixel_rgn_get_row (&srcPR, src_row, x1, y1+whichrow, width);
6192 gimp_pixel_rgn_get_row (&srcMask, src_mask_row, x1, y1+whichrow, width);
6194 for (j=0; j < RW; j++) {
6195 whichcol=(float)j*(float)width/(float)RW;
6197 /* No selection made = each point is completely selected! */
6198 if (NoSelectionMade)
6199 tempmask[i*RW+j]=255;
6201 tempmask[i*RW+j]=src_mask_row[whichcol];
6203 /* Add the row to the one long string which now contains the image! */
6204 tempRGB[i*RW*bytes+j*bytes+0]=src_row[whichcol*bytes+0];
6205 tempRGB[i*RW*bytes+j*bytes+1]=src_row[whichcol*bytes+1];
6206 tempRGB[i*RW*bytes+j*bytes+2]=src_row[whichcol*bytes+2];
6208 /* Hold on to the alpha as well */
6210 tempRGB[i*RW*bytes+j*bytes+3]=src_row[whichcol*bytes+3];
6217 temp->mask=tempmask;
6221 The following is a preview function which used the same ReducedImage type!
6222 Note that it uses fakes transparancy (if one is present by means of
6223 fake_transparancy which is defined as follows:
6225 gint fake_transparency(gint i, gint j)
6227 if ( ((i%20)- 10) * ((j%20)- 10)>0 )
6233 Now here's the preview function:
6236 my_preview_render_function(GtkWidget *preview,
6240 gint Inten, bytes=drawable->bpp;
6243 gint RW=reduced->width;
6244 gint RH=reduced->height;
6245 guchar *row=malloc(bytes*RW);;
6248 for (i=0; i < RH; i++) {
6249 for (j=0; j < RW; j++) {
6251 row[j*3+0] = reduced->rgb[i*RW*bytes + j*bytes + 0];
6252 row[j*3+1] = reduced->rgb[i*RW*bytes + j*bytes + 1];
6253 row[j*3+2] = reduced->rgb[i*RW*bytes + j*bytes + 2];
6256 for (k=0; k<3; k++) {
6257 float transp=reduced->rgb[i*RW*bytes+j*bytes+3]/255.0;
6258 row[3*j+k]=transp*a[3*j+k]+(1-transp)*fake_transparency(i,j);
6261 gtk_preview_draw_row( GTK_PREVIEW(preview),row,0,i,RW);
6265 gtk_widget_draw(preview,NULL);
6271 guint gtk_preview_get_type (void);
6273 void gtk_preview_uninit (void);
6275 GtkWidget* gtk_preview_new (GtkPreviewType type);
6276 /* Described above */
6277 void gtk_preview_size (GtkPreview *preview,
6280 /* Allows you to resize an existing preview. */
6281 /* Apparantly there's a bug in GTK which makes */
6282 /* this process messy. A way to clean up a mess */
6283 /* is to manually resize the window containing */
6284 /* the preview after resizing the preview. */
6286 void gtk_preview_put (GtkPreview *preview,
6297 void gtk_preview_put_row (GtkPreview *preview,
6305 void gtk_preview_draw_row (GtkPreview *preview,
6310 /* Described in the text */
6312 void gtk_preview_set_expand (GtkPreview *preview,
6316 /* No clue for any of the below but */
6317 /* should be standard for most widgets */
6318 void gtk_preview_set_gamma (double gamma);
6319 void gtk_preview_set_color_cube (guint nred_shades,
6320 guint ngreen_shades,
6322 guint ngray_shades);
6323 void gtk_preview_set_install_cmap (gint install_cmap);
6324 void gtk_preview_set_reserved (gint nreserved);
6325 GdkVisual* gtk_preview_get_visual (void);
6326 GdkColormap* gtk_preview_get_cmap (void);
6327 GtkPreviewInfo* gtk_preview_get_info (void);
6333 <!-- ***************************************************************** -->
6334 <sect>The EventBox Widget<label id="sec_The_EventBox_Widget">
6335 <!-- ***************************************************************** -->
6337 Some gtk widgets don't have associated X windows, so they just draw on
6338 their parents. Because of this, they cannot recieve events
6339 and if they are incorrectly sized, they don't clip so you can get
6340 messy overwritting etc. If you require more from these widgets, the
6341 EventBox is for you.
6343 At first glance, the EventBox widget might appear to be totally
6344 useless. It draws nothing on the screen and responds to no
6345 events. However, it does serve a function - it provides an X window for
6346 its child widget. This is important as many GTK widgets do not
6347 have an associated X window. Not having an X window saves memory and
6348 improves performance, but also has some drawbacks. A widget without an
6349 X window cannot receive events, and does not perform any clipping on
6350 it's contents. Although the name <em/EventBox/ emphasizes the
6351 event-handling function, the widget can also be used for clipping.
6352 (And more ... see the example below.)
6354 To create a new EventBox widget, use:
6357 GtkWidget *gtk_event_box_new( void );
6360 A child widget can then be added to this EventBox:
6363 gtk_container_add( GTK_CONTAINER(event_box), widget );
6366 The following example demonstrates both uses of an EventBox - a label
6367 is created that is clipped to a small box, and set up so that a
6368 mouse-click on the label causes the program to exit.
6371 /* example-start eventbox eventbox.c */
6373 #include <gtk/gtk.h>
6376 main (int argc, char *argv[])
6379 GtkWidget *event_box;
6382 gtk_init (&argc, &argv);
6384 window = gtk_window_new (GTK_WINDOW_TOPLEVEL);
6386 gtk_window_set_title (GTK_WINDOW (window), "Event Box");
6388 gtk_signal_connect (GTK_OBJECT (window), "destroy",
6389 GTK_SIGNAL_FUNC (gtk_exit), NULL);
6391 gtk_container_border_width (GTK_CONTAINER (window), 10);
6393 /* Create an EventBox and add it to our toplevel window */
6395 event_box = gtk_event_box_new ();
6396 gtk_container_add (GTK_CONTAINER(window), event_box);
6397 gtk_widget_show (event_box);
6399 /* Create a long label */
6401 label = gtk_label_new ("Click here to quit, quit, quit, quit, quit");
6402 gtk_container_add (GTK_CONTAINER (event_box), label);
6403 gtk_widget_show (label);
6405 /* Clip it short. */
6406 gtk_widget_set_usize (label, 110, 20);
6408 /* And bind an action to it */
6409 gtk_widget_set_events (event_box, GDK_BUTTON_PRESS_MASK);
6410 gtk_signal_connect (GTK_OBJECT(event_box), "button_press_event",
6411 GTK_SIGNAL_FUNC (gtk_exit), NULL);
6413 /* Yet one more thing you need an X window for ... */
6415 gtk_widget_realize (event_box);
6416 gdk_window_set_cursor (event_box->window, gdk_cursor_new (GDK_HAND1));
6418 gtk_widget_show (window);
6427 <!-- ***************************************************************** -->
6428 <sect>Setting Widget Attributes<label id="sec_setting_widget_attributes">
6429 <!-- ***************************************************************** -->
6431 This describes the functions used to operate on widgets. These can be used
6432 to set style, padding, size etc.
6434 (Maybe I should make a whole section on accelerators.)
6437 void gtk_widget_install_accelerator( GtkWidget *widget,
6438 GtkAcceleratorTable *table,
6443 void gtk_widget_remove_accelerator ( GtkWidget *widget,
6444 GtkAcceleratorTable *table,
6445 gchar *signal_name);
6447 void gtk_widget_activate( GtkWidget *widget );
6449 void gtk_widget_set_name( GtkWidget *widget,
6452 gchar *gtk_widget_get_name( GtkWidget *widget );
6454 void gtk_widget_set_sensitive( GtkWidget *widget,
6457 void gtk_widget_set_style( GtkWidget *widget,
6460 GtkStyle *gtk_widget_get_style( GtkWidget *widget );
6462 GtkStyle *gtk_widget_get_default_style( void );
6464 void gtk_widget_set_uposition( GtkWidget *widget,
6468 void gtk_widget_set_usize( GtkWidget *widget,
6472 void gtk_widget_grab_focus( GtkWidget *widget );
6474 void gtk_widget_show( GtkWidget *widget );
6476 void gtk_widget_hide( GtkWidget *widget );
6479 <!-- ***************************************************************** -->
6480 <sect>Timeouts, IO and Idle Functions<label id="sec_timeouts">
6481 <!-- ***************************************************************** -->
6483 <!-- ----------------------------------------------------------------- -->
6486 You may be wondering how you make GTK do useful work when in gtk_main.
6487 Well, you have several options. Using the following functions you can
6488 create a timeout function that will be called every "interval"
6492 gint gtk_timeout_add( guint32 interval,
6493 GtkFunction function,
6497 The first argument is the number of milliseconds between calls to your
6498 function. The second argument is the function you wish to have called, and
6499 the third, the data passed to this callback function. The return value is
6500 an integer "tag" which may be used to stop the timeout by calling:
6503 void gtk_timeout_remove( gint tag );
6506 You may also stop the timeout function by returning zero or FALSE from
6507 your callback function. Obviously this means if you want your function to
6508 continue to be called, it should return a non-zero value, ie TRUE.
6510 The declaration of your callback should look something like this:
6513 gint timeout_callback( gpointer data );
6516 <!-- ----------------------------------------------------------------- -->
6517 <sect1>Monitoring IO
6519 Another nifty feature of GTK, is the ability to have it check for data on a
6520 file descriptor for you (as returned by open(2) or socket(2)). This is
6521 especially useful for networking applications. The function:
6524 gint gdk_input_add( gint source,
6525 GdkInputCondition condition,
6526 GdkInputFunction function,
6530 Where the first argument is the file descriptor you wish to have watched,
6531 and the second specifies what you want GDK to look for. This may be one of:
6534 <item>GDK_INPUT_READ - Call your function when there is data ready for
6535 reading on your file descriptor.
6537 <item>GDK_INPUT_WRITE - Call your function when the file descriptor is
6541 As I'm sure you've figured out already, the third argument is the function
6542 you wish to have called when the above conditions are satisfied, and the
6543 fourth is the data to pass to this function.
6545 The return value is a tag that may be used to stop GDK from monitoring this
6546 file descriptor using the following function.
6549 void gdk_input_remove( gint tag );
6552 The callback function should be declared as:
6555 void input_callback( gpointer data,
6557 GdkInputCondition condition );
6560 <!-- ----------------------------------------------------------------- -->
6561 <sect1>Idle Functions
6563 <!-- Need to check on idle priorities - TRG -->
6564 What if you have a function you want called when nothing else is
6568 gint gtk_idle_add( GtkFunction function,
6572 This causes GTK to call the specified function whenever nothing else is
6576 void gtk_idle_remove( gint tag );
6579 I won't explain the meaning of the arguments as they follow very much like
6580 the ones above. The function pointed to by the first argument to
6581 gtk_idle_add will be called whenever the opportunity arises. As with the
6582 others, returning FALSE will stop the idle function from being called.
6584 <!-- ***************************************************************** -->
6585 <sect>Managing Selections
6586 <!-- ***************************************************************** -->
6588 <!-- ----------------------------------------------------------------- -->
6591 One type of interprocess communication supported by GTK is
6592 <em>selections</em>. A selection identifies a chunk of data, for
6593 instance, a portion of text, selected by the user in some fashion, for
6594 instance, by dragging with the mouse. Only one application on a
6595 display, (the <em>owner</em> can own a particular selection at one
6596 time, so when a selection is claimed by one application, the previous
6597 owner must indicate to the user that selection has been
6598 relinquished. Other applications can request the contents of a
6599 selection in different forms, called <em>targets</em>. There can be
6600 any number of selections, but most X applications only handle one, the
6601 <em>primary selection</em>.
6603 In most cases, it isn't necessary for a GTK application to deal with
6604 selections itself. The standard widgets, such as the Entry widget,
6605 already have the capability to claim the selection when appropriate
6606 (e.g., when the user drags over text), and to retrieve the contents of
6607 the selection owned by another widget, or another application (e.g.,
6608 when the user clicks the second mouse button). However, there may be
6609 cases in which you want to give other widgets the ability to supply
6610 the selection, or you wish to retrieve targets not supported by
6613 A fundamental concept needed to understand selection handling is that
6614 of the <em>atom</em>. An atom is an integer that uniquely identifies a
6615 string (on a certain display). Certain atoms are predefined by the X
6616 server, and in some cases there are constants in <tt>gtk.h</tt>
6617 corresponding to these atoms. For instance the constant
6618 <tt>GDK_PRIMARY_SELECTION</tt> corresponds to the string "PRIMARY".
6619 In other cases, you should use the functions
6620 <tt>gdk_atom_intern()</tt>, to get the atom corresponding to a string,
6621 and <tt>gdk_atom_name()</tt>, to get the name of an atom. Both
6622 selections and targets are identifed by atoms.
6624 <!-- ----------------------------------------------------------------- -->
6625 <sect1> Retrieving the selection
6627 Retrieving the selection is an asynchronous process. To start the
6631 gint gtk_selection_convert( GtkWidget *widget,
6637 This <em>converts</em> the selection into the form specified by
6638 <tt/target/. If at all possible, the time field should be the time
6639 from the event that triggered the selection. This helps make sure that
6640 events occur in the order that the user requested them. However, if it
6641 is not available (for instance, if the conversion was triggered by
6642 a "clicked" signal), then you can use the constant
6643 <tt>GDK_CURRENT_TIME</tt>.
6645 When the selection owner responds to the request, a
6646 "selection_received" signal is sent to your application. The handler
6647 for this signal receives a pointer to a <tt>GtkSelectionData</tt>
6648 structure, which is defined as:
6651 struct _GtkSelectionData
6662 <tt>selection</tt> and <tt>target</tt> are the values you gave in your
6663 <tt>gtk_selection_convert()</tt> call. <tt>type</tt> is an atom that
6664 identifies the type of data returned by the selection owner. Some
6665 possible values are "STRING", a string of latin-1 characters, "ATOM",
6666 a series of atoms, "INTEGER", an integer, etc. Most targets can only
6667 return one type. <tt/format/ gives the length of the units (for
6668 instance characters) in bits. Usually, you don't care about this when
6669 receiving data. <tt>data</tt> is a pointer to the returned data, and
6670 <tt>length</tt> gives the length of the returned data, in bytes. If
6671 <tt>length</tt> is negative, then an error occurred and the selection
6672 could not be retrieved. This might happen if no application owned the
6673 selection, or if you requested a target that the application didn't
6674 support. The buffer is actually guaranteed to be one byte longer than
6675 <tt>length</tt>; the extra byte will always be zero, so it isn't
6676 necessary to make a copy of strings just to null terminate them.
6678 In the following example, we retrieve the special target "TARGETS",
6679 which is a list of all targets into which the selection can be
6683 /* example-start selection gettargets.c */
6685 #include <gtk/gtk.h>
6687 void selection_received (GtkWidget *widget,
6688 GtkSelectionData *selection_data,
6691 /* Signal handler invoked when user clicks on the "Get Targets" button */
6693 get_targets (GtkWidget *widget, gpointer data)
6695 static GdkAtom targets_atom = GDK_NONE;
6697 /* Get the atom corresonding to the string "TARGETS" */
6698 if (targets_atom == GDK_NONE)
6699 targets_atom = gdk_atom_intern ("TARGETS", FALSE);
6701 /* And request the "TARGETS" target for the primary selection */
6702 gtk_selection_convert (widget, GDK_SELECTION_PRIMARY, targets_atom,
6706 /* Signal handler called when the selections owner returns the data */
6708 selection_received (GtkWidget *widget, GtkSelectionData *selection_data,
6715 /* **** IMPORTANT **** Check to see if retrieval succeeded */
6716 if (selection_data->length < 0)
6718 g_print ("Selection retrieval failed\n");
6721 /* Make sure we got the data in the expected form */
6722 if (selection_data->type != GDK_SELECTION_TYPE_ATOM)
6724 g_print ("Selection \"TARGETS\" was not returned as atoms!\n");
6728 /* Print out the atoms we received */
6729 atoms = (GdkAtom *)selection_data->data;
6732 for (i=0; i<selection_data->length/sizeof(GdkAtom); i++)
6735 name = gdk_atom_name (atoms[i]);
6737 g_print ("%s\n",name);
6739 g_print ("(bad atom)\n");
6746 main (int argc, char *argv[])
6751 gtk_init (&argc, &argv);
6753 /* Create the toplevel window */
6755 window = gtk_window_new (GTK_WINDOW_TOPLEVEL);
6756 gtk_window_set_title (GTK_WINDOW (window), "Event Box");
6757 gtk_container_border_width (GTK_CONTAINER (window), 10);
6759 gtk_signal_connect (GTK_OBJECT (window), "destroy",
6760 GTK_SIGNAL_FUNC (gtk_exit), NULL);
6762 /* Create a button the user can click to get targets */
6764 button = gtk_button_new_with_label ("Get Targets");
6765 gtk_container_add (GTK_CONTAINER (window), button);
6767 gtk_signal_connect (GTK_OBJECT(button), "clicked",
6768 GTK_SIGNAL_FUNC (get_targets), NULL);
6769 gtk_signal_connect (GTK_OBJECT(button), "selection_received",
6770 GTK_SIGNAL_FUNC (selection_received), NULL);
6772 gtk_widget_show (button);
6773 gtk_widget_show (window);
6782 <!-- ----------------------------------------------------------------- -->
6783 <sect1> Supplying the selection
6785 Supplying the selection is a bit more complicated. You must register
6786 handlers that will be called when your selection is requested. For
6787 each selection/target pair you will handle, you make a call to:
6790 void gtk_selection_add_handler( GtkWidget *widget,
6793 GtkSelectionFunction function,
6794 GtkRemoveFunction remove_func,
6798 <tt/widget/, <tt/selection/, and <tt/target/ identify the requests
6799 this handler will manage. <tt/remove_func/, if not
6800 NULL, will be called when the signal handler is removed. This is
6801 useful, for instance, for interpreted languages which need to
6802 keep track of a reference count for <tt/data/.
6804 The callback function has the signature:
6807 typedef void (*GtkSelectionFunction)( GtkWidget *widget,
6808 GtkSelectionData *selection_data,
6813 The GtkSelectionData is the same as above, but this time, we're
6814 responsible for filling in the fields <tt/type/, <tt/format/,
6815 <tt/data/, and <tt/length/. (The <tt/format/ field is actually
6816 important here - the X server uses it to figure out whether the data
6817 needs to be byte-swapped or not. Usually it will be 8 - <em/i.e./ a
6818 character - or 32 - <em/i.e./ a. integer.) This is done by calling the
6822 void gtk_selection_data_set( GtkSelectionData *selection_data,
6829 This function takes care of properly making a copy of the data so that
6830 you don't have to worry about keeping it around. (You should not fill
6831 in the fields of the GtkSelectionData structure by hand.)
6833 When prompted by the user, you claim ownership of the selection by
6837 gint gtk_selection_owner_set( GtkWidget *widget,
6842 If another application claims ownership of the selection, you will
6843 receive a "selection_clear_event".
6845 As an example of supplying the selection, the following program adds
6846 selection functionality to a toggle button. When the toggle button is
6847 depressed, the program claims the primary selection. The only target
6848 supported (aside from certain targets like "TARGETS" supplied by GTK
6849 itself), is the "STRING" target. When this target is requested, a
6850 string representation of the time is returned.
6853 /* example-start selection setselection.c */
6855 #include <gtk/gtk.h>
6858 /* Callback when the user toggles the selection */
6860 selection_toggled (GtkWidget *widget, gint *have_selection)
6862 if (GTK_TOGGLE_BUTTON(widget)->active)
6864 *have_selection = gtk_selection_owner_set (widget,
6865 GDK_SELECTION_PRIMARY,
6867 /* if claiming the selection failed, we return the button to
6869 if (!*have_selection)
6870 gtk_toggle_button_set_state (GTK_TOGGLE_BUTTON(widget), FALSE);
6874 if (*have_selection)
6876 /* Before clearing the selection by setting the owner to NULL,
6877 we check if we are the actual owner */
6878 if (gdk_selection_owner_get (GDK_SELECTION_PRIMARY) == widget->window)
6879 gtk_selection_owner_set (NULL, GDK_SELECTION_PRIMARY,
6881 *have_selection = FALSE;
6886 /* Called when another application claims the selection */
6888 selection_clear (GtkWidget *widget, GdkEventSelection *event,
6889 gint *have_selection)
6891 *have_selection = FALSE;
6892 gtk_toggle_button_set_state (GTK_TOGGLE_BUTTON(widget), FALSE);
6897 /* Supplies the current time as the selection. */
6899 selection_handle (GtkWidget *widget,
6900 GtkSelectionData *selection_data,
6904 time_t current_time;
6906 current_time = time (NULL);
6907 timestr = asctime (localtime(&current_time));
6908 /* When we return a single string, it should not be null terminated.
6909 That will be done for us */
6911 gtk_selection_data_set (selection_data, GDK_SELECTION_TYPE_STRING,
6912 8, timestr, strlen(timestr));
6916 main (int argc, char *argv[])
6920 GtkWidget *selection_button;
6922 static int have_selection = FALSE;
6924 gtk_init (&argc, &argv);
6926 /* Create the toplevel window */
6928 window = gtk_window_new (GTK_WINDOW_TOPLEVEL);
6929 gtk_window_set_title (GTK_WINDOW (window), "Event Box");
6930 gtk_container_border_width (GTK_CONTAINER (window), 10);
6932 gtk_signal_connect (GTK_OBJECT (window), "destroy",
6933 GTK_SIGNAL_FUNC (gtk_exit), NULL);
6935 /* Create a toggle button to act as the selection */
6937 selection_button = gtk_toggle_button_new_with_label ("Claim Selection");
6938 gtk_container_add (GTK_CONTAINER (window), selection_button);
6939 gtk_widget_show (selection_button);
6941 gtk_signal_connect (GTK_OBJECT(selection_button), "toggled",
6942 GTK_SIGNAL_FUNC (selection_toggled), &have_selection);
6943 gtk_signal_connect (GTK_OBJECT(selection_button), "selection_clear_event",
6944 GTK_SIGNAL_FUNC (selection_clear), &have_selection);
6946 gtk_selection_add_handler (selection_button, GDK_SELECTION_PRIMARY,
6947 GDK_SELECTION_TYPE_STRING,
6948 selection_handle, NULL);
6950 gtk_widget_show (selection_button);
6951 gtk_widget_show (window);
6961 <!-- ***************************************************************** -->
6962 <sect>glib<label id="sec_glib">
6963 <!-- ***************************************************************** -->
6965 glib provides many useful functions and definitions available for use
6966 when creating GDK and GTK applications. I will list them all here with
6967 a brief explanation. Many are duplicates of standard libc functions so
6968 I won't go into detail on those. This is mostly to be used as a reference,
6969 so you know what is available for use.
6971 <!-- ----------------------------------------------------------------- -->
6974 Definitions for the extremes of many of the standard types are:
6989 Also, the following typedefs. The ones left unspecified are dynamically set
6990 depending on the architecture. Remember to avoid counting on the size of a
6991 pointer if you want to be portable! Eg, a pointer on an Alpha is 8 bytes, but 4
7001 unsigned char guchar;
7002 unsigned short gushort;
7003 unsigned long gulong;
7008 long double gldouble;
7020 <!-- ----------------------------------------------------------------- -->
7021 <sect1>Doubly Linked Lists
7023 The following functions are used to create, manage, and destroy doubly
7024 linked lists. I assume you know what linked lists are, as it is beyond the scope
7025 of this document to explain them. Of course, it's not required that you
7026 know these for general use of GTK, but they are nice to know.
7029 GList *g_list_alloc( void );
7031 void g_list_free( GList *list );
7033 void g_list_free_1( GList *list );
7035 GList *g_list_append( GList *list,
7038 GList *g_list_prepend( GList *list,
7041 GList *g_list_insert( GList *list,
7045 GList *g_list_remove( GList *list,
7048 GList *g_list_remove_link( GList *list,
7051 GList *g_list_reverse( GList *list );
7053 GList *g_list_nth( GList *list,
7056 GList *g_list_find( GList *list,
7059 GList *g_list_last( GList *list );
7061 GList *g_list_first( GList *list );
7063 gint g_list_length( GList *list );
7065 void g_list_foreach( GList *list,
7067 gpointer user_data );
7070 <!-- ----------------------------------------------------------------- -->
7071 <sect1>Singly Linked Lists
7073 Many of the above functions for singly linked lists are identical to the
7074 above. Here is a complete list:
7076 GSList *g_slist_alloc( void );
7078 void g_slist_free( GSList *list );
7080 void g_slist_free_1( GSList *list );
7082 GSList *g_slist_append( GSList *list,
7085 GSList *g_slist_prepend( GSList *list,
7088 GSList *g_slist_insert( GSList *list,
7092 GSList *g_slist_remove( GSList *list,
7095 GSList *g_slist_remove_link( GSList *list,
7098 GSList *g_slist_reverse( GSList *list );
7100 GSList *g_slist_nth( GSList *list,
7103 GSList *g_slist_find( GSList *list,
7106 GSList *g_slist_last( GSList *list );
7108 gint g_slist_length( GSList *list );
7110 void g_slist_foreach( GSList *list,
7112 gpointer user_data );
7116 <!-- ----------------------------------------------------------------- -->
7117 <sect1>Memory Management
7120 gpointer g_malloc( gulong size );
7123 This is a replacement for malloc(). You do not need to check the return
7124 vaule as it is done for you in this function.
7127 gpointer g_malloc0( gulong size );
7130 Same as above, but zeroes the memory before returning a pointer to it.
7133 gpointer g_realloc( gpointer mem,
7137 Relocates "size" bytes of memory starting at "mem". Obviously, the
7138 memory should have been previously allocated.
7141 void g_free( gpointer mem );
7144 Frees memory. Easy one.
7147 void g_mem_profile( void );
7150 Dumps a profile of used memory, but requries that you add #define
7151 MEM_PROFILE to the top of glib/gmem.c and re-make and make install.
7154 void g_mem_check( gpointer mem );
7157 Checks that a memory location is valid. Requires you add #define
7158 MEM_CHECK to the top of gmem.c and re-make and make install.
7160 <!-- ----------------------------------------------------------------- -->
7166 GTimer *g_timer_new( void );
7168 void g_timer_destroy( GTimer *timer );
7170 void g_timer_start( GTimer *timer );
7172 void g_timer_stop( GTimer *timer );
7174 void g_timer_reset( GTimer *timer );
7176 gdouble g_timer_elapsed( GTimer *timer,
7177 gulong *microseconds );
7180 <!-- ----------------------------------------------------------------- -->
7181 <sect1>String Handling
7183 A whole mess of string handling functions. They all look very interesting, and
7184 probably better for many purposes than the standard C string functions, but
7185 require documentation.
7188 GString *g_string_new( gchar *init );
7190 void g_string_free( GString *string,
7191 gint free_segment );
7193 GString *g_string_assign( GString *lval,
7196 GString *g_string_truncate( GString *string,
7199 GString *g_string_append( GString *string,
7202 GString *g_string_append_c( GString *string,
7205 GString *g_string_prepend( GString *string,
7208 GString *g_string_prepend_c( GString *string,
7211 void g_string_sprintf( GString *string,
7215 void g_string_sprintfa ( GString *string,
7220 <!-- ----------------------------------------------------------------- -->
7221 <sect1>Utility and Error Functions
7224 gchar *g_strdup( const gchar *str );
7227 Replacement strdup function. Copies the original strings contents to
7228 newly allocated memory, and returns a pointer to it.
7231 gchar *g_strerror( gint errnum );
7234 I recommend using this for all error messages. It's much nicer, and more
7235 portable than perror() or others. The output is usually of the form:
7238 program name:function that failed:file or further description:strerror
7241 Here's an example of one such call used in our hello_world program:
7244 g_print("hello_world:open:%s:%s\n", filename, g_strerror(errno));
7248 void g_error( gchar *format, ... );
7251 Prints an error message. The format is just like printf, but it
7252 prepends "** ERROR **: " to your message, and exits the program.
7253 Use only for fatal errors.
7256 void g_warning( gchar *format, ... );
7259 Same as above, but prepends "** WARNING **: ", and does not exit the
7263 void g_message( gchar *format, ... );
7266 Prints "message: " prepended to the string you pass in.
7269 void g_print( gchar *format, ... );
7272 Replacement for printf().
7274 And our last function:
7277 gchar *g_strsignal( gint signum );
7280 Prints out the name of the Unix system signal given the signal number.
7281 Useful in generic signal handling functions.
7283 All of the above are more or less just stolen from glib.h. If anyone cares
7284 to document any function, just send me an email!
7286 <!-- ***************************************************************** -->
7287 <sect>GTK's rc Files
7288 <!-- ***************************************************************** -->
7290 GTK has it's own way of dealing with application defaults, by using rc
7291 files. These can be used to set the colors of just about any widget, and
7292 can also be used to tile pixmaps onto the background of some widgets.
7294 <!-- ----------------------------------------------------------------- -->
7295 <sect1>Functions For rc Files
7297 When your application starts, you should include a call to:
7300 void gtk_rc_parse( char *filename );
7303 Passing in the filename of your rc file. This will cause GTK to parse this
7304 file, and use the style settings for the widget types defined there.
7306 If you wish to have a special set of widgets that can take on a different
7307 style from others, or any other logical division of widgets, use a call to:
7310 void gtk_widget_set_name( GtkWidget *widget,
7314 Passing your newly created widget as the first argument, and the name
7315 you wish to give it as the second. This will allow you to change the
7316 attributes of this widget by name through the rc file.
7318 If we use a call something like this:
7321 button = gtk_button_new_with_label ("Special Button");
7322 gtk_widget_set_name (button, "special button");
7325 Then this button is given the name "special button" and may be addressed by
7326 name in the rc file as "special button.GtkButton". [<--- Verify ME!]
7328 The example rc file below, sets the properties of the main window, and lets
7329 all children of that main window inherit the style described by the "main
7330 button" style. The code used in the application is:
7333 window = gtk_window_new (GTK_WINDOW_TOPLEVEL);
7334 gtk_widget_set_name (window, "main window");
7337 And then the style is defined in the rc file using:
7340 widget "main window.*GtkButton*" style "main_button"
7343 Which sets all the GtkButton widgets in the "main window" to the
7344 "main_buttons" style as defined in the rc file.
7346 As you can see, this is a fairly powerful and flexible system. Use your
7347 imagination as to how best to take advantage of this.
7349 <!-- ----------------------------------------------------------------- -->
7350 <sect1>GTK's rc File Format
7352 The format of the GTK file is illustrated in the example below. This is
7353 the testgtkrc file from the GTK distribution, but I've added a
7354 few comments and things. You may wish to include this explanation
7355 your application to allow the user to fine tune his application.
7357 There are several directives to change the attributes of a widget.
7360 <item>fg - Sets the foreground color of a widget.
7361 <item>bg - Sets the background color of a widget.
7362 <item>bg_pixmap - Sets the background of a widget to a tiled pixmap.
7363 <item>font - Sets the font to be used with the given widget.
7366 In addition to this, there are several states a widget can be in, and you
7367 can set different colors, pixmaps and fonts for each state. These states are:
7370 <item>NORMAL - The normal state of a widget, without the mouse over top of
7371 it, and not being pressed etc.
7372 <item>PRELIGHT - When the mouse is over top of the widget, colors defined
7373 using this state will be in effect.
7374 <item>ACTIVE - When the widget is pressed or clicked it will be active, and
7375 the attributes assigned by this tag will be in effect.
7376 <item>INSENSITIVE - When a widget is set insensitive, and cannot be
7377 activated, it will take these attributes.
7378 <item>SELECTED - When an object is selected, it takes these attributes.
7381 When using the "fg" and "bg" keywords to set the colors of widgets, the
7385 fg[<STATE>] = { Red, Green, Blue }
7388 Where STATE is one of the above states (PRELIGHT, ACTIVE etc), and the Red,
7389 Green and Blue are values in the range of 0 - 1.0, { 1.0, 1.0, 1.0 } being
7390 white. They must be in float form, or they will register as 0, so a straight
7391 "1" will not work, it must be "1.0". A straight "0" is fine because it
7392 doesn't matter if it's not recognized. Unrecognized values are set to 0.
7394 bg_pixmap is very similar to the above, except the colors are replaced by a
7397 pixmap_path is a list of paths seperated by ":"'s. These paths will be
7398 searched for any pixmap you specify.
7400 The font directive is simply:
7402 font = "<font name>"
7405 Where the only hard part is figuring out the font string. Using xfontsel or
7406 similar utility should help.
7408 The "widget_class" sets the style of a class of widgets. These classes are
7409 listed in the widget overview on the class hierarchy.
7411 The "widget" directive sets a specificaly named set of widgets to a
7412 given style, overriding any style set for the given widget class.
7413 These widgets are registered inside the application using the
7414 gtk_widget_set_name() call. This allows you to specify the attributes of a
7415 widget on a per widget basis, rather than setting the attributes of an
7416 entire widget class. I urge you to document any of these special widgets so
7417 users may customize them.
7419 When the keyword <tt>parent</> is used as an attribute, the widget will take on
7420 the attributes of it's parent in the application.
7422 When defining a style, you may assign the attributes of a previously defined
7423 style to this new one.
7426 style "main_button" = "button"
7428 font = "-adobe-helvetica-medium-r-normal--*-100-*-*-*-*-*-*"
7429 bg[PRELIGHT] = { 0.75, 0, 0 }
7433 This example takes the "button" style, and creates a new "main_button" style
7434 simply by changing the font and prelight background color of the "button"
7437 Of course, many of these attributes don't apply to all widgets. It's a
7438 simple matter of common sense really. Anything that could apply, should.
7440 <!-- ----------------------------------------------------------------- -->
7441 <sect1>Example rc file
7445 # pixmap_path "<dir 1>:<dir 2>:<dir 3>:..."
7447 pixmap_path "/usr/include/X11R6/pixmaps:/home/imain/pixmaps"
7449 # style <name> [= <name>]
7454 # widget <widget_set> style <style_name>
7455 # widget_class <widget_class_set> style <style_name>
7458 # Here is a list of all the possible states. Note that some do not apply to
7461 # NORMAL - The normal state of a widget, without the mouse over top of
7462 # it, and not being pressed etc.
7464 # PRELIGHT - When the mouse is over top of the widget, colors defined
7465 # using this state will be in effect.
7467 # ACTIVE - When the widget is pressed or clicked it will be active, and
7468 # the attributes assigned by this tag will be in effect.
7470 # INSENSITIVE - When a widget is set insensitive, and cannot be
7471 # activated, it will take these attributes.
7473 # SELECTED - When an object is selected, it takes these attributes.
7475 # Given these states, we can set the attributes of the widgets in each of
7476 # these states using the following directives.
7478 # fg - Sets the foreground color of a widget.
7479 # fg - Sets the background color of a widget.
7480 # bg_pixmap - Sets the background of a widget to a tiled pixmap.
7481 # font - Sets the font to be used with the given widget.
7484 # This sets a style called "button". The name is not really important, as
7485 # it is assigned to the actual widgets at the bottom of the file.
7489 #This sets the padding around the window to the pixmap specified.
7490 #bg_pixmap[<STATE>] = "<pixmap filename>"
7491 bg_pixmap[NORMAL] = "warning.xpm"
7496 #Sets the foreground color (font color) to red when in the "NORMAL"
7499 fg[NORMAL] = { 1.0, 0, 0 }
7501 #Sets the background pixmap of this widget to that of it's parent.
7502 bg_pixmap[NORMAL] = "<parent>"
7507 # This shows all the possible states for a button. The only one that
7508 # doesn't apply is the SELECTED state.
7510 fg[PRELIGHT] = { 0, 1.0, 1.0 }
7511 bg[PRELIGHT] = { 0, 0, 1.0 }
7512 bg[ACTIVE] = { 1.0, 0, 0 }
7513 fg[ACTIVE] = { 0, 1.0, 0 }
7514 bg[NORMAL] = { 1.0, 1.0, 0 }
7515 fg[NORMAL] = { .99, 0, .99 }
7516 bg[INSENSITIVE] = { 1.0, 1.0, 1.0 }
7517 fg[INSENSITIVE] = { 1.0, 0, 1.0 }
7520 # In this example, we inherit the attributes of the "button" style and then
7521 # override the font and background color when prelit to create a new
7522 # "main_button" style.
7524 style "main_button" = "button"
7526 font = "-adobe-helvetica-medium-r-normal--*-100-*-*-*-*-*-*"
7527 bg[PRELIGHT] = { 0.75, 0, 0 }
7530 style "toggle_button" = "button"
7532 fg[NORMAL] = { 1.0, 0, 0 }
7533 fg[ACTIVE] = { 1.0, 0, 0 }
7535 # This sets the background pixmap of the toggle_button to that of it's
7536 # parent widget (as defined in the application).
7537 bg_pixmap[NORMAL] = "<parent>"
7542 bg_pixmap[NORMAL] = "marble.xpm"
7543 fg[NORMAL] = { 1.0, 1.0, 1.0 }
7548 font = "-adobe-helvetica-medium-r-normal--*-80-*-*-*-*-*-*"
7551 # pixmap_path "~/.pixmaps"
7553 # These set the widget types to use the styles defined above.
7554 # The widget types are listed in the class hierarchy, but could probably be
7555 # just listed in this document for the users reference.
7557 widget_class "GtkWindow" style "window"
7558 widget_class "GtkDialog" style "window"
7559 widget_class "GtkFileSelection" style "window"
7560 widget_class "*Gtk*Scale" style "scale"
7561 widget_class "*GtkCheckButton*" style "toggle_button"
7562 widget_class "*GtkRadioButton*" style "toggle_button"
7563 widget_class "*GtkButton*" style "button"
7564 widget_class "*Ruler" style "ruler"
7565 widget_class "*GtkText" style "text"
7567 # This sets all the buttons that are children of the "main window" to
7568 # the main_buton style. These must be documented to be taken advantage of.
7569 widget "main window.*GtkButton*" style "main_button"
7572 <!-- ***************************************************************** -->
7573 <sect>Writing Your Own Widgets
7574 <!-- ***************************************************************** -->
7576 <!-- ----------------------------------------------------------------- -->
7579 Although the GTK distribution comes with many types of widgets that
7580 should cover most basic needs, there may come a time when you need to
7581 create your own new widget type. Since GTK uses widget inheretence
7582 extensively, and there is already a widget that is close to what you want,
7583 it is often possible to make a useful new widget type in
7584 just a few lines of code. But before starting work on a new widget, check
7585 around first to make sure that someone has not already written
7586 it. This will prevent duplication of effort and keep the number of
7587 GTK widgets out there to a minimum, which will help keep both the code
7588 and the interface of different applications consistent. As a flip side
7589 to this, once you finish your widget, announce it to the world so
7590 other people can benefit. The best place to do this is probably the
7593 Complete sources for the example widgets are available at the place you
7594 got this tutorial, or from:
7596 <htmlurl url="http://www.gtk.org/~otaylor/gtk/tutorial/"
7597 name="http://www.gtk.org/~otaylor/gtk/tutorial/">
7600 <!-- ----------------------------------------------------------------- -->
7601 <sect1> The Anatomy Of A Widget
7603 In order to create a new widget, it is important to have an
7604 understanding of how GTK objects work. This section is just meant as a
7605 brief overview. See the reference documentation for the details.
7607 GTK widgets are implemented in an object oriented fashion. However,
7608 they are implemented in standard C. This greatly improves portability
7609 and stability over using current generation C++ compilers; however,
7610 it does mean that the widget writer has to pay attention to some of
7611 the implementation details. The information common to all instances of
7612 one class of widgets (e.g., to all Button widgets) is stored in the
7613 <em>class structure</em>. There is only one copy of this in
7614 which is stored information about the class's signals
7615 (which act like virtual functions in C). To support inheritance, the
7616 first field in the class structure must be a copy of the parent's
7617 class structure. The declaration of the class structure of GtkButtton
7621 struct _GtkButtonClass
7623 GtkContainerClass parent_class;
7625 void (* pressed) (GtkButton *button);
7626 void (* released) (GtkButton *button);
7627 void (* clicked) (GtkButton *button);
7628 void (* enter) (GtkButton *button);
7629 void (* leave) (GtkButton *button);
7633 When a button is treated as a container (for instance, when it is
7634 resized), its class structure can be cast to GtkContainerClass, and
7635 the relevant fields used to handle the signals.
7637 There is also a structure for each widget that is created on a
7638 per-instance basis. This structure has fields to store information that
7639 is different for each instance of the widget. We'll call this
7640 structure the <em>object structure</em>. For the Button class, it looks
7646 GtkContainer container;
7650 guint in_button : 1;
7651 guint button_down : 1;
7655 Note that, similar to the class structure, the first field is the
7656 object structure of the parent class, so that this structure can be
7657 cast to the parent class's object structure as needed.
7659 <!-- ----------------------------------------------------------------- -->
7660 <sect1> Creating a Composite widget
7662 <!-- ----------------------------------------------------------------- -->
7663 <sect2> Introduction
7665 One type of widget that you may be interested in creating is a
7666 widget that is merely an aggregate of other GTK widgets. This type of
7667 widget does nothing that couldn't be done without creating new
7668 widgets, but provides a convenient way of packaging user interface
7669 elements for reuse. The FileSelection and ColorSelection widgets in
7670 the standard distribution are examples of this type of widget.
7672 The example widget that we'll create in this section is the Tictactoe
7673 widget, a 3x3 array of toggle buttons which triggers a signal when all
7674 three buttons in a row, column, or on one of the diagonals are
7677 <!-- ----------------------------------------------------------------- -->
7678 <sect2> Choosing a parent class
7680 The parent class for a composite widget is typically the container
7681 class that holds all of the elements of the composite widget. For
7682 example, the parent class of the FileSelection widget is the
7683 Dialog class. Since our buttons will be arranged in a table, it
7684 might seem natural to make our parent class the GtkTable
7685 class. Unfortunately, this turns out not to work. The creation of a
7686 widget is divided among two functions - a <tt/WIDGETNAME_new()/
7687 function that the user calls, and a <tt/WIDGETNAME_init()/ function
7688 which does the basic work of initializing the widget which is
7689 independent of the arguments passed to the <tt/_new()/
7690 function. Descendent widgets only call the <tt/_init/ function of
7691 their parent widget. But this division of labor doesn't work well for
7692 tables, which when created, need to know the number of rows and
7693 columns in the table. Unless we want to duplicate most of the
7694 functionality of <tt/gtk_table_new()/ in our Tictactoe widget, we had
7695 best avoid deriving it from GtkTable. For that reason, we derive it
7696 from GtkVBox instead, and stick our table inside the VBox.
7698 <!-- ----------------------------------------------------------------- -->
7699 <sect2> The header file
7701 Each widget class has a header file which declares the object and
7702 class structures for that widget, along with public functions.
7703 A couple of features are worth pointing out. To prevent duplicate
7704 definitions, we wrap the entire header file in:
7707 #ifndef __TICTACTOE_H__
7708 #define __TICTACTOE_H__
7712 #endif /* __TICTACTOE_H__ */
7715 And to keep C++ programs that include the header file happy, in:
7720 #endif /* __cplusplus */
7726 #endif /* __cplusplus */
7729 Along with the functions and structures, we declare three standard
7730 macros in our header file, <tt/TICTACTOE(obj)/,
7731 <tt/TICTACTOE_CLASS(klass)/, and <tt/IS_TICTACTOE(obj)/, which cast a
7732 pointer into a pointer to the object or class structure, and check
7733 if an object is a Tictactoe widget respectively.
7735 Here is the complete header file:
7740 #ifndef __TICTACTOE_H__
7741 #define __TICTACTOE_H__
7743 #include <gdk/gdk.h>
7744 #include <gtk/gtkvbox.h>
7748 #endif /* __cplusplus */
7750 #define TICTACTOE(obj) GTK_CHECK_CAST (obj, tictactoe_get_type (), Tictactoe)
7751 #define TICTACTOE_CLASS(klass) GTK_CHECK_CLASS_CAST (klass, tictactoe_get_type (), TictactoeClass)
7752 #define IS_TICTACTOE(obj) GTK_CHECK_TYPE (obj, tictactoe_get_type ())
7755 typedef struct _Tictactoe Tictactoe;
7756 typedef struct _TictactoeClass TictactoeClass;
7762 GtkWidget *buttons[3][3];
7765 struct _TictactoeClass
7767 GtkVBoxClass parent_class;
7769 void (* tictactoe) (Tictactoe *ttt);
7772 guint tictactoe_get_type (void);
7773 GtkWidget* tictactoe_new (void);
7774 void tictactoe_clear (Tictactoe *ttt);
7778 #endif /* __cplusplus */
7780 #endif /* __TICTACTOE_H__ */
7784 <!-- ----------------------------------------------------------------- -->
7785 <sect2> The <tt/_get_type()/ function.
7787 We now continue on to the implementation of our widget. A core
7788 function for every widget is the function
7789 <tt/WIDGETNAME_get_type()/. This function, when first called, tells
7790 GTK about the widget class, and gets an ID that uniquely identifies
7791 the widget class. Upon subsequent calls, it just returns the ID.
7795 tictactoe_get_type ()
7797 static guint ttt_type = 0;
7801 GtkTypeInfo ttt_info =
7805 sizeof (TictactoeClass),
7806 (GtkClassInitFunc) tictactoe_class_init,
7807 (GtkObjectInitFunc) tictactoe_init,
7808 (GtkArgSetFunc) NULL,
7809 (GtkArgGetFunc) NULL
7812 ttt_type = gtk_type_unique (gtk_vbox_get_type (), &ttt_info);
7819 The GtkTypeInfo structure has the following definition:
7827 GtkClassInitFunc class_init_func;
7828 GtkObjectInitFunc object_init_func;
7829 GtkArgSetFunc arg_set_func;
7830 GtkArgGetFunc arg_get_func;
7834 The fields of this structure are pretty self-explanatory. We'll ignore
7835 the <tt/arg_set_func/ and <tt/arg_get_func/ fields here: they have an important,
7837 unimplemented, role in allowing widget options to be conveniently set
7838 from interpreted languages. Once GTK has a correctly filled in copy of
7839 this structure, it knows how to create objects of a particular widget
7842 <!-- ----------------------------------------------------------------- -->
7843 <sect2> The <tt/_class_init()/ function
7845 The <tt/WIDGETNAME_class_init()/ function initializes the fields of
7846 the widget's class structure, and sets up any signals for the
7847 class. For our Tictactoe widget it looks like:
7856 static gint tictactoe_signals[LAST_SIGNAL] = { 0 };
7859 tictactoe_class_init (TictactoeClass *class)
7861 GtkObjectClass *object_class;
7863 object_class = (GtkObjectClass*) class;
7865 tictactoe_signals[TICTACTOE_SIGNAL] = gtk_signal_new ("tictactoe",
7868 GTK_SIGNAL_OFFSET (TictactoeClass, tictactoe),
7869 gtk_signal_default_marshaller, GTK_TYPE_NONE, 0);
7872 gtk_object_class_add_signals (object_class, tictactoe_signals, LAST_SIGNAL);
7874 class->tictactoe = NULL;
7878 Our widget has just one signal, the <tt/tictactoe/ signal that is
7879 invoked when a row, column, or diagonal is completely filled in. Not
7880 every composite widget needs signals, so if you are reading this for
7881 the first time, you may want to skip to the next section now, as
7882 things are going to get a bit complicated.
7887 gint gtk_signal_new( const gchar *name,
7888 GtkSignalRunType run_type,
7889 GtkType object_type,
7890 gint function_offset,
7891 GtkSignalMarshaller marshaller,
7897 Creates a new signal. The parameters are:
7900 <item> <tt/name/: The name of the signal.
7901 <item> <tt/run_type/: Whether the default handler runs before or after
7902 user handlers. Usually this will be <tt/GTK_RUN_FIRST/, or <tt/GTK_RUN_LAST/,
7903 although there are other possibilities.
7904 <item> <tt/object_type/: The ID of the object that this signal applies
7905 to. (It will also apply to that objects descendents)
7906 <item> <tt/function_offset/: The offset within the class structure of
7907 a pointer to the default handler.
7908 <item> <tt/marshaller/: A function that is used to invoke the signal
7909 handler. For signal handlers that have no arguments other than the
7910 object that emitted the signal and user data, we can use the
7911 pre-supplied marshaller function <tt/gtk_signal_default_marshaller/.
7912 <item> <tt/return_val/: The type of the return val.
7913 <item> <tt/nparams/: The number of parameters of the signal handler
7914 (other than the two default ones mentioned above)
7915 <item> <tt/.../: The types of the parameters.
7918 When specifying types, the <tt/GtkType/ enumeration is used:
7943 /* it'd be great if the next two could be removed eventually */
7945 GTK_TYPE_C_CALLBACK,
7949 } GtkFundamentalType;
7952 <tt/gtk_signal_new()/ returns a unique integer identifier for the
7953 signal, that we store in the <tt/tictactoe_signals/ array, which we
7954 index using an enumeration. (Conventionally, the enumeration elements
7955 are the signal name, uppercased, but here there would be a conflict
7956 with the <tt/TICTACTOE()/ macro, so we called it <tt/TICTACTOE_SIGNAL/
7959 After creating our signals, we need to tell GTK to associate our
7960 signals with the Tictactoe class. We do that by calling
7961 <tt/gtk_object_class_add_signals()/. We then set the pointer which
7962 points to the default handler for the ``tictactoe'' signal to NULL,
7963 indicating that there is no default action.
7965 <!-- ----------------------------------------------------------------- -->
7966 <sect2> The <tt/_init()/ function.
7968 Each widget class also needs a function to initialize the object
7969 structure. Usually, this function has the fairly limited role of
7970 setting the fields of the structure to default values. For composite
7971 widgets, however, this function also creates the component widgets.
7975 tictactoe_init (Tictactoe *ttt)
7980 table = gtk_table_new (3, 3, TRUE);
7981 gtk_container_add (GTK_CONTAINER(ttt), table);
7982 gtk_widget_show (table);
7987 ttt->buttons[i][j] = gtk_toggle_button_new ();
7988 gtk_table_attach_defaults (GTK_TABLE(table), ttt->buttons[i][j],
7990 gtk_signal_connect (GTK_OBJECT (ttt->buttons[i][j]), "toggled",
7991 GTK_SIGNAL_FUNC (tictactoe_toggle), ttt);
7992 gtk_widget_set_usize (ttt->buttons[i][j], 20, 20);
7993 gtk_widget_show (ttt->buttons[i][j]);
7998 <!-- ----------------------------------------------------------------- -->
7999 <sect2> And the rest...
8001 There is one more function that every widget (except for base widget
8002 types like GtkBin that cannot be instantiated) needs to have - the
8003 function that the user calls to create an object of that type. This is
8004 conventionally called <tt/WIDGETNAME_new()/. In some
8005 widgets, though not for the Tictactoe widgets, this function takes
8006 arguments, and does some setup based on the arguments. The other two
8007 functions are specific to the Tictactoe widget.
8009 <tt/tictactoe_clear()/ is a public function that resets all the
8010 buttons in the widget to the up position. Note the use of
8011 <tt/gtk_signal_handler_block_by_data()/ to keep our signal handler for
8012 button toggles from being triggered unnecessarily.
8014 <tt/tictactoe_toggle()/ is the signal handler that is invoked when the
8015 user clicks on a button. It checks to see if there are any winning
8016 combinations that involve the toggled button, and if so, emits
8017 the "tictactoe" signal.
8023 return GTK_WIDGET ( gtk_type_new (tictactoe_get_type ()));
8027 tictactoe_clear (Tictactoe *ttt)
8034 gtk_signal_handler_block_by_data (GTK_OBJECT(ttt->buttons[i][j]), ttt);
8035 gtk_toggle_button_set_state (GTK_TOGGLE_BUTTON (ttt->buttons[i][j]),
8037 gtk_signal_handler_unblock_by_data (GTK_OBJECT(ttt->buttons[i][j]), ttt);
8042 tictactoe_toggle (GtkWidget *widget, Tictactoe *ttt)
8046 static int rwins[8][3] = { { 0, 0, 0 }, { 1, 1, 1 }, { 2, 2, 2 },
8047 { 0, 1, 2 }, { 0, 1, 2 }, { 0, 1, 2 },
8048 { 0, 1, 2 }, { 0, 1, 2 } };
8049 static int cwins[8][3] = { { 0, 1, 2 }, { 0, 1, 2 }, { 0, 1, 2 },
8050 { 0, 0, 0 }, { 1, 1, 1 }, { 2, 2, 2 },
8051 { 0, 1, 2 }, { 2, 1, 0 } };
8062 success = success &&
8063 GTK_TOGGLE_BUTTON(ttt->buttons[rwins[k][i]][cwins[k][i]])->active;
8065 ttt->buttons[rwins[k][i]][cwins[k][i]] == widget;
8068 if (success && found)
8070 gtk_signal_emit (GTK_OBJECT (ttt),
8071 tictactoe_signals[TICTACTOE_SIGNAL]);
8078 And finally, an example program using our Tictactoe widget:
8081 #include <gtk/gtk.h>
8082 #include "tictactoe.h"
8084 /* Invoked when a row, column or diagonal is completed */
8086 win (GtkWidget *widget, gpointer data)
8089 tictactoe_clear (TICTACTOE (widget));
8093 main (int argc, char *argv[])
8098 gtk_init (&argc, &argv);
8100 window = gtk_window_new (GTK_WINDOW_TOPLEVEL);
8102 gtk_window_set_title (GTK_WINDOW (window), "Aspect Frame");
8104 gtk_signal_connect (GTK_OBJECT (window), "destroy",
8105 GTK_SIGNAL_FUNC (gtk_exit), NULL);
8107 gtk_container_border_width (GTK_CONTAINER (window), 10);
8109 /* Create a new Tictactoe widget */
8110 ttt = tictactoe_new ();
8111 gtk_container_add (GTK_CONTAINER (window), ttt);
8112 gtk_widget_show (ttt);
8114 /* And attach to its "tictactoe" signal */
8115 gtk_signal_connect (GTK_OBJECT (ttt), "tictactoe",
8116 GTK_SIGNAL_FUNC (win), NULL);
8118 gtk_widget_show (window);
8127 <!-- ----------------------------------------------------------------- -->
8128 <sect1> Creating a widget from scratch.
8130 <!-- ----------------------------------------------------------------- -->
8131 <sect2> Introduction
8133 In this section, we'll learn more about how widgets display themselves
8134 on the screen and interact with events. As an example of this, we'll
8135 create an analog dial widget with a pointer that the user can drag to
8138 <!-- ----------------------------------------------------------------- -->
8139 <sect2> Displaying a widget on the screen
8141 There are several steps that are involved in displaying on the screen.
8142 After the widget is created with a call to <tt/WIDGETNAME_new()/,
8143 several more functions are needed:
8146 <item> <tt/WIDGETNAME_realize()/ is responsible for creating an X
8147 window for the widget if it has one.
8148 <item> <tt/WIDGETNAME_map()/ is invoked after the user calls
8149 <tt/gtk_widget_show()/. It is responsible for making sure the widget
8150 is actually drawn on the screen (<em/mapped/). For a container class,
8151 it must also make calls to <tt/map()/> functions of any child widgets.
8152 <item> <tt/WIDGETNAME_draw()/ is invoked when <tt/gtk_widget_draw()/
8153 is called for the widget or one of its ancestors. It makes the actual
8154 calls to the drawing functions to draw the widget on the screen. For
8155 container widgets, this function must make calls to
8156 <tt/gtk_widget_draw()/ for its child widgets.
8157 <item> <tt/WIDGETNAME_expose()/ is a handler for expose events for the
8158 widget. It makes the necessary calls to the drawing functions to draw
8159 the exposed portion on the screen. For container widgets, this
8160 function must generate expose events for its child widgets which don't
8161 have their own windows. (If they have their own windows, then X will
8162 generate the necessary expose events)
8165 You might notice that the last two functions are quite similar - each
8166 is responsible for drawing the widget on the screen. In fact many
8167 types of widgets don't really care about the difference between the
8168 two. The default <tt/draw()/ function in the widget class simply
8169 generates a synthetic expose event for the redrawn area. However, some
8170 types of widgets can save work by distinguishing between the two
8171 functions. For instance, if a widget has multiple X windows, then
8172 since expose events identify the exposed window, it can redraw only
8173 the affected window, which is not possible for calls to <tt/draw()/.
8175 Container widgets, even if they don't care about the difference for
8176 themselves, can't simply use the default <tt/draw()/ function because
8177 their child widgets might care about the difference. However,
8178 it would be wasteful to duplicate the drawing code between the two
8179 functions. The convention is that such widgets have a function called
8180 <tt/WIDGETNAME_paint()/ that does the actual work of drawing the
8181 widget, that is then called by the <tt/draw()/ and <tt/expose()/
8184 In our example approach, since the dial widget is not a container
8185 widget, and only has a single window, we can take the simplest
8186 approach and use the default <tt/draw()/ function and only implement
8187 an <tt/expose()/ function.
8189 <!-- ----------------------------------------------------------------- -->
8190 <sect2> The origins of the Dial Widget
8192 Just as all land animals are just variants on the first amphibian that
8193 crawled up out of the mud, Gtk widgets tend to start off as variants
8194 of some other, previously written widget. Thus, although this section
8195 is entilted ``Creating a Widget from Scratch'', the Dial widget really
8196 began with the source code for the Range widget. This was picked as a
8197 starting point because it would be nice if our Dial had the same
8198 interface as the Scale widgets which are just specialized descendents
8199 of the Range widget. So, though the source code is presented below in
8200 finished form, it should not be implied that it was written, <em>deus
8201 ex machina</em> in this fashion. Also, if you aren't yet familiar with
8202 how scale widgets work from the application writer's point of view, it
8203 would be a good idea to look them over before continuing.
8205 <!-- ----------------------------------------------------------------- -->
8208 Quite a bit of our widget should look pretty familiar from the
8209 Tictactoe widget. First, we have a header file:
8212 /* GTK - The GIMP Toolkit
8213 * Copyright (C) 1995-1997 Peter Mattis, Spencer Kimball and Josh MacDonald
8215 * This library is free software; you can redistribute it and/or
8216 * modify it under the terms of the GNU Library General Public
8217 * License as published by the Free Software Foundation; either
8218 * version 2 of the License, or (at your option) any later version.
8220 * This library is distributed in the hope that it will be useful,
8221 * but WITHOUT ANY WARRANTY; without even the implied warranty of
8222 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
8223 * Library General Public License for more details.
8225 * You should have received a copy of the GNU Library General Public
8226 * License along with this library; if not, write to the Free
8227 * Software Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
8230 #ifndef __GTK_DIAL_H__
8231 #define __GTK_DIAL_H__
8233 #include <gdk/gdk.h>
8234 #include <gtk/gtkadjustment.h>
8235 #include <gtk/gtkwidget.h>
8240 #endif /* __cplusplus */
8243 #define GTK_DIAL(obj) GTK_CHECK_CAST (obj, gtk_dial_get_type (), GtkDial)
8244 #define GTK_DIAL_CLASS(klass) GTK_CHECK_CLASS_CAST (klass, gtk_dial_get_type (), GtkDialClass)
8245 #define GTK_IS_DIAL(obj) GTK_CHECK_TYPE (obj, gtk_dial_get_type ())
8248 typedef struct _GtkDial GtkDial;
8249 typedef struct _GtkDialClass GtkDialClass;
8255 /* update policy (GTK_UPDATE_[CONTINUOUS/DELAYED/DISCONTINUOUS]) */
8258 /* Button currently pressed or 0 if none */
8261 /* Dimensions of dial components */
8265 /* ID of update timer, or 0 if none */
8271 /* Old values from adjustment stored so we know when something changes */
8276 /* The adjustment object that stores the data for this dial */
8277 GtkAdjustment *adjustment;
8280 struct _GtkDialClass
8282 GtkWidgetClass parent_class;
8286 GtkWidget* gtk_dial_new (GtkAdjustment *adjustment);
8287 guint gtk_dial_get_type (void);
8288 GtkAdjustment* gtk_dial_get_adjustment (GtkDial *dial);
8289 void gtk_dial_set_update_policy (GtkDial *dial,
8290 GtkUpdateType policy);
8292 void gtk_dial_set_adjustment (GtkDial *dial,
8293 GtkAdjustment *adjustment);
8296 #endif /* __cplusplus */
8299 #endif /* __GTK_DIAL_H__ */
8302 Since there is quite a bit more going on in this widget, than the last
8303 one, we have more fields in the data structure, but otherwise things
8306 Next, after including header files, and declaring a few constants,
8307 we have some functions to provide information about the widget
8313 #include <gtk/gtkmain.h>
8314 #include <gtk/gtksignal.h>
8316 #include "gtkdial.h"
8318 #define SCROLL_DELAY_LENGTH 300
8319 #define DIAL_DEFAULT_SIZE 100
8321 /* Forward declararations */
8323 [ omitted to save space ]
8327 static GtkWidgetClass *parent_class = NULL;
8330 gtk_dial_get_type ()
8332 static guint dial_type = 0;
8336 GtkTypeInfo dial_info =
8340 sizeof (GtkDialClass),
8341 (GtkClassInitFunc) gtk_dial_class_init,
8342 (GtkObjectInitFunc) gtk_dial_init,
8343 (GtkArgSetFunc) NULL,
8344 (GtkArgGetFunc) NULL,
8347 dial_type = gtk_type_unique (gtk_widget_get_type (), &dial_info);
8354 gtk_dial_class_init (GtkDialClass *class)
8356 GtkObjectClass *object_class;
8357 GtkWidgetClass *widget_class;
8359 object_class = (GtkObjectClass*) class;
8360 widget_class = (GtkWidgetClass*) class;
8362 parent_class = gtk_type_class (gtk_widget_get_type ());
8364 object_class->destroy = gtk_dial_destroy;
8366 widget_class->realize = gtk_dial_realize;
8367 widget_class->expose_event = gtk_dial_expose;
8368 widget_class->size_request = gtk_dial_size_request;
8369 widget_class->size_allocate = gtk_dial_size_allocate;
8370 widget_class->button_press_event = gtk_dial_button_press;
8371 widget_class->button_release_event = gtk_dial_button_release;
8372 widget_class->motion_notify_event = gtk_dial_motion_notify;
8376 gtk_dial_init (GtkDial *dial)
8379 dial->policy = GTK_UPDATE_CONTINUOUS;
8382 dial->pointer_width = 0;
8384 dial->old_value = 0.0;
8385 dial->old_lower = 0.0;
8386 dial->old_upper = 0.0;
8387 dial->adjustment = NULL;
8391 gtk_dial_new (GtkAdjustment *adjustment)
8395 dial = gtk_type_new (gtk_dial_get_type ());
8398 adjustment = (GtkAdjustment*) gtk_adjustment_new (0.0, 0.0, 0.0, 0.0, 0.0, 0.0);
8400 gtk_dial_set_adjustment (dial, adjustment);
8402 return GTK_WIDGET (dial);
8406 gtk_dial_destroy (GtkObject *object)
8410 g_return_if_fail (object != NULL);
8411 g_return_if_fail (GTK_IS_DIAL (object));
8413 dial = GTK_DIAL (object);
8415 if (dial->adjustment)
8416 gtk_object_unref (GTK_OBJECT (dial->adjustment));
8418 if (GTK_OBJECT_CLASS (parent_class)->destroy)
8419 (* GTK_OBJECT_CLASS (parent_class)->destroy) (object);
8423 Note that this <tt/init()/ function does less than for the Tictactoe
8424 widget, since this is not a composite widget, and the <tt/new()/
8425 function does more, since it now has an argument. Also, note that when
8426 we store a pointer to the Adjustment object, we increment its
8427 reference count, (and correspondingly decrement when we no longer use
8428 it) so that GTK can keep track of when it can be safely destroyed.
8431 Also, there are a few function to manipulate the widget's options:
8435 gtk_dial_get_adjustment (GtkDial *dial)
8437 g_return_val_if_fail (dial != NULL, NULL);
8438 g_return_val_if_fail (GTK_IS_DIAL (dial), NULL);
8440 return dial->adjustment;
8444 gtk_dial_set_update_policy (GtkDial *dial,
8445 GtkUpdateType policy)
8447 g_return_if_fail (dial != NULL);
8448 g_return_if_fail (GTK_IS_DIAL (dial));
8450 dial->policy = policy;
8454 gtk_dial_set_adjustment (GtkDial *dial,
8455 GtkAdjustment *adjustment)
8457 g_return_if_fail (dial != NULL);
8458 g_return_if_fail (GTK_IS_DIAL (dial));
8460 if (dial->adjustment)
8462 gtk_signal_disconnect_by_data (GTK_OBJECT (dial->adjustment), (gpointer) dial);
8463 gtk_object_unref (GTK_OBJECT (dial->adjustment));
8466 dial->adjustment = adjustment;
8467 gtk_object_ref (GTK_OBJECT (dial->adjustment));
8469 gtk_signal_connect (GTK_OBJECT (adjustment), "changed",
8470 (GtkSignalFunc) gtk_dial_adjustment_changed,
8472 gtk_signal_connect (GTK_OBJECT (adjustment), "value_changed",
8473 (GtkSignalFunc) gtk_dial_adjustment_value_changed,
8476 dial->old_value = adjustment->value;
8477 dial->old_lower = adjustment->lower;
8478 dial->old_upper = adjustment->upper;
8480 gtk_dial_update (dial);
8484 <sect2> <tt/gtk_dial_realize()/
8487 Now we come to some new types of functions. First, we have a function
8488 that does the work of creating the X window. Notice that a mask is
8489 passed to the function <tt/gdk_window_new()/ which specifies which fields of
8490 the GdkWindowAttr structure actually have data in them (the remaining
8491 fields wll be given default values). Also worth noting is the way the
8492 event mask of the widget is created. We call
8493 <tt/gtk_widget_get_events()/ to retrieve the event mask that the user
8494 has specified for this widget (with <tt/gtk_widget_set_events()/, and
8495 add the events that we are interested in ourselves.
8498 After creating the window, we set its style and background, and put a
8499 pointer to the widget in the user data field of the GdkWindow. This
8500 last step allows GTK to dispatch events for this window to the correct
8505 gtk_dial_realize (GtkWidget *widget)
8508 GdkWindowAttr attributes;
8509 gint attributes_mask;
8511 g_return_if_fail (widget != NULL);
8512 g_return_if_fail (GTK_IS_DIAL (widget));
8514 GTK_WIDGET_SET_FLAGS (widget, GTK_REALIZED);
8515 dial = GTK_DIAL (widget);
8517 attributes.x = widget->allocation.x;
8518 attributes.y = widget->allocation.y;
8519 attributes.width = widget->allocation.width;
8520 attributes.height = widget->allocation.height;
8521 attributes.wclass = GDK_INPUT_OUTPUT;
8522 attributes.window_type = GDK_WINDOW_CHILD;
8523 attributes.event_mask = gtk_widget_get_events (widget) |
8524 GDK_EXPOSURE_MASK | GDK_BUTTON_PRESS_MASK |
8525 GDK_BUTTON_RELEASE_MASK | GDK_POINTER_MOTION_MASK |
8526 GDK_POINTER_MOTION_HINT_MASK;
8527 attributes.visual = gtk_widget_get_visual (widget);
8528 attributes.colormap = gtk_widget_get_colormap (widget);
8530 attributes_mask = GDK_WA_X | GDK_WA_Y | GDK_WA_VISUAL | GDK_WA_COLORMAP;
8531 widget->window = gdk_window_new (widget->parent->window, &attributes, attributes_mask);
8533 widget->style = gtk_style_attach (widget->style, widget->window);
8535 gdk_window_set_user_data (widget->window, widget);
8537 gtk_style_set_background (widget->style, widget->window, GTK_STATE_ACTIVE);
8541 <sect2> Size negotiation
8544 Before the first time that the window containing a widget is
8545 displayed, and whenever the layout of the window changes, GTK asks
8546 each child widget for its desired size. This request is handled by the
8547 function, <tt/gtk_dial_size_request()/. Since our widget isn't a
8548 container widget, and has no real constraints on its size, we just
8549 return a reasonable default value.
8553 gtk_dial_size_request (GtkWidget *widget,
8554 GtkRequisition *requisition)
8556 requisition->width = DIAL_DEFAULT_SIZE;
8557 requisition->height = DIAL_DEFAULT_SIZE;
8562 After all the widgets have requested an ideal size, the layout of the
8563 window is computed and each child widget is notified of its actual
8564 size. Usually, this will at least as large as the requested size, but
8565 if for instance, the user has resized the window, it may occasionally
8566 be smaller than the requested size. The size notification is handled
8567 by the function <tt/gtk_dial_size_allocate()/. Notice that as well as
8568 computing the sizes of some component pieces for future use, this
8569 routine also does the grunt work of moving the widgets X window into
8570 the new position and size.
8574 gtk_dial_size_allocate (GtkWidget *widget,
8575 GtkAllocation *allocation)
8579 g_return_if_fail (widget != NULL);
8580 g_return_if_fail (GTK_IS_DIAL (widget));
8581 g_return_if_fail (allocation != NULL);
8583 widget->allocation = *allocation;
8584 if (GTK_WIDGET_REALIZED (widget))
8586 dial = GTK_DIAL (widget);
8588 gdk_window_move_resize (widget->window,
8589 allocation->x, allocation->y,
8590 allocation->width, allocation->height);
8592 dial->radius = MAX(allocation->width,allocation->height) * 0.45;
8593 dial->pointer_width = dial->radius / 5;
8598 <!-- ----------------------------------------------------------------- -->
8599 <sect2> <tt/gtk_dial_expose()/
8602 As mentioned above, all the drawing of this widget is done in the
8603 handler for expose events. There's not much to remark on here except
8604 the use of the function <tt/gtk_draw_polygon/ to draw the pointer with
8605 three dimensional shading according to the colors stored in the
8610 gtk_dial_expose (GtkWidget *widget,
8611 GdkEventExpose *event)
8621 g_return_val_if_fail (widget != NULL, FALSE);
8622 g_return_val_if_fail (GTK_IS_DIAL (widget), FALSE);
8623 g_return_val_if_fail (event != NULL, FALSE);
8625 if (event->count > 0)
8628 dial = GTK_DIAL (widget);
8630 gdk_window_clear_area (widget->window,
8632 widget->allocation.width,
8633 widget->allocation.height);
8635 xc = widget->allocation.width/2;
8636 yc = widget->allocation.height/2;
8640 for (i=0; i<25; i++)
8642 theta = (i*M_PI/18. - M_PI/6.);
8646 tick_length = (i%6 == 0) ? dial->pointer_width : dial->pointer_width/2;
8648 gdk_draw_line (widget->window,
8649 widget->style->fg_gc[widget->state],
8650 xc + c*(dial->radius - tick_length),
8651 yc - s*(dial->radius - tick_length),
8652 xc + c*dial->radius,
8653 yc - s*dial->radius);
8658 s = sin(dial->angle);
8659 c = cos(dial->angle);
8662 points[0].x = xc + s*dial->pointer_width/2;
8663 points[0].y = yc + c*dial->pointer_width/2;
8664 points[1].x = xc + c*dial->radius;
8665 points[1].y = yc - s*dial->radius;
8666 points[2].x = xc - s*dial->pointer_width/2;
8667 points[2].y = yc - c*dial->pointer_width/2;
8669 gtk_draw_polygon (widget->style,
8680 <!-- ----------------------------------------------------------------- -->
8681 <sect2> Event handling
8685 The rest of the widget's code handles various types of events, and
8686 isn't too different from what would be found in many GTK
8687 applications. Two types of events can occur - either the user can
8688 click on the widget with the mouse and drag to move the pointer, or
8689 the value of the Adjustment object can change due to some external
8693 When the user clicks on the widget, we check to see if the click was
8694 appropriately near the pointer, and if so, store then button that the
8695 user clicked with in the <tt/button/ field of the widget
8696 structure, and grab all mouse events with a call to
8697 <tt/gtk_grab_add()/. Subsequent motion of the mouse causes the
8698 value of the control to be recomputed (by the function
8699 <tt/gtk_dial_update_mouse/). Depending on the policy that has been
8700 set, "value_changed" events are either generated instantly
8701 (<tt/GTK_UPDATE_CONTINUOUS/), after a delay in a timer added with
8702 <tt/gtk_timeout_add()/ (<tt/GTK_UPDATE_DELAYED/), or only when the
8703 button is released (<tt/GTK_UPDATE_DISCONTINUOUS/).
8707 gtk_dial_button_press (GtkWidget *widget,
8708 GdkEventButton *event)
8714 double d_perpendicular;
8716 g_return_val_if_fail (widget != NULL, FALSE);
8717 g_return_val_if_fail (GTK_IS_DIAL (widget), FALSE);
8718 g_return_val_if_fail (event != NULL, FALSE);
8720 dial = GTK_DIAL (widget);
8722 /* Determine if button press was within pointer region - we
8723 do this by computing the parallel and perpendicular distance of
8724 the point where the mouse was pressed from the line passing through
8727 dx = event->x - widget->allocation.width / 2;
8728 dy = widget->allocation.height / 2 - event->y;
8730 s = sin(dial->angle);
8731 c = cos(dial->angle);
8733 d_parallel = s*dy + c*dx;
8734 d_perpendicular = fabs(s*dx - c*dy);
8736 if (!dial->button &&
8737 (d_perpendicular < dial->pointer_width/2) &&
8738 (d_parallel > - dial->pointer_width))
8740 gtk_grab_add (widget);
8742 dial->button = event->button;
8744 gtk_dial_update_mouse (dial, event->x, event->y);
8751 gtk_dial_button_release (GtkWidget *widget,
8752 GdkEventButton *event)
8756 g_return_val_if_fail (widget != NULL, FALSE);
8757 g_return_val_if_fail (GTK_IS_DIAL (widget), FALSE);
8758 g_return_val_if_fail (event != NULL, FALSE);
8760 dial = GTK_DIAL (widget);
8762 if (dial->button == event->button)
8764 gtk_grab_remove (widget);
8768 if (dial->policy == GTK_UPDATE_DELAYED)
8769 gtk_timeout_remove (dial->timer);
8771 if ((dial->policy != GTK_UPDATE_CONTINUOUS) &&
8772 (dial->old_value != dial->adjustment->value))
8773 gtk_signal_emit_by_name (GTK_OBJECT (dial->adjustment), "value_changed");
8780 gtk_dial_motion_notify (GtkWidget *widget,
8781 GdkEventMotion *event)
8784 GdkModifierType mods;
8787 g_return_val_if_fail (widget != NULL, FALSE);
8788 g_return_val_if_fail (GTK_IS_DIAL (widget), FALSE);
8789 g_return_val_if_fail (event != NULL, FALSE);
8791 dial = GTK_DIAL (widget);
8793 if (dial->button != 0)
8798 if (event->is_hint || (event->window != widget->window))
8799 gdk_window_get_pointer (widget->window, &x, &y, &mods);
8801 switch (dial->button)
8804 mask = GDK_BUTTON1_MASK;
8807 mask = GDK_BUTTON2_MASK;
8810 mask = GDK_BUTTON3_MASK;
8818 gtk_dial_update_mouse (dial, x,y);
8825 gtk_dial_timer (GtkDial *dial)
8827 g_return_val_if_fail (dial != NULL, FALSE);
8828 g_return_val_if_fail (GTK_IS_DIAL (dial), FALSE);
8830 if (dial->policy == GTK_UPDATE_DELAYED)
8831 gtk_signal_emit_by_name (GTK_OBJECT (dial->adjustment), "value_changed");
8837 gtk_dial_update_mouse (GtkDial *dial, gint x, gint y)
8842 g_return_if_fail (dial != NULL);
8843 g_return_if_fail (GTK_IS_DIAL (dial));
8845 xc = GTK_WIDGET(dial)->allocation.width / 2;
8846 yc = GTK_WIDGET(dial)->allocation.height / 2;
8848 old_value = dial->adjustment->value;
8849 dial->angle = atan2(yc-y, x-xc);
8851 if (dial->angle < -M_PI/2.)
8852 dial->angle += 2*M_PI;
8854 if (dial->angle < -M_PI/6)
8855 dial->angle = -M_PI/6;
8857 if (dial->angle > 7.*M_PI/6.)
8858 dial->angle = 7.*M_PI/6.;
8860 dial->adjustment->value = dial->adjustment->lower + (7.*M_PI/6 - dial->angle) *
8861 (dial->adjustment->upper - dial->adjustment->lower) / (4.*M_PI/3.);
8863 if (dial->adjustment->value != old_value)
8865 if (dial->policy == GTK_UPDATE_CONTINUOUS)
8867 gtk_signal_emit_by_name (GTK_OBJECT (dial->adjustment), "value_changed");
8871 gtk_widget_draw (GTK_WIDGET(dial), NULL);
8873 if (dial->policy == GTK_UPDATE_DELAYED)
8876 gtk_timeout_remove (dial->timer);
8878 dial->timer = gtk_timeout_add (SCROLL_DELAY_LENGTH,
8879 (GtkFunction) gtk_dial_timer,
8888 Changes to the Adjustment by external means are communicated to our
8889 widget by the ``changed'' and ``value_changed'' signals. The handlers
8890 for these functions call <tt/gtk_dial_update()/ to validate the
8891 arguments, compute the new pointer angle, and redraw the widget (by
8892 calling <tt/gtk_widget_draw()/).
8896 gtk_dial_update (GtkDial *dial)
8900 g_return_if_fail (dial != NULL);
8901 g_return_if_fail (GTK_IS_DIAL (dial));
8903 new_value = dial->adjustment->value;
8905 if (new_value < dial->adjustment->lower)
8906 new_value = dial->adjustment->lower;
8908 if (new_value > dial->adjustment->upper)
8909 new_value = dial->adjustment->upper;
8911 if (new_value != dial->adjustment->value)
8913 dial->adjustment->value = new_value;
8914 gtk_signal_emit_by_name (GTK_OBJECT (dial->adjustment), "value_changed");
8917 dial->angle = 7.*M_PI/6. - (new_value - dial->adjustment->lower) * 4.*M_PI/3. /
8918 (dial->adjustment->upper - dial->adjustment->lower);
8920 gtk_widget_draw (GTK_WIDGET(dial), NULL);
8924 gtk_dial_adjustment_changed (GtkAdjustment *adjustment,
8929 g_return_if_fail (adjustment != NULL);
8930 g_return_if_fail (data != NULL);
8932 dial = GTK_DIAL (data);
8934 if ((dial->old_value != adjustment->value) ||
8935 (dial->old_lower != adjustment->lower) ||
8936 (dial->old_upper != adjustment->upper))
8938 gtk_dial_update (dial);
8940 dial->old_value = adjustment->value;
8941 dial->old_lower = adjustment->lower;
8942 dial->old_upper = adjustment->upper;
8947 gtk_dial_adjustment_value_changed (GtkAdjustment *adjustment,
8952 g_return_if_fail (adjustment != NULL);
8953 g_return_if_fail (data != NULL);
8955 dial = GTK_DIAL (data);
8957 if (dial->old_value != adjustment->value)
8959 gtk_dial_update (dial);
8961 dial->old_value = adjustment->value;
8966 <!-- ----------------------------------------------------------------- -->
8967 <sect2> Possible Enhancements
8970 The Dial widget as we've described it so far runs about 670 lines of
8971 code. Although that might sound like a fair bit, we've really
8972 accomplished quite a bit with that much code, especially since much of
8973 that length is headers and boilerplate. However, there are quite a few
8974 more enhancements that could be made to this widget:
8977 <item> If you try this widget out, you'll find that there is some
8978 flashing as the pointer is dragged around. This is because the entire
8979 widget is erased every time the pointer is moved before being
8980 redrawn. Often, the best way to handle this problem is to draw to an
8981 offscreen pixmap, then copy the final results onto the screen in one
8982 step. (The ProgressBar widget draws itself in this fashion.)
8984 <item> The user should be able to use the up and down arrow keys to
8985 increase and decrease the value.
8987 <item> It would be nice if the widget had buttons to increase and
8988 decrease the value in small or large steps. Although it would be
8989 possible to use embedded Button widgets for this, we would also like
8990 the buttons to auto-repeat when held down, as the arrows on a
8991 scrollbar do. Most of the code to implement this type of behavior can
8992 be found in the GtkRange widget.
8994 <item> The Dial widget could be made into a container widget with a
8995 single child widget positioned at the bottom between the buttons
8996 mentioned above. The user could then add their choice of a label or
8997 entry widget to display the current value of the dial.
9001 <!-- ----------------------------------------------------------------- -->
9002 <sect1> Learning More
9005 Only a small part of the many details involved in creating widgets
9006 could be described above. If you want to write your own widgets, the
9007 best source of examples is the GTK source itself. Ask yourself some
9008 questions about the widget you want to write: is it a Container
9009 widget? does it have its own window? is it a modification of an
9010 existing widget? Then find a similar widget, and start making changes.
9013 <!-- ***************************************************************** -->
9014 <sect>Scribble, A Simple Example Drawing Program
9015 <!-- ***************************************************************** -->
9017 <!-- ----------------------------------------------------------------- -->
9021 In this section, we will build a simple drawing program. In the
9022 process, we will examine how to handle mouse events, how to draw in a
9023 window, and how to do drawing better by using a backing pixmap. After
9024 creating the simple drawing program, we will extend it by adding
9025 support for XInput devices, such as drawing tablets. GTK provides
9026 support routines which makes getting extended information, such as
9027 pressure and tilt, from such devices quite easy.
9029 <!-- ----------------------------------------------------------------- -->
9030 <sect1> Event Handling
9033 The GTK signals we have already discussed are for high-level actions,
9034 such as a menu item being selected. However, sometimes it is useful to
9035 learn about lower-level occurrences, such as the mouse being moved, or
9036 a key being pressed. There are also GTK signals corresponding to these
9037 low-level <em>events</em>. The handlers for these signals have an
9038 extra parameter which is a pointer to a structure containing
9039 information about the event. For instance, motion events handlers are
9040 passed a pointer to a GdkEventMotion structure which looks (in part)
9044 struct _GdkEventMotion
9057 <tt/type/ will be set to the event type, in this case
9058 <tt/GDK_MOTION_NOTIFY/, window is the window in which the event
9059 occured. <tt/x/ and <tt/y/ give the coordinates of the event,
9060 and <tt/state/ specifies the modifier state when the event
9061 occurred (that is, it specifies which modifier keys and mouse buttons
9062 were pressed.) It is the bitwise OR of some of the following:
9081 As for other signals, to determine what happens when an event occurs
9082 we call <tt>gtk_signal_connect()</tt>. But we also need let GTK
9083 know which events we want to be notified about. To do this, we call
9087 void gtk_widget_set_events (GtkWidget *widget,
9091 The second field specifies the events we are interested in. It
9092 is the bitwise OR of constants that specify different types
9093 of events. For future reference the event types are:
9097 GDK_POINTER_MOTION_MASK
9098 GDK_POINTER_MOTION_HINT_MASK
9099 GDK_BUTTON_MOTION_MASK
9100 GDK_BUTTON1_MOTION_MASK
9101 GDK_BUTTON2_MOTION_MASK
9102 GDK_BUTTON3_MOTION_MASK
9103 GDK_BUTTON_PRESS_MASK
9104 GDK_BUTTON_RELEASE_MASK
9106 GDK_KEY_RELEASE_MASK
9107 GDK_ENTER_NOTIFY_MASK
9108 GDK_LEAVE_NOTIFY_MASK
9109 GDK_FOCUS_CHANGE_MASK
9111 GDK_PROPERTY_CHANGE_MASK
9112 GDK_PROXIMITY_IN_MASK
9113 GDK_PROXIMITY_OUT_MASK
9116 There are a few subtle points that have to be observed when calling
9117 <tt/gtk_widget_set_events()/. First, it must be called before the X window
9118 for a GTK widget is created. In practical terms, this means you
9119 should call it immediately after creating the widget. Second, the
9120 widget must have an associated X window. For efficiency, many widget
9121 types do not have their own window, but draw in their parent's window.
9144 To capture events for these widgets, you need to use an EventBox
9145 widget. See the section on
9146 <ref id="sec_The_EventBox_Widget" name="The EventBox Widget"> for
9150 For our drawing program, we want to know when the mouse button is
9151 pressed and when the mouse is moved, so we specify
9152 <tt/GDK_POINTER_MOTION_MASK/ and <tt/GDK_BUTTON_PRESS_MASK/. We also
9153 want to know when we need to redraw our window, so we specify
9154 <tt/GDK_EXPOSURE_MASK/. Although we want to be notified via a
9155 Configure event when our window size changes, we don't have to specify
9156 the corresponding <tt/GDK_STRUCTURE_MASK/ flag, because it is
9157 automatically specified for all windows.
9160 It turns out, however, that there is a problem with just specifying
9161 <tt/GDK_POINTER_MOTION_MASK/. This will cause the server to add a new
9162 motion event to the event queue every time the user moves the mouse.
9163 Imagine that it takes us 0.1 seconds to handle a motion event, but the
9164 X server queues a new motion event every 0.05 seconds. We will soon
9165 get way behind the users drawing. If the user draws for 5 seconds,
9166 it will take us another 5 seconds to catch up after they release
9167 the mouse button! What we would like is to only get one motion
9168 event for each event we process. The way to do this is to
9169 specify <tt/GDK_POINTER_MOTION_HINT_MASK/.
9172 When we specify <tt/GDK_POINTER_MOTION_HINT_MASK/, the server sends
9173 us a motion event the first time the pointer moves after entering
9174 our window, or after a button press or release event. Subsequent
9175 motion events will be suppressed until we explicitely ask for
9176 the position of the pointer using the function:
9179 GdkWindow* gdk_window_get_pointer (GdkWindow *window,
9182 GdkModifierType *mask);
9185 (There is another function, <tt>gtk_widget_get_pointer()</tt> which
9186 has a simpler interface, but turns out not to be very useful, since
9187 it only retrieves the position of the mouse, not whether the buttons
9191 The code to set the events for our window then looks like:
9194 gtk_signal_connect (GTK_OBJECT (drawing_area), "expose_event",
9195 (GtkSignalFunc) expose_event, NULL);
9196 gtk_signal_connect (GTK_OBJECT(drawing_area),"configure_event",
9197 (GtkSignalFunc) configure_event, NULL);
9198 gtk_signal_connect (GTK_OBJECT (drawing_area), "motion_notify_event",
9199 (GtkSignalFunc) motion_notify_event, NULL);
9200 gtk_signal_connect (GTK_OBJECT (drawing_area), "button_press_event",
9201 (GtkSignalFunc) button_press_event, NULL);
9203 gtk_widget_set_events (drawing_area, GDK_EXPOSURE_MASK
9204 | GDK_LEAVE_NOTIFY_MASK
9205 | GDK_BUTTON_PRESS_MASK
9206 | GDK_POINTER_MOTION_MASK
9207 | GDK_POINTER_MOTION_HINT_MASK);
9210 We'll save the "expose_event" and "configure_event" handlers for
9211 later. The "motion_notify_event" and "button_press_event" handlers
9216 button_press_event (GtkWidget *widget, GdkEventButton *event)
9218 if (event->button == 1 && pixmap != NULL)
9219 draw_brush (widget, event->x, event->y);
9225 motion_notify_event (GtkWidget *widget, GdkEventMotion *event)
9228 GdkModifierType state;
9231 gdk_window_get_pointer (event->window, &x, &y, &state);
9236 state = event->state;
9239 if (state & GDK_BUTTON1_MASK && pixmap != NULL)
9240 draw_brush (widget, x, y);
9246 <!-- ----------------------------------------------------------------- -->
9247 <sect1> The DrawingArea Widget, And Drawing
9250 We know turn to the process of drawing on the screen. The
9251 widget we use for this is the DrawingArea widget. A drawing area
9252 widget is essentially an X window and nothing more. It is a blank
9253 canvas in which we can draw whatever we like. A drawing area
9254 is created using the call:
9257 GtkWidget* gtk_drawing_area_new (void);
9260 A default size for the widget can be specified by calling:
9263 void gtk_drawing_area_size (GtkDrawingArea *darea,
9268 This default size can be overriden, as is true for all widgets,
9269 by calling <tt>gtk_widget_set_usize()</tt>, and that, in turn, can
9270 be overridden if the user manually resizes the the window containing
9274 It should be noted that when we create a DrawingArea widget, we are,
9275 <em>completely</em> responsible for drawing the contents. If our
9276 window is obscured then uncovered, we get an exposure event and must
9277 redraw what was previously hidden.
9280 Having to remember everything that was drawn on the screen so we
9281 can properly redraw it can, to say the least, be a nuisance. In
9282 addition, it can be visually distracting if portions of the
9283 window are cleared, then redrawn step by step. The solution to
9284 this problem is to use an offscreen <em>backing pixmap</em>.
9285 Instead of drawing directly to the screen, we draw to an image
9286 stored in server memory but not displayed, then when the image
9287 changes or new portions of the image are displayed, we copy the
9288 relevant portions onto the screen.
9291 To create an offscreen pixmap, we call the function:
9294 GdkPixmap* gdk_pixmap_new (GdkWindow *window,
9300 The <tt>window</tt> parameter specifies a GDK window that this pixmap
9301 takes some of its properties from. <tt>width</tt> and <tt>height</tt>
9302 specify the size of the pixmap. <tt>depth</tt> specifies the <em>color
9303 depth</em>, that is the number of bits per pixel, for the new window.
9304 If the depth is specified as <tt>-1</tt>, it will match the depth
9308 We create the pixmap in our "configure_event" handler. This event
9309 is generated whenever the window changes size, including when it
9310 is originally created.
9313 /* Backing pixmap for drawing area */
9314 static GdkPixmap *pixmap = NULL;
9316 /* Create a new backing pixmap of the appropriate size */
9318 configure_event (GtkWidget *widget, GdkEventConfigure *event)
9322 gdk_pixmap_destroy(pixmap);
9324 pixmap = gdk_pixmap_new(widget->window,
9325 widget->allocation.width,
9326 widget->allocation.height,
9328 gdk_draw_rectangle (pixmap,
9329 widget->style->white_gc,
9332 widget->allocation.width,
9333 widget->allocation.height);
9339 The call to <tt>gdk_draw_rectangle()</tt> clears the pixmap
9340 initially to white. We'll say more about that in a moment.
9343 Our exposure event handler then simply copies the relevant portion
9344 of the pixmap onto the screen (we determine the area we need
9345 to redraw by using the event->area field of the exposure event):
9348 /* Refill the screen from the backing pixmap */
9350 expose_event (GtkWidget *widget, GdkEventExpose *event)
9352 gdk_draw_pixmap(widget->window,
9353 widget->style->fg_gc[GTK_WIDGET_STATE (widget)],
9355 event->area.x, event->area.y,
9356 event->area.x, event->area.y,
9357 event->area.width, event->area.height);
9363 We've now seen how to keep the screen up to date with our pixmap, but
9364 how do we actually draw interesting stuff on our pixmap? There are a
9365 large number of calls in GTK's GDK library for drawing on
9366 <em>drawables</em>. A drawable is simply something that can be drawn
9367 upon. It can be a window, a pixmap, or a bitmap (a black and white
9368 image). We've already seen two such calls above,
9369 <tt>gdk_draw_rectangle()</tt> and <tt>gdk_draw_pixmap()</tt>. The
9374 gdk_draw_rectangle ()
9383 gdk_draw_segments ()
9386 See the reference documentation or the header file
9387 <tt><gdk/gdk.h></tt> for further details on these functions.
9388 These functions all share the same first two arguments. The first
9389 argument is the drawable to draw upon, the second argument is a
9390 <em>graphics context</em> (GC).
9393 A graphics context encapsulates information about things such as
9394 foreground and background color and line width. GDK has a full set of
9395 functions for creating and modifying graphics contexts, but to keep
9396 things simple we'll just use predefined graphics contexts. Each widget
9397 has an associated style. (Which can be modified in a gtkrc file, see
9398 the section GTK's rc file.) This, among other things, stores a number
9399 of graphics contexts. Some examples of accessing these graphics
9403 widget->style->white_gc
9404 widget->style->black_gc
9405 widget->style->fg_gc[GTK_STATE_NORMAL]
9406 widget->style->bg_gc[GTK_WIDGET_STATE(widget)]
9409 The fields <tt>fg_gc</tt>, <tt>bg_gc</tt>, <tt>dark_gc</tt>, and
9410 <tt>light_gc</tt> are indexed by a parameter of type
9411 <tt>GtkStateType</tt> which can take on the values:
9418 GTK_STATE_INSENSITIVE
9421 For instance, the for <tt/GTK_STATE_SELECTED/ the default foreground
9422 color is white and the default background color, dark blue.
9425 Our function <tt>draw_brush()</tt>, which does the actual drawing
9426 on the screen, is then:
9429 /* Draw a rectangle on the screen */
9431 draw_brush (GtkWidget *widget, gdouble x, gdouble y)
9433 GdkRectangle update_rect;
9435 update_rect.x = x - 5;
9436 update_rect.y = y - 5;
9437 update_rect.width = 10;
9438 update_rect.height = 10;
9439 gdk_draw_rectangle (pixmap,
9440 widget->style->black_gc,
9442 update_rect.x, update_rect.y,
9443 update_rect.width, update_rect.height);
9444 gtk_widget_draw (widget, &update_rect);
9448 After we draw the rectangle representing the brush onto the pixmap,
9449 we call the function:
9452 void gtk_widget_draw (GtkWidget *widget,
9453 GdkRectangle *area);
9456 which notifies X that the area given by the <tt>area</tt> parameter
9457 needs to be updated. X will eventually generate an expose event
9458 (possibly combining the areas passed in several calls to
9459 <tt>gtk_widget_draw()</tt>) which will cause our expose event handler
9460 to copy the relevant portions to the screen.
9463 We have now covered the entire drawing program except for a few
9464 mundane details like creating the main window. The complete
9465 source code is available from the location from which you got
9466 this tutorial, or from:
9468 <htmlurl url="http://www.gtk.org/~otaylor/gtk/tutorial/"
9469 name="http://www.gtk.org/~otaylor/gtk/tutorial/">
9472 <!-- ----------------------------------------------------------------- -->
9473 <sect1> Adding XInput support
9477 It is now possible to buy quite inexpensive input devices such
9478 as drawing tablets, which allow drawing with a much greater
9479 ease of artistic expression than does a mouse. The simplest way
9480 to use such devices is simply as a replacement for the mouse,
9481 but that misses out many of the advantages of these devices,
9485 <item> Pressure sensitivity
9486 <item> Tilt reporting
9487 <item> Sub-pixel positioning
9488 <item> Multiple inputs (for example, a stylus with a point and eraser)
9491 For information about the XInput extension, see the <htmlurl
9492 url="http://www.msc.cornell.edu/~otaylor/xinput/XInput-HOWTO.html"
9493 name="XInput-HOWTO">.
9496 If we examine the full definition of, for example, the GdkEventMotion
9497 structure, we see that it has fields to support extended device
9501 struct _GdkEventMotion
9513 GdkInputSource source;
9518 <tt/pressure/ gives the pressure as a floating point number between
9519 0 and 1. <tt/xtilt/ and <tt/ytilt/ can take on values between
9520 -1 and 1, corresponding to the degree of tilt in each direction.
9521 <tt/source/ and <tt/deviceid/ specify the device for which the
9522 event occurred in two different ways. <tt/source/ gives some simple
9523 information about the type of device. It can take the enumeration
9533 <tt/deviceid/ specifies a unique numeric ID for the device. This can
9534 be used to find out further information about the device using the
9535 <tt/gdk_input_list_devices()/ call (see below). The special value
9536 <tt/GDK_CORE_POINTER/ is used for the core pointer device. (Usually
9539 <sect2> Enabling extended device information
9542 To let GTK know about our interest in the extended device information,
9543 we merely have to add a single line to our program:
9546 gtk_widget_set_extension_events (drawing_area, GDK_EXTENSION_EVENTS_CURSOR);
9549 By giving the value <tt/GDK_EXTENSION_EVENTS_CURSOR/ we say that
9550 we are interested in extension events, but only if we don't have
9551 to draw our own cursor. See the section <ref
9552 id="sec_Further_Sophistications" name="Further Sophistications"> below
9553 for more information about drawing the cursor. We could also
9554 give the values <tt/GDK_EXTENSION_EVENTS_ALL/ if we were willing
9555 to draw our own cursor, or <tt/GDK_EXTENSION_EVENTS_NONE/ to revert
9556 back to the default condition.
9559 This is not completely the end of the story however. By default,
9560 no extension devices are enabled. We need a mechanism to allow
9561 users to enable and configure their extension devices. GTK provides
9562 the InputDialog widget to automate this process. The following
9563 procedure manages an InputDialog widget. It creates the dialog if
9564 it isn't present, and raises it to the top otherwise.
9568 input_dialog_destroy (GtkWidget *w, gpointer data)
9570 *((GtkWidget **)data) = NULL;
9574 create_input_dialog ()
9576 static GtkWidget *inputd = NULL;
9580 inputd = gtk_input_dialog_new();
9582 gtk_signal_connect (GTK_OBJECT(inputd), "destroy",
9583 (GtkSignalFunc)input_dialog_destroy, &inputd);
9584 gtk_signal_connect_object (GTK_OBJECT(GTK_INPUT_DIALOG(inputd)->close_button),
9586 (GtkSignalFunc)gtk_widget_hide,
9587 GTK_OBJECT(inputd));
9588 gtk_widget_hide ( GTK_INPUT_DIALOG(inputd)->save_button);
9590 gtk_widget_show (inputd);
9594 if (!GTK_WIDGET_MAPPED(inputd))
9595 gtk_widget_show(inputd);
9597 gdk_window_raise(inputd->window);
9602 (You might want to take note of the way we handle this dialog. By
9603 connecting to the "destroy" signal, we make sure that we don't keep a
9604 pointer to dialog around after it is destroyed - that could lead to a
9608 The InputDialog has two buttons "Close" and "Save", which by default
9609 have no actions assigned to them. In the above function we make
9610 "Close" hide the dialog, hide the "Save" button, since we don't
9611 implement saving of XInput options in this program.
9613 <sect2> Using extended device information
9616 Once we've enabled the device, we can just use the extended
9617 device information in the extra fields of the event structures.
9618 In fact, it is always safe to use this information since these
9619 fields will have reasonable default values even when extended
9620 events are not enabled.
9623 Once change we do have to make is to call
9624 <tt/gdk_input_window_get_pointer()/ instead of
9625 <tt/gdk_window_get_pointer/. This is necessary because
9626 <tt/gdk_window_get_pointer/ doesn't return the extended device
9630 void gdk_input_window_get_pointer (GdkWindow *window,
9637 GdkModifierType *mask);
9640 When calling this function, we need to specify the device ID as
9641 well as the window. Usually, we'll get the device ID from the
9642 <tt/deviceid/ field of an event structure. Again, this function
9643 will return reasonable values when extension events are not
9644 enabled. (In this case, <tt/event->deviceid/ will have the value
9645 <tt/GDK_CORE_POINTER/).
9647 So the basic structure of our button-press and motion event handlers,
9648 doesn't change much - we just need to add code to deal with the
9649 extended information.
9653 button_press_event (GtkWidget *widget, GdkEventButton *event)
9655 print_button_press (event->deviceid);
9657 if (event->button == 1 && pixmap != NULL)
9658 draw_brush (widget, event->source, event->x, event->y, event->pressure);
9664 motion_notify_event (GtkWidget *widget, GdkEventMotion *event)
9668 GdkModifierType state;
9671 gdk_input_window_get_pointer (event->window, event->deviceid,
9672 &x, &y, &pressure, NULL, NULL, &state);
9677 pressure = event->pressure;
9678 state = event->state;
9681 if (state & GDK_BUTTON1_MASK && pixmap != NULL)
9682 draw_brush (widget, event->source, x, y, pressure);
9688 We also need to do something with the new information. Our new
9689 <tt/draw_brush()/ function draws with a different color for
9690 each <tt/event->source/ and changes the brush size depending
9694 /* Draw a rectangle on the screen, size depending on pressure,
9695 and color on the type of device */
9697 draw_brush (GtkWidget *widget, GdkInputSource source,
9698 gdouble x, gdouble y, gdouble pressure)
9701 GdkRectangle update_rect;
9705 case GDK_SOURCE_MOUSE:
9706 gc = widget->style->dark_gc[GTK_WIDGET_STATE (widget)];
9708 case GDK_SOURCE_PEN:
9709 gc = widget->style->black_gc;
9711 case GDK_SOURCE_ERASER:
9712 gc = widget->style->white_gc;
9715 gc = widget->style->light_gc[GTK_WIDGET_STATE (widget)];
9718 update_rect.x = x - 10 * pressure;
9719 update_rect.y = y - 10 * pressure;
9720 update_rect.width = 20 * pressure;
9721 update_rect.height = 20 * pressure;
9722 gdk_draw_rectangle (pixmap, gc, TRUE,
9723 update_rect.x, update_rect.y,
9724 update_rect.width, update_rect.height);
9725 gtk_widget_draw (widget, &update_rect);
9729 <sect2> Finding out more about a device
9732 As an example of how to find out more about a device, our program
9733 will print the name of the device that generates each button
9734 press. To find out the name of a device, we call the function:
9737 GList *gdk_input_list_devices (void);
9740 which returns a GList (a linked list type from the glib library)
9741 of GdkDeviceInfo structures. The GdkDeviceInfo strucure is defined
9745 struct _GdkDeviceInfo
9749 GdkInputSource source;
9759 Most of these fields are configuration information that you
9760 can ignore unless you are implemented XInput configuration
9761 saving. The we are interested in here is <tt/name/ which is
9762 simply the name that X assigns to the device. The other field
9763 that isn't configuration information is <tt/has_cursor/. If
9764 <tt/has_cursor/ is false, then we we need to draw our own
9765 cursor. But since we've specified <tt/GDK_EXTENSION_EVENTS_CURSOR/,
9766 we don't have to worry about this.
9769 Our <tt/print_button_press()/ function simply iterates through
9770 the returned list until it finds a match, then prints out
9771 the name of the device.
9775 print_button_press (guint32 deviceid)
9779 /* gdk_input_list_devices returns an internal list, so we shouldn't
9780 free it afterwards */
9781 tmp_list = gdk_input_list_devices();
9785 GdkDeviceInfo *info = (GdkDeviceInfo *)tmp_list->data;
9787 if (info->deviceid == deviceid)
9789 printf("Button press on device '%s'\n", info->name);
9793 tmp_list = tmp_list->next;
9798 That completes the changes to ``XInputize'' our program. As with
9799 the first version, the complete source is available at the location
9800 from which you got this tutorial, or from:
9802 <htmlurl url="http://www.gtk.org/~otaylor/gtk/tutorial/"
9803 name="http://www.gtk.org/~otaylor/gtk/tutorial/">
9806 <sect2> Further sophistications <label id="sec_Further_Sophistications">
9809 Although our program now supports XInput quite well, it lacks some
9810 features we would want in a full-featured application. First, the user
9811 probably doesn't want to have to configure their device each time they
9812 run the program, so we should allow them to save the device
9813 configuration. This is done by iterating through the return of
9814 <tt/gdk_input_list_devices()/ and writing out the configuration to a
9818 To restore the state next time the program is run, GDK provides
9819 functions to change device configuration:
9822 gdk_input_set_extension_events()
9823 gdk_input_set_source()
9824 gdk_input_set_mode()
9825 gdk_input_set_axes()
9829 (The list returned from <tt/gdk_input_list_devices()/ should not be
9830 modified directly.) An example of doing this can be found in the
9831 drawing program gsumi. (Available from <htmlurl
9832 url="http://www.msc.cornell.edu/~otaylor/gsumi/"
9833 name="http://www.msc.cornell.edu/~otaylor/gsumi/">) Eventually, it
9834 would be nice to have a standard way of doing this for all
9835 applications. This probably belongs at a slightly higher level than
9836 GTK, perhaps in the GNOME library.
9839 Another major ommission that we have mentioned above is the lack of
9840 cursor drawing. Platforms other than XFree86 currently do not allow
9841 simultaneously using a device as both the core pointer and directly by
9842 an application. See the <url
9843 url="http://www.msc.cornell.edu/~otaylor/xinput/XInput-HOWTO.html"
9844 name="XInput-HOWTO"> for more information about this. This means that
9845 applications that want to support the widest audience need to draw
9849 An application that draws it's own cursor needs to do two things:
9850 determine if the current device needs a cursor drawn or not, and
9851 determine if the current device is in proximity. (If the current
9852 device is a drawing tablet, it's a nice touch to make the cursor
9853 disappear when the stylus is lifted from the tablet. When the
9854 device is touching the stylus, that is called "in proximity.")
9855 The first is done by searching the device list, as we did
9856 to find out the device name. The second is achieved by selecting
9857 "proximity_out" events. An example of drawing one's own cursor is
9858 found in the 'testinput' program found in the GTK distribution.
9860 <!-- ***************************************************************** -->
9861 <sect>Tips For Writing GTK Applications
9862 <!-- ***************************************************************** -->
9865 This section is simply a gathering of wisdom, general style guidelines and hints to
9866 creating good GTK applications. It is totally useless right now cause it's
9867 only a topic sentence :)
9869 Use GNU autoconf and automake! They are your friends :) I am planning to
9870 make a quick intro on them here.
9872 <!-- ***************************************************************** -->
9874 <!-- ***************************************************************** -->
9877 This document, like so much other great software out there, was created for
9878 free by volunteers. If you are at all knowledgeable about any aspect of GTK
9879 that does not already have documentation, please consider contributing to
9882 If you do decide to contribute, please mail your text to Tony Gale,
9883 <tt><htmlurl url="mailto:gale@gtk.org"
9884 name="gale@gtk.org"></tt>. Also, be aware that the entirety of this
9885 document is free, and any addition by yourself must also be free. That is,
9886 people may use any portion of your examples in their programs, and copies
9887 of this document may be distributed at will etc.
9891 <!-- ***************************************************************** -->
9893 <!-- ***************************************************************** -->
9895 I would like to thank the following for their contributions to this text.
9898 <item>Bawer Dagdeviren, <tt><htmlurl url="mailto:chamele0n@geocities.com"
9899 name="chamele0n@geocities.com"></tt> for the menus tutorial.
9901 <item>Raph Levien, <tt><htmlurl url="mailto:raph@acm.org"
9902 name="raph@acm.org"></tt>
9903 for hello world ala GTK, widget packing, and general all around wisdom.
9904 He's also generously donated a home for this tutorial.
9906 <item>Peter Mattis, <tt><htmlurl url="mailto:petm@xcf.berkeley.edu"
9907 name="petm@xcf.berkeley.edu"></tt> for the simplest GTK program..
9908 and the ability to make it :)
9910 <item>Werner Koch <tt><htmlurl url="mailto:werner.koch@guug.de"
9911 name="werner.koch@guug.de"></tt> for converting the original plain text to
9912 SGML, and the widget class hierarchy.
9914 <item>Mark Crichton <tt><htmlurl url="mailto:crichton@expert.cc.purdue.edu"
9915 name="crichton@expert.cc.purdue.edu"></tt> for the menu factory code, and
9916 the table packing tutorial.
9918 <item>Owen Taylor <tt><htmlurl url="mailto:owt1@cornell.edu"
9919 name="owt1@cornell.edu"></tt> for the EventBox widget section (and
9920 the patch to the distro). He's also responsible for the selections code and
9921 tutorial, as well as the sections on writing your own GTK widgets, and the
9922 example application. Thanks a lot Owen for all you help!
9924 <item>Mark VanderBoom <tt><htmlurl url="mailto:mvboom42@calvin.edu"
9925 name="mvboom42@calvin.edu"></tt> for his wonderful work on the Notebook,
9926 Progress Bar, Dialogs, and File selection widgets. Thanks a lot Mark!
9927 You've been a great help.
9929 <item>Tim Janik <tt><htmlurl url="mailto:timj@psynet.net"
9930 name="timj@psynet.net"></tt> for his great job on the Lists Widget.
9933 <item>Rajat Datta <tt><htmlurl url="mailto:rajat@ix.netcom.com"
9934 name="rajat@ix.netcom.com"</tt> for the excellent job on the Pixmap tutorial.
9936 <item>Michael K. Johnson <tt><htmlurl url="mailto:johnsonm@redhat.com"
9937 name="johnsonm@redhat.com"></tt> for info and code for popup menus.
9941 And to all of you who commented and helped refine this document.
9945 <!-- ***************************************************************** -->
9946 <sect> Tutorial Copyright and Permissions Notice
9947 <!-- ***************************************************************** -->
9950 The GTK Tutorial is Copyright (C) 1997 Ian Main.
9952 Copyright (C) 1998 Tony Gale.
9954 Permission is granted to make and distribute verbatim copies of this
9955 manual provided the copyright notice and this permission notice are
9956 preserved on all copies.
9957 <P>Permission is granted to copy and distribute modified versions of
9958 this document under the conditions for verbatim copying, provided that
9959 this copyright notice is included exactly as in the original,
9960 and that the entire resulting derived work is distributed under
9961 the terms of a permission notice identical to this one.
9962 <P>Permission is granted to copy and distribute translations of this
9963 document into another language, under the above conditions for modified
9965 <P>If you are intending to incorporate this document into a published
9966 work, please contact the maintainer, and we will make an effort
9967 to ensure that you have the most up to date information available.
9968 <P>There is no guarentee that this document lives up to its intended
9969 purpose. This is simply provided as a free resource. As such,
9970 the authors and maintainers of the information provided within can
9971 not make any guarentee that the information is even accurate.